This commit is contained in:
2025-12-22 14:47:25 -05:00
parent d4e859f9a7
commit 00e9eb8986
81 changed files with 13933 additions and 0 deletions

24
frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

16
frontend/README.md Normal file
View File

@@ -0,0 +1,16 @@
# React + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and [`typescript-eslint`](https://typescript-eslint.io) in your project.

View File

@@ -0,0 +1,231 @@
{
"$schema": "https://biomejs.dev/schemas/2.3.10/schema.json",
"vcs": { "enabled": false, "clientKind": "git", "useIgnoreFile": false },
"files": { "ignoreUnknown": false },
"formatter": { "enabled": true, "indentStyle": "tab" },
"linter": {
"enabled": true,
"rules": { "recommended": false },
"includes": ["**", "!dist"]
},
"javascript": { "formatter": { "quoteStyle": "double" } },
"overrides": [
{
"includes": ["**/*.{js,jsx}"],
"linter": {
"rules": {
"complexity": {
"noAdjacentSpacesInRegex": "error",
"noExtraBooleanCast": "error",
"noUselessCatch": "error",
"noUselessEscapeInRegex": "error"
},
"correctness": {
"noConstAssign": "error",
"noConstantCondition": "error",
"noEmptyCharacterClassInRegex": "error",
"noEmptyPattern": "error",
"noGlobalObjectCalls": "error",
"noInvalidBuiltinInstantiation": "error",
"noInvalidConstructorSuper": "error",
"noNonoctalDecimalEscape": "error",
"noPrecisionLoss": "error",
"noSelfAssign": "error",
"noSetterReturn": "error",
"noSwitchDeclarations": "error",
"noUndeclaredVariables": "error",
"noUnreachable": "error",
"noUnreachableSuper": "error",
"noUnsafeFinally": "error",
"noUnsafeOptionalChaining": "error",
"noUnusedLabels": "error",
"noUnusedPrivateClassMembers": "error",
"noUnusedVariables": "error",
"useIsNan": "error",
"useValidForDirection": "error",
"useValidTypeof": "error",
"useYield": "error"
},
"suspicious": {
"noAsyncPromiseExecutor": "error",
"noCatchAssign": "error",
"noClassAssign": "error",
"noCompareNegZero": "error",
"noConstantBinaryExpressions": "error",
"noControlCharactersInRegex": "error",
"noDebugger": "error",
"noDuplicateCase": "error",
"noDuplicateClassMembers": "error",
"noDuplicateElseIf": "error",
"noDuplicateObjectKeys": "error",
"noDuplicateParameters": "error",
"noEmptyBlockStatements": "error",
"noFallthroughSwitchClause": "error",
"noFunctionAssign": "error",
"noGlobalAssign": "error",
"noImportAssign": "error",
"noIrregularWhitespace": "error",
"noMisleadingCharacterClass": "error",
"noPrototypeBuiltins": "error",
"noRedeclare": "error",
"noShadowRestrictedNames": "error",
"noSparseArray": "error",
"noUnsafeNegation": "error",
"noUselessRegexBackrefs": "error",
"noWith": "error",
"useGetterReturn": "error"
}
}
}
},
{
"includes": ["**/*.{js,jsx}"],
"linter": {
"rules": {
"correctness": {
"useExhaustiveDependencies": "warn",
"useHookAtTopLevel": "error"
}
}
}
},
{ "includes": ["**/*.{js,jsx}"], "linter": { "rules": {} } },
{
"includes": ["**/*.{js,jsx}"],
"javascript": {
"globals": [
"onanimationend",
"ongamepadconnected",
"onlostpointercapture",
"onanimationiteration",
"onkeyup",
"onmousedown",
"onanimationstart",
"onslotchange",
"onprogress",
"ontransitionstart",
"onpause",
"onended",
"onpointerover",
"onscrollend",
"onformdata",
"ontransitionrun",
"onanimationcancel",
"ondrag",
"onchange",
"onbeforeinstallprompt",
"onbeforexrselect",
"onmessage",
"ontransitioncancel",
"onpointerdown",
"onabort",
"onpointerout",
"oncuechange",
"ongotpointercapture",
"onscrollsnapchanging",
"onsearch",
"onsubmit",
"onstalled",
"onsuspend",
"onreset",
"onerror",
"onresize",
"onmouseenter",
"ongamepaddisconnected",
"ondragover",
"onbeforetoggle",
"onmouseover",
"onpagehide",
"onmousemove",
"onratechange",
"oncommand",
"onmessageerror",
"onwheel",
"ondevicemotion",
"onauxclick",
"ontransitionend",
"onpaste",
"onpageswap",
"ononline",
"ondeviceorientationabsolute",
"onkeydown",
"onclose",
"onselect",
"onpageshow",
"onpointercancel",
"onbeforematch",
"onpointerrawupdate",
"ondragleave",
"onscrollsnapchange",
"onseeked",
"onwaiting",
"onbeforeunload",
"onplaying",
"onvolumechange",
"ondragend",
"onstorage",
"onloadeddata",
"onfocus",
"onoffline",
"onplay",
"onafterprint",
"onclick",
"oncut",
"onmouseout",
"ondblclick",
"oncanplay",
"onloadstart",
"onappinstalled",
"onpointermove",
"ontoggle",
"oncontextmenu",
"onblur",
"oncancel",
"onbeforeprint",
"oncontextrestored",
"onloadedmetadata",
"onpointerup",
"onlanguagechange",
"oncopy",
"onselectstart",
"onscroll",
"onload",
"ondragstart",
"onbeforeinput",
"oncanplaythrough",
"oninput",
"oninvalid",
"ontimeupdate",
"ondurationchange",
"onselectionchange",
"onmouseup",
"location",
"onkeypress",
"onpointerleave",
"oncontextlost",
"ondrop",
"onsecuritypolicyviolation",
"oncontentvisibilityautostatechange",
"ondeviceorientation",
"onseeking",
"onrejectionhandled",
"onunload",
"onmouseleave",
"onhashchange",
"onpointerenter",
"onmousewheel",
"onunhandledrejection",
"ondragenter",
"onpopstate",
"onpagereveal",
"onemptied"
]
},
"linter": { "rules": { "correctness": { "noUnusedVariables": "error" } } }
}
],
"assist": {
"enabled": true,
"actions": { "source": { "organizeImports": "on" } }
}
}

View File

@@ -0,0 +1,29 @@
import js from "@eslint/js";
import globals from "globals";
import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh";
import { defineConfig, globalIgnores } from "eslint/config";
export default defineConfig([
globalIgnores(["dist"]),
{
files: ["**/*.{js,jsx}"],
extends: [
js.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
parserOptions: {
ecmaVersion: "latest",
ecmaFeatures: { jsx: true },
sourceType: "module",
},
},
rules: {
"no-unused-vars": ["error", { varsIgnorePattern: "^[A-Z_]" }],
},
},
]);

View File

@@ -0,0 +1,17 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link
rel="icon"
type="image"
href="https://torrtle.co/content/images/size/w256h256/2024/08/mntCXWP-1-1.png"
/>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ryan's trivia thang</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

3533
frontend/frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,33 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"axios": "^1.13.2",
"jwt-decode": "^4.0.0",
"oidc-client-ts": "^3.4.1",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react-router-dom": "^7.10.1",
"socket.io-client": "^4.8.1"
},
"devDependencies": {
"@biomejs/biome": "2.3.10",
"@eslint/js": "^9.39.1",
"@types/react": "^19.2.5",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.1.1",
"eslint": "^9.39.1",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.24",
"globals": "^16.5.0",
"vite": "^7.2.4"
}
}

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -0,0 +1,43 @@
#root {
/*max-width: 1280px;*/
margin: 0 auto;
width: 100%;
/*padding: 2rem;*/
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}

View File

@@ -0,0 +1,143 @@
import { BrowserRouter as Router, Routes, Route, Navigate } from "react-router-dom";
import { useEffect } from "react";
import { AuthProvider, useAuth } from "./contexts/AuthContext";
import { ProtectedRoute } from "./components/auth/ProtectedRoute";
import Login from "./pages/Login";
import AuthCallback from "./pages/AuthCallback";
import QuestionBankView from "./components/questionbank/QuestionBankView";
import GameSetupView from "./components/questionbank/GameSetupView";
import ContestantView from "./components/contestant/ContestantView";
import GameAdminView from "./components/admin/GameAdminView";
import CategoryManagementView from "./components/categories/CategoryManagementView";
import TemplatesView from "./components/templates/TemplatesView";
import AdminNavbar from "./components/common/AdminNavbar";
import { setAuthTokenGetter } from "./services/api";
import "./App.css";
function HomePage() {
const { user } = useAuth();
return (
<>
<AdminNavbar />
<div style={{ padding: "1rem 2rem", minHeight: "calc(100vh - 60px)" }}>
<h1 style={{ margin: "0 0 1.5rem 0" }}>
Trivia Game - Welcome {user?.profile?.name || user?.profile?.email}
</h1>
<div
style={{
background: "#f0f0f0",
borderRadius: "8px",
padding: "1.5rem",
}}
>
<h3>Quick Start</h3>
<ol>
<li>Create questions in the Question Bank</li>
<li>Create a new game and select questions</li>
<li>Add teams to your game</li>
<li>Open the Contestant View on your TV</li>
<li>Open the Admin View on your laptop to control the game</li>
</ol>
</div>
</div>
</>
);
}
function AppRoutes() {
const { getTokenSilently } = useAuth();
useEffect(() => {
// Set up token getter for API client
setAuthTokenGetter(getTokenSilently);
}, [getTokenSilently]);
return (
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/auth/callback" element={<AuthCallback />} />
{/* Protected routes */}
<Route
path="/"
element={
<ProtectedRoute>
<HomePage />
</ProtectedRoute>
}
/>
<Route
path="/questions"
element={
<ProtectedRoute>
<QuestionBankView />
</ProtectedRoute>
}
/>
<Route
path="/categories"
element={
<ProtectedRoute>
<CategoryManagementView />
</ProtectedRoute>
}
/>
<Route
path="/templates"
element={
<ProtectedRoute>
<TemplatesView />
</ProtectedRoute>
}
/>
<Route
path="/games/setup"
element={
<ProtectedRoute>
<GameSetupView />
</ProtectedRoute>
}
/>
{/* Contestant view - all authenticated users */}
<Route
path="/games/:gameId/contestant"
element={
<ProtectedRoute>
<ContestantView />
</ProtectedRoute>
}
/>
{/* Admin view */}
<Route
path="/games/:gameId/admin"
element={
<ProtectedRoute>
<GameAdminView />
</ProtectedRoute>
}
/>
{/* Catch all - redirect to home */}
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
);
}
function App() {
return (
<Router>
<AuthProvider>
<AppRoutes />
</AuthProvider>
</Router>
);
}
export default App;

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

@@ -0,0 +1,802 @@
import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import { useSocket } from "../../hooks/useSocket";
import { adminAPI, gamesAPI } from "../../services/api";
import AdminNavbar from "../common/AdminNavbar";
import AudioPlayer from "../audio/AudioPlayer";
export default function GameAdminView() {
const { gameId } = useParams();
const { socket, isConnected } = useSocket(gameId, "admin");
const [gameState, setGameState] = useState(null);
const [teams, setTeams] = useState([]);
const [currentQuestion, setCurrentQuestion] = useState(null);
const [questionIndex, setQuestionIndex] = useState(0);
const [totalQuestions, setTotalQuestions] = useState(0);
const [contestantViewUrl, setContestantViewUrl] = useState("");
const [showAnswer, setShowAnswer] = useState(false);
const [isSavingTemplate, setIsSavingTemplate] = useState(false);
const [timerSeconds, setTimerSeconds] = useState(30);
const [timerExpired, setTimerExpired] = useState(false);
const [timerPaused, setTimerPaused] = useState(false);
const [newTeamName, setNewTeamName] = useState("");
useEffect(() => {
loadGameState();
setContestantViewUrl(
`${window.location.origin}/games/${gameId}/contestant`,
);
}, [gameId]);
const loadGameState = async () => {
try {
const response = await adminAPI.getCurrentState(gameId);
setGameState(response.data);
setTeams(response.data.teams || []);
setCurrentQuestion(response.data.current_question);
setQuestionIndex(response.data.current_question_index);
setTotalQuestions(response.data.total_questions);
} catch (error) {
console.error("Error loading game state:", error);
}
};
useEffect(() => {
if (!socket) return;
socket.on("question_with_answer", (data) => {
console.log("Question changed (admin):", data);
setCurrentQuestion(data.question);
setQuestionIndex(data.question_index);
setTotalQuestions(data.total_questions);
setTimerSeconds(30);
setTimerExpired(false);
setTimerPaused(false);
});
socket.on("score_updated", (data) => {
console.log("Score updated:", data);
setTeams(data.all_scores);
});
socket.on("timer_paused", (data) => {
console.log("Timer paused:", data);
setTimerPaused(data.paused);
});
socket.on("lifeline_updated", (data) => {
console.log("Lifeline updated:", data);
setTeams(data.all_scores);
});
socket.on("timer_reset", (data) => {
console.log("Timer reset:", data);
setTimerSeconds(data.seconds);
setTimerExpired(false);
setTimerPaused(false);
});
return () => {
socket.off("question_with_answer");
socket.off("score_updated");
socket.off("timer_paused");
socket.off("lifeline_updated");
socket.off("timer_reset");
};
}, [socket]);
// Reset expired state when timer is reset
useEffect(() => {
if (timerSeconds > 0 && timerExpired) {
setTimerExpired(false);
}
}, [timerSeconds, timerExpired]);
// Timer countdown effect
useEffect(() => {
// Don't run timer if paused, no question is showing, or game is not active
if (timerPaused || !currentQuestion || !gameState?.is_active) {
return;
}
const timer = setInterval(() => {
setTimerSeconds((prev) => {
const newValue = prev - 1;
if (newValue <= 0) {
setTimerExpired(true);
return 0;
}
return newValue;
});
}, 1000);
return () => clearInterval(timer);
}, [timerPaused, currentQuestion, gameState?.is_active]);
const handleStartGame = async () => {
try {
// If game is active, restart (clear scores and reset to waiting state)
if (gameState?.is_active) {
await adminAPI.restartGame(gameId);
loadGameState();
} else {
await adminAPI.startGame(gameId);
loadGameState();
}
} catch (error) {
console.error("Error starting game:", error);
alert("Error starting game");
}
};
const handleNext = async () => {
try {
await adminAPI.nextQuestion(gameId);
// Auto-hide answer when navigating to next question
if (showAnswer) {
await adminAPI.toggleAnswer(gameId, false);
setShowAnswer(false);
}
} catch (error) {
console.error("Error:", error);
if (error.response?.status === 400) {
alert("Already at last question");
}
}
};
const handlePrev = async () => {
try {
await adminAPI.prevQuestion(gameId);
// Auto-hide answer when navigating to previous question
if (showAnswer) {
await adminAPI.toggleAnswer(gameId, false);
setShowAnswer(false);
}
} catch (error) {
console.error("Error:", error);
if (error.response?.status === 400) {
alert("Already at first question");
}
}
};
const handleAwardPoints = async (teamId, points) => {
try {
await adminAPI.awardPoints(gameId, teamId, points);
} catch (error) {
console.error("Error awarding points:", error);
alert("Error awarding points");
}
};
const handleAddTeam = async () => {
if (!newTeamName.trim()) {
alert("Please enter a team name");
return;
}
try {
await gamesAPI.addTeam(gameId, newTeamName.trim());
setNewTeamName("");
loadGameState(); // Reload to get updated team list
} catch (error) {
console.error("Error adding team:", error);
alert("Error adding team");
}
};
const handleUseLifeline = async (teamId) => {
try {
await adminAPI.useLifeline(gameId, teamId);
} catch (error) {
console.error("Error using lifeline:", error);
if (error.response?.data?.error) {
alert(error.response.data.error);
} else {
alert("Error using lifeline");
}
}
};
const handleAddLifeline = async (teamId) => {
try {
await adminAPI.addLifeline(gameId, teamId);
} catch (error) {
console.error("Error adding lifeline:", error);
alert("Error adding lifeline");
}
};
const handleToggleAnswer = async () => {
const newShowAnswer = !showAnswer;
try {
await adminAPI.toggleAnswer(gameId, newShowAnswer);
setShowAnswer(newShowAnswer);
// Pause timer when showing answer
if (newShowAnswer && !timerPaused) {
await adminAPI.pauseTimer(gameId, true);
}
} catch (error) {
console.error("Error toggling answer:", error);
alert("Error toggling answer");
}
};
const handleEndGame = async () => {
if (!window.confirm("Are you sure you want to end this game?")) {
return;
}
try {
await adminAPI.endGame(gameId);
alert("Game ended successfully");
loadGameState();
} catch (error) {
console.error("Error ending game:", error);
alert("Error ending game");
}
};
const handleSaveAsTemplate = async () => {
if (
!window.confirm(
"Save this game as a template? This will allow you to reuse this question set later.",
)
) {
return;
}
try {
setIsSavingTemplate(true);
await gamesAPI.saveAsTemplate(gameId);
alert("Game saved as template successfully!");
} catch (error) {
console.error("Error saving template:", error);
alert("Error saving template");
} finally {
setIsSavingTemplate(false);
}
};
return (
<>
<AdminNavbar />
<div
style={{
padding: "1rem 2rem",
maxWidth: "1400px",
margin: "0 auto",
minHeight: "calc(100vh - 60px)",
}}
>
{/* Header */}
<div
style={{
marginBottom: "1.5rem",
borderBottom: "2px solid #ccc",
paddingBottom: "1rem",
}}
>
<h1 style={{ margin: "0 0 0.75rem 0" }}>
Game Admin - {gameState?.game_name}
</h1>
<div style={{ display: "flex", gap: "1rem", alignItems: "center" }}>
<span>{isConnected ? "● Connected" : "○ Disconnected"}</span>
<button
onClick={() => window.open(contestantViewUrl, "_blank")}
style={{ padding: "0.5rem 1rem" }}
>
Open Contestant View
</button>
</div>
</div>
<div
style={{
display: "grid",
gridTemplateColumns: "1fr 1fr",
gap: "2rem",
}}
>
{/* Current Question with Answer */}
<div>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
marginBottom: "1rem",
}}
>
<h2 style={{ margin: 0 }}>Current Question</h2>
<div
style={{ display: "flex", gap: "0.5rem", alignItems: "center" }}
>
<div
style={{
padding: "0.75rem 1rem",
background: timerExpired
? "#ffebee"
: timerSeconds <= 10
? "#fff3e0"
: "#e8f5e9",
borderRadius: "4px",
fontWeight: "bold",
fontSize: "1.2rem",
color: timerExpired
? "#c62828"
: timerSeconds <= 10
? "#e65100"
: "#2e7d32",
minWidth: "120px",
textAlign: "center",
}}
>
{String(Math.floor(timerSeconds / 60)).padStart(2, "0")}:
{String(timerSeconds % 60).padStart(2, "0")}
{timerExpired && " (EXPIRED)"}
{timerPaused && " (PAUSED)"}
</div>
<button
onClick={async () => {
try {
await adminAPI.pauseTimer(gameId, !timerPaused);
} catch (error) {
console.error("Error toggling timer pause:", error);
}
}}
disabled={timerExpired}
style={{
padding: "0.5rem 1rem",
background: timerExpired
? "#ccc"
: timerPaused
? "#4CAF50"
: "#ff9800",
color: "white",
border: "none",
borderRadius: "4px",
cursor: timerExpired ? "not-allowed" : "pointer",
fontSize: "0.9rem",
}}
>
{timerPaused ? "▶ Resume" : "⏸ Pause"}
</button>
<button
onClick={async () => {
try {
await adminAPI.resetTimer(gameId);
} catch (error) {
console.error("Error resetting timer:", error);
}
}}
style={{
padding: "0.5rem 1rem",
background: "#2196F3",
color: "white",
border: "none",
borderRadius: "4px",
cursor: "pointer",
fontSize: "0.9rem",
}}
>
🔄 Reset
</button>
</div>
</div>
{currentQuestion ? (
<div
style={{
padding: "1.5rem",
border: "2px solid #2196F3",
borderRadius: "8px",
background: "#e3f2fd",
}}
>
{currentQuestion.type === "image" &&
currentQuestion.image_path && (
<img
src={currentQuestion.image_path}
alt="Question"
style={{
maxWidth: "100%",
marginBottom: "1rem",
borderRadius: "8px",
}}
/>
)}
{currentQuestion.type === "youtube_audio" &&
currentQuestion.audio_path && (
<AudioPlayer
audioPath={currentQuestion.audio_path}
isAdmin={true}
socket={socket}
gameId={gameId}
/>
)}
<p
style={{
fontSize: "1.3rem",
fontWeight: "bold",
marginBottom: "1rem",
}}
>
{currentQuestion.question_content}
</p>
<div
style={{
padding: "1rem",
background: "#4CAF50",
color: "white",
borderRadius: "4px",
}}
>
<strong>Answer:</strong> {currentQuestion.answer}
</div>
</div>
) : (
<p>No question selected. Click "Start Game" to begin.</p>
)}
</div>
{/* Team Scoring */}
<div>
<h2>Team Scoring</h2>
<div
style={{ display: "flex", gap: "0.5rem", marginBottom: "1rem" }}
>
<input
type="text"
value={newTeamName}
onChange={(e) => setNewTeamName(e.target.value)}
onKeyPress={(e) => e.key === "Enter" && handleAddTeam()}
placeholder="Enter team name"
style={{
padding: "0.5rem",
flex: 1,
fontSize: "1rem",
borderRadius: "4px",
border: "1px solid #ccc",
}}
/>
<button
onClick={handleAddTeam}
style={{
padding: "0.5rem 1rem",
background: "#4CAF50",
color: "white",
border: "none",
borderRadius: "4px",
cursor: "pointer",
fontSize: "1rem",
}}
>
Add Team
</button>
</div>
{teams.length === 0 ? (
<p>No teams in this game</p>
) : (
<div
style={{
display: "flex",
flexDirection: "column",
gap: "1rem",
}}
>
{teams.map((team) => (
<div
key={team.id}
style={{
padding: "1rem",
border: "1px solid #ccc",
borderRadius: "8px",
background: "white",
}}
>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
marginBottom: "0.5rem",
}}
>
<div
style={{
display: "flex",
alignItems: "center",
gap: "0.5rem",
}}
>
<strong style={{ fontSize: "1.2rem" }}>
{team.name}
</strong>
<span style={{ fontSize: "1rem" }}>
{Array.from({
length: team.phone_a_friend_count || 0,
}).map((_, i) => (
<span key={i}>📞</span>
))}
</span>
</div>
<span
style={{
fontSize: "1.5rem",
fontWeight: "bold",
color: "#2196F3",
}}
>
{team.total_score} pts
</span>
</div>
<div
style={{
display: "flex",
gap: "0.5rem",
flexWrap: "wrap",
}}
>
{[1, 2, 3, 5, 10].map((points) => (
<button
key={points}
onClick={() => handleAwardPoints(team.id, points)}
style={{
padding: "0.5rem 1rem",
background: "#4CAF50",
color: "white",
border: "none",
borderRadius: "4px",
cursor: "pointer",
}}
>
+{points}
</button>
))}
<button
onClick={() => handleAwardPoints(team.id, -1)}
style={{
padding: "0.5rem 1rem",
background: "#f44336",
color: "white",
border: "none",
borderRadius: "4px",
cursor: "pointer",
}}
>
-1
</button>
<button
onClick={() => handleUseLifeline(team.id)}
disabled={team.phone_a_friend_count <= 0}
style={{
padding: "0.5rem 1rem",
background:
team.phone_a_friend_count <= 0 ? "#ccc" : "#ff9800",
color: "white",
border: "none",
borderRadius: "4px",
cursor:
team.phone_a_friend_count <= 0
? "not-allowed"
: "pointer",
}}
>
📞 Use Lifeline
</button>
<button
onClick={() => handleAddLifeline(team.id)}
style={{
padding: "0.5rem 1rem",
background: "#9C27B0",
color: "white",
border: "none",
borderRadius: "4px",
cursor: "pointer",
}}
>
📞 Add Lifeline
</button>
</div>
</div>
))}
</div>
)}
</div>
</div>
{/* Game Controls */}
<div
style={{
background: "#f5f5f5",
borderRadius: "8px",
padding: "1.5rem",
marginTop: "2rem",
}}
>
<h2 style={{ marginTop: 0, marginBottom: "1rem" }}>Game Controls</h2>
{/* Question indicator and timer */}
<div
style={{
display: "flex",
gap: "1rem",
marginBottom: "1rem",
justifyContent: "space-between",
alignItems: "center",
}}
>
<div
style={{
padding: "0.75rem 1rem",
background: "white",
borderRadius: "4px",
fontWeight: "bold",
}}
>
Question {questionIndex + 1} of {totalQuestions}
</div>
<div
style={{ display: "flex", gap: "0.5rem", alignItems: "center" }}
>
<div
style={{
padding: "0.75rem 1rem",
background: timerExpired
? "#ffebee"
: timerSeconds <= 10
? "#fff3e0"
: "#e8f5e9",
borderRadius: "4px",
fontWeight: "bold",
fontSize: "1.2rem",
color: timerExpired
? "#c62828"
: timerSeconds <= 10
? "#e65100"
: "#2e7d32",
minWidth: "120px",
textAlign: "center",
}}
>
{String(Math.floor(timerSeconds / 60)).padStart(2, "0")}:
{String(timerSeconds % 60).padStart(2, "0")}
{timerExpired && " (EXPIRED)"}
{timerPaused && " (PAUSED)"}
</div>
<button
onClick={async () => {
try {
await adminAPI.pauseTimer(gameId, !timerPaused);
} catch (error) {
console.error("Error toggling timer pause:", error);
}
}}
disabled={timerExpired}
style={{
padding: "0.5rem 1rem",
background: timerExpired
? "#ccc"
: timerPaused
? "#4CAF50"
: "#ff9800",
color: "white",
border: "none",
borderRadius: "4px",
cursor: timerExpired ? "not-allowed" : "pointer",
fontSize: "0.9rem",
}}
>
{timerPaused ? "▶ Resume" : "⏸ Pause"}
</button>
</div>
</div>
{/* Button grid - 2 columns */}
<div
style={{
display: "grid",
gridTemplateColumns: "1fr 1fr",
gap: "0.75rem",
}}
>
{currentQuestion && (
<button
onClick={handleToggleAnswer}
style={{
padding: "0.75rem 1.5rem",
background: showAnswer ? "#ff9800" : "#4CAF50",
color: "white",
border: "none",
borderRadius: "4px",
cursor: "pointer",
fontSize: "1rem",
}}
>
{showAnswer ? "Hide Answer" : "Show Answer"}
</button>
)}
<button
onClick={handleNext}
disabled={questionIndex >= totalQuestions - 1}
style={{
padding: "0.75rem 1.5rem",
background:
questionIndex >= totalQuestions - 1 ? "#ccc" : "#2196F3",
color: "white",
border: "none",
borderRadius: "4px",
cursor:
questionIndex >= totalQuestions - 1
? "not-allowed"
: "pointer",
fontSize: "1rem",
}}
>
Next
</button>
<button
onClick={handlePrev}
disabled={questionIndex === 0}
style={{
padding: "0.75rem 1.5rem",
background: questionIndex === 0 ? "#ccc" : "#2196F3",
color: "white",
border: "none",
borderRadius: "4px",
cursor: questionIndex === 0 ? "not-allowed" : "pointer",
fontSize: "1rem",
}}
>
Previous
</button>
<button
onClick={handleSaveAsTemplate}
disabled={isSavingTemplate}
style={{
padding: "0.75rem 1.5rem",
background: isSavingTemplate ? "#ccc" : "#9C27B0",
color: "white",
border: "none",
borderRadius: "4px",
cursor: isSavingTemplate ? "not-allowed" : "pointer",
fontSize: "1rem",
}}
>
{isSavingTemplate ? "Saving..." : "Save as Template"}
</button>
<button
onClick={handleStartGame}
style={{
padding: "0.75rem 1.5rem",
background: "#4CAF50",
color: "white",
border: "none",
borderRadius: "4px",
cursor: "pointer",
fontSize: "1rem",
}}
>
{gameState?.is_active ? "Restart Game" : "Start Game"}
</button>
<button
onClick={handleEndGame}
disabled={!gameState?.is_active}
style={{
padding: "0.75rem 1.5rem",
background: !gameState?.is_active ? "#ccc" : "#f44336",
color: "white",
border: "none",
borderRadius: "4px",
cursor: !gameState?.is_active ? "not-allowed" : "pointer",
fontSize: "1rem",
}}
>
End Game
</button>
</div>
</div>
</div>
</>
);
}

View File

@@ -0,0 +1,247 @@
import { useState, useEffect, useRef } from "react";
import { audioControlAPI } from "../../services/api";
export default function AudioPlayer({ audioPath, isAdmin, socket, gameId }) {
const audioRef = useRef(null);
const [isPlaying, setIsPlaying] = useState(false);
const [currentTime, setCurrentTime] = useState(0);
const [duration, setDuration] = useState(0);
useEffect(() => {
if (!socket || !audioRef.current) return;
// Contestant receives playback commands
if (!isAdmin) {
socket.on("audio_play", () => {
audioRef.current?.play();
setIsPlaying(true);
});
socket.on("audio_pause", () => {
audioRef.current?.pause();
setIsPlaying(false);
});
socket.on("audio_stop", () => {
if (audioRef.current) {
audioRef.current.pause();
audioRef.current.currentTime = 0;
}
setIsPlaying(false);
setCurrentTime(0);
});
socket.on("audio_seek", (data) => {
if (audioRef.current) {
audioRef.current.currentTime = data.position;
}
});
return () => {
socket.off("audio_play");
socket.off("audio_pause");
socket.off("audio_stop");
socket.off("audio_seek");
};
}
}, [socket, isAdmin]);
// Track playback progress
useEffect(() => {
const audio = audioRef.current;
if (!audio) return;
const updateTime = () => setCurrentTime(audio.currentTime);
const updateDuration = () => setDuration(audio.duration);
const handleEnded = () => setIsPlaying(false);
audio.addEventListener("timeupdate", updateTime);
audio.addEventListener("loadedmetadata", updateDuration);
audio.addEventListener("ended", handleEnded);
return () => {
audio.removeEventListener("timeupdate", updateTime);
audio.removeEventListener("loadedmetadata", updateDuration);
audio.removeEventListener("ended", handleEnded);
};
}, []);
// Admin controls
const handlePlay = async () => {
try {
await audioControlAPI.play(gameId);
audioRef.current?.play();
setIsPlaying(true);
} catch (error) {
console.error("Error playing audio:", error);
}
};
const handlePause = async () => {
try {
await audioControlAPI.pause(gameId);
audioRef.current?.pause();
setIsPlaying(false);
} catch (error) {
console.error("Error pausing audio:", error);
}
};
const handleStop = async () => {
try {
await audioControlAPI.stop(gameId);
if (audioRef.current) {
audioRef.current.pause();
audioRef.current.currentTime = 0;
}
setIsPlaying(false);
setCurrentTime(0);
} catch (error) {
console.error("Error stopping audio:", error);
}
};
const handleProgressClick = async (e) => {
if (!isAdmin) return;
const rect = e.currentTarget.getBoundingClientRect();
const x = e.clientX - rect.left;
const percentage = x / rect.width;
const newTime = percentage * duration;
try {
await audioControlAPI.seek(gameId, newTime);
if (audioRef.current) {
audioRef.current.currentTime = newTime;
}
} catch (error) {
console.error("Error seeking audio:", error);
}
};
const formatTime = (seconds) => {
if (!seconds || isNaN(seconds)) return "0:00";
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${mins}:${secs.toString().padStart(2, "0")}`;
};
return (
<div
style={{
background: "#f5f5f5",
padding: "1.5rem",
borderRadius: "8px",
marginTop: "2rem",
}}
>
<audio ref={audioRef} src={audioPath} preload="auto" />
{/* Progress bar */}
<div
style={{
width: "100%",
height: "8px",
background: "#e0e0e0",
borderRadius: "4px",
marginBottom: "1rem",
cursor: isAdmin ? "pointer" : "default",
overflow: "hidden",
}}
onClick={handleProgressClick}
>
<div
style={{
width: `${duration > 0 ? (currentTime / duration) * 100 : 0}%`,
height: "100%",
background: "#2196F3",
borderRadius: "4px",
transition: "width 0.1s ease",
}}
/>
</div>
{/* Time display */}
<div
style={{
display: "flex",
justifyContent: "space-between",
marginBottom: "1rem",
fontSize: "0.875rem",
color: "#666",
}}
>
<span>{formatTime(currentTime)}</span>
<span>{formatTime(duration)}</span>
</div>
{/* Controls (admin only) */}
{isAdmin && (
<div
style={{ display: "flex", gap: "0.5rem", justifyContent: "center" }}
>
<button
onClick={handlePlay}
disabled={isPlaying}
style={{
padding: "0.5rem 1rem",
background: isPlaying ? "#ccc" : "#4CAF50",
color: "white",
border: "none",
borderRadius: "4px",
cursor: isPlaying ? "not-allowed" : "pointer",
fontSize: "1rem",
fontWeight: "500",
}}
>
Play
</button>
<button
onClick={handlePause}
disabled={!isPlaying}
style={{
padding: "0.5rem 1rem",
background: !isPlaying ? "#ccc" : "#ff9800",
color: "white",
border: "none",
borderRadius: "4px",
cursor: !isPlaying ? "not-allowed" : "pointer",
fontSize: "1rem",
fontWeight: "500",
}}
>
Pause
</button>
<button
onClick={handleStop}
style={{
padding: "0.5rem 1rem",
background: "#f44336",
color: "white",
border: "none",
borderRadius: "4px",
cursor: "pointer",
fontSize: "1rem",
fontWeight: "500",
}}
>
Stop
</button>
</div>
)}
{!isAdmin && (
<p
style={{
textAlign: "center",
color: "#666",
fontSize: "0.875rem",
margin: 0,
}}
>
Audio controlled by game host
</p>
)}
</div>
);
}

View File

@@ -0,0 +1,47 @@
import { Navigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
export function ProtectedRoute({ children }) {
const { isAuthenticated, isLoading } = useAuth();
if (isLoading) {
return (
<div
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100vh',
flexDirection: 'column',
gap: '1rem',
}}
>
<div
style={{
border: '4px solid #f3f3f3',
borderTop: '4px solid #3498db',
borderRadius: '50%',
width: '40px',
height: '40px',
animation: 'spin 1s linear infinite',
}}
/>
<p>Loading...</p>
<style>
{`
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
`}
</style>
</div>
);
}
if (!isAuthenticated) {
return <Navigate to="/login" replace />;
}
return children;
}

View File

@@ -0,0 +1,229 @@
import { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { categoriesAPI } from "../../services/api";
import AdminNavbar from "../common/AdminNavbar";
export default function CategoryManagementView() {
const [categories, setCategories] = useState([]);
const [showForm, setShowForm] = useState(false);
const [editingId, setEditingId] = useState(null);
const [formData, setFormData] = useState({ name: "" });
const [error, setError] = useState("");
useEffect(() => {
loadCategories();
}, []);
const loadCategories = async () => {
try {
const response = await categoriesAPI.getAll();
setCategories(response.data);
} catch (error) {
console.error("Error loading categories:", error);
}
};
const handleSubmit = async (e) => {
e.preventDefault();
setError("");
try {
if (editingId) {
await categoriesAPI.update(editingId, formData);
} else {
await categoriesAPI.create(formData);
}
setShowForm(false);
setEditingId(null);
setFormData({ name: "" });
loadCategories();
} catch (error) {
console.error("Error saving category:", error);
if (error.response?.status === 409) {
setError("Category already exists");
} else {
setError("Error saving category");
}
}
};
const handleEdit = (category) => {
setEditingId(category.id);
setFormData({ name: category.name });
setShowForm(true);
setError("");
};
const handleCancelEdit = () => {
setShowForm(false);
setEditingId(null);
setFormData({ name: "" });
setError("");
};
const handleDelete = async (id) => {
if (!confirm("Are you sure you want to delete this category?")) return;
try {
await categoriesAPI.delete(id);
loadCategories();
} catch (error) {
console.error("Error deleting category:", error);
alert("Error deleting category. It may be in use by questions.");
}
};
return (
<>
<AdminNavbar />
<div style={{ padding: "1rem 2rem", minHeight: "calc(100vh - 60px)" }}>
<div
style={{
marginBottom: "1.5rem",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<h1 style={{ margin: "0" }}>Category Management</h1>
<div>
<button
onClick={() => {
setShowForm(!showForm);
if (showForm) handleCancelEdit();
}}
style={{ marginRight: "1rem", padding: "0.5rem 1rem" }}
>
{showForm ? "Cancel" : "Add Category"}
</button>
</div>
</div>
{showForm && (
<form
onSubmit={handleSubmit}
style={{
marginBottom: "2rem",
padding: "1rem",
border: "1px solid #ccc",
borderRadius: "8px",
}}
>
<h3 style={{ marginTop: 0, marginBottom: "1rem" }}>
{editingId ? "Edit Category" : "Add Category"}
</h3>
{error && (
<div
style={{
padding: "0.75rem",
marginBottom: "1rem",
background: "#ffebee",
color: "#c62828",
borderRadius: "4px",
}}
>
{error}
</div>
)}
<div style={{ marginBottom: "1rem" }}>
<label style={{ display: "block", marginBottom: "0.5rem" }}>
Category Name:
</label>
<input
type="text"
value={formData.name}
onChange={(e) => setFormData({ name: e.target.value })}
required
style={{ padding: "0.5rem", width: "100%", maxWidth: "400px" }}
placeholder="e.g., History, Science, Sports"
autoFocus
/>
</div>
<div style={{ display: "flex", gap: "0.5rem" }}>
<button type="submit" style={{ padding: "0.5rem 1rem" }}>
{editingId ? "Update Category" : "Create Category"}
</button>
{editingId && (
<button
type="button"
onClick={handleCancelEdit}
style={{ padding: "0.5rem 1rem", background: "#ccc" }}
>
Cancel
</button>
)}
</div>
</form>
)}
<div>
<h2>Categories ({categories.length})</h2>
{categories.length === 0 ? (
<p>No categories yet. Create your first category above!</p>
) : (
<div style={{ display: "grid", gap: "1rem", maxWidth: "600px" }}>
{categories.map((category) => (
<div
key={category.id}
style={{
padding: "1rem",
border: "1px solid #ccc",
borderRadius: "8px",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<div>
<span
style={{
background: "#e8f5e9",
padding: "0.5rem 1rem",
borderRadius: "4px",
fontSize: "1rem",
color: "#2e7d32",
fontWeight: "bold",
}}
>
{category.name}
</span>
</div>
<div style={{ display: "flex", gap: "0.5rem" }}>
<button
onClick={() => handleEdit(category)}
style={{
padding: "0.5rem 1rem",
background: "#2196F3",
color: "white",
border: "none",
borderRadius: "4px",
cursor: "pointer",
}}
>
Edit
</button>
<button
onClick={() => handleDelete(category.id)}
style={{
padding: "0.5rem 1rem",
background: "#f44336",
color: "white",
border: "none",
borderRadius: "4px",
cursor: "pointer",
}}
>
Delete
</button>
</div>
</div>
))}
</div>
)}
</div>
</div>
</>
);
}

View File

@@ -0,0 +1,116 @@
import { Link, useLocation } from "react-router-dom";
import { useAuth } from "../../contexts/AuthContext";
export default function AdminNavbar() {
const location = useLocation();
const { user, logout } = useAuth();
const navItems = [
{ path: "/", label: "Home" },
{ path: "/questions", label: "Questions" },
{ path: "/categories", label: "Categories" },
{ path: "/templates", label: "Templates" },
{ path: "/games/setup", label: "New Game" },
];
const isActive = (path) => {
if (path === "/") {
return location.pathname === "/";
}
return location.pathname.startsWith(path);
};
return (
<nav
style={{
background: "black",
padding: "1rem 2rem",
position: "sticky",
top: 0,
zIndex: 1000,
}}
>
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
}}
>
<div style={{ display: "flex", alignItems: "center", gap: "0.5rem" }}>
<span
style={{ fontSize: "1.5rem", fontWeight: "bold", color: "white" }}
>
🎮 Trivia Admin
</span>
</div>
<div style={{ display: "flex", gap: "1rem", alignItems: "center" }}>
{navItems.map((item) => (
<Link
key={item.path}
to={item.path}
style={{
textDecoration: "none",
padding: "0.5rem 1rem",
borderRadius: "8px",
background: isActive(item.path) ? "white" : "transparent",
color: isActive(item.path) ? "black" : "white",
fontWeight: isActive(item.path) ? "bold" : "normal",
transition: "all 0.2s ease",
}}
onMouseEnter={(e) => {
if (!isActive(item.path)) {
e.target.style.background = "#333";
}
}}
onMouseLeave={(e) => {
if (!isActive(item.path)) {
e.target.style.background = "transparent";
}
}}
>
{item.label}
</Link>
))}
{/* User info and logout */}
<div
style={{
display: "flex",
gap: "0.75rem",
alignItems: "center",
marginLeft: "1rem",
paddingLeft: "1rem",
borderLeft: "1px solid #444",
}}
>
<span style={{ color: "white", fontSize: "0.9rem" }}>
{user?.profile?.name || user?.profile?.email}
</span>
<button
onClick={logout}
style={{
padding: "0.5rem 1rem",
background: "#e74c3c",
color: "white",
border: "none",
borderRadius: "6px",
cursor: "pointer",
fontSize: "0.9rem",
fontWeight: "500",
transition: "all 0.2s ease",
}}
onMouseEnter={(e) => {
e.target.style.background = "#c0392b";
}}
onMouseLeave={(e) => {
e.target.style.background = "#e74c3c";
}}
>
Logout
</button>
</div>
</div>
</div>
</nav>
);
}

View File

@@ -0,0 +1,508 @@
import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import { useSocket } from "../../hooks/useSocket";
import { gamesAPI } from "../../services/api";
import AudioPlayer from "../audio/AudioPlayer";
export default function ContestantView() {
const { gameId } = useParams();
const { socket, isConnected } = useSocket(gameId, "contestant");
const [currentQuestion, setCurrentQuestion] = useState(null);
const [scores, setScores] = useState([]);
const [gameName, setGameName] = useState("");
const [showAnswer, setShowAnswer] = useState(false);
const [answer, setAnswer] = useState("");
const [gameStartTime, setGameStartTime] = useState(null);
const [currentTime, setCurrentTime] = useState(new Date());
const [timerSeconds, setTimerSeconds] = useState(30);
const [timerActive, setTimerActive] = useState(false);
const [timerPaused, setTimerPaused] = useState(false);
const [categories, setCategories] = useState([]);
useEffect(() => {
// Load initial game state
const loadGameState = async () => {
try {
const response = await gamesAPI.getOne(gameId);
setGameName(response.data.name);
setScores(response.data.teams || []);
// Extract unique categories from game questions
if (response.data.questions) {
const uniqueCategories = [
...new Set(
response.data.questions
.map((q) => q.question?.category)
.filter((cat) => cat), // Remove null/undefined
),
];
setCategories(uniqueCategories);
}
} catch (error) {
console.error("Error loading game:", error);
}
};
loadGameState();
}, [gameId]);
// Update system clock every second
useEffect(() => {
const timer = setInterval(() => {
setCurrentTime(new Date());
}, 1000);
return () => clearInterval(timer);
}, []);
// Timer countdown effect
useEffect(() => {
console.log(
"Timer effect running: timerActive=",
timerActive,
"timerPaused=",
timerPaused,
"currentQuestion=",
currentQuestion,
);
// Don't run timer if not active, if paused, or if no question is showing
if (!timerActive || timerPaused || !currentQuestion) {
console.log(
"Timer not starting - either not active, paused, or no question",
);
return;
}
// Start the countdown
console.log("Starting timer countdown");
const timer = setInterval(() => {
setTimerSeconds((prev) => {
if (prev <= 1) {
setTimerActive(false);
return 0;
}
return prev - 1;
});
}, 1000);
// Cleanup: stop the timer when effect re-runs or component unmounts
return () => {
console.log("Cleaning up timer interval");
clearInterval(timer);
};
}, [timerActive, timerPaused, currentQuestion]);
useEffect(() => {
if (!socket) return;
socket.on("game_started", (data) => {
console.log("Game started:", data);
setGameName(data.game_name);
setGameStartTime(new Date());
});
socket.on("question_changed", (data) => {
console.log("Question changed:", data);
setCurrentQuestion(data.question);
setShowAnswer(false); // Hide answer when question changes
setAnswer("");
setTimerSeconds(30);
setTimerActive(true);
setTimerPaused(false);
});
socket.on("score_updated", (data) => {
console.log("Score updated:", data);
setScores(data.all_scores);
});
socket.on("answer_visibility_changed", (data) => {
console.log("Answer visibility changed:", data);
setShowAnswer(data.show_answer);
if (data.show_answer && data.answer) {
setAnswer(data.answer);
} else {
setAnswer("");
}
});
socket.on("timer_paused", (data) => {
console.log("Timer paused event received:", data);
console.log("Setting timerPaused to:", data.paused);
setTimerPaused(data.paused);
});
socket.on("game_ended", (data) => {
console.log("Game ended:", data);
setCurrentQuestion(null);
setShowAnswer(false);
setAnswer("");
setGameStartTime(null);
setTimerSeconds(30);
setTimerActive(false);
setTimerPaused(false);
});
socket.on("lifeline_updated", (data) => {
console.log("Lifeline updated:", data);
setScores(data.all_scores);
});
socket.on("timer_reset", (data) => {
console.log("Timer reset:", data);
setTimerSeconds(data.seconds);
setTimerActive(true);
setTimerPaused(false);
});
return () => {
socket.off("game_started");
socket.off("question_changed");
socket.off("score_updated");
socket.off("answer_visibility_changed");
socket.off("timer_paused");
socket.off("game_ended");
socket.off("lifeline_updated");
socket.off("timer_reset");
};
}, [socket]);
// Sort scores by score descending (auto-sorted leaderboard)
const sortedScores = [...scores].sort((a, b) => {
const scoreA = a.score || a.total_score || 0;
const scoreB = b.score || b.total_score || 0;
return scoreB - scoreA;
});
// Format system clock
const formatSystemTime = () => {
return currentTime.toLocaleTimeString("en-US", {
hour: "2-digit",
minute: "2-digit",
hour12: true,
});
};
// Format game clock (elapsed time)
const formatGameTime = () => {
if (!gameStartTime) return "00:00:00";
const elapsed = Math.floor((currentTime - gameStartTime) / 1000);
const hours = Math.floor(elapsed / 3600);
const minutes = Math.floor((elapsed % 3600) / 60);
const seconds = elapsed % 60;
return `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
};
return (
<div
style={{
minHeight: "100vh",
background: "white",
color: "black",
display: "flex",
flexDirection: "column",
// padding: "3rem",
width: "100%",
}}
>
{/* Header */}
<div
style={{
textAlign: "left",
marginBottom: "0.5rem",
paddingBottom: "0.5rem",
paddingTop: "1rem",
paddingLeft: "2rem",
paddingRight: "2rem",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<h1
style={{
fontSize: "3rem",
margin: "0",
fontWeight: "normal",
}}
>
{gameName || "Trivia Game"}
</h1>
<div
style={{
fontSize: "1.5rem",
color: "#666",
display: "flex",
gap: "2rem",
alignItems: "center",
}}
>
<div
style={{
fontSize: "2.5rem",
fontWeight: "bold",
color:
timerSeconds <= 10
? timerSeconds === 0
? "#666"
: "#f44336"
: "#4CAF50",
minWidth: "80px",
textAlign: "center",
}}
>
{String(Math.floor(timerSeconds / 60)).padStart(2, "0")}:
{String(timerSeconds % 60).padStart(2, "0")}
</div>
<div>{formatSystemTime()}</div>
</div>
</div>
{/* Main content area */}
<div
style={{ flex: 1, display: "flex", gap: "4rem", overflow: "hidden" }}
>
{/* Left side: Question Display */}
<div
style={{
flex: "2",
display: "flex",
alignItems: "flex-start",
justifyContent: "center",
overflow: "auto",
}}
>
<div
style={{
padding: "1rem 2rem 0 2rem",
width: "100%",
minHeight: "400px",
display: "flex",
alignItems: "flex-start",
justifyContent: "center",
}}
>
{currentQuestion ? (
<div style={{ width: "100%", textAlign: "center" }}>
{/* Timer progress bar */}
<div
style={{
width: "100%",
height: "8px",
background: "#e0e0e0",
borderRadius: "4px",
marginBottom: "2rem",
overflow: "hidden",
}}
>
<div
style={{
width: `${(timerSeconds / 30) * 100}%`,
height: "100%",
background:
timerSeconds > 10
? "#4CAF50"
: timerSeconds > 5
? "#ff9800"
: "#f44336",
transition: "width 1s linear, background 0.3s ease",
}}
/>
</div>
{currentQuestion.category && (
<div
style={{
fontSize: "1.5rem",
fontWeight: "normal",
textAlign: "center",
marginBottom: "1.5rem",
textTransform: "uppercase",
letterSpacing: "5px",
color: "#999",
}}
>
{currentQuestion.category}
</div>
)}
{currentQuestion.type === "image" &&
currentQuestion.image_path && (
<img
src={currentQuestion.image_path}
alt="Question"
style={{
maxWidth: "100%",
maxHeight: "500px",
margin: "0 auto 3rem",
display: "block",
}}
/>
)}
{currentQuestion.type === "youtube_audio" &&
currentQuestion.audio_path && (
<AudioPlayer
audioPath={currentQuestion.audio_path}
isAdmin={false}
socket={socket}
gameId={gameId}
/>
)}
<p
style={{
fontSize: "4rem",
fontWeight: "normal",
textAlign: "center",
margin: 0,
lineHeight: "1.2",
}}
>
{currentQuestion.question_content}
</p>
{showAnswer && answer && (
<div
style={{
marginTop: "4rem",
padding: "3rem",
background: "black",
color: "white",
}}
>
<div
style={{
fontSize: "1.5rem",
fontWeight: "normal",
marginBottom: "1rem",
letterSpacing: "3px",
}}
>
ANSWER:
</div>
<div style={{ fontSize: "3.5rem", fontWeight: "normal" }}>
{answer}
</div>
</div>
)}
</div>
) : (
<div style={{ textAlign: "center", width: "100%" }}>
<p
style={{
fontSize: "2.5rem",
color: "#666",
marginBottom: "3rem",
}}
>
Waiting for game to start...
</p>
{categories.length > 0 && (
<div>
<h2
style={{
fontSize: "2rem",
color: "#999",
marginBottom: "2rem",
letterSpacing: "3px",
textTransform: "uppercase",
}}
>
Categories
</h2>
<div
style={{
display: "flex",
flexWrap: "wrap",
gap: "1.5rem",
justifyContent: "center",
maxWidth: "800px",
margin: "0 auto",
}}
>
{categories.map((category, index) => (
<div
key={index}
style={{
padding: "1rem 2rem",
background: "#f5f5f5",
borderRadius: "8px",
fontSize: "1.8rem",
color: "#333",
}}
>
{category}
</div>
))}
</div>
</div>
)}
</div>
)}
</div>
</div>
{/* Right side: Scoreboard */}
<div
style={{
flex: "1",
display: "flex",
flexDirection: "column",
overflow: "hidden",
paddingRight: "100px",
}}
>
<h2
style={{
margin: "0 0 2rem 0",
fontSize: "2rem",
fontWeight: "normal",
}}
>
Teams
</h2>
{sortedScores.length === 0 ? (
<p style={{ color: "#999", margin: 0 }}>No teams yet</p>
) : (
<div
style={{
display: "flex",
flexDirection: "column",
gap: "1.5rem",
overflow: "auto",
}}
>
{sortedScores.map((team, index) => (
<div
key={team.team_id || team.id}
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "baseline",
fontSize: "1.8rem",
}}
>
<div
style={{
display: "flex",
alignItems: "center",
gap: "0.5rem",
}}
>
<span>{team.team_name || team.name}</span>
<span style={{ fontSize: "1.2rem" }}>
{Array.from({
length: team.phone_a_friend_count || 0,
}).map((_, i) => (
<span key={i}>📞</span>
))}
</span>
</div>
<div style={{ fontWeight: "bold" }}>
{team.score || team.total_score || 0}
</div>
</div>
))}
</div>
)}
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,741 @@
import { useState, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
import { questionsAPI, gamesAPI } from "../../services/api";
import AdminNavbar from "../common/AdminNavbar";
export default function GameSetupView() {
const navigate = useNavigate();
const [questions, setQuestions] = useState([]);
const [selectedQuestions, setSelectedQuestions] = useState([]);
const [gameName, setGameName] = useState("");
const [teams, setTeams] = useState([]);
const [newTeamName, setNewTeamName] = useState("");
const [showTemplateModal, setShowTemplateModal] = useState(false);
const [templates, setTemplates] = useState([]);
const [randomSelections, setRandomSelections] = useState({});
useEffect(() => {
loadQuestions();
}, []);
const loadQuestions = async () => {
try {
const response = await questionsAPI.getAll();
setQuestions(response.data);
} catch (error) {
console.error("Error loading questions:", error);
}
};
const loadTemplates = async () => {
try {
const response = await gamesAPI.getTemplates();
setTemplates(response.data);
} catch (error) {
console.error("Error loading templates:", error);
}
};
const handleLoadTemplate = async (template) => {
try {
const response = await gamesAPI.getOne(template.id);
// Pre-fill form with template data
setGameName(template.name + " (Copy)");
const templateQuestions = response.data.game_questions.map(
(gq) => gq.question,
);
setQuestions((prev) => {
// Merge template questions with existing questions, avoiding duplicates
const existingIds = new Set(prev.map((q) => q.id));
const newQuestions = templateQuestions.filter(
(q) => !existingIds.has(q.id),
);
return [...prev, ...newQuestions];
});
setSelectedQuestions(templateQuestions.map((q) => q.id));
setShowTemplateModal(false);
alert(
`Loaded ${templateQuestions.length} questions from template "${template.name}"`,
);
} catch (error) {
console.error("Error loading template:", error);
alert("Error loading template");
}
};
// Group questions by category
const groupedQuestions = questions.reduce((groups, question) => {
const category = question.category || "Uncategorized";
if (!groups[category]) {
groups[category] = [];
}
groups[category].push(question);
return groups;
}, {});
const categoryNames = Object.keys(groupedQuestions).sort();
const toggleQuestion = (questionId) => {
setSelectedQuestions((prev) =>
prev.includes(questionId)
? prev.filter((id) => id !== questionId)
: [...prev, questionId],
);
};
const moveQuestion = (index, direction) => {
const newOrder = [...selectedQuestions];
const targetIndex = direction === "up" ? index - 1 : index + 1;
if (targetIndex >= 0 && targetIndex < newOrder.length) {
[newOrder[index], newOrder[targetIndex]] = [
newOrder[targetIndex],
newOrder[index],
];
setSelectedQuestions(newOrder);
}
};
const removeQuestion = (questionId) => {
setSelectedQuestions((prev) => prev.filter((id) => id !== questionId));
};
const addTeam = () => {
if (newTeamName.trim()) {
setTeams([...teams, newTeamName.trim()]);
setNewTeamName("");
}
};
const removeTeam = (index) => {
setTeams(teams.filter((_, i) => i !== index));
};
const updateRandomSelection = (category, count) => {
setRandomSelections((prev) => ({
...prev,
[category]: count,
}));
};
const addRandomQuestions = async () => {
try {
const newQuestionIds = [];
for (const [category, count] of Object.entries(randomSelections)) {
if (count > 0) {
const response = await questionsAPI.getRandomByCategory(
category,
count,
);
const randomQuestions = response.data.questions;
// Add to questions list if not already there
setQuestions((prev) => {
const existingIds = new Set(prev.map((q) => q.id));
const newQuestions = randomQuestions.filter(
(q) => !existingIds.has(q.id),
);
return [...prev, ...newQuestions];
});
// Add question IDs to selected list
randomQuestions.forEach((q) => {
if (!selectedQuestions.includes(q.id)) {
newQuestionIds.push(q.id);
}
});
}
}
if (newQuestionIds.length > 0) {
setSelectedQuestions((prev) => [...prev, ...newQuestionIds]);
alert(`Added ${newQuestionIds.length} random questions to your game!`);
}
// Reset selections
setRandomSelections({});
} catch (error) {
console.error("Error adding random questions:", error);
alert(
"Error adding random questions: " +
(error.response?.data?.error || error.message),
);
}
};
const handleCreateGame = async () => {
if (!gameName.trim()) {
alert("Please enter a game name");
return;
}
if (selectedQuestions.length === 0) {
alert("Please select at least one question");
return;
}
if (teams.length === 0) {
alert("Please add at least one team");
return;
}
try {
// Create game
const gameResponse = await gamesAPI.create({ name: gameName });
const gameId = gameResponse.data.id;
// Add questions to game in the specified order
await gamesAPI.addQuestions(gameId, selectedQuestions);
// Add teams to game
for (const teamName of teams) {
await gamesAPI.addTeam(gameId, teamName);
}
alert("Game created successfully!");
navigate(`/games/${gameId}/admin`);
} catch (error) {
console.error("Error creating game:", error);
alert("Error creating game");
}
};
const getQuestionById = (id) => questions.find((q) => q.id === id);
return (
<>
<AdminNavbar />
<div
style={{
padding: "1rem 2rem",
minHeight: "calc(100vh - 60px)",
display: "flex",
justifyContent: "center",
}}
>
<div style={{ maxWidth: "900px", width: "100%" }}>
<h1 style={{ margin: "0 0 1.5rem 0" }}>Create New Game</h1>
<button
onClick={() => {
loadTemplates();
setShowTemplateModal(true);
}}
style={{
padding: "0.5rem 1rem",
marginBottom: "1.5rem",
background: "#9C27B0",
color: "white",
border: "none",
borderRadius: "4px",
cursor: "pointer",
}}
>
Load from Template
</button>
<div style={{ marginBottom: "1.5rem" }}>
<h2 style={{ marginTop: "0", marginBottom: "0.75rem" }}>
1. Game Name
</h2>
<input
type="text"
value={gameName}
onChange={(e) => setGameName(e.target.value)}
placeholder="Enter game name"
style={{
padding: "0.5rem",
width: "100%",
fontSize: "1rem",
boxSizing: "border-box",
}}
/>
</div>
<div
style={{
marginBottom: "1.5rem",
padding: "1rem",
background: "#fff3e0",
borderRadius: "8px",
border: "2px solid #ff9800",
}}
>
<h2
style={{
marginTop: "0",
marginBottom: "0.75rem",
color: "#e65100",
}}
>
2. Add Random Questions (Quick Setup)
</h2>
<p
style={{
margin: "0 0 1rem 0",
color: "#666",
fontSize: "0.9rem",
}}
>
Select how many random questions to add from each category
</p>
{categoryNames.length === 0 ? (
<p>No questions available yet.</p>
) : (
<>
<div
style={{
display: "grid",
gap: "0.75rem",
marginBottom: "1rem",
}}
>
{categoryNames.map((category) => {
const categoryCount = groupedQuestions[category].length;
return (
<div
key={category}
style={{
display: "flex",
alignItems: "center",
gap: "1rem",
padding: "0.75rem",
background: "white",
borderRadius: "4px",
border: "1px solid #ddd",
}}
>
<div style={{ flex: 1 }}>
<strong>{category}</strong>
<span
style={{
color: "#666",
fontSize: "0.9rem",
marginLeft: "0.5rem",
}}
>
({categoryCount} available)
</span>
</div>
<div
style={{
display: "flex",
alignItems: "center",
gap: "0.5rem",
}}
>
<label
htmlFor={`random-${category}`}
style={{ fontSize: "0.9rem" }}
>
Add:
</label>
<input
id={`random-${category}`}
type="number"
min="0"
max={categoryCount}
value={randomSelections[category] || 0}
onChange={(e) =>
updateRandomSelection(
category,
parseInt(e.target.value) || 0,
)
}
style={{
width: "70px",
padding: "0.5rem",
fontSize: "1rem",
textAlign: "center",
}}
/>
<span style={{ fontSize: "0.9rem", color: "#666" }}>
questions
</span>
</div>
</div>
);
})}
</div>
<button
onClick={addRandomQuestions}
disabled={Object.values(randomSelections).every(
(count) => count === 0,
)}
style={{
padding: "0.75rem 1.5rem",
background: Object.values(randomSelections).every(
(count) => count === 0,
)
? "#ccc"
: "#ff9800",
color: "white",
border: "none",
borderRadius: "4px",
cursor: Object.values(randomSelections).every(
(count) => count === 0,
)
? "not-allowed"
: "pointer",
fontWeight: "bold",
}}
>
Add Random Questions to Game
</button>
</>
)}
</div>
<div style={{ marginBottom: "1.5rem" }}>
<h2 style={{ marginTop: "0", marginBottom: "0.75rem" }}>
3. Select Questions Manually ({selectedQuestions.length} selected)
</h2>
{questions.length === 0 ? (
<p>
No questions available.{" "}
<Link to="/questions">Create some questions first</Link>
</p>
) : (
<div style={{ display: "grid", gap: "1.5rem" }}>
{categoryNames.map((category) => (
<div
key={category}
style={{
border: "1px solid #ddd",
borderRadius: "8px",
padding: "1rem",
}}
>
<h3
style={{
marginTop: 0,
marginBottom: "1rem",
color: "#2e7d32",
}}
>
{category}
</h3>
<div style={{ display: "grid", gap: "0.5rem" }}>
{groupedQuestions[category].map((q) => (
<div
key={q.id}
onClick={() => toggleQuestion(q.id)}
style={{
padding: "0.75rem",
border: `2px solid ${selectedQuestions.includes(q.id) ? "#4CAF50" : "#ccc"}`,
borderRadius: "4px",
cursor: "pointer",
background: selectedQuestions.includes(q.id)
? "#e8f5e9"
: "white",
}}
>
<div
style={{
display: "flex",
alignItems: "center",
gap: "1rem",
}}
>
<input
type="checkbox"
checked={selectedQuestions.includes(q.id)}
readOnly
style={{ cursor: "pointer" }}
/>
<div style={{ flex: 1 }}>
<span
style={{
background:
q.type === "image" ? "#e3f2fd" : "#f3e5f5",
padding: "0.25rem 0.5rem",
borderRadius: "4px",
fontSize: "0.8rem",
marginRight: "0.5rem",
}}
>
{q.type.toUpperCase()}
</span>
<span>{q.question_content}</span>
</div>
</div>
</div>
))}
</div>
</div>
))}
</div>
)}
</div>
{selectedQuestions.length > 0 && (
<div
style={{
marginBottom: "1.5rem",
padding: "1rem",
background: "#f5f5f5",
borderRadius: "8px",
}}
>
<h3 style={{ marginTop: 0, marginBottom: "0.75rem" }}>
Question Order
</h3>
<div style={{ display: "grid", gap: "0.5rem" }}>
{selectedQuestions.map((qId, index) => {
const question = getQuestionById(qId);
if (!question) return null;
return (
<div
key={qId}
style={{
padding: "0.75rem",
background: "white",
border: "1px solid #ddd",
borderRadius: "4px",
display: "flex",
alignItems: "center",
gap: "1rem",
}}
>
<span style={{ fontWeight: "bold", minWidth: "30px" }}>
#{index + 1}
</span>
<div style={{ flex: 1 }}>
{question.category && (
<span
style={{
background: "#e8f5e9",
padding: "0.25rem 0.5rem",
borderRadius: "4px",
fontSize: "0.8rem",
color: "#2e7d32",
marginRight: "0.5rem",
}}
>
{question.category}
</span>
)}
<span
style={{
background:
question.type === "image" ? "#e3f2fd" : "#f3e5f5",
padding: "0.25rem 0.5rem",
borderRadius: "4px",
fontSize: "0.8rem",
marginRight: "0.5rem",
}}
>
{question.type.toUpperCase()}
</span>
<span>{question.question_content}</span>
</div>
<div style={{ display: "flex", gap: "0.25rem" }}>
<button
onClick={() => moveQuestion(index, "up")}
disabled={index === 0}
style={{
padding: "0.25rem 0.5rem",
background: index === 0 ? "#ddd" : "#2196F3",
color: "white",
border: "none",
borderRadius: "4px",
cursor: index === 0 ? "not-allowed" : "pointer",
}}
>
</button>
<button
onClick={() => moveQuestion(index, "down")}
disabled={index === selectedQuestions.length - 1}
style={{
padding: "0.25rem 0.5rem",
background:
index === selectedQuestions.length - 1
? "#ddd"
: "#2196F3",
color: "white",
border: "none",
borderRadius: "4px",
cursor:
index === selectedQuestions.length - 1
? "not-allowed"
: "pointer",
}}
>
</button>
<button
onClick={() => removeQuestion(qId)}
style={{
padding: "0.25rem 0.5rem",
background: "#f44336",
color: "white",
border: "none",
borderRadius: "4px",
cursor: "pointer",
}}
>
</button>
</div>
</div>
);
})}
</div>
</div>
)}
<div style={{ marginBottom: "1.5rem" }}>
<h2 style={{ marginTop: "0", marginBottom: "0.75rem" }}>
4. Add Teams
</h2>
<div
style={{ display: "flex", gap: "0.5rem", marginBottom: "1rem" }}
>
<input
type="text"
value={newTeamName}
onChange={(e) => setNewTeamName(e.target.value)}
onKeyPress={(e) => e.key === "Enter" && addTeam()}
placeholder="Enter team name"
style={{ padding: "0.5rem", flex: 1 }}
/>
<button onClick={addTeam} style={{ padding: "0.5rem 1rem" }}>
Add Team
</button>
</div>
<div style={{ display: "flex", flexWrap: "wrap", gap: "0.5rem" }}>
{teams.map((team, index) => (
<div
key={index}
style={{
padding: "0.5rem 1rem",
background: "#e3f2fd",
borderRadius: "20px",
display: "flex",
alignItems: "center",
gap: "0.5rem",
}}
>
<span>{team}</span>
<button
onClick={() => removeTeam(index)}
style={{
background: "none",
border: "none",
cursor: "pointer",
color: "#f44336",
fontWeight: "bold",
}}
>
×
</button>
</div>
))}
</div>
</div>
<button
onClick={handleCreateGame}
disabled={
!gameName || selectedQuestions.length === 0 || teams.length === 0
}
style={{
padding: "1rem 2rem",
fontSize: "1.1rem",
background:
!gameName ||
selectedQuestions.length === 0 ||
teams.length === 0
? "#ccc"
: "#4CAF50",
color: "white",
border: "none",
borderRadius: "8px",
cursor:
!gameName ||
selectedQuestions.length === 0 ||
teams.length === 0
? "not-allowed"
: "pointer",
width: "100%",
}}
>
Create Game & Go to Admin View
</button>
{showTemplateModal && (
<div
style={{
position: "fixed",
top: 0,
left: 0,
right: 0,
bottom: 0,
background: "rgba(0,0,0,0.5)",
display: "flex",
alignItems: "center",
justifyContent: "center",
zIndex: 1000,
}}
>
<div
style={{
background: "white",
padding: "2rem",
borderRadius: "8px",
maxWidth: "600px",
maxHeight: "80vh",
overflow: "auto",
}}
>
<h2 style={{ marginTop: 0 }}>Select Template</h2>
{templates.length === 0 ? (
<p>No templates available</p>
) : (
<div
style={{
display: "flex",
flexDirection: "column",
gap: "1rem",
}}
>
{templates.map((template) => (
<div
key={template.id}
style={{
padding: "1rem",
border: "1px solid #ccc",
borderRadius: "4px",
cursor: "pointer",
}}
onClick={() => handleLoadTemplate(template)}
>
<strong>{template.name}</strong>
<p style={{ margin: "0.5rem 0 0 0", color: "#666" }}>
{template.total_questions} questions
</p>
</div>
))}
</div>
)}
<button
onClick={() => setShowTemplateModal(false)}
style={{
marginTop: "1rem",
padding: "0.5rem 1rem",
background: "#ccc",
border: "none",
borderRadius: "4px",
cursor: "pointer",
}}
>
Cancel
</button>
</div>
</div>
)}
</div>
</div>
</>
);
}

View File

@@ -0,0 +1,922 @@
import { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import {
questionsAPI,
categoriesAPI,
downloadJobsAPI,
} from "../../services/api";
import AdminNavbar from "../common/AdminNavbar";
export default function QuestionBankView() {
const [questions, setQuestions] = useState([]);
const [categories, setCategories] = useState([]);
const [showForm, setShowForm] = useState(false);
const [editingId, setEditingId] = useState(null);
const [formData, setFormData] = useState({
type: "text",
question_content: "",
answer: "",
category: "",
image: null,
youtube_url: "",
start_time: 0,
end_time: 0,
});
const [imagePreview, setImagePreview] = useState(null);
const [selectedQuestions, setSelectedQuestions] = useState([]);
const [showBulkCategory, setShowBulkCategory] = useState(false);
const [bulkCategory, setBulkCategory] = useState("");
const [downloadJob, setDownloadJob] = useState(null);
const [downloadProgress, setDownloadProgress] = useState(0);
useEffect(() => {
loadQuestions();
loadCategories();
}, []);
const loadQuestions = async () => {
try {
const response = await questionsAPI.getAll();
setQuestions(response.data);
} catch (error) {
console.error("Error loading questions:", error);
}
};
const loadCategories = async () => {
try {
const response = await categoriesAPI.getAll();
setCategories(response.data);
} catch (error) {
console.error("Error loading categories:", error);
}
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
if (editingId) {
// Update existing question
if (formData.type === "image" && formData.image) {
const formDataToSend = new FormData();
formDataToSend.append("type", "image");
formDataToSend.append("question_content", formData.question_content);
formDataToSend.append("answer", formData.answer);
formDataToSend.append("category", formData.category);
formDataToSend.append("image", formData.image);
await questionsAPI.updateWithImage(editingId, formDataToSend);
} else {
await questionsAPI.update(editingId, {
type: formData.type,
question_content: formData.question_content,
answer: formData.answer,
category: formData.category,
});
}
} else {
// Create new question
if (formData.type === "image" && formData.image) {
const formDataToSend = new FormData();
formDataToSend.append("type", "image");
formDataToSend.append("question_content", formData.question_content);
formDataToSend.append("answer", formData.answer);
formDataToSend.append("category", formData.category);
formDataToSend.append("image", formData.image);
await questionsAPI.createWithImage(formDataToSend);
} else if (formData.type === "youtube_audio") {
// Create YouTube audio question
const response = await questionsAPI.create({
type: "youtube_audio",
question_content: formData.question_content,
answer: formData.answer,
category: formData.category,
youtube_url: formData.youtube_url,
start_time: formData.start_time,
end_time: formData.end_time,
});
// Start polling for download progress if job was created
if (response.data.job) {
setDownloadJob(response.data.job);
pollDownloadStatus(response.data.job.id);
return; // Don't close form yet, wait for download
}
} else {
await questionsAPI.create({
type: formData.type,
question_content: formData.question_content,
answer: formData.answer,
category: formData.category,
});
}
}
setShowForm(false);
setEditingId(null);
setFormData({
type: "text",
question_content: "",
answer: "",
category: "",
image: null,
youtube_url: "",
start_time: 0,
end_time: 0,
});
setImagePreview(null);
loadQuestions();
} catch (error) {
console.error("Error saving question:", error);
alert("Error saving question");
}
};
const handleEdit = (question) => {
setEditingId(question.id);
setFormData({
type: question.type,
question_content: question.question_content,
answer: question.answer,
category: question.category || "",
image: null,
});
setShowForm(true);
};
const handleCancelEdit = () => {
setShowForm(false);
setEditingId(null);
setFormData({
type: "text",
question_content: "",
answer: "",
category: "",
image: null,
youtube_url: "",
start_time: 0,
end_time: 0,
});
setImagePreview(null);
setDownloadJob(null);
setDownloadProgress(0);
};
const pollDownloadStatus = async (jobId) => {
const pollInterval = setInterval(async () => {
try {
const response = await downloadJobsAPI.getStatus(jobId);
const job = response.data;
setDownloadProgress(job.progress);
if (job.status === "completed") {
clearInterval(pollInterval);
setDownloadJob(null);
setDownloadProgress(0);
setShowForm(false);
setFormData({
type: "text",
question_content: "",
answer: "",
category: "",
image: null,
youtube_url: "",
start_time: 0,
end_time: 0,
});
loadQuestions();
alert("Audio downloaded successfully!");
} else if (job.status === "failed") {
clearInterval(pollInterval);
setDownloadJob(null);
setDownloadProgress(0);
alert(`Download failed: ${job.error_message || "Unknown error"}`);
}
} catch (error) {
clearInterval(pollInterval);
console.error("Error polling download status:", error);
setDownloadJob(null);
setDownloadProgress(0);
}
}, 2000); // Poll every 2 seconds
};
const handleImageChange = (file) => {
if (file && file.type.startsWith("image/")) {
setFormData({ ...formData, image: file });
const reader = new FileReader();
reader.onloadend = () => {
setImagePreview(reader.result);
};
reader.readAsDataURL(file);
}
};
const handlePaste = (e) => {
const items = e.clipboardData?.items;
if (!items) return;
for (let i = 0; i < items.length; i++) {
if (items[i].type.startsWith("image/")) {
e.preventDefault();
const file = items[i].getAsFile();
if (file) {
handleImageChange(file);
}
break;
}
}
};
const handleDelete = async (id) => {
if (!confirm("Are you sure you want to delete this question?")) return;
try {
await questionsAPI.delete(id);
loadQuestions();
} catch (error) {
console.error("Error deleting question:", error);
}
};
const toggleQuestionSelection = (id) => {
setSelectedQuestions((prev) =>
prev.includes(id) ? prev.filter((qId) => qId !== id) : [...prev, id],
);
};
const toggleSelectAll = () => {
if (selectedQuestions.length === questions.length) {
setSelectedQuestions([]);
} else {
setSelectedQuestions(questions.map((q) => q.id));
}
};
const handleBulkDelete = async () => {
if (selectedQuestions.length === 0) return;
if (
!confirm(
`Are you sure you want to delete ${selectedQuestions.length} question(s)?`,
)
)
return;
try {
await Promise.all(selectedQuestions.map((id) => questionsAPI.delete(id)));
setSelectedQuestions([]);
loadQuestions();
} catch (error) {
console.error("Error bulk deleting questions:", error);
alert("Error deleting questions");
}
};
const handleBulkCategoryAssign = async () => {
if (selectedQuestions.length === 0) return;
try {
await Promise.all(
selectedQuestions.map((id) => {
const question = questions.find((q) => q.id === id);
return questionsAPI.update(id, {
question_content: question.question_content,
answer: question.answer,
type: question.type,
category: bulkCategory,
});
}),
);
setSelectedQuestions([]);
setShowBulkCategory(false);
setBulkCategory("");
loadQuestions();
} catch (error) {
console.error("Error bulk updating categories:", error);
alert("Error updating categories");
}
};
return (
<>
<AdminNavbar />
<div style={{ padding: "1rem 2rem", minHeight: "calc(100vh - 60px)" }}>
<div
style={{
marginBottom: "1.5rem",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<h1 style={{ margin: "0" }}>Question Bank</h1>
<div>
<button
onClick={() => {
setShowForm(!showForm);
if (showForm) handleCancelEdit();
}}
style={{ marginRight: "1rem", padding: "0.5rem 1rem" }}
>
{showForm ? "Cancel" : "Add Question"}
</button>
</div>
</div>
{showForm && (
<form
onSubmit={handleSubmit}
style={{
marginBottom: "2rem",
padding: "1rem",
border: "1px solid #ccc",
borderRadius: "8px",
}}
>
<h3 style={{ marginTop: 0, marginBottom: "1rem" }}>
{editingId ? "Edit Question" : "Add Question"}
</h3>
<div style={{ marginBottom: "1rem" }}>
<label style={{ display: "block", marginBottom: "0.5rem" }}>
Question Type:
</label>
<select
value={formData.type}
onChange={(e) =>
setFormData({ ...formData, type: e.target.value })
}
style={{ padding: "0.5rem", width: "200px" }}
>
<option value="text">Text Question</option>
<option value="image">Image Question</option>
<option value="youtube_audio">YouTube Audio</option>
</select>
</div>
<div style={{ marginBottom: "1rem" }}>
<label style={{ display: "block", marginBottom: "0.5rem" }}>
Category (optional):
</label>
<select
value={formData.category}
onChange={(e) =>
setFormData({ ...formData, category: e.target.value })
}
style={{ padding: "0.5rem", width: "100%" }}
>
<option value="">-- No Category --</option>
{categories.map((cat) => (
<option key={cat.id} value={cat.name}>
{cat.name}
</option>
))}
</select>
<Link
to="/categories"
style={{
fontSize: "0.8rem",
marginTop: "0.25rem",
display: "inline-block",
color: "#2196F3",
}}
>
Manage Categories
</Link>
</div>
<div style={{ marginBottom: "1rem" }}>
<label style={{ display: "block", marginBottom: "0.5rem" }}>
Question:
</label>
<input
type="text"
value={formData.question_content}
onChange={(e) =>
setFormData({ ...formData, question_content: e.target.value })
}
required
style={{ padding: "0.5rem", width: "100%" }}
placeholder="Enter question text"
/>
</div>
{formData.type === "image" && (
<div style={{ marginBottom: "1rem" }}>
<label style={{ display: "block", marginBottom: "0.5rem" }}>
Image:
</label>
<div
onPaste={handlePaste}
style={{
border: "2px dashed #ccc",
borderRadius: "8px",
padding: "1.5rem",
textAlign: "center",
marginBottom: "0.5rem",
background: "#f9f9f9",
cursor: "pointer",
}}
>
<p style={{ margin: "0 0 0.5rem 0", color: "#666" }}>
📋 Paste an image here (Ctrl/Cmd+V) or upload below
</p>
<input
type="file"
accept="image/*"
onChange={(e) => handleImageChange(e.target.files[0])}
required={!editingId && !formData.image}
style={{ padding: "0.5rem" }}
/>
</div>
{imagePreview && (
<div style={{ marginTop: "0.5rem" }}>
<p style={{ fontSize: "0.9rem", marginBottom: "0.5rem" }}>
Preview:
</p>
<img
src={imagePreview}
alt="Preview"
style={{
maxWidth: "300px",
maxHeight: "200px",
border: "1px solid #ddd",
borderRadius: "4px",
}}
/>
</div>
)}
{editingId && !imagePreview && (
<p
style={{
fontSize: "0.8rem",
color: "#666",
marginTop: "0.25rem",
}}
>
Leave empty to keep current image
</p>
)}
</div>
)}
{formData.type === "youtube_audio" && (
<div style={{ marginBottom: "1rem" }}>
<label style={{ display: "block", marginBottom: "0.5rem" }}>
YouTube URL:
<input
type="text"
value={formData.youtube_url}
onChange={(e) =>
setFormData({ ...formData, youtube_url: e.target.value })
}
placeholder="https://www.youtube.com/watch?v=..."
required
style={{
width: "100%",
padding: "0.5rem",
marginTop: "0.25rem",
border: "1px solid #ddd",
borderRadius: "4px",
}}
/>
</label>
<div
style={{
display: "grid",
gridTemplateColumns: "1fr 1fr",
gap: "1rem",
marginTop: "1rem",
}}
>
<label>
Start Time (seconds):
<input
type="number"
value={formData.start_time}
onChange={(e) =>
setFormData({
...formData,
start_time: parseInt(e.target.value) || 0,
})
}
min="0"
required
style={{
width: "100%",
padding: "0.5rem",
marginTop: "0.25rem",
border: "1px solid #ddd",
borderRadius: "4px",
}}
/>
</label>
<label>
End Time (seconds):
<input
type="number"
value={formData.end_time}
onChange={(e) =>
setFormData({
...formData,
end_time: parseInt(e.target.value) || 0,
})
}
min="0"
required
style={{
width: "100%",
padding: "0.5rem",
marginTop: "0.25rem",
border: "1px solid #ddd",
borderRadius: "4px",
}}
/>
</label>
</div>
<p
style={{
fontSize: "0.875rem",
color: "#666",
marginTop: "0.5rem",
}}
>
Clip duration: {formData.end_time - formData.start_time}{" "}
seconds (max 300)
</p>
</div>
)}
<div style={{ marginBottom: "1rem" }}>
<label style={{ display: "block", marginBottom: "0.5rem" }}>
Answer:
</label>
<input
type="text"
value={formData.answer}
onChange={(e) =>
setFormData({ ...formData, answer: e.target.value })
}
required
style={{ padding: "0.5rem", width: "100%" }}
placeholder="Enter answer"
/>
</div>
<div style={{ display: "flex", gap: "0.5rem" }}>
<button type="submit" style={{ padding: "0.5rem 1rem" }}>
{editingId ? "Update Question" : "Create Question"}
</button>
{editingId && (
<button
type="button"
onClick={handleCancelEdit}
style={{ padding: "0.5rem 1rem", background: "#ccc" }}
>
Cancel
</button>
)}
</div>
</form>
)}
<div>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
marginBottom: "1rem",
}}
>
<h2 style={{ margin: 0 }}>Questions ({questions.length})</h2>
{selectedQuestions.length > 0 && (
<div
style={{ display: "flex", gap: "0.5rem", alignItems: "center" }}
>
<span style={{ fontSize: "0.9rem", color: "#666" }}>
{selectedQuestions.length} selected
</span>
<button
onClick={() => setShowBulkCategory(!showBulkCategory)}
style={{
padding: "0.5rem 1rem",
background: "#2196F3",
color: "white",
border: "none",
borderRadius: "4px",
cursor: "pointer",
}}
>
Assign Category
</button>
<button
onClick={handleBulkDelete}
style={{
padding: "0.5rem 1rem",
background: "#f44336",
color: "white",
border: "none",
borderRadius: "4px",
cursor: "pointer",
}}
>
Delete Selected
</button>
</div>
)}
</div>
{showBulkCategory && selectedQuestions.length > 0 && (
<div
style={{
marginBottom: "1rem",
padding: "1rem",
background: "#f5f5f5",
borderRadius: "4px",
display: "flex",
gap: "0.5rem",
alignItems: "center",
}}
>
<label>Category:</label>
<select
value={bulkCategory}
onChange={(e) => setBulkCategory(e.target.value)}
style={{ padding: "0.5rem", flex: 1, maxWidth: "300px" }}
>
<option value="">-- No Category --</option>
{categories.map((cat) => (
<option key={cat.id} value={cat.name}>
{cat.name}
</option>
))}
</select>
<button
onClick={handleBulkCategoryAssign}
style={{
padding: "0.5rem 1rem",
background: "#4CAF50",
color: "white",
border: "none",
borderRadius: "4px",
cursor: "pointer",
}}
>
Apply
</button>
<button
onClick={() => {
setShowBulkCategory(false);
setBulkCategory("");
}}
style={{
padding: "0.5rem 1rem",
background: "#ccc",
border: "none",
borderRadius: "4px",
cursor: "pointer",
}}
>
Cancel
</button>
</div>
)}
{questions.length === 0 ? (
<p>No questions yet. Create your first question above!</p>
) : (
<div style={{ overflowX: "auto" }}>
<table
style={{
width: "100%",
borderCollapse: "collapse",
border: "1px solid #ddd",
}}
>
<thead>
<tr style={{ background: "#f5f5f5" }}>
<th
style={{
padding: "0.75rem",
textAlign: "center",
borderBottom: "2px solid #ddd",
width: "50px",
}}
>
<input
type="checkbox"
checked={
selectedQuestions.length === questions.length &&
questions.length > 0
}
onChange={toggleSelectAll}
style={{ cursor: "pointer" }}
/>
</th>
<th
style={{
padding: "0.75rem",
textAlign: "left",
borderBottom: "2px solid #ddd",
width: "80px",
}}
>
Type
</th>
<th
style={{
padding: "0.75rem",
textAlign: "left",
borderBottom: "2px solid #ddd",
width: "120px",
}}
>
Category
</th>
<th
style={{
padding: "0.75rem",
textAlign: "left",
borderBottom: "2px solid #ddd",
}}
>
Question
</th>
<th
style={{
padding: "0.75rem",
textAlign: "left",
borderBottom: "2px solid #ddd",
}}
>
Answer
</th>
<th
style={{
padding: "0.75rem",
textAlign: "center",
borderBottom: "2px solid #ddd",
width: "150px",
}}
>
Actions
</th>
</tr>
</thead>
<tbody>
{questions.map((q) => (
<tr key={q.id} style={{ borderBottom: "1px solid #ddd" }}>
<td style={{ padding: "0.75rem", textAlign: "center" }}>
<input
type="checkbox"
checked={selectedQuestions.includes(q.id)}
onChange={() => toggleQuestionSelection(q.id)}
style={{ cursor: "pointer" }}
/>
</td>
<td style={{ padding: "0.75rem" }}>
<span
style={{
background:
q.type === "image" ? "#e3f2fd" : "#f3e5f5",
padding: "0.25rem 0.5rem",
borderRadius: "4px",
fontSize: "0.8rem",
display: "inline-block",
}}
>
{q.type.toUpperCase()}
</span>
</td>
<td style={{ padding: "0.75rem" }}>
{q.category ? (
<span
style={{
background: "#e8f5e9",
padding: "0.25rem 0.5rem",
borderRadius: "4px",
fontSize: "0.8rem",
color: "#2e7d32",
display: "inline-block",
}}
>
{q.category}
</span>
) : (
<span style={{ color: "#999", fontSize: "0.8rem" }}>
None
</span>
)}
</td>
<td style={{ padding: "0.75rem" }}>
<div>{q.question_content}</div>
{q.image_path && (
<img
src={q.image_path}
alt="Question"
style={{
maxWidth: "100px",
marginTop: "0.5rem",
display: "block",
}}
/>
)}
</td>
<td style={{ padding: "0.75rem", fontWeight: "bold" }}>
{q.answer}
</td>
<td style={{ padding: "0.75rem", textAlign: "center" }}>
<div
style={{
display: "flex",
gap: "0.5rem",
justifyContent: "center",
}}
>
<button
onClick={() => handleEdit(q)}
style={{
padding: "0.4rem 0.8rem",
background: "#2196F3",
color: "white",
border: "none",
borderRadius: "4px",
cursor: "pointer",
fontSize: "0.9rem",
}}
>
Edit
</button>
<button
onClick={() => handleDelete(q.id)}
style={{
padding: "0.4rem 0.8rem",
background: "#f44336",
color: "white",
border: "none",
borderRadius: "4px",
cursor: "pointer",
fontSize: "0.9rem",
}}
>
Delete
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
{downloadJob && (
<div
style={{
position: "fixed",
bottom: "2rem",
right: "2rem",
background: "white",
padding: "1.5rem",
borderRadius: "8px",
boxShadow: "0 4px 6px rgba(0,0,0,0.1)",
minWidth: "300px",
zIndex: 1000,
}}
>
<h4 style={{ margin: "0 0 1rem 0" }}>Downloading Audio...</h4>
<div
style={{
width: "100%",
height: "8px",
background: "#e0e0e0",
borderRadius: "4px",
overflow: "hidden",
}}
>
<div
style={{
width: `${downloadProgress}%`,
height: "100%",
background: "#4CAF50",
transition: "width 0.3s ease",
}}
/>
</div>
<p
style={{
margin: "0.5rem 0 0 0",
fontSize: "0.875rem",
color: "#666",
}}
>
{downloadProgress}% complete
</p>
</div>
)}
</div>
</>
);
}

View File

@@ -0,0 +1,139 @@
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { gamesAPI } from "../../services/api";
import AdminNavbar from "../common/AdminNavbar";
export default function TemplatesView() {
const navigate = useNavigate();
const [templates, setTemplates] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
loadTemplates();
}, []);
const loadTemplates = async () => {
try {
setLoading(true);
const response = await gamesAPI.getTemplates();
setTemplates(response.data);
} catch (error) {
console.error("Error loading templates:", error);
} finally {
setLoading(false);
}
};
const handleUseTemplate = async (template) => {
const gameName = prompt(
`Enter a name for the new game (based on "${template.name}"):`,
);
if (!gameName) return;
try {
const response = await gamesAPI.cloneTemplate(template.id, gameName);
alert("Game created successfully!");
navigate(`/games/${response.data.id}/admin`);
} catch (error) {
console.error("Error cloning template:", error);
alert("Error creating game from template");
}
};
const handleDeleteTemplate = async (templateId, templateName) => {
if (!window.confirm(`Delete template "${templateName}"?`)) return;
try {
await gamesAPI.delete(templateId);
loadTemplates();
} catch (error) {
console.error("Error deleting template:", error);
alert("Error deleting template");
}
};
return (
<>
<AdminNavbar />
<div
style={{
padding: "0 2rem 1rem 2rem",
maxWidth: "1400px",
margin: "0 auto",
}}
>
<h1 style={{ margin: "0 0 1rem 0" }}>Game Templates</h1>
{loading ? (
<p>Loading templates...</p>
) : templates.length === 0 ? (
<p>
No templates yet. Save a game as a template from the Game Admin
view.
</p>
) : (
<div
style={{ display: "flex", flexDirection: "column", gap: "1rem" }}
>
{templates.map((template) => (
<div
key={template.id}
style={{
padding: "1.5rem",
border: "1px solid #ccc",
borderRadius: "8px",
background: "white",
}}
>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<div>
<h3 style={{ margin: "0 0 0.5rem 0" }}>{template.name}</h3>
<p style={{ margin: 0, color: "#666" }}>
{template.total_questions} questions
</p>
</div>
<div style={{ display: "flex", gap: "0.5rem" }}>
<button
onClick={() => handleUseTemplate(template)}
style={{
padding: "0.5rem 1rem",
background: "#4CAF50",
color: "white",
border: "none",
borderRadius: "4px",
cursor: "pointer",
}}
>
Use Template
</button>
<button
onClick={() =>
handleDeleteTemplate(template.id, template.name)
}
style={{
padding: "0.5rem 1rem",
background: "#f44336",
color: "white",
border: "none",
borderRadius: "4px",
cursor: "pointer",
}}
>
Delete
</button>
</div>
</div>
</div>
))}
</div>
)}
</div>
</>
);
}

View File

@@ -0,0 +1,159 @@
import { createContext, useContext, useState, useEffect } from 'react';
import { jwtDecode } from 'jwt-decode';
const AuthContext = createContext(null);
export function AuthProvider({ children }) {
const [user, setUser] = useState(null);
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [accessToken, setAccessToken] = useState(null);
useEffect(() => {
// Check if user is already logged in (token in localStorage)
const storedToken = localStorage.getItem('access_token');
const storedIdToken = localStorage.getItem('id_token');
console.log('AuthContext: Checking stored tokens', {
hasAccessToken: !!storedToken,
hasIdToken: !!storedIdToken
});
if (storedToken && storedIdToken) {
try {
const decoded = jwtDecode(storedIdToken);
// Check if token is expired
if (decoded.exp * 1000 > Date.now()) {
console.log('AuthContext: Tokens valid, setting authenticated', decoded);
setAccessToken(storedToken);
setUser({ profile: decoded });
setIsAuthenticated(true);
} else {
// Token expired, clear storage
console.log('AuthContext: Tokens expired');
localStorage.removeItem('access_token');
localStorage.removeItem('id_token');
}
} catch (error) {
console.error('Error decoding token:', error);
localStorage.removeItem('access_token');
localStorage.removeItem('id_token');
}
} else {
console.log('AuthContext: No tokens found in storage');
}
setIsLoading(false);
}, []);
const login = () => {
// Redirect to backend login endpoint
window.location.href = '/api/auth/login';
};
const handleCallback = async () => {
try {
// Extract tokens from URL hash (set by backend redirect)
const hash = window.location.hash.substring(1);
const params = new URLSearchParams(hash);
console.log('handleCallback: Hash params', hash);
const access_token = params.get('access_token');
const id_token = params.get('id_token');
console.log('handleCallback: Tokens extracted', {
hasAccessToken: !!access_token,
hasIdToken: !!id_token
});
if (!access_token || !id_token) {
throw new Error('No tokens found in callback');
}
// Store tokens
localStorage.setItem('access_token', access_token);
localStorage.setItem('id_token', id_token);
console.log('handleCallback: Tokens stored in localStorage');
// Decode ID token to get user info
const decoded = jwtDecode(id_token);
console.log('handleCallback: Decoded user', decoded);
setAccessToken(access_token);
setUser({ profile: decoded });
setIsAuthenticated(true);
console.log('handleCallback: Auth state updated, isAuthenticated=true');
// Clear hash from URL
window.history.replaceState(null, '', window.location.pathname);
return { profile: decoded };
} catch (error) {
console.error('Callback error:', error);
throw error;
}
};
const logout = async () => {
// Clear local storage
localStorage.removeItem('access_token');
localStorage.removeItem('id_token');
setAccessToken(null);
setUser(null);
setIsAuthenticated(false);
// Redirect to backend logout to clear cookies and get Authelia logout URL
window.location.href = '/api/auth/logout';
};
const getTokenSilently = async () => {
// Return ID token (JWT) for backend authentication
// Note: Authelia's access_token is opaque and can't be validated by backend
// We use id_token instead which is a proper JWT
const storedIdToken = localStorage.getItem('id_token');
if (storedIdToken) {
try {
const decoded = jwtDecode(storedIdToken);
// Check if token is expired
if (decoded.exp * 1000 > Date.now()) {
return storedIdToken;
} else {
console.log('ID token expired');
localStorage.removeItem('access_token');
localStorage.removeItem('id_token');
setIsAuthenticated(false);
}
} catch (error) {
console.error('Error decoding ID token:', error);
}
}
// No valid token available
return null;
};
const value = {
user,
isAuthenticated,
isLoading,
accessToken,
login,
logout,
handleCallback,
getTokenSilently,
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
export function useAuth() {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within AuthProvider');
}
return context;
}

View File

@@ -0,0 +1,81 @@
import { useEffect, useState, useRef } from "react";
import { io } from "socket.io-client";
import { useAuth } from "../contexts/AuthContext";
export function useSocket(gameId, role = "contestant") {
const [socket, setSocket] = useState(null);
const [isConnected, setIsConnected] = useState(false);
const socketRef = useRef(null);
const { getTokenSilently, isAuthenticated } = useAuth();
useEffect(() => {
if (!gameId || !isAuthenticated) return;
// Get ID token for authentication
const initSocket = async () => {
const token = await getTokenSilently();
if (!token) {
console.error('No token available for WebSocket connection');
return;
}
// Create socket connection with auth token
const newSocket = io({
transports: ["websocket", "polling"],
reconnection: true,
reconnectionDelay: 1000,
reconnectionAttempts: 5,
auth: {
token, // Send ID token (JWT) in connection auth
},
});
socketRef.current = newSocket;
newSocket.on("connect", () => {
console.log("Socket connected");
setIsConnected(true);
// Join the game room with token
newSocket.emit("join_game", {
game_id: parseInt(gameId),
role,
token, // Send ID token (JWT) in join_game event
});
});
newSocket.on("disconnect", () => {
console.log("Socket disconnected");
setIsConnected(false);
});
newSocket.on("joined", (data) => {
console.log("Joined game room:", data);
});
newSocket.on("error", (error) => {
console.error("Socket error:", error);
// If error is auth-related, disconnect
if (error.message?.includes('token') || error.message?.includes('auth')) {
newSocket.disconnect();
}
});
setSocket(newSocket);
};
initSocket();
// Cleanup on unmount
return () => {
if (socketRef.current) {
socketRef.current.emit("leave_game", {
game_id: parseInt(gameId),
role,
});
socketRef.current.disconnect();
}
};
}, [gameId, role, isAuthenticated, getTokenSilently]);
return { socket, isConnected };
}

View File

@@ -0,0 +1,69 @@
:root {
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
width: 100%;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}

View File

@@ -0,0 +1,10 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App.jsx";
createRoot(document.getElementById("root")).render(
<StrictMode>
<App />
</StrictMode>,
);

View File

@@ -0,0 +1,72 @@
import { useEffect, useState, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
export default function AuthCallback() {
const { handleCallback } = useAuth();
const navigate = useNavigate();
const [error, setError] = useState(null);
const hasRun = useRef(false);
useEffect(() => {
// Prevent double-run in React Strict Mode
if (hasRun.current) return;
hasRun.current = true;
handleCallback()
.then(() => {
navigate('/');
})
.catch((error) => {
console.error('Authentication failed:', error);
setError(error.message || 'Authentication failed');
setTimeout(() => {
navigate('/login');
}, 3000);
});
}, [handleCallback, navigate]);
return (
<div
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100vh',
flexDirection: 'column',
gap: '1rem',
}}
>
{error ? (
<>
<div style={{ color: '#e74c3c', fontSize: '1.2rem' }}>
{error}
</div>
<p>Redirecting to login...</p>
</>
) : (
<>
<div
style={{
border: '4px solid #f3f3f3',
borderTop: '4px solid #3498db',
borderRadius: '50%',
width: '50px',
height: '50px',
animation: 'spin 1s linear infinite',
}}
/>
<p>Completing login...</p>
<style>
{`
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
`}
</style>
</>
)}
</div>
);
}

View File

@@ -0,0 +1,70 @@
import { useEffect } from 'react';
import { useAuth } from '../contexts/AuthContext';
import { useNavigate } from 'react-router-dom';
export default function Login() {
const { login, isAuthenticated } = useAuth();
const navigate = useNavigate();
useEffect(() => {
if (isAuthenticated) {
navigate('/');
}
}, [isAuthenticated, navigate]);
return (
<div
style={{
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
height: '100vh',
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
}}
>
<div
style={{
background: 'white',
padding: '3rem',
borderRadius: '12px',
boxShadow: '0 10px 40px rgba(0,0,0,0.2)',
textAlign: 'center',
maxWidth: '400px',
}}
>
<h1 style={{ margin: '0 0 0.5rem 0', fontSize: '2.5rem', color: '#333' }}>
Trivia Game
</h1>
<p style={{ color: '#666', marginBottom: '2rem', fontSize: '1.1rem' }}>
Please log in to continue
</p>
<button
onClick={login}
style={{
padding: '1rem 2rem',
fontSize: '1.1rem',
cursor: 'pointer',
background: '#667eea',
color: 'white',
border: 'none',
borderRadius: '6px',
fontWeight: '500',
width: '100%',
transition: 'all 0.3s ease',
}}
onMouseOver={(e) => {
e.target.style.background = '#5568d3';
e.target.style.transform = 'translateY(-2px)';
}}
onMouseOut={(e) => {
e.target.style.background = '#667eea';
e.target.style.transform = 'translateY(0)';
}}
>
Login with Authelia
</button>
</div>
</div>
);
}

View File

@@ -0,0 +1,136 @@
import axios from "axios";
// Base URL will use proxy in development, direct path in production
const API_BASE_URL = "/api";
const api = axios.create({
baseURL: API_BASE_URL,
headers: {
"Content-Type": "application/json",
},
});
// Auth token getter (set by App.jsx)
let getAuthToken = null;
export function setAuthTokenGetter(tokenGetter) {
getAuthToken = tokenGetter;
}
// Request interceptor to add JWT token
api.interceptors.request.use(
async (config) => {
if (getAuthToken) {
const token = await getAuthToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
// Response interceptor to handle 401 errors
api.interceptors.response.use(
(response) => response,
async (error) => {
if (error.response?.status === 401) {
console.error('Authentication error - logging out');
// Dispatch custom event for auth context to handle
window.dispatchEvent(new Event('auth:unauthorized'));
}
return Promise.reject(error);
}
);
// Questions API
export const questionsAPI = {
getAll: () => api.get("/questions"),
getOne: (id) => api.get(`/questions/${id}`),
create: (data) => api.post("/questions", data),
createWithImage: (formData) =>
api.post("/questions", formData, {
headers: { "Content-Type": "multipart/form-data" },
}),
bulkCreate: (questions) => api.post("/questions/bulk", { questions }),
getRandomByCategory: (category, count) =>
api.get("/questions/random", {
params: { category, count },
}),
update: (id, data) => api.put(`/questions/${id}`, data),
updateWithImage: (id, formData) =>
api.put(`/questions/${id}`, formData, {
headers: { "Content-Type": "multipart/form-data" },
}),
delete: (id) => api.delete(`/questions/${id}`),
};
// Games API
export const gamesAPI = {
getAll: () => api.get("/games"),
getOne: (id) => api.get(`/games/${id}`),
create: (data) => api.post("/games", data),
delete: (id) => api.delete(`/games/${id}`),
addQuestions: (id, questionIds) =>
api.post(`/games/${id}/questions`, { question_ids: questionIds }),
addTeam: (id, teamName) => api.post(`/games/${id}/teams`, { name: teamName }),
saveAsTemplate: (id) => api.post(`/games/${id}/save-template`),
getTemplates: () => api.get("/games/templates"),
cloneTemplate: (id, name) => api.post(`/games/${id}/clone`, { name }),
};
// Teams API
export const teamsAPI = {
delete: (id) => api.delete(`/teams/${id}`),
};
// Admin API
export const adminAPI = {
startGame: (id) => api.post(`/admin/game/${id}/start`),
endGame: (id) => api.post(`/admin/game/${id}/end`),
restartGame: (id) => api.post(`/admin/game/${id}/restart`),
nextQuestion: (id) => api.post(`/admin/game/${id}/next`),
prevQuestion: (id) => api.post(`/admin/game/${id}/prev`),
awardPoints: (id, teamId, points) =>
api.post(`/admin/game/${id}/award`, { team_id: teamId, points }),
getCurrentState: (id) => api.get(`/admin/game/${id}/current`),
toggleAnswer: (id, showAnswer) =>
api.post(`/admin/game/${id}/toggle-answer`, { show_answer: showAnswer }),
pauseTimer: (id, paused) =>
api.post(`/admin/game/${id}/pause-timer`, { paused }),
resetTimer: (id) => api.post(`/admin/game/${id}/reset-timer`),
useLifeline: (gameId, teamId) =>
api.post(`/admin/game/${gameId}/team/${teamId}/use-lifeline`),
addLifeline: (gameId, teamId) =>
api.post(`/admin/game/${gameId}/team/${teamId}/add-lifeline`),
};
// Categories API
export const categoriesAPI = {
getAll: () => api.get("/categories"),
getOne: (id) => api.get(`/categories/${id}`),
create: (data) => api.post("/categories", data),
update: (id, data) => api.put(`/categories/${id}`, data),
delete: (id) => api.delete(`/categories/${id}`),
};
// Download Jobs API
export const downloadJobsAPI = {
getStatus: (jobId) => api.get(`/download-jobs/${jobId}`),
getByQuestion: (questionId) =>
api.get(`/download-jobs/question/${questionId}`),
};
// Audio Control API
export const audioControlAPI = {
play: (gameId) => api.post(`/admin/game/${gameId}/audio/play`),
pause: (gameId) => api.post(`/admin/game/${gameId}/audio/pause`),
stop: (gameId) => api.post(`/admin/game/${gameId}/audio/stop`),
seek: (gameId, position) =>
api.post(`/admin/game/${gameId}/audio/seek`, { position }),
};
export default api;

View File

@@ -0,0 +1,33 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
// Use environment variable for backend URL, default to localhost for local dev
const backendUrl = process.env.VITE_BACKEND_URL || "http://localhost:5001";
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
server: {
port: 3000,
host: "0.0.0.0",
proxy: {
"/api": {
target: backendUrl,
changeOrigin: true,
},
"/socket.io": {
target: backendUrl,
changeOrigin: true,
ws: true,
},
"/static": {
target: backendUrl,
changeOrigin: true,
},
},
},
build: {
outDir: "../backend/static",
emptyOutDir: true,
},
});