Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/winner page #281

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
551 changes: 534 additions & 17 deletions package-lock.json

Large diffs are not rendered by default.

13 changes: 11 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"build": "astro build",
"api:stub": "curl 'https://generator3.swagger.io/api/generate' -H 'accept: application/octet-stream' -H 'content-type: application/json' -H 'sec-fetch-dest: empty' -H 'sec-fetch-mode: cors' -H 'sec-fetch-site: same-origin' --data-raw \"{\\\"lang\\\":\\\"nodejs-server\\\",\\\"type\\\":\\\"SERVER\\\",\\\"codegenVersion\\\":\\\"V3\\\",\\\"spec\\\": $(cat ./public/docs/api/v0/openapi.json)}\" > ./stub-server.zip && unzip -o ./stub-server.zip -d ./stub-server && rm ./stub-server.zip && cd ./stub-server && npm install && echo 'STUB-SURVER: http://localhost:8080 && npm start",
"api:sdk": "npx openapi-zod-client@latest ./public/docs/api/v0/openapi.json -o ./src/sdk.ts -p ./prettier.config.mjs -b https://vote.tulsawebdevs.org --api-client-name=sdk --error-expr=\"status >= 300 || status < 200\" --export-schemas --export-types --complexity-threshold=10 --with-deprecated --with-description --with-docs --additional-props-default-value=false && npx -y replace-in-file@^7 --configFile=replaceInFile.config.cjs && npm run format",
"api:sdk:dev": "npx openapi-zod-client@latest ./public/docs/api/v0/openapi.json -o ./src/sdk.ts -p ./prettier.config.mjs -b http://localhost:3000 --api-client-name=sdk --error-expr=\"status >= 300 || status < 200\" --export-schemas --export-types --complexity-threshold=10 --with-deprecated --with-description --with-docs --additional-props-default-value=false && npx -y replace-in-file@^7 --configFile=replaceInFile.config.cjs && npm run format",
"postinstall": "npm run api:sdk",
"api:docs": "npx swagger-ui ./public/docs/api/v0/openapi.json",
"test": "vitest",
Expand All @@ -35,13 +36,12 @@
"@radix-ui/react-radio-group": "1.1.3",
"@radix-ui/react-select": "2.0.0",
"@radix-ui/react-slot": "1.0.2",
"@types/react": "18.3.3",
"@types/react-dom": "18.3.0",
"@vanilla-extract/css": "1.15.3",
"@vanilla-extract/recipes": "0.5.2",
"@zendeskgarden/container-tabs": "2.0.10",
"@zodios/core": "10.9.6",
"astro": "4.8.2",
"canvas-confetti": "^1.9.3",
"class-variance-authority": "0.7.0",
"clsx": "2.1.1",
"lucide-react": "0.372.0",
Expand All @@ -63,13 +63,21 @@
"@eslint/eslintrc": "3.0.2",
"@eslint/js": "8.57.0",
"@playwright/test": "1.41.2",
"@testing-library/dom": "^10.4.0",
"@testing-library/jest-dom": "^6.4.8",
"@testing-library/react": "^16.0.0",
"@testing-library/user-event": "^14.5.2",
"@types/canvas-confetti": "^1.6.4",
"@types/eslint__eslintrc": "2.1.1",
"@types/eslint__js": "8.42.3",
"@types/eslint-config-prettier": "6.11.3",
"@types/node": "20.12.11",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@types/swagger-ui-react": "4.18.3",
"@typescript-eslint/eslint-plugin": "7.0.2",
"@vanilla-extract/vite-plugin": "4.0.11",
"@vitejs/plugin-react": "^4.3.1",
"@vitest/coverage-v8": "1.6.0",
"astro-eslint-parser": "0.17.0",
"autoprefixer": "10.4.19",
Expand All @@ -86,6 +94,7 @@
"eslint-plugin-react-hooks": "4.6.2",
"eslint-plugin-unicorn": "51.0.1",
"eslint-plugin-yml": "1.14.0",
"jsdom": "^24.1.1",
"jsonc-eslint-parser": "2.4.0",
"postcss": "8.4.38",
"prettier": "3.2.5",
Expand Down
60 changes: 60 additions & 0 deletions public/docs/api/v0/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,46 @@
}
],
"paths": {
"/winner": {
"summary": "Retrieve the top voted proposal for upcoming event",
"parameters": [],
"get": {
"operationId": "getVoteWinner",
"parameters": [],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/ProposalWinner" },
"example": {
"id": 1,
"created": "2021-09-01T12:00:00Z",
"updated": "2021-09-01T12:00:00Z",
"title": "My Proposal",
"description": "A longer description of the proposal",
"summary": "A short summary of the proposal",
"authorName": "John Doe",
"type": "topic",
"status": "closed",
"results": [
{ "value": 2, "comment": null },
{ "value": 2, "comment": null },
{ "value": 2, "comment": null },
{ "value": 0, "comment": null },
{ "value": -1, "comment": null },
{ "value": -2, "comment": null }
]
}
}
}
},
"401": { "$ref": "#/components/responses/401" },
"404": { "$ref": "#/components/responses/404" },
"default": { "$ref": "#/components/responses/500" }
}
}
},
"/drafts": {
"summary": "Manage the current user's proposal drafts",
"parameters": [
Expand Down Expand Up @@ -410,6 +450,26 @@
}
]
},
"ProposalWinner": {
"type": "object",
"allOf": [
{ "$ref": "#/components/schemas/Proposal" },
{ "$ref": "#/components/schemas/DatabaseObject" },
{
"type": "object",
"required": ["status", "results", "authorName"],
"properties": {
"authorName": { "type": "string" },
"status": { "type": "string", "enum": ["closed"] },
"userVote": { "$ref": "#/components/schemas/Vote" },
"results": {
"type": "array",
"items": { "$ref": "#/components/schemas/Vote" }
}
}
}
]
},
"Proposal": {
"type": "object",
"required": ["title", "summary", "type"],
Expand Down
9 changes: 0 additions & 9 deletions src/features/voting/ProposalCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,6 @@ export default function ProposalCard(props: ProposalCardProps) {
[props.created],
);

const displayName = useMemo(
() =>
props.authorName
.split(' ')
.map((name) => name[0]?.toUpperCase() ?? '')
.join(''),
[props.authorName],
);

const votes = useMemo(() => {
if (props.status === 'closed') {
return props.results.reduce(
Expand Down
119 changes: 119 additions & 0 deletions src/features/voting/SelectWinner.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import confetti from 'canvas-confetti';
import { toast } from 'sonner';
import { isErrorFromAlias } from '@zodios/core';
import { Button } from '../ui/button.tsx';
import WinningProposal from './WinningProposal.tsx';
import { sdk, type ProposalWinner } from '../../sdk.ts';
import { useClerk } from '../auth/hooks.ts';

export default function SelectWinner() {
const clerkClient = useClerk();
const intervalRef = useRef<ReturnType<typeof setInterval>>();
const [loading, setLoading] = useState(false);
const [countdown, setCountdown] = useState(5);
const [start, setStart] = useState(false);
const [winner, setWinner] = useState<ProposalWinner>();

const onStartCountdown = () => {
setStart(true);

intervalRef.current = setInterval(() => {
setCountdown((previous) => previous - 1);
}, 1000);
};

const handleGetWinner = useCallback(async () => {
if (!clerkClient) return;

try {
setLoading(true);
const token = await clerkClient.session?.getToken();

const result = await sdk.getVoteWinner({
headers: token ? { Authorization: `Bearer ${token}` } : {},
});

setWinner(result);
launchConfetti();
} catch (error) {
handleError(error);
} finally {
setLoading(false);
setCountdown(5);
}
}, [clerkClient]);

useEffect(() => {
if (start && countdown < 1) {
clearInterval(intervalRef.current);
intervalRef.current = undefined;
setStart(false);
void handleGetWinner();
}
}, [countdown, start, handleGetWinner]);

return (
<div>
{start && (
<div
data-testid="winner-countdown"
className="animate-grow-shrink text-center text-9xl font-bold text-white"
>
{countdown}
</div>
)}

{winner && (
<div
data-testid="winner-result"
className="w-full p-3 md:min-w-[375px] md:max-w-[400px] md:p-0 animate-fade-in"
>
{/* eslint-disable-next-line react/jsx-props-no-spreading */}
<WinningProposal {...winner} />
</div>
)}

{!start && !winner && !loading && (
<Button
variant="destructive"
onClick={onStartCountdown}
size="lg"
className="text-xl"
>
Get Winner
</Button>
)}
</div>
);
}

function launchConfetti() {
const _fire = (particleRatio: number, options: confetti.Options) => {
void confetti({
origin: { y: 0.7 },
particleCount: Math.floor(200 * particleRatio),
...options,
});
};

_fire(0.25, { spread: 26, startVelocity: 55 });
_fire(0.2, { spread: 60 });
_fire(0.35, { spread: 100, decay: 0.91, scalar: 0.8 });
_fire(0.1, { spread: 120, startVelocity: 25, decay: 0.92, scalar: 1.2 });
_fire(0.1, { spread: 120, startVelocity: 45 });
}

function handleError(error: unknown) {
if (isErrorFromAlias(sdk.api, 'getVoteWinner', error)) {
if (error.response.status === 401) {
toast.error('You do not have permission to view winners.');
}

if (error.response.status === 404) {
toast.warning(error.response.data.message);
}
} else {
toast.error('Unable to get winner. Please try again.');
}
}
Loading
Loading