Files
faunosteo/apps/app/tests/unit/editor-annotations-tab.test.tsx
T
bchanot 91e94952f0 feat(editor): point handle, size slider with core minimum, move mode
HandleLayer: its own svg over the overlay, not aria-hidden; the selected
point (or link circle) gets a focusable « Point {nom} » handle whose hit
circle (data-handle) the press machine reads, sized in CSS px under zoom
(R-9, read once from any-pointer: coarse). The Task 2 stand-in (the
selected marker as its own handle) is removed.

Keys on the handle: arrows step 0.5 % of the frame (Shift x10) as a
stamped series, Enter or blur commit once, Escape drops it (R-11, R-13).
SizeSlider in the strip for a selected point and for the Point tool (A5):
the view's sizes as ticks, the core minimum as a red mark, snap 8 px,
arrows 1 %, Page Up/Down next size, one commit on release, Enter or blur;
a refusal restores the size and draws the refused place in red dashes.
« Déplacer le point » opens the move mode (board 06 B): drag anywhere or
four arrows move a preview only, clicks select nothing, « Valider la
position » commits once, « Annuler » and Escape restore; the focus comes
back to the button. Escape follows board 32 (escapeAction). The overlay
reads the preview from the work store and draws the old place in grey
dashes. Ctrl+Z now also works from a slider (not a text field).

Rewritten assertions:
- editor-annotations-tab « a finger drags the selected point »:
  drag(marker('anno-a')) -> drag(pointHandle()), same expected geometry.
- editor-geometry.spec « a point inherited out of its frame is repaired
  through the geometry group » (cx/cy typed 200) -> « ... repaired with
  the move mode »: a partial move refused and restored (cx 110, issue
  kept), then a move inside kept (issue gone, fewer errors).
2026-11-17 18:50:29 +01:00

1929 lines
67 KiB
TypeScript

/** Lot H: the Annotations tab (creation, corrected position, gestures, read-only, repair). */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
act,
cleanup,
fireEvent,
render,
renderHook,
screen,
waitFor,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { Annotation } from '@faunosteo/core-wasm/types'
import AnnotationsTab from '@/components/editor/tabs/AnnotationsTab'
import EditStrip from '@/components/editor/annotations/EditStrip'
import { selectionLead } from '@/editor/annotations/stripLead'
import { initialUi } from '@/editor/annotations/uiState'
import { usePlacement } from '@/editor/annotations/usePlacement'
import { fr } from '@/i18n/fr'
import { AnnounceContext } from '@/editor/focusRequest'
import { useLocaleStore } from '@/state/localeStore'
import {
ASSET,
drawnText,
insert,
point,
svgBytes,
} from '../helpers/editorFixtures'
import {
USER,
VERSION,
commitMove,
openReady,
resetStore,
pressAt,
sb,
store,
versionAnswer,
} from '../helpers/editorHarness'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
vi.mock('@faunosteo/supabase', async (orig) => ({
...(await orig<typeof import('@faunosteo/supabase')>()),
getSheetVersion: vi.fn(),
downloadSheetDrawing: vi.fn(),
saveSheetDraft: vi.fn(),
getOfficialSheetAdmin: vi.fn(),
submitSheetReview: vi.fn(),
}))
const props = {
readOnly: false,
navigate: vi.fn(),
reloadSheet: vi.fn(),
section: 'drawing' as const,
visited: ['drawing'] as const,
onOpenSection: vi.fn(),
onBack: vi.fn(),
}
const named = (id: string, cx: number, cy: number, r: number) =>
point(id, cx, cy, r)
const annotations = () => store.getState().previewState!.document.annotations
const geometryOf = (id: string) =>
annotations().find((a: Annotation) => a.id === id)?.geometry
/** Screen = drawing: the overlay's inverse CTM is the identity in the page under test. */
function stubCtm(): void {
const identity = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 }
Object.defineProperty(window.SVGElement.prototype, 'getScreenCTM', {
configurable: true,
value: () => ({ ...identity, inverse: () => identity }),
})
}
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
stubCtm()
})
afterEach(() => {
cleanup()
resetStore()
})
const text = () => insert(drawnText(), named('anno-a', 50, 50, 5))
async function mount(options: { text?: string; readOnly?: boolean } = {}) {
await openReady({ text: options.text ?? text() })
render(<AnnotationsTab {...props} readOnly={options.readOnly ?? false} />)
const drawing = options.readOnly
? 'catalogue-canvas-drawing'
: 'annotation-canvas-drawing'
await waitFor(() =>
expect(screen.getByTestId(drawing).querySelector('svg')).not.toBeNull(),
)
}
async function selectFromList(name: RegExp | string = /N/) {
const list = await screen.findByRole('list', {
name: 'Annotations de la vue',
})
await userEvent.setup().click(within(list).getAllByRole('button')[0])
void name
return screen.findByTestId('annotation-properties')
}
describe('selection and the list', () => {
it('lists the view annotations, selects one and shows its exact stored numbers', async () => {
await mount({
text: insert(drawnText(), named('anno-a', 743.0451049804688, 50, 5)),
})
const panel = await selectFromList()
expect(within(panel).getByLabelText('Centre x')).toHaveValue(
'743.0451049804688',
)
expect(screen.getByTestId('edit-strip-detail')).toHaveTextContent('Point')
})
it('names the selection in the strip, outside any live region', async () => {
await mount()
await selectFromList()
const lead = screen.getByTestId('edit-strip-lead')
expect(lead).toHaveTextContent('N')
expect(lead.closest('[aria-live]')).toBeNull()
expect(lead.closest('[role]')).toBeNull()
})
})
describe('a numeric edit', () => {
it('commits only when the typed number differs from the stored one', async () => {
await mount()
const panel = await selectFromList()
const user = userEvent.setup()
const version = store.getState().handleVersion
const cx = within(panel).getByLabelText('Centre x')
await user.click(cx)
await user.keyboard('{Enter}')
expect(store.getState().handleVersion).toBe(version)
await user.clear(cx)
await user.type(cx, '60{Enter}')
expect(geometryOf('anno-a')).toEqual({
type: 'circle',
cx: 60,
cy: 50,
r: 5,
})
expect(store.getState().handleVersion).toBe(version + 1)
})
it('keeps a refused value as « non appliqué » with the document unchanged, then applies a coherent set', async () => {
await mount({ text: insert(drawnText(), named('anno-a', 150, 150, 5)) })
const panel = await selectFromList()
const user = userEvent.setup()
const before = store.getState().documentText
expect(
within(panel).getByTestId('annotation-geometry-issues'),
).toBeInTheDocument()
const cx = within(panel).getByLabelText('Centre x')
await user.clear(cx)
await user.type(cx, '50{Enter}')
expect(store.getState().documentText).toBe(before)
expect(within(panel).getByText('non appliqué')).toBeInTheDocument()
expect(
within(panel).getByText(/Valeurs non appliquées/),
).toBeInTheDocument()
expect(
within(panel).getByRole('button', {
name: 'Revenir aux valeurs enregistrées',
}),
).toBeInTheDocument()
expect(within(panel).getByLabelText('Centre x')).toHaveValue('50')
const cy = within(panel).getByLabelText('Centre y')
await user.clear(cy)
await user.type(cy, '50{Enter}')
expect(geometryOf('anno-a')).toEqual({
type: 'circle',
cx: 50,
cy: 50,
r: 5,
})
expect(screen.queryByTestId('annotation-geometry-issues')).toBeNull()
})
it('reverts the group to the saved values', async () => {
await mount({ text: insert(drawnText(), named('anno-a', 150, 150, 5)) })
const panel = await selectFromList()
const user = userEvent.setup()
const cx = within(panel).getByLabelText('Centre x')
await user.clear(cx)
await user.type(cx, '50{Enter}')
await user.click(
within(panel).getByRole('button', {
name: 'Revenir aux valeurs enregistrées',
}),
)
expect(within(panel).getByLabelText('Centre x')).toHaveValue('150')
})
})
async function fillCreation(user: ReturnType<typeof userEvent.setup>) {
const panel = await screen.findByTestId('annotation-creation')
await user.type(within(panel).getByLabelText('Nom (FR)'), 'Nuque')
await user.type(within(panel).getByLabelText('Nom (EN)'), 'Poll')
await user.selectOptions(
within(panel).getByLabelText('Latéralité'),
'unpaired',
)
return panel
}
describe('the keyboard creation path', () => {
it('holds a point at the frame centre, asks the required fields, then inserts once', async () => {
await mount({ text: drawnText() })
const user = userEvent.setup()
await waitFor(() =>
expect(
screen.getByRole('button', { name: 'Ajouter un point' }),
).toBeEnabled(),
)
await user.click(screen.getByRole('button', { name: 'Ajouter un point' }))
const panel = await fillCreation(user)
expect(within(panel).getByLabelText('Centre x')).toHaveValue('50')
expect(within(panel).getByLabelText('Latéralité')).toHaveValue('unpaired')
expect(annotations()).toHaveLength(0)
await user.click(within(panel).getByRole('button', { name: 'Créer' }))
expect(annotations()).toHaveLength(1)
expect(annotations()[0]).toMatchObject({
kind: 'point',
name: { fr: 'Nuque', en: 'Poll' },
laterality: 'unpaired',
geometry: { type: 'circle', cx: 50, cy: 50 },
})
expect(
await screen.findByTestId('annotation-properties'),
).toBeInTheDocument()
})
it('refuses a creation without laterality and creates nothing', async () => {
await mount({ text: drawnText() })
const user = userEvent.setup()
await waitFor(() =>
expect(
screen.getByRole('button', { name: 'Ajouter une zone' }),
).toBeEnabled(),
)
await user.click(screen.getByRole('button', { name: 'Ajouter une zone' }))
const panel = await screen.findByTestId('annotation-creation')
await user.type(within(panel).getByLabelText('Nom (FR)'), 'A')
await user.type(within(panel).getByLabelText('Nom (EN)'), 'B')
await user.click(within(panel).getByRole('button', { name: 'Créer' }))
expect(within(panel).getByRole('alert')).toHaveTextContent(
'Choisissez la catégorie et la latéralité',
)
expect(annotations()).toHaveLength(0)
})
it('applies the geometry group to a pending zone, the core deciding at « Créer »', async () => {
await mount({ text: drawnText() })
const user = userEvent.setup()
await waitFor(() =>
expect(
screen.getByRole('button', { name: 'Ajouter une zone' }),
).toBeEnabled(),
)
await user.click(screen.getByRole('button', { name: 'Ajouter une zone' }))
const panel = await fillCreation(user)
const x = within(panel).getByLabelText('x du sommet 1')
await user.clear(x)
await user.type(x, '500{Enter}')
expect(within(panel).getByLabelText('x du sommet 1')).toHaveValue('500')
await user.click(within(panel).getByRole('button', { name: 'Créer' }))
expect(annotations()).toHaveLength(0)
expect(within(panel).getByRole('alert')).toBeInTheDocument()
expect(within(panel).getByLabelText('x du sommet 1')).toHaveValue('500')
})
})
describe('the point tool and the corrected position (C26)', () => {
async function clickCorner() {
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'Point' }))
pressAt(screen.getByTestId('annotation-canvas'), 0, 0)
return user
}
it('proposes C with the click marked apart, inserts it only on confirmation', async () => {
await mount({ text: drawnText() })
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Point' })).toBeEnabled(),
)
const user = await clickCorner()
const notice = await screen.findByTestId('correction-notice')
expect(notice).toHaveTextContent(
'Position corrigée proposée : x = 15, y = 15.',
)
expect(screen.getByTestId('overlay-click-cross')).toBeInTheDocument()
const panel = await fillCreation(user)
expect(annotations()).toHaveLength(0)
await user.click(
within(notice).getByRole('button', { name: 'Utiliser cette position' }),
)
expect(geometryOf(annotations()[0].id)).toEqual({
type: 'circle',
cx: 15,
cy: 15,
r: 15,
})
expect(panel).not.toBeInTheDocument()
expect(screen.queryByTestId('overlay-click-cross')).toBeNull()
const props = await screen.findByTestId('annotation-properties')
expect(within(props).getByLabelText('Centre x')).toHaveValue('15')
})
it('keeps the pending point at the click when the correction is cancelled', async () => {
await mount({ text: drawnText() })
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Point' })).toBeEnabled(),
)
const user = await clickCorner()
const notice = await screen.findByTestId('correction-notice')
await user.click(within(notice).getByRole('button', { name: 'Annuler' }))
expect(screen.queryByTestId('correction-notice')).toBeNull()
expect(screen.queryByTestId('overlay-click-cross')).toBeNull()
const panel = screen.getByTestId('annotation-creation')
expect(within(panel).getByLabelText('Centre x')).toHaveValue('0')
expect(annotations()).toHaveLength(0)
})
it('offers the correction when the core refuses a pending point', async () => {
await mount({ text: drawnText() })
const user = userEvent.setup()
await waitFor(() =>
expect(
screen.getByRole('button', { name: 'Ajouter un point' }),
).toBeEnabled(),
)
await user.click(screen.getByRole('button', { name: 'Ajouter un point' }))
const panel = await fillCreation(user)
const cx = within(panel).getByLabelText('Centre x')
await user.clear(cx)
await user.type(cx, '98{Enter}')
await user.click(within(panel).getByRole('button', { name: 'Créer' }))
expect(await screen.findByTestId('correction-notice')).toHaveTextContent(
'x = 85',
)
expect(annotations()).toHaveLength(0)
})
it('says to click inside the drawing, and proposes nothing, outside the frame', async () => {
await mount({ text: drawnText() })
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Point' })).toBeEnabled(),
)
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'Point' }))
pressAt(screen.getByTestId('annotation-canvas'), -5, 50)
expect(
await screen.findByText("Cliquez à l'intérieur du dessin."),
).toBeInTheDocument()
expect(screen.queryByTestId('annotation-creation')).toBeNull()
})
})
/** The selected point's handle: its hit circle in the handle layer (R-9). */
function pointHandle(): Element {
const handle = screen
.getByTestId('point-handle')
.querySelector('[data-handle]')
if (!handle) throw new Error('no point handle')
return handle
}
function marker(id: string): Element {
const found = screen
.getByTestId('annotation-canvas-drawing')
.querySelector(`[data-anno-id="${id}"]`)
if (!found) throw new Error(`no marker ${id}`)
return found
}
describe('select and move gestures (C34)', () => {
const down = (el: Element, x: number, y: number) =>
fireEvent.pointerDown(el, {
clientX: x,
clientY: y,
button: 0,
pointerId: 1,
})
const moveTo = (el: Element, x: number, y: number) =>
fireEvent.pointerMove(el, {
clientX: x,
clientY: y,
pointerId: 1,
buttons: 1,
})
const up = (el: Element, x: number, y: number) =>
fireEvent.pointerUp(el, { clientX: x, clientY: y, pointerId: 1 })
async function selected() {
await mount()
await selectFromList()
return marker('anno-a')
}
it('treats a press and release under 4 px as a click: nothing is committed', async () => {
const hit = await selected()
const version = store.getState().handleVersion
down(hit, 50, 50)
moveTo(hit, 52, 51)
up(hit, 52, 51)
expect(store.getState().handleVersion).toBe(version)
expect(geometryOf('anno-a')).toEqual({
type: 'circle',
cx: 50,
cy: 50,
r: 5,
})
})
it('moves the selected circle as a block after 4 px, in one update rounded to 2 decimals', async () => {
const hit = await selected()
const version = store.getState().handleVersion
down(hit, 50, 50)
moveTo(hit, 58, 50)
expect(screen.getByTestId('annotation-overlay')).toBeInTheDocument()
up(hit, 60.004, 40)
expect(geometryOf('anno-a')).toEqual({
type: 'circle',
cx: 60,
cy: 40,
r: 5,
})
expect(store.getState().handleVersion).toBe(version + 1)
})
it('rolls a drop half out of the frame back, with the core message', async () => {
const hit = await selected()
const before = store.getState().documentText
down(hit, 50, 50)
moveTo(hit, 90, 50)
up(hit, 98, 50)
expect(store.getState().documentText).toBe(before)
expect(await screen.findByRole('alert')).toBeInTheDocument()
})
it('drops the drag on pointer cancel with no command', async () => {
const hit = await selected()
const version = store.getState().handleVersion
down(hit, 50, 50)
moveTo(hit, 70, 50)
fireEvent.pointerCancel(hit, { pointerId: 1 })
up(hit, 70, 50)
expect(store.getState().handleVersion).toBe(version)
})
it('does not move an annotation that is not selected', async () => {
await mount()
const hit = marker('anno-a')
const version = store.getState().handleVersion
down(hit, 50, 50)
moveTo(hit, 70, 50)
up(hit, 70, 50)
expect(store.getState().handleVersion).toBe(version)
})
})
describe('an unmeasured view (C32)', () => {
async function mountMissing() {
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} />)
void ASSET
}
it('disables every tool and add button, shows the hint, keeps the annotation selectable read-only', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
await mountMissing()
for (const name of [
'Point',
'Zone',
'Accès à une vue détaillée',
'Ajouter un point',
'Ajouter une zone',
'Ajouter un accès',
]) {
expect(screen.getByRole('button', { name })).toBeDisabled()
}
expect(
screen.getAllByText(/Ce dessin n'est pas mesurable/).length,
).toBeGreaterThan(0)
const panel = await selectFromList()
expect(
within(panel).queryByRole('textbox', { name: 'Centre x' }),
).toBeNull()
expect(
within(panel).getByText('Centre x', { exact: false }),
).toBeInTheDocument()
expect(
within(panel).getByText(/Ce dessin n'est pas mesurable/),
).toBeInTheDocument()
})
})
describe('tools and categories', () => {
it('disables the drawing tools until an annotation category exists', async () => {
const bare = JSON.parse(drawnText())
bare.categories = []
await mount({ text: JSON.stringify(bare) })
expect(screen.getByRole('button', { name: 'Point' })).toBeDisabled()
expect(
screen.getByText(
"Créez d'abord une catégorie d'annotation (Annotations, section Catégories).",
),
).toBeInTheDocument()
})
it('enables the link tool only when the view has a direct detail child', async () => {
await mount({ text: drawnText() })
expect(
screen.getByRole('button', { name: 'Accès à une vue détaillée' }),
).toBeDisabled()
expect(
screen.getByRole('button', { name: 'Ajouter un accès' }),
).toBeDisabled()
})
it('keeps no undo or redo in the tool column (they sit in the header)', async () => {
await mount()
const tools = screen.getByRole('toolbar', { name: 'Outils' })
expect(
within(tools).queryByRole('button', { name: /Défaire|Refaire/ }),
).toBeNull()
})
})
describe('read-only', () => {
it('browses the annotations with no tool, no add button and the fields as text', async () => {
await mount({ readOnly: true })
expect(screen.queryByRole('button', { name: 'Point' })).toBeNull()
expect(
screen.queryByRole('button', { name: 'Ajouter un point' }),
).toBeNull()
const panel = await selectFromList()
expect(within(panel).queryByRole('textbox')).toBeNull()
expect(
within(panel).queryByRole('button', { name: 'Supprimer' }),
).toBeNull()
})
})
const triangle = [
[20, 20],
[80, 20],
[50, 80],
]
const zoneAnnotation = (geometry: object): Annotation =>
({
...(point('zone-a', 0, 0, 1).value as Annotation),
kind: 'zone',
geometry,
}) as Annotation
describe('tracing a zone or a link', () => {
const clickAt = (x: number, y: number) =>
pressAt(screen.getByTestId('annotation-canvas'), x, y)
it('closes on Enter, holds the polygon pending, inserts it on « Créer »', async () => {
await mount({ text: drawnText() })
const user = userEvent.setup()
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Zone' })).toBeEnabled(),
)
await user.click(screen.getByRole('button', { name: 'Zone' }))
triangle.forEach(([x, y]) => clickAt(x, y))
expect(
screen.getByRole('button', { name: 'Fermer le tracé' }),
).toBeEnabled()
fireEvent.keyDown(screen.getByTestId('annotation-canvas'), { key: 'Enter' })
const panel = await fillCreation(user)
expect(within(panel).getByLabelText('x du sommet 3')).toHaveValue('50')
await user.click(within(panel).getByRole('button', { name: 'Créer' }))
expect(annotations()[0]).toMatchObject({
kind: 'zone',
geometry: { type: 'polygon', points: triangle },
})
})
it('drops the tracing on Escape with nothing created', async () => {
await mount({ text: drawnText() })
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Zone' })).toBeEnabled(),
)
await userEvent.setup().click(screen.getByRole('button', { name: 'Zone' }))
clickAt(20, 20)
expect(screen.getByText('1 sommet posé')).toBeInTheDocument()
fireEvent.keyDown(screen.getByTestId('annotation-canvas'), {
key: 'Escape',
})
expect(screen.queryByText('1 sommet posé')).toBeNull()
expect(annotations()).toHaveLength(0)
})
it('closes on a click at the first vertex once three are placed', async () => {
await mount({ text: drawnText() })
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Zone' })).toBeEnabled(),
)
await userEvent.setup().click(screen.getByRole('button', { name: 'Zone' }))
triangle.forEach(([x, y]) => clickAt(x, y))
clickAt(20.5, 20)
expect(await screen.findByTestId('annotation-creation')).toBeInTheDocument()
})
it('links only to a detail view directly under this one', async () => {
const withView = insert(drawnText(), {
kind: 'view',
value: {
kind: 'detail',
id: 'view-det',
name: { fr: 'Tête', en: 'Head' },
svg_asset_id: null,
view_box: { min_x: 10, min_y: 10, width: 80, height: 80 },
parent_view_id: 'view-main',
},
})
await mount({ text: withView })
const user = userEvent.setup()
await waitFor(() =>
expect(
screen.getByRole('button', { name: 'Accès à une vue détaillée' }),
).toBeEnabled(),
)
await user.click(screen.getByRole('button', { name: 'Ajouter un accès' }))
const panel = await fillCreation(user)
const opens = within(panel).getByLabelText('Vue ouverte')
expect(
within(opens)
.getAllByRole('option')
.map((o) => o.textContent),
).toEqual(['Choisir…', 'Tête'])
await user.selectOptions(opens, 'view-det')
await user.click(within(panel).getByRole('button', { name: 'Créer' }))
expect(annotations()[0]).toMatchObject({
kind: 'detail_trigger',
opens_view_id: 'view-det',
})
})
})
describe('polygons and paths', () => {
const zoneText = (geometry: object) =>
insert(drawnText(), { kind: 'annotation', value: zoneAnnotation(geometry) })
it('adds and removes a vertex as part of the whole group', async () => {
await mount({ text: zoneText({ type: 'polygon', points: triangle }) })
const panel = await selectFromList()
const user = userEvent.setup()
await user.click(within(panel).getByLabelText('x du sommet 1'))
await user.click(
within(panel).getByRole('button', { name: 'Ajouter un sommet' }),
)
expect(geometryOf('zone-a')).toMatchObject({
points: [
[20, 20],
[50, 20],
[80, 20],
[50, 80],
],
})
await user.click(within(panel).getByRole('button', { name: 'Retirer' }))
expect(geometryOf('zone-a')).toMatchObject({
points: triangle.slice(0, 3).map((p, i) => (i === 0 ? [50, 20] : p)),
})
})
it('never offers to remove a vertex below three', async () => {
await mount({ text: zoneText({ type: 'polygon', points: triangle }) })
const panel = await selectFromList()
expect(
within(panel).getByRole('button', { name: 'Retirer' }),
).toBeDisabled()
})
it('moves a selected polygon as a block', async () => {
await mount({ text: zoneText({ type: 'polygon', points: triangle }) })
await selectFromList()
const hit = screen
.getByTestId('annotation-canvas-drawing')
.querySelector('[data-anno-id="zone-a"]')!
fireEvent.pointerDown(hit, {
clientX: 50,
clientY: 40,
button: 0,
pointerId: 1,
})
fireEvent.pointerMove(hit, {
clientX: 55,
clientY: 40,
pointerId: 1,
buttons: 1,
})
fireEvent.pointerUp(hit, { clientX: 60, clientY: 45, pointerId: 1 })
expect(geometryOf('zone-a')).toMatchObject({
points: [
[30, 25],
[90, 25],
[60, 85],
],
})
})
it('replaces a path by a traced polygon and never shows its data', async () => {
await mount({
text: zoneText({ type: 'path', d: 'M 20 20 L 80 20 L 50 80 Z' }),
})
const panel = await selectFromList()
expect(within(panel).queryByText(/M 20 20/)).toBeNull()
await userEvent.setup().click(
within(panel).getByRole('button', {
name: 'Remplacer par un polygone',
}),
)
const canvas = screen.getByTestId('annotation-canvas')
triangle.forEach(([x, y]) => pressAt(canvas, x, y))
fireEvent.keyDown(canvas, { key: 'Enter' })
await waitFor(() =>
expect(geometryOf('zone-a')).toEqual({
type: 'polygon',
points: triangle,
}),
)
})
})
describe('keys while tracing (H3)', () => {
const clickAt = (x: number, y: number) =>
pressAt(screen.getByTestId('annotation-canvas'), x, y)
async function traced() {
await mount({ text: drawnText() })
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Zone' })).toBeEnabled(),
)
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'Zone' }))
triangle.forEach(([x, y]) => clickAt(x, y))
return user
}
it('Enter on « Annuler le tracé » cancels the tracing instead of closing it', async () => {
const user = await traced()
screen.getByRole('button', { name: 'Annuler le tracé' }).focus()
await user.keyboard('{Enter}')
expect(
screen.queryByRole('button', { name: 'Annuler le tracé' }),
).toBeNull()
expect(screen.queryByTestId('annotation-creation')).toBeNull()
})
it('Enter on a view chip or a list row never closes the tracing', async () => {
await traced()
const views = screen.getByRole('group', { name: 'Vues' })
fireEvent.keyDown(within(views).getAllByRole('button')[0], {
key: 'Enter',
})
expect(screen.queryByTestId('annotation-creation')).toBeNull()
expect(
screen.getByRole('button', { name: 'Annuler le tracé' }),
).toBeInTheDocument()
})
})
describe('a second click with the point tool (H6)', () => {
it('moves the pending point and keeps what was typed', async () => {
await mount({ text: drawnText() })
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Point' })).toBeEnabled(),
)
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'Point' }))
pressAt(screen.getByTestId('annotation-canvas'), 50, 50)
const panel = await fillCreation(user)
pressAt(screen.getByTestId('annotation-canvas'), 60, 40)
await waitFor(() =>
expect(within(panel).getByLabelText('Centre x')).toHaveValue('60'),
)
expect(within(panel).getByLabelText('Nom (FR)')).toHaveValue('Nuque')
expect(within(panel).getByLabelText('Latéralité')).toHaveValue('unpaired')
expect(screen.getByTestId('annotation-creation')).toBe(panel)
})
})
describe('a typed radius (H5)', () => {
it('shows the core issue, not a corrected position', async () => {
const drawing = svgBytes('0 0 5000 5000')
sb.getSheetVersion.mockResolvedValue({
...versionAnswer(drawnText(), 3),
drawings: [{ asset_id: ASSET, sha256: drawing.sha256 }],
} as never)
sb.downloadSheetDrawing.mockResolvedValue(drawing.bytes)
store.getState().open(VERSION, USER, { canEdit: true })
await waitFor(() => expect(store.getState().status).toBe('ready'))
render(<AnnotationsTab {...props} />)
await waitFor(() =>
expect(
screen.getByRole('button', { name: 'Ajouter un point' }),
).toBeEnabled(),
)
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'Ajouter un point' }))
const panel = await fillCreation(user)
const r = within(panel).getByLabelText('Rayon')
await user.clear(r)
await user.type(r, '1{Enter}')
await user.click(within(panel).getByRole('button', { name: 'Créer' }))
expect(screen.queryByTestId('correction-notice')).toBeNull()
expect(within(panel).getByRole('alert')).toBeInTheDocument()
expect(annotations()).toHaveLength(0)
})
})
describe('the frame follows the view (H7)', () => {
it('holds the keyboard point at the centre of the view shown, after a switch', async () => {
const withView = insert(drawnText(), {
kind: 'view',
value: {
kind: 'detail',
id: 'view-det',
name: { fr: 'Tête', en: 'Head' },
svg_asset_id: null,
view_box: { min_x: 10, min_y: 20, width: 40, height: 60 },
parent_view_id: 'view-main',
},
})
await mount({ text: withView })
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'Tête' }))
await waitFor(() =>
expect(
screen.getByRole('button', { name: 'Ajouter un point' }),
).toBeEnabled(),
)
await user.click(screen.getByRole('button', { name: 'Ajouter un point' }))
const panel = await screen.findByTestId('annotation-creation')
expect(within(panel).getByLabelText('Centre x')).toHaveValue('30')
expect(within(panel).getByLabelText('Centre y')).toHaveValue('50')
})
})
describe('refusals through the tab (H8)', () => {
const zoneText = (geometry: object) =>
insert(drawnText(), { kind: 'annotation', value: zoneAnnotation(geometry) })
it('a refused « Remplacer par un polygone » drops the tracing, shows the core message', async () => {
const path = { type: 'path', d: 'M 20 20 L 80 20 L 50 80 Z' }
await mount({ text: zoneText(path) })
const panel = await selectFromList()
await userEvent.setup().click(
within(panel).getByRole('button', {
name: 'Remplacer par un polygone',
}),
)
const canvas = screen.getByTestId('annotation-canvas')
;[
[20, 20],
[500, 20],
[50, 80],
].forEach(([x, y]) => pressAt(canvas, x, y))
fireEvent.keyDown(canvas, { key: 'Enter' })
expect(await screen.findByRole('alert')).toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'Annuler le tracé' }),
).toBeNull()
expect(geometryOf('zone-a')).toEqual(path)
})
it('a refused vertex add and a refused remove stay « non appliqué », document unchanged', async () => {
await mount({
text: zoneText({ type: 'polygon', points: [...triangle, [20, 60]] }),
})
const panel = await selectFromList()
const user = userEvent.setup()
const before = store.getState().documentText
const x = within(panel).getByLabelText('x du sommet 1')
await user.clear(x)
await user.type(x, '500{Enter}')
await user.click(
within(panel).getByRole('button', { name: 'Ajouter un sommet' }),
)
expect(store.getState().documentText).toBe(before)
expect(within(panel).getAllByLabelText(/^x du sommet/)).toHaveLength(5)
expect(
within(panel).getByText(/Valeurs non appliquées/),
).toBeInTheDocument()
await user.click(within(panel).getByRole('button', { name: 'Retirer' }))
expect(store.getState().documentText).toBe(before)
expect(
within(panel).getByText(/Valeurs non appliquées/),
).toBeInTheDocument()
})
})
describe('the drag and the canvas follow the handle (H8)', () => {
const down = (el: Element, x: number, y: number) =>
fireEvent.pointerDown(el, {
clientX: x,
clientY: y,
button: 0,
pointerId: 1,
})
it('lostpointercapture drops the drag with no command', async () => {
await mount()
await selectFromList()
const hit = marker('anno-a')
const version = store.getState().handleVersion
down(hit, 50, 50)
fireEvent.pointerMove(hit, {
clientX: 70,
clientY: 50,
pointerId: 1,
buttons: 1,
})
fireEvent.lostPointerCapture(hit, { pointerId: 1 })
fireEvent.pointerUp(hit, { clientX: 70, clientY: 50, pointerId: 1 })
expect(store.getState().handleVersion).toBe(version)
})
it('a switch to read-only mid-drag drops it', async () => {
await openReady({ text: text() })
const view = render(<AnnotationsTab {...props} />)
await waitFor(() =>
expect(
screen.getByTestId('annotation-canvas-drawing').querySelector('svg'),
).not.toBeNull(),
)
await selectFromList()
const hit = marker('anno-a')
const version = store.getState().handleVersion
down(hit, 50, 50)
fireEvent.pointerMove(hit, {
clientX: 70,
clientY: 50,
pointerId: 1,
buttons: 1,
})
view.rerender(<AnnotationsTab {...props} readOnly />)
fireEvent.pointerUp(hit, { clientX: 70, clientY: 50, pointerId: 1 })
expect(store.getState().handleVersion).toBe(version)
expect(geometryOf('anno-a')).toEqual({
type: 'circle',
cx: 50,
cy: 50,
r: 5,
})
})
it('rebuilds the drawing when the handle changes under it', async () => {
await mount()
const first = marker('anno-a')
act(() => void commitMove(60))
await waitFor(() => expect(marker('anno-a')).not.toBe(first))
})
})
describe('« Désélectionner » (R1, A6)', () => {
const announce = vi.fn()
const rowOf = (id: string, prefix = '') =>
document.querySelector<HTMLElement>(
`[data-focus-key='{"kind":"annotation","id":"${id}"}']`,
) ?? document.getElementById(`${prefix}${id}`)
const snapshot = () => {
const state = store.getState()
return [
state.documentText,
state.handleVersion,
state.undo.length,
state.unsaved,
]
}
async function mountSpy(options: { text?: string; readOnly?: boolean } = {}) {
announce.mockReset()
await openReady({ text: options.text ?? text() })
const readOnly = options.readOnly ?? false
render(
<AnnounceContext value={announce}>
<AnnotationsTab {...props} readOnly={readOnly} />
</AnnounceContext>,
)
const drawing = readOnly
? 'catalogue-canvas-drawing'
: 'annotation-canvas-drawing'
await waitFor(() =>
expect(screen.getByTestId(drawing).querySelector('svg')).not.toBeNull(),
)
}
const button = (panel: HTMLElement, name = 'Désélectionner') =>
within(panel).getByRole('button', { name })
it('shows the overview, focuses the row, announces, and changes nothing else', async () => {
await mountSpy()
const panel = await selectFromList()
const before = snapshot()
await userEvent.setup().click(button(panel))
expect(screen.queryByTestId('annotation-properties')).toBeNull()
expect(screen.getByTestId('annotation-overview')).toBeInTheDocument()
expect(document.activeElement).toBe(rowOf('anno-a'))
expect(announce).toHaveBeenCalledWith('Aucune annotation sélectionnée.')
expect(snapshot()).toEqual(before)
})
it('focuses the drawing when a filter hides the row', async () => {
await mountSpy()
const panel = await selectFromList()
// The filter lives in the overview: type it there, then reselect from the drawing.
await userEvent.setup().click(button(panel))
const filter = screen.getByLabelText('Filtrer par nom')
fireEvent.change(filter, { target: { value: 'zzz-no-match' } })
pressAt(
screen
.getByTestId('annotation-canvas-drawing')
.querySelector('[data-anno-id="anno-a"]')!,
)
const reopened = await screen.findByTestId('annotation-properties')
await userEvent.setup().click(button(reopened))
expect(document.activeElement).toBe(screen.getByTestId('annotation-canvas'))
expect(screen.queryByTestId('annotation-properties')).toBeNull()
})
it('undo after it undoes the earlier edit', async () => {
await mountSpy()
const panel = await selectFromList()
const user = userEvent.setup()
await user.clear(within(panel).getByLabelText('Centre x'))
await user.type(within(panel).getByLabelText('Centre x'), '60{Enter}')
expect(geometryOf('anno-a')).toMatchObject({ cx: 60 })
await user.click(button(panel))
act(() => void store.getState().undoStep())
expect(geometryOf('anno-a')).toMatchObject({ cx: 50 })
})
it('read-only: no « Supprimer », it deselects and focuses the ro- row', async () => {
await mountSpy({ readOnly: true })
const panel = await selectFromList()
expect(
within(panel).queryByRole('button', { name: 'Supprimer' }),
).toBeNull()
await userEvent.setup().click(button(panel))
expect(screen.queryByTestId('annotation-properties')).toBeNull()
const row = document.querySelector(
'[data-focus-key=\'{"kind":"annotation","id":"anno-a"}\']',
)
expect(document.activeElement).toBe(row)
expect(announce).toHaveBeenCalledTimes(1)
})
it('commits a valid typed value once when the field is not blurred', async () => {
await mountSpy()
const panel = await selectFromList()
const user = userEvent.setup()
const cx = within(panel).getByLabelText('Centre x')
await user.clear(cx)
await user.type(cx, '60')
const depth = store.getState().undo.length
await user.click(button(panel))
expect(geometryOf('anno-a')).toMatchObject({ cx: 60 })
expect(store.getState().undo.length).toBe(depth + 1)
})
it('a refused typed value: the panel closes, the document is unchanged', async () => {
await mountSpy({ text: insert(drawnText(), named('anno-a', 150, 150, 5)) })
const panel = await selectFromList()
const user = userEvent.setup()
const before = store.getState().documentText
const cx = within(panel).getByLabelText('Centre x')
await user.clear(cx)
await user.type(cx, '1000000')
await user.click(button(panel))
expect(screen.queryByTestId('annotation-properties')).toBeNull()
expect(store.getState().documentText).toBe(before)
})
it('speaks English', async () => {
useLocaleStore.setState({ locale: 'en' })
await mountSpy()
await screen.findByTestId('annotation-overview')
await userEvent.setup().click(rowOf('anno-a')!)
const panel = await screen.findByTestId('annotation-properties')
await userEvent.setup().click(button(panel, 'Deselect'))
expect(announce).toHaveBeenCalledWith('No annotation selected.')
})
it('is not offered while a replace tracing runs', async () => {
await mountSpy({
text: insert(drawnText(), {
kind: 'annotation',
value: zoneAnnotation({ type: 'path', d: 'M 20 20 L 80 20 L 50 80 Z' }),
}),
})
const panel = await selectFromList()
await userEvent.setup().click(
within(panel).getByRole('button', {
name: 'Remplacer par un polygone',
}),
)
const open = await screen.findByTestId('annotation-properties')
expect(
within(open).queryByRole('button', { name: 'Désélectionner' }),
).toBeNull()
})
})
describe('a tap on the drawing (D6b)', () => {
const announce = vi.fn()
const DESELECTED = 'Aucune annotation sélectionnée.'
const drawing = (readOnly = false) =>
screen.getByTestId(
readOnly ? 'catalogue-canvas-drawing' : 'annotation-canvas-drawing',
)
const rect = (readOnly = false) => drawing(readOnly).querySelector('rect')!
const box = () => screen.getByTestId('annotation-canvas')
const snapshot = () => {
const state = store.getState()
return [
state.documentText,
state.handleVersion,
state.undo.length,
state.unsaved,
]
}
const init = (id = 1, type = 'mouse') => ({
pointerId: id,
isPrimary: true,
button: 0,
buttons: 1,
pointerType: type,
})
interface Tap {
dx?: number
upOn?: Element
type?: string
during?: () => void
}
/** pointerdown on `el`, an optional move, pointerup then click on `upOn`. */
function tap(el: Element, options: Tap = {}) {
const { dx = 0, upOn = el, type = 'mouse', during } = options
fireEvent.pointerDown(el, { ...init(1, type), clientX: 10, clientY: 10 })
if (dx !== 0) {
fireEvent.pointerMove(el, {
...init(1, type),
clientX: 10 + dx,
clientY: 10,
})
}
during?.()
fireEvent.pointerUp(upOn, {
...init(1, type),
clientX: 10 + dx,
clientY: 10,
})
fireEvent.click(upOn, { clientX: 10 + dx, clientY: 10 })
}
async function mountSpy(options: { text?: string; readOnly?: boolean } = {}) {
announce.mockReset()
await openReady({ text: options.text ?? text() })
const readOnly = options.readOnly ?? false
render(
<AnnounceContext value={announce}>
<AnnotationsTab {...props} readOnly={readOnly} />
</AnnounceContext>,
)
await waitFor(() =>
expect(drawing(readOnly).querySelector('svg')).not.toBeNull(),
)
}
const isDeselected = () =>
screen.queryByTestId('annotation-properties') === null
async function selected(options: { text?: string } = {}) {
await mountSpy(options)
await selectFromList()
}
it('deselects on the inner rect: focus on the box, announced, store unchanged', async () => {
await selected()
const before = snapshot()
tap(rect())
expect(isDeselected()).toBe(true)
expect(document.activeElement).toBe(box())
expect(announce).toHaveBeenCalledWith(DESELECTED)
expect(announce).toHaveBeenCalledTimes(1)
expect(snapshot()).toEqual(before)
})
it('deselects on the composed root svg and on the box margin', async () => {
await selected()
tap(drawing().querySelector('svg')!)
expect(isDeselected()).toBe(true)
await selectFromList()
tap(box())
expect(isDeselected()).toBe(true)
})
it('keeps the selection when the press began on the selected marker (click retargeted)', async () => {
await selected()
tap(marker('anno-a'), { upOn: box() })
expect(isDeselected()).toBe(false)
tap(marker('anno-a'), { dx: 2, upOn: box() })
expect(isDeselected()).toBe(false)
expect(announce).not.toHaveBeenCalled()
})
it('selects another marker and a zone polygon through the click', async () => {
const zone = zoneAnnotation({ type: 'polygon', points: triangle })
await selected({
text: insert(
insert(text(), { kind: 'annotation', value: zone }),
named('anno-b', 90, 90, 3),
),
})
tap(marker('anno-b'))
expect(screen.getByTestId('edit-strip-detail')).toHaveTextContent('Point')
tap(marker('zone-a'))
expect(screen.getByTestId('edit-strip-detail')).toHaveTextContent(
'Zone · 3 sommets',
)
expect(announce).not.toHaveBeenCalled()
})
it('selects a link (detail trigger) through the click', async () => {
const view = insert(drawnText(), {
kind: 'view',
value: {
kind: 'detail',
id: 'view-det',
name: { fr: 'Tête', en: 'Head' },
svg_asset_id: null,
view_box: { min_x: 10, min_y: 10, width: 80, height: 80 },
parent_view_id: 'view-main',
},
})
const link = {
id: 'link-a',
view_id: 'view-main',
category_id: 'cat-a',
laterality: 'unpaired',
geometry: { type: 'circle', cx: 90, cy: 90, r: 3 },
review_status: 'to_confirm',
color: null,
kind: 'detail_trigger',
name: null,
opens_view_id: 'view-det',
} as Annotation
await mountSpy({ text: insert(view, { kind: 'annotation', value: link }) })
tap(marker('link-a'))
expect(screen.getByTestId('annotation-properties')).toBeInTheDocument()
expect(announce).not.toHaveBeenCalled()
})
it('removes the document listener when the canvas unmounts mid-press', async () => {
await selected()
const spy = vi.spyOn(document, 'removeEventListener')
fireEvent.pointerDown(rect(), { ...init(), clientX: 10, clientY: 10 })
cleanup()
expect(spy).toHaveBeenCalledWith('pointerdown', expect.any(Function), true)
spy.mockRestore()
})
it('a context menu during the press removes the listener and does not deselect', async () => {
await selected()
const spy = vi.spyOn(document, 'removeEventListener')
tap(rect(), { during: () => fireEvent.contextMenu(rect()) })
expect(spy).toHaveBeenCalledWith('pointerdown', expect.any(Function), true)
expect(isDeselected()).toBe(false)
spy.mockRestore()
})
it('the read-only twin keeps the keyboard pan and zoom', async () => {
await mountSpy({ readOnly: true })
const canvas = screen.getByTestId('catalogue-canvas')
const view = drawing(true)
fireEvent.keyDown(canvas, { key: '+' })
expect(view.style.transform).toContain('scale(1.5)')
// Handled (default prevented) by the framing's keyboard pan; the box has no size here.
expect(fireEvent.keyDown(canvas, { key: 'ArrowLeft' })).toBe(false)
})
it('a pen tap deselects at the pointer-up, like a mouse tap', async () => {
await selected()
const hit = rect()
fireEvent.pointerDown(hit, { ...init(1, 'pen'), clientX: 10, clientY: 10 })
fireEvent.pointerUp(hit, { ...init(1, 'pen'), clientX: 10, clientY: 10 })
expect(isDeselected()).toBe(true)
expect(announce).toHaveBeenCalledWith(DESELECTED)
})
it('a pen tap is decided by its press: a click landing on a marker selects nothing', async () => {
await selected({ text: insert(text(), named('anno-b', 90, 90, 3)) })
tap(rect(), { type: 'pen', upOn: marker('anno-b') })
expect(announce).toHaveBeenCalledWith(DESELECTED)
expect(marker('anno-b')).not.toHaveAttribute('data-state')
expect(isDeselected()).toBe(true)
})
it('a hover move after the press does not count as a drag', async () => {
await selected()
fireEvent.pointerDown(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.pointerMove(rect(), {
...init(),
buttons: 0,
clientX: 20,
clientY: 10,
})
fireEvent.pointerUp(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.click(rect())
expect(isDeselected()).toBe(true)
})
it('a new press with the same id outside the box disarms a stale press', async () => {
await selected()
fireEvent.pointerDown(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.pointerUp(document.body, { ...init(), clientX: 10, clientY: 10 })
fireEvent.pointerDown(document.body, {
...init(),
clientX: 300,
clientY: 10,
})
fireEvent.pointerUp(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.click(rect())
expect(isDeselected()).toBe(false)
})
it('keeps a pending keyboard creation with its typed name', async () => {
await mountSpy({ text: drawnText() })
const user = userEvent.setup()
await waitFor(() =>
expect(
screen.getByRole('button', { name: 'Ajouter un point' }),
).toBeEnabled(),
)
await user.click(screen.getByRole('button', { name: 'Ajouter un point' }))
const panel = await screen.findByTestId('annotation-creation')
await user.type(within(panel).getByLabelText('Nom (FR)'), 'Nuque')
tap(rect())
expect(screen.getByTestId('annotation-creation')).toBeInTheDocument()
expect(within(panel).getByLabelText('Nom (FR)')).toHaveValue('Nuque')
})
it('tells a tap from a drag on the accumulated movement (4 px)', async () => {
await selected()
tap(rect(), { dx: 3 })
expect(isDeselected()).toBe(true)
await selectFromList()
tap(rect(), { dx: 6 })
expect(isDeselected()).toBe(false)
fireEvent.pointerDown(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.pointerMove(rect(), { ...init(), clientX: 15, clientY: 10 })
fireEvent.pointerMove(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.pointerUp(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.click(rect())
expect(isDeselected()).toBe(false)
})
it('a second pointer, inside the box or not, makes it a gesture; the next tap deselects', async () => {
await selected()
tap(rect(), {
during: () =>
fireEvent.pointerDown(box(), {
pointerId: 2,
isPrimary: false,
button: 0,
pointerType: 'touch',
}),
})
expect(isDeselected()).toBe(false)
tap(rect(), {
during: () =>
fireEvent.pointerDown(document.body, {
pointerId: 2,
isPrimary: false,
button: 0,
pointerType: 'touch',
}),
})
expect(isDeselected()).toBe(false)
tap(rect())
expect(isDeselected()).toBe(true)
})
it('ignores a right-button press and a context menu during the press', async () => {
await selected()
fireEvent.pointerDown(rect(), { ...init(), button: 2 })
fireEvent.pointerUp(rect(), { ...init(), button: 2 })
fireEvent.click(rect())
expect(isDeselected()).toBe(false)
tap(rect(), { during: () => fireEvent.contextMenu(rect()) })
expect(isDeselected()).toBe(false)
})
it('removes its document listener once the press ends', async () => {
await selected()
const spy = vi.spyOn(document, 'removeEventListener')
tap(rect())
expect(spy).toHaveBeenCalledWith('pointerdown', expect.any(Function), true)
spy.mockRestore()
})
it('adds a vertex, selection kept, in a replace tracing', async () => {
const zone = zoneAnnotation({
type: 'path',
d: 'M 20 20 L 80 20 L 50 80 Z',
})
await mountSpy({
text: insert(drawnText(), { kind: 'annotation', value: zone }),
})
tap(marker('zone-a'))
await userEvent
.setup()
.click(screen.getByRole('button', { name: 'Remplacer par un polygone' }))
// The zone tool is active: the select-tool deselect never runs.
triangle.forEach(([x, y]) => {
fireEvent.pointerDown(box(), { ...init(), clientX: x, clientY: y })
fireEvent.pointerUp(box(), { ...init(), clientX: x, clientY: y })
fireEvent.click(box(), { clientX: x, clientY: y })
})
fireEvent.keyDown(box(), { key: 'Enter' })
await waitFor(() =>
expect(geometryOf('zone-a')).toEqual({
type: 'polygon',
points: triangle,
}),
)
expect(announce).not.toHaveBeenCalled()
})
it('a drag of the selected marker moves it and keeps the selection', async () => {
await selected()
const hit = marker('anno-a')
fireEvent.pointerDown(hit, { ...init(), clientX: 50, clientY: 50 })
fireEvent.pointerMove(hit, { ...init(), clientX: 58, clientY: 50 })
fireEvent.pointerUp(hit, { ...init(), clientX: 60, clientY: 40 })
fireEvent.click(box())
expect(geometryOf('anno-a')).toMatchObject({ cx: 60, cy: 40 })
expect(isDeselected()).toBe(false)
})
it('a touch tap deselects at the pointer-up', async () => {
await selected()
const hit = rect()
fireEvent.pointerDown(hit, {
...init(1, 'touch'),
clientX: 10,
clientY: 10,
})
fireEvent.pointerUp(hit, { ...init(1, 'touch'), clientX: 10, clientY: 10 })
expect(isDeselected()).toBe(true)
})
it('a touch tap is decided by its press: a click adjusted toward a marker selects nothing', async () => {
await selected({ text: insert(text(), named('anno-b', 90, 90, 3)) })
tap(rect(), { type: 'touch', upOn: marker('anno-b') })
expect(announce).toHaveBeenCalledWith(DESELECTED)
expect(isDeselected()).toBe(true)
expect(marker('anno-b')).not.toHaveAttribute('data-state')
})
it('a press is either a pan or a click, never both (R-8)', async () => {
await selected()
vi.spyOn(box(), 'getBoundingClientRect').mockReturnValue({
...{ x: 0, y: 0, left: 0, top: 0, right: 400, bottom: 300 },
...{ width: 400, height: 300, toJSON: () => ({}) },
})
await userEvent
.setup()
.click(screen.getByRole('button', { name: 'Zoom avant' }))
const transform = () => drawing().parentElement!.style.transform
/** A press at (10, 10) moved through the given x offsets, released at the last. */
const press = (type: string, path: number[]) => {
fireEvent.pointerDown(rect(), {
...init(1, type),
clientX: 10,
clientY: 10,
})
for (const dx of path) {
fireEvent.pointerMove(rect(), {
...init(1, type),
clientX: 10 + dx,
clientY: 10,
})
}
const last = 10 + (path.at(-1) ?? 0)
fireEvent.pointerUp(rect(), {
...init(1, type),
clientX: last,
clientY: 10,
})
}
const zoomed = transform()
expect(zoomed).toContain('scale(1.5)')
// A pen within its 6 px slop: a click (it deselects), no pan.
press('pen', [5])
expect(transform()).toBe(zoomed)
expect(isDeselected()).toBe(true)
// A pen past its slop: a pan, no click.
await selectFromList()
press('pen', [4, 8])
expect(transform()).not.toBe(zoomed)
expect(isDeselected()).toBe(false)
// A mouse wiggling 14 px of path, never 4 px away from the press: a click, no pan.
const panned = transform()
press('mouse', [3, -3, 2])
expect(transform()).toBe(panned)
expect(isDeselected()).toBe(true)
})
it('a finger drags the selected point (its handle), never a selected zone (A13)', async () => {
const zone = zoneAnnotation({ type: 'polygon', points: triangle })
await selected({
text: insert(text(), { kind: 'annotation', value: zone }),
})
const drag = (el: Element) => {
fireEvent.pointerDown(el, {
...init(1, 'touch'),
clientX: 50,
clientY: 50,
})
fireEvent.pointerMove(el, {
...init(1, 'touch'),
clientX: 70,
clientY: 50,
})
fireEvent.pointerUp(el, { ...init(1, 'touch'), clientX: 70, clientY: 40 })
}
drag(pointHandle())
expect(geometryOf('anno-a')).toMatchObject({ cx: 70, cy: 40 })
tap(marker('zone-a'))
const before = store.getState().documentText
drag(marker('zone-a'))
expect(store.getState().documentText).toBe(before)
expect(isDeselected()).toBe(false)
})
it('a mouse tap deselects at the pointer-up and swallows the click on a marker', async () => {
await selected({ text: insert(text(), named('anno-b', 90, 90, 3)) })
tap(rect(), { upOn: rect() })
expect(isDeselected()).toBe(true)
fireEvent.pointerDown(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.pointerUp(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.click(marker('anno-b'))
expect(isDeselected()).toBe(true)
})
it('a press on a polygon vertex handle outside its fill deselects (documented)', async () => {
await mountSpy({
text: insert(drawnText(), {
kind: 'annotation',
value: zoneAnnotation({ type: 'polygon', points: triangle }),
}),
})
tap(marker('zone-a'))
const handle = screen
.getByTestId('annotation-overlay')
.querySelector('circle')!
tap(handle)
expect(isDeselected()).toBe(true)
})
it('read-only twin: deselects on the rect and focuses the catalogue canvas', async () => {
await mountSpy({ readOnly: true })
await selectFromList()
tap(rect(true))
expect(isDeselected()).toBe(true)
expect(document.activeElement).toBe(screen.getByTestId('catalogue-canvas'))
expect(announce).toHaveBeenCalledWith(DESELECTED)
})
it('undo after a tap deselect undoes the earlier edit, redo restores it', async () => {
await selected()
const user = userEvent.setup()
const cx = screen.getByLabelText('Centre x')
await user.clear(cx)
await user.type(cx, '60{Enter}')
tap(rect())
act(() => void store.getState().undoStep())
expect(geometryOf('anno-a')).toMatchObject({ cx: 50 })
act(() => void store.getState().redoStep())
expect(geometryOf('anno-a')).toMatchObject({ cx: 60 })
})
it('commits a typed valid value once and deselects when the press blurs the field', async () => {
await selected()
const user = userEvent.setup()
const cx = screen.getByLabelText('Centre x')
await user.clear(cx)
await user.type(cx, '60')
const depth = store.getState().undo.length
fireEvent.pointerDown(rect(), { ...init(), clientX: 10, clientY: 10 })
// What mousedown does: the focus moves to the box, the field commits, the drawing rebuilds.
act(() => box().focus())
fireEvent.pointerUp(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.click(rect())
expect(geometryOf('anno-a')).toMatchObject({ cx: 60 })
expect(store.getState().undo.length).toBe(depth + 1)
expect(isDeselected()).toBe(true)
})
it('a refused typed value: the panel closes, the document is unchanged', async () => {
await selected({ text: insert(drawnText(), named('anno-a', 150, 150, 5)) })
const user = userEvent.setup()
const before = store.getState().documentText
const cx = screen.getByLabelText('Centre x')
await user.clear(cx)
await user.type(cx, '1000000')
fireEvent.pointerDown(rect(), { ...init(), clientX: 10, clientY: 10 })
act(() => box().focus())
fireEvent.pointerUp(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.click(rect())
expect(isDeselected()).toBe(true)
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()
// Its full text in the strip too (A6), shown but not announced a second time.
const copy = within(notice())
.getByText(/^Déplacement refusé : /)
.closest('p')!
expect(copy).toHaveAttribute('aria-hidden', 'true')
expect(copy).not.toHaveAttribute('role')
expect(copy.className).toContain('danger')
})
it('the message sits on its own row under the add buttons, always mounted', async () => {
await mount()
const add = screen.getByRole('button', { name: 'Ajouter un point' })
expect(line()).not.toContainElement(add)
expect(line()).toHaveClass('h-11', 'overflow-hidden')
expect(line()).toHaveAttribute('role', 'status')
})
it('an undo then a redo never brings the message back', async () => {
await mount()
await selectFromList()
drag(marker('anno-a'), [60, 40])
expect(line()).toHaveTextContent('Point déplacé')
act(() => void store.getState().undoStep())
act(() => void store.getState().redoStep())
expect(line()).not.toHaveTextContent('Point déplacé')
})
it('a hold ends with its message: after « Défaire » the next message still expires', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
try {
await mount()
await selectFromList()
drag(marker('anno-a'), [60, 40])
const message = within(line()).getByTestId('gesture-message')
const undo = within(message).getByRole('button')
fireEvent.pointerEnter(message, { pointerType: 'mouse' })
act(() => undo.focus())
fireEvent.click(undo)
expect(line()).not.toHaveTextContent('Point déplacé')
drag(marker('anno-a'), [70, 40])
expect(line()).toHaveTextContent('Point déplacé')
act(() => void vi.advanceTimersByTime(6_100))
expect(line()).not.toHaveTextContent('Point déplacé')
} finally {
vi.useRealTimers()
}
})
it('a kept drop clears a refusal the strip still shows', async () => {
await mount()
const doc = store.getState().previewState!.document
const dispatch = vi.fn()
const { result } = renderHook(() =>
usePlacement({
ui: { ...initialUi, hint: 'Refusé' },
dispatch,
frame: null,
doc,
viewId: 'main',
context: { t: (key) => key, locale: 'fr' },
message: { show: vi.fn() },
}),
)
act(() =>
result.current.onDrop('anno-a', { type: 'circle', cx: 60, cy: 40, r: 5 }),
)
expect(geometryOf('anno-a')).toMatchObject({ cx: 60, cy: 40 })
expect(dispatch).toHaveBeenCalledWith({ type: 'hint', hint: null })
})
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()
}
})
})