Files
faunosteo/apps/app/tests/unit/editor-zone-edit.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

1243 lines
43 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.
/** U2 Task 5: vertices, « + », « − », zone move, redraw, paths and the handle cap. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
act,
cleanup,
fireEvent,
render,
screen,
waitFor,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { Annotation, Point } from '@faunosteo/core-wasm/types'
import AnnotationsTab from '@/components/editor/tabs/AnnotationsTab'
import HistoryButtons from '@/components/editor/HistoryButtons'
import { answerDrawing, guardDrawing } from '@/editor/annotations/drawingGuard'
import { useAnnotationWork, resetWork } from '@/editor/annotations/workStore'
import { useUndoShortcuts } from '@/editor/useUndoShortcuts'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import { stripLeadOf } from '@/editor/annotations/stripLead'
import { initialUi } from '@/editor/annotations/uiState'
import { drawnText, insert, point } from '../helpers/editorFixtures'
import { openReady, pressAt, resetStore, store } 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(),
}
function UndoKeys() {
useUndoShortcuts(true)
return null
}
const annotations = () => store.getState().previewState!.document.annotations
const annotationOf = (id: string) =>
annotations().find((a: Annotation) => a.id === id)!
const pointsOf = (id: string) => {
const geometry = annotationOf(id).geometry
return geometry?.type === 'polygon' ? geometry.points : null
}
const depth = () => store.getState().undo.length
function stubCtm(): void {
const identity = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 }
Object.defineProperty(window.SVGElement.prototype, 'getScreenCTM', {
configurable: true,
value: () => ({ ...identity, inverse: () => identity }),
})
}
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
stubCtm()
})
afterEach(() => {
cleanup()
resetStore()
resetWork()
})
const SQUARE: Point[] = [
[20, 20],
[80, 20],
[80, 80],
[20, 80],
]
const zone = (id: string, geometry: object): Annotation =>
({
...(point(id, 0, 0, 1).value as Annotation),
kind: 'zone',
geometry,
}) as Annotation
const withZone = (text: string, id: string, geometry: object) =>
insert(text, { kind: 'annotation', value: zone(id, geometry) })
const squareText = (points: Point[] = SQUARE) =>
withZone(drawnText(), 'z', { type: 'polygon', points })
const tab = (readOnly = false) => (
<div data-editor-workspace>
<AnnotationsTab {...props} readOnly={readOnly} />
</div>
)
async function mount(text: string) {
await openReady({ text })
const view = render(tab())
await waitFor(() =>
expect(
screen.getByTestId('annotation-canvas-drawing').querySelector('svg'),
).not.toBeNull(),
)
return view
}
async function select(index = 0) {
const list = await screen.findByRole('list', {
name: 'Annotations de la vue',
})
await userEvent.setup().click(within(list).getAllByRole('button')[index])
// U2 Task 6: a row selects only (A1); the strip holds the selection's commands.
await screen.findByRole('button', { name: 'Propriétés' })
return screen.getByTestId('edit-strip')
}
const mouse = {
pointerId: 1,
isPrimary: true,
button: 0,
buttons: 1,
pointerType: 'mouse',
}
/** The hit shape of a handle: the press machine reads its `data-handle`. */
const hitOf = (name: string) =>
screen.getByRole('button', { name }).querySelector('[data-handle]')!
const vertex = (n: number) =>
screen.getByRole('button', { name: `Sommet ${n} de N` })
const plus = (n: number) =>
screen.getByRole('button', {
name: `Ajouter un sommet après le sommet ${n} de N`,
})
const minus = (n: number) =>
screen.getByRole('button', { name: `Retirer le sommet ${n} de N` })
const clickHandle = (name: string, at: [number, number] = [0, 0]) =>
pressAt(hitOf(name), at[0], at[1])
const marker = (id: string) =>
screen
.getByTestId('annotation-canvas-drawing')
.querySelector(`[data-anno-id="${id}"]`)!
const detail = () => screen.getByTestId('edit-strip-detail')
/** A « − » bubble still drawn, else the canvas box: what a press at its place reaches. */
const liveBubbleOrCanvas = () =>
screen
.queryByRole('button', { name: /^Retirer le sommet/ })
?.querySelector('[data-handle]') ?? screen.getByTestId('annotation-canvas')
const message = () => screen.getByTestId('gesture-line')
const chosen = () => useAnnotationWork.getState().chosen
function drag(el: Element, from: [number, number], to: [number, number]) {
const [x0, y0] = from
const [x1, y1] = to
fireEvent.pointerDown(el, { ...mouse, clientX: x0, clientY: y0 })
fireEvent.pointerMove(el, { ...mouse, clientX: x1, clientY: y1 })
fireEvent.pointerUp(el, { ...mouse, buttons: 0, clientX: x1, clientY: y1 })
}
describe('a vertex (R-9)', () => {
it('a click chooses it, stamped; the strip says it; the interior unchooses it', async () => {
await mount(squareText())
await select()
expect(detail()).toHaveTextContent('Zone · 4 sommets')
clickHandle('Sommet 2 de N', [80, 20])
expect(chosen()).toEqual({
annotationId: 'z',
vertex: 1,
base: store.getState().documentText,
})
expect(detail()).toHaveTextContent('Zone · 4 sommets · sommet 2 choisi')
expect(minus(2)).toBeInTheDocument()
pressAt(marker('z'), 50, 50)
expect(chosen()).toBeNull()
expect(
screen.queryByRole('button', { name: /^Retirer le sommet/ }),
).toBeNull()
})
it('a drag commits once; a release on a neighbour commits nothing', async () => {
await mount(squareText())
await select()
const before = depth()
drag(hitOf('Sommet 2 de N'), [80, 20], [90, 10])
expect(pointsOf('z')![1]).toEqual([90, 10])
expect(depth()).toBe(before + 1)
expect(message()).toHaveTextContent('Sommet déplacé')
drag(hitOf('Sommet 2 de N'), [90, 10], [80, 80])
expect(pointsOf('z')![1]).toEqual([90, 10])
expect(depth()).toBe(before + 1)
})
it('« + » inserts at the midpoint and chooses the new vertex', async () => {
await mount(squareText())
await select()
const before = depth()
clickHandle('Ajouter un sommet après le sommet 1 de N', [50, 20])
expect(pointsOf('z')).toEqual([[20, 20], [50, 20], ...SQUARE.slice(1)])
expect(depth()).toBe(before + 1)
expect(chosen()).toMatchObject({ vertex: 1 })
expect(chosen()!.base).toBe(store.getState().documentText)
expect(detail()).toHaveTextContent('sommet 2 choisi')
expect(message()).toHaveTextContent('Sommet ajouté')
})
it('undo after « + » drops the chosen vertex: « − » removes nothing stale (Review Focus 2)', async () => {
await mount(squareText())
render(<UndoKeys />)
await select()
clickHandle('Ajouter un sommet après le sommet 1 de N', [50, 20])
const bubble = hitOf('Retirer le sommet 2 de N')
fireEvent.keyDown(document.body, { key: 'z', ctrlKey: true })
expect(pointsOf('z')).toEqual(SQUARE)
expect(chosen()).toBeNull()
expect(
screen.queryByRole('button', { name: /^Retirer le sommet/ }),
).toBeNull()
void bubble
const after = depth()
fireEvent.keyDown(vertex(2), { key: 'Delete' })
// A press where the bubble was reaches what is there now: a bubble still shown, else the
// box (which deselects).
pressAt(liveBubbleOrCanvas(), 50, 20)
expect(pointsOf('z')).toEqual(SQUARE)
expect(depth()).toBe(after)
})
it('« − » removes the chosen vertex', async () => {
await mount(squareText())
await select()
clickHandle('Sommet 3 de N', [80, 80])
clickHandle('Retirer le sommet 3 de N', [80, 70])
expect(pointsOf('z')).toEqual([SQUARE[0], SQUARE[1], SQUARE[3]])
expect(chosen()).toBeNull()
expect(message()).toHaveTextContent('Sommet retiré')
})
it('« − » is disabled at 3 with its reason; nothing is removed', async () => {
const triangle = SQUARE.slice(0, 3)
await mount(squareText(triangle))
await select()
const before = depth()
clickHandle('Sommet 1 de N', [20, 20])
expect(minus(1)).toHaveAttribute('aria-disabled', 'true')
clickHandle('Retirer le sommet 1 de N', [20, 10])
expect(pointsOf('z')).toEqual(triangle)
expect(depth()).toBe(before)
expect(message()).toHaveTextContent('Une zone garde au moins 3 sommets')
})
it('keys: focus chooses, arrows preview, Enter commits; Insert adds, Delete removes', async () => {
await mount(squareText())
await select()
const before = depth()
vertex(1).focus()
expect(chosen()).toMatchObject({ vertex: 0 })
fireEvent.keyDown(vertex(1), { key: 'ArrowRight' })
expect(pointsOf('z')![0]).toEqual([20, 20])
fireEvent.keyDown(vertex(1), { key: 'Enter' })
expect(pointsOf('z')![0]).toEqual([20.5, 20])
expect(depth()).toBe(before + 1)
fireEvent.keyDown(vertex(1), { key: 'Insert' })
expect(pointsOf('z')).toHaveLength(5)
expect(pointsOf('z')![1]).toEqual([50.25, 20])
expect(chosen()).toMatchObject({ vertex: 1 })
fireEvent.keyDown(vertex(2), { key: 'Delete' })
expect(pointsOf('z')).toHaveLength(4)
expect(depth()).toBe(before + 3)
})
it('Enter on a « + » inserts; Tab walks the handles, « + » included', async () => {
await mount(squareText())
await select()
const order = screen
.getAllByRole('button')
.filter((b) => b.closest('[data-testid="handle-layer"]'))
.map((b) => b.getAttribute('aria-label'))
expect(order).toContain('Ajouter un sommet après le sommet 4 de N')
expect(order).toContain('Sommet 4 de N')
fireEvent.keyDown(plus(4), { key: 'Enter' })
expect(pointsOf('z')).toHaveLength(5)
expect(pointsOf('z')![4]).toEqual([20, 50])
})
})
describe('handle names carry the zone name (criterion 18)', () => {
const named = (name: { fr: string; en: string }) =>
insert(drawnText(), {
kind: 'annotation',
value: {
...zone('z', { type: 'polygon', points: SQUARE }),
name,
} as Annotation,
})
it('« Sommet {n} de {nom} », the « + » and « − » too, in a named group', async () => {
await mount(named({ fr: 'Thoraciques', en: 'Thoracic' }))
await select()
expect(
screen.getByRole('group', { name: 'Sommets de Thoraciques' }),
).toBeInTheDocument()
clickHandle('Sommet 2 de Thoraciques', [80, 20])
expect(
screen.getByRole('button', {
name: 'Ajouter un sommet après le sommet 1 de Thoraciques',
}),
).toBeInTheDocument()
expect(
screen.getByRole('button', {
name: 'Retirer le sommet 2 de Thoraciques',
}),
).toBeInTheDocument()
})
it('in English, the name of the current locale', async () => {
useLocaleStore.setState({ locale: 'en' })
await mount(named({ fr: 'Thoraciques', en: 'Thoracic' }))
const list = await screen.findByRole('list', {
name: 'Annotations of the view',
})
await userEvent.setup().click(within(list).getAllByRole('button')[0])
expect(
await screen.findByRole('group', { name: 'Vertices of Thoracic' }),
).toBeInTheDocument()
expect(
screen.getByRole('button', { name: 'Vertex 3 of Thoracic' }),
).toBeInTheDocument()
expect(
screen.getByRole('button', {
name: 'Add a vertex after vertex 3 of Thoracic',
}),
).toBeInTheDocument()
})
})
describe('a double click on a handle (R-8, carried Task 2 gap)', () => {
const twice = (el: Element, x: number, y: number) => {
pressAt(el, x, y)
pressAt(el, x, y)
}
it('on « + »: one insert, never a second', async () => {
await mount(squareText())
await select()
const before = depth()
twice(hitOf('Ajouter un sommet après le sommet 1 de N'), 50, 20)
expect(pointsOf('z')).toHaveLength(5)
expect(depth()).toBe(before + 1)
})
it('on a vertex: chosen once, the second click runs no handle action', async () => {
await mount(squareText())
await select()
const spy = vi.spyOn(useAnnotationWork, 'setState')
twice(hitOf('Sommet 2 de N'), 80, 20)
const choices = spy.mock.calls.filter(
([patch]) => typeof patch === 'object' && 'chosen' in patch,
)
spy.mockRestore()
expect(choices).toHaveLength(1)
expect(chosen()).toMatchObject({ vertex: 1 })
})
it('on « − »: one removal, never a second', async () => {
await mount(squareText([...SQUARE, [10, 50]]))
await select()
clickHandle('Sommet 2 de N', [80, 20])
const before = depth()
pressAt(hitOf('Retirer le sommet 2 de N'), 80, 10)
// The second click of the double click lands on what is there now, at the same place.
pressAt(liveBubbleOrCanvas(), 80, 10)
expect(pointsOf('z')).toHaveLength(4)
expect(depth()).toBe(before + 1)
})
})
describe('moving the zone (A11, R-12)', () => {
it('the interior dragged by mouse moves the zone once', async () => {
await mount(squareText())
await select()
const before = depth()
drag(marker('z'), [50, 50], [60, 55])
expect(pointsOf('z')![0]).toEqual([30, 25])
expect(depth()).toBe(before + 1)
expect(message()).toHaveTextContent('Zone déplacée')
})
it('« Déplacer la zone » moves it whole; « Valider la position » commits once', async () => {
await mount(squareText())
await select()
const before = depth()
await userEvent
.setup()
.click(screen.getByRole('button', { name: 'Déplacer la zone' }))
expect(screen.getByTestId('edit-strip-title')).toHaveTextContent(
'Déplacer la zone',
)
const bar = screen.getByTestId('move-mode-bar')
fireEvent.click(
within(bar).getByRole('button', { name: 'Déplacer vers la droite' }),
)
expect(pointsOf('z')).toEqual(SQUARE)
fireEvent.click(
within(bar).getByRole('button', { name: 'Valider la position' }),
)
expect(pointsOf('z')).toEqual(SQUARE.map(([x, y]) => [x + 0.5, y]))
expect(depth()).toBe(before + 1)
})
it('« Déplacer le sommet » moves the chosen vertex only', async () => {
await mount(squareText())
await select()
clickHandle('Sommet 3 de N', [80, 80])
await userEvent
.setup()
.click(screen.getByRole('button', { name: 'Déplacer le sommet' }))
expect(screen.getByTestId('edit-strip-title')).toHaveTextContent(
'Déplacer le sommet',
)
const bar = screen.getByTestId('move-mode-bar')
fireEvent.click(
within(bar).getByRole('button', { name: 'Déplacer vers le bas' }),
)
fireEvent.click(
within(bar).getByRole('button', { name: 'Valider la position' }),
)
expect(pointsOf('z')).toEqual([SQUARE[0], SQUARE[1], [80, 80.5], SQUARE[3]])
})
})
describe('the handle cap (R-7, T18)', () => {
const many = (n: number): Point[] =>
Array.from({ length: n }, (_, i) => {
const angle = (2 * Math.PI * i) / n
return [
Math.round((50 + 30 * Math.cos(angle)) * 100) / 100,
Math.round((50 + 30 * Math.sin(angle)) * 100) / 100,
]
})
it('41 vertices: the outline, the cap message, no handle; move and redraw remain', async () => {
await mount(squareText(many(41)))
await select()
expect(screen.queryByRole('button', { name: /^Sommet / })).toBeNull()
expect(
screen.queryByRole('button', { name: /^Ajouter un sommet après/ }),
).toBeNull()
expect(screen.getByTestId('overlay-selection')).toBeInTheDocument()
expect(detail()).toHaveTextContent(
'Zone · 41 sommets, trop pour les poignées',
)
expect(
screen.getByRole('button', { name: 'Déplacer la zone' }),
).toBeInTheDocument()
expect(
screen.getByRole('button', { name: 'Redessiner' }),
).toBeInTheDocument()
})
it('40 vertices still have their handles', async () => {
await mount(squareText(many(40)))
await select()
expect(screen.getAllByRole('button', { name: /^Sommet / })).toHaveLength(40)
})
})
describe('paths (UX_TESTS « Paths »)', () => {
const PATH = { type: 'path', d: 'M 20 20 L 80 20 L 50 80 Z' }
const pathAndZone = () =>
withZone(withZone(drawnText(), 'p', PATH), 'z', {
type: 'polygon',
points: [
[55, 55],
[90, 55],
[90, 90],
[55, 90],
],
})
it('show no handle and offer « Remplacer par un polygone »', async () => {
await mount(pathAndZone())
const panel = await select(0)
expect(screen.queryByRole('button', { name: /^Sommet / })).toBeNull()
expect(
within(panel).getByRole('button', { name: 'Remplacer par un polygone' }),
).toBeInTheDocument()
})
it('keep their `d` byte-identical after gestures on a neighbour', async () => {
await mount(pathAndZone())
const before = JSON.stringify(annotationOf('p').geometry)
await select(1)
clickHandle('Ajouter un sommet après le sommet 1 de N', [72.5, 55])
clickHandle('Sommet 2 de N', [72.5, 55])
clickHandle('Retirer le sommet 2 de N', [72.5, 45])
drag(hitOf('Sommet 1 de N'), [55, 55], [60, 60])
drag(marker('z'), [80, 80], [85, 85])
expect(depth()).toBe(4)
expect(JSON.stringify(annotationOf('p').geometry)).toBe(before)
})
})
describe('redraw (R-12, board 06 C)', () => {
const canvas = () => screen.getByTestId('annotation-canvas')
const TRACE: [number, number][] = [
[30, 30],
[70, 30],
[70, 70],
[30, 70],
]
async function redrawing() {
await mount(squareText())
await select()
await userEvent
.setup()
.click(screen.getByRole('button', { name: 'Redessiner' }))
}
it('keeps the old outline during the trace, no handle; a close commits once and keeps every property', async () => {
await redrawing()
const kept = { ...annotationOf('z'), geometry: null }
expect(useAnnotationWork.getState().mode).toMatchObject({
kind: 'redraw',
started: false,
})
expect(screen.getByTestId('edit-strip-title')).toHaveTextContent(
'Redessiner · N',
)
expect(screen.queryByRole('button', { name: /^Sommet / })).toBeNull()
const before = depth()
TRACE.forEach(([x, y]) => pressAt(canvas(), x, y))
expect(screen.getByTestId('overlay-old-place')).toBeInTheDocument()
expect(useAnnotationWork.getState().mode?.started).toBe(true)
expect(pointsOf('z')).toEqual(SQUARE)
fireEvent.click(screen.getByRole('button', { name: 'Fermer le tracé' }))
expect(pointsOf('z')).toEqual(TRACE)
expect({ ...annotationOf('z'), geometry: null }).toEqual(kept)
expect(depth()).toBe(before + 1)
expect(useAnnotationWork.getState().mode).toBeNull()
expect(message()).toHaveTextContent('Zone redessinée')
expect(
screen.queryByText('Nouveau tracé abandonné : la fiche a changé.'),
).toBeNull()
})
it('a click within 12 px of the first vertex closes it (R-11)', async () => {
await redrawing()
TRACE.slice(0, 3).forEach(([x, y]) => pressAt(canvas(), x, y))
pressAt(canvas(), 38, 30)
expect(pointsOf('z')).toEqual(TRACE.slice(0, 3))
})
it('a refusal (too small to touch) keeps the trace open with the core message', async () => {
await redrawing()
const sliver: [number, number][] = [
[20, 50],
[80, 50],
[80, 50.5],
]
sliver.forEach(([x, y]) => pressAt(canvas(), x, y))
fireEvent.click(screen.getByRole('button', { name: 'Fermer le tracé' }))
expect(pointsOf('z')).toEqual(SQUARE)
expect(
screen.getByRole('button', { name: 'Fermer le tracé' }),
).toBeInTheDocument()
expect(screen.getByTestId('edit-strip-notice')).toHaveTextContent(
/too small/,
)
expect(screen.getByTestId('edit-strip-title')).toHaveTextContent(
'Fermeture refusée',
)
expect(useAnnotationWork.getState().mode).toMatchObject({
kind: 'redraw',
started: true,
})
})
it('Escape and « Annuler le tracé » cancel at once and keep the old shape', async () => {
await redrawing()
pressAt(canvas(), 30, 30)
fireEvent.keyDown(document.body, { key: 'Escape' })
expect(useAnnotationWork.getState().mode).toBeNull()
expect(screen.queryByRole('button', { name: 'Fermer le tracé' })).toBeNull()
expect(useAnnotationWork.getState().question).toBeNull()
expect(pointsOf('z')).toEqual(SQUARE)
await userEvent
.setup()
.click(screen.getByRole('button', { name: 'Redessiner' }))
pressAt(canvas(), 30, 30)
fireEvent.click(screen.getByRole('button', { name: 'Annuler le tracé' }))
expect(useAnnotationWork.getState().mode).toBeNull()
expect(pointsOf('z')).toEqual(SQUARE)
})
it('removing the last vertex back to none makes it unstarted again', async () => {
await redrawing()
pressAt(canvas(), 30, 30)
expect(useAnnotationWork.getState().mode?.started).toBe(true)
fireEvent.click(
screen.getByRole('button', { name: 'Retirer le dernier sommet' }),
)
expect(useAnnotationWork.getState().mode?.started).toBe(false)
})
it('the guard: Back before the first vertex ends it at once; after one, it asks', async () => {
await redrawing()
const back = vi.fn()
let allowed = false
act(() => void (allowed = guardDrawing(back)))
expect(allowed).toBe(true)
expect(useAnnotationWork.getState().mode).toBeNull()
expect(screen.queryByRole('button', { name: 'Fermer le tracé' })).toBeNull()
await userEvent
.setup()
.click(screen.getByRole('button', { name: 'Redessiner' }))
pressAt(canvas(), 30, 30)
act(() => void (allowed = guardDrawing(back)))
expect(allowed).toBe(false)
expect(useAnnotationWork.getState().question?.work).toBe('redraw')
expect(
screen.getByRole('button', { name: 'Fermer le tracé' }),
).toBeInTheDocument()
})
it('a row of the overview asks first once a vertex is placed (A3, R-12)', async () => {
await redrawing()
pressAt(canvas(), 30, 30)
const list = screen.getByRole('list', { name: 'Annotations de la vue' })
fireEvent.click(within(list).getAllByRole('button')[0]!)
expect(useAnnotationWork.getState().question?.work).toBe('redraw')
expect(
screen.getByRole('button', { name: 'Fermer le tracé' }),
).toBeInTheDocument()
})
it('a tool asks first once a vertex is placed; « Abandonner » ends the trace', async () => {
await redrawing()
pressAt(canvas(), 30, 30)
fireEvent.click(screen.getByRole('button', { name: 'Point' }))
expect(useAnnotationWork.getState().question?.work).toBe('redraw')
act(() => answerDrawing(true))
expect(useAnnotationWork.getState().mode).toBeNull()
expect(screen.queryByRole('button', { name: 'Fermer le tracé' })).toBeNull()
expect(pointsOf('z')).toEqual(SQUARE)
})
it('a document change made elsewhere drops a started redraw and says so (R-13)', async () => {
await redrawing()
pressAt(canvas(), 30, 30)
act(
() =>
void store.getState().commit({
op: 'update',
key: { kind: 'annotation', id: 'z' },
element: {
kind: 'annotation',
value: zone('z', { type: 'polygon', points: TRACE }),
},
}),
)
expect(useAnnotationWork.getState().mode).toBeNull()
expect(
await screen.findByText('Nouveau tracé abandonné : la fiche a changé.'),
).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Fermer le tracé' })).toBeNull()
})
it('« Remplacer par un polygone » on a path is the same redraw', async () => {
await mount(
withZone(drawnText(), 'p', {
type: 'path',
d: 'M 20 20 L 80 20 L 50 80 Z',
}),
)
const panel = await select()
await userEvent.setup().click(
within(panel).getByRole('button', {
name: 'Remplacer par un polygone',
}),
)
expect(useAnnotationWork.getState().mode).toMatchObject({ kind: 'redraw' })
})
})
describe('fix round 1: no lost series, no lost focus, no stale « − »', () => {
it('I-1: ArrowRight then Insert, no Enter: the step is committed, then the insert', async () => {
await mount(squareText())
await select()
const before = depth()
vertex(1).focus()
fireEvent.keyDown(vertex(1), { key: 'ArrowRight' })
fireEvent.keyDown(vertex(1), { key: 'Insert' })
expect(pointsOf('z')).toEqual([[20.5, 20], [50.25, 20], ...SQUARE.slice(1)])
expect(depth()).toBe(before + 2)
})
it('I-1: ArrowDown then Delete, no Enter: the step is committed, then the removal', async () => {
await mount(squareText([...SQUARE, [10, 50]]))
await select()
const before = depth()
vertex(1).focus()
fireEvent.keyDown(vertex(1), { key: 'ArrowDown' })
fireEvent.keyDown(vertex(1), { key: 'Delete' })
expect(pointsOf('z')).toEqual([...SQUARE.slice(1), [10, 50]])
expect(depth()).toBe(before + 2)
expect(message()).toHaveTextContent('Sommet retiré')
})
it('I-2: « Désélectionner » commits a pending series on a vertex', async () => {
await mount(squareText())
const panel = await select()
const before = depth()
vertex(2).focus()
fireEvent.keyDown(vertex(2), { key: 'ArrowDown' })
fireEvent.click(
within(panel).getByRole('button', { name: 'Désélectionner' }),
)
expect(pointsOf('z')![1]).toEqual([80, 20.5])
expect(depth()).toBe(before + 1)
expect(message()).toHaveTextContent('Sommet déplacé')
})
it('I-2: « Désélectionner » commits a pending series on a point handle', async () => {
await mount(insert(drawnText(), point('p', 50, 50, 5)))
const panel = await select()
const before = depth()
const handle = screen.getByTestId('point-handle')
handle.focus()
fireEvent.keyDown(handle, { key: 'ArrowRight' })
fireEvent.click(
within(panel).getByRole('button', { name: 'Désélectionner' }),
)
expect(annotationOf('p').geometry).toMatchObject({ cx: 50.5 })
expect(depth()).toBe(before + 1)
})
it('M-1: Delete on the last vertex keeps the focus on a vertex', async () => {
await mount(squareText([...SQUARE, [10, 50]]))
await select()
act(() => vertex(5).focus())
fireEvent.keyDown(vertex(5), { key: 'Delete' })
expect(pointsOf('z')).toHaveLength(4)
expect(document.activeElement).toBe(vertex(4))
})
it('M-1: Enter on « − » keeps the focus on a vertex', async () => {
await mount(squareText([...SQUARE, [10, 50]]))
await select()
act(() => vertex(2).focus())
act(() => minus(2).focus())
fireEvent.keyDown(minus(2), { key: 'Enter' })
expect(pointsOf('z')).toHaveLength(4)
expect(document.activeElement).toBe(vertex(2))
})
it('M-2: a chosen vertex stamped on another text removes nothing', async () => {
await mount(squareText())
await select()
clickHandle('Sommet 2 de N', [80, 20])
const before = depth()
act(() =>
useAnnotationWork.setState({
chosen: { annotationId: 'z', vertex: 1, base: 'an older text' },
}),
)
fireEvent.keyDown(vertex(2), { key: 'Delete' })
pressAt(liveBubbleOrCanvas(), 80, 10)
expect(pointsOf('z')).toEqual(SQUARE)
expect(depth()).toBe(before)
})
})
describe('I-3: the click a touch tap synthesises is absorbed', () => {
// A tap arms its absorber for 400 ms: let it lapse before the next test clicks.
afterEach(() => new Promise((done) => setTimeout(done, 450)))
const tapOn = (el: Element, pointerType: string) => {
const init = {
pointerId: 1,
isPrimary: true,
button: 0,
buttons: 1,
pointerType,
clientX: 50,
clientY: 50,
}
fireEvent.pointerDown(el, init)
fireEvent.pointerUp(el, { ...init, buttons: 0 })
}
const addPoint = () =>
screen.getByRole('button', { name: 'Ajouter un point' })
/** A click at the tap's own place, as the browser synthesises it. */
const clickAtTap = (el: Element) =>
fireEvent.click(el, { clientX: 50, clientY: 50 })
const creation = () => screen.queryByTestId('annotation-creation')
it('a touch tap: its click landing elsewhere does nothing; the next click does', async () => {
await mount(squareText())
await select()
tapOn(screen.getByTestId('annotation-canvas'), 'touch')
expect(screen.queryByRole('button', { name: 'Propriétés' })).toBeNull()
clickAtTap(addPoint())
expect(creation()).toBeNull()
clickAtTap(addPoint())
expect(creation()).not.toBeNull()
})
it('a pen tap is absorbed too; a mouse tap never is', async () => {
await mount(squareText())
tapOn(screen.getByTestId('annotation-canvas'), 'pen')
clickAtTap(addPoint())
expect(creation()).toBeNull()
tapOn(screen.getByTestId('annotation-canvas'), 'mouse')
clickAtTap(addPoint())
expect(creation()).not.toBeNull()
})
it('a click elsewhere right after a tap goes through', async () => {
await mount(squareText())
tapOn(screen.getByTestId('annotation-canvas'), 'touch')
fireEvent.click(addPoint(), { clientX: 300, clientY: 300 })
expect(creation()).not.toBeNull()
})
it('a real click after the double-click window goes through', async () => {
await mount(squareText())
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
try {
tapOn(screen.getByTestId('annotation-canvas'), 'touch')
act(() => void vi.advanceTimersByTime(450))
clickAtTap(addPoint())
expect(creation()).not.toBeNull()
} finally {
vi.useRealTimers()
}
})
})
describe('the zoom hint for short segments (R-18, D2)', () => {
const SHORT: Point[] = [
[20, 20],
[35, 20],
[80, 20],
[80, 80],
[20, 80],
]
const zoomHint = 'Zoomez pour ajouter un sommet sur les segments courts.'
beforeEach(() => {
// One CSS px per drawing unit at fit: the 100-unit frame in a 100 px box.
for (const side of ['clientWidth', 'clientHeight'])
Object.defineProperty(window.SVGSVGElement.prototype, side, {
configurable: true,
get: () => 100,
})
})
afterEach(() => {
for (const side of ['clientWidth', 'clientHeight'])
delete (
window.SVGSVGElement.prototype as unknown as Record<string, unknown>
)[side]
})
it('a hidden « + » shows the line; zooming until every « + » shows removes it', async () => {
await mount(squareText(SHORT))
await select()
expect(
screen.queryByRole('button', {
name: 'Ajouter un sommet après le sommet 1 de N',
}),
).toBeNull()
expect(plus(2)).toBeInTheDocument()
expect(screen.getByTestId('edit-strip-notice')).toHaveTextContent(zoomHint)
const zoomIn = screen.getByRole('button', { name: 'Zoom avant' })
fireEvent.click(zoomIn)
fireEvent.click(zoomIn)
await waitFor(() => expect(plus(1)).toBeInTheDocument())
expect(screen.getByTestId('edit-strip-notice')).not.toHaveTextContent(
zoomHint,
)
})
it('a refusal takes its place while shown', async () => {
await mount(squareText(SHORT))
await select()
drag(hitOf('Sommet 3 de N'), [80, 20], [500, 20])
const notice = screen.getByTestId('edit-strip-notice')
expect(notice).toHaveTextContent('Déplacement refusé')
expect(notice).not.toHaveTextContent(zoomHint)
})
it('is absent in a redraw', async () => {
await mount(squareText(SHORT))
await select()
await userEvent
.setup()
.click(screen.getByRole('button', { name: 'Redessiner' }))
expect(screen.getByTestId('edit-strip-notice')).not.toHaveTextContent(
zoomHint,
)
})
})
describe('M-5: « Fermeture refusée » titles a refused close only', () => {
const t = (key: string) => (fr as Record<string, string>)[key] ?? key
const tracing = (refused: boolean) => ({
...initialUi,
tool: 'zone' as const,
hint: 'un autre message',
tracing: {
target: 'zone' as const,
annotationId: null,
points: [] as Point[],
refused,
},
})
it('another hint during a tracing keeps the tracing title', () => {
const lead = stripLeadOf(
tracing(false),
undefined,
JSON.parse(drawnText()),
{
t,
locale: 'fr',
},
)
expect(lead.title).toBe('Ajouter une zone')
})
it('a refused close says so', () => {
const lead = stripLeadOf(
tracing(true),
undefined,
JSON.parse(drawnText()),
{
t,
locale: 'fr',
},
)
expect(lead.title).toBe('Fermeture refusée')
})
})
describe('final review I-1: a redo or a handle key never drops pending work', () => {
const redoKey = (target: Element) =>
fireEvent.keyDown(target, { key: 'z', ctrlKey: true, shiftKey: true })
const canvas = () => screen.getByTestId('annotation-canvas')
const ABANDONED = /abandonné : la fiche a changé/
/** One committed step on vertex 1, undone: the redo stack holds it. */
async function withRedo() {
await mount(squareText())
render(<UndoKeys />)
await select()
act(() => vertex(1).focus())
fireEvent.keyDown(vertex(1), { key: 'ArrowRight' })
fireEvent.keyDown(vertex(1), { key: 'Enter' })
act(() => void store.getState().undoStep())
expect(store.getState().redo).toHaveLength(1)
}
async function startedMove(name = 'Déplacer la zone') {
await userEvent.setup().click(screen.getByRole('button', { name }))
const bar = screen.getByTestId('move-mode-bar')
fireEvent.click(
within(bar).getByRole('button', { name: 'Déplacer vers la droite' }),
)
expect(useAnnotationWork.getState().mode?.started).toBe(true)
}
it('Ctrl+Shift+Z on a vertex keyed with arrows keeps the series; Enter commits it', async () => {
await withRedo()
fireEvent.keyDown(vertex(1), { key: 'ArrowDown' })
redoKey(vertex(1))
expect(useAnnotationWork.getState().preview?.source).toBe('keys')
expect(store.getState().redo).toHaveLength(1)
fireEvent.keyDown(vertex(1), { key: 'Enter' })
expect(pointsOf('z')![0]).toEqual([20, 20.5])
})
it('Ctrl+Shift+Z in a started move keeps the move, said by nothing', async () => {
await withRedo()
await startedMove()
redoKey(document.body)
expect(useAnnotationWork.getState().mode).toMatchObject({
kind: 'move',
started: true,
})
expect(pointsOf('z')).toEqual(SQUARE)
expect(screen.queryByText(ABANDONED)).toBeNull()
})
it('the header « Refaire » is off in a started move and keeps it', async () => {
await withRedo()
render(<HistoryButtons />)
await startedMove()
const redo = screen.getByRole('button', {
name: 'Refaire la dernière modification défaite',
})
// A click that leaves the focus in place (Safari does not focus a clicked button).
fireEvent.click(redo)
expect(useAnnotationWork.getState().mode?.started).toBe(true)
expect(store.getState().redo).toHaveLength(1)
expect(screen.queryByText(ABANDONED)).toBeNull()
expect(redo).toHaveAttribute('aria-disabled', 'true')
})
it('Ctrl+Shift+Z in a started redraw keeps the trace', async () => {
await withRedo()
await userEvent
.setup()
.click(screen.getByRole('button', { name: 'Redessiner' }))
pressAt(canvas(), 30, 30)
redoKey(canvas())
expect(useAnnotationWork.getState().mode).toMatchObject({
kind: 'redraw',
started: true,
})
expect(
screen.getByRole('button', { name: 'Fermer le tracé' }),
).toBeInTheDocument()
expect(screen.queryByText(ABANDONED)).toBeNull()
})
it('the header « Refaire » is off in a started redraw and keeps it', async () => {
await withRedo()
render(<HistoryButtons />)
await userEvent
.setup()
.click(screen.getByRole('button', { name: 'Redessiner' }))
pressAt(canvas(), 30, 30)
const redo = screen.getByRole('button', {
name: 'Refaire la dernière modification défaite',
})
fireEvent.click(redo)
expect(useAnnotationWork.getState().mode).toMatchObject({
kind: 'redraw',
started: true,
})
expect(store.getState().redo).toHaveLength(1)
expect(redo).toHaveAttribute('aria-disabled', 'true')
})
it('in a started zone move, Enter or Space on « + » and Insert change nothing', async () => {
await mount(squareText())
await select()
await startedMove()
const before = depth()
fireEvent.keyDown(plus(1), { key: 'Enter' })
fireEvent.keyDown(plus(4), { key: ' ' })
fireEvent.keyDown(vertex(1), { key: 'Insert' })
expect(pointsOf('z')).toEqual(SQUARE)
expect(depth()).toBe(before)
expect(useAnnotationWork.getState().mode?.started).toBe(true)
expect(screen.queryByText(ABANDONED)).toBeNull()
})
it('in a started vertex move, Enter on « − », Insert and Delete change nothing', async () => {
await mount(squareText())
await select()
clickHandle('Sommet 3 de N', [80, 80])
await startedMove('Déplacer le sommet')
const before = depth()
fireEvent.keyDown(minus(3), { key: 'Enter' })
fireEvent.keyDown(vertex(3), { key: 'Insert' })
fireEvent.keyDown(vertex(3), { key: 'Delete' })
fireEvent.keyDown(plus(2), { key: 'Enter' })
expect(pointsOf('z')).toEqual(SQUARE)
expect(depth()).toBe(before)
expect(useAnnotationWork.getState().mode?.started).toBe(true)
expect(screen.queryByText(ABANDONED)).toBeNull()
})
})
describe('final review I-1 audit: a press on the drawing never drops a keyed series', () => {
// A touch press moves the focus only after its pointer-up (if at all), and happy-dom
// moves none: the keyed vertex keeps the focus and no blur commits its series.
async function keyed(points: Point[] = SQUARE) {
await mount(squareText(points))
await select()
act(() => vertex(1).focus())
fireEvent.keyDown(vertex(1), { key: 'ArrowRight' })
expect(useAnnotationWork.getState().preview?.source).toBe('keys')
return depth()
}
it('a press on « + »: the step is committed, then the insert', async () => {
const before = await keyed()
clickHandle('Ajouter un sommet après le sommet 1 de N', [50.25, 20])
expect(pointsOf('z')).toEqual([[20.5, 20], [50.25, 20], ...SQUARE.slice(1)])
expect(depth()).toBe(before + 2)
})
it('a press on « − »: the step is committed, then the removal', async () => {
const before = await keyed([...SQUARE, [10, 50]])
clickHandle('Retirer le sommet 1 de N', [20.5, 20])
expect(pointsOf('z')).toEqual([...SQUARE.slice(1), [10, 50]])
expect(depth()).toBe(before + 2)
})
it('a drag of another vertex carries the keyed step', async () => {
await keyed()
drag(hitOf('Sommet 2 de N'), [80, 20], [90, 10])
expect(pointsOf('z')).toEqual([[20.5, 20], [90, 10], ...SQUARE.slice(2)])
})
})
describe('final review M-6: a redraw gives the focus back to « Redessiner »', () => {
const canvas = () => screen.getByTestId('annotation-canvas')
const TRACE: [number, number][] = [
[30, 30],
[70, 30],
[70, 70],
[30, 70],
]
const redrawButton = () => screen.getByRole('button', { name: 'Redessiner' })
async function redrawing(text = squareText()) {
await mount(text)
await select()
await userEvent.setup().click(redrawButton())
}
const press = (name: string) =>
userEvent.setup().click(screen.getByRole('button', { name }))
it('after « Annuler le tracé »', async () => {
await redrawing()
pressAt(canvas(), 30, 30)
await press('Annuler le tracé')
expect(useAnnotationWork.getState().mode).toBeNull()
expect(document.activeElement).toBe(redrawButton())
})
it('after a closed redraw', async () => {
await redrawing()
TRACE.forEach(([x, y]) => pressAt(canvas(), x, y))
await press('Fermer le tracé')
expect(pointsOf('z')).toEqual(TRACE)
expect(document.activeElement).toBe(redrawButton())
})
it('after a refused close, then « Annuler le tracé »', async () => {
await redrawing()
for (const [x, y] of [
[20, 50],
[80, 50],
[80, 50.5],
])
pressAt(canvas(), x, y)
await press('Fermer le tracé')
expect(useAnnotationWork.getState().mode?.started).toBe(true)
await press('Annuler le tracé')
expect(document.activeElement).toBe(redrawButton())
})
it('on a link polygon (no « Déplacer »), never on body', async () => {
const head = 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: 'l',
view_id: 'view-main',
category_id: 'cat-a',
laterality: 'unpaired',
geometry: { type: 'polygon', points: SQUARE },
review_status: 'to_confirm',
color: null,
kind: 'detail_trigger',
name: null,
opens_view_id: 'view-det',
} as Annotation
await redrawing(insert(head, { kind: 'annotation', value: link }))
expect(screen.queryByRole('button', { name: /^Déplacer/ })).toBeNull()
pressAt(canvas(), 30, 30)
await press('Annuler le tracé')
expect(document.activeElement).not.toBe(document.body)
expect(document.activeElement).toBe(redrawButton())
})
})
describe('Safari: a strip command clicked with the focus left on a keyed vertex', () => {
// Safari (and iPad Safari on a tap) does not focus a clicked button: no blur commits the
// series, so the command itself must (coordinator ruling on the final fix report).
async function keyedVertex() {
await mount(squareText())
await select()
clickHandle('Sommet 1 de N', [20, 20])
act(() => vertex(1).focus())
fireEvent.keyDown(vertex(1), { key: 'ArrowRight' })
expect(useAnnotationWork.getState().preview?.source).toBe('keys')
return depth()
}
it('« Déplacer le sommet » commits the step, then starts the mode', async () => {
const before = await keyedVertex()
fireEvent.click(screen.getByRole('button', { name: 'Déplacer le sommet' }))
expect(pointsOf('z')![0]).toEqual([20.5, 20])
expect(depth()).toBe(before + 1)
expect(useAnnotationWork.getState().mode).toMatchObject({
kind: 'move',
started: false,
base: store.getState().documentText,
})
})
it('« Redessiner » commits the step, then starts the redraw', async () => {
const before = await keyedVertex()
fireEvent.click(screen.getByRole('button', { name: 'Redessiner' }))
expect(pointsOf('z')![0]).toEqual([20.5, 20])
expect(depth()).toBe(before + 1)
expect(useAnnotationWork.getState().mode).toMatchObject({
kind: 'redraw',
base: store.getState().documentText,
})
})
it('« Propriétés » and « Désélectionner » already commit it', async () => {
let before = await keyedVertex()
fireEvent.click(screen.getByRole('button', { name: 'Propriétés' }))
expect(pointsOf('z')![0]).toEqual([20.5, 20])
expect(depth()).toBe(before + 1)
cleanup()
resetStore()
resetWork()
before = await keyedVertex()
fireEvent.click(screen.getByRole('button', { name: 'Désélectionner' }))
expect(pointsOf('z')![0]).toEqual([20.5, 20])
expect(depth()).toBe(before + 1)
})
})