feat(editor): fixed edit strip and message line without layout shift

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)
This commit is contained in:
bchanot committed 2026-11-17 17:45:41 +01:00
1 parent b2d78f9621
commit 1deb037fac
23 files changed
+1228 -181

No files matched your search

@@ -11,13 +11,18 @@ import {
pressAtBox, pressAtBox,
openEditor, openEditor,
pickAnnotation, pickAnnotation,
pointOf,
saveDraft, saveDraft,
saveLine,
seedDraft, seedDraft,
selectionTag, selectionTag,
selectTab, selectTab,
serverDocument, serverDocument,
shapeWith,
standardShape, standardShape,
UNSAVED_LINE,
} from '../support/editor' } 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, // 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. // 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 selectTab(page, dict, 'verification')
await expectAccessible(page, 'the verification tab after a deletion') 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')
})
})
}) })
+19 -14
View File
@@ -28,6 +28,7 @@ import {
serverRevision, serverRevision,
shapeWith, shapeWith,
toolButton, toolButton,
twinSelectionTag,
UNSAVED_LINE, UNSAVED_LINE,
} from '../support/editor' } from '../support/editor'
@@ -247,7 +248,7 @@ test.describe('deselect and D6b (editor, mouse and keyboard)', () => {
await toolButton(page, dict, 'zone').click() await toolButton(page, dict, 'zone').click()
await clickAt(page, { x: 300, y: 500 }) await clickAt(page, { x: 300, y: 500 })
await clickAt(page, { x: 400, 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 expect(bar).toBeVisible()
await box(page).focus() await box(page).focus()
await page.keyboard.press('Escape') await page.keyboard.press('Escape')
@@ -327,7 +328,8 @@ test.describe('deselect and D6b (editor, mouse and keyboard)', () => {
] as [string, { x: number; y: number }][]) { ] as [string, { x: number; y: number }][]) {
await clickAt(page, at) await clickAt(page, at)
await expectSelected(page, name) 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) expect(await top(), `${name} selected`).toBe(before)
await clickAt(page, IN_ROOT) await clickAt(page, IN_ROOT)
await expectDeselected(page) await expectDeselected(page)
@@ -745,23 +747,23 @@ test.describe('deselect and D6b (read-only twin at 375 px)', () => {
await takeRecord(page) await takeRecord(page)
await tap(cdp, await markerAt()) 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 shoot(info, 'r1-panel-375', properties(page))
await report('twin tap on a marker') await report('twin tap on a marker')
await takeRecord(page) await takeRecord(page)
await tap(cdp, await twinAt(IN_RECT.x, IN_RECT.y)) 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 expect(canvas).toBeFocused()
await report('twin tap on the rect') await report('twin tap on the rect')
await tap(cdp, await markerAt()) await tap(cdp, await markerAt())
await expect(selectionTag(page)).toContainText(POINT) await expect(twinSelectionTag(page)).toContainText(POINT)
await takeRecord(page) await takeRecord(page)
const from = await twinAt(IN_CIRCLE.x, IN_CIRCLE.y) const from = await twinAt(IN_CIRCLE.x, IN_CIRCLE.y)
await drag(cdp, from, { x: from.x + 30, y: from.y + 10 }) await drag(cdp, from, { x: from.x + 30, y: from.y + 10 })
await frames(page) await frames(page)
await expect(selectionTag(page)).toContainText(POINT) await expect(twinSelectionTag(page)).toContainText(POINT)
const drag1 = guards(await report('twin one-finger drag')) const drag1 = guards(await report('twin one-finger drag'))
expect(drag1.clicks, 'twin drag: no click').toBe(0) expect(drag1.clicks, 'twin drag: no click').toBe(0)
expect( 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, 'touchStart', [two, { x: two.x + 30, y: two.y }])
await touch(cdp, 'touchEnd', []) await touch(cdp, 'touchEnd', [])
await frames(page) await frames(page)
await expect(selectionTag(page)).toContainText(POINT) await expect(twinSelectionTag(page)).toContainText(POINT)
const pair = guards(await report('twin two-finger tap')) const pair = guards(await report('twin two-finger tap'))
expect(pair.nonPrimary, 'twin: a non-primary pointerdown').toBeGreaterThan( expect(pair.nonPrimary, 'twin: a non-primary pointerdown').toBeGreaterThan(
0, 0,
@@ -819,12 +821,12 @@ test.describe('deselect and D6b (read-only twin at 375 px)', () => {
[LINK, { x: 825, y: 575 }], [LINK, { x: 825, y: 575 }],
] as [string, { x: number; y: number }][]) { ] as [string, { x: number; y: number }][]) {
await tap(cdp, await twinAt(at.x, at.y)) await tap(cdp, await twinAt(at.x, at.y))
await expect(selectionTag(page)).toHaveCount(1) await expect(twinSelectionTag(page)).toHaveCount(1)
await expect(selectionTag(page)).toContainText(name) await expect(twinSelectionTag(page)).toContainText(name)
await expect(selectionTag(page)).toHaveCSS('position', 'absolute') await expect(twinSelectionTag(page)).toHaveCSS('position', 'absolute')
expect(await top(), `${name} selected`).toBe(before) expect(await top(), `${name} selected`).toBe(before)
await tap(cdp, await twinAt(IN_RECT.x, IN_RECT.y)) 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) 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, x: marker!.x + marker!.width / 2,
y: marker!.y + marker!.height / 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') const more = page.locator('#editor-tabs-more-button')
await more.click() await more.click()
@@ -859,10 +861,13 @@ test.describe('deselect and D6b (read-only twin at 375 px)', () => {
await page.keyboard.press('Escape') await page.keyboard.press('Escape')
await expect(more).toHaveAttribute('aria-expanded', 'false') await expect(more).toHaveAttribute('aria-expanded', 'false')
await expect(more).toBeFocused() await expect(more).toBeFocused()
await expectKept(page, POINT) await frames(page)
await expect(twinSelectionTag(page)).toContainText(POINT)
await page.keyboard.press('Escape') 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) await expect(liveRegion(page)).toHaveCount(1)
expect(saves).toEqual([]) expect(saves).toEqual([])
}) })
+1 -3
View File
@@ -388,9 +388,7 @@ test.describe('editor journey (owner trial steps)', () => {
), ),
}) })
.click() .click()
await expect(page.getByTestId('annotation-selection-tag')).toContainText( await expect(selectionTag(page)).toContainText('Point de bord')
'Point de bord',
)
await selectTab(page, dict, 'verification') await selectTab(page, dict, 'verification')
await page await page
.getByLabel(dict['editor.verification.note']) .getByLabel(dict['editor.verification.note'])
+7 -2
View File
@@ -629,7 +629,8 @@ export function savedLine(dict: Dict, revision: number): RegExp {
/** The header « Défaire » / « Refaire » button (enabled ones take a plain click). */ /** The header « Défaire » / « Refaire » button (enabled ones take a plain click). */
export const historyButton = (page: Page, dict: Dict, kind: 'undo' | 'redo') => 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`], name: dict[`editor.history.${kind}_title`],
exact: true, exact: true,
}) })
@@ -714,8 +715,12 @@ export const creationPanel = (page: Page) =>
export const annotationList = (page: Page, dict: Dict) => export const annotationList = (page: Page, dict: Dict) =>
page.getByRole('list', { name: dict['editor.annotations.list'] }) 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) => 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') page.getByTestId('annotation-selection-tag')
/** Selects an annotation from the overview card, leaving a selection first when there is one. */ /** Selects an annotation from the overview card, leaving a selection first when there is one. */
+146
View File
@@ -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<string, Box | null>
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<Snapshot> {
return page.evaluate((parts) => {
const shown = (selector: string) =>
[...document.querySelectorAll(selector)].find(
(element) => (element as HTMLElement).offsetParent !== null,
)
const boxes: Record<string, Box | null> = {}
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<void> {
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<ShiftScope['__shift']> {
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<void>,
exempt: readonly ShiftExemption[] = [],
): Promise<void> {
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)
}
@@ -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 (
<div
data-testid="edit-strip"
className="flex h-16 items-center gap-3 overflow-hidden rounded-xl border border-[var(--color-border)] bg-[var(--color-surface)] px-3"
>
<Lead lead={lead} />
<div
data-testid="edit-strip-notice"
role="status"
className="min-w-0 flex-1"
>
{notice && <Notice notice={notice} />}
</div>
<div className="flex shrink-0 items-center gap-2 p-1">{commands}</div>
</div>
)
}
function Lead({ lead }: { lead: StripLead }) {
return (
<div
data-testid="edit-strip-lead"
className="flex min-w-0 max-w-[45%] shrink items-start gap-2"
>
<span className="mt-0.5 shrink-0 text-[var(--color-ink-muted)]">
<EditorGlyph name={lead.icon} size={16} />
</span>
<div className="min-w-0">
<p className="flex min-w-0 items-center gap-2">
<span
data-testid="edit-strip-title"
// Only a selection carries a review status: the e2e suites read it as « selected ».
data-selection={lead.status ? '' : undefined}
className="truncate text-sm font-semibold text-[var(--color-ink)]"
>
{lead.title}
</span>
{lead.status && (
<span className="shrink-0">
<ReviewBadge status={lead.status} />
</span>
)}
</p>
<p
data-testid="edit-strip-detail"
className="truncate text-xs text-[var(--color-ink-muted)]"
>
{lead.detail}
</p>
</div>
</div>
)
}
function Notice({ notice }: { notice: StripNotice }) {
const error = notice.tone === 'error'
return (
<p
role={error ? 'alert' : undefined}
className={`flex min-w-0 items-start gap-1 text-xs ${
error
? 'text-[var(--color-danger-strong)]'
: 'text-[var(--color-ink-muted)]'
}`}
>
<span className="line-clamp-2 min-w-0">{notice.text}</span>
{notice.more !== undefined && notice.more > 0 && (
<span className="shrink-0 font-semibold">+{notice.more}</span>
)}
{notice.link && (
<button
type="button"
className="shrink-0 underline"
onClick={notice.link.onClick}
>
{notice.link.label}
</button>
)}
</p>
)
}
@@ -1,4 +1,5 @@
import { useEffect, useReducer, useState, type Dispatch } from 'react' import { useEffect, useReducer, useState, type Dispatch } from 'react'
import Button from '@/components/ui/Button'
import type { import type {
AnatomicalSheetDocument, AnatomicalSheetDocument,
Annotation, Annotation,
@@ -10,6 +11,11 @@ import { parseFrame, type Frame } from '@/editor/annotations/frame'
import { isEditable } from '@/editor/annotations/geometryEdit' import { isEditable } from '@/editor/annotations/geometryEdit'
import { useSelectionEscape } from '@/editor/annotations/deselect' import { useSelectionEscape } from '@/editor/annotations/deselect'
import { usePlacement } from '@/editor/annotations/usePlacement' import { usePlacement } from '@/editor/annotations/usePlacement'
import { stripLeadOf } from '@/editor/annotations/stripLead'
import {
useGestureMessage,
type GestureMessages,
} from '@/editor/annotations/useGestureMessage'
import { import {
initialUi, initialUi,
uiReducer, uiReducer,
@@ -23,19 +29,18 @@ import {
useViewModel, useViewModel,
type ViewModel, type ViewModel,
} from '@/editor/annotations/useViewModel' } from '@/editor/annotations/useViewModel'
import type { AnnotationSection } from '@/editor/navigation' import { targetOfKey, type AnnotationSection } from '@/editor/navigation'
import { usePlaceVisible } from '@/lib/placeVisibility' import { usePlaceVisible } from '@/lib/placeVisibility'
import type { EditorPlaceProps } from '@/editor/tabs' import type { EditorPlaceProps } from '@/editor/tabs'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore' import { useLocaleStore } from '@/state/localeStore'
import AnnotationCanvas from './AnnotationCanvas' import AnnotationCanvas from './AnnotationCanvas'
import { annotationName } from './AnnotationList'
import CreationPanel from './CreationPanel' import CreationPanel from './CreationPanel'
import EditStrip, { type StripNotice } from './EditStrip'
import GestureMessage from './GestureMessage'
import KeyboardAdd from './KeyboardAdd' import KeyboardAdd from './KeyboardAdd'
import OverviewPanel from './OverviewPanel' import OverviewPanel from './OverviewPanel'
import PropertiesPanel, { UnmeasuredHint } from './PropertiesPanel' import PropertiesPanel, { useGeometryIssues } from './PropertiesPanel'
import SelectionTag from './SelectionTag'
import TracingBar from './TracingBar'
import ViewSwitcher from './ViewSwitcher' import ViewSwitcher from './ViewSwitcher'
interface Props { interface Props {
@@ -127,10 +132,17 @@ function useCommitContext(): CommitContext {
return { t, locale } 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) { export default function EditableAnnotations(props: Props) {
const scene = useScene(props) const scene = useScene(props)
const context = useCommitContext() const { context, message, placement } = useWork(scene)
const placement = usePlacement({ ...scene, context })
const { ui, selected } = scene const { ui, selected } = scene
const visible = usePlaceVisible() const visible = usePlaceVisible()
const { asideRef, byDrawing } = useSelectionEscape( const { asideRef, byDrawing } = useSelectionEscape(
@@ -139,15 +151,19 @@ export default function EditableAnnotations(props: Props) {
visible && selected !== undefined && ui.tracing === null && !ui.pending, visible && selected !== undefined && ui.tracing === null && !ui.pending,
) )
return ( return (
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]"> <div className="space-y-3">
<CanvasColumn <SceneStrip scene={scene} placement={placement} />
scene={scene} <div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]">
placement={placement} <CanvasColumn
onDeselect={byDrawing} scene={scene}
/> placement={placement}
<aside ref={asideRef}> message={message}
<SidePanel scene={scene} context={context} /> onDeselect={byDrawing}
</aside> />
<aside ref={asideRef}>
<SidePanel scene={scene} context={context} />
</aside>
</div>
</div> </div>
) )
} }
@@ -157,13 +173,15 @@ type Placement = ReturnType<typeof usePlacement>
function CanvasColumn({ function CanvasColumn({
scene, scene,
placement, placement,
message,
onDeselect, onDeselect,
}: { }: {
scene: Scene scene: Scene
placement: Placement placement: Placement
message: GestureMessages
onDeselect: () => void onDeselect: () => void
}) { }) {
const { doc, ui, dispatch, model, selected } = scene const { doc, dispatch, model } = scene
const noCategory = doc.categories.length === 0 const noCategory = doc.categories.length === 0
return ( return (
<div className="min-w-0 space-y-3"> <div className="min-w-0 space-y-3">
@@ -172,52 +190,22 @@ function CanvasColumn({
current={scene.viewId} current={scene.viewId}
onSelect={(id) => dispatch({ type: 'view', viewId: id })} onSelect={(id) => dispatch({ type: 'view', viewId: id })}
/> />
<ToolNotes
tool={ui.tool}
hint={ui.hint}
model={model}
noCategory={noCategory}
viewId={scene.viewId}
navigate={scene.navigate}
/>
{selected && <TagOf annotation={selected} doc={doc} />}
<CanvasStage <CanvasStage
scene={scene} scene={scene}
placement={placement} placement={placement}
onDeselect={onDeselect} onDeselect={onDeselect}
/> />
{ui.tracing && ( <GestureMessage messages={message}>
<TracingBar <KeyboardAdd
count={ui.tracing.points.length} disabled={!model.measured || noCategory || scene.frame === null}
onClose={placement.closeTracing} linkDisabled={model.children.length === 0}
onCancel={() => dispatch({ type: 'trace_cancel' })} onAdd={(kind) => addAtCentre(kind, scene.frame, dispatch)}
/> />
)} </GestureMessage>
<KeyboardAdd
disabled={!model.measured || noCategory || scene.frame === null}
linkDisabled={model.children.length === 0}
onAdd={(kind) => addAtCentre(kind, scene.frame, dispatch)}
/>
</div> </div>
) )
} }
function TagOf({
annotation,
doc,
}: {
annotation: Annotation
doc: AnatomicalSheetDocument
}) {
const locale = useLocaleStore((s) => s.locale)
return (
<SelectionTag
kind={annotation.kind}
name={annotationName(annotation, doc.views, locale)}
/>
)
}
function CanvasStage({ function CanvasStage({
scene, scene,
placement, placement,
@@ -344,37 +332,120 @@ function overlayOf(
} }
} }
/** The tool line and the reasons a tool cannot be used now. */ /** The strip of the edit body: the lead of the scene, its notice, the tracing commands. */
function ToolNotes({ function SceneStrip({
tool, scene,
hint, placement,
model,
noCategory,
viewId,
navigate,
}: { }: {
tool: ToolId scene: Scene
hint: string | null placement: Placement
model: ViewModel
noCategory: boolean
viewId: string
navigate: EditorPlaceProps['navigate']
}) { }) {
const t = useT() 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 ( return (
<div className="space-y-1 text-sm text-[var(--color-ink-muted)]"> <EditStrip
<p>{t(`editor.annotations.tool_hint.${tool}`)}</p> lead={stripLeadOf(ui, selected, doc, { t, locale })}
{!model.measured && ( notice={notice}
<UnmeasuredHint navigate={navigate} viewId={viewId} /> commands={
)} ui.tracing && (
{noCategory && <p>{t('editor.annotations.no_category')}</p>} <TracingCommands
{linkBlocked && <p>{t('editor.annotations.no_child_view')}</p>} count={ui.tracing.points.length}
{hint && ( placement={placement}
<p role="alert" className="text-[var(--color-danger-strong)]"> onCancel={() => scene.dispatch({ type: 'trace_cancel' })}
{hint} />
</p> )
)} }
/>
)
}
/**
* 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 (
<div
tabIndex={-1}
data-testid="tracing-commands"
className="flex items-center gap-2 outline-none"
>
<Button
type="button"
size="sm"
className={COMMAND}
disabled={count < 3}
onClick={placement.closeTracing}
>
{t('editor.annotations.trace_close')}
</Button>
<Button
type="button"
size="sm"
variant="secondary"
className={COMMAND}
disabled={count === 0}
onClick={placement.popVertex}
>
{t('editor.annotations.trace_pop')}
</Button>
<Button
type="button"
size="sm"
variant="ghost"
className={COMMAND}
onClick={onCancel}
>
{t('editor.annotations.trace_cancel')}
</Button>
</div> </div>
) )
} }
@@ -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 (
<div
data-testid="gesture-line"
className="flex h-11 items-center gap-2 overflow-hidden"
>
<div className="shrink-0">{children}</div>
<div
role="status"
className="flex min-w-0 flex-1 justify-end py-1 pr-0.5"
>
<Message messages={messages} />
</div>
</div>
)
}
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 (
<p
data-testid="gesture-message"
role={error ? 'alert' : undefined}
{...hold}
className={`${PILL} ${
error
? 'bg-[var(--color-danger-strong)] text-white'
: 'bg-[var(--color-ink)] text-[var(--color-bg)]'
}`}
>
<span className="truncate" title={message.text}>
{message.text}
</span>
{message.undo && !error && (
<>
<button
type="button"
aria-label={t('editor.history.undo_title')}
className="shrink-0 font-semibold underline-offset-2 hover:underline"
onClick={() => undoLast(readOnly)}
>
{t('editor.history.undo')}
</button>
</>
)}
</p>
)
}
@@ -21,7 +21,7 @@ export default function KeyboardAdd({
}) { }) {
const t = useT() const t = useT()
return ( return (
<div className="flex flex-wrap gap-2"> <div className="flex flex-nowrap gap-2">
{KINDS.map((kind) => ( {KINDS.map((kind) => (
<Button <Button
key={kind} key={kind}
@@ -50,7 +50,7 @@ export interface PropertiesPanelProps {
} }
/** What still names this annotation as invalid: never hidden, never shown as valid. */ /** What still names this annotation as invalid: never hidden, never shown as valid. */
function useGeometryIssues(id: string): string[] { export function useGeometryIssues(id: string): string[] {
const state = useEditorStore((s) => s.previewState) const state = useEditorStore((s) => s.previewState)
const issues = state ? geometryErrorsById(state).get(id) : undefined const issues = state ? geometryErrorsById(state).get(id) : undefined
return [...new Set((issues ?? []).map((issue) => issue.message))] return [...new Set((issues ?? []).map((issue) => issue.message))]
@@ -1,34 +0,0 @@
import Button from '@/components/ui/Button'
import { usePlural } from '@/editor/plural'
import { useT } from '@/i18n/useT'
/** While a zone or link is being traced: close (3 vertices at least) or drop it. */
export default function TracingBar({
count,
onClose,
onCancel,
}: {
count: number
onClose: () => void
onCancel: () => void
}) {
const t = useT()
const plural = usePlural()
return (
<div
tabIndex={-1}
data-testid="tracing-bar"
className="flex flex-wrap items-center gap-2 outline-none"
>
<p className="text-sm text-[var(--color-ink-muted)]">
{plural('editor.annotations.tracing', count)}
</p>
<Button type="button" size="sm" disabled={count < 3} onClick={onClose}>
{t('editor.annotations.trace_close')}
</Button>
<Button type="button" size="sm" variant="ghost" onClick={onCancel}>
{t('editor.annotations.trace_cancel')}
</Button>
</div>
)
}
@@ -35,7 +35,7 @@ export interface DrawingState {
const BUSY_TARGET = { const BUSY_TARGET = {
creation: '[data-creation-heading]', creation: '[data-creation-heading]',
tracing: '[data-testid="tracing-bar"]', tracing: '[data-testid="tracing-commands"]',
} as const } as const
const focusFirst = (selector: string) => visibleElement(selector)?.focus() 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 * « 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 * 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 * the request is kept: nothing is dispatched (it would drop the work), the panel or the
* takes the focus and the live region says why. * strip's tracing commands take the focus and the live region says why.
*/ */
export function useAnnotationRequest( export function useAnnotationRequest(
focus: FocusRequest | undefined, focus: FocusRequest | undefined,
@@ -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<Annotation['kind'], GlyphName> = {
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,
}
}
@@ -33,6 +33,7 @@ export type UiAction =
| { type: 'pending_drop' } | { type: 'pending_drop' }
| { type: 'trace_start'; target: Tracing['target']; annotationId?: string } | { type: 'trace_start'; target: Tracing['target']; annotationId?: string }
| { type: 'trace_add'; point: Point } | { type: 'trace_add'; point: Point }
| { type: 'trace_pop' }
| { type: 'trace_cancel' } | { type: 'trace_cancel' }
| { type: 'hint'; hint: string | null } | { type: 'hint'; hint: string | null }
| { type: 'filter'; term: string } | { type: 'filter'; term: string }
@@ -108,6 +109,16 @@ export function uiReducer(state: UiState, action: UiAction): UiState {
}, },
} }
: state : state
case 'trace_pop':
return state.tracing
? {
...state,
tracing: {
...state.tracing,
points: state.tracing.points.slice(0, -1),
},
}
: state
case 'trace_cancel': case 'trace_cancel':
return { ...state, tracing: null, hint: null } return { ...state, tracing: null, hint: null }
case 'hint': case 'hint':
@@ -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<HTMLElement>) => {
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<GestureMessage | null>(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<typeof useGestureMessage>
@@ -9,6 +9,7 @@ import { updateGeometry, type CommitContext } from './annotationCommit'
import { pendingForClick, type NewKind } from './creation' import { pendingForClick, type NewKind } from './creation'
import { round2, type Frame, type XY } from './frame' import { round2, type Frame, type XY } from './frame'
import type { ToolId, Tracing, UiAction, UiState } from './uiState' 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. */ /** A click on the first vertex closes the tracing when within this share of F's span. */
const CLOSE_SHARE = 0.015 const CLOSE_SHARE = 0.015
@@ -25,6 +26,8 @@ export interface PlacementInput {
frame: Frame | null frame: Frame | null
doc: AnatomicalSheetDocument doc: AnatomicalSheetDocument
context: CommitContext context: CommitContext
/** The line under the drawing: a kept drop says so with « Défaire », a refused one in red. */
message: Pick<GestureMessages, 'show'>
} }
const asPoint = (at: XY): Point => [round2(at.x), round2(at.y)] 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) { function tracingActions(input: PlacementInput) {
const { ui, dispatch, frame } = input const { ui, dispatch, frame } = input
const closeTracing = () => const closeTracing = () =>
@@ -79,6 +82,10 @@ function tracingActions(input: PlacementInput) {
const onTraceKey = (event: KeyboardEvent) => { const onTraceKey = (event: KeyboardEvent) => {
if (!ui.tracing) return if (!ui.tracing) return
if (event.key === 'Enter') closeTracing() if (event.key === 'Enter') closeTracing()
if (event.key === 'Backspace') {
event.preventDefault()
dispatch({ type: 'trace_pop' })
}
if (event.key === 'Escape') { if (event.key === 'Escape') {
event.preventDefault() event.preventDefault()
dispatch({ type: 'trace_cancel' }) dispatch({ type: 'trace_cancel' })
@@ -87,14 +94,22 @@ function tracingActions(input: PlacementInput) {
return { closeTracing, trace, onTraceKey } return { closeTracing, trace, onTraceKey }
} }
/** A drop commits one update; the hint holds the core's words on a refusal. */ /** A drop commits one update; the line under the drawing says it, or the core's refusal. */
function dropAction(input: PlacementInput) { function dropAction({ doc, context, message }: PlacementInput) {
return (id: string, geometry: Geometry) => { 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 if (!annotation) return
const result = updateGeometry(annotation, geometry, input.context) const result = updateGeometry(annotation, geometry, context)
const hint = result.ok ? null : result.messages.join(' ') if (result.ok) {
input.dispatch({ type: 'hint', hint }) 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), onDrop: dropAction(input),
onTraceKey: tracing.onTraceKey, onTraceKey: tracing.onTraceKey,
closeTracing: tracing.closeTracing, closeTracing: tracing.closeTracing,
popVertex: () => dispatch({ type: 'trace_pop' }),
} }
} }
+17 -6
View File
@@ -1598,10 +1598,6 @@ export const en: Dict = {
'editor.annotations.tool.point': 'Point', 'editor.annotations.tool.point': 'Point',
'editor.annotations.tool.zone': 'Zone', 'editor.annotations.tool.zone': 'Zone',
'editor.annotations.tool.link': 'Link to a detail view', '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.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.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.', '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.list_empty': 'No annotation in this view.',
'editor.annotations.selection': 'Selection: {kind} « {name} »', 'editor.annotations.selection': 'Selection: {kind} « {name} »',
'editor.annotations.properties': 'Annotation properties', 'editor.annotations.properties': 'Annotation properties',
'editor.annotations.tracing_one': '{count} vertex placed.', 'editor.annotations.tracing_one': '{count} vertex placed',
'editor.annotations.tracing_other': '{count} vertices placed.', 'editor.annotations.tracing_other': '{count} vertices placed',
'editor.annotations.trace_close': 'Close the tracing', 'editor.annotations.trace_close': 'Close the tracing',
'editor.annotations.trace_cancel': 'Cancel 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.replace_polygon': 'Replace with a polygon',
'editor.annotations.no_geometry': 'This annotation has no geometry: trace a polygon to give it one.', '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.', 'editor.annotations.path': 'This annotation is a free path: its data cannot be edited here.',
+17 -6
View File
@@ -1628,10 +1628,6 @@ export const fr: Dict = {
'editor.annotations.tool.point': 'Point', 'editor.annotations.tool.point': 'Point',
'editor.annotations.tool.zone': 'Zone', 'editor.annotations.tool.zone': 'Zone',
'editor.annotations.tool.link': 'Accès à une vue détaillée', '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.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.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.", '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.list_empty': 'Aucune annotation dans cette vue.',
'editor.annotations.selection': 'Sélection : {kind} « {name} »', 'editor.annotations.selection': 'Sélection : {kind} « {name} »',
'editor.annotations.properties': "Propriétés de l'annotation", 'editor.annotations.properties': "Propriétés de l'annotation",
'editor.annotations.tracing_one': '{count} sommet posé.', 'editor.annotations.tracing_one': '{count} sommet posé',
'editor.annotations.tracing_other': '{count} sommets posés.', 'editor.annotations.tracing_other': '{count} sommets posés',
'editor.annotations.trace_close': 'Fermer le tracé', 'editor.annotations.trace_close': 'Fermer le tracé',
'editor.annotations.trace_cancel': 'Annuler 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.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.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.', 'editor.annotations.path': 'Cette annotation est un tracé libre (path) : ses données ne se modifient pas ici.',
+2
View File
@@ -4,6 +4,8 @@
html, body, #root { height: 100%; } html, body, #root { height: 100%; }
/* A modal dialog is open (components/ui/ModalDialog): the page behind it does not scroll. */ /* A modal dialog is open (components/ui/ModalDialog): the page behind it does not scroll. */
html:has(dialog:modal) { overflow: hidden; } 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 { body {
background: var(--color-bg); background: var(--color-bg);
color: var(--color-ink); color: var(--color-ink);
@@ -12,6 +12,9 @@ import {
import userEvent from '@testing-library/user-event' import userEvent from '@testing-library/user-event'
import type { Annotation } from '@faunosteo/core-wasm/types' import type { Annotation } from '@faunosteo/core-wasm/types'
import AnnotationsTab from '@/components/editor/tabs/AnnotationsTab' 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 { AnnounceContext } from '@/editor/focusRequest'
import { useLocaleStore } from '@/state/localeStore' import { useLocaleStore } from '@/state/localeStore'
import { import {
@@ -107,18 +110,16 @@ describe('selection and the list', () => {
expect(within(panel).getByLabelText('Centre x')).toHaveValue( expect(within(panel).getByLabelText('Centre x')).toHaveValue(
'743.0451049804688', '743.0451049804688',
) )
expect(screen.getByTestId('annotation-selection-tag')).toHaveTextContent( expect(screen.getByTestId('edit-strip-detail')).toHaveTextContent('Point')
'Sélection : 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 mount()
await selectFromList() await selectFromList()
const tag = screen.getByTestId('annotation-selection-tag') const lead = screen.getByTestId('edit-strip-lead')
expect(tag).toHaveClass('sr-only') expect(lead).toHaveTextContent('N')
expect(tag).not.toHaveAttribute('aria-live') expect(lead.closest('[aria-live]')).toBeNull()
expect(tag).not.toHaveAttribute('role') 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' })) await userEvent.setup().click(screen.getByRole('button', { name: 'Zone' }))
clickAt(20, 20) clickAt(20, 20)
expect(screen.getByText('1 sommet posé.')).toBeInTheDocument() expect(screen.getByText('1 sommet posé')).toBeInTheDocument()
fireEvent.keyDown(screen.getByTestId('annotation-canvas'), { fireEvent.keyDown(screen.getByTestId('annotation-canvas'), {
key: 'Escape', key: 'Escape',
}) })
expect(screen.queryByText('1 sommet posé.')).toBeNull() expect(screen.queryByText('1 sommet posé')).toBeNull()
expect(annotations()).toHaveLength(0) expect(annotations()).toHaveLength(0)
}) })
@@ -1214,10 +1215,10 @@ describe('a tap on the drawing (D6b)', () => {
), ),
}) })
tap(marker('anno-b')) tap(marker('anno-b'))
expect(screen.getByTestId('annotation-selection-tag')).toBeInTheDocument() expect(screen.getByTestId('edit-strip-detail')).toHaveTextContent('Point')
tap(marker('zone-a')) tap(marker('zone-a'))
expect(screen.getByTestId('annotation-selection-tag')).toHaveTextContent( expect(screen.getByTestId('edit-strip-detail')).toHaveTextContent(
'zone', 'Zone · 3 sommets',
) )
expect(announce).not.toHaveBeenCalled() expect(announce).not.toHaveBeenCalled()
}) })
@@ -1614,3 +1615,234 @@ describe('a tap on the drawing (D6b)', () => {
expect(store.getState().documentText).toBe(before) 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<string, string>)[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(<AnnotationsTab {...props} />)
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(
<EditStrip
lead={{ title: 'T', detail: 'Zone', icon: 'zone' }}
notice={{ tone: 'error', text: 'Premier problème', more: 2 }}
commands={null}
/>,
)
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()
}
})
})
+6 -4
View File
@@ -240,17 +240,19 @@ describe('Escape leaves alone', () => {
expect(store.getState().documentText).toBe(before) 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()) const user = await mount(ZONE())
await select(user, 'zone-a') await select(user, 'zone-a')
await user.click(inPanel('Remplacer par un polygone')) await user.click(inPanel('Remplacer par un polygone'))
const bar = await screen.findByTestId('tracing-bar') const bar = await screen.findByTestId('tracing-commands')
bar.focus() bar.focus()
escape(bar) escape(bar)
expect(screen.queryByTestId('tracing-bar')).not.toBeNull() expect(screen.queryByTestId('tracing-commands')).not.toBeNull()
canvasBox().focus() canvasBox().focus()
escape(canvasBox()) escape(canvasBox())
await waitFor(() => expect(screen.queryByTestId('tracing-bar')).toBeNull()) await waitFor(() =>
expect(screen.queryByTestId('tracing-commands')).toBeNull(),
)
expect(panel()).toBeDefined() expect(panel()).toBeDefined()
}) })
@@ -504,7 +504,9 @@ describe('« Aller à » while a creation or a tracing is in progress', () => {
pressAt(screen.getByTestId('annotation-canvas'), 20, 20) pressAt(screen.getByTestId('annotation-canvas'), 20, 20)
}) })
expect(tab('Annotations')).toHaveAttribute('aria-selected', 'true') 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() expect(bar).toBeVisible()
await waitFor(() => expect(document.activeElement).toBe(bar)) await waitFor(() => expect(document.activeElement).toBe(bar))
expect(liveText()).toContain('tracé est en cours') 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', 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)) await waitFor(() => expect(document.activeElement).toBe(bar))
expect(liveText()).toContain('tracé est en cours') expect(liveText()).toContain('tracé est en cours')
}) })
+6 -4
View File
@@ -228,9 +228,11 @@ describe('the shown view disappears (undo)', () => {
) )
await user.click(screen.getByRole('button', { name: 'Zone' })) await user.click(screen.getByRole('button', { name: 'Zone' }))
pressAt(screen.getByTestId('annotation-canvas'), 20, 30) pressAt(screen.getByTestId('annotation-canvas'), 20, 30)
expect(screen.getByTestId('tracing-bar')).toBeInTheDocument() expect(screen.getByTestId('tracing-commands')).toBeInTheDocument()
act(() => void store.getState().undoStep()) 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 () => { 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() 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) => { const { consumed, announce } = await withProgress(async (user) => {
await waitFor(() => await waitFor(() =>
expect(screen.getByRole('button', { name: 'Zone' })).toBeEnabled(), 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) pressAt(screen.getByTestId('annotation-canvas'), 20, 20)
}) })
await waitFor(() => expect(consumed).toHaveBeenCalledWith(7, 'kept')) 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(announce).toHaveBeenCalledWith(
expect.stringContaining('tracé est en cours'), expect.stringContaining('tracé est en cours'),
) )