Compare commits

..

4 Commits

Author SHA1 Message Date
ako
343a55a673 feat: add styles for polling app UI
Responsive single-column layout (max 480px) with styles for:
- Option items with label/vote-button rows
- Voted state highlighting (green tint)
- Active/closed timer color states
- Disabled button opacity
- Full-width copy URL button

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-11 14:49:17 +01:00
ako
a76f00a08a feat: implement P2P polling app with Automerge sync
Core functionality using Automerge CRDT for real-time P2P sync:
- Creates or loads a shared document via URL hash
- Syncs over BroadcastChannel (local tabs) and WebSocket (wss://sync.automerge.org)
- Persists state to IndexedDB
- Add poll options with case-insensitive duplicate detection
- Toggle-vote per option, tracked per-document in localStorage
- Options sorted by vote count descending
- 2-minute countdown timer that disables voting on expiry
- Copy-to-clipboard for shareable URL

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-11 14:49:12 +01:00
ako
1d773dcb07 feat: add HTML shell for P2P polling app
Defines the app layout with sections for:
- Status indicator for document load state
- Option input and add button
- Duplicate warning message area
- Timer section with start-voting button
- Options list for rendered poll items
- Copy URL button for sharing

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-11 14:49:02 +01:00
ako
812098a6bb chore: initialize Vite project with Automerge dependencies
Set up project scaffold for a P2P polling app:
- package.json with @automerge/vanillajs, automerge-repo, vite deps
- vite.config.js with wasm and top-level-await plugins required by Automerge
- pnpm-lock.yaml lockfile
- .gitignore excluding node_modules

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-11 14:48:56 +01:00
9 changed files with 1453 additions and 207 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
node_modules/

View File

@@ -1,200 +0,0 @@
<!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,7 +1 @@
# 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.
# P2P Poll App

214
app.js Normal file
View File

@@ -0,0 +1,214 @@
import {
Repo,
BroadcastChannelNetworkAdapter,
WebSocketClientAdapter,
IndexedDBStorageAdapter,
isValidAutomergeUrl,
} from "@automerge/vanillajs";
const REPO = new Repo({
network: [
new BroadcastChannelNetworkAdapter(),
new WebSocketClientAdapter("wss://sync.automerge.org"),
],
storage: new IndexedDBStorageAdapter(),
});
let HANDLE;
function getVotedKey(docUrl) {
return `p2p-poll-voted:${docUrl}`;
}
function getVotedOptions() {
const key = getVotedKey(document.location.hash);
return new Set(JSON.parse(localStorage.getItem(key) || "[]"));
}
function markVoted(opt) {
const key = getVotedKey(document.location.hash);
const voted = getVotedOptions();
voted.add(opt);
localStorage.setItem(key, JSON.stringify([...voted]));
}
function unmarkVoted(opt) {
const key = getVotedKey(document.location.hash);
const voted = getVotedOptions();
voted.delete(opt);
localStorage.setItem(key, JSON.stringify([...voted]));
}
const locationHash = document.location.hash.substring(1);
const statusEl = document.getElementById("status");
const optionsList = document.getElementById("options-list");
const optionInput = document.getElementById("option-input");
const addBtn = document.getElementById("add-btn");
const duplicateMsg = document.getElementById("duplicate-msg");
const copyBtn = document.getElementById("copy-btn");
const timerEl = document.getElementById("timer");
const startVotingBtn = document.getElementById("start-voting-btn");
if (isValidAutomergeUrl(locationHash)) {
statusEl.textContent = "Loading document…";
try {
HANDLE = await REPO.find(locationHash);
statusEl.textContent = "";
} catch (err) {
statusEl.textContent = "Could not load document. Starting a new one.";
HANDLE = REPO.create({ options: [], votes: {}, deadline: null });
document.location.hash = HANDLE.url;
}
} else {
HANDLE = REPO.create({ options: [], votes: {}, deadline: null });
document.location.hash = HANDLE.url;
}
HANDLE.on("change", ({ doc }) => render(doc));
const initialDoc = HANDLE.doc();
if (initialDoc) render(initialDoc);
let timerInterval = null;
function render(doc) {
renderOptions(doc);
renderTimer(doc);
}
function renderOptions(doc) {
const votes = doc.votes || {};
const deadline = doc.deadline ?? null;
const now = Date.now();
const votingClosed = deadline !== null && now >= deadline;
const votedOptions = getVotedOptions();
const sorted = [...(doc.options || [])].sort(
(a, b) => (votes[b] || 0) - (votes[a] || 0),
);
optionsList.innerHTML = "";
sorted.forEach((opt) => {
const count = votes[opt] || 0;
const alreadyVoted = votedOptions.has(opt);
const item = document.createElement("div");
item.className = "option-item";
const label = document.createElement("span");
label.className = "option-label";
label.textContent = opt;
const voteBtn = document.createElement("button");
voteBtn.className = alreadyVoted ? "vote-btn voted" : "vote-btn";
voteBtn.textContent = alreadyVoted ? `${count}` : `${count}`;
voteBtn.disabled = votingClosed;
if (votingClosed) voteBtn.title = "Voting is closed";
else if (alreadyVoted) voteBtn.title = "Click to remove your vote";
voteBtn.addEventListener("click", () => {
if (alreadyVoted) {
unmarkVoted(opt);
HANDLE.change((d) => {
if (!d.votes) d.votes = {};
d.votes[opt] = Math.max(0, (d.votes[opt] || 0) - 1);
});
} else {
markVoted(opt);
HANDLE.change((d) => {
if (!d.votes) d.votes = {};
d.votes[opt] = (d.votes[opt] || 0) + 1;
});
}
});
item.appendChild(label);
item.appendChild(voteBtn);
optionsList.appendChild(item);
});
}
function renderTimer(doc) {
const deadline = doc?.deadline ?? null;
const now = Date.now();
if (deadline === null) {
timerEl.textContent = "";
startVotingBtn.hidden = false;
return;
}
startVotingBtn.hidden = true;
if (now >= deadline) {
timerEl.textContent = "Voting closed.";
timerEl.className = "timer closed";
clearInterval(timerInterval);
timerInterval = null;
return;
}
const remaining = Math.ceil((deadline - now) / 1000);
const mins = Math.floor(remaining / 60);
const secs = remaining % 60;
timerEl.textContent = `Voting closes in ${mins}:${secs.toString().padStart(2, "0")}`;
timerEl.className = "timer active";
if (!timerInterval) {
timerInterval = setInterval(() => {
const d = HANDLE.doc();
if (!d) return;
renderTimer(d);
renderOptions(d);
if (Date.now() >= d.deadline) {
clearInterval(timerInterval);
timerInterval = null;
}
}, 1000);
}
}
startVotingBtn.addEventListener("click", () => {
HANDLE.change((d) => {
d.deadline = Date.now() + 2 * 60 * 1000;
});
});
addBtn.addEventListener("click", () => {
const value = optionInput.value.trim();
if (!value) return;
const doc = HANDLE.doc();
const valueLower = value.toLowerCase();
const isDuplicate = (doc?.options || []).some(
(opt) => opt.toLowerCase() === valueLower,
);
if (isDuplicate) {
duplicateMsg.textContent = `"${value}" is already in the list.`;
duplicateMsg.hidden = false;
return;
}
duplicateMsg.hidden = true;
HANDLE.change((d) => {
if (!d.options) d.options = [];
d.options.push(value);
});
optionInput.value = "";
});
optionInput.addEventListener("keydown", (e) => {
if (e.key === "Enter") addBtn.click();
});
optionInput.addEventListener("input", () => {
duplicateMsg.hidden = true;
});
copyBtn.addEventListener("click", () => {
navigator.clipboard.writeText(window.location.href).then(() => {
copyBtn.textContent = "Copied!";
setTimeout(() => (copyBtn.textContent = "Copy URL"), 1500);
});
});

31
index.html Normal file
View File

@@ -0,0 +1,31 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>P2P Polling App</title>
<link rel="stylesheet" href="./styles.css" />
</head>
<body>
<div id="app">
<h1>P2P Polling App</h1>
<div id="status"></div>
<div id="add-option">
<input
type="text"
id="option-input"
placeholder="Enter an option..."
/>
<button id="add-btn">Add Option</button>
</div>
<div id="duplicate-msg" hidden></div>
<div id="timer-section">
<div id="timer"></div>
<button id="start-voting-btn">Start 2-min Vote</button>
</div>
<div id="options-list"></div>
<button id="copy-btn">Copy URL</button>
</div>
<script type="module" src="./app.js"></script>
</body>
</html>

23
package.json Normal file
View File

@@ -0,0 +1,23 @@
{
"name": "p2p-poll-app",
"type": "module",
"engines": {
"node": ">=24"
},
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"@automerge/automerge-repo": "^2.0.0",
"@automerge/automerge-repo-network-websocket": "^2.0.0",
"@automerge/automerge-repo-storage-indexeddb": "^2.0.0",
"@automerge/vanillajs": "^2.5.3"
},
"devDependencies": {
"vite": "^6.0.0",
"vite-plugin-top-level-await": "^1.4.0",
"vite-plugin-wasm": "^3.3.0"
}
}

1083
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

93
styles.css Normal file
View File

@@ -0,0 +1,93 @@
body {
font-family: sans-serif;
max-width: 480px;
margin: 40px auto;
padding: 0 16px;
}
#add-option {
display: flex;
gap: 8px;
margin-bottom: 8px;
}
#option-input {
flex: 1;
padding: 8px;
font-size: 1rem;
border: 1px solid #ccc;
border-radius: 4px;
}
#duplicate-msg {
color: #c00;
font-size: 0.9rem;
margin-bottom: 12px;
}
button {
padding: 8px 16px;
font-size: 1rem;
cursor: pointer;
border: 1px solid #ccc;
border-radius: 4px;
background: #fff;
}
button:hover:not(:disabled) {
background: #f0f0f0;
}
button:disabled {
opacity: 0.5;
cursor: default;
}
#timer-section {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 16px;
}
.timer.active {
font-weight: bold;
color: #1a6e1a;
}
.timer.closed {
font-weight: bold;
color: #c00;
}
.option-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 12px;
border: 1px solid #ddd;
border-radius: 4px;
margin-bottom: 8px;
}
.option-label {
flex: 1;
}
.vote-btn {
padding: 4px 12px;
font-size: 0.9rem;
white-space: nowrap;
}
.vote-btn.voted {
background: #e6f4e6;
border-color: #4a9e4a;
color: #2a6e2a;
}
#copy-btn {
margin-top: 16px;
width: 100%;
}

7
vite.config.js Normal file
View File

@@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import wasm from 'vite-plugin-wasm'
import topLevelAwait from 'vite-plugin-top-level-await'
export default defineConfig({
plugins: [wasm(), topLevelAwait()]
})