diff --git a/apps/api/src/features/recipes/recipeRepository.ts b/apps/api/src/features/recipes/recipeRepository.ts index be2e8e8..8aac90e 100644 --- a/apps/api/src/features/recipes/recipeRepository.ts +++ b/apps/api/src/features/recipes/recipeRepository.ts @@ -237,9 +237,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..755969f 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,83 @@ 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('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(); + 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..82c6dfe 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,14 +36,40 @@ 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 = 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 }); + if (!(await handleSignOut())) useUnsavedChanges.setState({ unsaved }); + }; + const handleSignOut = async () => { setLogoutError(''); try { await signOut(); closeMenu(); navigate('/'); + return true; } catch { setLogoutError('Unable to sign out. Please try again.'); + return false; } }; @@ -108,7 +137,7 @@ function SiteHeader() { {currentUser.name} - @@ -144,6 +173,30 @@ function SiteHeader() { + void confirmSignOut()} + onCancel={() => setSignOutLoss(null)} + > + + ); } 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'); }, 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 b68cef3..25a8633 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') { @@ -105,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(); @@ -159,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(); @@ -672,6 +681,203 @@ describe('edit page titles', () => { }); }); +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); + }); + + 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( + [ + { + 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(); + }); +}); + describe('recipe size limits and error focus', () => { /** A valid new recipe, filled without per-key typing (fast on CI). */ function fillValid() { diff --git a/apps/web/src/features/recipes/RecipeCreatePage.tsx b/apps/web/src/features/recipes/RecipeCreatePage.tsx index 783dc3a..faf3d13 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.tsx @@ -49,6 +49,9 @@ import { MIN_SERVINGS, parseTags, } from '@t31/validation/recipe'; +import ConfirmationDialog from '../../components/ui/ConfirmationDialog/ConfirmationDialog'; +import { useUnsavedChanges } from '../../lib/unsavedChanges'; +import UnsavedChangesGuard from './UnsavedChangesGuard'; import './RecipeCreatePage.css'; @@ -237,13 +240,75 @@ 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 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 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 = + imagePending || + (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); + refreshStoredDraft(); + } setOfferedDraft(null); setDraftNotice(''); setSavedSnapshot(formSnapshot); @@ -309,6 +374,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { const removed = userId && clearDraft(userId, draftRecipeId, knownDrafts.current); setOfferedDraft(null); + if (removed) refreshStoredDraft(); setDraftNotice( removed || !userId || !loadDraft(userId, draftRecipeId) ? 'Draft discarded.' @@ -685,10 +751,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)); @@ -1245,6 +1314,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 3ecd906..c34d95a 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( 'word search and cached ratings are index-backed and stay correct', async () => {