/** 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 { 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()), 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) => (
) 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') 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() 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() const after = depth() pressAt(bubble, 50, 20) fireEvent.keyDown(vertex(2), { key: 'Delete' }) 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() const bubble = hitOf('Retirer le sommet 2') pressAt(bubble, 80, 10) pressAt(bubble, 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('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 )[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, ) }) })