feat(app): editable sheet preview, edit wrappers, cleaning preview and ids

This commit is contained in:
bchanot committed 2026-11-04 11:48:01 +01:00
1 parent 2f824a947c
commit 173be5949a
10 files changed
+663 -13

No files matched your search

@@ -0,0 +1,92 @@
import { beforeAll, describe, expect, it } from 'vitest'
import { setCoreRuntime } from '@/core/runtime'
import { cleanSvg, composeCleaningPreview } from '@/editor/core/cleaning'
import { applyEdit, dependentsOf } from '@/editor/core/editOps'
import { testCoreRuntime } from '../helpers/core'
const DIRTY =
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><style>.a{fill:red}</style>' +
'<defs><linearGradient id="g"><stop offset="0"/></linearGradient></defs>' +
'<rect id="r" class="a" width="4" height="4" fill="url(#g)"/></svg>'
beforeAll(async () => {
setCoreRuntime(await testCoreRuntime())
})
function cleaned() {
const out = cleanSvg(new TextEncoder().encode(DIRTY))
if (!out.ok || out.value.stored === null || out.value.sha256 === null) {
throw new Error('not cleanable')
}
return {
cleaning: out.value,
drawing: { stored: out.value.stored, sha256: out.value.sha256 },
}
}
describe('cleanSvg', () => {
it('reports a removal and a stored form without the handler', () => {
const { cleaning } = cleaned()
expect(cleaning.outcome).toBe('cleanable')
expect(cleaning.style_removed).toBe(true)
expect(cleaning.stored).not.toContain('<style')
})
it('rejects bytes that are not an SVG', () => {
const out = cleanSvg(new TextEncoder().encode('nope'))
expect(out).toMatchObject({ ok: true, value: { outcome: 'rejected' } })
const active = cleanSvg(
new TextEncoder().encode(
'<svg xmlns="http://www.w3.org/2000/svg"><rect onclick="x()"/></svg>',
),
)
expect(active).toMatchObject({
ok: true,
value: { reason: 'svg_active_content' },
})
})
})
describe('composeCleaningPreview', () => {
it('renders the stored drawing in a scope unique per preview and never the original', () => {
const { drawing } = cleaned()
const a = composeCleaningPreview(drawing)
const b = composeCleaningPreview(drawing)
if (!a.ok || !b.ok) throw new Error('compose failed')
expect(a.value.scope).toMatch(/^fv\.view-[a-z2-7]{10}\.$/)
expect(a.value.scope).not.toBe(b.value.scope)
const svg = a.value.preview.canvas(a.value.viewId)
if (!svg.ok) throw new Error(svg.kind)
expect(svg.value).toContain(`id="${a.value.scope}r"`)
expect(svg.value).not.toContain('<style')
a.value.preview.free()
b.value.preview.free()
expect(a.value.preview.canvas(a.value.viewId)).toMatchObject({
ok: false,
kind: 'core_unavailable',
})
})
})
describe('edit wrappers', () => {
it('refuses a remove of an unknown element with the core kind', () => {
const text = JSON.stringify(
(() => {
const p = composeCleaningPreview(cleaned().drawing)
if (!p.ok) throw new Error(p.kind)
const document = JSON.parse(p.value.preview.document)
p.value.preview.free()
return document
})(),
)
expect(
applyEdit(text, {
op: 'remove',
key: { kind: 'annotation', id: 'anno-none' },
}).ok,
).toBe(false)
expect(dependentsOf(text, { kind: 'view', id: 'view-main' })).toMatchObject(
{ ok: true },
)
})
})
@@ -0,0 +1,51 @@
import { describe, expect, it } from 'vitest'
import { newElementId } from '@/editor/ids'
import { sameDocument } from '@/editor/core/sameDocument'
describe('newElementId', () => {
it('is the prefix and ten characters of a-z2-7', () => {
for (const prefix of [
'view',
'anno',
'cat',
'ref',
'zone',
'fcat',
'node',
] as const) {
expect(newElementId(prefix)).toMatch(
new RegExp(`^${prefix}-[a-z2-7]{10}$`),
)
}
})
it('does not repeat in a thousand draws', () => {
const ids = new Set(
Array.from({ length: 1000 }, () => newElementId('anno')),
)
expect(ids.size).toBe(1000)
})
})
describe('sameDocument', () => {
it('ignores key order at any depth', () => {
expect(
sameDocument(
'{"a":1,"b":{"c":[1,2],"d":null}}',
'{"b":{"d":null,"c":[1,2]},"a":1}',
),
).toBe(true)
})
it('keeps array order and values significant', () => {
expect(sameDocument('{"a":[1,2]}', '{"a":[2,1]}')).toBe(false)
expect(sameDocument('{"a":1}', '{"a":1,"b":null}')).toBe(false)
expect(sameDocument('{"a":1}', '{"a":"1"}')).toBe(false)
expect(sameDocument('[]', '{}')).toBe(false)
})
it('compares a non-JSON text as a string', () => {
expect(sameDocument('x', 'x')).toBe(true)
expect(sameDocument('x', '{}')).toBe(false)
})
})
+205
View File
@@ -0,0 +1,205 @@
/**
* Lot C: the editable preview handle. A text or drawing is kept (for a rebuild after a trap
* or a generation change) only once the core accepted it.
*/
import { beforeAll, describe, expect, it } from 'vitest'
import type { CoreRuntime } from '@faunosteo/core-wasm'
import { CataloguePreview } from '@/catalogue/preview'
import { setCoreRuntime } from '@/core/runtime'
import { cleanSvg } from '@/editor/core/cleaning'
import { applyEdit } from '@/editor/core/editOps'
import { emptySheetDocument } from '@/core/sheetDocumentOps'
import { testCoreRuntime } from '../helpers/core'
const SVG =
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><rect width="4" height="4"/></svg>'
let runtime: CoreRuntime
beforeAll(async () => {
runtime = await testCoreRuntime()
setCoreRuntime(runtime)
})
function baseText(): string {
const empty = emptySheetDocument({
speciesId: 'equine',
name: { fr: 'Fiche', en: 'Sheet' },
})
if (!empty.ok) throw new Error(empty.kind)
return JSON.stringify(empty.value)
}
function renamed(text: string, name: string): string {
const document = JSON.parse(text)
document.name = { fr: name, en: name }
return JSON.stringify(document)
}
function withDetail(text: string, viewId: string, assetId: string): string {
const edited = applyEdit(text, {
op: 'insert',
element: {
kind: 'view',
value: {
kind: 'detail',
id: viewId,
name: { fr: 'D', en: 'D' },
svg_asset_id: assetId,
view_box: null,
parent_view_id: 'view-main',
},
},
})
if (!edited.ok) throw new Error(edited.kind)
return edited.value
}
function drawing(assetId: string, extra = '') {
const cleaned = cleanSvg(new TextEncoder().encode(SVG + extra))
if (!cleaned.ok || !cleaned.value.stored || !cleaned.value.sha256)
throw new Error('uncleanable')
const bytes = new TextEncoder().encode(cleaned.value.stored)
return { assetId, sha256: cleaned.value.sha256, bytes }
}
function draft(text = baseText()) {
return new CataloguePreview(runtime, { status: 'draft', document: text }, [])
}
function stateOf(preview: CataloguePreview) {
const state = preview.state()
if (!state.ok) throw new Error(state.kind)
return state.value
}
/** The next call finds a handle of an older generation and rebuilds from the kept input. */
function forceRebuild() {
runtime.generation += 1
}
describe('CataloguePreview editing', () => {
it('rebuilds with the replaced text and the added drawing', () => {
const asset = '11111111-1111-4111-8111-111111111111'
const preview = draft()
const text = withDetail(
renamed(baseText(), 'Nouveau'),
'view-aaaaaaaaaa',
asset,
)
expect(preview.replaceDocument(text).ok).toBe(true)
expect(preview.addDrawing(drawing(asset)).ok).toBe(true)
forceRebuild()
const state = stateOf(preview)
expect(state.document.name.fr).toBe('Nouveau')
expect(state.drawings).toMatchObject([{ asset_id: asset, state: 'ok' }])
expect(preview.canvas('view-aaaaaaaaaa').ok).toBe(true)
preview.free()
})
it('does not keep a refused text', () => {
const preview = draft()
const before = preview.document
const outcome = preview.replaceDocument('{"not":"a document"}')
expect(outcome).toMatchObject({ ok: false, reason: 'core' })
expect(preview.document).toBe(before)
forceRebuild()
expect(stateOf(preview).document.name.fr).toBe('Fiche')
preview.free()
})
it('refuses a bad drawing alone and keeps the good one', () => {
const good = '22222222-2222-4222-8222-222222222222'
const bad = '33333333-3333-4333-8333-333333333333'
const preview = draft(withDetail(baseText(), 'view-bbbbbbbbbb', good))
expect(preview.addDrawing(drawing(good)).ok).toBe(true)
const wrong = { ...drawing(bad), sha256: 'a'.repeat(64) }
expect(preview.addDrawing(wrong)).toMatchObject({
ok: false,
kind: 'drawing_hash_mismatch',
})
forceRebuild()
expect(stateOf(preview).drawings).toMatchObject([
{ asset_id: good, state: 'ok' },
])
preview.free()
})
it('replaces a re-added drawing and caps the count at 16', () => {
const preview = draft()
for (let i = 0; i < 16; i += 1) {
expect(preview.addDrawing(drawing(`id-${i}`)).ok).toBe(true)
}
expect(preview.addDrawing(drawing('id-16'))).toMatchObject({
ok: false,
kind: 'caps',
})
expect(preview.addDrawing(drawing('id-0', '\n')).ok).toBe(true)
forceRebuild()
expect(preview.state().ok).toBe(true)
preview.free()
})
})
describe('replaceDocument accept hook', () => {
it('rolls back and keeps everything when accept refuses', () => {
const preview = draft()
const before = stateOf(preview)
const outcome = preview.replaceDocument(
renamed(preview.document, 'Refusé'),
() => ({
accepted: false,
refusal: 'nope',
}),
)
expect(outcome).toEqual({ ok: false, reason: 'refused', refusal: 'nope' })
expect(stateOf(preview)).toEqual(before)
forceRebuild()
expect(stateOf(preview)).toEqual(before)
preview.free()
})
it('keeps the candidate when accept agrees, and hands it the candidate state', () => {
const preview = draft()
const seen: string[] = []
const outcome = preview.replaceDocument(
renamed(preview.document, 'Gardé'),
(state) => {
seen.push(state.document.name.fr)
return { accepted: true }
},
)
expect(outcome.ok).toBe(true)
expect(seen).toEqual(['Gardé'])
forceRebuild()
expect(stateOf(preview).document.name.fr).toBe('Gardé')
preview.free()
})
it('rolls back when state fails without a trap', () => {
const preview = draft()
const before = stateOf(preview)
const handle = (
preview as unknown as { handle: { call(op: string, i: string): string } }
).handle
const real = handle.call.bind(handle)
let failed = false
handle.call = (op, input) => {
if (op === 'preview.state' && !failed) {
failed = true
return '{"ok":false,"kind":"invalid_shape"}'
}
return real(op, input)
}
const outcome = preview.replaceDocument(renamed(preview.document, 'Perdu'))
expect(outcome).toMatchObject({
ok: false,
reason: 'core',
failure: { kind: 'invalid_shape' },
})
expect(stateOf(preview)).toEqual(before)
forceRebuild()
expect(stateOf(preview)).toEqual(before)
preview.free()
})
})