docs(canvas): explain registry contracts and editor publication flow

This commit is contained in:
2026-11-11 23:41:13 +08:00
parent aaeb5acf6e
commit afa30d4b35
8 changed files with 188 additions and 3 deletions
+21
View File
@@ -1,3 +1,7 @@
/**
* 内置 feature 与 component 装配。Handler 是纯规划器:读取目标与 patch,只返回字段变化。
* 权限、事务与发布仍由 editor 负责;UI 不能绕过 editor 直接调用 handler 来写文档。
*/
import {builtinDataValidator} from './element-data.ts';
import {rectangleGeometry,bezierChainSegments,type BezierChain} from './geometry.ts';
import type { CapabilityHandler, ComponentDefinition, Data, FieldChange, Geometry, Json } from './types.ts';
@@ -5,6 +9,8 @@ import { defineComponent, defineFeature } from './registry.ts';
import { presentationUnitsValid, unitScale } from './units.ts';
import { equal, fault, validJson } from './values.ts';
/** 创建限制字段白名单的几何 handler;可选 constrain 负责约束尺寸,最终几何由文档校验。
* 相同结果返回空数组,避免无变化拖动制造历史或网络操作。 */
const geometryHandler = (allowed: readonly (keyof Geometry)[], constrain?: (geometry: Geometry) => Geometry): CapabilityHandler => ({ element, input }) => {
if (element.structure !== 'node') throw fault('unsupported_capability', [element.id]);
const patch = input.patch as Partial<Geometry>;
@@ -12,17 +18,22 @@ const geometryHandler = (allowed: readonly (keyof Geometry)[], constrain?: (geom
const after = constrain ? constrain({ ...element.geometry, ...patch }) : { ...element.geometry, ...patch };
return equal(element.geometry, after) ? [] : [{ kind: 'field', target: { id: element.id, incarnation: element.incarnation }, field: 'geometry', before: element.geometry, after }];
};
/** 移动仅允许 x/y,不能顺带修改大小、旋转或 owner。 */
export const movable = () => defineFeature('geometry.move', { 'geometry.move': geometryHandler(['x', 'y']) });
/** 捕获 min/max/aspect 配置,构造只修改 width/height 的缩放行为。 */
export const resizable = (inputOptions: { min?: number; max?: number; aspect?: boolean } = {}) => {
const options = Object.freeze({ ...inputOptions });
if (options.min !== undefined && (!Number.isFinite(options.min) || options.min <= 0) || options.max !== undefined && (!Number.isFinite(options.max) || options.max < (options.min ?? 1))) throw fault('invalid_resize_constraint');
return defineFeature('geometry.resize', {
// 缩放 handler:在元素自身的表现单位下应用视觉约束,而不是固定 owner 空间像素值。
'geometry.resize': ({ element, input }) => {
if (element.structure !== 'node') throw fault('unsupported_capability', [element.id]);
const patch = input.patch as Partial<Geometry>;
return geometryHandler(['width', 'height'], geometry => {
// owner 变换后 unitScale 也会改变,因此 min/max 要乘它才能维持同一视觉尺寸约束。
const units=unitScale(element.data.presentation),min=(options.min??1)*units,max=(options.max??100000)*units;
let width = Math.min(max, Math.max(min, geometry.width)), height = Math.min(max, Math.max(min, geometry.height));
// 宽度优先;只给高度时反算宽度。保持原比例后越界则拒绝,不分别截断而破坏比例。
if (options.aspect) {
const ratio = element.geometry.width / element.geometry.height;
if (patch.width !== undefined) height = width / ratio; else width = height * ratio;
@@ -33,30 +44,39 @@ export const resizable = (inputOptions: { min?: number; max?: number; aspect?: b
},
});
};
/** 旋转只产生 rotation 修改;[0,360) 等最终范围约束由几何校验处理。 */
export const rotatable = () => defineFeature('geometry.rotate', { 'geometry.rotate': geometryHandler(['rotation']) });
/** 内容编辑按顶层 data 键生成独立条件变化,保存存在性,区分缺失字段与 null。 */
export const editable = () => defineFeature('content.edit', {
'content.edit': ({ element, input }) => {
const patch = input.patch as Data;
if (!patch || !validJson(patch) || Array.isArray(patch)) throw fault('invalid_data_patch', [element.id]);
// 每个字段携带 before,ACK/重放时才能检查冲突,而不是用整份节点覆盖后来的编辑。
return Object.entries(patch).flatMap(([key, after]): FieldChange[] => {
const before = element.data[key] ?? null;
return Object.hasOwn(element.data, key) && equal(before, after) ? [] : [{ kind: 'field', target: { id: element.id, incarnation: element.incarnation }, field: `data.${key}`, before, after, beforePresent: Object.hasOwn(element.data, key), afterPresent: true }];
});
},
});
/** 内置节点的基础 data 合同:title/text 为字符串,允许其它合法 JSON 扩展字段。 */
const textData = builtinDataValidator((data: Data) => presentationUnitsValid(data.presentation) && validJson(data) && typeof data.title === 'string' && typeof data.text === 'string');
/** 安装文本、图片、脚本、图标、frame 和 connection 的默认定义。
* 节点共用基础行为;frame 不安装旋转行为。复制声明与资源字段也是定义的一部分。 */
export function builtinComponents(): readonly ComponentDefinition[] {
return ['text', 'image', 'script', 'plain-text', 'plain-image', 'icon', 'frame'].map(id => defineComponent({
id, dataVersion: 1, structure: 'node', validate: textData,
features: [movable(), resizable(), ...(id === 'frame' ? [] : [rotatable()]), editable()],
resourceFields: ['image', 'plain-image'].includes(id) ? ['assetId','asset'] : [],
// frame 的 ports 引用必须随复制映射;任务/run/progress 不复制成新的执行任务。
geometry:rectangleGeometry,copy: { references: id === 'frame' ? [{path:['ports','*','nodeId'],target:'element',external:'reject'}] : [], omit: [['taskId'], ['runId'], ['progress'], ['runStatus']] },
})).concat([defineComponent({ id: 'connection', dataVersion: 1, structure: 'connection', validate: builtinDataValidator((data:Data) => validJson(data)), features: [editable(), connectionEditable()], resourceFields: [],geometry:{kind:'connection',version:1,strokeWidth:({element})=>{const appearance=element.data.appearance;return (appearance&&typeof appearance==='object'&&!Array.isArray(appearance)?appearance.width:undefined) as number||1.5;},segments:context=>{if(context.displayPath===undefined||!connectionPathValid(context.displayPath))throw fault('unsupported_connection_geometry');return bezierChainSegments(context.source,context.target,context.displayPath as unknown as BezierChain|null);}}, copy: { references: [], omit: [] } })]);
}
/** null 表示默认连线;否则仅支持最多 64 个 knot 的 bezier-chain,并校验控制点/唯一 ID。 */
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;
// 控制点只能是有限 x/y;缺少坐标、数组或非对象值均不接受。
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>();
@@ -66,6 +86,7 @@ export function connectionPathValid(path: Json): boolean {
}
return true;
}
/** 连线编辑 handler:旧 path 也必须可解释,拒绝用当前协议重写未知曲线路径。 */
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]);