@yft-design/engine 0.0.15 → 0.0.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,8 +8,20 @@
8
8
  * - 退化输入(<3 点 / 零面积)返回 [];共线点直接剔除不产三角形
9
9
  * - 自相交多边形无正确解(canvas nonzero 规则与三角化不可比),
10
10
  * 守卫耗尽后回退扇形三角化——保证终止与索引合法,仅病态数据触发
11
- * - 不支持带洞多边形(clipPath/复合路径属 Phase 4 议题,届时评估 earcut;
12
- * 本实现零依赖是为并行开发期不动 lockfile 的取舍)
11
+ * - 不支持带洞多边形(clipPath/复合路径由 pathData 的洞桥接预先合成简单
12
+ * 多边形;本实现零依赖是为并行开发期不动 lockfile 的取舍——批次 415 起
13
+ * 大环依赖 rbush(引擎运行时既有依赖,document 命中索引同源))
14
+ * - 批次 415:大环 rbush 点索引加速。占据检验(每耳候选 × 其余顶点包含
15
+ * 测试)是 O(n²) 主项——PDF 解析的长曲线 path(数千指令 flatten 后数万
16
+ * 顶点)单环全扫可达秒级,多页模板装载建景实测 15~18s 的 97%。索引后每
17
+ * 耳只测耳 bbox±EPS 内的存活顶点:点在耳三角形内/其边界段上必先落于耳
18
+ * bbox——候选集收缩是数学等价而非近似,谓词与失效语义逐字保留,输出与
19
+ * 全扫逐位一致(spec 内置旧实现副本随机对拍锁定)。
20
+ * 病态实录(批次 415 迭代):先试 uniform grid 失败——PDF 路径顶点全分布
21
+ * 在一维轮廓上,均匀 2D 格的边界格密度远超 n/格数 的均匀假设;洞桥接的
22
+ * 细长跨越耳(对角线远端相连)bbox 横跨大半多边形,「格数×平均密度」的
23
+ * 估计式降级两头挨打(不降级=格框架反噬、降级=全扫基数),真机 15.5s
24
+ * 不可救。rbush 查询返回真实覆盖点集而非估计,两种病态同时消解。
13
25
  */
14
26
  export interface Vec2 {
15
27
  x: number;
@@ -19,6 +31,7 @@ export interface Vec2 {
19
31
  export declare const polygonArea: (points: ArrayLike<Vec2>) => number;
20
32
  /**
21
33
  * 三角化简单多边形,返回三角形索引三元组数组(展开为 [i0,i1,i2, i0,i1,i2, ...])。
22
- * 时间 O(n²) 最坏(耳检验 × 扫描),shape 点数量级(几十~几百)下无感。
34
+ * 时间 O(n²) 最坏(耳检验 × 扫描);≥ INDEX_MIN_VERTICES 顶点自动启用 rbush
35
+ * 点索引,占据检验降为每耳 ~O(耳 bbox 内存活顶点)。
23
36
  */
24
37
  export declare const triangulatePolygon: (points: ArrayLike<Vec2>) => number[];
@@ -8,10 +8,25 @@
8
8
  * - 退化输入(<3 点 / 零面积)返回 [];共线点直接剔除不产三角形
9
9
  * - 自相交多边形无正确解(canvas nonzero 规则与三角化不可比),
10
10
  * 守卫耗尽后回退扇形三角化——保证终止与索引合法,仅病态数据触发
11
- * - 不支持带洞多边形(clipPath/复合路径属 Phase 4 议题,届时评估 earcut;
12
- * 本实现零依赖是为并行开发期不动 lockfile 的取舍)
11
+ * - 不支持带洞多边形(clipPath/复合路径由 pathData 的洞桥接预先合成简单
12
+ * 多边形;本实现零依赖是为并行开发期不动 lockfile 的取舍——批次 415 起
13
+ * 大环依赖 rbush(引擎运行时既有依赖,document 命中索引同源))
14
+ * - 批次 415:大环 rbush 点索引加速。占据检验(每耳候选 × 其余顶点包含
15
+ * 测试)是 O(n²) 主项——PDF 解析的长曲线 path(数千指令 flatten 后数万
16
+ * 顶点)单环全扫可达秒级,多页模板装载建景实测 15~18s 的 97%。索引后每
17
+ * 耳只测耳 bbox±EPS 内的存活顶点:点在耳三角形内/其边界段上必先落于耳
18
+ * bbox——候选集收缩是数学等价而非近似,谓词与失效语义逐字保留,输出与
19
+ * 全扫逐位一致(spec 内置旧实现副本随机对拍锁定)。
20
+ * 病态实录(批次 415 迭代):先试 uniform grid 失败——PDF 路径顶点全分布
21
+ * 在一维轮廓上,均匀 2D 格的边界格密度远超 n/格数 的均匀假设;洞桥接的
22
+ * 细长跨越耳(对角线远端相连)bbox 横跨大半多边形,「格数×平均密度」的
23
+ * 估计式降级两头挨打(不降级=格框架反噬、降级=全扫基数),真机 15.5s
24
+ * 不可救。rbush 查询返回真实覆盖点集而非估计,两种病态同时消解。
13
25
  */
26
+ import RBush from 'rbush';
14
27
  const EPS = 1e-12;
28
+ /** 索引加速阈值:小于该顶点数走全扫(建树成本在小环上不回本) */
29
+ const INDEX_MIN_VERTICES = 96;
15
30
  /** 叉积 (b−a)×(p−a):>0 = p 在 a→b 左侧(屏幕 y 向下时为顺时针侧) */
16
31
  const cross = (ax, ay, bx, by, px, py) => (bx - ax) * (py - ay) - (by - ay) * (px - ax);
17
32
  /** q 落在 a→b 线段范围内(边值 e 为该边叉积,≈0 时按点积区间判定) */
@@ -36,9 +51,30 @@ export const polygonArea = (points) => {
36
51
  }
37
52
  return area / 2;
38
53
  };
54
+ /**
55
+ * 耳候选占据检验(单点):其余顶点严格在耳内、或落在耳边界线段范围内才算
56
+ * 占据。P3-1b 洞桥接引入重合副本顶点与贴边点——早先的含边保守判定把它们
57
+ * 全当占据,整圈无耳耗尽守卫回退扇形(洞被盖住);纯严格内部又放行线段上
58
+ * 的点、产出退化三角。线延长线(段范围外)上的点不阻塞。与耳顶点重合的
59
+ * 点(桥接的 P/M 副本)不构成占据——它就是顶点自身。
60
+ */
61
+ const pointOccupiesEar = (points, qIndex, a, b, c) => {
62
+ const q = points[qIndex];
63
+ if ((Math.abs(q.x - a.x) < EPS && Math.abs(q.y - a.y) < EPS) || (Math.abs(q.x - b.x) < EPS && Math.abs(q.y - b.y) < EPS) || (Math.abs(q.x - c.x) < EPS && Math.abs(q.y - c.y) < EPS)) {
64
+ return false;
65
+ }
66
+ const e1 = cross(a.x, a.y, b.x, b.y, q.x, q.y);
67
+ const e2 = cross(b.x, b.y, c.x, c.y, q.x, q.y);
68
+ const e3 = cross(c.x, c.y, a.x, a.y, q.x, q.y);
69
+ if ((e1 > EPS && e2 > EPS && e3 > EPS) || (e1 < -EPS && e2 < -EPS && e3 < -EPS)) {
70
+ return true;
71
+ }
72
+ return blocksOnSegment(a, b, q, e1) || blocksOnSegment(b, c, q, e2) || blocksOnSegment(c, a, q, e3);
73
+ };
39
74
  /**
40
75
  * 三角化简单多边形,返回三角形索引三元组数组(展开为 [i0,i1,i2, i0,i1,i2, ...])。
41
- * 时间 O(n²) 最坏(耳检验 × 扫描),shape 点数量级(几十~几百)下无感。
76
+ * 时间 O(n²) 最坏(耳检验 × 扫描);≥ INDEX_MIN_VERTICES 顶点自动启用 rbush
77
+ * 点索引,占据检验降为每耳 ~O(耳 bbox 内存活顶点)。
42
78
  */
43
79
  export const triangulatePolygon = (points) => {
44
80
  const n = points.length;
@@ -57,9 +93,34 @@ export const triangulatePolygon = (points) => {
57
93
  // 守卫:耳检验失败轮转上限(自相交多边形可能整圈无耳),耗尽回退扇形
58
94
  let guard = remaining * remaining + 16;
59
95
  let i = 0;
96
+ // rbush 点索引(批次 415):点零尺寸 bbox + 原始下标,load 批建。删点不
97
+ // remove(rbush.remove 清子树重插,逐耳删点是 _all 全树遍历灾难——真机
98
+ // 16s 实录)——存活位标记,查询候选过滤,中期冗余 ≤2× 可接受
99
+ let tree = null;
100
+ let items = null;
101
+ let alive = null;
102
+ if (n >= INDEX_MIN_VERTICES) {
103
+ tree = new RBush();
104
+ items = new Array(n);
105
+ for (let k = 0; k < n; k++) {
106
+ const p = points[k];
107
+ items[k] = { minX: p.x, minY: p.y, maxX: p.x, maxY: p.y, v: k };
108
+ }
109
+ tree.load(items);
110
+ alive = new Uint8Array(n).fill(1);
111
+ }
112
+ // 死锁检测(批次 415 补三):自交环(洞桥接残余形态)上几乎每耳都被占据,
113
+ // 主循环空转到守卫耗尽才兜底——每空转迭代还带一次占据检验,n² 轮转 × O(n)
114
+ // 检验 = O(n³),千点级单环实测秒级(多页 PDF 模板装载 15s 的真凶)。
115
+ // 等价提前退出:转满一圈(remaining 次迭代)无任何删点 ⟹ (order, remaining,
116
+ // i) 状态完全复原(无删点时每迭代 i++,环绕归位)⟹ 恒空转到守卫耗尽走同
117
+ // 一兜底——此处直接 break 进兜底,输出逐位一致
118
+ let staleIterations = 0;
60
119
  while (remaining > 3 && guard-- > 0) {
61
120
  if (i >= remaining)
62
121
  i = 0;
122
+ if (++staleIterations > remaining)
123
+ break;
63
124
  const i0 = order[i];
64
125
  const i1 = order[(i + 1) % remaining];
65
126
  const i2 = order[(i + 2) % remaining];
@@ -68,40 +129,55 @@ export const triangulatePolygon = (points) => {
68
129
  const c = points[i2];
69
130
  const crossVal = cross(a.x, a.y, b.x, b.y, c.x, c.y);
70
131
  if (crossVal > EPS) {
71
- // 凸耳候选:其余顶点严格在耳内、或落在耳边界线段范围内才算占据。P3-1b
72
- // 洞桥接引入重合副本顶点与贴边点——早先的含边保守判定把它们全当占据,
73
- // 整圈无耳耗尽守卫回退扇形(洞被盖住);纯严格内部又放行线段上的点、
74
- // 产出退化三角。线延长线(段范围外)上的点不阻塞
132
+ // 凸耳候选:其余存活顶点均不占据才剪
75
133
  let occupied = false;
76
- for (let j = 3; j < remaining; j++) {
77
- const q = points[order[(i + j) % remaining]];
78
- // 与耳顶点重合的点(桥接的 P/M 副本)不构成占据——它就是顶点自身
79
- if ((Math.abs(q.x - a.x) < EPS && Math.abs(q.y - a.y) < EPS) || (Math.abs(q.x - b.x) < EPS && Math.abs(q.y - b.y) < EPS) || (Math.abs(q.x - c.x) < EPS && Math.abs(q.y - c.y) < EPS)) {
80
- continue;
134
+ if (tree && items) {
135
+ // 耳 bbox±EPS 查询:占据者(严格内部或骑边)必在其中(rbush 精确
136
+ // bbox 相交,无均匀密度假设——细长耳/轮廓密集分布两病态同解);
137
+ // 骑边恰在边界的浮点余量由 ±EPS 承接,与谓词自身容差同口径
138
+ const earMinX = Math.min(a.x, b.x, c.x) - EPS;
139
+ const earMaxX = Math.max(a.x, b.x, c.x) + EPS;
140
+ const earMinY = Math.min(a.y, b.y, c.y) - EPS;
141
+ const earMaxY = Math.max(a.y, b.y, c.y) + EPS;
142
+ const hits = tree.search({ minX: earMinX, minY: earMinY, maxX: earMaxX, maxY: earMaxY });
143
+ for (let h = 0; h < hits.length; h++) {
144
+ const v = hits[h].v;
145
+ if (!alive[v])
146
+ continue;
147
+ if (v === i0 || v === i1 || v === i2)
148
+ continue;
149
+ if (pointOccupiesEar(points, v, a, b, c)) {
150
+ occupied = true;
151
+ break;
152
+ }
81
153
  }
82
- const e1 = cross(a.x, a.y, b.x, b.y, q.x, q.y);
83
- const e2 = cross(b.x, b.y, c.x, c.y, q.x, q.y);
84
- const e3 = cross(c.x, c.y, a.x, a.y, q.x, q.y);
85
- if ((e1 > EPS && e2 > EPS && e3 > EPS) || (e1 < -EPS && e2 < -EPS && e3 < -EPS)) {
86
- occupied = true;
87
- break;
88
- }
89
- if (blocksOnSegment(a, b, q, e1) || blocksOnSegment(b, c, q, e2) || blocksOnSegment(c, a, q, e3)) {
90
- occupied = true;
91
- break;
154
+ }
155
+ else {
156
+ for (let j = 3; j < remaining; j++) {
157
+ const v = order[(i + j) % remaining];
158
+ if (pointOccupiesEar(points, v, a, b, c)) {
159
+ occupied = true;
160
+ break;
161
+ }
92
162
  }
93
163
  }
94
164
  if (!occupied) {
95
165
  triangles.push(i0, i1, i2);
96
- order.splice((i + 1) % remaining, 1);
166
+ const removed = order.splice((i + 1) % remaining, 1)[0];
97
167
  remaining--;
168
+ if (alive)
169
+ alive[removed] = 0;
170
+ staleIterations = 0;
98
171
  continue;
99
172
  }
100
173
  }
101
174
  else if (crossVal >= -EPS) {
102
175
  // 共线零面积顶点:直接剔除,防止扫描卡死
103
- order.splice((i + 1) % remaining, 1);
176
+ const removed = order.splice((i + 1) % remaining, 1)[0];
104
177
  remaining--;
178
+ if (alive)
179
+ alive[removed] = 0;
180
+ staleIterations = 0;
105
181
  continue;
106
182
  }
107
183
  i++;
@@ -1696,7 +1696,7 @@ export class SvgExporter {
1696
1696
  // 圆族 dims 兜底(model/scene ShapeNode.dims 同式):circle=2·radius、
1697
1697
  // ellipse=2·rx/ry——fabric 序列化原生带 radius/rx/ry,width/height 可缺席
1698
1698
  // (2026-10-08 报障:radius-only Circle 记 dims-missing:Circle 整页回退)
1699
- if (type.toLowerCase() === 'circle') {
1699
+ if (type === ElementTypes.CIRCLE) {
1700
1700
  const r = 2 * num(raw, 'radius', NaN);
1701
1701
  if (!Number.isFinite(width))
1702
1702
  width = r;
@@ -31,6 +31,7 @@ import { AnimatedNode, MaskNode } from '../model/scene';
31
31
  import { maskCropLiveState, maskCropWriteProps } from '../model/maskCropEdit';
32
32
  import { applyCropCorner, applyCropEdge, applyCropRatioCorner, applyCropRatioPreset, applyScaleEquallyCrop, CROP_HANDLE_OFFSETS, fullImageCornerLocal, liveStateFromRaw, liveStateToRawProps, moveCropImage } from '../model/cropEdit';
33
33
  import { isCornerHandle } from '../model/handles';
34
+ import { CompatHistoryActions } from '../model/compatEvents';
34
35
  import { lineQuad } from '../render/selectionOverlay';
35
36
  /** 手柄命中半径(屏幕 px;fabric 口径 cornerSize 13 方形域的圆近似)。
36
37
  * 圆手柄贴视觉直径放大(16px)取 14——同心(crop=0)时让位角括号
@@ -276,7 +277,7 @@ export class CropSessionController {
276
277
  this.detachKey?.();
277
278
  this.detachKey = null;
278
279
  // 应用 fireCropImageEvent:每退必发(无变化也发——应用历史层按 action 分流)
279
- this.host.document.applyTransform([node], () => ({}), 'modified', { action: 'crop' });
280
+ this.host.document.applyTransform([node], () => ({}), 'modified', { action: CompatHistoryActions.crop });
280
281
  this.host.requestRenderAll();
281
282
  }
282
283
  /** pointer 点框外通道(应用 canvasMouseDown 的退出分支,同 exit) */
@@ -14,6 +14,7 @@ import { clampExpandImageCenter, expandPixelOffsets, expandRectOf, EXPAND_HANDLE
14
14
  import { AnimatedNode, MaskNode } from '../model/scene';
15
15
  import { objectOriginFromCenter, transformPoint } from '../core/mat2d';
16
16
  import { lineQuad } from '../render/selectionOverlay';
17
+ import { CompatHistoryActions } from '../model/compatEvents';
17
18
  import { parseColor } from '../core/color';
18
19
  const rad = (deg) => (deg * Math.PI) / 180;
19
20
  const HANDLE_HIT_PX = 12;
@@ -124,7 +125,7 @@ export class ExpandSessionController {
124
125
  expandBottomOffset: offsets.bottom
125
126
  });
126
127
  }
127
- this.host.document.applyTransform([node], () => ({}), 'modified', { action: 'crop' });
128
+ this.host.document.applyTransform([node], () => ({}), 'modified', { action: CompatHistoryActions.crop });
128
129
  this.host.requestRenderAll();
129
130
  }
130
131
  exitByOutsideClick() {
@@ -5,6 +5,7 @@
5
5
  * 薄委托(公开 API 面不变)。
6
6
  */
7
7
  import { isReferenceLineNode, WORKSPACE_IDS } from '../model/scene';
8
+ import { CompatHistoryActions } from '../model/compatEvents';
8
9
  /** Ctrl+A:全选可见对象(排除 workspace 族——应用 selectAllElement 同口径;
9
10
  * 原只滤 DrawType,Clip/Safe/Line 等装饰层会漏进全选;参考线排除(批次 72)
10
11
  * ——引导 chrome 非内容,fabric 落定线 selectable:false 同不进全选) */
@@ -35,7 +36,7 @@ export function nudgeSelectionAction(doc, dx, dy, requestRenderAll) {
35
36
  doc.setProps(node, { left: (node.raw.left ?? 0) + dx, top: (node.raw.top ?? 0) + dy }, { deferIndexRebuild: true });
36
37
  }
37
38
  doc.commitGeometry();
38
- doc.events.fire('object:modified', targets, { action: 'drag', before });
39
+ doc.fireObjectModified(targets, { action: CompatHistoryActions.drag, before });
39
40
  requestRenderAll();
40
41
  return targets.length;
41
42
  }
@@ -26,6 +26,7 @@
26
26
  * 手势同步维护,选框刚性跟随而非按成员 AABB 重新拟合。
27
27
  */
28
28
  import { createNode, createReferenceLineRaw, GroupNode, isReferenceLineNode, PuzzleNode, TableNode } from '../model/scene';
29
+ import { CompatHistoryActions } from '../model/compatEvents';
29
30
  import { RULER_SIZE } from '../render/ruler';
30
31
  import { buildSelectionRange, getBorderCursor, selectionBounds } from '../model/tableEdit';
31
32
  import { CORNER_ROTATE_CURSOR_OFFSET, CORNER_ROTATE_ZONE_PX, cornerOffsetToRadius, getActiveChildHandles, getAdaptiveSelectionHandles, getCornerRotateZones, HANDLE_HIT_PX, isImageRadiusHandleNode, isRadiusHandleNode, isUserLockedNode, MOVE_CONTROL_HIT_PX, moveControlPosition, moveControlTarget, radiusHandleTarget, rectCornerMaxRadius, rotateControlSpecByAngle, selectionQuadCoords } from '../render/selectionOverlay';
@@ -1535,12 +1536,12 @@ export class PointerController {
1535
1536
  // 全部将被触碰的节点
1536
1537
  const touched = refitGroupShells(g.childMove.shells);
1537
1538
  const targets = [...new Set([g.childMove.child, ...touched])];
1538
- doc.applyTransform(targets, () => ({}), 'modified', { action: 'drag', before: g.historyBefore });
1539
+ doc.applyTransform(targets, () => ({}), 'modified', { action: CompatHistoryActions.drag, before: g.historyBefore });
1539
1540
  }
1540
1541
  else {
1541
1542
  const nodes = [...g.snapshot.keys()];
1542
1543
  if (!this.host.transferDraggedNodes?.(nodes, g.historyBefore, cssX, cssY)) {
1543
- doc.applyTransform(nodes, () => ({}), 'modified', { action: 'drag', before: g.historyBefore });
1544
+ doc.applyTransform(nodes, () => ({}), 'modified', { action: CompatHistoryActions.drag, before: g.historyBefore });
1544
1545
  }
1545
1546
  }
1546
1547
  }
@@ -1567,10 +1568,10 @@ export class PointerController {
1567
1568
  const band = this.host.rulerVisible ? rulerBandAt(cssX, cssY) : null;
1568
1569
  if (band === g.axis || (g.creating && !this.performed)) {
1569
1570
  doc.remove(g.node);
1570
- doc.events.fire('object:modified', [g.node], { action: 'drag', before: g.historyBefore ? [g.historyBefore.get(g.node)].filter((s) => !!s) : undefined });
1571
+ doc.fireObjectModified([g.node], { action: CompatHistoryActions.drag, before: g.historyBefore ? [g.historyBefore.get(g.node)].filter((s) => !!s) : undefined });
1571
1572
  }
1572
1573
  else if (this.performed) {
1573
- doc.applyTransform([g.node], () => ({ selectable: false }), 'modified', { action: 'drag', before: g.historyBefore });
1574
+ doc.applyTransform([g.node], () => ({ selectable: false }), 'modified', { action: CompatHistoryActions.drag, before: g.historyBefore });
1574
1575
  }
1575
1576
  }
1576
1577
  else if (g.type === 'scale' || g.type === 'rotate') {
@@ -1591,11 +1592,11 @@ export class PointerController {
1591
1592
  // 圆角拖拽收尾(批次 100):action='cornerRadius'(fabric transform 的
1592
1593
  // actionName 原值),before 快照含旧 radius 供撤销回放
1593
1594
  if (this.performed)
1594
- doc.applyTransform([g.node], () => ({}), 'modified', { action: 'cornerRadius', before: g.historyBefore });
1595
+ doc.applyTransform([g.node], () => ({}), 'modified', { action: CompatHistoryActions.cornerRadius, before: g.historyBefore });
1595
1596
  }
1596
1597
  else if (g.type === 'multi-scale' || g.type === 'multi-rotate') {
1597
1598
  if (this.performed)
1598
- doc.applyTransform(g.snapshot.members.map((m) => m.node), () => ({}), 'modified', { action: g.type === 'multi-scale' ? 'scale' : 'rotate', before: g.historyBefore });
1599
+ doc.applyTransform(g.snapshot.members.map((m) => m.node), () => ({}), 'modified', { action: g.type === 'multi-scale' ? CompatHistoryActions.scale : CompatHistoryActions.rotate, before: g.historyBefore });
1599
1600
  }
1600
1601
  else if (g.type === 'marquee') {
1601
1602
  doc.commitGeometry();
@@ -1619,23 +1620,23 @@ export class PointerController {
1619
1620
  g.node.borderDragging = false;
1620
1621
  if (this.performed) {
1621
1622
  g.node.rebuildTable();
1622
- doc.applyTransform([g.node], () => ({}), 'modified', { action: 'scale', before: g.historyBefore });
1623
+ doc.applyTransform([g.node], () => ({}), 'modified', { action: CompatHistoryActions.scale, before: g.historyBefore });
1623
1624
  }
1624
1625
  }
1625
1626
  else if (g.type === 'table-edge-resize') {
1626
1627
  // 逐帧已烘焙重排并回钉;up 只提交(纯点击不发历史)
1627
1628
  if (this.performed)
1628
- doc.applyTransform([g.node], () => ({}), 'modified', { action: 'scale', before: g.historyBefore });
1629
+ doc.applyTransform([g.node], () => ({}), 'modified', { action: CompatHistoryActions.scale, before: g.historyBefore });
1629
1630
  }
1630
1631
  else if (g.type === 'puzzle-edge-resize') {
1631
1632
  // 同 table-edge-resize:逐帧已烘焙并回钉,up 只提交(纯点击不发历史)
1632
1633
  if (this.performed)
1633
- doc.applyTransform([g.node], () => ({}), 'modified', { action: 'scale', before: g.historyBefore });
1634
+ doc.applyTransform([g.node], () => ({}), 'modified', { action: CompatHistoryActions.scale, before: g.historyBefore });
1634
1635
  }
1635
1636
  else if (g.type === 'puzzle-mask-edge-resize') {
1636
1637
  // 分割线拖拽逐帧已写回;up 对拼图组提交一条(应用 historyTarget=group 同口径)
1637
1638
  if (this.performed)
1638
- doc.applyTransform([g.node], () => ({}), 'modified', { action: 'scale', before: g.historyBefore });
1639
+ doc.applyTransform([g.node], () => ({}), 'modified', { action: CompatHistoryActions.scale, before: g.historyBefore });
1639
1640
  }
1640
1641
  else if (g.type === 'table-indicator-click') {
1641
1642
  // up 时复核指示器命中(fabric 控件 mouseUp 在 up 命中的控件上触发,移开即不插入)
@@ -24,6 +24,7 @@ import { DocBusBinder } from '../core/events';
24
24
  import { TextNode } from '../model/scene';
25
25
  import { getCellData, masterPosition } from '../model/tableEdit';
26
26
  import { TextAlignValues } from '../model/textAlign';
27
+ import { CompatHistoryActions } from '../model/compatEvents';
27
28
  /** 应用 TableDefaultOptions.fontSize(tableLayout 的 CONSTRUCTOR_FONT_SIZE 同源) */
28
29
  const DEFAULT_FONT_SIZE = 14;
29
30
  /** 应用 Table.defaults.fontFamily(fromObject 不透传——表格级恒为应用默认) */
@@ -190,7 +191,7 @@ export class TableCellEditingController {
190
191
  // 整表全量写回含 cellData;TableNode.set 的结构键自动重排承接视觉恢复)
191
192
  const beforeMap = new Map();
192
193
  beforeMap.set(s.table, JSON.parse(s.snapshot));
193
- doc.applyTransform([s.table], () => ({}), 'modified', { action: 'table-cell-edit', before: beforeMap });
194
+ doc.applyTransform([s.table], () => ({}), 'modified', { action: CompatHistoryActions.tableCellEdit, before: beforeMap });
194
195
  }
195
196
  this.host.requestRenderAll();
196
197
  }
@@ -34,6 +34,7 @@
34
34
  import { Warpvas } from 'warpvas';
35
35
  import { AnimatedNode } from '../model/scene';
36
36
  import { objectOriginFromCenter, transformPoint } from '../core/mat2d';
37
+ import { CompatHistoryActions } from '../model/compatEvents';
37
38
  import { lineQuad } from '../render/selectionOverlay';
38
39
  /** 锚点命中半径(屏幕 px;fabric controls cornerSize 口径的圆近似) */
39
40
  const ANCHOR_HIT_PX = 12;
@@ -448,7 +449,7 @@ export class WarpSessionController {
448
449
  // objectModifiedDirtyHandler 标脏/刷内存 templates[i](扭曲状态入
449
450
  // templates[i]——保存/翻页真正读的数据源;此前退出零事件,store 不知
450
451
  // 情 =「扭曲状态没有记录」根因:保存回旧图、翻页回旧图)
451
- this.host.document.applyTransform([node], () => ({}), 'modified', { action: 'warpvas-image', before: new Map([[node, before]]) });
452
+ this.host.document.applyTransform([node], () => ({}), 'modified', { action: CompatHistoryActions.warpImage, before: new Map([[node, before]]) });
452
453
  committed = true;
453
454
  }
454
455
  this.requestRenderAll();
@@ -47,8 +47,10 @@ import { bakePsdShadow, bakePsdStrokes } from '../render/imageEffects';
47
47
  /** 掩码单边上限(同 app alphaMask:512×512=256KB/张) */
48
48
  const ALPHA_MASK_MAX_SIZE = 512;
49
49
  /** 生成类位图(二维码/条码/图表):内容整块生成无镂空语义,命中恒实心。
50
- * QRCode 另按 name 兜底豁免(app _checkTransparencyWithCache 同款)。 */
51
- const GENERATED_IMAGE_TYPES = new Set(['qrcode', 'QRCode', 'barcode', 'BarCode', 'echart', 'FabricEchart']);
50
+ * 判型一律走 typeKey——raw.type 保留 fabric toObject 原始大小写('QRCode'/
51
+ * 'BarCode'),裸比对会漏豁免。QRCode 另按 name 兜底豁免(app
52
+ * _checkTransparencyWithCache 同款)。 */
53
+ const GENERATED_IMAGE_TYPES = new Set([ElementTypes.QRCODE, ElementTypes.BARCODE, ElementTypes.ECHART, ElementTypes.FABRIC_ECHART]);
52
54
  /** 扩出型效果声明(引擎真渲染且扩出源 alpha 之外):dropShadow(阴影画在源外)
53
55
  * 与 stroke(outside/center 段超出源轮廓)。null = 无(掩码只看源 alpha)。 */
54
56
  const extendingFxDecls = (node) => {
@@ -246,11 +248,13 @@ export const isHitTransparent = (node, x, y, ctx) => {
246
248
  return !groupChildHitAt(node, x, y, ctx);
247
249
  if (!node.isImageType)
248
250
  return false;
249
- if (GENERATED_IMAGE_TYPES.has(node.raw.type))
251
+ // 判型走 typeKey(小写坍缩):raw.type 是 fabric toObject 原始大小写——模板
252
+ // 序列化图片恒 'Image',裸比对过不了小写集合 → 误判实心 → 透传失效(模板269)
253
+ if (GENERATED_IMAGE_TYPES.has(node.typeKey))
250
254
  return false;
251
255
  if (typeof node.raw.name === 'string' && node.raw.name.toLowerCase() === 'qrcode')
252
256
  return false;
253
- if (!IMAGE_LIKE_TYPES.has(node.raw.type))
257
+ if (!IMAGE_LIKE_TYPES.has(node.typeKey))
254
258
  return false;
255
259
  // PSD 效果不设门:solidFill 族 α⊆源由源掩码涵盖;扩出型(阴影/描边)的
256
260
  // alpha 已并进掩码(unionExtendingFxAlpha)——效果层 bake 失败时掩码为
@@ -21,6 +21,28 @@ export interface CompatSelectionEvent {
21
21
  export interface CompatObjectEvent {
22
22
  target: CompatObject;
23
23
  }
24
+ /**
25
+ * compat 历史协议常量(P3 历史契约升级,2026-10-16——主仓风险册 R1/R12):
26
+ * - 动作名以本常量对象为**唯一事实源**——引擎内发射点一律引用成员,不再散布
27
+ * 裸字符串;应用侧消费判定(如 crop 族跳过录制)经主仓锁定 spec 对齐本源,
28
+ * 引擎侧改名/删除时主仓测试拦红(而非靠注释约定)。
29
+ * - protocolVersion:compat 事件契约版本。1 = 无版本位现状(≤v0.0.16);
30
+ * 2 = object:modified 携带 transactionId/protocolVersion。应用侧对
31
+ * 「事件携带版本 < 期望版本」告警;缺省(旧引擎)不告警。
32
+ */
33
+ export declare const COMPAT_PROTOCOL_VERSION = 2;
34
+ export declare const CompatHistoryActions: {
35
+ /** 指针拖拽 / 方向键平移 */
36
+ readonly drag: "drag";
37
+ /** 缩放手柄族(手势类型值亦为 'scale'/'rotate',经 g.type 透出) */
38
+ readonly scale: "scale";
39
+ readonly rotate: "rotate";
40
+ readonly cornerRadius: "cornerRadius";
41
+ /** crop 族:应用历史层跳过录制(cropSession / expandSession 同值) */
42
+ readonly crop: "crop";
43
+ readonly tableCellEdit: "table-cell-edit";
44
+ readonly warpImage: "warpvas-image";
45
+ };
24
46
  export interface CompatObjectModifiedEvent extends CompatObjectEvent {
25
47
  /** 引擎批量语义的原生载荷;fabric 单 target 之上的扩展字段 */
26
48
  targets?: CompatObject[];
@@ -30,8 +52,15 @@ export interface CompatObjectModifiedEvent extends CompatObjectEvent {
30
52
  transform?: {
31
53
  original?: unknown;
32
54
  };
33
- /** fabric 动作名(drag/scale/rotate;crop 族供历史层跳过录制) */
55
+ /** fabric 动作名(值域=CompatHistoryActions;crop 族供历史层跳过录制) */
34
56
  action?: string;
57
+ /** 事务锚点(P3/R12):一次用户事务(手势/会话/编辑退出)= 一个 id,引擎侧
58
+ * 统一生成并随事件透出;应用侧透传进 History.transactionId(主仓 buildHistory
59
+ * 的 ?? 透传位),把「一次操作」锚成可对账的链。 */
60
+ transactionId?: string;
61
+ /** compat 事件协议版本(P3/R1):缺省 = 1(≤v0.0.16 无版本位);应用侧对
62
+ * 低于期望版本的携带值告警(双仓字段漂移的运行时观测位)。 */
63
+ protocolVersion?: number;
35
64
  }
36
65
  /** 引擎扩展事件(fabric 没有):一次文本编辑会话的 before/after 差值提交 */
37
66
  export interface CompatTextCommittedEvent {
@@ -1,3 +1,25 @@
1
+ /**
2
+ * compat 历史协议常量(P3 历史契约升级,2026-10-16——主仓风险册 R1/R12):
3
+ * - 动作名以本常量对象为**唯一事实源**——引擎内发射点一律引用成员,不再散布
4
+ * 裸字符串;应用侧消费判定(如 crop 族跳过录制)经主仓锁定 spec 对齐本源,
5
+ * 引擎侧改名/删除时主仓测试拦红(而非靠注释约定)。
6
+ * - protocolVersion:compat 事件契约版本。1 = 无版本位现状(≤v0.0.16);
7
+ * 2 = object:modified 携带 transactionId/protocolVersion。应用侧对
8
+ * 「事件携带版本 < 期望版本」告警;缺省(旧引擎)不告警。
9
+ */
10
+ export const COMPAT_PROTOCOL_VERSION = 2;
11
+ export const CompatHistoryActions = {
12
+ /** 指针拖拽 / 方向键平移 */
13
+ drag: 'drag',
14
+ /** 缩放手柄族(手势类型值亦为 'scale'/'rotate',经 g.type 透出) */
15
+ scale: 'scale',
16
+ rotate: 'rotate',
17
+ cornerRadius: 'cornerRadius',
18
+ /** crop 族:应用历史层跳过录制(cropSession / expandSession 同值) */
19
+ crop: 'crop',
20
+ tableCellEdit: 'table-cell-edit',
21
+ warpImage: 'warpvas-image'
22
+ };
1
23
  /** 把 EngineDocument 事件桥接成 compat 口径;返回解绑函数 */
2
24
  export const attachDocumentEventBridge = (document, deps) => {
3
25
  const { bus, wrap, syncSelection, settleSnap } = deps;
@@ -39,7 +61,8 @@ export const attachDocumentEventBridge = (document, deps) => {
39
61
  const beforeAll = detail?.before;
40
62
  const before = beforeAll?.length ? keep.map((i) => beforeAll[i]).filter((s) => !!s) : undefined;
41
63
  const transform = before && (before.length > 1 || keep.length > 1) ? { original: { objects: before } } : before ? { original: before[0] } : undefined;
42
- bus.fire('object:modified', { target: wrapped[0], targets: wrapped, transform, action: detail?.action });
64
+ // P3 历史契约:事务锚点与协议版本随事件透出(tid 由 document 发射层统一补全)
65
+ bus.fire('object:modified', { target: wrapped[0], targets: wrapped, transform, action: detail?.action, transactionId: detail?.transactionId, protocolVersion: COMPAT_PROTOCOL_VERSION });
43
66
  }),
44
67
  ev.on('text:editing:entered', (node) => fireObject('text:editing:entered', node)),
45
68
  ev.on('text:editing:exited', (node) => fireObject('text:editing:exited', node)),
@@ -532,7 +532,7 @@ export declare class CompatObject {
532
532
  refreshTextDimensions(): void;
533
533
  /** 应用 Textbox.replaceFontFamily 逐字移植:对象级 + 逐字 styles 同步替换 */
534
534
  replaceFontFamily(oldFont: string, newFont: string): boolean;
535
- /** 引擎 raw.type 小写归一(类型键两形态并存) */
535
+ /** 引擎 raw.type 小写归一(类型键两形态并存;typeKeyOf 单源) */
536
536
  private get rawTypeLower();
537
537
  /** 应用 ArcText.setRadius(→setCurvature):曲率直写(引擎 arcLayout 同键消费,
538
538
  * curvature=1° 也经 radius=1e5 近直渲染——0 值合法) */
@@ -28,6 +28,9 @@ import { isGroupWidthHandleNode } from './groupResize';
28
28
  import { deriveArcCharTransformations } from './arcTextTransform';
29
29
  import { buildEngineShapePath } from './shapePath';
30
30
  import { attachTableFacade } from './tableFacade';
31
+ /** 变形文字族(archtext/waisttext/flagtext):setWarpStrength/clearCache 门
32
+ * (const 对象数组 includes 对 string 协变拒绝——模块级 string 集合单源) */
33
+ const WARP_TEXT_TYPES = new Set([ElementTypes.ARCHTEXT, ElementTypes.WAISTTEXT, ElementTypes.FLAGTEXT]);
31
34
  /** 文本排版三件的快照形态校验(svgExport.parseTextLayout 同口径——string[] 行 +
32
35
  * 逐行 charBox 数组 + finite 行高;不引引擎 export 模块防依赖倒挂) */
33
36
  const isValidTextLayoutSnapshot = (o) => {
@@ -104,7 +107,7 @@ export class CompatObject {
104
107
  // 拼图 resizeByContainer 同语义):next = cover(new) × (prev / cover(old)),
105
108
  // 幂等。同批显式写 clipImage 的面自带语义跳过(防双重折算)。
106
109
  let propsToWrite = props;
107
- if ((typeof props.width === 'number' || typeof props.height === 'number') && !('clipImage' in props) && MASK_TYPES.has(String(this.node.raw.type ?? ''))) {
110
+ if ((typeof props.width === 'number' || typeof props.height === 'number') && !('clipImage' in props) && MASK_TYPES.has(typeKeyOf(this.node.raw))) {
108
111
  const clip = clipImageRawOf(this.node);
109
112
  const raw = this.node.raw;
110
113
  const prevW = Number(raw.width) || 0;
@@ -772,7 +775,7 @@ export class CompatObject {
772
775
  /** fabric isType:types 含 constructor.type 或 this.type——引擎 raw.type 兼存小写
773
776
  * 形态('rect')而应用调用恒用规范名,改大小写不敏感比对(check.isTextObject 等消费) */
774
777
  isType(...types) {
775
- const own = String(this.node.raw.type ?? '').toLowerCase();
778
+ const own = typeKeyOf(this.node.raw);
776
779
  return types.some((type) => type.toLowerCase() === own);
777
780
  }
778
781
  /** fabric getStyleAtPosition(fontSize 多值检测等消费):扁平字符位按 '\n' 分解到
@@ -1070,21 +1073,21 @@ export class CompatObject {
1070
1073
  // 存在性=类型判别器(ARC/WARP/CIRCLE 变形面板按 typeof 判可写),按文本子类型
1071
1074
  // 条件暴露;引擎布局键同名直读 raw(arcLayout 消费 curvature/circle*、warpText
1072
1075
  // 消费 warpStrength),写值经 set 触发排版重算与重绘 ——
1073
- /** 引擎 raw.type 小写归一(类型键两形态并存) */
1076
+ /** 引擎 raw.type 小写归一(类型键两形态并存;typeKeyOf 单源) */
1074
1077
  get rawTypeLower() {
1075
- return String(this.node.raw.type ?? '').toLowerCase();
1078
+ return typeKeyOf(this.node.raw);
1076
1079
  }
1077
1080
  /** 应用 ArcText.setRadius(→setCurvature):曲率直写(引擎 arcLayout 同键消费,
1078
1081
  * curvature=1° 也经 radius=1e5 近直渲染——0 值合法) */
1079
1082
  get setRadius() {
1080
- if (this.rawTypeLower !== 'arctext')
1083
+ if (this.rawTypeLower !== ElementTypes.ARCTEXT)
1081
1084
  return undefined;
1082
1085
  return (value) => this.set({ curvature: value });
1083
1086
  }
1084
1087
  /** 应用 ArchText/WaistText/FlagText.setWarpStrength:钳 [-1,1] 后直写(引擎
1085
1088
  * warpText 同键消费;原实现的 store setElement 同步由面板历史链承接,不重复) */
1086
1089
  get setWarpStrength() {
1087
- if (!['archtext', 'waisttext', 'flagtext'].includes(this.rawTypeLower))
1090
+ if (!WARP_TEXT_TYPES.has(this.rawTypeLower))
1088
1091
  return undefined;
1089
1092
  return (value) => this.set({ warpStrength: Math.max(-1, Math.min(1, value)) });
1090
1093
  }
@@ -1094,7 +1097,7 @@ export class CompatObject {
1094
1097
  * font.ts rerenderTextObjects/refreshReplacedTextElements 的 typeof 守卫消费面
1095
1098
  * 同步点亮。ArchText 同烘焙族顺带覆盖(fabric 侧由各自 _render 缓存键自愈) */
1096
1099
  get clearCache() {
1097
- if (!['archtext', 'waisttext', 'flagtext'].includes(this.rawTypeLower))
1100
+ if (!WARP_TEXT_TYPES.has(this.rawTypeLower))
1098
1101
  return undefined;
1099
1102
  return () => {
1100
1103
  this.ctx.invalidateNodeBakes?.(this.node);
@@ -1104,7 +1107,7 @@ export class CompatObject {
1104
1107
  /** 应用 CircleText.setCircleParams:补丁直写(circleSize/circleStartAngle/
1105
1108
  * circleSweep/circleEccentricity/circleDirection——引擎 arcLayout 同键消费) */
1106
1109
  get setCircleParams() {
1107
- if (this.rawTypeLower !== 'circletext')
1110
+ if (this.rawTypeLower !== ElementTypes.CIRCLETEXT)
1108
1111
  return undefined;
1109
1112
  return (patch) => this.set(patch);
1110
1113
  }
@@ -48,6 +48,10 @@ export interface SelectionFrame {
48
48
  export interface ObjectModifiedDetail {
49
49
  action?: string;
50
50
  before?: SerializedNode[];
51
+ /** 事务锚点(P3/R12,2026-10-16):一次用户事务=一个 id。调用方(会话)携带
52
+ * 则透传共享;缺省由 fireObjectModified 统一生成——引擎内所有 object:modified
53
+ * 必经该发射口,保证事件恒带 tid。 */
54
+ transactionId?: string;
51
55
  }
52
56
  export interface EngineDocumentEvents {
53
57
  'selection:created': [targets: SceneNode[]];
@@ -269,7 +273,15 @@ export declare class EngineDocument {
269
273
  applyTransform(targets: SceneNode[], props: (target: SceneNode) => Partial<SerializedNode>, phase: 'moving' | 'scaling' | 'rotating' | 'cornerRadius' | 'modified', detail?: {
270
274
  action?: string;
271
275
  before?: Map<SceneNode, SerializedNode>;
276
+ transactionId?: string;
272
277
  }): void;
278
+ /**
279
+ * object:modified 的统一发射口(P3 历史契约,2026-10-16——主仓风险册 R12):
280
+ * detail 携带调用方 transactionId 则透传(同会话多事件共享一事务),缺省
281
+ * 生成——引擎内**所有** object:modified 必经此口(applyTransform/文本编辑
282
+ * 退出/直发手势收尾),保证事件恒带事务锚点。增量字段,旧订阅方零改动。
283
+ */
284
+ fireObjectModified(targets: SceneNode[], detail?: ObjectModifiedDetail): void;
273
285
  enterEditing(node: TextNode, options?: {
274
286
  transient?: boolean;
275
287
  }): void;