Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ Cloud Run service "allaboard" ── one container :3000 (node server.ts, Build
grid and moderation. **If you add a delta event, send it to `boardAudience` *and* call `noteChange`.**
- **Students only hold their own board's ink.** `init` and `breakout-sync` are built per socket (`subBoardsFor`):
teachers get every board; students get every board's metadata, background and chat, but `elements: []` except on
their own board (`placeSocket` sends the real contents when they move). So a student's Save .JSON contains only their
their own board (`placeSocket` sends the real contents when they move). So a student's Save class work contains only their
own board's ink, and a teacher's copy of boards they aren't viewing is ≤ 1.5 s old. (`room-restored` after an import
is still full, room-wide.)
- **Ink pacing (client).** `element-append-points` is queued and sent every 500 ms (`POINT_FLUSH_MS`); any other drawing emit goes through
Expand Down
44 changes: 43 additions & 1 deletion e2e/classroom.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -476,7 +476,7 @@ test.describe('teacher and students', () => {

const strokeOf = async (page: Page) => {
const download = page.waitForEvent('download');
await page.getByRole('button', { name: 'Save .JSON' }).click();
await page.getByRole('button', { name: 'Save class work' }).click();
const file = await (await download).path();
const snapshot = JSON.parse((await import('node:fs')).readFileSync(file!, 'utf8'));
return snapshot.elements[0].points as number[];
Expand Down Expand Up @@ -847,6 +847,48 @@ test.describe('room exists confirmation modal', () => {
await visitor.context.close();
await invitee.context.close();
});

test('lobby New Room makes the typed room (or a random one) and goes in, but warns when it already exists', async ({ browser }) => {
const freshRoom = uniqueRoom('newroom');
const maker = await newUser(browser);
const randomMaker = await newUser(browser);
const latecomer = await newUser(browser);

// No name yet: New Room says so and stays in the lobby.
await maker.page.goto('/');
await maker.page.getByLabel('Room Code').fill(freshRoom);
await maker.page.getByRole('button', { name: 'New Room' }).click();
await expect(maker.page.getByText('Type your name first, then press New Room.')).toBeVisible();
await expect(maker.page.getByLabel('Room Code')).toHaveValue(freshRoom);

// With a name: New Room makes that room and goes straight in.
await maker.page.getByLabel('Your Display Name').fill('Ms. Maker');
await maker.page.getByRole('button', { name: 'New Room' }).click();
await expect(maker.page.getByRole('dialog')).toHaveCount(0);
await expect(maker.page.locator('.konvajs-content').first()).toBeVisible();
await expect(maker.page).toHaveURL(new RegExp(`room=${freshRoom}`));

// An empty box makes a random room.
await randomMaker.page.goto('/');
await randomMaker.page.getByLabel('Your Display Name').fill('Mr. Random');
await randomMaker.page.getByLabel('Room Code').fill('');
await randomMaker.page.getByRole('button', { name: 'New Room' }).click();
await expect(randomMaker.page.locator('.konvajs-content').first()).toBeVisible();
await expect(randomMaker.page).toHaveURL(/room=class-/);

// A code that's already in use gets the "already exists" choice instead of a silent join.
await latecomer.page.goto('/');
await latecomer.page.getByLabel('Your Display Name').fill('Sam');
await latecomer.page.getByLabel('Room Code').fill(freshRoom);
await latecomer.page.getByRole('button', { name: 'New Room' }).click();
const dialog = latecomer.page.getByRole('dialog');
await expect(dialog.getByText('Room Already Exists')).toBeVisible();
await dialog.getByRole('button', { name: 'Cancel', exact: true }).click();
await expect(dialog).toHaveCount(0);
await expect(latecomer.page.getByRole('button', { name: 'Join Classroom' })).toBeVisible();

for (const u of [maker, randomMaker, latecomer]) await u.context.close();
});
});

test.describe('kick or ban contribution purge modal', () => {
Expand Down
32 changes: 31 additions & 1 deletion e2e/googleDrive.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,7 @@ test.describe('Google Drive integration (stubbed Google)', () => {
await joinRoom(page, uniqueRoom('gd-open'), 'Ms T', '4829');
await page.getByRole('button', { name: 'Open Room from Drive' }).click();

await expect(page.getByText('Restore Room Snapshot (.JSON)')).toBeVisible();
await expect(page.getByText('Open Class Work (.json)')).toBeVisible();
await expect(page.getByText('saved-room.json')).toBeVisible();
await expect(page.getByText('#prev-room')).toBeVisible();
await expect(page.getByText('1 items')).toBeVisible();
Expand Down Expand Up @@ -592,6 +592,36 @@ test.describe('Google Drive integration (stubbed Google)', () => {
expect(requests[2].url).toContain('/files/drive-file-42?uploadType=resumable');
});

test('lessons save to Drive as their own type, and the lesson picker lists only those first', async ({ page }) => {
await installFakeGoogle(page, { pickerAction: 'cancel' });
const requests = await fakeDriveUploads(page);
await joinRoom(page, uniqueRoom('gd-lesson'), 'Ms T', '4829');

await page.getByRole('button', { name: 'Save lesson…' }).click();
const save = page.getByTestId('save-lesson-modal');
await save.getByLabel('Lesson title').fill('Fractions');
await save.getByRole('button', { name: 'Save to Drive' }).click();
await expect(save.getByText(/Saved fractions-.*\.allaboard to My Drive/)).toBeVisible();
expect(requests[0].method).toBe('POST');
expect(requests[0].meta).toEqual({
name: expect.stringMatching(/^fractions-\d{4}-\d{2}-\d{2}\.allaboard$/),
mimeType: 'application/vnd.allaboard.lesson+json',
});
await save.getByRole('button', { name: 'Close', exact: true }).click();

// A room save (application/json) is never in "My lessons"; Browse Drive still finds older lessons saved as JSON.
await page.getByRole('button', { name: 'Load lesson…' }).click();
await page.getByTestId('load-lesson-modal').getByRole('button', { name: 'Open from Drive' }).click();
await expect.poll(async () => (await pickerLog(page)).length).toBe(1);
const [log] = await pickerLog(page);
expect(log.views.map((v) => v.calls.setLabel?.[0])).toEqual(['My lessons', 'Browse Drive']);
expect(log.views[0].calls.setMimeTypes).toEqual(['application/vnd.allaboard.lesson+json']);
expect(log.views[0].calls.setOwnedByMe).toEqual([true]);
expect(log.views[1].calls.setMimeTypes).toEqual([
'application/vnd.allaboard.lesson+json,application/json,application/octet-stream',
]);
});

test('Save Room to Drive saves a renamed file into a chosen folder, and remembers that folder', async ({ page }) => {
await installFakeGoogle(page);
const requests = await fakeDriveUploads(page);
Expand Down
4 changes: 2 additions & 2 deletions e2e/worksheets.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ test.describe('worksheet UI', () => {
await expect(page.getByRole('button', { name: 'Grid', exact: true })).toHaveAttribute('aria-pressed', 'true');

const downloadPromise = page.waitForEvent('download');
await page.getByRole('button', { name: 'Save .JSON' }).click();
await page.getByRole('button', { name: 'Save class work' }).click();
const download = await downloadPromise;
const fs = await import('node:fs/promises');
const saved = JSON.parse(await fs.readFile((await download.path())!, 'utf8'));
Expand Down Expand Up @@ -370,7 +370,7 @@ test.describe('worksheet UI', () => {
await expect(page.getByTitle('Remove background worksheet from this board')).toBeVisible();

const downloadPromise = page.waitForEvent('download');
await page.getByRole('button', { name: 'Save .JSON' }).click();
await page.getByRole('button', { name: 'Save class work' }).click();
const download = await downloadPromise;
const fs = await import('node:fs/promises');
const saved = JSON.parse(await fs.readFile((await download.path())!, 'utf8'));
Expand Down
48 changes: 40 additions & 8 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1426,6 +1426,43 @@ export default function App() {
performLobbyJoin(targetRoomId, trimmed, cleanPin);
};

/**
* Lobby "New Room": make the room typed in the Room Code box (a random unused code when it's empty) and join it.
* When a room with that code already exists, the same "room already exists" choice as Join comes up, so a
* "new" room never quietly lands you in someone else's.
*/
const handleLobbyNewRoom = async () => {
if (!socket || isCheckingRoom) return;
const trimmed = userName.trim();
if (!trimmed) {
setKickNotice('Type your name first, then press New Room.');
displayNameInputRef.current?.focus();
return;
}
const cleanPin = initialTeacherPin.trim();
if (cleanPin && cleanPin.length < MIN_TEACHER_PIN_LENGTH) {
setKickNotice(`Teacher PIN must be at least ${MIN_TEACHER_PIN_LENGTH} characters.`);
return;
}
const typed = roomId.replace(/^-|-$/g, '').trim();
setIsCheckingRoom(true);
try {
if (!typed) {
performLobbyJoin(await generateUnusedRoomCode(), trimmed, cleanPin);
return;
}
const target = normalizeRoomCode(typed);
const availability = await checkRoomAvailability(target);
if (availability?.exists) {
setPendingRoomPrompt({ source: 'lobby', availability, userName: trimmed, teacherPin: cleanPin });
return;
}
performLobbyJoin(target, trimmed, cleanPin);
} finally {
setIsCheckingRoom(false);
}
};

const handleCancelRoomPrompt = useCallback(() => {
if (!isCheckingRoom) {
setPendingRoomPrompt(null);
Expand Down Expand Up @@ -2018,14 +2055,9 @@ export default function App() {
<button
type="button"
disabled={isCheckingRoom}
onClick={() => {
setKickNotice(null);
setHasEditedLobbyRoom(true);
setRoomId('');
roomCodeInputRef.current?.focus();
}}
onClick={handleLobbyNewRoom}
className="flex items-center gap-1 px-2.5 py-1.5 rounded-[2px] border oh-btn text-brand-700 text-xs font-medium whitespace-nowrap cursor-pointer disabled:opacity-50 transition-colors shrink-0"
title="Type a custom room code"
title="Make a new room with the code you typed (a random one if the box is empty) and go in"
>
<PlusCircle size={13} />
<span>New Room</span>
Expand All @@ -2035,7 +2067,7 @@ export default function App() {
disabled={isCheckingRoom}
onClick={handleCreateNewRoom}
className="flex items-center gap-1 px-2.5 py-1.5 rounded-[2px] border oh-btn text-slate-700 text-xs font-medium whitespace-nowrap cursor-pointer disabled:opacity-50 transition-colors shrink-0"
title="Generate a random unused room code"
title="Fill the box with a random unused room code"
>
<Shuffle size={12} />
<span>Random</span>
Expand Down
8 changes: 4 additions & 4 deletions src/components/Canvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4400,10 +4400,10 @@ export default function Canvas({
type="button"
onClick={handleExportJSON}
className="flex items-center gap-1.5 px-2 py-1 text-xs font-medium oh-btn border text-slate-700 rounded-[2px] transition-colors whitespace-nowrap shrink-0 cursor-pointer"
title="Save room drawings, breakout boards, worksheet, and chat log as a portable .json snapshot"
title="Save everything in this room as a .json file: every student's board, the worksheets and the chat log. Open it later with Open class work."
>
<FileJson size={14} />
<span>Save .JSON</span>
<span>Save class work</span>
</button>

<button
Expand Down Expand Up @@ -5402,10 +5402,10 @@ export default function Canvas({
type="button"
onClick={() => fileInputRef.current?.click()}
className="flex items-center gap-1.5 px-3 py-1 rounded-[2px] border oh-btn text-xs font-medium text-slate-800 transition-colors whitespace-nowrap shrink-0 cursor-pointer"
title="Restore or merge a previously saved .json room snapshot"
title="Open a .json file made with Save class work: every student's board, the worksheets and the chat log"
>
<Upload size={13} />
<span>Import .JSON</span>
<span>Open class work</span>
</button>

{onTeacherLessonRequest && (
Expand Down
2 changes: 1 addition & 1 deletion src/components/CanvasModals.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1705,7 +1705,7 @@ export function RestoreSnapshotModal({
<div className="oh-panel-header flex items-start justify-between gap-4 px-5 py-3.5 border-b border-[#CBD5E1]">
<div>
<h3 className="font-display text-lg font-bold text-slate-900">
Restore Room Snapshot (.JSON)
Open Class Work (.json)
</h3>
<p className="text-xs text-slate-500 mt-0.5">
File: <span className="font-mono text-slate-700">{pendingSnapshot.fileName}</span>
Expand Down
5 changes: 3 additions & 2 deletions src/components/LessonPackModals.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
pickDriveFile,
pickDriveFolder,
saveJsonToDrive,
LESSON_MIME,
type DriveFolder,
} from '../lib/googleDrive';

Expand Down Expand Up @@ -218,7 +219,7 @@ export function SaveLessonModal({
try {
await getAccessToken(); // first, inside the click, so the sign-in popup isn't blocked
// Kept apart from this room's own Drive save, so saving a lesson never replaces the room file.
const saved = await saveJsonToDrive(`lesson:${roomId}`, build.fileName, folder, build.json);
const saved = await saveJsonToDrive(`lesson:${roomId}`, build.fileName, folder, build.json, LESSON_MIME);
setDriveMessage({ text: `Saved ${saved.fileName} to ${saved.folder.name}.`, isError: false });
} catch (err) {
setDriveMessage({ text: driveError(err, 'Could not save to Google Drive.'), isError: true });
Expand Down Expand Up @@ -679,7 +680,7 @@ export function LoadLessonModal({
<div className="pl-6 text-amber-800">
The main board's ink and worksheet will be replaced. Prepared rounds will be replaced.{' '}
<button type="button" onClick={onSaveRoomFirst} className="underline font-semibold cursor-pointer">
Save .JSON first
Save class work first
</button>
</div>
)}
Expand Down
32 changes: 21 additions & 11 deletions src/lib/googleDrive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ export const PPT_MIME = 'application/vnd.ms-powerpoint';
export const PDF_MIME = 'application/pdf';
export const OCTET_STREAM_MIME = 'application/octet-stream';
export const JSON_MIME = 'application/json';
/**
* Lessons saved to Drive get their own type, so the lesson picker can list only lessons: the Picker filters by type,
* not by file name, and room saves are application/json too. Lessons saved before this are application/json.
*/
export const LESSON_MIME = 'application/vnd.allaboard.lesson+json';
export const FOLDER_MIME = 'application/vnd.google-apps.folder';
export const MAX_PPTX_BYTES = 100 * 1024 * 1024;

Expand Down Expand Up @@ -505,8 +510,9 @@ async function openPicker(
/**
* Worksheet picker: Slides | PDFs | Browse Drive tabs.
* Snapshot picker: My room saves (only my .json files) | Browse Drive (starting in the last save folder).
* Lesson picker: My saved files | Browse Drive. Browse also allows application/octet-stream, because a `.allaboard`
* file someone uploaded to Drive by hand may carry that type. Still `drive.file`: the Picker grants per-file access.
* Lesson picker: My lessons (only files saved as lessons, LESSON_MIME) | Browse Drive. Browse also lists
* application/json (lessons saved before LESSON_MIME existed) and application/octet-stream (a `.allaboard` file someone
* uploaded to Drive by hand). Still `drive.file`: the Picker grants per-file access.
*/
export async function pickDriveFile(kind: 'worksheet' | 'snapshot' | 'lesson'): Promise<PickedDriveDoc | null> {
const accessToken = await getAccessToken();
Expand All @@ -531,13 +537,15 @@ export async function pickDriveFile(kind: 'worksheet' | 'snapshot' | 'lesson'):
if (!cachedAccount) await getDriveAccount();
const lastFolder = getLastDriveFolder();
views = [
makeView(pickerNs, 'DOCS', 'My saved files', (v) => {
v.setIncludeFolders(false).setSelectFolderEnabled(false).setMimeTypes(JSON_MIME);
makeView(pickerNs, 'DOCS', 'My lessons', (v) => {
v.setIncludeFolders(false).setSelectFolderEnabled(false).setMimeTypes(LESSON_MIME);
tryCall(v, 'setOwnedByMe', true);
if (listMode) tryCall(v, 'setMode', listMode);
}),
makeView(pickerNs, 'DOCS', 'Browse Drive', (v) => {
v.setIncludeFolders(true).setSelectFolderEnabled(false).setMimeTypes(`${JSON_MIME},${OCTET_STREAM_MIME}`);
v.setIncludeFolders(true)
.setSelectFolderEnabled(false)
.setMimeTypes(`${LESSON_MIME},${JSON_MIME},${OCTET_STREAM_MIME}`);
if (lastFolder.id) tryCall(v, 'setParent', lastFolder.id);
if (listMode) tryCall(v, 'setMode', listMode);
}),
Expand Down Expand Up @@ -814,15 +822,17 @@ export async function downloadDriveFile(
}

/**
* Saves a room snapshot to Drive as `fileName` inside `folder`.
* Saves a room snapshot (or, with LESSON_MIME, a lesson) to Drive as `fileName` inside `folder`.
* If that's the same name and folder as this room's last save, the file is updated in place;
* otherwise a new file is created. Remembers the result for next time.
* The type is set on updates too, so re-saving an older lesson makes it show under "My lessons".
*/
export async function saveJsonToDrive(
roomId: string,
fileName: string,
folder: DriveFolder,
json: string
json: string,
mimeType: string = JSON_MIME
): Promise<DriveSaveRecord> {
if (!cachedAccount) await getDriveAccount();
const last = getRoomDriveSave(roomId);
Expand All @@ -834,13 +844,13 @@ export async function saveJsonToDrive(
: 'https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable';
const method = fileId ? 'PATCH' : 'POST';
const metadata: Record<string, unknown> = fileId
? { name: fileName }
: { name: fileName, mimeType: JSON_MIME, ...(folder.id ? { parents: [folder.id] } : {}) };
? { name: fileName, ...(mimeType !== JSON_MIME ? { mimeType } : {}) }
: { name: fileName, mimeType, ...(folder.id ? { parents: [folder.id] } : {}) };
const res = await driveFetch(url, {
method,
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'X-Upload-Content-Type': JSON_MIME,
'X-Upload-Content-Type': mimeType,
},
body: JSON.stringify(metadata),
});
Expand All @@ -866,7 +876,7 @@ export async function saveJsonToDrive(

const putRes = await driveFetch(uploadUrl, {
method: 'PUT',
headers: { 'Content-Type': JSON_MIME },
headers: { 'Content-Type': mimeType },
body: json,
});
const saved = await putRes.json();
Expand Down
2 changes: 1 addition & 1 deletion src/lib/lessonPack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ export function validateLesson(raw: unknown): { lesson: LessonPack | null; error
if (!isObject(raw)) return { lesson: null, error: "This isn't an AllAboard lesson file." };
if (raw.kind !== LESSON_KIND) {
if (raw.kind === undefined && (raw.version === 1 || raw.version === 2) && 'elements' in raw) {
return { lesson: null, error: 'This is a room save. Use Import .JSON instead.' };
return { lesson: null, error: 'This is a class work save, not a lesson. Use Open class work instead.' };
}
return { lesson: null, error: "This isn't an AllAboard lesson file." };
}
Expand Down
Loading
Loading