ultra-text 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/README.md +267 -962
  2. package/THIRD_PARTY_NOTICES.md +3 -0
  3. package/dist/assets/{cpuSdf.worker-Du9o8q4p.js → cpuSdf.worker--X1Qpmdp.js} +148 -57
  4. package/dist/assets/cpuSdf.worker--X1Qpmdp.js.map +1 -0
  5. package/dist/atlas/appendAtlas.js +69 -26
  6. package/dist/atlas/appendAtlas.js.map +1 -1
  7. package/dist/atlas/buildAtlas.js +5 -15
  8. package/dist/atlas/buildAtlas.js.map +1 -1
  9. package/dist/atlas/cpuAtlas.d.ts +4 -1
  10. package/dist/atlas/cpuAtlas.js +8 -6
  11. package/dist/atlas/cpuAtlas.js.map +1 -1
  12. package/dist/atlas/cpuSdf.js +164 -50
  13. package/dist/atlas/cpuSdf.js.map +1 -1
  14. package/dist/atlas/cpuWorker.d.ts +5 -3
  15. package/dist/atlas/cpuWorker.js +119 -12
  16. package/dist/atlas/cpuWorker.js.map +1 -1
  17. package/dist/atlas/gpuAtlas.d.ts +7 -6
  18. package/dist/atlas/gpuAtlas.js +206 -247
  19. package/dist/atlas/gpuAtlas.js.map +1 -1
  20. package/dist/atlas/gpuCommon.d.ts +135 -0
  21. package/dist/atlas/gpuCommon.js +223 -0
  22. package/dist/atlas/gpuCommon.js.map +1 -0
  23. package/dist/atlas/jfaWgsl.js +59 -125
  24. package/dist/atlas/jfaWgsl.js.map +1 -1
  25. package/dist/atlas/rasterize.d.ts +2 -0
  26. package/dist/atlas/rasterize.js +104 -144
  27. package/dist/atlas/rasterize.js.map +1 -1
  28. package/dist/atlas/shapeRaster.js +2 -1
  29. package/dist/atlas/shapeRaster.js.map +1 -1
  30. package/dist/atlas/vanillaBounds.d.ts +64 -0
  31. package/dist/atlas/vanillaBounds.js +42 -0
  32. package/dist/atlas/vanillaBounds.js.map +1 -0
  33. package/dist/atlas/vanillaCore.d.ts +100 -0
  34. package/dist/atlas/vanillaCore.js +1012 -0
  35. package/dist/atlas/vanillaCore.js.map +1 -0
  36. package/dist/atlas/vanillaCpuAtlas.d.ts +9 -0
  37. package/dist/atlas/vanillaCpuAtlas.js +87 -0
  38. package/dist/atlas/vanillaCpuAtlas.js.map +1 -0
  39. package/dist/atlas/vanillaExtras.d.ts +8 -0
  40. package/dist/atlas/vanillaExtras.js +166 -0
  41. package/dist/atlas/vanillaExtras.js.map +1 -0
  42. package/dist/atlas/vanillaGpuHelpers.d.ts +232 -0
  43. package/dist/atlas/vanillaGpuHelpers.js +119 -0
  44. package/dist/atlas/vanillaGpuHelpers.js.map +1 -0
  45. package/dist/dom/DomSdf.js +263 -272
  46. package/dist/dom/DomSdf.js.map +1 -1
  47. package/dist/dom/DomSlug.d.ts +26 -0
  48. package/dist/dom/DomSlug.js +564 -0
  49. package/dist/dom/DomSlug.js.map +1 -0
  50. package/dist/dom/SlugText.d.ts +18 -0
  51. package/dist/dom/SlugText.js +94 -0
  52. package/dist/dom/SlugText.js.map +1 -0
  53. package/dist/dom/Text.js +4 -67
  54. package/dist/dom/Text.js.map +1 -1
  55. package/dist/dom/domAnalytic.d.ts +54 -0
  56. package/dist/dom/domAnalytic.js +282 -0
  57. package/dist/dom/domAnalytic.js.map +1 -0
  58. package/dist/dom/domExtras.d.ts +27 -0
  59. package/dist/dom/domExtras.js +137 -0
  60. package/dist/dom/domExtras.js.map +1 -0
  61. package/dist/dom/fontCanvas.d.ts +2 -0
  62. package/dist/dom/fontCanvas.js +119 -0
  63. package/dist/dom/fontCanvas.js.map +1 -0
  64. package/dist/dom/layoutSignature.js +156 -27
  65. package/dist/dom/layoutSignature.js.map +1 -1
  66. package/dist/dom/pretextLayout.js +55 -13
  67. package/dist/dom/pretextLayout.js.map +1 -1
  68. package/dist/dom/snapshot.js +563 -243
  69. package/dist/dom/snapshot.js.map +1 -1
  70. package/dist/dom/svgCapture.d.ts +8 -1
  71. package/dist/dom/svgCapture.js +75 -1
  72. package/dist/dom/svgCapture.js.map +1 -1
  73. package/dist/dom/textHost.d.ts +11 -0
  74. package/dist/dom/textHost.js +68 -0
  75. package/dist/dom/textHost.js.map +1 -0
  76. package/dist/dom/tone.js +76 -36
  77. package/dist/dom/tone.js.map +1 -1
  78. package/dist/index.js +4 -3
  79. package/dist/slug/SlugMaterial.d.ts +13 -4
  80. package/dist/slug/SlugMaterial.js +82 -12
  81. package/dist/slug/SlugMaterial.js.map +1 -1
  82. package/dist/slug/coverage.d.ts +17 -13
  83. package/dist/slug/coverage.js +195 -222
  84. package/dist/slug/coverage.js.map +1 -1
  85. package/dist/slug/preprocessCore.d.ts +6 -3
  86. package/dist/slug/preprocessCore.js +149 -95
  87. package/dist/slug/preprocessCore.js.map +1 -1
  88. package/dist/slug/runtime.d.ts +1 -0
  89. package/dist/slug/runtime.js +94 -46
  90. package/dist/slug/runtime.js.map +1 -1
  91. package/dist/slug/standaloneRuntime.d.ts +40 -0
  92. package/dist/slug/standaloneRuntime.js +175 -0
  93. package/dist/slug/standaloneRuntime.js.map +1 -0
  94. package/dist/slug/truetype.d.ts +22 -0
  95. package/dist/slug/truetype.js +467 -0
  96. package/dist/slug/truetype.js.map +1 -0
  97. package/dist/slug/vanillaCore.d.ts +340 -0
  98. package/dist/slug/vanillaCore.js +1621 -0
  99. package/dist/slug/vanillaCore.js.map +1 -0
  100. package/dist/slug-vanilla.d.ts +13 -0
  101. package/dist/slug-vanilla.js +13 -0
  102. package/dist/slug.d.ts +21 -0
  103. package/dist/slug.js +19 -0
  104. package/dist/text/GlyphTextMaterial.d.ts +11 -11
  105. package/dist/text/GlyphTextMaterial.js +102 -33
  106. package/dist/text/GlyphTextMaterial.js.map +1 -1
  107. package/dist/text/SdfTextMaterial.d.ts +5 -4
  108. package/dist/text/SdfTextMaterial.js +29 -9
  109. package/dist/text/SdfTextMaterial.js.map +1 -1
  110. package/dist/text/decorations.js +36 -19
  111. package/dist/text/decorations.js.map +1 -1
  112. package/dist/text/geometry.d.ts +3 -22
  113. package/dist/text/geometryUtils.d.ts +11 -1
  114. package/dist/text/geometryUtils.js +22 -1
  115. package/dist/text/geometryUtils.js.map +1 -1
  116. package/dist/text/glyphGeometry.d.ts +9 -0
  117. package/dist/text/glyphGeometry.js +353 -0
  118. package/dist/text/glyphGeometry.js.map +1 -0
  119. package/dist/text/index.d.ts +2 -1
  120. package/dist/text/rectGeometry.d.ts +13 -0
  121. package/dist/text/rectGeometry.js +97 -0
  122. package/dist/text/rectGeometry.js.map +1 -0
  123. package/dist/text/reflow.d.ts +18 -1
  124. package/dist/text/reflow.js +108 -38
  125. package/dist/text/reflow.js.map +1 -1
  126. package/dist/text/snap.d.ts +1 -0
  127. package/dist/text/snap.js +26 -0
  128. package/dist/text/snap.js.map +1 -0
  129. package/dist/types.d.ts +63 -14
  130. package/dist/vanilla.d.ts +13 -360
  131. package/dist/vanilla.js +8 -1402
  132. package/dist/windfoil/WindfoilMaterial.d.ts +2 -1
  133. package/dist/windfoil/WindfoilMaterial.js +8 -1
  134. package/dist/windfoil/WindfoilMaterial.js.map +1 -1
  135. package/dist/windfoil/abortable.d.ts +2 -0
  136. package/dist/windfoil/abortable.js +26 -0
  137. package/dist/windfoil/abortable.js.map +1 -0
  138. package/dist/windfoil/color.js +2 -1
  139. package/dist/windfoil/color.js.map +1 -1
  140. package/dist/windfoil/coverage.d.ts +3 -20
  141. package/dist/windfoil/coverage.js +7 -20
  142. package/dist/windfoil/coverage.js.map +1 -1
  143. package/dist/windfoil/emoji.js +1 -1
  144. package/dist/windfoil/emoji.js.map +1 -1
  145. package/dist/windfoil/emojiMetrics.js +1 -1
  146. package/dist/windfoil/emojiMetrics.js.map +1 -1
  147. package/dist/windfoil/geometry.d.ts +2 -2
  148. package/dist/windfoil/geometry.js +204 -64
  149. package/dist/windfoil/geometry.js.map +1 -1
  150. package/dist/windfoil/layerGrid.js +14 -10
  151. package/dist/windfoil/layerGrid.js.map +1 -1
  152. package/dist/windfoil/layerNormalization.d.ts +1 -1
  153. package/dist/windfoil/layerNormalization.js +1 -1
  154. package/dist/windfoil/layerNormalization.js.map +1 -1
  155. package/dist/windfoil/mixed.d.ts +1 -0
  156. package/dist/windfoil/mixed.js +44 -25
  157. package/dist/windfoil/mixed.js.map +1 -1
  158. package/dist/windfoil/outlineValidation.d.ts +86 -0
  159. package/dist/windfoil/outlineValidation.js +65 -0
  160. package/dist/windfoil/outlineValidation.js.map +1 -0
  161. package/dist/windfoil/preprocess.js +3 -2
  162. package/dist/windfoil/preprocess.js.map +1 -1
  163. package/dist/windfoil/preprocessCore.d.ts +5 -85
  164. package/dist/windfoil/preprocessCore.js +218 -209
  165. package/dist/windfoil/preprocessCore.js.map +1 -1
  166. package/dist/windfoil/requests.js +1 -1
  167. package/dist/windfoil/requests.js.map +1 -1
  168. package/dist/windfoil/runtime.d.ts +5 -2
  169. package/dist/windfoil/runtime.js +63 -40
  170. package/dist/windfoil/runtime.js.map +1 -1
  171. package/dist/windfoil/shapeResources.js +2 -1
  172. package/dist/windfoil/shapeResources.js.map +1 -1
  173. package/dist/windfoil/shapes.js +1 -1
  174. package/dist/windfoil/skirt.d.ts +22 -0
  175. package/dist/windfoil/skirt.js +20 -0
  176. package/dist/windfoil/skirt.js.map +1 -0
  177. package/dist/windfoil/storage.d.ts +62 -4
  178. package/dist/windfoil/storage.js +143 -28
  179. package/dist/windfoil/storage.js.map +1 -1
  180. package/dist/windfoil/trace/contours.d.ts +3 -3
  181. package/dist/windfoil/trace/contours.js +228 -137
  182. package/dist/windfoil/trace/contours.js.map +1 -1
  183. package/dist/windfoil/trace/fit.d.ts +3 -7
  184. package/dist/windfoil/trace/fit.js +668 -376
  185. package/dist/windfoil/trace/fit.js.map +1 -1
  186. package/dist/windfoil/trace/outline.js +60 -35
  187. package/dist/windfoil/trace/outline.js.map +1 -1
  188. package/dist/windfoil/trace/types.d.ts +15 -3
  189. package/dist/windfoil/tracedOutlines.d.ts +37 -1
  190. package/dist/windfoil/tracedOutlines.js +228 -64
  191. package/dist/windfoil/tracedOutlines.js.map +1 -1
  192. package/package.json +60 -11
  193. package/skills/ultra-text/SKILL.md +114 -0
  194. package/skills/ultra-text/references/frameworks.md +43 -0
  195. package/skills/ultra-text/references/three-tsl.md +78 -0
  196. package/skills/ultra-text/references/vanilla-webgpu.md +96 -0
  197. package/dist/assets/cpuSdf.worker-Du9o8q4p.js.map +0 -1
  198. package/dist/text/geometry.js +0 -348
  199. package/dist/text/geometry.js.map +0 -1
  200. 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";
2
+ import { parseCssColor } from "./tone.js";
3
3
  import { DEFAULT_IGNORE_SELECTOR, DEFAULT_TEXT_SELECTOR } 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";
@@ -37,11 +38,16 @@ function physicalAlign(value, rtl) {
37
38
  const side = value.replace("-webkit-", "");
38
39
  return /^(left|right|center|justify)$/.test(side) ? side : side === "end" !== rtl ? "right" : "left";
39
40
  }
41
+ var INV_2_22 = 2 ** -22;
42
+ var MAX_SHARED_FONT_CACHES = 256;
43
+ var SINGLE_CHAR = Array.from({ length: 128 }, (_, i) => String.fromCharCode(i));
40
44
  var sameBox = (a, b) => !!b && a.left === b.left && a.top === b.top && a.width === b.width && a.height === b.height;
41
- var colorProbe = null;
42
45
  var sharedKerningContext;
43
46
  var sharedWidthsByFont = /* @__PURE__ */ new Map();
47
+ var sharedAsciiWidthsByFont = /* @__PURE__ */ new Map();
48
+ var sharedPairWidthsByFont = /* @__PURE__ */ new Map();
44
49
  var cachedTextRuns = /* @__PURE__ */ new WeakMap();
50
+ var cachedBlockTemplates = /* @__PURE__ */ new WeakMap();
45
51
  var lastFontSetSize = -1;
46
52
  var TRANSPARENT_SRGBA = [
47
53
  0,
@@ -49,43 +55,13 @@ var TRANSPARENT_SRGBA = [
49
55
  0,
50
56
  0
51
57
  ];
52
- var parsedColors = /* @__PURE__ */ new Map([["transparent", TRANSPARENT_SRGBA], ["rgba(0, 0, 0, 0)", TRANSPARENT_SRGBA]]);
58
+ var STYLE_INSET_RE = /(?:^|;)\s*(?:left|top|right|bottom|inset)\s*:[^;]*/gi;
59
+ var STYLE_INSET_TEST_RE = /(?:^|;)\s*(?:left|top|right|bottom|inset)\s*:/i;
60
+ var SMALL_CAPS_RE = /(?:^|\s)small-caps(?:\s|$)/;
53
61
  function cssColorToSrgba(document, value, opacity) {
54
62
  if (opacity <= 0 || !value) return TRANSPARENT_SRGBA;
55
- let rgba = parsedColors.get(value);
56
- if (!rgba) {
57
- const functional = /rgba?\(([^)]+)\)/i.exec(value);
58
- if (functional) {
59
- const channels = functional[1].trim().split(/[\s,/]+/);
60
- const read = (i, max = 255) => {
61
- const v = channels[i];
62
- return v ? v.includes("%") ? parseFloat(v) / 100 : parseFloat(v) / max : max === 1 ? 1 : 0;
63
- };
64
- rgba = [
65
- read(0),
66
- read(1),
67
- read(2),
68
- read(3, 1)
69
- ];
70
- } else {
71
- colorProbe ??= document.createElement("canvas").getContext("2d", { willReadFrequently: true });
72
- if (!colorProbe) throw new Error("collectDomSnapshot: Canvas 2D is unavailable");
73
- colorProbe.fillStyle = "#000";
74
- colorProbe.fillStyle = value;
75
- colorProbe.clearRect(0, 0, 1, 1);
76
- colorProbe.fillRect(0, 0, 1, 1);
77
- const pixel = colorProbe.getImageData(0, 0, 1, 1).data;
78
- rgba = [
79
- pixel[0] / 255,
80
- pixel[1] / 255,
81
- pixel[2] / 255,
82
- pixel[3] / 255
83
- ];
84
- }
85
- if (parsedColors.size >= 1024) parsedColors.clear();
86
- parsedColors.set(value, rgba);
87
- }
88
- if (rgba[3] <= 0) return TRANSPARENT_SRGBA;
63
+ const rgba = parseCssColor(document, value, true);
64
+ if (!rgba || rgba[3] <= 0) return TRANSPARENT_SRGBA;
89
65
  return opacity === 1 ? rgba : [
90
66
  rgba[0],
91
67
  rgba[1],
@@ -96,7 +72,9 @@ function cssColorToSrgba(document, value, opacity) {
96
72
  var EMPTY_DECORATION_OWNERS = [];
97
73
  function canvasFont(style, bakeSize) {
98
74
  const rawStyle = style.fontStyle;
99
- 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();
75
+ const fontStyle = rawStyle === "italic" ? "italic " : rawStyle.startsWith("oblique") ? "oblique " : "";
76
+ const rawVariant = style.fontVariant;
77
+ return `${fontStyle}${rawVariant && rawVariant !== "normal" && SMALL_CAPS_RE.test(rawVariant) ? "small-caps " : ""}${style.fontWeight || "400"} ${bakeSize}px ${style.fontFamily}`.trim();
100
78
  }
101
79
  function fontMetrics(context, font, fontSize, cache) {
102
80
  let result = cache.get(font);
@@ -113,9 +91,9 @@ function fontMetrics(context, font, fontSize, cache) {
113
91
  * Chromium positions layout in 1/64ths of a layout pixel. Client rectangles are 32-bit
114
92
  * floats, so the slack grows with the coordinates themselves, not with their difference.
115
93
  */
116
- function offLayoutGrid(coordinate, origin, scale) {
117
- const units = (coordinate - origin) * 64 * scale;
118
- return Math.abs(units - Math.round(units)) > .02 + (Math.abs(coordinate) + Math.abs(origin)) * 64 * scale * 2 ** -22;
94
+ function offLayoutGrid(coordinate, origin, scale64, absOrigin) {
95
+ const units = (coordinate - origin) * scale64;
96
+ return Math.abs(units - Math.round(units)) > .02 + (Math.abs(coordinate) + absOrigin) * scale64 * INV_2_22;
119
97
  }
120
98
  function layoutDescents(context, boxHeights, scales, bakeSize, cache) {
121
99
  const candidates = [];
@@ -171,7 +149,7 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
171
149
  if (!Number.isFinite(pixelsPerUnit) || pixelsPerUnit <= 0) throw new RangeError("collectDomSnapshot: pixelsPerUnit must be a positive finite number");
172
150
  const invScale = 1 / pixelsPerUnit;
173
151
  const rootRect = root.getBoundingClientRect();
174
- const { left: rootLeft, bottom: rootBottom } = rootRect;
152
+ const { left: rootLeft, top: rootTop, bottom: rootBottom } = rootRect;
175
153
  if (rootRect.width <= 0 || rootRect.height <= 0) throw new Error("collectDomSnapshot: the source element has no layout box");
176
154
  if (options.layoutEngine !== void 0 && !["range", "pretext"].includes(options.layoutEngine)) throw new RangeError("collectDomSnapshot: layoutEngine must be 'range' or 'pretext'");
177
155
  const glyphs = [];
@@ -188,14 +166,45 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
188
166
  if (nativeBrowser && fonts.size !== lastFontSetSize) {
189
167
  lastFontSetSize = fonts.size;
190
168
  sharedWidthsByFont = /* @__PURE__ */ new Map();
169
+ sharedAsciiWidthsByFont = /* @__PURE__ */ new Map();
170
+ sharedPairWidthsByFont = /* @__PURE__ */ new Map();
191
171
  cachedTextRuns = /* @__PURE__ */ new WeakMap();
172
+ cachedBlockTemplates = /* @__PURE__ */ new WeakMap();
192
173
  }
174
+ const getContextDescriptor = Object.getOwnPropertyDescriptor(view.HTMLCanvasElement.prototype, "getContext")?.value;
175
+ const nativeCanvas = nativeBrowser && !(getContextDescriptor && "mock" in getContextDescriptor);
193
176
  let share = !svg && !("mock" in view.getComputedStyle);
194
- try {
195
- for (const s of root.getRootNode().styleSheets ?? []) for (const r of s.cssRules) if (/[:+~]/.test(r.cssText)) share = false;
196
- } catch {
197
- share = false;
198
- }
177
+ let shareChecked = false;
178
+ const hasNonShareableRule = (rules) => {
179
+ for (const r of rules) {
180
+ if ("selectorText" in r) {
181
+ if (/[:+~]|\[style\b/i.test(r.selectorText)) return true;
182
+ }
183
+ if ("cssRules" in r) {
184
+ if ("start" in r || hasNonShareableRule(r.cssRules)) return true;
185
+ } else if ("href" in r) return true;
186
+ }
187
+ return false;
188
+ };
189
+ const canShare = () => {
190
+ if (!share) return false;
191
+ if (!shareChecked) {
192
+ shareChecked = true;
193
+ try {
194
+ for (const s of root.getRootNode().styleSheets ?? []) {
195
+ if (s.disabled) continue;
196
+ if (hasNonShareableRule(s.cssRules)) {
197
+ share = false;
198
+ return false;
199
+ }
200
+ }
201
+ } catch {
202
+ share = false;
203
+ return false;
204
+ }
205
+ }
206
+ return share;
207
+ };
199
208
  const pathStyles = /* @__PURE__ */ new Map();
200
209
  const nodes = /* @__PURE__ */ new Map();
201
210
  const nodeOf = (el) => {
@@ -203,16 +212,33 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
203
212
  if (!rec) {
204
213
  const parent = el === root ? null : el.parentElement;
205
214
  const u = parent ? nodeOf(parent) : null;
206
- const hasAttrs = !attrOnly || el.hasAttributes();
215
+ const attrs = el.attributes;
216
+ const attrCount = attrs.length;
217
+ const hasAttrs = !attrOnly || attrCount > 0;
207
218
  let k = share && (el === root || u?.k !== void 0) ? `${u?.k ?? ""}>${el.localName}` : void 0;
208
- 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}`;
209
- const p = k ? pathStyles.get(k) : void 0;
219
+ let attrFlags = 0;
220
+ if (attrCount > 0) {
221
+ const buildK = k !== void 0 && el !== root;
222
+ for (let i = 0; i < attrCount; i++) {
223
+ const a = attrs[i];
224
+ const name = a.name;
225
+ if (name === "data-text-block" || name === "data-sdf-block") attrFlags |= 1;
226
+ else if (name === "data-text-ignore" || name === "data-sdf-ignore") attrFlags |= 2;
227
+ else if (name === DEPTH_ATTRIBUTE || name === LEGACY_DEPTH_ATTRIBUTE) attrFlags |= 4;
228
+ if (buildK) {
229
+ const value = a.value;
230
+ k = `${k}\u0001${name}=${name === "style" && value && STYLE_INSET_TEST_RE.test(value) ? value.replace(STYLE_INSET_RE, "") : value}`;
231
+ }
232
+ }
233
+ }
234
+ let p = k ? pathStyles.get(k) : void 0;
235
+ if (p !== void 0 && !canShare()) p = void 0;
210
236
  rec = {
211
237
  el,
212
238
  u,
213
- owner: hasAttrs && (defaultTextAttr ? el.hasAttribute("data-text-block") || el.hasAttribute("data-sdf-block") : el.matches(textSelector)) ? el : u?.owner ?? null,
214
- ig: (u?.ig ?? false) || hasAttrs && (defaultIgnoreAttr ? el.hasAttribute("data-text-ignore") || el.hasAttribute("data-sdf-ignore") : el.matches(ignoreSelector)),
215
- do: hasAttrs && (el.hasAttribute(DEPTH_ATTRIBUTE) || el.hasAttribute(LEGACY_DEPTH_ATTRIBUTE)) ? el : u?.do ?? null,
239
+ owner: hasAttrs && (defaultTextAttr ? (attrFlags & 1) !== 0 : el.matches(textSelector)) ? el : u?.owner ?? null,
240
+ ig: (u?.ig ?? false) || hasAttrs && (defaultIgnoreAttr ? (attrFlags & 2) !== 0 : el.matches(ignoreSelector)),
241
+ do: (attrFlags & 4) !== 0 ? el : u?.do ?? null,
216
242
  k,
217
243
  p
218
244
  };
@@ -239,11 +265,7 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
239
265
  return owner ? parsePx(owner.getAttribute(DEPTH_ATTRIBUTE) ?? owner.getAttribute(LEGACY_DEPTH_ATTRIBUTE), fallback) : fallback;
240
266
  };
241
267
  const isIgnored = (element) => nodeOf(element).ig;
242
- let shapeGroup = 0;
243
- const shapeBoxes = /* @__PURE__ */ new Map();
244
- const capturedSvgs = /* @__PURE__ */ new Set();
245
- const svgOptions = options.svg ? svg.resolveSvgOptions(options.svg) : null;
246
- const svgContext = svgOptions ? {
268
+ const svgRunner = svg ? svg.createSvgRunner(root, options.svg, {
247
269
  style: styleOf,
248
270
  opacity: opacityOf,
249
271
  displayNone,
@@ -252,23 +274,24 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
252
274
  requests,
253
275
  rootLeft,
254
276
  rootBottom,
255
- invScale,
256
- options: svgOptions,
257
- budget: { pathData: svgOptions.maxPathData ?? 1e6 }
258
- } : null;
259
- const captureShape = (element, blockIndex, clip, sequence) => {
260
- if (!svgContext || !svg || !element.matches(svgOptions.selector ?? "svg") && !(svgOptions.images && element.localName === "img")) return false;
261
- const ancestorSvg = element.parentElement?.closest("svg");
262
- if (ancestorSvg && root.contains(ancestorSvg)) return false;
263
- capturedSvgs.add(element);
264
- const capture = svg.captureSvg(element, svgContext);
265
- if (capture) {
266
- shapeBoxes.set(shapeGroup, capture.box);
267
- svg.appendSvg(capture, glyphs, blockIndex, shapeGroup++, clip, depthOf(element, options.textDepth ?? 1), sequence);
268
- }
277
+ invScale
278
+ }, depthOf, options.textDepth ?? 1, glyphs, textSelector, rootRect, blockLayouts) : null;
279
+ const blocks = [...root.matches(textSelector) ? [root] : [], ...root.querySelectorAll(textSelector)];
280
+ let activeBlock = null;
281
+ const filterState = { skippedNested: false };
282
+ const consumeSkipped = (state) => {
283
+ if (!state.skippedNested) return false;
284
+ state.skippedNested = false;
269
285
  return true;
270
286
  };
271
- const blocks = [...root.matches(textSelector) ? [root] : [], ...root.querySelectorAll(textSelector)];
287
+ const blockSet = blocks.length > 1 ? new Set(blocks) : null;
288
+ const nestedBlockFilter = blockSet ? (node) => {
289
+ if (node.nodeType === 1 && node !== activeBlock && blockSet.has(node)) {
290
+ filterState.skippedNested = true;
291
+ return 2;
292
+ }
293
+ return 1;
294
+ } : null;
272
295
  const layoutEngine = options.layoutEngine ?? "range";
273
296
  if (options.rtlReflow && layoutEngine !== "range") throw new RangeError("collectDomSnapshot: rtlReflow requires the Range layout engine");
274
297
  let range;
@@ -281,17 +304,44 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
281
304
  const boxHeights = /* @__PURE__ */ new Map();
282
305
  let offCssGrid = false;
283
306
  let offDeviceGrid = false;
284
- const offBox = (l, w, scale) => offLayoutGrid(l, rootLeft, scale) || offLayoutGrid(l + w, rootLeft, scale);
307
+ let gridDone = false;
308
+ const absRootLeft = Math.abs(rootLeft);
309
+ const scale64Device = 64 * deviceScale;
310
+ const offBox = (l, w, scale64) => offLayoutGrid(l, rootLeft, scale64, absRootLeft) || offLayoutGrid(l + w, rootLeft, scale64, absRootLeft);
285
311
  const trackLayoutGrid = (l, w) => {
286
- if (!offCssGrid) offCssGrid = offBox(l, w, 1);
287
- if (deviceScale !== 1 && !offDeviceGrid) offDeviceGrid = offBox(l, w, deviceScale);
312
+ if (gridDone) return;
313
+ if (!offCssGrid) offCssGrid = offBox(l, w, 64);
314
+ if (deviceScale !== 1 && !offDeviceGrid) offDeviceGrid = offBox(l, w, scale64Device);
315
+ if (offCssGrid && (deviceScale === 1 || offDeviceGrid)) gridDone = true;
288
316
  };
289
317
  const layoutScales = () => [...deviceScale === 1 || offDeviceGrid ? [] : [deviceScale], ...offCssGrid ? [] : [1]];
318
+ const measuresKerning = "OffscreenCanvas" in view;
319
+ let kerningContext;
320
+ let lastKerningFont = "";
321
+ const ensureKerningContext = () => {
322
+ if (kerningContext === void 0) {
323
+ kerningContext = (nativeBrowser ? sharedKerningContext : void 0) ?? new view.OffscreenCanvas(1, 1).getContext("2d");
324
+ if (kerningContext) kerningContext.letterSpacing = "0px";
325
+ if (nativeBrowser) sharedKerningContext = kerningContext;
326
+ }
327
+ return kerningContext;
328
+ };
329
+ const ensureFontProbe = () => {
330
+ if (fontProbe === void 0) {
331
+ if (nativeCanvas) {
332
+ const probe = ensureKerningContext();
333
+ if (probe) return fontProbe = probe;
334
+ }
335
+ fontProbe = document.createElement("canvas").getContext("2d");
336
+ }
337
+ return fontProbe;
338
+ };
290
339
  const readDecorations = (parent, layoutFont, fontSize, opacity) => {
291
340
  const owners = decorationsOf(parent);
292
341
  if (owners.length === 0) return EMPTY_DECORATION_OWNERS;
293
- fontProbe ??= document.createElement("canvas").getContext("2d");
294
- const [ascent, descent] = fontProbe ? fontMetrics(fontProbe, layoutFont, fontSize, metricsByFont) : [fontSize * .8, fontSize * .2];
342
+ const probe = ensureFontProbe();
343
+ const [ascent, descent] = probe ? fontMetrics(probe, layoutFont, fontSize, metricsByFont) : [fontSize * .8, fontSize * .2];
344
+ if (probe && probe === kerningContext) lastKerningFont = "";
295
345
  const result = [];
296
346
  for (const owner of owners) {
297
347
  const style = styleOf(owner);
@@ -320,10 +370,12 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
320
370
  const capturedKeys = /* @__PURE__ */ new Map();
321
371
  const fontEntries = /* @__PURE__ */ new Map();
322
372
  const fontRequestKey = (font) => options.textBackend === "windfoil" && font.opticalSizing === "auto" ? `${font.key}|${font.size}` : font.key;
323
- const requestKey = (font, keys, character) => {
324
- let key = keys.get(character);
373
+ const requestKey = (font, keys, character, asciiKeys) => {
374
+ const code = asciiKeys && character.length === 1 ? character.charCodeAt(0) : -1;
375
+ let key = code >= 0 && code < 128 ? asciiKeys[code] : keys.get(character);
325
376
  if (key === void 0) {
326
377
  key = `${fontRequestKey(font)}\u0000${character}`;
378
+ if (code >= 0 && code < 128) asciiKeys[code] = key;
327
379
  keys.set(character, key);
328
380
  requests.set(key, {
329
381
  key,
@@ -333,21 +385,34 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
333
385
  }
334
386
  return key;
335
387
  };
336
- const measuresKerning = "OffscreenCanvas" in view;
337
- let kerningContext;
338
- let lastKerningFont = "";
339
- const canvasWidth = (cssFont, widths, text) => {
388
+ const measureCanvasWidth = (cssFont, text) => {
389
+ const ctx = ensureKerningContext();
390
+ if (!ctx) return 0;
391
+ if (lastKerningFont !== cssFont) ctx.font = lastKerningFont = cssFont;
392
+ return ctx.measureText(text).width;
393
+ };
394
+ const canvasWidth = (cssFont, widths, asciiWidths, text) => {
395
+ const code = text.length === 1 ? text.charCodeAt(0) : -1;
396
+ if (code >= 0 && code < 128) {
397
+ const width = asciiWidths[code];
398
+ return width >= 0 ? width : asciiWidths[code] = measureCanvasWidth(cssFont, text);
399
+ }
340
400
  let width = widths.get(text);
341
- if (width === void 0) {
342
- if (kerningContext === void 0) {
343
- kerningContext = (nativeBrowser ? sharedKerningContext : void 0) ?? new view.OffscreenCanvas(1, 1).getContext("2d");
344
- if (kerningContext) kerningContext.letterSpacing = "0px";
345
- if (nativeBrowser) sharedKerningContext = kerningContext;
346
- }
347
- if (kerningContext && lastKerningFont !== cssFont) kerningContext.font = lastKerningFont = cssFont;
348
- width = kerningContext?.measureText(text).width ?? 0;
349
- widths.set(text, width);
401
+ if (width === void 0) widths.set(text, width = measureCanvasWidth(cssFont, text));
402
+ return width;
403
+ };
404
+ const canvasPairWidth = (cssFont, widths, pairWidths, first, second) => {
405
+ const c0 = first.length === 1 ? first.charCodeAt(0) : -1;
406
+ const c1 = second.length === 1 ? second.charCodeAt(0) : -1;
407
+ if (c0 >= 0 && c0 < 128 && c1 >= 0 && c1 < 128) {
408
+ const pairKey = c0 << 7 | c1;
409
+ let width = pairWidths.get(pairKey);
410
+ if (width === void 0) pairWidths.set(pairKey, width = measureCanvasWidth(cssFont, first + second));
411
+ return width;
350
412
  }
413
+ const text = first + second;
414
+ let width = widths.get(text);
415
+ if (width === void 0) widths.set(text, width = measureCanvasWidth(cssFont, text));
351
416
  return width;
352
417
  };
353
418
  const resolveFont = (style) => {
@@ -364,17 +429,7 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
364
429
  const featureSettings = or(style.fontFeatureSettings);
365
430
  const variationSettings = or(style.fontVariationSettings);
366
431
  const opticalSizing = or(style.fontOpticalSizing, "auto");
367
- const key = [
368
- family,
369
- weight,
370
- fontStyle,
371
- stretch,
372
- variant,
373
- kerning,
374
- featureSettings,
375
- variationSettings,
376
- opticalSizing
377
- ].join("|");
432
+ const key = `${family}|${weight}|${fontStyle}|${stretch}|${variant}|${kerning}|${featureSettings}|${variationSettings}|${opticalSizing}`;
378
433
  const size = parsePx(style.fontSize, 16);
379
434
  const cacheKey = `${key}\u0000${size}`;
380
435
  entry = fontEntries.get(cacheKey);
@@ -394,20 +449,40 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
394
449
  size
395
450
  };
396
451
  const reqKey = fontRequestKey(font);
397
- let keys = capturedKeys.get(reqKey);
398
- if (!keys) capturedKeys.set(reqKey, keys = /* @__PURE__ */ new Map());
452
+ let captured = capturedKeys.get(reqKey);
453
+ if (!captured) {
454
+ captured = [/* @__PURE__ */ new Map(), new Array(128)];
455
+ capturedKeys.set(reqKey, captured);
456
+ }
457
+ const [keys, asciiKeys] = captured;
399
458
  const layoutFont = font.canvasFont.replace(`${bakeSize}px`, `${size}px`);
400
459
  let widths = nativeBrowser ? sharedWidthsByFont.get(layoutFont) : void 0;
401
- if (!widths) {
402
- widths = /* @__PURE__ */ new Map();
403
- if (nativeBrowser) sharedWidthsByFont.set(layoutFont, widths);
460
+ let asciiWidths = nativeBrowser ? sharedAsciiWidthsByFont.get(layoutFont) : void 0;
461
+ let pairWidths = nativeBrowser ? sharedPairWidthsByFont.get(layoutFont) : void 0;
462
+ if (!widths || !asciiWidths || !pairWidths) {
463
+ if (nativeBrowser && sharedWidthsByFont.size >= MAX_SHARED_FONT_CACHES) {
464
+ sharedWidthsByFont.clear();
465
+ sharedAsciiWidthsByFont.clear();
466
+ sharedPairWidthsByFont.clear();
467
+ }
468
+ widths ??= /* @__PURE__ */ new Map();
469
+ asciiWidths ??= (/* @__PURE__ */ new Float64Array(128)).fill(-1);
470
+ pairWidths ??= /* @__PURE__ */ new Map();
471
+ if (nativeBrowser) {
472
+ sharedWidthsByFont.set(layoutFont, widths);
473
+ sharedAsciiWidthsByFont.set(layoutFont, asciiWidths);
474
+ sharedPairWidthsByFont.set(layoutFont, pairWidths);
475
+ }
404
476
  }
405
477
  entry = [
406
478
  font,
407
479
  keys,
408
480
  layoutFont,
409
481
  widths,
410
- measuresKerning ? canvasWidth(layoutFont, widths, " ") : 0
482
+ measuresKerning ? canvasWidth(layoutFont, widths, asciiWidths, " ") : 0,
483
+ asciiKeys,
484
+ asciiWidths,
485
+ pairWidths
411
486
  ];
412
487
  fontEntries.set(cacheKey, entry);
413
488
  }
@@ -419,7 +494,7 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
419
494
  if (isHidden(style)) return null;
420
495
  const opacity = opacityOf(parent);
421
496
  if (opacity <= 0) return null;
422
- const [font, keys, layoutFont, widths, space] = resolveFont(style);
497
+ const [font, keys, layoutFont, widths, space, asciiKeys, asciiWidths, pairWidths] = resolveFont(style);
423
498
  const spacing = parsePx(style.letterSpacing, 0, font.size);
424
499
  const wordSpacing = parsePx(style.wordSpacing, 0, font.size);
425
500
  const whiteSpace = style.whiteSpace;
@@ -427,9 +502,12 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
427
502
  decorations: readDecorations(parent, layoutFont, font.size, opacity),
428
503
  font,
429
504
  keys,
505
+ asciiKeys,
430
506
  fontSize: font.size * invScale,
431
507
  layoutFont,
432
508
  widths,
509
+ asciiWidths,
510
+ pairWidths,
433
511
  letterSpacing: spacing,
434
512
  wordSpacing,
435
513
  space: space && (space + spacing + wordSpacing) * invScale,
@@ -440,22 +518,25 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
440
518
  };
441
519
  };
442
520
  const transformSeed = (node, transform) => transform.caseMap === "capitalize" ? precedingCharacter(node, styleOf) : void 0;
443
- const expansionBoxes = (share, box, font) => {
521
+ const expansionBoxes = (share, bLeft, bTop, bBottom, bWidth, bHeight, font) => {
444
522
  if (share.length <= (share.codePointAt(0) > 65535 ? 2 : 1)) return void 0;
445
523
  const parts = Array.from(share);
446
- fontProbe ??= document.createElement("canvas").getContext("2d");
447
- if (fontProbe) fontProbe.font = font.canvasFont;
448
- const advances = parts.map((part) => /^\p{M}/u.test(part) ? 0 : fontProbe?.measureText(part).width ?? 1);
524
+ const probe = ensureFontProbe();
525
+ if (probe) {
526
+ probe.font = font.canvasFont;
527
+ if (probe === kerningContext) lastKerningFont = "";
528
+ }
529
+ const advances = parts.map((part) => /^\p{M}/u.test(part) ? 0 : probe?.measureText(part).width ?? 1);
449
530
  const total = advances.reduce((sum, advance) => sum + advance, 0);
450
- let left = box.left;
531
+ let left = bLeft;
451
532
  return parts.map((c, index) => {
452
- const width = total > 0 ? box.width * advances[index] / total : box.width / parts.length;
533
+ const width = total > 0 ? bWidth * advances[index] / total : bWidth / parts.length;
453
534
  const item = {
454
535
  left,
455
- top: box.top,
456
- bottom: box.bottom,
536
+ top: bTop,
537
+ bottom: bBottom,
457
538
  width,
458
- height: box.height,
539
+ height: bHeight,
459
540
  c
460
541
  };
461
542
  left += width;
@@ -480,6 +561,27 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
480
561
  const paintLines = [];
481
562
  const lineTops = [];
482
563
  const sequences = /* @__PURE__ */ new Map();
564
+ const blockStyleOf = (el, rec = nodeOf(el)) => {
565
+ if (rec.blk) return rec.blk;
566
+ if (rec.p) return rec.blk = blockStyleOf(rec.p.el, rec.p);
567
+ const blockStyle = styleOf(el, rec);
568
+ const overflow = blockStyle.overflow;
569
+ const rtl = blockStyle.direction === "rtl";
570
+ const align = physicalAlign(blockStyle.textAlign, rtl);
571
+ const lastValue = blockStyle.textAlignLast;
572
+ const lastAlign = physicalAlign(lastValue && lastValue !== "auto" ? lastValue : align === "justify" ? "" : align, rtl);
573
+ return rec.blk = {
574
+ overflowX: blockStyle.overflowX || overflow || "visible",
575
+ overflowY: blockStyle.overflowY || overflow || "visible",
576
+ insetLeft: inset(blockStyle, "Left"),
577
+ insetRight: inset(blockStyle, "Right"),
578
+ rtl,
579
+ align,
580
+ lastAlign,
581
+ justified: align === "justify" || lastAlign === "justify",
582
+ lineHeightRaw: blockStyle.lineHeight
583
+ };
584
+ };
483
585
  const toRect = (b) => [
484
586
  (b.left - rootLeft) * invScale,
485
587
  (rootBottom - b.bottom) * invScale,
@@ -490,36 +592,93 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
490
592
  const block = blocks[blockIndex];
491
593
  blockLayouts[blockIndex] = EMPTY_BLOCK;
492
594
  if (isIgnored(block) || displayNone(block)) continue;
493
- const blockStyle = styleOf(block);
494
595
  const blockRect = block.getBoundingClientRect();
495
596
  if (blockRect.width <= 0 || blockRect.height <= 0) continue;
496
- const overflow = blockStyle.overflow;
497
- const overflowX = blockStyle.overflowX || overflow || "visible";
498
- const overflowY = blockStyle.overflowY || overflow || "visible";
499
- const insetLeft = inset(blockStyle, "Left");
500
- const insetRight = inset(blockStyle, "Right");
501
- const rtl = blockStyle.direction === "rtl";
502
- const align = physicalAlign(blockStyle.textAlign, rtl);
503
- const lastValue = blockStyle.textAlignLast;
504
- const lastAlign = physicalAlign(lastValue && lastValue !== "auto" ? lastValue : align === "justify" ? "" : align, rtl);
505
- const justified = align === "justify" || lastAlign === "justify";
506
- const lineHeightRaw = blockStyle.lineHeight;
597
+ const relBlockRect = {
598
+ left: blockRect.left - rootLeft,
599
+ top: blockRect.top - rootTop,
600
+ width: blockRect.width,
601
+ height: blockRect.height
602
+ };
603
+ const { overflowX, overflowY, insetLeft, insetRight, rtl, align, lastAlign, justified, lineHeightRaw } = blockStyleOf(block);
507
604
  const clip = toRect(blockRect);
508
- const layoutClip = [...clip];
605
+ const layoutClip = [
606
+ clip[0],
607
+ clip[1],
608
+ clip[2],
609
+ clip[3]
610
+ ];
509
611
  let minLeft = blockRect.left;
510
612
  let maxRight = blockRect.right;
511
613
  let minTop = blockRect.top;
512
614
  let maxBottom = blockRect.bottom;
513
- const includeTextBox = (box) => {
514
- if (box.left < minLeft) minLeft = box.left;
515
- if (box.left + box.width > maxRight) maxRight = box.left + box.width;
516
- if (box.top < minTop) minTop = box.top;
517
- if (box.bottom > maxBottom) maxBottom = box.bottom;
615
+ const includeTextBox = (left, top, bottom, width) => {
616
+ if (left < minLeft) minLeft = left;
617
+ if (left + width > maxRight) maxRight = left + width;
618
+ if (top < minTop) minTop = top;
619
+ if (bottom > maxBottom) maxBottom = bottom;
518
620
  };
621
+ const includeTextBoxObj = (box) => includeTextBox(box.left, box.top, box.bottom, box.width);
519
622
  const blockStart = glyphs.length;
520
623
  const lineCountBefore = lineCount;
521
624
  let blockLeft = clip[0] + insetLeft * invScale;
522
625
  let blockWidth = clip[2] - clip[0] - (insetLeft + insetRight) * invScale;
626
+ let templateKey = "";
627
+ let templateTextNode = null;
628
+ let templateText = "";
629
+ let templateBoxHeight = 0;
630
+ const canTemplate = layoutEngine === "range" && nativeBrowser && !options.reshape && !options.svg && !options.pixelSnap && !block.firstElementChild && block.firstChild !== null && block.firstChild === block.lastChild && block.firstChild.nodeType === 3;
631
+ const templateBoxes = canTemplate && measuresBaselines ? [] : null;
632
+ if (canTemplate) {
633
+ const parentRec = resolveParent(block);
634
+ const inline = parentRec.inline;
635
+ if (inline && parentRec.owner === block && !inline.transform && inline.decorations.length === 0) {
636
+ const templateFont = inline.font;
637
+ templateTextNode = block.firstChild;
638
+ templateText = templateTextNode.data;
639
+ const c = inline.color;
640
+ templateKey = `${rootRect.height}|${block.scrollLeft}|${block.scrollTop}|${invScale}|${bakeSize}|${!!options.cjkLineBreaking}|${!!options.rtlReflow}|${options.textBackend ?? "sdf"}|${inline.layoutFont}|${templateFont.key}|${inline.letterSpacing}|${inline.wordSpacing}|${inline.z}|${inline.keepsSpaces}|${c[0]},${c[1]},${c[2]},${c[3]}|${overflowX}|${overflowY}|${insetLeft}|${insetRight}|${rtl}|${align}|${lastAlign}|${lineHeightRaw}`;
641
+ const tmpl = cachedBlockTemplates.get(block);
642
+ if (tmpl?.n === templateTextNode && tmpl.s === templateText && tmpl.v === templateKey && sameBox(relBlockRect, tmpl.r)) {
643
+ for (let i = 0; i < 4; i++) clip[i] = tmpl.c[i];
644
+ const tGlyphs = tmpl.g;
645
+ for (let i = 0, len = tGlyphs.length; i < len; i++) glyphs.push({
646
+ ...tGlyphs[i],
647
+ block: blockIndex,
648
+ clip,
649
+ color: c
650
+ });
651
+ const tq = tmpl.q;
652
+ for (let i = 0; i < tq.length; i += 2) {
653
+ const key = tq[i];
654
+ if (!requests.has(key)) requests.set(key, {
655
+ key,
656
+ character: tq[i + 1],
657
+ font: templateFont
658
+ });
659
+ }
660
+ if (measuresBaselines) {
661
+ const tBoxes = tmpl.b;
662
+ if (tBoxes) for (let i = 0; i < tBoxes.length; i += 2) trackLayoutGrid(tBoxes[i] + rootLeft, tBoxes[i + 1]);
663
+ if (tmpl.bh > 0) {
664
+ textRuns.push([
665
+ templateFont,
666
+ blockStart,
667
+ glyphs.length
668
+ ]);
669
+ if (!boxHeights.has(templateFont)) boxHeights.set(templateFont, tmpl.bh);
670
+ }
671
+ }
672
+ lineCount += tmpl.l;
673
+ if (tGlyphs.length > 0) blockLayouts[blockIndex] = {
674
+ ...tmpl.bl,
675
+ clip: layoutClip
676
+ };
677
+ afterSpace = true;
678
+ continue;
679
+ }
680
+ }
681
+ }
523
682
  if (appendBrowserRuns) {
524
683
  const lineKeys = /* @__PURE__ */ new Set();
525
684
  appendBrowserRuns(block, {
@@ -538,11 +697,11 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
538
697
  requests,
539
698
  lineKeys,
540
699
  lineSequences: /* @__PURE__ */ new Map(),
541
- ...svg ? { svg: (element, sequence) => {
542
- captureShape(element, blockIndex, clip, sequence);
700
+ ...svgRunner ? { svg: (element, sequence) => {
701
+ svgRunner.capture(element, blockIndex, clip, sequence);
543
702
  } } : {},
544
703
  box: (font, box) => {
545
- includeTextBox(box);
704
+ includeTextBoxObj(box);
546
705
  if (measuresBaselines) {
547
706
  trackLayoutGrid(box.left, box.width);
548
707
  if (!boxHeights.has(font)) boxHeights.set(font, box.height);
@@ -562,12 +721,22 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
562
721
  } else if (layoutEngine === "range") {
563
722
  range ??= document.createRange();
564
723
  sequences.clear();
724
+ let hasLastSeq = false;
725
+ let lastSeqKey = 0;
726
+ let lastSeqNext = 0;
565
727
  const nextSequence = (lineKey) => {
728
+ if (hasLastSeq && lineKey === lastSeqKey) return lastSeqNext++;
729
+ if (hasLastSeq) sequences.set(lastSeqKey, lastSeqNext);
730
+ hasLastSeq = true;
731
+ lastSeqKey = lineKey;
566
732
  const seq = sequences.get(lineKey) ?? 0;
567
- sequences.set(lineKey, seq + 1);
733
+ lastSeqNext = seq + 1;
734
+ sequences.set(lineKey, lastSeqNext);
568
735
  return seq;
569
736
  };
570
- const walker = block.firstElementChild ? document.createTreeWalker(block, 5) : null;
737
+ activeBlock = block;
738
+ filterState.skippedNested = false;
739
+ const walker = block.firstElementChild ? document.createTreeWalker(block, 5, nestedBlockFilter) : null;
571
740
  let markAnchorLineKey = 0;
572
741
  let hasMarkAnchor = false;
573
742
  let previousCharacter = "";
@@ -582,12 +751,16 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
582
751
  let nodeIndex = 0;
583
752
  let node = walker ? walker.nextNode() : block.firstChild;
584
753
  for (; node; node = walker ? walker.nextNode() : node.nextSibling) {
754
+ if (consumeSkipped(filterState)) {
755
+ hasMarkAnchor = false;
756
+ previousCharacter = "";
757
+ }
585
758
  nodeIndex++;
586
759
  if (node.nodeType !== 3) {
587
760
  if (!walker) continue;
588
761
  const element = node;
589
762
  const shapeStart = glyphs.length;
590
- if (svg && nodeOf(element).owner === block && captureShape(element, blockIndex, clip, (glyphs[glyphs.length - 1]?.sequence ?? -1) + 1)) {
763
+ if (svgRunner && nodeOf(element).owner === block && svgRunner.capture(element, blockIndex, clip, (glyphs[glyphs.length - 1]?.sequence ?? -1) + 1)) {
591
764
  const last = glyphs[glyphs.length - 1];
592
765
  if (last?.shapeGroup !== void 0) {
593
766
  const sequence = nextSequence(hasMarkAnchor ? markAnchorLineKey : Math.round(element.getBoundingClientRect().top * 4));
@@ -612,7 +785,7 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
612
785
  previousCharacter = "";
613
786
  continue;
614
787
  }
615
- const { font, keys, fontSize, layoutFont, widths, letterSpacing, wordSpacing, space, keepsSpaces, color, z, decorations, transform } = record.inline;
788
+ const { font, keys, asciiKeys, fontSize, layoutFont, widths, asciiWidths, pairWidths, letterSpacing, wordSpacing, space, keepsSpaces, color, z, decorations, transform } = record.inline;
616
789
  let utf16Offset = 0;
617
790
  let textData = textNode.data;
618
791
  let shown = transform ? transformClusters(textData, transform, transformSeed(textNode, transform)) : void 0;
@@ -624,7 +797,6 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
624
797
  if (shown) shown = shown.map((share) => reshaped.slice(end, end += share.length));
625
798
  else textData = reshaped;
626
799
  }
627
- const emojiText = isEmojiCandidate(textData);
628
800
  const runStart = glyphs.length;
629
801
  let boxHeight = 0;
630
802
  let clusterIndex = 0;
@@ -636,72 +808,207 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
636
808
  let hit;
637
809
  let canSync = false;
638
810
  let synced = false;
811
+ let syncSource;
812
+ let syncDelta = 0;
813
+ let prevRects;
814
+ let prevDelta = 0;
815
+ let suffixStart = Infinity;
816
+ let prevBmp = false;
817
+ let emojiText;
818
+ let clusters;
819
+ let rawString;
639
820
  if (nativeBrowser && !shown && !options.reshape && !options.svg) {
640
- const runKey = `${nodeIndex}|${blockRect.width}|${textData}|${layoutFont}|${letterSpacing}|${wordSpacing}`;
641
- hit = cachedTextRuns.get(textNode);
642
- if (hit?.[0] === runKey && sameBox(blockRect, hit[2])) {
821
+ const styleKey = `${nodeIndex}|${blockRect.width}|${block.scrollLeft}|${block.scrollTop}|${layoutFont}|${letterSpacing}|${wordSpacing}`;
822
+ const prevHit = cachedTextRuns.get(textNode);
823
+ if (prevHit?.styleKey === styleKey && prevHit.text === textData && sameBox(relBlockRect, prevHit.blockRect)) {
824
+ hit = prevHit;
825
+ emojiText = prevHit.emojiText;
826
+ clusters = prevHit.clusters;
827
+ rawString = prevHit.rawString;
643
828
  canSync = true;
644
829
  synced = blockSynced;
830
+ syncSource = prevHit.rects;
645
831
  } else {
646
832
  blockSynced = false;
647
- cachedTextRuns.set(textNode, hit = [
648
- runKey,
649
- [],
650
- void 0
651
- ]);
833
+ emojiText = isEmojiCandidate(textData);
834
+ clusters = glyphClusters(textData);
835
+ rawString = typeof clusters === "string";
836
+ if (prevHit?.styleKey === styleKey && prevHit.rawString && rawString && prevHit.bmp && sameBox(relBlockRect, prevHit.blockRect)) {
837
+ const prevText = prevHit.text;
838
+ const nA = prevText.length;
839
+ const nB = textData.length;
840
+ const minLen = nA < nB ? nA : nB;
841
+ let tail = 0;
842
+ while (tail < minLen && prevText.charCodeAt(nA - 1 - tail) === textData.charCodeAt(nB - 1 - tail)) tail++;
843
+ if (tail > 2) {
844
+ suffixStart = nB - tail;
845
+ prevRects = prevHit.rects;
846
+ prevDelta = nA - nB;
847
+ prevBmp = true;
848
+ }
849
+ }
850
+ cachedTextRuns.set(textNode, hit = {
851
+ styleKey,
852
+ text: textData,
853
+ rects: new Float64Array(textData.length * 5),
854
+ blockRect: void 0,
855
+ emojiText,
856
+ rawString,
857
+ clusters,
858
+ bmp: false
859
+ });
860
+ syncSource = hit.rects;
652
861
  }
862
+ } else {
863
+ emojiText = isEmojiCandidate(textData);
864
+ clusters = glyphClusters(textData);
865
+ rawString = typeof clusters === "string";
653
866
  }
654
- const rects = hit?.[1];
867
+ const rects = hit?.rects;
868
+ let bmp = rawString;
869
+ const clusterArr = rawString ? null : clusters;
870
+ const totalItems = rawString ? textData.length : clusterArr.length;
871
+ let pos = 0;
655
872
  let ci = -1;
656
- for (const cluster of glyphClusters(textData)) {
873
+ while (pos < totalItems) {
657
874
  ci++;
658
- const share = shown ? shown[clusterIndex++] : cluster;
659
- const nextOffset = utf16Offset + cluster.length;
660
- if (share === " " || share.length === 1 && share.charCodeAt(0) >= 9 && /^\s$/u.test(share)) {
661
- if (share === " " || !/[\u2007\u202f\ufeff]/.test(share)) {
875
+ let cluster;
876
+ let step;
877
+ let isPrintableAscii = false;
878
+ if (rawString) {
879
+ const c0 = textData.charCodeAt(pos);
880
+ if (!shown && (c0 === 32 || c0 >= 9 && c0 <= 13)) {
662
881
  if (!gap || keepsSpaces) gap += space;
663
- if (share !== "\xA0") afterSpace = true;
882
+ afterSpace = true;
883
+ hasMarkAnchor = hasKernPrevious = false;
884
+ previousCharacter = "";
885
+ pos++;
886
+ utf16Offset++;
887
+ continue;
664
888
  }
665
- hasMarkAnchor = hasKernPrevious = false;
666
- previousCharacter = "";
667
- utf16Offset = nextOffset;
668
- continue;
889
+ if (c0 >= 33 && c0 <= 126) {
890
+ step = 1;
891
+ cluster = SINGLE_CHAR[c0];
892
+ isPrintableAscii = true;
893
+ } else if (c0 >= 55296 && c0 <= 56319 && pos + 1 < totalItems && textData.charCodeAt(pos + 1) >= 56320 && textData.charCodeAt(pos + 1) <= 57343) {
894
+ step = 2;
895
+ bmp = false;
896
+ cluster = textData.slice(pos, pos + 2);
897
+ } else {
898
+ step = 1;
899
+ cluster = c0 < 128 ? SINGLE_CHAR[c0] : textData[pos];
900
+ }
901
+ } else {
902
+ step = 1;
903
+ cluster = clusterArr[pos];
669
904
  }
670
- if (!share) {
671
- hasKernPrevious = false;
672
- utf16Offset = nextOffset;
673
- continue;
905
+ pos += step;
906
+ const share = shown ? shown[clusterIndex++] : cluster;
907
+ const nextOffset = utf16Offset + cluster.length;
908
+ if (!isPrintableAscii || shown) {
909
+ const sc = share.length === 1 ? share.charCodeAt(0) : -1;
910
+ if (sc === 32 || sc === 160 || sc >= 9 && (sc <= 13 || sc > 126 && /^\s$/u.test(share))) {
911
+ if (sc === 32 || sc <= 13 || sc !== 8199 && sc !== 8239 && sc !== 65279) {
912
+ if (!gap || keepsSpaces) gap += space;
913
+ if (sc !== 160) afterSpace = true;
914
+ }
915
+ hasMarkAnchor = hasKernPrevious = false;
916
+ previousCharacter = "";
917
+ utf16Offset = nextOffset;
918
+ continue;
919
+ }
920
+ if (!share) {
921
+ hasKernPrevious = false;
922
+ utf16Offset = nextOffset;
923
+ continue;
924
+ }
674
925
  }
675
- let r;
676
- if (rects && synced) r = rects[ci];
677
- else {
926
+ let bLeft;
927
+ let bTop;
928
+ let bBottom;
929
+ let bWidth;
930
+ let bHeight;
931
+ const boxOff = ci * 5;
932
+ if (rects && synced) {
933
+ const sOff = (ci + syncDelta) * 5;
934
+ const rLeft = syncSource[sOff];
935
+ const rTop = syncSource[sOff + 1];
936
+ const rBottom = syncSource[sOff + 2];
937
+ bLeft = rLeft + rootLeft;
938
+ bTop = rTop + rootTop;
939
+ bBottom = rBottom + rootTop;
940
+ bWidth = syncSource[sOff + 3];
941
+ bHeight = syncSource[sOff + 4];
942
+ if (syncSource !== rects) {
943
+ rects[boxOff] = rLeft;
944
+ rects[boxOff + 1] = rTop;
945
+ rects[boxOff + 2] = rBottom;
946
+ rects[boxOff + 3] = bWidth;
947
+ rects[boxOff + 4] = bHeight;
948
+ }
949
+ } else {
678
950
  range.setEnd(textNode, nextOffset);
679
951
  range.setStart(textNode, utf16Offset);
680
952
  const d = range.getBoundingClientRect();
681
- r = {
682
- left: d.left,
683
- top: d.top,
684
- bottom: d.bottom,
685
- width: d.width,
686
- height: d.height
687
- };
953
+ bLeft = d.left;
954
+ bTop = d.top;
955
+ bBottom = d.bottom;
956
+ bWidth = d.width;
957
+ bHeight = d.height;
688
958
  if (rects) {
689
- if (canSync && sameBox(r, rects[ci])) synced = true;
690
- else rects[ci] = r;
959
+ const rLeft = bLeft - rootLeft;
960
+ const rTop = bTop - rootTop;
961
+ const rBottom = bBottom - rootTop;
962
+ if (canSync && rects[boxOff] === rLeft && rects[boxOff + 1] === rTop && rects[boxOff + 3] === bWidth && rects[boxOff + 4] === bHeight) {
963
+ synced = true;
964
+ syncSource = rects;
965
+ syncDelta = 0;
966
+ } else {
967
+ rects[boxOff] = rLeft;
968
+ rects[boxOff + 1] = rTop;
969
+ rects[boxOff + 2] = rBottom;
970
+ rects[boxOff + 3] = bWidth;
971
+ rects[boxOff + 4] = bHeight;
972
+ if (!textNode.nextSibling && (parent === block || parent !== null && !parent.nextSibling) && prevRects && prevBmp && !justified && pos - 1 > suffixStart + 1 && ci === pos - 1) {
973
+ const prevGlyph = glyphs[glyphs.length - 1];
974
+ if (prevGlyph?.block === blockIndex && prevGlyph.lineBottom !== (rootBottom - bBottom) * invScale || align === "left" && !rtl) {
975
+ const pOff = (ci + prevDelta) * 5;
976
+ if (pOff >= 0 && prevRects[pOff] === rLeft && prevRects[pOff + 1] === rTop && prevRects[pOff + 3] === bWidth && prevRects[pOff + 4] === bHeight) {
977
+ synced = true;
978
+ syncSource = prevRects;
979
+ syncDelta = prevDelta;
980
+ }
981
+ }
982
+ }
983
+ }
691
984
  }
692
985
  }
693
986
  utf16Offset = nextOffset;
694
- if (measuresBaselines) trackLayoutGrid(r.left, r.width);
695
- const parts = share === cluster ? void 0 : expansionBoxes(share, r, font);
696
- for (let part = 0, partLen = parts ? parts.length : 1; part < partLen; part++) {
697
- const box = parts ? parts[part] : r;
698
- const character = parts ? parts[part].c : share;
699
- const { left: bLeft, top: bTop, bottom: bBottom, width: bWidth, height: bHeight } = box;
700
- if (bWidth <= 0 || bHeight <= 0) {
987
+ if (measuresBaselines) trackLayoutGrid(bLeft, bWidth);
988
+ const parts = !shown || share === cluster ? void 0 : expansionBoxes(share, bLeft, bTop, bBottom, bWidth, bHeight, font);
989
+ if (templateBoxes && !parts && bWidth > 0 && bHeight > 0) templateBoxes.push(bLeft - rootLeft, bWidth);
990
+ const partLen = parts ? parts.length : 1;
991
+ for (let part = 0; part < partLen; part++) {
992
+ let pLeft = bLeft;
993
+ let pTop = bTop;
994
+ let pBottom = bBottom;
995
+ let pWidth = bWidth;
996
+ let pHeight = bHeight;
997
+ let character = share;
998
+ if (parts) {
999
+ const box = parts[part];
1000
+ pLeft = box.left;
1001
+ pTop = box.top;
1002
+ pBottom = box.bottom;
1003
+ pWidth = box.width;
1004
+ pHeight = box.height;
1005
+ character = box.c;
1006
+ }
1007
+ if (pWidth <= 0 || pHeight <= 0) {
701
1008
  const previous = glyphs[glyphs.length - 1];
702
1009
  hasKernPrevious = false;
703
1010
  if (!hasMarkAnchor || !previous || !/^\p{M}/u.test(character)) continue;
704
- const key = requestKey(font, keys, character);
1011
+ const key = requestKey(font, keys, character, asciiKeys);
705
1012
  const sequence = nextSequence(markAnchorLineKey);
706
1013
  if (options.pixelSnap) paintLines[glyphs.length] = paintLines[glyphs.length - 1];
707
1014
  glyphs.push({
@@ -720,43 +1027,43 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
720
1027
  });
721
1028
  continue;
722
1029
  }
723
- includeTextBox(box);
724
- const key = requestKey(font, keys, character);
1030
+ includeTextBox(pLeft, pTop, pBottom, pWidth);
1031
+ const key = requestKey(font, keys, character, asciiKeys);
725
1032
  const previous = glyphs[glyphs.length - 1];
726
1033
  const sameBlock = previous?.block === blockIndex;
727
1034
  const emoji = emojiText && isEmojiCandidate(character);
728
- const sharesLine = sameBlock && hasPrevBounds && Math.min(bBottom, prevBottom) - Math.max(bTop, prevTop) > Math.min(bHeight, prevHeight) * .5;
1035
+ const sharesLine = sameBlock && hasPrevBounds && Math.min(pBottom, prevBottom) - Math.max(pTop, prevTop) > Math.min(pHeight, prevHeight) * .5;
729
1036
  const sameEmojiLine = sharesLine && (emoji || previousEmoji);
730
- const lineKey = sameEmojiLine ? markAnchorLineKey : Math.round(bTop * 4);
1037
+ const lineKey = sameEmojiLine ? markAnchorLineKey : Math.round(pTop * 4);
731
1038
  const sequence = nextSequence(lineKey);
732
- const lineBottom = sameEmojiLine ? previous.lineBottom : (rootBottom - bBottom) * invScale;
1039
+ const lineBottom = sameEmojiLine ? previous.lineBottom : (rootBottom - pBottom) * invScale;
733
1040
  const lineChanged = sameBlock && previous.lineBottom !== lineBottom;
734
1041
  let kernShift = 0;
735
1042
  let kernCarry = 0;
736
1043
  let charWidth = -1;
737
1044
  if (hasKernPrevious && measuresKerning && !parts && !emoji && !lineChanged) {
738
- const firstWidth = kernPrevWidth >= 0 ? kernPrevWidth : canvasWidth(layoutFont, widths, kernPrevChar);
739
- const shown = bLeft - kernPrevLeft - letterSpacing - firstWidth - kernPrevCarry;
1045
+ const firstWidth = kernPrevWidth >= 0 ? kernPrevWidth : canvasWidth(layoutFont, widths, asciiWidths, kernPrevChar);
1046
+ const shown = pLeft - kernPrevLeft - letterSpacing - firstWidth - kernPrevCarry;
740
1047
  if (Math.abs(shown) > (nativeBrowser ? .02 : .0025)) {
741
- charWidth = canvasWidth(layoutFont, widths, character);
742
- const pair = canvasWidth(layoutFont, widths, kernPrevChar + character) - firstWidth - charWidth;
1048
+ charWidth = canvasWidth(layoutFont, widths, asciiWidths, character);
1049
+ const pair = canvasPairWidth(layoutFont, widths, pairWidths, kernPrevChar, character) - firstWidth - charWidth;
743
1050
  if (Math.abs(pair) > .01 && Math.abs(shown - pair / 2) <= Math.min(.25, Math.abs(pair) / 4)) {
744
1051
  kernCarry = pair - shown;
745
1052
  kernShift = kernCarry;
746
1053
  }
747
1054
  }
748
1055
  }
749
- const originX = (bLeft - rootLeft + kernShift) * invScale;
750
- boxHeight ||= bHeight;
1056
+ const originX = (pLeft - rootLeft + kernShift) * invScale;
1057
+ boxHeight ||= pHeight;
751
1058
  if (options.pixelSnap) {
752
- if (sharesLine) lineTops[lineTops.length - 1] = Math.min(lineTops.at(-1), bTop);
753
- else lineTops.push(bTop);
1059
+ if (sharesLine) lineTops[lineTops.length - 1] = Math.min(lineTops[lineTops.length - 1], pTop);
1060
+ else lineTops.push(pTop);
754
1061
  paintLines[glyphs.length] = lineTops.length - 1;
755
1062
  }
756
1063
  hasPrevBounds = true;
757
- prevTop = bTop;
758
- prevBottom = bBottom;
759
- prevHeight = bHeight;
1064
+ prevTop = pTop;
1065
+ prevBottom = pBottom;
1066
+ prevHeight = pHeight;
760
1067
  previousEmoji = emoji;
761
1068
  const isCjkSoft = options.cjkLineBreaking === true && canBreakCjk(previousCharacter, character);
762
1069
  if (sameBlock && !lineChanged && previous.shapeGroup === void 0) {
@@ -764,13 +1071,13 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
764
1071
  previous.advance = originX - previous.originX;
765
1072
  }
766
1073
  const soft = !sameBlock || isCjkSoft || afterSpace && !(forced && lineChanged);
767
- const lone = measuresKerning && !parts && !emoji ? (charWidth >= 0 ? charWidth : charWidth = canvasWidth(layoutFont, widths, character)) + letterSpacing : bWidth;
1074
+ const lone = measuresKerning && !parts && !emoji ? (charWidth >= 0 ? charWidth : charWidth = canvasWidth(layoutFont, widths, asciiWidths, character)) + letterSpacing : pWidth;
768
1075
  const glyph = {
769
1076
  glyphKey: key,
770
1077
  fontSize,
771
1078
  originX,
772
1079
  lineBottom,
773
- advance: (Math.abs(lone - bWidth) < .04 ? lone : bWidth) * invScale,
1080
+ advance: (Math.abs(lone - pWidth) < .04 ? lone : pWidth) * invScale,
774
1081
  block: blockIndex,
775
1082
  breakBefore: soft ? "soft" : lineChanged ? "hard" : "none",
776
1083
  clip,
@@ -791,7 +1098,7 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
791
1098
  else {
792
1099
  hasKernPrevious = true;
793
1100
  kernPrevChar = character;
794
- kernPrevLeft = bLeft;
1101
+ kernPrevLeft = pLeft;
795
1102
  kernPrevWidth = charWidth;
796
1103
  kernPrevCarry = kernCarry;
797
1104
  }
@@ -801,8 +1108,12 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
801
1108
  hasMarkAnchor = true;
802
1109
  }
803
1110
  }
804
- if (hit) hit[2] = blockRect;
1111
+ if (hit) {
1112
+ hit.blockRect = relBlockRect;
1113
+ hit.bmp = bmp;
1114
+ }
805
1115
  if (measuresBaselines && boxHeight > 0) {
1116
+ templateBoxHeight = boxHeight;
806
1117
  textRuns.push([
807
1118
  font,
808
1119
  runStart,
@@ -813,7 +1124,7 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
813
1124
  }
814
1125
  lineCount += sequences.size;
815
1126
  } else {
816
- const [lines, left, width] = pretextCapture[2](block, blockIndex, blockStyle, blockRect, clip, includeTextBox, align, lastAlign);
1127
+ const [lines, left, width] = pretextCapture[2](block, blockIndex, styleOf(block), blockRect, clip, includeTextBoxObj, align, lastAlign);
817
1128
  lineCount += lines;
818
1129
  blockLeft = left;
819
1130
  blockWidth = width;
@@ -827,12 +1138,7 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
827
1138
  clip[3] = (rootBottom - minTop) * invScale;
828
1139
  }
829
1140
  afterSpace = true;
830
- if (svg) {
831
- for (let index = blockStart; index < glyphs.length; index++) if (glyphs[index].shapeGroup !== void 0) {
832
- lineCount = lineCountBefore + svg.normalizeSvgLines(glyphs, blockStart, shapeBoxes);
833
- break;
834
- }
835
- }
1141
+ if (svgRunner) lineCount = svgRunner.finishBlock(blockStart, lineCountBefore, lineCount);
836
1142
  if (glyphs.length > blockStart) {
837
1143
  let first = -Infinity;
838
1144
  let second = -Infinity;
@@ -860,11 +1166,46 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
860
1166
  } : align !== natural ? { textAlign: align } : {}
861
1167
  };
862
1168
  }
1169
+ if (templateKey && templateTextNode && !svg) {
1170
+ const tGlyphs = [];
1171
+ const seen = /* @__PURE__ */ new Set();
1172
+ const tq = [];
1173
+ for (let i = blockStart; i < glyphs.length; i++) {
1174
+ const g = glyphs[i];
1175
+ tGlyphs.push({ ...g });
1176
+ if (!seen.has(g.glyphKey)) {
1177
+ const req = requests.get(g.glyphKey);
1178
+ if (req) {
1179
+ seen.add(g.glyphKey);
1180
+ tq.push(g.glyphKey, req.character);
1181
+ }
1182
+ }
1183
+ }
1184
+ cachedBlockTemplates.set(block, {
1185
+ n: templateTextNode,
1186
+ s: templateText,
1187
+ r: relBlockRect,
1188
+ v: templateKey,
1189
+ g: tGlyphs,
1190
+ q: tq,
1191
+ b: templateBoxes ? Float64Array.from(templateBoxes) : null,
1192
+ bh: templateBoxHeight,
1193
+ l: lineCount - lineCountBefore,
1194
+ c: [
1195
+ clip[0],
1196
+ clip[1],
1197
+ clip[2],
1198
+ clip[3]
1199
+ ],
1200
+ bl: blockLayouts[blockIndex]
1201
+ });
1202
+ }
863
1203
  }
864
1204
  if (textRuns.length > 0) {
865
1205
  const scales = layoutScales();
866
- if (scales.length > 0 && (fontProbe ??= document.createElement("canvas").getContext("2d"))) {
867
- const [descents, scale] = layoutDescents(fontProbe, boxHeights, scales, bakeSize, metricsByFont);
1206
+ const probe = scales.length > 0 ? ensureFontProbe() : null;
1207
+ if (probe) {
1208
+ const [descents, scale] = layoutDescents(probe, boxHeights, scales, bakeSize, metricsByFont);
868
1209
  layoutScale = scale;
869
1210
  for (const [font, from, to] of textRuns) {
870
1211
  const descent = descents.get(font);
@@ -884,7 +1225,7 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
884
1225
  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));
885
1226
  }
886
1227
  }
887
- const rectElements = [...root.matches(rectSelector) || options.includeRootBackground !== false ? [root] : [], ...root.querySelectorAll(rectSelector)];
1228
+ const rectElements = [...options.includeRootBackground !== false || root.matches(rectSelector) ? [root] : [], ...root.querySelectorAll(rectSelector)];
888
1229
  for (const element of rectElements) {
889
1230
  if (isIgnored(element) || displayNone(element)) continue;
890
1231
  const style = styleOf(element);
@@ -903,36 +1244,15 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
903
1244
  receiveShadow: element.hasAttribute("data-text-receive-shadow") || element.hasAttribute("data-sdf-receive-shadow")
904
1245
  });
905
1246
  }
906
- if (svgContext) for (const element of root.querySelectorAll(`${svgOptions.selector ?? "svg"}${svgOptions.images ? ",img" : ""}`)) {
907
- if (capturedSvgs.has(element) || element.closest(textSelector)) continue;
908
- const start = glyphs.length;
909
- const clip = [
910
- 0,
911
- 0,
912
- rootRect.width * invScale,
913
- rootRect.height * invScale
914
- ];
915
- captureShape(element, blockLayouts.length, clip, 0);
916
- if (glyphs.length > start) {
917
- const first = glyphs[start];
918
- blockLayouts.push({
919
- left: first.originX,
920
- firstBaseline: first.lineBottom,
921
- linePitch: 0,
922
- width: first.advance,
923
- clip
924
- });
925
- }
926
- }
927
1247
  for (const character of glyphClusters(options.extraGlyphs ?? "")) {
928
1248
  if (/^\s$/u.test(character)) continue;
929
1249
  const emoji = isEmojiCandidate(character);
930
- for (const [font, keys] of fontEntries.values()) {
1250
+ for (const [font, keys, , , , asciiKeys] of fontEntries.values()) {
931
1251
  if (!emoji && /\bemoji\b/i.test(font.family)) continue;
932
- requestKey(font, keys, character);
1252
+ requestKey(font, keys, character, asciiKeys);
933
1253
  }
934
1254
  }
935
- if (svg) svg.normalizeSvgMotion(glyphs);
1255
+ svgRunner?.finish();
936
1256
  const requestList = [...requests.values()].sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
937
1257
  const atlasSignature = requestList.map((request) => request.key).join("");
938
1258
  return {