ultra-text 1.0.1 → 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 (150) hide show
  1. package/README.md +224 -1002
  2. package/dist/assets/{cpuSdf.worker-xS57yQbP.js → cpuSdf.worker--X1Qpmdp.js} +136 -47
  3. package/dist/assets/cpuSdf.worker--X1Qpmdp.js.map +1 -0
  4. package/dist/atlas/appendAtlas.js +67 -25
  5. package/dist/atlas/appendAtlas.js.map +1 -1
  6. package/dist/atlas/buildAtlas.js +3 -2
  7. package/dist/atlas/buildAtlas.js.map +1 -1
  8. package/dist/atlas/cpuAtlas.d.ts +4 -1
  9. package/dist/atlas/cpuAtlas.js +8 -6
  10. package/dist/atlas/cpuAtlas.js.map +1 -1
  11. package/dist/atlas/cpuSdf.js +152 -40
  12. package/dist/atlas/cpuSdf.js.map +1 -1
  13. package/dist/atlas/cpuWorker.d.ts +5 -3
  14. package/dist/atlas/cpuWorker.js +119 -12
  15. package/dist/atlas/cpuWorker.js.map +1 -1
  16. package/dist/atlas/gpuAtlas.js +100 -276
  17. package/dist/atlas/gpuAtlas.js.map +1 -1
  18. package/dist/atlas/gpuCommon.d.ts +135 -0
  19. package/dist/atlas/gpuCommon.js +223 -0
  20. package/dist/atlas/gpuCommon.js.map +1 -0
  21. package/dist/atlas/jfaWgsl.js +47 -241
  22. package/dist/atlas/jfaWgsl.js.map +1 -1
  23. package/dist/atlas/rasterize.js +103 -58
  24. package/dist/atlas/rasterize.js.map +1 -1
  25. package/dist/atlas/shapeRaster.js +2 -1
  26. package/dist/atlas/shapeRaster.js.map +1 -1
  27. package/dist/atlas/vanillaBounds.d.ts +64 -0
  28. package/dist/atlas/vanillaBounds.js +42 -0
  29. package/dist/atlas/vanillaBounds.js.map +1 -0
  30. package/dist/atlas/vanillaCore.d.ts +100 -0
  31. package/dist/atlas/vanillaCore.js +1012 -0
  32. package/dist/atlas/vanillaCore.js.map +1 -0
  33. package/dist/atlas/vanillaCpuAtlas.d.ts +9 -0
  34. package/dist/atlas/vanillaCpuAtlas.js +87 -0
  35. package/dist/atlas/vanillaCpuAtlas.js.map +1 -0
  36. package/dist/atlas/vanillaExtras.d.ts +8 -0
  37. package/dist/atlas/vanillaExtras.js +166 -0
  38. package/dist/atlas/vanillaExtras.js.map +1 -0
  39. package/dist/atlas/vanillaGpuHelpers.d.ts +232 -0
  40. package/dist/atlas/vanillaGpuHelpers.js +119 -0
  41. package/dist/atlas/vanillaGpuHelpers.js.map +1 -0
  42. package/dist/dom/DomSdf.js +224 -284
  43. package/dist/dom/DomSdf.js.map +1 -1
  44. package/dist/dom/DomSlug.js +75 -151
  45. package/dist/dom/DomSlug.js.map +1 -1
  46. package/dist/dom/domAnalytic.d.ts +54 -0
  47. package/dist/dom/domAnalytic.js +282 -0
  48. package/dist/dom/domAnalytic.js.map +1 -0
  49. package/dist/dom/domExtras.d.ts +27 -0
  50. package/dist/dom/domExtras.js +137 -0
  51. package/dist/dom/domExtras.js.map +1 -0
  52. package/dist/dom/fontCanvas.js +27 -9
  53. package/dist/dom/fontCanvas.js.map +1 -1
  54. package/dist/dom/layoutSignature.js +150 -48
  55. package/dist/dom/layoutSignature.js.map +1 -1
  56. package/dist/dom/pretextLayout.js +55 -13
  57. package/dist/dom/pretextLayout.js.map +1 -1
  58. package/dist/dom/snapshot.js +369 -204
  59. package/dist/dom/snapshot.js.map +1 -1
  60. package/dist/dom/svgCapture.d.ts +8 -1
  61. package/dist/dom/svgCapture.js +75 -1
  62. package/dist/dom/svgCapture.js.map +1 -1
  63. package/dist/dom/tone.js +76 -36
  64. package/dist/dom/tone.js.map +1 -1
  65. package/dist/index.js +4 -3
  66. package/dist/slug/SlugMaterial.d.ts +11 -3
  67. package/dist/slug/SlugMaterial.js +54 -10
  68. package/dist/slug/SlugMaterial.js.map +1 -1
  69. package/dist/slug/coverage.d.ts +16 -12
  70. package/dist/slug/coverage.js +194 -221
  71. package/dist/slug/coverage.js.map +1 -1
  72. package/dist/slug/preprocessCore.d.ts +5 -1
  73. package/dist/slug/preprocessCore.js +118 -87
  74. package/dist/slug/preprocessCore.js.map +1 -1
  75. package/dist/slug/runtime.d.ts +1 -0
  76. package/dist/slug/runtime.js +90 -44
  77. package/dist/slug/runtime.js.map +1 -1
  78. package/dist/slug/standaloneRuntime.d.ts +3 -2
  79. package/dist/slug/standaloneRuntime.js +75 -40
  80. package/dist/slug/standaloneRuntime.js.map +1 -1
  81. package/dist/slug/truetype.js +166 -193
  82. package/dist/slug/truetype.js.map +1 -1
  83. package/dist/slug/vanillaCore.d.ts +340 -0
  84. package/dist/slug/vanillaCore.js +1621 -0
  85. package/dist/slug/vanillaCore.js.map +1 -0
  86. package/dist/slug-vanilla.d.ts +13 -364
  87. package/dist/slug-vanilla.js +5 -1453
  88. package/dist/slug.d.ts +1 -1
  89. package/dist/slug.js +6 -6
  90. package/dist/text/GlyphTextMaterial.d.ts +1 -1
  91. package/dist/text/GlyphTextMaterial.js +5 -5
  92. package/dist/text/GlyphTextMaterial.js.map +1 -1
  93. package/dist/text/SdfTextMaterial.js +7 -5
  94. package/dist/text/SdfTextMaterial.js.map +1 -1
  95. package/dist/text/decorations.js +36 -19
  96. package/dist/text/decorations.js.map +1 -1
  97. package/dist/text/geometry.d.ts +3 -22
  98. package/dist/text/geometryUtils.d.ts +11 -1
  99. package/dist/text/geometryUtils.js +22 -1
  100. package/dist/text/geometryUtils.js.map +1 -1
  101. package/dist/text/glyphGeometry.d.ts +9 -0
  102. package/dist/text/glyphGeometry.js +353 -0
  103. package/dist/text/glyphGeometry.js.map +1 -0
  104. package/dist/text/index.d.ts +2 -1
  105. package/dist/text/rectGeometry.d.ts +13 -0
  106. package/dist/text/rectGeometry.js +97 -0
  107. package/dist/text/rectGeometry.js.map +1 -0
  108. package/dist/text/reflow.d.ts +18 -1
  109. package/dist/text/reflow.js +108 -38
  110. package/dist/text/reflow.js.map +1 -1
  111. package/dist/text/snap.d.ts +1 -0
  112. package/dist/text/snap.js +26 -0
  113. package/dist/text/snap.js.map +1 -0
  114. package/dist/vanilla.d.ts +13 -363
  115. package/dist/vanilla.js +6 -1473
  116. package/dist/windfoil/geometry.d.ts +2 -2
  117. package/dist/windfoil/geometry.js +113 -40
  118. package/dist/windfoil/geometry.js.map +1 -1
  119. package/dist/windfoil/mixed.d.ts +1 -0
  120. package/dist/windfoil/mixed.js +44 -25
  121. package/dist/windfoil/mixed.js.map +1 -1
  122. package/dist/windfoil/preprocess.js +2 -2
  123. package/dist/windfoil/preprocessCore.d.ts +1 -0
  124. package/dist/windfoil/preprocessCore.js +9 -4
  125. package/dist/windfoil/preprocessCore.js.map +1 -1
  126. package/dist/windfoil/runtime.d.ts +3 -1
  127. package/dist/windfoil/runtime.js +62 -40
  128. package/dist/windfoil/runtime.js.map +1 -1
  129. package/dist/windfoil/storage.d.ts +60 -2
  130. package/dist/windfoil/storage.js +142 -6
  131. package/dist/windfoil/storage.js.map +1 -1
  132. package/dist/windfoil/trace/contours.d.ts +5 -0
  133. package/dist/windfoil/trace/contours.js +167 -43
  134. package/dist/windfoil/trace/contours.js.map +1 -1
  135. package/dist/windfoil/trace/fit.d.ts +3 -1
  136. package/dist/windfoil/trace/fit.js +471 -175
  137. package/dist/windfoil/trace/fit.js.map +1 -1
  138. package/dist/windfoil/trace/outline.js +55 -30
  139. package/dist/windfoil/trace/outline.js.map +1 -1
  140. package/dist/windfoil/trace/types.d.ts +10 -0
  141. package/dist/windfoil/tracedOutlines.js +59 -34
  142. package/dist/windfoil/tracedOutlines.js.map +1 -1
  143. package/package.json +11 -11
  144. package/skills/ultra-text/references/three-tsl.md +2 -2
  145. package/skills/ultra-text/references/vanilla-webgpu.md +3 -2
  146. package/dist/assets/cpuSdf.worker-xS57yQbP.js.map +0 -1
  147. package/dist/slug-vanilla.js.map +0 -1
  148. package/dist/text/geometry.js +0 -348
  149. package/dist/text/geometry.js.map +0 -1
  150. 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";
@@ -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,13 @@ 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]]);
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|$)/;
57
61
  function cssColorToSrgba(document, value, opacity) {
58
62
  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
- ];
88
- }
89
- if (parsedColors.size >= 1024) parsedColors.clear();
90
- parsedColors.set(value, rgba);
91
- }
92
- if (rgba[3] <= 0) return TRANSPARENT_SRGBA;
63
+ const rgba = parseCssColor(document, value, true);
64
+ if (!rgba || rgba[3] <= 0) return TRANSPARENT_SRGBA;
93
65
  return opacity === 1 ? rgba : [
94
66
  rgba[0],
95
67
  rgba[1],
@@ -100,7 +72,9 @@ function cssColorToSrgba(document, value, opacity) {
100
72
  var EMPTY_DECORATION_OWNERS = [];
101
73
  function canvasFont(style, bakeSize) {
102
74
  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();
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();
104
78
  }
105
79
  function fontMetrics(context, font, fontSize, cache) {
106
80
  let result = cache.get(font);
@@ -175,7 +149,7 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
175
149
  if (!Number.isFinite(pixelsPerUnit) || pixelsPerUnit <= 0) throw new RangeError("collectDomSnapshot: pixelsPerUnit must be a positive finite number");
176
150
  const invScale = 1 / pixelsPerUnit;
177
151
  const rootRect = root.getBoundingClientRect();
178
- const { left: rootLeft, bottom: rootBottom } = rootRect;
152
+ const { left: rootLeft, top: rootTop, bottom: rootBottom } = rootRect;
179
153
  if (rootRect.width <= 0 || rootRect.height <= 0) throw new Error("collectDomSnapshot: the source element has no layout box");
180
154
  if (options.layoutEngine !== void 0 && !["range", "pretext"].includes(options.layoutEngine)) throw new RangeError("collectDomSnapshot: layoutEngine must be 'range' or 'pretext'");
181
155
  const glyphs = [];
@@ -193,20 +167,36 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
193
167
  lastFontSetSize = fonts.size;
194
168
  sharedWidthsByFont = /* @__PURE__ */ new Map();
195
169
  sharedAsciiWidthsByFont = /* @__PURE__ */ new Map();
170
+ sharedPairWidthsByFont = /* @__PURE__ */ new Map();
196
171
  cachedTextRuns = /* @__PURE__ */ new WeakMap();
172
+ cachedBlockTemplates = /* @__PURE__ */ new WeakMap();
197
173
  }
198
174
  const getContextDescriptor = Object.getOwnPropertyDescriptor(view.HTMLCanvasElement.prototype, "getContext")?.value;
199
175
  const nativeCanvas = nativeBrowser && !(getContextDescriptor && "mock" in getContextDescriptor);
200
176
  let share = !svg && !("mock" in view.getComputedStyle);
201
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
+ };
202
189
  const canShare = () => {
203
190
  if (!share) return false;
204
191
  if (!shareChecked) {
205
192
  shareChecked = true;
206
193
  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;
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
+ }
210
200
  }
211
201
  } catch {
212
202
  share = false;
@@ -222,17 +212,33 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
222
212
  if (!rec) {
223
213
  const parent = el === root ? null : el.parentElement;
224
214
  const u = parent ? nodeOf(parent) : null;
225
- const hasAttrs = !attrOnly || el.hasAttributes();
215
+ const attrs = el.attributes;
216
+ const attrCount = attrs.length;
217
+ const hasAttrs = !attrOnly || attrCount > 0;
226
218
  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}`;
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
+ }
228
234
  let p = k ? pathStyles.get(k) : void 0;
229
235
  if (p !== void 0 && !canShare()) p = void 0;
230
236
  rec = {
231
237
  el,
232
238
  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,
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,
236
242
  k,
237
243
  p
238
244
  };
@@ -259,11 +265,7 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
259
265
  return owner ? parsePx(owner.getAttribute(DEPTH_ATTRIBUTE) ?? owner.getAttribute(LEGACY_DEPTH_ATTRIBUTE), fallback) : fallback;
260
266
  };
261
267
  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 ? {
268
+ const svgRunner = svg ? svg.createSvgRunner(root, options.svg, {
267
269
  style: styleOf,
268
270
  opacity: opacityOf,
269
271
  displayNone,
@@ -272,23 +274,24 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
272
274
  requests,
273
275
  rootLeft,
274
276
  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
- }
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;
289
285
  return true;
290
286
  };
291
- 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;
292
295
  const layoutEngine = options.layoutEngine ?? "range";
293
296
  if (options.rtlReflow && layoutEngine !== "range") throw new RangeError("collectDomSnapshot: rtlReflow requires the Range layout engine");
294
297
  let range;
@@ -369,23 +372,10 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
369
372
  const fontRequestKey = (font) => options.textBackend === "windfoil" && font.opticalSizing === "auto" ? `${font.key}|${font.size}` : font.key;
370
373
  const requestKey = (font, keys, character, asciiKeys) => {
371
374
  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);
375
+ let key = code >= 0 && code < 128 ? asciiKeys[code] : keys.get(character);
387
376
  if (key === void 0) {
388
377
  key = `${fontRequestKey(font)}\u0000${character}`;
378
+ if (code >= 0 && code < 128) asciiKeys[code] = key;
389
379
  keys.set(character, key);
390
380
  requests.set(key, {
391
381
  key,
@@ -395,25 +385,34 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
395
385
  }
396
386
  return key;
397
387
  };
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
+ };
398
394
  const canvasWidth = (cssFont, widths, asciiWidths, text) => {
399
395
  const code = text.length === 1 ? text.charCodeAt(0) : -1;
400
396
  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;
397
+ const width = asciiWidths[code];
398
+ return width >= 0 ? width : asciiWidths[code] = measureCanvasWidth(cssFont, text);
409
399
  }
410
400
  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);
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;
416
412
  }
413
+ const text = first + second;
414
+ let width = widths.get(text);
415
+ if (width === void 0) widths.set(text, width = measureCanvasWidth(cssFont, text));
417
416
  return width;
418
417
  };
419
418
  const resolveFont = (style) => {
@@ -430,17 +429,7 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
430
429
  const featureSettings = or(style.fontFeatureSettings);
431
430
  const variationSettings = or(style.fontVariationSettings);
432
431
  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("|");
432
+ const key = `${family}|${weight}|${fontStyle}|${stretch}|${variant}|${kerning}|${featureSettings}|${variationSettings}|${opticalSizing}`;
444
433
  const size = parsePx(style.fontSize, 16);
445
434
  const cacheKey = `${key}\u0000${size}`;
446
435
  entry = fontEntries.get(cacheKey);
@@ -469,16 +458,20 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
469
458
  const layoutFont = font.canvasFont.replace(`${bakeSize}px`, `${size}px`);
470
459
  let widths = nativeBrowser ? sharedWidthsByFont.get(layoutFont) : void 0;
471
460
  let asciiWidths = nativeBrowser ? sharedAsciiWidthsByFont.get(layoutFont) : void 0;
472
- if (!widths || !asciiWidths) {
461
+ let pairWidths = nativeBrowser ? sharedPairWidthsByFont.get(layoutFont) : void 0;
462
+ if (!widths || !asciiWidths || !pairWidths) {
473
463
  if (nativeBrowser && sharedWidthsByFont.size >= MAX_SHARED_FONT_CACHES) {
474
464
  sharedWidthsByFont.clear();
475
465
  sharedAsciiWidthsByFont.clear();
466
+ sharedPairWidthsByFont.clear();
476
467
  }
477
468
  widths ??= /* @__PURE__ */ new Map();
478
469
  asciiWidths ??= (/* @__PURE__ */ new Float64Array(128)).fill(-1);
470
+ pairWidths ??= /* @__PURE__ */ new Map();
479
471
  if (nativeBrowser) {
480
472
  sharedWidthsByFont.set(layoutFont, widths);
481
473
  sharedAsciiWidthsByFont.set(layoutFont, asciiWidths);
474
+ sharedPairWidthsByFont.set(layoutFont, pairWidths);
482
475
  }
483
476
  }
484
477
  entry = [
@@ -488,7 +481,8 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
488
481
  widths,
489
482
  measuresKerning ? canvasWidth(layoutFont, widths, asciiWidths, " ") : 0,
490
483
  asciiKeys,
491
- asciiWidths
484
+ asciiWidths,
485
+ pairWidths
492
486
  ];
493
487
  fontEntries.set(cacheKey, entry);
494
488
  }
@@ -500,7 +494,7 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
500
494
  if (isHidden(style)) return null;
501
495
  const opacity = opacityOf(parent);
502
496
  if (opacity <= 0) return null;
503
- const [font, keys, layoutFont, widths, space, asciiKeys, asciiWidths] = resolveFont(style);
497
+ const [font, keys, layoutFont, widths, space, asciiKeys, asciiWidths, pairWidths] = resolveFont(style);
504
498
  const spacing = parsePx(style.letterSpacing, 0, font.size);
505
499
  const wordSpacing = parsePx(style.wordSpacing, 0, font.size);
506
500
  const whiteSpace = style.whiteSpace;
@@ -513,6 +507,7 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
513
507
  layoutFont,
514
508
  widths,
515
509
  asciiWidths,
510
+ pairWidths,
516
511
  letterSpacing: spacing,
517
512
  wordSpacing,
518
513
  space: space && (space + spacing + wordSpacing) * invScale,
@@ -566,6 +561,27 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
566
561
  const paintLines = [];
567
562
  const lineTops = [];
568
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
+ };
569
585
  const toRect = (b) => [
570
586
  (b.left - rootLeft) * invScale,
571
587
  (rootBottom - b.bottom) * invScale,
@@ -576,22 +592,22 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
576
592
  const block = blocks[blockIndex];
577
593
  blockLayouts[blockIndex] = EMPTY_BLOCK;
578
594
  if (isIgnored(block) || displayNone(block)) continue;
579
- const blockStyle = styleOf(block);
580
595
  const blockRect = block.getBoundingClientRect();
581
596
  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;
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);
593
604
  const clip = toRect(blockRect);
594
- const layoutClip = [...clip];
605
+ const layoutClip = [
606
+ clip[0],
607
+ clip[1],
608
+ clip[2],
609
+ clip[3]
610
+ ];
595
611
  let minLeft = blockRect.left;
596
612
  let maxRight = blockRect.right;
597
613
  let minTop = blockRect.top;
@@ -607,6 +623,62 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
607
623
  const lineCountBefore = lineCount;
608
624
  let blockLeft = clip[0] + insetLeft * invScale;
609
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
+ }
610
682
  if (appendBrowserRuns) {
611
683
  const lineKeys = /* @__PURE__ */ new Set();
612
684
  appendBrowserRuns(block, {
@@ -625,8 +697,8 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
625
697
  requests,
626
698
  lineKeys,
627
699
  lineSequences: /* @__PURE__ */ new Map(),
628
- ...svg ? { svg: (element, sequence) => {
629
- captureShape(element, blockIndex, clip, sequence);
700
+ ...svgRunner ? { svg: (element, sequence) => {
701
+ svgRunner.capture(element, blockIndex, clip, sequence);
630
702
  } } : {},
631
703
  box: (font, box) => {
632
704
  includeTextBoxObj(box);
@@ -662,7 +734,9 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
662
734
  sequences.set(lineKey, lastSeqNext);
663
735
  return seq;
664
736
  };
665
- 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;
666
740
  let markAnchorLineKey = 0;
667
741
  let hasMarkAnchor = false;
668
742
  let previousCharacter = "";
@@ -677,12 +751,16 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
677
751
  let nodeIndex = 0;
678
752
  let node = walker ? walker.nextNode() : block.firstChild;
679
753
  for (; node; node = walker ? walker.nextNode() : node.nextSibling) {
754
+ if (consumeSkipped(filterState)) {
755
+ hasMarkAnchor = false;
756
+ previousCharacter = "";
757
+ }
680
758
  nodeIndex++;
681
759
  if (node.nodeType !== 3) {
682
760
  if (!walker) continue;
683
761
  const element = node;
684
762
  const shapeStart = glyphs.length;
685
- 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)) {
686
764
  const last = glyphs[glyphs.length - 1];
687
765
  if (last?.shapeGroup !== void 0) {
688
766
  const sequence = nextSequence(hasMarkAnchor ? markAnchorLineKey : Math.round(element.getBoundingClientRect().top * 4));
@@ -707,7 +785,7 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
707
785
  previousCharacter = "";
708
786
  continue;
709
787
  }
710
- const { font, keys, asciiKeys, fontSize, layoutFont, widths, asciiWidths, 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;
711
789
  let utf16Offset = 0;
712
790
  let textData = textNode.data;
713
791
  let shown = transform ? transformClusters(textData, transform, transformSeed(textNode, transform)) : void 0;
@@ -719,7 +797,6 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
719
797
  if (shown) shown = shown.map((share) => reshaped.slice(end, end += share.length));
720
798
  else textData = reshaped;
721
799
  }
722
- const emojiText = isEmojiCandidate(textData);
723
800
  const runStart = glyphs.length;
724
801
  let boxHeight = 0;
725
802
  let clusterIndex = 0;
@@ -731,32 +808,76 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
731
808
  let hit;
732
809
  let canSync = false;
733
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;
734
820
  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])) {
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;
738
828
  canSync = true;
739
829
  synced = blockSynced;
830
+ syncSource = prevHit.rects;
740
831
  } else {
741
832
  blockSynced = false;
742
- cachedTextRuns.set(textNode, hit = [
743
- runKey,
744
- new Float64Array(textData.length * 5),
745
- void 0
746
- ]);
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;
747
861
  }
862
+ } else {
863
+ emojiText = isEmojiCandidate(textData);
864
+ clusters = glyphClusters(textData);
865
+ rawString = typeof clusters === "string";
748
866
  }
749
- const rects = hit?.[1];
750
- const clusters = glyphClusters(textData);
751
- const rawString = typeof clusters === "string";
867
+ const rects = hit?.rects;
868
+ let bmp = rawString;
752
869
  const clusterArr = rawString ? null : clusters;
753
870
  const totalItems = rawString ? textData.length : clusterArr.length;
754
871
  let pos = 0;
755
872
  let ci = -1;
756
873
  while (pos < totalItems) {
757
874
  ci++;
758
- if (rawString && !shown) {
759
- if (textData.charCodeAt(pos) === 32) {
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)) {
760
881
  if (!gap || keepsSpaces) gap += space;
761
882
  afterSpace = true;
762
883
  hasMarkAnchor = hasKernPrevious = false;
@@ -765,13 +886,13 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
765
886
  utf16Offset++;
766
887
  continue;
767
888
  }
768
- }
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) {
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) {
774
894
  step = 2;
895
+ bmp = false;
775
896
  cluster = textData.slice(pos, pos + 2);
776
897
  } else {
777
898
  step = 1;
@@ -784,20 +905,23 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
784
905
  pos += step;
785
906
  const share = shown ? shown[clusterIndex++] : cluster;
786
907
  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;
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;
791
924
  }
792
- hasMarkAnchor = hasKernPrevious = false;
793
- previousCharacter = "";
794
- utf16Offset = nextOffset;
795
- continue;
796
- }
797
- if (!share) {
798
- hasKernPrevious = false;
799
- utf16Offset = nextOffset;
800
- continue;
801
925
  }
802
926
  let bLeft;
803
927
  let bTop;
@@ -806,11 +930,22 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
806
930
  let bHeight;
807
931
  const boxOff = ci * 5;
808
932
  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];
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
+ }
814
949
  } else {
815
950
  range.setEnd(textNode, nextOffset);
816
951
  range.setStart(textNode, utf16Offset);
@@ -821,19 +956,37 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
821
956
  bWidth = d.width;
822
957
  bHeight = d.height;
823
958
  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;
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;
829
970
  rects[boxOff + 3] = bWidth;
830
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
+ }
831
983
  }
832
984
  }
833
985
  }
834
986
  utf16Offset = nextOffset;
835
987
  if (measuresBaselines) trackLayoutGrid(bLeft, bWidth);
836
- const parts = share === cluster ? void 0 : expansionBoxes(share, bLeft, bTop, bBottom, bWidth, bHeight, font);
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);
837
990
  const partLen = parts ? parts.length : 1;
838
991
  for (let part = 0; part < partLen; part++) {
839
992
  let pLeft = bLeft;
@@ -893,7 +1046,7 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
893
1046
  const shown = pLeft - kernPrevLeft - letterSpacing - firstWidth - kernPrevCarry;
894
1047
  if (Math.abs(shown) > (nativeBrowser ? .02 : .0025)) {
895
1048
  charWidth = canvasWidth(layoutFont, widths, asciiWidths, character);
896
- const pair = canvasWidth(layoutFont, widths, asciiWidths, kernPrevChar + character) - firstWidth - charWidth;
1049
+ const pair = canvasPairWidth(layoutFont, widths, pairWidths, kernPrevChar, character) - firstWidth - charWidth;
897
1050
  if (Math.abs(pair) > .01 && Math.abs(shown - pair / 2) <= Math.min(.25, Math.abs(pair) / 4)) {
898
1051
  kernCarry = pair - shown;
899
1052
  kernShift = kernCarry;
@@ -903,7 +1056,7 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
903
1056
  const originX = (pLeft - rootLeft + kernShift) * invScale;
904
1057
  boxHeight ||= pHeight;
905
1058
  if (options.pixelSnap) {
906
- if (sharesLine) lineTops[lineTops.length - 1] = Math.min(lineTops.at(-1), pTop);
1059
+ if (sharesLine) lineTops[lineTops.length - 1] = Math.min(lineTops[lineTops.length - 1], pTop);
907
1060
  else lineTops.push(pTop);
908
1061
  paintLines[glyphs.length] = lineTops.length - 1;
909
1062
  }
@@ -955,8 +1108,12 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
955
1108
  hasMarkAnchor = true;
956
1109
  }
957
1110
  }
958
- if (hit) hit[2] = blockRect;
1111
+ if (hit) {
1112
+ hit.blockRect = relBlockRect;
1113
+ hit.bmp = bmp;
1114
+ }
959
1115
  if (measuresBaselines && boxHeight > 0) {
1116
+ templateBoxHeight = boxHeight;
960
1117
  textRuns.push([
961
1118
  font,
962
1119
  runStart,
@@ -967,7 +1124,7 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
967
1124
  }
968
1125
  lineCount += sequences.size;
969
1126
  } else {
970
- const [lines, left, width] = pretextCapture[2](block, blockIndex, blockStyle, blockRect, clip, includeTextBoxObj, align, lastAlign);
1127
+ const [lines, left, width] = pretextCapture[2](block, blockIndex, styleOf(block), blockRect, clip, includeTextBoxObj, align, lastAlign);
971
1128
  lineCount += lines;
972
1129
  blockLeft = left;
973
1130
  blockWidth = width;
@@ -981,12 +1138,7 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
981
1138
  clip[3] = (rootBottom - minTop) * invScale;
982
1139
  }
983
1140
  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
- }
1141
+ if (svgRunner) lineCount = svgRunner.finishBlock(blockStart, lineCountBefore, lineCount);
990
1142
  if (glyphs.length > blockStart) {
991
1143
  let first = -Infinity;
992
1144
  let second = -Infinity;
@@ -1014,6 +1166,40 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
1014
1166
  } : align !== natural ? { textAlign: align } : {}
1015
1167
  };
1016
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
+ }
1017
1203
  }
1018
1204
  if (textRuns.length > 0) {
1019
1205
  const scales = layoutScales();
@@ -1039,7 +1225,7 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
1039
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));
1040
1226
  }
1041
1227
  }
1042
- 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)];
1043
1229
  for (const element of rectElements) {
1044
1230
  if (isIgnored(element) || displayNone(element)) continue;
1045
1231
  const style = styleOf(element);
@@ -1058,27 +1244,6 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
1058
1244
  receiveShadow: element.hasAttribute("data-text-receive-shadow") || element.hasAttribute("data-sdf-receive-shadow")
1059
1245
  });
1060
1246
  }
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
- }
1082
1247
  for (const character of glyphClusters(options.extraGlyphs ?? "")) {
1083
1248
  if (/^\s$/u.test(character)) continue;
1084
1249
  const emoji = isEmojiCandidate(character);
@@ -1087,7 +1252,7 @@ function collectDomSnapshotSync(root, options, pretext, shaping, svg) {
1087
1252
  requestKey(font, keys, character, asciiKeys);
1088
1253
  }
1089
1254
  }
1090
- if (svg) svg.normalizeSvgMotion(glyphs);
1255
+ svgRunner?.finish();
1091
1256
  const requestList = [...requests.values()].sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
1092
1257
  const atlasSignature = requestList.map((request) => request.key).join("");
1093
1258
  return {