/** Lot N3: repair on attach to an unmeasured view (owner decision 7, R23). */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { cleanup, render, screen, waitFor, within, } from '@testing-library/react' import userEvent from '@testing-library/user-event' import type { AnatomicalSheetDocument, Annotation, Geometry, } from '@faunosteo/core-wasm/types' import ViewsSection from '@/components/editor/annotations/sections/ViewsSection' import { cleanSvg } from '@/editor/core/cleaning' import { attachToView } from '@/editor/drawingUpload' import { applyRepair, proposeGeometry } from '@/editor/repair' import { useLocaleStore } from '@/state/localeStore' import { getDict } from '@/i18n' import { emptyText, insert, point, svgBytes } from '../helpers/editorFixtures' import { openReady, resetStore, sb, 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(), registerSheetAsset: vi.fn(), listSheetAssets: vi.fn(), uploadSheetDrawing: vi.fn(), confirmSheetAssetUpload: vi.fn(), })) const props = { readOnly: false, navigate: vi.fn(), reloadSheet: vi.fn() } const NEW_ASSET = '22222222-2222-4222-8222-222222222222' const t = (key: string) => getDict('fr')[key as never] as string const doc = (): AnatomicalSheetDocument => JSON.parse(store.getState().documentText) const annotation = (id: string) => doc().annotations.find((a) => a.id === id) as Annotation const zone = (id: string, points: [number, number][]) => ({ kind: 'annotation' as const, value: { ...(point(id, 0, 0, 1).value as Annotation), kind: 'zone' as const, geometry: { type: 'polygon' as const, points }, } as Annotation, }) /** An unmeasured main view with a point and a zone far outside a 100 x 100 frame. */ function unmeasuredText(extra?: ReturnType['value'][]): string { let text = insert(emptyText(), { kind: 'category', value: { id: 'cat-a', name: { fr: 'N', en: 'N' }, color: null }, }) text = insert(text, point('anno-a', 500, 400, 5)) text = insert( text, zone('anno-z', [ [10, 10], [400, 10], [400, 400], ]), ) for (const value of extra ?? []) text = insert(text, { kind: 'annotation', value }) return text } async function holdNewDrawing(viewBox = '0 0 100 100') { const drawing = svgBytes(viewBox) const held = store.getState().addDrawing({ assetId: NEW_ASSET, sha256: drawing.sha256, bytes: drawing.bytes, }) expect(held).toEqual({ ok: true }) } beforeEach(() => useLocaleStore.setState({ locale: 'fr' })) afterEach(() => { cleanup() resetStore() }) describe('proposals (UI arithmetic in the new frame)', () => { const frame = { x: 0, y: 0, w: 100, h: 100 } it('moves a point into the frame with the creation arithmetic', () => { const proposed = proposeGeometry(frame, { type: 'circle', cx: 500, cy: 400, r: 5, }) expect(proposed).toEqual({ type: 'circle', cx: 85, cy: 85, r: 15 }) }) it('clamps each vertex of a polygon and leaves vertices inside as they are', () => { const proposed = proposeGeometry(frame, { type: 'polygon', points: [ [10.5, 20], [400, 50], [30, -8], ], }) expect(proposed).toEqual({ type: 'polygon', points: [ [10.5, 20], [100, 50], [30, 0], ], }) }) it('returns a path as it is: its points are never reshaped', () => { const path: Geometry = { type: 'path', d: 'M 1 1 L 5 5 Z' } expect(proposeGeometry(frame, path)).toBe(path) }) }) describe('the attach refusal on an unmeasured view', () => { it('turns into a repair offer with the new frame, the document untouched', async () => { await openReady({ text: unmeasuredText() }) await holdNewDrawing() const before = store.getState().documentText const step = attachToView('view-main', NEW_ASSET) expect(step).toMatchObject({ ok: false, error: { code: 'repair' } }) if (step.ok || step.error.code !== 'repair') throw new Error('no offer') expect(step.error.offer.frames['view-main']).toEqual({ x: 0, y: 0, w: 100, h: 100, }) expect(step.error.offer.refusal.annotationIds.sort()).toEqual([ 'anno-a', 'anno-z', ]) expect(store.getState().documentText).toBe(before) }) it('keeps the plain refusal on a measured view (C33)', async () => { await openReady() await holdNewDrawing('0 0 20 20') const step = attachToView('view-main', NEW_ASSET) expect(step).toMatchObject({ ok: false, error: { code: 'frame' } }) }) }) describe('applyRepair', () => { const context = { t, locale: 'fr' as const } const offerOf = () => { const step = attachToView('view-main', NEW_ASSET) if (step.ok || step.error.code !== 'repair') throw new Error('no offer') return step.error.offer } const proposals = (offer: ReturnType) => ({ 'anno-a': proposeGeometry( offer.frames['view-main'], annotation('anno-a').geometry as Geometry, ), 'anno-z': proposeGeometry( offer.frames['view-main'], annotation('anno-z').geometry as Geometry, ), }) it('commits the drawing and the repaired geometry as one undo entry', async () => { await openReady({ text: unmeasuredText() }) await holdNewDrawing() const text = store.getState().documentText const offer = offerOf() expect(applyRepair(offer, proposals(offer), context)).toEqual({ ok: true }) expect(doc().views[0]).toMatchObject({ svg_asset_id: NEW_ASSET }) expect(annotation('anno-a').geometry).toEqual({ type: 'circle', cx: 85, cy: 85, r: 15, }) expect(annotation('anno-a').review_status).toBe('to_confirm') expect(store.getState().undo).toHaveLength(1) store.getState().undoStep() expect(store.getState().documentText).toBe(text) }) it('keeps nothing and speaks per annotation when the core refuses the values', async () => { await openReady({ text: unmeasuredText() }) await holdNewDrawing() const before = store.getState().documentText const offer = offerOf() const result = applyRepair( offer, { ...proposals(offer), 'anno-a': { type: 'circle', cx: 500, cy: 400, r: 5 }, }, context, ) expect(result).toMatchObject({ ok: false, general: null }) if (result.ok) return expect(Object.keys(result.byAnnotation)).toEqual(['anno-a']) expect(result.byAnnotation['anno-a'].length).toBeGreaterThan(0) expect(store.getState().documentText).toBe(before) expect(store.getState().undo).toHaveLength(0) }) it('never rewrites a free path: its d is kept and the batch is refused', async () => { const pathValue = { ...(point('anno-p', 0, 0, 1).value as Annotation), kind: 'zone' as const, geometry: { type: 'path' as const, d: COMPLEX_PATH }, } as Annotation await openReady({ text: unmeasuredText([pathValue]) }) await holdNewDrawing() const before = store.getState().documentText const offer = offerOf() expect(offer.refusal.annotationIds).toContain('anno-p') const geometries = { ...proposals(offer), 'anno-p': proposeGeometry( offer.frames['view-main'], annotation('anno-p').geometry as Geometry, ), } expect(geometries['anno-p']).toEqual({ type: 'path', d: COMPLEX_PATH }) expect(applyRepair(offer, geometries, context)).toMatchObject({ ok: false }) expect(store.getState().documentText).toBe(before) expect(store.getState().undo).toHaveLength(0) }) it('is blocked while a recovery offer is pending', async () => { await openReady({ text: unmeasuredText() }) await holdNewDrawing() const offer = offerOf() store.setState({ recovery: 'pending' }) const result = applyRepair(offer, proposals(offer), context) expect(result).toMatchObject({ ok: false }) expect(doc().views[0].svg_asset_id).toBeNull() }) it('is refused for an offer of another session', async () => { await openReady({ text: unmeasuredText() }) await holdNewDrawing() const offer = { ...offerOf(), session: -1 } expect(applyRepair(offer, proposals(offer), context)).toMatchObject({ ok: false, }) expect(doc().views[0].svg_asset_id).toBeNull() }) }) function storedOf(text: string) { const cleaned = cleanSvg(new TextEncoder().encode(text)) if (!cleaned.ok || !cleaned.value.stored || !cleaned.value.sha256) throw new Error('bad') return { ...cleaned.value, bytes: new TextEncoder().encode(cleaned.value.stored), } } function serverGets(text: string) { const stored = storedOf(text) sb.registerSheetAsset.mockResolvedValue(NEW_ASSET) sb.listSheetAssets.mockResolvedValue([ { id: NEW_ASSET, sha256: stored.sha256!, byte_size: stored.byte_size!, uploaded_at: null, }, ]) sb.uploadSheetDrawing.mockResolvedValue('uploaded') sb.confirmSheetAssetUpload.mockResolvedValue(NEW_ASSET) sb.downloadSheetDrawing.mockImplementation(async (_c, hash) => hash === stored.sha256 ? stored.bytes : svgBytes().bytes, ) } const SVG = '' const COMPLEX_PATH = 'M 300 300 l 40 0 C 350 320 380 360 400 400 q 20 -30 -40 -50 ' + 'A 30 20 0 0 1 320 330 H 310 V 305 Z' async function pickAndOpenDialog(text = unmeasuredText()) { await openReady({ text }) serverGets(SVG) render() const user = userEvent.setup() const input = screen.getByTestId('view-view-main-file') as HTMLInputElement await user.upload(input, new File([SVG], 'd.svg', { type: 'image/svg+xml' })) const dialog = await screen.findByRole('dialog', { name: t('editor.views.repair.title'), }) return { user, dialog } } describe('the repair dialog', () => { it('lists the annotations with proposals; typing and nothing else applies nothing', async () => { const { user, dialog } = await pickAndOpenDialog() const before = store.getState().documentText expect( within(dialog).getByText( '2 annotations sortent du nouveau cadre de cette illustration.', { exact: false }, ), ).toBeTruthy() const row = within(dialog).getByTestId('repair-anno-a') expect(within(row).getByLabelText('Centre x')).toHaveValue('85') expect(within(row).getByLabelText('Centre y')).toHaveValue('85') await user.clear(within(row).getByLabelText('Centre x')) await user.type(within(row).getByLabelText('Centre x'), '60') expect(store.getState().documentText).toBe(before) expect(store.getState().undo).toHaveLength(0) }) it('applies one batch: drawing and values together, the dialog closes', async () => { const { user, dialog } = await pickAndOpenDialog() await user.click( within(dialog).getByRole('button', { name: t('editor.views.repair.apply'), }), ) await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) expect(doc().views[0].svg_asset_id).toBe(NEW_ASSET) expect(annotation('anno-a').geometry).toEqual({ type: 'circle', cx: 85, cy: 85, r: 15, }) expect(store.getState().undo).toHaveLength(1) }) it('keeps the typed values and the document when the core refuses', async () => { const { user, dialog } = await pickAndOpenDialog() const before = store.getState().documentText const row = within(dialog).getByTestId('repair-anno-a') const cx = within(row).getByLabelText('Centre x') await user.clear(cx) await user.type(cx, '900') await user.click( within(dialog).getByRole('button', { name: t('editor.views.repair.apply'), }), ) expect( await within(dialog).findByText(t('editor.views.repair.refused')), ).toBeTruthy() expect(within(row).getByLabelText('Centre x')).toHaveValue('900') expect(within(row).getByRole('alert')).toBeTruthy() expect(store.getState().documentText).toBe(before) expect(screen.getByRole('dialog')).toBeTruthy() }) it('cancels with the document unchanged and the drawing kept, saying how to repair', async () => { const { user, dialog } = await pickAndOpenDialog() const before = store.getState().documentText await user.click( within(dialog).getByRole('button', { name: t('editor.views.repair.cancel'), }), ) await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) expect(store.getState().documentText).toBe(before) expect(store.getState().drawings.map((d) => d.asset_id)).toContain( NEW_ASSET, ) expect(screen.getByText(/sortent du nouveau cadre/)).toBeTruthy() expect(screen.getByText(/L'illustration reste téléversée/)).toBeTruthy() expect(screen.queryByText(/Déplacez d'abord/)).toBeNull() }) it('blocks a free path with its reason, no conversion, and cancel keeps everything', async () => { const pathValue = { ...(point('anno-p', 0, 0, 1).value as Annotation), kind: 'zone' as const, geometry: { type: 'path' as const, d: COMPLEX_PATH }, } as Annotation const { user, dialog } = await pickAndOpenDialog( unmeasuredText([pathValue]), ) const before = store.getState().documentText const undoLength = store.getState().undo.length const apply = within(dialog).getByRole('button', { name: t('editor.views.repair.apply'), }) expect(apply).toBeDisabled() const row = within(dialog).getByTestId('repair-anno-p') expect( within(row).getByText(t('editor.views.repair.path_blocked')), ).toBeTruthy() expect(within(row).queryByRole('button')).toBeNull() expect(within(dialog).queryByText(/polygone/i)).toBeNull() await user.click(apply) expect(store.getState().documentText).toBe(before) await user.click( within(dialog).getByRole('button', { name: t('editor.views.repair.cancel'), }), ) await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) expect(store.getState().documentText).toBe(before) expect(store.getState().undo).toHaveLength(undoLength) expect(annotation('anno-p').geometry).toEqual({ type: 'path', d: COMPLEX_PATH, }) }) }) describe('the repair dialog (fix round 1)', () => { it('disables « Attacher et appliquer » while a group holds an unapplied draft', async () => { const { user, dialog } = await pickAndOpenDialog() const apply = within(dialog).getByRole('button', { name: t('editor.views.repair.apply'), }) expect(apply).toBeEnabled() const cx = within( within(dialog).getByTestId('repair-anno-a'), ).getByLabelText('Centre x') await user.clear(cx) await user.keyboard('{Enter}') expect(apply).toBeDisabled() await user.type(cx, '60{Enter}') expect(apply).toBeEnabled() }) it('headings sit under the dialog title as h3', async () => { const { dialog } = await pickAndOpenDialog() expect(within(dialog).getAllByRole('heading', { level: 3 }).length).toBe(2) }) it('words a refusal for the dialog, never the locked Annotations tab', async () => { await openReady({ text: unmeasuredText() }) await holdNewDrawing() const step = attachToView('view-main', NEW_ASSET) if (step.ok || step.error.code !== 'repair') throw new Error('no offer') const { offer } = step.error const context = { t, locale: 'fr' as const } const refused = (reason: string) => ({ ok: false as const, reason: 'refused' as const, refusal: { ...offer.refusal, reason: reason as never }, }) const { refusedResult } = await import('@/editor/repair') const words = [ 'newly_invalid', 'view_unmeasured', 'changed_unmeasured', ].map((reason) => { const result = refusedResult(refused(reason), context) return result.ok ? '' : (result.general ?? '') }) for (const word of words) { expect(word).not.toBe('') expect(word).not.toMatch(/onglet|Annotations|Vues/) } expect(words[0]).toMatch(/anno-a|N/) }) })