diff --git a/.claude/audits/2026-11-06-v1-2-6-u1-label-proposals.md b/.claude/audits/2026-11-06-v1-2-6-u1-label-proposals.md index 29ae2392..4e7af25e 100644 --- a/.claude/audits/2026-11-06-v1-2-6-u1-label-proposals.md +++ b/.claude/audits/2026-11-06-v1-2-6-u1-label-proposals.md @@ -55,3 +55,18 @@ Reused: `editor.annotations.list` (« Annotations de la vue », card title and l | `editor.references.no_match` | Aucune référence ne correspond. | No reference matches. | Panel, search or filter without result | proposal | | `editor.references.cited_one` / `_other` | citée {count} fois | cited {count} time / times | Each reference card | board text | | `editor.findings.references_open_one` / `_other` | {count} référence / {count} références | {count} reference / references | Finding detail, Citations block, opens the panel filtered | plan wording | + +## Lot E (header history, save line, Abandonner) + +| Key | FR | EN | Where | Status | +|---|---|---|---|---| +| `editor.history.undo` / `undo_title` | Annuler / Annuler la dernière modification | Undo / Undo the last change | Header button (visible label from 640 px; name and title) | T15 | +| `editor.history.redo` / `redo_title` | Rétablir / Rétablir la dernière modification annulée | Redo / Redo the last undone change | Header button | proposal | +| `editor.draft.discard` (relabelled) | Abandonner les modifications | Discard changes | Header button, dialog title; `discard_confirm` unchanged | C11 amended | +| `editor.draft.discard_copy` | La copie locale temporaire de ces modifications sera aussi supprimée. | The temporary local copy of these changes will be deleted too. | Discard confirmation, when a copy is stored | precision 9 | +| `editor.draft.status.unsaved` (reworded) | Modifications non enregistrées | Unsaved changes | Save line when the count is out of reach; status region | plan wording | +| `editor.draft.status.unsaved_count_one` / `_other` | {count} modification non enregistrée / {count} modifications non enregistrées | {count} unsaved change / changes | Save line | plan wording | +| `editor.draft.status.saved_at` | Enregistré à {time} · révision {revision} | Saved at {time} · revision {revision} | Save line, server time known | plan wording | +| `editor.draft.status.saved` | Enregistré · révision {revision} | Saved · revision {revision} | Save line, server time unknown or unreadable | owner wording | + +Removed keys: `editor.annotations.undo`, `editor.annotations.redo` (the tool column's pair moved to the header). diff --git a/apps/app/e2e/lan/trial-lan.spec.ts b/apps/app/e2e/lan/trial-lan.spec.ts index 03b00967..bb0496dc 100644 --- a/apps/app/e2e/lan/trial-lan.spec.ts +++ b/apps/app/e2e/lan/trial-lan.spec.ts @@ -21,12 +21,13 @@ const SVG = '' + '' -const revisionLine = (page: Page) => - page.getByRole('status').filter({ hasText: /^Révision \d+/ }) +const saveLine = (page: Page) => page.getByTestId('save-line') async function revisionShown(page: Page): Promise { - const text = (await revisionLine(page).textContent()) ?? '' - return Number(/Révision (\d+)/.exec(text)?.[1]) + const text = (await saveLine(page).textContent()) ?? '' + return Number( + /révision (\d+)|Révision (\d+)/.exec(text)?.slice(1).find(Boolean), + ) } async function nextCode(secret: string): Promise { @@ -148,7 +149,9 @@ test('trial through the LAN origin: MFA, new sheet, SVG import, save, reload', a await expect(page.getByText(dict['editor.upload.done'])).toBeVisible() const before = await revisionShown(page) await page.getByRole('button', { name: dict['common.save'] }).click() - await expect(revisionLine(page)).toHaveText(`Révision ${before + 1}`) + await expect(saveLine(page)).toHaveText( + new RegExp(`^Enregistré( à \\d\\d:\\d\\d)? · révision ${before + 1}$`), + ) await page.reload() await openViews(page) await expect( diff --git a/apps/app/e2e/shell/editor-annotations.spec.ts b/apps/app/e2e/shell/editor-annotations.spec.ts index 223eff7e..a10d6734 100644 --- a/apps/app/e2e/shell/editor-annotations.spec.ts +++ b/apps/app/e2e/shell/editor-annotations.spec.ts @@ -3,10 +3,12 @@ import type { Page, TestInfo } from '@playwright/test' import { expect, expectAccessible, test } from '../support/browser' import { dropLateReplays, routeToSandbox } from '../support/sandbox' import { - clientOf, clickDrawing, + clientOf, editorActor, geometryField, + historyButton, + pressAtBox, openEditor, pickAnnotation, saveDraft, @@ -128,12 +130,7 @@ test.describe('editor annotations (A3)', () => { await fillCreation(page, { fr: 'Accès un', en: 'Access one' }, 'detail-a') await createFromPanel(page) await expect(selectionTag(page)).toContainText('Accès un') - await expect( - page.getByRole('button', { - name: dict['editor.annotations.undo'], - exact: true, - }), - ).toBeEnabled() + await expect(historyButton(page, dict, 'undo')).toBeEnabled() // A numeric edit of the point, then undo and redo. await pickAnnotation(page, dict, /Point un/) @@ -141,19 +138,12 @@ test.describe('editor annotations (A3)', () => { await cx.fill('420') await cx.press('Enter') await expect(cx).toHaveValue('420') - await page - .getByRole('button', { - name: dict['editor.annotations.undo'], - exact: true, - }) - .click() + await historyButton(page, dict, 'undo').click() await expect(geometryField(page, dict, 'cx')).toHaveValue(placed) - await page - .getByRole('button', { - name: dict['editor.annotations.redo'], - exact: true, - }) - .click() + await historyButton(page, dict, 'redo').click() + await expect(geometryField(page, dict, 'cx')).toHaveValue('420') + // Nothing left to redo: the button is aria-disabled and a press changes nothing. + await pressAtBox(page, historyButton(page, dict, 'redo')) await expect(geometryField(page, dict, 'cx')).toHaveValue('420') await saveDraft(page, dict, seed.revision + 1) diff --git a/apps/app/e2e/shell/editor-journey.spec.ts b/apps/app/e2e/shell/editor-journey.spec.ts index c31a929e..3a9934a2 100644 --- a/apps/app/e2e/shell/editor-journey.spec.ts +++ b/apps/app/e2e/shell/editor-journey.spec.ts @@ -5,24 +5,29 @@ import { stepUpAdmin } from '../support/admin' import { expect, expectAccessible, test } from '../support/browser' import { dropLateReplays, routeToSandbox } from '../support/sandbox' import { - pickAnnotation, - selectionTag, clickDrawing, createFromPanel, creationPanel, editorActor, fillCreation, geometryField, + historyButton, INKSCAPE_EXPORT, openDraft, openSection, + pickAnnotation, place, + revisionText, + savedLine, saveDraft, + saveLine, secondSession, + selectionTag, selectTab, serverDocument, showDrawing, toolButton, + UNSAVED_LINE, } from '../support/editor' import { signIn } from '../support/shell' @@ -236,9 +241,7 @@ async function reloadAndRestore(page: Page, sheetId: string) { ).toBeVisible() expect(page.url()).toContain(sheetId) await clickButton(page, dict['editor.draft.recovery.restore']) - await expect( - page.getByText(dict['editor.draft.status.unsaved'], { exact: false }), - ).toBeVisible() + await expect(saveLine(page)).toHaveText(UNSAVED_LINE) } test.describe('editor journey (owner trial steps)', () => { @@ -272,18 +275,8 @@ test.describe('editor journey (owner trial steps)', () => { await createAnnotations(page) await repairGeometry(page) // Undo and redo the numeric repair path's last creation. - await page - .getByRole('button', { - name: dict['editor.annotations.undo'], - exact: true, - }) - .click() - await page - .getByRole('button', { - name: dict['editor.annotations.redo'], - exact: true, - }) - .click() + await historyButton(page, dict, 'undo').click() + await historyButton(page, dict, 'redo').click() const modified = await modifyAnnotations(page) await expectAccessible(page, 'the editor with annotations') await saveDraft(page, dict, 1) @@ -342,14 +335,7 @@ test.describe('editor journey (owner trial steps)', () => { await expect(conflict).toContainText('révision 3') await clickDialog(conflict, dict['editor.draft.conflict.reload']) await expect(conflict).toBeHidden() - await expect( - page.getByText( - dict['editor.draft.status.revision'].replace('{revision}', '3'), - { - exact: true, - }, - ), - ).toBeVisible() + await expect(saveLine(page)).toHaveText(revisionText(dict, 3)) // The conflict again, resolved by keeping this version after the confirmation. await commitText( @@ -369,14 +355,7 @@ test.describe('editor journey (owner trial steps)', () => { await expect(again).toContainText('Remplacer la révision 4') await clickDialog(again, dict['editor.draft.conflict.keep']) await expect(again).toBeHidden() - await expect( - page.getByText( - dict['editor.draft.status.revision'].replace('{revision}', '5'), - { - exact: true, - }, - ), - ).toBeVisible() + await expect(saveLine(page)).toHaveText(savedLine(dict, 5)) await second.context.close() await selectTab(page, dict, 'verification') diff --git a/apps/app/e2e/shell/editor-recovery.spec.ts b/apps/app/e2e/shell/editor-recovery.spec.ts index 2dc48cf8..8d251b36 100644 --- a/apps/app/e2e/shell/editor-recovery.spec.ts +++ b/apps/app/e2e/shell/editor-recovery.spec.ts @@ -4,7 +4,7 @@ import { rpc } from '../../../../packages/supabase/tests/sandbox/stack' import { expect, expectAccessible, test } from '../support/browser' import { dropLateReplays, routeToSandbox } from '../support/sandbox' import { - place, + type Actor, copyKeyOf, editorActor, expiringEditor, @@ -12,15 +12,18 @@ import { openDraft, openEditor, ownerActor, + place, reloadAccepting, + savedLine, saveDraft, + saveLine, seedDraft, selectTab, serverDocument, serverRevision, standardShape, storedCopy, - type Actor, + UNSAVED_LINE, } from '../support/editor' import { stepUpAdmin } from '../support/admin' import { secondSession } from '../support/editor' @@ -143,9 +146,7 @@ test.describe('editor recovery and concurrency', () => { const seed = await seedDraft(actor, { shape: standardShape }) await openGeneral(page, actor, seed.sheetId) await commitText(nameFr(page), 'Mon travail local') - await expect( - page.getByText(dict['editor.draft.status.unsaved'], { exact: false }), - ).toBeVisible() + await expect(saveLine(page)).toHaveText(UNSAVED_LINE) await advanceServer(actor, seed.draftId, 1) expect(await reloadAccepting(page)).toContain('beforeunload') @@ -168,14 +169,7 @@ test.describe('editor recovery and concurrency', () => { await expect(conflict).toContainText('Remplacer la révision 2') await button(conflict, dict['editor.draft.conflict.keep']).click() await expect(conflict).toBeHidden() - await expect( - page.getByText( - dict['editor.draft.status.revision'].replace('{revision}', '3'), - { - exact: true, - }, - ), - ).toBeVisible() + await expect(saveLine(page)).toHaveText(savedLine(dict, 3)) const saved = await serverDocument<{ name: { fr: string } }>(seed.draftId) expect(saved.name.fr).toBe('Mon travail local') }) diff --git a/apps/app/e2e/shell/editor-shell.spec.ts b/apps/app/e2e/shell/editor-shell.spec.ts index 75c9e3a0..adfbda2f 100644 --- a/apps/app/e2e/shell/editor-shell.spec.ts +++ b/apps/app/e2e/shell/editor-shell.spec.ts @@ -1,5 +1,5 @@ import { fr } from '@/i18n/fr' -import type { Page, TestInfo } from '@playwright/test' +import type { Locator, Page, TestInfo } from '@playwright/test' import { expect, test } from '../support/browser' import { dropLateReplays, routeToSandbox } from '../support/sandbox' import { @@ -17,6 +17,7 @@ import { selectTab, shapeWith, showDrawing, + historyButton, } from '../support/editor' // V1-2.6 U1 B2a: tabs, Annotations sections and the references panel stay mounted. What @@ -39,6 +40,17 @@ async function open(page: Page) { return { ...seed, actor } } +/** The button's centre hits the button itself: no panel or scrim covers it (any state). */ +const hitsItself = (button: Locator) => + button.evaluate((element) => { + const box = element.getBoundingClientRect() + const hit = document.elementFromPoint( + box.x + box.width / 2, + box.y + box.height / 2, + ) + return hit !== null && element.contains(hit) + }) + const active = (page: Page) => page.locator(':focus') const layerTransform = (page: Page) => page @@ -133,6 +145,12 @@ test.describe('editor shell, kept places (B2a)', () => { for (const scrolled of [false, true]) { await page.evaluate((y) => window.scrollTo(0, y), scrolled ? 400 : 0) for (const target of targets) await target.click({ trial: true }) + // « Annuler » / « Rétablir » may be aria-disabled (a trial click would wait). + for (const kind of ['undo', 'redo'] as const) { + const button = historyButton(page, dict, kind) + await button.scrollIntoViewIfNeeded() + expect(await hitsItself(button)).toBe(true) + } const box = await panel.boundingBox() for (const above of [header, tabs]) { const other = await above.boundingBox() diff --git a/apps/app/e2e/shell/editor-structures.spec.ts b/apps/app/e2e/shell/editor-structures.spec.ts index 64a8b758..bca3a8a1 100644 --- a/apps/app/e2e/shell/editor-structures.spec.ts +++ b/apps/app/e2e/shell/editor-structures.spec.ts @@ -8,11 +8,13 @@ import { editorActor, openEditor, openReferences, - place, openSection, pickAnnotation, + place, pointOf, + revisionText, saveDraft, + saveLine, seedDraft, selectTab, serverDocument, @@ -202,6 +204,9 @@ test.describe('editor structures (A4)', () => { await expect( node.getByText(dict['editor.findings.status.reviewed']), ).toBeVisible() + // The tab row (history buttons included) scrolled under the sticky top bar is not a + // target-size finding of its own: audit it from the top. + await page.evaluate(() => window.scrollTo(0, 0)) await expectAccessible(page, 'the findings tree') // Reorder: the new zone moves above the seeded one. @@ -244,9 +249,9 @@ test.describe('editor structures (A4)', () => { await page.reload() await selectTab(page, dict, 'findings') await expect(items.filter({ hasText: 'Catégorie renommée' })).toBeVisible() - await expect( - page.getByText(dict['editor.draft.status.unsaved'], { exact: false }), - ).toHaveCount(0) + await expect(saveLine(page)).toHaveText( + revisionText(dict, seed.revision + 1), + ) await expect( button(page, dict['editor.draft.recovery.restore']), ).toHaveCount(0) diff --git a/apps/app/e2e/support/editor.ts b/apps/app/e2e/support/editor.ts index 06114dbf..b9001960 100644 --- a/apps/app/e2e/support/editor.ts +++ b/apps/app/e2e/support/editor.ts @@ -410,18 +410,54 @@ export async function serverDocument>( ) as T } -/** Saves through « Enregistrer » and waits until the server revision line moves. */ +/** The visible save line (the hidden status region is another element). */ +export const saveLine = (page: Page) => page.getByTestId('save-line') + +const withRevision = (text: string, revision: number) => + text.replace('{revision}', String(revision)) + +/** « Révision n », the line of a draft with nothing saved in this session. */ +export const revisionText = (dict: Dict, revision: number) => + withRevision(dict['editor.draft.status.revision'], revision) + +/** The unsaved line, with or without its count. */ +export const UNSAVED_LINE = /non enregistrée|unsaved/i + +/** « Enregistré · révision n », with or without the server's time of the save. */ +export function savedLine(dict: Dict, revision: number): RegExp { + const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + const plain = escape( + withRevision(dict['editor.draft.status.saved'], revision), + ) + const timed = escape( + withRevision(dict['editor.draft.status.saved_at'], revision), + ) + return new RegExp( + `^(${plain}|${timed.replace('\\{time\\}', '\\d\\d:\\d\\d')})$`, + ) +} + +/** The header « Annuler » / « Rétablir » button (enabled ones take a plain click). */ +export const historyButton = (page: Page, dict: Dict, kind: 'undo' | 'redo') => + page.getByRole('button', { + name: dict[`editor.history.${kind}_title`], + exact: true, + }) + +/** + * Presses a button that may be `aria-disabled` at its box: Playwright's actionability + * treats `aria-disabled` as disabled, a person's pointer does not. + */ +export async function pressAtBox(page: Page, button: Locator) { + const box = await button.boundingBox() + if (!box) throw new Error('the button has no box') + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2) +} + +/** Saves through « Enregistrer » and waits until the save line shows the new revision. */ export async function saveDraft(page: Page, dict: Dict, revision: number) { await page.getByRole('button', { name: dict['common.save'] }).click() - await expect( - page.getByText( - dict['editor.draft.status.revision'].replace( - '{revision}', - String(revision), - ), - { exact: true }, - ), - ).toBeVisible() + await expect(saveLine(page)).toHaveText(savedLine(dict, revision)) } /** Client coordinates of a drawing point, through the overlay's own matrix. */ diff --git a/apps/app/src/components/editor/DiscardButton.tsx b/apps/app/src/components/editor/DiscardButton.tsx new file mode 100644 index 00000000..62564ee2 --- /dev/null +++ b/apps/app/src/components/editor/DiscardButton.tsx @@ -0,0 +1,71 @@ +import { useEffect, useState } from 'react' +import Button from '@/components/ui/Button' +import { useEditorReadOnly } from '@/editor/editingContext' +import { loadFailureMessage } from '@/editor/messages' +import { copyExists } from '@/editor/state/recovery' +import { useEditorStore } from '@/editor/state/editorStore' +import { useT } from '@/i18n/useT' +import ConfirmDialog from './ConfirmDialog' + +/** + * « Abandonner les modifications »: asks first, then the store reloads the server draft. + * The confirmation names the temporary local copy when one is stored at the moment it + * opens (a copy left by an earlier write counts, not only the last write's). + */ +export default function DiscardButton({ + onFailure, +}: { + /** A failed reload after a discard, worded for the notice under the header. */ + onFailure: (message: string | null) => void +}) { + const t = useT() + const unsaved = useEditorStore((s) => s.unsaved) + const saving = useEditorStore((s) => s.saving) + const readOnly = useEditorReadOnly() + const [asking, setAsking] = useState(false) + const [copyNamed, setCopyNamed] = useState(false) + // The editor turned read-only while asking: the confirmation closes without effect. + useEffect(() => { + if (readOnly) setAsking(false) + }, [readOnly]) + const ask = () => { + const { userId, versionId } = useEditorStore.getState() + setCopyNamed(copyExists(userId ?? '', versionId ?? '')) + setAsking(true) + } + const discard = async () => { + setAsking(false) + const result = await useEditorStore + .getState() + .discardChanges({ confirmed: true }) + onFailure( + !result.ok && result.reason === 'load' + ? loadFailureMessage(t, result.failure) + : null, + ) + } + const body = copyNamed + ? `${t('editor.draft.discard_ask')} ${t('editor.draft.discard_copy')}` + : t('editor.draft.discard_ask') + return ( + <> + + void discard()} + onCancel={() => setAsking(false)} + /> + + ) +} diff --git a/apps/app/src/components/editor/EditorGlyph.tsx b/apps/app/src/components/editor/EditorGlyph.tsx new file mode 100644 index 00000000..0dbb8161 --- /dev/null +++ b/apps/app/src/components/editor/EditorGlyph.tsx @@ -0,0 +1,50 @@ +export type GlyphName = + | 'select' + | 'point' + | 'zone' + | 'link' + | 'in' + | 'out' + | 'fit' + | 'undo' + | 'redo' + | 'search' + +/** The editor's one glyph table (24-unit grid strokes); `book` and `close` are in `Icon`. */ +const GLYPHS: Record = { + select: 'M5 3l12 7-5 1-3 5z', + point: 'M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8zM12 3v3M12 18v3M3 12h3M18 12h3', + zone: 'M12 3l8 6-3 10H7L4 9z', + link: 'M4 4h8v8H4zM12 12h8v8h-8z', + in: 'M11 5v12M5 11h12M20 20l-4-4', + out: 'M5 11h12M20 20l-4-4', + fit: 'M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5', + undo: 'M9 7L4 12l5 5M4 12h11a5 5 0 0 1 0 10', + redo: 'M15 7l5 5-5 5M20 12H9a5 5 0 0 0 0 10', + search: 'M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-4-4', +} + +/** A decorative glyph of the editor, drawn in the current text colour. */ +export default function EditorGlyph({ + name, + size = 20, +}: { + name: GlyphName + size?: number +}) { + return ( + + ) +} diff --git a/apps/app/src/components/editor/EditorTabs.tsx b/apps/app/src/components/editor/EditorTabs.tsx index d79c7a07..cf099ca5 100644 --- a/apps/app/src/components/editor/EditorTabs.tsx +++ b/apps/app/src/components/editor/EditorTabs.tsx @@ -10,6 +10,7 @@ import { } from '@/editor/tabs' import type { TabTier } from '@/editor/useViewport' import { useT } from '@/i18n/useT' +import HistoryButtons from './HistoryButtons' const BASE = 'min-h-11 whitespace-nowrap border-b-2 px-3 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]' @@ -143,6 +144,7 @@ interface EditorTabsProps { /** * The draft's tab row (boards 04 and 05): the four tabs from 640 px, Annotations and * Vérification below it with « Plus » opening a disclosure of the others (no measurement). + * « Annuler » and « Rétablir » sit at the right end of the row on every tab. */ export default function EditorTabs({ active, @@ -156,6 +158,7 @@ export default function EditorTabs({ {more.length > 0 && ( )} + ) } diff --git a/apps/app/src/components/editor/HeaderActions.tsx b/apps/app/src/components/editor/HeaderActions.tsx index 9ba8b98a..4f7cc112 100644 --- a/apps/app/src/components/editor/HeaderActions.tsx +++ b/apps/app/src/components/editor/HeaderActions.tsx @@ -1,12 +1,9 @@ -import { useEffect, useState } from 'react' import Button from '@/components/ui/Button' import Icon from '@/components/ui/Icon' -import { useEditorReadOnly } from '@/editor/editingContext' -import { loadFailureMessage } from '@/editor/messages' import { useEditorStore } from '@/editor/state/editorStore' import { REFERENCES_BUTTON_ID } from '@/editor/tabs' import { useT } from '@/i18n/useT' -import ConfirmDialog from './ConfirmDialog' +import DiscardButton from './DiscardButton' import SaveLine from './SaveLine' interface Props { @@ -18,50 +15,6 @@ interface Props { onFailure: (message: string | null) => void } -/** « Abandonner les modifications »: asks first, then the store reloads the server draft. */ -function DiscardButton({ onFailure }: Pick) { - const t = useT() - const unsaved = useEditorStore((s) => s.unsaved) - const saving = useEditorStore((s) => s.saving) - const readOnly = useEditorReadOnly() - const [asking, setAsking] = useState(false) - useEffect(() => { - if (readOnly) setAsking(false) - }, [readOnly]) - const discard = async () => { - setAsking(false) - const result = await useEditorStore - .getState() - .discardChanges({ confirmed: true }) - onFailure( - !result.ok && result.reason === 'load' - ? loadFailureMessage(t, result.failure) - : null, - ) - } - return ( - <> - - void discard()} - onCancel={() => setAsking(false)} - /> - - ) -} - function SaveButton() { const t = useT() const unsaved = useEditorStore((s) => s.unsaved) diff --git a/apps/app/src/components/editor/HistoryButtons.tsx b/apps/app/src/components/editor/HistoryButtons.tsx new file mode 100644 index 00000000..135f985b --- /dev/null +++ b/apps/app/src/components/editor/HistoryButtons.tsx @@ -0,0 +1,93 @@ +import { useRef } from 'react' +import { useEditorReadOnly } from '@/editor/editingContext' +import { commitFocusedField } from '@/editor/focusRequest' +import { canRedo, canUndo, useEditorStore } from '@/editor/state/editorStore' +import { useT } from '@/i18n/useT' +import EditorGlyph from './EditorGlyph' + +type Direction = 'undo' | 'redo' + +const SHORTCUT: Record = { + undo: 'Control+Z', + redo: 'Control+Shift+Z', +} + +const BUTTON = + 'inline-flex min-h-11 min-w-11 items-center justify-center gap-1.5 rounded-md ' + + 'px-2 text-sm text-[var(--color-ink)] hover:bg-[var(--color-surface-strong)] ' + + 'aria-disabled:cursor-not-allowed aria-disabled:opacity-40 aria-disabled:hover:bg-transparent ' + + 'xl:min-h-9 xl:min-w-0 focus-visible:outline-none focus-visible:ring-2 ' + + 'focus-visible:ring-[var(--color-accent)]' + +/** The text field the press left, kept to learn whether its commit was refused. */ +function leavingField(): HTMLElement | null { + const active = document.activeElement + const isField = + active instanceof HTMLInputElement || + active instanceof HTMLTextAreaElement || + active instanceof HTMLSelectElement + return isField ? active : null +} + +/** + * The press, in two steps: the pointer-down commits the typed text (the field's blur), the + * click then reads the store, so the typed text is the last change the undo reverts. A + * field whose commit was refused keeps its error: the step is skipped, focus goes back. + */ +function usePress(direction: Direction, readOnly: boolean) { + const left = useRef(null) + const onPointerDown = () => { + left.current = leavingField() + commitFocusedField() + } + const onClick = () => { + const field = left.current + left.current = null + if (field?.getAttribute('aria-invalid') === 'true') { + field.focus() + return + } + const store = useEditorStore.getState() + const can = direction === 'undo' ? canUndo(store) : canRedo(store) + if (readOnly || !can) return + if (direction === 'undo') store.undoStep() + else store.redoStep() + } + return { onPointerDown, onClick, onPointerLeave: () => (left.current = null) } +} + +function HistoryButton({ direction }: { direction: Direction }) { + const t = useT() + const readOnly = useEditorReadOnly() + const steppable = useEditorStore(direction === 'undo' ? canUndo : canRedo) + const name = t(`editor.history.${direction}_title`) + return ( + + ) +} + +/** « Annuler » and « Rétablir », at the right of the tab row on every tab. */ +export default function HistoryButtons() { + return ( +
+ + +
+ ) +} diff --git a/apps/app/src/components/editor/SaveLine.tsx b/apps/app/src/components/editor/SaveLine.tsx index 92104538..467a904c 100644 --- a/apps/app/src/components/editor/SaveLine.tsx +++ b/apps/app/src/components/editor/SaveLine.tsx @@ -1,39 +1,122 @@ +import { usePlural } from '@/editor/plural' +import { formatParisTime } from '@/editor/format' +import { + saveLineState, + useSavedDistance, + type SaveLineState, +} from '@/editor/saveLine' import { useEditorStore } from '@/editor/state/editorStore' import { useT } from '@/i18n/useT' +import { useLocaleStore } from '@/state/localeStore' type Translate = ReturnType -interface Status { - copyIssue: 'cap' | 'quota' | null - saving: boolean - unsaved: boolean - revision: number +/** Widest figures the line can show: a three-digit revision, 00:00, 999 changes. */ +const WIDEST_REVISION = 999 +const WIDEST_TIME = '00:00' + +function revisionText(t: Translate, key: string, revision: number): string { + return t(key).replace('{revision}', String(revision)) } -/** Board 04's line; only the copy failures replace it (the copy is temporary, this tab's). */ -function statusText(t: Translate, status: Status): string { - if (status.copyIssue !== null) - return t(`editor.draft.status.copy_${status.copyIssue}`) - if (status.saving) return t('editor.draft.status.saving') - const revision = t('editor.draft.status.revision').replace( - '{revision}', - String(status.revision), - ) - return status.unsaved - ? `${revision} · ${t('editor.draft.status.unsaved')}` - : revision +/** The line for a state; `withTime` false gives the form the status region announces. */ +function lineText( + t: Translate, + plural: ReturnType, + state: SaveLineState, + time: string | null, +): string { + switch (state.kind) { + case 'copy_issue': + return t(`editor.draft.status.copy_${state.issue}`) + case 'saving': + return t('editor.draft.status.saving') + case 'unsaved': + return state.count === null + ? t('editor.draft.status.unsaved') + : plural('editor.draft.status.unsaved_count', state.count) + case 'saved': + return time === null + ? revisionText(t, 'editor.draft.status.saved', state.revision) + : revisionText( + t, + 'editor.draft.status.saved_at', + state.revision, + ).replace('{time}', time) + case 'revision': + return revisionText(t, 'editor.draft.status.revision', state.revision) + } } -/** The revision line with its unsaved state, announced politely when it changes. */ +/** What the status region announces: the state, never each change of the count. */ +function announcement(t: Translate, state: SaveLineState): string { + switch (state.kind) { + case 'unsaved': + return t('editor.draft.status.unsaved') + case 'revision': + return '' + case 'saved': + return revisionText(t, 'editor.draft.status.saved', state.revision) + default: + return lineText(t, () => '', state, null) + } +} + +function useSaveLineState(): SaveLineState { + const distance = useSavedDistance() + const copyIssue = useEditorStore((s) => s.copyIssue) + const saving = useEditorStore((s) => s.saving) + const unsaved = useEditorStore((s) => s.unsaved) + const lastSave = useEditorStore((s) => s.lastSave) + const savedRevision = useEditorStore((s) => s.savedRevision) + return saveLineState({ + copyIssue, + saving, + unsaved, + distance, + lastSave, + savedRevision, + }) +} + +/** + * The save line (board 04). The visible line is a plain paragraph; a hidden status region + * announces the state changes. The longest forms are laid out invisibly in the same cell, + * so the line keeps its width when the text changes (tabular figures). + */ export default function SaveLine() { const t = useT() - const unsaved = useEditorStore((s) => s.unsaved) - const saving = useEditorStore((s) => s.saving) - const revision = useEditorStore((s) => s.savedRevision) - const copyIssue = useEditorStore((s) => s.copyIssue) + const plural = usePlural() + const locale = useLocaleStore((s) => s.locale) + const state = useSaveLineState() + const savedAt = state.kind === 'saved' ? state.savedAt : null + const time = savedAt === null ? null : formatParisTime(savedAt, locale) + const widest = [ + revisionText(t, 'editor.draft.status.saved_at', WIDEST_REVISION).replace( + '{time}', + WIDEST_TIME, + ), + plural('editor.draft.status.unsaved_count', 999), + ] return ( -

- {statusText(t, { copyIssue, saving, unsaved, revision })} -

+ <> +

+ + {lineText(t, plural, state, time)} + + {widest.map((text) => ( + + ))} +

+

+ {announcement(t, state)} +

+ ) } diff --git a/apps/app/src/components/editor/annotations/ToolColumn.tsx b/apps/app/src/components/editor/annotations/ToolColumn.tsx index 752154c5..8884049e 100644 --- a/apps/app/src/components/editor/annotations/ToolColumn.tsx +++ b/apps/app/src/components/editor/annotations/ToolColumn.tsx @@ -1,7 +1,7 @@ import type { ReactNode } from 'react' -import { canRedo, canUndo, useEditorStore } from '@/editor/state/editorStore' import type { ToolId } from '@/editor/annotations/uiState' import { useT } from '@/i18n/useT' +import EditorGlyph, { type GlyphName } from '../EditorGlyph' export interface ToolColumnProps { tool: ToolId @@ -21,18 +21,6 @@ const BUTTON = 'focus-visible:outline-none focus-visible:ring-2 ' + 'focus-visible:ring-[var(--color-accent)]' -const GLYPHS: Record = { - select: 'M5 3l12 7-5 1-3 5z', - point: 'M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8zM12 3v3M12 18v3M3 12h3M18 12h3', - zone: 'M12 3l8 6-3 10H7L4 9z', - link: 'M4 4h8v8H4zM12 12h8v8h-8z', - in: 'M11 5v12M5 11h12M20 20l-4-4', - out: 'M5 11h12M20 20l-4-4', - fit: 'M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5', - undo: 'M9 7L4 12l5 5M4 12h11a5 5 0 0 1 0 10', - redo: 'M15 7l5 5-5 5M20 12H9a5 5 0 0 0 0 10', -} - function ToolButton({ glyph, label, @@ -40,7 +28,7 @@ function ToolButton({ disabled, onClick, }: { - glyph: string + glyph: GlyphName label: string pressed?: boolean disabled?: boolean @@ -60,28 +48,14 @@ function ToolButton({ : 'bg-[var(--color-surface)] text-[var(--color-ink)]' }`} > - + ) } -/** Board 04's tool column: tools, zoom, then undo and redo (icon buttons). */ +/** Board 04's tool column: tools and zoom (the history sits in the header). */ export default function ToolColumn(props: ToolColumnProps) { const t = useT() - const undoable = useEditorStore(canUndo) - const redoable = useEditorStore(canRedo) const tool = (id: ToolId, disabled: boolean) => ( -
- useEditorStore.getState().undoStep()} - /> - useEditorStore.getState().redoStep()} - /> ) } diff --git a/apps/app/src/editor/saveLine.ts b/apps/app/src/editor/saveLine.ts new file mode 100644 index 00000000..aa3e8b94 --- /dev/null +++ b/apps/app/src/editor/saveLine.ts @@ -0,0 +1,75 @@ +import { useMemo } from 'react' +import { useEditorStore } from './state/editorStore' +import type { CopyIssue, EditorData, LastSave } from './state/editorTypes' +import type { HistoryEntry } from './state/undo' + +type DistanceInput = Pick< + EditorData, + 'staleBase' | 'documentText' | 'savedText' | 'undo' | 'redo' +> + +/** The 1-based depth, from the stack's top, of the nearest entry holding `text`. */ +function depthIn(stack: readonly HistoryEntry[], text: string): number | null { + for (let at = stack.length - 1; at >= 0; at -= 1) { + if (stack[at].text === text) return stack.length - at + } + return null +} + +/** + * How many history steps separate the document from the saved text: 0 when they are the + * same text, the depth of the nearest undo entry (else redo entry) holding the saved text, + * null when it is out of reach (older base, trimmed, or replaced by a later change). + */ +export function savedDistance(state: DistanceInput): number | null { + if (state.staleBase) return null + if (state.documentText === state.savedText) return 0 + return ( + depthIn(state.undo, state.savedText) ?? depthIn(state.redo, state.savedText) + ) +} + +/** `savedDistance`, recomputed only when one of its four inputs changes identity. */ +export function useSavedDistance(): number | null { + const staleBase = useEditorStore((s) => s.staleBase) + const documentText = useEditorStore((s) => s.documentText) + const savedText = useEditorStore((s) => s.savedText) + const undo = useEditorStore((s) => s.undo) + const redo = useEditorStore((s) => s.redo) + return useMemo( + () => savedDistance({ staleBase, documentText, savedText, undo, redo }), + [staleBase, documentText, savedText, undo, redo], + ) +} + +export interface SaveLineInput { + copyIssue: CopyIssue | null + saving: boolean + unsaved: boolean + distance: number | null + lastSave: LastSave | null + savedRevision: number +} + +export type SaveLineState = + | { kind: 'copy_issue'; issue: CopyIssue } + | { kind: 'saving' } + | { kind: 'unsaved'; count: number | null } + | { kind: 'saved'; revision: number; savedAt: string | null } + | { kind: 'revision'; revision: number } + +/** What the save line says, the first matching form wins. */ +export function saveLineState(input: SaveLineInput): SaveLineState { + if (input.copyIssue !== null) + return { kind: 'copy_issue', issue: input.copyIssue } + if (input.saving) return { kind: 'saving' } + if (input.unsaved) { + const known = input.distance !== null && input.distance > 0 + return { kind: 'unsaved', count: known ? input.distance : null } + } + const { lastSave, savedRevision } = input + if (lastSave && lastSave.revision === savedRevision) { + return { kind: 'saved', revision: savedRevision, savedAt: lastSave.savedAt } + } + return { kind: 'revision', revision: savedRevision } +} diff --git a/apps/app/src/editor/state/editorBase.ts b/apps/app/src/editor/state/editorBase.ts index ce519540..9916c591 100644 --- a/apps/app/src/editor/state/editorBase.ts +++ b/apps/app/src/editor/state/editorBase.ts @@ -26,6 +26,7 @@ export function initialData(): EditorData { submitting: false, reloading: false, saveFailure: null, + lastSave: null, conflict: null, recovery: 'none', offer: null, diff --git a/apps/app/src/editor/state/editorLoad.ts b/apps/app/src/editor/state/editorLoad.ts index 2cca58ce..838265c9 100644 --- a/apps/app/src/editor/state/editorLoad.ts +++ b/apps/app/src/editor/state/editorLoad.ts @@ -144,6 +144,7 @@ function reloadPatch(state: EditorState, text: string, next: PreviewState, revis handleVersion: state.handleVersion + 1, ...emptyHistory(), saveFailure: null, + lastSave: null, conflict: null, copyWritten: false, copyIssue: null, diff --git a/apps/app/src/editor/state/editorSave.ts b/apps/app/src/editor/state/editorSave.ts index d97a995c..0588bf73 100644 --- a/apps/app/src/editor/state/editorSave.ts +++ b/apps/app/src/editor/state/editorSave.ts @@ -70,6 +70,37 @@ export async function readConflict(api: StoreApi, session: number): Promise { + const asked = api.get().lastSave + try { + const admin = await getOfficialSheetAdmin(requireClient(), api.get().sheetId ?? '') + const state = api.get() + if (state.session !== session || state.lastSave !== asked) return + const savedAt = savedTimeOf(admin, state, revision) + if (savedAt !== null) api.set({ lastSave: { revision, savedAt } }) + } catch { + // Unreadable: the line stays « Enregistré · révision n ». + } +} + interface Attempt { session: number sentText: string @@ -89,6 +120,7 @@ function applySaved(api: StoreApi, attempt: Attempt, revision: number): SaveOutc unsaved, conflict: null, saveFailure: null, + lastSave: { revision, savedAt: null }, ...(unsaved ? {} : { copyWritten: false, copyIssue: null }), }) return { ok: true, revision } @@ -127,7 +159,9 @@ async function saveWith(api: StoreApi, expected: number): Promise { document: JSON.parse(attempt.sentText), } const answer = parseSaveAnswer(await saveSheetDraft(requireClient(), args)) - return applySaved(api, attempt, answer.revision) + const outcome = applySaved(api, attempt, answer.revision) + if (outcome.ok) void readSaveTime(api, attempt.session, outcome.revision) + return outcome } catch (error) { return failedSave(api, attempt, error) } diff --git a/apps/app/src/editor/state/editorTypes.ts b/apps/app/src/editor/state/editorTypes.ts index f5f9c8e9..4d5f3d2d 100644 --- a/apps/app/src/editor/state/editorTypes.ts +++ b/apps/app/src/editor/state/editorTypes.ts @@ -87,6 +87,15 @@ export type ConflictState = export type CopyIssue = 'cap' | 'quota' +/** + * The last save the server confirmed: its revision, and the server's time of that save once + * read (null when unreadable, never the browser's clock). + */ +export interface LastSave { + revision: number + savedAt: string | null +} + export interface EditorData { /** Session token: bumped by `open` and `close`; every async continuation checks it. */ session: number @@ -115,6 +124,7 @@ export interface EditorData { submitting: boolean reloading: boolean saveFailure: SheetFailureKind | null + lastSave: LastSave | null conflict: ConflictState | null recovery: RecoveryMode offer: RecoveryOffer | null diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index 7f14b08e..fbf115ef 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -1241,10 +1241,19 @@ export const en: Dict = { 'editor.draft.title': 'Draft, version {number}', 'editor.draft.read_only': 'Read-only', 'editor.draft.discard': 'Discard changes', + 'editor.draft.discard_copy': 'The temporary local copy of these changes will be deleted too.', 'editor.draft.discard_ask': 'Discard the unsaved changes? The draft will return to the last revision saved on the server.', 'editor.draft.discard_confirm': 'Discard changes', 'editor.draft.status.revision': 'Revision {revision}', - 'editor.draft.status.unsaved': 'unsaved changes', + 'editor.draft.status.unsaved': 'Unsaved changes', + 'editor.draft.status.unsaved_count_one': '{count} unsaved change', + 'editor.draft.status.unsaved_count_other': '{count} unsaved changes', + 'editor.draft.status.saved': 'Saved · revision {revision}', + 'editor.draft.status.saved_at': 'Saved at {time} · revision {revision}', + 'editor.history.undo': 'Undo', + 'editor.history.undo_title': 'Undo the last change', + 'editor.history.redo': 'Redo', + 'editor.history.redo_title': 'Redo the last undone change', 'editor.draft.status.saving': 'Saving…', 'editor.draft.status.copy_quota': "Temporary local copy impossible (tab full): not saved on the server", 'editor.draft.status.copy_cap': "Temporary local copy impossible (two other copies in this tab): not saved on the server", @@ -1509,8 +1518,6 @@ export const en: Dict = { 'editor.annotations.tool.point': 'Point', 'editor.annotations.tool.zone': 'Zone', 'editor.annotations.tool.link': 'Link to a detail view', - 'editor.annotations.undo': 'Undo', - 'editor.annotations.redo': 'Redo', 'editor.annotations.tool_hint.select': 'Tool: select and move · Esc cancels a tracing', 'editor.annotations.tool_hint.point': 'Tool: point · click in the drawing to place a point.', 'editor.annotations.tool_hint.zone': 'Tool: zone · click to place the vertices; Enter or « Close the tracing » finishes, Esc cancels.', diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index 78464729..2c6bb892 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -1271,11 +1271,20 @@ export const fr: Dict = { 'editor.draft.overview_link': 'Voir la fiche', 'editor.draft.title': 'Brouillon, version {number}', 'editor.draft.read_only': 'Lecture seule', - 'editor.draft.discard': 'Annuler les modifications', + 'editor.draft.discard': 'Abandonner les modifications', + 'editor.draft.discard_copy': 'La copie locale temporaire de ces modifications sera aussi supprimée.', 'editor.draft.discard_ask': 'Abandonner les modifications non enregistrées ? Le brouillon reprendra la dernière révision enregistrée sur le serveur.', 'editor.draft.discard_confirm': 'Abandonner les modifications', 'editor.draft.status.revision': 'Révision {revision}', - 'editor.draft.status.unsaved': 'modifications non enregistrées', + 'editor.draft.status.unsaved': 'Modifications non enregistrées', + 'editor.draft.status.unsaved_count_one': '{count} modification non enregistrée', + 'editor.draft.status.unsaved_count_other': '{count} modifications non enregistrées', + 'editor.draft.status.saved': 'Enregistré · révision {revision}', + 'editor.draft.status.saved_at': 'Enregistré à {time} · révision {revision}', + 'editor.history.undo': 'Annuler', + 'editor.history.undo_title': 'Annuler la dernière modification', + 'editor.history.redo': 'Rétablir', + 'editor.history.redo_title': 'Rétablir la dernière modification annulée', 'editor.draft.status.saving': 'Enregistrement…', 'editor.draft.status.copy_quota': "Copie locale temporaire impossible (onglet plein) : non enregistré sur le serveur", 'editor.draft.status.copy_cap': "Copie locale temporaire impossible (deux autres copies dans cet onglet) : non enregistré sur le serveur", @@ -1540,8 +1549,6 @@ export const fr: Dict = { 'editor.annotations.tool.point': 'Point', 'editor.annotations.tool.zone': 'Zone', 'editor.annotations.tool.link': 'Accès à une vue détaillée', - 'editor.annotations.undo': 'Annuler', - 'editor.annotations.redo': 'Rétablir', 'editor.annotations.tool_hint.select': 'Outil : sélectionner et déplacer · Échap annule un tracé', 'editor.annotations.tool_hint.point': 'Outil : point · cliquez dans le dessin pour placer un point.', 'editor.annotations.tool_hint.zone': 'Outil : zone · cliquez pour poser les sommets ; Entrée ou « Fermer le tracé » termine, Échap annule.', diff --git a/apps/app/tests/unit/editor-annotations-tab.test.tsx b/apps/app/tests/unit/editor-annotations-tab.test.tsx index 2ded0204..91260c2c 100644 --- a/apps/app/tests/unit/editor-annotations-tab.test.tsx +++ b/apps/app/tests/unit/editor-annotations-tab.test.tsx @@ -507,19 +507,12 @@ describe('tools and categories', () => { ).toBeDisabled() }) - it('undoes and redoes through the tool column', async () => { + it('keeps no undo or redo in the tool column (they sit in the header)', async () => { await mount() - await selectFromList() - const user = userEvent.setup() - const cx = within( - screen.getByTestId('annotation-properties'), - ).getByLabelText('Centre x') - await user.clear(cx) - await user.type(cx, '60{Enter}') - await user.click(screen.getByRole('button', { name: 'Annuler' })) - expect(geometryOf('anno-a')).toMatchObject({ cx: 50 }) - await user.click(screen.getByRole('button', { name: 'Rétablir' })) - expect(geometryOf('anno-a')).toMatchObject({ cx: 60 }) + const tools = screen.getByRole('toolbar', { name: 'Outils' }) + expect( + within(tools).queryByRole('button', { name: /Annuler|Rétablir/ }), + ).toBeNull() }) }) diff --git a/apps/app/tests/unit/editor-history-buttons.test.tsx b/apps/app/tests/unit/editor-history-buttons.test.tsx new file mode 100644 index 00000000..e7ead655 --- /dev/null +++ b/apps/app/tests/unit/editor-history-buttons.test.tsx @@ -0,0 +1,389 @@ +/** Lot E: the header « Annuler » / « Rétablir », the save line's announcements, discard. */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + act, + cleanup, + fireEvent, + screen, + waitFor, + within, +} from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { fr } from '@/i18n/fr' +import { + baseText, + commitMove, + resetStore, + sb, + serverHas, + storedCopy, + store, +} from '../helpers/editorHarness' +import { + adminAnswer, + grant, + mountDraft, + round, + setWidth, +} from '../helpers/editorRoute' + +vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) })) +vi.mock('@faunosteo/supabase', async (orig) => ({ + ...(await orig()), + getSheetVersion: vi.fn(), + downloadSheetDrawing: vi.fn(), + saveSheetDraft: vi.fn(), + getOfficialSheetAdmin: vi.fn(), + submitSheetReview: vi.fn(), +})) + +beforeEach(() => serverHas(baseText(), 3)) +afterEach(() => { + cleanup() + resetStore() + setWidth(1024) +}) + +const UNDO = 'Annuler la dernière modification' +const REDO = 'Rétablir la dernière modification annulée' +const ready = () => + screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' }) +const undoButton = () => screen.getByRole('button', { name: UNDO }) +const redoButton = () => screen.getByRole('button', { name: REDO }) +const disabled = (button: HTMLElement) => + button.getAttribute('aria-disabled') === 'true' +const geometry = () => + store.getState().previewState?.document.annotations[0].geometry +const nameFr = () => + store.getState().previewState?.document.annotations[0].name?.fr + +async function selectAnnotation(user: ReturnType) { + const list = await screen.findByRole('list', { + name: 'Annotations de la vue', + }) + await user.click(within(list).getAllByRole('button')[0]) + const panel = await screen.findByTestId('annotation-properties') + return within(panel).getByLabelText('Nom (FR)') as HTMLInputElement +} + +describe('the buttons', () => { + it('have the T15 names, titles, shortcuts and a visible label', async () => { + mountDraft() + await ready() + const row = within(screen.getByTestId('history-buttons')) + expect(undoButton()).toHaveAttribute('title', UNDO) + expect(redoButton()).toHaveAttribute('title', REDO) + expect(undoButton()).toHaveAttribute('aria-keyshortcuts', 'Control+Z') + expect(redoButton()).toHaveAttribute('aria-keyshortcuts', 'Control+Shift+Z') + expect(row.getAllByRole('button').map((b) => b.textContent)).toEqual([ + 'Annuler', + 'Rétablir', + ]) + expect(undoButton()).not.toHaveAttribute('disabled') + }) + + it('are enabled exactly when the store can step, and step', async () => { + const user = userEvent.setup() + mountDraft() + await ready() + expect([disabled(undoButton()), disabled(redoButton())]).toEqual([ + true, + true, + ]) + act(() => void commitMove(40)) + expect([disabled(undoButton()), disabled(redoButton())]).toEqual([ + false, + true, + ]) + await user.click(undoButton()) + expect(geometry()).toMatchObject({ cx: 50 }) + expect([disabled(undoButton()), disabled(redoButton())]).toEqual([ + true, + false, + ]) + await user.click(redoButton()) + expect(geometry()).toMatchObject({ cx: 40 }) + }) + + it('stay focused when the last undo empties the stack', async () => { + const user = userEvent.setup() + mountDraft() + await ready() + act(() => void commitMove(40)) + await user.click(undoButton()) + expect(disabled(undoButton())).toBe(true) + expect(undoButton()).toHaveFocus() + }) + + it('are disabled in every mode that cannot edit', async () => { + const modes: Array<[string, Parameters[0]]> = [ + ['narrow', { width: 800 }], + ['rights', { grants: [grant('sheet_reviewer')], roles: [] }], + ['frozen', { answer: adminAnswer({ rounds: [round('open')] }) }], + ['historical', { answer: adminAnswer({ historical: true }) }], + ['inactive', { answer: adminAnswer({ status: 'archived' }) }], + ] + for (const [, options] of modes) { + serverHas(baseText(), 3) + const view = mountDraft(options) + await ready() + store.setState({ undo: [{ text: baseText(), bytes: 1 }] }) + expect(disabled(undoButton())).toBe(true) + await userEvent.setup().click(undoButton()) + expect(store.getState().undo).toHaveLength(1) + view.unmount() + cleanup() + resetStore() + } + }) + + it('are disabled while a recovery decision is pending', async () => { + mountDraft() + await ready() + act(() => void commitMove(40)) + act(() => store.setState({ recovery: 'pending' })) + expect(disabled(undoButton())).toBe(true) + }) + + it('stay enabled while saving, in step with Ctrl+Z', async () => { + const user = userEvent.setup() + sb.saveSheetDraft.mockReturnValue(new Promise(() => undefined) as never) + mountDraft() + await ready() + act(() => void commitMove(40)) + await user.click(screen.getByRole('button', { name: 'Enregistrer' })) + await waitFor(() => expect(store.getState().saving).toBe(true)) + expect(disabled(undoButton())).toBe(false) + fireEvent.keyDown(document.body, { key: 'z', ctrlKey: true }) + expect(geometry()).toMatchObject({ cx: 50 }) + expect(store.getState().redo).toHaveLength(1) + await user.click(redoButton()) + expect(geometry()).toMatchObject({ cx: 40 }) + }) + + it('undo from Général and from Constats reverts a canvas change', async () => { + const user = userEvent.setup() + mountDraft() + await ready() + act(() => void commitMove(40)) + await user.click(screen.getByRole('tab', { name: 'Général' })) + await user.click(undoButton()) + expect(geometry()).toMatchObject({ cx: 50 }) + await user.click(redoButton()) + await user.click(screen.getByRole('tab', { name: 'Constats' })) + await user.click(undoButton()) + expect(geometry()).toMatchObject({ cx: 50 }) + }) + + it('leave no undo or redo pair in the tool column', async () => { + mountDraft() + await ready() + const tools = screen.getByRole('toolbar', { + name: fr['editor.annotations.tools'], + }) + expect( + within(tools).queryByRole('button', { name: /Annuler|Rétablir/ }), + ).toBeNull() + }) +}) + +describe('typed text and the press', () => { + it('undo reverts exactly the typed text, with and without earlier history', async () => { + const user = userEvent.setup() + mountDraft() + await ready() + const field = await selectAnnotation(user) + const original = nameFr() + await user.clear(field) + await user.type(field, 'Nouveau') + await user.pointer({ keys: '[MouseLeft]', target: undoButton() }) + expect(nameFr()).toBe(original) + expect(store.getState().redo).toHaveLength(1) + act(() => void commitMove(40)) + await user.clear(field) + await user.type(field, 'Encore') + await user.pointer({ keys: '[MouseLeft]', target: undoButton() }) + expect(nameFr()).toBe(original) + expect(geometry()).toMatchObject({ cx: 40 }) + }) + + it('the pointer press blurs the focused field', async () => { + const user = userEvent.setup() + mountDraft() + await ready() + const field = await selectAnnotation(user) + await user.clear(field) + await user.type(field, 'Saisie') + fireEvent.pointerDown(undoButton()) + expect(field).not.toHaveFocus() + expect(nameFr()).toBe('Saisie') + }) + + it('a refused blur commit skips the undo and returns focus to the field', async () => { + const user = userEvent.setup() + mountDraft() + await ready() + act(() => void commitMove(40)) + const field = await selectAnnotation(user) + await user.clear(field) + await user.pointer({ keys: '[MouseLeft]', target: undoButton() }) + expect(field).toHaveAttribute('aria-invalid', 'true') + expect(field).toHaveFocus() + expect(geometry()).toMatchObject({ cx: 40 }) + }) + + it('Ctrl+Z inside a field leaves the store untouched', async () => { + mountDraft() + await ready() + act(() => void commitMove(40)) + const before = store.getState().documentText + fireEvent.keyDown(document.querySelector('input') as Element, { + key: 'z', + ctrlKey: true, + }) + expect(store.getState().documentText).toBe(before) + }) +}) + +describe('the save status', () => { + it('announces state transitions, never each count', async () => { + const user = userEvent.setup() + sb.saveSheetDraft.mockResolvedValue({ revision: 4 } as never) + mountDraft() + await ready() + const status = screen.getByTestId('save-status') + expect(status).toHaveTextContent(/^$/) + act(() => void commitMove(40)) + expect(status).toHaveTextContent(/^Modifications non enregistrées$/) + act(() => void commitMove(41)) + expect(status).toHaveTextContent(/^Modifications non enregistrées$/) + expect(screen.getByTestId('save-line')).toHaveTextContent( + /^2 modifications non enregistrées$/, + ) + await user.click(screen.getByRole('button', { name: 'Enregistrer' })) + await waitFor(() => + expect(status).toHaveTextContent(/^Enregistré · révision 4$/), + ) + }) + + it('shows the server time once read, « Enregistré · révision n » otherwise', async () => { + const user = userEvent.setup() + sb.saveSheetDraft.mockResolvedValue({ revision: 4 } as never) + mountDraft() + await ready() + act(() => void commitMove(40)) + sb.getOfficialSheetAdmin.mockResolvedValue( + adminAnswer({ + draft_version: { version_id: 'ver-1', version_number: 4, revision: 4 }, + draft_last_save: { + revision: 4, + saved_at: '2026-11-04T13:32:00Z', + saved_by: null, + }, + }) as never, + ) + await user.click(screen.getByRole('button', { name: 'Enregistrer' })) + await waitFor(() => + expect(screen.getByTestId('save-line')).toHaveTextContent( + /^Enregistré à 14:32 · révision 4$/, + ), + ) + }) + + it('shows « Enregistré · révision n » when the read fails, editor still mounted', async () => { + const user = userEvent.setup() + sb.saveSheetDraft.mockResolvedValue({ revision: 4 } as never) + mountDraft() + await ready() + act(() => void commitMove(40)) + sb.getOfficialSheetAdmin.mockRejectedValue(new Error('offline')) + await user.click(screen.getByRole('button', { name: 'Enregistrer' })) + await waitFor(() => + expect(screen.getByTestId('save-line')).toHaveTextContent( + /^Enregistré · révision 4$/, + ), + ) + expect(screen.getByRole('heading', { level: 1 })).toBeInTheDocument() + }) + + it('shows no saved line while the save is in flight', async () => { + const user = userEvent.setup() + sb.saveSheetDraft.mockReturnValue(new Promise(() => undefined) as never) + mountDraft() + await ready() + act(() => void commitMove(40)) + await user.click(screen.getByRole('button', { name: 'Enregistrer' })) + expect(screen.getByTestId('save-line')).toHaveTextContent( + /^Enregistrement…$/, + ) + }) + + it('reserves its widest form so the row does not move', async () => { + mountDraft() + await ready() + const sizers = screen + .getByTestId('save-line') + .parentElement!.querySelectorAll('[aria-hidden]') + expect([...sizers].map((el) => el.textContent)).toEqual([ + 'Enregistré à 00:00 · révision 999', + '999 modifications non enregistrées', + ]) + }) +}) + +describe('« Abandonner les modifications »', () => { + const open = async (user: ReturnType) => { + await user.click( + screen.getByRole('button', { name: 'Abandonner les modifications' }), + ) + return within(await screen.findByRole('dialog')) + } + + it('names the stored copy, and keeps changes and copy on cancel', async () => { + const user = userEvent.setup() + mountDraft() + await ready() + act(() => void commitMove(40)) + const dialog = await open(user) + expect( + dialog.getByText(new RegExp(fr['editor.draft.discard_copy'])), + ).toBeInTheDocument() + await user.click(dialog.getByRole('button', { name: 'Annuler' })) + expect(store.getState().unsaved).toBe(true) + expect(storedCopy()).not.toBeNull() + }) + + it('names a copy left by an earlier write after a quota refusal', async () => { + const user = userEvent.setup() + mountDraft() + await ready() + act(() => void commitMove(40)) + expect(storedCopy()).not.toBeNull() + vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => { + throw new DOMException('full', 'QuotaExceededError') + }) + act(() => void commitMove(41)) + await waitFor(() => expect(store.getState().copyIssue).toBe('quota')) + const dialog = await open(user) + expect( + dialog.getByText(new RegExp(fr['editor.draft.discard_copy'])), + ).toBeInTheDocument() + }) + + it('does not mention a copy when none is stored', async () => { + const user = userEvent.setup() + vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => { + throw new DOMException('full', 'QuotaExceededError') + }) + mountDraft() + await ready() + act(() => void commitMove(40)) + const dialog = await open(user) + expect(dialog.getByText(fr['editor.draft.discard_ask'])).toBeInTheDocument() + expect( + dialog.queryByText(new RegExp(fr['editor.draft.discard_copy'])), + ).toBeNull() + }) +}) diff --git a/apps/app/tests/unit/editor-no-loss.test.tsx b/apps/app/tests/unit/editor-no-loss.test.tsx index 91f084e8..135d51db 100644 --- a/apps/app/tests/unit/editor-no-loss.test.tsx +++ b/apps/app/tests/unit/editor-no-loss.test.tsx @@ -314,7 +314,7 @@ describe('the guards of a width change', () => { element: point('anno-a', 60, 50, 5), }), ) - await user.click(button('Annuler les modifications')) + await user.click(button('Abandonner les modifications')) expect(document.querySelectorAll('dialog[open]')).toHaveLength(1) act(() => store.setState({ recovery: 'pending' })) await waitFor(() => diff --git a/apps/app/tests/unit/editor-route-conflict.test.tsx b/apps/app/tests/unit/editor-route-conflict.test.tsx index 9f397e0b..1d119499 100644 --- a/apps/app/tests/unit/editor-route-conflict.test.tsx +++ b/apps/app/tests/unit/editor-route-conflict.test.tsx @@ -97,7 +97,9 @@ describe('known revision', () => { expect.objectContaining({ expected_revision: 5 }), ) await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) - expect(await screen.findByText('Révision 6')).toBeInTheDocument() + await waitFor(() => + expect(screen.getByTestId('save-line')).toHaveTextContent(/^Enregistré · révision 6$/), + ) }) it('saved by the caller: the neutral own-account wording', async () => { @@ -137,7 +139,9 @@ describe('known revision', () => { await user.click(dialog.getByRole('button', { name: 'Recharger' })) await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) expect(store.getState()).toMatchObject({ unsaved: false, savedRevision: 5 }) - expect(await screen.findByText('Révision 5')).toBeInTheDocument() + await waitFor(() => + expect(screen.getByTestId('save-line')).toHaveTextContent(/^Révision 5$/), + ) }) it('Annuler leaves everything as it was', async () => { diff --git a/apps/app/tests/unit/editor-route-recovery.test.tsx b/apps/app/tests/unit/editor-route-recovery.test.tsx index f0ba5d92..ce402666 100644 --- a/apps/app/tests/unit/editor-route-recovery.test.tsx +++ b/apps/app/tests/unit/editor-route-recovery.test.tsx @@ -121,9 +121,9 @@ describe('the blocking offer', () => { mountDraft() await ready() await user.click(screen.getByRole('button', { name: 'Restaurer la copie' })) - expect( - await screen.findByText('Révision 3 · modifications non enregistrées'), - ).toBeInTheDocument() + await waitFor(() => + expect(screen.getByTestId('save-line')).toHaveTextContent(/^Modifications non enregistrées$/), + ) expect( screen.queryByRole('button', { name: 'Restaurer la copie' }), ).toBeNull() @@ -231,9 +231,9 @@ describe('cap and quota', () => { mountDraft() await ready() act(() => void commitMove(40)) - expect( - await screen.findByText(fr['editor.draft.status.copy_cap']), - ).toBeInTheDocument() + await waitFor(() => + expect(screen.getByTestId('save-line')).toHaveTextContent(fr['editor.draft.status.copy_cap']), + ) expect(storedCopy()).toBeNull() const items = screen .getAllByRole('listitem') @@ -256,7 +256,9 @@ describe('cap and quota', () => { await waitFor(() => expect(storedCopy()).not.toBeNull()) expect(sessionStorage.getItem(copyKeyOf('ver-2'))).toBeNull() expect(sessionStorage.getItem(copyKeyOf('ver-3'))).not.toBeNull() - expect(screen.queryByText(fr['editor.draft.status.copy_cap'])).toBeNull() + expect(screen.getByTestId('save-line')).not.toHaveTextContent( + fr['editor.draft.status.copy_cap'], + ) }) it('quota: the full-storage status and notice, the other copies untouched', async () => { @@ -267,9 +269,9 @@ describe('cap and quota', () => { mountDraft() await ready() act(() => void commitMove(40)) - expect( - await screen.findByText(fr['editor.draft.status.copy_quota']), - ).toBeInTheDocument() + await waitFor(() => + expect(screen.getByTestId('save-line')).toHaveTextContent(fr['editor.draft.status.copy_quota']), + ) expect( screen.getByText(fr['editor.draft.copy_issue.quota']), ).toBeInTheDocument() diff --git a/apps/app/tests/unit/editor-route.test.tsx b/apps/app/tests/unit/editor-route.test.tsx index a6919593..90149827 100644 --- a/apps/app/tests/unit/editor-route.test.tsx +++ b/apps/app/tests/unit/editor-route.test.tsx @@ -51,8 +51,7 @@ describe('edit mode', () => { await ready() expect(screen.getByText('Brouillon')).toBeInTheDocument() expect(screen.getByText('Copie de travail')).toBeInTheDocument() - expect(screen.getByRole('status', { name: '' })).toBeDefined() - expect(screen.getByText('Révision 3')).toBeInTheDocument() + expect(screen.getByTestId('save-line')).toHaveTextContent(/^Révision 3$/) const tabs = within(screen.getByRole('tablist')).getAllByRole('tab') expect(tabs.map((tab) => tab.textContent)).toEqual(TABS) expect(screen.getByRole('tab', { name: 'Annotations' })).toHaveAttribute( @@ -81,11 +80,13 @@ describe('edit mode', () => { mountDraft() await ready() act(() => void commitMove(40)) - expect( - await screen.findByText('Révision 3 · modifications non enregistrées'), - ).toBeInTheDocument() + await waitFor(() => + expect(screen.getByTestId('save-line')).toHaveTextContent(/^1 modification non enregistrée$/), + ) await user.click(screen.getByRole('button', { name: 'Enregistrer' })) - expect(await screen.findByText('Révision 4')).toBeInTheDocument() + await waitFor(() => + expect(screen.getByTestId('save-line')).toHaveTextContent(/^Enregistré · révision 4$/), + ) expect(sb.saveSheetDraft).toHaveBeenCalledWith( expect.anything(), expect.objectContaining({ version_id: VERSION, expected_revision: 3 }), @@ -93,21 +94,25 @@ describe('edit mode', () => { expect(storedCopy()).toBeNull() }) - it('« Annuler les modifications » asks first, then reloads the server draft', async () => { + it('« Abandonner les modifications » asks first, then reloads the server draft', async () => { const user = userEvent.setup() mountDraft() await ready() act(() => void commitMove(40)) await user.click( - await screen.findByRole('button', { name: 'Annuler les modifications' }), + await screen.findByRole('button', { name: 'Abandonner les modifications' }), ) - const dialog = within(await screen.findByRole('dialog')) - expect(dialog.getByText(fr['editor.draft.discard_ask'])).toBeInTheDocument() + const asked = await screen.findByRole('dialog') + expect(asked).toHaveTextContent(fr['editor.draft.discard_ask']) + expect(asked).toHaveTextContent(fr['editor.draft.discard_copy']) + const dialog = within(asked) await user.click( dialog.getByRole('button', { name: 'Abandonner les modifications' }), ) await waitFor(() => expect(store.getState().unsaved).toBe(false)) - expect(await screen.findByText('Révision 3')).toBeInTheDocument() + await waitFor(() => + expect(screen.getByTestId('save-line')).toHaveTextContent(/^Révision 3$/), + ) }) }) @@ -418,9 +423,9 @@ describe('permission lost during the session', () => { mountDraft() await ready() act(() => void commitMove(40)) - expect( - await screen.findByText(fr['editor.draft.status.copy_quota']), - ).toBeInTheDocument() + await waitFor(() => + expect(screen.getByTestId('save-line')).toHaveTextContent(fr['editor.draft.status.copy_quota']), + ) await user.click(screen.getByRole('button', { name: 'Enregistrer' })) const notice = await screen.findByText(/Votre session a expiré/) expect(notice).toHaveTextContent(fr['editor.draft.copy_not_kept']) diff --git a/apps/app/tests/unit/editor-save-line.test.ts b/apps/app/tests/unit/editor-save-line.test.ts new file mode 100644 index 00000000..66fefef1 --- /dev/null +++ b/apps/app/tests/unit/editor-save-line.test.ts @@ -0,0 +1,367 @@ +/** Lot E: the unsaved-count selector, the save line's forms and the server save time. */ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { SheetFailure } from '@faunosteo/supabase' +import { saveLineState, savedDistance } from '@/editor/saveLine' +import { + HISTORY_LIMIT_BYTES, + emptyHistory, + recordCommit, + stepBack, + stepForward, + entryOf, +} from '@/editor/state/undo' +import saveLineSource from '@/editor/saveLine.ts?raw' +import saveSource from '@/editor/state/editorSave.ts?raw' +import { + VERSION, + commitMove, + openReady, + resetStore, + sb, + store, +} from '../helpers/editorHarness' +import { adminAnswer } from '../helpers/editorRoute' + +vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) })) +vi.mock('@faunosteo/supabase', async (orig) => ({ + ...(await orig()), + getSheetVersion: vi.fn(), + downloadSheetDrawing: vi.fn(), + saveSheetDraft: vi.fn(), + getOfficialSheetAdmin: vi.fn(), + submitSheetReview: vi.fn(), +})) + +afterEach(resetStore) + +const distance = () => savedDistance(store.getState()) +const SAVED_AT = '2026-11-04T13:32:00Z' + +function deferred() { + let resolve!: (value: T) => void + const promise = new Promise((res) => { + resolve = res + }) + return { promise, resolve } +} + +function adminAt(revision: number, version = VERSION) { + return adminAnswer({ + draft_version: { version_id: version, version_number: 4, revision }, + draft_last_save: { revision, saved_at: SAVED_AT, saved_by: null }, + }) as never +} + +describe('savedDistance', () => { + it('is 0 at load and counts commits', async () => { + await openReady({ revision: 3 }) + expect(distance()).toBe(0) + commitMove(40) + expect(distance()).toBe(1) + commitMove(41) + expect(distance()).toBe(2) + }) + + it('follows undo and redo around the save point', async () => { + await openReady({ revision: 3 }) + commitMove(40) + commitMove(41) + store.getState().undoStep() + expect(distance()).toBe(1) + store.getState().undoStep() + expect(distance()).toBe(0) + store.getState().redoStep() + expect(distance()).toBe(1) + }) + + it('counts the redo side when the save point lies ahead', async () => { + await openReady({ revision: 3 }) + commitMove(40) + commitMove(41) + sb.saveSheetDraft.mockResolvedValue({ revision: 4 } as never) + await store.getState().save() + store.getState().undoStep() + store.getState().undoStep() + expect(distance()).toBe(2) + }) + + it('is null once a commit follows an undo past the save point', async () => { + await openReady({ revision: 3 }) + commitMove(40) + commitMove(41) + sb.saveSheetDraft.mockResolvedValue({ revision: 4 } as never) + await store.getState().save() + store.getState().undoStep() + store.getState().undoStep() + commitMove(50) + expect(distance()).toBeNull() + }) + + it('is null for a stale base', async () => { + await openReady({ revision: 3 }) + commitMove(40) + store.setState({ staleBase: true }) + expect(distance()).toBeNull() + }) + + it('is null once a trim dropped the saved text (commit, undo and redo)', () => { + const big = (mark: string) => mark.repeat(HISTORY_LIMIT_BYTES + 1) + const state = (history: ReturnType, text: string) => ({ + staleBase: false, + documentText: text, + savedText: 'saved', + ...history, + }) + const first = { undo: [entryOf('saved')], redo: [] } + expect(savedDistance(state(first, 'now'))).toBe(1) + const committed = recordCommit(first, big('a')) + expect(savedDistance(state(committed, 'now'))).toBeNull() + const undone = stepBack( + { undo: [entryOf('saved'), entryOf('mid')], redo: [] }, + big('b'), + ) + expect(savedDistance(state(undone!.history, undone!.text))).toBeNull() + const ahead = { undo: [entryOf('saved')], redo: [entryOf('mid')] } + const redone = stepForward(ahead, big('d')) + expect(savedDistance(state(redone!.history, redone!.text))).toBeNull() + }) + + it('is null after changes made while a save was in flight moved off the save point', async () => { + await openReady({ revision: 3 }) + commitMove(40) + commitMove(41) + commitMove(42) + const answer = deferred() + sb.saveSheetDraft.mockReturnValue(answer.promise as never) + const saving = store.getState().save() + store.getState().undoStep() + store.getState().undoStep() + commitMove(43) + commitMove(44) + commitMove(45) + answer.resolve({ revision: 4 }) + await saving + expect(distance()).toBeNull() + }) + + it('is null for one undo and one commit in flight', async () => { + await openReady({ revision: 3 }) + commitMove(40) + commitMove(41) + const answer = deferred() + sb.saveSheetDraft.mockReturnValue(answer.promise as never) + const saving = store.getState().save() + store.getState().undoStep() + commitMove(43) + answer.resolve({ revision: 4 }) + await saving + expect(distance()).toBeNull() + }) + + it('the nearest duplicate of the saved text wins', async () => { + await openReady({ revision: 3 }) + commitMove(40) + commitMove(41) + commitMove(40) + sb.saveSheetDraft.mockResolvedValue({ revision: 4 } as never) + await store.getState().save() + commitMove(42) + expect(distance()).toBe(1) + }) +}) + +describe('saveLineState', () => { + const base = { + copyIssue: null, + saving: false, + unsaved: false, + distance: 0 as number | null, + lastSave: null, + savedRevision: 5, + } + + it('gives the five forms, first match wins', () => { + const saved = { revision: 5, savedAt: SAVED_AT } + expect( + saveLineState({ ...base, copyIssue: 'cap', saving: true, unsaved: true }), + ).toEqual({ + kind: 'copy_issue', + issue: 'cap', + }) + expect(saveLineState({ ...base, saving: true, unsaved: true })).toEqual({ + kind: 'saving', + }) + expect( + saveLineState({ ...base, unsaved: true, distance: 3, lastSave: saved }), + ).toEqual({ + kind: 'unsaved', + count: 3, + }) + expect(saveLineState({ ...base, lastSave: saved })).toEqual({ + kind: 'saved', + revision: 5, + savedAt: SAVED_AT, + }) + expect( + saveLineState({ ...base, lastSave: { revision: 5, savedAt: null } }), + ).toEqual({ + kind: 'saved', + revision: 5, + savedAt: null, + }) + expect(saveLineState(base)).toEqual({ kind: 'revision', revision: 5 }) + }) + + it('has no count when the distance is unknown or zero', () => { + expect(saveLineState({ ...base, unsaved: true, distance: null })).toEqual({ + kind: 'unsaved', + count: null, + }) + expect(saveLineState({ ...base, unsaved: true, distance: 0 })).toEqual({ + kind: 'unsaved', + count: null, + }) + }) + + it('shows « Révision n » when the last save is of another revision', () => { + const old = { revision: 4, savedAt: SAVED_AT } + expect(saveLineState({ ...base, lastSave: old })).toEqual({ + kind: 'revision', + revision: 5, + }) + }) +}) + +describe('readSaveTime', () => { + async function savedOnce() { + await openReady({ revision: 3 }) + commitMove(40) + sb.saveSheetDraft.mockResolvedValue({ revision: 4 } as never) + } + + it('writes the server time for this version and revision', async () => { + await savedOnce() + sb.getOfficialSheetAdmin.mockResolvedValue(adminAt(4)) + expect(await store.getState().save()).toEqual({ ok: true, revision: 4 }) + await vi.waitFor(() => + expect(store.getState().lastSave).toEqual({ + revision: 4, + savedAt: SAVED_AT, + }), + ) + }) + + it('resolves the save before the read answers', async () => { + await savedOnce() + const read = deferred() + sb.getOfficialSheetAdmin.mockReturnValue(read.promise) + expect(await store.getState().save()).toEqual({ ok: true, revision: 4 }) + expect(store.getState().lastSave).toEqual({ revision: 4, savedAt: null }) + read.resolve(adminAt(4)) + await vi.waitFor(() => + expect(store.getState().lastSave?.savedAt).toBe(SAVED_AT), + ) + }) + + it('drops an answer for another version or another revision', async () => { + await savedOnce() + sb.getOfficialSheetAdmin.mockResolvedValue(adminAt(4, 'other')) + await store.getState().save() + await vi.waitFor(() => + expect(sb.getOfficialSheetAdmin).toHaveBeenCalledTimes(1), + ) + await Promise.resolve() + expect(store.getState().lastSave).toEqual({ revision: 4, savedAt: null }) + commitMove(41) + sb.saveSheetDraft.mockResolvedValue({ revision: 5 } as never) + sb.getOfficialSheetAdmin.mockResolvedValue(adminAt(4)) + await store.getState().save() + await vi.waitFor(() => + expect(sb.getOfficialSheetAdmin).toHaveBeenCalledTimes(2), + ) + await Promise.resolve() + expect(store.getState().lastSave).toEqual({ revision: 5, savedAt: null }) + }) + + it('drops a late answer after another save', async () => { + await savedOnce() + const late = deferred() + sb.getOfficialSheetAdmin.mockReturnValueOnce(late.promise) + await store.getState().save() + commitMove(41) + sb.saveSheetDraft.mockResolvedValue({ revision: 5 } as never) + sb.getOfficialSheetAdmin.mockResolvedValue(adminAt(5)) + await store.getState().save() + await vi.waitFor(() => + expect(store.getState().lastSave?.savedAt).toBe(SAVED_AT), + ) + late.resolve(adminAt(4)) + await Promise.resolve() + expect(store.getState().lastSave).toEqual({ + revision: 5, + savedAt: SAVED_AT, + }) + }) + + it('drops a late answer after a reload', async () => { + await savedOnce() + const late = deferred() + sb.getOfficialSheetAdmin.mockReturnValue(late.promise) + await store.getState().save() + await store.getState().reloadServerDraft({ confirmed: true }) + expect(store.getState().lastSave).toBeNull() + late.resolve(adminAt(4)) + await Promise.resolve() + expect(store.getState().lastSave).toBeNull() + }) + + it('leaves the time unknown on a refusal, a failure or garbage', async () => { + await savedOnce() + sb.getOfficialSheetAdmin.mockRejectedValue(new SheetFailure('forbidden')) + await store.getState().save() + await vi.waitFor(() => + expect(sb.getOfficialSheetAdmin).toHaveBeenCalledTimes(1), + ) + expect(store.getState().lastSave).toEqual({ revision: 4, savedAt: null }) + commitMove(41) + sb.saveSheetDraft.mockResolvedValue({ revision: 5 } as never) + sb.getOfficialSheetAdmin.mockResolvedValue( + adminAnswer({ + draft_version: { version_id: VERSION, version_number: 4, revision: 5 }, + draft_last_save: { + revision: 5, + saved_at: 'not a date', + saved_by: null, + }, + }) as never, + ) + await store.getState().save() + await vi.waitFor(() => + expect(sb.getOfficialSheetAdmin).toHaveBeenCalledTimes(2), + ) + await Promise.resolve() + expect(store.getState().lastSave).toEqual({ revision: 5, savedAt: null }) + expect(store.getState().status).toBe('ready') + }) + + it('is not called on draft.unchanged nor on a failed save', async () => { + await openReady({ revision: 3 }) + commitMove(40) + sb.saveSheetDraft.mockRejectedValue(new SheetFailure('draft.unchanged')) + await store.getState().save() + expect(store.getState().lastSave).toEqual({ revision: 3, savedAt: null }) + sb.saveSheetDraft.mockRejectedValue(new SheetFailure('draft.frozen')) + commitMove(41) + await store.getState().save() + await Promise.resolve() + expect(sb.getOfficialSheetAdmin).not.toHaveBeenCalled() + }) + + it('never reads the browser clock', () => { + expect(saveLineSource).not.toMatch(/Date\.now|new Date/) + const read = saveSource.slice(saveSource.indexOf('function savedTimeOf')) + expect(read.slice(0, read.indexOf('interface Attempt'))).not.toMatch( + /Date\.now|new Date/, + ) + }) +})