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
@@ -0,0 +1,1012 @@
1
+ import { checkCommonAtlasLimits, encodeJfaWork, jfaSteps, openErrorScopes, prefersTiledJfa, selectWorkgroupDimension, supportsDirectStore } from "./gpuCommon.js";
2
+ import { buildJfaWgsl } from "./jfaWgsl.js";
3
+ import { isColorCandidate } from "../dom/fontCanvas.js";
4
+ import { rasterizeGlyphAtlas } from "./rasterize.js";
5
+ import { resolveDomTextTone } from "../dom/tone.js";
6
+ import { collectDomSnapshot } from "../dom/snapshot.js";
7
+ import { layoutSignatureOf } from "../dom/layoutSignature.js";
8
+ import { byte, computeInstanceBounds } from "./vanillaBounds.js";
9
+ import { bufUsageOf, createGpuColorLayer, encodeMipmapChain, getDeviceMipPipeline, mipCount, resolveGpuDevice, texUsageOf, vanillaMipPipelines } from "./vanillaGpuHelpers.js";
10
+ // src/atlas/vanillaCore.ts
11
+ var devicePipelines = /* @__PURE__ */ new WeakMap();
12
+ function getDevicePipelines(device, tiledOnly) {
13
+ const directStore = supportsDirectStore(device.features);
14
+ const workgroupDim = selectWorkgroupDimension(device.limits);
15
+ let cache = devicePipelines.get(device);
16
+ if (cache?.directStore !== directStore || cache.workgroupDim !== workgroupDim) {
17
+ cache = {
18
+ workgroupDim,
19
+ directStore,
20
+ module: device.createShaderModule({ code: buildJfaWgsl(workgroupDim, directStore) })
21
+ };
22
+ devicePipelines.set(device, cache);
23
+ }
24
+ const compute = (entryPoint) => device.createComputePipeline({
25
+ layout: "auto",
26
+ compute: {
27
+ module: cache.module,
28
+ entryPoint
29
+ }
30
+ });
31
+ if (tiledOnly) return {
32
+ workgroupDim,
33
+ directStore,
34
+ seed: null,
35
+ jump: null,
36
+ jumpStore: null,
37
+ tiledStore: cache.tiledStore ??= compute("tiledStoreMain"),
38
+ resolve: null
39
+ };
40
+ return {
41
+ workgroupDim,
42
+ directStore,
43
+ ...cache.multi ??= {
44
+ seed: compute("seedMain"),
45
+ jump: compute("jumpMain"),
46
+ jumpStore: directStore ? compute("jumpStoreMain") : null,
47
+ resolve: directStore ? null : device.createRenderPipeline({
48
+ layout: "auto",
49
+ vertex: {
50
+ module: cache.module,
51
+ entryPoint: "fullscreenVert"
52
+ },
53
+ fragment: {
54
+ module: cache.module,
55
+ entryPoint: "resolveFrag",
56
+ targets: [{ format: "r8unorm" }]
57
+ }
58
+ })
59
+ },
60
+ tiledStore: null
61
+ };
62
+ }
63
+ async function buildVanillaGpuSdfAtlas(device, raster, options = {}) {
64
+ options.signal?.throwIfAborted();
65
+ const { width, height } = raster;
66
+ const steps = jfaSteps(raster.pxRange);
67
+ const directStore = supportsDirectStore(device.features);
68
+ checkCommonAtlasLimits("buildVanillaGpuSdfAtlas", device.limits, width, height, steps[0], directStore);
69
+ const bufUsage = bufUsageOf();
70
+ const texUsage = texUsageOf();
71
+ const scopes = openErrorScopes(device);
72
+ const mipmaps = options.mipmaps === true;
73
+ const mipLevelCount = mipCount(width, height, mipmaps);
74
+ let rasterTexture;
75
+ let outputTexture;
76
+ let retainOutput = false;
77
+ const transient = [];
78
+ try {
79
+ const pipelines = getDevicePipelines(device, directStore && steps[0] === 4);
80
+ outputTexture = device.createTexture({
81
+ size: [width, height],
82
+ mipLevelCount,
83
+ format: "r8unorm",
84
+ usage: texUsage.RENDER_ATTACHMENT | texUsage.TEXTURE_BINDING | texUsage.COPY_SRC | (pipelines.directStore ? texUsage.STORAGE_BINDING ?? 0 : 0)
85
+ });
86
+ const encoder = device.createCommandEncoder();
87
+ rasterTexture = encodeJfaWork(device, encoder, pipelines, raster.canvas, width, height, raster.pxRange, steps, outputTexture, transient, bufUsage, texUsage);
88
+ if (mipLevelCount > 1) {
89
+ const mip = getDeviceMipPipeline(device, "r8unorm");
90
+ encodeMipmapChain(device, encoder, outputTexture, mipLevelCount, mip.pipeline, mip.sampler);
91
+ }
92
+ device.queue.submit([encoder.finish()]);
93
+ } catch (error) {
94
+ scopes.close();
95
+ for (const b of transient) b.destroy();
96
+ outputTexture?.destroy();
97
+ throw error;
98
+ } finally {
99
+ rasterTexture?.destroy();
100
+ }
101
+ const rejection = await scopes.close();
102
+ for (const b of transient) b.destroy();
103
+ if (rejection !== null) {
104
+ devicePipelines.delete(device);
105
+ vanillaMipPipelines.delete(device);
106
+ outputTexture.destroy();
107
+ throw new Error(`buildVanillaGpuSdfAtlas: the device rejected the atlas passes: ${rejection}`);
108
+ }
109
+ try {
110
+ options.signal?.throwIfAborted();
111
+ const colorLayer = raster.colorBand ? createGpuColorLayer(device, width, raster.colorBand, mipmaps) : void 0;
112
+ retainOutput = true;
113
+ const retainedTexture = outputTexture;
114
+ let disposed = false;
115
+ const { shapeTop } = raster;
116
+ return {
117
+ ...shapeTop === void 0 ? {} : { shapeTop },
118
+ ...colorLayer ? { colorLayer } : {},
119
+ gpuTexture: retainedTexture,
120
+ width,
121
+ height,
122
+ pxRange: raster.pxRange,
123
+ bakeSize: raster.bakeSize,
124
+ glyphs: raster.glyphs,
125
+ mode: "gpu",
126
+ mipmaps,
127
+ anisotropy: mipmaps ? Math.max(1, options.anisotropy ?? 1) : 1,
128
+ dispose() {
129
+ if (disposed) return;
130
+ disposed = true;
131
+ colorLayer?.gpuTexture?.destroy();
132
+ retainedTexture.destroy();
133
+ }
134
+ };
135
+ } finally {
136
+ if (!retainOutput) outputTexture.destroy();
137
+ }
138
+ }
139
+ var warnedVanillaGpuFallback = false;
140
+ /**
141
+ * Engine-agnostic SDF atlas builder. Accepts a `GPUDevice`, an object holding `{ device }`
142
+ * (such as a Mini3 `Renderer`), or `null`/`undefined` for CPU generation.
143
+ * In `'auto'` mode (default), tries the WebGPU JFA path when a device is provided and falls
144
+ * back to the exact CPU EDT encoder if the device is absent or rejects the passes.
145
+ */
146
+ async function buildVanillaSdfAtlas(deviceOrRenderer, raster, options = {}, preparedWorker) {
147
+ options.signal?.throwIfAborted();
148
+ const mode = options.mode ?? "auto";
149
+ const device = resolveGpuDevice(deviceOrRenderer);
150
+ if (mode === "cpu") {
151
+ const { buildVanillaCpuSdfAtlas } = await import("./vanillaCpuAtlas.js");
152
+ return buildVanillaCpuSdfAtlas(raster, {
153
+ ...options,
154
+ device
155
+ }, preparedWorker);
156
+ }
157
+ if (!device) {
158
+ if (mode === "gpu") {
159
+ preparedWorker?.dispose();
160
+ throw new Error("buildVanillaSdfAtlas: mode \"gpu\" requires a WebGPU GPUDevice; use mode \"auto\" or \"cpu\" without a device");
161
+ }
162
+ const { buildVanillaCpuSdfAtlas } = await import("./vanillaCpuAtlas.js");
163
+ return buildVanillaCpuSdfAtlas(raster, options, preparedWorker);
164
+ }
165
+ if (mode === "gpu") {
166
+ preparedWorker?.dispose();
167
+ return buildVanillaGpuSdfAtlas(device, raster, options);
168
+ }
169
+ try {
170
+ const built = await buildVanillaGpuSdfAtlas(device, raster, options);
171
+ preparedWorker?.dispose();
172
+ return built;
173
+ } catch (error) {
174
+ options.signal?.throwIfAborted();
175
+ if (!warnedVanillaGpuFallback) {
176
+ warnedVanillaGpuFallback = true;
177
+ console.warn("[ultra-text] WebGPU JFA atlas generation failed; falling back to the CPU EDT generator.", error);
178
+ }
179
+ const { buildVanillaCpuSdfAtlas } = await import("./vanillaCpuAtlas.js");
180
+ return buildVanillaCpuSdfAtlas(raster, {
181
+ ...options,
182
+ device
183
+ }, preparedWorker);
184
+ }
185
+ }
186
+ /** Unit quad vertex positions (`[0,0,0, 1,0,0, 1,1,0, 0,1,0]`, 4 vertices × 3 floats). */
187
+ var UNIT_QUAD_POSITIONS = new Float32Array([
188
+ 0,
189
+ 0,
190
+ 0,
191
+ 1,
192
+ 0,
193
+ 0,
194
+ 1,
195
+ 1,
196
+ 0,
197
+ 0,
198
+ 1,
199
+ 0
200
+ ]);
201
+ /** Unit quad vertex normals (`[0,0,1, ...]`, 4 vertices × 3 floats). */
202
+ var UNIT_QUAD_NORMALS = new Float32Array([
203
+ 0,
204
+ 0,
205
+ 1,
206
+ 0,
207
+ 0,
208
+ 1,
209
+ 0,
210
+ 0,
211
+ 1,
212
+ 0,
213
+ 0,
214
+ 1
215
+ ]);
216
+ /** Unit quad triangle indices (`[0, 1, 2, 0, 2, 3]`, 6 uint16 indices). */
217
+ var UNIT_QUAD_INDICES = new Uint16Array([
218
+ 0,
219
+ 1,
220
+ 2,
221
+ 0,
222
+ 2,
223
+ 3
224
+ ]);
225
+ function metaSize(snapshot) {
226
+ return snapshot.sizeSwitched || snapshot.glyphs.some((glyph) => glyph.switchEm !== void 0) ? 3 : 2;
227
+ }
228
+ function writeMeta(target, index, size, glyph) {
229
+ target[index * size] = glyph.sequence;
230
+ target[index * size + 1] = glyph.z;
231
+ if (size === 3) target[index * size + 2] = glyph.switchEm ?? 0;
232
+ }
233
+ function needsRunMotion(snapshot) {
234
+ return snapshot.textShaping === "browser" || snapshot.glyphs.some((glyph) => glyph.motionOrigin !== void 0);
235
+ }
236
+ function shapeOrdinals(snapshot) {
237
+ const glyphs = snapshot.glyphs;
238
+ if (!glyphs.some((glyph) => glyph.shapeGroup !== void 0)) return void 0;
239
+ const out = new Float32Array(glyphs.length);
240
+ let ordinal = -1;
241
+ let previous;
242
+ for (let index = 0; index < glyphs.length; index++) {
243
+ const glyph = glyphs[index];
244
+ if (glyph.shapeGroup === void 0 || glyph.shapeGroup !== previous) ordinal++;
245
+ previous = glyph.shapeGroup;
246
+ out[index] = glyph.motionOrigin?.[2] ?? ordinal;
247
+ }
248
+ return out;
249
+ }
250
+ function writeUvRect(target, offset, slot) {
251
+ target[offset] = slot.u0 * 65535 + .5 | 0;
252
+ target[offset + 1] = slot.v1 * 65535 + .5 | 0;
253
+ target[offset + 2] = slot.u1 * 65535 + .5 | 0;
254
+ target[offset + 3] = slot.v0 * 65535 + .5 | 0;
255
+ }
256
+ var unorm16Floor = (value) => Math.min(65535, Math.max(0, Math.floor(value * 65535)));
257
+ var unorm16Ceil = (value) => Math.min(65535, Math.max(0, Math.ceil(value * 65535)));
258
+ function writeTrim(target, offset, slot, uvRects) {
259
+ const support = slot.support;
260
+ if (!support) {
261
+ target[offset] = uvRects[offset];
262
+ target[offset + 1] = uvRects[offset + 1];
263
+ target[offset + 2] = uvRects[offset + 2];
264
+ target[offset + 3] = uvRects[offset + 3];
265
+ return;
266
+ }
267
+ target[offset] = unorm16Floor(support.u0);
268
+ target[offset + 1] = unorm16Ceil(support.v1);
269
+ target[offset + 2] = unorm16Ceil(support.u1);
270
+ target[offset + 3] = unorm16Floor(support.v0);
271
+ }
272
+ function writeGlyphRect(rects, offset, glyph, slot, bakeSize, shaped) {
273
+ const scale = glyph.fontSize / bakeSize;
274
+ const scaleX = shaped && slot.advance > 0 ? glyph.advance / slot.advance : scale;
275
+ const baseline = glyph.lineBottom + (glyph.baselineOffset ?? slot.descent * scale);
276
+ rects[offset] = glyph.originX + slot.planeX0 * scaleX;
277
+ rects[offset + 1] = baseline + slot.planeY0 * scale;
278
+ rects[offset + 2] = glyph.originX + slot.planeX1 * scaleX;
279
+ rects[offset + 3] = baseline + slot.planeY1 * scale;
280
+ }
281
+ function writeVanillaRunMotion(runMotion, index, ordinal, glyph, rects, offset, motionOrdinals) {
282
+ if (!runMotion) return;
283
+ const rOffset = index * 3;
284
+ const origin = glyph.motionOrigin;
285
+ runMotion[rOffset] = origin ? origin[0] : (rects[offset] + rects[offset + 2]) * .5;
286
+ runMotion[rOffset + 1] = origin ? origin[1] : (rects[offset + 1] + rects[offset + 3]) * .5;
287
+ runMotion[rOffset + 2] = origin ? origin[2] : motionOrdinals?.[ordinal] ?? ordinal;
288
+ }
289
+ function writeVanillaGlyphBatch(snapshot, atlas, rects, uvRects, trims, clips, colors, metadata, metaItemSize, runMotion, motionOrdinals) {
290
+ const glyphs = snapshot.glyphs;
291
+ const total = glyphs.length;
292
+ const shaped = snapshot.textShaping === "browser";
293
+ const bakeSize = atlas.bakeSize;
294
+ const atlasGlyphs = atlas.glyphs;
295
+ let count = 0;
296
+ let maxSequence = 0;
297
+ let minZ = 0;
298
+ let maxZ = 0;
299
+ for (let ordinal = 0; ordinal < total; ordinal++) {
300
+ const glyph = glyphs[ordinal];
301
+ const slot = atlasGlyphs.get(glyph.glyphKey);
302
+ if (!slot) continue;
303
+ const index = count++;
304
+ const offset = index * 4;
305
+ writeGlyphRect(rects, offset, glyph, slot, bakeSize, shaped);
306
+ writeUvRect(uvRects, offset, slot);
307
+ if (trims) writeTrim(trims, offset, slot, uvRects);
308
+ const clip = glyph.clip;
309
+ clips[offset] = clip[0];
310
+ clips[offset + 1] = clip[1];
311
+ clips[offset + 2] = clip[2];
312
+ clips[offset + 3] = clip[3];
313
+ const color = glyph.color;
314
+ colors[offset] = byte(color[0]);
315
+ colors[offset + 1] = byte(color[1]);
316
+ colors[offset + 2] = byte(color[2]);
317
+ colors[offset + 3] = byte(color[3]);
318
+ writeMeta(metadata, index, metaItemSize, glyph);
319
+ writeVanillaRunMotion(runMotion, index, ordinal, glyph, rects, offset, motionOrdinals);
320
+ if (glyph.sequence > maxSequence) maxSequence = glyph.sequence;
321
+ if (glyph.z < minZ) minZ = glyph.z;
322
+ if (glyph.z > maxZ) maxZ = glyph.z;
323
+ }
324
+ return [
325
+ count,
326
+ maxSequence,
327
+ minZ,
328
+ maxZ
329
+ ];
330
+ }
331
+ /** Packs instanced glyph attribute arrays from a layout snapshot and SDF atlas. */
332
+ function packGlyphInstances(snapshot, atlas, motionPadding = 0, motionOrdinals) {
333
+ const hasRunMotion = needsRunMotion(snapshot);
334
+ motionOrdinals ??= hasRunMotion ? shapeOrdinals(snapshot) : void 0;
335
+ const total = snapshot.glyphs.length;
336
+ const rects = new Float32Array(total * 4);
337
+ const uvRects = new Uint16Array(total * 4);
338
+ const clips = new Float32Array(total * 4);
339
+ const colors = new Uint8Array(total * 4);
340
+ const metaItemSize = metaSize(snapshot);
341
+ const metadata = new Float32Array(total * metaItemSize);
342
+ const runMotion = hasRunMotion || motionOrdinals ? new Float32Array(total * 3) : null;
343
+ const trims = runMotion ? null : new Uint16Array(total * 4);
344
+ const [count, maxSequence, minZ, maxZ] = writeVanillaGlyphBatch(snapshot, atlas, rects, uvRects, trims, clips, colors, metadata, metaItemSize, runMotion, motionOrdinals);
345
+ const full = count === total;
346
+ return {
347
+ count,
348
+ maxSequence,
349
+ rects: full ? rects : rects.subarray(0, count * 4),
350
+ uvRects: full ? uvRects : uvRects.subarray(0, count * 4),
351
+ trims: trims ? full ? trims : trims.subarray(0, count * 4) : null,
352
+ clips: full ? clips : clips.subarray(0, count * 4),
353
+ colors: full ? colors : colors.subarray(0, count * 4),
354
+ metadata: full ? metadata : metadata.subarray(0, count * metaItemSize),
355
+ metaItemSize,
356
+ runMotion: runMotion ? full ? runMotion : runMotion.subarray(0, count * 3) : null,
357
+ bounds: computeInstanceBounds(snapshot.width, snapshot.height, motionPadding, minZ, maxZ)
358
+ };
359
+ }
360
+ /**
361
+ * Rewrites the glyph instance arrays that change on a reflow (`rects`, `clips`, `metadata`,
362
+ * `runMotion`, `bounds`) in place without reallocating. Returns `maxSequence`, or `null` when
363
+ * the glyph count no longer matches.
364
+ */
365
+ function updateGlyphInstances(instances, snapshot, atlas, motionPadding = 0, motionOrdinals) {
366
+ const { rects, clips, metadata, metaItemSize, runMotion, count: instanceCount } = instances;
367
+ const glyphs = snapshot.glyphs;
368
+ const total = glyphs.length;
369
+ if (total < instanceCount) return null;
370
+ motionOrdinals ??= needsRunMotion(snapshot) ? shapeOrdinals(snapshot) : void 0;
371
+ const shaped = snapshot.textShaping === "browser";
372
+ const bakeSize = atlas.bakeSize;
373
+ const atlasGlyphs = atlas.glyphs;
374
+ let count = 0;
375
+ let maxSequence = 0;
376
+ let minZ = 0;
377
+ let maxZ = 0;
378
+ for (let ordinal = 0; ordinal < total; ordinal++) {
379
+ const glyph = glyphs[ordinal];
380
+ const slot = atlasGlyphs.get(glyph.glyphKey);
381
+ if (!slot) continue;
382
+ if (count >= instanceCount) return null;
383
+ const index = count++;
384
+ const offset = index * 4;
385
+ writeGlyphRect(rects, offset, glyph, slot, bakeSize, shaped);
386
+ const clip = glyph.clip;
387
+ clips[offset] = clip[0];
388
+ clips[offset + 1] = clip[1];
389
+ clips[offset + 2] = clip[2];
390
+ clips[offset + 3] = clip[3];
391
+ metadata[index * metaItemSize] = glyph.sequence;
392
+ writeVanillaRunMotion(runMotion, index, ordinal, glyph, rects, offset, motionOrdinals);
393
+ if (glyph.sequence > maxSequence) maxSequence = glyph.sequence;
394
+ if (glyph.z < minZ) minZ = glyph.z;
395
+ if (glyph.z > maxZ) maxZ = glyph.z;
396
+ }
397
+ if (count !== instanceCount) return null;
398
+ instances.maxSequence = maxSequence;
399
+ instances.bounds = computeInstanceBounds(snapshot.width, snapshot.height, motionPadding, minZ, maxZ);
400
+ return maxSequence;
401
+ }
402
+ /**
403
+ * Rewrites all glyph instance arrays in place when the drawable count and layout match.
404
+ * Returns `maxSequence`, or `null` without mutating when the buffers do not fit.
405
+ */
406
+ function updateGlyphContentInstances(instances, snapshot, atlas, motionPadding = 0, motionOrdinals) {
407
+ const glyphs = snapshot.glyphs;
408
+ const total = glyphs.length;
409
+ const expectedCount = instances.count;
410
+ if (total < expectedCount || metaSize(snapshot) !== instances.metaItemSize) return null;
411
+ const hasRun = needsRunMotion(snapshot);
412
+ motionOrdinals ??= hasRun ? shapeOrdinals(snapshot) : void 0;
413
+ if ((hasRun || !!motionOrdinals) !== (instances.runMotion !== null)) return null;
414
+ const atlasGlyphs = atlas.glyphs;
415
+ let drawable = 0;
416
+ for (let i = 0; i < total; i++) if (atlasGlyphs.has(glyphs[i].glyphKey)) {
417
+ drawable++;
418
+ if (drawable > expectedCount) return null;
419
+ } else if (drawable + (total - 1 - i) < expectedCount) return null;
420
+ if (drawable !== expectedCount) return null;
421
+ const [, maxSequence, minZ, maxZ] = writeVanillaGlyphBatch(snapshot, atlas, instances.rects, instances.uvRects, instances.trims, instances.clips, instances.colors, instances.metadata, instances.metaItemSize, instances.runMotion, motionOrdinals);
422
+ instances.maxSequence = maxSequence;
423
+ instances.bounds = computeInstanceBounds(snapshot.width, snapshot.height, motionPadding, minZ, maxZ);
424
+ return maxSequence;
425
+ }
426
+ function nowMs() {
427
+ return typeof performance !== "undefined" ? performance.now() : Date.now();
428
+ }
429
+ function makeAbortError() {
430
+ if (typeof DOMException !== "undefined") return new DOMException("The operation was aborted", "AbortError");
431
+ const error = /* @__PURE__ */ new Error("The operation was aborted");
432
+ error.name = "AbortError";
433
+ return error;
434
+ }
435
+ function isAbortError(error) {
436
+ return error instanceof Error && error.name === "AbortError";
437
+ }
438
+ function linkAbortSignals(...signals) {
439
+ const controller = new AbortController();
440
+ const activeSignals = signals.filter((signal) => signal !== void 0);
441
+ for (const signal of activeSignals) if (signal.aborted) {
442
+ controller.abort(signal.reason ?? makeAbortError());
443
+ return [controller, () => void 0];
444
+ }
445
+ const listeners = activeSignals.map((signal) => {
446
+ const onAbort = () => {
447
+ controller.abort(signal.reason ?? makeAbortError());
448
+ };
449
+ signal.addEventListener("abort", onAbort, { once: true });
450
+ return [signal, onAbort];
451
+ });
452
+ return [controller, () => {
453
+ for (const [signal, onAbort] of listeners) signal.removeEventListener("abort", onAbort);
454
+ }];
455
+ }
456
+ async function waitForDocumentFonts(document, signal) {
457
+ signal?.throwIfAborted();
458
+ const fonts = document.fonts;
459
+ if (!fonts) return;
460
+ if (!signal) {
461
+ await Promise.resolve(fonts.ready);
462
+ return;
463
+ }
464
+ await new Promise((resolve, reject) => {
465
+ const onAbort = () => {
466
+ reject(signal.reason instanceof Error ? signal.reason : new DOMException(String(signal.reason ?? "The operation was aborted"), "AbortError"));
467
+ };
468
+ signal.addEventListener("abort", onAbort, { once: true });
469
+ Promise.resolve(fonts.ready).then(() => {
470
+ signal.removeEventListener("abort", onAbort);
471
+ resolve();
472
+ }, (error) => {
473
+ signal.removeEventListener("abort", onAbort);
474
+ reject(error instanceof Error ? error : new Error(String(error)));
475
+ });
476
+ });
477
+ }
478
+ function hasAllGlyphs(atlas, snapshot, colorGlyphsOption) {
479
+ const bitmap = colorGlyphsOption === "none" && snapshot.requests.some((request) => request.shape?.bitmap);
480
+ return snapshot.requests.every((request) => {
481
+ const slot = atlas.glyphs.get(request.key);
482
+ return slot !== void 0 && !(colorGlyphsOption === "none" && bitmap && !request.shape && slot.color) && (!isColorCandidate(request, colorGlyphsOption) || slot.color !== void 0);
483
+ });
484
+ }
485
+ var VanillaDomText = class VanillaDomText {
486
+ element;
487
+ device;
488
+ options;
489
+ glyphs;
490
+ plainRects = null;
491
+ litRects = null;
492
+ decorations = null;
493
+ tone = null;
494
+ motion;
495
+ #a;
496
+ #s = null;
497
+ #rw = null;
498
+ #rs = null;
499
+ #rf = null;
500
+ #rm = null;
501
+ #ex = null;
502
+ #w = 0;
503
+ #h = 0;
504
+ #as = "";
505
+ #ls = "";
506
+ #o = true;
507
+ #st;
508
+ #ro = null;
509
+ #mo = null;
510
+ #uf = null;
511
+ #f = null;
512
+ #ac = null;
513
+ #rv = 0;
514
+ #av = 0;
515
+ #sel = false;
516
+ #d = false;
517
+ #cbs = /* @__PURE__ */ new Set();
518
+ constructor(element, deviceOrRenderer, options) {
519
+ this.element = element;
520
+ this.device = resolveGpuDevice(deviceOrRenderer);
521
+ this.options = Object.freeze({ ...options });
522
+ this.motion = {
523
+ enabled: options.motion?.enabled ?? true,
524
+ mode: options.motion?.mode ?? "slide-up",
525
+ strength: Math.max(0, options.motion?.strength ?? 18),
526
+ speed: Math.max(0, options.motion?.speed ?? 1.35),
527
+ stagger: Math.max(0, options.motion?.stagger ?? .045)
528
+ };
529
+ if (options.onChange) this.#cbs.add(options.onChange);
530
+ }
531
+ static async create(element, deviceOrRenderer, options = {}) {
532
+ if (!element.isConnected) throw new Error("VanillaDomText.create requires a connected HTMLElement");
533
+ options.signal?.throwIfAborted();
534
+ if (options.sharedAtlas && (options.sharedAtlas.mipmaps !== (options.quality === "high") || (options.colorGlyphs ?? "emoji") !== "none" !== Boolean(options.sharedAtlas.colorLayer))) throw new Error("VanillaDomText: sharedAtlas must match quality and colorGlyphs options");
535
+ const instance = new VanillaDomText(element, deviceOrRenderer, options);
536
+ try {
537
+ instance.applySelectableAttribute();
538
+ await instance.rebuild(options.signal ? { signal: options.signal } : {});
539
+ instance.setupObservers();
540
+ instance.notify("create");
541
+ return instance;
542
+ } catch (error) {
543
+ instance.dispose();
544
+ throw error;
545
+ }
546
+ }
547
+ get atlas() {
548
+ return this.#a;
549
+ }
550
+ get stats() {
551
+ return this.#st;
552
+ }
553
+ get snapshot() {
554
+ return this.#rw === null ? this.#s : this.#rs ??= this.#rm.reflowSnapshot(this.#s, this.#rw);
555
+ }
556
+ get width() {
557
+ return this.#w;
558
+ }
559
+ get height() {
560
+ return this.#h;
561
+ }
562
+ get isDisposed() {
563
+ return this.#d;
564
+ }
565
+ subscribe(listener) {
566
+ this.#cbs.add(listener);
567
+ return () => {
568
+ this.#cbs.delete(listener);
569
+ };
570
+ }
571
+ reflow(width) {
572
+ if (this.#d) throw new Error("Cannot reflow a disposed VanillaDomText instance");
573
+ if (this.options.reflowable !== true || !this.#s) throw new Error("VanillaDomText.reflow requires { reflowable: true } at creation time");
574
+ if (this.#s.textShaping === "browser") throw new Error("VanillaDomText.reflow does not support textShaping: \"browser\"; call rebuild() after resizing");
575
+ if (!Number.isFinite(width) || width <= 0) throw new RangeError("VanillaDomText.reflow: width must be a positive finite number");
576
+ const reflowMod = this.#rm;
577
+ const geometryStart = nowMs();
578
+ const nextSnapshot = reflowMod.reflowSnapshotWithState(this.#s, width, this.#rf ??= reflowMod.createReflowState(this.#s));
579
+ const motionPadding = Math.max(0, this.motion.strength);
580
+ if (updateGlyphInstances(this.glyphs, nextSnapshot, this.#a, motionPadding) === null) this.glyphs = packGlyphInstances(nextSnapshot, this.#a, motionPadding);
581
+ if (this.decorations) {
582
+ const extras = this.#ex;
583
+ const drawable = (key) => this.#a.glyphs.has(key);
584
+ if (!extras.updateDecorationInstances(this.decorations, nextSnapshot, this.glyphs.rects, drawable, motionPadding)) this.decorations = extras.packDecorationInstances(nextSnapshot, this.glyphs.rects, drawable, motionPadding);
585
+ }
586
+ const geometryBuildMs = nowMs() - geometryStart;
587
+ this.#rw = width;
588
+ this.#rs = null;
589
+ this.#w = nextSnapshot.width;
590
+ this.#h = nextSnapshot.height;
591
+ this.#ls = "";
592
+ const draws = (this.plainRects ? 1 : 0) + (this.litRects ? 1 : 0) + (this.glyphs.count > 0 ? 1 : 0) + (this.decorations ? 1 : 0);
593
+ this.#st = Object.freeze({
594
+ ...this.#st,
595
+ atlasBuildMs: 0,
596
+ layoutReadMs: 0,
597
+ geometryBuildMs,
598
+ lines: nextSnapshot.lineCount,
599
+ draws
600
+ });
601
+ this.notify("reflow");
602
+ return this;
603
+ }
604
+ setMotion(motion) {
605
+ if (this.#d) return this;
606
+ const previousStrength = this.motion.strength;
607
+ this.motion = {
608
+ enabled: motion.enabled ?? this.motion.enabled,
609
+ mode: motion.mode ?? this.motion.mode,
610
+ strength: Math.max(0, motion.strength ?? this.motion.strength),
611
+ speed: Math.max(0, motion.speed ?? this.motion.speed),
612
+ stagger: Math.max(0, motion.stagger ?? this.motion.stagger)
613
+ };
614
+ if (this.motion.strength !== previousStrength && this.#s) {
615
+ const padding = this.motion.strength;
616
+ let minZ = 0;
617
+ let maxZ = 0;
618
+ for (const glyph of this.#s.glyphs) {
619
+ if (glyph.z < minZ) minZ = glyph.z;
620
+ if (glyph.z > maxZ) maxZ = glyph.z;
621
+ }
622
+ this.glyphs.bounds = computeInstanceBounds(this.#w, this.#h, padding, minZ, maxZ);
623
+ }
624
+ this.notify("motion");
625
+ return this;
626
+ }
627
+ async rebuild(rebuildOptions = {}) {
628
+ if (this.#d) throw new Error("Cannot rebuild a disposed VanillaDomText instance");
629
+ if (!this.element.isConnected) throw new Error("Cannot rebuild VanillaDomText when the source element is disconnected");
630
+ const version = ++this.#rv;
631
+ this.#ac?.abort(makeAbortError());
632
+ const [controller, unlinkSignals] = linkAbortSignals(this.options.signal, rebuildOptions.signal);
633
+ this.#ac = controller;
634
+ const { signal } = controller;
635
+ let nextAtlas;
636
+ let nextOwnsAtlas = true;
637
+ let preparedWorkerPromise;
638
+ let consumedWorker = false;
639
+ try {
640
+ const opts = this.options;
641
+ const reflowPromise = opts.reflowable === true && !this.#rm ? import("../text/reflow.js").then((mod) => {
642
+ this.#rm = mod;
643
+ }) : void 0;
644
+ await waitForDocumentFonts(this.element.ownerDocument, signal);
645
+ signal.throwIfAborted();
646
+ const { device } = this;
647
+ const sharedAtlas = opts.sharedAtlas;
648
+ const currentAtlas = this.#a;
649
+ const gpuUpload = opts.atlasMode !== "cpu" && typeof device?.createShaderModule === "function";
650
+ const tiledOnly = gpuUpload ? prefersTiledJfa(supportsDirectStore(device.features), opts.padding) : false;
651
+ const cached = gpuUpload ? devicePipelines.get(device) : void 0;
652
+ if (gpuUpload && (tiledOnly ? !cached?.tiledStore : !cached?.multi) && !sharedAtlas && !currentAtlas) try {
653
+ getDevicePipelines(device, tiledOnly);
654
+ device.queue.submit([]);
655
+ } catch {}
656
+ else if (!gpuUpload && !sharedAtlas && !currentAtlas && opts.cpuWorker !== false && typeof Worker !== "undefined") preparedWorkerPromise = import("./cpuWorker.js").then((mod) => mod.prepareCpuWorker()).catch(() => null);
657
+ const layoutStart = nowMs();
658
+ const snapshotOptions = {
659
+ ...opts,
660
+ signal
661
+ };
662
+ const snapshot = await collectDomSnapshot(this.element, snapshotOptions);
663
+ const layoutReadMs = nowMs() - layoutStart;
664
+ signal.throwIfAborted();
665
+ const hasRects = snapshot.rects.length > 0;
666
+ const hasDecorations = snapshot.glyphs.some((glyph) => Boolean(glyph.decorations?.length));
667
+ const extrasPromise = (hasRects || hasDecorations) && !this.#ex ? import("./vanillaExtras.js").then((mod) => {
668
+ this.#ex = mod;
669
+ }) : void 0;
670
+ const nextTone = this.resolveCaptureTone(snapshot);
671
+ const canUseSharedAtlas = Boolean(sharedAtlas && hasAllGlyphs(sharedAtlas, snapshot, opts.colorGlyphs));
672
+ const canReusePrivateAtlas = Boolean(!canUseSharedAtlas && currentAtlas && this.#o && (this.#as === snapshot.atlasSignature || hasAllGlyphs(currentAtlas, snapshot, opts.colorGlyphs)));
673
+ const nextLayoutSignature = layoutSignatureOf(snapshot);
674
+ if (this.#ls === "" && this.#s) this.#ls = layoutSignatureOf(this.snapshot);
675
+ if ((canUseSharedAtlas || canReusePrivateAtlas) && this.#ls !== "" && nextLayoutSignature === this.#ls) {
676
+ if (reflowPromise) await reflowPromise;
677
+ if (version !== this.#rv || this.#d) throw makeAbortError();
678
+ this.tone = nextTone;
679
+ this.#s = snapshot;
680
+ this.#rw = null;
681
+ this.#rs = null;
682
+ this.#rf = null;
683
+ this.#w = snapshot.width;
684
+ this.#h = snapshot.height;
685
+ this.#st = Object.freeze({
686
+ ...this.#st,
687
+ atlasBuildMs: 0,
688
+ layoutReadMs,
689
+ geometryBuildMs: 0
690
+ });
691
+ this.notify("rebuild");
692
+ return this;
693
+ }
694
+ const atlasStart = nowMs();
695
+ const highQuality = opts.quality === "high";
696
+ if (canUseSharedAtlas && sharedAtlas) {
697
+ nextAtlas = sharedAtlas;
698
+ nextOwnsAtlas = false;
699
+ } else if (canReusePrivateAtlas && currentAtlas) {
700
+ nextAtlas = currentAtlas;
701
+ nextOwnsAtlas = true;
702
+ } else {
703
+ const raster = await rasterizeGlyphAtlas(this.element.ownerDocument, snapshot.requests, {
704
+ ...opts,
705
+ previousAtlas: currentAtlas !== sharedAtlas ? currentAtlas : void 0,
706
+ ...gpuUpload ? { gpuUpload } : {},
707
+ signal
708
+ });
709
+ signal.throwIfAborted();
710
+ const preparedWorker = preparedWorkerPromise ? await preparedWorkerPromise : void 0;
711
+ consumedWorker = true;
712
+ nextAtlas = await buildVanillaSdfAtlas(device, raster, {
713
+ ...opts.cpuWorker === void 0 ? {} : { cpuWorker: opts.cpuWorker },
714
+ mode: opts.atlasMode ?? "auto",
715
+ mipmaps: highQuality,
716
+ anisotropy: highQuality ? 4 : 1,
717
+ signal
718
+ }, preparedWorker);
719
+ nextAtlas.colorGlyphs = opts.colorGlyphs ?? "emoji";
720
+ nextOwnsAtlas = true;
721
+ }
722
+ const atlasBuildMs = canUseSharedAtlas || canReusePrivateAtlas ? 0 : nowMs() - atlasStart;
723
+ if (extrasPromise) await extrasPromise;
724
+ if (reflowPromise) await reflowPromise;
725
+ signal.throwIfAborted();
726
+ if (version !== this.#rv || this.#d) throw makeAbortError();
727
+ const resolvedAtlas = nextAtlas;
728
+ const geometryStart = nowMs();
729
+ const motionPadding = Math.max(0, this.motion.strength);
730
+ const drawable = (key) => resolvedAtlas.glyphs.has(key);
731
+ const currentGlyphs = this.glyphs;
732
+ if (!currentGlyphs || updateGlyphContentInstances(currentGlyphs, snapshot, resolvedAtlas, motionPadding) === null) this.glyphs = packGlyphInstances(snapshot, resolvedAtlas, motionPadding);
733
+ if (hasRects) {
734
+ const extras = this.#ex;
735
+ if (!this.plainRects || !extras.updateRectInstances(this.plainRects, snapshot, false)) this.plainRects = extras.packRectInstances(snapshot, false);
736
+ if (!this.litRects || !extras.updateRectInstances(this.litRects, snapshot, true)) this.litRects = extras.packRectInstances(snapshot, true);
737
+ } else {
738
+ this.plainRects = null;
739
+ this.litRects = null;
740
+ }
741
+ if (hasDecorations) {
742
+ const extras = this.#ex;
743
+ if (!this.decorations || !extras.updateDecorationInstances(this.decorations, snapshot, this.glyphs.rects, drawable, motionPadding)) this.decorations = extras.packDecorationInstances(snapshot, this.glyphs.rects, drawable, motionPadding);
744
+ } else this.decorations = null;
745
+ const geometryBuildMs = nowMs() - geometryStart;
746
+ const previousAtlas = this.#a;
747
+ const previousOwnsAtlas = this.#o;
748
+ this.#a = resolvedAtlas;
749
+ this.#o = nextOwnsAtlas;
750
+ this.tone = nextTone;
751
+ this.#s = snapshot;
752
+ this.#rw = null;
753
+ this.#rs = null;
754
+ this.#rf = null;
755
+ this.#w = snapshot.width;
756
+ this.#h = snapshot.height;
757
+ if (!canUseSharedAtlas && !canReusePrivateAtlas) this.#as = snapshot.atlasSignature;
758
+ this.#ls = nextLayoutSignature;
759
+ this.#av = version;
760
+ let textGlyphs = 0;
761
+ let shapes = 0;
762
+ let colorGlyphCount = 0;
763
+ for (const glyph of snapshot.glyphs) if (glyph.shapeGroup !== void 0) shapes++;
764
+ else {
765
+ textGlyphs++;
766
+ if (resolvedAtlas.glyphs.get(glyph.glyphKey)?.color) colorGlyphCount++;
767
+ }
768
+ const mipFactor = highQuality ? 4 / 3 : 1;
769
+ const colorBytes = resolvedAtlas.colorLayer ? resolvedAtlas.width * resolvedAtlas.colorLayer.height * 4 : 0;
770
+ const textStorageBytes = Math.round((resolvedAtlas.width * resolvedAtlas.height + colorBytes) * mipFactor);
771
+ const draws = (this.plainRects ? 1 : 0) + (this.litRects ? 1 : 0) + (this.glyphs.count > 0 ? 1 : 0) + (this.decorations ? 1 : 0);
772
+ this.#st = Object.freeze({
773
+ colorGlyphs: colorGlyphCount,
774
+ shapes,
775
+ fallbackGlyphs: 0,
776
+ switchableGlyphs: 0,
777
+ atlasBuildMs,
778
+ layoutReadMs,
779
+ geometryBuildMs,
780
+ glyphs: textGlyphs,
781
+ rects: snapshot.rects.length,
782
+ lines: snapshot.lineCount,
783
+ draws,
784
+ atlasWidth: resolvedAtlas.width,
785
+ atlasHeight: resolvedAtlas.height,
786
+ textBackend: "sdf",
787
+ atlasMode: resolvedAtlas.mode,
788
+ textStorageBytes
789
+ });
790
+ if (previousAtlas && previousOwnsAtlas && previousAtlas !== resolvedAtlas) previousAtlas.dispose();
791
+ if (this.#av > 1) this.notify("rebuild");
792
+ return this;
793
+ } catch (error) {
794
+ if (nextAtlas && nextOwnsAtlas && nextAtlas !== this.#a) nextAtlas.dispose();
795
+ throw error;
796
+ } finally {
797
+ if (preparedWorkerPromise && !consumedWorker) preparedWorkerPromise.then((worker) => worker?.dispose());
798
+ unlinkSignals();
799
+ if (this.#ac === controller) this.#ac = null;
800
+ }
801
+ }
802
+ dispose() {
803
+ if (this.#d) return;
804
+ this.#d = true;
805
+ this.#ac?.abort(makeAbortError());
806
+ this.#ac = null;
807
+ if (this.#f !== null && typeof cancelAnimationFrame === "function") {
808
+ cancelAnimationFrame(this.#f);
809
+ this.#f = null;
810
+ }
811
+ this.#ro?.disconnect();
812
+ this.#ro = null;
813
+ this.#mo?.disconnect();
814
+ this.#mo = null;
815
+ this.#uf?.();
816
+ this.#uf = null;
817
+ if (this.#sel) {
818
+ this.element.classList.remove("sdf-selectable");
819
+ this.#sel = false;
820
+ }
821
+ const currentAtlas = this.#a;
822
+ if (currentAtlas && this.#o) currentAtlas.dispose();
823
+ this.#s = null;
824
+ this.#rw = null;
825
+ this.#rs = null;
826
+ this.#rf = null;
827
+ this.#w = 0;
828
+ this.#h = 0;
829
+ this.notify("dispose");
830
+ this.#cbs.clear();
831
+ }
832
+ resolveCaptureTone(snapshot) {
833
+ return resolveDomTextTone(this.element, this.options.tone, {
834
+ glyphs: snapshot.glyphs,
835
+ rects: snapshot.rects,
836
+ rootRect: this.options.includeRootBackground !== false
837
+ });
838
+ }
839
+ notify(reason) {
840
+ for (const listener of this.#cbs) listener(this, reason);
841
+ }
842
+ applySelectableAttribute() {
843
+ if (this.options.selectable !== true) return;
844
+ if (!this.element.classList.contains("sdf-selectable")) {
845
+ this.element.classList.add("sdf-selectable");
846
+ this.#sel = true;
847
+ }
848
+ }
849
+ setupObservers() {
850
+ if (this.options.observe === false || this.#d) return;
851
+ const schedule = () => {
852
+ if (this.#d || this.#f !== null) return;
853
+ if (typeof requestAnimationFrame === "function") this.#f = requestAnimationFrame(() => {
854
+ this.#f = null;
855
+ if (this.#d || !this.element.isConnected) return;
856
+ this.rebuild().catch((error) => {
857
+ if (!isAbortError(error)) this.options.onError?.(error);
858
+ });
859
+ });
860
+ };
861
+ if (typeof ResizeObserver !== "undefined") {
862
+ this.#ro = new ResizeObserver(schedule);
863
+ this.#ro.observe(this.element);
864
+ }
865
+ if (typeof MutationObserver !== "undefined") {
866
+ this.#mo = new MutationObserver(schedule);
867
+ this.#mo.observe(this.element, {
868
+ subtree: true,
869
+ childList: true,
870
+ characterData: true,
871
+ attributes: true,
872
+ attributeFilter: [
873
+ "style",
874
+ "class",
875
+ "dir",
876
+ "lang",
877
+ "data-text-depth",
878
+ "data-sdf-depth"
879
+ ]
880
+ });
881
+ }
882
+ const fonts = this.element.ownerDocument.fonts;
883
+ if (fonts && typeof fonts.addEventListener === "function") {
884
+ fonts.addEventListener("loadingdone", schedule);
885
+ this.#uf = () => {
886
+ fonts.removeEventListener("loadingdone", schedule);
887
+ };
888
+ }
889
+ }
890
+ };
891
+ var UNITLESS_CSS = new Set("aspect-ratio columns column-count fill-opacity flex flex-grow flex-shrink font-weight grid-column grid-row line-clamp line-height opacity order orphans scale stroke-opacity tab-size widows z-index zoom".split(" "));
892
+ var BASE_TEXT_STYLE = {
893
+ position: "fixed",
894
+ left: "0",
895
+ top: "0",
896
+ margin: "0",
897
+ pointerEvents: "none",
898
+ userSelect: "none",
899
+ webkitUserSelect: "none",
900
+ visibility: "hidden",
901
+ zIndex: "-2147483648"
902
+ };
903
+ function kebabProperty(name) {
904
+ if (name.startsWith("--")) return name;
905
+ return name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
906
+ }
907
+ function applyBaseStyle(element) {
908
+ for (const [property, value] of Object.entries(BASE_TEXT_STYLE)) element.style.setProperty(kebabProperty(property), value);
909
+ }
910
+ function applyTextCss(element, css) {
911
+ element.removeAttribute("style");
912
+ if (typeof css === "string") element.style.cssText = css;
913
+ else if (css) for (const [rawName, rawValue] of Object.entries(css)) {
914
+ if (rawValue === void 0 || rawValue === null) continue;
915
+ const property = kebabProperty(rawName);
916
+ const value = typeof rawValue === "number" && !property.startsWith("--") && !UNITLESS_CSS.has(property) ? `${String(rawValue)}px` : String(rawValue);
917
+ element.style.setProperty(property, value);
918
+ }
919
+ applyBaseStyle(element);
920
+ }
921
+ function classTokens(cssClass) {
922
+ if (!cssClass) return [];
923
+ return (typeof cssClass === "string" ? [cssClass] : Array.isArray(cssClass) ? cssClass : Object.entries(cssClass).filter(([, enabled]) => Boolean(enabled)).map(([name]) => name)).flatMap((entry) => entry.split(/\s+/)).filter(Boolean);
924
+ }
925
+ function createOwnedTextElement(text, options) {
926
+ const parent = options.parent ?? (typeof document !== "undefined" ? document.body : null);
927
+ if (!parent?.isConnected) throw new Error("VanillaText requires a connected parent element or document.body");
928
+ const element = parent.ownerDocument.createElement("div");
929
+ element.setAttribute("data-sdf-block", "");
930
+ element.setAttribute("aria-hidden", "true");
931
+ element.textContent = text;
932
+ applyTextCss(element, options.css);
933
+ parent.appendChild(element);
934
+ return element;
935
+ }
936
+ function stripTextOnlyOptions(options) {
937
+ const domOptions = { ...options };
938
+ delete domOptions.css;
939
+ delete domOptions.cssClass;
940
+ delete domOptions.parent;
941
+ delete domOptions.device;
942
+ delete domOptions.renderer;
943
+ return domOptions;
944
+ }
945
+ var VanillaText = class VanillaText extends VanillaDomText {
946
+ ready;
947
+ #t;
948
+ #c = [];
949
+ constructor(text, options = {}) {
950
+ options.signal?.throwIfAborted();
951
+ const element = createOwnedTextElement(text, options);
952
+ super(element, options.device ?? options.renderer, stripTextOnlyOptions(options));
953
+ this.#t = text;
954
+ this.#acls(options.cssClass);
955
+ this.ready = this.#p(options.signal);
956
+ }
957
+ async #p(signal) {
958
+ try {
959
+ await this.rebuild(signal ? { signal } : {});
960
+ this.setupObservers();
961
+ this.notify("create");
962
+ return this;
963
+ } catch (error) {
964
+ this.dispose();
965
+ throw error;
966
+ }
967
+ }
968
+ static async create(textOrElement, optionsOrDevice, maybeOptions) {
969
+ if (typeof textOrElement === "string") return new VanillaText(textOrElement, optionsOrDevice ?? {}).ready;
970
+ return super.create(textOrElement, optionsOrDevice, maybeOptions);
971
+ }
972
+ get text() {
973
+ return this.#t;
974
+ }
975
+ set text(value) {
976
+ this.#t = value;
977
+ if (!this.isDisposed) this.element.textContent = value;
978
+ }
979
+ async setText(value, options) {
980
+ this.text = value;
981
+ return this.rebuild(options);
982
+ }
983
+ async setCss(css, options) {
984
+ if (!this.isDisposed) applyTextCss(this.element, css);
985
+ return this.rebuild(options);
986
+ }
987
+ async setClass(cssClass, options) {
988
+ if (!this.isDisposed) this.#acls(cssClass);
989
+ return this.rebuild(options);
990
+ }
991
+ dispose() {
992
+ const wasDisposed = this.isDisposed;
993
+ super.dispose();
994
+ if (!wasDisposed) this.element.remove();
995
+ }
996
+ resolveCaptureTone(snapshot) {
997
+ return resolveDomTextTone(this.element, this.options.tone, {
998
+ glyphs: snapshot.glyphs,
999
+ rects: snapshot.rects,
1000
+ rootRect: this.options.includeRootBackground !== false,
1001
+ page: false
1002
+ });
1003
+ }
1004
+ #acls(cssClass) {
1005
+ if (this.#c.length > 0) this.element.classList.remove(...this.#c);
1006
+ this.#c = classTokens(cssClass);
1007
+ if (this.#c.length > 0) this.element.classList.add(...this.#c);
1008
+ }
1009
+ };
1010
+ export { VanillaDomText as DomSdf, VanillaDomText as DomText, VanillaDomText, VanillaText as Text, VanillaText, UNIT_QUAD_INDICES, UNIT_QUAD_NORMALS, UNIT_QUAD_POSITIONS, buildVanillaSdfAtlas as buildSdfAtlas, buildVanillaSdfAtlas, buildVanillaGpuSdfAtlas, computeInstanceBounds, packGlyphInstances, updateGlyphContentInstances, updateGlyphInstances };
1011
+
1012
+ //# sourceMappingURL=vanillaCore.js.map