feat(editor): repair out-of-frame annotations when attaching a drawing

This commit is contained in:
bchanot committed 2026-11-04 20:10:07 +01:00
1 parent 4ab85adeb0
commit 3776a33b79
22 files changed
+1277 -19

No files matched your search

+157
View File
@@ -0,0 +1,157 @@
/** Lot N3: one atomic batch of edit commands (R23), on the Node core. */
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { EditCommand } from '@faunosteo/core-wasm/types'
import {
ASSET,
emptyText,
insert,
point,
svgBytes,
} from '../helpers/editorFixtures'
import {
openReady,
resetStore,
serverHas,
storedCopy,
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(),
}))
afterEach(resetStore)
/** An unmeasured main view (no drawing) holding one point at (500, 400). */
function unmeasuredText(): string {
const withCategory = insert(emptyText(), {
kind: 'category',
value: { id: 'cat-a', name: { fr: 'N', en: 'N' }, color: null },
})
return insert(withCategory, point('anno-a', 500, 400, 5))
}
async function openUnmeasured() {
await openReady({ text: unmeasuredText() })
serverHas(unmeasuredText(), 3, false)
const drawing = svgBytes('0 0 100 100')
const held = store
.getState()
.addDrawing({
assetId: ASSET,
sha256: drawing.sha256,
bytes: drawing.bytes,
})
expect(held).toEqual({ ok: true })
}
const doc = () => JSON.parse(store.getState().documentText)
const attachCommand = (): EditCommand => ({
op: 'update',
key: { kind: 'view', id: 'view-main' },
element: {
kind: 'view',
value: { ...doc().views[0], svg_asset_id: ASSET },
},
})
const moved = (cx: number): EditCommand => ({
op: 'update',
key: { kind: 'annotation', id: 'anno-a' },
element: point('anno-a', cx, 50, 5),
})
describe('commitBatch', () => {
it('applies the commands in order and commits once: one undo entry, one copy write', async () => {
await openUnmeasured()
const before = store.getState()
const outcome = store.getState().commitBatch([attachCommand(), moved(50)])
expect(outcome).toEqual({ ok: true })
const after = store.getState()
expect(doc().views[0].svg_asset_id).toBe(ASSET)
expect(doc().annotations[0].geometry.cx).toBe(50)
expect(after.undo).toHaveLength(1)
expect(after.handleVersion).toBe(before.handleVersion + 1)
expect(storedCopy()).not.toBeNull()
})
it('restores both the view and the geometry with one undo', async () => {
await openUnmeasured()
const text = store.getState().documentText
store.getState().commitBatch([attachCommand(), moved(50)])
expect(store.getState().undoStep()).toEqual({ ok: true })
expect(store.getState().documentText).toBe(text)
})
it('keeps nothing when one command is refused by sheet.edit', async () => {
await openUnmeasured()
const before = store.getState()
const missing: EditCommand = {
op: 'remove',
key: { kind: 'annotation', id: 'nope' },
}
const outcome = store.getState().commitBatch([attachCommand(), missing])
expect(outcome).toMatchObject({ ok: false, reason: 'core' })
const after = store.getState()
expect(after.documentText).toBe(before.documentText)
expect(after.handleVersion).toBe(before.handleVersion)
expect(after.undo).toHaveLength(0)
expect(storedCopy()).toBeNull()
})
it('keeps nothing when accept refuses the end state', async () => {
await openUnmeasured()
const before = store.getState()
const outcome = store.getState().commitBatch([attachCommand(), moved(50)], {
accept: () => ({ accepted: false, refusal: 'no' as const }),
})
expect(outcome).toEqual({ ok: false, reason: 'refused', refusal: 'no' })
const after = store.getState()
expect(after.documentText).toBe(before.documentText)
expect(after.undo).toHaveLength(0)
expect(after.preview?.document).toBe(before.documentText)
})
it('hands accept the END state only, never an intermediate one', async () => {
await openUnmeasured()
const accept = vi.fn(() => ({ accepted: true as const }))
store.getState().commitBatch([attachCommand(), moved(50)], { accept })
expect(accept).toHaveBeenCalledTimes(1)
const [state] = accept.mock.calls[0] as unknown as [
{ document: { annotations: { geometry: { cx: number } }[] } },
]
expect(state.document.annotations[0].geometry.cx).toBe(50)
})
it('is blocked while a recovery offer is pending and when read-only', async () => {
await openUnmeasured()
store.setState({ recovery: 'pending' })
expect(store.getState().commitBatch([attachCommand()])).toMatchObject({
ok: false,
reason: 'blocked',
kind: 'recovery.pending',
})
store.setState({ recovery: 'none', canEdit: false })
expect(store.getState().commitBatch([attachCommand()])).toMatchObject({
ok: false,
reason: 'blocked',
kind: 'read_only',
})
expect(store.getState().undo).toHaveLength(0)
})
it('refuses an empty batch without touching the document', async () => {
await openUnmeasured()
expect(store.getState().commitBatch([])).toMatchObject({
ok: false,
reason: 'blocked',
kind: 'empty',
})
})
})
@@ -6,6 +6,7 @@ import type {
AnatomicalSheetDocument,
FindingNode,
} from '@faunosteo/core-wasm/types'
import FindingCreateForm from '@/components/editor/findings/FindingCreateForm'
import FindingsTab from '@/components/editor/tabs/FindingsTab'
import { buildItems, keyMove, visibleItems } from '@/editor/findings/tree'
import { useLocaleStore } from '@/state/localeStore'
@@ -527,3 +528,36 @@ describe('Constats tab', () => {
expect(items()[0]).toHaveFocus()
})
})
describe('the category form title (N1 review)', () => {
const parentOf = (id: string) => {
const found = buildItems(doc()).find((item) => item.id.includes(`"${id}"`) && item.path.at(-1) === id || item.zoneId === id && item.kind === 'zone')
if (!found) throw new Error(`no ${id}`)
return found
}
const title = (parent: ReturnType<typeof parentOf> | null) => {
render(
<FindingCreateForm
pending={{ kind: 'category', parent }}
onCreated={vi.fn()}
onCancel={vi.fn()}
/>,
)
return document.querySelector('p.font-medium')?.textContent
}
it.each(['zone-a', 'fcat-a', 'node-a'])(
'names the zone when the parent is %s',
async (id) => {
await openReady({ text: treeText() })
expect(title(parentOf(id))).toBe(
'Nouvelle catégorie dans la zone « Zone A »',
)
},
)
it('falls back to an existing label, never a missing key, without a parent', async () => {
await openReady({ text: treeText() })
expect(title(null)).toBe('Ajouter une catégorie')
})
})
+393
View File
@@ -0,0 +1,393 @@
/** 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 ViewsTab from '@/components/editor/tabs/ViewsTab'
import { cleanSvg } from '@/editor/core/cleaning'
import { attachToView } from '@/editor/drawingUpload'
import {
applyRepair,
polygonReplacement,
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<typeof import('@faunosteo/supabase')>()),
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, onSelectTab: 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<typeof zone>['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('leaves a path to the conversion, which offers a triangle in the frame', () => {
const path: Geometry = { type: 'path', d: 'M 1 1 L 5 5 Z' }
expect(proposeGeometry(frame, path)).toBe(path)
expect(polygonReplacement(frame)).toMatchObject({
type: 'polygon',
points: expect.arrayContaining([expect.any(Array)]),
})
})
})
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<typeof offerOf>) => ({
'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('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 =
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><rect width="4" height="4"/></svg>'
async function pickAndOpenDialog(text = unmeasuredText()) {
await openReady({ text })
serverGets(SVG)
render(<ViewsTab {...props} />)
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 path until it is replaced by a polygon, inside the same form', async () => {
const pathValue = {
...(point('anno-p', 0, 0, 1).value as Annotation),
kind: 'zone' as const,
geometry: { type: 'path' as const, d: 'M 300 300 L 400 300 L 350 400 Z' },
} as Annotation
const { user, dialog } = await pickAndOpenDialog(
unmeasuredText([pathValue]),
)
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()
await user.click(
within(row).getByRole('button', {
name: t('editor.annotations.replace_polygon'),
}),
)
expect(apply).toBeEnabled()
await user.click(apply)
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(annotation('anno-p').geometry).toMatchObject({ type: 'polygon' })
})
})