forked from quic-issues/427e7578-d7bf-49c8-aee9-2dd999e25316
p2p poll logic added
This commit is contained in:
68
hooks/usePollManager.ts
Normal file
68
hooks/usePollManager.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
type Option = {
|
||||
id: string;
|
||||
text: string;
|
||||
votes: number;
|
||||
voters: string[];
|
||||
};
|
||||
|
||||
type Poll = {
|
||||
id: string;
|
||||
question: string;
|
||||
options: Option[];
|
||||
};
|
||||
|
||||
export default function usePollManager(peerManager: any) {
|
||||
const [poll, setPoll] = useState<Poll | null>(null);
|
||||
const [myVote, setMyVote] = useState<string | null>(null);
|
||||
|
||||
const createPoll = (question: string, options: string[]) => {
|
||||
const newPoll: Poll = {
|
||||
id: Date.now().toString(),
|
||||
question,
|
||||
options: options.map((opt, i) => ({
|
||||
id: `opt-${i}`,
|
||||
text: opt,
|
||||
votes: 0,
|
||||
voters: [],
|
||||
})),
|
||||
};
|
||||
|
||||
setPoll(newPoll);
|
||||
peerManager.broadcast({ type: "poll", poll: newPoll });
|
||||
};
|
||||
|
||||
const vote = (optionId: string, peerId: string) => {
|
||||
if (!poll) return;
|
||||
|
||||
const updated = { ...poll };
|
||||
|
||||
updated.options.forEach((opt) => {
|
||||
const index = opt.voters.indexOf(peerId);
|
||||
if (index !== -1) {
|
||||
opt.voters.splice(index, 1);
|
||||
opt.votes--;
|
||||
}
|
||||
});
|
||||
|
||||
const option = updated.options.find((o) => o.id === optionId);
|
||||
if (!option) return;
|
||||
|
||||
option.votes++;
|
||||
option.voters.push(peerId);
|
||||
|
||||
setPoll(updated);
|
||||
setMyVote(optionId);
|
||||
|
||||
peerManager.broadcast({
|
||||
type: "vote",
|
||||
optionId,
|
||||
voterId: peerId,
|
||||
});
|
||||
};
|
||||
|
||||
return { poll, createPoll, vote, myVote };
|
||||
}
|
||||
Reference in New Issue
Block a user