@yft-design/engine 0.0.17 → 0.0.19

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 (279) hide show
  1. package/README.md +23 -11
  2. package/dist/EngineCanvas.d.ts +0 -255
  3. package/dist/core/color.d.ts +0 -11
  4. package/dist/core/distanceField.d.ts +0 -13
  5. package/dist/core/events.d.ts +0 -25
  6. package/dist/core/gradient.d.ts +0 -47
  7. package/dist/core/homography.d.ts +0 -20
  8. package/dist/core/imageFilters.d.ts +0 -31
  9. package/dist/core/mat2d.d.ts +0 -62
  10. package/dist/core/pathData.d.ts +0 -36
  11. package/dist/core/pattern.d.ts +0 -14
  12. package/dist/core/point.d.ts +0 -14
  13. package/dist/core/psdEffects.d.ts +0 -48
  14. package/dist/core/roundedRect.d.ts +0 -48
  15. package/dist/core/shadow.d.ts +0 -23
  16. package/dist/core/snap.d.ts +0 -103
  17. package/dist/core/stroke.d.ts +0 -13
  18. package/dist/core/triangulate.d.ts +0 -31
  19. package/dist/core/warpMesh.d.ts +0 -38
  20. package/dist/debug/canvasInspection.d.ts +0 -20
  21. package/dist/debug/pixelDiff.d.ts +0 -7
  22. package/dist/debug/pixelDiff.js +1 -64
  23. package/dist/debug/seed.d.ts +0 -426
  24. package/dist/debug/seed.js +28 -3806
  25. package/dist/decoders/webp2sprite.d.ts +0 -16
  26. package/dist/engineFlag.d.ts +0 -76
  27. package/dist/export/SceneExporter.d.ts +0 -58
  28. package/dist/export/glExport.d.ts +0 -41
  29. package/dist/export/svgExport.d.ts +0 -181
  30. package/dist/index.d.ts +1 -14
  31. package/dist/index.js +1060 -64
  32. package/dist/interact/animationPlayback.d.ts +0 -62
  33. package/dist/interact/canvasInteractions.d.ts +1 -38
  34. package/dist/interact/cropSession.d.ts +0 -68
  35. package/dist/interact/dblClick.d.ts +0 -32
  36. package/dist/interact/expandSession.d.ts +0 -46
  37. package/dist/interact/hotkeyActions.d.ts +0 -12
  38. package/dist/interact/pageTransfer.d.ts +0 -2
  39. package/dist/interact/pathSession.d.ts +0 -42
  40. package/dist/interact/pointer.d.ts +0 -87
  41. package/dist/interact/pointerTablePuzzle.d.ts +0 -60
  42. package/dist/interact/pointerTransform.d.ts +0 -48
  43. package/dist/interact/pointerTypes.d.ts +6 -148
  44. package/dist/interact/snapGuide.d.ts +0 -68
  45. package/dist/interact/tableCellEditing.d.ts +0 -34
  46. package/dist/interact/tableInteraction.d.ts +0 -31
  47. package/dist/interact/textEditing.d.ts +0 -44
  48. package/dist/interact/warpFacade.d.ts +0 -5
  49. package/dist/interact/warpSession.d.ts +0 -55
  50. package/dist/interact/wheelScroll.d.ts +0 -42
  51. package/dist/model/alphaHit.d.ts +0 -51
  52. package/dist/model/animation.d.ts +0 -99
  53. package/dist/model/arcLayout.d.ts +0 -33
  54. package/dist/model/arcTextTransform.d.ts +0 -4
  55. package/dist/model/compatEvents.d.ts +0 -72
  56. package/dist/model/compatObject.d.ts +0 -360
  57. package/dist/model/cropEdit.d.ts +0 -60
  58. package/dist/model/document.d.ts +0 -167
  59. package/dist/model/elementTypes.d.ts +0 -47
  60. package/dist/model/expandEdit.d.ts +0 -36
  61. package/dist/model/fabricPrimitives.d.ts +0 -24
  62. package/dist/model/filler.d.ts +0 -12
  63. package/dist/model/groupAssemble.d.ts +0 -5
  64. package/dist/model/groupChildMove.d.ts +0 -37
  65. package/dist/model/groupResize.d.ts +0 -42
  66. package/dist/model/handles.d.ts +0 -24
  67. package/dist/model/imageMaskBake.d.ts +0 -50
  68. package/dist/model/lineConstruct.d.ts +0 -8
  69. package/dist/model/maskCropEdit.d.ts +0 -34
  70. package/dist/model/pathBackground.d.ts +0 -33
  71. package/dist/model/pathConstruct.d.ts +0 -24
  72. package/dist/model/pathEdit.d.ts +0 -55
  73. package/dist/model/puzzleEdit.d.ts +0 -66
  74. package/dist/model/puzzleLayout.d.ts +0 -31
  75. package/dist/model/scene.d.ts +0 -603
  76. package/dist/model/schema.d.ts +0 -48
  77. package/dist/model/shapePath.d.ts +0 -5
  78. package/dist/model/smartObjectBake.d.ts +0 -6
  79. package/dist/model/tableEdit.d.ts +0 -90
  80. package/dist/model/tableFacade.d.ts +0 -5
  81. package/dist/model/tableLayout.d.ts +0 -40
  82. package/dist/model/textAlign.d.ts +0 -22
  83. package/dist/model/textLayout.d.ts +0 -213
  84. package/dist/render/GLBlend.d.ts +0 -24
  85. package/dist/render/GLContext.d.ts +0 -11
  86. package/dist/render/GLIsolate.d.ts +0 -25
  87. package/dist/render/GLTextureCache.d.ts +0 -72
  88. package/dist/render/GlyphAtlas.d.ts +0 -98
  89. package/dist/render/MeshBatch.d.ts +0 -71
  90. package/dist/render/QuadBatch.d.ts +0 -87
  91. package/dist/render/SceneRenderer.d.ts +0 -137
  92. package/dist/render/SourceManager.d.ts +0 -82
  93. package/dist/render/TextRenderer.d.ts +0 -120
  94. package/dist/render/arcText.d.ts +0 -28
  95. package/dist/render/bakeGate.d.ts +0 -35
  96. package/dist/render/batchOrder.d.ts +0 -60
  97. package/dist/render/blendMode.d.ts +0 -27
  98. package/dist/render/clipMaskPainter.d.ts +0 -42
  99. package/dist/render/fontInvalidation.d.ts +0 -18
  100. package/dist/render/fontInvalidationController.d.ts +0 -52
  101. package/dist/render/frameOverlay.d.ts +0 -32
  102. package/dist/render/framePipeline.d.ts +0 -27
  103. package/dist/render/gpuFilterPasses.d.ts +0 -15
  104. package/dist/render/gpuFx.d.ts +0 -82
  105. package/dist/render/gpuImageFilters.d.ts +0 -41
  106. package/dist/render/gpuShadow.d.ts +0 -38
  107. package/dist/render/gradientRamp.d.ts +0 -14
  108. package/dist/render/imageEffects.d.ts +0 -99
  109. package/dist/render/lineDecorationSdf.d.ts +0 -32
  110. package/dist/render/maskRender.d.ts +0 -60
  111. package/dist/render/multiPage.d.ts +0 -91
  112. package/dist/render/progressiveLoad.d.ts +0 -27
  113. package/dist/render/psdEffectPainter.d.ts +0 -25
  114. package/dist/render/psdWarpText.d.ts +0 -19
  115. package/dist/render/puzzleClamp.d.ts +0 -15
  116. package/dist/render/renderEpoch.d.ts +0 -21
  117. package/dist/render/retainedFrame.d.ts +0 -36
  118. package/dist/render/ruler.d.ts +0 -36
  119. package/dist/render/screenClip.d.ts +0 -31
  120. package/dist/render/scrollText.d.ts +0 -46
  121. package/dist/render/segmentTable.d.ts +0 -30
  122. package/dist/render/selectionOverlay.d.ts +0 -203
  123. package/dist/render/settleScheduler.d.ts +0 -24
  124. package/dist/render/shaders.d.ts +4 -24
  125. package/dist/render/shadowBake.d.ts +0 -28
  126. package/dist/render/shadowPainter.d.ts +0 -8
  127. package/dist/render/sharedGpuPainters.d.ts +0 -13
  128. package/dist/render/sourceHydration.d.ts +0 -8
  129. package/dist/render/strokeBake.d.ts +0 -59
  130. package/dist/render/strokeMiterOutline.d.ts +0 -29
  131. package/dist/render/strokePainter.d.ts +0 -31
  132. package/dist/render/strokeSdf.d.ts +0 -52
  133. package/dist/render/svgRaster.d.ts +0 -34
  134. package/dist/render/tableOverlay.d.ts +0 -35
  135. package/dist/render/textHighlight.d.ts +0 -67
  136. package/dist/render/textureUpload.d.ts +0 -13
  137. package/dist/render/verticalText.d.ts +0 -21
  138. package/dist/render/warpText.d.ts +0 -48
  139. package/dist/render/workspaceBackdrop.d.ts +0 -22
  140. package/dist/render/workspaceChecker.d.ts +0 -34
  141. package/dist/render/workspaceGlow.d.ts +0 -38
  142. package/package.json +4 -3
  143. package/dist/EngineCanvas.js +0 -1202
  144. package/dist/core/canvasPerf.js +0 -170
  145. package/dist/core/color.js +0 -107
  146. package/dist/core/distanceField.js +0 -92
  147. package/dist/core/events.js +0 -80
  148. package/dist/core/gradient.js +0 -175
  149. package/dist/core/homography.js +0 -123
  150. package/dist/core/imageFilters.js +0 -330
  151. package/dist/core/mat2d.js +0 -241
  152. package/dist/core/pathData.js +0 -926
  153. package/dist/core/pattern.js +0 -40
  154. package/dist/core/point.js +0 -119
  155. package/dist/core/psdEffects.js +0 -158
  156. package/dist/core/roundedRect.js +0 -164
  157. package/dist/core/shadow.js +0 -47
  158. package/dist/core/snap.js +0 -793
  159. package/dist/core/stroke.js +0 -45
  160. package/dist/core/triangulate.js +0 -194
  161. package/dist/core/warpMesh.js +0 -469
  162. package/dist/debug/canvasInspection.js +0 -113
  163. package/dist/decoders/gif2sprite.js +0 -84
  164. package/dist/decoders/webp2sprite.js +0 -133
  165. package/dist/engineFlag.js +0 -104
  166. package/dist/export/SceneExporter.js +0 -286
  167. package/dist/export/glExport.js +0 -79
  168. package/dist/export/svgExport.js +0 -1803
  169. package/dist/interact/animationPlayback.js +0 -358
  170. package/dist/interact/canvasInteractions.js +0 -174
  171. package/dist/interact/cropSession.js +0 -527
  172. package/dist/interact/dblClick.js +0 -120
  173. package/dist/interact/expandSession.js +0 -282
  174. package/dist/interact/hotkeyActions.js +0 -42
  175. package/dist/interact/pageTransfer.js +0 -56
  176. package/dist/interact/pathSession.js +0 -480
  177. package/dist/interact/pointer.js +0 -1692
  178. package/dist/interact/pointerTablePuzzle.js +0 -358
  179. package/dist/interact/pointerTransform.js +0 -441
  180. package/dist/interact/pointerTypes.js +0 -96
  181. package/dist/interact/snapGuide.js +0 -377
  182. package/dist/interact/tableCellEditing.js +0 -207
  183. package/dist/interact/tableInteraction.js +0 -219
  184. package/dist/interact/textEditing.js +0 -423
  185. package/dist/interact/warpFacade.js +0 -51
  186. package/dist/interact/warpSession.js +0 -583
  187. package/dist/interact/wheelScroll.js +0 -100
  188. package/dist/model/alphaHit.js +0 -267
  189. package/dist/model/animation.js +0 -510
  190. package/dist/model/arcLayout.js +0 -308
  191. package/dist/model/arcTextTransform.js +0 -87
  192. package/dist/model/compatEvents.js +0 -96
  193. package/dist/model/compatObject.js +0 -1583
  194. package/dist/model/cropEdit.js +0 -497
  195. package/dist/model/document.js +0 -590
  196. package/dist/model/elementTypes.js +0 -119
  197. package/dist/model/expandEdit.js +0 -161
  198. package/dist/model/fabricPrimitives.js +0 -9
  199. package/dist/model/filler.js +0 -1
  200. package/dist/model/groupAssemble.js +0 -98
  201. package/dist/model/groupChildMove.js +0 -145
  202. package/dist/model/groupResize.js +0 -109
  203. package/dist/model/handles.js +0 -29
  204. package/dist/model/imageMaskBake.js +0 -136
  205. package/dist/model/lineConstruct.js +0 -79
  206. package/dist/model/maskCropEdit.js +0 -90
  207. package/dist/model/pathBackground.js +0 -196
  208. package/dist/model/pathConstruct.js +0 -55
  209. package/dist/model/pathEdit.js +0 -378
  210. package/dist/model/puzzleEdit.js +0 -742
  211. package/dist/model/puzzleLayout.js +0 -143
  212. package/dist/model/scene.js +0 -2930
  213. package/dist/model/schema.js +0 -13
  214. package/dist/model/shapePath.js +0 -137
  215. package/dist/model/smartObjectBake.js +0 -295
  216. package/dist/model/tableEdit.js +0 -751
  217. package/dist/model/tableFacade.js +0 -808
  218. package/dist/model/tableLayout.js +0 -194
  219. package/dist/model/textAlign.js +0 -36
  220. package/dist/model/textLayout.js +0 -842
  221. package/dist/render/GLBlend.js +0 -270
  222. package/dist/render/GLContext.js +0 -48
  223. package/dist/render/GLIsolate.js +0 -188
  224. package/dist/render/GLTextureCache.js +0 -224
  225. package/dist/render/GlyphAtlas.js +0 -412
  226. package/dist/render/MeshBatch.js +0 -416
  227. package/dist/render/QuadBatch.js +0 -561
  228. package/dist/render/SceneRenderer.js +0 -753
  229. package/dist/render/SourceManager.js +0 -523
  230. package/dist/render/TextRenderer.js +0 -854
  231. package/dist/render/arcText.js +0 -187
  232. package/dist/render/bakeGate.js +0 -32
  233. package/dist/render/batchOrder.js +0 -168
  234. package/dist/render/blendMode.js +0 -142
  235. package/dist/render/clipMaskPainter.js +0 -244
  236. package/dist/render/fontInvalidation.js +0 -77
  237. package/dist/render/fontInvalidationController.js +0 -119
  238. package/dist/render/frameOverlay.js +0 -124
  239. package/dist/render/framePipeline.js +0 -96
  240. package/dist/render/gpuFilterPasses.js +0 -883
  241. package/dist/render/gpuFx.js +0 -673
  242. package/dist/render/gpuImageFilters.js +0 -295
  243. package/dist/render/gpuShadow.js +0 -327
  244. package/dist/render/gradientRamp.js +0 -74
  245. package/dist/render/imageEffects.js +0 -415
  246. package/dist/render/lineDecorationSdf.js +0 -189
  247. package/dist/render/maskRender.js +0 -217
  248. package/dist/render/multiPage.js +0 -420
  249. package/dist/render/progressiveLoad.js +0 -86
  250. package/dist/render/psdEffectPainter.js +0 -333
  251. package/dist/render/psdWarpText.js +0 -212
  252. package/dist/render/puzzleClamp.js +0 -30
  253. package/dist/render/renderEpoch.js +0 -35
  254. package/dist/render/renderViewport.js +0 -18
  255. package/dist/render/retainedFrame.js +0 -192
  256. package/dist/render/ruler.js +0 -287
  257. package/dist/render/screenClip.js +0 -67
  258. package/dist/render/scrollText.js +0 -266
  259. package/dist/render/segmentTable.js +0 -117
  260. package/dist/render/selectionOverlay.js +0 -1008
  261. package/dist/render/settleScheduler.js +0 -51
  262. package/dist/render/shaders.js +0 -450
  263. package/dist/render/shadowBake.js +0 -203
  264. package/dist/render/shadowPainter.js +0 -93
  265. package/dist/render/sharedGpuPainters.js +0 -42
  266. package/dist/render/sourceHydration.js +0 -48
  267. package/dist/render/strokeBake.js +0 -516
  268. package/dist/render/strokeMiterOutline.js +0 -224
  269. package/dist/render/strokePainter.js +0 -207
  270. package/dist/render/strokeSdf.js +0 -262
  271. package/dist/render/svgRaster.js +0 -71
  272. package/dist/render/tableOverlay.js +0 -233
  273. package/dist/render/textHighlight.js +0 -380
  274. package/dist/render/textureUpload.js +0 -26
  275. package/dist/render/verticalText.js +0 -63
  276. package/dist/render/warpText.js +0 -384
  277. package/dist/render/workspaceBackdrop.js +0 -60
  278. package/dist/render/workspaceChecker.js +0 -170
  279. package/dist/render/workspaceGlow.js +0 -198
@@ -1,842 +0,0 @@
1
- /**
2
- * fabric 文本排版算法的纯函数移植(main-webgl2 Phase 2a)。
3
- *
4
- * 与 fabric 6.9.0 的 Text/Textbox 逐公式对齐(源码精读结论):
5
- * - 度量:共享 ctx 上以 CACHE_FONT_SIZE=400px 度量并按 fontSize/400 缩放,
6
- * kernedWidth 用「前字+当前字 couple 度量 − 前字宽度」实现字偶字距(_measureChar);
7
- * couple 只在前后字字体声明(含逐字 fontSize/fontFamily/weight/style)一致时生效
8
- * (fabric stylesAreEqual = 实际字号下的 fontDeclaration 逐串相等)
9
- * - charSpacing:fontSize×charSpacing/1000 同时加到 width 与 kernedWidth;
10
- * 行宽额外减去末尾一次(measureLine)
11
- * - 换行(Textbox):wordSplit 按 /[ \t\r]/ 分词 → 逐词 grapheme 度量(样式按
12
- * 原始行/原始偏移解析)→ _wrapLine 的累加/回退状态机(含 infix 空格按其
13
- * 原始偏移样式度量与 additionalSpace 的加减)
14
- * - 行高:impl = 行内逐字 max(fontSize)×1.13(getHeightOfLineImpl,空行取行首
15
- * 原始位样式);calcTextHeight 末行不乘 lineHeight,其余行乘(fabric 历史语义)
16
- * - 字符盒 left:prev.left + prev.width + kernedWidth − width(_getGraphemeBox)
17
- * - 行偏移:center=(W−w)/2、right=W−w、left/justify=0(ltr 子集)
18
- * - 字体声明:`${fontStyle} ${fontWeight} ${size}px ${family}`,非 generic 字体加引号
19
- *
20
- * 逐字度量(P2-2):styles 里 fontSize/fontFamily/fontWeight/fontStyle 参与
21
- * 度量(getCompleteStyleDeclaration 合并语义);fill/textBackgroundColor 等
22
- * 视觉属性照旧透传。deltaY 仍属后续阶段。
23
- * 描边(P2-3):stroke/strokeWidth 逐字覆写只影响渲染(TextStrokeDecl),
24
- * 与 fabric 一致不进度量——盒宽/行高/换行结果与无描边时逐值相同。
25
- * 装饰线(P2-4):underline/overline/linethrough 不进度量,渲染侧由
26
- * lineDecorationRuns 按 fabric _renderTextDecoration 的 run 状态机产出线段 quad;
27
- * 颜色逐字跟 fill(fabric ctx.fillStyle = getValueOfPropertyAt(FILL) 同语义)。
28
- * Phase 2a 范围注记:ltr 子集(rtl 反向对齐不做);justify 全家 + disperse
29
- * 分散对齐已实现(enlargeSpaces 移植 + 编辑器 fork 口径:空格均摊加宽 +
30
- * 字符盒平移,纯 justify 只豁免末行、justify-left/center/right 变体段末行
31
- * 豁免并按对应方式收尾、disperse 全行含末行都拉、CJK 行逐字分布——详见
32
- * stretch 块头注),grapheme 切分用码点级(CJK/拉丁与 fabric 一致,
33
- * emoji 簇差异已知,后续对齐)。
34
- * splitByGrapheme(P4-4 表格单元格模式):LayoutOptions.splitByGrapheme ——
35
- * 词=单字素、无 infix 空格、样式映射不吃空格(fabric 三处守卫逐条对齐)。
36
- * 竖排(P4-5c):LayoutOptions.vertical —— 应用 Textbox vertical:true 的
37
- * 内部坐标系移植(fabric 竖排 = 横排布局 + 对象 angle:90 + CJK 类字形逆旋转,
38
- * 引擎只移植 advance/尺寸/装饰线口径,姿态在渲染侧);四套 advance 各站点
39
- * 照抄互不通用:行宽 CJK 用盒高拉丁用 width、渲染 advance CJK 用盒高+spacing
40
- * 拉丁用 width、装饰线 CJK 用盒高拉丁用 kernedWidth、calcTextWidth 双类都
41
- * 加 space;换行判定轴不覆写(fabric 原样近似)。
42
- * 布局级 parity 由 e2e 直接对比 fabric Textbox 的 _textLines/__lineWidths/height。
43
- */
44
- import { TextAlignValues, isJustifyFamilyAlign, isJustifyVariantAlign } from './textAlign';
45
- /** fabric CACHE_FONT_SIZE:所有字体度量在固定字号下做缓存 */
46
- export const CACHE_FONT_SIZE = 400;
47
- /** fabric _fontSizeMult:行高实现值 = max(fontSize) × 1.13 */
48
- export const FONT_SIZE_MULT = 1.13;
49
- /** fabric _fontSizeFraction:基线上移比例——首基线 = impl×(1−0.222),实测自
50
- * fillText 拦截(两行文本 y=−h/2+Σimpl×lineHeight+impl×0.778 逐点吻合) */
51
- export const FONT_SIZE_FRACTION = 0.222;
52
- /** fabric Textbox 默认 dynamicMinWidth(换行最大宽下限之一) */
53
- export const DYNAMIC_MIN_WIDTH = 2;
54
- /** fabric textDefaultValues.offsets:装饰线 y = 基线 + offsetY ×(run 起始字符 fontSize) */
55
- export const DECORATION_OFFSETS = { underline: 0.1, linethrough: -0.28167, overline: -0.81333 };
56
- /** fabric textDecorationThickness 类缺省(对象 fontSize 的千分比) */
57
- export const DEFAULT_DECORATION_THICKNESS = 66.667;
58
- /**
59
- * 竖排字符类判定(P4-5c)。isLatin 是应用 TextCommon.ts:120 三 regex 的引擎
60
- * 副本(空格/数字/半角标点都算拉丁——影响 advance 与姿态分支);符号集是
61
- * 应用 configs/canvas.ts ChineseSymbols/ChineseBrackets 的副本。引擎不 import
62
- * 应用层(先例:arcLayout.ts 复制 angularDiffSigned),上游改列表时须同步。
63
- */
64
- const LATIN_LETTER = /[a-zA-Z.\s]+/;
65
- const LATIN_NUM = /[0-9]/;
66
- // 字符集与应用 TextCommon 的 SYMBOL_REGX 逐字符相同(仅去掉字符类内的冗余转义过 lint)
67
- const LATIN_SYMBOL = /[()[\]{}></:;:,.?!]/;
68
- export const isLatinChar = (ch) => LATIN_LETTER.test(ch) || LATIN_NUM.test(ch) || LATIN_SYMBOL.test(ch);
69
- const CHINESE_SYMBOLS = new Set([
70
- 'ー',
71
- '「',
72
- '」',
73
- '『',
74
- '』',
75
- '(',
76
- ')',
77
- '〔',
78
- '〕',
79
- '[',
80
- ']',
81
- '{',
82
- '}',
83
- '⦅',
84
- '⦆',
85
- '〈',
86
- '〉',
87
- '《',
88
- '》',
89
- '【',
90
- '】',
91
- '〖',
92
- '〗',
93
- '〘',
94
- '〙',
95
- '〚',
96
- '〛',
97
- '゛',
98
- '゜',
99
- '。',
100
- '、',
101
- '・',
102
- '゠',
103
- '=',
104
- '〜',
105
- '…',
106
- '•',
107
- '‥',
108
- '◦',
109
- '﹅',
110
- '﹆'
111
- ]);
112
- const CHINESE_BRACKETS = new Set(['「', '」', '『', '』', '〔', '〕', '[', ']', '{', '}', '⦅', '⦆', '〈', '〉', '《', '》', '【', '】', '〖', '〗', '〘', '〙', '〚', '〛', '(', ')']);
113
- export const verticalCharClass = (ch) => {
114
- if (isLatinChar(ch))
115
- return 'latin';
116
- if (CHINESE_BRACKETS.has(ch))
117
- return 'bracket';
118
- if (CHINESE_SYMBOLS.has(ch))
119
- return 'symbol';
120
- return 'cjk';
121
- };
122
- /** 竖排逐字渲染 advance(fabric _renderChars 2459-2478 per-char 口径):
123
- * 拉丁 = charBox.width(已含 charSpacing),CJK 族 = charBox.height(=逐字
124
- * fontSize) + verticalCharSpacing(对象 fontSize × charSpacing / 1000,
125
- * fabric _getWidthOfCharSpacing——CJK 的 spacing 不在 kernedWidth 里须手动加) */
126
- export const verticalRenderAdvance = (ch, box, verticalCharSpacing) => (isLatinChar(ch) ? box.width : box.height + verticalCharSpacing);
127
- /** 竖排旋转类的 translate 锚点偏移(fabric _renderStr 2728/2734 经验魔数照抄):
128
- * x 恒 +fontSize/1.1;y 普通CJK = +charBox.height/2 − fontSize/3.14,
129
- * 标点 = −fontSize/3.14(句读推向字面上侧)。仅 symbol/cjk 类消费。 */
130
- export const verticalAnchorShiftX = (fontSize) => fontSize / 1.1;
131
- export const verticalAnchorShiftY = (klass, box, fontSize) => (klass === 'symbol' ? -fontSize / 3.14 : box.height / 2 - fontSize / 3.14);
132
- /** K-line 垂直偏移的逐字抖动量(fabric Textbox._renderStr 2714-2757,应用
133
- * 「上下上下」变形):偶字不动、奇字偏移 (textOffsetY/300)·fontSize/2——
134
- * textOffsetY∈[-300,300](面板滑杆界),正下负上;fontSize 取该字有效字号
135
- * (逐字覆写优先)。globalCharIndex 按视觉行字素数跨行累计(fabric 对
136
- * _textLines 逐行求和口径,不含 \n 分隔符——勿用 styleMap.flatStart,它含
137
- * 分隔符会错位奇偶)。竖排同式偏移落在锚点 y 上(fabric 对 charTop 加偏移
138
- * 后再算旋转锚点,对象经 angle:90 后视觉呈左右交错)。 */
139
- export const charJitterY = (textOffsetY, fontSize, globalCharIndex) => {
140
- if (textOffsetY === 0)
141
- return 0;
142
- return globalCharIndex % 2 === 0 ? 0 : (textOffsetY / 300) * fontSize * 0.5;
143
- };
144
- /** 节点级抖动上界(虚线烘焙/特效剪影的画布余量用):|textOffsetY|/300·0.5·
145
- * 全字最大有效字号——逐字覆写 fontSize 会抬高峰值,保守取 max。 */
146
- export const maxCharJitterY = (textOffsetY, style, lines) => {
147
- if (textOffsetY === 0)
148
- return 0;
149
- let max = style.fontSize;
150
- for (const line of lines) {
151
- for (const o of line.charStyles) {
152
- const size = o?.fontSize;
153
- if (typeof size === 'number' && size > max)
154
- max = size;
155
- }
156
- }
157
- return (Math.abs(textOffsetY) / 300) * max * 0.5;
158
- };
159
- let sharedInkCtx = null;
160
- /** 缺省墨迹度量:共享 canvas;无 2d 上下文/缺实际边界度量时回退 em 比例
161
- * (同 glyphAtlas 的 0.88/0.24 口径——right/center 对齐量略保守收入盒内) */
162
- export const defaultInkMeasure = (decl, text, fontSize) => {
163
- const fallback = { left: 0, right: 0, ascent: fontSize * 0.88, descent: fontSize * 0.24 };
164
- if (typeof document === 'undefined')
165
- return fallback;
166
- if (!sharedInkCtx) {
167
- const canvas = document.createElement('canvas');
168
- canvas.width = 8;
169
- canvas.height = 8;
170
- sharedInkCtx = canvas.getContext('2d');
171
- }
172
- if (!sharedInkCtx)
173
- return fallback;
174
- sharedInkCtx.font = decl;
175
- const m = sharedInkCtx.measureText(text);
176
- if (m.actualBoundingBoxAscent === undefined || m.actualBoundingBoxDescent === undefined)
177
- return fallback;
178
- return {
179
- left: -(m.actualBoundingBoxLeft ?? 0),
180
- right: m.actualBoundingBoxRight ?? 0,
181
- ascent: m.actualBoundingBoxAscent,
182
- descent: m.actualBoundingBoxDescent
183
- };
184
- };
185
- const inkMetricsByMeasure = new WeakMap();
186
- /** 度量缓存注册表:WeakMap 键不可枚举,登记创建出的缓存表供迟到失效总清 */
187
- const measureCacheRegistry = new Set();
188
- const measureInk = (inkMeasure, style, char) => {
189
- let byDecl = inkMetricsByMeasure.get(inkMeasure);
190
- if (!byDecl) {
191
- byDecl = new Map();
192
- inkMetricsByMeasure.set(inkMeasure, byDecl);
193
- measureCacheRegistry.add(byDecl);
194
- }
195
- const key = `${fontDeclaration(style, style.fontSize)}|${char}`;
196
- let m = byDecl.get(key);
197
- if (!m) {
198
- m = inkMeasure(fontDeclaration(style, style.fontSize), char, style.fontSize);
199
- byDecl.set(key, m);
200
- }
201
- return m;
202
- };
203
- /**
204
- * 竖排行沿流向(内部坐标 +x,即对象 angle:90 后的屏幕 +y)的墨迹范围,相对
205
- * 行首笔位。渲染链口径(与 renderGlyphPass / verticalGlyphOps 同一摆位公式):
206
- * - 旋转类(symbol/cjk):锚点 = 笔位 + fontSize/1.1,rotate(−π/2) 后墨迹相对
207
- * 锚点 = [−ascent, +descent](GL cell 摆位 relY 投影;40px「中」探针实测
208
- * [3,41] vs 36.36−asc34/+desc6 逐像素吻合);
209
- * - 平画类(latin/bracket):墨迹相对笔位 = [ink.left, ink.right],latin 画位
210
- * 再前移 kerned−width(fabric signWidth)。
211
- * 供竖排 center/right 对齐量消费(见 layoutTextbox 行偏移处的补丁注释);
212
- * left 对齐不调用(offset 恒 0,与 fabric 逐像素一致的主路径不动)。
213
- */
214
- export const verticalLineInkRun = (line, style, inkMeasure = defaultInkMeasure) => {
215
- const vSpacing = style.charSpacing ? (style.fontSize * style.charSpacing) / 1000 : 0;
216
- let penV = 0;
217
- let start = 0;
218
- let end = 0;
219
- for (let i = 0; i < line.graphemes.length; i++) {
220
- const g = line.graphemes[i];
221
- const box = line.boxes[i];
222
- const glyphStyle = resolveCharStyle(style, line.charStyles[i]);
223
- const klass = verticalCharClass(g);
224
- let lead;
225
- let trail;
226
- if (klass === 'latin' || klass === 'bracket') {
227
- const shift = klass === 'latin' ? box.kernedWidth - box.width : 0;
228
- const ink = measureInk(inkMeasure, glyphStyle, g);
229
- lead = ink.left + shift;
230
- trail = ink.right + shift;
231
- }
232
- else {
233
- const ink = measureInk(inkMeasure, glyphStyle, g);
234
- lead = verticalAnchorShiftX(glyphStyle.fontSize) - ink.ascent;
235
- trail = verticalAnchorShiftX(glyphStyle.fontSize) + ink.descent;
236
- }
237
- if (i === 0)
238
- start = lead;
239
- end = penV + trail;
240
- penV += verticalRenderAdvance(g, box, vSpacing);
241
- }
242
- return { start, end };
243
- };
244
- export const GENERIC_FONTS = new Set([
245
- 'serif',
246
- 'sans-serif',
247
- 'monospace',
248
- 'cursive',
249
- 'fantasy',
250
- 'system-ui',
251
- 'ui-serif',
252
- 'ui-sans-serif',
253
- 'ui-monospace',
254
- 'ui-rounded',
255
- 'math',
256
- 'emoji',
257
- 'fangsong',
258
- 'inherit',
259
- 'initial',
260
- 'unset'
261
- ]);
262
- /** 与 fabric _getFontDeclaration 同构的字体声明(forMeasuring 时用 CACHE_FONT_SIZE) */
263
- export const fontDeclaration = (style, size) => {
264
- const family = style.fontFamily;
265
- const parsed = family.includes("'") || family.includes('"') || family.includes(',') || GENERIC_FONTS.has(family.toLowerCase()) ? family : `"${family}"`;
266
- return `${style.fontStyle ?? 'normal'} ${style.fontWeight ?? 'normal'} ${size}px ${parsed}`;
267
- };
268
- /** 前缀串(fabric Textbox._getParagraphPrefix:id=0 按视觉行号编号,含空行) */
269
- export const paragraphPrefixOf = (paragraph, lineIndex) => {
270
- if (!paragraph)
271
- return undefined;
272
- if (paragraph.id === 0)
273
- return `${lineIndex + 1}`;
274
- return paragraph.content || undefined;
275
- };
276
- /**
277
- * 逐字描边解析(fabric getCompleteStyleDeclaration 语义:逐字覆写优先、对象级兜底)。
278
- * 对象无描边但逐字给了 stroke+strokeWidth 时同样成声明——fabric 的
279
- * `_renderTextStroke` 只因 isEmptyStyles() 才整体跳过。
280
- *
281
- * 已知缺口:strokeDashArray/strokeDashOffset 不在此列——fabric 按行(无逐字样式时)
282
- * 或按 run 一次 strokeText,虚线相位在整行/整 run 内连续;引擎图集是逐字形 cell,
283
- * 相位会逐字重来。虚线描边留待 P3-2(描边展开与对齐)按 run 级栅格化处理。
284
- */
285
- export const resolveStrokeDecl = (base, o) => {
286
- const color = o?.stroke ?? base?.color;
287
- const width = o?.strokeWidth ?? base?.width;
288
- if (!color || !width)
289
- return null;
290
- return {
291
- color,
292
- width,
293
- lineJoin: base?.lineJoin,
294
- miterLimit: base?.miterLimit,
295
- lineCap: base?.lineCap
296
- };
297
- };
298
- /** 行内 CJK 判定(编辑器 Textbox.enlargeSpaces fork 的 cjkRegex 原样:Han 统一
299
- * 表意 + 平假名 + 片假名 + 谚文音节;扩展区/兼容区不在此列——fork 口径原样保留)。
300
- * 纯 justify/disperse 的 CJK 行按逐字分布拉伸;渲染侧 run 断段(dash 描边/
301
- * scrollText)同源判定逐字断段。 */
302
- export const CJK_LINE_RE = /[\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/;
303
- /**
304
- * 行末 x(相对行首):fabric `_measureLine` 的**行末哨兵盒**口径 =
305
- * 末字符盒 left + width(width 含行尾 charSpacing)。justify 拉伸行的空格
306
- * 加宽/平移同样作用于末盒 → 端点落在拉伸末端(fabric enlargeSpaces 对哨兵盒
307
- * 的 acc 平移同语义)。`line.width` 保持自然行宽(fabric `__lineWidths` 口径,
308
- * 布局对拍用),行末光标/选区端点一律走本口径,两者不可混用。
309
- */
310
- export const lineEndOffset = (line) => {
311
- const last = line.boxes[line.boxes.length - 1];
312
- return last ? last.left + last.width : 0;
313
- };
314
- /**
315
- * 行首列表前缀的 canvas 绘制(fabric _renderChars 前缀块 2408-2444 的等价抽取):
316
- * 在 (x, baselineY) 以行首字符的字体声明 fillText/strokeText 前缀串(一次出笔,
317
- * 前缀内 kerning 保留——GL 图集管线的逐字 advance 是其近似)。竖排同样在此
318
- * 出笔(fabric 前缀块无竖排分支:不旋转、画在列首行基线)。返回前缀宽
319
- * (无前缀 = 0),供调用方把正文 run 起点 `left += prefixWidth`(fabric 同款)。
320
- */
321
- export const drawParagraphPrefix = (ctx, line, x, baselineY, opts = {}) => {
322
- const prefix = line.prefix;
323
- if (!prefix)
324
- return 0;
325
- const prevFont = ctx.font;
326
- ctx.font = fontDeclaration(prefix.style, prefix.style.fontSize);
327
- if (opts.fill) {
328
- if (opts.fill !== 'keep')
329
- ctx.fillStyle = opts.fill;
330
- ctx.fillText(prefix.text, x, baselineY);
331
- }
332
- if (opts.stroke && opts.stroke.width > 0) {
333
- ctx.lineWidth = opts.stroke.width;
334
- ctx.strokeStyle = opts.stroke.color;
335
- ctx.strokeText(prefix.text, x, baselineY);
336
- }
337
- ctx.font = prevFont;
338
- return prefix.width;
339
- };
340
- /**
341
- * 单行装饰线 run(P2-4,fabric `_renderTextDecoration` 状态机的纯函数移植)。
342
- *
343
- * 语义要点(源码逐行核对):
344
- * - run 分段键 = (开关, fill, 逐字 fontSize, thickness)——任一变化即断段;
345
- * 断段后的新 run 首字符贡献**普通 width**(非 kernedWidth,fabric 原样行为),
346
- * 续段字符累加 kernedWidth;
347
- * - 线宽 = **对象** fontSize × thickness‰ / 1000(fabric finalTickness 用 this.fontSize,
348
- * 逐字大字号不会加粗装饰线);y 偏移的 size 乘数则取 run 起始字符的逐字 fontSize;
349
- * - 末次 flush 的宽度额外扣除一次对象级 charSpacing(fillRect(boxWidth − charSpacing));
350
- * - 开关/色/线宽任一为假则该段不产出(fabric lastDecoration && lastFill && lastTickness)。
351
- * 行内逐字全 false 时返回空(fabric 整行跳过 styleHas 判定的视觉等价)。
352
- * deltaY 参与 fabric 的分段键与 y 公式,引擎暂不支持逐字 deltaY(恒 0),后续接。
353
- */
354
- export const lineDecorationRuns = (line, type, defaults) => {
355
- const runs = [];
356
- const objOn = !!defaults[type];
357
- const valueAt = (i) => !!(line.charStyles[i]?.[type] ?? objOn);
358
- if (!line.graphemes.some((_, i) => valueAt(i)))
359
- return runs;
360
- const fillAt = (i) => line.charStyles[i]?.fill ?? defaults.fill ?? '';
361
- const ticknessAt = (i) => line.charStyles[i]?.textDecorationThickness ?? defaults.textDecorationThickness ?? DEFAULT_DECORATION_THICKNESS;
362
- const sizeAt = (i) => line.charStyles[i]?.fontSize ?? defaults.fontSize;
363
- const offsetY = DECORATION_OFFSETS[type];
364
- const aligner = type === 'linethrough' ? 0.5 : type === 'overline' ? 1 : 0;
365
- const spacingWidth = defaults.charSpacing ? (defaults.fontSize * defaults.charSpacing) / 1000 : 0;
366
- const push = (on, fill, ticknessPermille, size, x, width) => {
367
- if (!on || !fill || !ticknessPermille || width <= 0)
368
- return;
369
- const thickness = (defaults.fontSize * ticknessPermille) / 1000;
370
- runs.push({ x, width, y: offsetY * size - aligner * thickness, thickness, color: fill });
371
- };
372
- let boxStart = 0;
373
- let boxWidth = 0;
374
- let lastOn = valueAt(0);
375
- let lastFill = fillAt(0);
376
- let lastTickness = ticknessAt(0);
377
- let lastSize = sizeAt(0);
378
- for (let j = 0; j < line.graphemes.length; j++) {
379
- const on = valueAt(j);
380
- const fill = fillAt(j);
381
- const tickness = ticknessAt(j);
382
- const size = sizeAt(j);
383
- const box = line.boxes[j];
384
- // P4-5c 竖排 advance(应用 Textbox 1261/1269):CJK 用盒高、拉丁用 kernedWidth
385
- // ——与 _renderChars 的渲染 advance(width / height+spacing)是两套口径,各自照抄
386
- const advance = defaults.vertical ? (isLatinChar(line.graphemes[j]) ? box.kernedWidth : box.height) : box.kernedWidth;
387
- if ((on !== lastOn || fill !== lastFill || tickness !== lastTickness || size !== lastSize) && boxWidth > 0) {
388
- push(lastOn, lastFill, lastTickness, lastSize, boxStart, boxWidth);
389
- boxStart = box.left;
390
- boxWidth = defaults.vertical ? advance : box.width;
391
- lastOn = on;
392
- lastFill = fill;
393
- lastTickness = tickness;
394
- lastSize = size;
395
- }
396
- else {
397
- boxWidth += defaults.vertical ? advance : box.kernedWidth;
398
- }
399
- }
400
- push(lastOn, lastFill, lastTickness, lastSize, boxStart, boxWidth - spacingWidth);
401
- return runs;
402
- };
403
- let sharedCtx = null;
404
- export const defaultMeasure = (decl, text) => {
405
- if (typeof document === 'undefined')
406
- return 0;
407
- if (!sharedCtx) {
408
- const canvas = document.createElement('canvas');
409
- canvas.width = 8;
410
- canvas.height = 8;
411
- // jsdom 无 2d 上下文实现:度量退化为 0(单测走注入度量,不依赖真实字体)
412
- sharedCtx = canvas.getContext('2d');
413
- if (!sharedCtx)
414
- return 0;
415
- }
416
- sharedCtx.font = decl;
417
- return sharedCtx.measureText(text).width;
418
- };
419
- /** grapheme 切分:码点级(Intl.Segmenter 的 grapheme 级差异属后续对齐项) */
420
- export const graphemeSplit = (value) => Array.from(value);
421
- const wordSplit = (value) => value.split(/[ \t\r]/);
422
- /** per-font 度量缓存(fabric cache.getFontCache 同语义:400px 下的 char/couple 宽) */
423
- class FontMeasure {
424
- decl;
425
- measure;
426
- charWidths = new Map();
427
- coupleWidths = new Map();
428
- constructor(decl, measure) {
429
- this.decl = decl;
430
- this.measure = measure;
431
- }
432
- charWidth(char) {
433
- let w = this.charWidths.get(char);
434
- if (w === undefined) {
435
- w = this.measure(this.decl, char);
436
- this.charWidths.set(char, w);
437
- }
438
- return w;
439
- }
440
- coupleWidth(prev, char) {
441
- const key = prev + '\u0000' + char;
442
- let w = this.coupleWidths.get(key);
443
- if (w === undefined) {
444
- w = this.measure(this.decl, prev + char);
445
- this.coupleWidths.set(key, w);
446
- }
447
- return w;
448
- }
449
- }
450
- const fontMeasuresByMeasure = new WeakMap();
451
- const getFontMeasure = (decl, measure) => {
452
- // 缓存按度量函数分组:生产恒用 defaultMeasure(单例),测试注入各自的 mock 互不串扰
453
- let byDecl = fontMeasuresByMeasure.get(measure);
454
- if (!byDecl) {
455
- byDecl = new Map();
456
- fontMeasuresByMeasure.set(measure, byDecl);
457
- measureCacheRegistry.add(byDecl);
458
- }
459
- let fm = byDecl.get(decl);
460
- if (!fm) {
461
- fm = new FontMeasure(decl, measure);
462
- byDecl.set(decl, fm);
463
- }
464
- return fm;
465
- };
466
- /** 字体迟到失效的度量总清(EngineCanvas.handleFontsLoaded 消费):字符宽/字距宽/墨迹
467
- * 三类按「字体声明串」键的缓存全部作废。声明串不含字体加载态——同族从回退变真实后
468
- * 键不变,旧缓存命中会把 fallback 宽度带进重排(字形换了但折行/行宽仍错,且字距
469
- * couple 键按声明串命中无法自愈)。调用时机稀有(字体到达),粗粒度全清安全。 */
470
- export const clearAllMeasureCaches = () => {
471
- for (const cache of measureCacheRegistry)
472
- cache.clear();
473
- };
474
- /** fabric getCompleteStyleDeclaration 同构:对象样式为底、逐字覆写只合并字体四件套
475
- * (fill/textBackgroundColor 等视觉属性不影响度量,由渲染侧直接读 charStyles) */
476
- const resolveCharStyle = (base, o) => {
477
- if (!o || (o.fontSize === undefined && o.fontFamily === undefined && o.fontWeight === undefined && o.fontStyle === undefined))
478
- return base;
479
- return {
480
- ...base,
481
- fontSize: o.fontSize ?? base.fontSize,
482
- fontFamily: o.fontFamily ?? base.fontFamily,
483
- fontWeight: o.fontWeight ?? base.fontWeight,
484
- fontStyle: o.fontStyle ?? base.fontStyle
485
- };
486
- };
487
- /** fabric _measureChar 的纯函数版:400px 度量 ×(fontSize/400);kerning couple 只在
488
- * 前后字「实际字号下的字体声明」一致时生效(fabric stylesAreEqual 同语义——
489
- * _getFontDeclaration 不带 forMeasuring 时含实际 fontSize,声明不同的两字间
490
- * 不做 couple 度量,kernedWidth 退化为 width) */
491
- const measureChar = (measure, style, char, prev, prevStyle) => {
492
- const fm = getFontMeasure(fontDeclaration(style, CACHE_FONT_SIZE), measure);
493
- const multiplier = style.fontSize / CACHE_FONT_SIZE;
494
- const width = fm.charWidth(char);
495
- let kernedWidth = width;
496
- if (prev && prevStyle && fontDeclaration(prevStyle, prevStyle.fontSize) === fontDeclaration(style, style.fontSize)) {
497
- kernedWidth = fm.coupleWidth(prev, char) - fm.charWidth(prev);
498
- }
499
- return { width: width * multiplier, kernedWidth: kernedWidth * multiplier };
500
- };
501
- const getWidthOfCharSpacing = (style) => (style.charSpacing ? (style.fontSize * style.charSpacing) / 1000 : 0);
502
- /** fabric Textbox._wrapLine 状态机的忠实移植,返回 grapheme 行数组。
503
- * infix 空格按其在原始行内的偏移查样式度量(fabric _measureWord([infix],
504
- * lineIndex, offset)),offset 游走与 fabric 逐行累加(词长+1)同构。
505
- * splitByGrapheme 模式(P4-4):infix=''(永不压入行)、infixWidth 恒 0——
506
- * fabric `!splitByGrapheme` 的两处守卫同构 */
507
- const wrapLine = (lineIndex, desiredWidth, wordsData, largestWordWidth, style, styleAt, measure, splitByGrapheme = false) => {
508
- const additionalSpace = getWidthOfCharSpacing(style);
509
- const graphemeLines = [];
510
- const infix = ' ';
511
- let lineWidth = 0;
512
- let line = [];
513
- let infixWidth = 0;
514
- let lineJustStarted = true;
515
- let offset = 0;
516
- const maxWidth = Math.max(desiredWidth, largestWordWidth, DYNAMIC_MIN_WIDTH);
517
- const data = wordsData[lineIndex];
518
- for (let i = 0; i < data.length; i++) {
519
- const word = data[i].graphemes;
520
- const wordWidth = data[i].width;
521
- offset += word.length;
522
- lineWidth += (splitByGrapheme ? 0 : infixWidth) + wordWidth - additionalSpace;
523
- if (lineWidth > maxWidth && !lineJustStarted) {
524
- graphemeLines.push(line);
525
- line = [];
526
- lineWidth = wordWidth;
527
- lineJustStarted = true;
528
- }
529
- else {
530
- lineWidth += additionalSpace;
531
- }
532
- if (!lineJustStarted && !splitByGrapheme) {
533
- line.push(infix);
534
- }
535
- line = line.concat(word);
536
- // fabric _measureWord([infix], lineIndex, offset):_getGraphemeBox 会把
537
- // charSpacing 加进 kernedWidth,故 infix 宽 = 空格宽 + charSpacing
538
- infixWidth = splitByGrapheme ? 0 : measureChar(measure, styleAt(lineIndex, offset), infix).kernedWidth + additionalSpace;
539
- offset++;
540
- lineJustStarted = false;
541
- }
542
- if (data.length)
543
- graphemeLines.push(line);
544
- return graphemeLines;
545
- };
546
- /**
547
- * 完整排版:text + 样式 → 行切分 + 字符盒 + 尺寸。
548
- * 字符盒 left/width/kernedWidth 与 fabric __charBounds 同单位(对象本地坐标,
549
- * fontSize 像素、scale=1),渲染侧直接消费。
550
- * 逐字 fontSize/fontFamily/fontWeight/fontStyle 按原始行/字索引参与度量
551
- * (换行期词宽、最终字符盒、行高 impl 全部走逐字样式)。
552
- */
553
- export const layoutTextbox = (text, style, options = {}) => {
554
- const measure = options.measure ?? defaultMeasure;
555
- const inkMeasure = options.inkMeasure ?? defaultInkMeasure;
556
- const rawStyles = options.styles;
557
- const styleAt = (line, char) => resolveCharStyle(style, rawStyles?.[line]?.[char]);
558
- const spacing = getWidthOfCharSpacing(style);
559
- const lineHeightMult = style.lineHeight ?? 1.16;
560
- // 词宽度(fabric _measureWord:Σ kernedWidth,skipLeft=true;样式按原始行/偏移解析)
561
- const measureWord = (graphemes, rawLine, charOffset) => {
562
- let width = 0;
563
- let prev;
564
- for (let i = 0; i < graphemes.length; i++) {
565
- const info = measureChar(measure, styleAt(rawLine, charOffset + i), graphemes[i], prev, i > 0 ? styleAt(rawLine, charOffset + i - 1) : undefined);
566
- width += info.kernedWidth + spacing;
567
- prev = graphemes[i];
568
- }
569
- return width;
570
- };
571
- const rawLines = (text ?? '').split('\n');
572
- let graphemeLines;
573
- // fabric Textbox dynamicMinWidth 语义:最长「词」放不下时按词宽撑盒(不重排),
574
- // CJK 整句无空格时整句即一个词——不补这条,盒宽与 fabric 系统性不一致
575
- let largestWordWidth = 0;
576
- if (options.boxWidth == null) {
577
- graphemeLines = rawLines.map((l) => graphemeSplit(l));
578
- }
579
- else if (options.splitByGrapheme) {
580
- // fabric getGraphemeDataForRender 的 splitByGrapheme 分支:词 = 单字素、
581
- // infix='',空行落 [{word:[],width:0}] 单条目(换行后仍产出一条空行)
582
- const wordsData = [];
583
- for (let lineIndex = 0; lineIndex < rawLines.length; lineIndex++) {
584
- const graphemes = graphemeSplit(rawLines[lineIndex]);
585
- if (graphemes.length === 0) {
586
- wordsData.push([{ graphemes: [], width: 0, charOffset: 0 }]);
587
- continue;
588
- }
589
- // fabric offset += 字素长 + infix.length(0) —— 每字素的 charOffset 即行内索引
590
- const lineWords = graphemes.map((g, i) => {
591
- const width = measureWord([g], lineIndex, i);
592
- largestWordWidth = Math.max(width, largestWordWidth);
593
- return { graphemes: [g], width, charOffset: i };
594
- });
595
- wordsData.push(lineWords);
596
- }
597
- graphemeLines = [];
598
- for (let i = 0; i < wordsData.length; i++) {
599
- graphemeLines.push(...wrapLine(i, options.boxWidth, wordsData, largestWordWidth, style, styleAt, measure, true));
600
- }
601
- }
602
- else {
603
- // fabric getGraphemeDataForRender + _wrapText(词内 charOffset 供逐字样式解析)
604
- const wordsData = [];
605
- for (let lineIndex = 0; lineIndex < rawLines.length; lineIndex++) {
606
- const lineWords = [];
607
- let offset = 0;
608
- for (const word of wordSplit(rawLines[lineIndex])) {
609
- const graphemes = graphemeSplit(word);
610
- const width = measureWord(graphemes, lineIndex, offset);
611
- largestWordWidth = Math.max(width, largestWordWidth);
612
- lineWords.push({ graphemes, width, charOffset: offset });
613
- offset += graphemes.length + 1; // +1 = 词后 infix 空格(与 fabric 同构)
614
- }
615
- wordsData.push(lineWords);
616
- }
617
- graphemeLines = [];
618
- for (let i = 0; i < wordsData.length; i++) {
619
- graphemeLines.push(...wrapLine(i, options.boxWidth, wordsData, largestWordWidth, style, styleAt, measure));
620
- }
621
- }
622
- // fabric _generateStyleMap 移植:视觉行 → 原始行/偏移(含换行被吃掉的分隔符游走)。
623
- // flat = Array.from(text)(含 \n);视觉行首在 flat 中的偏移同时记录(光标映射用)
624
- const flatGraphemes = graphemeSplit(text ?? '');
625
- const styleMapEntries = [];
626
- {
627
- let realLineCount = 0;
628
- let realLineCharCount = 0;
629
- let charCount = 0;
630
- for (let i = 0; i < graphemeLines.length; i++) {
631
- const separator = flatGraphemes[charCount];
632
- if (separator === '\n' && i > 0) {
633
- realLineCharCount = 0;
634
- charCount++;
635
- realLineCount++;
636
- }
637
- else if (i > 0 && !options.splitByGrapheme && /[ \t\r]/.test(separator ?? '')) {
638
- // 自动换行吃掉的分隔空格(词级换行模式;splitByGrapheme 下空格是
639
- // 实字素不落行——fabric _generateStyleMap 的 !splitByGrapheme 守卫)
640
- realLineCharCount++;
641
- charCount++;
642
- }
643
- styleMapEntries[i] = { line: realLineCount, offset: realLineCharCount, flatStart: charCount };
644
- charCount += graphemeLines[i].length;
645
- realLineCharCount += graphemeLines[i].length;
646
- }
647
- }
648
- // 每行字符盒与行宽(fabric _measureLine:样式按视觉行→原始行映射解析)
649
- const lines = graphemeLines.map((graphemes, lineIndex) => {
650
- const entry = styleMapEntries[lineIndex];
651
- const boxes = [];
652
- let width = 0;
653
- for (let i = 0; i < graphemes.length; i++) {
654
- const info = measureChar(measure, styleAt(entry.line, entry.offset + i), graphemes[i], i > 0 ? graphemes[i - 1] : undefined, i > 0 ? styleAt(entry.line, entry.offset + i - 1) : undefined);
655
- const box = {
656
- left: 0,
657
- width: info.width + spacing,
658
- kernedWidth: info.kernedWidth + spacing,
659
- // fabric _getGraphemeBox:height = 逐字 fontSize(竖排 CJK advance 基数)
660
- height: styleAt(entry.line, entry.offset + i).fontSize
661
- };
662
- if (i > 0) {
663
- box.left = boxes[i - 1].left + boxes[i - 1].width + info.kernedWidth - info.width;
664
- }
665
- boxes.push(box);
666
- // P4-5c 竖排行宽(应用 Textbox._measureLine 1307-1311):CJK 用盒高、
667
- // 拉丁用 width(注意不是 kernedWidth——与横排累加口径不同,各自照抄)
668
- if (options.vertical && !isLatinChar(graphemes[i])) {
669
- width += box.height;
670
- }
671
- else {
672
- width += box.kernedWidth;
673
- }
674
- }
675
- if (spacing !== 0)
676
- width -= spacing;
677
- if (width < 0)
678
- width = 0;
679
- const charStyles = graphemes.map((_, j) => rawStyles?.[entry.line]?.[entry.offset + j]);
680
- // fabric getHeightOfLineImpl:行高 impl = 行内逐字 max(fontSize)×_fontSizeMult
681
- // (getHeightOfChar = 样式覆写优先);空行取行首原始位样式(getValueOfPropertyAt(line,0))
682
- let maxFont = 0;
683
- if (graphemes.length > 0) {
684
- for (let i = 0; i < graphemes.length; i++) {
685
- maxFont = Math.max(maxFont, rawStyles?.[entry.line]?.[entry.offset + i]?.fontSize ?? style.fontSize);
686
- }
687
- }
688
- else {
689
- maxFont = rawStyles?.[entry.line]?.[entry.offset]?.fontSize ?? style.fontSize;
690
- }
691
- // 列表前缀(fabric _measureLine 1315-1337):前缀宽并入行宽 + 该行全部
692
- // 字符盒 left 平移(含行末哨兵语义——引擎哨兵由末盒 left+width 推导,平移
693
- // 自动生效);空行同样编号(前缀按视觉行号)。leftOffset/justify 在本
694
- // map 之后跑,对齐把「前缀+文字」作为整体收边(fabric getLineWidth 同口径)
695
- let prefix;
696
- if (options.paragraph) {
697
- const prefixText = paragraphPrefixOf(options.paragraph, lineIndex);
698
- if (prefixText) {
699
- const prefixStyle = styleAt(entry.line, entry.offset);
700
- const prefixDecl = fontDeclaration(prefixStyle, prefixStyle.fontSize);
701
- const prefixWidth = measure(prefixDecl, prefixText);
702
- // 宽 0(jsdom 无 2d ctx 的度量退化)= 无前缀:不平移也不留给渲染层
703
- //(零宽前缀画在未平移的首字上必重叠,浏览器实测非空串恒 > 0)
704
- if (prefixWidth > 0) {
705
- prefix = {
706
- text: prefixText,
707
- width: prefixWidth,
708
- advances: graphemeSplit(prefixText).map((g) => measure(prefixDecl, g)),
709
- style: prefixStyle
710
- };
711
- for (const box of boxes)
712
- box.left += prefix.width;
713
- width += prefix.width;
714
- }
715
- }
716
- }
717
- return { graphemes, boxes, width, leftOffset: 0, baseline: 0, top: 0, implHeight: maxFont * FONT_SIZE_MULT, styleMap: entry, charStyles, prefix };
718
- });
719
- // 高度与基线:fabric calcTextHeight(末行 impl 不乘 lineHeight);
720
- // 基线 = Σ_{j<i}(impl_j×lineHeight) + impl_i×(1−_fontSizeFraction)
721
- // ——注意首基线不是 impl(源码 _renderChars 里 top -= impl×0.222),
722
- // 历史上只看 _renderTextCommon 会误推成 impl,已用 fillText 拦截实测校准
723
- let height = 0;
724
- let acc = 0;
725
- for (let i = 0; i < lines.length; i++) {
726
- const impl = lines[i].implHeight;
727
- const isLast = i === lines.length - 1;
728
- lines[i].top = acc;
729
- lines[i].baseline = acc + impl * (1 - FONT_SIZE_FRACTION);
730
- acc += impl * lineHeightMult;
731
- height += isLast ? impl : impl * lineHeightMult;
732
- }
733
- // 行偏移(ltr 子集:rtl 的反向对齐不在此列);盒宽按 dynamicMinWidth 语义扩展后
734
- // 参与对齐计算(fabric 用扩展后的 this.width)。justify 变体的段末行按
735
- // left/center/right 收尾(fabric _getLineLeftOffset 的 JUSTIFY_* 分支),
736
- // 其余(left/justify/justify-left 与将被拉伸的 justify-* 非段末行)恒 0
737
- const expandedBoxWidth = options.boxWidth != null ? Math.max(options.boxWidth, largestWordWidth - spacing) : 0;
738
- // P4-5c 竖排 text/itext 盒宽:fabric calcTextWidth 竖排分支(应用 Textbox
739
- // 2165-2198)= 最长列 + cursorWidth(2);逐字累加 isLatin ? width+space :
740
- // height+space——width 已含 spacing 仍再加一次 space,是 fabric 原样 quirk
741
- const verticalCalcWidth = () => {
742
- let longest = 0;
743
- for (const line of lines) {
744
- let len = 0;
745
- for (let j = 0; j < line.graphemes.length; j++) {
746
- len += isLatinChar(line.graphemes[j]) ? line.boxes[j].width + spacing : line.boxes[j].height + spacing;
747
- }
748
- longest = Math.max(longest, len);
749
- }
750
- return longest + 2;
751
- };
752
- const verticalWidth = options.vertical ? verticalCalcWidth() : undefined;
753
- const boxW = options.boxWidth != null ? expandedBoxWidth : options.vertical ? verticalWidth : Math.max(0, ...lines.map((l) => l.width));
754
- const align = style.textAlign ?? TextAlignValues.LEFT;
755
- // 段末行判定(fabric Textbox.isEndOfWrapping:下一视觉行已属新原始行即段末;
756
- // text/itext 无自动换行,fabric Text.isEndOfWrapping 只认最后一行)
757
- const isEndOfWrapping = (i) => {
758
- if (options.boxWidth == null)
759
- return i === lines.length - 1;
760
- const next = lines[i + 1]?.styleMap;
761
- return !next || next.line !== lines[i].styleMap.line;
762
- };
763
- for (let i = 0; i < lines.length; i++) {
764
- const centerish = align === TextAlignValues.CENTER || (align === TextAlignValues.JUSTIFY_CENTER && isEndOfWrapping(i));
765
- const rightish = align === TextAlignValues.RIGHT || (align === TextAlignValues.JUSTIFY_RIGHT && isEndOfWrapping(i));
766
- // P4-5c 补丁(2026-09-20,仅 webgl2 引擎侧——登记为有意偏差):竖排
767
- // center/right 的对齐量改按渲染链墨迹口径(verticalLineInkRun)。应用侧
768
- // fabric 以度量列长收边(_measureLine 竖排 CJK=盒高、不含 charSpacing),
769
- // 而渲染笔位每字多推进 spacing 且锚点前移 fontSize/1.1——right/center 时
770
- // 墨迹越过盒远端(charSpacing=120×6 字实测超底 28.8px=n×spacing)。
771
- // 引擎按墨迹收边:left 对齐零改动(主路径与 fabric 逐像素一致不变),
772
- // center/right 与应用侧的偏差见 roadmap §1(应用侧修复须另立批次)。
773
- if (options.vertical && (centerish || rightish) && lines[i].graphemes.length > 0) {
774
- const ink = verticalLineInkRun(lines[i], style, inkMeasure);
775
- lines[i].leftOffset = centerish ? (boxW - ink.start - ink.end) / 2 : boxW - ink.end;
776
- continue;
777
- }
778
- const diff = boxW - lines[i].width;
779
- if (centerish) {
780
- lines[i].leftOffset = diff / 2;
781
- }
782
- else if (rightish) {
783
- lines[i].leftOffset = diff;
784
- }
785
- }
786
- // 两端/分散对齐(fabric enlargeSpaces 移植 + 编辑器 fork 口径 a7e9b58cd):
787
- // 把 (盒宽 − 自然行宽) 均摊进行内可拉单元的 width/kernedWidth 并平移后续
788
- // 字符盒 left——fabric 在度量后直接改 __charBounds,渲染/光标/选区/装饰线
789
- // 全部随盒生效,引擎同口径改 boxes。line.width 保持自然行宽(fabric
790
- // __lineWidths 不被 enlargeSpaces 触碰,布局对拍口径);行末端点(光标/
791
- // 选区)用 lineEndOffset 的哨兵盒口径,末盒被同步平移/加宽后即落在拉伸末端。
792
- // 行豁免矩阵(编辑器 Textbox.enlargeSpaces fork;2026-10-14 引擎从「fabric
793
- // 上游含末行全拉」对齐到产品口径——产品编辑器的纯 justify 从不拉末行):
794
- // - 纯 'justify':只豁免最后一行(段末行照拉)
795
- // - 'justify-left/center/right' 变体:跳过段末行+末行,由上面的行偏移收尾
796
- // - 'disperse'(分散对齐):全部行含末行都拉(fork 无豁免)
797
- // 分布粒度(纯 justify/disperse 共用,fork 的 cjkRegex 分路;变体恒空格
798
- // 粒度——fork 变体走 super.enlargeSpaces):行内含 CJK(CJK_LINE_RE)→
799
- // 逐字分布,slack 均摊进 (n−1) 个字间隙,每字加宽、末字只平移不加宽(首尾
800
- // 两缘恰好贴盒;fork 按 UTF-16 split('') 计数,引擎按 grapheme 计数,代理
801
- // 对行的计数更准,属登记偏差);无 CJK → 只加宽空格(fabric 原生,行内
802
- // 无空格或行宽已达盒宽不拉伸)。竖排不拉伸(编辑器 verticaltext mixin
803
- // 从不消费对齐拉伸;竖排 left/center/right 行偏移不受影响)。
804
- const disperse = align === TextAlignValues.DISPERSE;
805
- if ((isJustifyFamilyAlign(align) || disperse) && !options.vertical) {
806
- for (let i = 0; i < lines.length; i++) {
807
- const line = lines[i];
808
- const variant = isJustifyVariantAlign(align);
809
- if (variant && (i === lines.length - 1 || isEndOfWrapping(i)))
810
- continue;
811
- if (!variant && !disperse && i === lines.length - 1)
812
- continue;
813
- if (line.width >= boxW)
814
- continue;
815
- const charWise = !variant && line.graphemes.some((g) => CJK_LINE_RE.test(g));
816
- const slots = charWise ? line.graphemes.length - 1 : line.graphemes.reduce((n, g) => (/[ \t\r]/.test(g) ? n + 1 : n), 0);
817
- if (slots <= 0)
818
- continue;
819
- const diffSpace = (boxW - line.width) / slots;
820
- let accumulated = 0;
821
- for (let j = 0; j < line.graphemes.length; j++) {
822
- const box = line.boxes[j];
823
- const stretchThis = charWise ? j < line.graphemes.length - 1 : /[ \t\r]/.test(line.graphemes[j]);
824
- box.left += accumulated;
825
- if (stretchThis) {
826
- box.width += diffSpace;
827
- box.kernedWidth += diffSpace;
828
- accumulated += diffSpace;
829
- }
830
- }
831
- }
832
- }
833
- // flat grapheme → UTF-16 码元偏移(textarea selectionStart 是码元口径)
834
- const graphemeCodeUnitOffsets = [];
835
- let codeUnit = 0;
836
- for (const g of flatGraphemes) {
837
- graphemeCodeUnitOffsets.push(codeUnit);
838
- codeUnit += g.length;
839
- }
840
- graphemeCodeUnitOffsets.push(codeUnit); // 末尾光标位
841
- return { lines, width: boxW, height, graphemeCodeUnitOffsets, verticalWidth };
842
- };