fix(editor): no silent move loss, no empty commit, focus kept

- « Toutes les annotations » in the properties panel asks the drawing
  guard before it drops a started move (R-12); tests also cover a tool
  and « Ajouter un point ».
- A keyboard series back on its place, or a slider pinned at its stop,
  commits nothing.
- Escape that deselects from the handle or the slider moves the focus to
  the row (or the drawing) instead of losing it.
- A link circle keeps its handle, named « Accès {nom} », with no slider
  and no move mode (no label for it in REVUE).
- The move-mode drop notice waits until the body is shown (R-14).
- No layout shift: the strip's lead has a fixed width, the commands and
  the message pill get a new box per set or message.
- Doc: hit shapes use pointer-events auto; the fine « − » bubble is
  board 05's size.
- Tests: R-14 flip, A5 through the Point tool click, the repair e2e
  wrapped in expectNoShift.
This commit is contained in:
bchanot committed 2026-11-17 19:08:08 +01:00
1 parent 91e94952f0
commit 44de465c6d
10 files changed
+240 -35

No files matched your search

+21 -5
View File
@@ -1,6 +1,7 @@
import { fr } from '@/i18n/fr'
import type { Page, TestInfo } from '@playwright/test'
import { expect, expectAccessible, test } from '../support/browser'
import { expectNoShift } from '../support/layout'
import { dropLateReplays, routeToSandbox } from '../support/sandbox'
import {
place,
@@ -198,9 +199,18 @@ test.describe('editor geometry (adversarial)', () => {
})
// A partial move (still out of the frame): refused by the core, the point restored.
await move.click()
// Nothing around the drawing moves (A14); the side panel's content may (Task 6).
const swaps = ['aside-content'] as const
await expectNoShift(page, () => move.click(), swaps)
await dragInMode(page, { x: 250, y: 250 }, { x: 260, y: 260 })
await confirm.click()
await expectNoShift(
page,
async () => {
await confirm.click()
await expect(page.getByTestId('gesture-message')).toBeVisible()
},
swaps,
)
await expect(page.getByTestId('gesture-message')).toContainText(
dict['editor.annotations.message.move_refused'].split(' :')[0],
)
@@ -209,10 +219,16 @@ test.describe('editor geometry (adversarial)', () => {
await expect(issues).toBeVisible()
// Far enough inside: kept, the issue gone, one error less.
await move.click()
await expectNoShift(page, () => move.click(), swaps)
await dragInMode(page, { x: 250, y: 250 }, { x: 290, y: 290 })
await confirm.click()
await expect(issues).toHaveCount(0)
await expectNoShift(
page,
async () => {
await confirm.click()
await expect(issues).toHaveCount(0)
},
swaps,
)
expect(Math.abs(Number(await cx.inputValue()) - 150)).toBeLessThan(2)
const after = (await verification.innerText()).replace(/\D/g, '')
expect(Number(after || 0)).toBeLessThan(errorsBefore)
@@ -60,7 +60,9 @@ function Lead({ lead }: { lead: StripLead }) {
return (
<div
data-testid="edit-strip-lead"
className="flex min-w-0 max-w-[45%] shrink items-start gap-2"
// A fixed width: a longer or shorter lead (a mode, a tracing) never moves the
// notice beside it (A14).
className="flex w-2/5 min-w-0 shrink-0 items-start gap-2"
>
<span className="mt-0.5 shrink-0 text-[var(--color-ink-muted)]">
<EditorGlyph name={lead.icon} size={16} />
@@ -177,17 +177,21 @@ function useModeFollowsSelection(selectedId: string | null) {
}, [modeId, selectedId])
}
/** R-13: a started mode a change made elsewhere dropped is said on the line. */
/**
* R-13: a started mode a change made elsewhere dropped is said on the line, once the body
* is shown (a drop while read-only is said on the way back).
*/
function useDroppedNotice(message: GestureMessages) {
const t = useT()
const visible = usePlaceVisible()
const dropped = useAnnotationWork((s) => s.dropped)
const show = message.show
useEffect(() => {
if (dropped === null) return
if (dropped === null || !visible) return
useAnnotationWork.setState({ dropped: null })
const text = t(`editor.annotations.dropped.${dropped}`)
show(text, { undo: false, tone: 'info' })
}, [dropped, show, t])
}, [dropped, visible, show, t])
}
export default function EditableAnnotations(props: Props) {
@@ -253,15 +257,19 @@ function CanvasColumn({
)
}
/** The point handle of the movable selected circle, named « Point {nom} ». */
/** The handle of the movable selected circle, named « Point {nom} » (« Accès {nom} »). */
function useHandle(target: Annotation | null, doc: AnatomicalSheetDocument) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
if (!target?.geometry) return null
const name = annotationName(target, doc.views, locale)
const kind = t(`editor.annotations.kind.${target.kind}`)
const label = t('editor.annotations.handle.shape')
.replace('{kind}', () => kind)
.replace('{name}', () => name)
return {
annotationId: target.id,
label: t('editor.annotations.handle.point').replace('{name}', () => name),
label,
stored: target.geometry,
}
}
@@ -369,7 +377,8 @@ function SidePanel({
dispatch={dispatch}
context={context}
navigate={scene.navigate}
onShowAll={() => dispatch({ type: 'select', id: null })}
// « Tout afficher » leaves the selection: a started move asks first (R-12).
onShowAll={guarded(() => dispatch({ type: 'select', id: null }))}
busy={ui.tracing !== null || moving}
/>
)
@@ -436,7 +445,7 @@ function SceneStrip({ scene, work }: { scene: Scene; work: Work }) {
lead={lead}
notice={notice}
commands={<SceneCommands scene={scene} work={work} />}
commandsKey={commandsKeyOf(ui, moving, work.target !== null)}
commandsKey={commandsKeyOf(ui, moving, work.target?.kind === 'point')}
/>
)
}
@@ -459,7 +468,8 @@ function SceneCommands({ scene, work }: { scene: Scene; work: Work }) {
/>
)
}
if (work.target) {
// A link circle keeps its handle but has no size and no move mode (R-10; no label).
if (work.target?.kind === 'point') {
const props = { doc, viewId, frame, edit: work.edit }
return <SelectionPointCommands annotation={work.target} {...props} />
}
@@ -48,8 +48,11 @@ function Message({ messages }: { messages: GestureMessages }) {
const { message, hold } = messages
if (!message) return null
const error = message.tone === 'error'
const { stamp } = message
return (
<p
// Another message is another pill: a wider one replacing it moves no box (A14).
key={`${message.text}|${stamp.undo}|${stamp.redo}|${stamp.text.length}`}
data-testid="gesture-message"
role={error ? 'alert' : undefined}
{...hold}
+11 -4
View File
@@ -24,6 +24,12 @@ export function focusRowOrDrawing(id: string): boolean {
return focusRow({ kind: 'annotation', id }) || focusDrawing()
}
/** The focused element left with the selection (a handle, the slider): the row takes it. */
function focusIfLost(id: string): void {
const active = document.activeElement
if (active === null || active === document.body) focusRowOrDrawing(id)
}
/** After a tap on the drawing: the box takes the focus, unless it already holds it. */
function drawingFocus(): void {
if (visibleElement(CANVAS_BOX) !== document.activeElement) focusDrawing()
@@ -31,9 +37,9 @@ function drawingFocus(): void {
/**
* Deselecting: `id` is the RESOLVED selection (never the raw id, which can name a removed
* annotation). The button always moves the focus to the row; Escape does only when it was
* pressed inside the properties panel, whose focused element is about to leave the page.
* Anywhere else the focus stays where it is. Both answer whether something was deselected.
* annotation). The button always moves the focus to the row; Escape does when it was
* pressed inside the properties panel, or when the focused element left with the selection
* (the handle, the slider, « Déplacer le point »). Anywhere else the focus stays where it is. Both answer whether something was deselected.
*/
export function useDeselect(id: string | null, clear: () => void) {
const t = useT()
@@ -50,7 +56,8 @@ export function useDeselect(id: string | null, clear: () => void) {
}
return {
byButton: () => run(focusRowOrDrawing),
byKey: (fromPanel: boolean) => run(fromPanel ? focusRowOrDrawing : null),
byKey: (fromPanel: boolean) =>
run(fromPanel ? focusRowOrDrawing : focusIfLost),
byDrawing: () => run(drawingFocus),
}
}
@@ -4,7 +4,12 @@ import { useEditorStore } from '../state/editorStore'
import { moveStep, type Frame } from './frame'
import type { GeometryChange } from './usePlacement'
import { takeMove, takePreview, stepSelection } from './previewCommit'
import { endMode, startMove, useAnnotationWork } from './workStore'
import {
endMode,
startMove,
useAnnotationWork,
type Preview,
} from './workStore'
type Drop = (id: string, geometry: Geometry, change?: GeometryChange) => void
@@ -40,15 +45,26 @@ function step(input: PointEditInput, direction: Direction, big: boolean) {
stepSelection(target.id, target.geometry, { x: x * size, y: y * size })
}
/** The commits of the pending work: each takes its preview, fresh only (R-13). */
function commits(onDrop: Drop) {
/** A preview back on the stored shape (there and back, a pinned slider) is no change. */
function changed(
preview: Preview | null,
target: Annotation | null,
): preview is Preview {
if (!preview || preview.annotationId !== target?.id) return false
return JSON.stringify(preview.geometry) !== JSON.stringify(target.geometry)
}
/** The commits of the pending work: each takes its preview, fresh and changed only (R-13). */
function commits({ onDrop, target }: PointEditInput) {
const keys = () => {
const preview = takePreview('keys')
if (preview) onDrop(preview.annotationId, preview.geometry)
if (changed(preview, target)) onDrop(preview.annotationId, preview.geometry)
}
const size = () => {
const preview = takePreview('size')
if (preview) onDrop(preview.annotationId, preview.geometry, 'size')
if (changed(preview, target)) {
onDrop(preview.annotationId, preview.geometry, 'size')
}
}
const move = () => {
const preview = takeMove()
@@ -80,7 +96,7 @@ function handleKeys(input: PointEditInput, commit: ReturnType<typeof commits>) {
* « Valider la position » committing once, « Annuler »).
*/
export function usePointEdit(input: PointEditInput) {
const commit = commits(input.onDrop)
const commit = commits(input)
return {
onHandleKey: handleKeys(input, commit),
// BDR-050: leaving the handle commits its series; a move mode waits for « Valider ».
+1 -1
View File
@@ -1672,7 +1672,7 @@ export const en: Dict = {
'editor.annotations.move.right': 'Move right',
'editor.annotations.move.confirm': 'Confirm position',
'editor.annotations.move.cancel': 'Cancel',
'editor.annotations.handle.point': 'Point {name}',
'editor.annotations.handle.shape': '{kind} {name}',
'editor.annotations.guard.move': 'Discard the move?',
'editor.annotations.guard.redraw': 'Discard the new tracing?',
'editor.annotations.guard.creation': 'Discard the creation?',
+1 -1
View File
@@ -1702,7 +1702,7 @@ export const fr: Dict = {
'editor.annotations.move.right': 'Déplacer vers la droite',
'editor.annotations.move.confirm': 'Valider la position',
'editor.annotations.move.cancel': 'Annuler',
'editor.annotations.handle.point': 'Point {name}',
'editor.annotations.handle.shape': '{kind} {name}',
'editor.annotations.guard.move': 'Abandonner le déplacement ?',
'editor.annotations.guard.redraw': 'Abandonner le nouveau tracé ?',
'editor.annotations.guard.creation': 'Abandonner la création ?',
+157 -6
View File
@@ -26,6 +26,7 @@ import {
USER,
VERSION,
openReady,
pressAt,
resetStore,
sb,
store,
@@ -88,22 +89,53 @@ afterEach(() => {
resetWork()
})
/** A link circle on the main view, opening the detail view `view-det` it adds first. */
const withLink = (text: string, id: string) => {
const withView = insert(text, {
kind: 'view',
value: {
kind: 'detail',
id: 'view-det',
name: { fr: 'Tête', en: 'Head' },
svg_asset_id: null,
view_box: { min_x: 10, min_y: 10, width: 80, height: 80 },
parent_view_id: 'view-main',
},
})
const value = {
id,
view_id: 'view-main',
category_id: 'cat-a',
laterality: 'unpaired',
geometry: { type: 'circle', cx: 70, cy: 70, r: 6 },
review_status: 'to_confirm',
color: null,
kind: 'detail_trigger',
name: null,
opens_view_id: 'view-det',
} as Annotation
return insert(withView, { kind: 'annotation', value })
}
const withPoints = (...points: ReturnType<typeof point>[]) =>
points.reduce((text, p) => insert(text, p), drawnText())
const tab = (readOnly = false) => (
// The Escape listener acts inside the editor workspace only.
<div data-editor-workspace>
<AnnotationsTab {...props} readOnly={readOnly} />
</div>
)
async function mount(text: string) {
await openReady({ text })
// The Escape listener acts inside the editor workspace only.
render(
<div data-editor-workspace>
<AnnotationsTab {...props} />
</div>,
)
const view = render(tab())
await waitFor(() =>
expect(
screen.getByTestId('annotation-canvas-drawing').querySelector('svg'),
).not.toBeNull(),
)
return view
}
/** The same tab on a 4000 × 3000 drawing: the core gives the main view a minimum radius. */
@@ -435,3 +467,122 @@ describe('A5: a new point takes the most used size', () => {
expect(slider()).toHaveValue('9')
})
})
describe('review fixes: no silent loss, no empty commit, no lost focus', () => {
const two = () => withPoints(point('a', 50, 50, 5), point('b', 20, 20, 5))
const started = async () => {
const view = await mount(two())
await select()
await userEvent.setup().click(moveButton())
fireEvent.click(arrow('la droite'))
return view
}
const question = () => useAnnotationWork.getState().question?.work ?? null
it('« Tout afficher », a tool and « Ajouter un point » ask before a started move goes', async () => {
await started()
const panel = screen.getByTestId('annotation-properties')
fireEvent.click(
within(panel).getByRole('button', { name: 'Toutes les annotations' }),
)
expect(question()).toBe('move')
expect(useAnnotationWork.getState().mode?.started).toBe(true)
expect(screen.getByTestId('annotation-properties')).toBeInTheDocument()
act(() => useAnnotationWork.setState({ question: null }))
fireEvent.click(screen.getByRole('button', { name: 'Point' }))
expect(question()).toBe('move')
expect(screen.getByTestId('move-mode-bar')).toBeInTheDocument()
act(() => useAnnotationWork.setState({ question: null }))
fireEvent.click(screen.getByRole('button', { name: 'Ajouter un point' }))
expect(question()).toBe('move')
expect(screen.queryByTestId('annotation-creation')).toBeNull()
})
it('an unstarted mode ends at once on a tool change', async () => {
await mount(two())
await select()
await userEvent.setup().click(moveButton())
fireEvent.click(screen.getByRole('button', { name: 'Point' }))
expect(question()).toBeNull()
expect(useAnnotationWork.getState().mode).toBeNull()
})
it('a series back on its place and a slider pinned at its stop commit nothing', async () => {
await mount(two())
await select()
const before = depth()
fireEvent.keyDown(handle(), { key: 'ArrowRight' })
fireEvent.keyDown(handle(), { key: 'ArrowLeft' })
fireEvent.keyDown(handle(), { key: 'Enter' })
fireEvent.keyDown(slider(), { key: 'PageUp' })
fireEvent.blur(slider())
expect(depth()).toBe(before)
expect(message()).not.toHaveTextContent('Défaire')
})
it('Escape that deselects from the handle or the slider keeps the focus on the page', async () => {
await mount(two())
await select()
handle().focus()
fireEvent.keyDown(handle(), { key: 'Escape' })
expect(screen.queryByTestId('annotation-properties')).toBeNull()
expect(document.activeElement).not.toBe(document.body)
await select()
slider().focus()
fireEvent.keyDown(slider(), { key: 'Escape' })
expect(screen.queryByTestId('annotation-properties')).toBeNull()
expect(document.activeElement).not.toBe(document.body)
})
it('R-14: a read-only flip suspends a started mode; it resumes and commits after', async () => {
const view = await started()
const before = depth()
view.rerender(tab(true))
expect(useAnnotationWork.getState().mode?.started).toBe(true)
view.rerender(tab(false))
expect(screen.getByTestId('move-mode-bar')).toBeInTheDocument()
fireEvent.click(
within(bar()).getByRole('button', { name: 'Valider la position' }),
)
expect(geometryOf('a')).toMatchObject({ cx: 50.5 })
expect(depth()).toBe(before + 1)
})
it('a link circle keeps its handle (« Accès … ») but gets no size and no move mode', async () => {
await mount(withLink(two(), 'l'))
await select(2)
expect(screen.getByTestId('point-handle')).toHaveAccessibleName(/^Accès /)
expect(screen.queryByTestId('size-slider')).toBeNull()
expect(
screen.queryByRole('button', { name: 'Déplacer le point' }),
).toBeNull()
})
})
describe('A5 through the Point tool click', () => {
const sized = () =>
withPoints(
point('a', 20, 20, 7),
point('b', 40, 40, 7),
point('c', 60, 60, 9),
)
it('a click places the point at the most used size, or at the size the slider chose', async () => {
await mount(sized())
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'Point' }))
pressAt(screen.getByTestId('annotation-canvas'), 50, 80)
const panel = await screen.findByTestId('annotation-creation')
expect(within(panel).getByLabelText('Rayon')).toHaveValue('7')
})
it('a size chosen on the slider before the click feeds it', async () => {
await mount(sized())
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'Point' }))
fireEvent.change(slider(), { target: { value: '9' } })
pressAt(screen.getByTestId('annotation-canvas'), 50, 80)
const panel = await screen.findByTestId('annotation-creation')
expect(within(panel).getByLabelText('Rayon')).toHaveValue('9')
})
})
+3 -3
View File
@@ -159,8 +159,8 @@ overlay in the same transformed container, with the same `viewBox` and
`preserveAspectRatio`. It is not `aria-hidden`: each handle is a focusable
`role="button"` (`tabindex="0"`) named after what it moves (« Point {nom} » for
a point), with a visible focus ring. The layer's root sets
`pointer-events: none`; each handle's hit shape sets `pointer-events: all` with
a transparent fill and carries `data-handle` (the JSON of its handle
`pointer-events: none`; each handle's hit shape turns it back on
(`pointer-events: auto`, painted shapes only) with a transparent fill and carries `data-handle` (the JSON of its handle
reference), which the press machine reads through `elementsFromPoint`. Handle
sizes are constant in CSS px under zoom: the layer divides them by the drawing's
px per unit (the box size over the frame, times the zoom). The device size is
@@ -169,7 +169,7 @@ read once from `(any-pointer: coarse)`:
| Device | Vertex | « + » | « − » bubble | Hit radius |
|---|---|---|---|---|
| Coarse (finger) | 18 px | 24 px | 44 × 36 px | 22 px |
| Fine (mouse, pen) | 12 px | 16 px | none | 10 px |
| Fine (mouse, pen) | 12 px | 16 px | board 05 size | 10 px |
The point handle covers the selected point's own circle (at least the hit
radius), so the whole marker can be held. A chosen vertex is drawn bigger,