@yft-design/engine 0.0.0-stage → 0.0.2

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.
Files changed (255) hide show
  1. package/README.md +39 -2
  2. package/assets/images/greyfloral.png +0 -0
  3. package/assets/images/honey_im_subtle.png +0 -0
  4. package/assets/images/nasty_fabric.png +0 -0
  5. package/assets/images/retina_wood.png +0 -0
  6. package/assets/images/rotate.png +0 -0
  7. package/dist/EngineCanvas.d.ts +500 -0
  8. package/dist/EngineCanvas.js +927 -0
  9. package/dist/core/canvasPerf.d.ts +23 -0
  10. package/dist/core/canvasPerf.js +170 -0
  11. package/dist/core/color.d.ts +52 -0
  12. package/dist/core/color.js +107 -0
  13. package/dist/core/distanceField.d.ts +15 -0
  14. package/dist/core/distanceField.js +92 -0
  15. package/dist/core/events.d.ts +34 -0
  16. package/dist/core/events.js +52 -0
  17. package/dist/core/gradient.d.ts +97 -0
  18. package/dist/core/gradient.js +175 -0
  19. package/dist/core/imageFilters.d.ts +150 -0
  20. package/dist/core/imageFilters.js +330 -0
  21. package/dist/core/mat2d.d.ts +151 -0
  22. package/dist/core/mat2d.js +241 -0
  23. package/dist/core/pathData.d.ts +53 -0
  24. package/dist/core/pathData.js +926 -0
  25. package/dist/core/pattern.d.ts +38 -0
  26. package/dist/core/pattern.js +40 -0
  27. package/dist/core/point.d.ts +59 -0
  28. package/dist/core/point.js +119 -0
  29. package/dist/core/psdEffects.d.ts +126 -0
  30. package/dist/core/psdEffects.js +158 -0
  31. package/dist/core/roundedRect.d.ts +62 -0
  32. package/dist/core/roundedRect.js +163 -0
  33. package/dist/core/shadow.d.ts +51 -0
  34. package/dist/core/shadow.js +47 -0
  35. package/dist/core/snap.d.ts +232 -0
  36. package/dist/core/snap.js +793 -0
  37. package/dist/core/stroke.d.ts +41 -0
  38. package/dist/core/stroke.js +44 -0
  39. package/dist/core/triangulate.d.ts +24 -0
  40. package/dist/core/triangulate.js +118 -0
  41. package/dist/debug/canvasInspection.d.ts +92 -0
  42. package/dist/debug/canvasInspection.js +113 -0
  43. package/dist/debug/pixelDiff.d.ts +22 -0
  44. package/dist/debug/pixelDiff.js +64 -0
  45. package/dist/debug/seed.d.ts +473 -0
  46. package/dist/debug/seed.js +3803 -0
  47. package/dist/decoders/gif2sprite.d.ts +9 -0
  48. package/dist/decoders/gif2sprite.js +84 -0
  49. package/dist/decoders/webp2sprite.d.ts +22 -0
  50. package/dist/decoders/webp2sprite.js +133 -0
  51. package/dist/engineFlag.d.ts +72 -0
  52. package/dist/engineFlag.js +86 -0
  53. package/dist/export/SceneExporter.d.ts +92 -0
  54. package/dist/export/SceneExporter.js +280 -0
  55. package/dist/export/glExport.d.ts +66 -0
  56. package/dist/export/glExport.js +79 -0
  57. package/dist/export/svgExport.d.ts +277 -0
  58. package/dist/export/svgExport.js +1790 -0
  59. package/dist/index.d.ts +52 -0
  60. package/dist/index.js +48 -0
  61. package/dist/interact/animationPlayback.d.ts +125 -0
  62. package/dist/interact/animationPlayback.js +344 -0
  63. package/dist/interact/canvasInteractions.d.ts +50 -0
  64. package/dist/interact/canvasInteractions.js +150 -0
  65. package/dist/interact/cropSession.d.ts +123 -0
  66. package/dist/interact/cropSession.js +526 -0
  67. package/dist/interact/dblClick.d.ts +51 -0
  68. package/dist/interact/dblClick.js +106 -0
  69. package/dist/interact/expandSession.d.ts +107 -0
  70. package/dist/interact/expandSession.js +281 -0
  71. package/dist/interact/hotkeyActions.d.ts +16 -0
  72. package/dist/interact/hotkeyActions.js +41 -0
  73. package/dist/interact/pathSession.d.ts +141 -0
  74. package/dist/interact/pathSession.js +480 -0
  75. package/dist/interact/pointer.d.ts +106 -0
  76. package/dist/interact/pointer.js +1594 -0
  77. package/dist/interact/pointerTablePuzzle.d.ts +100 -0
  78. package/dist/interact/pointerTablePuzzle.js +358 -0
  79. package/dist/interact/pointerTransform.d.ts +86 -0
  80. package/dist/interact/pointerTransform.js +440 -0
  81. package/dist/interact/pointerTypes.d.ts +577 -0
  82. package/dist/interact/pointerTypes.js +96 -0
  83. package/dist/interact/snapGuide.d.ts +127 -0
  84. package/dist/interact/snapGuide.js +376 -0
  85. package/dist/interact/tableCellEditing.d.ts +61 -0
  86. package/dist/interact/tableCellEditing.js +198 -0
  87. package/dist/interact/tableInteraction.d.ts +55 -0
  88. package/dist/interact/tableInteraction.js +212 -0
  89. package/dist/interact/textEditing.d.ts +77 -0
  90. package/dist/interact/textEditing.js +410 -0
  91. package/dist/interact/warpFacade.d.ts +36 -0
  92. package/dist/interact/warpFacade.js +51 -0
  93. package/dist/interact/warpSession.d.ts +191 -0
  94. package/dist/interact/warpSession.js +582 -0
  95. package/dist/interact/wheelScroll.d.ts +62 -0
  96. package/dist/interact/wheelScroll.js +72 -0
  97. package/dist/model/alphaHit.d.ts +59 -0
  98. package/dist/model/alphaHit.js +262 -0
  99. package/dist/model/animation.d.ts +228 -0
  100. package/dist/model/animation.js +510 -0
  101. package/dist/model/arcLayout.d.ts +54 -0
  102. package/dist/model/arcLayout.js +307 -0
  103. package/dist/model/arcTextTransform.d.ts +7 -0
  104. package/dist/model/arcTextTransform.js +87 -0
  105. package/dist/model/compatEvents.d.ts +135 -0
  106. package/dist/model/compatEvents.js +73 -0
  107. package/dist/model/compatObject.d.ts +716 -0
  108. package/dist/model/compatObject.js +1579 -0
  109. package/dist/model/cropEdit.d.ts +118 -0
  110. package/dist/model/cropEdit.js +497 -0
  111. package/dist/model/document.d.ts +294 -0
  112. package/dist/model/document.js +572 -0
  113. package/dist/model/expandEdit.d.ts +93 -0
  114. package/dist/model/expandEdit.js +161 -0
  115. package/dist/model/fabricPrimitives.d.ts +156 -0
  116. package/dist/model/fabricPrimitives.js +9 -0
  117. package/dist/model/filler.d.ts +53 -0
  118. package/dist/model/filler.js +1 -0
  119. package/dist/model/groupAssemble.d.ts +7 -0
  120. package/dist/model/groupAssemble.js +98 -0
  121. package/dist/model/groupChildMove.d.ts +46 -0
  122. package/dist/model/groupChildMove.js +145 -0
  123. package/dist/model/groupResize.d.ts +78 -0
  124. package/dist/model/groupResize.js +108 -0
  125. package/dist/model/handles.d.ts +40 -0
  126. package/dist/model/handles.js +29 -0
  127. package/dist/model/imageMaskBake.d.ts +75 -0
  128. package/dist/model/imageMaskBake.js +136 -0
  129. package/dist/model/lineConstruct.d.ts +13 -0
  130. package/dist/model/lineConstruct.js +79 -0
  131. package/dist/model/maskCropEdit.d.ts +64 -0
  132. package/dist/model/maskCropEdit.js +90 -0
  133. package/dist/model/pathBackground.d.ts +51 -0
  134. package/dist/model/pathBackground.js +196 -0
  135. package/dist/model/pathConstruct.d.ts +27 -0
  136. package/dist/model/pathConstruct.js +55 -0
  137. package/dist/model/pathEdit.d.ts +114 -0
  138. package/dist/model/pathEdit.js +378 -0
  139. package/dist/model/puzzleEdit.d.ts +136 -0
  140. package/dist/model/puzzleEdit.js +742 -0
  141. package/dist/model/puzzleLayout.d.ts +91 -0
  142. package/dist/model/puzzleLayout.js +143 -0
  143. package/dist/model/scene.d.ts +1004 -0
  144. package/dist/model/scene.js +2841 -0
  145. package/dist/model/schema.d.ts +290 -0
  146. package/dist/model/schema.js +13 -0
  147. package/dist/model/shapePath.d.ts +14 -0
  148. package/dist/model/shapePath.js +136 -0
  149. package/dist/model/tableEdit.d.ts +196 -0
  150. package/dist/model/tableEdit.js +751 -0
  151. package/dist/model/tableFacade.d.ts +6 -0
  152. package/dist/model/tableFacade.js +808 -0
  153. package/dist/model/tableLayout.d.ts +85 -0
  154. package/dist/model/tableLayout.js +193 -0
  155. package/dist/model/textLayout.d.ts +357 -0
  156. package/dist/model/textLayout.js +822 -0
  157. package/dist/render/GLBlend.d.ts +40 -0
  158. package/dist/render/GLBlend.js +270 -0
  159. package/dist/render/GLContext.d.ts +25 -0
  160. package/dist/render/GLContext.js +48 -0
  161. package/dist/render/GLIsolate.d.ts +46 -0
  162. package/dist/render/GLIsolate.js +188 -0
  163. package/dist/render/GLTextureCache.d.ts +86 -0
  164. package/dist/render/GLTextureCache.js +187 -0
  165. package/dist/render/GlyphAtlas.d.ts +151 -0
  166. package/dist/render/GlyphAtlas.js +404 -0
  167. package/dist/render/MeshBatch.d.ts +123 -0
  168. package/dist/render/MeshBatch.js +416 -0
  169. package/dist/render/QuadBatch.d.ts +138 -0
  170. package/dist/render/QuadBatch.js +490 -0
  171. package/dist/render/SceneRenderer.d.ts +186 -0
  172. package/dist/render/SceneRenderer.js +700 -0
  173. package/dist/render/SourceManager.d.ts +121 -0
  174. package/dist/render/SourceManager.js +505 -0
  175. package/dist/render/TextRenderer.d.ts +140 -0
  176. package/dist/render/TextRenderer.js +795 -0
  177. package/dist/render/arcText.d.ts +40 -0
  178. package/dist/render/arcText.js +187 -0
  179. package/dist/render/batchOrder.d.ts +105 -0
  180. package/dist/render/batchOrder.js +168 -0
  181. package/dist/render/blendMode.d.ts +35 -0
  182. package/dist/render/blendMode.js +142 -0
  183. package/dist/render/clipMaskPainter.d.ts +17 -0
  184. package/dist/render/clipMaskPainter.js +121 -0
  185. package/dist/render/fontInvalidation.d.ts +25 -0
  186. package/dist/render/fontInvalidation.js +77 -0
  187. package/dist/render/fontInvalidationController.d.ts +76 -0
  188. package/dist/render/fontInvalidationController.js +114 -0
  189. package/dist/render/frameOverlay.d.ts +62 -0
  190. package/dist/render/frameOverlay.js +124 -0
  191. package/dist/render/framePipeline.d.ts +99 -0
  192. package/dist/render/framePipeline.js +95 -0
  193. package/dist/render/gpuFilterPasses.d.ts +25 -0
  194. package/dist/render/gpuFilterPasses.js +883 -0
  195. package/dist/render/gpuFx.d.ts +136 -0
  196. package/dist/render/gpuFx.js +614 -0
  197. package/dist/render/gpuImageFilters.d.ts +59 -0
  198. package/dist/render/gpuImageFilters.js +289 -0
  199. package/dist/render/gpuShadow.d.ts +52 -0
  200. package/dist/render/gpuShadow.js +289 -0
  201. package/dist/render/gradientRamp.d.ts +45 -0
  202. package/dist/render/gradientRamp.js +74 -0
  203. package/dist/render/imageEffects.d.ts +123 -0
  204. package/dist/render/imageEffects.js +390 -0
  205. package/dist/render/maskRender.d.ts +92 -0
  206. package/dist/render/maskRender.js +224 -0
  207. package/dist/render/progressiveLoad.d.ts +45 -0
  208. package/dist/render/progressiveLoad.js +86 -0
  209. package/dist/render/psdEffectPainter.d.ts +34 -0
  210. package/dist/render/psdEffectPainter.js +309 -0
  211. package/dist/render/puzzleClamp.d.ts +28 -0
  212. package/dist/render/puzzleClamp.js +30 -0
  213. package/dist/render/retainedFrame.d.ts +85 -0
  214. package/dist/render/retainedFrame.js +193 -0
  215. package/dist/render/ruler.d.ts +90 -0
  216. package/dist/render/ruler.js +287 -0
  217. package/dist/render/scrollText.d.ts +65 -0
  218. package/dist/render/scrollText.js +261 -0
  219. package/dist/render/selectionOverlay.d.ts +318 -0
  220. package/dist/render/selectionOverlay.js +921 -0
  221. package/dist/render/shaders.d.ts +38 -0
  222. package/dist/render/shaders.js +314 -0
  223. package/dist/render/shadowBake.d.ts +43 -0
  224. package/dist/render/shadowBake.js +202 -0
  225. package/dist/render/shadowPainter.d.ts +13 -0
  226. package/dist/render/shadowPainter.js +80 -0
  227. package/dist/render/sharedGpuPainters.d.ts +25 -0
  228. package/dist/render/sharedGpuPainters.js +40 -0
  229. package/dist/render/sourceHydration.d.ts +12 -0
  230. package/dist/render/sourceHydration.js +48 -0
  231. package/dist/render/strokeBake.d.ts +85 -0
  232. package/dist/render/strokeBake.js +515 -0
  233. package/dist/render/strokePainter.d.ts +28 -0
  234. package/dist/render/strokePainter.js +119 -0
  235. package/dist/render/strokeSdf.d.ts +35 -0
  236. package/dist/render/strokeSdf.js +74 -0
  237. package/dist/render/svgRaster.d.ts +46 -0
  238. package/dist/render/svgRaster.js +71 -0
  239. package/dist/render/tableOverlay.d.ts +38 -0
  240. package/dist/render/tableOverlay.js +233 -0
  241. package/dist/render/textHighlight.d.ts +117 -0
  242. package/dist/render/textHighlight.js +380 -0
  243. package/dist/render/textureUpload.d.ts +18 -0
  244. package/dist/render/textureUpload.js +26 -0
  245. package/dist/render/verticalText.d.ts +38 -0
  246. package/dist/render/verticalText.js +63 -0
  247. package/dist/render/warpText.d.ts +58 -0
  248. package/dist/render/warpText.js +380 -0
  249. package/dist/render/workspaceBackdrop.d.ts +35 -0
  250. package/dist/render/workspaceBackdrop.js +71 -0
  251. package/dist/render/workspaceChecker.d.ts +54 -0
  252. package/dist/render/workspaceChecker.js +170 -0
  253. package/dist/render/workspaceGlow.d.ts +51 -0
  254. package/dist/render/workspaceGlow.js +171 -0
  255. package/package.json +44 -3
@@ -0,0 +1,1790 @@
1
+ /**
2
+ * 纯数据侧 SVG 序列化器(P6-5 SVG 导出引擎化,批次 19 第一片)。
3
+ *
4
+ * store 序列化 JSON 快照 → SVG 字符串,全程不经任何画布/渲染器/GL——与
5
+ * P6-1 的 FBO 光栅导出互补:矢量格式的「引擎化」不替换渲染管线,而是把
6
+ * fabric toSVG 的序列化职责收进纯数据模块(终局去 fabric 依赖的导出面)。
7
+ *
8
+ * 形态:`SvgExporter` 类(同目录 SceneExporter 同款——状态进实例、免 ctx
9
+ * 线穿):实例承接一次导出运行级配置(textMode/fonts/naturalSizes),
10
+ * `exportPage` 逐页可复用(每页重置 defs/idSeq/skipped)。`serializePageToSvg`
11
+ * 保留为单页一次性薄出口(调用方免管实例生命周期)。
12
+ *
13
+ * 数学口径全部复用引擎既有纯函数(对拍过的 fabric 6.9.0 同源公式):
14
+ * - 变换:core/mat2d.objectOwnMatrix(fabric calcOwnMatrix 纯函数版)——每对象
15
+ * `<g transform="matrix(...)">`,组递归靠 DOM 嵌套自然合成(与引擎
16
+ * syncChildMatrices 的 parent∘own 同构)。
17
+ * - 渐变:core/gradient.gradientSpaceMatrix 的全量矩阵 → SVG gradientTransform,
18
+ * userSpaceOnUse + 原始 decl 坐标——canvas createGradient + setTransform 的
19
+ * 同构表达,percentage 非均匀缩放天然成立(radial 的椭圆变形同样走它)。
20
+ * - 图片裁剪:model/scene.imageCropRect 双口径(legacy/visible);裁剪图需
21
+ * 调用方注入自然尺寸(app 胶水预载),无裁剪图 width/height 直读。
22
+ * - clipPath:P4-3 同口径——相对定位(缺省)形状矩阵 = 宿主本地系 ∘ 自身
23
+ * left/top 矩阵;absolutePositioned = 场景系(宿主逆矩阵补偿)。transform
24
+ * 直接落在 clip 形状元素上(SVG 规范 clipPath 子元素只允许形状,不能包 <g>)。
25
+ * - 文字转曲:应用 Textbox.buildCharPaths 数学逐行同源(快照 textLines/
26
+ * charBounds/lineHeights 直消费——store 快照自带 fabric 布局产物,无需重排;
27
+ * 逐字前进用 box.width、首字 kerning 差、lineTop 基线公式);非转曲模式
28
+ * `<text>` 逐字 tspan(x 逐字显式——charSpacing 进了 charBounds,run 级
29
+ * tspan 会丢字距)。
30
+ *
31
+ * 不支持构造(pattern 填充/gco/竖排/变形弧形滚动文本/effects/animated/
32
+ * inverted clipPath 等)进 skippedTypes 计数,调用方(app 胶水)见非空即整页
33
+ * 回退 fabric 2D——「宁可回退,不可静默丢对象出货」(P6-1 同款兜底语义)。
34
+ * 输出为裸 SVG(无 @font-face);子集注入与 sanitizeSvg 沿用 useCanvasExport
35
+ * 既有链路(引擎模块不碰应用字体基建)。根元素带 data-engine-svg="1" 标记,
36
+ * 供 e2e/排障区分引擎产物与 fabric 产物。
37
+ */
38
+ import { gradientSpaceMatrix, parseGradientDecl } from '../core/gradient';
39
+ import { invert, multiply, objectOwnMatrix } from '../core/mat2d';
40
+ import { parsePathData } from '../core/pathData';
41
+ import { computeTableLayout } from '../model/tableLayout';
42
+ import { parsePatternDecl, patternSpaceMatrix } from '../core/pattern';
43
+ import { arcTextKind, computeArcTextLayout } from '../model/arcLayout';
44
+ import { imageCropRect, IMAGE_LIKE_TYPES, textBitmapFillAlpha, WORKSPACE_IDS } from '../model/scene';
45
+ import { charJitterY, layoutTextbox, verticalAnchorShiftX, verticalAnchorShiftY, verticalCharClass, verticalRenderAdvance } from '../model/textLayout';
46
+ import { planTextHighlight } from '../render/textHighlight';
47
+ // ---- 类型集(与 model/scene 的集合对齐的序列化侧子集 + 小写历史口径兜底) ----
48
+ const SOLID_TYPES = new Set(['rect', 'Rect', 'fabricrect']);
49
+ const ROUND_TYPES = new Set(['ellipse', 'Ellipse', 'circle', 'Circle']);
50
+ const TRIANGLE_TYPES = new Set(['triangle', 'Triangle']);
51
+ const PATH_TYPES = new Set(['Path', 'path']);
52
+ const POLYGON_TYPES = new Set(['polygon', 'Polygon']);
53
+ const POLYLINE_TYPES = new Set(['polyline', 'Polyline']);
54
+ /** 线段族:纯线段(emitNode 的 dims 兜底同覆盖 arrow/Dimension 两形态) */
55
+ const LINE_TYPES = new Set(['Line', 'line', 'ReferenceLine', 'arrow', 'Arrow', 'dimension', 'Dimension']);
56
+ /** 线族装饰(arrow/Dimension——端头装饰走 emitLineDecoration 专用 emitter,几何与渲染侧 bakeLineDecoration 同构) */
57
+ const ARROW_TYPES = new Set(['arrow', 'Arrow']);
58
+ const DIMENSION_TYPES = new Set(['dimension', 'Dimension']);
59
+ const GROUP_TYPES = new Set(['group', 'Group', 'Puzzle', 'puzzle']);
60
+ /** 序列化侧图片族 = scene IMAGE_LIKE_TYPES + GIF(SVG 以 <image href> 引用——
61
+ * 动图在支持的查看器播放、静态查看器显首帧;不动 scene 共享集避免
62
+ * AnimatedNode.isImageType 语义牵连。Video 不承接——SVG 规范无视频引用,须
63
+ * 帧位图化(余量登记) */
64
+ const SVG_IMAGE_TYPES = new Set([...IMAGE_LIKE_TYPES, 'GIF', 'gif']);
65
+ const TABLE_TYPES = new Set(['Table', 'table']);
66
+ const MASK_TYPES = new Set(['Mask', 'mask']);
67
+ /** gco → SVG mix-blend-mode 直通白名单(同值域;fabric toSVG 时代同样以平铺/
68
+ * 混合近似承接);白名单外(source-atop 等合成态)继续 skip */
69
+ const BLEND_MODES = new Set([
70
+ 'multiply',
71
+ 'screen',
72
+ 'overlay',
73
+ 'darken',
74
+ 'lighten',
75
+ 'color-dodge',
76
+ 'color-burn',
77
+ 'hard-light',
78
+ 'soft-light',
79
+ 'difference',
80
+ 'exclusion',
81
+ 'hue',
82
+ 'saturation',
83
+ 'color',
84
+ 'luminosity'
85
+ ]);
86
+ /** 常规文本族(含 ScrollText 静态基态承接——滚动循环视口截断是动画态,静态导出
87
+ * 出整行基串为登记近似;ArcText/CircleText 进 emitText 后由 arcTextKind 分派
88
+ * 弧形专用 emitter;ArchText/WaistText/FlagText 由 warp 分派变形 emitter) */
89
+ const TEXT_TYPES = new Set(['textbox', 'Textbox', 'itext', 'IText', 'i-text', 'text', 'Text', 'ScrollText', 'scrollText', 'ArcText', 'CircleText', 'ArchText', 'WaistText', 'FlagText', 'TextImage']);
90
+ /** 变形族判别(render/warpText.warpTextKind 同式——export 不引 render 域,内联):
91
+ * warpStrength=0 的变形族是普通文本(走常规快照路径) */
92
+ const warpKindOf = (raw) => {
93
+ const s = Number(raw.warpStrength) || 0;
94
+ if (!s)
95
+ return null;
96
+ if (raw.type === 'ArchText')
97
+ return 'arch';
98
+ if (raw.type === 'WaistText')
99
+ return 'waist';
100
+ if (raw.type === 'FlagText')
101
+ return 'flag';
102
+ return null;
103
+ };
104
+ /** 对象形态 effects(特效面板写入/模板快照的真实载体——parsePsdEffects 只吃
105
+ * 此形态;数组形态是异常构造,维持既有 skip 计数口径)。对象形态进位图分派
106
+ * (baker 判活跃特效),此前该形态静默绕过 skip = 矢量导出丢特效的洞。 */
107
+ const hasObjectEffects = (raw) => {
108
+ const e = raw.effects;
109
+ return !!e && typeof e === 'object' && !Array.isArray(e);
110
+ };
111
+ /** 文本装饰在场(划重点 raw.texts / 文字背景 textBackgroundColor——含逐字覆写
112
+ * 可能性由 charStyles 自查,此处只查对象级快速门)。装饰层消费 TextLayout
113
+ * (引擎布局对象),在场时 emitText 优先走引擎布局路径与字形共用同布局。 */
114
+ const hasTextDecorations = (raw) => {
115
+ if (typeof raw.textBackgroundColor === 'string' && raw.textBackgroundColor)
116
+ return true;
117
+ return Array.isArray(raw.texts) && raw.texts.length > 0;
118
+ };
119
+ /** clipPath 可承接形状(P4-3 clipDecl 同款:SHAPE 族 + rect,收小写历史口径) */
120
+ const CLIP_TYPES = new Set(['rect', 'Rect', 'fabricrect', 'ellipse', 'Ellipse', 'circle', 'Circle', 'polygon', 'Polygon', 'polyline', 'Polyline', 'Path', 'path']);
121
+ /** fabric 6 Text._fontSizeFraction(基线公式常量,buildCharPaths 同源) */
122
+ const FONT_SIZE_FRACTION = 0.222;
123
+ // workspace 族过滤口径已上移 model/scene.WORKSPACE_IDS(框选/全选共用同源)
124
+ // ---- 无状态小工具(不持页内状态,保持纯函数) ----
125
+ const num = (raw, key, fallback) => {
126
+ const v = raw[key];
127
+ if (typeof v === 'number')
128
+ return Number.isFinite(v) ? v : fallback;
129
+ // 应用模板序列化的数值字段可成串(fontSize:'80' 实测形态)——引擎渲染侧靠
130
+ // 算术隐式转换显示正常,本侧严格 typeof number 会静默吃 fallback(转曲字形
131
+ // 腰斩=「变小/字距拉开」根因,批次 78 一补)。数值串按数收,其余仍走 fallback。
132
+ if (typeof v === 'string' && v.trim() !== '') {
133
+ const n = Number(v.trim());
134
+ if (Number.isFinite(n))
135
+ return n;
136
+ }
137
+ return fallback;
138
+ };
139
+ const str = (raw, key) => {
140
+ const v = raw[key];
141
+ return typeof v === 'string' ? v : undefined;
142
+ };
143
+ /** 数字格式化:4 位小数截断 + 去尾零(fabric toSVG util.toFixed 同精度观感) */
144
+ const fmt = (n) => {
145
+ const r = Math.round(n * 1e4) / 1e4;
146
+ return Object.is(r, -0) ? '0' : String(r);
147
+ };
148
+ const escapeXml = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;');
149
+ /** 属性值口径的颜色串校验:hex/rgb(a)/命名色放行,其余(cmyk() 等)不支持 */
150
+ const COLOR_RE = /^(#[0-9a-fA-F]{3,8}|rgba?\(\s*[\d.]+\s*,\s*[\d.]+\s*,\s*[\d.]+\s*(,\s*[\d.]+\s*)?\)|[a-zA-Z][a-zA-Z0-9_-]*)$/;
151
+ const colorAttr = (value) => (COLOR_RE.test(value.trim()) ? value.trim() : null);
152
+ const isBlankColor = (value) => value == null || value === '' || value === 'transparent' || value === 'rgba(0,0,0,0)' || value === 'none';
153
+ /** mat → SVG transform 串 */
154
+ const matAttr = (m) => `matrix(${m.map(fmt).join(',')})`;
155
+ const translateMat = (tx, ty) => [1, 0, 0, 1, tx, ty];
156
+ const toNode = (raw) => raw;
157
+ /** 对象自身矩阵:dims 传内容尺寸(裁剪图传可见尺寸——engine dims 同口径) */
158
+ const ownMatrix = (raw, width, height) => objectOwnMatrix({ ...raw, width, height });
159
+ /** null = 无阴影;undefined = 阴影形态不承接 */
160
+ const parseShadow = (raw) => {
161
+ const value = raw.shadow;
162
+ if (!value)
163
+ return null;
164
+ if (typeof value !== 'object' || Array.isArray(value))
165
+ return undefined;
166
+ const o = value;
167
+ const color = typeof o.color === 'string' ? o.color : 'rgb(0,0,0)';
168
+ if (!colorAttr(color))
169
+ return undefined;
170
+ return {
171
+ color,
172
+ blur: typeof o.blur === 'number' && Number.isFinite(o.blur) ? o.blur : 0,
173
+ offsetX: typeof o.offsetX === 'number' && Number.isFinite(o.offsetX) ? o.offsetX : 0,
174
+ offsetY: typeof o.offsetY === 'number' && Number.isFinite(o.offsetY) ? o.offsetY : 0
175
+ };
176
+ };
177
+ const pathOffsetTransform = (raw) => {
178
+ const off = raw.pathOffset;
179
+ if (!off || typeof off !== 'object')
180
+ return null;
181
+ const ox = typeof off.x === 'number' && Number.isFinite(off.x) ? off.x : 0;
182
+ const oy = typeof off.y === 'number' && Number.isFinite(off.y) ? off.y : 0;
183
+ return ox || oy ? translateMat(-ox, -oy) : null;
184
+ };
185
+ /** PathCommand[] → SVG d 串(parsePathData 产物串行化——Z 无参数特判) */
186
+ const commandsToPathD = (commands) => commands
187
+ .map((c) => c.length === 1
188
+ ? c[0]
189
+ : `${c[0]} ${c
190
+ .slice(1)
191
+ .map((n) => fmt(Number(n)))
192
+ .join(' ')}`)
193
+ .join(' ');
194
+ const shapeGeometry = (raw, width, height) => {
195
+ const type = raw.type;
196
+ if (SOLID_TYPES.has(type)) {
197
+ const rx = Math.min(num(raw, 'rx', 0), width / 2);
198
+ const ry = Math.min(num(raw, 'ry', 0), height / 2);
199
+ const radius = rx > 0 || ry > 0 ? ` rx="${fmt(rx)}" ry="${fmt(ry > 0 ? ry : rx)}"` : '';
200
+ return {
201
+ open: `<rect x="${fmt(-width / 2)}" y="${fmt(-height / 2)}" width="${fmt(width)}" height="${fmt(height)}"${radius}`,
202
+ internalTransform: null
203
+ };
204
+ }
205
+ if (ROUND_TYPES.has(type)) {
206
+ return { open: `<ellipse cx="0" cy="0" rx="${fmt(width / 2)}" ry="${fmt(height / 2)}"`, internalTransform: null };
207
+ }
208
+ if (TRIANGLE_TYPES.has(type)) {
209
+ // fabric Triangle._render:(-w/2,h/2) → (0,-h/2) → (w/2,h/2)(顶点在上)
210
+ return {
211
+ open: `<polygon points="${fmt(-width / 2)},${fmt(height / 2)} 0,${fmt(-height / 2)} ${fmt(width / 2)},${fmt(height / 2)}"`,
212
+ internalTransform: null
213
+ };
214
+ }
215
+ if (PATH_TYPES.has(type)) {
216
+ // 双形态:SVG 串 / fabric toObject 的指令数组(默认模板实测形态)——parsePathData 归一
217
+ const commands = parsePathData(raw.path);
218
+ if (!commands)
219
+ return null;
220
+ return { open: `<path d="${escapeXml(commandsToPathD(commands))}"`, internalTransform: pathOffsetTransform(raw) };
221
+ }
222
+ if (POLYGON_TYPES.has(type) || POLYLINE_TYPES.has(type)) {
223
+ const points = raw.points;
224
+ if (!Array.isArray(points) || points.length === 0)
225
+ return null;
226
+ const pts = points
227
+ .map((p) => {
228
+ const o = p;
229
+ const x = typeof o.x === 'number' ? o.x : NaN;
230
+ const y = typeof o.y === 'number' ? o.y : NaN;
231
+ return Number.isFinite(x) && Number.isFinite(y) ? `${fmt(x)},${fmt(y)}` : null;
232
+ })
233
+ .filter((s) => s !== null);
234
+ if (!pts.length)
235
+ return null;
236
+ const tag = POLYGON_TYPES.has(type) ? 'polygon' : 'polyline';
237
+ return { open: `<${tag} points="${pts.join(' ')}"`, internalTransform: pathOffsetTransform(raw) };
238
+ }
239
+ if (LINE_TYPES.has(type)) {
240
+ return {
241
+ open: `<line x1="${fmt(num(raw, 'x1', 0))}" y1="${fmt(num(raw, 'y1', 0))}" x2="${fmt(num(raw, 'x2', 0))}" y2="${fmt(num(raw, 'y2', 0))}"`,
242
+ internalTransform: null
243
+ };
244
+ }
245
+ return null;
246
+ };
247
+ /** 几何元素完整化:合成外部矩阵与内部平移 + paint 属性 + 自闭合 */
248
+ const geometryElement = (geometry, transform, attrs) => {
249
+ const t = transform && geometry.internalTransform ? multiply(transform, geometry.internalTransform) : transform ?? geometry.internalTransform;
250
+ return `${geometry.open}${t ? ` transform="${matAttr(t)}"` : ''}${attrs}/>`;
251
+ };
252
+ /** 填充/描边属性串(paint-order/dash/cap/join/strokeUniform 近似) */
253
+ const paintAttrs = (raw, fill, stroke) => {
254
+ let attrs = '';
255
+ if (fill !== null) {
256
+ attrs += ` fill="${escapeXml(fill)}"`;
257
+ const rule = str(raw, 'fillRule');
258
+ if (rule)
259
+ attrs += ` fill-rule="${escapeXml(rule)}"`;
260
+ }
261
+ else {
262
+ attrs += ' fill="none"';
263
+ }
264
+ if (stroke !== null) {
265
+ attrs += ` stroke="${escapeXml(stroke)}"`;
266
+ attrs += ` stroke-width="${fmt(num(raw, 'strokeWidth', 1))}"`;
267
+ const dash = raw.strokeDashArray;
268
+ if (Array.isArray(dash) && dash.length > 0) {
269
+ const parts = dash.map((d) => (typeof d === 'number' && Number.isFinite(d) ? fmt(d) : null)).filter((s) => s !== null);
270
+ if (parts.length)
271
+ attrs += ` stroke-dasharray="${parts.join(',')}"`;
272
+ }
273
+ const cap = str(raw, 'strokeLineCap');
274
+ if (cap)
275
+ attrs += ` stroke-linecap="${escapeXml(cap)}"`;
276
+ const join = str(raw, 'strokeLineJoin');
277
+ if (join)
278
+ attrs += ` stroke-linejoin="${escapeXml(join)}"`;
279
+ const miter = raw.strokeMiterLimit;
280
+ if (typeof miter === 'number' && Number.isFinite(miter))
281
+ attrs += ` stroke-miterlimit="${fmt(miter)}"`;
282
+ // fabric strokeUniform = 描边宽不随对象缩放;1:1 导出下与视口系恒宽等价
283
+ if (raw.strokeUniform === true)
284
+ attrs += ' vector-effect="non-scaling-stroke"';
285
+ if (str(raw, 'paintFirst') === 'stroke')
286
+ attrs += ' paint-order="stroke"';
287
+ }
288
+ return attrs;
289
+ };
290
+ const strokeVisible = (raw) => !isBlankColor(raw.stroke) && num(raw, 'strokeWidth', 1) > 0;
291
+ /**
292
+ * opentype 度量桥(弧形/竖排布局用):MeasureFn 协议 (decl, text) → px 宽。
293
+ * decl 是 fontDeclaration 串(`${style} ${weight} ${size}px ${family}`)——尾部
294
+ * 正则取 size/family;opentype Font.getAdvanceWidth 内部累加 advance+kerning,
295
+ * 与 measureText 的 coupleWidth/charWidth 差分协议同构(measureChar 消费面)。
296
+ * weight 不分文件(同 family 同 Font——合成粗体与浏览器 canvas 同口径近似)。
297
+ * resolver 未供度量(无 getAdvanceWidth)返回 null——调用方 skip 回退。
298
+ */
299
+ const measureFromFonts = (fonts) => {
300
+ const cache = new Map();
301
+ return (decl, text) => {
302
+ const m = /([\d.]+)px\s+([\s\S]+)$/.exec(decl);
303
+ if (!m)
304
+ return 0;
305
+ const size = Number(m[1]);
306
+ const family = m[2].replace(/^["']+|["']+$/g, '');
307
+ const key = `${family}|${size}|${text}`;
308
+ const hit = cache.get(key);
309
+ if (hit !== undefined)
310
+ return hit;
311
+ const font = fonts.getFont(family) ?? fonts.getSubsetFont?.(family, text[0] ?? '') ?? null;
312
+ const width = font && typeof font.getAdvanceWidth === 'function' ? font.getAdvanceWidth(text, size) : 0;
313
+ cache.set(key, width);
314
+ return width;
315
+ };
316
+ };
317
+ /**
318
+ * Dimension 文本宽度近似(引擎序列化器红线=纯数据模块,无 DOM measureText)。
319
+ * Arial 口径系数:CJK 全宽 1.0、其余 0.55——只用于文本背景框宽度(视觉近似),
320
+ * 文本本体仍是矢量 <text> 不受影响。渲染侧 bakeLineDecoration 用浏览器实测宽,
321
+ * 两边框宽可有 ~5% 偏差(可接受——标注文本框非模板字体族,不进对拍口径)。
322
+ */
323
+ const approxTextWidth = (text, fontPx) => {
324
+ let units = 0;
325
+ for (const ch of text)
326
+ units += ch.charCodeAt(0) > 0xff ? 1.0 : 0.55;
327
+ return units * fontPx;
328
+ };
329
+ const parseTextLayout = (raw) => {
330
+ const textLines = raw.textLines;
331
+ const charBounds = raw.charBounds;
332
+ const lineHeights = raw.lineHeights;
333
+ if (!Array.isArray(textLines) || !Array.isArray(charBounds) || !Array.isArray(lineHeights))
334
+ return null;
335
+ if (textLines.length === 0 || charBounds.length !== textLines.length || lineHeights.length !== textLines.length)
336
+ return null;
337
+ for (let i = 0; i < textLines.length; i++) {
338
+ if (typeof textLines[i] !== 'string' || !Array.isArray(charBounds[i]))
339
+ return null;
340
+ if (typeof lineHeights[i] !== 'number' || !Number.isFinite(lineHeights[i]))
341
+ return null;
342
+ }
343
+ return { textLines: textLines, charBounds: charBounds, lineHeights: lineHeights };
344
+ };
345
+ /** range 样式(stylesToArray 快照形态 [{start,end,style}],全局字符下标含 \n) */
346
+ const rangeStyleAt = (raw, globalIndex) => {
347
+ const styles = raw.styles;
348
+ if (!Array.isArray(styles))
349
+ return {};
350
+ for (const entry of styles) {
351
+ if (!entry || typeof entry !== 'object')
352
+ continue;
353
+ const e = entry;
354
+ const start = typeof e.start === 'number' ? e.start : -1;
355
+ const end = typeof e.end === 'number' ? e.end : -1;
356
+ if (globalIndex >= start && globalIndex < end && e.style && typeof e.style === 'object') {
357
+ return e.style;
358
+ }
359
+ }
360
+ return {};
361
+ };
362
+ const charStyleAt = (raw, lineIndex, charIndex, layout) => {
363
+ let globalIndex = charIndex;
364
+ for (let i = 0; i < lineIndex; i++)
365
+ globalIndex += layout.textLines[i].length + 1;
366
+ const range = rangeStyleAt(raw, globalIndex);
367
+ const pick = (key, fallback) => (range[key] !== undefined ? range[key] : fallback);
368
+ return {
369
+ fontFamily: pick('fontFamily', str(raw, 'fontFamily') ?? 'Arial'),
370
+ fontSize: pick('fontSize', num(raw, 'fontSize', 40)),
371
+ fontWeight: pick('fontWeight', String(str(raw, 'fontWeight') ?? 'normal')),
372
+ fontStyle: pick('fontStyle', str(raw, 'fontStyle') ?? 'normal'),
373
+ fill: pick('fill', raw.fill),
374
+ stroke: pick('stroke', raw.stroke),
375
+ strokeWidth: pick('strokeWidth', num(raw, 'strokeWidth', 1)),
376
+ underline: pick('underline', raw.underline === true),
377
+ linethrough: pick('linethrough', raw.linethrough === true),
378
+ overline: pick('overline', raw.overline === true)
379
+ };
380
+ };
381
+ /** 对象级文本样式(TextNode.textStyle 同源——引擎布局通道的基底) */
382
+ const baseTextStyle = (raw) => ({
383
+ fontFamily: raw.fontFamily ?? 'Times New Roman',
384
+ fontSize: raw.fontSize ?? 40,
385
+ fontWeight: raw.fontWeight,
386
+ fontStyle: raw.fontStyle ?? undefined,
387
+ lineHeight: raw.lineHeight ?? 1.16,
388
+ charSpacing: raw.charSpacing ?? 0,
389
+ textAlign: raw.textAlign ?? 'left'
390
+ });
391
+ /** 逐字覆写合成(render/arcText.glyphStyleOf 同源逻辑——export 不引 render 域,内联):
392
+ * 字体四件套覆写 + fill 覆写,其余取对象级 */
393
+ const mergeCharStyle = (base, o, raw) => ({
394
+ fontFamily: o?.fontFamily ?? base.fontFamily,
395
+ fontSize: o?.fontSize ?? base.fontSize,
396
+ fontWeight: String(o?.fontWeight ?? base.fontWeight ?? 'normal'),
397
+ fontStyle: o?.fontStyle ?? base.fontStyle ?? 'normal',
398
+ fill: o?.fill ?? raw.fill,
399
+ stroke: raw.stroke,
400
+ strokeWidth: num(raw, 'strokeWidth', 1),
401
+ underline: raw.underline === true,
402
+ linethrough: raw.linethrough === true,
403
+ overline: raw.overline === true
404
+ });
405
+ /**
406
+ * styles 快照双形态归一(引擎布局通道用):序列化 raw.styles 是 range 数组
407
+ * (stylesToArray [{start,end,style}],全局字符下标含 \n——rangeStyleAt 同源),
408
+ * layoutTextbox 消费 map 形态({line:{offset:override}})。已是 map(非数组)
409
+ * 直接透传;\n 位跳过(fabric 数组化同款)。
410
+ */
411
+ const stylesArrayToMap = (text, styles) => {
412
+ if (!Array.isArray(styles) || styles.length === 0) {
413
+ return styles && typeof styles === 'object' ? styles : undefined;
414
+ }
415
+ const lineStarts = [0];
416
+ for (let i = 0; i < text.length; i++)
417
+ if (text[i] === '\n')
418
+ lineStarts.push(i + 1);
419
+ const locate = (global) => {
420
+ let line = -1;
421
+ for (let k = 0; k < lineStarts.length; k++)
422
+ if (global >= lineStarts[k])
423
+ line = k;
424
+ return line < 0 ? null : [line, global - lineStarts[line]];
425
+ };
426
+ const map = {};
427
+ for (const entry of styles) {
428
+ if (!entry || typeof entry !== 'object')
429
+ continue;
430
+ const start = typeof entry.start === 'number' ? entry.start : -1;
431
+ const end = typeof entry.end === 'number' ? entry.end : -1;
432
+ if (start < 0 || end <= start || !entry.style || typeof entry.style !== 'object')
433
+ continue;
434
+ for (let g = start; g < end && g < text.length; g++) {
435
+ if (text[g] === '\n')
436
+ continue;
437
+ const loc = locate(g);
438
+ if (loc)
439
+ (map[loc[0]] ??= {})[loc[1]] = entry.style;
440
+ }
441
+ }
442
+ return Object.keys(map).length > 0 ? map : undefined;
443
+ };
444
+ /** 行左偏移(fabric _getLineLeftOffset:justify 非段末行恒 0——fabric 口径) */ const lineLeftOffset = (align, boxWidth, lineWidth, isEndOfWrapping) => {
445
+ const a = align ?? 'left';
446
+ if (a.startsWith('justify')) {
447
+ if (!isEndOfWrapping)
448
+ return 0;
449
+ const tail = a.slice('justify'.length);
450
+ if (tail === '-center')
451
+ return (boxWidth - lineWidth) / 2;
452
+ if (tail === '-right')
453
+ return boxWidth - lineWidth;
454
+ return 0;
455
+ }
456
+ if (a === 'center')
457
+ return (boxWidth - lineWidth) / 2;
458
+ if (a === 'right')
459
+ return boxWidth - lineWidth;
460
+ return 0;
461
+ };
462
+ /** opentype path.commands → SVG path data(M/L/Q/C/Z,toSVGWithPaths 同源手工序列化) */
463
+ const glyphToPathData = (commands) => {
464
+ const parts = [];
465
+ for (const cmd of commands) {
466
+ switch (cmd.type) {
467
+ case 'M':
468
+ parts.push(`M${fmt(cmd.x ?? 0)} ${fmt(cmd.y ?? 0)}`);
469
+ break;
470
+ case 'L':
471
+ parts.push(`L${fmt(cmd.x ?? 0)} ${fmt(cmd.y ?? 0)}`);
472
+ break;
473
+ case 'Q':
474
+ parts.push(`Q${fmt(cmd.x1 ?? 0)} ${fmt(cmd.y1 ?? 0)} ${fmt(cmd.x ?? 0)} ${fmt(cmd.y ?? 0)}`);
475
+ break;
476
+ case 'C':
477
+ parts.push(`C${fmt(cmd.x1 ?? 0)} ${fmt(cmd.y1 ?? 0)} ${fmt(cmd.x2 ?? 0)} ${fmt(cmd.y2 ?? 0)} ${fmt(cmd.x ?? 0)} ${fmt(cmd.y ?? 0)}`);
478
+ break;
479
+ case 'Z':
480
+ parts.push('Z');
481
+ break;
482
+ default:
483
+ break;
484
+ }
485
+ }
486
+ return parts.join('');
487
+ };
488
+ const layoutGlyphAnchors = (raw, layout, width, height, opts = {}) => {
489
+ // 段末行判定:最后一个非空行之后的空行不算 wrapping 段(fabric isEndOfWrapping)
490
+ let lastNonEmpty = -1;
491
+ for (let i = 0; i < layout.textLines.length; i++) {
492
+ if (layout.textLines[i].length > 0)
493
+ lastNonEmpty = i;
494
+ }
495
+ const lineHeight = num(raw, 'lineHeight', 1.16) || 1.16;
496
+ const align = str(raw, 'textAlign');
497
+ const leftOffset0 = -width / 2;
498
+ const topOffset0 = -height / 2;
499
+ const anchors = [];
500
+ let cumulativeHeight = 0;
501
+ for (let lineIndex = 0; lineIndex < layout.textLines.length; lineIndex++) {
502
+ const line = layout.textLines[lineIndex];
503
+ const boxes = layout.charBounds[lineIndex];
504
+ const heightOfLine = layout.lineHeights[lineIndex];
505
+ const maxHeight = heightOfLine / lineHeight;
506
+ // buildCharPaths 行基线(与 _renderStr 实测渲染 top 一致)
507
+ const lineTop = topOffset0 + cumulativeHeight + maxHeight - (heightOfLine * FONT_SIZE_FRACTION) / lineHeight;
508
+ let lineWidth = 0;
509
+ for (const box of boxes) {
510
+ if (!box || typeof box.left !== 'number' || typeof box.kernedWidth !== 'number')
511
+ continue;
512
+ lineWidth = Math.max(lineWidth, box.left + box.kernedWidth);
513
+ }
514
+ const offset = lineLeftOffset(align, width, lineWidth, lineIndex >= lastNonEmpty);
515
+ const lineLeft = opts.lineLefts?.[lineIndex] ?? leftOffset0 + offset;
516
+ const boxLeftAnchor = opts.anchor === 'boxLeft';
517
+ let drawingLeft = lineLeft;
518
+ let boxWidth = 0;
519
+ for (let i = 0; i <= line.length - 1; i++) {
520
+ const char = line[i];
521
+ const box = boxes[i];
522
+ if (!box || typeof box.width !== 'number' || typeof box.kernedWidth !== 'number')
523
+ continue;
524
+ if (boxLeftAnchor) {
525
+ // 引擎渲染摆位真值:x = lineLeft + box.left(box.left 由度量累计,含
526
+ // charSpacing/kerning——与 TextRenderer 的 penX 同式)
527
+ anchors.push({ char, x: lineLeft + (box.left || 0), y: lineTop, style: charStyleAt(raw, lineIndex, i, layout) });
528
+ continue;
529
+ }
530
+ // buildCharPaths 前进口径:首字吃 kerning 差、逐字按 box.width 前进
531
+ if (boxWidth === 0) {
532
+ drawingLeft += box.kernedWidth - box.width;
533
+ boxWidth = box.width;
534
+ }
535
+ else {
536
+ boxWidth += box.width;
537
+ }
538
+ anchors.push({ char, x: drawingLeft, y: lineTop, style: charStyleAt(raw, lineIndex, i, layout) });
539
+ drawingLeft += boxWidth;
540
+ boxWidth = 0;
541
+ }
542
+ cumulativeHeight += heightOfLine;
543
+ }
544
+ return anchors;
545
+ };
546
+ /**
547
+ * 文本 raw → 转曲路径数据(fabric mixin toPath 同源口径):layoutGlyphAnchors
548
+ * 逐字锚点 × opentype 字形轮廓 → 单条 path 串(`M..L..Z` 空隔连接,盒中心系——
549
+ * 与应用 buildCharPaths 产出的 charPaths 坐标同源)。右栏转曲(compat toPath)
550
+ * 消费;emitText paths 模式仍走自身输出(同锚点不同串化,fill/描边属性化)。
551
+ * null = 不承接(盒尺寸缺失/竖排/rtl/无排版快照)或字形缺失(任一非空白字符
552
+ * 字体未就绪——调用方按「整对象字形缺失」过滤,与 fabric charPaths 空 → 空
553
+ * path 的兜底同语义);全空白文本同样 null(无字形可转)。
554
+ */
555
+ export const buildTextGlyphPathData = (raw, fonts, opts = {}) => {
556
+ if (!fonts)
557
+ return null;
558
+ const r = raw;
559
+ const width = num(r, 'width', NaN);
560
+ const height = num(r, 'height', NaN);
561
+ if (!Number.isFinite(width) || !Number.isFinite(height))
562
+ return null;
563
+ if (r.vertical === true || (typeof r.direction === 'string' && r.direction !== 'ltr'))
564
+ return null;
565
+ const layout = parseTextLayout(r);
566
+ if (!layout)
567
+ return null;
568
+ const parts = [];
569
+ for (const { char, x, y, style } of layoutGlyphAnchors(r, layout, width, height, opts)) {
570
+ if (!char.trim())
571
+ continue;
572
+ const font = fonts.getFont(style.fontFamily) ?? fonts.getSubsetFont?.(style.fontFamily, char) ?? null;
573
+ if (!font)
574
+ return null;
575
+ const d = glyphToPathData(font.getPath(char, x, y, style.fontSize).commands);
576
+ // mixin 口径:整段命令收尾非 Z 则补 Z 闭合(轮廓开放时兜底)
577
+ parts.push(d.endsWith('Z') ? d : `${d} Z`);
578
+ }
579
+ return parts.length > 0 ? { path: parts.join(' ') } : null;
580
+ };
581
+ // ---- 序列化器(状态进实例:defs/idSeq/skipped + 运行级配置) ----
582
+ export class SvgExporter {
583
+ options;
584
+ /** 页内 defs(渐变/滤镜/clip),exportPage 开头重置 */
585
+ defs = [];
586
+ idSeq = 0;
587
+ skipped = {};
588
+ constructor(options) {
589
+ this.options = options;
590
+ }
591
+ /** 页序列化(实例可跨页复用——每页重置 defs/idSeq/skipped) */
592
+ exportPage(page) {
593
+ this.defs = [];
594
+ this.idSeq = 0;
595
+ this.skipped = {};
596
+ const parts = [];
597
+ for (const entry of page.objects) {
598
+ if (!entry || typeof entry !== 'object' || typeof entry.type !== 'string')
599
+ continue;
600
+ const emitted = this.emitNode(entry);
601
+ if (emitted === null)
602
+ continue; // 已计数——调用方按 skippedTypes 非空整体回退
603
+ if (emitted)
604
+ parts.push(emitted);
605
+ }
606
+ const background = page.background && !isBlankColor(page.background) ? colorAttr(page.background) : null;
607
+ const bgRect = background
608
+ ? `<rect x="${fmt(page.viewBox.x)}" y="${fmt(page.viewBox.y)}" width="${fmt(page.viewBox.width)}" height="${fmt(page.viewBox.height)}" fill="${escapeXml(background)}"/>`
609
+ : '';
610
+ const defs = this.defs.length ? `<defs>${this.defs.join('')}</defs>` : '';
611
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${fmt(page.width)}px" height="${fmt(page.height)}px" viewBox="${fmt(page.viewBox.x)} ${fmt(page.viewBox.y)} ${fmt(page.viewBox.width)} ${fmt(page.viewBox.height)}" data-engine-svg="1">` +
612
+ bgRect +
613
+ defs +
614
+ parts.join('') +
615
+ '</svg>';
616
+ return { svg, skippedTypes: this.skipped };
617
+ }
618
+ skip(key) {
619
+ this.skipped[key] = (this.skipped[key] ?? 0) + 1;
620
+ }
621
+ nextId(prefix) {
622
+ this.idSeq += 1;
623
+ return `${prefix}${this.idSeq}`;
624
+ }
625
+ emitGradientDef(decl, width, height) {
626
+ const id = this.nextId('esvg-g');
627
+ // gradientTransform = gradientSpaceMatrix 的**全量矩阵(含平移)**:引擎口径
628
+ // 本地点 p 在 decl 系采样于 M⁻¹·p(toGradientSpace);SVG 的 userSpaceOnUse +
629
+ // gradientTransform G 的采样点是 G⁻¹·p ——令 G = M 即两侧同采样。M 把 decl
630
+ // 几何映进本地系(percentage:轴端点 (0,0)-(0,1) → 本地 (±w/2,±h/2))。
631
+ // 只发线性部分(丢了平移)会把渐变挤进 1 单位角落;发逆矩阵则塌成中心硬阶
632
+ // (两侧形态都被 e2e 栅格化对拍抓出过)
633
+ const m = gradientSpaceMatrix(decl, width, height);
634
+ const gt = ` gradientTransform="matrix(${fmt(m[0])},${fmt(m[1])},${fmt(m[2])},${fmt(m[3])},${fmt(m[4])},${fmt(m[5])})"`;
635
+ const stops = decl.stops
636
+ .map((s) => {
637
+ const [r, g, b, a] = s.color;
638
+ const rgb = `rgb(${Math.round(r * 255)},${Math.round(g * 255)},${Math.round(b * 255)})`;
639
+ return `<stop offset="${fmt(s.offset)}" stop-color="${rgb}"${a < 1 ? ` stop-opacity="${fmt(a)}"` : ''}/>`;
640
+ })
641
+ .join('');
642
+ if (decl.kind === 'linear') {
643
+ this.defs.push(`<linearGradient id="${id}" gradientUnits="userSpaceOnUse" x1="${fmt(decl.x1)}" y1="${fmt(decl.y1)}" x2="${fmt(decl.x2)}" y2="${fmt(decl.y2)}"${gt}>${stops}</linearGradient>`);
644
+ }
645
+ else {
646
+ this.defs.push(`<radialGradient id="${id}" gradientUnits="userSpaceOnUse" cx="${fmt(decl.x2)}" cy="${fmt(decl.y2)}" r="${fmt(decl.r2)}" fx="${fmt(decl.x1)}" fy="${fmt(decl.y1)}"${decl.r1 > 0 ? ` fr="${fmt(decl.r1)}"` : ''}${gt}>${stops}</radialGradient>`);
647
+ }
648
+ return `url(#${id})`;
649
+ }
650
+ /**
651
+ * fill/stroke 的 paint 解析。
652
+ * 返回 null = 该 paint 不画(空色);undefined = 不支持(调用方 skip)。
653
+ */
654
+ resolvePaint(value, width, height) {
655
+ if (isBlankColor(value))
656
+ return null;
657
+ if (typeof value === 'string')
658
+ return colorAttr(value) ?? undefined;
659
+ if (!value || typeof value !== 'object' || Array.isArray(value))
660
+ return undefined;
661
+ const decl = parseGradientDecl(value);
662
+ if (decl)
663
+ return this.emitGradientDef(decl, width, height);
664
+ const pattern = parsePatternDecl(value);
665
+ if (pattern)
666
+ return this.emitPatternDef(pattern, width, height);
667
+ return undefined;
668
+ }
669
+ /**
670
+ * pattern 填充 → defs <pattern>(fabric toSVG 同口径:tile 全平铺——repeat-x/y/
671
+ * no-repeat 的单次轴近似全平铺,与 fabric 时代的 SVG 输出一致)。tile 尺寸 =
672
+ * 图像自然尺寸(naturalSizes 注入,缺即 fill-unsupported 回退);
673
+ * patternTransform = patternSpaceMatrix 全量矩阵(渐变 gradientTransform 同例)。
674
+ */
675
+ emitPatternDef(decl, width, height) {
676
+ const size = this.options.naturalSizes?.get(decl.src);
677
+ if (!size || size.width <= 0 || size.height <= 0)
678
+ return undefined;
679
+ const id = this.nextId('esvg-pt');
680
+ const m = patternSpaceMatrix(decl, width, height);
681
+ this.defs.push(`<pattern id="${id}" patternUnits="userSpaceOnUse" width="${fmt(size.width)}" height="${fmt(size.height)}" patternTransform="${matAttr(m)}">` +
682
+ `<image href="${escapeXml(decl.src)}" xlink:href="${escapeXml(decl.src)}" x="0" y="0" width="${fmt(size.width)}" height="${fmt(size.height)}"/>` +
683
+ '</pattern>');
684
+ return `url(#${id})`;
685
+ }
686
+ emitShadowFilter(decl) {
687
+ const id = this.nextId('esvg-s');
688
+ // canvas shadowBlur ≈ 2σ(Chromium 实测口径);region 放宽防大偏移被裁
689
+ this.defs.push(`<filter id="${id}" x="-50%" y="-50%" width="200%" height="200%"><feDropShadow dx="${fmt(decl.offsetX)}" dy="${fmt(decl.offsetY)}" stdDeviation="${fmt(decl.blur / 2)}" flood-color="${escapeXml(decl.color)}"/></filter>`);
690
+ return id;
691
+ }
692
+ /** clipPath 形状 → defs;不支持形态返回 null(调用方 skip 节点) */
693
+ emitClipPath(host, hostMatrix) {
694
+ const cp = host.clipPath;
695
+ if (!cp || typeof cp !== 'object' || Array.isArray(cp))
696
+ return null;
697
+ const decl = cp;
698
+ if (typeof decl.type !== 'string' || !CLIP_TYPES.has(decl.type))
699
+ return null;
700
+ if (decl.inverted === true)
701
+ return null;
702
+ const clipW = num(decl, 'width', 0);
703
+ const clipH = num(decl, 'height', 0);
704
+ const geometry = shapeGeometry(decl, clipW, clipH);
705
+ if (!geometry)
706
+ return null;
707
+ // 相对定位(缺省):clip 坐标在宿主本地系;absolutePositioned:场景系——
708
+ // fabric 以宿主逆矩阵补偿(P4-3 同口径)
709
+ const clipM = ownMatrix(decl, clipW, clipH);
710
+ const m = decl.absolutePositioned === true ? multiply(invert(hostMatrix), clipM) : clipM;
711
+ const id = this.nextId('esvg-c');
712
+ this.defs.push(`<clipPath id="${id}">${geometryElement(geometry, m, '')}</clipPath>`);
713
+ return ` clip-path="url(#${id})"`;
714
+ }
715
+ /** 位图文本发射公共件:image 中心锚定(logicalW×H——渲染 pushQuad 同构)+
716
+ * fabric 阴影 feDropShadow(位图不含 PSD 体系外的 raw.shadow)+ textScale
717
+ * 绕中心缩放(emitText 家族语义级缩放同款) */
718
+ emitBakedTextImage(raw, baked) {
719
+ const shadow = parseShadow(raw);
720
+ if (shadow === undefined) {
721
+ this.skip('shadow-unsupported');
722
+ return null;
723
+ }
724
+ let out = `<image href="${escapeXml(baked.dataUrl)}" xlink:href="${escapeXml(baked.dataUrl)}" x="${fmt(-baked.width / 2)}" y="${fmt(-baked.height / 2)}" width="${fmt(baked.width)}" height="${fmt(baked.height)}"/>`;
725
+ if (shadow)
726
+ out = `<g filter="url(#${this.emitShadowFilter(shadow)})">${out}</g>`;
727
+ const tsx = num(raw, 'textScaleX', 1) || 1;
728
+ const tsy = num(raw, 'textScaleY', 1) || 1;
729
+ if (Math.abs(tsx - 1) > 1e-9 || Math.abs(tsy - 1) > 1e-9)
730
+ out = `<g transform="scale(${fmt(tsx)},${fmt(tsy)})">${out}</g>`;
731
+ return out;
732
+ }
733
+ emitText(raw) {
734
+ // 弧形/竖排/变形分派先于 dims 检查(各族 dims 由引擎布局重算——竖排序列化
735
+ // 可缺 height、弧形以弧 bbox 为准,raw 存值不作数)
736
+ if (arcTextKind(raw))
737
+ return this.emitArcText(raw);
738
+ if (raw.vertical === true)
739
+ return this.emitVerticalText(raw);
740
+ const warp = warpKindOf(raw);
741
+ if (warp)
742
+ return this.emitWarpedText(raw, warp);
743
+ const width = num(raw, 'width', NaN);
744
+ const height = num(raw, 'height', NaN);
745
+ if (!Number.isFinite(width) || !Number.isFinite(height)) {
746
+ // 合成 textbox(表格单元格 children)无 height 无快照——布局回退可用即走
747
+ // 引擎锚点路径(emitNode 的两级 dims 兜底同口径)
748
+ if (Number.isFinite(width) && !Number.isFinite(height)) {
749
+ const eng = this.engineLayoutOf(raw, false);
750
+ if (eng)
751
+ return this.emitTextFromEngineLayout(raw, eng);
752
+ }
753
+ this.skip('text-dims-missing');
754
+ return null;
755
+ }
756
+ if (typeof raw.direction === 'string' && raw.direction !== 'ltr') {
757
+ this.skip('text-vertical-or-rtl');
758
+ return null;
759
+ }
760
+ // 对象形态 effects(真实特效载体)→ 位图优先(baker 判活跃特效;null =
761
+ // 无特效走矢量 / 烘焙失败特效丢失的登记近似)
762
+ if (hasObjectEffects(raw)) {
763
+ const baked = this.options.bakeTextBitmap?.(raw, 'plain') ?? null;
764
+ if (baked)
765
+ return this.emitBakedTextImage(raw, baked);
766
+ }
767
+ if (Array.isArray(raw.effects) && raw.effects.length > 0) {
768
+ this.skip('text-effects');
769
+ return null;
770
+ }
771
+ // 装饰在场(划重点/文字背景)→ 引擎布局路径(装饰层消费 TextLayout,须与
772
+ // 字形共用同布局——快照路径无布局对象可喂装饰数学;布局不可用落回快照,
773
+ // 装饰静默丢=登记近似,与特效烘焙失败同语义)
774
+ if (hasTextDecorations(raw)) {
775
+ const eng = this.engineLayoutOf(raw, false);
776
+ if (eng)
777
+ return this.emitTextFromEngineLayout(raw, eng);
778
+ }
779
+ const layout = parseTextLayout(raw);
780
+ if (!layout) {
781
+ // 空文本(无字素)直出空 <text>(fabric toSVG 同款)——不因空文本框整页回退
782
+ const text = str(raw, 'text');
783
+ if (!text || !Array.from(text).some((ch) => ch !== '\n'))
784
+ return '<text xml:space="preserve"></text>';
785
+ // 布局锚点回退(引擎布局通道):合成 textbox(表格单元格 children)无
786
+ // textLines/charBounds 快照——measure 在场时现算布局,锚点 = 渲染管线的
787
+ // fillText 口径(lineLeft + box.left、contentTopY + baseline——TextRenderer 同式)
788
+ const eng = this.engineLayoutOf(raw, false);
789
+ if (eng)
790
+ return this.emitTextFromEngineLayout(raw, eng);
791
+ this.skip('text-layout-missing');
792
+ return null;
793
+ }
794
+ const shadow = parseShadow(raw);
795
+ if (shadow === undefined) {
796
+ this.skip('shadow-unsupported');
797
+ return null;
798
+ }
799
+ // textScaleX/Y(应用 Textbox 附加的盒缩放,PDFGenerator 同款):内容绕中心再缩一层
800
+ const tsx = num(raw, 'textScaleX', 1) || 1;
801
+ const tsy = num(raw, 'textScaleY', 1) || 1;
802
+ const needsTextScale = Math.abs(tsx - 1) > 1e-9 || Math.abs(tsy - 1) > 1e-9;
803
+ // 逐字锚点(paths/tspan 两模式共用——行基线/对齐/前进口径见 layoutGlyphAnchors)
804
+ const anchors = layoutGlyphAnchors(raw, layout, width, height);
805
+ const content = this.emitAnchorGlyphs(anchors, width, height);
806
+ if (content === null)
807
+ return null;
808
+ let out = content;
809
+ if (shadow)
810
+ out = `<g filter="url(#${this.emitShadowFilter(shadow)})">${out}</g>`;
811
+ if (needsTextScale)
812
+ out = `<g transform="scale(${fmt(tsx)},${fmt(tsy)})">${out}</g>`;
813
+ return out;
814
+ }
815
+ /**
816
+ * 逐字锚点发射(paths/text 双模式)。rotation/centerX 是弧形(字符中心+基线锚,
817
+ * fillText textAlign center 语义)与竖排 cjk(锚点旋转 −90°)的形态位;常规
818
+ * 横排不携带——走原字节路径(既有用例锁输出)。返回 null = 已计数 skip。
819
+ */
820
+ emitAnchorGlyphs(anchors, width, height) {
821
+ const paths = [];
822
+ const tspans = [];
823
+ const singles = [];
824
+ for (const { char, x, y, rotation, centerX, scaleY, style } of anchors) {
825
+ const transformed = rotation !== undefined || centerX === true || scaleY !== undefined;
826
+ const deg = rotation !== undefined ? (rotation * 180) / Math.PI : 0;
827
+ if (this.options.textMode === 'paths') {
828
+ if (char.trim()) {
829
+ const font = this.options.fonts?.getFont(style.fontFamily) ?? this.options.fonts?.getSubsetFont?.(style.fontFamily, char) ?? null;
830
+ if (!font) {
831
+ this.skip(`text-font-missing:${style.fontFamily}`);
832
+ return null;
833
+ }
834
+ const fill = this.resolvePaint(style.fill, width, height);
835
+ if (fill === undefined) {
836
+ this.skip('text-fill-unsupported');
837
+ return null;
838
+ }
839
+ let attrs = fill !== null ? ` fill="${escapeXml(fill)}"` : ' fill="none"';
840
+ if (typeof style.stroke === 'string' && !isBlankColor(style.stroke) && style.strokeWidth > 0) {
841
+ attrs += ` stroke="${escapeXml(style.stroke)}" stroke-width="${fmt(style.strokeWidth)}"`;
842
+ }
843
+ if (transformed) {
844
+ // 弧形/竖排/变形族:锚点平移+(旋转/纵向缩放),字形基线锚在组内原点
845
+ //(centerX 时左移 advance/2)
846
+ const offX = centerX ? -((font.getAdvanceWidth?.(char, style.fontSize) ?? 0) / 2) : 0;
847
+ const d = glyphToPathData(font.getPath(char, offX, 0, style.fontSize).commands);
848
+ let tf = `translate(${fmt(x)},${fmt(y)})`;
849
+ if (rotation !== undefined)
850
+ tf += ` rotate(${fmt(deg)})`;
851
+ if (scaleY !== undefined)
852
+ tf += ` scale(1,${fmt(scaleY)})`;
853
+ paths.push(`<g transform="${tf}"><path d="${d}"${attrs}/></g>`);
854
+ }
855
+ else {
856
+ const d = glyphToPathData(font.getPath(char, x, y, style.fontSize).commands);
857
+ paths.push(`<path d="${d}"${attrs}/>`);
858
+ }
859
+ }
860
+ }
861
+ else {
862
+ const fill = this.resolvePaint(style.fill, width, height);
863
+ if (fill === undefined) {
864
+ this.skip('text-fill-unsupported');
865
+ return null;
866
+ }
867
+ if (transformed) {
868
+ // 弧形/竖排/变形族:每字独立 <text>(transform 锚点 + text-anchor;基线锚 = 默认 alphabetic)
869
+ let attrs = ` transform="translate(${fmt(x)},${fmt(y)})${rotation !== undefined ? ` rotate(${fmt(deg)})` : ''}${scaleY !== undefined ? ` scale(1,${fmt(scaleY)})` : ''}"`;
870
+ if (centerX)
871
+ attrs += ' text-anchor="middle"';
872
+ attrs += ` font-family="${escapeXml(style.fontFamily)}"`;
873
+ attrs += ` font-size="${fmt(style.fontSize)}"`;
874
+ if (style.fontWeight !== 'normal')
875
+ attrs += ` font-weight="${escapeXml(style.fontWeight)}"`;
876
+ if (style.fontStyle !== 'normal')
877
+ attrs += ` font-style="${escapeXml(style.fontStyle)}"`;
878
+ attrs += fill !== null ? ` fill="${escapeXml(fill)}"` : ' fill="none"';
879
+ if (typeof style.stroke === 'string' && !isBlankColor(style.stroke) && style.strokeWidth > 0) {
880
+ attrs += ` stroke="${escapeXml(style.stroke)}" stroke-width="${fmt(style.strokeWidth)}"`;
881
+ }
882
+ singles.push(`<text xml:space="preserve"${attrs}>${escapeXml(char)}</text>`);
883
+ }
884
+ else {
885
+ let attrs = ` x="${fmt(x)}" y="${fmt(y)}"`;
886
+ attrs += ` font-family="${escapeXml(style.fontFamily)}"`;
887
+ attrs += ` font-size="${fmt(style.fontSize)}"`;
888
+ if (style.fontWeight !== 'normal')
889
+ attrs += ` font-weight="${escapeXml(style.fontWeight)}"`;
890
+ if (style.fontStyle !== 'normal')
891
+ attrs += ` font-style="${escapeXml(style.fontStyle)}"`;
892
+ attrs += fill !== null ? ` fill="${escapeXml(fill)}"` : ' fill="none"';
893
+ if (typeof style.stroke === 'string' && !isBlankColor(style.stroke) && style.strokeWidth > 0) {
894
+ attrs += ` stroke="${escapeXml(style.stroke)}" stroke-width="${fmt(style.strokeWidth)}"`;
895
+ }
896
+ const decorations = [style.underline ? 'underline' : '', style.overline ? 'overline' : '', style.linethrough ? 'line-through' : ''].filter(Boolean);
897
+ if (decorations.length)
898
+ attrs += ` text-decoration="${decorations.join(' ')}"`;
899
+ tspans.push(`<tspan${attrs}>${escapeXml(char)}</tspan>`);
900
+ }
901
+ }
902
+ }
903
+ if (this.options.textMode === 'paths')
904
+ return paths.join('');
905
+ // 竖排混态(latin 平画 tspan + cjk 旋转单字 <text>)共存——tspan 包 <text> 后拼接
906
+ const tspanContent = tspans.length > 0 ? `<text xml:space="preserve">${tspans.join('')}</text>` : '';
907
+ return singles.length > 0 ? singles.join('') + tspanContent : tspanContent;
908
+ }
909
+ /**
910
+ * 弧形/圆形文本(render/arcText.drawArcChars 的序列化等价):引擎布局通道
911
+ * (opentype 度量注入 layoutTextbox)→ computeArcTextLayout 每字 {中心,旋转}
912
+ * (fillText textAlign center + alphabetic 基线锚)。本地系 = layout 坐标 −
913
+ * contentOffset(渲染 quad 居中于对象中心、内容按 −offset 平移的同式)。
914
+ * effects/阴影/描边烘焙族不承接(渲染侧走特效烘焙——与快照路径同门 skip)。
915
+ */
916
+ emitArcText(raw) {
917
+ // 对象形态 effects → bakeArcText 位图优先(特效合成进位图);null 回退矢量
918
+ if (hasObjectEffects(raw)) {
919
+ const baked = this.options.bakeTextBitmap?.(raw, arcTextKind(raw) ?? 'arc') ?? null;
920
+ if (baked)
921
+ return this.emitBakedTextImage(raw, baked);
922
+ }
923
+ if (Array.isArray(raw.effects) && raw.effects.length > 0) {
924
+ this.skip('text-effects');
925
+ return null;
926
+ }
927
+ const eng = this.arcLayoutOf(raw);
928
+ if (!eng) {
929
+ this.skip(`text-font-missing:${str(raw, 'fontFamily') ?? ''}`);
930
+ return null;
931
+ }
932
+ const shadow = parseShadow(raw);
933
+ if (shadow === undefined) {
934
+ this.skip('shadow-unsupported');
935
+ return null;
936
+ }
937
+ const base = baseTextStyle(raw);
938
+ const anchors = [];
939
+ for (const p of eng.arc.chars) {
940
+ anchors.push({
941
+ char: p.char,
942
+ x: p.x - eng.arc.contentOffsetX,
943
+ y: p.y - eng.arc.contentOffsetY,
944
+ rotation: p.rotation,
945
+ centerX: true,
946
+ style: mergeCharStyle(base, eng.layout.lines[p.line]?.charStyles?.[p.index], raw)
947
+ });
948
+ }
949
+ const content = this.emitAnchorGlyphs(anchors, num(raw, 'width', 0) || eng.arc.width, eng.arc.height);
950
+ if (content === null)
951
+ return null;
952
+ return shadow ? `<g filter="url(#${this.emitShadowFilter(shadow)})">${content}</g>` : content;
953
+ }
954
+ /**
955
+ * 竖排文本(TextRenderer 竖排逐字姿态的序列化等价——fabric _renderStr 同构):
956
+ * latin/bracket 平画(基线左缘锚,latin 有 kerned−width 的 drawX 前移)、
957
+ * symbol/cjk 锚点旋转 −90°(anchorX = fontSize/1.1、anchorY 按 klass 移位);
958
+ * penV 逐字推进(latin=box.width、CJK 族=height+spacing);K-line jitter 同式。
959
+ * dimsY = max(layout.height, raw.height)(TextNode.dims 同口径)。
960
+ */
961
+ emitVerticalText(raw) {
962
+ // 对象形态 effects → bakeTextEffects 位图优先(竖排彩色逐字 + 特效合成);
963
+ // null 回退矢量(无特效正确;烘焙失败特效丢失的登记近似)
964
+ if (hasObjectEffects(raw)) {
965
+ const baked = this.options.bakeTextBitmap?.(raw, 'vertical') ?? null;
966
+ if (baked)
967
+ return this.emitBakedTextImage(raw, baked);
968
+ }
969
+ if (Array.isArray(raw.effects) && raw.effects.length > 0) {
970
+ this.skip('text-effects');
971
+ return null;
972
+ }
973
+ const layout = this.engineLayoutOf(raw, true);
974
+ if (!layout) {
975
+ this.skip(`text-font-missing:${str(raw, 'fontFamily') ?? ''}`);
976
+ return null;
977
+ }
978
+ const shadow = parseShadow(raw);
979
+ if (shadow === undefined) {
980
+ this.skip('shadow-unsupported');
981
+ return null;
982
+ }
983
+ const base = baseTextStyle(raw);
984
+ const verticalCharSpacing = base.charSpacing ? (base.fontSize * base.charSpacing) / 1000 : 0;
985
+ const textOffsetY = Number(raw.textOffsetY) || 0;
986
+ const dimsY = Math.max(layout.height, num(raw, 'height', 0));
987
+ const anchors = [];
988
+ let globalCharIndex = 0;
989
+ for (const line of layout.lines) {
990
+ const lineLeft = -layout.width / 2 + line.leftOffset;
991
+ const baselineY = -dimsY / 2 + line.baseline;
992
+ let penV = 0;
993
+ for (let i = 0; i < line.graphemes.length; i++) {
994
+ const g = line.graphemes[i];
995
+ const o = line.charStyles[i];
996
+ const glyphFontSize = o?.fontSize ?? base.fontSize;
997
+ const jitter = charJitterY(textOffsetY, glyphFontSize, globalCharIndex + i);
998
+ const box = line.boxes[i];
999
+ const klass = verticalCharClass(g);
1000
+ if (klass === 'latin' || klass === 'bracket') {
1001
+ const drawX = lineLeft + penV + (klass === 'latin' ? box.kernedWidth - box.width : 0);
1002
+ anchors.push({ char: g, x: drawX, y: baselineY + jitter, style: mergeCharStyle(base, o, raw) });
1003
+ }
1004
+ else {
1005
+ const anchorX = lineLeft + penV + verticalAnchorShiftX(glyphFontSize);
1006
+ const anchorY = baselineY + jitter + verticalAnchorShiftY(klass, box, glyphFontSize);
1007
+ anchors.push({ char: g, x: anchorX, y: anchorY, rotation: -Math.PI / 2, style: mergeCharStyle(base, o, raw) });
1008
+ }
1009
+ penV += verticalRenderAdvance(g, box, verticalCharSpacing);
1010
+ }
1011
+ globalCharIndex += line.graphemes.length;
1012
+ }
1013
+ const content = this.emitAnchorGlyphs(anchors, layout.width, dimsY);
1014
+ if (content === null)
1015
+ return null;
1016
+ // 装饰层(竖排背景照画——渲染侧无竖排特判同构;划重点 emitTextDecorations
1017
+ // 内部自挡竖排)shadow 域外、textScale 域内(emitTextFromEngineLayout 同序)
1018
+ const decor = this.emitTextDecorations(raw, layout, dimsY);
1019
+ const tsx = num(raw, 'textScaleX', 1) || 1;
1020
+ const tsy = num(raw, 'textScaleY', 1) || 1;
1021
+ let body = content;
1022
+ if (shadow)
1023
+ body = `<g filter="url(#${this.emitShadowFilter(shadow)})">${body}</g>`;
1024
+ let out = decor + body;
1025
+ if (Math.abs(tsx - 1) > 1e-9 || Math.abs(tsy - 1) > 1e-9)
1026
+ out = `<g transform="scale(${fmt(tsx)},${fmt(tsy)})">${out}</g>`;
1027
+ return out;
1028
+ }
1029
+ /**
1030
+ * 变形文本(ArchText/WaistText/FlagText,warpStrength≠0)——双路径:
1031
+ * - 位图优先(bakeWarpBitmap 注入在场):render/warpText.bakeWarpedText 同源
1032
+ * 像素 → <image dataURL> 嵌入(quad logicalW×H 居中于对象中心——渲染
1033
+ * pushQuad 同构;PSD 特效已合成进位图,位图路径不再 skip effects);
1034
+ * - 矢量近似(注入缺省/不可烘焙回退):渲染侧按列纵向形变的字符粒度近似:
1035
+ * - flag:sin(nx·π)·maxDisp·strength 列平移(无缩放——字符粒度即精确);
1036
+ * - arch:列 scaleY(底锚 contentBottom)y' = s·y + B(1−s);
1037
+ * - waist:列 scaleY(墨迹中心锚)y' = s·y + C(1−s)。
1038
+ * 锚点口径对齐 renderTextRuns(box.left 直读 + 行基线、无 K线 jitter——渲染
1039
+ * warp 路径同款)。渲染的墨迹扫描量(centerX/textHalfWidth/contentBottom/
1040
+ * centerY)以 layout 近似:中心=本地原点(烘焙中心定位)、半宽=baseTextWidth/2
1041
+ * (max(layout.width, boxW, fontSize) 同烘焙式)、底锚=盒底、中心锚=0——
1042
+ * 盒高=内容高时精确,盒被抬高的偏差为登记近似。effects/阴影烘焙族不承接
1043
+ * (渲染在烘焙内合成,与弧形同门 skip)。
1044
+ */
1045
+ emitWarpedText(raw, kind) {
1046
+ const baked = this.options.bakeTextBitmap?.(raw, kind) ?? null;
1047
+ if (baked)
1048
+ return this.emitBakedTextImage(raw, baked);
1049
+ if (Array.isArray(raw.effects) && raw.effects.length > 0) {
1050
+ this.skip('text-effects');
1051
+ return null;
1052
+ }
1053
+ const layout = this.engineLayoutOf(raw, false);
1054
+ if (!layout) {
1055
+ this.skip(`text-font-missing:${str(raw, 'fontFamily') ?? ''}`);
1056
+ return null;
1057
+ }
1058
+ const shadow = parseShadow(raw);
1059
+ if (shadow === undefined) {
1060
+ this.skip('shadow-unsupported');
1061
+ return null;
1062
+ }
1063
+ const fontSize = num(raw, 'fontSize', 40) || 40;
1064
+ const strength = Math.max(-1, Math.min(1, num(raw, 'warpStrength', 0) || 0));
1065
+ const boxW = num(raw, 'width', 0);
1066
+ const boxH = num(raw, 'height', 0);
1067
+ const dimsY = Math.max(layout.height, boxH);
1068
+ const baseTextWidth = Math.max(layout.width, boxW, fontSize);
1069
+ const maxDisp = kind === 'flag' ? Math.abs(strength) * (boxH || fontSize) * 0.3 : 0;
1070
+ const halfW = baseTextWidth / 2;
1071
+ const baseBottom = dimsY / 2;
1072
+ const base = baseTextStyle(raw);
1073
+ const anchors = [];
1074
+ for (const line of layout.lines) {
1075
+ const lineLeft = -layout.width / 2 + line.leftOffset;
1076
+ const baselineY = -dimsY / 2 + line.baseline;
1077
+ for (let i = 0; i < line.graphemes.length; i++) {
1078
+ const box = line.boxes[i];
1079
+ const style = mergeCharStyle(base, line.charStyles[i], raw);
1080
+ const x = lineLeft + box.left;
1081
+ const charCX = x + box.width / 2;
1082
+ const nx = halfW > 0 ? charCX / halfW : 0;
1083
+ if (kind === 'flag') {
1084
+ const off = Math.sin(nx * Math.PI) * maxDisp * strength;
1085
+ anchors.push({ char: line.graphemes[i], x, y: baselineY + off, style });
1086
+ }
1087
+ else if (kind === 'arch') {
1088
+ const nx1 = Math.max(-1, Math.min(1, nx));
1089
+ const falloff = Math.sqrt(Math.max(0, 1 - nx1 * nx1));
1090
+ const smooth = falloff * falloff * (3 - 2 * falloff);
1091
+ const archFalloff = strength > 0 ? Math.pow(smooth, 2.5) : smooth;
1092
+ const s = Math.min(1 + Math.max(0, strength), Math.max(0.05, 1 + strength * archFalloff));
1093
+ anchors.push({ char: line.graphemes[i], x, y: s * baselineY + baseBottom * (1 - s), scaleY: s, style });
1094
+ }
1095
+ else {
1096
+ const s = Math.min(1 + Math.abs(strength), Math.max(0.4, 1 + strength * (nx * nx - 0.5)));
1097
+ anchors.push({ char: line.graphemes[i], x, y: s * baselineY, scaleY: s, style });
1098
+ }
1099
+ }
1100
+ }
1101
+ const content = this.emitAnchorGlyphs(anchors, baseTextWidth, dimsY);
1102
+ if (content === null)
1103
+ return null;
1104
+ const tsx = num(raw, 'textScaleX', 1) || 1;
1105
+ const tsy = num(raw, 'textScaleY', 1) || 1;
1106
+ let out = content;
1107
+ if (shadow)
1108
+ out = `<g filter="url(#${this.emitShadowFilter(shadow)})">${out}</g>`;
1109
+ if (Math.abs(tsx - 1) > 1e-9 || Math.abs(tsy - 1) > 1e-9)
1110
+ out = `<g transform="scale(${fmt(tsx)},${fmt(tsy)})">${out}</g>`;
1111
+ return out;
1112
+ }
1113
+ /**
1114
+ * 蒙版(Mask)——render/maskRender.bakeMaskCompositeCanvas 的 SVG 等价:
1115
+ * clipImage(填充图)经变换链(中心 → 旋转 → 缩放·翻转 → 偏移中和 → 图心
1116
+ * 对齐)绘制,被主图(src)alpha 蒙版(SVG <mask mask-type="alpha">——
1117
+ * canvas destination-in 的 alpha 语义同款)+ 圆角 clipPath(cornerRadius
1118
+ * 四角 quad 曲线)。本地系 (0,0,w,h) 左上——外层 ownMatrix 中心系补
1119
+ * translate(−w/2,−h/2)。clipImage 的 cw/ch 取 naturalSizes(缺即
1120
+ * image-natural-missing 回退)。动态 clipImage(Video/GIF)取静态源近似
1121
+ * (首帧 src 引用——SVG 规范限制,登记)。无 clipImage → 位图直出(src
1122
+ * 原样 + 原生阴影——renderMaskNode 直出分支同构)。Puzzle = 组(objects 含
1123
+ * Mask 子对象)走 GROUP_TYPES 递归自动承接。
1124
+ */
1125
+ emitMask(raw) {
1126
+ const src = str(raw, 'src');
1127
+ if (!src) {
1128
+ this.skip('image-src-missing');
1129
+ return null;
1130
+ }
1131
+ const w = num(raw, 'width', 0);
1132
+ const h = num(raw, 'height', 0);
1133
+ if (!(w > 0) || !(h > 0)) {
1134
+ this.skip('image-dims-missing');
1135
+ return null;
1136
+ }
1137
+ const clipRaw = raw.clipImage;
1138
+ const clip = clipRaw && typeof clipRaw === 'object' ? clipRaw : null;
1139
+ const clipSrc = clip ? str(clip, 'src') : undefined;
1140
+ if (!clip || !clipSrc) {
1141
+ // 无填充图 → 位图直出(render/SceneRenderer.renderMaskNode 无 clipImage
1142
+ // 分支同构:src 原样绘制+原生阴影——空拼图格占位图导出 parity;无圆角
1143
+ // clip(渲染直出分支同不圆角)。此前无条件 skip 曾使空拼图整页回退。
1144
+ const shadow = parseShadow(raw);
1145
+ if (shadow === undefined) {
1146
+ this.skip('shadow-unsupported');
1147
+ return null;
1148
+ }
1149
+ let image = `<image href="${escapeXml(src)}" xlink:href="${escapeXml(src)}" x="${fmt(-w / 2)}" y="${fmt(-h / 2)}" width="${fmt(w)}" height="${fmt(h)}"/>`;
1150
+ if (shadow)
1151
+ image = `<g filter="url(#${this.emitShadowFilter(shadow)})">${image}</g>`;
1152
+ return image;
1153
+ }
1154
+ const size = this.options.naturalSizes?.get(clipSrc);
1155
+ if (!size || size.width <= 0 || size.height <= 0) {
1156
+ this.skip('image-natural-missing');
1157
+ return null;
1158
+ }
1159
+ const cw = size.width;
1160
+ const ch = size.height;
1161
+ const maskId = this.nextId('esvg-mk');
1162
+ this.defs.push(`<mask id="${maskId}" maskUnits="userSpaceOnUse" mask-type="alpha" x="${fmt(-w / 2)}" y="${fmt(-h / 2)}" width="${fmt(w)}" height="${fmt(h)}">` +
1163
+ `<image href="${escapeXml(src)}" xlink:href="${escapeXml(src)}" x="${fmt(-w / 2)}" y="${fmt(-h / 2)}" width="${fmt(w)}" height="${fmt(h)}"/>` +
1164
+ '</mask>');
1165
+ let open = `<g transform="translate(${fmt(-w / 2)},${fmt(-h / 2)})" mask="url(#${maskId})"`;
1166
+ const r = Math.max(0, Math.min(num(raw, 'cornerRadius', 0), Math.min(w, h) / 2));
1167
+ if (r > 0) {
1168
+ const clipId = this.nextId('esvg-mc');
1169
+ // 四角 quad 曲线(bakeMaskCompositeCanvas 同式,本地 (0,0,w,h))
1170
+ this.defs.push(`<clipPath id="${clipId}"><path d="M ${fmt(r)} 0 L ${fmt(w - r)} 0 Q ${fmt(w)} 0 ${fmt(w)} ${fmt(r)} L ${fmt(w)} ${fmt(h - r)} Q ${fmt(w)} ${fmt(h)} ${fmt(w - r)} ${fmt(h)} L ${fmt(r)} ${fmt(h)} Q 0 ${fmt(h)} 0 ${fmt(h - r)} L 0 ${fmt(r)} Q 0 0 ${fmt(r)} 0 Z"/></clipPath>`);
1171
+ open += ` clip-path="url(#${clipId})"`;
1172
+ }
1173
+ open += '>';
1174
+ // clipImage 变换链(bakeMaskCompositeCanvas 逐式;clipX/Y 为对象本地偏移)
1175
+ const angle = num(clip, 'angle', 0);
1176
+ const sx = num(clip, 'scaleX', 1) || 1;
1177
+ const sy = num(clip, 'scaleY', 1) || 1;
1178
+ const fx = clip.flipX === true ? -1 : 1;
1179
+ const fy = clip.flipY === true ? -1 : 1;
1180
+ const offsetX = num(raw, 'clipX', 0);
1181
+ const offsetY = num(raw, 'clipY', 0);
1182
+ const tf = `translate(${fmt(w / 2)},${fmt(h / 2)})` +
1183
+ ` rotate(${fmt(angle)})` +
1184
+ ` scale(${fmt(sx * fx)},${fmt(sy * fy)})` +
1185
+ ` translate(${fmt(offsetX / (sx || 1))},${fmt(offsetY / (sy || 1))})` +
1186
+ ` translate(${fmt(-cw / 2)},${fmt(-ch / 2)})`;
1187
+ return open + `<g transform="${tf}"><image href="${escapeXml(clipSrc)}" xlink:href="${escapeXml(clipSrc)}" x="0" y="0" width="${fmt(cw)}" height="${fmt(ch)}"/></g>` + '</g>';
1188
+ }
1189
+ /**
1190
+ * 表格(Table)——computeTableLayout 直出的合成子节点(行主序 rect/textbox
1191
+ * 交错,中心系 left/top 与 emitNode 本地系一致)逐个递归发射:单元格矩形
1192
+ * 走 shapeGeometry、单元格文本走 emitText(合成 textbox 无快照——emitText 的
1193
+ * 引擎布局锚点回退承接)。measure 注入与渲染同源(DOM measureText)。
1194
+ */
1195
+ emitTable(raw) {
1196
+ const table = this.tableLayoutOf(raw);
1197
+ if (!table) {
1198
+ this.skip(`text-font-missing:${typeof raw.fontFamily === 'string' ? raw.fontFamily : ''}`);
1199
+ return null;
1200
+ }
1201
+ const parts = [];
1202
+ for (const child of table.children) {
1203
+ if (!child || typeof child !== 'object' || typeof child.type !== 'string')
1204
+ continue;
1205
+ const emitted = this.emitNode(child);
1206
+ if (emitted === null)
1207
+ return null;
1208
+ if (emitted)
1209
+ parts.push(emitted);
1210
+ }
1211
+ return parts.join('');
1212
+ }
1213
+ /**
1214
+ * 引擎布局锚点发射(快照缺失回退):锚点 = 渲染管线 fillText 口径
1215
+ * (x = lineLeft + box.left、y = contentTopY + line.baseline——TextRenderer
1216
+ * renderGlyphPass 同式,无 jitter)。dimsY = max(layout.height, boxH)。
1217
+ */
1218
+ /**
1219
+ * 文本装饰层(划重点/文字背景)——renderTextBackgrounds + renderTextHighlight
1220
+ * 的 SVG 等价(本地中心系,与锚点同系直接拼接):
1221
+ * - 文字背景:每行同色 run 一块 rect(逐字覆写 ?? 对象级、run 宽 kernedWidth
1222
+ * 累计、高 line.implHeight——渲染侧逐式;竖排照画,渲染侧无竖排特判同构);
1223
+ * - 划重点:planTextHighlight(render/textHighlight 的**纯函数面**——纯数学
1224
+ * 无 DOM,与渲染侧共用同源布局数学;export 域唯一 render 引用,登记)的
1225
+ * HighlightDrawOp 逐式映射 `<g translate scale><path/></g>`(stroke-width
1226
+ * 随变换系缩放 = canvas lineWidth 受 CTM 影响的同语义)。竖排不承接
1227
+ * (renderTextHighlight 同款登记缺口)。
1228
+ * z 序 = fabric _renderText 定制链 bg → underline → highlight → 字形——
1229
+ * underline/overline/linethrough 序列化面暂不承接(后续批次)。装饰在
1230
+ * shadow filter 域外(引擎阴影剪影=纯字形不含装饰,与画布所见一致)。
1231
+ */
1232
+ emitTextDecorations(raw, layout, dimsY) {
1233
+ const parts = [];
1234
+ const contentTopY = -dimsY / 2;
1235
+ const defaultBg = typeof raw.textBackgroundColor === 'string' ? raw.textBackgroundColor : '';
1236
+ if (defaultBg || layout.lines.some((l) => l.charStyles.some((o) => o?.textBackgroundColor))) {
1237
+ for (const line of layout.lines) {
1238
+ const lineLeft = -layout.width / 2 + line.leftOffset;
1239
+ const lineTopY = contentTopY + line.top;
1240
+ const bgAt = (i) => line.charStyles[i]?.textBackgroundColor ?? defaultBg;
1241
+ let runStart = 0;
1242
+ let runWidth = 0;
1243
+ let runColor = bgAt(0);
1244
+ const flushBg = () => {
1245
+ if (!runColor || runWidth <= 0)
1246
+ return;
1247
+ const fill = colorAttr(runColor);
1248
+ if (!fill)
1249
+ return;
1250
+ parts.push(`<rect x="${fmt(lineLeft + line.boxes[runStart].left)}" y="${fmt(lineTopY)}" width="${fmt(runWidth)}" height="${fmt(line.implHeight)}" fill="${escapeXml(fill)}"/>`);
1251
+ };
1252
+ for (let i = 0; i < line.graphemes.length; i++) {
1253
+ const current = bgAt(i);
1254
+ if (current !== runColor) {
1255
+ flushBg();
1256
+ runStart = i;
1257
+ runWidth = line.boxes[i].width;
1258
+ runColor = current;
1259
+ }
1260
+ else {
1261
+ runWidth += line.boxes[i].kernedWidth;
1262
+ }
1263
+ }
1264
+ flushBg();
1265
+ }
1266
+ }
1267
+ if (Array.isArray(raw.texts) && raw.texts.length > 0 && raw.vertical !== true) {
1268
+ const plan = planTextHighlight(raw.text ?? '', layout, raw.texts, contentTopY, baseTextStyle(raw).fontSize);
1269
+ if (plan) {
1270
+ for (const op of plan.ops) {
1271
+ const path = op.isFill
1272
+ ? `<path d="${escapeXml(op.d)}" fill="${escapeXml(colorAttr(op.fill) ?? op.fill)}"/>`
1273
+ : `<path d="${escapeXml(op.d)}" fill="none" stroke="${escapeXml(colorAttr(op.stroke) ?? op.stroke)}" stroke-width="${fmt(op.strokeWidth)}"/>`;
1274
+ parts.push(`<g transform="translate(${fmt(op.translateX)},${fmt(op.translateY)}) scale(${fmt(op.scaleX)},${fmt(op.scaleY)})">${path}</g>`);
1275
+ }
1276
+ }
1277
+ }
1278
+ return parts.join('');
1279
+ }
1280
+ emitTextFromEngineLayout(raw, layout) {
1281
+ const shadow = parseShadow(raw);
1282
+ if (shadow === undefined) {
1283
+ this.skip('shadow-unsupported');
1284
+ return null;
1285
+ }
1286
+ const base = baseTextStyle(raw);
1287
+ const dimsY = Math.max(layout.height, num(raw, 'height', 0));
1288
+ const anchors = [];
1289
+ for (const line of layout.lines) {
1290
+ const lineLeft = -layout.width / 2 + line.leftOffset;
1291
+ const baselineY = -dimsY / 2 + line.baseline;
1292
+ for (let i = 0; i < line.graphemes.length; i++) {
1293
+ anchors.push({ char: line.graphemes[i], x: lineLeft + line.boxes[i].left, y: baselineY, style: mergeCharStyle(base, line.charStyles[i], raw) });
1294
+ }
1295
+ }
1296
+ const content = this.emitAnchorGlyphs(anchors, layout.width, dimsY);
1297
+ if (content === null)
1298
+ return null;
1299
+ const tsx = num(raw, 'textScaleX', 1) || 1;
1300
+ const tsy = num(raw, 'textScaleY', 1) || 1;
1301
+ // 装饰层(bg/划重点)在 shadow 域外(引擎阴影剪影=纯字形)、textScale 域内
1302
+ const decor = this.emitTextDecorations(raw, layout, dimsY);
1303
+ let body = content;
1304
+ if (shadow)
1305
+ body = `<g filter="url(#${this.emitShadowFilter(shadow)})">${body}</g>`;
1306
+ let out = decor + body;
1307
+ if (Math.abs(tsx - 1) > 1e-9 || Math.abs(tsy - 1) > 1e-9)
1308
+ out = `<g transform="scale(${fmt(tsx)},${fmt(tsy)})">${out}</g>`;
1309
+ return out;
1310
+ }
1311
+ tableCache = new Map();
1312
+ tableLayoutOf(raw) {
1313
+ const hit = this.tableCache.get(raw);
1314
+ if (hit !== undefined)
1315
+ return hit;
1316
+ if (this.layoutMeasure === undefined) {
1317
+ this.layoutMeasure = this.options.measure ?? (this.options.fonts ? measureFromFonts(this.options.fonts) : null);
1318
+ }
1319
+ if (!this.layoutMeasure)
1320
+ return null;
1321
+ let result;
1322
+ try {
1323
+ result = computeTableLayout(raw, this.layoutMeasure);
1324
+ }
1325
+ catch {
1326
+ result = null;
1327
+ }
1328
+ this.tableCache.set(raw, result);
1329
+ return result;
1330
+ }
1331
+ /** 引擎布局通道缓存(弧形:layout+arc 一体;同 raw 单页内 emitNode dims 与 emitText 双消费) */
1332
+ arcCache = new Map();
1333
+ layoutMeasure;
1334
+ engineLayoutOf(raw, vertical) {
1335
+ if (this.layoutMeasure === undefined) {
1336
+ // 注入度量优先(app 侧 DOM measureText 与渲染同源);退化 fonts 的 opentype 桥
1337
+ this.layoutMeasure = this.options.measure ?? (this.options.fonts ? measureFromFonts(this.options.fonts) : null);
1338
+ }
1339
+ if (!this.layoutMeasure)
1340
+ return null;
1341
+ if (!this.options.measure) {
1342
+ // opentype 桥路径的主族探测门:字体缺失时度量恒 0 会产出零宽错误布局而非
1343
+ // 回退(注入度量无此问题——document.fonts 回退态度量仍可用,导出可用性优先)
1344
+ const family = baseTextStyle(raw).fontFamily;
1345
+ if (!this.options.fonts?.getFont(family))
1346
+ return null;
1347
+ }
1348
+ const text = raw.text ?? '';
1349
+ return layoutTextbox(text, baseTextStyle(raw), {
1350
+ measure: this.layoutMeasure,
1351
+ // boxWidth 判定与 TextNode.textLayout 同式(弧形/竖排非 textbox 盒)
1352
+ boxWidth: raw.type === 'textbox' || raw.type === 'Textbox' ? raw.width ?? 0 : null,
1353
+ styles: stylesArrayToMap(text, raw.styles),
1354
+ splitByGrapheme: raw.splitByGrapheme === true,
1355
+ vertical,
1356
+ paragraph: arcTextKind(raw) ? undefined : raw.paragraph
1357
+ });
1358
+ }
1359
+ arcLayoutOf(raw) {
1360
+ const hit = this.arcCache.get(raw);
1361
+ if (hit !== undefined)
1362
+ return hit;
1363
+ const layout = this.engineLayoutOf(raw, false);
1364
+ const result = layout ? { layout, arc: computeArcTextLayout(layout, raw, baseTextStyle(raw).lineHeight ?? 1.16) } : null;
1365
+ this.arcCache.set(raw, result);
1366
+ return result;
1367
+ }
1368
+ emitImage(raw) {
1369
+ const src = str(raw, 'src');
1370
+ if (!src) {
1371
+ this.skip('image-src-missing');
1372
+ return null;
1373
+ }
1374
+ if (Array.isArray(raw.filters) && raw.filters.length > 0) {
1375
+ this.skip('image-filters');
1376
+ return null;
1377
+ }
1378
+ if (Array.isArray(raw.effects) && raw.effects.length > 0) {
1379
+ this.skip('image-effects');
1380
+ return null;
1381
+ }
1382
+ const gco = str(raw, 'globalCompositeOperation');
1383
+ if (gco && gco !== 'source-over' && !BLEND_MODES.has(gco)) {
1384
+ this.skip('image-gco');
1385
+ return null;
1386
+ }
1387
+ const crop = imageCropRect(toNode(raw));
1388
+ if (crop) {
1389
+ const natural = this.options.naturalSizes?.get(src);
1390
+ if (!natural) {
1391
+ this.skip('image-natural-missing');
1392
+ return null;
1393
+ }
1394
+ const vw = crop.sw;
1395
+ const vh = crop.sh;
1396
+ if (vw <= 0 || vh <= 0) {
1397
+ this.skip('image-crop-empty');
1398
+ return null;
1399
+ }
1400
+ // 全图按源像素 1:1 摆进本地系(k=1),crop 窗外部分 clip 掉——对象矩阵承担缩放。
1401
+ // image 不发 preserveAspectRatio:Chromium SVG-as-image 下该属性(含 none)会让
1402
+ // 外链图加载失败(2026-09-23 单变量实验 0/10000 vs 无属性 8130/10000);框纵横比
1403
+ // 按构造与源一致,none 冗余——fabric toSVG 亦不发(2026-09-23 真实模板对拍修复)
1404
+ const kx = vw / crop.sw;
1405
+ const ky = vh / crop.sh;
1406
+ const x0 = -vw / 2 - crop.sx * kx;
1407
+ const y0 = -vh / 2 - crop.sy * ky;
1408
+ const id = this.nextId('esvg-ic');
1409
+ // 图片圆角(批次 98):clip rect 带 rx/ry——应用 FabricImage.toSVG 的
1410
+ // 裁切+圆角分支同款(raw 值直出,SVG 规范自钳半边;渲染面是 uniform 口径
1411
+ // 的另一通道,两口径与应用双面各自对齐)
1412
+ const imgRx = num(raw, 'rx', 0);
1413
+ const imgRy = num(raw, 'ry', 0);
1414
+ const imgRounded = imgRx > 0 || imgRy > 0 ? ` rx="${fmt(imgRx)}" ry="${fmt(imgRy)}"` : '';
1415
+ this.defs.push(`<clipPath id="${id}"><rect x="${fmt(-vw / 2)}" y="${fmt(-vh / 2)}" width="${fmt(vw)}" height="${fmt(vh)}"${imgRounded}/></clipPath>`);
1416
+ return `<g clip-path="url(#${id})"><image xlink:href="${escapeXml(src)}" x="${fmt(x0)}" y="${fmt(y0)}" width="${fmt(natural.width * kx)}" height="${fmt(natural.height * ky)}"/></g>`;
1417
+ }
1418
+ const vw = num(raw, 'width', NaN);
1419
+ const vh = num(raw, 'height', NaN);
1420
+ if (!Number.isFinite(vw) || !Number.isFinite(vh)) {
1421
+ this.skip('image-dims-missing');
1422
+ return null;
1423
+ }
1424
+ const shadow = parseShadow(raw);
1425
+ if (shadow === undefined) {
1426
+ this.skip('shadow-unsupported');
1427
+ return null;
1428
+ }
1429
+ let image = `<image xlink:href="${escapeXml(src)}" x="${fmt(-vw / 2)}" y="${fmt(-vh / 2)}" width="${fmt(vw)}" height="${fmt(vh)}"/>`;
1430
+ // 图片圆角(批次 98):无裁切分支的圆角 clip 包裹(应用 FabricImage.toSVG
1431
+ // 的 imageRounded_ 同构)
1432
+ const imgRx = num(raw, 'rx', 0);
1433
+ const imgRy = num(raw, 'ry', 0);
1434
+ if (imgRx > 0 || imgRy > 0) {
1435
+ const id = this.nextId('esvg-ir');
1436
+ this.defs.push(`<clipPath id="${id}"><rect x="${fmt(-vw / 2)}" y="${fmt(-vh / 2)}" width="${fmt(vw)}" height="${fmt(vh)}" rx="${fmt(imgRx)}" ry="${fmt(imgRy)}"/></clipPath>`);
1437
+ image = `<g clip-path="url(#${id})">${image}</g>`;
1438
+ }
1439
+ if (shadow)
1440
+ image = `<g filter="url(#${this.emitShadowFilter(shadow)})">${image}</g>`;
1441
+ return image;
1442
+ }
1443
+ /** 单对象内容序列化(不含外层 <g>——由调用方包矩阵/透明度);null = 不支持(已计数) */
1444
+ emitObjectContent(raw, matrix, width, height) {
1445
+ const type = raw.type;
1446
+ if (GROUP_TYPES.has(type)) {
1447
+ const children = raw.objects;
1448
+ if (!Array.isArray(children)) {
1449
+ this.skip('group-objects-missing');
1450
+ return null;
1451
+ }
1452
+ const parts = [];
1453
+ for (const child of children) {
1454
+ if (!child || typeof child !== 'object' || typeof child.type !== 'string')
1455
+ continue;
1456
+ const emitted = this.emitNode(child);
1457
+ if (emitted === null)
1458
+ return null;
1459
+ if (emitted)
1460
+ parts.push(emitted);
1461
+ }
1462
+ return parts.join('');
1463
+ }
1464
+ if (TABLE_TYPES.has(type))
1465
+ return this.emitTable(raw);
1466
+ if (MASK_TYPES.has(type))
1467
+ return this.emitMask(raw);
1468
+ if (SVG_IMAGE_TYPES.has(type))
1469
+ return this.emitImage(raw);
1470
+ // 批次 314 图片文字(TextImage)位图态:renderSrc 在场直出 <image>——位图
1471
+ // 已含 PSD 图层视觉(effects 已烘焙进像素),不走 emitImage 的 filters/
1472
+ // effects 拦截与 crop 语义;转正态(renderSrc 已删)落下方常规文本族通道。
1473
+ // renderRect.angle=PSD 文档系轴对齐位图对元素角的逆旋(渲染侧 SceneRenderer
1474
+ // 同口径——SVG rotate 正向与引擎一致,绕本地位图中心)
1475
+ if (type === 'TextImage' && typeof raw.renderSrc === 'string') {
1476
+ const rect = raw.renderRect;
1477
+ const w = typeof rect?.w === 'number' && rect.w > 0 ? rect.w : num(raw, 'width', NaN);
1478
+ const h = typeof rect?.h === 'number' && rect.h > 0 ? rect.h : num(raw, 'height', NaN);
1479
+ if (!Number.isFinite(w) || !Number.isFinite(h) || w <= 0 || h <= 0) {
1480
+ this.skip('textimage-dims-missing');
1481
+ return null;
1482
+ }
1483
+ const x0 = -w / 2 + (typeof rect?.x === 'number' ? rect.x : 0);
1484
+ const y0 = -h / 2 + (typeof rect?.y === 'number' ? rect.y : 0);
1485
+ // 批次 344:填充不透明度调制(SceneRenderer 位图 quad 同口径;emitNode 的
1486
+ // <g opacity> 是物体透明度,两者相乘=Photoshop 合成语义)
1487
+ const fillAlpha = textBitmapFillAlpha(raw);
1488
+ let image = `<image xlink:href="${escapeXml(str(raw, 'renderSrc') ?? '')}" x="${fmt(x0)}" y="${fmt(y0)}" width="${fmt(w)}" height="${fmt(h)}"${fillAlpha < 1 ? ` opacity="${fmt(fillAlpha)}"` : ''}/>`;
1489
+ const angle = typeof rect?.angle === 'number' && Number.isFinite(rect.angle) ? rect.angle : 0;
1490
+ if (angle)
1491
+ image = `<g transform="rotate(${fmt(-angle)})">${image}</g>`;
1492
+ return image;
1493
+ }
1494
+ if (TEXT_TYPES.has(type))
1495
+ return this.emitText(raw);
1496
+ // gco → mix-blend-mode(emitNode 层统一透传,BLEND_MODES 白名单外仍在此拦截)
1497
+ const gco = str(raw, 'globalCompositeOperation');
1498
+ if (gco && gco !== 'source-over' && !BLEND_MODES.has(gco)) {
1499
+ this.skip('shape-gco');
1500
+ return null;
1501
+ }
1502
+ // 应用 FabricRect 的 strokeAlignment(inner/outer 描边几何外扩)不承接
1503
+ if (typeof raw.strokeAlignment === 'string' && raw.strokeAlignment !== 'center' && !isBlankColor(raw.stroke)) {
1504
+ this.skip('shape-stroke-alignment');
1505
+ return null;
1506
+ }
1507
+ // 线族装饰(arrow/Dimension):端头装饰专用 emitter(gco/strokeAlignment 门在上,同形状族口径)
1508
+ if (ARROW_TYPES.has(type) || DIMENSION_TYPES.has(type)) {
1509
+ return this.emitLineDecoration(raw, ARROW_TYPES.has(type));
1510
+ }
1511
+ const geometry = shapeGeometry(raw, width, height);
1512
+ if (!geometry) {
1513
+ this.skip(`type:${type}`);
1514
+ return null;
1515
+ }
1516
+ const fill = this.resolvePaint(raw.fill, width, height);
1517
+ if (fill === undefined) {
1518
+ this.skip('fill-unsupported');
1519
+ return null;
1520
+ }
1521
+ let stroke = null;
1522
+ if (strokeVisible(raw)) {
1523
+ const resolved = this.resolvePaint(raw.stroke, width, height);
1524
+ if (resolved === undefined) {
1525
+ this.skip('stroke-unsupported');
1526
+ return null;
1527
+ }
1528
+ stroke = resolved;
1529
+ }
1530
+ const shadow = parseShadow(raw);
1531
+ if (shadow === undefined) {
1532
+ this.skip('shadow-unsupported');
1533
+ return null;
1534
+ }
1535
+ const attrs = paintAttrs(raw, fill, stroke) + (shadow ? ` filter="url(#${this.emitShadowFilter(shadow)})"` : '');
1536
+ return geometryElement(geometry, null, attrs);
1537
+ }
1538
+ /**
1539
+ * 线族装饰(arrow/Dimension)——渲染侧 render/strokeBake.bakeLineDecoration 同构:
1540
+ * - Arrow:杆两端各内缩 headH(对应端有头时)+ 实心三角头(tip 在端点、向后
1541
+ * headH、底边 ±headW/2;头尺寸 = arrowWidth/Height 预设 × √strokeWidth、
1542
+ * 无 strokeUniform 补偿——渲染侧同款,arrowType 非 start/both 一律按 end);
1543
+ * - Dimension:整线(dash/cap/join 全语义)+ 两端法向端刻(长 = textFontSize、
1544
+ * round 帽、无 dash)+ 中点文本框(法向偏移 offset = fontPx + strokeWidth/2
1545
+ * + 5,Arial 硬编码同渲染侧,bg 框宽走 approxTextWidth 近似)。
1546
+ * Dimension 文本非模板字体族(系统 Arial)——textMode=paths 下仍出 <text>
1547
+ * (转曲语义只约束模板字体外发)。
1548
+ */
1549
+ emitLineDecoration(raw, isArrow) {
1550
+ const type = typeof raw.type === 'string' ? raw.type : 'line-decoration';
1551
+ const x1 = num(raw, 'x1', NaN);
1552
+ const y1 = num(raw, 'y1', NaN);
1553
+ const x2 = num(raw, 'x2', NaN);
1554
+ const y2 = num(raw, 'y2', NaN);
1555
+ if (!Number.isFinite(x1) || !Number.isFinite(y1) || !Number.isFinite(x2) || !Number.isFinite(y2)) {
1556
+ this.skip(`dims-missing:${type}`);
1557
+ return null;
1558
+ }
1559
+ // 线色兜底 #000000(渲染侧同款——线族 stroke 缺省仍画黑,不走形状族 strokeVisible 判定)
1560
+ const strokeRaw = raw.stroke;
1561
+ const strokeCol = typeof strokeRaw === 'string' && !isBlankColor(strokeRaw) ? strokeRaw : '#000000';
1562
+ if (!colorAttr(strokeCol)) {
1563
+ this.skip('stroke-unsupported');
1564
+ return null;
1565
+ }
1566
+ const strokeWidth = num(raw, 'strokeWidth', 1);
1567
+ const dash = raw.strokeDashArray;
1568
+ const dashAttr = Array.isArray(dash) && dash.length > 0
1569
+ ? ` stroke-dasharray="${dash
1570
+ .map((d) => (typeof d === 'number' && Number.isFinite(d) ? fmt(d) : null))
1571
+ .filter((s) => s !== null)
1572
+ .join(',')}"`
1573
+ : '';
1574
+ const dx = x2 - x1;
1575
+ const dy = y2 - y1;
1576
+ const angle = Math.atan2(dy, dx);
1577
+ const cos = Math.cos(angle);
1578
+ const sin = Math.sin(angle);
1579
+ if (isArrow) {
1580
+ const arrowType = raw.arrowType === 'start' || raw.arrowType === 'both' ? raw.arrowType : 'end';
1581
+ const atStart = arrowType === 'start' || arrowType === 'both';
1582
+ const atEnd = arrowType === 'end' || arrowType === 'both';
1583
+ const sizeScale = Math.sqrt(strokeWidth);
1584
+ const headW = num(raw, 'arrowWidth', 15) * sizeScale;
1585
+ const headH = num(raw, 'arrowHeight', 22.5) * sizeScale;
1586
+ const ax1 = x1 + cos * (atStart ? headH : 0);
1587
+ const ay1 = y1 + sin * (atStart ? headH : 0);
1588
+ const ax2 = x2 - cos * (atEnd ? headH : 0);
1589
+ const ay2 = y2 - sin * (atEnd ? headH : 0);
1590
+ const strokeAttrs = ` stroke="${escapeXml(strokeCol)}" stroke-width="${fmt(strokeWidth)}"${dashAttr}`;
1591
+ const parts = [`<line x1="${fmt(ax1)}" y1="${fmt(ay1)}" x2="${fmt(ax2)}" y2="${fmt(ay2)}"${strokeAttrs} fill="none"/>`];
1592
+ // 三角头:tip 在端点,两点 = tip + R(dirAngle)·(-headH, ∓headW/2)
1593
+ const head = (tipX, tipY, dirAngle) => {
1594
+ const c = Math.cos(dirAngle);
1595
+ const s = Math.sin(dirAngle);
1596
+ const bx1 = tipX - headH * c + (headW / 2) * s;
1597
+ const by1 = tipY - headH * s - (headW / 2) * c;
1598
+ const bx2 = tipX - headH * c - (headW / 2) * s;
1599
+ const by2 = tipY - headH * s + (headW / 2) * c;
1600
+ parts.push(`<path d="M ${fmt(tipX)} ${fmt(tipY)} L ${fmt(bx1)} ${fmt(by1)} L ${fmt(bx2)} ${fmt(by2)} Z" fill="${escapeXml(strokeCol)}"/>`);
1601
+ };
1602
+ if (atEnd)
1603
+ head(x2, y2, angle);
1604
+ if (atStart)
1605
+ head(x1, y1, angle + Math.PI);
1606
+ return parts.join('');
1607
+ }
1608
+ // ---- Dimension ----
1609
+ // 整线:decl 全语义(cap/join/miter 随 stroke 输出)
1610
+ let strokeAttrs = ` stroke="${escapeXml(strokeCol)}" stroke-width="${fmt(strokeWidth)}"${dashAttr}`;
1611
+ const cap = str(raw, 'strokeLineCap');
1612
+ if (cap)
1613
+ strokeAttrs += ` stroke-linecap="${escapeXml(cap)}"`;
1614
+ const join = str(raw, 'strokeLineJoin');
1615
+ if (join)
1616
+ strokeAttrs += ` stroke-linejoin="${escapeXml(join)}"`;
1617
+ const miter = raw.strokeMiterLimit;
1618
+ if (typeof miter === 'number' && Number.isFinite(miter))
1619
+ strokeAttrs += ` stroke-miterlimit="${fmt(miter)}"`;
1620
+ const parts = [`<line x1="${fmt(x1)}" y1="${fmt(y1)}" x2="${fmt(x2)}" y2="${fmt(y2)}"${strokeAttrs} fill="none"/>`];
1621
+ // 端刻:两端法向短刻(长 = textFontSize、round 帽、无 dash)
1622
+ const half = (num(raw, 'textFontSize', 50) || 50) / 2;
1623
+ const nx = -sin;
1624
+ const ny = cos;
1625
+ const tickAttrs = ` stroke="${escapeXml(strokeCol)}" stroke-width="${fmt(strokeWidth)}" stroke-linecap="round"`;
1626
+ for (const [ex, ey] of [
1627
+ [x1, y1],
1628
+ [x2, y2]
1629
+ ]) {
1630
+ parts.push(`<line x1="${fmt(ex - nx * half)}" y1="${fmt(ey - ny * half)}" x2="${fmt(ex + nx * half)}" y2="${fmt(ey + ny * half)}"${tickAttrs} fill="none"/>`);
1631
+ }
1632
+ // 中点文本框(法向偏移;follow 缺省 true,旋转取线角)
1633
+ const fontPx = num(raw, 'textFontSize', 50) || 50;
1634
+ const text = typeof raw.text === 'string' && raw.text.trim() ? raw.text : '50cm';
1635
+ const pad = num(raw, 'textPadding', 4);
1636
+ const textW = approxTextWidth(text, fontPx) + pad * 2;
1637
+ const textH = fontPx + pad * 2;
1638
+ const offset = fontPx + strokeWidth / 2 + 5;
1639
+ const cx = (x1 + x2) / 2 + nx * offset;
1640
+ const cy = (y1 + y2) / 2 + ny * offset;
1641
+ const deg = raw.textFollowLine === false ? 0 : (angle * 180) / Math.PI;
1642
+ const textColor = typeof raw.textColor === 'string' && colorAttr(raw.textColor) ? raw.textColor : '#333333';
1643
+ const bgRaw = typeof raw.textBackgroundColor === 'string' ? raw.textBackgroundColor : '#ffffff';
1644
+ const bg = colorAttr(bgRaw);
1645
+ parts.push(`<g transform="translate(${fmt(cx)},${fmt(cy)}) rotate(${fmt(deg)})">` +
1646
+ (bgRaw && bg ? `<rect x="${fmt(-textW / 2)}" y="${fmt(-textH / 2)}" width="${fmt(textW)}" height="${fmt(textH)}" fill="${escapeXml(bg)}"/>` : '') +
1647
+ `<text text-anchor="middle" dominant-baseline="central" font-family="Arial, sans-serif" font-size="${fmt(fontPx)}" fill="${escapeXml(textColor)}">${escapeXml(text)}</text>` +
1648
+ '</g>');
1649
+ return parts.join('');
1650
+ }
1651
+ /**
1652
+ * 单节点完整序列化(外层 <g transform=matrix opacity clip>)。
1653
+ * 返回 '' = 有意剔除(WorkSpace/excludeFromExport/不可见);null = 不支持(已计数)。
1654
+ */
1655
+ emitNode(raw) {
1656
+ if (WORKSPACE_IDS.has(str(raw, 'id') ?? ''))
1657
+ return '';
1658
+ if (raw.excludeFromExport === true)
1659
+ return '';
1660
+ if (raw.visible === false)
1661
+ return '';
1662
+ const type = raw.type;
1663
+ // 内容尺寸(矩阵中心换算与几何共用):裁剪图用可见尺寸、图片缺宽回退自然尺寸
1664
+ let width = num(raw, 'width', NaN);
1665
+ let height = num(raw, 'height', NaN);
1666
+ if (SVG_IMAGE_TYPES.has(type)) {
1667
+ const crop = imageCropRect(toNode(raw));
1668
+ if (crop) {
1669
+ width = crop.sw;
1670
+ height = crop.sh;
1671
+ }
1672
+ else if (!Number.isFinite(width) || !Number.isFinite(height)) {
1673
+ const natural = this.options.naturalSizes?.get(str(raw, 'src') ?? '');
1674
+ width = natural?.width ?? NaN;
1675
+ height = natural?.height ?? NaN;
1676
+ }
1677
+ }
1678
+ else if (LINE_TYPES.has(type) && (!Number.isFinite(width) || !Number.isFinite(height))) {
1679
+ width = Math.abs(num(raw, 'x2', 0) - num(raw, 'x1', 0));
1680
+ height = Math.abs(num(raw, 'y2', 0) - num(raw, 'y1', 0));
1681
+ }
1682
+ else if (ROUND_TYPES.has(type) && (!Number.isFinite(width) || !Number.isFinite(height))) {
1683
+ // 圆族 dims 兜底(model/scene ShapeNode.dims 同式):circle=2·radius、
1684
+ // ellipse=2·rx/ry——fabric 序列化原生带 radius/rx/ry,width/height 可缺席
1685
+ // (2026-10-08 报障:radius-only Circle 记 dims-missing:Circle 整页回退)
1686
+ if (type.toLowerCase() === 'circle') {
1687
+ const r = 2 * num(raw, 'radius', NaN);
1688
+ if (!Number.isFinite(width))
1689
+ width = r;
1690
+ if (!Number.isFinite(height))
1691
+ height = r;
1692
+ }
1693
+ else {
1694
+ if (!Number.isFinite(width))
1695
+ width = 2 * num(raw, 'rx', NaN);
1696
+ if (!Number.isFinite(height))
1697
+ height = 2 * num(raw, 'ry', NaN);
1698
+ }
1699
+ }
1700
+ else if ((POLYGON_TYPES.has(type) || POLYLINE_TYPES.has(type)) && (!Number.isFinite(width) || !Number.isFinite(height))) {
1701
+ // 多边形 dims 兜底(ShapeNode.dims → polygonDims 同式):points bbox——
1702
+ // width/height 缺席的 points-only raw 同害(渲染侧恒可画)
1703
+ const pts = raw.points;
1704
+ if (Array.isArray(pts) && pts.length > 0) {
1705
+ let minX = Infinity;
1706
+ let minY = Infinity;
1707
+ let maxX = -Infinity;
1708
+ let maxY = -Infinity;
1709
+ for (const p of pts) {
1710
+ const x = typeof p?.x === 'number' && Number.isFinite(p.x) ? p.x : NaN;
1711
+ const y = typeof p?.y === 'number' && Number.isFinite(p.y) ? p.y : NaN;
1712
+ if (!Number.isFinite(x) || !Number.isFinite(y))
1713
+ continue;
1714
+ if (minX > x)
1715
+ minX = x;
1716
+ if (minY > y)
1717
+ minY = y;
1718
+ if (maxX < x)
1719
+ maxX = x;
1720
+ if (maxY < y)
1721
+ maxY = y;
1722
+ }
1723
+ if (Number.isFinite(minX) && Number.isFinite(minY)) {
1724
+ if (!Number.isFinite(width))
1725
+ width = maxX - minX;
1726
+ if (!Number.isFinite(height))
1727
+ height = maxY - minY;
1728
+ }
1729
+ }
1730
+ }
1731
+ else if (TEXT_TYPES.has(type) && !Number.isFinite(height)) {
1732
+ // 文本 height 缺失兜底(两级):lineHeights 快照(fabric __lineHeights 同源,
1733
+ // 已含 lineHeight 乘子,求和 = layout.height);合成 textbox(表格单元格
1734
+ // children——无快照)走引擎布局通道现算
1735
+ if (Array.isArray(raw.lineHeights)) {
1736
+ height = raw.lineHeights.reduce((sum, h) => sum + (typeof h === 'number' && Number.isFinite(h) ? h : 0), 0);
1737
+ }
1738
+ else {
1739
+ const eng = this.engineLayoutOf(raw, false);
1740
+ if (eng)
1741
+ height = eng.height;
1742
+ }
1743
+ }
1744
+ // 弧形/圆形 dims 覆盖(渲染 initDimensions 以弧形 bbox 重算——序列化存值不作数,
1745
+ // ownMatrix 的对象中心/旋转基准随之对齐;fonts 缺失时维持存值——emitArcText 自会 skip)
1746
+ if (arcTextKind(raw)) {
1747
+ const eng = this.arcLayoutOf(raw);
1748
+ if (eng) {
1749
+ width = eng.arc.width;
1750
+ height = eng.arc.height;
1751
+ }
1752
+ }
1753
+ // Table dims 覆盖(computeTableLayout 重算值——序列化存值不作数,渲染同口径)
1754
+ if (TABLE_TYPES.has(type)) {
1755
+ const t = this.tableLayoutOf(raw);
1756
+ if (t) {
1757
+ width = t.width;
1758
+ height = t.height;
1759
+ }
1760
+ }
1761
+ if (!Number.isFinite(width) || !Number.isFinite(height)) {
1762
+ this.skip(`dims-missing:${type}`);
1763
+ return null;
1764
+ }
1765
+ const matrix = ownMatrix(raw, width, height);
1766
+ const content = this.emitObjectContent(raw, matrix, width, height);
1767
+ if (content === null)
1768
+ return null;
1769
+ if (content === '')
1770
+ return '';
1771
+ let open = `<g transform="${matAttr(matrix)}"`;
1772
+ const gcoAll = str(raw, 'globalCompositeOperation');
1773
+ if (gcoAll && gcoAll !== 'source-over' && BLEND_MODES.has(gcoAll))
1774
+ open += ` style="mix-blend-mode:${escapeXml(gcoAll)}"`;
1775
+ const opacity = num(raw, 'opacity', 1);
1776
+ if (opacity < 1)
1777
+ open += ` opacity="${fmt(opacity)}"`;
1778
+ // clipPath 施加在矩阵 g 上(几何在宿主本地系,clip 定义也在本地系)
1779
+ const clip = this.emitClipPath(raw, matrix);
1780
+ if (clip === null && raw.clipPath) {
1781
+ this.skip('clip-unsupported');
1782
+ return null;
1783
+ }
1784
+ if (clip)
1785
+ open += clip;
1786
+ return `${open}>${content}</g>`;
1787
+ }
1788
+ }
1789
+ /** 单页一次性出口:等价 new SvgExporter(options).exportPage(page)——调用方免管实例 */
1790
+ export const serializePageToSvg = (request) => new SvgExporter({ textMode: request.textMode, fonts: request.fonts, naturalSizes: request.naturalSizes, measure: request.measure, bakeTextBitmap: request.bakeTextBitmap }).exportPage(request);