kaboot/App.tsx
Joey Yakimowich-Payne af21f2bcdc
feat: add comprehensive game configuration system
Add a centralized game configuration system that allows customizable
scoring mechanics and game rules. Users can now set default game
configurations that persist across sessions, and individual quizzes
can have their own configuration overrides.

## New Features

### Game Configuration Options
- Shuffle Questions: Randomize question order when starting a game
- Shuffle Answers: Randomize answer positions for each question
- Host Participates: Toggle whether the host plays as a competitor
  or spectates (host now shows as 'Spectator' when not participating)
- Streak Bonus: Multiplied points for consecutive correct answers,
  with configurable threshold and multiplier values
- Comeback Bonus: Extra points for players ranked below top 3
- Wrong Answer Penalty: Deduct percentage of max points for incorrect
  answers (configurable percentage)
- First Correct Bonus: Extra points for the first player to answer
  correctly on each question

### Default Settings Management
- New Settings icon in landing page header (authenticated users only)
- DefaultConfigModal for editing user-wide default game settings
- Default configs are loaded when creating new quizzes
- Defaults persist to database via new user API endpoints

### Reusable UI Components
- GameConfigPanel: Comprehensive toggle-based settings panel with
  expandable sub-options, tooltips, and suggested values based on
  question count
- DefaultConfigModal: Modal wrapper for editing default configurations

## Technical Changes

### Frontend
- New useUserConfig hook for fetching/saving user default configurations
- QuizEditor now uses GameConfigPanel instead of inline toggle checkboxes
- GameScreen handles spectator mode with disabled answer buttons
- Updated useGame hook with new scoring calculations and config state
- Improved useAuthenticatedFetch with deduped silent refresh and
  redirect-once pattern to prevent multiple auth redirects

### Backend
- Added game_config column to quizzes table (JSON storage)
- Added default_game_config column to users table
- New PATCH endpoint for quiz config updates: /api/quizzes/:id/config
- New PUT endpoint for user defaults: /api/users/me/default-config
- Auto-migration in connection.ts for existing databases

### Scoring System
- New calculatePoints() function in constants.ts handles all scoring
  logic including streaks, comebacks, penalties, and first-correct bonus
- New calculateBasePoints() for time-based point calculation
- New getPlayerRank() helper for comeback bonus eligibility

### Tests
- Added tests for DefaultConfigModal component
- Added tests for GameConfigPanel component
- Added tests for QuizEditor config integration
- Added tests for useUserConfig hook
- Updated API tests for new endpoints

## Type Changes
- Added GameConfig interface with all configuration options
- Added DEFAULT_GAME_CONFIG constant with sensible defaults
- Quiz type now includes optional config property
2026-01-14 01:43:23 -07:00

251 lines
No EOL
7.7 KiB
TypeScript

import React, { useState } from 'react';
import { useAuth } from 'react-oidc-context';
import { useGame } from './hooks/useGame';
import { useQuizLibrary } from './hooks/useQuizLibrary';
import { useUserConfig } from './hooks/useUserConfig';
import { Landing } from './components/Landing';
import { Lobby } from './components/Lobby';
import { GameScreen } from './components/GameScreen';
import { Scoreboard } from './components/Scoreboard';
import { Podium } from './components/Podium';
import { QuizCreator } from './components/QuizCreator';
import { RevealScreen } from './components/RevealScreen';
import { SaveQuizPrompt } from './components/SaveQuizPrompt';
import { QuizEditor } from './components/QuizEditor';
import { SaveOptionsModal } from './components/SaveOptionsModal';
import type { Quiz, GameConfig } from './types';
const seededRandom = (seed: number) => {
const x = Math.sin(seed * 9999) * 10000;
return x - Math.floor(x);
};
const FLOATING_SHAPES = [...Array(15)].map((_, i) => ({
left: `${seededRandom(i * 1) * 100}%`,
width: `${seededRandom(i * 2) * 100 + 40}px`,
height: `${seededRandom(i * 3) * 100 + 40}px`,
animationDuration: `${seededRandom(i * 4) * 20 + 15}s`,
animationDelay: `-${seededRandom(i * 5) * 20}s`,
borderRadius: seededRandom(i * 6) > 0.5 ? '50%' : '20%',
background: 'rgba(255, 255, 255, 0.05)',
}));
const FloatingShapes = React.memo(() => {
return (
<>
{FLOATING_SHAPES.map((style, i) => (
<div key={i} className="floating-shape" style={style} />
))}
</>
);
});
function App() {
const auth = useAuth();
const { saveQuiz, updateQuiz, saving } = useQuizLibrary();
const { defaultConfig } = useUserConfig();
const [showSaveOptions, setShowSaveOptions] = useState(false);
const [pendingEditedQuiz, setPendingEditedQuiz] = useState<Quiz | null>(null);
const {
role,
gameState,
quiz,
players,
currentQuestionIndex,
timeLeft,
error,
gamePin,
startQuizGen,
startManualCreation,
finalizeManualQuiz,
loadSavedQuiz,
joinGame,
startGame,
handleAnswer,
hasAnswered,
lastPointsEarned,
nextQuestion,
showScoreboard,
currentCorrectShape,
selectedOption,
currentPlayerScore,
currentStreak,
currentPlayerId,
pendingQuizToSave,
dismissSavePrompt,
sourceQuizId,
updateQuizFromEditor,
startGameFromEditor,
backFromEditor,
gameConfig
} = useGame();
const handleSaveQuiz = async () => {
if (!pendingQuizToSave) return;
const source = pendingQuizToSave.topic ? 'ai_generated' : 'manual';
const topic = pendingQuizToSave.topic || undefined;
await saveQuiz(pendingQuizToSave.quiz, source, topic);
dismissSavePrompt();
};
const handleEditorSave = async (editedQuiz: Quiz) => {
updateQuizFromEditor(editedQuiz);
if (auth.isAuthenticated) {
if (sourceQuizId) {
// Quiz was loaded from library - show options modal
setPendingEditedQuiz(editedQuiz);
setShowSaveOptions(true);
} else {
// New quiz (AI-generated or manual) - save as new
const source = pendingQuizToSave?.topic ? 'ai_generated' : 'manual';
const topic = pendingQuizToSave?.topic || undefined;
await saveQuiz(editedQuiz, source, topic);
}
}
};
const handleOverwriteQuiz = async () => {
if (!pendingEditedQuiz || !sourceQuizId) return;
await updateQuiz(sourceQuizId, pendingEditedQuiz);
setShowSaveOptions(false);
setPendingEditedQuiz(null);
};
const handleSaveAsNew = async () => {
if (!pendingEditedQuiz) return;
await saveQuiz(pendingEditedQuiz, 'manual');
setShowSaveOptions(false);
setPendingEditedQuiz(null);
};
const currentQ = quiz?.questions[currentQuestionIndex];
// Logic to find correct option, handling both Host (has isCorrect flag) and Client (masked, needs shape)
const correctOpt = currentQ?.options.find(o => {
if (role === 'HOST') return o.isCorrect;
return o.shape === currentCorrectShape;
});
return (
<div className="min-h-screen text-white relative">
<FloatingShapes />
<div className="relative z-10">
{gameState === 'LANDING' || gameState === 'GENERATING' ? (
<Landing
onGenerate={startQuizGen}
onCreateManual={startManualCreation}
onLoadQuiz={loadSavedQuiz}
onJoin={joinGame}
isLoading={gameState === 'GENERATING'}
error={error}
/>
) : null}
{gameState === 'CREATING' ? (
<QuizCreator
onFinalize={finalizeManualQuiz}
onCancel={() => window.location.reload()}
/>
) : null}
{gameState === 'EDITING' && quiz ? (
<QuizEditor
quiz={quiz}
onSave={handleEditorSave}
onStartGame={startGameFromEditor}
onBack={backFromEditor}
showSaveButton={auth.isAuthenticated}
defaultConfig={defaultConfig}
/>
) : null}
{gameState === 'LOBBY' ? (
<>
<Lobby
quizTitle={quiz?.title || 'Kaboot'}
players={players}
gamePin={gamePin}
role={role}
onStart={startGame}
/>
{auth.isAuthenticated && pendingQuizToSave && (
<SaveQuizPrompt
isOpen={true}
quizTitle={pendingQuizToSave.quiz.title}
onSave={handleSaveQuiz}
onSkip={dismissSavePrompt}
/>
)}
</>
) : null}
{(gameState === 'COUNTDOWN' || gameState === 'QUESTION') && quiz ? (
gameState === 'COUNTDOWN' ? (
<div className="flex flex-col items-center justify-center h-screen animate-bounce">
<div className="text-4xl font-display font-bold mb-4">Get Ready!</div>
<div className="text-[12rem] font-black leading-none drop-shadow-[0_10px_0_rgba(0,0,0,0.3)]">
{timeLeft}
</div>
</div>
) : (
<GameScreen
question={quiz.questions[currentQuestionIndex]}
timeLeft={timeLeft}
totalQuestions={quiz.questions.length}
currentQuestionIndex={currentQuestionIndex}
gameState={gameState}
role={role}
onAnswer={handleAnswer}
hasAnswered={hasAnswered}
lastPointsEarned={lastPointsEarned}
hostPlays={gameConfig.hostParticipates}
/>
)
) : null}
{gameState === 'REVEAL' && correctOpt ? (
<RevealScreen
isCorrect={lastPointsEarned !== null && lastPointsEarned > 0}
pointsEarned={lastPointsEarned || 0}
newScore={currentPlayerScore}
streak={currentStreak}
correctOption={correctOpt}
selectedOption={selectedOption}
role={role}
onNext={showScoreboard}
/>
) : null}
{gameState === 'SCOREBOARD' ? (
<Scoreboard
players={players}
onNext={nextQuestion}
isHost={role === 'HOST'}
currentPlayerId={currentPlayerId}
/>
) : null}
{gameState === 'PODIUM' ? (
<Podium
players={players}
onRestart={() => window.location.reload()}
/>
) : null}
</div>
<SaveOptionsModal
isOpen={showSaveOptions}
onClose={() => {
setShowSaveOptions(false);
setPendingEditedQuiz(null);
}}
onOverwrite={handleOverwriteQuiz}
onSaveNew={handleSaveAsNew}
isSaving={saving}
/>
</div>
);
}
export default App;