diff --git a/src/app/join/draft.ts b/src/app/join/draft.ts new file mode 100644 index 0000000..d9856cc --- /dev/null +++ b/src/app/join/draft.ts @@ -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; + +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. + } +} diff --git a/src/app/join/join-form.tsx b/src/app/join/join-form.tsx index 6ab608a..679b212 100644 --- a/src/app/join/join-form.tsx +++ b/src/app/join/join-form.tsx @@ -1,6 +1,6 @@ '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'; @@ -8,6 +8,7 @@ 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'; @@ -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(); + // 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(null); const [filled, setFilled] = useState({ done: 0, total: REQUIRED.length, sections: SECTIONS.map(() => false) }); const [resumeName, setResumeName] = useState(null); @@ -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 ( diff --git a/tests/e2e/admin-applications.spec.ts b/tests/e2e/admin-applications.spec.ts index 509d33e..0db6fc2 100644 --- a/tests/e2e/admin-applications.spec.ts +++ b/tests/e2e/admin-applications.spec.ts @@ -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'); @@ -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');