fix(editor): keyboard refused-commit rule, missing history tests

Keyboard activation after a refused blur commit skips the undo and refocuses the field. Adds restore, Général-from-Annotations and DeleteDialog tests; SaveLine helpers.
This commit is contained in:
bchanot committed 2026-11-08 18:09:10 +01:00
1 parent 99b669bf8f
commit 89da8d3f55
4 files changed
+133 -35

No files matched your search

@@ -1,4 +1,4 @@
import { useRef } from 'react' import { useRef, type FocusEvent } from 'react'
import { useEditorReadOnly } from '@/editor/editingContext' import { useEditorReadOnly } from '@/editor/editingContext'
import { commitFocusedField } from '@/editor/focusRequest' import { commitFocusedField } from '@/editor/focusRequest'
import { canRedo, canUndo, useEditorStore } from '@/editor/state/editorStore' import { canRedo, canUndo, useEditorStore } from '@/editor/state/editorStore'
@@ -19,30 +19,36 @@ const BUTTON =
'xl:min-h-9 xl:min-w-0 focus-visible:outline-none focus-visible:ring-2 ' + 'xl:min-h-9 xl:min-w-0 focus-visible:outline-none focus-visible:ring-2 ' +
'focus-visible:ring-[var(--color-accent)]' 'focus-visible:ring-[var(--color-accent)]'
/** The text field the press left, kept to learn whether its commit was refused. */ /** The element when it is a text field of the editor, else null. */
function leavingField(): HTMLElement | null { function asField(element: Element | EventTarget | null): HTMLElement | null {
const active = document.activeElement
const isField = const isField =
active instanceof HTMLInputElement || element instanceof HTMLInputElement ||
active instanceof HTMLTextAreaElement || element instanceof HTMLTextAreaElement ||
active instanceof HTMLSelectElement element instanceof HTMLSelectElement
return isField ? active : null return isField ? element : null
} }
/** /**
* The press, in two steps: the pointer-down commits the typed text (the field's blur), the * The press, in two steps: leaving a field commits the typed text (its blur: forced at
* click then reads the store, so the typed text is the last change the undo reverts. A * pointer-down, natural when Tab reaches the button), the click or key then reads the
* field whose commit was refused keeps its error: the step is skipped, focus goes back. * 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 and focus goes back to it.
*/ */
function usePress(direction: Direction, readOnly: boolean) { function usePress(direction: Direction, readOnly: boolean) {
const left = useRef<HTMLElement | null>(null) const left = useRef<HTMLElement | null>(null)
const forget = () => {
left.current = null
}
const onPointerDown = () => { const onPointerDown = () => {
left.current = leavingField() left.current = asField(document.activeElement)
commitFocusedField() commitFocusedField()
} }
const onFocus = (event: FocusEvent<HTMLElement>) => {
left.current = asField(event.relatedTarget) ?? left.current
}
const onClick = () => { const onClick = () => {
const field = left.current const field = left.current
left.current = null forget()
if (field?.getAttribute('aria-invalid') === 'true') { if (field?.getAttribute('aria-invalid') === 'true') {
field.focus() field.focus()
return return
@@ -53,7 +59,13 @@ function usePress(direction: Direction, readOnly: boolean) {
if (direction === 'undo') store.undoStep() if (direction === 'undo') store.undoStep()
else store.redoStep() else store.redoStep()
} }
return { onPointerDown, onClick, onPointerLeave: () => (left.current = null) } return {
onPointerDown,
onFocus,
onBlur: forget,
onPointerLeave: forget,
onClick,
}
} }
function HistoryButton({ direction }: { direction: Direction }) { function HistoryButton({ direction }: { direction: Direction }) {
@@ -61,6 +73,7 @@ function HistoryButton({ direction }: { direction: Direction }) {
const readOnly = useEditorReadOnly() const readOnly = useEditorReadOnly()
const steppable = useEditorStore(direction === 'undo' ? canUndo : canRedo) const steppable = useEditorStore(direction === 'undo' ? canUndo : canRedo)
const name = t(`editor.history.${direction}_title`) const name = t(`editor.history.${direction}_title`)
const press = usePress(direction, readOnly)
return ( return (
<button <button
type="button" type="button"
@@ -68,7 +81,7 @@ function HistoryButton({ direction }: { direction: Direction }) {
title={name} title={name}
aria-disabled={readOnly || !steppable} aria-disabled={readOnly || !steppable}
aria-keyshortcuts={SHORTCUT[direction]} aria-keyshortcuts={SHORTCUT[direction]}
{...usePress(direction, readOnly)} {...press}
className={BUTTON} className={BUTTON}
> >
<EditorGlyph name={direction} /> <EditorGlyph name={direction} />
+34 -20
View File
@@ -19,7 +19,7 @@ function revisionText(t: Translate, key: string, revision: number): string {
return t(key).replace('{revision}', String(revision)) return t(key).replace('{revision}', String(revision))
} }
/** The line for a state; `withTime` false gives the form the status region announces. */ /** The line for a state; `time` is the server's save time already formatted, or null. */
function lineText( function lineText(
t: Translate, t: Translate,
plural: ReturnType<typeof usePlural>, plural: ReturnType<typeof usePlural>,
@@ -51,14 +51,16 @@ function lineText(
/** What the status region announces: the state, never each change of the count. */ /** What the status region announces: the state, never each change of the count. */
function announcement(t: Translate, state: SaveLineState): string { function announcement(t: Translate, state: SaveLineState): string {
switch (state.kind) { switch (state.kind) {
case 'copy_issue':
return t(`editor.draft.status.copy_${state.issue}`)
case 'saving':
return t('editor.draft.status.saving')
case 'unsaved': case 'unsaved':
return t('editor.draft.status.unsaved') return t('editor.draft.status.unsaved')
case 'revision':
return ''
case 'saved': case 'saved':
return revisionText(t, 'editor.draft.status.saved', state.revision) return revisionText(t, 'editor.draft.status.saved', state.revision)
default: case 'revision':
return lineText(t, () => '', state, null) return ''
} }
} }
@@ -79,6 +81,27 @@ function useSaveLineState(): SaveLineState {
}) })
} }
/** The longest forms, laid out invisibly so the line keeps its width. */
function useWidestForms(): string[] {
const t = useT()
const plural = usePlural()
const timed = revisionText(t, 'editor.draft.status.saved_at', WIDEST_REVISION)
return [
timed.replace('{time}', WIDEST_TIME),
plural('editor.draft.status.unsaved_count', 999),
]
}
/** The line's text for the store's state, the server time in Paris time. */
function useLineText(state: SaveLineState): string {
const t = useT()
const plural = usePlural()
const locale = useLocaleStore((s) => s.locale)
const savedAt = state.kind === 'saved' ? state.savedAt : null
const time = savedAt === null ? null : formatParisTime(savedAt, locale)
return lineText(t, plural, state, time)
}
/** /**
* The save line (board 04). The visible line is a plain paragraph; a hidden status region * 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, * announces the state changes. The longest forms are laid out invisibly in the same cell,
@@ -86,31 +109,22 @@ function useSaveLineState(): SaveLineState {
*/ */
export default function SaveLine() { export default function SaveLine() {
const t = useT() const t = useT()
const plural = usePlural()
const locale = useLocaleStore((s) => s.locale)
const state = useSaveLineState() const state = useSaveLineState()
const savedAt = state.kind === 'saved' ? state.savedAt : null const text = useLineText(state)
const time = savedAt === null ? null : formatParisTime(savedAt, locale) const widest = useWidestForms()
const widest = [
revisionText(t, 'editor.draft.status.saved_at', WIDEST_REVISION).replace(
'{time}',
WIDEST_TIME,
),
plural('editor.draft.status.unsaved_count', 999),
]
return ( return (
<> <>
<p className="grid text-sm tabular-nums text-[var(--color-ink-muted)]"> <p className="grid text-sm tabular-nums text-[var(--color-ink-muted)]">
<span data-testid="save-line" className="col-start-1 row-start-1"> <span data-testid="save-line" className="col-start-1 row-start-1">
{lineText(t, plural, state, time)} {text}
</span> </span>
{widest.map((text) => ( {widest.map((form) => (
<span <span
key={text} key={form}
aria-hidden="true" aria-hidden="true"
className="invisible col-start-1 row-start-1 h-0 overflow-hidden whitespace-nowrap" className="invisible col-start-1 row-start-1 h-0 overflow-hidden whitespace-nowrap"
> >
{text} {form}
</span> </span>
))} ))}
</p> </p>
@@ -4,11 +4,13 @@ import {
act, act,
cleanup, cleanup,
fireEvent, fireEvent,
render,
screen, screen,
waitFor, waitFor,
within, within,
} from '@testing-library/react' } from '@testing-library/react'
import userEvent from '@testing-library/user-event' import userEvent from '@testing-library/user-event'
import DeleteDialog from '@/components/editor/DeleteDialog'
import { fr } from '@/i18n/fr' import { fr } from '@/i18n/fr'
import { import {
baseText, baseText,
@@ -175,6 +177,24 @@ describe('the buttons', () => {
expect(geometry()).toMatchObject({ cx: 50 }) expect(geometry()).toMatchObject({ cx: 50 })
}) })
it('undo from Annotations reverts a Général change', async () => {
const user = userEvent.setup()
mountDraft()
await ready()
const original = store.getState().previewState?.document.name?.fr
await user.click(screen.getByRole('tab', { name: 'Général' }))
const place = document.querySelector(
'[data-place="general"]',
) as HTMLElement
const field = within(place).getByLabelText('Nom (FR)')
await user.clear(field)
await user.type(field, 'Renommée')
await user.click(screen.getByRole('tab', { name: 'Annotations' }))
expect(store.getState().previewState?.document.name?.fr).toBe('Renommée')
await user.click(undoButton())
expect(store.getState().previewState?.document.name?.fr).toBe(original)
})
it('leave no undo or redo pair in the tool column', async () => { it('leave no undo or redo pair in the tool column', async () => {
mountDraft() mountDraft()
await ready() await ready()
@@ -232,6 +252,38 @@ describe('typed text and the press', () => {
expect(geometry()).toMatchObject({ cx: 40 }) expect(geometry()).toMatchObject({ cx: 40 })
}) })
it('a keyboard activation after a refused blur commit skips the undo too', async () => {
const user = userEvent.setup()
mountDraft()
await ready()
act(() => void commitMove(40))
const field = await selectAnnotation(user)
await user.clear(field)
field.blur()
act(() => undoButton().focus())
fireEvent.focus(undoButton(), { relatedTarget: field })
await user.keyboard('{Enter}')
expect(field).toHaveAttribute('aria-invalid', 'true')
expect(field).toHaveFocus()
expect(geometry()).toMatchObject({ cx: 40 })
expect(store.getState().undo).toHaveLength(1)
})
it('Ctrl+Z is ignored while a DeleteDialog is open', async () => {
mountDraft()
await ready()
act(() => void commitMove(40))
render(
<DeleteDialog
target={{ key: { kind: 'annotation', id: 'anno-a' }, label: 'N' }}
onClose={vi.fn()}
/>,
)
await screen.findByRole('dialog')
fireEvent.keyDown(document.body, { key: 'z', ctrlKey: true })
expect(geometry()).toMatchObject({ cx: 40 })
})
it('Ctrl+Z inside a field leaves the store untouched', async () => { it('Ctrl+Z inside a field leaves the store untouched', async () => {
mountDraft() mountDraft()
await ready() await ready()
@@ -13,8 +13,12 @@ import {
import saveLineSource from '@/editor/saveLine.ts?raw' import saveLineSource from '@/editor/saveLine.ts?raw'
import saveSource from '@/editor/state/editorSave.ts?raw' import saveSource from '@/editor/state/editorSave.ts?raw'
import { import {
SHEET,
USER,
VERSION, VERSION,
baseText,
commitMove, commitMove,
copyKeyOf,
openReady, openReady,
resetStore, resetStore,
sb, sb,
@@ -97,6 +101,21 @@ describe('savedDistance', () => {
expect(distance()).toBeNull() expect(distance()).toBeNull()
}) })
it('is null after a restored recovery copy', async () => {
const copy = JSON.parse(baseText(), (key, value) => (key === 'cx' ? 10 : value))
sessionStorage.setItem(
copyKeyOf(),
JSON.stringify({
v: 1, user_id: USER, version_id: VERSION, sheet_id: SHEET, sheet_name: 'Fiche',
revision: 3, written_at: '2026-11-03T10:00:00Z', document: copy, drawings: [],
}),
)
await openReady({ revision: 3 })
expect(await store.getState().restoreCopy()).toEqual({ ok: true })
expect(store.getState().unsaved).toBe(true)
expect(distance()).toBeNull()
})
it('is null for a stale base', async () => { it('is null for a stale base', async () => {
await openReady({ revision: 3 }) await openReady({ revision: 3 })
commitMove(40) commitMove(40)