From 9cfcef35847593d51b5962e7655616f6af8ac430 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Tue, 17 Nov 2026 16:46:24 +0100 Subject: [PATCH 1/5] fix(recipe): protect recipe edits from conflicts, leaving and sign-out - updateRecipe takes an optional expectedUpdatedAt. The editor sends the version it loaded; if the recipe changed since (another tab or device) the API refuses with CONFLICT under the row lock, and the form keeps the user's changes with an explanation of how to keep them. - Unsaved changes (form differs from how it opened and from the draft in this browser) trigger the browser's prompt on reload/close and, through a data router (createBrowserRouter) and useBlocker, a Leave/Stay dialog for in-app navigation. A successful save navigates away unasked. - Sign-out asks first when it would delete saved drafts or close the editor with unsaved changes, and says which. - Save draft asks before replacing a draft that was offered but not restored or discarded, or that another tab saved meanwhile. - After logging in from /recipes//edit the user returns to that editor (strict UUID pattern, no other paths). Closes #121 --- .../src/features/recipes/recipeRepository.ts | 20 ++- .../src/features/recipes/recipeResolvers.ts | 1 + apps/api/src/generated.ts | 1 + apps/api/src/schema.graphql | 5 +- .../shell/SiteHeader/SiteHeader.test.tsx | 71 ++++++++- .../shell/SiteHeader/SiteHeader.tsx | 49 +++++- .../src/features/auth/authNavigation.test.ts | 18 ++- apps/web/src/features/auth/authNavigation.ts | 12 +- .../recipes/RecipeCreatePage.test.tsx | 146 +++++++++++++++++- .../src/features/recipes/RecipeCreatePage.tsx | 78 +++++++++- .../features/recipes/UnsavedChangesGuard.tsx | 51 ++++++ apps/web/src/features/recipes/recipeApi.ts | 16 +- apps/web/src/lib/recipeDrafts.test.ts | 5 + apps/web/src/lib/recipeDrafts.ts | 13 ++ apps/web/src/lib/unsavedChanges.ts | 8 + apps/web/src/main.tsx | 12 +- contracts/generated.ts | 5 +- contracts/operations.graphql | 8 +- scripts/test-recipe-api.ts | 60 +++++++ 19 files changed, 554 insertions(+), 25 deletions(-) create mode 100644 apps/web/src/features/recipes/UnsavedChangesGuard.tsx create mode 100644 apps/web/src/lib/unsavedChanges.ts diff --git a/apps/api/src/features/recipes/recipeRepository.ts b/apps/api/src/features/recipes/recipeRepository.ts index ffd4316..9acc0c6 100644 --- a/apps/api/src/features/recipes/recipeRepository.ts +++ b/apps/api/src/features/recipes/recipeRepository.ts @@ -192,9 +192,27 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') { return readRequired(client, id, userId); }); }, - async update(id: string, input: RecipeInput, userId: string) { + async update( + id: string, + input: RecipeInput, + userId: string, + expectedUpdatedAt?: string | null, + ) { return transaction(async (client) => { await owned(client, id, userId); + // Optimistic concurrency: compare with updatedAt as the API serves + // it (milliseconds, UTC), under the row lock owned() just took. + if (expectedUpdatedAt) { + const current = await client.query<{ updatedAt: string }>( + `SELECT to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "updatedAt" FROM ${t('recipes')} WHERE id=$1`, + [id], + ); + if (current.rows[0]!.updatedAt !== expectedUpdatedAt) + throw new GraphQLError( + 'This recipe was changed after you opened it.', + { extensions: { code: 'CONFLICT' } }, + ); + } await validateImageReference( client, schema, diff --git a/apps/api/src/features/recipes/recipeResolvers.ts b/apps/api/src/features/recipes/recipeResolvers.ts index 044fcc1..1522c8f 100644 --- a/apps/api/src/features/recipes/recipeResolvers.ts +++ b/apps/api/src/features/recipes/recipeResolvers.ts @@ -58,6 +58,7 @@ export function createRecipeResolvers(repository: RecipeRepository) { recipeId(args.id), validate(recipeInputSchema, args.input), userId, + validate(z.string().max(40).nullish(), args.expectedUpdatedAt), ); }, deleteRecipe: (_parent, args, context) => diff --git a/apps/api/src/generated.ts b/apps/api/src/generated.ts index 9d173b2..dfe2dc0 100644 --- a/apps/api/src/generated.ts +++ b/apps/api/src/generated.ts @@ -82,6 +82,7 @@ export type MutationCreateRecipeArgs = { export type MutationUpdateRecipeArgs = { id: Scalars['ID']['input']; input: RecipeInput; + expectedUpdatedAt?: InputMaybe; }; export type MutationDeleteRecipeArgs = { diff --git a/apps/api/src/schema.graphql b/apps/api/src/schema.graphql index 92bfd5c..6c7fc58 100644 --- a/apps/api/src/schema.graphql +++ b/apps/api/src/schema.graphql @@ -43,7 +43,10 @@ type Query { type Mutation { createRecipe(input: RecipeInput!): Recipe! - updateRecipe(id: ID!, input: RecipeInput!): Recipe! + # expectedUpdatedAt: the recipe's updatedAt when the editor loaded it. If + # the recipe has changed since, the update fails with code CONFLICT + # instead of overwriting the newer version. + updateRecipe(id: ID!, input: RecipeInput!, expectedUpdatedAt: String): Recipe! deleteRecipe(id: ID!): Boolean! saveRecipe(id: ID!): Recipe! unsaveRecipe(id: ID!): Boolean! diff --git a/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx b/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx index accf529..95f6e53 100644 --- a/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx +++ b/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx @@ -1,10 +1,16 @@ import '@testing-library/jest-dom/vitest'; -import { render, screen, waitFor } from '@testing-library/react'; +import { render, screen, waitFor, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { MemoryRouter } from 'react-router-dom'; import { signOutUser } from '../../../features/auth/authApi'; +import { + countUserDrafts, + saveDraft, + type RecipeDraftFields, +} from '../../../lib/recipeDrafts'; +import { useUnsavedChanges } from '../../../lib/unsavedChanges'; import { useAppStore } from '../../../store'; import SiteHeader from './SiteHeader'; @@ -128,3 +134,66 @@ describe('SiteHeader authentication', () => { expect(useAppStore.getState().currentUser).toEqual(authenticatedUser); }); }); + +describe('SiteHeader sign-out warning', () => { + const fields = { title: 'Draft' } as RecipeDraftFields; + beforeEach(() => { + vi.clearAllMocks(); + localStorage.clear(); + useUnsavedChanges.setState({ unsaved: false }); + useAppStore.setState({ + currentUser: authenticatedUser, + sessionStatus: 'authenticated', + }); + vi.mocked(signOutUser).mockResolvedValue(true); + }); + + it('warns that drafts and unsaved editor changes will be lost', async () => { + saveDraft(authenticatedUser.id, 'new', { baseUpdatedAt: null, fields }); + saveDraft(authenticatedUser.id, 'recipe-1', { + baseUpdatedAt: null, + fields, + }); + saveDraft('someone-else', 'new', { baseUpdatedAt: null, fields }); + useUnsavedChanges.setState({ unsaved: true }); + const user = userEvent.setup(); + renderHeader(); + + await user.click(screen.getByRole('button', { name: 'Sign out' })); + const dialog = screen.getByRole('dialog'); + expect(dialog).toHaveTextContent( + 'Your unsaved changes in the recipe editor will be lost.', + ); + expect(dialog).toHaveTextContent( + 'Your 2 saved drafts in this browser will be deleted.', + ); + await user.click( + within(dialog).getByRole('button', { name: 'Stay signed in' }), + ); + expect(signOutUser).not.toHaveBeenCalled(); + expect(countUserDrafts(authenticatedUser.id)).toBe(2); + + await user.click(screen.getByRole('button', { name: 'Sign out' })); + await user.click( + within(screen.getByRole('dialog')).getByRole('button', { + name: 'Sign out', + }), + ); + await waitFor(() => expect(signOutUser).toHaveBeenCalledOnce()); + await waitFor(() => expect(countUserDrafts(authenticatedUser.id)).toBe(0)); + expect(countUserDrafts('someone-else')).toBe(1); + // The editor must not ask again about the changes just given up. + expect(useUnsavedChanges.getState().unsaved).toBe(false); + }); + + it('names a single draft in the singular', async () => { + saveDraft(authenticatedUser.id, 'new', { baseUpdatedAt: null, fields }); + const user = userEvent.setup(); + renderHeader(); + await user.click(screen.getByRole('button', { name: 'Sign out' })); + expect(screen.getByRole('dialog')).toHaveTextContent( + 'Your saved draft in this browser will be deleted.', + ); + expect(screen.getByRole('dialog')).not.toHaveTextContent('unsaved'); + }); +}); diff --git a/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx b/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx index 9fa2d73..d349af0 100644 --- a/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx +++ b/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx @@ -16,6 +16,9 @@ import './SiteHeader.css'; import LogoMark from '../../brand/LogoMark/LogoMark'; import LinkButton from '../../ui/LinkButton/LinkButton'; import { Icon } from '../../ui/Icon/Icon'; +import ConfirmationDialog from '../../ui/ConfirmationDialog/ConfirmationDialog'; +import { countUserDrafts } from '../../../lib/recipeDrafts'; +import { useUnsavedChanges } from '../../../lib/unsavedChanges'; const pages = [ { to: '/', label: 'Explore', icon: HomeIcon }, @@ -33,6 +36,26 @@ function SiteHeader() { const closeMenu = () => setMenuOpen(false); + /* + * Signing out deletes this user's drafts (shared computers) and closes + * the recipe editor, so say what would be lost and ask first. + */ + const [signOutLoss, setSignOutLoss] = useState<{ + drafts: number; + unsaved: boolean; + } | null>(null); + const requestSignOut = () => { + const drafts = currentUser ? countUserDrafts(currentUser.id) : 0; + const { unsaved } = useUnsavedChanges.getState(); + if (drafts || unsaved) setSignOutLoss({ drafts, unsaved }); + else void handleSignOut(); + }; + const confirmSignOut = () => { + setSignOutLoss(null); + useUnsavedChanges.setState({ unsaved: false }); + void handleSignOut(); + }; + const handleSignOut = async () => { setLogoutError(''); try { @@ -108,7 +131,7 @@ function SiteHeader() { {currentUser.name} - @@ -144,6 +167,30 @@ function SiteHeader() { + setSignOutLoss(null)} + > +
    + {signOutLoss?.unsaved && ( +
  • Your unsaved changes in the recipe editor will be lost.
  • + )} + {Boolean(signOutLoss?.drafts) && ( +
  • + {signOutLoss?.drafts === 1 + ? 'Your saved draft' + : `Your ${signOutLoss?.drafts} saved drafts`}{' '} + in this browser will be deleted. +
  • + )} +
+
); } diff --git a/apps/web/src/features/auth/authNavigation.test.ts b/apps/web/src/features/auth/authNavigation.test.ts index ac187dc..3203a41 100644 --- a/apps/web/src/features/auth/authNavigation.test.ts +++ b/apps/web/src/features/auth/authNavigation.test.ts @@ -8,13 +8,19 @@ describe('authentication return navigation', () => { { from: '//example.com' }, { from: '/login' }, { from: '/cookbook\\evil' }, + { from: '/recipes/abc/edit' }, + { from: '/recipes/11111111-1111-4111-8111-111111111111/editor' }, + { from: '/recipes/11111111-1111-4111-8111-111111111111/edit/../../x' }, + { from: '//example.com/recipes/11111111-1111-4111-8111-111111111111/edit' }, + { from: '/recipes/11111111-1111-4111-8111-111111111111' }, ])('falls back for unsafe or unsupported state %j', (state) => { expect(getAuthReturnPath(state)).toBe('/'); }); - it.each(['/cookbook?view=saved#recipes', '/recipes/new'])( - 'preserves protected destination %s', - (from) => { - expect(getAuthReturnPath({ from })).toBe(from); - }, - ); + it.each([ + '/cookbook?view=saved#recipes', + '/recipes/new', + '/recipes/11111111-1111-4111-8111-111111111111/edit', + ])('preserves protected destination %s', (from) => { + expect(getAuthReturnPath({ from })).toBe(from); + }); }); diff --git a/apps/web/src/features/auth/authNavigation.ts b/apps/web/src/features/auth/authNavigation.ts index 2d4ef38..18e33fc 100644 --- a/apps/web/src/features/auth/authNavigation.ts +++ b/apps/web/src/features/auth/authNavigation.ts @@ -1,9 +1,17 @@ +// The recipe editor of one recipe id; nothing else under /recipes/. +const EDIT_ROUTE = + /^\/recipes\/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\/edit$/; + // Only return to known protected routes. Never navigate to a supplied origin. export function getAuthReturnPath(state: unknown): string { if (typeof state !== 'object' || state === null || !('from' in state)) return '/'; const from = state.from; if (typeof from !== 'string' || from.includes('\\')) return '/'; - const pathname = from.split(/[?#]/)[0]; - return pathname === '/cookbook' || pathname === '/recipes/new' ? from : '/'; + const pathname = from.split(/[?#]/)[0] ?? ''; + return pathname === '/cookbook' || + pathname === '/recipes/new' || + EDIT_ROUTE.test(pathname) + ? from + : '/'; } diff --git a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx index 058a87a..8021508 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx @@ -8,7 +8,15 @@ import { useRecipeChanges } from './recipeApi'; import { act } from '@testing-library/react'; import RecipeCreatePage from './RecipeCreatePage'; -import { MemoryRouter, Routes, Route } from 'react-router-dom'; +import { + createMemoryRouter, + Link, + MemoryRouter, + Routes, + Route, + RouterProvider, +} from 'react-router-dom'; +import { loadDraft, saveDraft } from '../../lib/recipeDrafts'; import { apiRecipe, mockRecipeFetch } from '../../test/recipeApiFixtures'; function mount(entry = '/recipes/new') { @@ -671,3 +679,139 @@ describe('edit page titles', () => { expect(document.title).toBe('Recipe unavailable – Recipe Platform'); }); }); + +describe('protecting edits', () => { + beforeEach(() => localStorage.clear()); + + it('sends the version it loaded and keeps the form when the recipe changed meanwhile', async () => { + let sent: Record = {}; + mockRecipeFetch((operation, variables) => { + if (operation !== 'UpdateRecipe') + return { + data: { recipe: { ...apiRecipe, isCreatedByCurrentUser: true } }, + }; + sent = variables; + return { + errors: [{ message: 'Changed.', extensions: { code: 'CONFLICT' } }], + }; + }); + const user = userEvent.setup(); + mount('/recipes/' + apiRecipe.id + '/edit'); + const title = await screen.findByLabelText(/Recipe title/); + fireEvent.change(title, { target: { value: 'My version' } }); + await user.click(screen.getByRole('button', { name: 'Save changes' })); + expect( + await screen.findByText(/was changed in another tab or session/), + ).toBeInTheDocument(); + expect(sent.expectedUpdatedAt).toBe(apiRecipe.updatedAt); + expect(title).toHaveValue('My version'); + }); + + it('asks before replacing a draft that was offered but not restored', async () => { + saveDraft(apiUser.id, 'new', { + baseUpdatedAt: null, + fields: { + title: 'Older draft', + description: '', + category: '', + difficulty: '', + visibility: 'public', + prepTime: '', + cookingTime: '', + servings: '', + tags: '', + imageUrl: null, + ingredients: [{ name: '', amount: '', unit: 'g' }], + instructions: [''], + }, + }); + const user = userEvent.setup(); + mount(); + expect(screen.getByText('Saved draft found')).toBeInTheDocument(); + fireEvent.change(screen.getByLabelText(/Recipe title/), { + target: { value: 'Newer form' }, + }); + await user.click(screen.getByRole('button', { name: 'Save draft' })); + expect( + screen.getByRole('heading', { name: 'Replace saved draft?' }), + ).toBeInTheDocument(); + await user.click(screen.getByRole('button', { name: 'Keep it' })); + expect(loadDraft(apiUser.id, 'new')?.fields.title).toBe('Older draft'); + + await user.click(screen.getByRole('button', { name: 'Save draft' })); + await user.click(screen.getByRole('button', { name: 'Replace draft' })); + expect(loadDraft(apiUser.id, 'new')?.fields.title).toBe('Newer form'); + expect(screen.getByText('Draft saved')).toBeInTheDocument(); + }); + + it('lets the browser warn on reload only while changes are unsaved', async () => { + const user = userEvent.setup(); + mount(); + const reload = () => { + const event = new Event('beforeunload', { cancelable: true }); + window.dispatchEvent(event); + return event.defaultPrevented; + }; + expect(reload()).toBe(false); + fireEvent.change(screen.getByLabelText(/Recipe title/), { + target: { value: 'Unsaved soup' }, + }); + expect(reload()).toBe(true); + // Kept as a draft in this browser: nothing is lost by leaving. + await user.click(screen.getByRole('button', { name: 'Save draft' })); + expect(reload()).toBe(false); + }); + + function mountWithDataRouter() { + const router = createMemoryRouter( + [ + { + path: '/recipes/new', + element: ( + <> + Go to My Cookbook + + + ), + }, + { path: '/recipes/:id', element:

Saved recipe destination

}, + { path: '/cookbook', element:

Cookbook page

}, + ], + { initialEntries: ['/recipes/new'] }, + ); + render(); + } + + it('asks before following a link away from unsaved changes', async () => { + const user = userEvent.setup(); + mountWithDataRouter(); + fireEvent.change(screen.getByLabelText(/Recipe title/), { + target: { value: 'Unsaved soup' }, + }); + await user.click(screen.getByRole('link', { name: 'Go to My Cookbook' })); + expect( + await screen.findByRole('heading', { name: 'Leave without saving?' }), + ).toBeInTheDocument(); + await user.click(screen.getByRole('button', { name: 'Stay' })); + expect(screen.getByLabelText(/Recipe title/)).toHaveValue('Unsaved soup'); + + await user.click(screen.getByRole('link', { name: 'Go to My Cookbook' })); + await user.click(await screen.findByRole('button', { name: 'Leave' })); + expect( + await screen.findByRole('heading', { name: 'Cookbook page' }), + ).toBeInTheDocument(); + }); + + it('does not ask after the recipe is published', async () => { + mockRecipeFetch(() => ({ data: { createRecipe: apiRecipe } })); + mountWithDataRouter(); + const user = await fillRecipe(); + await user.click(screen.getByRole('button', { name: 'Publish recipe' })); + expect( + await screen.findByRole('heading', { name: 'Saved recipe destination' }), + ).toBeInTheDocument(); + expect( + screen.queryByRole('heading', { name: 'Leave without saving?' }), + ).not.toBeInTheDocument(); + }); +}); diff --git a/apps/web/src/features/recipes/RecipeCreatePage.tsx b/apps/web/src/features/recipes/RecipeCreatePage.tsx index c5296be..bb61c9e 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.tsx @@ -41,6 +41,9 @@ import { } from '../../lib/recipeDrafts'; import { INGREDIENT_UNITS, normalizeUnit } from '../../lib/ingredientUnits'; import { MAX_SERVINGS, MIN_SERVINGS } from '@t31/validation/recipe'; +import ConfirmationDialog from '../../components/ui/ConfirmationDialog/ConfirmationDialog'; +import { useUnsavedChanges } from '../../lib/unsavedChanges'; +import UnsavedChangesGuard from './UnsavedChangesGuard'; import './RecipeCreatePage.css'; @@ -214,13 +217,61 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { const formSnapshot = JSON.stringify(draftFields()); const draftMessageIsCurrent = savedSnapshot === formSnapshot; + /* + * Unsaved changes: the form differs from how it was opened and from the + * draft this browser holds for it (saved or restored here). Leaving, + * reloading or signing out then asks first (UnsavedChangesGuard, + * SiteHeader). The refs let the guard read the latest state when the + * user leaves, and let a successful save navigate away unasked. + */ + const [openedSnapshot] = useState(formSnapshot); + const [storedSnapshot, setStoredSnapshot] = useState(null); + const unsaved = + formSnapshot !== openedSnapshot && formSnapshot !== storedSnapshot; + const unsavedRef = useRef(unsaved); + const leaving = useRef(false); + useEffect(() => { + unsavedRef.current = unsaved; + useUnsavedChanges.setState({ unsaved }); + }, [unsaved]); + useEffect(() => () => useUnsavedChanges.setState({ unsaved: false }), []); + // The header clears the shared flag when the user confirms signing out + // with unsaved changes, so they are not asked a second time. + const isDirty = useCallback( + () => + unsavedRef.current && + !leaving.current && + useUnsavedChanges.getState().unsaved, + [], + ); + + const [confirmReplaceDraft, setConfirmReplaceDraft] = useState(false); function handleSaveDraft() { if (!userId || imageRestoring) return; + // Do not silently replace a draft this tab has not restored or written: + // the one offered on opening, or one another tab saved in the meantime. + const stored = loadDraft(userId, draftRecipeId); + if ( + offeredDraft || + (stored && !knownDrafts.current.includes(stored.savedAt)) + ) { + setConfirmReplaceDraft(true); + return; + } + writeDraft(); + } + + function writeDraft() { + setConfirmReplaceDraft(false); + if (!userId) return; const saved = saveDraft(userId, draftRecipeId, { baseUpdatedAt: recipe?.updatedAt ?? null, fields: draftFields(), }); - if (saved) knownDrafts.current.push(saved.savedAt); + if (saved) { + knownDrafts.current.push(saved.savedAt); + setStoredSnapshot(formSnapshot); + } setOfferedDraft(null); setDraftNotice(''); setSavedSnapshot(formSnapshot); @@ -250,6 +301,8 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { ); setErrors({}); setOfferedDraft(null); + // The restored form is what the browser holds: not an unsaved change. + setStoredSnapshot(JSON.stringify(fields)); // 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. const draftImage = fields.imageUrl; @@ -283,6 +336,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { const removed = userId && clearDraft(userId, draftRecipeId, knownDrafts.current); setOfferedDraft(null); + if (removed) setStoredSnapshot(null); setDraftNotice( removed || !userId || !loadDraft(userId, draftRecipeId) ? 'Draft discarded.' @@ -653,10 +707,13 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { imageUrl, cuisine: recipe?.cuisine || null, }; - const saved = await writeRecipe(input, recipe?.id); + // Editing sends the version it loaded; if the recipe changed since + // (another tab or device), the API refuses instead of overwriting it. + const saved = await writeRecipe(input, recipe?.id, recipe?.updatedAt); // The saved recipe replaces the draft (but not a newer one saved in // another tab after this form read or saved its draft). if (userId) clearDraft(userId, draftRecipeId, knownDrafts.current); + leaving.current = true; navigate('/recipes/' + saved.id, { replace: Boolean(recipe) }); } catch (error) { setSubmitError(recipeErrorMessage(error)); @@ -1171,6 +1228,23 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { + + setConfirmReplaceDraft(false)} + > + Saving replaces that draft with this form. + ); } diff --git a/apps/web/src/features/recipes/UnsavedChangesGuard.tsx b/apps/web/src/features/recipes/UnsavedChangesGuard.tsx new file mode 100644 index 0000000..fc8743b --- /dev/null +++ b/apps/web/src/features/recipes/UnsavedChangesGuard.tsx @@ -0,0 +1,51 @@ +import { useContext, useEffect } from 'react'; +import { UNSAFE_DataRouterContext, useBlocker } from 'react-router-dom'; +import ConfirmationDialog from '../../components/ui/ConfirmationDialog/ConfirmationDialog'; + +type GuardProps = { + /** Read at the moment of leaving, so a just-finished save is not blocked. */ + isDirty: () => boolean; +}; + +/* + * Asks before leaving a page with unsaved changes. Reloading, closing the + * tab or typing another address gets the browser's own prompt + * (beforeunload); links and Back/Forward inside the app get a dialog. + * The dialog needs a data router (main.tsx); under a plain router, as in + * most unit tests, only the browser prompt is used. + */ +export default function UnsavedChangesGuard({ isDirty }: GuardProps) { + useEffect(() => { + function warn(event: BeforeUnloadEvent) { + if (!isDirty()) return; + event.preventDefault(); + // Older browsers need returnValue set to show the prompt. + event.returnValue = ''; + } + window.addEventListener('beforeunload', warn); + return () => window.removeEventListener('beforeunload', warn); + }, [isDirty]); + const dataRouter = useContext(UNSAFE_DataRouterContext); + return dataRouter ? : null; +} + +function LeavePrompt({ isDirty }: GuardProps) { + const blocker = useBlocker( + ({ currentLocation, nextLocation }) => + currentLocation.pathname !== nextLocation.pathname && isDirty(), + ); + return ( + blocker.proceed?.()} + onCancel={() => blocker.reset?.()} + > + To keep them, stay and save the recipe or a draft first. + + ); +} diff --git a/apps/web/src/features/recipes/recipeApi.ts b/apps/web/src/features/recipes/recipeApi.ts index dad8b9d..2af7982 100644 --- a/apps/web/src/features/recipes/recipeApi.ts +++ b/apps/web/src/features/recipes/recipeApi.ts @@ -65,9 +65,19 @@ export async function getRecipe(id: string, signal?: AbortSignal) { return recipe ? toRecipe(recipe) : null; } -export async function writeRecipe(input: RecipeInput, id?: string) { +export async function writeRecipe( + input: RecipeInput, + id?: string, + expectedUpdatedAt?: string, +) { const recipe = id - ? (await graphqlRequest(UpdateRecipeDocument, { id, input })).updateRecipe + ? ( + await graphqlRequest(UpdateRecipeDocument, { + id, + input, + expectedUpdatedAt, + }) + ).updateRecipe : (await graphqlRequest(CreateRecipeDocument, { input })).createRecipe; invalidateRecipes(); return toRecipe(recipe); @@ -97,6 +107,8 @@ export function recipeErrorMessage(error: unknown) { FORBIDDEN: 'You do not have permission to perform this action.', NOT_FOUND: 'This recipe is unavailable or you no longer have access.', BAD_USER_INPUT: 'Check the recipe fields and try again.', + CONFLICT: + 'This recipe was changed in another tab or session after you opened it, so your version was not saved. Your changes are still in the form: save a draft, reload the page to see the latest version, then restore the draft if you want to keep your changes.', }; return messages[error.code] ?? error.message; } diff --git a/apps/web/src/lib/recipeDrafts.test.ts b/apps/web/src/lib/recipeDrafts.test.ts index 1e02435..084a146 100644 --- a/apps/web/src/lib/recipeDrafts.test.ts +++ b/apps/web/src/lib/recipeDrafts.test.ts @@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it } from 'vitest'; import { clearDraft, clearUserDrafts, + countUserDrafts, loadDraft, saveDraft, type RecipeDraftFields, @@ -40,9 +41,13 @@ describe('recipe drafts', () => { saveDraft('alice', 'new', { baseUpdatedAt: null, fields }); saveDraft('alice', 'r1', { baseUpdatedAt: null, fields }); saveDraft('bob', 'new', { baseUpdatedAt: null, fields }); + expect(countUserDrafts('alice')).toBe(2); + expect(countUserDrafts('bob')).toBe(1); clearDraft('alice', 'new'); expect(loadDraft('alice', 'new')).toBeNull(); + expect(countUserDrafts('alice')).toBe(1); clearUserDrafts('alice'); + expect(countUserDrafts('alice')).toBe(0); expect(loadDraft('alice', 'r1')).toBeNull(); expect(loadDraft('bob', 'new')).not.toBeNull(); }); diff --git a/apps/web/src/lib/recipeDrafts.ts b/apps/web/src/lib/recipeDrafts.ts index 9407660..a36c446 100644 --- a/apps/web/src/lib/recipeDrafts.ts +++ b/apps/web/src/lib/recipeDrafts.ts @@ -160,3 +160,16 @@ export function clearUserDrafts(userId: string) { // Storage unavailable: nothing to clear. } } + +/** How many drafts one user has in this browser (0 if storage is unavailable). */ +export function countUserDrafts(userId: string) { + try { + const own = `${PREFIX}${userId}:`; + let count = 0; + for (let index = 0; index < localStorage.length; index += 1) + if (localStorage.key(index)?.startsWith(own)) count += 1; + return count; + } catch { + return 0; + } +} diff --git a/apps/web/src/lib/unsavedChanges.ts b/apps/web/src/lib/unsavedChanges.ts new file mode 100644 index 0000000..4a2f934 --- /dev/null +++ b/apps/web/src/lib/unsavedChanges.ts @@ -0,0 +1,8 @@ +import { create } from 'zustand'; + +/* + * Whether the recipe editor currently has changes that are neither saved + * nor kept as a draft. The editor sets it; the header reads it to warn + * before signing out, which would close the editor. + */ +export const useUnsavedChanges = create(() => ({ unsaved: false })); diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index 8ead562..5676925 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -1,6 +1,6 @@ import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; -import { BrowserRouter } from 'react-router-dom'; +import { createBrowserRouter, RouterProvider } from 'react-router-dom'; import './styles/layers.css'; import './styles/resets.css'; @@ -10,10 +10,14 @@ import './styles/utilities.css'; import { App } from './App'; +// A data router (rather than ) so the recipe editor can ask +// before leaving with unsaved changes (useBlocker). App keeps its . +const router = createBrowserRouter([{ path: '*', element: }], { + basename: '/project2/', +}); + createRoot(document.getElementById('root')!).render( - - - + , ); diff --git a/contracts/generated.ts b/contracts/generated.ts index e16b73a..6ce6fc2 100644 --- a/contracts/generated.ts +++ b/contracts/generated.ts @@ -269,6 +269,7 @@ export type CreateRecipeMutation = { export type UpdateRecipeMutationVariables = Exact<{ id: string | number; input: RecipeInput; + expectedUpdatedAt?: string | null | undefined; }>; export type UpdateRecipeMutation = { @@ -691,8 +692,8 @@ export const CreateRecipeDocument = new TypedDocumentString(` CreateRecipeMutationVariables >; export const UpdateRecipeDocument = new TypedDocumentString(` - mutation UpdateRecipe($id: ID!, $input: RecipeInput!) { - updateRecipe(id: $id, input: $input) { + mutation UpdateRecipe($id: ID!, $input: RecipeInput!, $expectedUpdatedAt: String) { + updateRecipe(id: $id, input: $input, expectedUpdatedAt: $expectedUpdatedAt) { ...RecipeFields } } diff --git a/contracts/operations.graphql b/contracts/operations.graphql index da1d6c8..5683a7b 100644 --- a/contracts/operations.graphql +++ b/contracts/operations.graphql @@ -124,8 +124,12 @@ mutation CreateRecipe($input: RecipeInput!) { ...RecipeFields } } -mutation UpdateRecipe($id: ID!, $input: RecipeInput!) { - updateRecipe(id: $id, input: $input) { +mutation UpdateRecipe( + $id: ID! + $input: RecipeInput! + $expectedUpdatedAt: String +) { + updateRecipe(id: $id, input: $input, expectedUpdatedAt: $expectedUpdatedAt) { ...RecipeFields } } diff --git a/scripts/test-recipe-api.ts b/scripts/test-recipe-api.ts index ecb053c..4cfdbab 100644 --- a/scripts/test-recipe-api.ts +++ b/scripts/test-recipe-api.ts @@ -741,6 +741,66 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { } }, ); + await t.test( + 'refuses an update based on an outdated version (CONFLICT)', + async () => { + const { createRecipe } = await ok( + CreateRecipeDocument, + { input: { ...input, title: 'Edited in two tabs' } }, + owner.cookie, + ); + try { + // updatedAt has millisecond precision; make sure the save below + // gets a later one than the create. + await new Promise((resolve) => setTimeout(resolve, 5)); + // Tab A saves first, from the version both tabs loaded. + const { updateRecipe: first } = await ok( + UpdateRecipeDocument, + { + id: createRecipe.id, + input: { ...input, title: 'Saved by tab A' }, + expectedUpdatedAt: createRecipe.updatedAt, + }, + owner.cookie, + ); + assert.notEqual(first.updatedAt, createRecipe.updatedAt); + // Tab B still has the old version: refused, nothing overwritten. + await fails( + UpdateRecipeDocument, + { + id: createRecipe.id, + input: { ...input, title: 'Saved by tab B' }, + expectedUpdatedAt: createRecipe.updatedAt, + }, + 'CONFLICT', + owner.cookie, + ); + const { recipe } = await ok( + RecipeDocument, + { id: createRecipe.id }, + owner.cookie, + ); + assert.equal(recipe?.title, 'Saved by tab A'); + // With the current version, or without one (older clients), it saves. + await ok( + UpdateRecipeDocument, + { + id: createRecipe.id, + input: { ...input, title: 'Saved by tab B' }, + expectedUpdatedAt: first.updatedAt, + }, + owner.cookie, + ); + await ok( + UpdateRecipeDocument, + { id: createRecipe.id, input }, + owner.cookie, + ); + } finally { + await ok(DeleteRecipeDocument, { id: createRecipe.id }, owner.cookie); + } + }, + ); await t.test('only the owner can update or delete', async () => { await fails( UpdateRecipeDocument, From 08147c6e75e99049456f8948d818d80f5cea6a61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Tue, 17 Nov 2026 16:50:08 +0100 Subject: [PATCH 2/5] test(auth): allow for the lazy Log in page's first import on CI The redirect test waited 1 s (the default) for the lazy-loaded Log in page. As the file's first test it pays the cold import, which took 1.6 s on the CI runner once the header imported the confirmation dialog. Refs #121 --- apps/web/src/features/auth/RequireAuth.test.tsx | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/apps/web/src/features/auth/RequireAuth.test.tsx b/apps/web/src/features/auth/RequireAuth.test.tsx index 5af641b..03771df 100644 --- a/apps/web/src/features/auth/RequireAuth.test.tsx +++ b/apps/web/src/features/auth/RequireAuth.test.tsx @@ -52,8 +52,14 @@ describe('protected routes with session restoration', () => { 'redirects a logged-out visitor from %s', async (path) => { renderApp(path); + // Log in is lazy-loaded; the first import in a test run can take + // over a second on the CI runner. expect( - await screen.findByRole('heading', { name: 'Log in' }), + await screen.findByRole( + 'heading', + { name: 'Log in' }, + { timeout: 5000 }, + ), ).toBeInTheDocument(); expect(screen.getByTestId('location')).toHaveTextContent('/login'); }, From c1160725efb66e7d3c15c6bbba860e6e5855d78c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Tue, 17 Nov 2026 16:57:40 +0100 Subject: [PATCH 3/5] fix(recipe): keep protecting editor changes when sign-out fails Confirming sign-out clears the shared unsaved flag so the editor does not ask again while it closes. If sign-out then failed, the flag stayed off and the editor's leave and reload prompts were disabled for the rest of the session. The previous value is now restored on failure. Refs #121 --- .../shell/SiteHeader/SiteHeader.test.tsx | 17 +++++++++++++++++ .../components/shell/SiteHeader/SiteHeader.tsx | 12 +++++++++--- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx b/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx index 95f6e53..755969f 100644 --- a/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx +++ b/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx @@ -186,6 +186,23 @@ describe('SiteHeader sign-out warning', () => { expect(useUnsavedChanges.getState().unsaved).toBe(false); }); + it('protects the unsaved changes again when signing out fails', async () => { + useUnsavedChanges.setState({ unsaved: true }); + vi.mocked(signOutUser).mockRejectedValueOnce(new Error('Offline')); + const user = userEvent.setup(); + renderHeader(); + await user.click(screen.getByRole('button', { name: 'Sign out' })); + await user.click( + within(screen.getByRole('dialog')).getByRole('button', { + name: 'Sign out', + }), + ); + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Unable to sign out', + ); + expect(useUnsavedChanges.getState().unsaved).toBe(true); + }); + it('names a single draft in the singular', async () => { saveDraft(authenticatedUser.id, 'new', { baseUpdatedAt: null, fields }); const user = userEvent.setup(); diff --git a/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx b/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx index d349af0..82c6dfe 100644 --- a/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx +++ b/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx @@ -50,10 +50,14 @@ function SiteHeader() { if (drafts || unsaved) setSignOutLoss({ drafts, unsaved }); else void handleSignOut(); }; - const confirmSignOut = () => { + const confirmSignOut = async () => { + const unsaved = Boolean(signOutLoss?.unsaved); setSignOutLoss(null); + // The user gave up the editor's changes: the editor must not ask again + // as sign-out closes it. If signing out fails, the editor stays open + // and its changes are protected again. useUnsavedChanges.setState({ unsaved: false }); - void handleSignOut(); + if (!(await handleSignOut())) useUnsavedChanges.setState({ unsaved }); }; const handleSignOut = async () => { @@ -62,8 +66,10 @@ function SiteHeader() { await signOut(); closeMenu(); navigate('/'); + return true; } catch { setLogoutError('Unable to sign out. Please try again.'); + return false; } }; @@ -174,7 +180,7 @@ function SiteHeader() { confirmLabel="Sign out" cancelLabel="Stay signed in" tone="warning" - onConfirm={confirmSignOut} + onConfirm={() => void confirmSignOut()} onCancel={() => setSignOutLoss(null)} >
    From 761bc0cd17d36fe6f4edf30224658e80a407ae4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Tue, 17 Nov 2026 18:36:06 +0100 Subject: [PATCH 4/5] fix(recipe): warn about a pending image and about drafts changed elsewhere Choosing an image opens the crop dialog and uploads it later, and until then nothing in the form differs, so reloading or leaving discarded the pending image without a warning. A picked image that is not uploaded yet now counts as an unsaved change. The editor also remembered the draft it had saved or restored and treated the form as kept for good. If another tab replaced or deleted that draft, leaving still passed without a warning and the changes were lost. It now reads the draft stored in this browser whenever it changes (storage event, saving, discarding) and compares the form against that. --- .../recipes/RecipeCreatePage.test.tsx | 61 +++++++++++++++++++ .../src/features/recipes/RecipeCreatePage.tsx | 32 +++++++--- 2 files changed, 83 insertions(+), 10 deletions(-) diff --git a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx index b467a56..290831d 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx @@ -762,6 +762,67 @@ describe('protecting edits', () => { expect(reload()).toBe(false); }); + it('counts a chosen image as unsaved before it is uploaded', () => { + mount(); + const reload = () => { + const event = new Event('beforeunload', { cancelable: true }); + window.dispatchEvent(event); + return event.defaultPrevented; + }; + expect(reload()).toBe(false); + URL.createObjectURL = vi.fn(() => 'blob:chosen'); + URL.revokeObjectURL = vi.fn(); + fireEvent.change(screen.getByLabelText('Upload a recipe image'), { + target: { + files: [new File(['x'], 'soup.png', { type: 'image/png' })], + }, + }); + // Nothing else changed, but the picked image is not saved anywhere yet. + expect(reload()).toBe(true); + fireEvent.click(screen.getByRole('button', { name: 'Cancel' })); + expect(reload()).toBe(false); + }); + + it('warns when another tab replaces or deletes the saved draft', async () => { + const user = userEvent.setup(); + mount(); + const reload = () => { + const event = new Event('beforeunload', { cancelable: true }); + window.dispatchEvent(event); + return event.defaultPrevented; + }; + const draftKey = 'recipe-platform:draft:' + apiUser.id + ':new'; + const otherTab = (change: () => void) => { + change(); + act(() => { + window.dispatchEvent(new StorageEvent('storage', { key: draftKey })); + }); + }; + fireEvent.change(screen.getByLabelText(/Recipe title/), { + target: { value: 'My soup' }, + }); + await user.click(screen.getByRole('button', { name: 'Save draft' })); + expect(reload()).toBe(false); + + // Another tab saves its own draft over this one: ours is no longer kept. + otherTab(() => + saveDraft(apiUser.id, 'new', { + baseUpdatedAt: null, + fields: { ...loadDraft(apiUser.id, 'new')!.fields, title: 'Theirs' }, + }), + ); + expect(reload()).toBe(true); + + // Saving again over it asks first, then keeps this form as the draft. + await user.click(screen.getByRole('button', { name: 'Save draft' })); + await user.click(screen.getByRole('button', { name: 'Replace draft' })); + expect(reload()).toBe(false); + + // Another tab deletes the draft. + otherTab(() => localStorage.removeItem(draftKey)); + expect(reload()).toBe(true); + }); + function mountWithDataRouter() { const router = createMemoryRouter( [ diff --git a/apps/web/src/features/recipes/RecipeCreatePage.tsx b/apps/web/src/features/recipes/RecipeCreatePage.tsx index 0fdfc73..faf3d13 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.tsx @@ -242,15 +242,29 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { /* * Unsaved changes: the form differs from how it was opened and from the - * draft this browser holds for it (saved or restored here). Leaving, - * reloading or signing out then asks first (UnsavedChangesGuard, - * SiteHeader). The refs let the guard read the latest state when the - * user leaves, and let a successful save navigate away unasked. + * draft this browser holds for it right now, or an image is being chosen + * or uploaded. The stored draft is read again whenever it changes, also + * in another tab, so a draft replaced or deleted there is not counted as + * saving this form. Leaving, reloading or signing out then asks first + * (UnsavedChangesGuard, SiteHeader). The refs let the guard read the + * latest state when the user leaves, and let a successful save navigate + * away unasked. */ const [openedSnapshot] = useState(formSnapshot); - const [storedSnapshot, setStoredSnapshot] = useState(null); + const readStoredSnapshot = () => { + const stored = userId ? loadDraft(userId, draftRecipeId) : null; + return stored ? JSON.stringify(stored.fields) : null; + }; + const [storedSnapshot, setStoredSnapshot] = useState(readStoredSnapshot); + const refreshStoredDraft = () => setStoredSnapshot(readStoredSnapshot()); + useEffect(() => { + window.addEventListener('storage', refreshStoredDraft); + return () => window.removeEventListener('storage', refreshStoredDraft); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [userId, draftRecipeId]); const unsaved = - formSnapshot !== openedSnapshot && formSnapshot !== storedSnapshot; + imagePending || + (formSnapshot !== openedSnapshot && formSnapshot !== storedSnapshot); const unsavedRef = useRef(unsaved); const leaving = useRef(false); useEffect(() => { @@ -293,7 +307,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { }); if (saved) { knownDrafts.current.push(saved.savedAt); - setStoredSnapshot(formSnapshot); + refreshStoredDraft(); } setOfferedDraft(null); setDraftNotice(''); @@ -327,8 +341,6 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { rowCountErrors(fields.ingredients.length, fields.instructions.length), ); setOfferedDraft(null); - // The restored form is what the browser holds: not an unsaved change. - setStoredSnapshot(JSON.stringify(fields)); // 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. const draftImage = fields.imageUrl; @@ -362,7 +374,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { const removed = userId && clearDraft(userId, draftRecipeId, knownDrafts.current); setOfferedDraft(null); - if (removed) setStoredSnapshot(null); + if (removed) refreshStoredDraft(); setDraftNotice( removed || !userId || !loadDraft(userId, draftRecipeId) ? 'Draft discarded.' From d467a09e1735b49654d52e3721e2dbb04a2cf435 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Tue, 17 Nov 2026 18:36:11 +0100 Subject: [PATCH 5/5] test(recipe): give the drag-reorder test time on slow CI The test types and drags through the whole form and took about 4.95 s on the CI runner against vitest's 5 s default, timing out once. Give it 15 s. --- apps/web/src/features/recipes/RecipeCreatePage.test.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx index 290831d..25a8633 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx @@ -113,6 +113,7 @@ describe('RecipeCreatePage', () => { expect(screen.queryByLabelText('Step 2')).not.toBeInTheDocument(); }); + // Many real keystrokes and drags: close to the 5 s default on the CI runner. it('supports structured ingredients and reordering by dragging the handle', async () => { const user = userEvent.setup(); @@ -167,7 +168,7 @@ describe('RecipeCreatePage', () => { expect(screen.getByLabelText('Step 1')).toHaveValue('Bake'); expect(screen.getByLabelText('Step 2')).toHaveValue('Mix'); - }); + }, 15_000); it('reorders ingredients and instructions by drag and drop', async () => { const user = userEvent.setup();