ultra-text 1.0.1 → 1.0.3

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 (237) hide show
  1. package/README.md +339 -1039
  2. package/dist/assets/cpuSdf.worker-Dy4P5_TI.js +466 -0
  3. package/dist/assets/cpuSdf.worker-Dy4P5_TI.js.map +1 -0
  4. package/dist/assets/traceOutline.worker-B5uVKmR4.js +1725 -0
  5. package/dist/assets/traceOutline.worker-B5uVKmR4.js.map +1 -0
  6. package/dist/atlas/appendAtlas.js +97 -31
  7. package/dist/atlas/appendAtlas.js.map +1 -1
  8. package/dist/atlas/buildAtlas.js +4 -3
  9. package/dist/atlas/buildAtlas.js.map +1 -1
  10. package/dist/atlas/colorGlyphs.d.ts +0 -10
  11. package/dist/atlas/colorGlyphs.js +97 -155
  12. package/dist/atlas/colorGlyphs.js.map +1 -1
  13. package/dist/atlas/colorTexture.d.ts +1 -0
  14. package/dist/atlas/colorTexture.js +64 -0
  15. package/dist/atlas/colorTexture.js.map +1 -0
  16. package/dist/atlas/cpuAtlas.d.ts +4 -1
  17. package/dist/atlas/cpuAtlas.js +14 -7
  18. package/dist/atlas/cpuAtlas.js.map +1 -1
  19. package/dist/atlas/cpuSdf.d.ts +1 -1
  20. package/dist/atlas/cpuSdf.js +235 -68
  21. package/dist/atlas/cpuSdf.js.map +1 -1
  22. package/dist/atlas/cpuWorker.d.ts +11 -3
  23. package/dist/atlas/cpuWorker.js +179 -22
  24. package/dist/atlas/cpuWorker.js.map +1 -1
  25. package/dist/atlas/gpuAtlas.js +188 -287
  26. package/dist/atlas/gpuAtlas.js.map +1 -1
  27. package/dist/atlas/gpuCommon.d.ts +257 -0
  28. package/dist/atlas/gpuCommon.js +845 -0
  29. package/dist/atlas/gpuCommon.js.map +1 -0
  30. package/dist/atlas/jfaWgsl.d.ts +1 -1
  31. package/dist/atlas/jfaWgsl.js +226 -249
  32. package/dist/atlas/jfaWgsl.js.map +1 -1
  33. package/dist/atlas/rasterize.d.ts +22 -0
  34. package/dist/atlas/rasterize.js +329 -158
  35. package/dist/atlas/rasterize.js.map +1 -1
  36. package/dist/atlas/shapeRaster.js +2 -1
  37. package/dist/atlas/shapeRaster.js.map +1 -1
  38. package/dist/atlas/vanillaBounds.d.ts +64 -0
  39. package/dist/atlas/vanillaBounds.js +42 -0
  40. package/dist/atlas/vanillaBounds.js.map +1 -0
  41. package/dist/atlas/vanillaCore.d.ts +100 -0
  42. package/dist/atlas/vanillaCore.js +1065 -0
  43. package/dist/atlas/vanillaCore.js.map +1 -0
  44. package/dist/atlas/vanillaCpuAtlas.d.ts +9 -0
  45. package/dist/atlas/vanillaCpuAtlas.js +72 -0
  46. package/dist/atlas/vanillaCpuAtlas.js.map +1 -0
  47. package/dist/atlas/vanillaExtras.d.ts +8 -0
  48. package/dist/atlas/vanillaExtras.js +167 -0
  49. package/dist/atlas/vanillaExtras.js.map +1 -0
  50. package/dist/atlas/vanillaGpuHelpers.d.ts +295 -0
  51. package/dist/atlas/vanillaGpuHelpers.js +354 -0
  52. package/dist/atlas/vanillaGpuHelpers.js.map +1 -0
  53. package/dist/dom/DomSdf.js +243 -297
  54. package/dist/dom/DomSdf.js.map +1 -1
  55. package/dist/dom/DomSlug.js +94 -165
  56. package/dist/dom/DomSlug.js.map +1 -1
  57. package/dist/dom/Text.d.ts +4 -1
  58. package/dist/dom/Text.js +5 -1
  59. package/dist/dom/Text.js.map +1 -1
  60. package/dist/dom/browserShaping.js +31 -14
  61. package/dist/dom/browserShaping.js.map +1 -1
  62. package/dist/dom/clusters.js +13 -2
  63. package/dist/dom/clusters.js.map +1 -1
  64. package/dist/dom/cssEffects.d.ts +4 -0
  65. package/dist/dom/cssEffects.js +72 -0
  66. package/dist/dom/cssEffects.js.map +1 -0
  67. package/dist/dom/domAnalytic.d.ts +53 -0
  68. package/dist/dom/domAnalytic.js +282 -0
  69. package/dist/dom/domAnalytic.js.map +1 -0
  70. package/dist/dom/domExtras.d.ts +27 -0
  71. package/dist/dom/domExtras.js +137 -0
  72. package/dist/dom/domExtras.js.map +1 -0
  73. package/dist/dom/fontCanvas.d.ts +16 -0
  74. package/dist/dom/fontCanvas.js +31 -13
  75. package/dist/dom/fontCanvas.js.map +1 -1
  76. package/dist/dom/layoutSignature.js +175 -57
  77. package/dist/dom/layoutSignature.js.map +1 -1
  78. package/dist/dom/markup.d.ts +10 -0
  79. package/dist/dom/markup.js +16 -1
  80. package/dist/dom/markup.js.map +1 -1
  81. package/dist/dom/pretextLayout.js +78 -28
  82. package/dist/dom/pretextLayout.js.map +1 -1
  83. package/dist/dom/snapshot.d.ts +4 -0
  84. package/dist/dom/snapshot.js +891 -484
  85. package/dist/dom/snapshot.js.map +1 -1
  86. package/dist/dom/snapshotsEqual.d.ts +7 -0
  87. package/dist/dom/snapshotsEqual.js +68 -0
  88. package/dist/dom/snapshotsEqual.js.map +1 -0
  89. package/dist/dom/svgCapture.d.ts +8 -1
  90. package/dist/dom/svgCapture.js +105 -28
  91. package/dist/dom/svgCapture.js.map +1 -1
  92. package/dist/dom/textTransform.d.ts +13 -1
  93. package/dist/dom/textTransform.js +31 -13
  94. package/dist/dom/textTransform.js.map +1 -1
  95. package/dist/dom/tone.js +91 -44
  96. package/dist/dom/tone.js.map +1 -1
  97. package/dist/index.js +4 -3
  98. package/dist/slug/SlugMaterial.d.ts +17 -3
  99. package/dist/slug/SlugMaterial.js +98 -26
  100. package/dist/slug/SlugMaterial.js.map +1 -1
  101. package/dist/slug/cff.d.ts +5 -0
  102. package/dist/slug/cff.js +780 -0
  103. package/dist/slug/cff.js.map +1 -0
  104. package/dist/slug/coverage.d.ts +19 -15
  105. package/dist/slug/coverage.js +380 -225
  106. package/dist/slug/coverage.js.map +1 -1
  107. package/dist/slug/preprocessCore.d.ts +6 -2
  108. package/dist/slug/preprocessCore.js +199 -148
  109. package/dist/slug/preprocessCore.js.map +1 -1
  110. package/dist/slug/runtime.d.ts +1 -0
  111. package/dist/slug/runtime.js +113 -74
  112. package/dist/slug/runtime.js.map +1 -1
  113. package/dist/slug/standaloneRuntime.d.ts +3 -2
  114. package/dist/slug/standaloneRuntime.js +112 -67
  115. package/dist/slug/standaloneRuntime.js.map +1 -1
  116. package/dist/slug/truetype.d.ts +14 -6
  117. package/dist/slug/truetype.js +356 -255
  118. package/dist/slug/truetype.js.map +1 -1
  119. package/dist/slug/vanillaCore.d.ts +410 -0
  120. package/dist/slug/vanillaCore.js +1630 -0
  121. package/dist/slug/vanillaCore.js.map +1 -0
  122. package/dist/slug-vanilla.d.ts +13 -364
  123. package/dist/slug-vanilla.js +7 -1454
  124. package/dist/slug.d.ts +2 -2
  125. package/dist/slug.js +7 -7
  126. package/dist/text/GlyphTextMaterial.d.ts +6 -1
  127. package/dist/text/GlyphTextMaterial.js +16 -12
  128. package/dist/text/GlyphTextMaterial.js.map +1 -1
  129. package/dist/text/RectMaterial.js +6 -10
  130. package/dist/text/RectMaterial.js.map +1 -1
  131. package/dist/text/SdfTextMaterial.d.ts +9 -3
  132. package/dist/text/SdfTextMaterial.js +125 -38
  133. package/dist/text/SdfTextMaterial.js.map +1 -1
  134. package/dist/text/decorations.d.ts +7 -2
  135. package/dist/text/decorations.js +187 -79
  136. package/dist/text/decorations.js.map +1 -1
  137. package/dist/text/geometry.d.ts +3 -22
  138. package/dist/text/geometryUtils.d.ts +16 -1
  139. package/dist/text/geometryUtils.js +83 -8
  140. package/dist/text/geometryUtils.js.map +1 -1
  141. package/dist/text/glyphGeometry.d.ts +9 -0
  142. package/dist/text/glyphGeometry.js +434 -0
  143. package/dist/text/glyphGeometry.js.map +1 -0
  144. package/dist/text/index.d.ts +2 -1
  145. package/dist/text/rectGeometry.d.ts +13 -0
  146. package/dist/text/rectGeometry.js +101 -0
  147. package/dist/text/rectGeometry.js.map +1 -0
  148. package/dist/text/reflow.d.ts +23 -1
  149. package/dist/text/reflow.js +223 -94
  150. package/dist/text/reflow.js.map +1 -1
  151. package/dist/text/snap.d.ts +15 -0
  152. package/dist/text/snap.js +26 -0
  153. package/dist/text/snap.js.map +1 -0
  154. package/dist/text/tone.js +2 -2
  155. package/dist/text/tone.js.map +1 -1
  156. package/dist/types.d.ts +23 -7
  157. package/dist/vanilla.d.ts +13 -363
  158. package/dist/vanilla.js +7 -1474
  159. package/dist/windfoil/WindfoilCompositeMaterial.d.ts +1 -1
  160. package/dist/windfoil/WindfoilCompositeMaterial.js +10 -3
  161. package/dist/windfoil/WindfoilCompositeMaterial.js.map +1 -1
  162. package/dist/windfoil/WindfoilMaterial.d.ts +12 -5
  163. package/dist/windfoil/WindfoilMaterial.js +71 -8
  164. package/dist/windfoil/WindfoilMaterial.js.map +1 -1
  165. package/dist/windfoil/compositeGeometry.js +12 -5
  166. package/dist/windfoil/compositeGeometry.js.map +1 -1
  167. package/dist/windfoil/coverage.d.ts +10 -2
  168. package/dist/windfoil/coverage.js +147 -59
  169. package/dist/windfoil/coverage.js.map +1 -1
  170. package/dist/windfoil/geometry.d.ts +17 -2
  171. package/dist/windfoil/geometry.js +220 -57
  172. package/dist/windfoil/geometry.js.map +1 -1
  173. package/dist/windfoil/layerGrid.js +8 -8
  174. package/dist/windfoil/layerGrid.js.map +1 -1
  175. package/dist/windfoil/mixed.d.ts +1 -0
  176. package/dist/windfoil/mixed.js +57 -29
  177. package/dist/windfoil/mixed.js.map +1 -1
  178. package/dist/windfoil/preprocess.js +2 -2
  179. package/dist/windfoil/preprocessCore.d.ts +2 -0
  180. package/dist/windfoil/preprocessCore.js +69 -37
  181. package/dist/windfoil/preprocessCore.js.map +1 -1
  182. package/dist/windfoil/requests.d.ts +1 -1
  183. package/dist/windfoil/requests.js +11 -4
  184. package/dist/windfoil/requests.js.map +1 -1
  185. package/dist/windfoil/resolveOutline.d.ts +9 -0
  186. package/dist/windfoil/resolveOutline.js +20 -0
  187. package/dist/windfoil/resolveOutline.js.map +1 -0
  188. package/dist/windfoil/runtime.d.ts +4 -1
  189. package/dist/windfoil/runtime.js +69 -63
  190. package/dist/windfoil/runtime.js.map +1 -1
  191. package/dist/windfoil/shapeGeometry.js +80 -34
  192. package/dist/windfoil/shapeGeometry.js.map +1 -1
  193. package/dist/windfoil/sizeSwitch.d.ts +1 -1
  194. package/dist/windfoil/sizeSwitch.js +13 -8
  195. package/dist/windfoil/sizeSwitch.js.map +1 -1
  196. package/dist/windfoil/storage.d.ts +78 -6
  197. package/dist/windfoil/storage.js +166 -11
  198. package/dist/windfoil/storage.js.map +1 -1
  199. package/dist/windfoil/svg/curves.d.ts +20 -0
  200. package/dist/windfoil/svg/curves.js +145 -42
  201. package/dist/windfoil/svg/curves.js.map +1 -1
  202. package/dist/windfoil/svg/document.js +10 -1
  203. package/dist/windfoil/svg/document.js.map +1 -1
  204. package/dist/windfoil/svg/pathConverter.js +66 -50
  205. package/dist/windfoil/svg/pathConverter.js.map +1 -1
  206. package/dist/windfoil/svg/pathData.d.ts +9 -0
  207. package/dist/windfoil/svg/pathData.js +142 -109
  208. package/dist/windfoil/svg/pathData.js.map +1 -1
  209. package/dist/windfoil/svg/winding.js +34 -10
  210. package/dist/windfoil/svg/winding.js.map +1 -1
  211. package/dist/windfoil/trace/contours.d.ts +5 -0
  212. package/dist/windfoil/trace/contours.js +256 -62
  213. package/dist/windfoil/trace/contours.js.map +1 -1
  214. package/dist/windfoil/trace/fit.d.ts +3 -1
  215. package/dist/windfoil/trace/fit.js +915 -265
  216. package/dist/windfoil/trace/fit.js.map +1 -1
  217. package/dist/windfoil/trace/outline.js +55 -30
  218. package/dist/windfoil/trace/outline.js.map +1 -1
  219. package/dist/windfoil/trace/traceOutline.worker.d.ts +24 -0
  220. package/dist/windfoil/trace/traceWorker.d.ts +13 -0
  221. package/dist/windfoil/trace/traceWorker.js +192 -0
  222. package/dist/windfoil/trace/traceWorker.js.map +1 -0
  223. package/dist/windfoil/trace/types.d.ts +10 -0
  224. package/dist/windfoil/tracedOutlines.d.ts +2 -0
  225. package/dist/windfoil/tracedOutlines.js +393 -103
  226. package/dist/windfoil/tracedOutlines.js.map +1 -1
  227. package/package.json +48 -29
  228. package/skills/ultra-text/SKILL.md +9 -10
  229. package/skills/ultra-text/references/frameworks.md +46 -2
  230. package/skills/ultra-text/references/three-tsl.md +27 -25
  231. package/skills/ultra-text/references/vanilla-webgpu.md +5 -2
  232. package/dist/assets/cpuSdf.worker-xS57yQbP.js +0 -322
  233. package/dist/assets/cpuSdf.worker-xS57yQbP.js.map +0 -1
  234. package/dist/slug-vanilla.js.map +0 -1
  235. package/dist/text/geometry.js +0 -348
  236. package/dist/text/geometry.js.map +0 -1
  237. package/dist/vanilla.js.map +0 -1
@@ -1,6 +1,7 @@
1
1
  import { glyphClusters, isEmojiCandidate } from "./clusters.js";
2
- import { snapGlyph } from "../text/reflow.js";
3
- import { DEFAULT_IGNORE_SELECTOR, DEFAULT_TEXT_SELECTOR } from "./markup.js";
2
+ import { parseCssColor } from "./tone.js";
3
+ import { DEFAULT_IGNORE_SELECTOR, DEFAULT_TEXT_SELECTOR, isImmutableCapture, snapshotFlags } from "./markup.js";
4
+ import { snapGlyph } from "../text/snap.js";
4
5
  import { precedingCharacter, resolveTextTransform, transformClusters } from "./textTransform.js";
5
6
  // src/dom/snapshot.ts
6
7
  var DEPTH_ATTRIBUTE = "data-text-depth";
@@ -41,11 +42,12 @@ var INV_2_22 = 2 ** -22;
41
42
  var MAX_SHARED_FONT_CACHES = 256;
42
43
  var SINGLE_CHAR = Array.from({ length: 128 }, (_, i) => String.fromCharCode(i));
43
44
  var sameBox = (a, b) => !!b && a.left === b.left && a.top === b.top && a.width === b.width && a.height === b.height;
44
- var colorProbe = null;
45
45
  var sharedKerningContext;
46
46
  var sharedWidthsByFont = /* @__PURE__ */ new Map();
47
47
  var sharedAsciiWidthsByFont = /* @__PURE__ */ new Map();
48
+ var sharedPairWidthsByFont = /* @__PURE__ */ new Map();
48
49
  var cachedTextRuns = /* @__PURE__ */ new WeakMap();
50
+ var cachedBlockTemplates = /* @__PURE__ */ new WeakMap();
49
51
  var lastFontSetSize = -1;
50
52
  var TRANSPARENT_SRGBA = [
51
53
  0,
@@ -53,43 +55,90 @@ var TRANSPARENT_SRGBA = [
53
55
  0,
54
56
  0
55
57
  ];
56
- var parsedColors = /* @__PURE__ */ new Map([["transparent", TRANSPARENT_SRGBA], ["rgba(0, 0, 0, 0)", TRANSPARENT_SRGBA]]);
57
- function cssColorToSrgba(document, value, opacity) {
58
- if (opacity <= 0 || !value) return TRANSPARENT_SRGBA;
59
- let rgba = parsedColors.get(value);
60
- if (!rgba) {
61
- const functional = /rgba?\(([^)]+)\)/i.exec(value);
62
- if (functional) {
63
- const channels = functional[1].trim().split(/[\s,/]+/);
64
- const read = (i, max = 255) => {
65
- const v = channels[i];
66
- return v ? v.includes("%") ? parseFloat(v) / 100 : parseFloat(v) / max : max === 1 ? 1 : 0;
67
- };
68
- rgba = [
69
- read(0),
70
- read(1),
71
- read(2),
72
- read(3, 1)
73
- ];
74
- } else {
75
- colorProbe ??= document.createElement("canvas").getContext("2d", { willReadFrequently: true });
76
- if (!colorProbe) throw new Error("collectDomSnapshot: Canvas 2D is unavailable");
77
- colorProbe.fillStyle = "#000";
78
- colorProbe.fillStyle = value;
79
- colorProbe.clearRect(0, 0, 1, 1);
80
- colorProbe.fillRect(0, 0, 1, 1);
81
- const pixel = colorProbe.getImageData(0, 0, 1, 1).data;
82
- rgba = [
83
- pixel[0] / 255,
84
- pixel[1] / 255,
85
- pixel[2] / 255,
86
- pixel[3] / 255
87
- ];
58
+ var SMALL_CAPS_RE = /(?:^|\s)small-caps(?:\s|$)/;
59
+ var strippedStyleCache = /* @__PURE__ */ new Map();
60
+ function stripStyleInsets(value) {
61
+ const cached = strippedStyleCache.get(value);
62
+ if (cached !== void 0) return cached;
63
+ const len = value.length;
64
+ let out = "";
65
+ let lastKept = 0;
66
+ let i = 0;
67
+ let declStart = 0;
68
+ while (i < len) {
69
+ while (i < len && value.charCodeAt(i) <= 32) i++;
70
+ let matchLen = 0;
71
+ if (i < len) {
72
+ const c0 = value.charCodeAt(i) | 32;
73
+ if (c0 === 108 && i + 4 < len) {
74
+ if ((value.charCodeAt(i + 1) | 32) === 101 && (value.charCodeAt(i + 2) | 32) === 102 && (value.charCodeAt(i + 3) | 32) === 116) matchLen = 4;
75
+ } else if (c0 === 116 && i + 3 < len) {
76
+ if ((value.charCodeAt(i + 1) | 32) === 111 && (value.charCodeAt(i + 2) | 32) === 112) matchLen = 3;
77
+ } else if (c0 === 114 && i + 5 < len) {
78
+ if ((value.charCodeAt(i + 1) | 32) === 105 && (value.charCodeAt(i + 2) | 32) === 103 && (value.charCodeAt(i + 3) | 32) === 104 && (value.charCodeAt(i + 4) | 32) === 116) matchLen = 5;
79
+ } else if (c0 === 98 && i + 6 < len) {
80
+ if ((value.charCodeAt(i + 1) | 32) === 111 && (value.charCodeAt(i + 2) | 32) === 116 && (value.charCodeAt(i + 3) | 32) === 116 && (value.charCodeAt(i + 4) | 32) === 111 && (value.charCodeAt(i + 5) | 32) === 109) matchLen = 6;
81
+ } else if (c0 === 105 && i + 5 < len) {
82
+ if ((value.charCodeAt(i + 1) | 32) === 110 && (value.charCodeAt(i + 2) | 32) === 115 && (value.charCodeAt(i + 3) | 32) === 101 && (value.charCodeAt(i + 4) | 32) === 116) matchLen = 5;
83
+ }
84
+ }
85
+ let matched = false;
86
+ if (matchLen > 0) {
87
+ let j = i + matchLen;
88
+ while (j < len && value.charCodeAt(j) <= 32) j++;
89
+ if (j < len && value.charCodeAt(j) === 58) matched = true;
90
+ }
91
+ const semi = value.indexOf(";", i);
92
+ const nextDecl = semi >= 0 ? semi : len;
93
+ if (matched) {
94
+ if (declStart > lastKept) out += value.slice(lastKept, declStart);
95
+ lastKept = nextDecl;
88
96
  }
89
- if (parsedColors.size >= 1024) parsedColors.clear();
90
- parsedColors.set(value, rgba);
97
+ if (semi < 0) break;
98
+ declStart = semi;
99
+ i = semi + 1;
91
100
  }
92
- if (rgba[3] <= 0) return TRANSPARENT_SRGBA;
101
+ const result = lastKept === 0 ? value : lastKept < len ? out + value.slice(lastKept) : out;
102
+ if (strippedStyleCache.size >= 1024) strippedStyleCache.clear();
103
+ strippedStyleCache.set(value, result);
104
+ return result;
105
+ }
106
+ function hasNonShareableRule(rules) {
107
+ for (const r of rules) {
108
+ if ("selectorText" in r) {
109
+ if (/[:+~]|\[style\b/i.test(r.selectorText)) return true;
110
+ }
111
+ if ("cssRules" in r) {
112
+ if ("start" in r || hasNonShareableRule(r.cssRules)) return true;
113
+ } else if ("href" in r) return true;
114
+ }
115
+ return false;
116
+ }
117
+ function measureExpansionBoxes(share, bLeft, bTop, bBottom, bWidth, bHeight, font, probe) {
118
+ if (share.length <= (share.codePointAt(0) > 65535 ? 2 : 1)) return void 0;
119
+ const parts = Array.from(share);
120
+ if (probe) probe.font = font.canvasFont;
121
+ const advances = parts.map((part) => /^\p{M}/u.test(part) ? 0 : probe?.measureText(part).width ?? 1);
122
+ const total = advances.reduce((sum, advance) => sum + advance, 0);
123
+ let left = bLeft;
124
+ return parts.map((c, index) => {
125
+ const width = total > 0 ? bWidth * advances[index] / total : bWidth / parts.length;
126
+ const item = {
127
+ left,
128
+ top: bTop,
129
+ bottom: bBottom,
130
+ width,
131
+ height: bHeight,
132
+ c
133
+ };
134
+ left += width;
135
+ return item;
136
+ });
137
+ }
138
+ function cssColorToSrgba(document, value, opacity) {
139
+ if (opacity <= 0 || !value) return TRANSPARENT_SRGBA;
140
+ const rgba = parseCssColor(document, value, true);
141
+ if (!rgba || rgba[3] <= 0) return TRANSPARENT_SRGBA;
93
142
  return opacity === 1 ? rgba : [
94
143
  rgba[0],
95
144
  rgba[1],
@@ -100,7 +149,9 @@ function cssColorToSrgba(document, value, opacity) {
100
149
  var EMPTY_DECORATION_OWNERS = [];
101
150
  function canvasFont(style, bakeSize) {
102
151
  const rawStyle = style.fontStyle;
103
- return `${rawStyle === "italic" ? "italic " : rawStyle.startsWith("oblique") ? "oblique " : ""}${/(?:^|\s)small-caps(?:\s|$)/.test(style.fontVariant) ? "small-caps " : ""}${style.fontWeight || "400"} ${bakeSize}px ${style.fontFamily}`.trim();
152
+ const fontStyle = rawStyle === "italic" ? "italic " : rawStyle.startsWith("oblique") ? "oblique " : "";
153
+ const rawVariant = style.fontVariant;
154
+ return `${fontStyle}${rawVariant && rawVariant !== "normal" && SMALL_CAPS_RE.test(rawVariant) ? "small-caps " : ""}${style.fontWeight || "400"} ${bakeSize}px ${style.fontFamily}`.trim();
104
155
  }
105
156
  function fontMetrics(context, font, fontSize, cache) {
106
157
  let result = cache.get(font);
@@ -150,19 +201,20 @@ function layoutDescents(context, boxHeights, scales, bakeSize, cache) {
150
201
  return [result, scales.length === 1 ? scales[0] : scales[settled]];
151
202
  }
152
203
  function collectDomSnapshot(root, options = {}) {
153
- if (options.svg || options.textShaping === "browser" || options.layoutEngine === "pretext") return Promise.all([
204
+ if (options.svg || options.textShaping === "browser" || options.layoutEngine === "pretext" || options.outline === "css" || options.dropShadow === "css") return Promise.all([
154
205
  options.layoutEngine === "pretext" ? import("./pretextLayout.js") : void 0,
155
206
  options.textShaping === "browser" ? import("./browserShaping.js") : void 0,
156
- options.svg ? import("./svgCapture.js") : void 0
157
- ]).then(([pretext, shaping, svg]) => {
207
+ options.svg ? import("./svgCapture.js") : void 0,
208
+ options.outline === "css" || options.dropShadow === "css" ? import("./cssEffects.js") : void 0
209
+ ]).then(([pretext, shaping, svg, cssEffects]) => {
158
210
  if (svg && pretext) throw new RangeError("svg requires the Range layout engine");
159
211
  svg?.resolveSvgOptions(options.svg);
160
212
  shaping?.validateBrowserShaping(options);
161
- return collectDomSnapshotSync(root, options, pretext, shaping, svg);
213
+ return collectDomSnapshotSync(root, options, pretext, shaping, svg, cssEffects);
162
214
  });
163
215
  return collectDomSnapshotSync(root, options);
164
216
  }
165
- function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
217
+ function collectDomSnapshotSync(root, options, pretext, shaping, svg, cssEffects) {
166
218
  const document = root.ownerDocument;
167
219
  const view = document.defaultView;
168
220
  if (!view) throw new Error("collectDomSnapshot: the element is not attached to a browser document");
@@ -174,13 +226,18 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
174
226
  const pixelsPerUnit = options.pixelsPerUnit ?? 1;
175
227
  if (!Number.isFinite(pixelsPerUnit) || pixelsPerUnit <= 0) throw new RangeError("collectDomSnapshot: pixelsPerUnit must be a positive finite number");
176
228
  const invScale = 1 / pixelsPerUnit;
229
+ const wantCssShadow = options.dropShadow === "css";
230
+ const wantCssOutline = options.outline === "css";
231
+ let cssDropShadow;
232
+ let cssOutline;
177
233
  const rootRect = root.getBoundingClientRect();
178
- const { left: rootLeft, bottom: rootBottom } = rootRect;
234
+ const { left: rootLeft, top: rootTop, bottom: rootBottom } = rootRect;
179
235
  if (rootRect.width <= 0 || rootRect.height <= 0) throw new Error("collectDomSnapshot: the source element has no layout box");
180
236
  if (options.layoutEngine !== void 0 && !["range", "pretext"].includes(options.layoutEngine)) throw new RangeError("collectDomSnapshot: layoutEngine must be 'range' or 'pretext'");
181
237
  const glyphs = [];
182
238
  const blockLayouts = [];
183
239
  let afterSpace = true;
240
+ let hasAnyDecorations = false;
184
241
  const rects = [];
185
242
  const requests = /* @__PURE__ */ new Map();
186
243
  let lineCount = 0;
@@ -193,7 +250,9 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
193
250
  lastFontSetSize = fonts.size;
194
251
  sharedWidthsByFont = /* @__PURE__ */ new Map();
195
252
  sharedAsciiWidthsByFont = /* @__PURE__ */ new Map();
253
+ sharedPairWidthsByFont = /* @__PURE__ */ new Map();
196
254
  cachedTextRuns = /* @__PURE__ */ new WeakMap();
255
+ cachedBlockTemplates = /* @__PURE__ */ new WeakMap();
197
256
  }
198
257
  const getContextDescriptor = Object.getOwnPropertyDescriptor(view.HTMLCanvasElement.prototype, "getContext")?.value;
199
258
  const nativeCanvas = nativeBrowser && !(getContextDescriptor && "mock" in getContextDescriptor);
@@ -204,9 +263,12 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
204
263
  if (!shareChecked) {
205
264
  shareChecked = true;
206
265
  try {
207
- for (const s of root.getRootNode().styleSheets ?? []) for (const r of s.cssRules) if (/[:+~]/.test(r.cssText)) {
208
- share = false;
209
- return false;
266
+ for (const s of root.getRootNode().styleSheets ?? []) {
267
+ if (s.disabled) continue;
268
+ if (hasNonShareableRule(s.cssRules)) {
269
+ share = false;
270
+ return false;
271
+ }
210
272
  }
211
273
  } catch {
212
274
  share = false;
@@ -217,27 +279,68 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
217
279
  };
218
280
  const pathStyles = /* @__PURE__ */ new Map();
219
281
  const nodes = /* @__PURE__ */ new Map();
282
+ let rootRec;
283
+ let nextNodeKid = 1;
284
+ const attrFlagOf = (name) => name === "data-text-block" || name === "data-sdf-block" ? 1 : name === "data-text-ignore" || name === "data-sdf-ignore" ? 2 : name === DEPTH_ATTRIBUTE || name === LEGACY_DEPTH_ATTRIBUTE ? 4 : 0;
220
285
  const nodeOf = (el) => {
221
286
  let rec = nodes.get(el);
222
287
  if (!rec) {
223
288
  const parent = el === root ? null : el.parentElement;
224
- const u = parent ? nodeOf(parent) : null;
225
- const hasAttrs = !attrOnly || el.hasAttributes();
226
- let k = share && (el === root || u?.k !== void 0) ? `${u?.k ?? ""}>${el.localName}` : void 0;
227
- if (k && el !== root) for (const a of el.attributes) k += `\u0001${a.name}=${a.name === "style" ? a.value.replace(/(?:^|;)\s*(?:left|top|right|bottom|inset)\s*:[^;]*/gi, "") : a.value}`;
289
+ const u = parent ? parent === root && rootRec ? rootRec : nodeOf(parent) : null;
290
+ const attrs = el.attributes;
291
+ const attrCount = attrs.length;
292
+ const hasAttrs = !attrOnly || attrCount > 0;
293
+ const parentKid = u ? u.p ? u.p.kid : u.kid : 0;
294
+ let k = share && (el === root || u?.k !== void 0) ? `${parentKid}>${el.localName}` : void 0;
295
+ let attrFlags = 0;
296
+ if (attrCount > 0) {
297
+ const buildK = k !== void 0 && el !== root;
298
+ if (buildK && attrCount === 1) {
299
+ const a0 = attrs[0];
300
+ const n0 = a0.name;
301
+ attrFlags = attrFlagOf(n0);
302
+ const v0 = a0.value;
303
+ k = `${k}\u0001${n0}=${n0 === "style" && v0 ? strippedStyleCache.get(v0) ?? stripStyleInsets(v0) : v0}`;
304
+ } else if (buildK && attrCount === 2) {
305
+ const a0 = attrs[0];
306
+ const a1 = attrs[1];
307
+ const n0 = a0.name;
308
+ const n1 = a1.name;
309
+ attrFlags = attrFlagOf(n0) | attrFlagOf(n1);
310
+ const v0 = a0.value;
311
+ const v1 = a1.value;
312
+ const sv0 = n0 === "style" && v0 ? strippedStyleCache.get(v0) ?? stripStyleInsets(v0) : v0;
313
+ const sv1 = n1 === "style" && v1 ? strippedStyleCache.get(v1) ?? stripStyleInsets(v1) : v1;
314
+ k = `${k}\u0001${n0}=${sv0}\u0001${n1}=${sv1}`;
315
+ } else for (let i = 0; i < attrCount; i++) {
316
+ const a = attrs[i];
317
+ const name = a.name;
318
+ attrFlags |= attrFlagOf(name);
319
+ if (buildK) {
320
+ const value = a.value;
321
+ k = `${k}\u0001${name}=${name === "style" && value ? strippedStyleCache.get(value) ?? stripStyleInsets(value) : value}`;
322
+ }
323
+ }
324
+ }
228
325
  let p = k ? pathStyles.get(k) : void 0;
229
- if (p !== void 0 && !canShare()) p = void 0;
326
+ if (p !== void 0 && !canShare()) {
327
+ p = void 0;
328
+ k = void 0;
329
+ }
330
+ const kid = k && !p ? nextNodeKid++ : void 0;
230
331
  rec = {
231
332
  el,
232
333
  u,
233
- owner: hasAttrs && (defaultTextAttr ? el.hasAttribute("data-text-block") || el.hasAttribute("data-sdf-block") : el.matches(textSelector)) ? el : u?.owner ?? null,
234
- ig: (u?.ig ?? false) || hasAttrs && (defaultIgnoreAttr ? el.hasAttribute("data-text-ignore") || el.hasAttribute("data-sdf-ignore") : el.matches(ignoreSelector)),
235
- do: hasAttrs && (el.hasAttribute(DEPTH_ATTRIBUTE) || el.hasAttribute(LEGACY_DEPTH_ATTRIBUTE)) ? el : u?.do ?? null,
334
+ owner: hasAttrs && (defaultTextAttr ? (attrFlags & 1) !== 0 : el.matches(textSelector)) ? el : u?.owner ?? null,
335
+ ig: (u?.ig ?? false) || hasAttrs && (defaultIgnoreAttr ? (attrFlags & 2) !== 0 : el.matches(ignoreSelector)),
336
+ do: (attrFlags & 4) !== 0 ? el : u?.do ?? null,
236
337
  k,
338
+ kid,
237
339
  p
238
340
  };
239
341
  if (k && !p) pathStyles.set(k, rec);
240
342
  nodes.set(el, rec);
343
+ if (el === root) rootRec = rec;
241
344
  }
242
345
  return rec;
243
346
  };
@@ -259,11 +362,16 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
259
362
  return owner ? parsePx(owner.getAttribute(DEPTH_ATTRIBUTE) ?? owner.getAttribute(LEGACY_DEPTH_ATTRIBUTE), fallback) : fallback;
260
363
  };
261
364
  const isIgnored = (element) => nodeOf(element).ig;
262
- let shapeGroup = 0;
263
- const shapeBoxes = /* @__PURE__ */ new Map();
264
- const capturedSvgs = /* @__PURE__ */ new Set();
265
- const svgOptions = options.svg ? svg.resolveSvgOptions(options.svg) : null;
266
- const svgContext = svgOptions ? {
365
+ const readCssEffects = (style, fontSize, opacity) => {
366
+ if (!cssEffects) return;
367
+ if (wantCssShadow && !cssDropShadow) cssDropShadow = cssEffects.parseCssTextShadow(document, parseCssColor, style, fontSize, invScale, opacity);
368
+ if (wantCssOutline && !cssOutline) cssOutline = cssEffects.parseCssTextStroke(document, parseCssColor, style, fontSize, invScale, opacity);
369
+ };
370
+ if (wantCssShadow || wantCssOutline) {
371
+ const rootStyle = styleOf(root);
372
+ readCssEffects(rootStyle, parsePx(rootStyle.fontSize, 16), opacityOf(root));
373
+ }
374
+ const svgRunner = svg ? svg.createSvgRunner(root, options.svg, {
267
375
  style: styleOf,
268
376
  opacity: opacityOf,
269
377
  displayNone,
@@ -272,24 +380,28 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
272
380
  requests,
273
381
  rootLeft,
274
382
  rootBottom,
275
- invScale,
276
- options: svgOptions,
277
- budget: { pathData: svgOptions.maxPathData ?? 1e6 }
278
- } : null;
279
- const captureShape = (element, blockIndex, clip, sequence) => {
280
- if (!svgContext || !svg || !element.matches(svgOptions.selector ?? "svg") && !(svgOptions.images && element.localName === "img")) return false;
281
- const ancestorSvg = element.parentElement?.closest("svg");
282
- if (ancestorSvg && root.contains(ancestorSvg)) return false;
283
- capturedSvgs.add(element);
284
- const capture = svg.captureSvg(element, svgContext);
285
- if (capture) {
286
- shapeBoxes.set(shapeGroup, capture.box);
287
- svg.appendSvg(capture, glyphs, blockIndex, shapeGroup++, clip, depthOf(element, options.textDepth ?? 1), sequence);
288
- }
383
+ invScale
384
+ }, depthOf, options.textDepth ?? 1, glyphs, textSelector, rootRect, blockLayouts) : null;
385
+ const blocks = [...root.matches(textSelector) ? [root] : [], ...root.querySelectorAll(textSelector)];
386
+ let activeBlock = null;
387
+ const filterState = { skippedNested: false };
388
+ const consumeSkipped = (state) => {
389
+ if (!state.skippedNested) return false;
390
+ state.skippedNested = false;
289
391
  return true;
290
392
  };
291
- const blocks = [...root.matches(textSelector) ? [root] : [], ...root.querySelectorAll(textSelector)];
393
+ const blockSet = blocks.length > 1 ? new Set(blocks) : null;
394
+ const treeWalkerFn = document.createTreeWalker;
395
+ const useNativeWalk = !("mock" in treeWalkerFn) && Function.prototype.toString.call(treeWalkerFn).includes("[native");
396
+ const nestedBlockFilter = !useNativeWalk && blockSet ? (node) => {
397
+ if (node.nodeType === 1 && node !== activeBlock && blockSet.has(node)) {
398
+ filterState.skippedNested = true;
399
+ return 2;
400
+ }
401
+ return 1;
402
+ } : null;
292
403
  const layoutEngine = options.layoutEngine ?? "range";
404
+ const cacheRangeRuns = layoutEngine === "range" && nativeBrowser && !options.reshape && !shaping && !svg;
293
405
  if (options.rtlReflow && layoutEngine !== "range") throw new RangeError("collectDomSnapshot: rtlReflow requires the Range layout engine");
294
406
  let range;
295
407
  const appendBrowserRuns = shaping?.createBrowserCapture(document);
@@ -298,6 +410,13 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
298
410
  const measuresBaselines = "CanvasRenderingContext2D" in view;
299
411
  const deviceScale = view.devicePixelRatio > 0 ? view.devicePixelRatio : 1;
300
412
  const textRuns = [];
413
+ const hitRuns = [];
414
+ const pendingTemplates = [];
415
+ const EMPTY_GLYPHS = [];
416
+ const snapTmplPrefix = `${rootRect.height}|${rootLeft}|${deviceScale}|${invScale}|${bakeSize}|${!!options.cjkLineBreaking}|${!!options.rtlReflow}|${options.textBackend ?? "sdf"}`;
417
+ let trackBlockGrid = false;
418
+ let blockOffCss = false;
419
+ let blockOffDev = false;
301
420
  const boxHeights = /* @__PURE__ */ new Map();
302
421
  let offCssGrid = false;
303
422
  let offDeviceGrid = false;
@@ -306,10 +425,21 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
306
425
  const scale64Device = 64 * deviceScale;
307
426
  const offBox = (l, w, scale64) => offLayoutGrid(l, rootLeft, scale64, absRootLeft) || offLayoutGrid(l + w, rootLeft, scale64, absRootLeft);
308
427
  const trackLayoutGrid = (l, w) => {
309
- if (gridDone) return;
310
- if (!offCssGrid) offCssGrid = offBox(l, w, 64);
311
- if (deviceScale !== 1 && !offDeviceGrid) offDeviceGrid = offBox(l, w, scale64Device);
312
- if (offCssGrid && (deviceScale === 1 || offDeviceGrid)) gridDone = true;
428
+ if (trackBlockGrid && !blockOffCss || !gridDone && !offCssGrid) {
429
+ if (offBox(l, w, 64)) {
430
+ if (trackBlockGrid) blockOffCss = true;
431
+ if (!gridDone) offCssGrid = true;
432
+ }
433
+ }
434
+ if (deviceScale !== 1) {
435
+ if (trackBlockGrid && !blockOffDev || !gridDone && !offDeviceGrid) {
436
+ if (offBox(l, w, scale64Device)) {
437
+ if (trackBlockGrid) blockOffDev = true;
438
+ if (!gridDone) offDeviceGrid = true;
439
+ }
440
+ }
441
+ }
442
+ if (!gridDone && offCssGrid && (deviceScale === 1 || offDeviceGrid)) gridDone = true;
313
443
  };
314
444
  const layoutScales = () => [...deviceScale === 1 || offDeviceGrid ? [] : [deviceScale], ...offCssGrid ? [] : [1]];
315
445
  const measuresKerning = "OffscreenCanvas" in view;
@@ -369,24 +499,11 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
369
499
  const fontRequestKey = (font) => options.textBackend === "windfoil" && font.opticalSizing === "auto" ? `${font.key}|${font.size}` : font.key;
370
500
  const requestKey = (font, keys, character, asciiKeys) => {
371
501
  const code = asciiKeys && character.length === 1 ? character.charCodeAt(0) : -1;
372
- if (code >= 0 && code < 128) {
373
- let key = asciiKeys[code];
374
- if (key === void 0) {
375
- key = `${fontRequestKey(font)}\u0000${character}`;
376
- asciiKeys[code] = key;
377
- keys.set(character, key);
378
- requests.set(key, {
379
- key,
380
- character,
381
- font
382
- });
383
- }
384
- return key;
385
- }
386
- let key = keys.get(character);
502
+ let key = code >= 0 && code < 128 ? asciiKeys[code] : keys.get(character);
387
503
  if (key === void 0) {
388
504
  key = `${fontRequestKey(font)}\u0000${character}`;
389
- keys.set(character, key);
505
+ if (asciiKeys && code >= 0 && code < 128) asciiKeys[code] = key;
506
+ else keys.set(character, key);
390
507
  requests.set(key, {
391
508
  key,
392
509
  character,
@@ -395,25 +512,34 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
395
512
  }
396
513
  return key;
397
514
  };
515
+ const measureCanvasWidth = (cssFont, text) => {
516
+ const ctx = ensureKerningContext();
517
+ if (!ctx) return 0;
518
+ if (lastKerningFont !== cssFont) ctx.font = lastKerningFont = cssFont;
519
+ return ctx.measureText(text).width;
520
+ };
398
521
  const canvasWidth = (cssFont, widths, asciiWidths, text) => {
399
522
  const code = text.length === 1 ? text.charCodeAt(0) : -1;
400
523
  if (code >= 0 && code < 128) {
401
- let width = asciiWidths[code];
402
- if (width < 0) {
403
- const ctx = ensureKerningContext();
404
- if (ctx && lastKerningFont !== cssFont) ctx.font = lastKerningFont = cssFont;
405
- width = ctx?.measureText(text).width ?? 0;
406
- asciiWidths[code] = width;
407
- }
408
- return width;
524
+ const width = asciiWidths[code];
525
+ return width >= 0 ? width : asciiWidths[code] = measureCanvasWidth(cssFont, text);
409
526
  }
410
527
  let width = widths.get(text);
411
- if (width === void 0) {
412
- const ctx = ensureKerningContext();
413
- if (ctx && lastKerningFont !== cssFont) ctx.font = lastKerningFont = cssFont;
414
- width = ctx?.measureText(text).width ?? 0;
415
- widths.set(text, width);
528
+ if (width === void 0) widths.set(text, width = measureCanvasWidth(cssFont, text));
529
+ return width;
530
+ };
531
+ const canvasPairWidth = (cssFont, widths, pairWidths, first, second) => {
532
+ const c0 = first.length === 1 ? first.charCodeAt(0) : -1;
533
+ const c1 = second.length === 1 ? second.charCodeAt(0) : -1;
534
+ if (c0 >= 0 && c0 < 128 && c1 >= 0 && c1 < 128) {
535
+ const pairKey = c0 << 7 | c1;
536
+ let width = pairWidths.get(pairKey);
537
+ if (width === void 0) pairWidths.set(pairKey, width = measureCanvasWidth(cssFont, first + second));
538
+ return width;
416
539
  }
540
+ const text = first + second;
541
+ let width = widths.get(text);
542
+ if (width === void 0) widths.set(text, width = measureCanvasWidth(cssFont, text));
417
543
  return width;
418
544
  };
419
545
  const resolveFont = (style) => {
@@ -430,17 +556,7 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
430
556
  const featureSettings = or(style.fontFeatureSettings);
431
557
  const variationSettings = or(style.fontVariationSettings);
432
558
  const opticalSizing = or(style.fontOpticalSizing, "auto");
433
- const key = [
434
- family,
435
- weight,
436
- fontStyle,
437
- stretch,
438
- variant,
439
- kerning,
440
- featureSettings,
441
- variationSettings,
442
- opticalSizing
443
- ].join("|");
559
+ const key = `${family}|${weight}|${fontStyle}|${stretch}|${variant}|${kerning}|${featureSettings}|${variationSettings}|${opticalSizing}`;
444
560
  const size = parsePx(style.fontSize, 16);
445
561
  const cacheKey = `${key}\u0000${size}`;
446
562
  entry = fontEntries.get(cacheKey);
@@ -469,16 +585,20 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
469
585
  const layoutFont = font.canvasFont.replace(`${bakeSize}px`, `${size}px`);
470
586
  let widths = nativeBrowser ? sharedWidthsByFont.get(layoutFont) : void 0;
471
587
  let asciiWidths = nativeBrowser ? sharedAsciiWidthsByFont.get(layoutFont) : void 0;
472
- if (!widths || !asciiWidths) {
588
+ let pairWidths = nativeBrowser ? sharedPairWidthsByFont.get(layoutFont) : void 0;
589
+ if (!widths || !asciiWidths || !pairWidths) {
473
590
  if (nativeBrowser && sharedWidthsByFont.size >= MAX_SHARED_FONT_CACHES) {
474
591
  sharedWidthsByFont.clear();
475
592
  sharedAsciiWidthsByFont.clear();
593
+ sharedPairWidthsByFont.clear();
476
594
  }
477
595
  widths ??= /* @__PURE__ */ new Map();
478
596
  asciiWidths ??= (/* @__PURE__ */ new Float64Array(128)).fill(-1);
597
+ pairWidths ??= /* @__PURE__ */ new Map();
479
598
  if (nativeBrowser) {
480
599
  sharedWidthsByFont.set(layoutFont, widths);
481
600
  sharedAsciiWidthsByFont.set(layoutFont, asciiWidths);
601
+ sharedPairWidthsByFont.set(layoutFont, pairWidths);
482
602
  }
483
603
  }
484
604
  entry = [
@@ -488,7 +608,8 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
488
608
  widths,
489
609
  measuresKerning ? canvasWidth(layoutFont, widths, asciiWidths, " ") : 0,
490
610
  asciiKeys,
491
- asciiWidths
611
+ asciiWidths,
612
+ pairWidths
492
613
  ];
493
614
  fontEntries.set(cacheKey, entry);
494
615
  }
@@ -500,12 +621,15 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
500
621
  if (isHidden(style)) return null;
501
622
  const opacity = opacityOf(parent);
502
623
  if (opacity <= 0) return null;
503
- const [font, keys, layoutFont, widths, space, asciiKeys, asciiWidths] = resolveFont(style);
624
+ const [font, keys, layoutFont, widths, space, asciiKeys, asciiWidths, pairWidths] = resolveFont(style);
625
+ if (wantCssShadow && !cssDropShadow || wantCssOutline && !cssOutline) readCssEffects(style, font.size, opacity);
504
626
  const spacing = parsePx(style.letterSpacing, 0, font.size);
505
627
  const wordSpacing = parsePx(style.wordSpacing, 0, font.size);
506
628
  const whiteSpace = style.whiteSpace;
629
+ const decorations = readDecorations(parent, layoutFont, font.size, opacity);
630
+ if (decorations.length > 0) hasAnyDecorations = true;
507
631
  return {
508
- decorations: readDecorations(parent, layoutFont, font.size, opacity),
632
+ decorations,
509
633
  font,
510
634
  keys,
511
635
  asciiKeys,
@@ -513,44 +637,25 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
513
637
  layoutFont,
514
638
  widths,
515
639
  asciiWidths,
640
+ pairWidths,
516
641
  letterSpacing: spacing,
517
642
  wordSpacing,
518
643
  space: space && (space + spacing + wordSpacing) * invScale,
519
644
  keepsSpaces: whiteSpace !== "normal" && /pre(?!-l)|bre/.test(whiteSpace),
520
645
  color: cssColorToSrgba(document, style.color, opacity),
521
646
  z: depthOf(parent, options.textDepth ?? 1),
522
- transform: resolveTextTransform(style.textTransform, parent)
647
+ transform: resolveTextTransform(style.textTransform, parent),
648
+ runKey: `${layoutFont}|${spacing}|${wordSpacing}`
523
649
  };
524
650
  };
525
651
  const transformSeed = (node, transform) => transform.caseMap === "capitalize" ? precedingCharacter(node, styleOf) : void 0;
526
652
  const expansionBoxes = (share, bLeft, bTop, bBottom, bWidth, bHeight, font) => {
527
- if (share.length <= (share.codePointAt(0) > 65535 ? 2 : 1)) return void 0;
528
- const parts = Array.from(share);
529
- const probe = ensureFontProbe();
530
- if (probe) {
531
- probe.font = font.canvasFont;
532
- if (probe === kerningContext) lastKerningFont = "";
533
- }
534
- const advances = parts.map((part) => /^\p{M}/u.test(part) ? 0 : probe?.measureText(part).width ?? 1);
535
- const total = advances.reduce((sum, advance) => sum + advance, 0);
536
- let left = bLeft;
537
- return parts.map((c, index) => {
538
- const width = total > 0 ? bWidth * advances[index] / total : bWidth / parts.length;
539
- const item = {
540
- left,
541
- top: bTop,
542
- bottom: bBottom,
543
- width,
544
- height: bHeight,
545
- c
546
- };
547
- left += width;
548
- return item;
549
- });
653
+ const probe = share.length > 1 ? ensureFontProbe() : null;
654
+ if (probe && probe === kerningContext) lastKerningFont = "";
655
+ return measureExpansionBoxes(share, bLeft, bTop, bBottom, bWidth, bHeight, font, probe);
550
656
  };
551
657
  const paragraphOf = (el, rec, block) => el === block || !isInlineBox(el, rec) ? el : rec.u?.owner === block ? rec.u.paragraph ??= paragraphOf(rec.u.el, rec.u, block) : block;
552
- const resolveParent = (parent) => {
553
- const rec = nodeOf(parent);
658
+ const resolveParent = (parent, rec = nodeOf(parent)) => {
554
659
  if (rec.inline === void 0) {
555
660
  if (rec.p) {
556
661
  if (rec.p.inline === void 0) resolveParent(rec.p.el);
@@ -566,6 +671,29 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
566
671
  const paintLines = [];
567
672
  const lineTops = [];
568
673
  const sequences = /* @__PURE__ */ new Map();
674
+ const blockStyleOf = (el, rec = nodeOf(el)) => {
675
+ if (rec.blk) return rec.blk;
676
+ if (rec.p) return rec.blk = blockStyleOf(rec.p.el, rec.p);
677
+ const blockStyle = styleOf(el, rec);
678
+ const overflow = blockStyle.overflow;
679
+ const rtl = blockStyle.direction === "rtl";
680
+ const align = physicalAlign(blockStyle.textAlign, rtl);
681
+ const lastValue = blockStyle.textAlignLast;
682
+ const lastAlign = physicalAlign(lastValue && lastValue !== "auto" ? lastValue : align === "justify" ? "" : align, rtl);
683
+ return rec.blk = {
684
+ overflowX: blockStyle.overflowX || overflow || "visible",
685
+ overflowY: blockStyle.overflowY || overflow || "visible",
686
+ insetLeft: inset(blockStyle, "Left"),
687
+ insetRight: inset(blockStyle, "Right"),
688
+ insetTop: inset(blockStyle, "Top"),
689
+ textIndent: blockStyle.textIndent,
690
+ rtl,
691
+ align,
692
+ lastAlign,
693
+ justified: align === "justify" || lastAlign === "justify",
694
+ lineHeightRaw: blockStyle.lineHeight
695
+ };
696
+ };
569
697
  const toRect = (b) => [
570
698
  (b.left - rootLeft) * invScale,
571
699
  (rootBottom - b.bottom) * invScale,
@@ -575,23 +703,104 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
575
703
  for (let blockIndex = 0; blockIndex < blocks.length; blockIndex++) {
576
704
  const block = blocks[blockIndex];
577
705
  blockLayouts[blockIndex] = EMPTY_BLOCK;
578
- if (isIgnored(block) || displayNone(block)) continue;
579
- const blockStyle = styleOf(block);
580
- const blockRect = block.getBoundingClientRect();
706
+ const blockRec = nodeOf(block);
707
+ if (blockRec.ig || displayNone(block, blockRec)) continue;
708
+ const blockRect = block === root ? rootRect : block.getBoundingClientRect();
581
709
  if (blockRect.width <= 0 || blockRect.height <= 0) continue;
582
- const overflow = blockStyle.overflow;
583
- const overflowX = blockStyle.overflowX || overflow || "visible";
584
- const overflowY = blockStyle.overflowY || overflow || "visible";
585
- const insetLeft = inset(blockStyle, "Left");
586
- const insetRight = inset(blockStyle, "Right");
587
- const rtl = blockStyle.direction === "rtl";
588
- const align = physicalAlign(blockStyle.textAlign, rtl);
589
- const lastValue = blockStyle.textAlignLast;
590
- const lastAlign = physicalAlign(lastValue && lastValue !== "auto" ? lastValue : align === "justify" ? "" : align, rtl);
591
- const justified = align === "justify" || lastAlign === "justify";
592
- const lineHeightRaw = blockStyle.lineHeight;
710
+ const relLeft = blockRect.left - rootLeft;
711
+ const relTop = blockRect.top - rootTop;
712
+ const relWidth = blockRect.width;
713
+ const relHeight = blockRect.height;
714
+ const blockStyle = blockStyleOf(block, blockRec);
715
+ const { overflowX, overflowY, insetLeft, insetRight, insetTop, textIndent, rtl, align, lastAlign, justified, lineHeightRaw } = blockStyle;
716
+ const blockStart = glyphs.length;
717
+ const lineCountBefore = lineCount;
718
+ let tmplReady = false;
719
+ let templateTextNode = null;
720
+ let templateText = "";
721
+ let tmplScrollLeft = 0;
722
+ let tmplScrollTop = 0;
723
+ let tmplInlineTk = "";
724
+ let tmplBlkTk = "";
725
+ let templateBoxHeight = 0;
726
+ trackBlockGrid = false;
727
+ blockOffCss = false;
728
+ blockOffDev = false;
729
+ if (cacheRangeRuns && !options.pixelSnap && !block.firstElementChild && block.firstChild !== null && block.firstChild === block.lastChild && block.firstChild.nodeType === 3) {
730
+ const parentRec = resolveParent(block, blockRec);
731
+ const inline = parentRec.inline;
732
+ if (inline && parentRec.owner === block && !inline.transform && inline.decorations.length === 0) {
733
+ const templateFont = inline.font;
734
+ templateTextNode = block.firstChild;
735
+ templateText = templateTextNode.data;
736
+ const c = inline.color;
737
+ tmplInlineTk = inline.tk ?? (inline.tk = `${inline.layoutFont}|${templateFont.key}|${inline.letterSpacing}|${inline.wordSpacing}|${inline.z}|${inline.keepsSpaces}|${c[0]},${c[1]},${c[2]},${c[3]}`);
738
+ tmplBlkTk = blockStyle.tk ?? (blockStyle.tk = `${overflowX}|${overflowY}|${insetLeft}|${insetRight}|${insetTop}|${textIndent}|${rtl}|${align}|${lastAlign}|${lineHeightRaw}`);
739
+ tmplScrollLeft = block.scrollLeft;
740
+ tmplScrollTop = block.scrollTop;
741
+ const tmpl = cachedBlockTemplates.get(block);
742
+ if (tmpl?.n === templateTextNode && tmpl.s === templateText && tmpl.bi === blockIndex && tmpl.sl === tmplScrollLeft && tmpl.st === tmplScrollTop && tmpl.it === tmplInlineTk && tmpl.bt === tmplBlkTk && tmpl.p === snapTmplPrefix && tmpl.r.left === relLeft && tmpl.r.top === relTop && tmpl.r.width === relWidth && tmpl.r.height === relHeight) {
743
+ const immutableHit = isImmutableCapture();
744
+ const tGlyphs = tmpl.g;
745
+ if (immutableHit) for (let i = 0, len = tGlyphs.length; i < len; i++) glyphs.push(tGlyphs[i]);
746
+ else {
747
+ const hitClip = [
748
+ tmpl.c[0],
749
+ tmpl.c[1],
750
+ tmpl.c[2],
751
+ tmpl.c[3]
752
+ ];
753
+ for (let i = 0, len = tGlyphs.length; i < len; i++) glyphs.push({
754
+ ...tGlyphs[i],
755
+ clip: hitClip
756
+ });
757
+ }
758
+ const tReq = tmpl.req;
759
+ for (let i = 0, len = tReq.length; i < len; i++) {
760
+ const req = tReq[i];
761
+ if (!requests.has(req.key)) requests.set(req.key, req);
762
+ }
763
+ if (measuresBaselines) {
764
+ if (tmpl.oc) offCssGrid = true;
765
+ if (tmpl.od) offDeviceGrid = true;
766
+ if (offCssGrid && (deviceScale === 1 || offDeviceGrid)) gridDone = true;
767
+ if (tmpl.bh > 0) {
768
+ const prevHitRun = hitRuns[hitRuns.length - 1];
769
+ if (prevHitRun?.[0] === templateFont && prevHitRun[2] === blockStart && prevHitRun[3] === tmpl.bo) prevHitRun[2] = glyphs.length;
770
+ else hitRuns.push([
771
+ templateFont,
772
+ blockStart,
773
+ glyphs.length,
774
+ tmpl.bo
775
+ ]);
776
+ if (!boxHeights.has(templateFont)) boxHeights.set(templateFont, tmpl.bh);
777
+ }
778
+ }
779
+ lineCount += tmpl.l;
780
+ if (tGlyphs.length > 0) blockLayouts[blockIndex] = immutableHit ? tmpl.bl : {
781
+ ...tmpl.bl,
782
+ clip: toRect(blockRect)
783
+ };
784
+ afterSpace = true;
785
+ continue;
786
+ }
787
+ tmplReady = true;
788
+ trackBlockGrid = measuresBaselines;
789
+ }
790
+ }
791
+ const relBlockRect = {
792
+ left: relLeft,
793
+ top: relTop,
794
+ width: relWidth,
795
+ height: relHeight
796
+ };
593
797
  const clip = toRect(blockRect);
594
- const layoutClip = [...clip];
798
+ const layoutClip = [
799
+ clip[0],
800
+ clip[1],
801
+ clip[2],
802
+ clip[3]
803
+ ];
595
804
  let minLeft = blockRect.left;
596
805
  let maxRight = blockRect.right;
597
806
  let minTop = blockRect.top;
@@ -603,8 +812,6 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
603
812
  if (bottom > maxBottom) maxBottom = bottom;
604
813
  };
605
814
  const includeTextBoxObj = (box) => includeTextBox(box.left, box.top, box.bottom, box.width);
606
- const blockStart = glyphs.length;
607
- const lineCountBefore = lineCount;
608
815
  let blockLeft = clip[0] + insetLeft * invScale;
609
816
  let blockWidth = clip[2] - clip[0] - (insetLeft + insetRight) * invScale;
610
817
  if (appendBrowserRuns) {
@@ -625,8 +832,8 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
625
832
  requests,
626
833
  lineKeys,
627
834
  lineSequences: /* @__PURE__ */ new Map(),
628
- ...svg ? { svg: (element, sequence) => {
629
- captureShape(element, blockIndex, clip, sequence);
835
+ ...svgRunner ? { svg: (element, sequence) => {
836
+ svgRunner.capture(element, blockIndex, clip, sequence);
630
837
  } } : {},
631
838
  box: (font, box) => {
632
839
  includeTextBoxObj(box);
@@ -662,7 +869,11 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
662
869
  sequences.set(lineKey, lastSeqNext);
663
870
  return seq;
664
871
  };
665
- const walker = block.firstElementChild ? document.createTreeWalker(block, 5) : null;
872
+ const hasElementChild = block.firstElementChild !== null;
873
+ activeBlock = block;
874
+ filterState.skippedNested = false;
875
+ const walker = !useNativeWalk && hasElementChild ? document.createTreeWalker(block, 5, nestedBlockFilter) : null;
876
+ const blockRunKey = cacheRangeRuns ? `${blockRect.width}|${block.scrollLeft}|${block.scrollTop}|${insetLeft}|${insetRight}|${insetTop}|${textIndent}|${rtl}|${align}|${lastAlign}|${lineHeightRaw}` : "";
666
877
  let markAnchorLineKey = 0;
667
878
  let hasMarkAnchor = false;
668
879
  let previousCharacter = "";
@@ -676,298 +887,428 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
676
887
  let blockSynced = true;
677
888
  let nodeIndex = 0;
678
889
  let node = walker ? walker.nextNode() : block.firstChild;
679
- for (; node; node = walker ? walker.nextNode() : node.nextSibling) {
680
- nodeIndex++;
681
- if (node.nodeType !== 3) {
682
- if (!walker) continue;
683
- const element = node;
684
- const shapeStart = glyphs.length;
685
- if (svg && nodeOf(element).owner === block && captureShape(element, blockIndex, clip, (glyphs[glyphs.length - 1]?.sequence ?? -1) + 1)) {
686
- const last = glyphs[glyphs.length - 1];
687
- if (last?.shapeGroup !== void 0) {
688
- const sequence = nextSequence(hasMarkAnchor ? markAnchorLineKey : Math.round(element.getBoundingClientRect().top * 4));
689
- for (let i = glyphs.length - 1; i >= 0 && glyphs[i].shapeGroup === last.shapeGroup; i--) glyphs[i].sequence = sequence;
690
- if (gap && justified && shapeStart < glyphs.length) glyphs[shapeStart].gapBefore = gap;
691
- }
692
- gap = 0;
693
- afterSpace = true;
694
- hasMarkAnchor = false;
695
- previousCharacter = "";
696
- }
697
- forced ||= element.tagName === "BR" && !displayNone(element);
698
- if (forced || options.cjkLineBreaking && !isInlineBox(element)) previousCharacter = "";
699
- continue;
700
- }
701
- const textNode = node;
702
- const parent = textNode.parentElement;
703
- if (svg && parent?.closest("svg") && !parent.closest("foreignObject")) continue;
704
- const record = parent ? resolveParent(parent) : null;
705
- if (!record?.inline || record.owner !== block) {
890
+ while (node) {
891
+ if (walker && consumeSkipped(filterState)) {
706
892
  hasMarkAnchor = false;
707
893
  previousCharacter = "";
708
- continue;
709
- }
710
- const { font, keys, asciiKeys, fontSize, layoutFont, widths, asciiWidths, letterSpacing, wordSpacing, space, keepsSpaces, color, z, decorations, transform } = record.inline;
711
- let utf16Offset = 0;
712
- let textData = textNode.data;
713
- let shown = transform ? transformClusters(textData, transform, transformSeed(textNode, transform)) : void 0;
714
- if (options.reshape) {
715
- const input = shown ? shown.join("") : textData;
716
- const reshaped = options.reshape(input);
717
- if (reshapeBoundaries(input) !== reshapeBoundaries(reshaped)) throw new RangeError("collectDomSnapshot: Range reshaping must preserve code point boundaries and whitespace");
718
- let end = 0;
719
- if (shown) shown = shown.map((share) => reshaped.slice(end, end += share.length));
720
- else textData = reshaped;
721
894
  }
722
- const emojiText = isEmojiCandidate(textData);
723
- const runStart = glyphs.length;
724
- let boxHeight = 0;
725
- let clusterIndex = 0;
726
- let hasKernPrevious = false;
727
- let kernPrevChar = "";
728
- let kernPrevLeft = 0;
729
- let kernPrevWidth = -1;
730
- let kernPrevCarry = 0;
731
- let hit;
732
- let canSync = false;
733
- let synced = false;
734
- if (nativeBrowser && !shown && !options.reshape && !options.svg) {
735
- const runKey = `${nodeIndex}|${blockRect.width}|${textData}|${layoutFont}|${letterSpacing}|${wordSpacing}`;
736
- hit = cachedTextRuns.get(textNode);
737
- if (hit?.[0] === runKey && sameBox(blockRect, hit[2])) {
738
- canSync = true;
739
- synced = blockSynced;
895
+ let nextNode = null;
896
+ const nType = node.nodeType;
897
+ if (nType === 1) {
898
+ const element = node;
899
+ if (!walker && blockSet?.has(element)) {
900
+ hasMarkAnchor = false;
901
+ previousCharacter = "";
740
902
  } else {
741
- blockSynced = false;
742
- cachedTextRuns.set(textNode, hit = [
743
- runKey,
744
- new Float64Array(textData.length * 5),
745
- void 0
746
- ]);
747
- }
748
- }
749
- const rects = hit?.[1];
750
- const clusters = glyphClusters(textData);
751
- const rawString = typeof clusters === "string";
752
- const clusterArr = rawString ? null : clusters;
753
- const totalItems = rawString ? textData.length : clusterArr.length;
754
- let pos = 0;
755
- let ci = -1;
756
- while (pos < totalItems) {
757
- ci++;
758
- if (rawString && !shown) {
759
- if (textData.charCodeAt(pos) === 32) {
760
- if (!gap || keepsSpaces) gap += space;
903
+ nodeIndex++;
904
+ const shapeStart = glyphs.length;
905
+ if (svgRunner && nodeOf(element).owner === block && svgRunner.capture(element, blockIndex, clip, (glyphs[glyphs.length - 1]?.sequence ?? -1) + 1)) {
906
+ const last = glyphs[glyphs.length - 1];
907
+ if (last?.shapeGroup !== void 0) {
908
+ const sequence = nextSequence(hasMarkAnchor ? markAnchorLineKey : Math.round(element.getBoundingClientRect().top * 4));
909
+ for (let i = glyphs.length - 1; i >= 0 && glyphs[i].shapeGroup === last.shapeGroup; i--) glyphs[i].sequence = sequence;
910
+ if (gap && justified && shapeStart < glyphs.length) glyphs[shapeStart].gapBefore = gap;
911
+ }
912
+ gap = 0;
761
913
  afterSpace = true;
762
- hasMarkAnchor = hasKernPrevious = false;
914
+ hasMarkAnchor = false;
763
915
  previousCharacter = "";
764
- pos++;
765
- utf16Offset++;
766
- continue;
767
916
  }
917
+ forced ||= element.tagName === "BR" && !displayNone(element);
918
+ if (forced || options.cjkLineBreaking && !isInlineBox(element)) previousCharacter = "";
919
+ if (!walker) nextNode = element.firstChild;
768
920
  }
769
- let cluster;
770
- let step;
771
- if (rawString) {
772
- const c0 = textData.charCodeAt(pos);
773
- if (c0 >= 55296 && c0 <= 56319 && pos + 1 < totalItems && textData.charCodeAt(pos + 1) >= 56320 && textData.charCodeAt(pos + 1) <= 57343) {
774
- step = 2;
775
- cluster = textData.slice(pos, pos + 2);
921
+ } else if (nType === 3) {
922
+ nodeIndex++;
923
+ const textNode = node;
924
+ const parent = textNode.parentElement;
925
+ if (!(svg && parent?.closest("svg") && !parent.closest("foreignObject"))) {
926
+ const record = parent ? resolveParent(parent) : null;
927
+ if (!record?.inline || record.owner !== block) {
928
+ hasMarkAnchor = false;
929
+ previousCharacter = "";
776
930
  } else {
777
- step = 1;
778
- cluster = c0 < 128 ? SINGLE_CHAR[c0] : textData[pos];
779
- }
780
- } else {
781
- step = 1;
782
- cluster = clusterArr[pos];
783
- }
784
- pos += step;
785
- const share = shown ? shown[clusterIndex++] : cluster;
786
- const nextOffset = utf16Offset + cluster.length;
787
- if (share === " " || share.length === 1 && share.charCodeAt(0) >= 9 && /^\s$/u.test(share)) {
788
- if (share === " " || !/[\u2007\u202f\ufeff]/.test(share)) {
789
- if (!gap || keepsSpaces) gap += space;
790
- if (share !== "\xA0") afterSpace = true;
791
- }
792
- hasMarkAnchor = hasKernPrevious = false;
793
- previousCharacter = "";
794
- utf16Offset = nextOffset;
795
- continue;
796
- }
797
- if (!share) {
798
- hasKernPrevious = false;
799
- utf16Offset = nextOffset;
800
- continue;
801
- }
802
- let bLeft;
803
- let bTop;
804
- let bBottom;
805
- let bWidth;
806
- let bHeight;
807
- const boxOff = ci * 5;
808
- if (rects && synced) {
809
- bLeft = rects[boxOff];
810
- bTop = rects[boxOff + 1];
811
- bBottom = rects[boxOff + 2];
812
- bWidth = rects[boxOff + 3];
813
- bHeight = rects[boxOff + 4];
814
- } else {
815
- range.setEnd(textNode, nextOffset);
816
- range.setStart(textNode, utf16Offset);
817
- const d = range.getBoundingClientRect();
818
- bLeft = d.left;
819
- bTop = d.top;
820
- bBottom = d.bottom;
821
- bWidth = d.width;
822
- bHeight = d.height;
823
- if (rects) {
824
- if (canSync && rects[boxOff] === bLeft && rects[boxOff + 1] === bTop && rects[boxOff + 3] === bWidth && rects[boxOff + 4] === bHeight) synced = true;
825
- else {
826
- rects[boxOff] = bLeft;
827
- rects[boxOff + 1] = bTop;
828
- rects[boxOff + 2] = bBottom;
829
- rects[boxOff + 3] = bWidth;
830
- rects[boxOff + 4] = bHeight;
931
+ const { font, keys, asciiKeys, fontSize, layoutFont, widths, asciiWidths, pairWidths, letterSpacing, space, keepsSpaces, color, z, decorations, transform, runKey } = record.inline;
932
+ let utf16Offset = 0;
933
+ let textData = textNode.data;
934
+ let shown = transform ? transformClusters(textData, transform, transformSeed(textNode, transform)) : void 0;
935
+ if (options.reshape) {
936
+ const input = shown ? shown.join("") : textData;
937
+ const reshaped = options.reshape(input);
938
+ if (reshapeBoundaries(input) !== reshapeBoundaries(reshaped)) throw new RangeError("collectDomSnapshot: Range reshaping must preserve code point boundaries and whitespace");
939
+ let end = 0;
940
+ if (shown) shown = shown.map((share) => reshaped.slice(end, end += share.length));
941
+ else textData = reshaped;
831
942
  }
832
- }
833
- }
834
- utf16Offset = nextOffset;
835
- if (measuresBaselines) trackLayoutGrid(bLeft, bWidth);
836
- const parts = share === cluster ? void 0 : expansionBoxes(share, bLeft, bTop, bBottom, bWidth, bHeight, font);
837
- const partLen = parts ? parts.length : 1;
838
- for (let part = 0; part < partLen; part++) {
839
- let pLeft = bLeft;
840
- let pTop = bTop;
841
- let pBottom = bBottom;
842
- let pWidth = bWidth;
843
- let pHeight = bHeight;
844
- let character = share;
845
- if (parts) {
846
- const box = parts[part];
847
- pLeft = box.left;
848
- pTop = box.top;
849
- pBottom = box.bottom;
850
- pWidth = box.width;
851
- pHeight = box.height;
852
- character = box.c;
853
- }
854
- if (pWidth <= 0 || pHeight <= 0) {
855
- const previous = glyphs[glyphs.length - 1];
856
- hasKernPrevious = false;
857
- if (!hasMarkAnchor || !previous || !/^\p{M}/u.test(character)) continue;
858
- const key = requestKey(font, keys, character, asciiKeys);
859
- const sequence = nextSequence(markAnchorLineKey);
860
- if (options.pixelSnap) paintLines[glyphs.length] = paintLines[glyphs.length - 1];
861
- glyphs.push({
862
- glyphKey: key,
863
- fontSize,
864
- originX: previous.originX + previous.advance,
865
- lineBottom: previous.lineBottom,
866
- advance: 0,
867
- ...options.rtlReflow ? { decorationWidth: 0 } : {},
868
- block: blockIndex,
869
- breakBefore: "none",
870
- clip,
871
- color,
872
- sequence,
873
- z
874
- });
875
- continue;
876
- }
877
- includeTextBox(pLeft, pTop, pBottom, pWidth);
878
- const key = requestKey(font, keys, character, asciiKeys);
879
- const previous = glyphs[glyphs.length - 1];
880
- const sameBlock = previous?.block === blockIndex;
881
- const emoji = emojiText && isEmojiCandidate(character);
882
- const sharesLine = sameBlock && hasPrevBounds && Math.min(pBottom, prevBottom) - Math.max(pTop, prevTop) > Math.min(pHeight, prevHeight) * .5;
883
- const sameEmojiLine = sharesLine && (emoji || previousEmoji);
884
- const lineKey = sameEmojiLine ? markAnchorLineKey : Math.round(pTop * 4);
885
- const sequence = nextSequence(lineKey);
886
- const lineBottom = sameEmojiLine ? previous.lineBottom : (rootBottom - pBottom) * invScale;
887
- const lineChanged = sameBlock && previous.lineBottom !== lineBottom;
888
- let kernShift = 0;
889
- let kernCarry = 0;
890
- let charWidth = -1;
891
- if (hasKernPrevious && measuresKerning && !parts && !emoji && !lineChanged) {
892
- const firstWidth = kernPrevWidth >= 0 ? kernPrevWidth : canvasWidth(layoutFont, widths, asciiWidths, kernPrevChar);
893
- const shown = pLeft - kernPrevLeft - letterSpacing - firstWidth - kernPrevCarry;
894
- if (Math.abs(shown) > (nativeBrowser ? .02 : .0025)) {
895
- charWidth = canvasWidth(layoutFont, widths, asciiWidths, character);
896
- const pair = canvasWidth(layoutFont, widths, asciiWidths, kernPrevChar + character) - firstWidth - charWidth;
897
- if (Math.abs(pair) > .01 && Math.abs(shown - pair / 2) <= Math.min(.25, Math.abs(pair) / 4)) {
898
- kernCarry = pair - shown;
899
- kernShift = kernCarry;
943
+ const runStart = glyphs.length;
944
+ let boxHeight = 0;
945
+ let clusterIndex = 0;
946
+ let hasKernPrevious = false;
947
+ let kernPrevChar = "";
948
+ let kernPrevCode = -1;
949
+ let kernPrevLeft = 0;
950
+ let kernPrevWidth = -1;
951
+ let kernPrevCarry = 0;
952
+ let hit;
953
+ let canSync = false;
954
+ let synced = false;
955
+ let syncSource;
956
+ let syncDelta = 0;
957
+ let prevRects;
958
+ let prevDelta = 0;
959
+ let suffixStart = Infinity;
960
+ let emojiText;
961
+ let clusters;
962
+ let rawString;
963
+ if (cacheRangeRuns && !shown) {
964
+ const styleKey = `${nodeIndex}|${blockRunKey}|${runKey}`;
965
+ const prevHit = cachedTextRuns.get(textNode);
966
+ if (prevHit?.styleKey === styleKey && prevHit.text === textData && sameBox(relBlockRect, prevHit.blockRect)) {
967
+ hit = prevHit;
968
+ emojiText = prevHit.emojiText;
969
+ clusters = prevHit.clusters;
970
+ rawString = prevHit.rawString;
971
+ canSync = true;
972
+ synced = blockSynced;
973
+ syncSource = prevHit.rects;
974
+ } else {
975
+ blockSynced = false;
976
+ emojiText = isEmojiCandidate(textData);
977
+ clusters = glyphClusters(textData);
978
+ rawString = typeof clusters === "string";
979
+ if (prevHit?.styleKey === styleKey && prevHit.rawString && rawString && prevHit.bmp && sameBox(relBlockRect, prevHit.blockRect) && !justified && !textNode.nextSibling && (parent === block || parent !== null && !parent.nextSibling)) {
980
+ const prevText = prevHit.text;
981
+ const nA = prevText.length;
982
+ const nB = textData.length;
983
+ const minLen = nA < nB ? nA : nB;
984
+ let tail = 0;
985
+ while (tail < minLen && prevText.charCodeAt(nA - 1 - tail) === textData.charCodeAt(nB - 1 - tail)) tail++;
986
+ if (tail > 2) {
987
+ suffixStart = nB - tail;
988
+ prevRects = prevHit.rects;
989
+ prevDelta = nA - nB;
990
+ }
991
+ }
992
+ cachedTextRuns.set(textNode, hit = {
993
+ styleKey,
994
+ text: textData,
995
+ rects: new Float64Array(textData.length * 5),
996
+ blockRect: void 0,
997
+ emojiText,
998
+ rawString,
999
+ clusters,
1000
+ bmp: false
1001
+ });
1002
+ syncSource = hit.rects;
900
1003
  }
1004
+ } else {
1005
+ emojiText = isEmojiCandidate(textData);
1006
+ clusters = glyphClusters(textData);
1007
+ rawString = typeof clusters === "string";
1008
+ }
1009
+ const rects = hit?.rects;
1010
+ let bmp = rawString;
1011
+ const clusterArr = rawString ? null : clusters;
1012
+ const totalItems = rawString ? textData.length : clusterArr.length;
1013
+ let pos = 0;
1014
+ let ci = -1;
1015
+ while (pos < totalItems) {
1016
+ ci++;
1017
+ let cluster;
1018
+ let step;
1019
+ let asciiCode = -1;
1020
+ if (rawString) {
1021
+ const c0 = textData.charCodeAt(pos);
1022
+ if (!shown && (c0 === 32 || c0 >= 9 && c0 <= 13)) {
1023
+ if (!gap || keepsSpaces) gap += space;
1024
+ afterSpace = true;
1025
+ hasMarkAnchor = hasKernPrevious = false;
1026
+ previousCharacter = "";
1027
+ pos++;
1028
+ utf16Offset++;
1029
+ continue;
1030
+ }
1031
+ if (c0 >= 33 && c0 <= 126) {
1032
+ step = 1;
1033
+ cluster = SINGLE_CHAR[c0];
1034
+ asciiCode = c0;
1035
+ } else if (c0 >= 55296 && c0 <= 56319 && pos + 1 < totalItems && textData.charCodeAt(pos + 1) >= 56320 && textData.charCodeAt(pos + 1) <= 57343) {
1036
+ step = 2;
1037
+ bmp = false;
1038
+ cluster = textData.slice(pos, pos + 2);
1039
+ } else {
1040
+ step = 1;
1041
+ cluster = c0 < 128 ? SINGLE_CHAR[c0] : textData[pos];
1042
+ }
1043
+ } else {
1044
+ step = 1;
1045
+ cluster = clusterArr[pos];
1046
+ }
1047
+ pos += step;
1048
+ const share = shown ? shown[clusterIndex++] : cluster;
1049
+ const nextOffset = utf16Offset + cluster.length;
1050
+ if (asciiCode < 0 || shown) {
1051
+ const sc = share.length === 1 ? share.charCodeAt(0) : -1;
1052
+ if (sc === 32 || sc === 160 || sc >= 9 && (sc <= 13 || sc > 126 && /^\s$/u.test(share))) {
1053
+ if (sc === 32 || sc <= 13 || sc !== 8199 && sc !== 8239 && sc !== 65279) {
1054
+ if (!gap || keepsSpaces) gap += space;
1055
+ if (sc !== 160) afterSpace = true;
1056
+ }
1057
+ hasMarkAnchor = hasKernPrevious = false;
1058
+ previousCharacter = "";
1059
+ utf16Offset = nextOffset;
1060
+ continue;
1061
+ }
1062
+ if (!share) {
1063
+ hasKernPrevious = false;
1064
+ utf16Offset = nextOffset;
1065
+ continue;
1066
+ }
1067
+ }
1068
+ let bLeft;
1069
+ let bTop;
1070
+ let bBottom;
1071
+ let bWidth;
1072
+ let bHeight;
1073
+ const boxOff = ci * 5;
1074
+ if (rects && synced) {
1075
+ const sOff = (ci + syncDelta) * 5;
1076
+ const rLeft = syncSource[sOff];
1077
+ const rTop = syncSource[sOff + 1];
1078
+ const rBottom = syncSource[sOff + 2];
1079
+ bLeft = rLeft + rootLeft;
1080
+ bTop = rTop + rootTop;
1081
+ bBottom = rBottom + rootTop;
1082
+ bWidth = syncSource[sOff + 3];
1083
+ bHeight = syncSource[sOff + 4];
1084
+ if (syncSource !== rects) {
1085
+ rects[boxOff] = rLeft;
1086
+ rects[boxOff + 1] = rTop;
1087
+ rects[boxOff + 2] = rBottom;
1088
+ rects[boxOff + 3] = bWidth;
1089
+ rects[boxOff + 4] = bHeight;
1090
+ }
1091
+ } else {
1092
+ range.setEnd(textNode, nextOffset);
1093
+ range.setStart(textNode, utf16Offset);
1094
+ const d = range.getBoundingClientRect();
1095
+ bLeft = d.left;
1096
+ bTop = d.top;
1097
+ bBottom = d.bottom;
1098
+ bWidth = d.width;
1099
+ bHeight = d.height;
1100
+ if (rects) {
1101
+ const rLeft = bLeft - rootLeft;
1102
+ const rTop = bTop - rootTop;
1103
+ const rBottom = bBottom - rootTop;
1104
+ if (canSync && rects[boxOff] === rLeft && rects[boxOff + 1] === rTop && rects[boxOff + 3] === bWidth && rects[boxOff + 4] === bHeight) {
1105
+ synced = true;
1106
+ syncSource = rects;
1107
+ syncDelta = 0;
1108
+ } else {
1109
+ rects[boxOff] = rLeft;
1110
+ rects[boxOff + 1] = rTop;
1111
+ rects[boxOff + 2] = rBottom;
1112
+ rects[boxOff + 3] = bWidth;
1113
+ rects[boxOff + 4] = bHeight;
1114
+ if (prevRects && pos - 1 > suffixStart + 1 && ci === pos - 1) {
1115
+ const prevGlyph = glyphs[glyphs.length - 1];
1116
+ if (prevGlyph?.block === blockIndex && prevGlyph.lineBottom !== (rootBottom - bBottom) * invScale || align === "left" && !rtl) {
1117
+ const pOff = (ci + prevDelta) * 5;
1118
+ if (pOff >= 0 && prevRects[pOff] === rLeft && prevRects[pOff + 1] === rTop && prevRects[pOff + 3] === bWidth && prevRects[pOff + 4] === bHeight) {
1119
+ synced = true;
1120
+ syncSource = prevRects;
1121
+ syncDelta = prevDelta;
1122
+ }
1123
+ }
1124
+ }
1125
+ }
1126
+ }
1127
+ }
1128
+ utf16Offset = nextOffset;
1129
+ if (measuresBaselines && (!gridDone || trackBlockGrid)) trackLayoutGrid(bLeft, bWidth);
1130
+ const parts = !shown || share === cluster ? void 0 : expansionBoxes(share, bLeft, bTop, bBottom, bWidth, bHeight, font);
1131
+ const partLen = parts ? parts.length : 1;
1132
+ for (let part = 0; part < partLen; part++) {
1133
+ let pLeft = bLeft;
1134
+ let pTop = bTop;
1135
+ let pBottom = bBottom;
1136
+ let pWidth = bWidth;
1137
+ let pHeight = bHeight;
1138
+ let character = share;
1139
+ let partAscii = shown ? -1 : asciiCode;
1140
+ if (parts) {
1141
+ const box = parts[part];
1142
+ pLeft = box.left;
1143
+ pTop = box.top;
1144
+ pBottom = box.bottom;
1145
+ pWidth = box.width;
1146
+ pHeight = box.height;
1147
+ character = box.c;
1148
+ partAscii = -1;
1149
+ }
1150
+ if (pWidth <= 0 || pHeight <= 0) {
1151
+ const previous = glyphs[glyphs.length - 1];
1152
+ hasKernPrevious = false;
1153
+ if (!hasMarkAnchor || !previous || !/^\p{M}/u.test(character)) continue;
1154
+ const key = requestKey(font, keys, character, asciiKeys);
1155
+ const sequence = nextSequence(markAnchorLineKey);
1156
+ if (options.pixelSnap) paintLines[glyphs.length] = paintLines[glyphs.length - 1];
1157
+ glyphs.push({
1158
+ glyphKey: key,
1159
+ fontSize,
1160
+ originX: previous.originX + previous.advance,
1161
+ lineBottom: previous.lineBottom,
1162
+ advance: 0,
1163
+ ...options.rtlReflow ? { decorationWidth: 0 } : {},
1164
+ block: blockIndex,
1165
+ breakBefore: "none",
1166
+ clip,
1167
+ color,
1168
+ sequence,
1169
+ z
1170
+ });
1171
+ continue;
1172
+ }
1173
+ if (pLeft < minLeft) minLeft = pLeft;
1174
+ if (pLeft + pWidth > maxRight) maxRight = pLeft + pWidth;
1175
+ if (pTop < minTop) minTop = pTop;
1176
+ if (pBottom > maxBottom) maxBottom = pBottom;
1177
+ const key = (partAscii >= 0 ? asciiKeys[partAscii] : void 0) ?? requestKey(font, keys, character, asciiKeys);
1178
+ const previous = glyphs[glyphs.length - 1];
1179
+ const sameBlock = previous?.block === blockIndex;
1180
+ const emoji = partAscii < 0 && emojiText && isEmojiCandidate(character);
1181
+ const sharesLine = sameBlock && hasPrevBounds && Math.min(pBottom, prevBottom) - Math.max(pTop, prevTop) > Math.min(pHeight, prevHeight) * .5;
1182
+ const sameEmojiLine = sharesLine && (emoji || previousEmoji);
1183
+ const lineKey = sameEmojiLine ? markAnchorLineKey : Math.round(pTop * 4);
1184
+ const sequence = nextSequence(lineKey);
1185
+ const lineBottom = sameEmojiLine ? previous.lineBottom : (rootBottom - pBottom) * invScale;
1186
+ const lineChanged = sameBlock && previous.lineBottom !== lineBottom;
1187
+ let kernShift = 0;
1188
+ let kernCarry = 0;
1189
+ let charWidth = -1;
1190
+ if (hasKernPrevious && measuresKerning && !parts && !emoji && !lineChanged) {
1191
+ const firstWidth = kernPrevWidth >= 0 ? kernPrevWidth : canvasWidth(layoutFont, widths, asciiWidths, kernPrevChar);
1192
+ const shownKern = pLeft - kernPrevLeft - letterSpacing - firstWidth - kernPrevCarry;
1193
+ if (Math.abs(shownKern) > (nativeBrowser ? .02 : .0025)) {
1194
+ if (partAscii >= 0) {
1195
+ charWidth = asciiWidths[partAscii];
1196
+ if (charWidth < 0) charWidth = asciiWidths[partAscii] = measureCanvasWidth(layoutFont, character);
1197
+ } else charWidth = canvasWidth(layoutFont, widths, asciiWidths, character);
1198
+ let pairTotal;
1199
+ if (kernPrevCode >= 0 && partAscii >= 0) {
1200
+ const pairKey = kernPrevCode << 7 | partAscii;
1201
+ let cachedPair = pairWidths.get(pairKey);
1202
+ if (cachedPair === void 0) pairWidths.set(pairKey, cachedPair = measureCanvasWidth(layoutFont, kernPrevChar + character));
1203
+ pairTotal = cachedPair;
1204
+ } else pairTotal = canvasPairWidth(layoutFont, widths, pairWidths, kernPrevChar, character);
1205
+ const pair = pairTotal - firstWidth - charWidth;
1206
+ if (Math.abs(pair) > .01 && Math.abs(shownKern - pair / 2) <= Math.min(.25, Math.abs(pair) / 4)) {
1207
+ kernCarry = pair - shownKern;
1208
+ kernShift = kernCarry;
1209
+ }
1210
+ }
1211
+ }
1212
+ const originX = (pLeft - rootLeft + kernShift) * invScale;
1213
+ boxHeight ||= pHeight;
1214
+ if (options.pixelSnap) {
1215
+ if (sharesLine) lineTops[lineTops.length - 1] = Math.min(lineTops[lineTops.length - 1], pTop);
1216
+ else lineTops.push(pTop);
1217
+ paintLines[glyphs.length] = lineTops.length - 1;
1218
+ }
1219
+ hasPrevBounds = true;
1220
+ prevTop = pTop;
1221
+ prevBottom = pBottom;
1222
+ prevHeight = pHeight;
1223
+ previousEmoji = emoji;
1224
+ const isCjkSoft = options.cjkLineBreaking === true && canBreakCjk(previousCharacter, character);
1225
+ if (sameBlock && !lineChanged && previous.shapeGroup === void 0) {
1226
+ if (gap || afterSpace || isCjkSoft) previous.decorationWidth ??= previous.advance;
1227
+ previous.advance = originX - previous.originX;
1228
+ }
1229
+ const soft = !sameBlock || isCjkSoft || afterSpace && !(forced && lineChanged);
1230
+ let lone;
1231
+ if (measuresKerning && !parts && !emoji) {
1232
+ if (charWidth < 0) {
1233
+ if (partAscii >= 0) {
1234
+ charWidth = asciiWidths[partAscii];
1235
+ if (charWidth < 0) charWidth = asciiWidths[partAscii] = measureCanvasWidth(layoutFont, character);
1236
+ } else charWidth = canvasWidth(layoutFont, widths, asciiWidths, character);
1237
+ }
1238
+ lone = charWidth + letterSpacing;
1239
+ } else lone = pWidth;
1240
+ const glyph = {
1241
+ glyphKey: key,
1242
+ fontSize,
1243
+ originX,
1244
+ lineBottom,
1245
+ advance: (Math.abs(lone - pWidth) < .04 ? lone : pWidth) * invScale,
1246
+ block: blockIndex,
1247
+ breakBefore: soft ? "soft" : lineChanged ? "hard" : "none",
1248
+ clip,
1249
+ color,
1250
+ sequence,
1251
+ z
1252
+ };
1253
+ if (isCjkSoft) glyph.gapBefore = 0;
1254
+ else if (gap && (justified ? soft || !lineChanged : soft && lineChanged && previous.shapeGroup === void 0)) glyph.gapBefore = gap;
1255
+ if (decorations.length || options.rtlReflow) {
1256
+ glyph.decorations = decorations;
1257
+ glyph.decorationWidth = glyph.advance;
1258
+ }
1259
+ glyphs.push(glyph);
1260
+ gap = 0;
1261
+ forced = false;
1262
+ if (parts || emoji) hasKernPrevious = false;
1263
+ else {
1264
+ hasKernPrevious = true;
1265
+ kernPrevChar = character;
1266
+ kernPrevCode = partAscii;
1267
+ kernPrevLeft = pLeft;
1268
+ kernPrevWidth = charWidth;
1269
+ kernPrevCarry = kernCarry;
1270
+ }
1271
+ afterSpace = false;
1272
+ if (options.cjkLineBreaking) previousCharacter = character;
1273
+ markAnchorLineKey = lineKey;
1274
+ hasMarkAnchor = true;
1275
+ }
1276
+ }
1277
+ if (hit) {
1278
+ hit.blockRect = relBlockRect;
1279
+ hit.bmp = bmp;
1280
+ }
1281
+ if (measuresBaselines && boxHeight > 0) {
1282
+ templateBoxHeight = boxHeight;
1283
+ textRuns.push([
1284
+ font,
1285
+ runStart,
1286
+ glyphs.length
1287
+ ]);
1288
+ if (!boxHeights.has(font)) boxHeights.set(font, boxHeight);
901
1289
  }
902
1290
  }
903
- const originX = (pLeft - rootLeft + kernShift) * invScale;
904
- boxHeight ||= pHeight;
905
- if (options.pixelSnap) {
906
- if (sharesLine) lineTops[lineTops.length - 1] = Math.min(lineTops.at(-1), pTop);
907
- else lineTops.push(pTop);
908
- paintLines[glyphs.length] = lineTops.length - 1;
909
- }
910
- hasPrevBounds = true;
911
- prevTop = pTop;
912
- prevBottom = pBottom;
913
- prevHeight = pHeight;
914
- previousEmoji = emoji;
915
- const isCjkSoft = options.cjkLineBreaking === true && canBreakCjk(previousCharacter, character);
916
- if (sameBlock && !lineChanged && previous.shapeGroup === void 0) {
917
- if (gap || afterSpace || isCjkSoft) previous.decorationWidth ??= previous.advance;
918
- previous.advance = originX - previous.originX;
919
- }
920
- const soft = !sameBlock || isCjkSoft || afterSpace && !(forced && lineChanged);
921
- const lone = measuresKerning && !parts && !emoji ? (charWidth >= 0 ? charWidth : charWidth = canvasWidth(layoutFont, widths, asciiWidths, character)) + letterSpacing : pWidth;
922
- const glyph = {
923
- glyphKey: key,
924
- fontSize,
925
- originX,
926
- lineBottom,
927
- advance: (Math.abs(lone - pWidth) < .04 ? lone : pWidth) * invScale,
928
- block: blockIndex,
929
- breakBefore: soft ? "soft" : lineChanged ? "hard" : "none",
930
- clip,
931
- color,
932
- sequence,
933
- z
934
- };
935
- if (isCjkSoft) glyph.gapBefore = 0;
936
- else if (gap && (justified ? soft || !lineChanged : soft && lineChanged && previous.shapeGroup === void 0)) glyph.gapBefore = gap;
937
- if (decorations.length || options.rtlReflow) {
938
- glyph.decorations = decorations;
939
- glyph.decorationWidth = glyph.advance;
940
- }
941
- glyphs.push(glyph);
942
- gap = 0;
943
- forced = false;
944
- if (parts || emoji) hasKernPrevious = false;
945
- else {
946
- hasKernPrevious = true;
947
- kernPrevChar = character;
948
- kernPrevLeft = pLeft;
949
- kernPrevWidth = charWidth;
950
- kernPrevCarry = kernCarry;
951
- }
952
- afterSpace = false;
953
- if (options.cjkLineBreaking) previousCharacter = character;
954
- markAnchorLineKey = lineKey;
955
- hasMarkAnchor = true;
956
1291
  }
957
1292
  }
958
- if (hit) hit[2] = blockRect;
959
- if (measuresBaselines && boxHeight > 0) {
960
- textRuns.push([
961
- font,
962
- runStart,
963
- glyphs.length
964
- ]);
965
- if (!boxHeights.has(font)) boxHeights.set(font, boxHeight);
1293
+ if (walker) node = walker.nextNode();
1294
+ else if (nextNode) node = nextNode;
1295
+ else if (!hasElementChild) node = node.nextSibling;
1296
+ else {
1297
+ let back = node;
1298
+ while (back && back !== block) {
1299
+ const sib = back.nextSibling;
1300
+ if (sib) {
1301
+ node = sib;
1302
+ break;
1303
+ }
1304
+ back = back.parentNode;
1305
+ }
1306
+ if (!back || back === block) node = null;
966
1307
  }
967
1308
  }
968
1309
  lineCount += sequences.size;
969
1310
  } else {
970
- const [lines, left, width] = pretextCapture[2](block, blockIndex, blockStyle, blockRect, clip, includeTextBoxObj, align, lastAlign);
1311
+ const [lines, left, width] = pretextCapture[2](block, blockIndex, styleOf(block), blockRect, clip, includeTextBoxObj, align, lastAlign);
971
1312
  lineCount += lines;
972
1313
  blockLeft = left;
973
1314
  blockWidth = width;
@@ -981,12 +1322,7 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
981
1322
  clip[3] = (rootBottom - minTop) * invScale;
982
1323
  }
983
1324
  afterSpace = true;
984
- if (svg) {
985
- for (let index = blockStart; index < glyphs.length; index++) if (glyphs[index].shapeGroup !== void 0) {
986
- lineCount = lineCountBefore + svg.normalizeSvgLines(glyphs, blockStart, shapeBoxes);
987
- break;
988
- }
989
- }
1325
+ if (svgRunner) lineCount = svgRunner.finishBlock(blockStart, lineCountBefore, lineCount);
990
1326
  if (glyphs.length > blockStart) {
991
1327
  let first = -Infinity;
992
1328
  let second = -Infinity;
@@ -1014,8 +1350,53 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
1014
1350
  } : align !== natural ? { textAlign: align } : {}
1015
1351
  };
1016
1352
  }
1353
+ if (tmplReady && templateTextNode && !svg) {
1354
+ const seen = /* @__PURE__ */ new Set();
1355
+ const tReq = [];
1356
+ for (let i = blockStart; i < glyphs.length; i++) {
1357
+ const key = glyphs[i].glyphKey;
1358
+ if (!seen.has(key)) {
1359
+ const req = requests.get(key);
1360
+ if (req) {
1361
+ seen.add(key);
1362
+ tReq.push(req);
1363
+ }
1364
+ }
1365
+ }
1366
+ pendingTemplates.push([
1367
+ block,
1368
+ {
1369
+ n: templateTextNode,
1370
+ s: templateText,
1371
+ r: relBlockRect,
1372
+ p: snapTmplPrefix,
1373
+ sl: tmplScrollLeft,
1374
+ st: tmplScrollTop,
1375
+ bi: blockIndex,
1376
+ it: tmplInlineTk,
1377
+ bt: tmplBlkTk,
1378
+ g: EMPTY_GLYPHS,
1379
+ req: tReq,
1380
+ oc: blockOffCss,
1381
+ od: blockOffDev,
1382
+ bh: templateBoxHeight,
1383
+ l: lineCount - lineCountBefore,
1384
+ c: [
1385
+ clip[0],
1386
+ clip[1],
1387
+ clip[2],
1388
+ clip[3]
1389
+ ],
1390
+ bl: blockLayouts[blockIndex],
1391
+ bo: void 0
1392
+ },
1393
+ blockStart,
1394
+ glyphs.length
1395
+ ]);
1396
+ }
1017
1397
  }
1018
- if (textRuns.length > 0) {
1398
+ trackBlockGrid = false;
1399
+ if (textRuns.length > 0 || hitRuns.length > 0) {
1019
1400
  const scales = layoutScales();
1020
1401
  const probe = scales.length > 0 ? ensureFontProbe() : null;
1021
1402
  if (probe) {
@@ -1023,10 +1404,42 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
1023
1404
  layoutScale = scale;
1024
1405
  for (const [font, from, to] of textRuns) {
1025
1406
  const descent = descents.get(font);
1026
- if (descent !== void 0) for (let index = from; index < to; index++) glyphs[index].baselineOffset = descent * invScale;
1407
+ if (descent !== void 0) {
1408
+ const bo = descent * invScale;
1409
+ for (let index = from; index < to; index++) glyphs[index].baselineOffset = bo;
1410
+ }
1411
+ }
1412
+ for (const [font, from, to, oldBo] of hitRuns) {
1413
+ const descent = descents.get(font);
1414
+ const newBo = descent !== void 0 ? descent * invScale : void 0;
1415
+ if (newBo !== oldBo) for (let index = from; index < to; index++) {
1416
+ const clone = { ...glyphs[index] };
1417
+ if (newBo !== void 0) clone.baselineOffset = newBo;
1418
+ else delete clone.baselineOffset;
1419
+ glyphs[index] = clone;
1420
+ }
1027
1421
  }
1028
1422
  }
1029
1423
  }
1424
+ const cloneForTemplate = !isImmutableCapture();
1425
+ for (const [el, tmpl, from, to] of pendingTemplates) {
1426
+ tmpl.bo = glyphs[from]?.baselineOffset;
1427
+ const slice = glyphs.slice(from, to);
1428
+ if (cloneForTemplate) {
1429
+ const c = tmpl.c;
1430
+ const copyClip = [
1431
+ c[0],
1432
+ c[1],
1433
+ c[2],
1434
+ c[3]
1435
+ ];
1436
+ tmpl.g = slice.map((g) => ({
1437
+ ...g,
1438
+ clip: copyClip
1439
+ }));
1440
+ } else tmpl.g = slice;
1441
+ cachedBlockTemplates.set(el, tmpl);
1442
+ }
1030
1443
  let snapGrid;
1031
1444
  if (options.pixelSnap) {
1032
1445
  const rowScale = layoutScale ?? deviceScale;
@@ -1039,15 +1452,14 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
1039
1452
  snapGlyph(glyph, shaping ? 0 : rootLeft * 4 * deviceScale + glyph.originX * snapGrid[0], rootBottom * rowScale - glyph.lineBottom * snapGrid[1], snapGrid, top - Math.floor(top + .5 + 1e-6));
1040
1453
  }
1041
1454
  }
1042
- const rectElements = [...root.matches(rectSelector) || options.includeRootBackground !== false ? [root] : [], ...root.querySelectorAll(rectSelector)];
1043
- for (const element of rectElements) {
1044
- if (isIgnored(element) || displayNone(element)) continue;
1455
+ const captureRect = (element) => {
1456
+ if (isIgnored(element) || displayNone(element)) return;
1045
1457
  const style = styleOf(element);
1046
- if (isHidden(style)) continue;
1458
+ if (isHidden(style)) return;
1047
1459
  const color = cssColorToSrgba(document, style.backgroundColor, opacityOf(element));
1048
- if (color[3] <= 0) continue;
1460
+ if (color[3] <= 0) return;
1049
1461
  const bounds = element === root ? rootRect : element.getBoundingClientRect();
1050
- if (bounds.width <= 0 || bounds.height <= 0) continue;
1462
+ if (bounds.width <= 0 || bounds.height <= 0) return;
1051
1463
  const zDefault = element === root ? options.panelDepth ?? -1 : options.rectDepth ?? 0;
1052
1464
  const rawRad = style.borderTopLeftRadius.split(/[\s/]/, 1)[0] ?? "";
1053
1465
  rects.push({
@@ -1057,28 +1469,10 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
1057
1469
  z: depthOf(element, zDefault),
1058
1470
  receiveShadow: element.hasAttribute("data-text-receive-shadow") || element.hasAttribute("data-sdf-receive-shadow")
1059
1471
  });
1060
- }
1061
- if (svgContext) for (const element of root.querySelectorAll(`${svgOptions.selector ?? "svg"}${svgOptions.images ? ",img" : ""}`)) {
1062
- if (capturedSvgs.has(element) || element.closest(textSelector)) continue;
1063
- const start = glyphs.length;
1064
- const clip = [
1065
- 0,
1066
- 0,
1067
- rootRect.width * invScale,
1068
- rootRect.height * invScale
1069
- ];
1070
- captureShape(element, blockLayouts.length, clip, 0);
1071
- if (glyphs.length > start) {
1072
- const first = glyphs[start];
1073
- blockLayouts.push({
1074
- left: first.originX,
1075
- firstBaseline: first.lineBottom,
1076
- linePitch: 0,
1077
- width: first.advance,
1078
- clip
1079
- });
1080
- }
1081
- }
1472
+ };
1473
+ if (options.includeRootBackground !== false || root.matches(rectSelector)) captureRect(root);
1474
+ const matchedRects = root.querySelectorAll(rectSelector);
1475
+ for (let i = 0, len = matchedRects.length; i < len; i++) captureRect(matchedRects[i]);
1082
1476
  for (const character of glyphClusters(options.extraGlyphs ?? "")) {
1083
1477
  if (/^\s$/u.test(character)) continue;
1084
1478
  const emoji = isEmojiCandidate(character);
@@ -1087,10 +1481,19 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
1087
1481
  requestKey(font, keys, character, asciiKeys);
1088
1482
  }
1089
1483
  }
1090
- if (svg) svg.normalizeSvgMotion(glyphs);
1091
- const requestList = [...requests.values()].sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
1092
- const atlasSignature = requestList.map((request) => request.key).join("");
1093
- return {
1484
+ svgRunner?.finish();
1485
+ const requestList = Array.from(requests.values()).sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
1486
+ const requestKeys = new Array(requestList.length);
1487
+ for (let i = 0; i < requestList.length; i++) requestKeys[i] = requestList[i].key;
1488
+ const atlasSignature = requestKeys.join("");
1489
+ let hasRunMotion = Boolean(shaping);
1490
+ if (!hasRunMotion && svg) {
1491
+ for (const glyph of glyphs) if (glyph.motionOrigin !== void 0) {
1492
+ hasRunMotion = true;
1493
+ break;
1494
+ }
1495
+ }
1496
+ const snapshot = {
1094
1497
  ...shaping ? { textShaping: "browser" } : {},
1095
1498
  width: rootRect.width * invScale,
1096
1499
  height: rootRect.height * invScale,
@@ -1100,8 +1503,12 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
1100
1503
  requests: requestList,
1101
1504
  atlasSignature,
1102
1505
  lineCount,
1103
- ...snapGrid ? { snapGrid } : {}
1506
+ ...snapGrid ? { snapGrid } : {},
1507
+ ...cssDropShadow ? { dropShadow: cssDropShadow } : {},
1508
+ ...cssOutline ? { outline: cssOutline } : {}
1104
1509
  };
1510
+ snapshotFlags.set(snapshot, (hasRunMotion ? 1 : 0) | 2 | (hasAnyDecorations ? 0 : 4));
1511
+ return snapshot;
1105
1512
  }
1106
1513
  export { collectDomSnapshot, physicalAlign };
1107
1514