From e31bbae239aa4a1c8153c90c315ea778ada98738 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 15:37:24 +0000 Subject: [PATCH] Worksheet variants A-D on prepared rounds, and Send worksheet remembers what was sent - Prepared-round form (individual rounds): add worksheets B-D, pick who gets which (everyone A / deal out alphabetically / by name-stamp corner on Main) and the late-joiner rule. The server deals them out at launch and to late joiners. - Stored per round as teacher-only roundVariants: survives restarts, room saves and lesson packs (student picks only when the teacher opts in). - Send worksheet... reopens with the round's files, rule and picks, keeps each board's letter until the rule changes, and sends only boards that change. - New teacher:set-round-variants event; tests for the pure module, the server paths and two browser flows. Co-Authored-By: Claude Opus 5.5 --- TODO.md | 37 ++- docs/ARCHITECTURE.md | 2 + e2e/preparedRounds.spec.ts | 60 +++++ e2e/sendWorksheet.spec.ts | 22 +- server.ts | 163 ++++++++++++- src/App.tsx | 14 ++ src/components/Canvas.tsx | 15 ++ src/components/CanvasModals.tsx | 123 +++++++++- src/components/LessonPackModals.tsx | 28 ++- src/components/SendWorksheetModal.tsx | 232 +++++++++++++++---- src/components/WorksheetVariantsEditor.tsx | 203 ++++++++++++++++ src/lib/lessonPack.ts | 49 +++- src/lib/roomSnapshot.ts | 2 + src/lib/roundVariants.ts | 192 ++++++++++++++++ src/lib/stampQuadrants.ts | 2 +- src/types.ts | 6 + tests/roundVariants.test.ts | 99 ++++++++ tests/roundVariantsServer.test.ts | 254 +++++++++++++++++++++ 18 files changed, 1422 insertions(+), 81 deletions(-) create mode 100644 src/components/WorksheetVariantsEditor.tsx create mode 100644 src/lib/roundVariants.ts create mode 100644 tests/roundVariants.test.ts create mode 100644 tests/roundVariantsServer.test.ts diff --git a/TODO.md b/TODO.md index 1ed88ac..03029d6 100644 --- a/TODO.md +++ b/TODO.md @@ -13,28 +13,21 @@ specs are in git history. - [x] **Everyone's current boards:** replaces only each board's **background**, never the student's ink. Done (Nov 2026): Live Grid → **Send worksheet…** sends up to four variants (A–D) to selected boards of the viewed round (same / rotate / by name-stamp corner), via `teacher:set-background-multi`. - - [ ] **A prepared breakout round** (see below): sets that round's worksheet template, so students who enter - it later get it. - - [ ] **Set up worksheet variants (A–D) before class, on a prepared round.** Today variants can only be sent - from Live Grid → **Send worksheet…**, after the round is live and students already have boards. - - In the prepared-round form (Breakout manager → **Save for later** / **Edit**), let the teacher upload up to - four variants and pick the distribution: same for all / deal out in turn / by name-stamp corner. - - On **Launch**, the server gives each new board its variant. Corner mode reads the main board's stamps at - launch time. Late joiners get their variant by the same rule, not always A. - - Save variants and the distribution rule **on the round**, so they survive a restart. - - **Lesson packs must carry all of it.** Anything a teacher sets up ahead of time (prepared rounds, their - variants A–D, the distribution rule, the corner mapping, per-student overrides, the late-joiner rule) must - go into **Save lesson…** (`.allaboard`) and come back intact with **Load lesson…**. Per-student overrides - only make sense in the same class, so on load, match them by student name and drop the ones that don't - match. Add a round-trip test: save a pack, load it into a fresh room, and check that every prepared field - matches. - - [ ] **Make a sent distribution editable.** Reopening **Send worksheet…** starts empty: the uploaded variants - and who got which are forgotten, so changing one student's card means uploading everything again. - - Remember each round's variants and assignments, and reopen the modal with them filled in. - - Allow changing one board's letter, swapping a variant's file, or switching the distribution rule, and send - only the boards whose worksheet actually changes. - - Keep the existing rule: ink stays and only the worksheet underneath changes. Warn about boards that - already have work, as the modal does now. + - [x] **A prepared breakout round** (see below): sets that round's worksheet template, so students who enter + it later get it. Done: the prepared-round form's worksheet is the round's template, and **Edit** changes it. + - [x] **Set up worksheet variants (A–D) before class, on a prepared round.** + Done (Nov 2026): the prepared-round form (individual rounds) adds worksheets B–D, the rule (same / deal out in + turn / by name-stamp corner, with the corner map) and the late-joiner rule. On **Launch** the server deals them + out alphabetically by student, or reads Main's name stamps; late joiners get theirs by the same rule (or A). + Stored on the room as teacher-only `roundVariants` (`src/lib/roundVariants.ts`), so they survive restarts and + room saves. Lesson packs carry them; per-student picks (matched by name) go in only when the teacher ticks + "include student picks", and who-got-which never does. Tests: `tests/roundVariantsServer.test.ts`. + Group rounds have no variants yet. + - [x] **Make a sent distribution editable.** + Done (Nov 2026): **Send worksheet…** reopens with the round's A–D files, rule, corner map and per-student picks. + Each board keeps the letter it has until the teacher changes the rule; changing one board's letter or a file + sends only the boards whose worksheet changes. Individual rounds save it all (`teacher:set-round-variants`), + so late joiners get their variant too. - **Server:** a teacher-only path that applies `internBackground` once and then reuses the same asset URL for every board. With content-addressed assets, 30 boards cost one stored image. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 0d4cd4c..71c8d92 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -123,6 +123,7 @@ Cloud Run service "allaboard" ── one container :3000 (node server.ts, Build | `breakoutConfig` | `mode` (`main`/`individual`/`groups`, i.e. where students are **now**), `activeRoundId`, `rounds[]`, `allowSelfSelect`, `chatScope`, `userBoardOverrides` | | `roundTemplates[roundId]` | The worksheet each round's boards start with (copied to late joiners). Sent to **teachers only** (`init`, `breakout-sync`, `round-templates-sync`) and saved in room exports. | | `roundTemplateInk[roundId]` | **Template ink**: teacher Main ink (no name stamps) a round copies onto each of its boards, with new ids and the teacher as author so students can't erase it. Individual boards get it as they're made (late joiners too); group boards at launch. Set by `copyInk` with `copyWorksheet` on `new-round` / `edit-prepared`. Teachers only, like `roundTemplates`; in room exports and lesson packs (`LessonRound.ink`). | +| `roundVariants[roundId]` | **Worksheet variants** for an individual round: worksheets B–D (A is always `roundTemplates[roundId]`), the rule (`same` / `rotate` / `corner` + corner map), the late-joiner rule, per-student picks by lowercased name, and `assigned` (userId → letter, session data). Used when each board is made (`provisionIndividualBoard`; launch deals out alphabetically). Set by `variants` on `new-round` / `edit-prepared` and by `teacher:set-round-variants` (Send worksheet…). Teachers only; in room exports and lesson packs without `assigned` (picks only when the teacher opts in). | | `timer`, `lockedNames`, `bannedUsers`, `isCanvasLocked`, `hideStudentCursors`, `teacherPin`, `lastActiveAt` | As named | | `usersByUserId` | **Runtime only** (not persisted): roster, `sockets` set, `isTeacher`, student status | @@ -153,6 +154,7 @@ Cloud Run service "allaboard" ── one container :3000 (node server.ts, Build - Room and identity: `check-room` (ack, no side effects), `join-room`, `update-profile`, `user:set-status`, `cursor-move`, `disconnect` - Teacher actions: `teacher:auth`, `teacher:step-down`, `teacher:configure-breakout` (actions above), `teacher:set-background`, `teacher:set-background-multi` (one worksheet to many boards; optional `roundTemplateFor` sets the round template), + `teacher:set-round-variants` (ack; an individual round's worksheets B–D, rule and picks, `src/lib/roundVariants.ts`), `teacher:update-background`, `teacher:rename-user`, `teacher:delete-message`, `teacher:unban-user`, `teacher:purge-user-contributions`, `teacher:set-lock`, `teacher:set-hide-cursors`, `teacher:set-one-name-stamp`, `teacher:clear-status`, `teacher:spotlight-board`, `laser-pulse`, `teacher:clear-all`, `teacher:import-room` - Lesson packs (teacher-only, ack; `src/lib/lessonPack.ts`): `teacher:export-lesson` (server builds the skeleton, diff --git a/e2e/preparedRounds.spec.ts b/e2e/preparedRounds.spec.ts index dd26ad6..b78627e 100644 --- a/e2e/preparedRounds.spec.ts +++ b/e2e/preparedRounds.spec.ts @@ -48,3 +48,63 @@ test('a prepared individual round moves nobody until the teacher launches it', a for (const u of [teacher, alex]) await u.context.close(); }); + +async function labeledPng(page: Page, label: string) { + const b64 = await page.evaluate((text) => { + const c = document.createElement('canvas'); + c.width = 400; + c.height = 300; + const ctx = c.getContext('2d')!; + ctx.fillStyle = '#ffffff'; + ctx.fillRect(0, 0, 400, 300); + ctx.fillStyle = '#111827'; + ctx.font = '64px sans-serif'; + ctx.fillText(text, 40, 120); + return c.toDataURL('image/png').split(',')[1]; + }, label); + return { name: `card_${label}.png`, mimeType: 'image/png', buffer: Buffer.from(b64, 'base64') }; +} + +test('a prepared round deals out worksheets A and B when it launches', async ({ browser }) => { + test.setTimeout(60_000); + const room = uniqueRoom('prepvar'); + const teacher = await newUser(browser); + const alex = await newUser(browser); + const bea = await newUser(browser); + await joinRoom(teacher.page, room, 'Ms T', PIN); + await joinRoom(alex.page, room, 'Alex'); + await joinRoom(bea.page, room, 'Bea'); + + await teacher.page.getByTitle('Assign individual student boards or breakout group rooms').click(); + await teacher.page.getByLabel('Round name (optional):').fill('Cards'); + await teacher.page.getByLabel('Upload a worksheet file for this round').setInputFiles(await labeledPng(teacher.page, 'A')); + await expect(teacher.page.getByText('Uploaded: card_A.png')).toBeVisible(); + + const editor = teacher.page.getByTestId('variants-editor'); + await editor.getByRole('button', { name: 'Add worksheet B' }).click(); + await editor.getByLabel('Worksheet B', { exact: true }).setInputFiles(await labeledPng(teacher.page, 'B')); + await expect(editor.getByText(/card_B\.png · 1 page/)).toBeVisible(); + await editor.getByLabel(/Deal out A, B in turn/).check(); + await teacher.page.getByRole('button', { name: 'Save for later' }).click(); + + const list = teacher.page.getByTestId('prepared-rounds'); + await expect(list.getByText(/\+ worksheet B \(dealt out in turn\)/)).toBeVisible(); + await expect(alex.page.getByText(/Active Board:/)).toHaveCount(0); + + await list.getByRole('button', { name: 'Launch' }).click(); + await expect(teacher.page.getByText(/Live Classroom Boards Overview/)).toBeVisible(); + const alexImg = teacher.page.getByAltText("Alex's Board"); + const beaImg = teacher.page.getByAltText("Bea's Board"); + await expect(alexImg).toHaveAttribute('src', /^\/api\/assets\//); + await expect(beaImg).toHaveAttribute('src', /^\/api\/assets\//); + expect(await alexImg.getAttribute('src')).not.toEqual(await beaImg.getAttribute('src')); + + // Send worksheet… starts from what the round handed out. + await teacher.page.getByRole('button', { name: 'Send worksheet…' }).click(); + const dialog = teacher.page.getByRole('dialog'); + await expect(dialog.getByText(/card_B\.png · 1 page/)).toBeVisible(); + await expect(dialog.getByLabel("Worksheet for Alex's Board")).toHaveValue('A'); + await expect(dialog.getByLabel("Worksheet for Bea's Board")).toHaveValue('B'); + + for (const u of [teacher, alex, bea]) await u.context.close(); +}); diff --git a/e2e/sendWorksheet.spec.ts b/e2e/sendWorksheet.spec.ts index f64f696..f192bf5 100644 --- a/e2e/sendWorksheet.spec.ts +++ b/e2e/sendWorksheet.spec.ts @@ -53,7 +53,25 @@ test('Send worksheet rotates A/B across individual boards', async ({ browser }) const beaImg = teacher.page.getByAltText("Bea's Board"); await expect(alexImg).toHaveAttribute('src', /^\/api\/assets\//); await expect(beaImg).toHaveAttribute('src', /^\/api\/assets\//); - expect(await alexImg.getAttribute('src')).not.toEqual(await beaImg.getAttribute('src')); + const aSrc = await alexImg.getAttribute('src'); + expect(aSrc).not.toEqual(await beaImg.getAttribute('src')); - for (const u of [teacher, alex, bea]) await u.context.close(); + // Reopening starts from what was sent: both files, and each board keeps its letter. + await teacher.page.getByRole('button', { name: 'Send worksheet…' }).click(); + await expect(dialog.getByText(/card_A\.png · 1 page/)).toBeVisible(); + await expect(dialog.getByText(/card_B\.png · 1 page/)).toBeVisible(); + await expect(dialog.getByLabel("Worksheet for Alex's Board")).toHaveValue('A'); + await expect(dialog.getByLabel("Worksheet for Bea's Board")).toHaveValue('B'); + // Change one board by hand and send again: only Bea's board changes. + await dialog.getByLabel("Worksheet for Bea's Board").selectOption('A'); + await dialog.getByRole('button', { name: 'Send', exact: true }).click(); + await expect(dialog).toHaveCount(0); + await expect(beaImg).toHaveAttribute('src', aSrc!); + + // A late joiner gets the next letter in turn: Alex A, Bea A (picked), so Cal gets A (2 handed out, 2 letters). + const cal = await newUser(browser); + await joinRoom(cal.page, room, 'Cal'); + await expect(teacher.page.getByAltText("Cal's Board")).toHaveAttribute('src', /^\/api\/assets\//); + + for (const u of [teacher, alex, bea, cal]) await u.context.close(); }); diff --git a/server.ts b/server.ts index 60e1068..b0e6d8c 100644 --- a/server.ts +++ b/server.ts @@ -34,6 +34,15 @@ import { isAnonymousAuthorId, makeAnonymousAuthorId } from './src/lib/anonymousI import { OVERVIEW_SYNC_MS, buildDigest, emptyChanges, type BoardChanges, type BoardDigest } from './src/lib/boardDigest.ts'; import { CURSOR_EMIT_MS } from './src/lib/drawThrottle.ts'; import { buildLessonPack, filterMainInk, validateLesson, type LessonPack, type MainInkChoice } from './src/lib/lessonPack.ts'; +import { + availableLetters, + byStudentName, + hasVariantContent, + normalizeRoundVariants, + pickVariant, + variantBackground, + type RoundVariants, +} from './src/lib/roundVariants.ts'; import { monitorEventLoopDelay } from 'node:perf_hooks'; import { MAX_APPEND_NUMBERS, @@ -151,6 +160,8 @@ interface RoomState { roundTemplates: Record; /** Teacher ink copied onto every board of a round when it's made (template ink). Server ids; teacher-authored. */ roundTemplateInk: Record; + /** Worksheets B–D and the rule for who gets which, per individual round (A is the round template). Teacher-only. */ + roundVariants: Record; timer: TimerState; usersByUserId: Map; /** userId → SHA-256 of that browser's private key. Server-only; never broadcast. */ @@ -174,6 +185,7 @@ interface SerializedRoom { breakoutConfig?: BreakoutConfigState; roundTemplates?: Record; roundTemplateInk?: Record; + roundVariants?: Record; timer?: TimerState; userKeyHashes?: Record; lockedNames?: Record; @@ -368,6 +380,7 @@ export async function startServer(options: StartServerOptions = {}) { breakoutConfig, roundTemplates: item.roundTemplates && typeof item.roundTemplates === 'object' ? item.roundTemplates : {}, roundTemplateInk: storedTemplateInk(item.roundTemplateInk), + roundVariants: storedRoundVariants(item.roundVariants), timer: item.timer || { isRunning: false, durationMs: 5 * 60 * 1000, @@ -401,6 +414,7 @@ export async function startServer(options: StartServerOptions = {}) { breakoutConfig: room.breakoutConfig, roundTemplates: room.roundTemplates, roundTemplateInk: room.roundTemplateInk, + roundVariants: room.roundVariants, timer: room.timer, userKeyHashes: Object.fromEntries(room.userKeyHashes), lockedNames: room.lockedNames, @@ -442,6 +456,9 @@ export async function startServer(options: StartServerOptions = {}) { for (const key of Object.keys(room.roundTemplates)) { room.roundTemplates[key] = internBackground(store, room.roundTemplates[key]); } + for (const v of Object.values(room.roundVariants)) { + v.extra = v.extra.map((bg) => (bg ? internBackground(store, bg) : null)); + } if (room.breakoutConfig.autoIndividualBackground !== undefined) { room.breakoutConfig.autoIndividualBackground = internBackground( store, @@ -613,6 +630,7 @@ export async function startServer(options: StartServerOptions = {}) { breakoutConfig: { mode: 'main', activeRoundId: undefined, rounds: [], allowSelfSelect: false, chatScope: 'unified' }, roundTemplates: {}, roundTemplateInk: {}, + roundVariants: {}, timer: { isRunning: false, durationMs: 5 * 60 * 1000, @@ -953,6 +971,45 @@ export async function startServer(options: StartServerOptions = {}) { return out; } + /** A stored `roundVariants` (SQLite row): only valid records. Backgrounds are interned by internRoomAssets. */ + function storedRoundVariants(raw: unknown): Record { + const out: Record = {}; + if (!raw || typeof raw !== 'object') return out; + for (const [key, value] of Object.entries(raw as Record)) { + const v = normalizeRoundVariants(value); + if (v) out[key] = v; + } + return out; + } + + /** A variants record from a client or a file: checked, worksheets interned. null when it carries nothing. */ + function cleanRoundVariants(raw: unknown): RoundVariants | null { + const v = normalizeRoundVariants(raw); + if (!v) return null; + v.extra = v.extra.map((bg) => (bg ? cloneBackground(bg) : null)); + return hasVariantContent(v) ? v : null; + } + + /** Imported `roundVariants`: only keys naming an individual round in `cfg`. */ + function cleanImportedRoundVariants(raw: unknown, cfg: BreakoutConfigLike): Record { + const out: Record = {}; + if (!raw || typeof raw !== 'object') return out; + const ids = new Set(getRounds(cfg).filter((r) => r.mode === 'individual').map((r) => r.id)); + for (const [key, value] of Object.entries(raw as Record)) { + if (!ids.has(key)) continue; + const v = cleanRoundVariants(value); + if (v) out[key] = v; + } + return out; + } + + /** Sets or clears a round's variants. Group rounds never have any. */ + function setRoundVariants(room: RoomState, roundId: string, mode: string, raw: unknown) { + const v = mode === 'individual' ? cleanRoundVariants(raw) : null; + if (v) room.roundVariants[roundId] = v; + else delete room.roundVariants[roundId]; + } + /** * Imported `roundTemplateInk`: only keys naming a round in `cfg`, each a list of sound elements (no name stamps) at * most `MAX_BOARD_ELEMENTS` long, with fresh server ids. @@ -1008,7 +1065,7 @@ export async function startServer(options: StartServerOptions = {}) { /** Teacher-only: the round templates and their ink, as sent with `init`, `breakout-sync` and `round-templates-sync`. */ function teacherTemplatesPayload(room: RoomState) { - return { roundTemplates: room.roundTemplates, roundTemplateInk: room.roundTemplateInk }; + return { roundTemplates: room.roundTemplates, roundTemplateInk: room.roundTemplateInk, roundVariants: room.roundVariants }; } // ---------- Lesson packs (PLANS_LESSON_PACKS.md, phase 2) ---------- @@ -1023,7 +1080,14 @@ export async function startServer(options: StartServerOptions = {}) { function buildLessonForRoom( room: RoomState, caller: { userId: string; name: string }, - opts: { title?: unknown; exportedBy?: unknown; mainInk?: unknown; includeLaunchedRounds?: unknown; roundIds?: unknown } + opts: { + title?: unknown; + exportedBy?: unknown; + mainInk?: unknown; + includeLaunchedRounds?: unknown; + roundIds?: unknown; + includeStudentPicks?: unknown; + } ): LessonPack { const cfg = room.breakoutConfig; const rounds = getRounds(cfg); @@ -1040,6 +1104,8 @@ export async function startServer(options: StartServerOptions = {}) { rounds, roundTemplates, roundTemplateInk: room.roundTemplateInk, + roundVariants: room.roundVariants, + includeStudentPicks: opts.includeStudentPicks === true, boards: Array.from(room.subBoards.values()).map((sb) => ({ id: sb.id, roundId: sb.roundId, @@ -1084,11 +1150,19 @@ export async function startServer(options: StartServerOptions = {}) { } // Intern any stray data: URL (a hand-edited file), then require every page to be a stored asset. lesson.main.background = cloneBackground(lesson.main.background); - for (const r of lesson.rounds) r.worksheet = cloneBackground(r.worksheet); + for (const r of lesson.rounds) { + r.worksheet = cloneBackground(r.worksheet); + if (r.variants) r.variants.extra = r.variants.extra.map((bg) => cloneBackground(bg)); + } if (lesson.settings.autoIndividualBackground) { lesson.settings.autoIndividualBackground = cloneBackground(lesson.settings.autoIndividualBackground); } - const backgrounds = [lesson.main.background, ...lesson.rounds.map((r) => r.worksheet), lesson.settings.autoIndividualBackground]; + const backgrounds = [ + lesson.main.background, + ...lesson.rounds.map((r) => r.worksheet), + ...lesson.rounds.flatMap((r) => r.variants?.extra ?? []), + lesson.settings.autoIndividualBackground, + ]; let missing = 0; for (const bg of backgrounds) { for (const page of bg?.pages ?? []) { @@ -1129,6 +1203,7 @@ export async function startServer(options: StartServerOptions = {}) { for (const sb of getBoardsInRound(room.subBoards, roundId)) room.subBoards.delete(sb.id); delete room.roundTemplates[roundId]; delete room.roundTemplateInk[roundId]; + delete room.roundVariants[roundId]; } /** @@ -1154,6 +1229,7 @@ export async function startServer(options: StartServerOptions = {}) { const templateInk = lessonInk(lr.ink ?? [], roundId, author); if (templateInk.length > 0) room.roundTemplateInk[roundId] = templateInk; else delete room.roundTemplateInk[roundId]; + setRoundVariants(room, roundId, lr.mode, lr.variants ? { ...lr.variants, assigned: {} } : null); const meta: BreakoutRoundMeta = { id: roundId, number, @@ -1214,7 +1290,8 @@ export async function startServer(options: StartServerOptions = {}) { function provisionIndividualBoard( room: RoomState, roundId: string, - user: { userId: string; name: string } + user: { userId: string; name: string }, + late = true ): boolean { const existing = getBoardsInRound(room.subBoards, roundId).find( (sb) => sb.kind === 'individual' && sb.assignedUserIds.includes(user.userId) @@ -1231,12 +1308,37 @@ export async function startServer(options: StartServerOptions = {}) { title: `${user.name}'s Board`, assignedUserIds: [user.userId], elements: templateInkForBoard(room, roundId, id), - background: cloneBackground(getRoundTemplate(room, roundId)), + background: cloneBackground(variantWorksheetFor(room, roundId, user, late)), messages: [], }); return true; } + /** The worksheet a new individual board gets: the round's own, or the student's variant (B–D) by the round's rule. */ + function variantWorksheetFor(room: RoomState, roundId: string, user: { userId: string; name: string }, late: boolean) { + const template = getRoundTemplate(room, roundId); + const variants = room.roundVariants[roundId]; + if (!variants) return template; + const before = variants.assigned[user.userId]; + const index = + typeof before === 'number' && availableLetters(variants).includes(before) + ? before + : pickVariant(variants, { + userId: user.userId, + name: user.name, + late, + mainElements: room.elements, + mainBackground: room.background, + }); + variants.assigned[user.userId] = index; + return variantBackground(variants, index, template); + } + + /** Students in the order worksheets are dealt out: alphabetical by name. */ + function studentsInDealOrder(room: RoomState): ServerUserRecord[] { + return getBreakoutStudents(room).sort(byStudentName); + } + /** Applies group titles/assignments + allowSelfSelect + chatScope to a round. NEVER touches elements/background/messages. */ function applyRoundEdits(room: RoomState, round: BreakoutRoundMeta, payload: ConfigureBreakoutPayload) { const cfg = room.breakoutConfig; @@ -1322,6 +1424,7 @@ export async function startServer(options: StartServerOptions = {}) { const templateBg = payloadWorksheet(room, payload) ?? null; room.roundTemplates[roundId] = cloneBackground(templateBg); setRoundTemplateInk(room, roundId, payload, callerId); + setRoundVariants(room, roundId, mode, payload.variants); const chatScope: 'unified' | 'board' = payload.chatScope === 'board' ? 'board' : 'unified'; const allowSelfSelect = Boolean(payload.allowSelfSelect); @@ -1335,7 +1438,7 @@ export async function startServer(options: StartServerOptions = {}) { }; if (mode === 'individual') { - if (!prepared) for (const u of getBreakoutStudents(room)) provisionIndividualBoard(room, roundId, u); + if (!prepared) for (const u of studentsInDealOrder(room)) provisionIndividualBoard(room, roundId, u, false); } else { createGroupBoards(room, roundId, groups, templateBg); // A prepared round's group boards get the template ink when it's launched (launchPreparedRound). @@ -1403,6 +1506,13 @@ export async function startServer(options: StartServerOptions = {}) { io.to(room.id).emit('background-sync', { boardId: sb.id, background: sb.background }); } } + if (payload.variants !== undefined) { + // The form doesn't edit per-student picks: keep the ones already on the round (e.g. from a lesson pack). + const keep = room.roundVariants[round.id]?.overrides; + const raw: Record | null = + payload.variants && typeof payload.variants === 'object' ? (payload.variants as unknown as Record) : null; + setRoundVariants(room, round.id, round.mode, raw && !('overrides' in raw) && keep ? { ...raw, overrides: keep } : raw); + } if (round.mode === 'groups' && Array.isArray(payload.groups)) { const wanted = payload.groups.filter(Boolean).slice(0, MAX_GROUPS_PER_ROUND); @@ -1447,6 +1557,7 @@ export async function startServer(options: StartServerOptions = {}) { const roundId = makeRoundId(roundNumber); room.roundTemplates[roundId] = cloneBackground(cfg.autoIndividualBackground ?? null); delete room.roundTemplateInk[roundId]; + delete room.roundVariants[roundId]; const roundMeta: BreakoutRoundMeta = { id: roundId, number: roundNumber, @@ -1817,7 +1928,8 @@ export async function startServer(options: StartServerOptions = {}) { callback?.({ ok: false, error: 'There is no breakout round to resume or edit yet.' }); return; } - if (isPreparedRound(round)) { + const launchingNow = isPreparedRound(round); + if (launchingNow) { if (action !== 'resume') { callback?.({ ok: false, error: 'Launch this prepared round first, or edit it with Edit.' }); return; @@ -1831,7 +1943,7 @@ export async function startServer(options: StartServerOptions = {}) { delete cfg.userBoardOverrides; } if (round.mode === 'individual' && cfg.mode === 'individual' && cfg.activeRoundId === round.id) { - for (const u of getBreakoutStudents(room)) provisionIndividualBoard(room, round.id, u); + for (const u of studentsInDealOrder(room)) provisionIndividualBoard(room, round.id, u, !launchingNow); } } else if (action === 'edit-prepared') { const result = editPreparedRound(room, safePayload, meta.userId); @@ -1850,6 +1962,7 @@ export async function startServer(options: StartServerOptions = {}) { for (const sb of getBoardsInRound(room.subBoards, round.id)) room.subBoards.delete(sb.id); delete room.roundTemplates[round.id]; delete room.roundTemplateInk[round.id]; + delete room.roundVariants[round.id]; } else { // 'new-round' (prepare: true creates it without moving anyone) const result = createRound(room, safePayload, safePayload.prepare === true, meta.userId); @@ -2067,6 +2180,27 @@ export async function startServer(options: StartServerOptions = {}) { callback?.({ ok: true, updated, skipped }); }); + // Teacher-only: remember a round's worksheet variants and who got which (Send worksheet…), so reopening it + // starts from what was sent and late joiners get their variant. Worksheets should already be asset URLs. + socket.on('teacher:set-round-variants', (payload, callback) => { + const meta = socketMeta.get(socket.id); + const room = meta && rooms.get(meta.roomId); + if (!meta || !room || !room.usersByUserId.get(meta.userId)?.isTeacher) { + callback?.({ ok: false, error: 'Only a verified Teacher can change worksheet variants.' }); + return; + } + const round = getRoundById(room.breakoutConfig, payload?.roundId); + if (!round || round.mode !== 'individual') { + callback?.({ ok: false, error: 'Worksheet variants are for individual rounds only.' }); + return; + } + setRoundVariants(room, round.id, round.mode, payload?.variants ?? null); + room.lastActiveAt = Date.now(); + scheduleSaveToDisk(room, true); + io.to(teacherChannel(room.id)).emit('round-templates-sync', teacherTemplatesPayload(room)); + callback?.({ ok: true }); + }); + // Teacher-only Background Worksheet transform update (position, scale, layout) socket.on('teacher:update-background', ({ boardId = 'main', patch }) => { const meta = socketMeta.get(socket.id); @@ -2106,6 +2240,7 @@ export async function startServer(options: StartServerOptions = {}) { assets: importedAssets, roundTemplates: importedRoundTemplates, roundTemplateInk: importedTemplateInk, + roundVariants: importedRoundVariants, }, callback ) => { @@ -2168,6 +2303,7 @@ export async function startServer(options: StartServerOptions = {}) { const mergedRounds = getRounds(room.breakoutConfig); const importedTemplates = cleanImportedRoundTemplates(importedRoundTemplates, importedCfg); const importedInk = cleanImportedTemplateInk(importedTemplateInk, importedCfg); + const importedVariants = cleanImportedRoundVariants(importedRoundVariants, importedCfg); for (const r of getRounds(importedCfg)) { if (knownRoundIds.has(r.id)) continue; mergedRounds.push(r); @@ -2175,6 +2311,7 @@ export async function startServer(options: StartServerOptions = {}) { room.roundTemplates[r.id] = importedTemplates[r.id]; } if (importedInk[r.id]) room.roundTemplateInk[r.id] = importedInk[r.id]; + if (importedVariants[r.id]) room.roundVariants[r.id] = importedVariants[r.id]; } room.breakoutConfig.rounds = mergedRounds; } @@ -2186,6 +2323,7 @@ export async function startServer(options: StartServerOptions = {}) { room.subBoards = deserializeSubBoards(importedSubBoards); room.roundTemplates = {}; room.roundTemplateInk = {}; + room.roundVariants = {}; } if (importedBreakoutConfig) { room.breakoutConfig = normalizeBreakoutConfig(importedBreakoutConfig); @@ -2196,6 +2334,9 @@ export async function startServer(options: StartServerOptions = {}) { if (importedTemplateInk && typeof importedTemplateInk === 'object') { room.roundTemplateInk = cleanImportedTemplateInk(importedTemplateInk, room.breakoutConfig); } + if (importedRoundVariants && typeof importedRoundVariants === 'object') { + room.roundVariants = cleanImportedRoundVariants(importedRoundVariants, room.breakoutConfig); + } room.isCanvasLocked = true; } else { room.elements = validElements; @@ -2205,6 +2346,7 @@ export async function startServer(options: StartServerOptions = {}) { room.subBoards = deserializeSubBoards(importedSubBoards); room.roundTemplates = {}; room.roundTemplateInk = {}; + room.roundVariants = {}; } if (importedBreakoutConfig) { room.breakoutConfig = normalizeBreakoutConfig(importedBreakoutConfig); @@ -2215,6 +2357,9 @@ export async function startServer(options: StartServerOptions = {}) { if (importedTemplateInk && typeof importedTemplateInk === 'object') { room.roundTemplateInk = cleanImportedTemplateInk(importedTemplateInk, room.breakoutConfig); } + if (importedRoundVariants && typeof importedRoundVariants === 'object') { + room.roundVariants = cleanImportedRoundVariants(importedRoundVariants, room.breakoutConfig); + } room.isCanvasLocked = false; } diff --git a/src/App.tsx b/src/App.tsx index a7bebcc..79ae9a3 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -35,6 +35,7 @@ import RoomHistoryDropdown from './components/RoomHistoryDropdown'; import { normalizeRoomCode, sanitizeRoomCodeDraft } from './lib/roomCode'; import { recordRoomHistory } from './lib/roomHistory'; import type { LessonRequestEvent } from './lib/lessonPack'; +import type { RoundVariants } from './lib/roundVariants'; import { motion } from 'motion/react'; import { LogIn, Users, KeyRound, PlusCircle, Shuffle, Eye, EyeOff, LifeBuoy } from 'lucide-react'; import { POINT_FLUSH_MS } from './lib/drawThrottle'; @@ -242,6 +243,8 @@ export default function App() { const [roundTemplates, setRoundTemplates] = useState>({}); /** Teacher-only: ink each round copies onto its boards (server `roundTemplateInk`). Empty for students. */ const [roundTemplateInk, setRoundTemplateInk] = useState>({}); + /** Teacher-only: worksheet variants B–D and who gets which, per individual round (server `roundVariants`). */ + const [roundVariants, setRoundVariants] = useState>({}); const [teacherSelectedBoardId, setTeacherSelectedBoardId] = useState('main'); const [users, setUsers] = useState([]); @@ -414,11 +417,13 @@ export default function App() { isTeacher: verifiedTeacher, roundTemplates: initRoundTemplates, roundTemplateInk: initRoundTemplateInk, + roundVariants: initRoundVariants, assignedName, isNameLocked: initNameLocked, }) => { setRoundTemplates(initRoundTemplates && typeof initRoundTemplates === 'object' ? initRoundTemplates : {}); setRoundTemplateInk(initRoundTemplateInk && typeof initRoundTemplateInk === 'object' ? initRoundTemplateInk : {}); + setRoundVariants(initRoundVariants && typeof initRoundVariants === 'object' ? initRoundVariants : {}); const nextSeen = new Set(); if (Array.isArray(initMsgs)) { setMessages(initMsgs); @@ -463,16 +468,19 @@ export default function App() { subBoards: syncedSubBoards, roundTemplates: syncedRoundTemplates, roundTemplateInk: syncedTemplateInk, + roundVariants: syncedVariants, }: { breakoutConfig: BreakoutConfig; subBoards: Record; roundTemplates?: Record; roundTemplateInk?: Record; + roundVariants?: Record; }) => { setRoomSettings((prev) => ({ ...prev, breakoutConfig: syncedConfig })); if (syncedSubBoards) setSubBoards(syncedSubBoards); if (syncedRoundTemplates && typeof syncedRoundTemplates === 'object') setRoundTemplates(syncedRoundTemplates); if (syncedTemplateInk && typeof syncedTemplateInk === 'object') setRoundTemplateInk(syncedTemplateInk); + if (syncedVariants && typeof syncedVariants === 'object') setRoundVariants(syncedVariants); } ); @@ -481,12 +489,15 @@ export default function App() { ({ roundTemplates: synced, roundTemplateInk: syncedInk, + roundVariants: syncedVariants, }: { roundTemplates?: Record; roundTemplateInk?: Record; + roundVariants?: Record; }) => { if (synced && typeof synced === 'object') setRoundTemplates(synced); if (syncedInk && typeof syncedInk === 'object') setRoundTemplateInk(syncedInk); + if (syncedVariants && typeof syncedVariants === 'object') setRoundVariants(syncedVariants); } ); @@ -1070,6 +1081,7 @@ export default function App() { assets?: Record; roundTemplates?: Record; roundTemplateInk?: Record; + roundVariants?: Record; }, mode: ImportRestoreMode ): Promise<{ ok: boolean; error?: string }> => { @@ -1089,6 +1101,7 @@ export default function App() { assets: snapshot.assets, roundTemplates: snapshot.roundTemplates, roundTemplateInk: snapshot.roundTemplateInk, + roundVariants: snapshot.roundVariants, mode, }, (response: { ok: boolean; error?: string }) => { @@ -2178,6 +2191,7 @@ export default function App() { breakoutConfig={breakoutConfig} roundTemplates={roundTemplates} roundTemplateInk={roundTemplateInk} + roundVariants={roundVariants} users={users} remoteCursors={remoteCursors} laserSocket={socket} diff --git a/src/components/Canvas.tsx b/src/components/Canvas.tsx index 3fcd3f8..3650a9e 100644 --- a/src/components/Canvas.tsx +++ b/src/components/Canvas.tsx @@ -184,6 +184,7 @@ import { CURSOR_EMIT_MS } from '../lib/drawThrottle'; import { isPhoneViewport } from '../lib/compactLayout'; import { STATUS_OPTIONS } from './StudentStatusBadge'; import { LoadLessonModal, SaveLessonModal, type LessonRequest } from './LessonPackModals'; +import { variantBackgrounds, type RoundVariants } from '../lib/roundVariants'; type HistoryAction = | { kind: 'add'; items: CanvasElement[] } @@ -204,6 +205,8 @@ interface CanvasProps { roundTemplates?: Record; /** Teacher-only: ink each round copies onto its boards. */ roundTemplateInk?: Record; + /** Teacher-only: worksheet variants B–D per individual round. */ + roundVariants?: Record; users: User[]; remoteCursors: Record; laserSocket: Socket | null; @@ -254,6 +257,7 @@ interface CanvasProps { assets?: Record; roundTemplates?: Record; roundTemplateInk?: Record; + roundVariants?: Record; }, mode: ImportRestoreMode ) => Promise<{ ok: boolean; error?: string }>; @@ -685,6 +689,7 @@ function WorksheetPageNode({ const EMPTY_ROUND_TEMPLATES: Record = {}; const EMPTY_TEMPLATE_INK: Record = {}; +const EMPTY_ROUND_VARIANTS: Record = {}; export default function Canvas({ roomId, @@ -697,6 +702,7 @@ export default function Canvas({ breakoutConfig, roundTemplates = EMPTY_ROUND_TEMPLATES, roundTemplateInk = EMPTY_TEMPLATE_INK, + roundVariants = EMPTY_ROUND_VARIANTS, users, remoteCursors, laserSocket, @@ -2437,6 +2443,7 @@ export default function Canvas({ ...Object.values(subBoards || {}).map((sb) => sb?.background), breakoutConfig.autoIndividualBackground, ...Object.values(roundTemplates), + ...Object.values(roundVariants).flatMap((v) => variantBackgrounds(v)), ]) ); const snapshot: RoomSnapshot = { @@ -2452,6 +2459,7 @@ export default function Canvas({ breakoutConfig, ...(Object.keys(roundTemplates).length > 0 ? { roundTemplates } : {}), ...(Object.keys(roundTemplateInk).length > 0 ? { roundTemplateInk } : {}), + ...(Object.keys(roundVariants).length > 0 ? { roundVariants } : {}), }; return { @@ -2640,6 +2648,7 @@ export default function Canvas({ assets: pendingSnapshot.assets, roundTemplates: pendingSnapshot.roundTemplates, roundTemplateInk: pendingSnapshot.roundTemplateInk, + roundVariants: pendingSnapshot.roundVariants, }, importMode ); @@ -5634,6 +5643,9 @@ export default function Canvas({ onTeacherClearStatus={onTeacherClearStatus} onSpotlightBoard={onSpotlightBoard} onSendWorksheet={onTeacherSendWorksheet} + roundTemplates={roundTemplates} + roundVariants={roundVariants} + onTeacherRequest={onTeacherLessonRequest} users={users} fullMainElements={fullMainElements} fullMainBackground={fullMainBackground} @@ -5657,6 +5669,8 @@ export default function Canvas({ preparedRounds={preparedRounds} roundTemplates={roundTemplates} roundTemplateInk={roundTemplateInk} + roundVariants={roundVariants} + onTeacherRequest={onTeacherLessonRequest} mainTeacherInkCount={mainTeacherInkCount} subBoards={subBoards} onLoadDraftGroupsForRound={loadDraftGroupsForRound} @@ -5756,6 +5770,7 @@ export default function Canvas({ userName={userName} rounds={getRounds(breakoutConfig)} roundTemplates={roundTemplates} + roundVariants={roundVariants} mainBackground={fullMainBackground} driveConfigured={isGoogleDriveConfigured()} onRequest={onTeacherLessonRequest} diff --git a/src/components/CanvasModals.tsx b/src/components/CanvasModals.tsx index beab0ab..7679aed 100644 --- a/src/components/CanvasModals.tsx +++ b/src/components/CanvasModals.tsx @@ -37,6 +37,16 @@ import { AlertCircle, Check, Download, FolderOpen, Shuffle, X } from 'lucide-rea import { cn } from '../lib/utils'; import { StudentStatusBadge } from './StudentStatusBadge'; import { SendWorksheetModal, type SendWorksheetResult } from './SendWorksheetModal'; +import { + WorksheetVariantsEditor, + draftFromVariants, + draftHasVariants, + emptyVariantsDraft, + missingVariantLetters, + type VariantsDraft, +} from './WorksheetVariantsEditor'; +import { uploadWorksheetPages, variantsNote, type RoundVariants } from '../lib/roundVariants'; +import type { LessonRequest } from './LessonPackModals'; export type { PendingSnapshotData }; @@ -59,6 +69,10 @@ interface LiveGridOverviewProps { bg: RoomBackground | null, roundTemplateFor?: string ) => Promise; + /** Each round's worksheet A and saved variants, so Send worksheet… starts from what was sent. */ + roundTemplates?: Record; + roundVariants?: Record; + onTeacherRequest?: LessonRequest; users: User[]; fullMainElements: CanvasElement[]; fullMainBackground: RoomBackground | null; @@ -87,6 +101,9 @@ export function LiveGridOverview({ onTeacherClearStatus, onSpotlightBoard, onSendWorksheet, + roundTemplates, + roundVariants, + onTeacherRequest, users, fullMainElements, fullMainBackground, @@ -299,6 +316,10 @@ export function LiveGridOverview({ mainElements={fullMainElements} mainBackground={fullMainBackground} onSend={onSendWorksheet} + roundWorksheet={roundTemplates?.[viewingRound.id] ?? null} + roundVariants={roundVariants?.[viewingRound.id] ?? null} + users={users} + onRequest={onTeacherRequest} onClose={() => setShowSendWorksheet(false)} /> )} @@ -364,6 +385,7 @@ interface PreparedRoundsListProps { rounds: BreakoutRoundMeta[]; roundTemplates: Record; roundTemplateInk: Record; + roundVariants: Record; subBoards: Record; busy: boolean; confirmDeleteId: string | null; @@ -379,6 +401,7 @@ function PreparedRoundsList({ rounds, roundTemplates, roundTemplateInk, + roundVariants, subBoards, busy, confirmDeleteId, @@ -409,6 +432,7 @@ function PreparedRoundsList({ {' · Worksheet: '} {templateName(roundTemplates[r.id])} {inkNote(roundTemplateInk[r.id])} + {variantsNote(roundVariants[r.id])}
@@ -499,6 +523,10 @@ interface BreakoutManagerModalProps { roundTemplates?: Record; /** Teacher-only: ink each round copies onto its boards (template ink). */ roundTemplateInk?: Record; + /** Teacher-only: worksheet variants B–D per individual round. */ + roundVariants?: Record; + /** Teacher socket requests (used to upload variant worksheet images one at a time). */ + onTeacherRequest?: LessonRequest; /** How many marks "Also copy my ink from Main" would copy. */ mainTeacherInkCount?: number; subBoards?: Record; @@ -550,6 +578,8 @@ export function BreakoutManagerModal({ preparedRounds = [], roundTemplates = {}, roundTemplateInk = {}, + roundVariants = {}, + onTeacherRequest, mainTeacherInkCount = 0, subBoards = {}, onLoadDraftGroupsForRound, @@ -568,6 +598,36 @@ export function BreakoutManagerModal({ const [preparedNotice, setPreparedNotice] = useState(''); // "Also copy my ink from Main": only with the Copy Current worksheet, so the ink lines up with its pages. const [copyInk, setCopyInk] = useState(false); + // Worksheets B–D for an individual round, and who gets which. + const [variantsDraft, setVariantsDraft] = useState(emptyVariantsDraft); + const [variantsBusy, setVariantsBusy] = useState(false); + const usesVariants = draftBreakoutMode === 'individual'; + const variantsBlocked = usesVariants && (variantsBusy || missingVariantLetters(variantsDraft).length > 0); + + /** The variants to send: worksheet images uploaded first, one at a time. null = none (or a group round). */ + const buildVariantsPayload = async (keepPicks: boolean): Promise => { + if (!usesVariants || !draftHasVariants(variantsDraft)) return null; + const upload = async (dataUrl: string) => { + if (!onTeacherRequest) return dataUrl; + const res = await onTeacherRequest('teacher:upload-asset', { dataUrl }); + if (!res?.ok || typeof res.url !== 'string') throw new Error(res?.error || 'Could not upload a worksheet image.'); + return res.url as string; + }; + const extra: (RoomBackground | null)[] = []; + for (let i = 0; i < 3; i++) { + extra.push(i < variantsDraft.slots ? await uploadWorksheetPages(variantsDraft.extra[i], upload) : null); + } + const payload: Partial = { + extra, + rule: variantsDraft.rule, + cornerMap: variantsDraft.cornerMap, + lateJoiners: variantsDraft.lateJoiners, + assigned: {}, + }; + // Without `overrides` the server keeps the round's per-student picks (edit); a new round starts with none. + if (!keepPicks) payload.overrides = {}; + return payload as RoundVariants; + }; const chooseWorksheet = (choice: RoundWorksheetChoice) => { setWorksheetTouched(true); @@ -663,6 +723,7 @@ export function BreakoutManagerModal({ rounds={preparedRounds} roundTemplates={roundTemplates} roundTemplateInk={roundTemplateInk} + roundVariants={roundVariants} subBoards={subBoards} busy={preparedBusy} confirmDeleteId={confirmDeleteId} @@ -696,6 +757,7 @@ export function BreakoutManagerModal({ setRoundName(preparedRoundName(round)); setWorksheetTouched(false); setCopyInk(Boolean(roundTemplateInk[round.id]?.length)); + setVariantsDraft(draftFromVariants(roundVariants[round.id])); setPreparedView({ kind: 'edit-prepared', round }); }} onDelete={async (round) => { @@ -719,7 +781,10 @@ export function BreakoutManagerModal({

)} + {usesVariants && ( + + )} + {usesVariants && missingVariantLetters(variantsDraft).length > 0 && ( +

+ Choose a file for worksheet {missingVariantLetters(variantsDraft).join(', ')}, or remove it. +

+ )} )} @@ -1325,7 +1410,12 @@ export function BreakoutManagerModal({ ) : isEditingPrepared && preparedView ? ( + + ); + })} + {value.slots < 3 && ( + + )} + {error &&

{error}

} + + {value.slots > 0 && ( +
+
Who gets which
+ + + + {value.rule === 'corner' && ( +
+ {CORNER_KEYS.map((k) => ( + + ))} +
+ )} + +
+ )} + + ); +} diff --git a/src/lib/lessonPack.ts b/src/lib/lessonPack.ts index fb378b3..dab21ef 100644 --- a/src/lib/lessonPack.ts +++ b/src/lib/lessonPack.ts @@ -6,6 +6,7 @@ * embeds the images, and both sides check a file with `validateLesson`. */ import type { BreakoutRoundMeta, CanvasElement, RoomBackground } from '../types.ts'; +import { normalizeRoundVariants, type RoundVariants } from './roundVariants.ts'; export const LESSON_KIND = 'allaboard-lesson'; /** Bump only on a breaking change; loaders refuse newer versions. */ @@ -28,7 +29,8 @@ export type LessonRequestEvent = | 'teacher:export-lesson' | 'teacher:has-assets' | 'teacher:upload-asset' - | 'teacher:load-lesson'; + | 'teacher:load-lesson' + | 'teacher:set-round-variants'; export type MainInkChoice = 'teacher' | 'all' | 'none'; export type ChatScope = 'unified' | 'board'; @@ -48,8 +50,15 @@ export interface LessonRound { ink?: CanvasElement[]; allowSelfSelect?: boolean; chatScope?: ChatScope; + /** + * Individual rounds only: worksheets B–D, the rule for who gets which, and (only when the teacher chose to save + * them) per-student picks by name. Never who got which in class. + */ + variants?: LessonVariants; } +export type LessonVariants = Omit; + export interface LessonSettings { oneNameStamp?: boolean; hideStudentCursors?: boolean; @@ -97,6 +106,10 @@ export interface LessonBuildInput { roundTemplates: Record; /** Template ink per round id (phase 3): teacher ink copied onto each of the round's boards. */ roundTemplateInk?: Record; + /** Worksheet variants per round id (server `roundVariants`). */ + roundVariants?: Record; + /** Keep per-student worksheet picks (student names). Off unless the teacher ticks it. */ + includeStudentPicks?: boolean; boards: LessonBoardInput[]; /** Which rounds to include. Omitted: every prepared round, plus launched rounds when `includeLaunchedRounds`. */ roundIds?: string[]; @@ -187,6 +200,11 @@ export function buildLessonPack(input: LessonBuildInput): LessonPack { if (ink.some((list) => list.length > 0)) round.groupInk = ink; } } + const v = round.mode === 'individual' ? input.roundVariants?.[r.id] : undefined; + if (v) { + const lv = lessonVariants(v, input.includeStudentPicks === true); + if (lv) round.variants = lv; + } if (r.prepared === true) { if (typeof r.allowSelfSelect === 'boolean') round.allowSelfSelect = r.allowSelfSelect; if (r.chatScope === 'board' || r.chatScope === 'unified') round.chatScope = r.chatScope; @@ -230,12 +248,26 @@ export function buildLessonPack(input: LessonBuildInput): LessonPack { return pack; } +/** A round's variants as a pack keeps them: no "who got which", picks by name only when asked. null if empty. */ +export function lessonVariants(v: RoundVariants, includeStudentPicks: boolean): LessonVariants | null { + const extra = v.extra.map((bg) => cloneBg(bg)); + const overrides = includeStudentPicks ? { ...v.overrides } : {}; + if (!extra.some(Boolean) && Object.keys(overrides).length === 0) return null; + return { extra, rule: v.rule, cornerMap: { ...v.cornerMap }, lateJoiners: v.lateJoiners, overrides }; +} + +/** True when any round has per-student picks (for the Save lesson checkbox). */ +export function hasStudentPicks(roundVariants: Record | undefined): boolean { + return Object.values(roundVariants ?? {}).some((v) => v && Object.keys(v.overrides).length > 0); +} + // ---------- Assets ---------- function allBackgrounds(lesson: LessonPack): RoomBackground[] { const list: Array = [ lesson.main.background, ...lesson.rounds.map((r) => r.worksheet), + ...lesson.rounds.flatMap((r) => r.variants?.extra ?? []), lesson.settings.autoIndividualBackground, ]; return list.filter((bg): bg is RoomBackground => Boolean(bg)); @@ -412,6 +444,21 @@ export function validateLesson(raw: unknown): { lesson: LessonPack | null; error } if (typeof r.allowSelfSelect === 'boolean') round.allowSelfSelect = r.allowSelfSelect; if (r.chatScope === 'board' || r.chatScope === 'unified') round.chatScope = r.chatScope; + if (r.variants !== undefined && mode === 'individual') { + if (!isObject(r.variants)) return { lesson: null, error: `${where}: the worksheet variants are damaged.` }; + const rawExtra = Array.isArray(r.variants.extra) ? r.variants.extra.slice(0, 3) : []; + const extra: (RoomBackground | null)[] = []; + for (let vi = 0; vi < 3; vi++) { + const bg = checkBackground(rawExtra[vi], `${where}, worksheet ${'BCD'[vi]}`); + if (!bg.ok) return { lesson: null, error: bg.error }; + extra.push(bg.value); + } + const v = normalizeRoundVariants({ ...r.variants, extra, assigned: {} }); + if (v) { + const lv = lessonVariants(v, true); + if (lv) round.variants = lv; + } + } rounds.push(round); } diff --git a/src/lib/roomSnapshot.ts b/src/lib/roomSnapshot.ts index 31111fd..227ca85 100644 --- a/src/lib/roomSnapshot.ts +++ b/src/lib/roomSnapshot.ts @@ -51,6 +51,8 @@ export function parseSnapshotText(fileName: string, text: string, fallbackRoomId parsed.roundTemplates && typeof parsed.roundTemplates === 'object' ? parsed.roundTemplates : undefined, roundTemplateInk: parsed.roundTemplateInk && typeof parsed.roundTemplateInk === 'object' ? parsed.roundTemplateInk : undefined, + roundVariants: + parsed.roundVariants && typeof parsed.roundVariants === 'object' ? parsed.roundVariants : undefined, }, }; } diff --git a/src/lib/roundVariants.ts b/src/lib/roundVariants.ts new file mode 100644 index 0000000..ec45a42 --- /dev/null +++ b/src/lib/roundVariants.ts @@ -0,0 +1,192 @@ +/** + * Worksheet variants (A–D) for an individual breakout round, and the rule that decides who gets which. + * + * Worksheet A is always the round's own worksheet (`roundTemplates[roundId]` on the server). This record holds B, C + * and D plus the rule, so A can never drift out of sync with the round's worksheet. + * + * Used by the server (launch and late joiners), the prepared-round form, Send worksheet… and lesson packs. + * Pure: no React, DOM or Node imports. + */ +import type { CanvasElement, RoomBackground } from '../types.ts'; +import { quadrantsByUser, type Quadrant } from './stampQuadrants.ts'; + +export const VARIANT_LETTERS = ['A', 'B', 'C', 'D'] as const; +export type VariantLetter = (typeof VARIANT_LETTERS)[number]; +/** 'same': everyone A. 'rotate': deal out in turn, alphabetical by student. 'corner': by name-stamp corner on Main. */ +export type VariantRule = 'same' | 'rotate' | 'corner'; +export type CornerKey = Quadrant | 'none'; +export const CORNER_KEYS: CornerKey[] = ['tl', 'tr', 'bl', 'br', 'none']; + +export interface RoundVariants { + /** Worksheets B, C, D (index 0 = B). null = that letter has no worksheet. */ + extra: (RoomBackground | null)[]; + rule: VariantRule; + /** Corner → letter index (0 = A). Used when `rule` is 'corner'. */ + cornerMap: Record; + /** Students who arrive after launch: by the same rule, or always A. */ + lateJoiners: 'rule' | 'a'; + /** The teacher's per-student picks, keyed by `studentKey(name)`. Survives rejoins and lesson packs. */ + overrides: Record; + /** Who got which letter (userId → index). Session data: kept in room saves, never in lesson packs. */ + assigned: Record; +} + +export const DEFAULT_CORNER_MAP: Record = { tl: 0, tr: 1, bl: 2, br: 3, none: 0 }; +const MAX_OVERRIDES = 200; +const MAX_ASSIGNED = 500; + +export function emptyRoundVariants(): RoundVariants { + return { extra: [null, null, null], rule: 'same', cornerMap: { ...DEFAULT_CORNER_MAP }, lateJoiners: 'rule', overrides: {}, assigned: {} }; +} + +/** How per-student picks are matched: trimmed, lowercased display name. */ +export function studentKey(name: unknown): string { + return typeof name === 'string' ? name.trim().toLowerCase().slice(0, 60) : ''; +} + +function isObject(v: unknown): v is Record { + return Boolean(v) && typeof v === 'object' && !Array.isArray(v); +} + +function letterIndex(v: unknown): number | null { + return typeof v === 'number' && Number.isInteger(v) && v >= 0 && v <= 3 ? v : null; +} + +function isBackground(v: unknown): v is RoomBackground { + return isObject(v) && Array.isArray(v.pages); +} + +function indexMap(raw: unknown, max: number, cleanKey: (k: string) => string): Record { + const out: Record = {}; + if (!isObject(raw)) return out; + let n = 0; + for (const [k, v] of Object.entries(raw)) { + const key = cleanKey(k); + const idx = letterIndex(v); + if (!key || idx === null) continue; + out[key] = idx; + if (++n >= max) break; + } + return out; +} + +/** + * Turns any stored, imported or client-sent value into a valid record, or null when it carries nothing (no extra + * worksheet, no picks). Backgrounds are kept as given: the server interns them separately. Never throws. + */ +export function normalizeRoundVariants(raw: unknown): RoundVariants | null { + if (!isObject(raw)) return null; + const extraRaw = Array.isArray(raw.extra) ? raw.extra : []; + const extra = [0, 1, 2].map((i) => (isBackground(extraRaw[i]) ? (extraRaw[i] as RoomBackground) : null)); + const rule: VariantRule = raw.rule === 'rotate' || raw.rule === 'corner' ? raw.rule : 'same'; + const cornerMap = { ...DEFAULT_CORNER_MAP }; + if (isObject(raw.cornerMap)) { + for (const k of CORNER_KEYS) { + const idx = letterIndex(raw.cornerMap[k]); + if (idx !== null) cornerMap[k] = idx; + } + } + const out: RoundVariants = { + extra, + rule, + cornerMap, + lateJoiners: raw.lateJoiners === 'a' ? 'a' : 'rule', + overrides: indexMap(raw.overrides, MAX_OVERRIDES, studentKey), + assigned: indexMap(raw.assigned, MAX_ASSIGNED, (k) => k.slice(0, 200)), + }; + return hasVariantContent(out) ? out : null; +} + +/** True when the record changes anything compared with "everyone gets A". */ +export function hasVariantContent(v: RoundVariants | null | undefined): boolean { + if (!v) return false; + return v.extra.some(Boolean) || Object.keys(v.overrides).length > 0 || Object.keys(v.assigned).length > 0; +} + +/** Letter indexes that have a worksheet: A always (it's the round's worksheet), then B–D when set. */ +export function availableLetters(v: RoundVariants | null | undefined): number[] { + const out = [0]; + if (v) v.extra.forEach((bg, i) => { if (bg) out.push(i + 1); }); + return out; +} + +/** The worksheet for a letter: A is the round's own worksheet. */ +export function variantBackground( + v: RoundVariants | null | undefined, + index: number, + roundWorksheet: RoomBackground | null +): RoomBackground | null { + if (index <= 0 || !v) return roundWorksheet; + return v.extra[index - 1] ?? roundWorksheet; +} + +export interface VariantPickContext { + userId: string; + name: string; + /** Arrived after the round launched (late joiner, rejoin without a board). */ + late: boolean; + /** Main board, for corner mode. */ + mainElements: CanvasElement[]; + mainBackground: RoomBackground | null; +} + +/** + * Which letter a student gets. Order: the teacher's pick for that name, then late-joiner rule, then the round's rule. + * 'rotate' deals the next letter in turn (the caller provisions students alphabetically at launch). + */ +export function pickVariant(v: RoundVariants | null | undefined, ctx: VariantPickContext): number { + if (!v) return 0; + const letters = availableLetters(v); + const ok = (i: number | undefined): i is number => typeof i === 'number' && letters.includes(i); + const override = v.overrides[studentKey(ctx.name)]; + if (ok(override)) return override; + if (ctx.late && v.lateJoiners === 'a') return 0; + if (v.rule === 'rotate') return letters[Object.keys(v.assigned).length % letters.length]; + if (v.rule === 'corner') { + const q = quadrantsByUser(ctx.mainElements, ctx.mainBackground, [ctx.userId])[ctx.userId] ?? null; + const idx = v.cornerMap[q ?? 'none']; + return ok(idx) ? idx : 0; + } + return 0; +} + +/** Every worksheet in the record (B–D), for asset embedding and interning. */ +export function variantBackgrounds(v: RoundVariants | null | undefined): RoomBackground[] { + return v ? v.extra.filter((bg): bg is RoomBackground => Boolean(bg)) : []; +} + +/** Sorts students for dealing out in turn: alphabetical by name, then id. */ +export function byStudentName(a: T, b: T): number { + return a.name.localeCompare(b.name, undefined, { sensitivity: 'base', numeric: true }) || a.userId.localeCompare(b.userId); +} + +/** Same page images in the same order: the board already shows this worksheet. */ +export function sameWorksheet(a: RoomBackground | null | undefined, b: RoomBackground | null | undefined): boolean { + if (!a || !b) return !a && !b; + if (a.pages.length !== b.pages.length) return false; + return a.pages.every((p, i) => p.dataUrl === b.pages[i].dataUrl); +} + +/** + * A copy of a worksheet whose `data:` pages are uploaded one at a time (`upload` returns the asset URL), so a payload + * with several worksheets stays far under the socket size limit. Pages that are already URLs are kept. + */ +export async function uploadWorksheetPages( + bg: RoomBackground | null, + upload: (dataUrl: string) => Promise +): Promise { + if (!bg) return null; + const pages = []; + for (const page of bg.pages) { + pages.push(page.dataUrl.startsWith('data:') ? { ...page, dataUrl: await upload(page.dataUrl) } : page); + } + return { ...bg, pages }; +} + +/** " + worksheets B, C (by corner)" for a round with variants, else "". */ +export function variantsNote(v: Pick | null | undefined): string { + const letters = (v?.extra ?? []).map((bg, i) => (bg ? 'BCD'[i] : '')).filter(Boolean); + if (letters.length === 0) return ''; + const rule = v!.rule === 'rotate' ? 'dealt out in turn' : v!.rule === 'corner' ? 'by name-stamp corner' : 'A for all'; + return ` + worksheet${letters.length === 1 ? '' : 's'} ${letters.join(', ')} (${rule})`; +} diff --git a/src/lib/stampQuadrants.ts b/src/lib/stampQuadrants.ts index 0c96899..a0642b4 100644 --- a/src/lib/stampQuadrants.ts +++ b/src/lib/stampQuadrants.ts @@ -1,5 +1,5 @@ import type { CanvasElement, RoomBackground } from '../types'; -import { layoutPages } from './worksheetLayout'; +import { layoutPages } from './worksheetLayout.ts'; /** Which quarter of a worksheet page a point falls in. */ export type Quadrant = 'tl' | 'tr' | 'bl' | 'br'; diff --git a/src/types.ts b/src/types.ts index 5057266..cb0a00a 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,3 +1,4 @@ +import type { RoundVariants } from './lib/roundVariants'; export type StudentStampKind = 'check' | 'question' | 'star' | 'thumbsup' | 'heart' | 'username'; export type TeacherStampKind = @@ -159,6 +160,8 @@ export interface ConfigureBreakoutPayload { autoIndividualBackground?: RoomBackground | null; // used by 'set-auto-individual' prepare?: boolean; // 'new-round': create the round without moving anyone title?: string; // 'new-round' / 'edit-prepared': teacher's own round name, <= 40 chars + /** 'new-round' / 'edit-prepared', individual rounds: worksheets B–D and who gets which. null clears them. */ + variants?: RoundVariants | null; } export interface SubBoardData { @@ -258,6 +261,8 @@ export interface RoomSnapshot { roundTemplates?: Record; /** Teacher ink copied onto each round's boards (server `room.roundTemplateInk`). Absent in older files. */ roundTemplateInk?: Record; + /** Worksheet variants B–D per individual round (server `room.roundVariants`). Absent in older files. */ + roundVariants?: Record; } export interface PendingSnapshotData { @@ -273,4 +278,5 @@ export interface PendingSnapshotData { assets?: Record; roundTemplates?: Record; roundTemplateInk?: Record; + roundVariants?: Record; } diff --git a/tests/roundVariants.test.ts b/tests/roundVariants.test.ts new file mode 100644 index 0000000..24ec6da --- /dev/null +++ b/tests/roundVariants.test.ts @@ -0,0 +1,99 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import type { CanvasElement, RoomBackground } from '../src/types.ts'; +import { + availableLetters, + emptyRoundVariants, + normalizeRoundVariants, + pickVariant, + sameWorksheet, + studentKey, + uploadWorksheetPages, + variantBackground, + variantsNote, + type RoundVariants, +} from '../src/lib/roundVariants.ts'; + +const sheet = (url: string): RoomBackground => + ({ fileName: url, pages: [{ dataUrl: url, width: 100, height: 100 }] }) as RoomBackground; + +const withExtra = (patch: Partial): RoundVariants => ({ ...emptyRoundVariants(), ...patch }); + +const stamp = (userId: string, x: number, y: number): CanvasElement => + ({ id: `s-${userId}`, boardId: 'main', userId, tool: 'stamp', stamp: 'username', x, y, timestamp: 1 }) as CanvasElement; + +const ctx = (userId: string, name = userId, late = false, mainElements: CanvasElement[] = []) => ({ + userId, + name, + late, + mainElements, + mainBackground: sheet('/api/assets/main'), +}); + +describe('roundVariants', () => { + it('normalizes junk to null and keeps valid fields', () => { + assert.equal(normalizeRoundVariants(null), null); + assert.equal(normalizeRoundVariants({ rule: 'rotate' }), null, 'no worksheets and no picks carries nothing'); + const v = normalizeRoundVariants({ + extra: [sheet('b'), 'junk', sheet('d')], + rule: 'corner', + cornerMap: { tl: 3, tr: 9, none: 1 }, + lateJoiners: 'a', + overrides: { ' Alex ': 2, bea: 7 }, + assigned: { u1: 1 }, + })!; + assert.deepEqual(v.extra.map((bg) => bg?.fileName ?? null), ['b', null, 'd']); + assert.equal(v.rule, 'corner'); + assert.deepEqual(v.cornerMap, { tl: 3, tr: 1, bl: 2, br: 3, none: 1 }); + assert.equal(v.lateJoiners, 'a'); + assert.deepEqual(v.overrides, { alex: 2 }); + assert.deepEqual(v.assigned, { u1: 1 }); + }); + + it('lists available letters and finds each worksheet', () => { + const v = withExtra({ extra: [null, sheet('c'), null] }); + assert.deepEqual(availableLetters(v), [0, 2]); + assert.equal(variantBackground(v, 0, sheet('a'))?.fileName, 'a'); + assert.equal(variantBackground(v, 2, sheet('a'))?.fileName, 'c'); + assert.equal(variantBackground(v, 1, sheet('a'))?.fileName, 'a', 'a letter with no worksheet falls back to A'); + }); + + it('deals out in turn, honors picks by name and the late-joiner rule', () => { + const v = withExtra({ extra: [sheet('b'), null, null], rule: 'rotate' }); + assert.equal(pickVariant(v, ctx('u1')), 0); + v.assigned.u1 = 0; + assert.equal(pickVariant(v, ctx('u2')), 1); + v.assigned.u2 = 1; + v.overrides[studentKey('Cal')] = 1; + assert.equal(pickVariant(v, ctx('u3', ' cal ')), 1, 'pick by name wins over the rule'); + v.lateJoiners = 'a'; + assert.equal(pickVariant(v, ctx('u4', 'Dee', true)), 0); + v.overrides.cal = 3; + assert.equal(pickVariant(v, ctx('u3', 'Cal')), 0, 'a pick for a letter with no worksheet is ignored'); + }); + + it('picks by name-stamp corner', () => { + const v = withExtra({ extra: [sheet('b'), sheet('c'), sheet('d')], rule: 'corner' }); + const main = [stamp('u1', 10, 10), stamp('u2', 90, 90)]; + assert.equal(pickVariant(v, ctx('u1', 'u1', false, main)), 0); + assert.equal(pickVariant(v, ctx('u2', 'u2', false, main)), 3); + v.cornerMap.none = 1; + assert.equal(pickVariant(v, ctx('u3', 'u3', false, main)), 1, 'no stamp uses the "none" letter'); + }); + + it('compares worksheets and uploads only data pages', async () => { + assert.ok(sameWorksheet(sheet('/api/assets/x'), sheet('/api/assets/x'))); + assert.ok(!sameWorksheet(sheet('/api/assets/x'), sheet('/api/assets/y'))); + assert.ok(sameWorksheet(null, undefined)); + const bg = { fileName: 'f', pages: [{ dataUrl: 'data:image/png;base64,AA', width: 1, height: 1 }, { dataUrl: '/api/assets/k', width: 1, height: 1 }] } as RoomBackground; + const uploaded: string[] = []; + const out = await uploadWorksheetPages(bg, async (d) => { uploaded.push(d); return '/api/assets/new'; }); + assert.deepEqual(out!.pages.map((p) => p.dataUrl), ['/api/assets/new', '/api/assets/k']); + assert.equal(uploaded.length, 1); + }); + + it('describes a round with variants', () => { + assert.equal(variantsNote(null), ''); + assert.equal(variantsNote(withExtra({ extra: [sheet('b'), null, sheet('d')], rule: 'corner' })), ' + worksheets B, D (by name-stamp corner)'); + }); +}); diff --git a/tests/roundVariantsServer.test.ts b/tests/roundVariantsServer.test.ts new file mode 100644 index 0000000..5e9851d --- /dev/null +++ b/tests/roundVariantsServer.test.ts @@ -0,0 +1,254 @@ +import { describe, it, beforeEach, afterEach } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import type { Socket } from 'socket.io-client'; +import { lessonAssetUrls, type LessonPack } from '../src/lib/lessonPack.ts'; +import { PNG, type ServerHandle, delay, emitAck, socketPool, startTestServer, waitForEvent, worksheet } from './socketHelpers.ts'; + +/** A 100×100 worksheet page at (0, 0), so stamp corners are easy to place. */ +const board100 = (fileName: string) => ({ ...worksheet(fileName), pages: [{ dataUrl: PNG, width: 100, height: 100 }] }); + +const nameStamp = (id: string, userId: string, x: number, y: number) => ({ + id, + boardId: 'main', + userId, + userName: userId, + tool: 'stamp', + stamp: 'username', + color: '#000', + strokeWidth: 3, + x, + y, +}); + +const variants = (extra: Partial>, more: Record = {}) => ({ + extra: [extra.B ? worksheet(extra.B) : null, extra.C ? worksheet(extra.C) : null, extra.D ? worksheet(extra.D) : null], + rule: 'same', + ...more, +}); + +describe('worksheet variants A–D on rounds', () => { + let srv: ServerHandle; + let dir: string; + const extraServers: { srv: ServerHandle; dir: string }[] = []; + const pool = socketPool(); + + beforeEach(async () => { + ({ srv, dir } = await startTestServer()); + }); + afterEach(async () => { + pool.closeAll(); + await srv.close(); + fs.rmSync(dir, { recursive: true, force: true }); + for (const e of extraServers.splice(0)) { + await e.srv.close(); + fs.rmSync(e.dir, { recursive: true, force: true }); + } + }); + + async function setupClass(roomId: string, server = srv) { + const { socket: teacher } = await pool.join(server, { roomId, userId: 't1', name: 'Teacher' }); + assert.equal((await emitAck(teacher, 'teacher:auth', { pin: '1234' })).ok, true); + const { socket: sam } = await pool.join(server, { roomId, userId: 's1', name: 'Sam' }); + const { socket: ada } = await pool.join(server, { roomId, userId: 's2', name: 'Ada' }); + await delay(30); + return { teacher, sam, ada }; + } + + async function configure(teacher: Socket, payload: any) { + const sync = waitForEvent(teacher, 'breakout-sync'); + const res = await emitAck(teacher, 'teacher:configure-breakout', payload); + assert.equal(res.ok, true, res.error); + return { res, sync: await sync }; + } + + const fileOf = (sync: any, userId: string, round = 'r1') => sync.subBoards[`${round}_ind_${userId}`]?.background?.fileName; + + it('V1 – deal out in turn: launch deals alphabetically, late joiners keep dealing', async () => { + const { teacher } = await setupClass('v-1'); + const { sync: prepared } = await configure(teacher, { + action: 'new-round', + prepare: true, + mode: 'individual', + customBackground: worksheet('a.png'), + variants: variants({ B: 'b.png' }, { rule: 'rotate' }), + }); + assert.equal(prepared.roundVariants.r1.rule, 'rotate'); + assert.equal(prepared.roundVariants.r1.extra[0].fileName, 'b.png'); + assert.match(prepared.roundVariants.r1.extra[0].pages[0].dataUrl, /^\/api\/assets\//); + assert.deepEqual(Object.keys(prepared.subBoards), [], 'nobody moved'); + + const { sync } = await configure(teacher, { action: 'resume', roundId: 'r1' }); + assert.equal(fileOf(sync, 's2'), 'a.png', 'Ada is first alphabetically'); + assert.equal(fileOf(sync, 's1'), 'b.png'); + assert.deepEqual(sync.roundVariants.r1.assigned, { s2: 0, s1: 1 }); + + const late = waitForEvent(teacher, 'breakout-sync'); + await pool.join(srv, { roomId: 'v-1', userId: 's3', name: 'Zed' }); + assert.equal(fileOf(await late, 's3'), 'a.png', 'third student: back to A'); + }); + + it('V2 – by name-stamp corner, read at launch; late joiners by the same rule or always A', async () => { + const { teacher, sam, ada } = await setupClass('v-2'); + teacher.emit('teacher:set-background', { background: board100('corners.png') }); + await delay(30); + sam.emit('element-start', nameStamp('st1', 's1', 10, 10)); // top-left + ada.emit('element-start', nameStamp('st2', 's2', 90, 90)); // bottom-right + await delay(50); + await configure(teacher, { + action: 'new-round', + prepare: true, + mode: 'individual', + customBackground: worksheet('a.png'), + variants: variants({ B: 'b.png', D: 'd.png' }, { rule: 'corner', cornerMap: { tl: 0, tr: 1, bl: 2, br: 3, none: 1 } }), + }); + const { sync } = await configure(teacher, { action: 'resume', roundId: 'r1' }); + assert.equal(fileOf(sync, 's1'), 'a.png'); + assert.equal(fileOf(sync, 's2'), 'd.png'); + + // A late joiner with no stamp gets the "no stamp" letter (B). + let late = waitForEvent(teacher, 'breakout-sync'); + await pool.join(srv, { roomId: 'v-2', userId: 's3', name: 'Zed' }); + assert.equal(fileOf(await late, 's3'), 'b.png'); + + // "Late joiners always get A" overrides the rule for anyone after launch. + const res = await emitAck(teacher, 'teacher:set-round-variants', { + roundId: 'r1', + variants: { ...sync.roundVariants.r1, lateJoiners: 'a' }, + }); + assert.equal(res.ok, true, res.error); + late = waitForEvent(teacher, 'breakout-sync'); + await pool.join(srv, { roomId: 'v-2', userId: 's4', name: 'Yan' }); + assert.equal(fileOf(await late, 's4'), 'a.png'); + }); + + it('V3 – a per-student pick by name wins over the rule, and edit-prepared keeps picks', async () => { + const { teacher } = await setupClass('v-3'); + await configure(teacher, { + action: 'new-round', + prepare: true, + mode: 'individual', + customBackground: worksheet('a.png'), + variants: variants({ C: 'c.png' }, { overrides: { ' SAM ': 2 } }), + }); + // The prepared-round form sends no overrides: the round keeps the pick. + const { sync: edited } = await configure(teacher, { + action: 'edit-prepared', + roundId: 'r1', + variants: variants({ C: 'c.png' }), + }); + assert.deepEqual(edited.roundVariants.r1.overrides, { sam: 2 }); + const { sync } = await configure(teacher, { action: 'resume', roundId: 'r1' }); + assert.equal(fileOf(sync, 's1'), 'c.png'); + assert.equal(fileOf(sync, 's2'), 'a.png'); + }); + + it('V4 – clearing variants, group rounds and students', async () => { + const { teacher, sam } = await setupClass('v-4'); + await configure(teacher, { + action: 'new-round', + prepare: true, + mode: 'individual', + variants: variants({ B: 'b.png' }, { rule: 'rotate' }), + }); + const { sync } = await configure(teacher, { action: 'edit-prepared', roundId: 'r1', variants: null }); + assert.equal(sync.roundVariants.r1, undefined); + + const { sync: grp } = await configure(teacher, { + action: 'new-round', + prepare: true, + mode: 'groups', + groups: [{ id: 'g', title: 'G', assignedUserIds: [] }], + variants: variants({ B: 'b.png' }), + }); + assert.equal(grp.roundVariants.r2, undefined, 'group rounds take no variants'); + assert.equal((await emitAck(teacher, 'teacher:set-round-variants', { roundId: 'r2', variants: variants({ B: 'b.png' }) })).ok, false); + assert.equal((await emitAck(sam, 'teacher:set-round-variants', { roundId: 'r1', variants: variants({ B: 'b.png' }) })).ok, false); + const studentSync = waitForEvent(sam, 'breakout-sync'); + await configure(teacher, { action: 'resume', roundId: 'r1' }); + assert.equal((await studentSync).roundVariants, undefined, 'students never see variants'); + }); + + it('V5 – variants survive a restart and a room save round trip', async () => { + const { teacher } = await setupClass('v-5'); + await configure(teacher, { + action: 'new-round', + prepare: true, + mode: 'individual', + customBackground: worksheet('a.png'), + variants: variants({ B: 'b.png' }, { rule: 'rotate' }), + }); + await srv.flushRoomsToDiskAsync(); + pool.closeAll(); + await srv.close(); + ({ srv } = await startTestServer(dir)); + const { socket: t2, init } = await pool.join(srv, { roomId: 'v-5', userId: 't1', name: 'Teacher', teacherPin: '1234' }); + assert.equal(init.roundVariants.r1.extra[0].fileName, 'b.png'); + assert.equal(init.roundVariants.r1.rule, 'rotate'); + + // Room save (Save .JSON → Import .JSON) into another room keeps them. + const { socket: t3 } = await pool.join(srv, { roomId: 'v-5-copy', userId: 't1', name: 'Teacher' }); + assert.equal((await emitAck(t3, 'teacher:auth', { pin: '1234' })).ok, true); + const templates = waitForEvent(t3, 'round-templates-sync'); + const res = await emitAck(t3, 'teacher:import-room', { + elements: [], + messages: [], + subBoards: init.subBoards, + breakoutConfig: init.roomSettings.breakoutConfig, + roundTemplates: init.roundTemplates, + roundVariants: init.roundVariants, + mode: 'replace', + }); + assert.equal(res.ok, true, res.error); + assert.equal((await templates).roundVariants.r1.extra[0].fileName, 'b.png'); + void t2; + }); + + it('V6 – lesson packs carry variants; per-student picks only when asked; never who got which', async () => { + const { teacher } = await setupClass('v-6'); + await configure(teacher, { + action: 'new-round', + prepare: true, + mode: 'individual', + customBackground: worksheet('a.png'), + variants: variants({ B: 'b.png', C: 'c.png' }, { rule: 'corner', cornerMap: { tl: 2, tr: 1, bl: 0, br: 0, none: 2 }, lateJoiners: 'a', overrides: { sam: 1 } }), + }); + let res = await emitAck(teacher, 'teacher:export-lesson', {}); + let lesson: LessonPack = res.lesson; + assert.equal(JSON.stringify(lesson).includes('sam'), false, 'no student names by default'); + assert.deepEqual(lesson.rounds[0].variants?.overrides, {}); + res = await emitAck(teacher, 'teacher:export-lesson', { includeStudentPicks: true }); + lesson = res.lesson; + assert.deepEqual(lesson.rounds[0].variants?.overrides, { sam: 1 }); + assert.equal('assigned' in (lesson.rounds[0].variants as object), false); + + // Load on a second server, as another teacher's computer would. + const assets: Record = {}; + for (const u of lessonAssetUrls(lesson)) { + const r = await fetch(`http://127.0.0.1:${srv.port}${u}`); + assets[u] = `data:image/png;base64,${Buffer.from(await r.arrayBuffer()).toString('base64')}`; + } + const other = await startTestServer(); + extraServers.push(other); + const { teacher: t2 } = await setupClass('v-6-src', other.srv); + const has = await emitAck(t2, 'teacher:has-assets', { urls: Object.keys(assets) }); + for (const u of has.missing) assert.equal((await emitAck(t2, 'teacher:upload-asset', { dataUrl: assets[u] })).ok, true); + res = await emitAck(t2, 'teacher:load-lesson', { lesson, target: 'new', newRoomId: 'v-6-new', pin: '5678' }); + assert.equal(res.ok, true, res.error); + const { init } = await pool.join(other.srv, { roomId: 'v-6-new', userId: 't1', name: 'Teacher', teacherPin: '5678' }); + const v = init.roundVariants.r1; + assert.deepEqual(v.extra.map((bg: any) => bg?.fileName ?? null), ['b.png', 'c.png', null]); + assert.equal(v.rule, 'corner'); + assert.deepEqual(v.cornerMap, { tl: 2, tr: 1, bl: 0, br: 0, none: 2 }); + assert.equal(v.lateJoiners, 'a'); + assert.deepEqual(v.overrides, { sam: 1 }); + assert.deepEqual(v.assigned, {}); + assert.equal(init.roundTemplates.r1.fileName, 'a.png'); + + // A pack with a missing variant image is refused. + const broken = structuredClone(lesson); + broken.rounds[0].variants!.extra[1]!.pages[0].dataUrl = `/api/assets/${'2'.repeat(64)}`; + res = await emitAck(t2, 'teacher:load-lesson', { lesson: broken, target: 'new', newRoomId: 'v-6-bad', pin: '5678' }); + assert.match(res.error, /missing/); + }); +});