91 lines
2.5 KiB
TypeScript
91 lines
2.5 KiB
TypeScript
import {
|
|
castVote,
|
|
createAssemblyDoc,
|
|
putProposal,
|
|
type AssemblyDoc,
|
|
type ProposalRecord,
|
|
type VoteRecord,
|
|
} from "../src/lib/assembly.ts";
|
|
import {
|
|
connectAssemblySync,
|
|
tallyProposal,
|
|
type AssemblySync,
|
|
type VoteTally,
|
|
} from "../src/lib/assemblySync.ts";
|
|
|
|
interface InitOptions {
|
|
room: string;
|
|
signaling: string[];
|
|
}
|
|
|
|
interface CommonsHarness {
|
|
init(opts: InitOptions): string;
|
|
seedProposal(proposal: ProposalRecord): void;
|
|
vote(proposalId: string, voterId: string, choice: VoteRecord["choice"]): void;
|
|
tally(proposalId: string): VoteTally;
|
|
peerCount(): number;
|
|
voteCount(): number;
|
|
online(): boolean;
|
|
setConnected(connected: boolean): void;
|
|
}
|
|
|
|
let assembly: AssemblyDoc | null = null;
|
|
let sync: AssemblySync | null = null;
|
|
|
|
function render(): void {
|
|
const statusEl = document.getElementById("status");
|
|
const tallyEl = document.getElementById("tally");
|
|
if (statusEl && sync) {
|
|
statusEl.textContent = `online=${navigator.onLine} peers=${sync.connectedPeerCount()} votes=${assembly?.votes.size ?? 0}`;
|
|
}
|
|
if (tallyEl && assembly) {
|
|
tallyEl.textContent = JSON.stringify([...assembly.votes.values()], null, 2);
|
|
}
|
|
}
|
|
|
|
const harness: CommonsHarness = {
|
|
init(opts) {
|
|
assembly = createAssemblyDoc();
|
|
sync = connectAssemblySync(assembly, opts.room, {
|
|
signaling: opts.signaling,
|
|
peerOpts: { config: { iceServers: [] } },
|
|
});
|
|
sync.provider.on("peers", render);
|
|
sync.provider.on("synced", render);
|
|
assembly.doc.on("update", render);
|
|
render();
|
|
return sync.room;
|
|
},
|
|
seedProposal(proposal) {
|
|
if (!assembly) throw new Error("harness not initialized");
|
|
putProposal(assembly, proposal);
|
|
},
|
|
vote(proposalId, voterId, choice) {
|
|
if (!assembly) throw new Error("harness not initialized");
|
|
castVote(assembly, { proposalId, voterId, choice, castAt: Date.now() });
|
|
},
|
|
tally(proposalId) {
|
|
if (!assembly) throw new Error("harness not initialized");
|
|
return tallyProposal(assembly, proposalId);
|
|
},
|
|
peerCount() {
|
|
return sync?.connectedPeerCount() ?? 0;
|
|
},
|
|
voteCount() {
|
|
return assembly?.votes.size ?? 0;
|
|
},
|
|
online() {
|
|
return navigator.onLine;
|
|
},
|
|
setConnected(connected) {
|
|
if (!sync) throw new Error("harness not initialized");
|
|
if (connected) sync.provider.connect();
|
|
else sync.provider.disconnect();
|
|
render();
|
|
},
|
|
};
|
|
|
|
(window as unknown as { commons: CommonsHarness }).commons = harness;
|
|
window.addEventListener("online", render);
|
|
window.addEventListener("offline", render);
|