From 1deb037fac1ddd35dd734b0b7de4c265dd268fd8 Mon Sep 17 00:00:00 2001 From: bchanot Date: Tue, 17 Nov 2026 17:45:41 +0100 Subject: [PATCH] feat(editor): fixed edit strip and message line without layout shift MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit U2 Task 3 (A6, A14, R-2). A fixed-height strip over the drawing and the right column replaces the tool line, the sr-only selection tag of the edit body and TracingBar: lead (name + status, type + detail), notice (refusal, first geometry issue + n, unmeasured view with its link, no category, no child view), commands (Fermer le trace, Retirer le dernier sommet, Annuler le trace). A fixed-height line under the drawing holds the add buttons and the gesture message: a kept drop says « Point deplace » with « Defaire » (same store undo as the header), a refused drop says « Deplacement refuse : ... » as a red alert. 6 s, held by mouse hover and focus inside, closed by any commit, undo or redo. trace_pop and Backspace remove the last vertex. The busy « Aller a » target is the strip's tracing commands. scrollbar-gutter stable, scoped to the editor. e2e helper expectNoShift (boxes, scroll height, gutter, client width, layout-shift sum). DraftHeader untouched: no shift seen. Rewritten assertions (old -> new): - tab unit « Sélection : point » on annotation-selection-tag -> strip detail « Point » - tab unit tag sr-only, not live -> strip lead outside any live region - tab unit « 1 sommet posé. » -> « 1 sommet posé » (board 04 wording) - tab unit D6b tag present / « zone » -> strip detail « Point » / « Zone · 3 sommets » - keep-alive, sections, escape units: tracing-bar -> tracing-commands - e2e selectionTag helper -> strip title with data-selection; the twin's tag is twinSelectionTag (deselect 375 px describe) - e2e deselect « tag position absolute » (edit) -> strip height 64 px, drawing top unchanged; twin Escape test keeps tag 0, properties 0, overview visible - e2e deselect and journey tracing-bar / annotation-selection-tag -> tracing-commands / selectionTag - e2e historyButton scoped to history-buttons (the message's « Défaire » has the same accessible name) --- apps/app/e2e/shell/editor-annotations.spec.ts | 121 ++++++++ apps/app/e2e/shell/editor-deselect.spec.ts | 33 ++- apps/app/e2e/shell/editor-journey.spec.ts | 4 +- apps/app/e2e/support/editor.ts | 9 +- apps/app/e2e/support/layout.ts | 146 ++++++++++ .../editor/annotations/EditStrip.tsx | 111 ++++++++ .../annotations/EditableAnnotations.tsx | 231 ++++++++++------ .../editor/annotations/GestureMessage.tsx | 79 ++++++ .../editor/annotations/KeyboardAdd.tsx | 2 +- .../editor/annotations/PropertiesPanel.tsx | 2 +- .../editor/annotations/TracingBar.tsx | 34 --- .../app/src/editor/annotations/focusTarget.ts | 6 +- apps/app/src/editor/annotations/stripLead.ts | 161 +++++++++++ apps/app/src/editor/annotations/uiState.ts | 11 + .../editor/annotations/useGestureMessage.ts | 93 +++++++ .../src/editor/annotations/usePlacement.ts | 30 +- apps/app/src/i18n/en.ts | 23 +- apps/app/src/i18n/fr.ts | 23 +- apps/app/src/styles/index.css | 2 + .../unit/editor-annotations-tab.test.tsx | 258 +++++++++++++++++- apps/app/tests/unit/editor-escape.test.tsx | 10 +- .../app/tests/unit/editor-keep-alive.test.tsx | 10 +- apps/app/tests/unit/editor-sections.test.tsx | 10 +- 23 files changed, 1228 insertions(+), 181 deletions(-) create mode 100644 apps/app/e2e/support/layout.ts create mode 100644 apps/app/src/components/editor/annotations/EditStrip.tsx create mode 100644 apps/app/src/components/editor/annotations/GestureMessage.tsx delete mode 100644 apps/app/src/components/editor/annotations/TracingBar.tsx create mode 100644 apps/app/src/editor/annotations/stripLead.ts create mode 100644 apps/app/src/editor/annotations/useGestureMessage.ts diff --git a/apps/app/e2e/shell/editor-annotations.spec.ts b/apps/app/e2e/shell/editor-annotations.spec.ts index a10d6734..d53d2dca 100644 --- a/apps/app/e2e/shell/editor-annotations.spec.ts +++ b/apps/app/e2e/shell/editor-annotations.spec.ts @@ -11,13 +11,18 @@ import { pressAtBox, openEditor, pickAnnotation, + pointOf, saveDraft, + saveLine, seedDraft, selectionTag, selectTab, serverDocument, + shapeWith, standardShape, + UNSAVED_LINE, } from '../support/editor' +import { expectNoShift } from '../support/layout' // V1-2.6 A3 (contract C7, C8, C21): points, zones and links by clicks and by keyboard, // move by drag, numeric edits, undo and redo, then the save that carries them. @@ -286,4 +291,120 @@ test.describe('editor annotations (A3)', () => { await selectTab(page, dict, 'verification') await expectAccessible(page, 'the verification tab after a deletion') }) + + test.describe('the drawing never moves (A14)', () => { + const button = (page: Page, key: string) => + page.getByRole('button', { name: dict[key], exact: true }) + const line = (page: Page) => page.getByTestId('gesture-line') + + async function openWithPoint(page: Page, width: number) { + await page.setViewportSize({ width, height: 800 }) + // Installed before any timer: the message's 6 s run on this clock (fast-forwarded below). + await page.clock.install() + const actor = await editorActor('fr') + const point = pointOf('p-a', 'main', { cx: 500, cy: 300, r: 40 }, 'Pt A') + const seed = await seedDraft(actor, { shape: shapeWith(point) }) + await openEditor(page, dict, actor, seed.sheetId) + await expect(tool(page, 'point')).toBeEnabled() + return actor + } + + /** A drag of the point from (500, 300) to `to`, in drawing units. */ + async function dragPoint(page: Page, to: { x: number; y: number }) { + const from = await clientOf(page, 500, 300) + const end = await clientOf(page, to.x, to.y) + await page.mouse.move(from.x, from.y) + await page.mouse.down() + await page.mouse.move(end.x, end.y, { steps: 6 }) + await page.mouse.up() + } + + for (const width of [1024, 1180, 1280]) { + test(`at ${width} px: selection, tools, tracing, the first commit, the message`, async ({ + page, + requests, + }) => { + const actor = await openWithPoint(page, width) + requests.forbid(actor.account.email, actor.account.password) + // shortcut: the side panel still swaps the overview for the properties or the + // creation panel until Tasks 6 and 7 (dialogs); its height is exempt there only. + const swaps = ['aside-content'] as const + await expectNoShift( + page, + async () => { + await clickDrawing(page, 500, 300) + await expect(selectionTag(page)).toContainText('Pt A') + }, + swaps, + ) + // The first commit: the save line changes, the message shows (the properties panel + // rewrites its review badge: aside content until Task 6). + await expectNoShift( + page, + async () => { + await dragPoint(page, { x: 560, y: 330 }) + await expect(line(page)).toContainText( + dict['editor.annotations.message.moved.point'], + ) + await expect(saveLine(page)).toHaveText(UNSAVED_LINE) + }, + swaps, + ) + // Its expiry, 6 s later. + await expectNoShift(page, async () => { + await page.clock.fastForward(6_100) + await expect(line(page)).not.toContainText( + dict['editor.annotations.message.moved.point'], + ) + }) + await expectNoShift( + page, + async () => { + await clickDrawing(page, 20, 20) + await expect(selectionTag(page)).toHaveCount(0) + }, + swaps, + ) + await expectNoShift(page, () => tool(page, 'zone').click()) + await expectNoShift(page, () => clickDrawing(page, 600, 150)) + for (const [x, y] of [ + [800, 150], + [700, 400], + ]) + await expectNoShift(page, () => clickDrawing(page, x, y)) + await expectNoShift(page, () => + button(page, 'editor.annotations.trace_pop').click(), + ) + await expectNoShift(page, () => clickDrawing(page, 700, 400)) + await expectNoShift( + page, + async () => { + await button(page, 'editor.annotations.trace_close').click() + await expect(creation(page)).toBeVisible() + }, + swaps, + ) + }) + } + + test('the editor keeps a stable scrollbar gutter; the dashboard does not', async ({ + page, + requests, + }, info) => { + test.skip( + info.project.name !== 'chromium-desktop', + 'measured at 1 280 px', + ) + const actor = await openWithPoint(page, 1280) + requests.forbid(actor.account.email, actor.account.password) + const gutter = () => + page.evaluate( + () => getComputedStyle(document.documentElement).scrollbarGutter, + ) + expect(await gutter()).toBe('stable') + await page.goto('/app') + await expect(page.locator('[data-editor-workspace]')).toHaveCount(0) + expect(await gutter()).toBe('auto') + }) + }) }) diff --git a/apps/app/e2e/shell/editor-deselect.spec.ts b/apps/app/e2e/shell/editor-deselect.spec.ts index 118bde68..20fad57b 100644 --- a/apps/app/e2e/shell/editor-deselect.spec.ts +++ b/apps/app/e2e/shell/editor-deselect.spec.ts @@ -28,6 +28,7 @@ import { serverRevision, shapeWith, toolButton, + twinSelectionTag, UNSAVED_LINE, } from '../support/editor' @@ -247,7 +248,7 @@ test.describe('deselect and D6b (editor, mouse and keyboard)', () => { await toolButton(page, dict, 'zone').click() await clickAt(page, { x: 300, y: 500 }) await clickAt(page, { x: 400, y: 500 }) - const bar = page.getByTestId('tracing-bar') + const bar = page.getByTestId('tracing-commands') await expect(bar).toBeVisible() await box(page).focus() await page.keyboard.press('Escape') @@ -327,7 +328,8 @@ test.describe('deselect and D6b (editor, mouse and keyboard)', () => { ] as [string, { x: number; y: number }][]) { await clickAt(page, at) await expectSelected(page, name) - await expect(selectionTag(page)).toHaveCSS('position', 'absolute') + // The name shows in the fixed-height strip, which never moves the drawing. + await expect(page.getByTestId('edit-strip')).toHaveCSS('height', '64px') expect(await top(), `${name} selected`).toBe(before) await clickAt(page, IN_ROOT) await expectDeselected(page) @@ -745,23 +747,23 @@ test.describe('deselect and D6b (read-only twin at 375 px)', () => { await takeRecord(page) await tap(cdp, await markerAt()) - await expect(selectionTag(page)).toContainText(POINT) + await expect(twinSelectionTag(page)).toContainText(POINT) await shoot(info, 'r1-panel-375', properties(page)) await report('twin tap on a marker') await takeRecord(page) await tap(cdp, await twinAt(IN_RECT.x, IN_RECT.y)) - await expect(selectionTag(page)).toHaveCount(0) + await expect(twinSelectionTag(page)).toHaveCount(0) await expect(canvas).toBeFocused() await report('twin tap on the rect') await tap(cdp, await markerAt()) - await expect(selectionTag(page)).toContainText(POINT) + await expect(twinSelectionTag(page)).toContainText(POINT) await takeRecord(page) const from = await twinAt(IN_CIRCLE.x, IN_CIRCLE.y) await drag(cdp, from, { x: from.x + 30, y: from.y + 10 }) await frames(page) - await expect(selectionTag(page)).toContainText(POINT) + await expect(twinSelectionTag(page)).toContainText(POINT) const drag1 = guards(await report('twin one-finger drag')) expect(drag1.clicks, 'twin drag: no click').toBe(0) expect( @@ -774,7 +776,7 @@ test.describe('deselect and D6b (read-only twin at 375 px)', () => { await touch(cdp, 'touchStart', [two, { x: two.x + 30, y: two.y }]) await touch(cdp, 'touchEnd', []) await frames(page) - await expect(selectionTag(page)).toContainText(POINT) + await expect(twinSelectionTag(page)).toContainText(POINT) const pair = guards(await report('twin two-finger tap')) expect(pair.nonPrimary, 'twin: a non-primary pointerdown').toBeGreaterThan( 0, @@ -819,12 +821,12 @@ test.describe('deselect and D6b (read-only twin at 375 px)', () => { [LINK, { x: 825, y: 575 }], ] as [string, { x: number; y: number }][]) { await tap(cdp, await twinAt(at.x, at.y)) - await expect(selectionTag(page)).toHaveCount(1) - await expect(selectionTag(page)).toContainText(name) - await expect(selectionTag(page)).toHaveCSS('position', 'absolute') + await expect(twinSelectionTag(page)).toHaveCount(1) + await expect(twinSelectionTag(page)).toContainText(name) + await expect(twinSelectionTag(page)).toHaveCSS('position', 'absolute') expect(await top(), `${name} selected`).toBe(before) await tap(cdp, await twinAt(IN_RECT.x, IN_RECT.y)) - await expect(selectionTag(page)).toHaveCount(0) + await expect(twinSelectionTag(page)).toHaveCount(0) expect(await top(), `${name} deselected`).toBe(before) } }) @@ -850,7 +852,7 @@ test.describe('deselect and D6b (read-only twin at 375 px)', () => { x: marker!.x + marker!.width / 2, y: marker!.y + marker!.height / 2, }) - await expect(selectionTag(page)).toContainText(POINT) + await expect(twinSelectionTag(page)).toContainText(POINT) const more = page.locator('#editor-tabs-more-button') await more.click() @@ -859,10 +861,13 @@ test.describe('deselect and D6b (read-only twin at 375 px)', () => { await page.keyboard.press('Escape') await expect(more).toHaveAttribute('aria-expanded', 'false') await expect(more).toBeFocused() - await expectKept(page, POINT) + await frames(page) + await expect(twinSelectionTag(page)).toContainText(POINT) await page.keyboard.press('Escape') - await expectDeselected(page) + await expect(twinSelectionTag(page)).toHaveCount(0) + await expect(properties(page)).toHaveCount(0) + await expect(overview(page)).toBeVisible() await expect(liveRegion(page)).toHaveCount(1) expect(saves).toEqual([]) }) diff --git a/apps/app/e2e/shell/editor-journey.spec.ts b/apps/app/e2e/shell/editor-journey.spec.ts index 7adc7105..c553a13c 100644 --- a/apps/app/e2e/shell/editor-journey.spec.ts +++ b/apps/app/e2e/shell/editor-journey.spec.ts @@ -388,9 +388,7 @@ test.describe('editor journey (owner trial steps)', () => { ), }) .click() - await expect(page.getByTestId('annotation-selection-tag')).toContainText( - 'Point de bord', - ) + await expect(selectionTag(page)).toContainText('Point de bord') await selectTab(page, dict, 'verification') await page .getByLabel(dict['editor.verification.note']) diff --git a/apps/app/e2e/support/editor.ts b/apps/app/e2e/support/editor.ts index 7b736df4..053006d9 100644 --- a/apps/app/e2e/support/editor.ts +++ b/apps/app/e2e/support/editor.ts @@ -629,7 +629,8 @@ export function savedLine(dict: Dict, revision: number): RegExp { /** The header « Défaire » / « Refaire » button (enabled ones take a plain click). */ export const historyButton = (page: Page, dict: Dict, kind: 'undo' | 'redo') => - page.getByRole('button', { + // Scoped: the message under the drawing carries a « Défaire » of the same name (T15). + page.getByTestId('history-buttons').getByRole('button', { name: dict[`editor.history.${kind}_title`], exact: true, }) @@ -714,8 +715,12 @@ export const creationPanel = (page: Page) => export const annotationList = (page: Page, dict: Dict) => page.getByRole('list', { name: dict['editor.annotations.list'] }) -/** The screen-reader-only tag rendered while an annotation is selected. */ +/** The edit strip's name of the selected annotation (U2 Task 3: the strip replaced the tag). */ export const selectionTag = (page: Page) => + page.locator('[data-testid="edit-strip-title"][data-selection]') + +/** The read-only twin's screen-reader-only tag, rendered while an annotation is selected. */ +export const twinSelectionTag = (page: Page) => page.getByTestId('annotation-selection-tag') /** Selects an annotation from the overview card, leaving a selection first when there is one. */ diff --git a/apps/app/e2e/support/layout.ts b/apps/app/e2e/support/layout.ts new file mode 100644 index 00000000..c9c1cdd8 --- /dev/null +++ b/apps/app/e2e/support/layout.ts @@ -0,0 +1,146 @@ +/** + * The no-shift probe of U2 (adjustment A14, plan Task 3): a state change of the annotations + * tab moves no box. The boxes of the canvas, the strip, the aside and the draft header, + * the page's scroll height, its scrollbar gutter and its client width are read before and + * after `act`; a layout-shift observer adds up every entry in between, the ones following + * an input included (a message appearing after a drop is still a shift). + */ +import { expect, type Page } from '@playwright/test' + +/** + * What may change by design until a later task, named at the call site only: the side + * panel's own content (its height, the scroll height, and shifts whose every moved node is + * inside it) while it still swaps the overview, the properties and the creation panel. + */ +export type ShiftExemption = 'aside-content' + +interface Box { + x: number + y: number + width: number + height: number +} + +interface Snapshot { + boxes: Record + scrollHeight: number + gutter: string + clientWidth: number +} + +const PARTS = { + canvas: '[data-testid="annotation-canvas"]', + strip: '[data-testid="edit-strip"]', + aside: '[data-testid="editor-tab-annotations"] aside', + header: 'header:has(> nav + div > h1)', +} as const + +function snapshot(page: Page): Promise { + return page.evaluate((parts) => { + const shown = (selector: string) => + [...document.querySelectorAll(selector)].find( + (element) => (element as HTMLElement).offsetParent !== null, + ) + const boxes: Record = {} + for (const [name, selector] of Object.entries(parts)) { + const rect = shown(selector)?.getBoundingClientRect() + boxes[name] = rect + ? { x: rect.x, y: rect.y, width: rect.width, height: rect.height } + : null + } + const root = document.documentElement + return { + boxes, + scrollHeight: root.scrollHeight, + gutter: getComputedStyle(root).scrollbarGutter, + clientWidth: root.clientWidth, + } + }, PARTS) +} + +/** The page side of the probe: the summed shift and what moved, for the failure message. */ +interface ShiftScope { + __shift: { total: number; moved: string[] } + __shiftObserver?: PerformanceObserver +} + +/** Starts summing layout-shift entries; read back with `shiftTotal`. */ +function observeShifts(page: Page, asideExempt: boolean): Promise { + return page.evaluate( + ({ exempt, aside }) => { + const scope = window as unknown as ShiftScope + scope.__shiftObserver?.disconnect() + scope.__shift = { total: 0, moved: [] } + const observer = new PerformanceObserver((list) => { + for (const entry of list.getEntries()) { + const shift = entry as unknown as { + value: number + sources: { node?: Node }[] + } + const inAside = shift.sources.every((source) => + (source.node as Element | undefined)?.closest?.(aside), + ) + if (exempt && inAside) continue + scope.__shift.total += shift.value + for (const source of shift.sources) { + const node = source.node as Element | undefined + scope.__shift.moved.push( + node?.outerHTML?.slice(0, 160) ?? String(source.node), + ) + } + } + }) + observer.observe({ type: 'layout-shift' }) + scope.__shiftObserver = observer + }, + { exempt: asideExempt, aside: PARTS.aside }, + ) +} + +/** Two frames for layout to settle, then the pending entries and the total. */ +function shiftTotal(page: Page): Promise { + return page.evaluate(async () => { + await new Promise((done) => + requestAnimationFrame(() => requestAnimationFrame(done)), + ) + const scope = window as unknown as ShiftScope + const observer = scope.__shiftObserver! + const pending = observer.takeRecords() + observer.disconnect() + for (const entry of pending) { + scope.__shift.total += (entry as unknown as { value: number }).value + } + return scope.__shift + }) +} + +/** + * Runs `act` and asserts nothing moved. `exempt: ['aside-content']` lets the side panel's + * content change (see `ShiftExemption`); the aside's position and width, the canvas, the + * strip and the header are still checked, and every shift outside the aside. + */ +export async function expectNoShift( + page: Page, + act: () => Promise, + exempt: readonly ShiftExemption[] = [], +): Promise { + const before = await snapshot(page) + const loose = exempt.includes('aside-content') + await observeShifts(page, loose) + await act() + const shift = await shiftTotal(page) + const after = await snapshot(page) + const drop = (shot: Snapshot) => ({ + ...shot, + scrollHeight: loose ? 0 : shot.scrollHeight, + boxes: { + ...shot.boxes, + aside: + loose && shot.boxes.aside + ? { ...shot.boxes.aside, height: 0 } + : shot.boxes.aside, + }, + }) + expect(drop(after)).toEqual(drop(before)) + expect(shift.total, `layout shift of ${shift.moved.join(' | ')}`).toBe(0) +} diff --git a/apps/app/src/components/editor/annotations/EditStrip.tsx b/apps/app/src/components/editor/annotations/EditStrip.tsx new file mode 100644 index 00000000..f8cfb50d --- /dev/null +++ b/apps/app/src/components/editor/annotations/EditStrip.tsx @@ -0,0 +1,111 @@ +import type { ReactNode } from 'react' +import type { StripLead } from '@/editor/annotations/stripLead' +import EditorGlyph from '../EditorGlyph' +import ReviewBadge from './ReviewBadge' + +export type { StripLead } + +/** The strip's middle: a refusal or a reason, two lines at most. */ +export interface StripNotice { + tone: 'error' | 'info' + text: string + /** How many more of the same kind are not shown (« +n »). */ + more?: number + link?: { label: string; onClick(): void } +} + +/** + * The fixed strip over the drawing and the right column (A6, LRN-131): left, what is + * selected or in progress on two lines; middle, a refusal or a reason; right, the commands. + * Its height never changes, so nothing under it moves when its content does. + */ +export default function EditStrip({ + lead, + notice, + commands, +}: { + lead: StripLead + notice: StripNotice | null + commands: ReactNode +}) { + return ( +
+ +
+ {notice && } +
+
{commands}
+
+ ) +} + +function Lead({ lead }: { lead: StripLead }) { + return ( +
+ + + +
+

+ + {lead.title} + + {lead.status && ( + + + + )} +

+

+ {lead.detail} +

+
+
+ ) +} + +function Notice({ notice }: { notice: StripNotice }) { + const error = notice.tone === 'error' + return ( +

+ {notice.text} + {notice.more !== undefined && notice.more > 0 && ( + +{notice.more} + )} + {notice.link && ( + + )} +

+ ) +} diff --git a/apps/app/src/components/editor/annotations/EditableAnnotations.tsx b/apps/app/src/components/editor/annotations/EditableAnnotations.tsx index f9af47a7..8156e35b 100644 --- a/apps/app/src/components/editor/annotations/EditableAnnotations.tsx +++ b/apps/app/src/components/editor/annotations/EditableAnnotations.tsx @@ -1,4 +1,5 @@ import { useEffect, useReducer, useState, type Dispatch } from 'react' +import Button from '@/components/ui/Button' import type { AnatomicalSheetDocument, Annotation, @@ -10,6 +11,11 @@ import { parseFrame, type Frame } from '@/editor/annotations/frame' import { isEditable } from '@/editor/annotations/geometryEdit' import { useSelectionEscape } from '@/editor/annotations/deselect' import { usePlacement } from '@/editor/annotations/usePlacement' +import { stripLeadOf } from '@/editor/annotations/stripLead' +import { + useGestureMessage, + type GestureMessages, +} from '@/editor/annotations/useGestureMessage' import { initialUi, uiReducer, @@ -23,19 +29,18 @@ import { useViewModel, type ViewModel, } from '@/editor/annotations/useViewModel' -import type { AnnotationSection } from '@/editor/navigation' +import { targetOfKey, type AnnotationSection } from '@/editor/navigation' import { usePlaceVisible } from '@/lib/placeVisibility' 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 CreationPanel from './CreationPanel' +import EditStrip, { type StripNotice } from './EditStrip' +import GestureMessage from './GestureMessage' import KeyboardAdd from './KeyboardAdd' import OverviewPanel from './OverviewPanel' -import PropertiesPanel, { UnmeasuredHint } from './PropertiesPanel' -import SelectionTag from './SelectionTag' -import TracingBar from './TracingBar' +import PropertiesPanel, { useGeometryIssues } from './PropertiesPanel' import ViewSwitcher from './ViewSwitcher' interface Props { @@ -127,10 +132,17 @@ function useCommitContext(): CommitContext { return { t, locale } } +/** The tab's work: the commit context, the line under the drawing and the placement. */ +function useWork(scene: Scene) { + const context = useCommitContext() + const message = useGestureMessage() + const placement = usePlacement({ ...scene, context, message }) + return { context, message, placement } +} + export default function EditableAnnotations(props: Props) { const scene = useScene(props) - const context = useCommitContext() - const placement = usePlacement({ ...scene, context }) + const { context, message, placement } = useWork(scene) const { ui, selected } = scene const visible = usePlaceVisible() const { asideRef, byDrawing } = useSelectionEscape( @@ -139,15 +151,19 @@ export default function EditableAnnotations(props: Props) { visible && selected !== undefined && ui.tracing === null && !ui.pending, ) return ( -
- - +
+ +
+ + +
) } @@ -157,13 +173,15 @@ type Placement = ReturnType function CanvasColumn({ scene, placement, + message, onDeselect, }: { scene: Scene placement: Placement + message: GestureMessages onDeselect: () => void }) { - const { doc, ui, dispatch, model, selected } = scene + const { doc, dispatch, model } = scene const noCategory = doc.categories.length === 0 return (
@@ -172,52 +190,22 @@ function CanvasColumn({ current={scene.viewId} onSelect={(id) => dispatch({ type: 'view', viewId: id })} /> - - {selected && } - {ui.tracing && ( - dispatch({ type: 'trace_cancel' })} + + addAtCentre(kind, scene.frame, dispatch)} /> - )} - addAtCentre(kind, scene.frame, dispatch)} - /> +
) } -function TagOf({ - annotation, - doc, -}: { - annotation: Annotation - doc: AnatomicalSheetDocument -}) { - const locale = useLocaleStore((s) => s.locale) - return ( - - ) -} - function CanvasStage({ scene, placement, @@ -344,37 +332,120 @@ function overlayOf( } } -/** The tool line and the reasons a tool cannot be used now. */ -function ToolNotes({ - tool, - hint, - model, - noCategory, - viewId, - navigate, +/** The strip of the edit body: the lead of the scene, its notice, the tracing commands. */ +function SceneStrip({ + scene, + placement, }: { - tool: ToolId - hint: string | null - model: ViewModel - noCategory: boolean - viewId: string - navigate: EditorPlaceProps['navigate'] + scene: Scene + placement: Placement }) { const t = useT() - const linkBlocked = tool === 'link' && model.children.length === 0 + const locale = useLocaleStore((s) => s.locale) + const notice = useStripNotice(scene) + const { ui, selected, doc } = scene return ( -
-

{t(`editor.annotations.tool_hint.${tool}`)}

- {!model.measured && ( - - )} - {noCategory &&

{t('editor.annotations.no_category')}

} - {linkBlocked &&

{t('editor.annotations.no_child_view')}

} - {hint && ( -

- {hint} -

- )} + scene.dispatch({ type: 'trace_cancel' })} + /> + ) + } + /> + ) +} + +/** + * The strip's middle, first match wins: a refusal, the selection's geometry issues (the + * first, then « +n »), then why a tool cannot be used now. + */ +function useStripNotice(scene: Scene): StripNotice | null { + const t = useT() + const issues = useGeometryIssues(scene.selected?.id ?? '') + const { ui, model, doc } = scene + if (ui.hint) return { tone: 'error', text: ui.hint } + if (scene.selected && issues.length > 0) { + return { tone: 'error', text: issues[0]!, more: issues.length - 1 } + } + if (!model.measured) return unmeasuredNotice(scene, t) + if (doc.categories.length === 0) { + return { tone: 'info', text: t('editor.annotations.no_category') } + } + if (ui.tool === 'link' && model.children.length === 0) { + return { tone: 'info', text: t('editor.annotations.no_child_view') } + } + return null +} + +/** Points to the views section, on the view whose drawing cannot be measured. */ +function unmeasuredNotice( + scene: Scene, + t: (key: string) => string, +): StripNotice { + const target = targetOfKey({ kind: 'view', id: scene.viewId }) + return { + tone: 'info', + text: t('editor.annotations.unmeasured.hint'), + link: { + label: t('editor.place.views'), + onClick: () => scene.navigate(target), + }, + } +} + +const COMMAND = 'min-h-11 xl:min-h-9' + +/** While a zone or link is traced: close (3 vertices at least), take one back, or drop it. */ +function TracingCommands({ + count, + placement, + onCancel, +}: { + count: number + placement: Placement + onCancel: () => void +}) { + const t = useT() + return ( +
+ + +
) } diff --git a/apps/app/src/components/editor/annotations/GestureMessage.tsx b/apps/app/src/components/editor/annotations/GestureMessage.tsx new file mode 100644 index 00000000..555c6e12 --- /dev/null +++ b/apps/app/src/components/editor/annotations/GestureMessage.tsx @@ -0,0 +1,79 @@ +import type { ReactNode } from 'react' +import { useEditorReadOnly } from '@/editor/editingContext' +import type { GestureMessages } from '@/editor/annotations/useGestureMessage' +import { canUndo, useEditorStore } from '@/editor/state/editorStore' +import { useT } from '@/i18n/useT' + +// Compact: at 1 280 px the column leaves about 145 px beside the three add buttons. +const PILL = + 'inline-flex h-9 max-w-full items-center gap-1.5 rounded-md px-2 text-xs' + +/** The header's undo (T15): the same store step, under the same conditions. */ +function undoLast(readOnly: boolean): void { + const store = useEditorStore.getState() + if (!readOnly && canUndo(store)) store.undoStep() +} + +/** + * The fixed line under the drawing (A14, R-2): the add buttons on the left, the message on + * the right, one line truncated. Its height never changes, so a message showing or leaving + * moves nothing. The status region (polite) is always mounted; a refusal is an alert of its own. + */ +export default function GestureMessage({ + messages, + children, +}: { + messages: GestureMessages + children: ReactNode +}) { + return ( +
+
{children}
+
+ +
+
+ ) +} + +function Message({ messages }: { messages: GestureMessages }) { + const t = useT() + const readOnly = useEditorReadOnly() + const { message, hold } = messages + if (!message) return null + const error = message.tone === 'error' + return ( +

+ + {message.text} + + {message.undo && !error && ( + <> + + + )} +

+ ) +} diff --git a/apps/app/src/components/editor/annotations/KeyboardAdd.tsx b/apps/app/src/components/editor/annotations/KeyboardAdd.tsx index 2e40f8d0..fb7191ec 100644 --- a/apps/app/src/components/editor/annotations/KeyboardAdd.tsx +++ b/apps/app/src/components/editor/annotations/KeyboardAdd.tsx @@ -21,7 +21,7 @@ export default function KeyboardAdd({ }) { const t = useT() return ( -
+
{KINDS.map((kind) => ( - -
- ) -} diff --git a/apps/app/src/editor/annotations/focusTarget.ts b/apps/app/src/editor/annotations/focusTarget.ts index 86075ee2..aa51567d 100644 --- a/apps/app/src/editor/annotations/focusTarget.ts +++ b/apps/app/src/editor/annotations/focusTarget.ts @@ -35,7 +35,7 @@ export interface DrawingState { const BUSY_TARGET = { creation: '[data-creation-heading]', - tracing: '[data-testid="tracing-bar"]', + tracing: '[data-testid="tracing-commands"]', } as const const focusFirst = (selector: string) => visibleElement(selector)?.focus() @@ -70,8 +70,8 @@ function showAnnotation( /** * « Aller à » an annotation on the drawing: shows its view, selects it, then focuses the * properties heading once it has rendered. While a creation or a tracing is in progress - * the request is kept: nothing is dispatched (it would drop the work), the panel or bar - * takes the focus and the live region says why. + * the request is kept: nothing is dispatched (it would drop the work), the panel or the + * strip's tracing commands take the focus and the live region says why. */ export function useAnnotationRequest( focus: FocusRequest | undefined, diff --git a/apps/app/src/editor/annotations/stripLead.ts b/apps/app/src/editor/annotations/stripLead.ts new file mode 100644 index 00000000..5b7a2079 --- /dev/null +++ b/apps/app/src/editor/annotations/stripLead.ts @@ -0,0 +1,161 @@ +import type { + Annotation, + AnatomicalSheetDocument, + ReviewStatus, + SheetView, +} from '@faunosteo/core-wasm/types' +import { annotationName } from '@/components/editor/annotations/AnnotationList' +import type { GlyphName } from '@/components/editor/EditorGlyph' +import type { Locale } from '@/i18n/types' +import { pluralKey } from '../plural' +import type { PendingElement } from './creation' +import type { ToolId, Tracing, UiState } from './uiState' + +/** The strip's left part: what is selected or in progress, then its type and detail. */ +export interface StripLead { + title: string + status?: ReviewStatus + detail: string + icon: GlyphName +} + +export interface LeadContext { + t: (key: string) => string + locale: Locale + /** The sheet cannot be edited now: the detail says so (board 33 E). */ + readOnly?: boolean +} + +const ICON: Record = { + point: 'point', + zone: 'zone', + detail_trigger: 'link', +} + +/** A count phrase of `key`; `{kind}` is filled too when given. */ +function counted( + ctx: LeadContext, + key: string, + count: number, + kind = '', +): string { + return ctx + .t(pluralKey(ctx.locale, key, count)) + .replace('{count}', String(count)) + .replace('{kind}', () => kind) +} + +/** « Point », « Zone · 9 sommets »; « … · fiche en lecture seule » when read-only. */ +export function selectionLead( + annotation: Annotation, + views: readonly SheetView[], + ctx: LeadContext, +): StripLead { + const kind = ctx.t(`editor.annotations.kind.${annotation.kind}`) + const geometry = annotation.geometry + const shape = + geometry?.type === 'polygon' + ? counted( + ctx, + 'editor.annotations.strip.vertices', + geometry.points.length, + kind, + ) + : kind + return { + title: annotationName(annotation, views, ctx.locale), + status: annotation.review_status, + detail: ctx.readOnly + ? ctx + .t('editor.annotations.strip.read_only') + .replace('{detail}', () => shape) + : shape, + icon: ICON[annotation.kind], + } +} + +/** A tracing: « Ajouter une zone » or « Redessiner · {nom} », then the vertices placed. */ +function tracingLead( + tracing: Tracing, + replaced: string, + ctx: LeadContext, +): StripLead { + const title = + tracing.target === 'replace' + ? ctx + .t('editor.annotations.strip.redraw') + .replace('{name}', () => replaced) + : ctx.t(`editor.annotations.add.${tracing.target}`) + return { + title, + detail: counted(ctx, 'editor.annotations.tracing', tracing.points.length), + icon: tracing.target === 'detail_trigger' ? 'link' : 'zone', + } +} + +/** A pending creation, placed or closed, waiting for its properties. */ +function pendingLead(pending: PendingElement, ctx: LeadContext): StripLead { + const { geometry } = pending + return { + title: ctx.t(`editor.annotations.new.${pending.kind}`), + detail: + geometry.type === 'polygon' + ? counted( + ctx, + 'editor.annotations.strip.closed', + geometry.points.length, + ) + : ctx.t('editor.annotations.strip.placed'), + icon: ICON[pending.kind], + } +} + +const TOOL_LEAD: Record< + ToolId, + { title: string; detail: string; icon: GlyphName } +> = { + select: { + title: 'editor.annotations.tool.select', + detail: 'editor.annotations.strip.select', + icon: 'select', + }, + point: { + title: 'editor.annotations.add.point', + detail: 'editor.annotations.strip.place_point', + icon: 'point', + }, + zone: { + title: 'editor.annotations.add.zone', + detail: 'editor.annotations.strip.first_vertex', + icon: 'zone', + }, + link: { + title: 'editor.annotations.add.detail_trigger', + detail: 'editor.annotations.strip.first_vertex', + icon: 'link', + }, +} + +/** What the strip leads with: a creation, then a tracing, then the selection, then the tool. */ +export function stripLeadOf( + ui: UiState, + selected: Annotation | undefined, + doc: AnatomicalSheetDocument, + ctx: LeadContext, +): StripLead { + if (ui.pending) return pendingLead(ui.pending, ctx) + if (ui.tracing) { + const replaced = doc.annotations.find( + (a) => a.id === ui.tracing?.annotationId, + ) + const name = replaced ? annotationName(replaced, doc.views, ctx.locale) : '' + return tracingLead(ui.tracing, name, ctx) + } + if (selected) return selectionLead(selected, doc.views, ctx) + const lead = TOOL_LEAD[ui.tool] + return { + title: ctx.t(lead.title), + detail: ctx.t(lead.detail), + icon: lead.icon, + } +} diff --git a/apps/app/src/editor/annotations/uiState.ts b/apps/app/src/editor/annotations/uiState.ts index 7fb83750..3cebf4a7 100644 --- a/apps/app/src/editor/annotations/uiState.ts +++ b/apps/app/src/editor/annotations/uiState.ts @@ -33,6 +33,7 @@ export type UiAction = | { type: 'pending_drop' } | { type: 'trace_start'; target: Tracing['target']; annotationId?: string } | { type: 'trace_add'; point: Point } + | { type: 'trace_pop' } | { type: 'trace_cancel' } | { type: 'hint'; hint: string | null } | { type: 'filter'; term: string } @@ -108,6 +109,16 @@ export function uiReducer(state: UiState, action: UiAction): UiState { }, } : state + case 'trace_pop': + return state.tracing + ? { + ...state, + tracing: { + ...state.tracing, + points: state.tracing.points.slice(0, -1), + }, + } + : state case 'trace_cancel': return { ...state, tracing: null, hint: null } case 'hint': diff --git a/apps/app/src/editor/annotations/useGestureMessage.ts b/apps/app/src/editor/annotations/useGestureMessage.ts new file mode 100644 index 00000000..9c13bde1 --- /dev/null +++ b/apps/app/src/editor/annotations/useGestureMessage.ts @@ -0,0 +1,93 @@ +import { useEffect, useState, type FocusEvent, type PointerEvent } from 'react' +import { useEditorStore } from '../state/editorStore' + +/** A6/A14: how long a message stays (R-2) and how long a hint does (R-1). */ +const MESSAGE_MS = 6_000 +const HINT_MS = 4_000 + +/** The document and the history a message was shown on: any change closes it (R-2). */ +interface Stamp { + text: string + undo: number + redo: number +} + +export interface GestureMessage { + text: string + tone: 'info' | 'error' + /** Offers « Défaire » (a kept gesture); never on a refusal. */ + undo: boolean + hint: boolean + stamp: Stamp +} + +function currentStamp(): Stamp { + const { documentText, undo, redo } = useEditorStore.getState() + return { text: documentText, undo: undo.length, redo: redo.length } +} + +/** The shown message while the document and both history stacks are those it was shown on. */ +function useLive(message: GestureMessage | null): GestureMessage | null { + const text = useEditorStore((s) => s.documentText) + const undo = useEditorStore((s) => s.undo.length) + const redo = useEditorStore((s) => s.redo.length) + if (!message) return null + const { stamp } = message + const same = stamp.text === text && stamp.undo === undo && stamp.redo === redo + return same ? message : null +} + +/** Hover with a mouse and focus inside hold the message; a touch never does (R-2). */ +function useHold() { + const [hovered, setHovered] = useState(false) + const [focused, setFocused] = useState(false) + const handlers = { + onPointerEnter: (event: PointerEvent) => { + if (event.pointerType === 'mouse') setHovered(true) + }, + onPointerLeave: () => setHovered(false), + onFocus: () => setFocused(true), + onBlur: (event: FocusEvent) => { + if (!event.currentTarget.contains(event.relatedTarget as Node | null)) { + setFocused(false) + } + }, + } + return { held: hovered || focused, handlers } +} + +/** + * The line under the drawing (A14, R-2): « Point déplacé · Défaire » after a gesture, a + * refusal in red, or a hint while nothing else is shown. A message lasts 6 s, held while a + * mouse hovers it or the focus is inside; any commit, undo or redo closes it. + */ +export function useGestureMessage() { + const [shown, setShown] = useState(null) + const message = useLive(shown) + const { held, handlers } = useHold() + useEffect(() => { + if (!message || held) return + const timer = setTimeout( + () => setShown(null), + message.hint ? HINT_MS : MESSAGE_MS, + ) + 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 hint = (text: string) => { + if (message) return + setShown({ + text, + tone: 'info', + undo: false, + hint: true, + stamp: currentStamp(), + }) + } + return { message, show, hint, hold: handlers } +} + +export type GestureMessages = ReturnType diff --git a/apps/app/src/editor/annotations/usePlacement.ts b/apps/app/src/editor/annotations/usePlacement.ts index 7d7e8720..c8a14942 100644 --- a/apps/app/src/editor/annotations/usePlacement.ts +++ b/apps/app/src/editor/annotations/usePlacement.ts @@ -9,6 +9,7 @@ import { updateGeometry, type CommitContext } from './annotationCommit' import { pendingForClick, type NewKind } from './creation' import { round2, type Frame, type XY } from './frame' import type { ToolId, Tracing, UiAction, UiState } from './uiState' +import type { GestureMessages } from './useGestureMessage' /** A click on the first vertex closes the tracing when within this share of F's span. */ const CLOSE_SHARE = 0.015 @@ -25,6 +26,8 @@ export interface PlacementInput { frame: Frame | null doc: AnatomicalSheetDocument context: CommitContext + /** The line under the drawing: a kept drop says so with « Défaire », a refused one in red. */ + message: Pick } const asPoint = (at: XY): Point => [round2(at.x), round2(at.y)] @@ -62,7 +65,7 @@ export function closingActions( ] } -/** Tracing with the zone and link tools: vertices, closing, Enter and Escape. */ +/** Tracing with the zone and link tools: vertices, closing, Enter, Backspace and Escape. */ function tracingActions(input: PlacementInput) { const { ui, dispatch, frame } = input const closeTracing = () => @@ -79,6 +82,10 @@ function tracingActions(input: PlacementInput) { const onTraceKey = (event: KeyboardEvent) => { if (!ui.tracing) return if (event.key === 'Enter') closeTracing() + if (event.key === 'Backspace') { + event.preventDefault() + dispatch({ type: 'trace_pop' }) + } if (event.key === 'Escape') { event.preventDefault() dispatch({ type: 'trace_cancel' }) @@ -87,14 +94,22 @@ function tracingActions(input: PlacementInput) { return { closeTracing, trace, onTraceKey } } -/** A drop commits one update; the hint holds the core's words on a refusal. */ -function dropAction(input: PlacementInput) { +/** A drop commits one update; the line under the drawing says it, or the core's refusal. */ +function dropAction({ doc, context, message }: PlacementInput) { return (id: string, geometry: Geometry) => { - const annotation = input.doc.annotations.find((a) => a.id === id) + const annotation = doc.annotations.find((a) => a.id === id) if (!annotation) return - const result = updateGeometry(annotation, geometry, input.context) - const hint = result.ok ? null : result.messages.join(' ') - input.dispatch({ type: 'hint', hint }) + const result = updateGeometry(annotation, geometry, context) + if (result.ok) { + const text = context.t( + `editor.annotations.message.moved.${annotation.kind}`, + ) + return message.show(text, { undo: true, tone: 'info' }) + } + const text = context + .t('editor.annotations.message.move_refused') + .replace('{text}', () => result.messages.join(' ')) + message.show(text, { undo: false, tone: 'error' }) } } @@ -122,5 +137,6 @@ export function usePlacement(input: PlacementInput) { onDrop: dropAction(input), onTraceKey: tracing.onTraceKey, closeTracing: tracing.closeTracing, + popVertex: () => dispatch({ type: 'trace_pop' }), } } diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index 9c74d061..9829b5a9 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -1598,10 +1598,6 @@ export const en: Dict = { 'editor.annotations.tool.point': 'Point', 'editor.annotations.tool.zone': 'Zone', 'editor.annotations.tool.link': 'Link to a detail view', - 'editor.annotations.tool_hint.select': 'Tool: select and move · Esc cancels a tracing', - 'editor.annotations.tool_hint.point': 'Tool: point · click in the drawing to place a point.', - 'editor.annotations.tool_hint.zone': 'Tool: zone · click to place the vertices; Enter or « Close the tracing » finishes, Esc cancels.', - 'editor.annotations.tool_hint.link': 'Tool: link to a detail view · trace the outline that opens the view; Enter finishes, Esc cancels.', 'editor.annotations.views': 'Views', 'editor.annotations.unmeasured.hint': 'This drawing cannot be measured: add or fix its illustration (Annotations, Views section) before placing or moving elements.', 'editor.annotations.outside': 'Click inside the drawing.', @@ -1646,10 +1642,25 @@ export const en: Dict = { 'editor.annotations.list_empty': 'No annotation in this view.', 'editor.annotations.selection': 'Selection: {kind} « {name} »', 'editor.annotations.properties': 'Annotation properties', - 'editor.annotations.tracing_one': '{count} vertex placed.', - 'editor.annotations.tracing_other': '{count} vertices placed.', + 'editor.annotations.tracing_one': '{count} vertex placed', + 'editor.annotations.tracing_other': '{count} vertices placed', 'editor.annotations.trace_close': 'Close the tracing', 'editor.annotations.trace_cancel': 'Cancel the tracing', + 'editor.annotations.trace_pop': 'Remove last vertex', + 'editor.annotations.strip.select': 'Click an annotation to select it', + 'editor.annotations.strip.place_point': 'Click in the drawing to place the point', + 'editor.annotations.strip.first_vertex': 'Click in the drawing to place the first vertex', + 'editor.annotations.strip.vertices_one': '{kind} · {count} vertex', + 'editor.annotations.strip.vertices_other': '{kind} · {count} vertices', + 'editor.annotations.strip.read_only': '{detail} · read-only sheet', + 'editor.annotations.strip.redraw': 'Redraw · {name}', + 'editor.annotations.strip.placed': 'Point placed, waiting for its properties', + 'editor.annotations.strip.closed_one': 'Tracing closed, {count} vertex, waiting for its properties', + 'editor.annotations.strip.closed_other': 'Tracing closed, {count} vertices, waiting for its properties', + 'editor.annotations.message.moved.point': 'Point moved', + 'editor.annotations.message.moved.zone': 'Zone moved', + 'editor.annotations.message.moved.detail_trigger': 'Access moved', + 'editor.annotations.message.move_refused': 'Move refused: {text}', 'editor.annotations.replace_polygon': 'Replace with a polygon', 'editor.annotations.no_geometry': 'This annotation has no geometry: trace a polygon to give it one.', 'editor.annotations.path': 'This annotation is a free path: its data cannot be edited here.', diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index 90541b9f..f332d4a8 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -1628,10 +1628,6 @@ export const fr: Dict = { 'editor.annotations.tool.point': 'Point', 'editor.annotations.tool.zone': 'Zone', 'editor.annotations.tool.link': 'Accès à une vue détaillée', - 'editor.annotations.tool_hint.select': 'Outil : sélectionner et déplacer · Échap annule un tracé', - 'editor.annotations.tool_hint.point': 'Outil : point · cliquez dans le dessin pour placer un point.', - 'editor.annotations.tool_hint.zone': 'Outil : zone · cliquez pour poser les sommets ; Entrée ou « Fermer le tracé » termine, Échap annule.', - 'editor.annotations.tool_hint.link': 'Outil : accès à une vue détaillée · tracez le contour qui ouvre la vue ; Entrée termine, Échap annule.', 'editor.annotations.views': 'Vues', 'editor.annotations.unmeasured.hint': "Ce dessin n'est pas mesurable : ajoutez ou corrigez son illustration (Annotations, section Vues) avant de placer ou de déplacer des éléments.", 'editor.annotations.outside': "Cliquez à l'intérieur du dessin.", @@ -1676,10 +1672,25 @@ export const fr: Dict = { 'editor.annotations.list_empty': 'Aucune annotation dans cette vue.', 'editor.annotations.selection': 'Sélection : {kind} « {name} »', 'editor.annotations.properties': "Propriétés de l'annotation", - 'editor.annotations.tracing_one': '{count} sommet posé.', - 'editor.annotations.tracing_other': '{count} sommets posés.', + 'editor.annotations.tracing_one': '{count} sommet posé', + 'editor.annotations.tracing_other': '{count} sommets posés', 'editor.annotations.trace_close': 'Fermer le tracé', 'editor.annotations.trace_cancel': 'Annuler le tracé', + 'editor.annotations.trace_pop': 'Retirer le dernier sommet', + 'editor.annotations.strip.select': 'Cliquez sur une annotation pour la sélectionner', + 'editor.annotations.strip.place_point': 'Cliquez dans le dessin pour placer le point', + 'editor.annotations.strip.first_vertex': 'Cliquez dans le dessin pour poser le premier sommet', + 'editor.annotations.strip.vertices_one': '{kind} · {count} sommet', + 'editor.annotations.strip.vertices_other': '{kind} · {count} sommets', + 'editor.annotations.strip.read_only': '{detail} · fiche en lecture seule', + 'editor.annotations.strip.redraw': 'Redessiner · {name}', + 'editor.annotations.strip.placed': 'Point placé, en attente de ses propriétés', + 'editor.annotations.strip.closed_one': 'Tracé fermé, {count} sommet, en attente de ses propriétés', + 'editor.annotations.strip.closed_other': 'Tracé fermé, {count} sommets, en attente de ses propriétés', + 'editor.annotations.message.moved.point': 'Point déplacé', + 'editor.annotations.message.moved.zone': 'Zone déplacée', + 'editor.annotations.message.moved.detail_trigger': 'Accès déplacé', + 'editor.annotations.message.move_refused': 'Déplacement refusé : {text}', 'editor.annotations.replace_polygon': 'Remplacer par un polygone', 'editor.annotations.no_geometry': "Cette annotation n'a pas de géométrie : tracez un polygone pour lui en donner une.", 'editor.annotations.path': 'Cette annotation est un tracé libre (path) : ses données ne se modifient pas ici.', diff --git a/apps/app/src/styles/index.css b/apps/app/src/styles/index.css index e3013938..a1056a5c 100644 --- a/apps/app/src/styles/index.css +++ b/apps/app/src/styles/index.css @@ -4,6 +4,8 @@ html, body, #root { height: 100%; } /* A modal dialog is open (components/ui/ModalDialog): the page behind it does not scroll. */ html:has(dialog:modal) { overflow: hidden; } +/* The editor keeps its scrollbar width whatever opens or closes (R-2, A14): nothing moves. */ +html:has([data-editor-workspace]) { scrollbar-gutter: stable; } body { background: var(--color-bg); color: var(--color-ink); diff --git a/apps/app/tests/unit/editor-annotations-tab.test.tsx b/apps/app/tests/unit/editor-annotations-tab.test.tsx index cb63e140..9fba3aa3 100644 --- a/apps/app/tests/unit/editor-annotations-tab.test.tsx +++ b/apps/app/tests/unit/editor-annotations-tab.test.tsx @@ -12,6 +12,9 @@ import { import userEvent from '@testing-library/user-event' import type { Annotation } from '@faunosteo/core-wasm/types' import AnnotationsTab from '@/components/editor/tabs/AnnotationsTab' +import EditStrip from '@/components/editor/annotations/EditStrip' +import { selectionLead } from '@/editor/annotations/stripLead' +import { fr } from '@/i18n/fr' import { AnnounceContext } from '@/editor/focusRequest' import { useLocaleStore } from '@/state/localeStore' import { @@ -107,18 +110,16 @@ describe('selection and the list', () => { expect(within(panel).getByLabelText('Centre x')).toHaveValue( '743.0451049804688', ) - expect(screen.getByTestId('annotation-selection-tag')).toHaveTextContent( - 'Sélection : point', - ) + expect(screen.getByTestId('edit-strip-detail')).toHaveTextContent('Point') }) - it('keeps the selection tag out of the visual flow and not live', async () => { + it('names the selection in the strip, outside any live region', async () => { await mount() await selectFromList() - const tag = screen.getByTestId('annotation-selection-tag') - expect(tag).toHaveClass('sr-only') - expect(tag).not.toHaveAttribute('aria-live') - expect(tag).not.toHaveAttribute('role') + const lead = screen.getByTestId('edit-strip-lead') + expect(lead).toHaveTextContent('N') + expect(lead.closest('[aria-live]')).toBeNull() + expect(lead.closest('[role]')).toBeNull() }) }) @@ -585,11 +586,11 @@ describe('tracing a zone or a link', () => { ) await userEvent.setup().click(screen.getByRole('button', { name: 'Zone' })) clickAt(20, 20) - expect(screen.getByText('1 sommet posé.')).toBeInTheDocument() + expect(screen.getByText('1 sommet posé')).toBeInTheDocument() fireEvent.keyDown(screen.getByTestId('annotation-canvas'), { key: 'Escape', }) - expect(screen.queryByText('1 sommet posé.')).toBeNull() + expect(screen.queryByText('1 sommet posé')).toBeNull() expect(annotations()).toHaveLength(0) }) @@ -1214,10 +1215,10 @@ describe('a tap on the drawing (D6b)', () => { ), }) tap(marker('anno-b')) - expect(screen.getByTestId('annotation-selection-tag')).toBeInTheDocument() + expect(screen.getByTestId('edit-strip-detail')).toHaveTextContent('Point') tap(marker('zone-a')) - expect(screen.getByTestId('annotation-selection-tag')).toHaveTextContent( - 'zone', + expect(screen.getByTestId('edit-strip-detail')).toHaveTextContent( + 'Zone · 3 sommets', ) expect(announce).not.toHaveBeenCalled() }) @@ -1614,3 +1615,234 @@ describe('a tap on the drawing (D6b)', () => { expect(store.getState().documentText).toBe(before) }) }) + +describe('the strip', () => { + const strip = () => screen.getByTestId('edit-strip') + const lead = () => within(strip()).getByTestId('edit-strip-lead') + const notice = () => within(strip()).getByTestId('edit-strip-notice') + const line = () => screen.getByTestId('gesture-line') + const canvas = () => screen.getByTestId('annotation-canvas') + const button = (name: string) => screen.getByRole('button', { name }) + const drag = (el: Element, to: [number, number]) => { + const at = (x: number, y: number) => ({ + clientX: x, + clientY: y, + pointerId: 1, + button: 0, + buttons: 1, + }) + fireEvent.pointerDown(el, at(50, 50)) + fireEvent.pointerMove(el, at(58, 50)) + fireEvent.pointerUp(el, { ...at(...to), buttons: 0 }) + } + async function tool(name: string) { + await waitFor(() => expect(button(name)).toBeEnabled()) + await userEvent.setup().click(button(name)) + } + const zoneText = (points: number[][], name = 'N') => + insert(drawnText(), { + kind: 'annotation', + value: { + ...zoneAnnotation({ type: 'polygon', points }), + name: { fr: name, en: name }, + }, + }) + + it('has a fixed height, hides its overflow and spans both columns', async () => { + await mount() + expect(strip()).toHaveClass('h-16', 'overflow-hidden') + expect(strip().nextElementSibling?.querySelector('aside')).not.toBeNull() + expect(screen.queryByTestId('tracing-bar')).toBeNull() + }) + + it('the Point tool: « Ajouter un point », then where to click', async () => { + await mount({ text: drawnText() }) + await tool('Point') + expect(lead()).toHaveTextContent('Ajouter un point') + expect(lead()).toHaveTextContent( + 'Cliquez dans le dessin pour placer le point', + ) + }) + + it('a selected point: its name, its status, then « Point »; the sr-only tag is gone', async () => { + await mount() + await selectFromList() + expect(within(lead()).getByTestId('edit-strip-title')).toHaveTextContent( + 'N', + ) + expect(lead()).toHaveTextContent('À confirmer') + expect(within(lead()).getByTestId('edit-strip-detail')).toHaveTextContent( + /^Point$/, + ) + expect(screen.queryByTestId('annotation-selection-tag')).toBeNull() + }) + + it('a selected zone: « Zone · 9 sommets »', async () => { + const nine = [...Array(9).keys()].map((i) => + [ + 50 + 30 * Math.cos((i * 2 * Math.PI) / 9), + 50 + 30 * Math.sin((i * 2 * Math.PI) / 9), + ].map((v) => Math.round(v * 100) / 100), + ) + await mount({ text: zoneText(nine) }) + await selectFromList() + expect(within(lead()).getByTestId('edit-strip-detail')).toHaveTextContent( + 'Zone · 9 sommets', + ) + }) + + it('a long name truncates before the status', async () => { + await mount({ text: zoneText(triangle, 'Un nom très long '.repeat(12)) }) + await selectFromList() + const title = within(lead()).getByTestId('edit-strip-title') + expect(title).toHaveClass('truncate') + expect(title.nextElementSibling).toHaveClass('shrink-0') + expect(title.nextElementSibling).toHaveTextContent('À confirmer') + }) + + it('tracing: the count and the three commands; « Retirer le dernier sommet » and Backspace remove the last vertex', async () => { + await mount({ text: drawnText() }) + await tool('Zone') + triangle.forEach(([x, y]) => pressAt(canvas(), x, y)) + expect(lead()).toHaveTextContent('Ajouter une zone') + expect(lead()).toHaveTextContent('3 sommets posés') + const commands = within(strip()).getByTestId('tracing-commands') + for (const name of [ + 'Fermer le tracé', + 'Retirer le dernier sommet', + 'Annuler le tracé', + ]) { + expect(within(commands).getByRole('button', { name })).toBeEnabled() + } + await userEvent.setup().click(button('Retirer le dernier sommet')) + expect(lead()).toHaveTextContent('2 sommets posés') + expect(button('Fermer le tracé')).toBeDisabled() + fireEvent.keyDown(canvas(), { key: 'Backspace' }) + expect(lead()).toHaveTextContent('1 sommet posé') + }) + + it('read-only: « Point · fiche en lecture seule » from the lead builder', () => { + const t = (key: string) => (fr as Record)[key] ?? key + const value = point('p', 1, 1, 1).value as Annotation + expect( + selectionLead(value, [], { t, locale: 'fr', readOnly: true }), + ).toMatchObject({ + title: 'N', + status: 'to_confirm', + detail: 'Point · fiche en lecture seule', + icon: 'point', + }) + }) + + it('an unmeasured view: the hint in the notice, with its link to the views section', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const drawing = svgBytes() + sb.getSheetVersion.mockResolvedValue({ + ...versionAnswer(text(), 3), + drawings: [], + } as never) + sb.downloadSheetDrawing.mockResolvedValue(drawing.bytes) + store.getState().open(VERSION, USER, { canEdit: true }) + await waitFor(() => expect(store.getState().status).toBe('ready')) + render() + await waitFor(() => + expect(notice()).toHaveTextContent(/Ce dessin n'est pas mesurable/), + ) + await userEvent + .setup() + .click(within(notice()).getByRole('button', { name: 'Vues' })) + expect(props.navigate).toHaveBeenCalled() + }) + + it('geometry issues: the issue of the selection in the notice, as an error', async () => { + await mount({ + text: zoneText([ + [150, 150], + [250, 150], + [150, 250], + ]), + }) + await selectFromList() + const issues = within(screen.getByTestId('annotation-properties')) + .getAllByRole('listitem') + .map((item) => item.textContent) + // The core gives one frame fault per annotation: « +n » is shown by the strip below. + expect(issues).toHaveLength(1) + expect(within(notice()).getByRole('alert')).toHaveTextContent(issues[0]!) + expect(notice()).not.toHaveTextContent('+') + }) + + it('geometry issues: the first one, then « +n » for the others', () => { + render( + , + ) + expect(notice()).toHaveTextContent('Premier problème+2') + }) + + it('a drop shows « Point déplacé · Défaire »; « Défaire » undoes it', async () => { + await mount() + await selectFromList() + const before = store.getState().documentText + drag(marker('anno-a'), [60, 40]) + expect(line()).toHaveTextContent('Point déplacé') + const undo = within(line()).getByRole('button', { + name: 'Défaire la dernière modification', + }) + expect(undo).toHaveTextContent('Défaire') + await userEvent.setup().click(undo) + expect(store.getState().documentText).toBe(before) + expect(line()).not.toHaveTextContent('Point déplacé') + }) + + it('a new commit replaces the message; an undo from the header clears it', async () => { + await mount() + await selectFromList() + drag(marker('anno-a'), [60, 40]) + expect(line()).toHaveTextContent('Point déplacé') + const cx = screen.getByLabelText('Centre x') + const user = userEvent.setup() + await user.clear(cx) + await user.type(cx, '30{Enter}') + expect(line()).not.toHaveTextContent('Point déplacé') + drag(marker('anno-a'), [40, 40]) + expect(line()).toHaveTextContent('Point déplacé') + act(() => void store.getState().undoStep()) + expect(line()).not.toHaveTextContent('Point déplacé') + }) + + it('a refused drop: « Déplacement refusé : … » as an alert, red, no « Défaire »', async () => { + await mount() + await selectFromList() + drag(marker('anno-a'), [98, 50]) + const alert = within(line()).getByRole('alert') + expect(alert).toHaveTextContent(/^Déplacement refusé : /) + expect(alert.className).toContain('danger') + expect(within(line()).queryByRole('button', { name: /Défaire/ })).toBeNull() + }) + + it('expires after 6 s; a mouse hover pauses it, a touch does not', async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }) + try { + await mount() + await selectFromList() + drag(marker('anno-a'), [60, 40]) + const message = () => within(line()).getByTestId('gesture-message') + fireEvent.pointerEnter(message(), { pointerType: 'touch' }) + act(() => void vi.advanceTimersByTime(6_100)) + expect(line()).not.toHaveTextContent('Point déplacé') + drag(marker('anno-a'), [70, 40]) + fireEvent.pointerEnter(message(), { pointerType: 'mouse' }) + act(() => void vi.advanceTimersByTime(10_000)) + expect(line()).toHaveTextContent('Point déplacé') + fireEvent.pointerLeave(message(), { pointerType: 'mouse' }) + act(() => void vi.advanceTimersByTime(6_100)) + expect(line()).not.toHaveTextContent('Point déplacé') + } finally { + vi.useRealTimers() + } + }) +}) diff --git a/apps/app/tests/unit/editor-escape.test.tsx b/apps/app/tests/unit/editor-escape.test.tsx index d8d394ab..5b279d41 100644 --- a/apps/app/tests/unit/editor-escape.test.tsx +++ b/apps/app/tests/unit/editor-escape.test.tsx @@ -240,17 +240,19 @@ describe('Escape leaves alone', () => { expect(store.getState().documentText).toBe(before) }) - it('a tracing: the TracingBar keeps its Escape, the canvas box cancels the tracing only', async () => { + it('a tracing: the strip tracing commands keep their Escape, the canvas box cancels the tracing only', async () => { const user = await mount(ZONE()) await select(user, 'zone-a') await user.click(inPanel('Remplacer par un polygone')) - const bar = await screen.findByTestId('tracing-bar') + const bar = await screen.findByTestId('tracing-commands') bar.focus() escape(bar) - expect(screen.queryByTestId('tracing-bar')).not.toBeNull() + expect(screen.queryByTestId('tracing-commands')).not.toBeNull() canvasBox().focus() escape(canvasBox()) - await waitFor(() => expect(screen.queryByTestId('tracing-bar')).toBeNull()) + await waitFor(() => + expect(screen.queryByTestId('tracing-commands')).toBeNull(), + ) expect(panel()).toBeDefined() }) diff --git a/apps/app/tests/unit/editor-keep-alive.test.tsx b/apps/app/tests/unit/editor-keep-alive.test.tsx index b07a8c74..26c5f36b 100644 --- a/apps/app/tests/unit/editor-keep-alive.test.tsx +++ b/apps/app/tests/unit/editor-keep-alive.test.tsx @@ -504,7 +504,9 @@ describe('« Aller à » while a creation or a tracing is in progress', () => { pressAt(screen.getByTestId('annotation-canvas'), 20, 20) }) expect(tab('Annotations')).toHaveAttribute('aria-selected', 'true') - const bar = within(place('annotations.drawing')).getByTestId('tracing-bar') + const bar = within(place('annotations.drawing')).getByTestId( + 'tracing-commands', + ) expect(bar).toBeVisible() await waitFor(() => expect(document.activeElement).toBe(bar)) expect(liveText()).toContain('tracé est en cours') @@ -531,9 +533,11 @@ describe('« Aller à » while a creation or a tracing is in progress', () => { name: 'Remplacer par un polygone', }), ) - expect(drawing.getByTestId('tracing-bar')).toBeVisible() + expect(drawing.getByTestId('tracing-commands')).toBeVisible() }) - const bar = within(place('annotations.drawing')).getByTestId('tracing-bar') + const bar = within(place('annotations.drawing')).getByTestId( + 'tracing-commands', + ) await waitFor(() => expect(document.activeElement).toBe(bar)) expect(liveText()).toContain('tracé est en cours') }) diff --git a/apps/app/tests/unit/editor-sections.test.tsx b/apps/app/tests/unit/editor-sections.test.tsx index ff39fb92..17b51630 100644 --- a/apps/app/tests/unit/editor-sections.test.tsx +++ b/apps/app/tests/unit/editor-sections.test.tsx @@ -228,9 +228,11 @@ describe('the shown view disappears (undo)', () => { ) await user.click(screen.getByRole('button', { name: 'Zone' })) pressAt(screen.getByTestId('annotation-canvas'), 20, 30) - expect(screen.getByTestId('tracing-bar')).toBeInTheDocument() + expect(screen.getByTestId('tracing-commands')).toBeInTheDocument() act(() => void store.getState().undoStep()) - await waitFor(() => expect(screen.queryByTestId('tracing-bar')).toBeNull()) + await waitFor(() => + expect(screen.queryByTestId('tracing-commands')).toBeNull(), + ) }) it('dispatches nothing while the shown view still exists', async () => { @@ -268,7 +270,7 @@ describe('« Aller à » an annotation while something is in progress', () => { expect(screen.queryByTestId('annotation-properties')).toBeNull() }) - it('an open zone tracing is kept: the bar takes the focus', async () => { + it('an open zone tracing is kept: the strip tracing commands take the focus', async () => { const { consumed, announce } = await withProgress(async (user) => { await waitFor(() => expect(screen.getByRole('button', { name: 'Zone' })).toBeEnabled(), @@ -277,7 +279,7 @@ describe('« Aller à » an annotation while something is in progress', () => { pressAt(screen.getByTestId('annotation-canvas'), 20, 20) }) await waitFor(() => expect(consumed).toHaveBeenCalledWith(7, 'kept')) - expect(document.activeElement).toBe(screen.getByTestId('tracing-bar')) + expect(document.activeElement).toBe(screen.getByTestId('tracing-commands')) expect(announce).toHaveBeenCalledWith( expect.stringContaining('tracé est en cours'), )