feat(editor): say why redo is unavailable during pending work

This commit is contained in:
bchanot committed 2026-11-19 12:38:26 +01:00
1 parent e341f03390
commit 00e995a6cb
7 files changed
+216 -21

No files matched your search

@@ -222,6 +222,31 @@ test.describe('editor annotations (A3)', () => {
).toBe('zone-a')
})
test('a held « Refaire » says why: description on focus, message on press, nothing moves', async ({
page,
requests,
}) => {
const { actor } = await openAnnotations(page)
requests.forbid(actor.account.email, actor.account.password)
const reason = dict['editor.history.hold_creation']
// A zone tracing is a creation with no modal dialog: the header stays reachable.
await tool(page, 'zone').click()
await clickDrawing(page, 600, 200)
const redo = historyButton(page, dict, 'redo')
await redo.focus()
await expect(redo).toHaveAttribute('aria-disabled', 'true')
await expect(redo).toHaveAccessibleDescription(reason)
await expect(historyButton(page, dict, 'undo')).toHaveAccessibleDescription(
reason,
)
await expectAccessible(page, 'a held « Refaire » during a creation')
await expectNoShift(page, async () => {
await pressAtBox(page, redo)
await expect(page.getByTestId('gesture-line')).toContainText(reason)
})
await expect(page.getByTestId('gesture-message')).toHaveCount(1)
})
test('a click with jitter never moves; a drag moves by the pointer delta', async ({
page,
requests,
@@ -10,7 +10,9 @@ import { canRedo, canUndo, useEditorStore } from '@/editor/state/editorStore'
import {
cancelPending,
holdsRedo,
pressHeldHistory,
useAnnotationWork,
type HistoryHold,
} from '@/editor/annotations/workStore'
import { useT } from '@/i18n/useT'
import EditorGlyph from './EditorGlyph'
@@ -39,13 +41,16 @@ function asField(element: Element | EventTarget | null): HTMLElement | null {
}
/**
* A12: both are inactive during a creation (R-13); I-1: redo also while work it would drop
* A12: both are held 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 = (
function holdOf(
direction: Direction,
work: ReturnType<typeof useAnnotationWork.getState>,
) => work.creation !== null || (direction === 'redo' && holdsRedo(work))
): HistoryHold | null {
if (work.creation !== null) return 'creation'
return direction === 'redo' && holdsRedo(work) ? 'pending' : null
}
/**
* The press, in two steps: leaving a field commits the typed text (its blur: forced at
@@ -80,8 +85,9 @@ function usePress(
left.current = asField(event.relatedTarget) ?? left.current
}
const onClick = () => {
// A12: undo and redo are inactive during a creation (R-13).
if (inactive(direction, useAnnotationWork.getState())) return
// A12, I-1: a held button does nothing but say why.
const hold = holdOf(direction, useAnnotationWork.getState())
if (hold) return pressHeldHistory(hold)
const field = left.current
forget()
if (field?.isConnected && field.getAttribute('aria-invalid') === 'true') {
@@ -116,24 +122,33 @@ function HistoryButton({
const t = useT()
const readOnly = useEditorReadOnly()
const steppable = useEditorStore(direction === 'undo' ? canUndo : canRedo)
const held = useAnnotationWork((s) => inactive(direction, s))
const hold = useAnnotationWork((s) => holdOf(direction, s))
const name = t(`editor.history.${direction}_title`)
const press = usePress(direction, readOnly, left)
const reasonId = `history-hold-${direction}`
return (
<button
type="button"
aria-label={name}
title={`${name} (${t(`editor.history.${direction}_shortcut`)})`}
aria-disabled={readOnly || !steppable || held}
aria-keyshortcuts={SHORTCUT[direction]}
{...press}
className={BUTTON}
>
<EditorGlyph name={direction} />
<span aria-hidden="true" className="hidden sm:inline">
{t(`editor.history.${direction}`)}
</span>
</button>
<>
<button
type="button"
aria-label={name}
title={`${name} (${t(`editor.history.${direction}_shortcut`)})`}
aria-disabled={readOnly || !steppable || hold !== null}
aria-describedby={hold ? reasonId : undefined}
aria-keyshortcuts={SHORTCUT[direction]}
{...press}
className={BUTTON}
>
<EditorGlyph name={direction} />
<span aria-hidden="true" className="hidden sm:inline">
{t(`editor.history.${direction}`)}
</span>
</button>
{hold && (
<span id={reasonId} className="sr-only">
{t(`editor.history.hold_${hold}`)}
</span>
)}
</>
)
}
@@ -1,4 +1,4 @@
import { useEffect, useReducer, useState, type Dispatch } from 'react'
import { useEffect, useReducer, useRef, useState, type Dispatch } from 'react'
import type {
AnatomicalSheetDocument,
Annotation,
@@ -203,6 +203,29 @@ function resumedOf({ creation, model }: Scene): ZoneTarget | null {
return geometry.type === 'polygon' ? { id: PENDING_ID, geometry } : null
}
/**
* A press on a held « Défaire » / « Refaire » (the header's buttons, outside this tree) says
* why on the line under the drawing. A press from before this tab mounted is not replayed.
*/
function useHeldHistoryMessage(
message: GestureMessages,
t: CommitContext['t'],
) {
const press = useAnnotationWork((s) => s.historyPress)
const seen = useRef(press)
useEffect(() => {
if (press === seen.current) return
seen.current = press
if (press) {
message.show(t(`editor.history.hold_${press.reason}`), {
undo: false,
tone: 'info',
})
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- show is rebuilt per render
}, [press])
}
/**
* The tab's work: the commit context, the line under the drawing, the placement, the
* editing of the movable selection (point handle keys, slider, move mode) and of a
@@ -212,6 +235,7 @@ function resumedOf({ creation, model }: Scene): ZoneTarget | null {
function useWork(scene: Scene) {
const context = useCommitContext()
const message = useGestureMessage()
useHeldHistoryMessage(message, context.t)
const placement = usePlacement({ ...scene, context, message })
useCreationFollow({ ...scene, message, t: context.t })
const target = movableOf(scene.selected, scene.model, scene.ui.tool)
@@ -87,6 +87,11 @@ interface Work {
question: DrawingQuestion | null
/** A two-finger pan or zoom worked in this editor visit: the hint never shows again (R-1). */
twoFingers: boolean
/**
* A press on a held « Défaire » / « Refaire »: the tab's message line says why. The serial
* makes a repeated press a new message, announced again.
*/
historyPress: { reason: HistoryHold; serial: number } | null
}
const NO_WORK: Work = {
creation: null,
@@ -98,10 +103,20 @@ const NO_WORK: Work = {
dropped: null,
question: null,
twoFingers: false,
historyPress: null,
}
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'
/** A press on a held history button: the message line says why (see `historyPress`). */
export function pressHeldHistory(reason: HistoryHold): void {
const serial = (useAnnotationWork.getState().historyPress?.serial ?? 0) + 1
useAnnotationWork.setState({ historyPress: { reason, serial } })
}
/** R-12: what a navigation must ask about; an unstarted mode asks nothing and simply ends. */
export function guardWork(work: Work): GuardWork {
if (work.creation !== null) return 'creation'
+4
View File
@@ -1413,6 +1413,10 @@ export const en: Dict = {
'editor.history.undo_shortcut': 'Ctrl+Z or ⌘Z',
'editor.history.redo_title': 'Redo the last undone change',
'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_pending':
'Redo waits for the change in progress: confirm or cancel it.',
'editor.draft.status.saving': 'Saving…',
'editor.draft.status.copy_quota':
'Temporary local copy impossible (tab full): not saved on the server',
+4
View File
@@ -1470,6 +1470,10 @@ export const fr: Dict = {
'editor.history.redo': 'Refaire',
'editor.history.redo_title': 'Refaire la dernière modification défaite',
'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_pending':
'Refaire attend la fin de la modification en cours : validez-la ou annulez-la.',
'editor.draft.status.saving': 'Enregistrement…',
'editor.draft.status.copy_quota':
'Copie locale temporaire impossible (onglet plein) : non enregistré sur le serveur',
@@ -14,6 +14,9 @@ import DeleteDialog from '@/components/editor/DeleteDialog'
import { en } from '@/i18n/en'
import { fr } from '@/i18n/fr'
import { useLocaleStore } from '@/state/localeStore'
import { emptyForm } from '@/editor/annotations/creation'
import { traceVertex } from '@/editor/annotations/creationWork'
import { useAnnotationWork, resetWork } from '@/editor/annotations/workStore'
import {
baseText,
commitMove,
@@ -559,3 +562,108 @@ describe('« Abandonner les modifications »', () => {
).toBeNull()
})
})
describe('why a button is held (point 6)', () => {
const CREATION =
"Indisponible pendant une création : créez l'annotation ou abandonnez-la."
const PENDING =
'Refaire attend la fin de la modification en cours : validez-la ou annulez-la.'
const STORED = { type: 'circle' as const, cx: 1, cy: 2, r: 3 }
afterEach(() => act(() => resetWork()))
const line = () => screen.getByTestId('gesture-line')
const reason = (button: HTMLElement) => {
const id = button.getAttribute('aria-describedby')
return id ? document.getElementById(id)?.textContent : null
}
async function openAnnotations() {
const user = userEvent.setup()
mountDraft()
await ready()
await user.click(screen.getByRole('tab', { name: 'Annotations' }))
await screen.findByTestId('gesture-line')
return user
}
const create = () =>
act(() =>
traceVertex(
{
viewId: 'v',
frame: null,
origin: 'tool',
form: emptyForm({ categories: [] } as never),
},
'zone',
[1, 1],
),
)
// A slider change in progress: a size preview on the stored document (I-1).
const pend = () =>
act(() =>
useAnnotationWork.setState({
preview: {
annotationId: 'anno-a',
geometry: { ...STORED, r: 9 },
base: store.getState().documentText,
source: 'size',
},
}),
)
it('a creation describes both buttons and every press says why, once', async () => {
const user = await openAnnotations()
create()
expect(reason(undoButton())).toBe(CREATION)
expect(reason(redoButton())).toBe(CREATION)
expect(disabled(redoButton())).toBe(true)
await user.click(redoButton())
expect(line()).toHaveTextContent(CREATION)
const first = within(line()).getByTestId('gesture-message')
redoButton().focus()
await user.keyboard('{Enter}')
expect(line()).toHaveTextContent(CREATION)
expect(within(line()).getByTestId('gesture-message')).not.toBe(first)
await user.keyboard(' ')
expect(within(line()).getAllByTestId('gesture-message')).toHaveLength(1)
undoButton().focus()
await user.keyboard('{Enter}')
expect(line()).toHaveTextContent(CREATION)
})
it('pending work holds redo only, with its own reason', async () => {
const user = await openAnnotations()
pend()
expect(reason(redoButton())).toBe(PENDING)
expect(reason(undoButton())).toBeNull()
await user.click(redoButton())
expect(line()).toHaveTextContent(PENDING)
})
it('say it in English', async () => {
const user = await openAnnotations()
act(() => useLocaleStore.setState({ locale: 'en' }))
create()
const redo = screen.getByRole('button', {
name: 'Redo the last undone change',
})
expect(reason(redo)).toBe(
'Unavailable during a creation: create the annotation or discard it.',
)
await user.click(redo)
expect(line()).toHaveTextContent('Unavailable during a creation')
})
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()
cleanup()
resetStore()
serverHas(baseText(), 3)
mountDraft({ width: 800 })
await ready()
await user.click(undoButton())
expect(reason(undoButton())).toBeNull()
expect(reason(redoButton())).toBeNull()
})
})