Files
faunosteo/apps/app/tests/unit/editor-zone-edit.test.tsx
T
bchanot cd794f3c39 feat(editor): properties dialog over the column, transactional save
U2 Task 6 (A1, A2, A3, A9, A10, R-3, R-5, R-6, R-14, R-16).

- Dialog: `anchor` places the panel at the column's left and width,
  from its top, under a 22 % ink veil that ignores clicks; the visual
  viewport below 320 px; centred without an anchor box.
- Navigation: `annotation` layer (LAYERS, EditorView, history entry,
  leave guards, left-draft flag); Back closes, Forward reopens.
- AnnotationDialog: read body, « Modifier » form (CreationFields with
  « Couleur », missingFields, R-3 messages), one `update` on the
  current annotation by id, « Marquer comme relu », « Modifier la
  forme », « Supprimer »; read-only flip keeps the draft.
- The column always shows the overview, selected row marked; Enter on
  it, a second click or a double click, the strip's « Propriétés »
  open the dialog. « Aller à » focuses the row (R-5).
- Read-only twin: strip and read-only dialog at 1 024 px and wider,
  inline read body below. PropertiesPanel and AnnotationFields gone.
- Strip lead 256 px and a fixed status slot, so the commands fit at
  1 024 px and a status change moves nothing.
- e2e: `aside-content` exemption removed; scroll-to-top workarounds
  of editor-geometry, editor-zones and editor-journey removed.

Removed assertions mapped:
  editor-annotations-tab.test.tsx:
  - selectFromList waited for `annotation-properties` -> waits for the strip's « Propriétés » (selection without dialog, A1)
  - refused place: issues block `annotation-geometry-issues` in the panel -> the strip notice alert (present, then gone)
  - keyboard creation / C26 confirmation: `annotation-properties` after create -> strip « Propriétés » (new element selected)
  - Désélectionner from the panel -> « Désélectionner » in the strip (all 7 tests); « panel closes » -> strip has no « Propriétés »
  - undo after deselect (typed name) -> handle key series then deselect then undo
  - commits a valid typed value once without blur (name field) -> a pending handle key series committed once by the strip deselect
  - a refused typed value: the panel closes (two tests: strip deselect, tap deselect) -> removed: no field outside the dialog; the dialog's draft writes nothing before « Enregistrer » (new dialog tests)
  - not offered while a replace tracing runs: panel's Désélectionner absent -> strip offers neither « Désélectionner » nor « Propriétés » during the tracing
  - tap: isDeselected read `annotation-properties` -> strip « Propriétés » absent; link select -> strip title data-selection
  - tap: undo after tap deselect (typed name) -> handle series; typed value committed on blur -> handle series committed on blur
  - strip geometry issues: list read in the panel -> list read in the properties dialog's issues block
  - a new commit replaces the message (typed name) -> « Marquer comme relu » in the dialog
  editor-escape.test.tsx:
  - `panel()` = `annotation-properties` -> the strip's « Propriétés » or the phone twin's inline read body
  - Escape from a panel button (« Marquer comme relu ») -> from the selected row in the side column: focus on the row
  - after A then B from the panel (via « Toutes les annotations ») -> select A, select B, Escape from a button of the side column: focus on B's row
  - a text field (panel « Nom (FR) ») -> the overview « Filtrer par nom »
  - redraw via the panel's « Remplacer par un polygone » -> the strip's command
  - modal / delete dialog opened by the panel's « Supprimer » -> « Supprimer » of the properties dialog
  - read-only width: hidden `annotation-properties` -> hidden strip « Propriétés » of the kept edit body
  editor-history-buttons.test.tsx (typed text and the press, 8 tests): the annotation's committed « Nom (FR) » field of the panel -> the sheet's committed « Nom (FR) » on Général (same TextField commit-on-blur path; annotation fields are now a dialog draft)
  editor-focus-request.test.tsx: « Aller à » focuses `data-properties-heading` inside `annotation-properties` -> focuses the annotation's row, marked aria-current, no dialog (R-5)
  editor-sections.test.tsx: « Aller à » with nothing in progress focused the properties heading -> focuses the row (R-5); creation kept: no `annotation-properties` -> no strip « Propriétés »
  editor-overview.test.tsx (edit and read-only): row opens `annotation-properties`, « Toutes les annotations » returns -> row selects, stays marked aria-current, no dialog; strip « Désélectionner » returns focus to the row; filter kept across select and « Désélectionner »
  editor-citations-guards.test.tsx: LAYERS_TOP_DOWN gains 'annotation' at the bottom
  editor-keep-alive.test.tsx: `annotation-properties` visible after the round trip -> the strip's « Propriétés » visible (selection kept)
  editor-no-loss.test.tsx: ids `ro-annotation-name-fr` and `annotation-name-fr` (both panels' fields) -> the twin's inline read body (no ids), then the dialog edit form's `annotation-edit-fr`, kept through a flip to 800 px, no duplicate id; « Aller à » visible `annotation-properties` -> visible `annotation-read` (inline twin), none at 1 280
  editor-point-edit.test.tsx / editor-zone-edit.test.tsx: `select()` waited for `annotation-properties` and returned it -> waits for the strip's « Propriétés » and returns the strip (its « Désélectionner » and « Remplacer par un polygone » moved there)
  - move mode Escape: `annotation-properties` still there -> the strip's « Propriétés » back after the mode
  - « Toutes les annotations » asks first during a started move -> Enter on the selected row asks first (no dialog), and the strip offers neither « Propriétés » nor « Désélectionner » during the mode
  - Escape from the handle / slider: `annotation-properties` gone -> the strip's « Propriétés » gone
  - I-3 touch tap: `annotation-properties` gone -> the strip's « Propriétés » gone
  e2e (sandbox):
  - support/layout.ts: `aside-content` exemption removed (ShiftExemption type, the loose compare); every `swaps`/`SWAPS` argument removed (editor-annotations, editor-zones, editor-geometry)
  - support/editor.ts pickAnnotation: clicked « Toutes les annotations » first when the panel showed -> the overview is always shown: clicks the row, then scrolls back to the top (the page no longer shortens)
  - editor-annotations: `annotation-properties` visible after a creation -> strip with « Propriétés »; review toggle and « Supprimer » of the panel -> the properties dialog's; a jitter click on the selected point now opens the dialog (A1), closed by Escape before the drag; handle names exact (the marked row shares the prefix); trace close moved out of expectNoShift (creation panel until Task 7, shortcut + TODO)
  - editor-deselect: `annotation-properties` -> the strip with « Propriétés » or the twin's inline read body; Escape in a field: panel « Nom (FR) » -> overview filter; delete dialog from the panel -> from the properties dialog (Escape closes it, then the dialog); « a typed value is applied by the click that deselects » (name field, refused blank) -> a pending point-handle key series applied by the deselecting click and by « Désélectionner » (refused value: no field outside the dialog); « the selected one stays » -> a second click, double click and jitter open the dialog, Escape closes it, selection kept
  - editor-geometry: `annotation-geometry-issues` in the panel -> read in the properties dialog, then the strip notice; after the refusal the error count unchanged; scroll-to-top workaround removed
  - editor-zones: panel « Désélectionner » -> strip; scroll-to-top after pickAnnotation removed (helper does it)
  - editor-structures: panel « Supprimer » -> properties dialog « Supprimer », confirmation over it
  - editor-journey: `#annotation-name-fr` committed field + `#annotation-laterality` -> the dialog's edit form, one « Enregistrer »; scroll-to-top removed
  - editor-shell / editor-shell-journeys: « Aller à » focus on `data-properties-heading` -> the annotation's row (aria-current), no dialog (R-5)
  - editor-shell-layout: focus kind `annotation-properties` -> removed (the overview is the side)
2026-11-17 22:01:57 +01:00

884 lines
30 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 { 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}` })
const plus = (n: number) =>
screen.getByRole('button', { name: `Ajouter un sommet après le sommet ${n}` })
const minus = (n: number) =>
screen.getByRole('button', { name: `Retirer le sommet ${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', [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'), [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'), [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', [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', [50, 20])
const bubble = hitOf('Retirer le sommet 2')
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', [80, 80])
clickHandle('Retirer le sommet 3', [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', [20, 20])
expect(minus(1)).toHaveAttribute('aria-disabled', 'true')
clickHandle('Retirer le sommet 1', [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')
expect(order).toContain('Sommet 4')
fireEvent.keyDown(plus(4), { key: 'Enter' })
expect(pointsOf('z')).toHaveLength(5)
expect(pointsOf('z')![4]).toEqual([20, 50])
})
})
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'), 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'), 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', [80, 20])
const before = depth()
pressAt(hitOf('Retirer le sommet 2'), 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', [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', [72.5, 55])
clickHandle('Sommet 2', [72.5, 55])
clickHandle('Retirer le sommet 2', [72.5, 45])
drag(hitOf('Sommet 1'), [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 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', [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',
}),
).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'), [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')
})
})