fix(editor): « Défaire » cancels pending work; reasons only when they help

A press on « Défaire » over a pending series or mode keeps the focus and
skips the field commit, so its handle's blur no longer commits before
the cancel (R-13): the redo stack survives. A held button gives its
reason only when that cause alone holds it; redo during a creation gets
its own text, and the pending text says to cancel with « Défaire ».
This commit is contained in:
bchanot committed 2026-11-19 14:52:51 +01:00
1 parent de418b29a9
commit 59e189c375
6 files changed
+184 -40

No files matched your search

+31 -3
View File
@@ -228,7 +228,18 @@ test.describe('editor annotations (A3)', () => {
}) => { }) => {
const { actor } = await openAnnotations(page) const { actor } = await openAnnotations(page)
requests.forbid(actor.account.email, actor.account.password) requests.forbid(actor.account.email, actor.account.password)
const reason = dict['editor.history.hold_creation'] const reason = dict['editor.history.hold_creation_redo']
// Something to undo and to redo: a reason shows only when the creation alone holds.
for (const [name, x] of [
['Point un', 300],
['Point deux', 400],
] as const) {
await tool(page, 'point').click()
await clickDrawing(page, x, 300)
await fillCreation(page, { fr: name, en: name })
await createFromPanel(page)
}
await historyButton(page, dict, 'undo').click()
// A zone tracing is a creation with no modal dialog: the header stays reachable. // A zone tracing is a creation with no modal dialog: the header stays reachable.
await tool(page, 'zone').click() await tool(page, 'zone').click()
await clickDrawing(page, 600, 200) await clickDrawing(page, 600, 200)
@@ -237,7 +248,7 @@ test.describe('editor annotations (A3)', () => {
await expect(redo).toHaveAttribute('aria-disabled', 'true') await expect(redo).toHaveAttribute('aria-disabled', 'true')
await expect(redo).toHaveAccessibleDescription(reason) await expect(redo).toHaveAccessibleDescription(reason)
await expect(historyButton(page, dict, 'undo')).toHaveAccessibleDescription( await expect(historyButton(page, dict, 'undo')).toHaveAccessibleDescription(
reason, dict['editor.history.hold_creation'],
) )
await expectAccessible(page, 'a held « Refaire » during a creation') await expectAccessible(page, 'a held « Refaire » during a creation')
await expectNoShift(page, async () => { await expectNoShift(page, async () => {
@@ -247,7 +258,7 @@ test.describe('editor annotations (A3)', () => {
await expect(page.getByTestId('gesture-message')).toHaveCount(1) await expect(page.getByTestId('gesture-message')).toHaveCount(1)
}) })
test('a mouse click on « Refaire » during an arrow series says why and keeps the focus', async ({ test('a mouse click on « Refaire » during an arrow series says why; « Défaire » cancels and keeps the redo', async ({
page, page,
requests, requests,
}) => { }) => {
@@ -261,9 +272,20 @@ test.describe('editor annotations (A3)', () => {
name: 'Point Point un', name: 'Point Point un',
exact: true, exact: true,
}) })
const placed = await shownNumber(page, 'cx')
// A move to redo: one arrow committed by Enter, then undone.
await handle.focus() await handle.focus()
await page.keyboard.press('ArrowRight') await page.keyboard.press('ArrowRight')
await page.keyboard.press('Enter')
const moved = await shownNumber(page, 'cx')
const undo = historyButton(page, dict, 'undo')
const redo = historyButton(page, dict, 'redo') const redo = historyButton(page, dict, 'redo')
await undo.click()
await expect(shownShape(page)).toHaveAttribute('cx', String(placed))
// Two arrows pending: a commit then an undo would leave them, not the move, to redo.
await handle.focus()
await page.keyboard.press('ArrowRight')
await page.keyboard.press('ArrowRight')
await expect(redo).toHaveAccessibleDescription( await expect(redo).toHaveAccessibleDescription(
dict['editor.history.hold_pending'], dict['editor.history.hold_pending'],
) )
@@ -278,6 +300,12 @@ test.describe('editor annotations (A3)', () => {
await expect(redo).toHaveAccessibleDescription( await expect(redo).toHaveAccessibleDescription(
dict['editor.history.hold_pending'], dict['editor.history.hold_pending'],
) )
// The reason's advice holds: « Défaire » cancels the series, the redo is still there.
await pressAtBox(page, undo)
await expect(shownShape(page)).toHaveAttribute('cx', String(placed))
await expect(redo).toHaveAttribute('aria-disabled', 'false')
await redo.click()
await expect(shownShape(page)).toHaveAttribute('cx', String(moved))
}) })
test('a click with jitter never moves; a drag moves by the pointer delta', async ({ test('a click with jitter never moves; a drag moves by the pointer delta', async ({
@@ -10,6 +10,7 @@ import { commitFocusedField } from '@/editor/focusRequest'
import { canRedo, canUndo, useEditorStore } from '@/editor/state/editorStore' import { canRedo, canUndo, useEditorStore } from '@/editor/state/editorStore'
import { import {
cancelPending, cancelPending,
hasPending,
holdsRedo, holdsRedo,
pressHeldHistory, pressHeldHistory,
useAnnotationWork, useAnnotationWork,
@@ -42,25 +43,53 @@ function asField(element: Element | EventTarget | null): HTMLElement | null {
} }
/** /**
* A12: both are held during a creation (R-13); I-1: redo also while work it would drop * A12: both are inactive during a creation (R-13); I-1: redo also while work it would drop
* is pending (a started mode, a keyboard series, a slider change). * is pending (a started mode, a keyboard series, a slider change).
*/ */
const inactive = (
direction: Direction,
work: ReturnType<typeof useAnnotationWork.getState>,
) => work.creation !== null || (direction === 'redo' && holdsRedo(work))
const steppableNow = (direction: Direction) => {
const store = useEditorStore.getState()
return direction === 'undo' ? canUndo(store) : canRedo(store)
}
/**
* Why an inactive button is held: only when that cause alone keeps it from acting (rev 4
* I-1). With nothing to undo or redo, it is held as before point 6, without a word.
*/
function holdOf( function holdOf(
direction: Direction, direction: Direction,
work: ReturnType<typeof useAnnotationWork.getState>, work: ReturnType<typeof useAnnotationWork.getState>,
steppable: boolean,
): HistoryHold | null { ): HistoryHold | null {
if (work.creation !== null) return 'creation' if (!steppable || !inactive(direction, work)) return null
return direction === 'redo' && holdsRedo(work) ? 'pending' : null if (work.creation === null) return 'pending'
return direction === 'undo' ? 'creation' : 'creation_redo'
} }
const holdNow = (direction: Direction) =>
holdOf(direction, useAnnotationWork.getState(), steppableNow(direction))
/**
* The press leaves the focus where it is: a held button only says why, and « Défaire »
* over pending work only cancels it (R-13), which a blur of its handle would commit first.
*/
const keepsFocus = (direction: Direction) =>
holdNow(direction) !== null ||
(direction === 'undo' && hasPending(useAnnotationWork.getState()))
/** /**
* The press, in two steps: leaving a field commits the typed text (its blur: forced at * The press, in two steps: leaving a field commits the typed text (its blur: forced at
* pointer-down unless the button is held, natural when Tab reaches the button), the click or * pointer-down unless the press keeps the focus, natural when Tab reaches it), the click
* key then reads the store, so the typed text is the last change the undo reverts. A field * or key then reads the store, so the typed text is the last change the undo reverts. A
* whose commit was refused keeps its error: the step is skipped and focus goes back to it. The field is * field whose commit was refused keeps its error: the step is skipped and focus goes back
* remembered across the pair: from a field, « Défaire » is two Shift+Tab away. A touch * to it. The field is remembered across the pair: from a field, « Défaire » is two
* press fires pointer leave between its up and its click, so only a mouse leaving the * Shift+Tab away. A touch press fires pointer leave between its up and its click, so only
* button forgets the field (a hovering pointer that left meant no press), or a cancel. * a mouse leaving the button forgets the field (a hovering pointer that left meant no
* press), or a cancel.
*/ */
function usePress( function usePress(
direction: Direction, direction: Direction,
@@ -78,13 +107,11 @@ function usePress(
const onPointerLeave = (event: PointerEvent<HTMLElement>) => { const onPointerLeave = (event: PointerEvent<HTMLElement>) => {
if (event.pointerType === 'mouse') forget() if (event.pointerType === 'mouse') forget()
} }
const isHeld = () => holdOf(direction, useAnnotationWork.getState()) !== null
// A held press only says why: the focus stays on the pending work, which is not committed.
const onMouseDown = (event: MouseEvent<HTMLElement>) => { const onMouseDown = (event: MouseEvent<HTMLElement>) => {
if (isHeld()) event.preventDefault() if (keepsFocus(direction)) event.preventDefault()
} }
const onPointerDown = () => { const onPointerDown = () => {
if (isHeld()) return if (keepsFocus(direction)) return
left.current = asField(document.activeElement) ?? left.current left.current = asField(document.activeElement) ?? left.current
commitFocusedField() commitFocusedField()
} }
@@ -92,9 +119,10 @@ function usePress(
left.current = asField(event.relatedTarget) ?? left.current left.current = asField(event.relatedTarget) ?? left.current
} }
const onClick = () => { const onClick = () => {
// A12, I-1: a held button does nothing but say why. // A12, I-1: a held button does nothing but say why; an inactive one does nothing.
const hold = holdOf(direction, useAnnotationWork.getState()) const hold = holdNow(direction)
if (hold) return pressHeldHistory(hold) if (hold) return pressHeldHistory(hold)
if (inactive(direction, useAnnotationWork.getState())) return
const field = left.current const field = left.current
forget() forget()
if (field?.isConnected && field.getAttribute('aria-invalid') === 'true') { if (field?.isConnected && field.getAttribute('aria-invalid') === 'true') {
@@ -130,7 +158,7 @@ function HistoryButton({
const t = useT() const t = useT()
const readOnly = useEditorReadOnly() const readOnly = useEditorReadOnly()
const steppable = useEditorStore(direction === 'undo' ? canUndo : canRedo) const steppable = useEditorStore(direction === 'undo' ? canUndo : canRedo)
const hold = useAnnotationWork((s) => holdOf(direction, s)) const hold = useAnnotationWork((s) => holdOf(direction, s, steppable))
const name = t(`editor.history.${direction}_title`) const name = t(`editor.history.${direction}_title`)
const press = usePress(direction, readOnly, left) const press = usePress(direction, readOnly, left)
const reasonId = `history-hold-${direction}` const reasonId = `history-hold-${direction}`
+9 -5
View File
@@ -109,7 +109,7 @@ const NO_WORK: Work = {
export const useAnnotationWork = create<Work>(() => NO_WORK) export const useAnnotationWork = create<Work>(() => NO_WORK)
/** Why « Défaire » or « Refaire » is held (point 6): a creation, or pending work. */ /** Why « Défaire » or « Refaire » is held (point 6): a creation, or pending work. */
export type HistoryHold = 'creation' | 'pending' export type HistoryHold = 'creation' | 'creation_redo' | 'pending'
/** A press on a held history button: the message line says why (see `historyPress`). */ /** A press on a held history button: the message line says why (see `historyPress`). */
export function pressHeldHistory(reason: HistoryHold): void { export function pressHeldHistory(reason: HistoryHold): void {
@@ -170,21 +170,25 @@ export function setModePreview(geometry: Geometry, stored: Geometry): void {
}) })
} }
/** A mode, a slider change or a keyboard series that an undo would only cancel (R-13). */
export function hasPending(work: Pick<Work, 'mode' | 'preview'>): boolean {
return work.mode !== null || work.preview !== null
}
/** /**
* R-13: an undo while a mode, a slider or a keyboard series is pending only cancels it. * R-13: an undo while a mode, a slider or a keyboard series is pending only cancels it.
* Answers whether there was something to cancel. * Answers whether there was something to cancel.
*/ */
export function cancelPending(): boolean { export function cancelPending(): boolean {
const { mode, preview } = useAnnotationWork.getState() if (!hasPending(useAnnotationWork.getState())) return false
if (mode === null && preview === null) return false
endMode() endMode()
return true return true
} }
/** /**
* Work a redo would drop without a word (final review I-1): a started mode, a keyboard * Work a redo would drop without a word (final review I-1): a started mode, a keyboard
* series or a slider change. Redo waits until it is committed or cancelled; an unstarted * series or a slider change. Redo waits until it is cancelled (a commit clears the redo
* mode loses nothing and does not hold it. * stack); an unstarted mode loses nothing and does not hold it.
*/ */
export function holdsRedo(work: Pick<Work, 'mode' | 'preview'>): boolean { export function holdsRedo(work: Pick<Work, 'mode' | 'preview'>): boolean {
if (work.mode?.started) return true if (work.mode?.started) return true
+3 -1
View File
@@ -1415,8 +1415,10 @@ export const en: Dict = {
'editor.history.redo_shortcut': 'Ctrl+Shift+Z or ⇧⌘Z', 'editor.history.redo_shortcut': 'Ctrl+Shift+Z or ⇧⌘Z',
'editor.history.hold_creation': 'editor.history.hold_creation':
'Unavailable during a creation: create the annotation or discard it.', 'Unavailable during a creation: create the annotation or discard it.',
'editor.history.hold_creation_redo':
'Redo is paused during a creation: discard it to redo.',
'editor.history.hold_pending': 'editor.history.hold_pending':
'Redo waits for the change in progress: confirm or cancel it.', 'Redo is paused during the change in progress: cancel it with Undo to redo.',
'editor.draft.status.saving': 'Saving…', 'editor.draft.status.saving': 'Saving…',
'editor.draft.status.copy_quota': 'editor.draft.status.copy_quota':
'Temporary local copy impossible (tab full): not saved on the server', 'Temporary local copy impossible (tab full): not saved on the server',
+3 -1
View File
@@ -1472,8 +1472,10 @@ export const fr: Dict = {
'editor.history.redo_shortcut': 'Ctrl+Maj+Z ou ⇧⌘Z', 'editor.history.redo_shortcut': 'Ctrl+Maj+Z ou ⇧⌘Z',
'editor.history.hold_creation': 'editor.history.hold_creation':
"Indisponible pendant une création : créez l'annotation ou abandonnez-la.", "Indisponible pendant une création : créez l'annotation ou abandonnez-la.",
'editor.history.hold_creation_redo':
'Refaire est suspendu pendant une création : abandonnez-la pour pouvoir refaire.',
'editor.history.hold_pending': 'editor.history.hold_pending':
'Refaire attend la fin de la modification en cours : validez-la ou annulez-la.', 'Refaire est suspendu pendant la modification en cours : annulez-la avec Défaire pour pouvoir refaire.',
'editor.draft.status.saving': 'Enregistrement…', 'editor.draft.status.saving': 'Enregistrement…',
'editor.draft.status.copy_quota': 'editor.draft.status.copy_quota':
'Copie locale temporaire impossible (onglet plein) : non enregistré sur le serveur', 'Copie locale temporaire impossible (onglet plein) : non enregistré sur le serveur',
@@ -566,8 +566,10 @@ describe('« Abandonner les modifications »', () => {
describe('why a button is held (point 6)', () => { describe('why a button is held (point 6)', () => {
const CREATION = const CREATION =
"Indisponible pendant une création : créez l'annotation ou abandonnez-la." "Indisponible pendant une création : créez l'annotation ou abandonnez-la."
const REDO_CREATION =
'Refaire est suspendu pendant une création : abandonnez-la pour pouvoir refaire.'
const PENDING = const PENDING =
'Refaire attend la fin de la modification en cours : validez-la ou annulez-la.' 'Refaire est suspendu pendant la modification en cours : annulez-la avec Défaire pour pouvoir refaire.'
const STORED = { type: 'circle' as const, cx: 1, cy: 2, r: 3 } const STORED = { type: 'circle' as const, cx: 1, cy: 2, r: 3 }
afterEach(() => act(() => resetWork())) afterEach(() => act(() => resetWork()))
const line = () => screen.getByTestId('gesture-line') const line = () => screen.getByTestId('gesture-line')
@@ -575,6 +577,8 @@ describe('why a button is held (point 6)', () => {
const id = button.getAttribute('aria-describedby') const id = button.getAttribute('aria-describedby')
return id ? document.getElementById(id)?.textContent : null return id ? document.getElementById(id)?.textContent : null
} }
const noMessage = () =>
expect(within(line()).queryByTestId('gesture-message')).toBeNull()
async function openAnnotations() { async function openAnnotations() {
const user = userEvent.setup() const user = userEvent.setup()
mountDraft() mountDraft()
@@ -583,6 +587,14 @@ describe('why a button is held (point 6)', () => {
await screen.findByTestId('gesture-line') await screen.findByTestId('gesture-line')
return user return user
} }
// Something to undo and to redo: a reason shows only when its cause alone holds the button.
const stacks = () =>
act(() =>
store.setState({
undo: [{ text: baseText(), bytes: 1 }],
redo: [{ text: baseText(), bytes: 1 }],
}),
)
const create = () => const create = () =>
act(() => act(() =>
traceVertex( traceVertex(
@@ -608,19 +620,30 @@ describe('why a button is held (point 6)', () => {
}, },
}), }),
) )
// A handle's blur commits its series (here: ends the preview), as the real one does.
function focusedHandle() {
const handle = document.createElement('button')
handle.addEventListener('blur', () =>
useAnnotationWork.setState({ preview: null }),
)
document.body.append(handle)
handle.focus()
return handle
}
it('a creation describes both buttons and every press says why, once', async () => { it('a creation describes each button with its own reason and every press says why, once', async () => {
const user = await openAnnotations() const user = await openAnnotations()
stacks()
create() create()
expect(reason(undoButton())).toBe(CREATION) expect(reason(undoButton())).toBe(CREATION)
expect(reason(redoButton())).toBe(CREATION) expect(reason(redoButton())).toBe(REDO_CREATION)
expect(disabled(redoButton())).toBe(true) expect(disabled(redoButton())).toBe(true)
await user.click(redoButton()) await user.click(redoButton())
expect(line()).toHaveTextContent(CREATION) expect(line()).toHaveTextContent(REDO_CREATION)
const first = within(line()).getByTestId('gesture-message') const first = within(line()).getByTestId('gesture-message')
redoButton().focus() redoButton().focus()
await user.keyboard('{Enter}') await user.keyboard('{Enter}')
expect(line()).toHaveTextContent(CREATION) expect(line()).toHaveTextContent(REDO_CREATION)
expect(within(line()).getByTestId('gesture-message')).not.toBe(first) expect(within(line()).getByTestId('gesture-message')).not.toBe(first)
await user.keyboard(' ') await user.keyboard(' ')
expect(within(line()).getAllByTestId('gesture-message')).toHaveLength(1) expect(within(line()).getAllByTestId('gesture-message')).toHaveLength(1)
@@ -631,6 +654,7 @@ describe('why a button is held (point 6)', () => {
it('pending work holds redo only, with its own reason', async () => { it('pending work holds redo only, with its own reason', async () => {
const user = await openAnnotations() const user = await openAnnotations()
stacks()
pend() pend()
expect(reason(redoButton())).toBe(PENDING) expect(reason(redoButton())).toBe(PENDING)
expect(reason(undoButton())).toBeNull() expect(reason(undoButton())).toBeNull()
@@ -641,13 +665,7 @@ describe('why a button is held (point 6)', () => {
it('a mouse press on a held « Refaire » leaves the focused pending work alone', async () => { it('a mouse press on a held « Refaire » leaves the focused pending work alone', async () => {
const user = await openAnnotations() const user = await openAnnotations()
pend() pend()
// A handle's blur commits its series (here: ends the preview), as the real one does. const handle = focusedHandle()
const handle = document.createElement('button')
handle.addEventListener('blur', () =>
useAnnotationWork.setState({ preview: null }),
)
document.body.append(handle)
handle.focus()
store.setState({ redo: [{ text: baseText(), bytes: 1 }] }) store.setState({ redo: [{ text: baseText(), bytes: 1 }] })
await user.pointer([ await user.pointer([
{ keys: '[MouseLeft>]', target: redoButton() }, { keys: '[MouseLeft>]', target: redoButton() },
@@ -660,8 +678,58 @@ describe('why a button is held (point 6)', () => {
handle.remove() handle.remove()
}) })
for (const [kind, keys] of [
['mouse', '[MouseLeft]'],
['touch', '[TouchA]'],
] as const) {
it(`a ${kind} press on « Défaire » during pending work only cancels it: focus and redo stay`, async () => {
const user = await openAnnotations()
stacks()
pend()
let committed = false
const handle = focusedHandle()
handle.addEventListener('blur', () => {
committed = true
})
await user.pointer({ keys, target: undoButton() })
expect(committed).toBe(false)
expect(handle).toHaveFocus()
expect(useAnnotationWork.getState().preview).toBeNull()
expect(store.getState().undo).toHaveLength(1)
expect(store.getState().redo).toHaveLength(1)
handle.remove()
})
}
it('with nothing to redo, pending work gives « Refaire » no reason and a press commits it', async () => {
const user = await openAnnotations()
pend()
expect(reason(redoButton())).toBeNull()
expect(disabled(redoButton())).toBe(true)
const handle = focusedHandle()
await user.click(redoButton())
expect(handle).not.toHaveFocus()
expect(useAnnotationWork.getState().preview).toBeNull()
noMessage()
handle.remove()
})
it('a creation with nothing to undo or redo gives no reason, and a press says nothing', async () => {
const user = await openAnnotations()
create()
expect(reason(undoButton())).toBeNull()
expect(reason(redoButton())).toBeNull()
await user.click(redoButton())
await user.click(undoButton())
undoButton().focus()
await user.keyboard('{Enter}')
noMessage()
expect(useAnnotationWork.getState().creation).not.toBeNull()
})
it('Space on a held « Défaire » and Enter on a pending « Refaire » say why', async () => { it('Space on a held « Défaire » and Enter on a pending « Refaire » say why', async () => {
const user = await openAnnotations() const user = await openAnnotations()
stacks()
create() create()
undoButton().focus() undoButton().focus()
await user.keyboard(' ') await user.keyboard(' ')
@@ -676,22 +744,34 @@ describe('why a button is held (point 6)', () => {
it('say it in English', async () => { it('say it in English', async () => {
const user = await openAnnotations() const user = await openAnnotations()
act(() => useLocaleStore.setState({ locale: 'en' })) act(() => useLocaleStore.setState({ locale: 'en' }))
stacks()
create() create()
const redo = screen.getByRole('button', { const redo = screen.getByRole('button', {
name: 'Redo the last undone change', name: 'Redo the last undone change',
}) })
const undo = screen.getByRole('button', {
name: 'Undo the last change',
})
expect(reason(redo)).toBe( expect(reason(redo)).toBe(
'Redo is paused during a creation: discard it to redo.',
)
expect(reason(undo)).toBe(
'Unavailable during a creation: create the annotation or discard it.', 'Unavailable during a creation: create the annotation or discard it.',
) )
await user.click(redo) await user.click(redo)
expect(line()).toHaveTextContent('Unavailable during a creation') expect(line()).toHaveTextContent('Redo is paused during a creation')
act(() => resetWork())
pend()
expect(reason(redo)).toBe(
'Redo is paused during the change in progress: cancel it with Undo to redo.',
)
}) })
it('give no reason when nothing is pending, nothing to redo or read-only', async () => { it('give no reason when nothing is pending, nothing to redo or read-only', async () => {
const user = await openAnnotations() const user = await openAnnotations()
expect(reason(redoButton())).toBeNull() expect(reason(redoButton())).toBeNull()
await user.click(redoButton()) await user.click(redoButton())
expect(within(line()).queryByTestId('gesture-message')).toBeNull() noMessage()
cleanup() cleanup()
resetStore() resetStore()
serverHas(baseText(), 3) serverHas(baseText(), 3)