Files
faunosteo/apps/app/tests/unit/editor-annotations-tab.test.tsx
T
bchanot b6aa2819ea fix(editor): name vertex handles after their zone, in a named group
Criterion 18: « Sommet {n} de {nom} », « Ajouter un sommet après le sommet
{n} de {nom} », « Retirer le sommet {n} de {nom} » (EN « Vertex {n} of
{name} » …), {nom} the zone's display name in the current locale; the
handle group is a role="group" named « Sommets de {nom} ».

Tests: no assertion removed; every unit and e2e locator that read the old
names now reads the same handle with the zone name appended (fixtures: N,
Vertèbres thoraciques, Zone dessinée, Zone clavier). New unit tests in
editor-zone-edit cover the FR names, the group and the EN locale.
2026-11-18 14:09:24 +01:00

1969 lines
70 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/** 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 { LayeredTab } from '../helpers/annotationLayer'
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
/** The selection as the overlay draws it (U2 Task 5: no coordinate field in the panel). */
const shownCircle = () =>
screen.getByTestId('overlay-selection').querySelector('circle')!
/** A mouse drag of `el` from `from` to `to`, past the 4 px slop. */
function mouseDrag(el: Element, from: [number, number], to: [number, number]) {
const at = ([x, y]: [number, number], buttons = 1) => ({
clientX: x,
clientY: y,
pointerId: 1,
isPrimary: true,
button: 0,
buttons,
pointerType: 'mouse',
})
fireEvent.pointerDown(el, at(from))
fireEvent.pointerMove(el, at(to))
fireEvent.pointerUp(el, at(to, 0))
}
/** 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(<LayeredTab {...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
// A1: a row selects only; the strip names the selection (the dialog stays closed).
await screen.findByRole('button', { name: 'Propriétés' })
return screen.getByTestId('edit-strip')
}
/** « Propriétés » in the strip: the properties dialog of the selection (A1). */
async function openProperties() {
await userEvent
.setup()
.click(screen.getByRole('button', { name: 'Propriétés' }))
return screen.findByRole('dialog')
}
describe('selection and the list', () => {
it('lists the view annotations, selects one and draws its exact stored numbers', async () => {
await mount({
text: insert(drawnText(), named('anno-a', 743.0451049804688, 50, 5)),
})
await selectFromList()
expect(shownCircle()).toHaveAttribute('cx', '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('an edit on the drawing (U2 Task 5: the numeric group left the panel)', () => {
it('commits only when the shape changes', async () => {
await mount()
await selectFromList()
const version = store.getState().handleVersion
const handle = screen.getByTestId('point-handle')
fireEvent.keyDown(handle, { key: 'Enter' })
expect(store.getState().handleVersion).toBe(version)
fireEvent.keyDown(handle, { key: 'ArrowRight' })
fireEvent.keyDown(handle, { key: 'Enter' })
expect(geometryOf('anno-a')).toEqual({
type: 'circle',
cx: 50.5,
cy: 50,
r: 5,
})
expect(store.getState().handleVersion).toBe(version + 1)
})
it('a refused place keeps the stored shape, then a place inside the frame repairs it', async () => {
await mount({ text: insert(drawnText(), named('anno-a', 150, 150, 5)) })
const strip = await selectFromList()
const before = store.getState().documentText
// The issue shows in the strip's notice (U2 Task 6: the panel left).
const issue = () => within(strip).queryByRole('alert')
expect(issue()).toBeInTheDocument()
mouseDrag(pointHandle(), [150, 150], [50, 150])
expect(store.getState().documentText).toBe(before)
expect(screen.getByTestId('overlay-refused-place')).toBeInTheDocument()
expect(shownCircle()).toHaveAttribute('cx', '150')
mouseDrag(pointHandle(), [150, 150], [50, 50])
expect(geometryOf('anno-a')).toEqual({
type: 'circle',
cx: 50,
cy: 50,
r: 5,
})
expect(issue()).toBeNull()
})
it('Escape drops a pending series: the stored shape shows again', async () => {
await mount({ text: insert(drawnText(), named('anno-a', 50, 50, 5)) })
await selectFromList()
const before = store.getState().documentText
const handle = screen.getByTestId('point-handle')
fireEvent.keyDown(handle, { key: 'ArrowRight' })
expect(shownCircle()).toHaveAttribute('cx', '50.5')
// This mount has no workspace wrapper: Escape is pressed with nothing focused.
fireEvent.keyDown(document.body, { key: 'Escape' })
expect(shownCircle()).toHaveAttribute('cx', '50')
expect(store.getState().documentText).toBe(before)
})
})
/** The creation dialog's form (U2 Task 7: no side panel, no coordinate field, A8). */
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
}
/** The ghost of the new shape: its filled shape, drawn by the overlay. */
const ghostShape = () =>
screen.getByTestId('overlay-ghost').querySelector('circle, polygon')!
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' }))
expect(
await screen.findByRole('dialog', { name: 'Nouveau point' }),
).toBeInTheDocument()
const panel = await fillCreation(user)
expect(ghostShape()).toHaveAttribute('cx', '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 },
})
// A7: back to « Sélectionner », the new point selected, « Point créé · Défaire ».
expect(
await screen.findByRole('button', { name: 'Propriétés' }),
).toBeInTheDocument()
expect(
screen.getByRole('button', { name: 'Sélectionner et déplacer' }),
).toHaveAttribute('aria-pressed', 'true')
expect(screen.getByTestId('gesture-line')).toHaveTextContent('Point créé')
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(store.getState().undo).toHaveLength(1)
})
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' }))
// R-3, board 33 B: only the missing field is named, under it and in the summary.
const alerts = within(panel).getAllByRole('alert')
expect(alerts.map((a) => a.textContent)).toEqual([
'Choisissez une latéralité.',
'À compléter : Latéralité.',
])
expect(
within(panel).getByText('Choisissez une latéralité.'),
).toBeInTheDocument()
expect(within(panel).queryByText(/Choisissez une catégorie/)).toBeNull()
expect(within(panel).queryByText(/Saisissez/)).toBeNull()
expect(within(panel).getByLabelText('Latéralité')).toHaveFocus()
expect(annotations()).toHaveLength(0)
})
it('places a triangle at the centre: the ghost shows it, « Créer » inserts it (A8: no field)', 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)
expect(within(panel).queryByLabelText('x du sommet 1')).toBeNull()
expect(
within(panel).getByText('Zone tracée, 3 sommets'),
).toBeInTheDocument()
expect(ghostShape().tagName).toBe('polygon')
await user.click(within(panel).getByRole('button', { name: 'Créer' }))
expect(annotations()[0]).toMatchObject({ kind: 'zone' })
expect(annotations()[0].geometry).toMatchObject({ type: 'polygon' })
})
})
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')
// R-4: the notice is in the dialog, without numbers.
expect(
screen.getByRole('dialog', { name: 'Nouveau point' }),
).toContainElement(notice)
expect(notice).toHaveTextContent(
"Le point ne tient pas à l'endroit choisi : la position corrigée est proposée sur le dessin.",
)
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,
})
await waitFor(() => expect(panel).not.toBeInTheDocument())
expect(screen.queryByTestId('overlay-click-cross')).toBeNull()
await screen.findByRole('button', { name: 'Propriétés' })
expect(shownCircle()).toHaveAttribute('cx', '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()
expect(screen.getByTestId('annotation-creation')).toBeInTheDocument()
expect(ghostShape()).toHaveAttribute('cx', '0')
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()
// Nothing edits the geometry of an unmeasured view: no handle, no field.
expect(screen.queryByTestId('point-handle')).toBeNull()
expect(within(panel).queryByRole('textbox', { name: /^Centre/ })).toBeNull()
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' })
expect(
await screen.findByRole('dialog', { name: 'Nouvelle zone' }),
).toBeInTheDocument()
const panel = await fillCreation(user)
expect(ghostShape()).toHaveAttribute('points', triangle.join(' '))
await user.click(within(panel).getByRole('button', { name: 'Créer' }))
expect(annotations()[0]).toMatchObject({
kind: 'zone',
geometry: { type: 'polygon', points: triangle },
})
})
it('Escape on a tracing asks first (board 32 row 3); « Abandonner » drops it', async () => {
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' }))
clickAt(20, 20)
expect(screen.getByText('1 sommet posé')).toBeInTheDocument()
fireEvent.keyDown(screen.getByTestId('annotation-canvas'), {
key: 'Escape',
})
const ask = await screen.findByRole('dialog', {
name: 'Abandonner la création ?',
})
await user.click(within(ask).getByRole('button', { name: 'Continuer' }))
expect(screen.getByText('1 sommet posé')).toBeInTheDocument()
fireEvent.keyDown(screen.getByTestId('annotation-canvas'), {
key: 'Escape',
})
await user.click(
within(
await screen.findByRole('dialog', { name: 'Abandonner la création ?' }),
).getByRole('button', { name: 'Abandonner' }),
)
expect(screen.queryByText('1 sommet posé')).toBeNull()
expect(annotations()).toHaveLength(0)
})
it('« Annuler le tracé » is an explicit cancel: it acts at once', async () => {
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' }))
clickAt(20, 20)
await user.click(screen.getByRole('button', { name: 'Annuler le tracé' }))
expect(screen.queryByRole('dialog')).toBeNull()
expect(screen.queryByText('1 sommet posé')).toBeNull()
})
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) })
const handleHit = (name: string) =>
screen.getByRole('button', { name }).querySelector('[data-handle]')!
it('« + » adds a vertex on the drawing and « − » removes it', async () => {
await mount({ text: zoneText({ type: 'polygon', points: triangle }) })
await selectFromList()
pressAt(handleHit('Ajouter un sommet après le sommet 1 de N'), 50, 20)
expect(geometryOf('zone-a')).toMatchObject({
points: [
[20, 20],
[50, 20],
[80, 20],
[50, 80],
],
})
pressAt(handleHit('Retirer le sommet 2 de N'), 50, 10)
expect(geometryOf('zone-a')).toMatchObject({ points: triangle })
})
it('never removes a vertex below three: « − » is greyed', async () => {
await mount({ text: zoneText({ type: 'polygon', points: triangle }) })
await selectFromList()
pressAt(handleHit('Sommet 1 de N'), 20, 20)
expect(
screen.getByRole('button', { name: 'Retirer le sommet 1 de N' }),
).toHaveAttribute('aria-disabled', 'true')
})
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)
// « Replacer le point »: the dialog hides, the next click moves the ghost and shows it.
await user.click(
within(panel).getByRole('button', { name: 'Replacer le point' }),
)
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(ghostShape()).toHaveAttribute('cx', '50')
pressAt(screen.getByTestId('annotation-canvas'), 60, 40)
const again = await screen.findByTestId('annotation-creation')
expect(ghostShape()).toHaveAttribute('cx', '60')
expect(within(again).getByLabelText('Nom (FR)')).toHaveValue('Nuque')
expect(within(again).getByLabelText('Latéralité')).toHaveValue('unpaired')
})
})
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' }))
await screen.findByTestId('annotation-creation')
expect(ghostShape()).toHaveAttribute('cx', '30')
expect(ghostShape()).toHaveAttribute('cy', '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 » keeps the tracing open, with 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()
// Board 33 A: the tracing stays open with its commands (it was dropped before Task 5).
expect(
screen.getByRole('button', { name: 'Annuler le tracé' }),
).toBeInTheDocument()
expect(screen.getByTestId('edit-strip-title')).toHaveTextContent(
'Fermeture refusée',
)
expect(geometryOf('zone-a')).toEqual(path)
})
it('a refused vertex move restores the shape exactly, document unchanged', async () => {
await mount({
text: zoneText({ type: 'polygon', points: [...triangle, [20, 60]] }),
})
await selectFromList()
const before = store.getState().documentText
const vertex = screen
.getByRole('button', { name: 'Sommet 1 de N' })
.querySelector('[data-handle]')!
mouseDrag(vertex, [20, 20], [500, 20])
expect(store.getState().documentText).toBe(before)
expect(screen.getByTestId('overlay-refused-place')).toBeInTheDocument()
expect(screen.getByTestId('gesture-line')).toHaveTextContent(
'Déplacement refusé',
)
})
})
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.queryByRole('button', { name: 'Propriétés' })).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"]')!,
)
await screen.findByRole('button', { name: 'Propriétés' })
await userEvent.setup().click(button(screen.getByTestId('edit-strip')))
expect(document.activeElement).toBe(screen.getByTestId('annotation-canvas'))
expect(screen.queryByRole('button', { name: 'Propriétés' })).toBeNull()
})
it('undo after it undoes the earlier edit', async () => {
await mountSpy()
const panel = await selectFromList()
const handle = screen.getByTestId('point-handle')
fireEvent.keyDown(handle, { key: 'ArrowRight' })
fireEvent.keyDown(handle, { key: 'Enter' })
expect(geometryOf('anno-a')).toMatchObject({ cx: 50.5 })
await userEvent.setup().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.queryByRole('button', { name: 'Propriétés' })).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 pending key series once when the handle is not blurred', async () => {
await mountSpy()
const panel = await selectFromList()
const handle = screen.getByTestId('point-handle')
handle.focus()
fireEvent.keyDown(handle, { key: 'ArrowRight' })
const depth = store.getState().undo.length
await userEvent.setup().click(button(panel))
expect(geometryOf('anno-a')).toMatchObject({ cx: 50.5 })
expect(store.getState().undo.length).toBe(depth + 1)
})
it('speaks English', async () => {
useLocaleStore.setState({ locale: 'en' })
await mountSpy()
await screen.findByTestId('annotation-overview')
await userEvent.setup().click(rowOf('anno-a')!)
await screen.findByRole('button', { name: 'Properties' })
await userEvent
.setup()
.click(button(screen.getByTestId('edit-strip'), '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',
}),
)
await screen.findByRole('button', { name: 'Annuler le tracé' })
expect(screen.queryByRole('button', { name: 'Désélectionner' })).toBeNull()
expect(screen.queryByRole('button', { name: 'Propriétés' })).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(),
)
}
// U2 Task 6: a selection shows « Propriétés » in the strip (the panel left).
const isDeselected = () =>
screen.queryByRole('button', { name: 'Propriétés' }) === 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('edit-strip-title')).toHaveAttribute(
'data-selection',
)
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)
})
// Final review M-8: since T2 a `click` on the canvas does nothing, so the click this test
// fired on a marker (and the empty tap before it) could not change the outcome: gone.
it('a mouse tap deselects at the pointer-up', async () => {
await selected({ text: insert(text(), named('anno-b', 90, 90, 3)) })
tap(rect(), { upOn: rect() })
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 handle = screen.getByTestId('point-handle')
fireEvent.keyDown(handle, { key: 'ArrowRight' })
fireEvent.keyDown(handle, { key: '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: 50.5 })
})
it('commits a pending key series once and deselects when the press blurs the handle', async () => {
await selected()
const handle = screen.getByTestId('point-handle')
act(() => handle.focus())
fireEvent.keyDown(handle, { key: 'ArrowRight' })
const depth = store.getState().undo.length
fireEvent.pointerDown(rect(), { ...init(), clientX: 10, clientY: 10 })
// What mousedown does: the focus moves to the box, the series commits on the blur.
act(() => box().focus())
fireEvent.pointerUp(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.click(rect())
expect(geometryOf('anno-a')).toMatchObject({ cx: 50.5 })
expect(store.getState().undo.length).toBe(depth + 1)
expect(isDeselected()).toBe(true)
})
})
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 dialog = await openProperties()
const issues = within(
within(dialog).getByTestId('annotation-geometry-issues'),
)
.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é')
// A commit that is no gesture: the review toggle of the properties dialog (A10).
const user = userEvent.setup()
const dialog = await openProperties()
await user.click(
within(dialog).getByRole('button', { name: 'Marquer comme relu' }),
)
await user.click(within(dialog).getByRole('button', { name: 'Fermer' }))
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')
// M-3: the polite region is inside the row, always mounted, empty at rest.
expect(within(line()).getByRole('status')).toBeEmptyDOMElement()
})
it('M-3: a refusal is an alert outside any status region, in the line and the strip', async () => {
await mount()
await selectFromList()
drag(marker('anno-a'), [98, 50])
const alert = within(line()).getByRole('alert')
expect(alert.closest('[role="status"]')).toBeNull()
render(
<EditStrip
lead={{ title: 'T', detail: 'Zone', icon: 'zone' }}
notice={{ tone: 'error', text: 'Problème' }}
commands={null}
/>,
)
const strip = screen.getAllByTestId('edit-strip-notice').at(-1)!
const issue = within(strip).getByRole('alert')
expect(issue.closest('[role="status"]')).toBeNull()
expect(within(strip).getByRole('status')).toBeEmptyDOMElement()
})
it('M-3: the same refusal twice is a new pill, announced again', async () => {
await mount()
await selectFromList()
drag(marker('anno-a'), [98, 50])
const first = within(line()).getByRole('alert')
drag(marker('anno-a'), [98, 50])
const second = within(line()).getByRole('alert')
expect(second).toHaveTextContent(first.textContent!)
expect(second).not.toBe(first)
})
it("M-4: after the line's « Défaire » the focus is on the drawing, not lost", async () => {
await mount()
await selectFromList()
drag(marker('anno-a'), [60, 40])
const undo = within(line()).getByRole('button', {
name: 'Défaire la dernière modification',
})
await userEvent.setup().click(undo)
expect(line()).not.toHaveTextContent('Point déplacé')
expect(document.activeElement).toBe(
document.querySelector(
'[data-place="annotations.drawing"] [role="group"][tabindex="0"]',
),
)
expect(document.activeElement).not.toBe(document.body)
})
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é' },
tracing: null,
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()
}
})
})