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)
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.
await tool(page, 'zone').click()
await clickDrawing(page, 600, 200)
@@ -237,7 +248,7 @@ test.describe('editor annotations (A3)', () => {
await expect(redo).toHaveAttribute('aria-disabled', 'true')
await expect(redo).toHaveAccessibleDescription(reason)
await expect(historyButton(page, dict, 'undo')).toHaveAccessibleDescription(
reason,
dict['editor.history.hold_creation'],
)
await expectAccessible(page, 'a held « Refaire » during a creation')
await expectNoShift(page, async () => {
@@ -247,7 +258,7 @@ test.describe('editor annotations (A3)', () => {
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,
requests,
}) => {
@@ -261,9 +272,20 @@ test.describe('editor annotations (A3)', () => {
name: 'Point Point un',
exact: true,
})
const placed = await shownNumber(page, 'cx')
// A move to redo: one arrow committed by Enter, then undone.
await handle.focus()
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')
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(
dict['editor.history.hold_pending'],
)
@@ -278,6 +300,12 @@ test.describe('editor annotations (A3)', () => {
await expect(redo).toHaveAccessibleDescription(
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 ({
@@ -10,6 +10,7 @@ import { commitFocusedField } from '@/editor/focusRequest'
import { canRedo, canUndo, useEditorStore } from '@/editor/state/editorStore'
import {
cancelPending,
hasPending,
holdsRedo,
pressHeldHistory,
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).
*/
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(
direction: Direction,
work: ReturnType<typeof useAnnotationWork.getState>,
steppable: boolean,
): HistoryHold | null {
if (work.creation !== null) return 'creation'
return direction === 'redo' && holdsRedo(work) ? 'pending' : null
if (!steppable || !inactive(direction, work)) return 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
* pointer-down unless the button is held, natural when Tab reaches the button), the click or
* key 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 and focus goes back to it. The field is
* remembered across the pair: from a field, « Défaire » is two Shift+Tab away. A touch
* press fires pointer leave between its up and its click, so only a mouse leaving the
* button forgets the field (a hovering pointer that left meant no press), or a cancel.
* pointer-down unless the press keeps the focus, natural when Tab reaches it), the click
* or key 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 and focus goes back
* to it. The field is remembered across the pair: from a field, « Défaire » is two
* Shift+Tab away. A touch press fires pointer leave between its up and its click, so only
* a mouse leaving the button forgets the field (a hovering pointer that left meant no
* press), or a cancel.
*/
function usePress(
direction: Direction,
@@ -78,13 +107,11 @@ function usePress(
const onPointerLeave = (event: PointerEvent<HTMLElement>) => {
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>) => {
if (isHeld()) event.preventDefault()
if (keepsFocus(direction)) event.preventDefault()
}
const onPointerDown = () => {
if (isHeld()) return
if (keepsFocus(direction)) return
left.current = asField(document.activeElement) ?? left.current
commitFocusedField()
}
@@ -92,9 +119,10 @@ function usePress(
left.current = asField(event.relatedTarget) ?? left.current
}
const onClick = () => {
// A12, I-1: a held button does nothing but say why.
const hold = holdOf(direction, useAnnotationWork.getState())
// A12, I-1: a held button does nothing but say why; an inactive one does nothing.
const hold = holdNow(direction)
if (hold) return pressHeldHistory(hold)
if (inactive(direction, useAnnotationWork.getState())) return
const field = left.current
forget()
if (field?.isConnected && field.getAttribute('aria-invalid') === 'true') {
@@ -130,7 +158,7 @@ function HistoryButton({
const t = useT()
const readOnly = useEditorReadOnly()
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 press = usePress(direction, readOnly, left)
const reasonId = `history-hold-${direction}`
+9 -5
View File
@@ -109,7 +109,7 @@ const NO_WORK: Work = {
export const useAnnotationWork = create<Work>(() => NO_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`). */
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.
* Answers whether there was something to cancel.
*/
export function cancelPending(): boolean {
const { mode, preview } = useAnnotationWork.getState()
if (mode === null && preview === null) return false
if (!hasPending(useAnnotationWork.getState())) return false
endMode()
return true
}
/**
* 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
* mode loses nothing and does not hold it.
* series or a slider change. Redo waits until it is cancelled (a commit clears the redo
* stack); an unstarted mode loses nothing and does not hold it.
*/
export function holdsRedo(work: Pick<Work, 'mode' | 'preview'>): boolean {
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.hold_creation':
'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':
'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.copy_quota':
'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.hold_creation':
"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':
'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.copy_quota':
'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)', () => {
const CREATION =
"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 =
'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 }
afterEach(() => act(() => resetWork()))
const line = () => screen.getByTestId('gesture-line')
@@ -575,6 +577,8 @@ describe('why a button is held (point 6)', () => {
const id = button.getAttribute('aria-describedby')
return id ? document.getElementById(id)?.textContent : null
}
const noMessage = () =>
expect(within(line()).queryByTestId('gesture-message')).toBeNull()
async function openAnnotations() {
const user = userEvent.setup()
mountDraft()
@@ -583,6 +587,14 @@ describe('why a button is held (point 6)', () => {
await screen.findByTestId('gesture-line')
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 = () =>
act(() =>
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()
stacks()
create()
expect(reason(undoButton())).toBe(CREATION)
expect(reason(redoButton())).toBe(CREATION)
expect(reason(redoButton())).toBe(REDO_CREATION)
expect(disabled(redoButton())).toBe(true)
await user.click(redoButton())
expect(line()).toHaveTextContent(CREATION)
expect(line()).toHaveTextContent(REDO_CREATION)
const first = within(line()).getByTestId('gesture-message')
redoButton().focus()
await user.keyboard('{Enter}')
expect(line()).toHaveTextContent(CREATION)
expect(line()).toHaveTextContent(REDO_CREATION)
expect(within(line()).getByTestId('gesture-message')).not.toBe(first)
await user.keyboard(' ')
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 () => {
const user = await openAnnotations()
stacks()
pend()
expect(reason(redoButton())).toBe(PENDING)
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 () => {
const user = await openAnnotations()
pend()
// A handle's blur commits its series (here: ends the preview), as the real one does.
const handle = document.createElement('button')
handle.addEventListener('blur', () =>
useAnnotationWork.setState({ preview: null }),
)
document.body.append(handle)
handle.focus()
const handle = focusedHandle()
store.setState({ redo: [{ text: baseText(), bytes: 1 }] })
await user.pointer([
{ keys: '[MouseLeft>]', target: redoButton() },
@@ -660,8 +678,58 @@ describe('why a button is held (point 6)', () => {
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 () => {
const user = await openAnnotations()
stacks()
create()
undoButton().focus()
await user.keyboard(' ')
@@ -676,22 +744,34 @@ describe('why a button is held (point 6)', () => {
it('say it in English', async () => {
const user = await openAnnotations()
act(() => useLocaleStore.setState({ locale: 'en' }))
stacks()
create()
const redo = screen.getByRole('button', {
name: 'Redo the last undone change',
})
const undo = screen.getByRole('button', {
name: 'Undo the last change',
})
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.',
)
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 () => {
const user = await openAnnotations()
expect(reason(redoButton())).toBeNull()
await user.click(redoButton())
expect(within(line()).queryByTestId('gesture-message')).toBeNull()
noMessage()
cleanup()
resetStore()
serverHas(baseText(), 3)