Files
faunosteo/apps/app/tests/unit/editor-zone-edit.test.tsx
T
bchanot e596e0765e fix(editor): no lost series, tap click absorbed, focus kept on handles
Task 5 review fix round 1.
- I-1: Insert and Delete on a vertex commit pending arrow steps first,
  then act on the stored polygon (read from the store, not the render).
- I-2: deselect commits a handle's pending series before the handle
  unmounts (commitFocusedSeries, no reliance on blur at removal).
- I-3: a touch or pen tap absorbs the click the browser synthesises at
  its place, once, within 400 ms and 8 px; mouse and later clicks pass.
  Scroll anchoring is off while the editor shows: the deselect's panel
  swap scrolled the drawing under the finger. editor-deselect step c is
  back at the page's end, and asserts the drawing does not move.
- I-4, M-2: the double-click and undo tests press what is there now;
  a hand-set stale chosen vertex removes nothing.
- I-5: editor-zones undos, the vertex choice and the refused-trace
  clicks run under expectNoShift; new e2e for I-2.
- M-1: Delete on the last vertex and Enter on « − » keep the focus on a
  vertex (the next one is chosen).
- M-4: the strip notice comment names R-18. M-5: the tracing carries a
  `refused` flag; only a refused close titles « Fermeture refusée ».
- M-7: TODO lines (bubble size shortcut, scroll-padding-top, scroll
  clamp at the page's end).

Rewritten assertions: zone-edit « − » double click and undo-then-« − »
pressed the detached bubble -> press the live bubble or the box at the
same place. editor-deselect step c: scroll-to-top removed, drawing y
asserted unchanged. editor-geometry: scroll-to-top kept with the clamp
named (reported, TODO). editor-zones and editor-journey: comment says
the scroll-to-top undoes Playwright's own auto-scroll.
2026-11-17 21:04:23 +01:00

882 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])
return screen.findByTestId('annotation-properties')
}
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.queryByTestId('annotation-properties')).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')
})
})