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

+106 -4
View File
@@ -2,6 +2,7 @@ import {
CORE_UNAVAILABLE,
closedRefusal,
parseOutcome,
type CoreFailure,
type CoreOutcome,
type CoreRuntime,
type GluePreviewSheet,
@@ -19,6 +20,24 @@ export interface PreviewDrawing {
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
* 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,
* a handle of a dropped instance is never called. `free` releases it when the
* 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 {
private handle: GluePreviewSheet | null = null
private handleGeneration = -1
private freed = false
private readonly drawings = new Map<string, PreviewDrawing>()
constructor(
private readonly runtime: CoreRuntime,
private readonly input: PreviewInput,
private readonly drawings: readonly PreviewDrawing[],
) {}
private input: PreviewInput,
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. */
state(): CoreOutcome<PreviewState> {
@@ -53,6 +129,32 @@ export class CataloguePreview {
/** After this, every call answers `core_unavailable`: a page that left never rebuilds. */
free(): void {
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
this.handle = null
if (!handle || this.handleGeneration !== this.runtime.generation) return
@@ -79,7 +181,7 @@ export class CataloguePreview {
this.handle = null
return this.runtime.invoke<GluePreviewSheet>((glue) => {
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`.
builder.add_drawing(drawing.assetId, drawing.sha256, drawing.bytes)
}
+40 -8
View File
@@ -7,7 +7,14 @@ import {
type PointerEvent,
type RefObject,
} 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. */
const DRAG_THRESHOLD = 4
@@ -15,7 +22,14 @@ const KEY_PAN = 40
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()
return {
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
* 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 pointers = useRef(new Map<number, Point>())
const moved = useRef(0)
const dragged = useRef(false)
// The wheel listener reads the scale without re-subscribing on every change.
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(() => {
@@ -81,10 +103,14 @@ export function useFraming(viewport: RefObject<HTMLElement | null>, resetKey: st
}, [viewport, zoom])
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) {
moved.current = 0
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)
if (!before) return
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)
moved.current += distance(before, now)
if (moved.current > DRAG_THRESHOLD) dragged.current = true
if (others.length === 1) {
const other = others[0][1]
const box = boxOf(viewport.current)
const at = { 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)
const at = {
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)
} else if (others.length === 0 && dragged.current) {
} else if (others.length === 0 && dragged.current && panAllowed.current) {
event.currentTarget.setPointerCapture?.(event.pointerId)
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'])
/** The core's composed view parsed into the page (`DOMParser` runs no script), or why not. */
function buildView(
export function buildView(
preview: CataloguePreview,
viewId: string,
): { ok: true; svg: Element } | { ok: false; failure: CanvasFailure } {
+73
View File
@@ -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}.` } }
}
+36
View File
@@ -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
}
+38
View File
@@ -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
}
}
+21
View File
@@ -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}`
}