Preserve opaque canvas elements with safe renderer fallbacks

This commit is contained in:
2026-11-08 18:45:10 +08:00
parent 6ff34b67e7
commit 361e636ce7
6 changed files with 88 additions and 13 deletions
+31 -9
View File
@@ -8,8 +8,9 @@ import type { CanvasEdgeModel, EdgeData } from '../canvas-v2.ts';
import { childCanvasTransform, toWorld, transformPath, type Transform } from '../canvas-core/coordinates.ts';
export { toWorld, toLocal, transformPath, type Transform } from '../canvas-core/coordinates.ts';
const origin:Transform={x:0,y:0,scale:1,rotation:0};
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' };
export type FallbackProjection = {reason:'unknown-component'|'unsupported-version'|'renderer-unavailable';componentId:string;dataVersion:number;handles:{id:string;side:'top'|'right'|'bottom'|'left'}[]};
export type ProjectionNode = Omit<CanvasNode, 'type'|'data'> & { type: NonNullable<CanvasNode['type']> | 'unsupported';data:CanvasNode['data']&{__headlessFallback?:FallbackProjection} };
const nodeTypes: Record<string, NonNullable<CanvasNode['type']>> = { text:'material', image:'material', script:'material', 'plain-text': 'plainText', 'plain-image': 'plainImage', frame: 'frame', icon: 'icon' };
const object = (value: Json | undefined) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
/** Renderer projection retains identity/owner in the model, including nested and collapsed canvases. */
@@ -25,16 +26,18 @@ export function projectCanvas(document: Document, canvasId: Id, registry: Regist
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 resolved=registry.resolve(element),renderer=element.dataVersion===1?nodeTypes[element.componentId]:undefined;
const fallback:FallbackProjection|undefined=!known||!renderer?{reason:resolved==='known'?'renderer-unavailable':resolved,componentId:element.componentId,dataVersion:element.dataVersion,handles:[]}:undefined;
const type = fallback ? 'unsupported' : renderer!;
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*(known?unitScale(data.presentation):1), ...(child ? { subgraph: { boardId: child } } : {}) } as CanvasNode['data'],
style: { width, height, ...(element.componentId === 'frame'&&!fallback ? { pointerEvents: 'none' as const } : {}) },
data: { ...(fallback?{}:data), kind: element.componentId as CanvasNode['data']['kind'], title: typeof data.title === 'string' ? data.title : element.componentId, text: !fallback&&typeof data.text === 'string' ? data.text : '', __headlessFallback:fallback, rotation: (g.rotation + transform.rotation) % 360, viewScale: transform.scale*(!fallback?unitScale(data.presentation):1), ...(child ? { subgraph: { boardId: child } } : {}) } as CanvasNode['data'],
};
nodes.push(projected); visible.add(element.id);
if (child) {
const presentation = object(data.presentation);
if (presentation.collapsed === true || !known) {
if (!!fallback || presentation.collapsed === true) {
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 {
transforms.set(child, childCanvasTransform(transform,g,data.presentation)); visit(child, depth + 1);
@@ -48,10 +51,29 @@ export function projectCanvas(document: Document, canvasId: Id, registry: Regist
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 fallbackEdge=registry.resolve(element)!=='known'||element.componentId!=='connection'||element.dataVersion!==1;
const path = fallbackEdge ? undefined : transformPath(edgePreview?.target.id === element.id ? edgePreview.path : element.path, transforms.get(element.ownerCanvasId)!);
const renderPath = path!==undefined&&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 });
edges.push({ id: element.id, ...(fallbackEdge?{type:'unsupported'}:{}), 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: fallbackEdge?{}:{ ...edgeData, ...(renderPath ? { path: renderPath } : {}) } as EdgeData });
}
// Handles come from known envelope endpoints, never from opaque component payloads.
const nodesById=new Map(nodes.map(node=>[node.id,node]));
const fallbackNodes=new Map(nodes.filter(node=>node.data.__headlessFallback).map(node=>[node.id,node.data.__headlessFallback!]));
const handleIds=new Map<Id,Set<string>>();
for(const [id,fallback] of fallbackNodes){fallback.handles=(['top','right','bottom','left'] as const).map(side=>({id:side,side}));handleIds.set(id,new Set(fallback.handles.map(handle=>handle.id)));}
for(const edge of edges)for(const end of ['source','target'] as const){
const fallback=fallbackNodes.get(edge[end]);
if(!fallback){
if(edge.type==='unsupported'){
const node=nodesById.get(edge[end]),field=end==='source'?'sourceHandle':'targetHandle',handle=edge[field];
if(!handleIds.has(edge[end])){const ids=new Set(['top','right','bottom','left']);if(Array.isArray(node?.data.ports))for(const port of node.data.ports)if(port&&typeof port.id==='string')ids.add(`port:${port.id}`);handleIds.set(edge[end],ids);}
if(handle&&!handleIds.get(edge[end])!.has(handle))edge[field]=undefined;
}
continue;
}
const field=end==='source'?'sourceHandle':'targetHandle',handle=edge[field]|| (end==='source'?'right':'left');edge[field]=handle;
const seen=handleIds.get(edge[end])!;if(!seen.has(handle)){seen.add(handle);fallback.handles.push({id:handle,side:end==='source'?'right':'left'});}
}
return { nodes, edges, transforms };
}