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
41 changes: 41 additions & 0 deletions src/app/join/draft.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/* Unsent answers, kept in sessionStorage so a refresh does not lose them. They go when the tab closes or the form is sent. */

const KEY = 'tes-join-draft';
/** The file cannot be refilled by the browser, the trap is for bots, and consent is given fresh. */
const SKIP = new Set(['resume', 'website', 'consent']);

export type Draft = Record<string, string>;

export function readDraft(): Draft | null {
try {
const parsed: unknown = JSON.parse(sessionStorage.getItem(KEY) ?? 'null');
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
const entries = Object.entries(parsed).filter((entry): entry is [string, string] => typeof entry[1] === 'string' && !SKIP.has(entry[0]));
return entries.length ? Object.fromEntries(entries) : null;
} catch {
return null;
}
}

/** Stored in the shape the server returns, with checkbox picks one per line. */
export function saveDraft(form: HTMLFormElement) {
const data = new FormData(form);
const draft: Draft = {};
for (const name of new Set(data.keys())) {
if (SKIP.has(name)) continue;
draft[name] = data.getAll(name).filter((value) => typeof value === 'string').join('\n');
}
try {
sessionStorage.setItem(KEY, JSON.stringify(draft));
} catch {
// Storage blocked or full: the form still works, it just is not kept.
}
}

export function clearDraft() {
try {
sessionStorage.removeItem(KEY);
} catch {
// Nothing was stored.
}
}
18 changes: 14 additions & 4 deletions src/app/join/join-form.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
'use client';

import { useActionState, useEffect, useRef, useState, type ReactNode } from 'react';
import { useActionState, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import Link from 'next/link';
import { useFormStatus } from 'react-dom';
import { ArrowRight, Check, FileText } from 'lucide-react';
import { initialFormState, type FormState } from '@/lib/admin/form-state';
import { ANSWER_MAX, ANSWER_MIN, COMMITMENTS, MAX_DOMAINS, YEARS, domainQuestion, domainsFor, rolesFor } from '@/lib/recruitment/options';
import { IMPORTANCE_LABELS, type Importance } from '@/lib/recruitment/rubric';
import { submitApplication } from './actions';
import { clearDraft, readDraft, saveDraft, type Draft } from './draft';
import { CommitmentGlyph, JoinSidebar, SectionHeading, Signature } from './form-art';
import { DomainPicker, RolePicker } from './pickers';

Expand Down Expand Up @@ -98,7 +99,14 @@ function SubmitButton() {
}

export function JoinForm({ departments, importance }: Props) {
const [state, formAction] = useActionState(submitApplication, initialFormState);
const [result, formAction] = useActionState(submitApplication, initialFormState);
// Undefined until read after hydration, so the server and first client render match.
const [draft, setDraft] = useState<Draft | null>();
// eslint-disable-next-line react-hooks/set-state-in-effect -- sessionStorage only exists in the browser.
useEffect(() => setDraft(readDraft()), []);
// A returned form has the latest answers; before the first attempt, a saved draft fills it.
const state = useMemo(() => (!result.values && draft ? { ...result, values: draft } : result), [result, draft]);
useEffect(() => { if (result.status === 'saved') clearDraft(); }, [result.status]);
const formRef = useRef<HTMLFormElement>(null);
const [filled, setFilled] = useState({ done: 0, total: REQUIRED.length, sections: SECTIONS.map(() => false) });
const [resumeName, setResumeName] = useState<string | null>(null);
Expand Down Expand Up @@ -149,9 +157,11 @@ export function JoinForm({ departments, importance }: Props) {
total: required.length,
sections: SECTIONS.map((names) => names.filter((name) => required.includes(name)).every(answered)),
});
// Not before the draft is read, or the empty form would overwrite it.
if (draft !== undefined) saveDraft(form);
};
// Runs after the domain question appears or goes, so the count includes it.
useEffect(measure, [state, pickedRoles, year, otherClubs, departments]);
// Runs after the domain question appears or goes, so the count and the draft include it.
useEffect(measure, [state, draft, pickedRoles, pickedDomains, year, otherClubs, departments]);

if (state.status === 'saved') {
return (
Expand Down
15 changes: 15 additions & 0 deletions tests/e2e/admin-applications.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,19 @@ async function fillApplication(page: Page) {
await page.getByLabel(/I confirm these answers are my own/).check();
}

test('unsent answers survive a refresh, but consent is asked again', async ({ page }) => {
await page.goto('/join');
await fillApplication(page);
await page.reload();
await expect(page.getByLabel('Name')).toHaveValue(applicant);
await expect(page.getByLabel('Year of study')).toHaveValue('2');
await expect(page.getByLabel('How would you like to contribute to TES?')).toHaveValue(/keyboard shortcuts/);
await expect(page.getByRole('checkbox', { name: /^Design/ })).toBeChecked();
await expect(page.getByRole('checkbox', { name: 'Web Development' })).toBeChecked();
await expect(page.getByLabel('Which clubs, and what do you do there?')).toHaveValue('Robotics club, events team');
await expect(page.getByLabel(/I confirm these answers are my own/)).not.toBeChecked();
});

test('an applicant sees what is missing, then sends the form once', async ({ page }, testInfo) => {
test.skip(testInfo.project.name !== 'desktop', 'Writes shared data; run once.');
await page.goto('/join');
Expand Down Expand Up @@ -70,7 +83,9 @@ test('an applicant sees what is missing, then sends the form once', async ({ pag
await expect(page.getByRole('heading', { level: 1 })).toHaveText('Thank you, Playwright.');
await page.screenshot({ path: 'test-results/join-sent.png' });

// Sending clears the saved answers.
await page.goto('/join');
await expect(page.getByLabel('Name')).toHaveValue('');
await fillApplication(page);
await page.getByRole('button', { name: 'Send application' }).click();
await expect(page.locator('#rollNumber-error')).toContainText('We already have an application from this roll number');
Expand Down
Loading