Files
faunosteo/apps/app/tests/unit/editor-annotations-commit.test.ts
T

373 lines
12 KiB
TypeScript

/**
* Lot H: every geometry commit goes through the store under the geometry `accept` (C26,
* C32, C33): proof on the Node core that no page action leaves an annotation with a
* geometry error it did not already have, and that an invalid one can be repaired.
*/
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { Annotation, Geometry, ViewBox } from '@faunosteo/core-wasm/types'
import {
insertAnnotation,
updateGeometry,
type CommitContext,
} from '@/editor/annotations/annotationCommit'
import { translatedGeometry } from '@/editor/annotations/gesture'
import {
geometryAccept,
geometryErrorsById,
unmeasuredViews,
} from '@/editor/issues'
import {
ASSET,
drawnText,
insert,
point,
svgBytes,
} from '../helpers/editorFixtures'
import {
USER,
VERSION,
openReady,
resetStore,
sb,
store,
versionAnswer,
} 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 context: CommitContext = { t: (key) => key, locale: 'fr' }
afterEach(resetStore)
const state = () => store.getState().previewState!
const annotation = (id: string): Annotation => {
const found = state().document.annotations.find((a) => a.id === id)
if (!found) throw new Error(`no ${id}`)
return found
}
const errors = () => geometryErrorsById(state())
const circle = (cx: number, cy: number, r: number): Geometry => ({
type: 'circle',
cx,
cy,
r,
})
const asAnnotation = (element: ReturnType<typeof point>) =>
element.value as Annotation
function zoneText(id: string, geometry: Geometry, base = drawnText()): string {
const value = {
...asAnnotation(point(id, 0, 0, 1)),
kind: 'zone',
geometry,
} as Annotation
return insert(base, { kind: 'annotation', value })
}
/** Opens a draft whose main drawing has `viewBox`, or none (a missing drawing). */
async function openWith(text: string, viewBox: string | null): Promise<void> {
const drawing = svgBytes(viewBox ?? '0 0 100 100')
const answer = versionAnswer(text, 3, viewBox !== null)
sb.getSheetVersion.mockResolvedValue({
...answer,
drawings:
viewBox === null ? [] : [{ asset_id: ASSET, sha256: drawing.sha256 }],
} as never)
sb.downloadSheetDrawing.mockResolvedValue(drawing.bytes)
store.getState().open(VERSION, USER, { canEdit: true })
await vi.waitFor(() => expect(store.getState().status).not.toBe('loading'))
}
describe('a new point (C26)', () => {
it('is refused out of frame, the store and the handle unchanged', async () => {
await openReady({ text: drawnText() })
const version = store.getState().handleVersion
const result = insertAnnotation(
(id) => asAnnotation(point(id, 150, 50, 5)),
context,
)
expect(result).toMatchObject({
ok: false,
codes: ['annotation.geometry.out_of_frame'],
})
expect(store.getState().handleVersion).toBe(version)
expect(store.getState().documentText).toBe(drawnText())
expect(store.getState().unsaved).toBe(false)
})
it('is kept when valid, with no geometry error', async () => {
await openReady({ text: drawnText() })
expect(
insertAnnotation((id) => asAnnotation(point(id, 50, 50, 5)), context),
).toMatchObject({ ok: true })
expect(state().document.annotations).toHaveLength(1)
expect(errors().size).toBe(0)
})
})
describe('a move or a typed value on a valid point', () => {
const open = () =>
openReady({ text: insert(drawnText(), point('anno-a', 50, 50, 5)) })
it('rolls back a drag that drops it half out of the frame', async () => {
await open()
const before = store.getState().documentText
const dropped = translatedGeometry(circle(50, 50, 5), { x: 48, y: 0 })!
const result = updateGeometry(annotation('anno-a'), dropped, context)
expect(result).toMatchObject({
ok: false,
codes: ['annotation.geometry.out_of_frame'],
})
expect(store.getState().documentText).toBe(before)
expect(errors().size).toBe(0)
})
it('commits a drag that stays inside, rounded to two decimals', async () => {
await open()
const moved = translatedGeometry(circle(50, 50, 5), {
x: 10.004,
y: -3.333,
})!
expect(updateGeometry(annotation('anno-a'), moved, context)).toEqual({
ok: true,
})
expect(annotation('anno-a').geometry).toEqual(circle(60, 46.67, 5))
})
it('refuses a typed radius the core reports too_small', async () => {
await openWith(
insert(drawnText(), point('anno-a', 2500, 2500, 400)),
'0 0 5000 5000',
)
expect(errors().size).toBe(0)
const result = updateGeometry(
annotation('anno-a'),
circle(2500, 2500, 1),
context,
)
expect(result).toMatchObject({
ok: false,
codes: ['annotation.geometry.too_small'],
})
expect(annotation('anno-a').geometry).toEqual(circle(2500, 2500, 400))
})
})
describe('repairing an annotation that is already invalid (C33)', () => {
it('refuses cx alone, keeps the error visible, applies the coherent set', async () => {
await openReady({ text: insert(drawnText(), point('anno-a', 150, 150, 5)) })
expect(errors().has('anno-a')).toBe(true)
const before = store.getState().documentText
const half = updateGeometry(
annotation('anno-a'),
circle(50, 150, 5),
context,
)
expect(half).toMatchObject({
ok: false,
codes: ['annotation.geometry.out_of_frame'],
})
expect(store.getState().documentText).toBe(before)
expect(errors().has('anno-a')).toBe(true)
expect(
updateGeometry(annotation('anno-a'), circle(50, 50, 5), context),
).toEqual({ ok: true })
expect(errors().size).toBe(0)
})
it('repairs a polygon the same way, one vertex then the whole set', async () => {
const bad: Geometry = {
type: 'polygon',
points: [
[150, 150],
[190, 150],
[170, 190],
],
}
await openReady({ text: zoneText('zone-a', bad) })
expect(errors().has('zone-a')).toBe(true)
const partial: Geometry = {
type: 'polygon',
points: [
[20, 20],
[190, 150],
[170, 190],
],
}
expect(updateGeometry(annotation('zone-a'), partial, context).ok).toBe(
false,
)
const whole: Geometry = {
type: 'polygon',
points: [
[20, 20],
[80, 20],
[50, 80],
],
}
expect(updateGeometry(annotation('zone-a'), whole, context)).toEqual({
ok: true,
})
expect(errors().size).toBe(0)
})
it('repairs an invalid point that came back from a restored copy', async () => {
const invalid = JSON.parse(insert(drawnText(), point('anno-a', 150, 50, 5)))
sessionStorage.setItem(
`osteo:sheet-draft:${USER}:${VERSION}`,
JSON.stringify({
v: 1,
user_id: USER,
version_id: VERSION,
sheet_id: 'sheet-1',
sheet_name: 'Fiche',
revision: 3,
written_at: '2026-11-03T10:00:00Z',
document: invalid,
drawings: [{ asset_id: ASSET, sha256: svgBytes().sha256 }],
}),
)
await openReady({
text: insert(drawnText(), point('anno-a', 50, 50, 5)),
revision: 3,
})
expect(await store.getState().restoreCopy()).toEqual({ ok: true })
expect(errors().has('anno-a')).toBe(true)
expect(
updateGeometry(annotation('anno-a'), circle(50, 50, 5), context),
).toEqual({ ok: true })
expect(errors().size).toBe(0)
})
it('refuses a drop that leaves an already-invalid point invalid', async () => {
await openReady({ text: insert(drawnText(), point('anno-a', 150, 50, 5)) })
const result = updateGeometry(
annotation('anno-a'),
circle(140, 50, 5),
context,
)
expect(result.ok).toBe(false)
expect(annotation('anno-a').geometry).toEqual(circle(150, 50, 5))
})
})
describe('a frame change (rule 7)', () => {
const crop = (box: ViewBox) => {
const main = state().document.views.find((v) => v.kind === 'main')!
const command = {
op: 'update' as const,
key: { kind: 'view' as const, id: main.id },
element: { kind: 'view' as const, value: { ...main, view_box: box } },
}
const accept = geometryAccept({ before: state(), changedIds: [] })
return store.getState().commit(command, { accept })
}
it('is refused when it pushes a valid point out of the frame', async () => {
await openReady({ text: insert(drawnText(), point('anno-a', 50, 50, 5)) })
const before = store.getState().documentText
expect(crop({ min_x: 0, min_y: 0, width: 40, height: 40 }).ok).toBe(false)
expect(store.getState().documentText).toBe(before)
})
it('is refused when it makes a point too_small, nothing kept', async () => {
await openWith(
insert(drawnText(), point('anno-a', 2500, 2500, 400)),
'0 0 5000 5000',
)
const before = store.getState().documentText
const outcome = crop({ min_x: 0, min_y: 0, width: 200000, height: 200000 })
expect(outcome).toMatchObject({ ok: false, reason: 'refused' })
if (outcome.ok || outcome.reason !== 'refused')
throw new Error('not refused')
expect(outcome.refusal.issues.map((i) => i.code)).toContain(
'annotation.geometry.too_small',
)
expect(store.getState().documentText).toBe(before)
})
it('is accepted when only an already-invalid point is affected', async () => {
await openReady({ text: insert(drawnText(), point('anno-a', 150, 50, 5)) })
expect(crop({ min_x: 0, min_y: 0, width: 80, height: 80 }).ok).toBe(true)
})
})
describe('an unmeasured view (C32)', () => {
const valid = () => insert(drawnText(), point('anno-a', 50, 50, 5))
it('refuses a creation and a move when the drawing is missing', async () => {
await openWith(valid(), null)
expect(unmeasuredViews(state()).has('view-main')).toBe(true)
const created = insertAnnotation(
(id) => asAnnotation(point(id, 40, 40, 5)),
context,
)
expect(created).toEqual({
ok: false,
messages: ['editor.annotations.unmeasured.hint'],
codes: [],
})
const moved = updateGeometry(
annotation('anno-a'),
circle(60, 50, 5),
context,
)
expect(moved.ok).toBe(false)
expect(annotation('anno-a').geometry).toEqual(circle(50, 50, 5))
})
it('refuses them on a crop of span 0.5', async () => {
const view = {
kind: 'view' as const,
value: {
kind: 'detail' as const,
id: 'view-det',
name: { fr: 'D', en: 'D' },
svg_asset_id: null,
view_box: { min_x: 0, min_y: 0, width: 0.5, height: 0.5 },
parent_view_id: 'view-main',
},
}
await openReady({ text: insert(drawnText(), view) })
expect(unmeasuredViews(state()).has('view-det')).toBe(true)
const created = insertAnnotation(
(id) => asAnnotation(point(id, 0.25, 0.25, 0.1, 'view-det')),
context,
)
expect(created.ok).toBe(false)
expect(state().document.annotations).toHaveLength(0)
})
it('refuses them on a drawing without viewBox', async () => {
const bare =
'<svg xmlns="http://www.w3.org/2000/svg"><rect width="4" height="4"/></svg>'
const { cleanSvg } = await import('@/editor/core/cleaning')
const cleaned = cleanSvg(new TextEncoder().encode(bare))
if (!cleaned.ok || !cleaned.value.stored || !cleaned.value.sha256)
throw new Error('svg')
sb.getSheetVersion.mockResolvedValue({
...versionAnswer(valid(), 3),
drawings: [{ asset_id: ASSET, sha256: cleaned.value.sha256 }],
} as never)
sb.downloadSheetDrawing.mockResolvedValue(
new TextEncoder().encode(cleaned.value.stored),
)
store.getState().open(VERSION, USER, { canEdit: true })
await vi.waitFor(() => expect(store.getState().status).not.toBe('loading'))
expect(unmeasuredViews(state()).has('view-main')).toBe(true)
const moved = updateGeometry(
annotation('anno-a'),
circle(60, 50, 5),
context,
)
expect(moved.ok).toBe(false)
})
})