feat(app): editable sheet preview, edit wrappers, cleaning preview and ids
This commit is contained in:
1 parent
2f824a947c
commit
173be5949a
10 files changed
+663
-13
No files matched your search
@@ -2,6 +2,7 @@ import {
|
|||||||
CORE_UNAVAILABLE,
|
CORE_UNAVAILABLE,
|
||||||
closedRefusal,
|
closedRefusal,
|
||||||
parseOutcome,
|
parseOutcome,
|
||||||
|
type CoreFailure,
|
||||||
type CoreOutcome,
|
type CoreOutcome,
|
||||||
type CoreRuntime,
|
type CoreRuntime,
|
||||||
type GluePreviewSheet,
|
type GluePreviewSheet,
|
||||||
@@ -19,6 +20,24 @@ export interface PreviewDrawing {
|
|||||||
bytes: Uint8Array
|
bytes: Uint8Array
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** What `accept` answers about the candidate state: kept, or a refusal the caller shows. */
|
||||||
|
export type Acceptance<R> = { accepted: true } | { accepted: false; refusal: R }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `replaceDocument`'s answer. Only `ok: true` tells the caller to bump its handle counter;
|
||||||
|
* a `core` failure carries the closed kind, a `refused` one the caller's own refusal.
|
||||||
|
*/
|
||||||
|
export type ReplaceOutcome<R> =
|
||||||
|
| { ok: true; state: PreviewState }
|
||||||
|
| { ok: false; reason: 'core'; failure: CoreFailure }
|
||||||
|
| { ok: false; reason: 'refused'; refusal: R }
|
||||||
|
|
||||||
|
/** A trap or a stopped module: no handle to roll back, the rebuild uses the kept input. */
|
||||||
|
const TRAPPED_KINDS: ReadonlySet<string> = new Set([
|
||||||
|
'internal',
|
||||||
|
'core_unavailable',
|
||||||
|
])
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A stored version loaded into the core (`PreviewSheet`, RUST.md §12): the
|
* A stored version loaded into the core (`PreviewSheet`, RUST.md §12): the
|
||||||
* core checks each drawing's sha256 against its row, the fingerprint, the caps
|
* core checks each drawing's sha256 against its row, the fingerprint, the caps
|
||||||
@@ -27,17 +46,74 @@ export interface PreviewDrawing {
|
|||||||
* the module: after a trap and a recovery it is rebuilt from the kept input,
|
* the module: after a trap and a recovery it is rebuilt from the kept input,
|
||||||
* a handle of a dropped instance is never called. `free` releases it when the
|
* a handle of a dropped instance is never called. `free` releases it when the
|
||||||
* page leaves.
|
* page leaves.
|
||||||
|
*
|
||||||
|
* A draft's handle is editable: `replaceDocument` and `addDrawing` keep a new
|
||||||
|
* text or drawing only once the core accepted it, so a rebuild after a trap
|
||||||
|
* starts from the last accepted text and drawings (a text that trapped is
|
||||||
|
* never kept, LRN-058).
|
||||||
*/
|
*/
|
||||||
export class CataloguePreview {
|
export class CataloguePreview {
|
||||||
private handle: GluePreviewSheet | null = null
|
private handle: GluePreviewSheet | null = null
|
||||||
private handleGeneration = -1
|
private handleGeneration = -1
|
||||||
private freed = false
|
private freed = false
|
||||||
|
private readonly drawings = new Map<string, PreviewDrawing>()
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly runtime: CoreRuntime,
|
private readonly runtime: CoreRuntime,
|
||||||
private readonly input: PreviewInput,
|
private input: PreviewInput,
|
||||||
private readonly drawings: readonly PreviewDrawing[],
|
drawings: readonly PreviewDrawing[],
|
||||||
) {}
|
) {
|
||||||
|
for (const drawing of drawings) this.drawings.set(drawing.assetId, drawing)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The last accepted document text (what a rebuild would load). */
|
||||||
|
get document(): string {
|
||||||
|
return this.input.document
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replaces the draft's document. The new text becomes the kept input only when
|
||||||
|
* `replace_document`, `preview.state` and `accept(state)` all succeed; otherwise the
|
||||||
|
* handle returns to the previous text and the kept input and drawings stay as they were.
|
||||||
|
*/
|
||||||
|
replaceDocument<R = never>(
|
||||||
|
text: string,
|
||||||
|
accept?: (state: PreviewState) => Acceptance<R>,
|
||||||
|
): ReplaceOutcome<R> {
|
||||||
|
const previous = this.input.document
|
||||||
|
const handle = this.current()
|
||||||
|
if (!handle.ok) return { ok: false, reason: 'core', failure: handle }
|
||||||
|
const replaced = this.runtime.invoke(() =>
|
||||||
|
parseOutcome<null>(handle.value.replace_document(text)),
|
||||||
|
)
|
||||||
|
if (!replaced.ok) return { ok: false, reason: 'core', failure: replaced }
|
||||||
|
const outcome = this.judge(accept)
|
||||||
|
if (outcome.ok) this.input = { ...this.input, document: text }
|
||||||
|
else if (
|
||||||
|
outcome.reason === 'refused' ||
|
||||||
|
!TRAPPED_KINDS.has(outcome.failure.kind)
|
||||||
|
) {
|
||||||
|
this.rollback(previous)
|
||||||
|
}
|
||||||
|
return outcome
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Adds or replaces a drawing; kept (for a rebuild) only when the core accepted it. */
|
||||||
|
addDrawing(drawing: PreviewDrawing): CoreOutcome<null> {
|
||||||
|
const handle = this.current()
|
||||||
|
if (!handle.ok) return handle
|
||||||
|
const added = this.runtime.invoke(() =>
|
||||||
|
parseOutcome<null>(
|
||||||
|
handle.value.add_drawing(
|
||||||
|
drawing.assetId,
|
||||||
|
drawing.sha256,
|
||||||
|
drawing.bytes,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
if (added.ok) this.drawings.set(drawing.assetId, drawing)
|
||||||
|
return added
|
||||||
|
}
|
||||||
|
|
||||||
/** The first call builds the handle: the builder's refusals come back as closed kinds. */
|
/** The first call builds the handle: the builder's refusals come back as closed kinds. */
|
||||||
state(): CoreOutcome<PreviewState> {
|
state(): CoreOutcome<PreviewState> {
|
||||||
@@ -53,6 +129,32 @@ export class CataloguePreview {
|
|||||||
/** After this, every call answers `core_unavailable`: a page that left never rebuilds. */
|
/** After this, every call answers `core_unavailable`: a page that left never rebuilds. */
|
||||||
free(): void {
|
free(): void {
|
||||||
this.freed = true
|
this.freed = true
|
||||||
|
this.discardHandle()
|
||||||
|
}
|
||||||
|
|
||||||
|
private judge<R>(
|
||||||
|
accept: ((state: PreviewState) => Acceptance<R>) | undefined,
|
||||||
|
): ReplaceOutcome<R> {
|
||||||
|
const state = this.state()
|
||||||
|
if (!state.ok) return { ok: false, reason: 'core', failure: state }
|
||||||
|
const verdict = accept?.(state.value) ?? { accepted: true }
|
||||||
|
return verdict.accepted
|
||||||
|
? { ok: true, state: state.value }
|
||||||
|
: { ok: false, reason: 'refused', refusal: verdict.refusal }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Puts the handle back on the kept text; if even that fails the handle is dropped and rebuilt. */
|
||||||
|
private rollback(previous: string): void {
|
||||||
|
const handle = this.current()
|
||||||
|
const restored = handle.ok
|
||||||
|
? this.runtime.invoke(() =>
|
||||||
|
parseOutcome<null>(handle.value.replace_document(previous)),
|
||||||
|
)
|
||||||
|
: handle
|
||||||
|
if (!restored.ok) this.discardHandle()
|
||||||
|
}
|
||||||
|
|
||||||
|
private discardHandle(): void {
|
||||||
const handle = this.handle
|
const handle = this.handle
|
||||||
this.handle = null
|
this.handle = null
|
||||||
if (!handle || this.handleGeneration !== this.runtime.generation) return
|
if (!handle || this.handleGeneration !== this.runtime.generation) return
|
||||||
@@ -79,7 +181,7 @@ export class CataloguePreview {
|
|||||||
this.handle = null
|
this.handle = null
|
||||||
return this.runtime.invoke<GluePreviewSheet>((glue) => {
|
return this.runtime.invoke<GluePreviewSheet>((glue) => {
|
||||||
const builder = new glue.PreviewBuilder()
|
const builder = new glue.PreviewBuilder()
|
||||||
for (const drawing of this.drawings) {
|
for (const drawing of this.drawings.values()) {
|
||||||
// `false` past the handle's bounds: the build then refuses with `caps`.
|
// `false` past the handle's bounds: the build then refuses with `caps`.
|
||||||
builder.add_drawing(drawing.assetId, drawing.sha256, drawing.bytes)
|
builder.add_drawing(drawing.assetId, drawing.sha256, drawing.bytes)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,14 @@ import {
|
|||||||
type PointerEvent,
|
type PointerEvent,
|
||||||
type RefObject,
|
type RefObject,
|
||||||
} from 'react'
|
} from 'react'
|
||||||
import { FIT, ZOOM_STEP, panBy, zoomBy, type Box, type Framing } from './framing'
|
import {
|
||||||
|
FIT,
|
||||||
|
ZOOM_STEP,
|
||||||
|
panBy,
|
||||||
|
zoomBy,
|
||||||
|
type Box,
|
||||||
|
type Framing,
|
||||||
|
} from './framing'
|
||||||
|
|
||||||
/** Movement past which a press is a drag, not a click on a zone. */
|
/** Movement past which a press is a drag, not a click on a zone. */
|
||||||
const DRAG_THRESHOLD = 4
|
const DRAG_THRESHOLD = 4
|
||||||
@@ -15,7 +22,14 @@ const KEY_PAN = 40
|
|||||||
|
|
||||||
type Point = { x: number; y: number }
|
type Point = { x: number; y: number }
|
||||||
|
|
||||||
function boxOf(element: HTMLElement | null): Box & { left: number; top: number } {
|
export interface FramingOptions {
|
||||||
|
/** Asked on a one-pointer press; false leaves that drag to the caller (a drawing tool). */
|
||||||
|
canPan?: (event: PointerEvent) => boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
function boxOf(
|
||||||
|
element: HTMLElement | null,
|
||||||
|
): Box & { left: number; top: number } {
|
||||||
const rect = element?.getBoundingClientRect()
|
const rect = element?.getBoundingClientRect()
|
||||||
return {
|
return {
|
||||||
width: rect?.width ?? 0,
|
width: rect?.width ?? 0,
|
||||||
@@ -36,13 +50,21 @@ function distance(a: Point, b: Point): number {
|
|||||||
* + and −, 0 fits). `reset` comes back to the whole drawing. A press that
|
* + and −, 0 fits). `reset` comes back to the whole drawing. A press that
|
||||||
* moved is not a click: `swallowClick` says so once.
|
* moved is not a click: `swallowClick` says so once.
|
||||||
*/
|
*/
|
||||||
export function useFraming(viewport: RefObject<HTMLElement | null>, resetKey: string) {
|
export function useFraming(
|
||||||
|
viewport: RefObject<HTMLElement | null>,
|
||||||
|
resetKey: string,
|
||||||
|
options: FramingOptions = {},
|
||||||
|
) {
|
||||||
const [framing, setFraming] = useState<Framing>(FIT)
|
const [framing, setFraming] = useState<Framing>(FIT)
|
||||||
const pointers = useRef(new Map<number, Point>())
|
const pointers = useRef(new Map<number, Point>())
|
||||||
const moved = useRef(0)
|
const moved = useRef(0)
|
||||||
const dragged = useRef(false)
|
const dragged = useRef(false)
|
||||||
// The wheel listener reads the scale without re-subscribing on every change.
|
// The wheel listener reads the scale without re-subscribing on every change.
|
||||||
const scale = useRef(FIT.scale)
|
const scale = useRef(FIT.scale)
|
||||||
|
// The press decision is made once, at pointer-down, and kept for the whole gesture.
|
||||||
|
const panAllowed = useRef(true)
|
||||||
|
const canPan = useRef(options.canPan)
|
||||||
|
canPan.current = options.canPan
|
||||||
|
|
||||||
useEffect(() => setFraming(FIT), [resetKey])
|
useEffect(() => setFraming(FIT), [resetKey])
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -81,10 +103,14 @@ export function useFraming(viewport: RefObject<HTMLElement | null>, resetKey: st
|
|||||||
}, [viewport, zoom])
|
}, [viewport, zoom])
|
||||||
|
|
||||||
const onPointerDown = useCallback((event: PointerEvent) => {
|
const onPointerDown = useCallback((event: PointerEvent) => {
|
||||||
pointers.current.set(event.pointerId, { x: event.clientX, y: event.clientY })
|
pointers.current.set(event.pointerId, {
|
||||||
|
x: event.clientX,
|
||||||
|
y: event.clientY,
|
||||||
|
})
|
||||||
if (pointers.current.size === 1) {
|
if (pointers.current.size === 1) {
|
||||||
moved.current = 0
|
moved.current = 0
|
||||||
dragged.current = false
|
dragged.current = false
|
||||||
|
panAllowed.current = canPan.current?.(event) ?? true
|
||||||
}
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
@@ -93,17 +119,23 @@ export function useFraming(viewport: RefObject<HTMLElement | null>, resetKey: st
|
|||||||
const before = pointers.current.get(event.pointerId)
|
const before = pointers.current.get(event.pointerId)
|
||||||
if (!before) return
|
if (!before) return
|
||||||
const now = { x: event.clientX, y: event.clientY }
|
const now = { x: event.clientX, y: event.clientY }
|
||||||
const others = [...pointers.current].filter(([id]) => id !== event.pointerId)
|
const others = [...pointers.current].filter(
|
||||||
|
([id]) => id !== event.pointerId,
|
||||||
|
)
|
||||||
pointers.current.set(event.pointerId, now)
|
pointers.current.set(event.pointerId, now)
|
||||||
moved.current += distance(before, now)
|
moved.current += distance(before, now)
|
||||||
if (moved.current > DRAG_THRESHOLD) dragged.current = true
|
if (moved.current > DRAG_THRESHOLD) dragged.current = true
|
||||||
if (others.length === 1) {
|
if (others.length === 1) {
|
||||||
const other = others[0][1]
|
const other = others[0][1]
|
||||||
const box = boxOf(viewport.current)
|
const box = boxOf(viewport.current)
|
||||||
const at = { x: (now.x + other.x) / 2 - box.left, y: (now.y + other.y) / 2 - box.top }
|
const at = {
|
||||||
const factor = distance(now, other) / Math.max(distance(before, other), 1)
|
x: (now.x + other.x) / 2 - box.left,
|
||||||
|
y: (now.y + other.y) / 2 - box.top,
|
||||||
|
}
|
||||||
|
const factor =
|
||||||
|
distance(now, other) / Math.max(distance(before, other), 1)
|
||||||
zoom(factor, at)
|
zoom(factor, at)
|
||||||
} else if (others.length === 0 && dragged.current) {
|
} else if (others.length === 0 && dragged.current && panAllowed.current) {
|
||||||
event.currentTarget.setPointerCapture?.(event.pointerId)
|
event.currentTarget.setPointerCapture?.(event.pointerId)
|
||||||
pan(now.x - before.x, now.y - before.y)
|
pan(now.x - before.x, now.y - before.y)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ const ANNOTATED = '[data-anno-id]'
|
|||||||
const ENGINE_KINDS: ReadonlySet<string> = new Set(['core_unavailable', 'internal'])
|
const ENGINE_KINDS: ReadonlySet<string> = new Set(['core_unavailable', 'internal'])
|
||||||
|
|
||||||
/** The core's composed view parsed into the page (`DOMParser` runs no script), or why not. */
|
/** The core's composed view parsed into the page (`DOMParser` runs no script), or why not. */
|
||||||
function buildView(
|
export function buildView(
|
||||||
preview: CataloguePreview,
|
preview: CataloguePreview,
|
||||||
viewId: string,
|
viewId: string,
|
||||||
): { ok: true; svg: Element } | { ok: false; failure: CanvasFailure } {
|
): { ok: true; svg: Element } | { ok: false; failure: CanvasFailure } {
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import { parseOutcome, type CoreOutcome } from '@faunosteo/core-wasm'
|
||||||
|
import type { SvgCleaning } from '@faunosteo/core-wasm/types'
|
||||||
|
import { CataloguePreview } from '@/catalogue/preview'
|
||||||
|
import { coreRuntime } from '@/core/runtime'
|
||||||
|
import { generateUuid } from '@/lib/id'
|
||||||
|
import { newElementId } from '../ids'
|
||||||
|
import { applyEdit } from './editOps'
|
||||||
|
|
||||||
|
/** The cleaning answer for a file picked for upload: clean, cleanable or rejected. */
|
||||||
|
export function cleanSvg(bytes: Uint8Array): CoreOutcome<SvgCleaning> {
|
||||||
|
return coreRuntime().invoke((glue) =>
|
||||||
|
parseOutcome<SvgCleaning>(glue.clean_svg(bytes)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The cleaned drawing the core stores: its text and the sha256 the core computed for it. */
|
||||||
|
export interface StoredDrawing {
|
||||||
|
stored: string
|
||||||
|
sha256: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CleaningPreview {
|
||||||
|
preview: CataloguePreview
|
||||||
|
viewId: string
|
||||||
|
/** The id prefix the composed tree carries (`fv.<view>.`), unique in the page. */
|
||||||
|
scope: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const NAME = { fr: 'Aperçu', en: 'Preview' }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A throwaway draft holding only the cleaned drawing, so the dialog renders the core's
|
||||||
|
* composed tree and never the original file. The caller frees `preview` on close.
|
||||||
|
*/
|
||||||
|
export function composeCleaningPreview(
|
||||||
|
drawing: StoredDrawing,
|
||||||
|
): CoreOutcome<CleaningPreview> {
|
||||||
|
const runtime = coreRuntime()
|
||||||
|
const empty = runtime.call<unknown>(
|
||||||
|
'sheet.empty',
|
||||||
|
JSON.stringify({ species_id: 'preview', name: NAME }),
|
||||||
|
)
|
||||||
|
if (!empty.ok) return empty
|
||||||
|
const assetId = generateUuid()
|
||||||
|
const viewId = newElementId('view')
|
||||||
|
const edited = applyEdit(JSON.stringify(empty.value), {
|
||||||
|
op: 'insert',
|
||||||
|
element: {
|
||||||
|
kind: 'view',
|
||||||
|
value: {
|
||||||
|
kind: 'detail',
|
||||||
|
id: viewId,
|
||||||
|
name: NAME,
|
||||||
|
svg_asset_id: assetId,
|
||||||
|
view_box: null,
|
||||||
|
parent_view_id: 'view-main',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if (!edited.ok) return edited
|
||||||
|
const preview = new CataloguePreview(
|
||||||
|
runtime,
|
||||||
|
{ status: 'draft', document: edited.value },
|
||||||
|
[],
|
||||||
|
)
|
||||||
|
const bytes = new TextEncoder().encode(drawing.stored)
|
||||||
|
const added = preview.addDrawing({ assetId, sha256: drawing.sha256, bytes })
|
||||||
|
if (!added.ok) {
|
||||||
|
preview.free()
|
||||||
|
return added
|
||||||
|
}
|
||||||
|
return { ok: true, value: { preview, viewId, scope: `fv.${viewId}.` } }
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import type { CoreOutcome } from '@faunosteo/core-wasm'
|
||||||
|
import type {
|
||||||
|
Dependent,
|
||||||
|
EditCommand,
|
||||||
|
ElementKey,
|
||||||
|
SheetDependents,
|
||||||
|
SheetEditOutput,
|
||||||
|
} from '@faunosteo/core-wasm/types'
|
||||||
|
import { coreRuntime } from '@/core/runtime'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The editor's document rules, all the core's (BDR-043): the page holds the document as
|
||||||
|
* one JSON text and passes it through; the answer is serialised back to a text.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** One `sheet.edit` command on a document text; the refusal is the core's closed kind. */
|
||||||
|
export function applyEdit(
|
||||||
|
text: string,
|
||||||
|
command: EditCommand,
|
||||||
|
): CoreOutcome<string> {
|
||||||
|
const input = `{"document":${text},"command":${JSON.stringify(command)}}`
|
||||||
|
const outcome = coreRuntime().call<SheetEditOutput>('sheet.edit', input)
|
||||||
|
return outcome.ok
|
||||||
|
? { ok: true, value: JSON.stringify(outcome.value.document) }
|
||||||
|
: outcome
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What refers to the element `key` (removal and rename warnings). */
|
||||||
|
export function dependentsOf(
|
||||||
|
text: string,
|
||||||
|
key: ElementKey,
|
||||||
|
): CoreOutcome<Dependent[]> {
|
||||||
|
const input = `{"document":${text},"key":${JSON.stringify(key)}}`
|
||||||
|
const outcome = coreRuntime().call<SheetDependents>('sheet.dependents', input)
|
||||||
|
return outcome.ok ? { ok: true, value: outcome.value.dependents } : outcome
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
function deepEqual(a: unknown, b: unknown): boolean {
|
||||||
|
if (a === b) return true
|
||||||
|
if (
|
||||||
|
typeof a !== 'object' ||
|
||||||
|
typeof b !== 'object' ||
|
||||||
|
a === null ||
|
||||||
|
b === null
|
||||||
|
)
|
||||||
|
return false
|
||||||
|
if (Array.isArray(a) || Array.isArray(b)) {
|
||||||
|
return (
|
||||||
|
Array.isArray(a) &&
|
||||||
|
Array.isArray(b) &&
|
||||||
|
a.length === b.length &&
|
||||||
|
a.every((item, index) => deepEqual(item, b[index]))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
const left = a as Record<string, unknown>
|
||||||
|
const right = b as Record<string, unknown>
|
||||||
|
const keys = Object.keys(left)
|
||||||
|
return (
|
||||||
|
keys.length === Object.keys(right).length &&
|
||||||
|
keys.every((key) => key in right && deepEqual(left[key], right[key]))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Two document texts are the same document when their parsed JSON is deeply equal: key
|
||||||
|
* order is ignored (the server's jsonb order against the core's serde order), array order
|
||||||
|
* is not. A text that is not JSON equals only an identical string.
|
||||||
|
*/
|
||||||
|
export function sameDocument(a: string, b: string): boolean {
|
||||||
|
try {
|
||||||
|
return deepEqual(JSON.parse(a), JSON.parse(b))
|
||||||
|
} catch {
|
||||||
|
return a === b
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
const ALPHABET = 'abcdefghijklmnopqrstuvwxyz234567'
|
||||||
|
const SUFFIX_LENGTH = 10
|
||||||
|
|
||||||
|
export type IdPrefix =
|
||||||
|
| 'view'
|
||||||
|
| 'anno'
|
||||||
|
| 'cat'
|
||||||
|
| 'ref'
|
||||||
|
| 'zone'
|
||||||
|
| 'fcat'
|
||||||
|
| 'node'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A new element id, `<prefix>-<10 chars a-z2-7>`. 32 symbols: a byte masked to 5 bits
|
||||||
|
* is unbiased. No document walk; a `duplicate_key` answer is the caller's one retry.
|
||||||
|
*/
|
||||||
|
export function newElementId(prefix: IdPrefix): string {
|
||||||
|
const bytes = crypto.getRandomValues(new Uint8Array(SUFFIX_LENGTH))
|
||||||
|
const suffix = Array.from(bytes, (byte) => ALPHABET[byte & 31]).join('')
|
||||||
|
return `${prefix}-${suffix}`
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -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()
|
||||||
|
})
|
||||||
|
})
|
||||||
Reference in new issue
Block a user