From 91e94952f0b30a00d47e9148941bbf6008839c0c Mon Sep 17 00:00:00 2001 From: bchanot Date: Tue, 17 Nov 2026 18:50:29 +0100 Subject: [PATCH] feat(editor): point handle, size slider with core minimum, move mode MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit HandleLayer: its own svg over the overlay, not aria-hidden; the selected point (or link circle) gets a focusable « Point {nom} » handle whose hit circle (data-handle) the press machine reads, sized in CSS px under zoom (R-9, read once from any-pointer: coarse). The Task 2 stand-in (the selected marker as its own handle) is removed. Keys on the handle: arrows step 0.5 % of the frame (Shift x10) as a stamped series, Enter or blur commit once, Escape drops it (R-11, R-13). SizeSlider in the strip for a selected point and for the Point tool (A5): the view's sizes as ticks, the core minimum as a red mark, snap 8 px, arrows 1 %, Page Up/Down next size, one commit on release, Enter or blur; a refusal restores the size and draws the refused place in red dashes. « Déplacer le point » opens the move mode (board 06 B): drag anywhere or four arrows move a preview only, clicks select nothing, « Valider la position » commits once, « Annuler » and Escape restore; the focus comes back to the button. Escape follows board 32 (escapeAction). The overlay reads the preview from the work store and draws the old place in grey dashes. Ctrl+Z now also works from a slider (not a text field). Rewritten assertions: - editor-annotations-tab « a finger drags the selected point »: drag(marker('anno-a')) -> drag(pointHandle()), same expected geometry. - editor-geometry.spec « a point inherited out of its frame is repaired through the geometry group » (cx/cy typed 200) -> « ... repaired with the move mode »: a partial move refused and restored (cx 110, issue kept), then a move inside kept (issue gone, fewer errors). --- apps/app/e2e/shell/editor-annotations.spec.ts | 103 +++++ apps/app/e2e/shell/editor-geometry.spec.ts | 47 +- .../app/src/components/editor/EditorGlyph.tsx | 2 + .../editor/annotations/AnnotationCanvas.tsx | 30 +- .../editor/annotations/AnnotationOverlay.tsx | 38 +- .../editor/annotations/EditStrip.tsx | 10 +- .../annotations/EditableAnnotations.tsx | 217 ++++++--- .../editor/annotations/HandleLayer.tsx | 132 ++++++ .../editor/annotations/MoveModeBar.tsx | 64 +++ .../editor/annotations/PointCommands.tsx | 169 +++++++ .../editor/annotations/SizeSlider.tsx | 147 ++++++ apps/app/src/editor/annotations/deselect.ts | 48 +- apps/app/src/editor/annotations/handleSize.ts | 26 ++ .../src/editor/annotations/previewCommit.ts | 66 +++ .../src/editor/annotations/useBlockDrag.ts | 45 +- .../editor/annotations/useGestureMessage.ts | 23 +- .../src/editor/annotations/usePlacement.ts | 27 +- .../src/editor/annotations/usePointEdit.ts | 99 ++++ .../src/editor/annotations/usePressGesture.ts | 54 +-- apps/app/src/editor/useUndoShortcuts.ts | 6 +- .../unit/editor-annotations-tab.test.tsx | 11 +- .../app/tests/unit/editor-point-edit.test.tsx | 437 ++++++++++++++++++ .../tests/unit/editor-undo-shortcuts.test.tsx | 27 +- 23 files changed, 1679 insertions(+), 149 deletions(-) create mode 100644 apps/app/src/components/editor/annotations/HandleLayer.tsx create mode 100644 apps/app/src/components/editor/annotations/MoveModeBar.tsx create mode 100644 apps/app/src/components/editor/annotations/PointCommands.tsx create mode 100644 apps/app/src/components/editor/annotations/SizeSlider.tsx create mode 100644 apps/app/src/editor/annotations/handleSize.ts create mode 100644 apps/app/src/editor/annotations/previewCommit.ts create mode 100644 apps/app/src/editor/annotations/usePointEdit.ts create mode 100644 apps/app/tests/unit/editor-point-edit.test.tsx diff --git a/apps/app/e2e/shell/editor-annotations.spec.ts b/apps/app/e2e/shell/editor-annotations.spec.ts index bc86807a..fb80c6f1 100644 --- a/apps/app/e2e/shell/editor-annotations.spec.ts +++ b/apps/app/e2e/shell/editor-annotations.spec.ts @@ -394,6 +394,109 @@ test.describe('editor annotations (A3)', () => { }) } + test('the point (U2 Task 4): handle drag, size by a track click, the move mode', async ({ + page, + requests, + }) => { + const actor = await openWithPoint(page, 1280) + requests.forbid(actor.account.email, actor.account.password) + const swaps = ['aside-content'] as const + await expectNoShift( + page, + async () => { + await clickDrawing(page, 500, 300) + await expect(selectionTag(page)).toContainText('Pt A') + }, + swaps, + ) + const handle = page.getByRole('button', { name: 'Point Pt A' }) + await expect(handle).toHaveAttribute('tabindex', '0') + const slider = page.getByTestId('size-slider').getByRole('slider') + await expect(slider).toHaveValue('40') + await expectAccessible(page, 'a selected point: handle, slider, move') + + // The handle follows the pointer; the drop is one commit. + const cx = geometryField(page, dict, 'cx') + await expectNoShift( + page, + async () => { + await dragPoint(page, { x: 560, y: 330 }) + await expect(line(page)).toContainText( + dict['editor.annotations.message.moved.point'], + ) + }, + swaps, + ) + expect(Math.abs(Number(await cx.inputValue()) - 560)).toBeLessThan(2) + + // A click on the track, no drag (WCAG 2.5.7): one commit at the release. + const r = geometryField(page, dict, 'r') + const track = (await slider.boundingBox())! + await expectNoShift( + page, + async () => { + await page.mouse.click( + track.x + track.width * 0.8, + track.y + track.height / 2, + ) + await expect(line(page)).toContainText( + dict['editor.annotations.message.resized'], + ) + }, + swaps, + ) + expect(Number(await r.inputValue())).toBeGreaterThan(40) + await page.keyboard.press('Control+z') + await expect(r).toHaveValue('40') + + // The move mode: three steps (5 units each on a 1 000 px wide frame), validated once. + const x0 = Number(await cx.inputValue()) + await expectNoShift( + page, + () => button(page, 'editor.annotations.move.point').click(), + swaps, + ) + const right = button(page, 'editor.annotations.move.right') + await expect(right).toBeVisible() + await expectAccessible(page, 'the move mode') + for (let step = 0; step < 3; step++) await right.click() + await expect(cx).toHaveValue(String(x0)) + await expectNoShift( + page, + async () => { + await button(page, 'editor.annotations.move.confirm').click() + await expect(right).toHaveCount(0) + }, + swaps, + ) + await expect(cx).toHaveValue(String(x0 + 15)) + await expect(button(page, 'editor.annotations.move.point')).toBeFocused() + }) + + test('the point handle keeps its size in CSS px under zoom (R-9)', async ({ + page, + requests, + }) => { + await page.setViewportSize({ width: 1280, height: 800 }) + const actor = await editorActor('fr') + const tiny = pointOf('p-t', 'main', { cx: 500, cy: 300, r: 4 }, 'Pt T') + const seed = await seedDraft(actor, { shape: shapeWith(tiny) }) + await openEditor(page, dict, actor, seed.sheetId) + requests.forbid(actor.account.email, actor.account.password) + await pickAnnotation(page, dict, /Pt T/) + const hit = page.getByTestId('point-handle').locator('[data-handle]') + const fit = (await hit.boundingBox())! + // R-9: a 10 px hit radius with a mouse (Chromium desktop has a fine pointer). + expect(Math.abs(fit.width - 20)).toBeLessThan(2) + await page + .getByRole('button', { name: dict['catalogue.zoom.in'] }) + .click() + await expect + .poll(async () => Math.round((await hit.boundingBox())!.width)) + .toBeLessThan(22) + expect(Math.abs((await hit.boundingBox())!.width - 20)).toBeLessThan(2) + }) + test('the editor keeps a stable scrollbar gutter; the dashboard does not', async ({ page, requests, diff --git a/apps/app/e2e/shell/editor-geometry.spec.ts b/apps/app/e2e/shell/editor-geometry.spec.ts index 1354aa11..6d9817ec 100644 --- a/apps/app/e2e/shell/editor-geometry.spec.ts +++ b/apps/app/e2e/shell/editor-geometry.spec.ts @@ -23,7 +23,7 @@ import { // V1-2.6 geometry and adversarial cases (contract C7, C8, C21; owner 2026-11-04): a click // near the edge of a frame (the corrected position shown, confirmed and cancelled), a -// point inherited out of its frame repaired through the geometry group, a crop change +// point inherited out of its frame repaired with the move mode (U2 Task 4), a crop change // refused when it would invalidate a point, an unmeasured view with its tools disabled, // and the touch path (touch-action, pointer capture) in a real browser. @@ -52,6 +52,20 @@ async function proposed(page: Page): Promise<{ x: string; y: string }> { return { x: found[1], y: found[2] } } +/** A mouse drag on the drawing in the move mode, between two points in drawing units. */ +async function dragInMode( + page: Page, + from: { x: number; y: number }, + to: { x: number; y: number }, +) { + const start = await clientOf(page, from.x, from.y) + const end = await clientOf(page, to.x, to.y) + await page.mouse.move(start.x, start.y) + await page.mouse.down() + await page.mouse.move(end.x, end.y, { steps: 6 }) + await page.mouse.up() +} + async function fillNames(page: Page, fr: string, en: string) { await creation(page).getByLabel(dict['editor.annotations.name_fr']).fill(fr) await creation(page).getByLabel(dict['editor.annotations.name_en']).fill(en) @@ -155,7 +169,7 @@ test.describe('editor geometry (adversarial)', () => { await expect(selectionTag(page)).toContainText('Bord détail') }) - test('a point inherited out of its frame is repaired through the geometry group', async ({ + test('a point inherited out of its frame is repaired with the move mode', async ({ page, requests, }) => { @@ -175,14 +189,31 @@ test.describe('editor geometry (adversarial)', () => { (await verification.innerText()).replace(/\D/g, ''), ) expect(errorsBefore).toBeGreaterThan(0) - const cx = geometryField(page, dict, 'cx') - await cx.fill('200') - await cx.press('Enter') - const cy = geometryField(page, dict, 'cy') - await cy.fill('200') - await cy.press('Enter') + const move = page.getByRole('button', { + name: dict['editor.annotations.move.point'], + }) + const confirm = page.getByRole('button', { + name: dict['editor.annotations.move.confirm'], + }) + + // A partial move (still out of the frame): refused by the core, the point restored. + await move.click() + await dragInMode(page, { x: 250, y: 250 }, { x: 260, y: 260 }) + await confirm.click() + await expect(page.getByTestId('gesture-message')).toContainText( + dict['editor.annotations.message.move_refused'].split(' :')[0], + ) + await expect(page.getByTestId('overlay-refused-place')).toBeAttached() + await expect(cx).toHaveValue('110') + await expect(issues).toBeVisible() + + // Far enough inside: kept, the issue gone, one error less. + await move.click() + await dragInMode(page, { x: 250, y: 250 }, { x: 290, y: 290 }) + await confirm.click() await expect(issues).toHaveCount(0) + expect(Math.abs(Number(await cx.inputValue()) - 150)).toBeLessThan(2) const after = (await verification.innerText()).replace(/\D/g, '') expect(Number(after || 0)).toBeLessThan(errorsBefore) }) diff --git a/apps/app/src/components/editor/EditorGlyph.tsx b/apps/app/src/components/editor/EditorGlyph.tsx index f3862bba..533d12ed 100644 --- a/apps/app/src/components/editor/EditorGlyph.tsx +++ b/apps/app/src/components/editor/EditorGlyph.tsx @@ -10,6 +10,7 @@ export type GlyphName = | 'redo' | 'search' | 'deselect' + | 'move' /** The editor's one glyph table (24-unit grid strokes); `book` and `close` are in `Icon`. */ const GLYPHS: Record = { @@ -23,6 +24,7 @@ const GLYPHS: Record = { undo: 'M9 7L4 12l5 5M4 12h11a5 5 0 0 1 0 10', redo: 'M15 7l5 5-5 5M20 12H9a5 5 0 0 0 0 10', search: 'M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-4-4', + move: 'M12 3v18M3 12h18M9 6l3-3 3 3M9 18l3 3 3-3M6 9l-3 3 3 3M18 9l3 3-3 3', deselect: 'M4 8V5a1 1 0 0 1 1-1h3M16 4h3a1 1 0 0 1 1 1v3M20 16v3a1 1 0 0 1-1 1h-3M8 20H5a1 1 0 0 1-1-1v-3M9 9l6 6M15 9l-6 6', } diff --git a/apps/app/src/components/editor/annotations/AnnotationCanvas.tsx b/apps/app/src/components/editor/annotations/AnnotationCanvas.tsx index dbd98f34..8d74700c 100644 --- a/apps/app/src/components/editor/annotations/AnnotationCanvas.tsx +++ b/apps/app/src/components/editor/annotations/AnnotationCanvas.tsx @@ -16,6 +16,7 @@ import type { MoveTarget } from '@/editor/annotations/useBlockDrag' import type { ToolId } from '@/editor/annotations/uiState' import { useT } from '@/i18n/useT' import AnnotationOverlay, { type OverlayProps } from './AnnotationOverlay' +import HandleLayer, { type HandleLayerProps } from './HandleLayer' import ToolColumn, { type ToolColumnProps } from './ToolColumn' type OverlayData = Omit< @@ -23,6 +24,12 @@ type OverlayData = Omit< 'svgRef' | 'viewBox' | 'ratio' | 'dragged' > +/** The handle layer's content: the handle and its keys (the layer measures itself). */ +export type HandleData = Pick< + HandleLayerProps, + 'handle' | 'onKeyDown' | 'onBlur' +> + export interface AnnotationCanvasProps { viewId: string viewName: string @@ -31,6 +38,7 @@ export interface AnnotationCanvasProps { /** The selected annotation when it can be moved now. */ moveTarget: MoveTarget | null overlay: OverlayData + handles: HandleData tools: Omit /** The composed root as rebuilt (with its view); null on failure. */ onRoot: (root: RootAttributes | null) => void @@ -80,6 +88,7 @@ export default function AnnotationCanvas(props: AnnotationCanvasProps) { svgRef: overlay, dragged: gestures.drag, }, + handles: { ...props.handles, scale: gestures.framing.framing.scale }, }} /> @@ -135,10 +144,14 @@ interface LayerProps { root: RootAttributes | null transform: string overlay: Omit + handles: HandleData & { scale: number } } -/** The transformed box: the core's drawing and, in the same coordinates, the overlay. */ -function DrawingLayer({ host, root, transform, overlay }: LayerProps) { +/** + * The transformed box: the core's drawing and, in the same coordinates, the overlay and + * the handle layer above it. + */ +function DrawingLayer({ host, root, transform, overlay, handles }: LayerProps) { return (
{root?.viewBox && ( - + <> + + + )}
) diff --git a/apps/app/src/components/editor/annotations/AnnotationOverlay.tsx b/apps/app/src/components/editor/annotations/AnnotationOverlay.tsx index aefe2eab..80e834da 100644 --- a/apps/app/src/components/editor/annotations/AnnotationOverlay.tsx +++ b/apps/app/src/components/editor/annotations/AnnotationOverlay.tsx @@ -3,6 +3,7 @@ import type { Geometry, Point } from '@faunosteo/core-wasm/types' import type { Correction } from '@/editor/annotations/correction' import type { Frame } from '@/editor/annotations/frame' import { isEditable } from '@/editor/annotations/geometryEdit' +import { useAnnotationWork } from '@/editor/annotations/workStore' export interface OverlayProps { svgRef: Ref @@ -10,8 +11,11 @@ export interface OverlayProps { viewBox: string ratio: string frame: Frame | null + selectedId: string | null selected: Geometry | null dragged: Geometry | null + /** The place the core just refused (red dashes while its message shows). */ + refused: Geometry | null pending: Geometry | null tracing: Point[] | null correction: Correction | null @@ -105,16 +109,28 @@ function TracingPath({ points, size }: { points: Point[]; size: number }) { ) } +/** The selection's pending preview (move mode, slider, keys), read without the tab. */ +function usePreviewOf(selectedId: string | null): Geometry | null { + return useAnnotationWork((s) => + selectedId !== null && s.preview?.annotationId === selectedId + ? s.preview.geometry + : null, + ) +} + /** * The page-drawn overlay (docs/ANNOTATION-RENDERING.md « Editor overlay »): numbers only, * no annotation. Selection outline, vertex circles, the tracing in progress, the pending - * or dragged outline, a corrected position with the click marked apart. It never takes - * the pointer: the canvas box does. + * or dragged outline, a corrected position with the click marked apart; during a gesture + * the old place in grey dashes, after a refusal the refused place in red dashes. It never + * takes the pointer: the canvas box does. */ export default function AnnotationOverlay(props: OverlayProps) { - const { frame, selected, dragged, pending, tracing, correction } = props + const { frame, selected, pending, tracing, correction } = props const size = frame ? Math.max(frame.w, frame.h) / 200 : 1 - const shown = dragged ?? selected + const preview = usePreviewOf(props.selectedId) + const moved = props.dragged ?? preview + const shown = moved ?? selected return ( + {moved && selected && isEditable(selected) && ( + + + + )} + {props.refused && ( + + + + )} {shown && isEditable(shown) && ( <> diff --git a/apps/app/src/components/editor/annotations/EditStrip.tsx b/apps/app/src/components/editor/annotations/EditStrip.tsx index a7cf9b54..093c5c0a 100644 --- a/apps/app/src/components/editor/annotations/EditStrip.tsx +++ b/apps/app/src/components/editor/annotations/EditStrip.tsx @@ -25,10 +25,16 @@ export default function EditStrip({ lead, notice, commands, + commandsKey, }: { lead: StripLead notice: StripNotice | null commands: ReactNode + /** + * Which set of commands shows: a new set gets a new box, so a wider one never moves an + * existing box (A14: new content is no layout shift, a box moving is). + */ + commandsKey?: string }) { return (
{notice && }
-
{commands}
+
+ {commands} +
) } diff --git a/apps/app/src/components/editor/annotations/EditableAnnotations.tsx b/apps/app/src/components/editor/annotations/EditableAnnotations.tsx index be633208..af80cf89 100644 --- a/apps/app/src/components/editor/annotations/EditableAnnotations.tsx +++ b/apps/app/src/components/editor/annotations/EditableAnnotations.tsx @@ -3,12 +3,16 @@ import Button from '@/components/ui/Button' import type { AnatomicalSheetDocument, Annotation, + Geometry, } from '@faunosteo/core-wasm/types' import type { CommitContext } from '@/editor/annotations/annotationCommit' import { useAnnotationRequest } from '@/editor/annotations/focusTarget' import { keyboardPending, type NewKind } from '@/editor/annotations/creation' import { parseFrame, type Frame } from '@/editor/annotations/frame' import { newPointSize } from '@/editor/annotations/pointSize' +import { guardDrawing } from '@/editor/annotations/drawingGuard' +import { usePointEdit } from '@/editor/annotations/usePointEdit' +import { endMode, useAnnotationWork } from '@/editor/annotations/workStore' import { isEditable } from '@/editor/annotations/geometryEdit' import { useSelectionEscape } from '@/editor/annotations/deselect' import { usePlacement } from '@/editor/annotations/usePlacement' @@ -37,6 +41,12 @@ import type { EditorPlaceProps } from '@/editor/tabs' import { useT } from '@/i18n/useT' import { useLocaleStore } from '@/state/localeStore' import AnnotationCanvas from './AnnotationCanvas' +import { annotationName } from './AnnotationList' +import { + SelectionPointCommands, + ToolSize, + useMoveFocusReturn, +} from './PointCommands' import CreationPanel from './CreationPanel' import EditStrip, { type StripNotice } from './EditStrip' import GestureMessage from './GestureMessage' @@ -134,36 +144,70 @@ function useCommitContext(): CommitContext { return { t, locale } } -/** The tab's work: the commit context, the line under the drawing and the placement. */ +/** + * The tab's work: the commit context, the line under the drawing, the placement and the + * point editing (handle keys, slider, move mode) on the movable selected circle. + */ function useWork(scene: Scene) { const context = useCommitContext() const message = useGestureMessage() const placement = usePlacement({ ...scene, context, message }) - return { context, message, placement } + const target = circleTargetOf(scene.selected, scene.model, scene.ui.tool) + const edit = usePointEdit({ + target, + frame: scene.frame, + onDrop: placement.onDrop, + }) + useModeFollowsSelection(scene.ui.selectedId) + useDroppedNotice(message) + return { context, message, placement, edit, target } +} + +type Work = ReturnType + +/** + * The move mode belongs to the selection: another selection (a list row, a view change) + * ends it. A read-only flip keeps the body and its selection, so it suspends the mode + * instead (R-14). + */ +function useModeFollowsSelection(selectedId: string | null) { + const modeId = useAnnotationWork((s) => s.mode?.annotationId ?? null) + useEffect(() => { + if (modeId !== null && modeId !== selectedId) endMode() + }, [modeId, selectedId]) +} + +/** R-13: a started mode a change made elsewhere dropped is said on the line. */ +function useDroppedNotice(message: GestureMessages) { + const t = useT() + const dropped = useAnnotationWork((s) => s.dropped) + const show = message.show + useEffect(() => { + if (dropped === null) return + useAnnotationWork.setState({ dropped: null }) + const text = t(`editor.annotations.dropped.${dropped}`) + show(text, { undo: false, tone: 'info' }) + }, [dropped, show, t]) } export default function EditableAnnotations(props: Props) { const scene = useScene(props) - const { context, message, placement } = useWork(scene) + const work = useWork(scene) const { ui, selected } = scene const visible = usePlaceVisible() const { asideRef, byDrawing } = useSelectionEscape( selected?.id ?? null, () => scene.dispatch({ type: 'select', id: null }), - visible && selected !== undefined && ui.tracing === null && !ui.pending, + visible && selected !== undefined && ui.tracing === null, + { editable: true, creating: ui.pending !== null }, ) return (
- +
- +
@@ -172,15 +216,18 @@ export default function EditableAnnotations(props: Props) { type Placement = ReturnType +/** A move that drops the drawing's work asks first (R-12): the action runs once allowed. */ +const guarded = (action: () => void) => () => { + if (guardDrawing(action)) action() +} + function CanvasColumn({ scene, - placement, - message, + work, onDeselect, }: { scene: Scene - placement: Placement - message: GestureMessages + work: Work onDeselect: () => void }) { const { doc, dispatch, model } = scene @@ -190,37 +237,49 @@ function CanvasColumn({ dispatch({ type: 'view', viewId: id })} + onSelect={(id) => + guarded(() => dispatch({ type: 'view', viewId: id }))() + } /> - - + + addAtCentre(kind, scene)} + onAdd={(kind) => guarded(() => addAtCentre(kind, scene))()} /> ) } +/** The point handle of the movable selected circle, named « Point {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) + return { + annotationId: target.id, + label: t('editor.annotations.handle.point').replace('{name}', () => name), + stored: target.geometry, + } +} + function CanvasStage({ scene, - placement, + work, onDeselect, }: { scene: Scene - placement: Placement + work: Work onDeselect: () => void }) { const locale = useLocaleStore((s) => s.locale) // Hidden (the editor is read-only): no drag in flight survives, none is committed. const shown = usePlaceVisible() const { doc, ui, dispatch, model, frame, selected } = scene + const handle = useHandle(shown ? work.target : null, doc) const view = doc.views.find((v) => v.id === scene.viewId) const blocked = !model.measured || doc.categories.length === 0 if (!view) return null @@ -231,19 +290,24 @@ function CanvasStage({ tool={ui.tool} selectedId={ui.selectedId} moveTarget={shown ? moveTargetOf(selected, model, ui.tool) : null} - overlay={overlayOf(ui, selected, frame)} + overlay={overlayOf(ui, selected, frame, work.message.message?.place)} + handles={{ + handle, + onKeyDown: work.edit.onHandleKey, + onBlur: work.edit.onHandleBlur, + }} tools={{ tool: ui.tool, - onTool: (tool) => dispatch({ type: 'tool', tool }), + onTool: (tool) => guarded(() => dispatch({ type: 'tool', tool }))(), drawingDisabled: blocked, linkDisabled: model.children.length === 0, }} onRoot={scene.setRoot} onSelect={(id) => dispatch({ type: 'select', id })} - onPlace={placement.onPlace} - onDrop={placement.onDrop} + onPlace={work.placement.onPlace} + onDrop={work.placement.onDrop} onDeselect={onDeselect} - onTraceKey={placement.onTraceKey} + onTraceKey={work.placement.onTraceKey} /> ) } @@ -266,6 +330,8 @@ function SidePanel({ context: CommitContext }) { const { doc, ui, dispatch, model, frame, selected } = scene + // During the move mode the panel offers no deselect: only the mode's own exits. + const moving = useAnnotationWork((s) => s.mode?.kind === 'move') if (ui.pending) { return ( dispatch({ type: 'select', id: null })} - busy={ui.tracing !== null} + busy={ui.tracing !== null || moving} /> ) } @@ -320,13 +386,26 @@ function moveTargetOf( : null } +/** The selected point or link circle, when it can be moved now (R-9: its handle). */ +function circleTargetOf( + selected: Annotation | undefined, + model: ViewModel, + tool: ToolId, +): Annotation | null { + const movable = moveTargetOf(selected, model, tool) !== null + return movable && selected?.geometry?.type === 'circle' ? selected : null +} + function overlayOf( ui: UiState, selected: Annotation | undefined, frame: Frame | null, + refused: Geometry | null | undefined, ) { return { frame, + selectedId: selected?.id ?? null, + refused: refused ?? null, selected: selected?.geometry ?? null, pending: ui.pending?.geometry ?? null, tracing: ui.tracing?.points ?? null, @@ -334,33 +413,65 @@ function overlayOf( } } -/** The strip of the edit body: the lead of the scene, its notice, the tracing commands. */ -function SceneStrip({ - scene, - placement, - message, -}: { - scene: Scene - placement: Placement - message: GestureMessages -}) { +/** + * The strip of the edit body: the lead of the scene (the move mode's own while it runs), + * its notice, the commands. + */ +function SceneStrip({ scene, work }: { scene: Scene; work: Work }) { const t = useT() const locale = useLocaleStore((s) => s.locale) - const notice = useStripNotice(scene, message.message) + const notice = useStripNotice(scene, work.message.message) + const moving = useAnnotationWork((s) => s.mode?.kind === 'move') + useMoveFocusReturn(moving) const { ui, selected, doc } = scene + const lead = moving + ? { + title: t('editor.annotations.move.point'), + detail: t('editor.annotations.move.hint'), + icon: 'move' as const, + } + : stripLeadOf(ui, selected, doc, { t, locale }) return ( scene.dispatch({ type: 'trace_cancel' })} - /> - ) - } + commands={} + commandsKey={commandsKeyOf(ui, moving, work.target !== null)} + /> + ) +} + +function commandsKeyOf(ui: UiState, moving: boolean, point: boolean) { + if (ui.tracing) return 'tracing' + if (moving) return 'move' + return point ? 'point' : `tool-${ui.tool}` +} + +/** A tracing's commands, a movable point's, or the Point tool's size (A5). */ +function SceneCommands({ scene, work }: { scene: Scene; work: Work }) { + const { ui, doc, viewId, frame, dispatch } = scene + if (ui.tracing) { + return ( + dispatch({ type: 'trace_cancel' })} + /> + ) + } + if (work.target) { + const props = { doc, viewId, frame, edit: work.edit } + return + } + if (ui.tool !== 'point' || ui.pending || !frame) return null + const size = ui.size + return ( + ) } diff --git a/apps/app/src/components/editor/annotations/HandleLayer.tsx b/apps/app/src/components/editor/annotations/HandleLayer.tsx new file mode 100644 index 00000000..5b467c99 --- /dev/null +++ b/apps/app/src/components/editor/annotations/HandleLayer.tsx @@ -0,0 +1,132 @@ +import { + useLayoutEffect, + useRef, + useState, + type FocusEvent, + type KeyboardEvent, + type RefObject, +} from 'react' +import type { Geometry } from '@faunosteo/core-wasm/types' +import { parseFrame } from '@/editor/annotations/frame' +import { handleSizes } from '@/editor/annotations/handleSize' +import { useAnnotationWork } from '@/editor/annotations/workStore' + +/** The selected point (or link circle) whose handle the layer draws. */ +export interface PointHandle { + annotationId: string + /** Its accessible name: « Point {nom} ». */ + label: string + stored: Geometry +} + +export interface HandleLayerProps { + viewBox: string + ratio: string + /** The framing's zoom: handles keep their CSS px size under it. */ + scale: number + handle: PointHandle | null + onKeyDown: (event: KeyboardEvent) => void + onBlur: (event: FocusEvent) => void +} + +/** The svg's own box in CSS px before the framing's transform. */ +function useBoxSize(svg: RefObject) { + const [size, setSize] = useState({ w: 0, h: 0 }) + useLayoutEffect(() => { + const element = svg.current + if (!element) return + const read = () => + // An svg without layout (tests) has no client size: one unit per px then. + setSize({ w: element.clientWidth || 0, h: element.clientHeight || 0 }) + read() + if (typeof ResizeObserver === 'undefined') return + const observer = new ResizeObserver(read) + observer.observe(element) + return () => observer.disconnect() + }, [svg]) + return size +} + +/** + * Drawing units per CSS px: the box over the frame (`meet`), times the zoom. Unknown + * before layout (0 px), one unit per px. + * shortcut: assumes a `meet` ratio (the core's default); a `none` ratio would need one + * factor per axis. Upgrade: read both factors when a drawing ships `none`. + */ +function unitsPerPx( + viewBox: string, + size: { w: number; h: number }, + scale: number, +) { + const frame = parseFrame(viewBox) + if (!frame || size.w === 0 || size.h === 0) return 1 + return 1 / (Math.min(size.w / frame.w, size.h / frame.h) * scale) +} + +/** + * The handle layer (docs/ANNOTATION-RENDERING.md « Editor overlay »): its own svg over the + * overlay, same `viewBox`, NOT aria-hidden. Each handle is a focusable button whose hit + * shape carries `data-handle` for the press machine. The point handle covers the point's + * circle, at least the hit radius, and follows the pending preview. + */ +export default function HandleLayer(props: HandleLayerProps) { + const svg = useRef(null) + const unit = unitsPerPx(props.viewBox, useBoxSize(svg), props.scale) + return ( + + {props.handle && ( + + )} + + ) +} + +function PointHandleShape({ + handle, + unit, + onKeyDown, + onBlur, +}: HandleLayerProps & { handle: PointHandle; unit: number }) { + const preview = useAnnotationWork((s) => + s.preview?.annotationId === handle.annotationId ? s.preview.geometry : null, + ) + const shown = preview ?? handle.stored + if (shown.type !== 'circle') return null + const r = Math.max(shown.r, handleSizes().hit * unit) + return ( + + + + + ) +} diff --git a/apps/app/src/components/editor/annotations/MoveModeBar.tsx b/apps/app/src/components/editor/annotations/MoveModeBar.tsx new file mode 100644 index 00000000..5949ccbd --- /dev/null +++ b/apps/app/src/components/editor/annotations/MoveModeBar.tsx @@ -0,0 +1,64 @@ +import { useEffect, useRef } from 'react' +import Button from '@/components/ui/Button' +import type { Direction } from '@/editor/annotations/usePointEdit' +import { useT } from '@/i18n/useT' + +const COMMAND = 'min-h-11 xl:min-h-9' + +const ARROWS: { direction: Direction; glyph: string }[] = [ + { direction: 'left', glyph: '←' }, + { direction: 'up', glyph: '↑' }, + { direction: 'down', glyph: '↓' }, + { direction: 'right', glyph: '→' }, +] + +export interface MoveModeBarProps { + onStep: (direction: Direction) => void + onConfirm: () => void + onCancel: () => void +} + +/** + * The move mode's commands in the strip (board 06 B, A11, WCAG 2.5.7): four arrows, one + * step per click, then « Valider la position » (one commit) or « Annuler » (the place + * before). The focus enters on the first arrow. + */ +export default function MoveModeBar({ + onStep, + onConfirm, + onCancel, +}: MoveModeBarProps) { + const t = useT() + const first = useRef(null) + useEffect(() => first.current?.focus(), []) + return ( +
+ {ARROWS.map(({ direction, glyph }, index) => ( + + ))} + + +
+ ) +} diff --git a/apps/app/src/components/editor/annotations/PointCommands.tsx b/apps/app/src/components/editor/annotations/PointCommands.tsx new file mode 100644 index 00000000..3c5ab979 --- /dev/null +++ b/apps/app/src/components/editor/annotations/PointCommands.tsx @@ -0,0 +1,169 @@ +import { useEffect, useRef, type Dispatch } from 'react' +import { visibleElement } from '@/editor/focusRequest' +import type { + Annotation, + AnatomicalSheetDocument, +} from '@faunosteo/core-wasm/types' +import Button from '@/components/ui/Button' +import { defaultRadius, type Frame } from '@/editor/annotations/frame' +import { + newPointSize, + sizeRange, + sizeStops, +} from '@/editor/annotations/pointSize' +import type { UiAction } from '@/editor/annotations/uiState' +import type { PointEdit } from '@/editor/annotations/usePointEdit' +import { useAnnotationWork } from '@/editor/annotations/workStore' +import { useEditorStore } from '@/editor/state/editorStore' +import { useT } from '@/i18n/useT' +import EditorGlyph from '../EditorGlyph' +import MoveModeBar from './MoveModeBar' +import SizeSlider from './SizeSlider' + +const COMMAND = 'min-h-11 gap-1.5 xl:min-h-9' + +/** The core's smallest radius for the view (Task 1), null when it has none. */ +function useMinimum(viewId: string): number | null { + return useEditorStore((s) => s.previewState?.min_point_radius[viewId] ?? null) +} + +interface SliderScope { + doc: AnatomicalSheetDocument + viewId: string + /** The size a view without any point falls back to. */ + fallback: number +} + +/** The slider's stops, range and red mark on the view (R-10). */ +function useSizeScale({ doc, viewId, fallback }: SliderScope) { + const minimum = useMinimum(viewId) + const stops = sizeStops(doc.annotations, viewId) + return { stops, minimum, range: sizeRange(stops, minimum, fallback) } +} + +/** The selection's radius now: its pending preview, else the stored one. */ +function useShownRadius(annotation: Annotation): number { + return useAnnotationWork((s) => { + const preview = + s.preview?.annotationId === annotation.id ? s.preview.geometry : null + const shown = preview ?? annotation.geometry + return shown?.type === 'circle' ? shown.r : 0 + }) +} + +/** A size change previewed on the selection (`size`), stamped with the current text. */ +function previewSize(annotation: Annotation, radius: number): void { + const { preview } = useAnnotationWork.getState() + const own = preview?.annotationId === annotation.id ? preview.geometry : null + const shown = own ?? annotation.geometry + if (shown?.type !== 'circle') return + const base = useEditorStore.getState().documentText + const geometry = { ...shown, r: radius } + useAnnotationWork.setState({ + preview: { annotationId: annotation.id, geometry, base, source: 'size' }, + }) +} + +/** + * Focus back on « Déplacer le point » when the move mode ends with the focus lost (its bar + * unmounted under it: « Valider », « Annuler », Escape). Mounted by the strip, which + * outlives the commands it swaps. + */ +export function useMoveFocusReturn(inMode: boolean) { + const was = useRef(inMode) + useEffect(() => { + const active = document.activeElement + const lost = active === null || active === document.body + if (was.current && !inMode && lost) { + visibleElement('[data-testid="edit-strip"] [data-move-entry]')?.focus() + } + was.current = inMode + }, [inMode]) +} + +export interface SelectionPointProps { + annotation: Annotation + doc: AnatomicalSheetDocument + viewId: string + frame: Frame | null + edit: PointEdit +} + +/** + * The strip's commands for a selected point (board 03): the size slider and « Déplacer le + * point »; during the move mode, its bar (board 06 B). + */ +export function SelectionPointCommands(props: SelectionPointProps) { + const t = useT() + const { annotation, edit } = props + const inMode = useAnnotationWork( + (s) => s.mode?.kind === 'move' && s.mode.annotationId === annotation.id, + ) + if (inMode) { + return ( + + ) + } + return ( + <> + {annotation.kind === 'point' && } + + + ) +} + +function SelectionSize({ annotation, doc, viewId, edit }: SelectionPointProps) { + const value = useShownRadius(annotation) + const scale = useSizeScale({ doc, viewId, fallback: value }) + return ( + previewSize(annotation, radius)} + onCommit={edit.commitSize} + /> + ) +} + +export interface ToolSizeProps { + doc: AnatomicalSheetDocument + viewId: string + frame: Frame + /** The size chosen for the next point; null: the view's own (A5). */ + size: number | null + dispatch: Dispatch +} + +/** The Point tool's slider before the click (A5): it sets the size of the next point. */ +export function ToolSize({ + doc, + viewId, + frame, + size, + dispatch, +}: ToolSizeProps) { + const scale = useSizeScale({ doc, viewId, fallback: defaultRadius(frame) }) + return ( + dispatch({ type: 'size', size: radius })} + onCommit={() => undefined} + /> + ) +} diff --git a/apps/app/src/components/editor/annotations/SizeSlider.tsx b/apps/app/src/components/editor/annotations/SizeSlider.tsx new file mode 100644 index 00000000..a74bb764 --- /dev/null +++ b/apps/app/src/components/editor/annotations/SizeSlider.tsx @@ -0,0 +1,147 @@ +import { useId, useRef, type ChangeEvent, type KeyboardEvent } from 'react' +import { round2 } from '@/editor/annotations/frame' +import { snapSize, type SizeRange } from '@/editor/annotations/pointSize' +import { useT } from '@/i18n/useT' + +export interface SizeSliderProps { + value: number + /** The view's point radii (R-10): drawn as ticks, the thumb snaps to them. */ + stops: readonly number[] + range: SizeRange + /** The core's smallest radius for this view: the red mark; null draws none. */ + minimum: number | null + onPreview: (radius: number) => void + /** Release, Enter or blur (BDR-050): one commit of what was previewed. */ + onCommit: () => void +} + +/** R-10: the thumb snaps to a stop within 8 CSS px of the track. */ +const SNAP_PX = 8 + +const THUMB_PX = 16 + +/** Where a value sits along the thumb's travel, as a share of it. */ +function xOf(value: number, { low, high }: SizeRange): string { + const share = Math.min(Math.max((value - low) / (high - low), 0), 1) + return `${share * 100}%` +} + +/** Page Up and Page Down: the next stop above or below the value. */ +function nextStop(value: number, stops: readonly number[], up: boolean) { + const found = up + ? stops.find((stop) => stop > value) + : [...stops].reverse().find((stop) => stop < value) + return found ?? value +} + +/** The value a key gives, or null for a key the slider leaves alone. */ +function keyValue(event: KeyboardEvent, props: SizeSliderProps): number | null { + const { value, range } = props + const step = (range.high - range.low) / 100 + const clamp = (v: number) => + round2(Math.min(Math.max(v, range.low), range.high)) + if (event.key === 'ArrowRight' || event.key === 'ArrowUp') + return clamp(value + step) + if (event.key === 'ArrowLeft' || event.key === 'ArrowDown') + return clamp(value - step) + if (event.key === 'PageUp') return nextStop(value, props.stops, true) + if (event.key === 'PageDown') return nextStop(value, props.stops, false) + return null +} + +/** + * The strip's size slider (board 03 B, R-10): no number shown, the view's sizes as ticks, + * the core's minimum as a red mark. A track click or a drag previews and commits on + * release; arrows step by 1 % of the range, Page Up and Page Down jump to the next size, + * Enter or leaving it commits (one undo step). + */ +export default function SizeSlider(props: SizeSliderProps) { + const t = useT() + const id = useId() + const input = useRef(null) + const { range, stops, minimum } = props + const onChange = (event: ChangeEvent) => { + const width = input.current?.clientWidth ?? 0 + const reach = width > 0 ? (SNAP_PX * (range.high - range.low)) / width : 0 + props.onPreview(snapSize(Number(event.target.value), stops, reach)) + } + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Enter') return props.onCommit() + const next = keyValue(event, props) + if (next === null) return + event.preventDefault() + props.onPreview(next) + } + return ( +
+ +
+ + +
+
+ ) +} + +/** + * The ticks and the red mark, drawn in an svg spanning the thumb's travel: the range + * follows the view's sizes, so a commit can move them, and svg shapes moving shift no + * layout box (A14). + */ +function Marks({ + stops, + range, + minimum, +}: Pick) { + return ( + + ) +} diff --git a/apps/app/src/editor/annotations/deselect.ts b/apps/app/src/editor/annotations/deselect.ts index 78d4e8e4..f8b31de3 100644 --- a/apps/app/src/editor/annotations/deselect.ts +++ b/apps/app/src/editor/annotations/deselect.ts @@ -9,6 +9,8 @@ import { } from '@/editor/focusRequest' import { CANVAS_BOX } from '@/editor/useEditorNavigation' import { useT } from '@/i18n/useT' +import { escapeAction, type EscapeAction } from './escape' +import { endMode, useAnnotationWork } from './workStore' /** The drawing's focusable box of the shown body, when there is one. */ export function focusDrawing(): boolean { @@ -89,20 +91,54 @@ export function useEscapeDeselect( }, [active]) } +/** The editable body's pending work, as board 32 orders Escape (rows 3 to 6). */ +function escapeOf(id: string | null, creating: boolean): EscapeAction { + const work = useAnnotationWork.getState() + return escapeAction({ + previewPending: work.preview !== null && work.preview.source !== 'move', + creating, + inMode: work.mode !== null, + chosenVertex: work.chosen?.annotationId === id ? work.chosen.vertex : null, + selectedId: id, + }) +} + +/** What one Escape does; `deselect` when nothing pending is left. */ +function runEscape(action: EscapeAction, deselect: () => boolean): boolean { + if (action === 'drop_preview') useAnnotationWork.setState({ preview: null }) + else if (action === 'drop_mode') endMode() + else if (action === 'unchoose') useAnnotationWork.setState({ chosen: null }) + else if (action === 'deselect') return deselect() + // `ask_creation`: the creation dialog asks (U2 Task 7); nothing here yet. + return action !== null && action !== 'ask_creation' +} + +/** Where Escape applies: the editable body runs the work order; the read-only twin deselects. */ +export interface EscapeScope { + editable: boolean + /** A creation in progress (the editable body only). */ + creating?: boolean +} + /** - * A body's Escape: deselects `id` while `active`. Returns the ref of the panel column, which - * tells a key pressed inside the panel (focus follows the row) from one pressed elsewhere, - * and the tap-on-the-drawing deselect. + * A body's Escape while `active`: one situation per press (board 32): a pending preview, + * then a mode, a chosen vertex, then the selection `id`. Returns the ref of the panel + * column, which tells a key pressed inside the panel (focus follows the row) from one + * pressed elsewhere, and the tap-on-the-drawing deselect. */ export function useSelectionEscape( id: string | null, clear: () => void, active: boolean, + scope: EscapeScope = { editable: false }, ) { const asideRef = useRef(null) const deselect = useDeselect(id, clear) - useEscapeDeselect(active, (event) => - deselect.byKey(asideRef.current?.contains(event.target as Node) ?? false), - ) + useEscapeDeselect(active, (event) => { + const inPanel = asideRef.current?.contains(event.target as Node) ?? false + const byKey = () => deselect.byKey(inPanel) + if (!scope.editable) return byKey() + return runEscape(escapeOf(id, scope.creating ?? false), byKey) + }) return { asideRef, byDrawing: deselect.byDrawing } } diff --git a/apps/app/src/editor/annotations/handleSize.ts b/apps/app/src/editor/annotations/handleSize.ts new file mode 100644 index 00000000..77d61b0a --- /dev/null +++ b/apps/app/src/editor/annotations/handleSize.ts @@ -0,0 +1,26 @@ +/** R-9: handle sizes in CSS px, constant under zoom. */ +export interface HandleSizes { + vertex: number + insert: number + /** The radius around a handle's centre that a press reaches. */ + hit: number +} + +const FINE: HandleSizes = { vertex: 12, insert: 16, hit: 10 } +const COARSE: HandleSizes = { vertex: 18, insert: 24, hit: 22 } + +let device: HandleSizes | null = null + +/** + * The device's sizes, read ONCE from `(any-pointer: coarse)` (R-9): a hybrid device keeps + * the size it started with, so no handle is re-created under the finger. + */ +export function handleSizes(): HandleSizes { + if (device === null) { + const coarse = + typeof window.matchMedia === 'function' && + window.matchMedia('(any-pointer: coarse)').matches + device = coarse ? COARSE : FINE + } + return device +} diff --git a/apps/app/src/editor/annotations/previewCommit.ts b/apps/app/src/editor/annotations/previewCommit.ts new file mode 100644 index 00000000..6dd7879c --- /dev/null +++ b/apps/app/src/editor/annotations/previewCommit.ts @@ -0,0 +1,66 @@ +import type { Geometry } from '@faunosteo/core-wasm/types' +import { useEditorStore } from '../state/editorStore' +import { translatedGeometry } from './gesture' +import { + endMode, + setModePreview, + useAnnotationWork, + type Preview, +} from './workStore' + +const fresh = (preview: Preview | null): Preview | null => + preview && preview.base === useEditorStore.getState().documentText + ? preview + : null + +/** + * A keyboard series or a size change ends (Enter, blur, release): the preview of `source` + * leaves the store and is returned when it was computed on the current text (R-13); a + * stale one is dropped, never committed. + */ +export function takePreview(source: Preview['source']): Preview | null { + const { preview } = useAnnotationWork.getState() + if (preview?.source !== source) return null + useAnnotationWork.setState({ preview: null }) + return fresh(preview) +} + +/** « Valider la position »: the mode ends first; a started, fresh move is returned. */ +export function takeMove(): Preview | null { + const { mode, preview } = useAnnotationWork.getState() + endMode() + return mode?.started ? fresh(preview) : null +} + +/** What `annotationId` shows now: its pending preview, else the stored shape. */ +export function shownGeometry( + annotationId: string, + stored: Geometry, +): Geometry { + const { preview } = useAnnotationWork.getState() + return preview?.annotationId === annotationId ? preview.geometry : stored +} + +/** + * One step of the selection by `delta` drawing units: into the move mode when it is on, + * else as a keyboard series (`keys`), stamped with the current text. + */ +export function stepSelection( + annotationId: string, + stored: Geometry, + delta: { x: number; y: number }, +): void { + const moved = translatedGeometry(shownGeometry(annotationId, stored), delta) + if (!moved) return + if (useAnnotationWork.getState().mode?.kind === 'move') { + return setModePreview(moved, stored) + } + const base = useEditorStore.getState().documentText + const preview: Preview = { + annotationId, + geometry: moved, + base, + source: 'keys', + } + useAnnotationWork.setState({ preview }) +} diff --git a/apps/app/src/editor/annotations/useBlockDrag.ts b/apps/app/src/editor/annotations/useBlockDrag.ts index a348f4c3..aa7112ce 100644 --- a/apps/app/src/editor/annotations/useBlockDrag.ts +++ b/apps/app/src/editor/annotations/useBlockDrag.ts @@ -3,6 +3,8 @@ import type { Annotation, Geometry } from '@faunosteo/core-wasm/types' import { useEditorStore } from '../state/editorStore' import type { XY } from './frame' import { clientToDrawing, translatedGeometry } from './gesture' +import { shownGeometry } from './previewCommit' +import { setModePreview } from './workStore' import type { EditableGeometry } from './geometryEdit' export interface MoveTarget { @@ -23,6 +25,10 @@ interface Drag { target: MoveTarget /** The press point in drawing units: the block moves by the pointer's delta from it. */ origin: XY + /** The shape the drag starts from: the stored one, or the move mode's last place. */ + base: Geometry + /** A drag of the move mode (board 06 B): it moves the mode's preview, never commits. */ + mode: boolean } function translatedAt( @@ -32,7 +38,7 @@ function translatedAt( ): Geometry | null { const now = clientToDrawing(overlay.current, client) if (!now) return null - return translatedGeometry(drag.target.geometry, { + return translatedGeometry(drag.base, { x: now.x - drag.origin.x, y: now.y - drag.origin.y, }) @@ -49,40 +55,59 @@ function useDropOnChange(target: MoveTarget | null, drop: () => void) { type SetPreview = (geometry: Geometry | null) => void +/** The drag's shape at `geometry`: local to the canvas, or the move mode's preview. */ +function shower(drag: RefObject, setPreview: SetPreview) { + return (geometry: Geometry | null) => { + const gesture = drag.current + if (!gesture?.mode) return setPreview(geometry) + if (geometry) setModePreview(geometry, gesture.target.geometry) + } +} + /** Start, follow, drop and cancel of the block drag held in `drag`. */ function dragActions( input: BlockDragInput, drag: RefObject, setPreview: SetPreview, ) { + const show = shower(drag, setPreview) const cancel = () => { + // A cancelled drag of the mode puts the shape back where that drag found it. + show(drag.current?.mode ? drag.current.base : null) drag.current = null setPreview(null) } - const start = (pressedAt: XY, client: XY) => { + const start = (pressedAt: XY, client: XY, mode = false) => { const origin = clientToDrawing(input.overlay.current, pressedAt) - if (!input.target || !origin) return - drag.current = { target: input.target, origin } - setPreview(translatedAt(input.overlay, drag.current, client)) + const { target } = input + if (!target || !origin) return + const base = mode + ? shownGeometry(target.id, target.geometry) + : target.geometry + drag.current = { target, origin, base, mode } + show(translatedAt(input.overlay, drag.current, client)) } const follow = (client: XY) => { - if (drag.current) - setPreview(translatedAt(input.overlay, drag.current, client)) + if (drag.current) show(translatedAt(input.overlay, drag.current, client)) } const drop = (client: XY) => { const gesture = drag.current const dropped = gesture ? translatedAt(input.overlay, gesture, client) : null - cancel() - if (gesture && dropped) input.onDrop(gesture.target.id, dropped) + if (gesture?.mode) show(dropped) + drag.current = null + setPreview(null) + if (gesture && !gesture.mode && dropped) + input.onDrop(gesture.target.id, dropped) } return { start, follow, drop, cancel } } /** * The selection moved as a block (`drag_shape`, `drag_point`): the overlay previews the - * translated outline, kept local to the canvas for speed; the drop commits once. + * translated outline, kept local to the canvas for speed; the drop commits once. A drag + * of the move mode (`drag_mode`) moves the mode's preview instead, and commits nothing. */ export function useBlockDrag(input: BlockDragInput) { const drag = useRef(null) diff --git a/apps/app/src/editor/annotations/useGestureMessage.ts b/apps/app/src/editor/annotations/useGestureMessage.ts index 733f2338..e42df8e8 100644 --- a/apps/app/src/editor/annotations/useGestureMessage.ts +++ b/apps/app/src/editor/annotations/useGestureMessage.ts @@ -5,6 +5,7 @@ import { type FocusEvent, type PointerEvent, } from 'react' +import type { Geometry } from '@faunosteo/core-wasm/types' import { useEditorStore } from '../state/editorStore' /** A6/A14: how long a message stays (R-2) and how long a hint does (R-1). */ @@ -25,6 +26,14 @@ export interface GestureMessage { undo: boolean hint: boolean stamp: Stamp + /** The place the core refused, drawn in red dashes while the refusal shows. */ + place: Geometry | null +} + +export interface ShowOptions { + undo: boolean + tone: GestureMessage['tone'] + place?: Geometry } function currentStamp(): Stamp { @@ -102,10 +111,15 @@ export function useGestureMessage() { ) return () => clearTimeout(timer) }, [message, held]) - const show = ( - text: string, - { undo, tone }: { undo: boolean; tone: GestureMessage['tone'] }, - ) => setShown({ text, tone, undo, hint: false, stamp: currentStamp() }) + const show = (text: string, { undo, tone, place }: ShowOptions) => + setShown({ + text, + tone, + undo, + hint: false, + stamp: currentStamp(), + place: place ?? null, + }) const hint = (text: string) => { if (message) return setShown({ @@ -114,6 +128,7 @@ export function useGestureMessage() { undo: false, hint: true, stamp: currentStamp(), + place: null, }) } return { message, show, hint, hold: handlers } diff --git a/apps/app/src/editor/annotations/usePlacement.ts b/apps/app/src/editor/annotations/usePlacement.ts index d5c805c2..214d15bd 100644 --- a/apps/app/src/editor/annotations/usePlacement.ts +++ b/apps/app/src/editor/annotations/usePlacement.ts @@ -1,5 +1,6 @@ import type { Dispatch, KeyboardEvent } from 'react' import type { + Annotation, AnatomicalSheetDocument, Geometry, Point, @@ -96,24 +97,36 @@ function tracingActions(input: PlacementInput) { return { closeTracing, trace, onTraceKey } } -/** A drop commits one update; the line under the drawing says it, or the core's refusal. */ +/** A move (drag, move mode, arrow keys) or a size change of the selection. */ +export type GeometryChange = 'move' | 'size' + +/** The message keys of a kept and of a refused change. */ +function changeKeys(change: GeometryChange, kind: Annotation['kind']) { + return change === 'size' + ? { kept: 'resized', refused: 'size_refused' } + : { kept: `moved.${kind}`, refused: 'move_refused' } +} + +/** + * A drop commits one update; the line under the drawing says it, or the core's refusal + * with the refused place drawn (the shape stays where it was). + */ function dropAction({ doc, context, message, dispatch }: PlacementInput) { - return (id: string, geometry: Geometry) => { + return (id: string, geometry: Geometry, change: GeometryChange = 'move') => { const annotation = doc.annotations.find((a) => a.id === id) if (!annotation) return + const keys = changeKeys(change, annotation.kind) const result = updateGeometry(annotation, geometry, context) if (result.ok) { // A kept move ends any refusal the strip still shows. dispatch({ type: 'hint', hint: null }) - const text = context.t( - `editor.annotations.message.moved.${annotation.kind}`, - ) + const text = context.t(`editor.annotations.message.${keys.kept}`) return message.show(text, { undo: true, tone: 'info' }) } const text = context - .t('editor.annotations.message.move_refused') + .t(`editor.annotations.message.${keys.refused}`) .replace('{text}', () => result.messages.join(' ')) - message.show(text, { undo: false, tone: 'error' }) + message.show(text, { undo: false, tone: 'error', place: geometry }) } } diff --git a/apps/app/src/editor/annotations/usePointEdit.ts b/apps/app/src/editor/annotations/usePointEdit.ts new file mode 100644 index 00000000..82dd785f --- /dev/null +++ b/apps/app/src/editor/annotations/usePointEdit.ts @@ -0,0 +1,99 @@ +import type { KeyboardEvent } from 'react' +import type { Annotation, Geometry } from '@faunosteo/core-wasm/types' +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' + +type Drop = (id: string, geometry: Geometry, change?: GeometryChange) => void + +export interface PointEditInput { + /** The selection when it can be moved now (a circle: a point or a link). */ + target: Annotation | null + frame: Frame | null + onDrop: Drop +} + +export type Direction = 'left' | 'up' | 'down' | 'right' + +const DELTA: Record = { + left: [-1, 0], + up: [0, -1], + down: [0, 1], + right: [1, 0], +} + +const KEY_DIRECTION: Record = { + ArrowLeft: 'left', + ArrowUp: 'up', + ArrowDown: 'down', + ArrowRight: 'right', +} + +/** One step (R-11) of the target, into the move mode or a keyboard series. */ +function step(input: PointEditInput, direction: Direction, big: boolean) { + const { target, frame } = input + if (!target?.geometry || !frame) return + const size = moveStep(frame, big) + const [x, y] = DELTA[direction] + 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) { + const keys = () => { + const preview = takePreview('keys') + if (preview) onDrop(preview.annotationId, preview.geometry) + } + const size = () => { + const preview = takePreview('size') + if (preview) onDrop(preview.annotationId, preview.geometry, 'size') + } + const move = () => { + const preview = takeMove() + if (preview) onDrop(preview.annotationId, preview.geometry) + } + return { keys, size, move } +} + +const inMoveMode = () => useAnnotationWork.getState().mode?.kind === 'move' + +/** The point handle's keys: arrows step (Shift ×10), Enter commits the series or the mode. */ +function handleKeys(input: PointEditInput, commit: ReturnType) { + return (event: KeyboardEvent) => { + const direction = KEY_DIRECTION[event.key] + if (direction) { + event.preventDefault() + return step(input, direction, event.shiftKey) + } + if (event.key !== 'Enter') return + event.preventDefault() + if (inMoveMode()) commit.move() + else commit.keys() + } +} + +/** + * Point editing (R-10 to R-13): the handle's keyboard series (one commit on Enter or + * blur), the size slider's commit, and the move mode (« Déplacer le point », its arrows, + * « Valider la position » committing once, « Annuler »). + */ +export function usePointEdit(input: PointEditInput) { + const commit = commits(input.onDrop) + return { + onHandleKey: handleKeys(input, commit), + // BDR-050: leaving the handle commits its series; a move mode waits for « Valider ». + onHandleBlur: () => commit.keys(), + commitSize: commit.size, + startMove: () => { + if (!input.target) return + startMove(input.target.id, useEditorStore.getState().documentText) + }, + stepMove: (direction: Direction) => step(input, direction, false), + confirmMove: commit.move, + cancelMove: endMode, + } +} + +export type PointEdit = ReturnType diff --git a/apps/app/src/editor/annotations/usePressGesture.ts b/apps/app/src/editor/annotations/usePressGesture.ts index b2bf191c..8b18f35f 100644 --- a/apps/app/src/editor/annotations/usePressGesture.ts +++ b/apps/app/src/editor/annotations/usePressGesture.ts @@ -20,11 +20,7 @@ import { } from './press' import type { ToolId } from './uiState' import { annotationIdOf } from './useCanvasBuild' -import { - useBlockDrag, - type BlockDragInput, - type MoveTarget, -} from './useBlockDrag' +import { useBlockDrag, type BlockDragInput } from './useBlockDrag' import { useAnnotationWork } from './workStore' export interface PressInput extends BlockDragInput { @@ -48,46 +44,35 @@ function centreOf(element: Element): XY { return { x: box.left + box.width / 2, y: box.top + box.height / 2 } } -/** - * One element under the press as a hit: a handle by its `data-handle`, else an annotation. - * Until the handle layer exists, the selected point's own marker stands for its handle. - */ -function hitOf(element: Element, pointId: string | null): Hit | null { +/** One element under the press as a hit: a handle of the handle layer, else an annotation. */ +function hitOf(element: Element): Hit | null { const handle = element.getAttribute('data-handle') if (handle !== null) { const ref = JSON.parse(handle) as HandleRef return { kind: 'handle', handle: ref, centre: centreOf(element) } } const id = annotationIdOf(element) - if (id === null) return null - if (id !== pointId) return { kind: 'annotation', id } - const marker = element.closest('[data-anno-id]') ?? element - const centre = centreOf(marker) - return { kind: 'handle', handle: { kind: 'point' }, centre } + return id === null ? null : { kind: 'annotation', id } } /** Everything under the client point inside the canvas box, top first. */ -function hitsAt( - viewport: Element | null, - at: XY, - pointId: string | null, -): Hit[] { +function hitsAt(viewport: Element | null, at: XY): Hit[] { if (!viewport) return [] return document .elementsFromPoint(at.x, at.y) .filter((element) => viewport.contains(element)) - .flatMap((element) => hitOf(element, pointId) ?? []) + .flatMap((element) => hitOf(element) ?? []) } +/** « Déplacer … » is on: a drag anywhere moves its target and a click selects nothing. */ +const inMoveMode = () => useAnnotationWork.getState().mode?.kind === 'move' + function selectionOf(selectedId: string | null): Selection { const chosen = useAnnotationWork.getState().chosen const own = selectedId !== null && chosen?.annotationId === selectedId return { selectedId, chosenVertex: own ? chosen.vertex : null } } -const pointIdOf = (target: MoveTarget | null) => - target?.kind === 'point' ? target.id : null - const HANDLE_ACTIONS = new Set([ 'choose_vertex', 'insert', @@ -153,12 +138,13 @@ function selectClick(f: Feed, target: PressTarget, event: PointerEvent): void { runClick(double ? doubled(action, target, sel) : action, f.input) } +/** A click with the select tool (none during the move mode, R-12), or with a drawing tool. */ function onClick(f: Feed, target: PressTarget, event: PointerEvent): void { - if (f.input.tool === 'select') selectClick(f, target, event) - else place(f.input, event) + if (f.input.tool !== 'select') return place(f.input, event) + if (!inMoveMode()) selectClick(f, target, event) } -const BLOCK_DRAGS = new Set(['drag_shape', 'drag_point']) +const BLOCK_DRAGS = new Set(['drag_shape', 'drag_point', 'drag_mode']) function applyEffect(f: Feed, effect: PressEffect, event: PointerEvent | null) { if (effect?.type === 'drag_cancel') f.drag.cancel() @@ -166,14 +152,20 @@ function applyEffect(f: Feed, effect: PressEffect, event: PointerEvent | null) { if (effect.type === 'click') onClick(f, effect.target, event) if (effect.type === 'drag_end') f.drag.drop(clientOf(event)) if (effect.type === 'drag_start' && BLOCK_DRAGS.has(effect.action.type)) { - f.drag.start(f.machine.current.pressedAt, clientOf(event)) + const mode = effect.action.type === 'drag_mode' + f.drag.start(f.machine.current.pressedAt, clientOf(event), mode) } } +const contextOf = (input: PressInput) => ({ + movable: input.target !== null, + moveMode: inMoveMode(), +}) + /** One event through the machine and its effect; at idle the press is over. */ function feed(f: Feed, event: PressEvent, pointer: PointerEvent | null) { const m = f.machine.current - const context = { movable: f.input.target !== null, moveMode: false } + const context = contextOf(f.input) const step = stepPress(m.press, event, context) m.press = step.press applyEffect(f, step.effect, pointer) @@ -231,7 +223,7 @@ function startPress(latest: RefObject, event: PointerEvent): void { if (m.press.phase !== 'idle') feed(f, { type: 'cancel' }, null) m.pressedAt = clientOf(event) const kind = pointerKindOf(event.pointerType) - const context = { kind, movable: f.input.target !== null, moveMode: false } + const context = { kind, ...contextOf(f.input) } // The drag of the selection keeps its pointer even past the box's edge. if (BLOCK_DRAGS.has(dragAction(m.target, context).type)) { event.currentTarget.setPointerCapture?.(event.pointerId) @@ -241,7 +233,7 @@ function startPress(latest: RefObject, event: PointerEvent): void { /** The press's target: the selection's handles, then the topmost annotation. */ function targetAt(input: PressInput, at: XY): PressTarget { - const hits = hitsAt(input.viewport.current, at, pointIdOf(input.target)) + const hits = hitsAt(input.viewport.current, at) return pressTarget(hits, at, selectionOf(input.selectedId)) } diff --git a/apps/app/src/editor/useUndoShortcuts.ts b/apps/app/src/editor/useUndoShortcuts.ts index 0fb4f9c1..ddc60710 100644 --- a/apps/app/src/editor/useUndoShortcuts.ts +++ b/apps/app/src/editor/useUndoShortcuts.ts @@ -1,8 +1,8 @@ import { useEffect } from 'react' import { cancelPending } from './annotations/workStore' +import { isTextField } from './focusRequest' import { useEditorStore } from './state/editorStore' -const TEXT_TARGET = 'input, textarea, select, [contenteditable="true"]' const MODAL_OPEN = 'dialog[open]' /** @@ -14,8 +14,8 @@ export function useUndoShortcuts(writable: boolean): void { useEffect(() => { if (!writable) return const onKey = (event: KeyboardEvent) => { - const { target } = event - if (target instanceof Element && target.closest(TEXT_TARGET)) return + // A text field keeps its own undo; a slider or a checkbox does not (R-13). + if (isTextField(event.target)) return if (document.querySelector(MODAL_OPEN)) return if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== 'z') return diff --git a/apps/app/tests/unit/editor-annotations-tab.test.tsx b/apps/app/tests/unit/editor-annotations-tab.test.tsx index 7c3ad69f..15862689 100644 --- a/apps/app/tests/unit/editor-annotations-tab.test.tsx +++ b/apps/app/tests/unit/editor-annotations-tab.test.tsx @@ -361,6 +361,15 @@ describe('the point tool and the corrected position (C26)', () => { }) }) +/** The selected point's handle: its hit circle in the handle layer (R-9). */ +function pointHandle(): Element { + const handle = screen + .getByTestId('point-handle') + .querySelector('[data-handle]') + if (!handle) throw new Error('no point handle') + return handle +} + function marker(id: string): Element { const found = screen .getByTestId('annotation-canvas-drawing') @@ -1530,7 +1539,7 @@ describe('a tap on the drawing (D6b)', () => { }) fireEvent.pointerUp(el, { ...init(1, 'touch'), clientX: 70, clientY: 40 }) } - drag(marker('anno-a')) + drag(pointHandle()) expect(geometryOf('anno-a')).toMatchObject({ cx: 70, cy: 40 }) tap(marker('zone-a')) const before = store.getState().documentText diff --git a/apps/app/tests/unit/editor-point-edit.test.tsx b/apps/app/tests/unit/editor-point-edit.test.tsx new file mode 100644 index 00000000..90f3469c --- /dev/null +++ b/apps/app/tests/unit/editor-point-edit.test.tsx @@ -0,0 +1,437 @@ +/** U2 Task 4: the point handle, the size slider and the move mode in the Annotations tab. */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + act, + cleanup, + fireEvent, + render, + screen, + waitFor, + within, +} from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import type { Annotation } from '@faunosteo/core-wasm/types' +import AnnotationsTab from '@/components/editor/tabs/AnnotationsTab' +import { useAnnotationWork, resetWork } from '@/editor/annotations/workStore' +import { useLocaleStore } from '@/state/localeStore' +import { useUndoShortcuts } from '@/editor/useUndoShortcuts' +import { + ASSET, + drawnText, + insert, + point, + svgBytes, +} from '../helpers/editorFixtures' +import { + USER, + VERSION, + openReady, + resetStore, + sb, + store, + versionAnswer, +} from '../helpers/editorHarness' + +vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) })) +vi.mock('@faunosteo/supabase', async (orig) => ({ + ...(await orig()), + getSheetVersion: vi.fn(), + downloadSheetDrawing: vi.fn(), + saveSheetDraft: vi.fn(), + getOfficialSheetAdmin: vi.fn(), + submitSheetReview: vi.fn(), +})) + +const props = { + readOnly: false, + navigate: vi.fn(), + reloadSheet: vi.fn(), + section: 'drawing' as const, + visited: ['drawing'] as const, + onOpenSection: vi.fn(), + onBack: vi.fn(), +} + +function UndoKeys() { + useUndoShortcuts(true) + return null +} + +const annotations = () => store.getState().previewState!.document.annotations +const geometryOf = (id: string) => + annotations().find((a: Annotation) => a.id === id)?.geometry +const depth = () => store.getState().undo.length + +/** A change made elsewhere: the other point `b` moved through the store. */ +const moveOther = () => + store.getState().commit({ + op: 'update', + key: { kind: 'annotation', id: 'b' }, + element: point('b', 30, 30, 5), + }) + +function stubCtm(): void { + const identity = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 } + Object.defineProperty(window.SVGElement.prototype, 'getScreenCTM', { + configurable: true, + value: () => ({ ...identity, inverse: () => identity }), + }) +} + +beforeEach(() => { + useLocaleStore.setState({ locale: 'fr' }) + stubCtm() +}) +afterEach(() => { + cleanup() + resetStore() + resetWork() +}) + +const withPoints = (...points: ReturnType[]) => + points.reduce((text, p) => insert(text, p), drawnText()) + +async function mount(text: string) { + await openReady({ text }) + // The Escape listener acts inside the editor workspace only. + render( +
+ +
, + ) + await waitFor(() => + expect( + screen.getByTestId('annotation-canvas-drawing').querySelector('svg'), + ).not.toBeNull(), + ) +} + +/** The same tab on a 4000 × 3000 drawing: the core gives the main view a minimum radius. */ +async function mountLarge(text: string) { + const drawing = svgBytes('0 0 4000 3000') + sb.getSheetVersion.mockResolvedValue({ + ...versionAnswer(text, 3), + drawings: [{ asset_id: ASSET, sha256: drawing.sha256 }], + } as never) + sb.downloadSheetDrawing.mockResolvedValue(drawing.bytes) + store.getState().open(VERSION, USER, { canEdit: true }) + await waitFor(() => expect(store.getState().status).toBe('ready')) + // The Escape listener acts inside the editor workspace only. + render( +
+ +
, + ) + await waitFor(() => + expect( + screen.getByTestId('annotation-canvas-drawing').querySelector('svg'), + ).not.toBeNull(), + ) +} + +async function select(index = 0) { + const list = await screen.findByRole('list', { + name: 'Annotations de la vue', + }) + await userEvent.setup().click(within(list).getAllByRole('button')[index]) + return screen.findByTestId('annotation-properties') +} + +const slider = () => + within(screen.getByTestId('size-slider')).getByRole('slider') +const handle = () => screen.getByRole('button', { name: 'Point N' }) +const message = () => screen.getByTestId('gesture-line') +const moveButton = () => + screen.getByRole('button', { name: 'Déplacer le point' }) +const bar = () => screen.getByTestId('move-mode-bar') +const arrow = (name: string) => + within(bar()).getByRole('button', { name: `Déplacer vers ${name}` }) + +describe('the size slider (R-10)', () => { + it('shows the view stops and the red mark at the core value', async () => { + await mountLarge( + withPoints( + point('a', 500, 500, 30), + point('b', 900, 500, 34), + point('c', 1500, 500, 34), + ), + ) + await select() + const minimum = store.getState().previewState!.min_point_radius['view-main'] + expect(minimum).toBeGreaterThan(0) + expect(screen.getAllByTestId('size-stop')).toHaveLength(2) + expect(screen.getByTestId('size-minimum')).toHaveAttribute( + 'data-value', + String(minimum), + ) + const low = Math.round((Math.min(30, minimum) / 2) * 100) / 100 + expect(slider()).toHaveAttribute('min', String(low)) + expect(slider()).toHaveAttribute('max', '68') + }) + + it('has no red mark where the core gives no minimum', async () => { + await mount(withPoints(point('a', 50, 50, 5))) + await select() + expect(screen.queryByTestId('size-minimum')).toBeNull() + }) + + it('arrows and Page Up preview only; leaving the slider commits once', async () => { + await mount(withPoints(point('a', 50, 50, 5), point('b', 20, 20, 8))) + await select() + const before = depth() + fireEvent.keyDown(slider(), { key: 'ArrowRight' }) + fireEvent.keyDown(slider(), { key: 'ArrowRight' }) + expect(geometryOf('a')).toMatchObject({ r: 5 }) + fireEvent.keyDown(slider(), { key: 'PageUp' }) + expect(slider()).toHaveValue('8') + expect(depth()).toBe(before) + fireEvent.blur(slider()) + expect(geometryOf('a')).toMatchObject({ r: 8 }) + expect(depth()).toBe(before + 1) + expect(message()).toHaveTextContent('Taille modifiée') + }) + + it('a track click commits once at the release (WCAG 2.5.7)', async () => { + await mount(withPoints(point('a', 50, 50, 5))) + await select() + const before = depth() + fireEvent.change(slider(), { target: { value: '7' } }) + expect(geometryOf('a')).toMatchObject({ r: 5 }) + fireEvent.pointerUp(slider()) + fireEvent.blur(slider()) + expect(geometryOf('a')).toMatchObject({ r: 7 }) + expect(depth()).toBe(before + 1) + }) + + it('Ctrl+Z on the slider cancels its preview, then undoes (R-13)', async () => { + await mount(withPoints(point('a', 50, 50, 5))) + render() + await select() + fireEvent.change(slider(), { target: { value: '7' } }) + fireEvent.keyDown(slider(), { key: 'z', ctrlKey: true }) + expect(useAnnotationWork.getState().preview).toBeNull() + expect(slider()).toHaveValue('5') + fireEvent.change(slider(), { target: { value: '7' } }) + fireEvent.pointerUp(slider()) + expect(geometryOf('a')).toMatchObject({ r: 7 }) + fireEvent.keyDown(slider(), { key: 'z', ctrlKey: true }) + expect(geometryOf('a')).toMatchObject({ r: 5 }) + }) + + it('a value under the mark is refused by the core and restored in red', async () => { + await mountLarge(withPoints(point('a', 500, 500, 30))) + await select() + const before = depth() + fireEvent.change(slider(), { target: { value: '8' } }) + fireEvent.pointerUp(slider()) + expect(geometryOf('a')).toMatchObject({ r: 30 }) + expect(depth()).toBe(before) + expect(slider()).toHaveValue('30') + expect(within(message()).getByRole('alert')).toHaveTextContent( + 'Taille refusée', + ) + expect(screen.getByTestId('overlay-refused-place')).toBeInTheDocument() + }) +}) + +describe('the move mode (A11, R-12, R-13)', () => { + const two = () => withPoints(point('a', 50, 50, 5), point('b', 20, 20, 5)) + + it('its arrows commit nothing until « Valider la position », which commits once', async () => { + await mount(two()) + await select() + const before = depth() + await userEvent.setup().click(moveButton()) + expect(document.activeElement).toBe(arrow('la gauche')) + expect(screen.getByTestId('edit-strip-title')).toHaveTextContent( + 'Déplacer le point', + ) + fireEvent.click(arrow('la droite')) + fireEvent.click(arrow('la droite')) + fireEvent.click(arrow('le bas')) + expect(geometryOf('a')).toMatchObject({ cx: 50, cy: 50 }) + expect(screen.getByTestId('overlay-old-place')).toBeInTheDocument() + expect(depth()).toBe(before) + fireEvent.click( + within(bar()).getByRole('button', { name: 'Valider la position' }), + ) + expect(geometryOf('a')).toMatchObject({ cx: 51, cy: 50.5 }) + expect(depth()).toBe(before + 1) + expect(message()).toHaveTextContent('Point déplacé') + expect(screen.queryByTestId('move-mode-bar')).toBeNull() + }) + + it('« Annuler » restores the place, the focus back on « Déplacer le point »', async () => { + await mount(two()) + await select() + await userEvent.setup().click(moveButton()) + fireEvent.click(arrow('la droite')) + fireEvent.click(within(bar()).getByRole('button', { name: 'Annuler' })) + expect(useAnnotationWork.getState()).toMatchObject({ + mode: null, + preview: null, + }) + expect(geometryOf('a')).toMatchObject({ cx: 50 }) + await waitFor(() => expect(document.activeElement).toBe(moveButton())) + }) + + it('Escape restores the place', async () => { + await mount(two()) + await select() + await userEvent.setup().click(moveButton()) + fireEvent.click(arrow('la droite')) + fireEvent.keyDown(arrow('la droite'), { key: 'Escape' }) + expect(useAnnotationWork.getState().mode).toBeNull() + expect(screen.queryByTestId('move-mode-bar')).toBeNull() + expect(screen.getByTestId('annotation-properties')).toBeInTheDocument() + }) + + it('a click on another annotation selects nothing during the mode', async () => { + await mount(two()) + await select() + await userEvent.setup().click(moveButton()) + const other = screen + .getByTestId('annotation-canvas-drawing') + .querySelector('[data-anno-id="b"]')! + const init = { + pointerId: 1, + isPrimary: true, + button: 0, + buttons: 1, + pointerType: 'mouse', + } + fireEvent.pointerDown(other, { ...init, clientX: 20, clientY: 20 }) + fireEvent.pointerUp(other, { ...init, clientX: 20, clientY: 20 }) + expect(useAnnotationWork.getState().mode?.annotationId).toBe('a') + expect(screen.getByTestId('move-mode-bar')).toBeInTheDocument() + }) + + it('a drag anywhere moves the mode preview and commits nothing', async () => { + await mount(two()) + await select() + await userEvent.setup().click(moveButton()) + const box = screen.getByTestId('annotation-canvas') + const init = { + pointerId: 1, + isPrimary: true, + button: 0, + buttons: 1, + pointerType: 'touch', + } + fireEvent.pointerDown(box, { ...init, clientX: 80, clientY: 80 }) + fireEvent.pointerMove(box, { ...init, clientX: 92, clientY: 80 }) + fireEvent.pointerUp(box, { ...init, clientX: 92, clientY: 80 }) + expect(useAnnotationWork.getState().preview?.geometry).toMatchObject({ + cx: 62, + }) + expect(geometryOf('a')).toMatchObject({ cx: 50 }) + expect(useAnnotationWork.getState().mode?.started).toBe(true) + }) + + it('Ctrl+Z only cancels it; a later Enter on the handle commits nothing', async () => { + await mount(two()) + render() + await select() + await userEvent.setup().click(moveButton()) + fireEvent.click(arrow('la droite')) + const before = depth() + fireEvent.keyDown(document.body, { key: 'z', ctrlKey: true }) + expect(useAnnotationWork.getState()).toMatchObject({ + mode: null, + preview: null, + }) + expect(depth()).toBe(before) + fireEvent.keyDown(handle(), { key: 'Enter' }) + expect(geometryOf('a')).toMatchObject({ cx: 50 }) + expect(depth()).toBe(before) + }) + + it('a document change during the mode drops it and says so', async () => { + await mount(two()) + await select() + await userEvent.setup().click(moveButton()) + fireEvent.click(arrow('la droite')) + act(() => void moveOther()) + expect(useAnnotationWork.getState().mode).toBeNull() + expect( + await screen.findByText('Déplacement abandonné : la fiche a changé.'), + ).toBeInTheDocument() + expect(screen.queryByTestId('move-mode-bar')).toBeNull() + }) +}) + +describe('the point handle (R-9, R-11)', () => { + it('is a focusable button outside any aria-hidden subtree, named « Point {nom} »', async () => { + await mount(withPoints(point('a', 50, 50, 5))) + await select() + expect(handle()).toHaveAttribute('tabindex', '0') + expect(handle().closest('[aria-hidden="true"]')).toBeNull() + }) + + it('arrows move a preview only (no pan), Enter commits once; Shift ×10', async () => { + await mount(withPoints(point('a', 50, 50, 5))) + await select() + const before = depth() + const transform = () => + (screen.getByTestId('annotation-canvas').firstElementChild as HTMLElement) + .style.transform + const panned = transform() + handle().focus() + fireEvent.keyDown(handle(), { key: 'ArrowRight' }) + fireEvent.keyDown(handle(), { key: 'ArrowDown', shiftKey: true }) + expect(transform()).toBe(panned) + expect(geometryOf('a')).toMatchObject({ cx: 50, cy: 50 }) + expect(depth()).toBe(before) + fireEvent.keyDown(handle(), { key: 'Enter' }) + expect(geometryOf('a')).toMatchObject({ cx: 50.5, cy: 55 }) + expect(depth()).toBe(before + 1) + }) + + it('leaving the handle commits the series (BDR-050); Escape drops it', async () => { + await mount(withPoints(point('a', 50, 50, 5))) + await select() + fireEvent.keyDown(handle(), { key: 'ArrowLeft' }) + fireEvent.keyDown(handle(), { key: 'Escape' }) + expect(useAnnotationWork.getState().preview).toBeNull() + fireEvent.blur(handle()) + expect(geometryOf('a')).toMatchObject({ cx: 50 }) + fireEvent.keyDown(handle(), { key: 'ArrowLeft' }) + fireEvent.blur(handle()) + expect(geometryOf('a')).toMatchObject({ cx: 49.5 }) + }) + + it('a stale series never commits (R-13)', async () => { + await mount(withPoints(point('a', 50, 50, 5), point('b', 20, 20, 5))) + await select() + fireEvent.keyDown(handle(), { key: 'ArrowLeft' }) + act(() => void moveOther()) + fireEvent.keyDown(handle(), { key: 'Enter' }) + expect(geometryOf('a')).toMatchObject({ cx: 50 }) + }) +}) + +describe('A5: a new point takes the most used size', () => { + const sized = () => + withPoints( + point('a', 20, 20, 7), + point('b', 40, 40, 7), + point('c', 60, 60, 9), + ) + + it('the keyboard point and the Point tool click', async () => { + await mount(sized()) + const user = userEvent.setup() + await user.click(screen.getByRole('button', { name: 'Ajouter un point' })) + const panel = await screen.findByTestId('annotation-creation') + expect(within(panel).getByLabelText('Rayon')).toHaveValue('7') + }) + + it('the Point tool shows the slider at that size; a new size feeds the click', async () => { + await mount(sized()) + const user = userEvent.setup() + await user.click(screen.getByRole('button', { name: 'Point' })) + expect(slider()).toHaveValue('7') + fireEvent.change(slider(), { target: { value: '9' } }) + expect(slider()).toHaveValue('9') + }) +}) diff --git a/apps/app/tests/unit/editor-undo-shortcuts.test.tsx b/apps/app/tests/unit/editor-undo-shortcuts.test.tsx index cabfe699..7df96a72 100644 --- a/apps/app/tests/unit/editor-undo-shortcuts.test.tsx +++ b/apps/app/tests/unit/editor-undo-shortcuts.test.tsx @@ -10,11 +10,7 @@ import { store, } from '../helpers/editorHarness' import { mountDraft, setWidth } from '../helpers/editorRoute' -import { - setModePreview, - startMove, - useAnnotationWork, -} from '@/editor/annotations/workStore' +import { useAnnotationWork } from '@/editor/annotations/workStore' vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) })) vi.mock('@faunosteo/supabase', async (orig) => ({ @@ -90,20 +86,23 @@ describe('editor-wide undo', () => { }) describe('undo with something pending (R-13)', () => { - it('Ctrl+Z only cancels a move mode; the next one undoes', async () => { + it('Ctrl+Z only cancels a keyboard series; the next one undoes', async () => { mountDraft() await ready() act(() => void commitMove(40)) const stored = store.getState().previewState!.document.annotations[0] - act(() => { - startMove(stored.id, store.getState().documentText) - setModePreview( - { type: 'circle', cx: 90, cy: 50, r: 10 }, - stored.geometry!, - ) - }) + act(() => + useAnnotationWork.setState({ + preview: { + annotationId: stored.id, + geometry: { type: 'circle', cx: 90, cy: 50, r: 10 }, + base: store.getState().documentText, + source: 'keys', + }, + }), + ) ctrlZ(document.body) - expect(useAnnotationWork.getState().mode).toBeNull() + expect(useAnnotationWork.getState().preview).toBeNull() expect(cx()).toMatchObject({ cx: 40 }) ctrlZ(document.body) expect(cx()).toMatchObject({ cx: 50 })