Compare commits

..

1 Commits

Author SHA1 Message Date
c02f1cfb4c Implementation of polling app 2026-03-18 17:41:37 +01:00
12 changed files with 207 additions and 10295 deletions

200
PollingApp.html Normal file
View File

@@ -0,0 +1,200 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PeertoPeer Poll up to 14 users (no vote loops)</title>
<style>
body {font-family:Arial,Helvetica,sans-serif; margin:20px;}
#options li {margin:5px 0;}
button {margin-left:5px;}
</style>
</head>
<body>
<h2>PeertoPeer Poll (max14 participants)</h2>
<div id="setup">
<label>Your Peer ID: <input id="myId" readonly size="30"></label><br><br>
<label>Room host ID (leave empty if you are the first client):
<input id="hostId" placeholder="host peer id">
</label>
<button id="joinBtn">Join / Create Room</button>
<p id="status"></p>
</div>
<hr>
<h3>Poll</h3>
<ul id="options"></ul>
<input id="newOption" placeholder="New option text">
<button id="addOptionBtn">Add option</button>
<script src="https://unpkg.com/peerjs@1.5.4/dist/peerjs.min.js"></script>
<script>
/* ---------- 1. Initialise PeerJS ---------- */
const peer = new Peer(); // public signalling server
const myIdInput = document.getElementById('myId');
const statusEl = document.getElementById('status');
let isHost = false; // true for the first client
let connections = []; // all open DataConnections
let knownPeers = new Set(); // IDs of every peer we know (including host)
peer.on('open', id => {
myIdInput.value = id;
statusEl.textContent = 'Enter a host ID (or leave empty) and click Join.';
});
/* ---------- 2. Accept incoming connections (host side) ---------- */
peer.on('connection', incoming => {
registerConnection(incoming);
});
/* ---------- 3. Join / create a room ---------- */
document.getElementById('joinBtn').onclick = () => {
const hostId = document.getElementById('hostId').value.trim();
if (hostId) {
isHost = false;
connectToPeer(hostId);
statusEl.textContent = `Connecting to host ${hostId}`;
} else {
isHost = true;
knownPeers.add(peer.id);
statusEl.textContent = 'Room created share this Peer ID with others.';
}
};
/* ---------- 4. Helper: connect to a remote peer ---------- */
function connectToPeer(peerId) {
if (knownPeers.has(peerId)) return;
const conn = peer.connect(peerId);
registerConnection(conn);
}
/* ---------- 5. Register a DataConnection ---------- */
function registerConnection(conn) {
if (!conn) return;
connections.push(conn);
knownPeers.add(conn.peer);
conn.on('open', () => {
// 1⃣ Send full poll state
conn.send({type: 'full', payload: poll, msgId: crypto.randomUUID()});
// 2⃣ If we are the host, tell the newcomer about other peers
if (isHost) {
const others = Array.from(knownPeers).filter(id => id !== conn.peer && id !== peer.id);
if (others.length) conn.send({type: 'peer-list', payload: others, msgId: crypto.randomUUID()});
}
});
conn.on('data', data => handleMessage(data, conn.peer));
conn.on('close', () => {
connections = connections.filter(c => c !== conn);
knownPeers.delete(conn.peer);
});
}
/* ---------- 6. Shared poll state ---------- */
let poll = {options: []}; // each option: {id, text, votes}
/* ---------- 7. Track my own votes ---------- */
const myVotes = new Set(); // option.id values
/* ---------- 8. Remember which messages we already processed ---------- */
const seenMsgIds = new Set();
/* ---------- 9. Broadcast helper (skip the sender) ---------- */
function broadcast(msg, except = null) {
connections.forEach(c => {
if (c.open && c.peer !== except) c.send(msg);
});
}
/* ---------- 10. Message handling ---------- */
function handleMessage(msg, senderId) {
// Ignore duplicates
if (seenMsgIds.has(msg.msgId)) return;
seenMsgIds.add(msg.msgId);
switch (msg.type) {
case 'full':
poll = msg.payload;
render();
break;
case 'add':
poll.options.push(msg.payload);
render();
broadcast(msg, senderId); // forward once
break;
case 'vote':
const opt = poll.options.find(o => o.id === msg.payload.id);
if (opt) opt.votes++;
render();
broadcast(msg, senderId);
break;
case 'peer-list':
msg.payload.forEach(id => {
if (id !== peer.id && !knownPeers.has(id)) connectToPeer(id);
});
break;
}
}
/* ---------- 11. UI rendering ---------- */
function render() {
const ul = document.getElementById('options');
ul.innerHTML = '';
poll.options.forEach(opt => {
const li = document.createElement('li');
li.textContent = `${opt.text} ${opt.votes} vote(s)`;
const btn = document.createElement('button');
btn.textContent = myVotes.has(opt.id) ? 'Voted' : 'Vote';
btn.disabled = myVotes.has(opt.id);
btn.onclick = () => {
// Record locally prevents doubleclick on the same client
myVotes.add(opt.id);
btn.textContent = 'Voted';
btn.disabled = true;
const voteMsg = {
type: 'vote',
payload: {id: opt.id},
msgId: crypto.randomUUID()
};
// Apply locally first
opt.votes++;
render();
// Send to all peers
broadcast(voteMsg);
};
li.appendChild(btn);
ul.appendChild(li);
});
}
/* ---------- 12. Add new option ---------- */
document.getElementById('addOptionBtn').onclick = () => {
const txt = document.getElementById('newOption').value.trim();
if (!txt) return;
const option = {id: crypto.randomUUID(), text: txt, votes: 0};
poll.options.push(option);
render();
const addMsg = {
type: 'add',
payload: option,
msgId: crypto.randomUUID()
};
broadcast(addMsg);
document.getElementById('newOption').value = '';
};
</script>
</body>
</html>

View File

@@ -1 +1,7 @@
# P2P Poll App
# P2P Poll App
This is a very simple polling app using peerjs.
It runs as a single HTML file and can handle multiple users in one poll room.
The app once open is self explanatory.
App created with the help of GPTOSS120B.

24
p2p-poll/.gitignore vendored
View File

@@ -1,24 +0,0 @@
# Nuxt dev/build outputs
.output
.data
.nuxt
.nitro
.cache
dist
# Node dependencies
node_modules
# Logs
logs
*.log
# Misc
.DS_Store
.fleet
.idea
# Local env files
.env
.env.*
!.env.example

View File

@@ -1,75 +0,0 @@
# Nuxt Minimal Starter
Look at the [Nuxt documentation](https://nuxt.com/docs/getting-started/introduction) to learn more.
## Setup
Make sure to install dependencies:
```bash
# npm
npm install
# pnpm
pnpm install
# yarn
yarn install
# bun
bun install
```
## Development Server
Start the development server on `http://localhost:3000`:
```bash
# npm
npm run dev
# pnpm
pnpm dev
# yarn
yarn dev
# bun
bun run dev
```
## Production
Build the application for production:
```bash
# npm
npm run build
# pnpm
pnpm build
# yarn
yarn build
# bun
bun run build
```
Locally preview production build:
```bash
# npm
npm run preview
# pnpm
pnpm preview
# yarn
yarn preview
# bun
bun run preview
```
Check out the [deployment documentation](https://nuxt.com/docs/getting-started/deployment) for more information.

View File

@@ -1,152 +0,0 @@
<style>
/* Basic styling to make it look clean */
body {
font-family: system-ui, -apple-system, sans-serif;
background-color: #f4f4f9;
color: #333;
margin: 0;
display: flex;
justify-content: center;
padding: 2rem;
}
.poll-container {
background: white;
padding: 2rem;
border-radius: 12px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
width: 100%;
max-width: 500px;
}
header {
margin-bottom: 2rem;
text-align: center;
}
h1 { margin: 0 0 0.5rem 0; }
.status {
font-size: 0.85rem;
color: #666;
}
.status .connected { color: #10b981; font-weight: bold; }
.add-option-form {
display: flex;
gap: 0.5rem;
margin-bottom: 2rem;
}
input {
flex-grow: 1;
padding: 0.75rem;
border: 1px solid #ccc;
border-radius: 6px;
font-size: 1rem;
}
button {
background: #3b82f6;
color: white;
border: none;
padding: 0.75rem 1rem;
border-radius: 6px;
cursor: pointer;
font-weight: bold;
transition: background 0.2s;
}
button:hover { background: #2563eb; }
.poll-list {
list-style: none;
padding: 0;
margin: 0;
}
.poll-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem;
background: #f8fafc;
border: 1px solid #e2e8f0;
border-radius: 8px;
margin-bottom: 0.5rem;
}
.option-name { font-weight: 500; }
.vote-section { display: flex; align-items: center; gap: 1rem; }
.vote-count { font-size: 0.9rem; color: #475569; }
.vote-btn { padding: 0.4rem 0.8rem; background: #10b981; }
.vote-btn:hover { background: #059669; }
.empty-state { text-align: center; color: #94a3b8; font-style: italic; }
</style>
<template>
<div class="poll-container">
<ClientOnly>
<header>
<h1>P2P Polling App 🗳</h1>
<div class="status">
<span :class="{ 'connected': isConnected }">
{{ isConnected ? 'Synced' : 'Connecting...' }}
</span>
<span> | Peers online: {{ connectedPeers }}</span>
</div>
</header>
<main>
<form @submit.prevent="handleAddNewOption" class="add-option-form">
<input
v-model="newOption"
type="text"
placeholder="Enter a new poll option..."
required
/>
<button type="submit">Add Option</button>
</form>
<div v-if="Object.keys(pollData).length === 0" class="empty-state">
No options yet. Be the first to add one!
</div>
<ul v-else class="poll-list">
<li v-for="(votes, optionName) in pollData" :key="optionName" class="poll-item">
<span class="option-name">{{ optionName }}</span>
<div class="vote-section">
<span class="vote-count">{{ votes }} {{ votes === 1 ? 'vote' : 'votes' }}</span>
<button @click="vote(String(optionName))" class="vote-btn">+1</button>
</div>
</li>
</ul>
</main>
<template #fallback>
<div class="empty-state">Loading P2P Node...</div>
</template>
</ClientOnly>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
// Manually define 'global' for the browser
if (process.client) {
(window as any).global = window;
}
import { usePoll } from '../composables/usePoll';
// Because WebRTC requires the browser environment (window/navigator),
// we ensure our composable only runs on the client side in Nuxt.
const newOption = ref('');
// Destructure our P2P logic
const { pollData, isConnected, connectedPeers, addOption, vote } = usePoll();
const handleAddNewOption = () => {
addOption(newOption.value);
newOption.value = ''; // Reset input
};
</script>

View File

@@ -1,81 +0,0 @@
// composables/usePoll.ts
import { ref, onMounted, onUnmounted } from 'vue';
import * as Y from 'yjs';
export const usePoll = () => {
// Reactive Vue state to drive the UI
const pollData = ref<Record<string, number>>({});
const isConnected = ref(false);
const connectedPeers = ref(1); // 1 = just you initially
let ydoc: Y.Doc;
let provider: any;
let yMap: Y.Map<number>;
onMounted(async () => {
// 1. Initialize the Yjs document
ydoc = new Y.Doc();
// 2. Connect via WebRTC.
// 'nuxt-p2p-poll-demo-room' is the shared room name.
// Anyone using this exact string will sync together.
const { WebrtcProvider } = await import('y-webrtc');
provider = new WebrtcProvider('nuxt-p2p-poll-demo-room', ydoc);
// Track connection status
provider.on('synced', (arg: {synced: boolean}) => {
isConnected.value = arg.synced;
});
provider.on('peers', (data: any) => {
// data.webrtcPeers contains the connected peer IDs
connectedPeers.value = data.webrtcPeers.length + 1; // +1 for self
});
// 3. Define our shared state structure. We'll use a Map
// where the Key is the Poll Option (string) and Value is the Vote Count (number)
yMap = ydoc.getMap<number>('shared-poll');
// 4. Listen for changes from other peers and update our Vue reactive state
yMap.observe(() => {
pollData.value = yMap.toJSON();
});
// Initial load in case data already exists in the room
pollData.value = yMap.toJSON();
});
onUnmounted(() => {
// Clean up when the component is destroyed
if (provider) {
provider.disconnect();
}
if (ydoc) {
ydoc.destroy();
}
});
// Action: Add a new option to the poll
const addOption = (optionName: string) => {
const trimmedName = optionName.trim();
if (trimmedName && !yMap.has(trimmedName)) {
yMap.set(trimmedName, 0); // Initialize with 0 votes
}
};
// Action: Vote for an existing option
const vote = (optionName: string) => {
if (yMap.has(optionName)) {
const currentVotes = yMap.get(optionName) || 0;
yMap.set(optionName, currentVotes + 1);
}
};
return {
pollData,
isConnected,
connectedPeers,
addOption,
vote
};
};

View File

@@ -1,11 +0,0 @@
// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
compatibilityDate: '2025-07-15',
devtools: { enabled: true },
ssr: false,
vite: {
optimizeDeps: {
include: ['yjs', 'y-webrtc']
}
}
})

File diff suppressed because it is too large Load Diff

View File

@@ -1,19 +0,0 @@
{
"name": "p2p-poll",
"type": "module",
"private": true,
"scripts": {
"build": "nuxt build",
"dev": "nuxt dev",
"generate": "nuxt generate",
"preview": "nuxt preview",
"postinstall": "nuxt prepare"
},
"dependencies": {
"nuxt": "^4.1.3",
"vue": "^3.5.30",
"vue-router": "^5.0.3",
"y-webrtc": "^10.3.0",
"yjs": "^13.6.30"
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

View File

@@ -1,2 +0,0 @@
User-Agent: *
Disallow:

View File

@@ -1,18 +0,0 @@
{
// https://nuxt.com/docs/guide/concepts/typescript
"files": [],
"references": [
{
"path": "./.nuxt/tsconfig.app.json"
},
{
"path": "./.nuxt/tsconfig.server.json"
},
{
"path": "./.nuxt/tsconfig.shared.json"
},
{
"path": "./.nuxt/tsconfig.node.json"
}
]
}