fix(editor): redo and move-mode handle keys keep pending work

Final review I-1. Redo (Ctrl+Shift+Z and the header « Refaire ») is
inactive while a started move or redraw, a keyboard series or a size
change is pending (holdsRedo): the work stays, the user commits or
cancels it first. In a move mode, Insert and Delete on a vertex and
Enter or Space on « + » and « − » do nothing, as the press machine.

Tests: no assertion removed. The history-guards move-mode helper and
reset run in act, since « Refaire » now re-renders on a started mode.
This commit is contained in:
bchanot committed 2026-11-18 13:00:03 +01:00
1 parent c6b8c7e48a
commit ae80511964
7 files changed
+211 -12

No files matched your search

@@ -9,6 +9,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,
holdsRedo,
useAnnotationWork, useAnnotationWork,
} from '@/editor/annotations/workStore' } from '@/editor/annotations/workStore'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
@@ -37,6 +38,15 @@ function asField(element: Element | EventTarget | null): HTMLElement | null {
return isField ? element : null return isField ? element : null
} }
/**
* 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))
/** /**
* 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, natural when Tab reaches the button), the click or key then reads the * pointer-down, natural when Tab reaches the button), the click or key then reads the
@@ -71,7 +81,7 @@ function usePress(
} }
const onClick = () => { const onClick = () => {
// A12: undo and redo are inactive during a creation (R-13). // A12: undo and redo are inactive during a creation (R-13).
if (useAnnotationWork.getState().creation) return 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') {
@@ -106,7 +116,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 creating = useAnnotationWork((s) => s.creation !== null) const held = useAnnotationWork((s) => inactive(direction, s))
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)
return ( return (
@@ -114,7 +124,7 @@ function HistoryButton({
type="button" type="button"
aria-label={name} aria-label={name}
title={`${name} (${t(`editor.history.${direction}_shortcut`)})`} title={`${name} (${t(`editor.history.${direction}_shortcut`)})`}
aria-disabled={readOnly || !steppable || creating} aria-disabled={readOnly || !steppable || held}
aria-keyshortcuts={SHORTCUT[direction]} aria-keyshortcuts={SHORTCUT[direction]}
{...press} {...press}
className={BUTTON} className={BUTTON}
@@ -104,6 +104,8 @@ function vertexKey(input: ZoneEditInput, index: number, event: KeyboardEvent) {
return inMoveMode() ? input.confirmMove() : commitKeys(input) return inMoveMode() ? input.confirmMove() : commitKeys(input)
} }
if (event.key !== 'Insert' && event.key !== 'Delete') return if (event.key !== 'Insert' && event.key !== 'Delete') return
// Final review I-1: a move mode changes the position only, as the press machine does.
if (inMoveMode()) return
// I-1: arrow steps still pending are committed first; the change applies to that place. // I-1: arrow steps still pending are committed first; the change applies to that place.
commitKeys(input) commitKeys(input)
const chosen = id ? freshChosen(id) : null const chosen = id ? freshChosen(id) : null
@@ -139,16 +141,17 @@ export function useZoneEdit(input: ZoneEditInput) {
}, },
// BDR-050: leaving the vertex commits its series; a move mode waits for « Valider ». // BDR-050: leaving the vertex commits its series; a move mode waits for « Valider ».
onVertexBlur: () => commitKeys(input), onVertexBlur: () => commitKeys(input),
// Final review I-1: in a move mode « + » and « − » do nothing (no click there either).
onInsertKey: (after: number, event: KeyboardEvent) => { onInsertKey: (after: number, event: KeyboardEvent) => {
if (!isPress(event)) return if (!isPress(event)) return
event.preventDefault() event.preventDefault()
insertAfter(input, after) if (!inMoveMode()) insertAfter(input, after)
}, },
// The bubble's own index is the chosen vertex (it is drawn only over that one). // The bubble's own index is the chosen vertex (it is drawn only over that one).
onRemoveKey: (_index: number, event: KeyboardEvent) => { onRemoveKey: (_index: number, event: KeyboardEvent) => {
if (!isPress(event)) return if (!isPress(event)) return
event.preventDefault() event.preventDefault()
deleteChosen(input) if (!inMoveMode()) deleteChosen(input)
}, },
} }
} }
@@ -155,6 +155,16 @@ export function cancelPending(): boolean {
return true 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.
*/
export function holdsRedo(work: Pick<Work, 'mode' | 'preview'>): boolean {
if (work.mode?.started) return true
return work.preview !== null && work.preview.source !== 'move'
}
const fresh = <T extends { base: string }>(item: T | null, text: string) => const fresh = <T extends { base: string }>(item: T | null, text: string) =>
item && item.base !== text ? null : item item && item.base !== text ? null : item
+9 -2
View File
@@ -1,5 +1,9 @@
import { useEffect } from 'react' import { useEffect } from 'react'
import { cancelPending, useAnnotationWork } from './annotations/workStore' import {
cancelPending,
holdsRedo,
useAnnotationWork,
} from './annotations/workStore'
import { isTextField } from './focusRequest' import { isTextField } from './focusRequest'
import { useEditorStore } from './state/editorStore' import { useEditorStore } from './state/editorStore'
@@ -23,7 +27,10 @@ export function useUndoShortcuts(writable: boolean): void {
return return
event.preventDefault() event.preventDefault()
const store = useEditorStore.getState() const store = useEditorStore.getState()
if (event.shiftKey) store.redoStep() // I-1: a redo would drop pending work without a word; it waits for it.
if (event.shiftKey) {
if (!holdsRedo(useAnnotationWork.getState())) store.redoStep()
}
// R-13: a pending preview or mode is only cancelled; the next undo undoes. // R-13: a pending preview or mode is only cancelled; the next undo undoes.
else if (!cancelPending()) store.undoStep() else if (!cancelPending()) store.undoStep()
} }
@@ -395,12 +395,14 @@ describe('final review: queued landings (M-6)', () => {
describe('the drawing guard (R-12): a move mode and the navigations', () => { describe('the drawing guard (R-12): a move mode and the navigations', () => {
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(resetWork) afterEach(() => act(() => resetWork()))
const tabShown = () => screen.getByRole('tab', { selected: true }) const tabShown = () => screen.getByRole('tab', { selected: true })
const started = () => { // In act: « Refaire » now follows a started mode (final review I-1) and re-renders.
startMove('a', 'doc') const started = () =>
setModePreview({ ...STORED, cx: 9 }, STORED) act(() => {
} startMove('a', 'doc')
setModePreview({ ...STORED, cx: 9 }, STORED)
})
it('with no step taken, a tab ends the mode at once, without a question', async () => { it('with no step taken, a tab ends the mode at once, without a question', async () => {
useLocaleStore.setState({ locale: 'fr' }) useLocaleStore.setState({ locale: 'fr' })
@@ -131,3 +131,57 @@ describe('undo with something pending (R-13)', () => {
expect(cx()).toMatchObject({ cx: 50 }) expect(cx()).toMatchObject({ cx: 50 })
}) })
}) })
describe('redo with something pending (final review I-1)', () => {
const REDO = 'Refaire la dernière modification défaite'
/** A commit undone: the redo stack holds it, the shape is back at cx 50. */
async function undone() {
mountDraft()
await ready()
act(() => void commitMove(40))
ctrlZ(document.body)
expect(cx()).toMatchObject({ cx: 50 })
}
const pend = (source: 'keys' | 'size') => {
const stored = store.getState().previewState!.document.annotations[0]
act(() =>
useAnnotationWork.setState({
preview: {
annotationId: stored.id,
geometry: { type: 'circle', cx: 60, cy: 50, r: 10 },
base: store.getState().documentText,
source,
},
}),
)
}
it('Ctrl+Shift+Z keeps a pending size change and redoes nothing', async () => {
await undone()
pend('size')
ctrlZ(document.body, true)
expect(useAnnotationWork.getState().preview?.source).toBe('size')
expect(cx()).toMatchObject({ cx: 50 })
})
it('the header « Refaire » is off and keeps a keyboard series', async () => {
await undone()
pend('keys')
const redo = screen.getByRole('button', { name: REDO })
// A click that leaves the focus in place (Safari does not focus a clicked button).
fireEvent.click(redo)
expect(useAnnotationWork.getState().preview?.source).toBe('keys')
expect(cx()).toMatchObject({ cx: 50 })
expect(redo).toHaveAttribute('aria-disabled', 'true')
})
it('once the work is gone, redo works again', async () => {
await undone()
pend('keys')
act(() => useAnnotationWork.setState({ preview: null }))
const redo = screen.getByRole('button', { name: REDO })
expect(redo).toHaveAttribute('aria-disabled', 'false')
fireEvent.click(redo)
expect(cx()).toMatchObject({ cx: 40 })
})
})
@@ -12,6 +12,7 @@ import {
import userEvent from '@testing-library/user-event' import userEvent from '@testing-library/user-event'
import type { Annotation, Point } from '@faunosteo/core-wasm/types' import type { Annotation, Point } from '@faunosteo/core-wasm/types'
import AnnotationsTab from '@/components/editor/tabs/AnnotationsTab' import AnnotationsTab from '@/components/editor/tabs/AnnotationsTab'
import HistoryButtons from '@/components/editor/HistoryButtons'
import { answerDrawing, guardDrawing } from '@/editor/annotations/drawingGuard' import { answerDrawing, guardDrawing } from '@/editor/annotations/drawingGuard'
import { useAnnotationWork, resetWork } from '@/editor/annotations/workStore' import { useAnnotationWork, resetWork } from '@/editor/annotations/workStore'
import { useUndoShortcuts } from '@/editor/useUndoShortcuts' import { useUndoShortcuts } from '@/editor/useUndoShortcuts'
@@ -892,3 +893,115 @@ describe('M-5: « Fermeture refusée » titles a refused close only', () => {
expect(lead.title).toBe('Fermeture refusée') expect(lead.title).toBe('Fermeture refusée')
}) })
}) })
describe('final review I-1: a redo or a handle key never drops pending work', () => {
const redoKey = (target: Element) =>
fireEvent.keyDown(target, { key: 'z', ctrlKey: true, shiftKey: true })
const canvas = () => screen.getByTestId('annotation-canvas')
const ABANDONED = /abandonné : la fiche a changé/
/** One committed step on vertex 1, undone: the redo stack holds it. */
async function withRedo() {
await mount(squareText())
render(<UndoKeys />)
await select()
act(() => vertex(1).focus())
fireEvent.keyDown(vertex(1), { key: 'ArrowRight' })
fireEvent.keyDown(vertex(1), { key: 'Enter' })
act(() => void store.getState().undoStep())
expect(store.getState().redo).toHaveLength(1)
}
async function startedMove(name = 'Déplacer la zone') {
await userEvent.setup().click(screen.getByRole('button', { name }))
const bar = screen.getByTestId('move-mode-bar')
fireEvent.click(
within(bar).getByRole('button', { name: 'Déplacer vers la droite' }),
)
expect(useAnnotationWork.getState().mode?.started).toBe(true)
}
it('Ctrl+Shift+Z on a vertex keyed with arrows keeps the series; Enter commits it', async () => {
await withRedo()
fireEvent.keyDown(vertex(1), { key: 'ArrowDown' })
redoKey(vertex(1))
expect(useAnnotationWork.getState().preview?.source).toBe('keys')
expect(store.getState().redo).toHaveLength(1)
fireEvent.keyDown(vertex(1), { key: 'Enter' })
expect(pointsOf('z')![0]).toEqual([20, 20.5])
})
it('Ctrl+Shift+Z in a started move keeps the move, said by nothing', async () => {
await withRedo()
await startedMove()
redoKey(document.body)
expect(useAnnotationWork.getState().mode).toMatchObject({
kind: 'move',
started: true,
})
expect(pointsOf('z')).toEqual(SQUARE)
expect(screen.queryByText(ABANDONED)).toBeNull()
})
it('the header « Refaire » is off in a started move and keeps it', async () => {
await withRedo()
render(<HistoryButtons />)
await startedMove()
const redo = screen.getByRole('button', {
name: 'Refaire la dernière modification défaite',
})
// A click that leaves the focus in place (Safari does not focus a clicked button).
fireEvent.click(redo)
expect(useAnnotationWork.getState().mode?.started).toBe(true)
expect(store.getState().redo).toHaveLength(1)
expect(screen.queryByText(ABANDONED)).toBeNull()
expect(redo).toHaveAttribute('aria-disabled', 'true')
})
it('Ctrl+Shift+Z in a started redraw keeps the trace', async () => {
await withRedo()
await userEvent
.setup()
.click(screen.getByRole('button', { name: 'Redessiner' }))
pressAt(canvas(), 30, 30)
redoKey(canvas())
expect(useAnnotationWork.getState().mode).toMatchObject({
kind: 'redraw',
started: true,
})
expect(
screen.getByRole('button', { name: 'Fermer le tracé' }),
).toBeInTheDocument()
expect(screen.queryByText(ABANDONED)).toBeNull()
})
it('in a started zone move, Enter or Space on « + » and Insert change nothing', async () => {
await mount(squareText())
await select()
await startedMove()
const before = depth()
fireEvent.keyDown(plus(1), { key: 'Enter' })
fireEvent.keyDown(plus(4), { key: ' ' })
fireEvent.keyDown(vertex(1), { key: 'Insert' })
expect(pointsOf('z')).toEqual(SQUARE)
expect(depth()).toBe(before)
expect(useAnnotationWork.getState().mode?.started).toBe(true)
expect(screen.queryByText(ABANDONED)).toBeNull()
})
it('in a started vertex move, Enter on « − », Insert and Delete change nothing', async () => {
await mount(squareText())
await select()
clickHandle('Sommet 3', [80, 80])
await startedMove('Déplacer le sommet')
const before = depth()
fireEvent.keyDown(minus(3), { key: 'Enter' })
fireEvent.keyDown(vertex(3), { key: 'Insert' })
fireEvent.keyDown(vertex(3), { key: 'Delete' })
fireEvent.keyDown(plus(2), { key: 'Enter' })
expect(pointsOf('z')).toEqual(SQUARE)
expect(depth()).toBe(before)
expect(useAnnotationWork.getState().mode?.started).toBe(true)
expect(screen.queryByText(ABANDONED)).toBeNull()
})
})