ultra-text 1.0.1 → 1.0.3

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