From 114b7e8e43687876beedb67e50fa20236f6ca68e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Mon, 16 Nov 2026 15:21:42 +0100 Subject: [PATCH 1/5] fix(a11y): make ingredient and step reordering keyboard accessible Rows could only be reordered by dragging (fails WCAG 2.2 SC 2.5.7) and used array indexes as React keys, so DOM state could stay behind when rows moved. Each row now has a stable key, and Move up / Move down buttons that keep focus on the moved row (or its other button at the first/last place) and announce the new position in a live region. Drag-and-drop still works. On phones the row buttons move to their own line under the fields. The test named 'button-based reordering' (which actually dragged) is renamed and a keyboard test is added. Closes #104 --- .../src/features/recipes/RecipeCreatePage.css | 15 +- .../recipes/RecipeCreatePage.test.tsx | 47 +++++- .../src/features/recipes/RecipeCreatePage.tsx | 138 ++++++++++++++++-- apps/web/src/icons/navigation.tsx | 8 + 4 files changed, 190 insertions(+), 18 deletions(-) diff --git a/apps/web/src/features/recipes/RecipeCreatePage.css b/apps/web/src/features/recipes/RecipeCreatePage.css index 416ee0e..72cd4af 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.css +++ b/apps/web/src/features/recipes/RecipeCreatePage.css @@ -336,11 +336,13 @@ background: var(--color-surface-selected); } + /* Move up / move down / remove buttons at the end of each row. */ .recipe-create-page__delete-control { display: flex; align-items: center; justify-content: center; - width: var(--target-size-min); + gap: var(--space-1); + min-width: var(--target-size-min); height: var(--target-size-min); } @@ -381,6 +383,17 @@ padding-block: var(--space-8) var(--space-12); } + /* Move/remove buttons get their own line under the fields, so the + fields keep their full width on phones. */ + .recipe-create-page__repeatable-row { + grid-template-columns: auto minmax(0, 1fr); + } + + .recipe-create-page__repeatable-row > .recipe-create-page__delete-control { + grid-column: 2; + justify-self: end; + } + .recipe-create-page__content { margin-top: var(--space-6); } diff --git a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx index b05c11c..4415442 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx @@ -105,7 +105,7 @@ describe('RecipeCreatePage', () => { expect(screen.queryByLabelText('Step 2')).not.toBeInTheDocument(); }); - it('supports structured ingredients and button-based reordering', async () => { + it('supports structured ingredients and reordering by dragging the handle', async () => { const user = userEvent.setup(); mount(); @@ -346,3 +346,48 @@ it('does not fetch or reset the new recipe form after list invalidation', () => expect(title).toHaveValue('New draft'); expect(fetch).not.toHaveBeenCalled(); }); +it('reorders ingredients and steps with the keyboard, keeping focus and announcing the position', async () => { + const user = userEvent.setup(); + mount(); + await user.type(screen.getByLabelText('Ingredient 1'), 'Flour'); + await user.click(screen.getByRole('button', { name: 'Add ingredient' })); + await user.type(screen.getByLabelText('Ingredient 2'), 'Sugar'); + await user.click(screen.getByRole('button', { name: 'Add ingredient' })); + await user.type(screen.getByLabelText('Ingredient 3'), 'Salt'); + + // The first row cannot move up; the last cannot move down. + expect( + screen.getByRole('button', { name: 'Move ingredient 1 up' }), + ).toBeDisabled(); + expect( + screen.getByRole('button', { name: 'Move ingredient 3 down' }), + ).toBeDisabled(); + + screen.getByRole('button', { name: 'Move ingredient 1 down' }).focus(); + await user.keyboard('{Enter}'); + expect(screen.getByLabelText('Ingredient 1')).toHaveValue('Sugar'); + expect(screen.getByLabelText('Ingredient 2')).toHaveValue('Flour'); + // Focus follows the moved row, so pressing again keeps moving Flour. + expect( + screen.getByRole('button', { name: 'Move ingredient 2 down' }), + ).toHaveFocus(); + expect(screen.getByRole('status')).toHaveTextContent( + 'Ingredient moved to position 2 of 3.', + ); + await user.keyboard('{Enter}'); + expect(screen.getByLabelText('Ingredient 3')).toHaveValue('Flour'); + // At the last place the down button is disabled, so focus moves to up. + expect( + screen.getByRole('button', { name: 'Move ingredient 3 up' }), + ).toHaveFocus(); + + await user.type(screen.getByLabelText('Step 1'), 'Mix'); + await user.click(screen.getByRole('button', { name: 'Add step' })); + await user.type(screen.getByLabelText('Step 2'), 'Bake'); + await user.click(screen.getByRole('button', { name: 'Move step 2 up' })); + expect(screen.getByLabelText('Step 1')).toHaveValue('Bake'); + expect(screen.getByLabelText('Step 2')).toHaveValue('Mix'); + expect(screen.getByRole('status')).toHaveTextContent( + 'Step moved to position 1 of 2.', + ); +}); diff --git a/apps/web/src/features/recipes/RecipeCreatePage.tsx b/apps/web/src/features/recipes/RecipeCreatePage.tsx index 625399f..5995106 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.tsx @@ -8,6 +8,7 @@ import { } from 'react'; import { DeleteIcon, DragHandleIcon } from '../../icons/actions'; +import { ChevronDownIcon, ChevronUpIcon } from '../../icons/navigation'; import Button from '../../components/ui/Button/Button'; import Field from '../../components/ui/Field/Field'; import FeedbackMessage from '../../components/ui/FeedbackMessage/FeedbackMessage'; @@ -54,13 +55,27 @@ type IngredientFieldErrors = { type FormStatus = 'idle' | 'draft'; +/* + * Rows carry a stable key so React keeps each row's DOM (focus, typed text) + * with its data when rows are moved or removed; array indexes would not. + */ type IngredientDraft = { + key: string; name: string; amount: string; unit: string; note?: string; }; +type InstructionDraft = { key: string; text: string }; +type RowType = 'ingredient' | 'instruction'; + +let lastRowKey = 0; +function newRowKey() { + lastRowKey += 1; + return `row-${lastRowKey}`; +} + function moveItem(items: T[], fromIndex: number, toIndex: number) { const nextItems = [...items]; const [movedItem] = nextItems.splice(fromIndex, 1); @@ -92,14 +107,26 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { ); const [difficulty, setDifficulty] = useState(recipe?.difficulty ?? ''); const [ingredients, setIngredients] = useState( - recipe?.ingredients.map((item) => ({ - ...item, - amount: String(item.amount), - })) ?? [{ name: '', amount: '', unit: 'g' }], + () => + recipe?.ingredients.map((item) => ({ + key: newRowKey(), + name: item.name, + amount: String(item.amount), + unit: item.unit, + note: item.note ?? undefined, + })) ?? [{ key: newRowKey(), name: '', amount: '', unit: 'g' }], ); - const [instructions, setInstructions] = useState( - recipe?.instructions.map((item) => item.text) ?? [''], + const [instructions, setInstructions] = useState( + () => + recipe?.instructions.map((item) => ({ + key: newRowKey(), + text: item.text, + })) ?? [{ key: newRowKey(), text: '' }], ); + // Announced after a row is moved with the keyboard buttons. + const [moveAnnouncement, setMoveAnnouncement] = useState(''); + // Id of the control to focus after the next render (see moveRow). + const pendingFocusId = useRef(null); const [draggingRow, setDraggingRow] = useState< { type: 'ingredient' | 'instruction'; index: number } | undefined >(); @@ -121,7 +148,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { function addIngredient() { setIngredients((currentIngredients) => [ ...currentIngredients, - { name: '', amount: '', unit: 'g' }, + { key: newRowKey(), name: '', amount: '', unit: 'g' }, ]); } @@ -173,7 +200,10 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { ); function addInstruction() { - setInstructions((currentInstructions) => [...currentInstructions, '']); + setInstructions((currentInstructions) => [ + ...currentInstructions, + { key: newRowKey(), text: '' }, + ]); } function removeInstruction(index: number) { @@ -187,7 +217,9 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { function updateInstruction(index: number, value: string) { setInstructions((currentInstructions) => currentInstructions.map((instruction, instructionIndex) => - instructionIndex === index ? value : instruction, + instructionIndex === index + ? { ...instruction, text: value } + : instruction, ), ); setErrors((currentErrors) => ({ @@ -287,6 +319,37 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { setDraggingRow({ type, index }); } + /* + * Keyboard alternative to dragging (WCAG 2.5.7): moves a row one place, + * keeps focus on the moved row's button (or its other move button when it + * reaches the first/last place) and announces the new position. + */ + function moveRow(type: RowType, index: number, direction: -1 | 1) { + const rows = type === 'ingredient' ? ingredients : instructions; + const target = index + direction; + if (target < 0 || target >= rows.length) return; + if (type === 'ingredient') reorderIngredients(index, target); + else reorderInstructions(index, target); + const atEdge = target === 0 || target === rows.length - 1; + const button = atEdge + ? target === 0 + ? 'down' + : 'up' + : direction === -1 + ? 'up' + : 'down'; + pendingFocusId.current = `${type}-${rows[index]!.key}-move-${button}`; + setMoveAnnouncement( + `${type === 'ingredient' ? 'Ingredient' : 'Step'} moved to position ${target + 1} of ${rows.length}.`, + ); + } + + useEffect(() => { + if (!pendingFocusId.current) return; + document.getElementById(pendingFocusId.current)?.focus(); + pendingFocusId.current = null; + }); + function validateForm(): RecipeErrors { const nextErrors: RecipeErrors = {}; @@ -345,10 +408,10 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { ) nextErrors.ingredients = ingredientErrors; - const instructionErrors = instructions.map((instruction) => - !instruction.trim() + const instructionErrors = instructions.map(({ text }) => + !text.trim() ? 'Add an instruction.' - : instruction.trim().length > 5000 + : text.trim().length > 5000 ? 'Keep instructions under 5000 characters.' : '', ); @@ -420,7 +483,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { unit: item.unit, note: item.note, })), - instructions: instructions.map((text) => text.trim()), + instructions: instructions.map(({ text }) => text.trim()), tags: tags .split(',') .map((tag) => tag.trim()) @@ -460,6 +523,9 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { onSubmit={handleSubmit} noValidate > +

+ {moveAnnouncement} +

@@ -755,6 +821,26 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
+ moveRow('ingredient', index, -1)} + disabled={index === 0} + /> + moveRow('ingredient', index, 1)} + disabled={index === ingredients.length - 1} + /> @@ -814,7 +900,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { label={`Step ${index + 1}`} id={`instruction-${index}`} className="recipe-create-page__step-textarea" - value={instruction} + value={instruction.text} error={errors.instructions?.[index]} onChange={(event) => updateInstruction(index, event.target.value) @@ -823,6 +909,26 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { rows={2} />
+ moveRow('instruction', index, -1)} + disabled={index === 0} + /> + moveRow('instruction', index, 1)} + disabled={index === instructions.length - 1} + /> + + + ); +} + export function ChevronDownIcon(props: IconProps) { return ( From 2c234a4246463151f36850bb2c2d49388ff9473b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Mon, 16 Nov 2026 18:54:08 +0100 Subject: [PATCH 2/5] feat(recipe): persist recipe drafts across navigation and reload "Save draft" only showed a message; the draft was lost on navigation or reload. Drafts are now stored in localStorage per user and recipe (lib/recipeDrafts.ts). Opening the form offers to restore or discard a saved draft, warns when the recipe changed after the draft was saved, leaves out an uploaded image that no longer loads, and clears the draft after a successful save. Signing out removes the user's drafts. Closes #105 --- README.md | 2 +- .../src/features/recipes/RecipeCreatePage.css | 7 + .../recipes/RecipeCreatePage.test.tsx | 73 +++++++++ .../src/features/recipes/RecipeCreatePage.tsx | 150 +++++++++++++++++- apps/web/src/lib/recipeDrafts.test.ts | 60 +++++++ apps/web/src/lib/recipeDrafts.ts | 103 ++++++++++++ apps/web/src/store.test.ts | 16 ++ apps/web/src/store.ts | 6 +- 8 files changed, 407 insertions(+), 10 deletions(-) create mode 100644 apps/web/src/lib/recipeDrafts.test.ts create mode 100644 apps/web/src/lib/recipeDrafts.ts diff --git a/README.md b/README.md index 1441d45..7a5a765 100644 --- a/README.md +++ b/README.md @@ -397,7 +397,7 @@ KI-verktøy får ikke ekte passord, tokens, personopplysninger eller andre hemme - Søk dekker tittel og beskrivelse; ingrediens- og tagsøk er videre arbeid. - Trending er ikke implementert. Høyest vurdering bruker gjennomsnittet uten vekting etter antall stemmer. -- Utkast beholdes bare i skjemaet og overlever ikke navigering eller oppdatering. +- Utkast lagres bare i nettleseren (localStorage) per bruker og oppskrift, ikke på serveren, og følger derfor ikke brukeren til en annen enhet. De slettes ved utlogging. - Seed inneholder 51 demooppskrifter og demonstrerer ikke ytelse med store datamengder. - Bildeoperasjoner bruker en global lås for korrekt koordinering. Dette begrenser samtidige skriveoperasjoner. - Bildekvoter har faste grenser. Registrering har IP-begrensning, men flere kontoer kan fortsatt omgå brukerkvotene. Refererte bilder teller mot totalgrensen og slettes ikke av cleanup. diff --git a/apps/web/src/features/recipes/RecipeCreatePage.css b/apps/web/src/features/recipes/RecipeCreatePage.css index 72cd4af..9e6c650 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.css +++ b/apps/web/src/features/recipes/RecipeCreatePage.css @@ -336,6 +336,13 @@ background: var(--color-surface-selected); } + .recipe-create-page__draft-actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-2); + margin-top: var(--space-2); + } + /* Move up / move down / remove buttons at the end of each row. */ .recipe-create-page__delete-control { display: flex; diff --git a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx index 4415442..b62e213 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx @@ -391,3 +391,76 @@ it('reorders ingredients and steps with the keyboard, keeping focus and announci 'Step moved to position 1 of 2.', ); }); +describe('recipe drafts', () => { + beforeEach(() => localStorage.clear()); + + it('saves a draft that survives a reload and can be restored or discarded', async () => { + const user = userEvent.setup(); + const first = mount(); + await user.type(screen.getByLabelText(/Recipe title/i), 'Draft soup'); + await user.type(screen.getByLabelText('Step 1'), 'Simmer'); + await user.click(screen.getByRole('button', { name: 'Save draft' })); + expect(screen.getByText('Draft saved')).toBeInTheDocument(); + first.unmount(); + + // A fresh form (as after navigation or reload) offers the draft. + const second = mount(); + expect(screen.getByText('Saved draft found')).toBeInTheDocument(); + expect(screen.getByLabelText(/Recipe title/i)).toHaveValue(''); + await user.click(screen.getByRole('button', { name: 'Restore draft' })); + expect(screen.getByLabelText(/Recipe title/i)).toHaveValue('Draft soup'); + expect(screen.getByLabelText('Step 1')).toHaveValue('Simmer'); + second.unmount(); + + mount(); + await user.click(screen.getByRole('button', { name: 'Discard draft' })); + expect(screen.queryByText('Saved draft found')).not.toBeInTheDocument(); + expect(localStorage.length).toBe(0); + }); + + it('marks a draft of an existing recipe as outdated after the recipe changed', async () => { + localStorage.setItem( + `recipe-platform:draft:${apiUser.id}:${apiRecipe.id}`, + JSON.stringify({ + version: 1, + savedAt: '2026-10-01T10:00:00Z', + baseUpdatedAt: '2026-01-01T00:00:00Z', + fields: { + title: 'Old title', + description: '', + category: 'soup', + difficulty: 'easy', + visibility: 'public', + prepTime: '1', + cookingTime: '1', + servings: '1', + tags: '', + imageUrl: null, + ingredients: [{ name: 'Water', amount: '1', unit: 'l' }], + instructions: ['Boil'], + }, + }), + ); + mockRecipeFetch(() => ({ + data: { recipe: { ...apiRecipe, isCreatedByCurrentUser: true } }, + })); + mount('/recipes/' + apiRecipe.id + '/edit'); + expect(await screen.findByText('Outdated draft found')).toBeInTheDocument(); + }); + + it('clears the draft after the recipe is saved', async () => { + mockRecipeFetch((operation) => + operation === 'UpdateRecipe' + ? { data: { updateRecipe: apiRecipe } } + : { data: { recipe: { ...apiRecipe, isCreatedByCurrentUser: true } } }, + ); + const user = userEvent.setup(); + mount('/recipes/' + apiRecipe.id + '/edit'); + await screen.findByRole('heading', { name: 'Edit Recipe' }); + await user.click(screen.getByRole('button', { name: 'Save draft' })); + expect(localStorage.length).toBe(1); + await user.click(screen.getByRole('button', { name: 'Save changes' })); + await screen.findByRole('heading', { name: 'Saved recipe destination' }); + expect(localStorage.length).toBe(0); + }); +}); diff --git a/apps/web/src/features/recipes/RecipeCreatePage.tsx b/apps/web/src/features/recipes/RecipeCreatePage.tsx index 5995106..639478a 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.tsx @@ -30,6 +30,9 @@ import { useRecipeQuery } from './useRecipeQuery'; import RecipeQueryStatus from './RecipeQueryStatus'; import LinkButton from '../../components/ui/LinkButton/LinkButton'; import RecipeImageField from './RecipeImageField'; +import { useAppStore } from '../../store'; +import { recipeImageUrl } from '../../lib/recipeImageUrl'; +import { clearDraft, loadDraft, saveDraft } from '../../lib/recipeDrafts'; import './RecipeCreatePage.css'; @@ -53,7 +56,7 @@ type IngredientFieldErrors = { unit?: string; }; -type FormStatus = 'idle' | 'draft'; +type FormStatus = 'idle' | 'draft' | 'draft-failed'; /* * Rows carry a stable key so React keeps each row's DOM (focus, typed text) @@ -76,6 +79,13 @@ function newRowKey() { return `row-${lastRowKey}`; } +function formatDraftTime(savedAt: string) { + return new Date(savedAt).toLocaleString('en-GB', { + dateStyle: 'medium', + timeStyle: 'short', + }); +} + function moveItem(items: T[], fromIndex: number, toIndex: number) { const nextItems = [...items]; const [movedItem] = nextItems.splice(fromIndex, 1); @@ -127,6 +137,95 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { const [moveAnnouncement, setMoveAnnouncement] = useState(''); // Id of the control to focus after the next render (see moveRow). const pendingFocusId = useRef(null); + + /* + * Drafts are saved in this browser per user and recipe ("new" for a new + * recipe), see lib/recipeDrafts.ts. A saved draft is offered when the + * form opens; it is outdated if the recipe was changed after the draft. + */ + const userId = useAppStore((state) => state.currentUser?.id); + const draftRecipeId = recipe?.id ?? 'new'; + const [offeredDraft, setOfferedDraft] = useState(() => + userId ? loadDraft(userId, draftRecipeId) : null, + ); + const [draftNotice, setDraftNotice] = useState(''); + const draftIsOutdated = Boolean( + recipe && offeredDraft && offeredDraft.baseUpdatedAt !== recipe.updatedAt, + ); + + function handleSaveDraft() { + if (!userId) return; + const saved = saveDraft(userId, draftRecipeId, { + baseUpdatedAt: recipe?.updatedAt ?? null, + fields: { + title, + description, + category, + difficulty, + visibility, + prepTime, + cookingTime, + servings, + tags, + imageUrl, + ingredients: ingredients.map(({ name, amount, unit, note }) => ({ + name, + amount, + unit, + note, + })), + instructions: instructions.map(({ text }) => text), + }, + }); + setOfferedDraft(null); + setDraftNotice(''); + setStatus(saved ? 'draft' : 'draft-failed'); + } + + function restoreDraft() { + if (!offeredDraft) return; + const { fields } = offeredDraft; + setTitle(fields.title); + setDescription(fields.description); + setCategory(fields.category); + setDifficulty(fields.difficulty); + setVisibility(fields.visibility); + setPrepTime(fields.prepTime); + setCookingTime(fields.cookingTime); + setServings(fields.servings); + setTags(fields.tags); + setIngredients( + fields.ingredients.map((ingredient) => ({ + ...ingredient, + key: newRowKey(), + })), + ); + setInstructions( + fields.instructions.map((text) => ({ key: newRowKey(), text })), + ); + setErrors({}); + setOfferedDraft(null); + setDraftNotice('Draft restored.'); + // Unused uploads are cleaned up after 24 hours, so the draft's image may + // be gone; keep the current image instead of a broken one. + if (!fields.imageUrl) { + setImageUrl(null); + return; + } + const probe = new Image(); + probe.onload = () => setImageUrl(fields.imageUrl); + probe.onerror = () => + setDraftNotice( + 'Draft restored. Its image is no longer available and was left out.', + ); + probe.src = recipeImageUrl(fields.imageUrl); + } + + function discardDraft() { + if (userId) clearDraft(userId, draftRecipeId); + setOfferedDraft(null); + setDraftNotice('Draft discarded.'); + } const [draggingRow, setDraggingRow] = useState< { type: 'ingredient' | 'instruction'; index: number } | undefined >(); @@ -492,6 +591,8 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { cuisine: recipe?.cuisine || null, }; const saved = await writeRecipe(input, recipe?.id); + // The saved recipe replaces the draft. + if (userId) clearDraft(userId, draftRecipeId); navigate('/recipes/' + saved.id, { replace: Boolean(recipe) }); } catch (error) { setSubmitError(recipeErrorMessage(error)); @@ -536,9 +637,46 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { {submitError} )} + {offeredDraft && ( + +

+ {draftIsOutdated + ? `You saved a draft on ${formatDraftTime(offeredDraft.savedAt)}, but the recipe has changed since. Restoring replaces the form with the older draft.` + : `You have a draft saved on ${formatDraftTime(offeredDraft.savedAt)}.`} +

+
+ + +
+
+ )} + {draftNotice && ( + {draftNotice} + )} {status === 'draft' && ( - - Your draft is available in this form until you leave the page. + + Saved in this browser. It will be offered when you open this form + again, also after reloading the page. + + )} + {status === 'draft-failed' && ( + + Your browser did not allow saving the draft. Your changes are + still in the form. )} @@ -954,11 +1092,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
- -
diff --git a/apps/web/src/lib/recipeDrafts.test.ts b/apps/web/src/lib/recipeDrafts.test.ts index 95577b4..1e02435 100644 --- a/apps/web/src/lib/recipeDrafts.test.ts +++ b/apps/web/src/lib/recipeDrafts.test.ts @@ -58,3 +58,62 @@ describe('recipe drafts', () => { expect(localStorage.getItem('recipe-platform:draft:alice:new')).toBeNull(); }); }); + +describe('damaged drafts and other tabs', () => { + const stored = (changes: Record) => + JSON.stringify({ + version: 1, + savedAt: '2026-10-01T10:00:00Z', + baseUpdatedAt: null, + fields, + ...changes, + }); + + it.each([ + ['a non-string title', { fields: { ...fields, title: 5 } }], + ['an unknown visibility', { fields: { ...fields, visibility: 'team' } }], + ['a numeric image', { fields: { ...fields, imageUrl: 3 } }], + ['a null ingredient', { fields: { ...fields, ingredients: [null] } }], + [ + 'an ingredient without a unit', + { fields: { ...fields, ingredients: [{ name: 'Salt', amount: '1' }] } }, + ], + [ + 'a numeric note', + { + fields: { + ...fields, + ingredients: [{ name: 'Salt', amount: '1', unit: 'g', note: 2 }], + }, + }, + ], + ['a non-text step', { fields: { ...fields, instructions: [{}] } }], + ['a missing field', { fields: { ...fields, servings: undefined } }], + ['an invalid save time', { savedAt: 'yesterday' }], + ['an invalid base time', { baseUpdatedAt: 42 }], + ])('drops a draft with %s', (_, changes) => { + localStorage.setItem('recipe-platform:draft:alice:new', stored(changes)); + expect(loadDraft('alice', 'new')).toBeNull(); + expect(localStorage.getItem('recipe-platform:draft:alice:new')).toBeNull(); + }); + + it('keeps a valid draft with an ingredient note', () => { + const withNote = { + ...fields, + ingredients: [{ name: 'Salt', amount: '1', unit: 'g', note: 'flaky' }], + }; + localStorage.setItem( + 'recipe-platform:draft:alice:new', + stored({ fields: withNote }), + ); + expect(loadDraft('alice', 'new')?.fields).toEqual(withNote); + }); + + it('only clears the version of a draft this tab knows about', () => { + localStorage.setItem('recipe-platform:draft:alice:new', stored({})); + expect(clearDraft('alice', 'new', ['2026-09-01T00:00:00Z'])).toBe(false); + expect(loadDraft('alice', 'new')).not.toBeNull(); + expect(clearDraft('alice', 'new', ['2026-10-01T10:00:00Z'])).toBe(true); + expect(loadDraft('alice', 'new')).toBeNull(); + }); +}); diff --git a/apps/web/src/lib/recipeDrafts.ts b/apps/web/src/lib/recipeDrafts.ts index f8d18cc..9407660 100644 --- a/apps/web/src/lib/recipeDrafts.ts +++ b/apps/web/src/lib/recipeDrafts.ts @@ -58,34 +58,93 @@ export function saveDraft( } } +const isString = (value: unknown): value is string => typeof value === 'string'; +const isObject = (value: unknown): value is Record => + typeof value === 'object' && value !== null && !Array.isArray(value); + +/* + * localStorage can hold anything: an older format, a manual edit, another + * app's data. Check every field the form reads, so a damaged draft is + * dropped here instead of breaking the form when it is restored or saved. + */ +function isRecipeDraft(value: unknown): value is RecipeDraft { + if (!isObject(value) || !isObject(value.fields)) return false; + const fields = value.fields; + return ( + value.version === 1 && + isString(value.savedAt) && + !Number.isNaN(Date.parse(value.savedAt)) && + (value.baseUpdatedAt === null || isString(value.baseUpdatedAt)) && + ( + [ + 'title', + 'description', + 'category', + 'difficulty', + 'prepTime', + 'cookingTime', + 'servings', + 'tags', + ] as const + ).every((name) => isString(fields[name])) && + (fields.visibility === 'public' || fields.visibility === 'private') && + (fields.imageUrl === null || isString(fields.imageUrl)) && + Array.isArray(fields.ingredients) && + fields.ingredients.every( + (ingredient) => + isObject(ingredient) && + isString(ingredient.name) && + isString(ingredient.amount) && + isString(ingredient.unit) && + (ingredient.note === undefined || isString(ingredient.note)), + ) && + Array.isArray(fields.instructions) && + fields.instructions.every(isString) + ); +} + export function loadDraft(userId: string, recipeId: string) { try { const raw = localStorage.getItem(key(userId, recipeId)); if (!raw) return null; - const draft = JSON.parse(raw) as Partial; - const fields = draft.fields; - if ( - draft.version !== 1 || - typeof draft.savedAt !== 'string' || - !fields || - !Array.isArray(fields.ingredients) || - !Array.isArray(fields.instructions) - ) { + let draft: unknown; + try { + draft = JSON.parse(raw); + } catch { + draft = null; + } + if (!isRecipeDraft(draft)) { // Unknown or damaged format: drop it rather than break the form. localStorage.removeItem(key(userId, recipeId)); return null; } - return draft as RecipeDraft; + return draft; } catch { return null; } } -export function clearDraft(userId: string, recipeId: string) { +/** + * Removes a draft. With `onlySavedAt`, only a draft saved at one of those + * times is removed: another tab may have saved a newer draft of the same + * recipe since this tab read it, and that one must be kept. Returns whether + * a draft was removed. + */ +export function clearDraft( + userId: string, + recipeId: string, + onlySavedAt?: readonly string[], +) { try { + if (onlySavedAt) { + const stored = loadDraft(userId, recipeId); + if (!stored || !onlySavedAt.includes(stored.savedAt)) return false; + } localStorage.removeItem(key(userId, recipeId)); + return true; } catch { // Storage unavailable: nothing to clear. + return false; } } diff --git a/apps/web/src/store.test.ts b/apps/web/src/store.test.ts index 2b4c62c..a4b00a7 100644 --- a/apps/web/src/store.test.ts +++ b/apps/web/src/store.test.ts @@ -100,4 +100,29 @@ describe('drafts on sign-out', () => { '{}', ); }); + + it('clears the drafts of the user who signed out, even if the user changes meanwhile', async () => { + localStorage.clear(); + localStorage.setItem(`recipe-platform:draft:${user.id}:new`, '{}'); + localStorage.setItem('recipe-platform:draft:next-user:new', '{}'); + useAppStore.setState({ currentUser: user, sessionStatus: 'authenticated' }); + let finishSignOut!: (value: boolean) => void; + vi.mocked(signOutUser).mockReturnValue( + new Promise((resolve) => (finishSignOut = resolve)), + ); + const signingOut = useAppStore.getState().signOut(); + // Another auth change lands while the sign-out request is in flight. + useAppStore.setState({ + currentUser: { ...user, id: 'next-user' }, + sessionStatus: 'authenticated', + }); + finishSignOut(true); + await signingOut; + expect( + localStorage.getItem(`recipe-platform:draft:${user.id}:new`), + ).toBeNull(); + expect(localStorage.getItem('recipe-platform:draft:next-user:new')).toBe( + '{}', + ); + }); }); diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index 4bcc9fa..b72f5a6 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -87,12 +87,14 @@ export const useAppStore = create((set, get) => ({ }, signOut: async () => { + // Read the user before awaiting: by the time sign-out finishes, the + // current user may already be someone else (or nobody). + const userId = get().currentUser?.id; // Do not claim logout succeeded while the server session is still active. await signOutUser(); authVersion += 1; localStorage.removeItem(LEGACY_TOKEN_KEY); // Recipe drafts are personal; do not leave them on a shared computer. - const userId = get().currentUser?.id; if (userId) clearUserDrafts(userId); set({ currentUser: null, sessionStatus: 'anonymous' }); },