Connect canonical projects to persistent workspace runtimes and canvas views
This commit is contained in:
@@ -59,6 +59,16 @@ export async function startOAuth(provider: "google" | "slack") {
|
||||
export const errorText = (error: unknown) => {
|
||||
const code = error instanceof Error ? error.message : "";
|
||||
const messages: Record<string, string> = {
|
||||
identity_changed: "账户已变化,当前画布已停止同步,请重新打开。",
|
||||
engine_closing: "画布正在关闭,本地修改会保留用于恢复。",
|
||||
storage_scope_in_use: "这张图谱已在另一个标签页中打开,请先关闭那里的编辑器。",
|
||||
persistent_storage_unavailable: "浏览器无法保存本地恢复记录,请检查存储权限后重试。",
|
||||
workspace_close_failed: "本地修改尚未保存成功,请释放浏览器存储空间后重试退出。",
|
||||
host_close_failed: "部分本地修改尚未保存成功,请释放浏览器存储空间后重试退出。",
|
||||
resource_bytes_unavailable: "此图片的本地文件暂不可用,相关修改已保留,请重新选择图片。",
|
||||
recovery_checksum_mismatch: "本地恢复记录校验失败,原记录已保留,请先备份再处理。",
|
||||
recovery_journal_gap: "本地恢复记录不完整,原记录已保留,请先备份再处理。",
|
||||
unsupported_component: "这个元素需要更新版本或安装对应功能后才能编辑。",
|
||||
invalid_credentials: "邮箱或密码不正确,或邮箱尚未验证。",
|
||||
rate_limited: "请求太频繁,请稍后再试。",
|
||||
invalid_session: "登录已过期,请重新登录。",
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { Document, ElementRecord, Geometry, Id, Json, Point, Registry } from '../canvas-core/types.ts';
|
||||
import { connectionPathValid } from '../canvas-core/features.ts';
|
||||
import { fault } from '../canvas-core/values.ts';
|
||||
import type { CanvasNode } from '../canvas-elements.ts';
|
||||
import type { CanvasEdgeModel, EdgeData } from '../canvas-v2.ts';
|
||||
|
||||
export type Transform = { x: number; y: number; scale: number; rotation: number };
|
||||
const origin: Transform = { x: 0, y: 0, scale: 1, rotation: 0 };
|
||||
const rotate = (point: Point, angle: number): Point => { const a = angle * Math.PI / 180; return { x: point.x * Math.cos(a) - point.y * Math.sin(a), y: point.x * Math.sin(a) + point.y * Math.cos(a) }; };
|
||||
export function toWorld(transform: Transform, point: Point): Point { const value = rotate(point, transform.rotation); return { x: transform.x + value.x * transform.scale, y: transform.y + value.y * transform.scale }; }
|
||||
export function toLocal(transform: Transform, point: Point): Point { return rotate({ x: (point.x - transform.x) / transform.scale, y: (point.y - transform.y) / transform.scale }, -transform.rotation); }
|
||||
export type ProjectionNode = Omit<CanvasNode, 'type'> & { type: NonNullable<CanvasNode['type']> | 'unsupported' };
|
||||
const nodeTypes: Record<string, NonNullable<CanvasNode['type']>> = { 'plain-text': 'plainText', 'plain-image': 'plainImage', frame: 'frame', icon: 'icon' };
|
||||
const object = (value: Json | undefined) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
||||
export function transformPath(path: Json, transform: Transform, inverse = false): Json {
|
||||
const raw = object(path);
|
||||
if (raw.type !== 'bezier-chain' || !Array.isArray(raw.knots)) return path;
|
||||
const point = (input: Json | undefined, vector = false): Json | undefined => {
|
||||
const p = object(input); if (typeof p.x !== 'number' || typeof p.y !== 'number') return input;
|
||||
const t = vector ? { ...transform, x: 0, y: 0 } : transform;
|
||||
return { ...p, ...(inverse ? toLocal(t, { x: p.x, y: p.y }) : toWorld(t, { x: p.x, y: p.y })) };
|
||||
};
|
||||
return { ...raw, ...(raw.startControl ? { startControl: point(raw.startControl, true)! } : {}), ...(raw.endControl ? { endControl: point(raw.endControl, true)! } : {}), knots: raw.knots.map(knot => {
|
||||
const k = object(knot); return { ...k, position: point(k.position)!, in: point(k.in, true)!, out: point(k.out, true)! };
|
||||
}) };
|
||||
}
|
||||
|
||||
/** Renderer projection retains identity/owner in the model, including nested and collapsed canvases. */
|
||||
export function projectCanvas(document: Document, canvasId: Id, registry: Registry, selected: ReadonlySet<Id> | { has(id: Id): boolean }, geometry: (id: Id) => Geometry | undefined, edgePreview?: { target: { id: Id }; path: Json } | null) {
|
||||
if (!document.canvases.has(canvasId)) throw fault('canvas_not_loaded', [canvasId]);
|
||||
const transforms = new Map<Id, Transform>([[canvasId, origin]]), hiddenBy = new Map<Id, Id>(), childByEntry = new Map<Id, Id>();
|
||||
for (const canvas of document.canvases.values()) if (canvas.parent) childByEntry.set(canvas.parent.entryElementId, canvas.id);
|
||||
const members = new Map<Id, ElementRecord[]>();
|
||||
for (const element of document.elements.values()) { const list = members.get(element.ownerCanvasId) ?? []; list.push(element); members.set(element.ownerCanvasId, list); }
|
||||
const nodes: ProjectionNode[] = [], visible = new Set<Id>();
|
||||
const visit = (id: Id, depth: number) => {
|
||||
const transform = transforms.get(id)!;
|
||||
for (const element of members.get(id) ?? []) if (element.structure === 'node') {
|
||||
const g = geometry(element.id) ?? element.geometry, center = toWorld(transform, { x: g.x + g.width / 2, y: g.y + g.height / 2 });
|
||||
const width = g.width * transform.scale, height = g.height * transform.scale, known = registry.resolve(element) === 'known';
|
||||
const type = !known ? 'unsupported' : nodeTypes[element.componentId] ?? 'material';
|
||||
const child = childByEntry.get(element.id), data = element.data;
|
||||
const projected: ProjectionNode = { id: element.id, type, position: { x: center.x - width / 2, y: center.y - height / 2 }, width, height, selected: selected.has(element.id), draggable: known && registry.supports(element, 'geometry.move'), zIndex: element.componentId === 'frame' ? depth - 100 : depth * 2,
|
||||
style: { width, height, ...(element.componentId === 'frame' ? { pointerEvents: 'none' as const } : {}) },
|
||||
data: { ...data, kind: element.componentId as CanvasNode['data']['kind'], title: typeof data.title === 'string' ? data.title : element.componentId, text: typeof data.text === 'string' ? data.text : '', rotation: (g.rotation + transform.rotation) % 360, viewScale: transform.scale, ...(child ? { subgraph: { boardId: child } } : {}) } as CanvasNode['data'],
|
||||
};
|
||||
nodes.push(projected); visible.add(element.id);
|
||||
if (child) {
|
||||
const presentation = object(data.presentation), scale = typeof presentation.contentScale === 'number' && presentation.contentScale > 0 ? presentation.contentScale : 1;
|
||||
if (presentation.collapsed === true || !known) {
|
||||
const stack = [child]; while (stack.length) { const hidden = stack.pop()!; hiddenBy.set(hidden, element.id); for (const canvas of document.canvases.values()) if (canvas.parent?.canvasId === hidden) stack.push(canvas.id); }
|
||||
} else {
|
||||
const offset = rotate({ x: 24 - g.width / 2, y: 36 - g.height / 2 }, g.rotation);
|
||||
const start = toWorld(transform, { x: g.x + g.width / 2 + offset.x, y: g.y + g.height / 2 + offset.y });
|
||||
transforms.set(child, { ...start, scale: transform.scale * scale, rotation: transform.rotation + g.rotation }); visit(child, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
visit(canvasId, 0);
|
||||
const edges: CanvasEdgeModel[] = [];
|
||||
for (const element of document.elements.values()) if (element.structure === 'connection' && transforms.has(element.ownerCanvasId)) {
|
||||
const endpoint = (id: Id) => visible.has(id) ? id : hiddenBy.get(document.elements.get(id)?.ownerCanvasId ?? '');
|
||||
const source = endpoint(element.source.elementId), target = endpoint(element.target.elementId);
|
||||
if (!source || !target || source === target) continue;
|
||||
const path = transformPath(edgePreview?.target.id === element.id ? edgePreview.path : element.path, transforms.get(element.ownerCanvasId)!);
|
||||
const renderPath = registry.resolve(element) === 'known' && connectionPathValid(path) ? path : undefined;
|
||||
const { path: unusedPath, ...edgeData } = element.data; void unusedPath;
|
||||
edges.push({ id: element.id, source, target, sourceHandle: source === element.source.elementId ? element.source.portId : undefined, targetHandle: target === element.target.elementId ? element.target.portId : undefined, selected: selected.has(element.id), data: { ...edgeData, ...(renderPath ? { path: renderPath } : {}) } as EdgeData });
|
||||
}
|
||||
return { nodes, edges, transforms };
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Applied, Availability, Capability, Change, Command, Commit, CoreSnapshot, Document, ElementRecord, Geometry, HistoryEntry, HistoryState, Id, OperationIntent, Origin, Registry, Result, Snapshot } from './types.ts';
|
||||
import { applyChanges, commonCanvas, createDocument, invert, targetElement, validateDocument } from './document.ts';
|
||||
import { clone, equal, fault, freeze, readMap, reject } from './values.ts';
|
||||
import { clone, equal, fault, freeze, readMap, reject, validJson } from './values.ts';
|
||||
|
||||
export type EditorOptions<Runtime = undefined> = {
|
||||
registry: Registry; document: Document; createId?: () => Id; historyLimit?: number;
|
||||
@@ -52,7 +52,12 @@ export function createEditor<Runtime = undefined>(options: EditorOptions<Runtime
|
||||
} else {
|
||||
let element = targetElement(document, command.target);
|
||||
if (options.registry.resolve(element) !== 'known') throw fault('unsupported_component', [element.id]);
|
||||
if (command.type === 'element.remove') {
|
||||
if (command.type === 'connection.path') {
|
||||
if (element.structure !== 'connection' || !options.registry.supports(element, 'connection.edit')) throw fault('unsupported_capability', [element.id]);
|
||||
if (!validJson(command.path)) throw fault('invalid_connection_path', [element.id]);
|
||||
changes = options.registry.handlers.get(element.componentId)!.get('connection.edit')!({ element, input: freeze({ patch: { path: clone(command.path) } }) });
|
||||
for (const change of changes) if (change.kind !== 'field' || change.field !== 'path' || change.target.id !== element.id || change.target.incarnation !== element.incarnation) throw fault('invalid_handler_change', [element.id]);
|
||||
} else if (command.type === 'element.remove') {
|
||||
changes = [{ kind: 'element', id: element.id, before: element, after: null }];
|
||||
for (const edge of document.elements.values()) if (edge.structure === 'connection' && (edge.source.elementId === element.id || edge.target.elementId === element.id)) changes = [...changes, { kind: 'element', id: edge.id, before: edge, after: null }];
|
||||
} else if (command.type === 'element.move') {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { CapabilityHandler, ComponentDefinition, Data, FieldChange, Geometry } from './types.ts';
|
||||
import type { CapabilityHandler, ComponentDefinition, Data, FieldChange, Geometry, Json } from './types.ts';
|
||||
import { defineComponent, defineFeature } from './registry.ts';
|
||||
import { equal, fault, validJson } from './values.ts';
|
||||
|
||||
@@ -47,5 +47,24 @@ export function builtinComponents(): readonly ComponentDefinition[] {
|
||||
id, dataVersion: 1, structure: 'node', validate: textData,
|
||||
features: [movable(), resizable(), ...(id === 'frame' ? [] : [rotatable()]), editable()],
|
||||
resourceFields: ['image', 'plain-image'].includes(id) ? ['assetId','asset'] : [],
|
||||
})).concat([defineComponent({ id: 'connection', dataVersion: 1, structure: 'connection', validate: data => validJson(data), features: [editable()], resourceFields: [] })]);
|
||||
})).concat([defineComponent({ id: 'connection', dataVersion: 1, structure: 'connection', validate: data => validJson(data), features: [editable(), connectionEditable()], resourceFields: [] })]);
|
||||
}
|
||||
|
||||
export function connectionPathValid(path: Json): boolean {
|
||||
if (path === null) return true;
|
||||
if (typeof path !== 'object' || Array.isArray(path) || path.type !== 'bezier-chain' || !Array.isArray(path.knots) || path.knots.length > 64) return false;
|
||||
const point = (value: Json | undefined) => value && typeof value === 'object' && !Array.isArray(value) && typeof value.x === 'number' && typeof value.y === 'number' && Number.isFinite(value.x) && Number.isFinite(value.y);
|
||||
if (path.startControl !== undefined && !point(path.startControl) || path.endControl !== undefined && !point(path.endControl)) return false;
|
||||
const ids = new Set<string>();
|
||||
for (const knot of path.knots) {
|
||||
if (!knot || typeof knot !== 'object' || Array.isArray(knot) || typeof knot.id !== 'string' || !knot.id || ids.has(knot.id) || !['corner', 'smooth', 'symmetric'].includes(knot.mode as string) || !point(knot.position) || !point(knot.in) || !point(knot.out)) return false;
|
||||
ids.add(knot.id);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
export const connectionEditable = () => defineFeature('connection.path', { 'connection.edit': ({ element, input }) => {
|
||||
const path = (input.patch as { path?: Json }).path;
|
||||
if (element.structure !== 'connection' || !connectionPathValid(element.path)) throw fault('unsupported_connection_path', [element.id]);
|
||||
if (path === undefined || !validJson(path) || !connectionPathValid(path)) throw fault('invalid_connection_path', [element.id]);
|
||||
return equal(element.path, path) ? [] : [{ kind: 'field', target: { id: element.id, incarnation: element.incarnation }, field: 'path', before: element.path, after: path }];
|
||||
} });
|
||||
|
||||
@@ -1,31 +1,38 @@
|
||||
import type { Editor } from './editor.ts';
|
||||
import type { Availability, Capability, ElementRecord, Geometry, Id, Result, Target } from './types.ts';
|
||||
import type { Availability, Capability, ElementRecord, Geometry, Id, Json, Result, Target } from './types.ts';
|
||||
import { geometryValid, targetElement } from './document.ts';
|
||||
import { equal, fault, freeze, readMap, readSet, reject } from './values.ts';
|
||||
import { clone, equal, fault, freeze, readMap, readSet, reject, validJson } from './values.ts';
|
||||
|
||||
export type ViewState = { readonly id: Id; readonly selection: ReturnType<typeof readSet<Id>>; readonly viewport: { readonly x: number; readonly y: number; readonly zoom: number }; readonly tool: 'select' | 'pan'; readonly modes: ReadonlyMap<Id, string> };
|
||||
export type GestureState = { readonly viewId: Id; readonly targets: readonly Target[]; readonly preview: ReadonlyMap<Id, Geometry>; readonly phase: 'active' | 'committing' };
|
||||
export type SessionSnapshot = { readonly views: ReadonlyMap<Id, ViewState>; readonly gesture: GestureState | null; readonly lastCancelReason: string | null };
|
||||
export type ViewState = { readonly id: Id; readonly canvasId: Id; readonly selection: ReturnType<typeof readSet<Id>>; readonly viewport: { readonly x: number; readonly y: number; readonly zoom: number }; readonly tool: 'select' | 'pan'; readonly modes: ReadonlyMap<Id, string> };
|
||||
export type GestureState = { readonly token: number; readonly viewId: Id; readonly targets: readonly Target[]; readonly preview: ReadonlyMap<Id, Geometry>; readonly phase: 'active' | 'committing' };
|
||||
export type ConnectionGesture = { readonly token: number; readonly viewId: Id; readonly target: Target; readonly path: Json; readonly phase: 'active' | 'committing' };
|
||||
export type SessionSnapshot = { readonly views: ReadonlyMap<Id, ViewState>; readonly gesture: GestureState | null; readonly connectionGesture: ConnectionGesture | null; readonly lastCancelReason: string | null };
|
||||
|
||||
/** Transient interaction state belongs to views; no pointer event enters the ledger. */
|
||||
export function createSessions(editor: Editor) {
|
||||
let snapshot: SessionSnapshot = Object.freeze({ views: readMap(new Map<Id, ViewState>()), gesture: null, lastCancelReason: null });
|
||||
let baseline = new Map<Id, ElementRecord>(), disposed = false;
|
||||
let snapshot: SessionSnapshot = Object.freeze({ views: readMap(new Map<Id, ViewState>()), gesture: null, connectionGesture: null, lastCancelReason: null });
|
||||
let baseline = new Map<Id, ElementRecord>(), connectionBaseline: ElementRecord | undefined, disposed = false, nextGestureToken = 0;
|
||||
const listeners = new Set<() => void>();
|
||||
const notify = () => { for (const listener of [...listeners]) try { listener(); } catch { /* A renderer cannot invalidate model commits. */ } };
|
||||
function setView(view: ViewState) { const views = new Map(snapshot.views); views.set(view.id, view); snapshot = Object.freeze({ ...snapshot, views: readMap(views) }); notify(); }
|
||||
function cancel(reason = 'canceled') {
|
||||
if (!snapshot.gesture) return;
|
||||
baseline.clear(); snapshot = Object.freeze({ ...snapshot, gesture: null, lastCancelReason: reason }); notify();
|
||||
if (!snapshot.gesture && !snapshot.connectionGesture) return;
|
||||
baseline.clear(); connectionBaseline = undefined; snapshot = Object.freeze({ ...snapshot, gesture: null, connectionGesture: null, lastCancelReason: reason }); notify();
|
||||
}
|
||||
const detachEditor = editor.subscribe(() => {
|
||||
const document = editor.getSnapshot().document;
|
||||
const views = new Map(snapshot.views); let changed = false;
|
||||
for (const [id, view] of views) {
|
||||
const canvasMissing = !document.canvases.has(view.canvasId);
|
||||
const selection = [...view.selection].filter(target => document.elements.has(target)), modes = new Map([...view.modes].filter(([target]) => document.elements.has(target)));
|
||||
if (selection.length !== view.selection.size || modes.size !== view.modes.size) { views.set(id, freeze({ ...view, selection: readSet(selection), modes: readMap(modes) })); changed = true; }
|
||||
if (canvasMissing || selection.length !== view.selection.size || modes.size !== view.modes.size) { views.set(id, freeze({ ...view, canvasId: canvasMissing ? [...document.canvases.values()].find(canvas => !canvas.parent)!.id : view.canvasId, selection: readSet(canvasMissing ? [] : selection), modes: readMap(canvasMissing ? new Map() : modes) })); changed = true; }
|
||||
}
|
||||
if (changed) { snapshot = Object.freeze({ ...snapshot, views: readMap(views) }); notify(); }
|
||||
if (snapshot.connectionGesture?.phase === 'active') {
|
||||
const current = document.elements.get(snapshot.connectionGesture.target.id), before = connectionBaseline;
|
||||
if (!current || current.structure !== 'connection' || before?.structure !== 'connection' || current.incarnation !== before.incarnation || current.ownerCanvasId !== before.ownerCanvasId || !equal(current.path, before.path)) cancel('target_changed');
|
||||
else if (!editor.can({ type: 'connection.path', target: snapshot.connectionGesture.target, path: current.path }).enabled) cancel('permission_changed');
|
||||
}
|
||||
if (snapshot.gesture?.phase !== 'active') return;
|
||||
for (const target of snapshot.gesture.targets) {
|
||||
const before = baseline.get(target.id), current = document.elements.get(target.id);
|
||||
@@ -64,10 +71,17 @@ export function createSessions(editor: Editor) {
|
||||
}
|
||||
return Object.freeze({
|
||||
getSnapshot: () => snapshot,
|
||||
attach(id: Id) {
|
||||
attach(id: Id, canvasId = [...editor.getSnapshot().document.canvases.values()].find(canvas => !canvas.parent)!.id) {
|
||||
if (disposed || snapshot.views.has(id)) throw fault('duplicate_view', [id]);
|
||||
setView(freeze({ id, selection: readSet<Id>([]), viewport: { x: 0, y: 0, zoom: 1 }, tool: 'select', modes: readMap(new Map<Id, string>()) }));
|
||||
return () => { if (snapshot.gesture?.viewId === id) cancel('view_detached'); const views = new Map(snapshot.views); views.delete(id); snapshot = Object.freeze({ ...snapshot, views: readMap(views) }); notify(); };
|
||||
if (!editor.getSnapshot().document.canvases.has(canvasId)) throw fault('canvas_missing', [canvasId]);
|
||||
setView(freeze({ id, canvasId, selection: readSet<Id>([]), viewport: { x: 0, y: 0, zoom: 1 }, tool: 'select', modes: readMap(new Map<Id, string>()) }));
|
||||
return () => { if ((snapshot.gesture?.viewId === id || snapshot.connectionGesture?.viewId === id)) cancel('view_detached'); const views = new Map(snapshot.views); views.delete(id); snapshot = Object.freeze({ ...snapshot, views: readMap(views) }); notify(); };
|
||||
},
|
||||
canvas(id: Id, canvasId: Id) {
|
||||
const current = view(id);
|
||||
if (!editor.getSnapshot().document.canvases.has(canvasId)) throw fault('canvas_missing', [canvasId]);
|
||||
if ((snapshot.gesture?.viewId === id || snapshot.connectionGesture?.viewId === id)) cancel('canvas_changed');
|
||||
setView(freeze({ ...current, canvasId, selection: readSet<Id>([]), modes: readMap(new Map<Id, string>()) }));
|
||||
},
|
||||
select(id: Id, ids: readonly Id[]) {
|
||||
const current = view(id), document = editor.getSnapshot().document;
|
||||
@@ -83,13 +97,45 @@ export function createSessions(editor: Editor) {
|
||||
begin(viewId: Id, targets: readonly Target[]): Availability {
|
||||
try {
|
||||
view(viewId);
|
||||
if (snapshot.gesture || !targets.length || new Set(targets.map(target => target.id)).size !== targets.length) throw fault('gesture_busy');
|
||||
if (snapshot.gesture || snapshot.connectionGesture || !targets.length || new Set(targets.map(target => target.id)).size !== targets.length) throw fault('gesture_busy');
|
||||
baseline = new Map(targets.map(target => { const element = targetElement(editor.getSnapshot().document, target); if (element.structure !== 'node' || editor.registry.resolve(element) !== 'known') throw fault('unsupported_component', [target.id]); return [target.id, element]; }));
|
||||
for (const target of targets) { const allowed = editor.can({ type: 'element.geometry', target, patch: {} }); if (!allowed.enabled) throw fault(allowed.code, allowed.targets); }
|
||||
snapshot = Object.freeze({ ...snapshot, lastCancelReason: null, gesture: freeze({ viewId, targets: targets.map(target => ({ ...target })), preview: readMap(new Map<Id, Geometry>()), phase: 'active' as const }) }); notify();
|
||||
snapshot = Object.freeze({ ...snapshot, lastCancelReason: null, gesture: freeze({ token: ++nextGestureToken, viewId, targets: targets.map(target => ({ ...target })), preview: readMap(new Map<Id, Geometry>()), phase: 'active' as const }) }); notify();
|
||||
return { enabled: true };
|
||||
} catch (error) { const result = reject(error); return { enabled: false, code: result.code, targets: result.targets }; }
|
||||
},
|
||||
beginConnection(viewId: Id, target: Target): Availability {
|
||||
try {
|
||||
view(viewId);
|
||||
if (snapshot.gesture || snapshot.connectionGesture) throw fault('gesture_busy');
|
||||
const element = targetElement(editor.getSnapshot().document, target);
|
||||
if (element.structure !== 'connection') throw fault('unsupported_capability', [target.id]);
|
||||
const allowed = editor.can({ type: 'connection.path', target, path: element.path });
|
||||
if (!allowed.enabled) throw fault(allowed.code, allowed.targets);
|
||||
connectionBaseline = element;
|
||||
snapshot = Object.freeze({ ...snapshot, lastCancelReason: null, connectionGesture: freeze({ token: ++nextGestureToken, viewId, target: { ...target }, path: element.path, phase: 'active' as const }) }); notify();
|
||||
return { enabled: true };
|
||||
} catch (error) { const result = reject(error); return { enabled: false, code: result.code, targets: result.targets }; }
|
||||
},
|
||||
updateConnection(viewId: Id, path: Json): Availability {
|
||||
try {
|
||||
view(viewId);
|
||||
if (snapshot.connectionGesture?.viewId !== viewId) throw fault('gesture_not_owned');
|
||||
if (!validJson(path)) throw fault('invalid_connection_path');
|
||||
snapshot = Object.freeze({ ...snapshot, connectionGesture: freeze({ ...snapshot.connectionGesture, path: clone(path) }) }); notify();
|
||||
return { enabled: true };
|
||||
} catch (error) { const result = reject(error); return { enabled: false, code: result.code, targets: result.targets }; }
|
||||
},
|
||||
commitConnection(viewId: Id): Result {
|
||||
try {
|
||||
view(viewId);
|
||||
const gesture = snapshot.connectionGesture;
|
||||
if (!gesture || gesture.viewId !== viewId) throw fault('gesture_not_owned');
|
||||
snapshot = Object.freeze({ ...snapshot, connectionGesture: freeze({ ...gesture, phase: 'committing' as const }) });
|
||||
const result = editor.dispatch({ type: 'connection.path', target: gesture.target, path: gesture.path }, { label: 'Edit connection' });
|
||||
cancel(result.status === 'rejected' ? result.code : 'committed'); return result;
|
||||
} catch (error) { cancel('commit_failed'); return reject(error); }
|
||||
},
|
||||
update,
|
||||
commit(viewId: Id): Result {
|
||||
try {
|
||||
|
||||
@@ -20,6 +20,7 @@ export type Change = FieldChange
|
||||
| { readonly kind: 'canvas'; readonly id: Id; readonly before: CanvasRecord | null; readonly after: CanvasRecord | null };
|
||||
export type Command =
|
||||
| { readonly type: 'element.create'; readonly element: ElementRecord }
|
||||
| { readonly type: 'connection.path'; readonly target: Target; readonly path: Json }
|
||||
| { readonly type: 'element.remove'; readonly target: Target }
|
||||
| { readonly type: 'element.data'; readonly target: Target; readonly patch: Data }
|
||||
| { readonly type: 'element.geometry'; readonly target: Target; readonly patch: Partial<Geometry> }
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { Profile } from './api.ts';
|
||||
import type { CanvasRequest } from './canvas-sync.ts';
|
||||
import { decodeSnapshot } from './canvas-sync.ts';
|
||||
import { CANVAS_ACCEPT } from './canvas-v2.ts';
|
||||
import { matchesRef, type Board } from './workspace.ts';
|
||||
import type { Registry } from './canvas-core/types.ts';
|
||||
import { loadFoundryModel, type ServiceTransport } from './canvas-service/foundry.ts';
|
||||
|
||||
/** Read canonical first: a migrated project must never be opened through snapshot writers. */
|
||||
export async function loadCanvasEntry(options: { request: CanvasRequest; workspaceRef: string; boardRef: string; registry: Registry; transport(accountId: string): ServiceTransport; signal?: AbortSignal }) {
|
||||
const path = `workspaces/${encodeURIComponent(options.workspaceRef)}/materials/${encodeURIComponent(options.boardRef)}`;
|
||||
const [board, profile] = await Promise.all([options.request<Board>(path, { signal: options.signal }), options.request<Profile>('profile', { signal: options.signal })]);
|
||||
options.signal?.throwIfAborted();
|
||||
if (board.kind !== 'board' || !matchesRef(board, options.boardRef) || !board.workspace_id || !profile.id) throw new Error('invalid_reference');
|
||||
const transport = options.transport(profile.id);
|
||||
try {
|
||||
const model = await loadFoundryModel(transport, board.workspace_id, board.id, options.registry, options.signal);
|
||||
options.signal?.throwIfAborted();
|
||||
if (model.status === 'ready') return { mode: 'headless' as const, board, profile, model };
|
||||
// Existing projects keep their current editor until the user explicitly migrates them.
|
||||
} catch (error) {
|
||||
options.signal?.throwIfAborted();
|
||||
if ((error as { code?: string }).code !== 'not_found') throw error;
|
||||
}
|
||||
const snapshot = decodeSnapshot(await options.request(path + '/canvas', { signal: options.signal, headers: { Accept: CANVAS_ACCEPT } }));
|
||||
return { mode: 'legacy' as const, board, profile, snapshot };
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { Document, Id, Registry } from '../canvas-core/types.ts';
|
||||
import type { Document, Id, Registry, Result } from '../canvas-core/types.ts';
|
||||
import { createEditor, type EditorOptions, type Transaction } from '../canvas-core/editor.ts';
|
||||
import { createDocument } from '../canvas-core/document.ts';
|
||||
import { createSessions } from '../canvas-core/gestures.ts';
|
||||
import { equal, fault, freeze, readMap } from '../canvas-core/values.ts';
|
||||
import { equal, fault, freeze, readMap, reject } from '../canvas-core/values.ts';
|
||||
import type { EngineSnapshot, PersistencePort, RuntimeState } from './contracts.ts';
|
||||
import { createLedger, type FrozenRequest } from './ledger.ts';
|
||||
import { operationCanvases, replayPending } from './reconcile.ts';
|
||||
@@ -14,7 +14,7 @@ import type { StoragePort, StorageScope } from './storage.ts';
|
||||
export type EngineOptions = {
|
||||
scope: StorageScope; registry: Registry; document: Document; versions: ReadonlyMap<Id, number>;
|
||||
storage: StoragePort; persistence: PersistencePort; assets?: AssetPort; createId?: () => Id;
|
||||
historyLimit?: number; policy?: EditorOptions['policy']; clock?: Clock;
|
||||
historyLimit?: number; policy?: EditorOptions['policy']; traversalPolicy?: EditorOptions['traversalPolicy']; clock?: Clock;
|
||||
onError?: (error: unknown) => void;
|
||||
};
|
||||
|
||||
@@ -35,7 +35,7 @@ export async function openProjectEngine(options: EngineOptions) {
|
||||
const initial: RuntimeState = recovered?.runtime ?? Object.freeze({ acknowledged: createDocument(options.document.projectId, [...options.document.canvases.values()], [...options.document.elements.values()], options.document.tombstones), versions: readMap(options.versions), ledger: createLedger().getSnapshot(), receipts: readMap(new Map()), conflicts: readMap(new Map()), resources: readMap(new Map()), resourcePins: readMap(new Map()) });
|
||||
const editor = createEditor({ registry: options.registry, document: options.document, recovery: recovered, runtime: initial, createId: options.createId, historyLimit: options.historyLimit,
|
||||
policy(command, document) { if (closing || closed) return { enabled: false, code: 'engine_closing', targets: [] }; return options.policy?.(command, document) ?? { enabled: true }; },
|
||||
traversalPolicy() { return closing || closed ? { enabled: false, code: 'engine_closing', targets: [] } : { enabled: true }; },
|
||||
traversalPolicy(entry, direction) { return closing || closed ? { enabled: false, code: 'engine_closing', targets: [] } : options.traversalPolicy?.(entry, direction) ?? { enabled: true }; },
|
||||
onListenerError: report,
|
||||
nextOperationSequence(runtime, fallback) { let next = fallback; for (const record of runtime.ledger.operations.values()) next = Math.max(next, record.intent.sequence + 1); return next + staged.length; },
|
||||
reduceRuntime(previous, next, commit) {
|
||||
@@ -195,6 +195,25 @@ export async function openProjectEngine(options: EngineOptions) {
|
||||
scheduler.start(); prepareDigests();
|
||||
return Object.freeze({
|
||||
editor, sessions,
|
||||
refresh(document: Document, versions: ReadonlyMap<Id, number>): Result {
|
||||
const root = editor.getSnapshot(), previous = root.runtime;
|
||||
try {
|
||||
if (closing || closed) throw fault('engine_closing');
|
||||
if (document.projectId !== root.document.projectId) throw fault('project_mismatch');
|
||||
if ([...previous.ledger.requests.values()].some(request => request.phase !== 'resolved')) throw fault('refresh_waiting_for_receipts');
|
||||
for (const canvas of document.canvases.keys()) if (!Number.isSafeInteger(versions.get(canvas)) || versions.get(canvas)! < 1) throw fault('missing_server_version', [canvas]);
|
||||
for (const [id, version] of previous.versions) if ((versions.get(id) ?? -1) < version) throw fault('stale_canonical_version', [id]);
|
||||
if (equal([...previous.versions], [...versions]) && equal([...previous.acknowledged.canvases], [...document.canvases]) && equal([...previous.acknowledged.elements], [...document.elements]) && equal([...previous.acknowledged.tombstones], [...document.tombstones])) return { status: 'applied', revision: root.revision, operationIds: [] };
|
||||
const acknowledged = createDocument(document.projectId, [...document.canvases.values()], [...document.elements.values()], document.tombstones);
|
||||
const working = replayPending(acknowledged, previous.ledger, options.registry);
|
||||
const conflicts = new Map(previous.conflicts); conflicts.delete('refresh');
|
||||
return editor.reconcile(working, Object.freeze({ ...previous, acknowledged, versions: readMap(versions), conflicts: readMap(conflicts) }), root.rootRevision);
|
||||
} catch (error) {
|
||||
const result = reject(error);
|
||||
if (result.code !== 'refresh_waiting_for_receipts' && result.code !== 'engine_closing') editor.updateRuntime(previous => { const conflicts = new Map(previous.conflicts); conflicts.set('refresh', result.code); return Object.freeze({ ...previous, conflicts: readMap(conflicts) }); });
|
||||
return result;
|
||||
}
|
||||
},
|
||||
stageFiles(files: readonly StagedFile[], callback: (resources: readonly ResourceHandle[], transaction: Transaction) => unknown) {
|
||||
if (closing || closed) throw fault('engine_closing');
|
||||
if (staged.length) throw fault('reentrant_dispatch');
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { Id, Registry } from '../canvas-core/types.ts';
|
||||
import { fault, readMap } from '../canvas-core/values.ts';
|
||||
import type { WorkspaceRuntime } from './workspace.ts';
|
||||
|
||||
/** Host lifetime matches the signed-in application, independently of navigation. */
|
||||
export function createRuntimeHost(options: { registry: Registry; workspace(accountId: Id, workspaceId: Id, authEpoch: number, current: () => boolean): WorkspaceRuntime; onError?: (error: unknown) => void }) {
|
||||
let accountId: Id | null = null, authEpoch = 0, disposed = false;
|
||||
const workspaces = new Map<Id, WorkspaceRuntime>(), retired = new Set<WorkspaceRuntime>();
|
||||
const closeRetired = async () => {
|
||||
const results = await Promise.allSettled([...retired].map(async runtime => { await runtime.close(); retired.delete(runtime); }));
|
||||
const errors = results.flatMap(result => result.status === 'rejected' ? [result.reason] : []);
|
||||
if (errors.length) throw new AggregateError(errors, 'host_close_failed');
|
||||
};
|
||||
function retire() { authEpoch++; accountId = null; for (const runtime of workspaces.values()) retired.add(runtime); workspaces.clear(); }
|
||||
function activate(account: Id) {
|
||||
if (disposed) throw fault('host_disposed');
|
||||
if (accountId !== account) {
|
||||
retire(); accountId = account;
|
||||
void closeRetired().catch(error => { try { options.onError?.(error); } catch { /* Reporting cannot change scope. */ } });
|
||||
}
|
||||
}
|
||||
return Object.freeze({
|
||||
registry: options.registry,
|
||||
bindAccount(account: Id) { activate(account); const epoch = authEpoch; return () => !disposed && accountId === account && authEpoch === epoch; },
|
||||
identity: () => Object.freeze({ accountId, authEpoch }),
|
||||
getWorkspaces: () => readMap(workspaces),
|
||||
workspace(account: Id, workspace: Id) {
|
||||
activate(account);
|
||||
let runtime = workspaces.get(workspace);
|
||||
if (!runtime) {
|
||||
const epoch = authEpoch;
|
||||
runtime = options.workspace(account, workspace, epoch, () => !disposed && accountId === account && authEpoch === epoch);
|
||||
workspaces.set(workspace, runtime);
|
||||
}
|
||||
return runtime;
|
||||
},
|
||||
retireIdentity() { retire(); return closeRetired(); },
|
||||
close() { disposed = true; retire(); return closeRetired(); },
|
||||
});
|
||||
}
|
||||
export type RuntimeHost = ReturnType<typeof createRuntimeHost>;
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { Document, Id, Registry } from '../canvas-core/types.ts';
|
||||
import { fault, readMap } from '../canvas-core/values.ts';
|
||||
import { openProjectEngine, type EngineOptions } from './engine.ts';
|
||||
import type { StoragePort } from './storage.ts';
|
||||
|
||||
export type ProjectEngine = Awaited<ReturnType<typeof openProjectEngine>>;
|
||||
export type WorkspaceOptions = {
|
||||
accountId: Id; workspaceId: Id; authEpoch: number; registry: Registry; storage: StoragePort;
|
||||
isCurrentIdentity(): boolean;
|
||||
adapters(projectId: Id, current: () => boolean): Pick<EngineOptions, 'persistence' | 'assets'>;
|
||||
onError?: (error: unknown) => void;
|
||||
};
|
||||
|
||||
/** Workspace owns persistent projects; a view only borrows one and never closes it. */
|
||||
export function createWorkspaceRuntime(options: WorkspaceOptions) {
|
||||
const projects = new Map<Id, Promise<ProjectEngine>>();
|
||||
let accepting = true, closed = false, closing: Promise<void> | undefined;
|
||||
const current = () => accepting && !closed && options.isCurrentIdentity();
|
||||
return Object.freeze({
|
||||
accountId: options.accountId, workspaceId: options.workspaceId, authEpoch: options.authEpoch, registry: options.registry,
|
||||
isCurrentIdentity: current,
|
||||
getProjects: () => readMap(projects),
|
||||
open(document: Document, versions: ReadonlyMap<Id, number>) {
|
||||
if (!current()) return Promise.reject(fault('identity_changed'));
|
||||
const existing = projects.get(document.projectId);
|
||||
if (existing) return existing.then(engine => { if (!current()) throw fault('identity_changed'); engine.refresh(document, versions); return engine; });
|
||||
const opening = openProjectEngine({ scope: { accountId: options.accountId, workspaceId: options.workspaceId, projectId: document.projectId }, registry: options.registry, document, versions, storage: options.storage, ...options.adapters(document.projectId, current), onError: options.onError,
|
||||
traversalPolicy: () => current() ? { enabled: true } : { enabled: false, code: 'identity_changed', targets: [] },
|
||||
policy: () => current() ? { enabled: true } : { enabled: false, code: 'identity_changed', targets: [] },
|
||||
});
|
||||
projects.set(document.projectId, opening);
|
||||
void opening.catch(() => { if (projects.get(document.projectId) === opening) projects.delete(document.projectId); });
|
||||
return opening.then(engine => { if (!current()) throw fault('identity_changed'); engine.refresh(document, versions); return engine; });
|
||||
},
|
||||
close() {
|
||||
accepting = false; // Fence commands/transports before awaiting pending opens or storage.
|
||||
if (closed) return Promise.resolve();
|
||||
if (closing) return closing;
|
||||
const task = (async () => {
|
||||
const results = await Promise.allSettled([...projects.values()].map(async pending => {
|
||||
let engine: ProjectEngine;
|
||||
try { engine = await pending; } catch { return; }
|
||||
await engine.close();
|
||||
}));
|
||||
const errors = results.flatMap(result => result.status === 'rejected' ? [result.reason] : []);
|
||||
if (errors.length) throw new AggregateError(errors, 'workspace_close_failed');
|
||||
options.storage.close(); projects.clear(); closed = true;
|
||||
})();
|
||||
closing = task.finally(() => { closing = undefined; });
|
||||
return closing;
|
||||
},
|
||||
});
|
||||
}
|
||||
export type WorkspaceRuntime = ReturnType<typeof createWorkspaceRuntime>;
|
||||
Reference in New Issue
Block a user