ultra-text 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/README.md +224 -1002
  2. package/dist/assets/{cpuSdf.worker-xS57yQbP.js → cpuSdf.worker--X1Qpmdp.js} +136 -47
  3. package/dist/assets/cpuSdf.worker--X1Qpmdp.js.map +1 -0
  4. package/dist/atlas/appendAtlas.js +67 -25
  5. package/dist/atlas/appendAtlas.js.map +1 -1
  6. package/dist/atlas/buildAtlas.js +3 -2
  7. package/dist/atlas/buildAtlas.js.map +1 -1
  8. package/dist/atlas/cpuAtlas.d.ts +4 -1
  9. package/dist/atlas/cpuAtlas.js +8 -6
  10. package/dist/atlas/cpuAtlas.js.map +1 -1
  11. package/dist/atlas/cpuSdf.js +152 -40
  12. package/dist/atlas/cpuSdf.js.map +1 -1
  13. package/dist/atlas/cpuWorker.d.ts +5 -3
  14. package/dist/atlas/cpuWorker.js +119 -12
  15. package/dist/atlas/cpuWorker.js.map +1 -1
  16. package/dist/atlas/gpuAtlas.js +100 -276
  17. package/dist/atlas/gpuAtlas.js.map +1 -1
  18. package/dist/atlas/gpuCommon.d.ts +135 -0
  19. package/dist/atlas/gpuCommon.js +223 -0
  20. package/dist/atlas/gpuCommon.js.map +1 -0
  21. package/dist/atlas/jfaWgsl.js +47 -241
  22. package/dist/atlas/jfaWgsl.js.map +1 -1
  23. package/dist/atlas/rasterize.js +103 -58
  24. package/dist/atlas/rasterize.js.map +1 -1
  25. package/dist/atlas/shapeRaster.js +2 -1
  26. package/dist/atlas/shapeRaster.js.map +1 -1
  27. package/dist/atlas/vanillaBounds.d.ts +64 -0
  28. package/dist/atlas/vanillaBounds.js +42 -0
  29. package/dist/atlas/vanillaBounds.js.map +1 -0
  30. package/dist/atlas/vanillaCore.d.ts +100 -0
  31. package/dist/atlas/vanillaCore.js +1012 -0
  32. package/dist/atlas/vanillaCore.js.map +1 -0
  33. package/dist/atlas/vanillaCpuAtlas.d.ts +9 -0
  34. package/dist/atlas/vanillaCpuAtlas.js +87 -0
  35. package/dist/atlas/vanillaCpuAtlas.js.map +1 -0
  36. package/dist/atlas/vanillaExtras.d.ts +8 -0
  37. package/dist/atlas/vanillaExtras.js +166 -0
  38. package/dist/atlas/vanillaExtras.js.map +1 -0
  39. package/dist/atlas/vanillaGpuHelpers.d.ts +232 -0
  40. package/dist/atlas/vanillaGpuHelpers.js +119 -0
  41. package/dist/atlas/vanillaGpuHelpers.js.map +1 -0
  42. package/dist/dom/DomSdf.js +224 -284
  43. package/dist/dom/DomSdf.js.map +1 -1
  44. package/dist/dom/DomSlug.js +75 -151
  45. package/dist/dom/DomSlug.js.map +1 -1
  46. package/dist/dom/domAnalytic.d.ts +54 -0
  47. package/dist/dom/domAnalytic.js +282 -0
  48. package/dist/dom/domAnalytic.js.map +1 -0
  49. package/dist/dom/domExtras.d.ts +27 -0
  50. package/dist/dom/domExtras.js +137 -0
  51. package/dist/dom/domExtras.js.map +1 -0
  52. package/dist/dom/fontCanvas.js +27 -9
  53. package/dist/dom/fontCanvas.js.map +1 -1
  54. package/dist/dom/layoutSignature.js +150 -48
  55. package/dist/dom/layoutSignature.js.map +1 -1
  56. package/dist/dom/pretextLayout.js +55 -13
  57. package/dist/dom/pretextLayout.js.map +1 -1
  58. package/dist/dom/snapshot.js +369 -204
  59. package/dist/dom/snapshot.js.map +1 -1
  60. package/dist/dom/svgCapture.d.ts +8 -1
  61. package/dist/dom/svgCapture.js +75 -1
  62. package/dist/dom/svgCapture.js.map +1 -1
  63. package/dist/dom/tone.js +76 -36
  64. package/dist/dom/tone.js.map +1 -1
  65. package/dist/index.js +4 -3
  66. package/dist/slug/SlugMaterial.d.ts +11 -3
  67. package/dist/slug/SlugMaterial.js +54 -10
  68. package/dist/slug/SlugMaterial.js.map +1 -1
  69. package/dist/slug/coverage.d.ts +16 -12
  70. package/dist/slug/coverage.js +194 -221
  71. package/dist/slug/coverage.js.map +1 -1
  72. package/dist/slug/preprocessCore.d.ts +5 -1
  73. package/dist/slug/preprocessCore.js +118 -87
  74. package/dist/slug/preprocessCore.js.map +1 -1
  75. package/dist/slug/runtime.d.ts +1 -0
  76. package/dist/slug/runtime.js +90 -44
  77. package/dist/slug/runtime.js.map +1 -1
  78. package/dist/slug/standaloneRuntime.d.ts +3 -2
  79. package/dist/slug/standaloneRuntime.js +75 -40
  80. package/dist/slug/standaloneRuntime.js.map +1 -1
  81. package/dist/slug/truetype.js +166 -193
  82. package/dist/slug/truetype.js.map +1 -1
  83. package/dist/slug/vanillaCore.d.ts +340 -0
  84. package/dist/slug/vanillaCore.js +1621 -0
  85. package/dist/slug/vanillaCore.js.map +1 -0
  86. package/dist/slug-vanilla.d.ts +13 -364
  87. package/dist/slug-vanilla.js +5 -1453
  88. package/dist/slug.d.ts +1 -1
  89. package/dist/slug.js +6 -6
  90. package/dist/text/GlyphTextMaterial.d.ts +1 -1
  91. package/dist/text/GlyphTextMaterial.js +5 -5
  92. package/dist/text/GlyphTextMaterial.js.map +1 -1
  93. package/dist/text/SdfTextMaterial.js +7 -5
  94. package/dist/text/SdfTextMaterial.js.map +1 -1
  95. package/dist/text/decorations.js +36 -19
  96. package/dist/text/decorations.js.map +1 -1
  97. package/dist/text/geometry.d.ts +3 -22
  98. package/dist/text/geometryUtils.d.ts +11 -1
  99. package/dist/text/geometryUtils.js +22 -1
  100. package/dist/text/geometryUtils.js.map +1 -1
  101. package/dist/text/glyphGeometry.d.ts +9 -0
  102. package/dist/text/glyphGeometry.js +353 -0
  103. package/dist/text/glyphGeometry.js.map +1 -0
  104. package/dist/text/index.d.ts +2 -1
  105. package/dist/text/rectGeometry.d.ts +13 -0
  106. package/dist/text/rectGeometry.js +97 -0
  107. package/dist/text/rectGeometry.js.map +1 -0
  108. package/dist/text/reflow.d.ts +18 -1
  109. package/dist/text/reflow.js +108 -38
  110. package/dist/text/reflow.js.map +1 -1
  111. package/dist/text/snap.d.ts +1 -0
  112. package/dist/text/snap.js +26 -0
  113. package/dist/text/snap.js.map +1 -0
  114. package/dist/vanilla.d.ts +13 -363
  115. package/dist/vanilla.js +6 -1473
  116. package/dist/windfoil/geometry.d.ts +2 -2
  117. package/dist/windfoil/geometry.js +113 -40
  118. package/dist/windfoil/geometry.js.map +1 -1
  119. package/dist/windfoil/mixed.d.ts +1 -0
  120. package/dist/windfoil/mixed.js +44 -25
  121. package/dist/windfoil/mixed.js.map +1 -1
  122. package/dist/windfoil/preprocess.js +2 -2
  123. package/dist/windfoil/preprocessCore.d.ts +1 -0
  124. package/dist/windfoil/preprocessCore.js +9 -4
  125. package/dist/windfoil/preprocessCore.js.map +1 -1
  126. package/dist/windfoil/runtime.d.ts +3 -1
  127. package/dist/windfoil/runtime.js +62 -40
  128. package/dist/windfoil/runtime.js.map +1 -1
  129. package/dist/windfoil/storage.d.ts +60 -2
  130. package/dist/windfoil/storage.js +142 -6
  131. package/dist/windfoil/storage.js.map +1 -1
  132. package/dist/windfoil/trace/contours.d.ts +5 -0
  133. package/dist/windfoil/trace/contours.js +167 -43
  134. package/dist/windfoil/trace/contours.js.map +1 -1
  135. package/dist/windfoil/trace/fit.d.ts +3 -1
  136. package/dist/windfoil/trace/fit.js +471 -175
  137. package/dist/windfoil/trace/fit.js.map +1 -1
  138. package/dist/windfoil/trace/outline.js +55 -30
  139. package/dist/windfoil/trace/outline.js.map +1 -1
  140. package/dist/windfoil/trace/types.d.ts +10 -0
  141. package/dist/windfoil/tracedOutlines.js +59 -34
  142. package/dist/windfoil/tracedOutlines.js.map +1 -1
  143. package/package.json +11 -11
  144. package/skills/ultra-text/references/three-tsl.md +2 -2
  145. package/skills/ultra-text/references/vanilla-webgpu.md +3 -2
  146. package/dist/assets/cpuSdf.worker-xS57yQbP.js.map +0 -1
  147. package/dist/slug-vanilla.js.map +0 -1
  148. package/dist/text/geometry.js +0 -348
  149. package/dist/text/geometry.js.map +0 -1
  150. package/dist/vanilla.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"tracedOutlines.js","names":[],"sources":["../../src/windfoil/tracedOutlines.ts"],"sourcesContent":["import {\n allFontsLoaded,\n createCanvas,\n isColorCandidate,\n setFontContext,\n waitForFonts,\n} from '../dom/fontCanvas.js'\nimport type {\n ColorGlyphMode,\n FontStyleSnapshot,\n GlyphRequest,\n WindfoilGlyphOutline,\n WindfoilOutlineProvider,\n} from '../types.js'\nimport { createTraceScratch, traceCoverage } from './trace/outline.js'\n\n/** Options of the built-in Canvas 2D outline tracer. */\nexport interface TracedOutlineOptions {\n /** Trace resolution in pixels per em, also each outline's `unitsPerEm`. Defaults to `256`. */\n readonly size?: number\n /** Furthest, in trace pixels, a fitted curve may stray from its contour. Defaults to `0.25`. */\n readonly tolerance?: number\n /** Which glyphs to test for colour ink, as `DomSdfOptions.colorGlyphs`. Defaults to `'emoji'`. */\n readonly colorGlyphs?: ColorGlyphMode\n}\n\n/** A `WindfoilOutlineProvider` that traces the browser's own glyphs, and its cache. */\nexport interface TracedOutlines {\n readonly provider: WindfoilOutlineProvider\n /** Forgets every traced outline, as after a webfont load; work in flight is not kept. */\n clear(): void\n /** Forgets the outlines of every glyph key not listed. */\n retain(keys: Iterable<string>): void\n}\n\n/** A batch yields to the page once it has traced for this long. */\nconst SLICE_MS = 8\n/** A font assignment the canvas rejects leaves this one in place. */\nconst SENTINEL_FONT = '1px serif'\nconst SIZE_TOKEN = /[\\d.]+px/\n\n/** The requests one task made with one signal, traced together. */\ninterface Batch {\n readonly signal: AbortSignal\n readonly requests: Map<string, GlyphRequest>\n readonly done: Promise<ReadonlyMap<string, WindfoilGlyphOutline | null>>\n}\n\n/** One glyph between measuring and tracing, in trace pixels; y grows downwards. */\ninterface Measured {\n readonly request: GlyphRequest\n readonly ascent: number\n readonly descent: number\n /** How far the ink box and the font box reach from the pen: left, right, up and down. */\n readonly reach: readonly [number, number, number, number]\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n if (signal.aborted) {\n throw signal.reason ?? new DOMException('The outline trace was aborted', 'AbortError')\n }\n}\n\n/**\n * A task after the page's own: a message is not clamped to 4 ms as a nested timer is, and it\n * does not run ahead of rendering as a `scheduler.yield()` continuation does, which held frames\n * back for 100 ms at a time in Chrome 156.\n */\nfunction nextTask(): Promise<void> {\n return new Promise((resolve) => {\n if (typeof MessageChannel !== 'function') {\n setTimeout(resolve, 0)\n return\n }\n const { port1, port2 } = new MessageChannel()\n port1.onmessage = () => {\n port1.close()\n resolve()\n }\n port2.postMessage(null)\n })\n}\n\n/** Canvas box of a glyph with `margin` pixels around its reach: pen position and size. */\nfunction boxOf(\n reach: Measured['reach'],\n margin: number,\n): [originX: number, baselineY: number, width: number, height: number] {\n const originX = margin + Math.ceil(reach[0])\n const baselineY = margin + Math.ceil(reach[2])\n return [\n originX,\n baselineY,\n originX + Math.ceil(reach[1]) + margin,\n baselineY + Math.ceil(reach[3]) + margin,\n ]\n}\n\n/** Whether any texel on the edge of a `width` x `height` RGBA read holds ink. */\nfunction touchesEdge(\n rgba: Uint8ClampedArray,\n width: number,\n height: number,\n rowStride = width * 4,\n baseOffset = 0,\n): boolean {\n for (let x = 0; x < width; x++) {\n if (\n rgba[baseOffset + x * 4 + 3]! > 0 ||\n rgba[baseOffset + (height - 1) * rowStride + x * 4 + 3]! > 0\n ) {\n return true\n }\n }\n for (let y = 0; y < height; y++) {\n const row = baseOffset + y * rowStride\n if (rgba[row + 3]! > 0 || rgba[row + (width - 1) * 4 + 3]! > 0) return true\n }\n return false\n}\n\nconst MAX_SHEET = 2048\nconst SHEET_GAP = 1\n\n/**\n * The outline provider `DomSdf` and `DomSlug` use for Windfoil and Slug text when the caller gives\n * none. Each glyph is drawn as the SDF rasterizer draws it (the captured canvas font with its\n * stretch and kerning, an in-document canvas without font smoothing, exact geometry, a neutral\n * grey), at `size` pixels per em, then traced at half coverage and fitted with quadratics. The\n * outline follows that raster, not the font file: font-variation and feature settings are not\n * applied, as on any canvas. Colour glyphs, glyphs of a font the canvas rejects and shaped runs\n * resolve to `null`, for the SDF companion; a glyph without ink to an empty outline. Without a\n * 2D canvas every glyph is `null`, so the whole capture falls back to SDF. `descent` is the SDF\n * slot's, measured at the captured font's own size, so analytic and SDF glyphs share a baseline.\n * Ink the metrics miss is drawn again with half an em more room all round; a glyph whose ink\n * still reaches the edge of its box resolves to `null` too, rather than trace clipped.\n *\n * Calls made in one task with one signal trace as one batch, in slices of about 8 ms between\n * which the page runs and the signal is checked. Each batch has its own working memory, which\n * goes with it. Outlines stay cached per instance until `clear()` or `retain()` drops them; one\n * traced while `document.fonts.check()` still reported its font as not ready is never cached.\n */\nexport function createTracedOutlineProvider(\n document: Document,\n options: TracedOutlineOptions = {},\n): TracedOutlines {\n const size = options.size ?? 256\n const tolerance = options.tolerance ?? 0.25\n const colorGlyphs = options.colorGlyphs ?? 'emoji'\n const cache = new Map<string, WindfoilGlyphOutline | null>()\n let epoch = 0\n /** The batches still open to requests of this task, by signal. */\n const open = new Map<AbortSignal, Batch>()\n\n const run = async (\n signal: AbortSignal,\n requests: ReadonlyMap<string, GlyphRequest>,\n started: number,\n ): Promise<ReadonlyMap<string, WindfoilGlyphOutline | null>> => {\n const results = new Map<string, WindfoilGlyphOutline | null>()\n // Each font of the batch, as captured and as traced: the captured canvas font with only\n // its size rewritten, as an adaptive SDF bake does.\n const groups = new Map<string, [GlyphRequest[], FontStyleSnapshot]>()\n for (const request of requests.values()) {\n // Shapes resolve elsewhere; a shaped run is one tile of a line, which no outline covers.\n if (request.shape || request.shaping) {\n results.set(request.key, null)\n continue\n }\n const group = groups.get(request.font.key)\n if (group) group[0].push(request)\n else {\n const font = request.font\n groups.set(font.key, [\n [request],\n { ...font, canvasFont: font.canvasFont.replace(SIZE_TOKEN, `${size}px`) },\n ])\n }\n }\n const traced = (request: GlyphRequest): GlyphRequest => ({\n ...request,\n font: groups.get(request.font.key)![1],\n })\n await waitForFonts(\n document,\n [...groups.values()].flatMap(([list]) => list.map(traced)),\n signal,\n )\n throwIfAborted(signal)\n\n const preloaded = allFontsLoaded(document)\n const fonts = document.fonts as FontFaceSet | undefined\n const keep = (request: GlyphRequest, outline: WindfoilGlyphOutline | null): void => {\n results.set(request.key, outline)\n let ready = epoch === started\n if (ready && !preloaded) {\n try {\n ready = fonts?.check(traced(request).font.canvasFont, request.character) ?? true\n } catch {\n ready = false\n }\n }\n if (ready) cache.set(request.key, outline)\n }\n\n const canvas = createCanvas(document)\n try {\n const context = canvas.getContext('2d', { willReadFrequently: true })\n if (!context) {\n // Not cached: the whole capture falls back to SDF, and a later build may try again.\n for (const [list] of groups.values())\n for (const request of list) results.set(request.key, null)\n return results\n }\n let current: FontStyleSnapshot | null = null\n const accepted = new Map<FontStyleSnapshot, boolean>()\n /** Applies a request's font as the rasterizer does; false when the canvas rejected it. */\n const use = (request: GlyphRequest): boolean => {\n if (current !== request.font) {\n context.font = SENTINEL_FONT\n const sentinel = context.font\n setFontContext(context, request, undefined, null)\n current = request.font\n accepted.set(request.font, context.font !== sentinel)\n }\n return accepted.get(request.font)!\n }\n\n // Measure every glyph first: sizing the canvas resets its context.\n const margin = Math.max(4, Math.ceil(size / 32))\n const measured: Measured[] = []\n let canvasWidth = 1\n let canvasHeight = 1\n for (const [list] of groups.values()) {\n throwIfAborted(signal)\n const bake = Number.parseFloat(SIZE_TOKEN.exec(list[0]!.font.canvasFont)?.[0] ?? '')\n if (!(bake > 0) || !use(list[0]!)) {\n for (const request of list) keep(request, null)\n continue\n }\n // The SDF slot's metrics, measured at the captured font's own size.\n const scale = size / bake\n const slots = list.map((request) => {\n const slot = context.measureText(request.character)\n return [\n Math.max(1, slot.fontBoundingBoxAscent || slot.actualBoundingBoxAscent) * scale,\n Math.max(1, slot.fontBoundingBoxDescent || slot.actualBoundingBoxDescent) * scale,\n ] as const\n })\n if (!use(traced(list[0]!))) {\n for (const request of list) keep(request, null)\n continue\n }\n list.forEach((request, index) => {\n const [ascent, descent] = slots[index]!\n // Ink can only be found in the ink box and the font box.\n const metrics = context.measureText(request.character)\n const reach = [\n Math.max(0, metrics.actualBoundingBoxLeft || 0),\n Math.max(metrics.width || 0, metrics.actualBoundingBoxRight || 0),\n Math.max(ascent, metrics.actualBoundingBoxAscent || 0),\n Math.max(descent, metrics.actualBoundingBoxDescent || 0),\n ] as const\n const [, , width, height] = boxOf(reach, margin)\n if (!(width <= 8 * size && height <= 8 * size)) {\n keep(request, null)\n return\n }\n canvasWidth = Math.max(canvasWidth, width)\n canvasHeight = Math.max(canvasHeight, height)\n measured.push({ request: traced(request), ascent, descent, reach })\n })\n }\n const resize = (width: number, height: number): void => {\n if (width <= canvas.width && height <= canvas.height) return\n canvas.width = Math.max(width, canvas.width)\n canvas.height = Math.max(height, canvas.height)\n current = null\n }\n resize(canvasWidth, canvasHeight)\n\n const exact = 'textRendering' in context\n const draw = (\n glyph: Measured,\n [originX, baselineY, width, height]: ReturnType<typeof boxOf>,\n fill: string,\n rendering: CanvasTextRendering,\n ): Uint8ClampedArray => {\n resize(width, height)\n use(glyph.request)\n context.fillStyle = fill\n if (exact) context.textRendering = rendering\n context.clearRect(0, 0, width, height)\n context.fillText(glyph.request.character, originX, baselineY)\n return context.getImageData(0, 0, width, height).data\n }\n const colorModule = measured.some((glyph) => isColorCandidate(glyph.request, colorGlyphs))\n ? await import('../atlas/colorGlyphs.js')\n : null\n throwIfAborted(signal)\n // This batch's working memory, grown to fit its largest glyph (about 1 MB at 256 px per\n // em) and released with the batch, so an idle tracer holds none.\n const scratch = createTraceScratch()\n let sliceStart = performance.now()\n const view = document.defaultView\n const getContextFn = view\n ? (Object.getOwnPropertyDescriptor(view.HTMLCanvasElement.prototype, 'getContext')\n ?.value as object | undefined)\n : undefined\n const mockedCanvas = !getContextFn || 'mock' in getContextFn\n const finishGlyph = async (\n glyph: Measured,\n box: ReturnType<typeof boxOf>,\n retried: boolean,\n ): Promise<void> => {\n // The SDF bake's text rendering: exact geometry, the neutral middle of a contrast table.\n let currentBox = box\n let rgba = draw(glyph, currentBox, '#606060', 'geometricPrecision')\n let clipped = touchesEdge(rgba, currentBox[2], currentBox[3])\n if (clipped && !retried) {\n // The metrics missed some ink: once more with half an em of room all round.\n currentBox = boxOf(glyph.reach, margin + size / 2)\n rgba = draw(glyph, currentBox, '#606060', 'geometricPrecision')\n clipped = touchesEdge(rgba, currentBox[2], currentBox[3])\n }\n // Ink past even that room would trace clipped: the SDF companion draws the glyph.\n let outline: WindfoilGlyphOutline | null = null\n if (!clipped) {\n const { quadratics, bbox } = traceCoverage(\n {\n alpha: rgba,\n width: currentBox[2],\n height: currentBox[3],\n stride: 4,\n offset: 3,\n originX: currentBox[0],\n baselineY: currentBox[1],\n },\n tolerance,\n scratch,\n )\n outline = {\n unitsPerEm: size,\n ascent: glyph.ascent,\n descent: -glyph.descent,\n bbox,\n quadratics,\n }\n }\n keep(requests.get(glyph.request.key)!, outline)\n if (performance.now() - sliceStart > SLICE_MS) {\n await nextTask()\n throwIfAborted(signal)\n sliceStart = performance.now()\n }\n }\n\n if (mockedCanvas || measured.length < 2) {\n for (const glyph of measured) {\n throwIfAborted(signal)\n const box = boxOf(glyph.reach, margin)\n const [, , width, height] = box\n // A candidate the font draws in the fill colour alone is text, as in the SDF bake:\n // only ink that ignores the fill goes to the companion.\n const colored =\n colorModule !== null &&\n isColorCandidate(glyph.request, colorGlyphs) &&\n colorModule.encodeColorBand(\n draw(glyph, box, '#fff', 'auto'),\n draw(glyph, box, '#000', 'auto'),\n width,\n height,\n 0,\n [{ x: 0, y: 0, width, height }],\n ).colored[0] === true\n if (colored) {\n keep(requests.get(glyph.request.key)!, null)\n if (performance.now() - sliceStart > SLICE_MS) {\n await nextTask()\n throwIfAborted(signal)\n sliceStart = performance.now()\n }\n continue\n }\n await finishGlyph(glyph, box, false)\n }\n } else {\n interface Tile {\n readonly glyph: Measured\n readonly box: ReturnType<typeof boxOf>\n readonly x: number\n readonly y: number\n }\n const plain: { readonly glyph: Measured; readonly box: ReturnType<typeof boxOf> }[] = []\n const oversized: { readonly glyph: Measured; readonly box: ReturnType<typeof boxOf> }[] = []\n const retries: Measured[] = []\n for (const glyph of measured) {\n throwIfAborted(signal)\n const box = boxOf(glyph.reach, margin)\n const [, , width, height] = box\n const colored =\n colorModule !== null &&\n isColorCandidate(glyph.request, colorGlyphs) &&\n colorModule.encodeColorBand(\n draw(glyph, box, '#fff', 'auto'),\n draw(glyph, box, '#000', 'auto'),\n width,\n height,\n 0,\n [{ x: 0, y: 0, width, height }],\n ).colored[0] === true\n if (colored) {\n keep(requests.get(glyph.request.key)!, null)\n continue\n }\n if (width > MAX_SHEET || height > MAX_SHEET) oversized.push({ glyph, box })\n else plain.push({ glyph, box })\n }\n\n const flushSheet = async (sheet: Tile[], sheetW: number, sheetH: number): Promise<void> => {\n resize(sheetW, sheetH)\n context.clearRect(0, 0, sheetW, sheetH)\n context.fillStyle = '#606060'\n if (exact) context.textRendering = 'geometricPrecision'\n for (const item of sheet) {\n throwIfAborted(signal)\n use(item.glyph.request)\n context.fillText(\n item.glyph.request.character,\n item.x + item.box[0],\n item.y + item.box[1],\n )\n }\n const rgba = context.getImageData(0, 0, sheetW, sheetH).data\n const rowStride = sheetW * 4\n for (const item of sheet) {\n throwIfAborted(signal)\n const [originX, baselineY, width, height] = item.box\n const tileOffset = (item.y * sheetW + item.x) * 4\n if (touchesEdge(rgba, width, height, rowStride, tileOffset)) {\n retries.push(item.glyph)\n continue\n }\n const { quadratics, bbox } = traceCoverage(\n {\n alpha: rgba,\n width,\n height,\n stride: 4,\n offset: tileOffset + 3,\n rowStride,\n originX,\n baselineY,\n },\n tolerance,\n scratch,\n )\n keep(requests.get(item.glyph.request.key)!, {\n unitsPerEm: size,\n ascent: item.glyph.ascent,\n descent: -item.glyph.descent,\n bbox,\n quadratics,\n })\n if (performance.now() - sliceStart > SLICE_MS) {\n await nextTask()\n throwIfAborted(signal)\n sliceStart = performance.now()\n }\n }\n }\n\n if (plain.length < 2) {\n for (const item of plain) {\n throwIfAborted(signal)\n await finishGlyph(item.glyph, item.box, false)\n }\n } else {\n let sheet: Tile[] = []\n let packX = 0\n let packY = 0\n let rowH = 0\n let sheetW = 0\n let sheetH = 0\n for (const { glyph, box } of plain) {\n const width = box[2]\n const height = box[3]\n if (packX > 0 && packX + width > MAX_SHEET) {\n packX = 0\n packY += rowH + SHEET_GAP\n rowH = 0\n }\n if (packY + height > MAX_SHEET) {\n await flushSheet(sheet, sheetW, sheetH)\n sheet = []\n packX = 0\n packY = 0\n rowH = 0\n sheetW = 0\n sheetH = 0\n }\n sheet.push({ glyph, box, x: packX, y: packY })\n sheetW = Math.max(sheetW, packX + width)\n sheetH = Math.max(sheetH, packY + height)\n packX += width + SHEET_GAP\n rowH = Math.max(rowH, height)\n }\n if (sheet.length > 0) await flushSheet(sheet, sheetW, sheetH)\n }\n for (const item of oversized) {\n throwIfAborted(signal)\n await finishGlyph(item.glyph, item.box, false)\n }\n for (const glyph of retries) {\n throwIfAborted(signal)\n await finishGlyph(glyph, boxOf(glyph.reach, margin + size / 2), true)\n }\n }\n return results\n } finally {\n // Release the backing store now: Safari counts a detached canvas against its canvas\n // memory until it is collected.\n canvas.width = 0\n canvas.height = 0\n canvas.remove()\n }\n }\n\n const provider: WindfoilOutlineProvider = (request, signal) => {\n throwIfAborted(signal)\n const cached = cache.get(request.key)\n if (cached !== undefined) return cached\n let batch = open.get(signal)\n if (!batch) {\n const requests = new Map<string, GlyphRequest>()\n // Everything this task asks for with this signal joins before the batch starts. What a\n // clear() before then would drop is not cached either.\n const started = epoch\n const next: Batch = {\n signal,\n requests,\n done: Promise.resolve().then(() => {\n if (open.get(signal) === next) open.delete(signal)\n return run(signal, requests, started)\n }),\n }\n open.set(signal, (batch = next))\n }\n batch.requests.set(request.key, request)\n return batch.done.then((results) => results.get(request.key) ?? null)\n }\n\n return {\n provider,\n clear() {\n epoch++\n cache.clear()\n },\n retain(keys) {\n const live = new Set(keys)\n for (const key of cache.keys()) if (!live.has(key)) cache.delete(key)\n },\n }\n}\n"],"mappings":";;;;AAoCA,IAAM,WAAW;;AAEjB,IAAM,gBAAgB;AACtB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W,IAAI,IAA0B;GAG/C,MAAM,UAAU;GAChB,MAAM,OAAc;IAClB;IACA;IACA,MAAM,QAAQ,QAAQ,CAAC,CAAC,WAAW;KACjC,IAAI,KAAK,IAAI,MAAM,MAAM,MAAM,KAAK,OAAO,MAAM;KACjD,OAAO,IAAI,QAAQ,UAAU,OAAO;IACtC,CAAC;GACH;GACA,KAAK,IAAI,QAAS,QAAQ,IAAK;EACjC;EACA,MAAM,SAAS,IAAI,QAAQ,KAAK,OAAO;EACvC,OAAO,MAAM,KAAK,MAAM,YAAY,QAAQ,IAAI,QAAQ,GAAG,KAAK,IAAI;CACtE;CAEA,OAAO;EACL;EACA,QAAQ;GACN;GACA,MAAM,MAAM;EACd;EACA,OAAO,MAAM;GACX,MAAM,OAAO,IAAI,IAAI,IAAI;GACzB,KAAK,MAAM,OAAO,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,GAAG,GAAG,MAAM,OAAO,GAAG;EACtE;CACF;AACF"}
1
+ {"version":3,"file":"tracedOutlines.js","names":[],"sources":["../../src/windfoil/tracedOutlines.ts"],"sourcesContent":["import {\n allFontsLoaded,\n createCanvas,\n isColorCandidate,\n setFontContext,\n waitForFonts,\n} from '../dom/fontCanvas.js'\nimport type {\n ColorGlyphMode,\n FontStyleSnapshot,\n GlyphRequest,\n WindfoilGlyphOutline,\n WindfoilOutlineProvider,\n} from '../types.js'\nimport { createTraceScratch, traceCoverage } from './trace/outline.js'\n\n/** Options of the built-in Canvas 2D outline tracer. */\nexport interface TracedOutlineOptions {\n /** Trace resolution in pixels per em, also each outline's `unitsPerEm`. Defaults to `256`. */\n readonly size?: number\n /** Furthest, in trace pixels, a fitted curve may stray from its contour. Defaults to `0.25`. */\n readonly tolerance?: number\n /** Which glyphs to test for colour ink, as `DomSdfOptions.colorGlyphs`. Defaults to `'emoji'`. */\n readonly colorGlyphs?: ColorGlyphMode\n}\n\n/** A `WindfoilOutlineProvider` that traces the browser's own glyphs, and its cache. */\nexport interface TracedOutlines {\n readonly provider: WindfoilOutlineProvider\n /** Forgets every traced outline, as after a webfont load; work in flight is not kept. */\n clear(): void\n /** Forgets the outlines of every glyph key not listed. */\n retain(keys: Iterable<string>): void\n}\n\n/** A batch yields to the page once it has traced for this long. */\nconst SLICE_MS = 8\n/** A font assignment the canvas rejects leaves this one in place. */\nconst SENTINEL_FONT = '1px serif'\nconst SIZE_TOKEN = /[\\d.]+px/\n\n/** The requests one task made with one signal, traced together. */\ninterface Batch {\n readonly signal: AbortSignal\n readonly requests: Map<string, GlyphRequest>\n readonly done: Promise<ReadonlyMap<string, WindfoilGlyphOutline | null>>\n}\n\n/** One glyph between measuring and tracing, in trace pixels; y grows downwards. */\ninterface Measured {\n readonly request: GlyphRequest\n readonly ascent: number\n readonly descent: number\n /** How far the ink box and the font box reach from the pen: left, right, up and down. */\n readonly reach: readonly [number, number, number, number]\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n if (signal.aborted) {\n throw signal.reason ?? new DOMException('The outline trace was aborted', 'AbortError')\n }\n}\n\n/**\n * A task after the page's own: a message is not clamped to 4 ms as a nested timer is, and it\n * does not run ahead of rendering as a `scheduler.yield()` continuation does, which held frames\n * back for 100 ms at a time in Chrome 156.\n */\nfunction nextTask(): Promise<void> {\n return new Promise((resolve) => {\n if (typeof MessageChannel !== 'function') {\n setTimeout(resolve, 0)\n return\n }\n const { port1, port2 } = new MessageChannel()\n port1.onmessage = () => {\n port1.close()\n resolve()\n }\n port2.postMessage(null)\n })\n}\n\n/** Canvas box of a glyph with `margin` pixels around its reach: pen position and size. */\nfunction boxOf(\n reach: Measured['reach'],\n margin: number,\n): [originX: number, baselineY: number, width: number, height: number] {\n const originX = margin + Math.ceil(reach[0])\n const baselineY = margin + Math.ceil(reach[2])\n return [\n originX,\n baselineY,\n originX + Math.ceil(reach[1]) + margin,\n baselineY + Math.ceil(reach[3]) + margin,\n ]\n}\n\n/** Whether any texel on the edge of a `width` x `height` RGBA read holds ink. */\nfunction touchesEdge(\n rgba: Uint8ClampedArray,\n width: number,\n height: number,\n rowStride = width * 4,\n baseOffset = 0,\n): boolean {\n for (let x = 0; x < width; x++) {\n if (\n rgba[baseOffset + x * 4 + 3]! > 0 ||\n rgba[baseOffset + (height - 1) * rowStride + x * 4 + 3]! > 0\n ) {\n return true\n }\n }\n for (let y = 0; y < height; y++) {\n const row = baseOffset + y * rowStride\n if (rgba[row + 3]! > 0 || rgba[row + (width - 1) * 4 + 3]! > 0) return true\n }\n return false\n}\n\nconst MAX_SHEET = 2048\nconst SHEET_GAP = 1\n\n/**\n * The outline provider `DomSdf` and `DomSlug` use for Windfoil and Slug text when the caller gives\n * none. Each glyph is drawn as the SDF rasterizer draws it (the captured canvas font with its\n * stretch and kerning, an in-document canvas without font smoothing, exact geometry, a neutral\n * grey), at `size` pixels per em, then traced at half coverage and fitted with quadratics. The\n * outline follows that raster, not the font file: font-variation and feature settings are not\n * applied, as on any canvas. Colour glyphs, glyphs of a font the canvas rejects and shaped runs\n * resolve to `null`, for the SDF companion; a glyph without ink to an empty outline. Without a\n * 2D canvas every glyph is `null`, so the whole capture falls back to SDF. `descent` is the SDF\n * slot's, measured at the captured font's own size, so analytic and SDF glyphs share a baseline.\n * Ink the metrics miss is drawn again with half an em more room all round; a glyph whose ink\n * still reaches the edge of its box resolves to `null` too, rather than trace clipped.\n *\n * Calls made in one task with one signal trace as one batch, in slices of about 8 ms between\n * which the page runs and the signal is checked. Each batch has its own working memory, which\n * goes with it. Outlines stay cached per instance until `clear()` or `retain()` drops them; one\n * traced while `document.fonts.check()` still reported its font as not ready is never cached.\n */\nexport function createTracedOutlineProvider(\n document: Document,\n options: TracedOutlineOptions = {},\n): TracedOutlines {\n const size = options.size ?? 256\n const tolerance = options.tolerance ?? 0.25\n const colorGlyphs = options.colorGlyphs ?? 'emoji'\n const cache = new Map<string, WindfoilGlyphOutline | null>()\n let epoch = 0\n let cachedCanvas: HTMLCanvasElement | null = null\n let cachedContext: CanvasRenderingContext2D | null = null\n /** The batches still open to requests of this task, by signal. */\n const open = new Map<AbortSignal, Batch>()\n\n const run = async (\n signal: AbortSignal,\n requests: ReadonlyMap<string, GlyphRequest>,\n started: number,\n ): Promise<ReadonlyMap<string, WindfoilGlyphOutline | null>> => {\n const results = new Map<string, WindfoilGlyphOutline | null>()\n // Each font of the batch, as captured and as traced: the captured canvas font with only\n // its size rewritten, as an adaptive SDF bake does.\n const groups = new Map<string, [GlyphRequest[], GlyphRequest[], FontStyleSnapshot]>()\n const waitList: GlyphRequest[] = []\n for (const request of requests.values()) {\n // Shapes resolve elsewhere; a shaped run is one tile of a line, which no outline covers.\n if (request.shape || request.shaping) {\n results.set(request.key, null)\n continue\n }\n let group = groups.get(request.font.key)\n if (!group) {\n const font = request.font\n group = [[], [], { ...font, canvasFont: font.canvasFont.replace(SIZE_TOKEN, `${size}px`) }]\n groups.set(font.key, group)\n }\n const tracedReq: GlyphRequest = {\n key: request.key,\n character: request.character,\n font: group[2],\n }\n group[0].push(request)\n group[1].push(tracedReq)\n waitList.push(tracedReq)\n }\n await waitForFonts(document, waitList, signal)\n throwIfAborted(signal)\n\n const preloaded = allFontsLoaded(document)\n const fonts = document.fonts as FontFaceSet | undefined\n const keep = (request: GlyphRequest, outline: WindfoilGlyphOutline | null): void => {\n results.set(request.key, outline)\n let ready = epoch === started\n if (ready && !preloaded) {\n try {\n ready =\n fonts?.check(groups.get(request.font.key)![2].canvasFont, request.character) ?? true\n } catch {\n ready = false\n }\n }\n if (ready) cache.set(request.key, outline)\n }\n\n let canvas: HTMLCanvasElement\n let context: CanvasRenderingContext2D | null\n if (cachedCanvas?.ownerDocument === document && cachedContext) {\n canvas = cachedCanvas\n canvas.width = 1\n canvas.height = 1\n document.documentElement.append(canvas)\n context = cachedContext\n } else {\n canvas = createCanvas(document)\n context = canvas.getContext('2d', { willReadFrequently: true })\n if (context) {\n cachedCanvas = canvas\n cachedContext = context\n }\n }\n try {\n if (!context) {\n // Not cached: the whole capture falls back to SDF, and a later build may try again.\n for (const [list] of groups.values())\n for (const request of list) results.set(request.key, null)\n return results\n }\n let current: FontStyleSnapshot | null = null\n const accepted = new Map<FontStyleSnapshot, boolean>()\n /** Applies a request's font as the rasterizer does; false when the canvas rejected it. */\n const use = (request: GlyphRequest): boolean => {\n if (current !== request.font) {\n context.font = SENTINEL_FONT\n const sentinel = context.font\n setFontContext(context, request, undefined, null)\n current = request.font\n accepted.set(request.font, context.font !== sentinel)\n }\n return accepted.get(request.font)!\n }\n\n // Measure every glyph first: sizing the canvas resets its context.\n const margin = Math.max(4, Math.ceil(size / 32))\n const measured: Measured[] = []\n for (const [list, tracedList] of groups.values()) {\n throwIfAborted(signal)\n const bake = Number.parseFloat(SIZE_TOKEN.exec(list[0]!.font.canvasFont)?.[0] ?? '')\n if (!(bake > 0) || !use(list[0]!)) {\n for (const request of list) keep(request, null)\n continue\n }\n // The SDF slot's metrics, measured at the captured font's own size.\n const scale = size / bake\n const slots = list.map((request) => {\n const slot = context.measureText(request.character)\n return [\n Math.max(1, slot.fontBoundingBoxAscent || slot.actualBoundingBoxAscent) * scale,\n Math.max(1, slot.fontBoundingBoxDescent || slot.actualBoundingBoxDescent) * scale,\n ] as const\n })\n if (!use(tracedList[0]!)) {\n for (const request of list) keep(request, null)\n continue\n }\n for (let index = 0; index < list.length; index++) {\n const request = list[index]!\n const tracedReq = tracedList[index]!\n const [ascent, descent] = slots[index]!\n // Ink can only be found in the tight actual bounding box when reported, or the font box.\n const metrics = context.measureText(request.character)\n const hasHBox = metrics.actualBoundingBoxLeft > 0 || metrics.actualBoundingBoxRight > 0\n const hasVBox =\n metrics.actualBoundingBoxAscent > 0 || metrics.actualBoundingBoxDescent > 0\n const reach = [\n Math.max(0, metrics.actualBoundingBoxLeft || 0),\n Math.max(hasHBox ? 0 : metrics.width || 0, metrics.actualBoundingBoxRight || 0),\n Math.max(hasVBox ? 0 : ascent, metrics.actualBoundingBoxAscent || 0),\n Math.max(hasVBox ? 0 : descent, metrics.actualBoundingBoxDescent || 0),\n ] as const\n const [, , width, height] = boxOf(reach, margin)\n if (!(width <= 8 * size && height <= 8 * size)) {\n keep(request, null)\n continue\n }\n measured.push({ request: tracedReq, ascent, descent, reach })\n }\n }\n const resize = (width: number, height: number): boolean => {\n if (width <= canvas.width && height <= canvas.height) return false\n canvas.width = Math.max(width, canvas.width)\n canvas.height = Math.max(height, canvas.height)\n current = null\n return true\n }\n\n const exact = 'textRendering' in context\n const draw = (\n glyph: Measured,\n [originX, baselineY, width, height]: ReturnType<typeof boxOf>,\n fill: string,\n rendering: CanvasTextRendering,\n ): Uint8ClampedArray => {\n const resized = resize(width, height)\n use(glyph.request)\n context.fillStyle = fill\n if (exact) context.textRendering = rendering\n if (!resized) context.clearRect(0, 0, width, height)\n context.fillText(glyph.request.character, originX, baselineY)\n return context.getImageData(0, 0, width, height).data\n }\n const colorModule = measured.some((glyph) => isColorCandidate(glyph.request, colorGlyphs))\n ? await import('../atlas/colorGlyphs.js')\n : null\n throwIfAborted(signal)\n // This batch's working memory, grown to fit its largest glyph (about 1 MB at 256 px per\n // em) and released with the batch, so an idle tracer holds none.\n const scratch = createTraceScratch()\n let sliceStart = performance.now()\n const view = document.defaultView\n const getContextFn = view\n ? (Object.getOwnPropertyDescriptor(view.HTMLCanvasElement.prototype, 'getContext')\n ?.value as object | undefined)\n : undefined\n const mockedCanvas = !getContextFn || 'mock' in getContextFn\n const finishGlyph = async (\n glyph: Measured,\n box: ReturnType<typeof boxOf>,\n retried: boolean,\n ): Promise<void> => {\n // The SDF bake's text rendering: exact geometry, the neutral middle of a contrast table.\n let currentBox = box\n let rgba = draw(glyph, currentBox, '#606060', 'geometricPrecision')\n let clipped = touchesEdge(rgba, currentBox[2], currentBox[3])\n if (clipped && !retried) {\n // The metrics missed some ink: once more with half an em of room all round.\n currentBox = boxOf(glyph.reach, margin + size / 2)\n rgba = draw(glyph, currentBox, '#606060', 'geometricPrecision')\n clipped = touchesEdge(rgba, currentBox[2], currentBox[3])\n }\n // Ink past even that room would trace clipped: the SDF companion draws the glyph.\n let outline: WindfoilGlyphOutline | null = null\n if (!clipped) {\n const { quadratics, bbox } = traceCoverage(\n {\n alpha: rgba,\n width: currentBox[2],\n height: currentBox[3],\n stride: 4,\n offset: 3,\n originX: currentBox[0],\n baselineY: currentBox[1],\n },\n tolerance,\n scratch,\n )\n outline = {\n unitsPerEm: size,\n ascent: glyph.ascent,\n descent: -glyph.descent,\n bbox,\n quadratics,\n }\n }\n keep(requests.get(glyph.request.key)!, outline)\n if (performance.now() - sliceStart > SLICE_MS) {\n await nextTask()\n throwIfAborted(signal)\n sliceStart = performance.now()\n }\n }\n\n if (mockedCanvas || measured.length < 2) {\n for (const glyph of measured) {\n throwIfAborted(signal)\n const box = boxOf(glyph.reach, margin)\n const [, , width, height] = box\n // A candidate the font draws in the fill colour alone is text, as in the SDF bake:\n // only ink that ignores the fill goes to the companion.\n const colored =\n colorModule !== null &&\n isColorCandidate(glyph.request, colorGlyphs) &&\n colorModule.encodeColorBand(\n draw(glyph, box, '#fff', 'auto'),\n draw(glyph, box, '#000', 'auto'),\n width,\n height,\n 0,\n [{ x: 0, y: 0, width, height }],\n ).colored[0] === true\n if (colored) {\n keep(requests.get(glyph.request.key)!, null)\n if (performance.now() - sliceStart > SLICE_MS) {\n await nextTask()\n throwIfAborted(signal)\n sliceStart = performance.now()\n }\n continue\n }\n await finishGlyph(glyph, box, false)\n }\n } else {\n interface Tile {\n readonly glyph: Measured\n readonly box: ReturnType<typeof boxOf>\n readonly x: number\n readonly y: number\n }\n const plain: { readonly glyph: Measured; readonly box: ReturnType<typeof boxOf> }[] = []\n const oversized: { readonly glyph: Measured; readonly box: ReturnType<typeof boxOf> }[] = []\n const retries: Measured[] = []\n for (const glyph of measured) {\n throwIfAborted(signal)\n const box = boxOf(glyph.reach, margin)\n const [, , width, height] = box\n const colored =\n colorModule !== null &&\n isColorCandidate(glyph.request, colorGlyphs) &&\n colorModule.encodeColorBand(\n draw(glyph, box, '#fff', 'auto'),\n draw(glyph, box, '#000', 'auto'),\n width,\n height,\n 0,\n [{ x: 0, y: 0, width, height }],\n ).colored[0] === true\n if (colored) {\n keep(requests.get(glyph.request.key)!, null)\n continue\n }\n if (width > MAX_SHEET || height > MAX_SHEET) oversized.push({ glyph, box })\n else plain.push({ glyph, box })\n }\n\n const flushSheet = async (sheet: Tile[], sheetW: number, sheetH: number): Promise<void> => {\n const resized = resize(sheetW, sheetH)\n if (!resized) context.clearRect(0, 0, sheetW, sheetH)\n context.fillStyle = '#606060'\n if (exact) context.textRendering = 'geometricPrecision'\n for (const item of sheet) {\n throwIfAborted(signal)\n use(item.glyph.request)\n context.fillText(\n item.glyph.request.character,\n item.x + item.box[0],\n item.y + item.box[1],\n )\n }\n const rgba = context.getImageData(0, 0, sheetW, sheetH).data\n const rowStride = sheetW * 4\n for (const item of sheet) {\n throwIfAborted(signal)\n const [originX, baselineY, width, height] = item.box\n const tileOffset = (item.y * sheetW + item.x) * 4\n if (touchesEdge(rgba, width, height, rowStride, tileOffset)) {\n retries.push(item.glyph)\n continue\n }\n const { quadratics, bbox } = traceCoverage(\n {\n alpha: rgba,\n width,\n height,\n stride: 4,\n offset: tileOffset + 3,\n rowStride,\n originX,\n baselineY,\n },\n tolerance,\n scratch,\n )\n keep(requests.get(item.glyph.request.key)!, {\n unitsPerEm: size,\n ascent: item.glyph.ascent,\n descent: -item.glyph.descent,\n bbox,\n quadratics,\n })\n if (performance.now() - sliceStart > SLICE_MS) {\n await nextTask()\n throwIfAborted(signal)\n sliceStart = performance.now()\n }\n }\n }\n\n if (plain.length < 2) {\n for (const item of plain) {\n throwIfAborted(signal)\n await finishGlyph(item.glyph, item.box, false)\n }\n } else {\n plain.sort((a, b) => b.box[3] - a.box[3] || b.box[2] - a.box[2])\n let sheet: Tile[] = []\n let packX = 0\n let packY = 0\n let rowH = 0\n let sheetW = 0\n let sheetH = 0\n for (const { glyph, box } of plain) {\n const width = box[2]\n const height = box[3]\n if (packX > 0 && packX + width > MAX_SHEET) {\n packX = 0\n packY += rowH + SHEET_GAP\n rowH = 0\n }\n if (packY + height > MAX_SHEET) {\n await flushSheet(sheet, sheetW, sheetH)\n sheet = []\n packX = 0\n packY = 0\n rowH = 0\n sheetW = 0\n sheetH = 0\n }\n sheet.push({ glyph, box, x: packX, y: packY })\n sheetW = Math.max(sheetW, packX + width)\n sheetH = Math.max(sheetH, packY + height)\n packX += width + SHEET_GAP\n rowH = Math.max(rowH, height)\n }\n if (sheet.length > 0) await flushSheet(sheet, sheetW, sheetH)\n }\n for (const item of oversized) {\n throwIfAborted(signal)\n await finishGlyph(item.glyph, item.box, false)\n }\n for (const glyph of retries) {\n throwIfAborted(signal)\n await finishGlyph(glyph, boxOf(glyph.reach, margin + size / 2), true)\n }\n }\n return results\n } finally {\n // Release the backing store now: Safari counts a detached canvas against its canvas\n // memory until it is collected.\n canvas.width = 0\n canvas.height = 0\n canvas.remove()\n }\n }\n\n const provider: WindfoilOutlineProvider = (request, signal) => {\n throwIfAborted(signal)\n const cached = cache.get(request.key)\n if (cached !== undefined) return cached\n let batch = open.get(signal)\n if (!batch) {\n const requests = new Map<string, GlyphRequest>()\n // Everything this task asks for with this signal joins before the batch starts. What a\n // clear() before then would drop is not cached either.\n const started = epoch\n const next: Batch = {\n signal,\n requests,\n done: Promise.resolve().then(() => {\n if (open.get(signal) === next) open.delete(signal)\n return run(signal, requests, started)\n }),\n }\n open.set(signal, (batch = next))\n }\n batch.requests.set(request.key, request)\n return batch.done.then((results) => results.get(request.key) ?? null)\n }\n\n return {\n provider,\n clear() {\n epoch++\n cache.clear()\n },\n retain(keys) {\n const live = new Set(keys)\n for (const key of cache.keys()) if (!live.has(key)) cache.delete(key)\n },\n }\n}\n"],"mappings":";;;;AAoCA,IAAM,WAAW;;AAEjB,IAAM,gBAAgB;AACtB,IAAM,aAAa;AAkBnB,SAAS,eAAe,QAA2B;CACjD,IAAI,OAAO,SACT,MAAM,OAAO,UAAU,IAAI,aAAa,iCAAiC,YAAY;AAEzF;;;;;;AAOA,SAAS,W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AAM;KACrB,MAAM,YAAY,OAAO,MAAM,MAAM,OAAO,SAAS,OAAO,CAAC,GAAG,IAAI;IACtE;GACF;GACA,OAAO;EACT,UAAU;GAGR,OAAO,QAAQ;GACf,OAAO,SAAS;GAChB,OAAO,OAAO;EAChB;CACF;CAEA,MAAM,YAAqC,SAAS,WAAW;EAC7D,eAAe,MAAM;EACrB,MAAM,SAAS,MAAM,IAAI,QAAQ,GAAG;EACpC,IAAI,WAAW,KAAA,GAAW,OAAO;EACjC,IAAI,QAAQ,KAAK,IAAI,MAAM;EAC3B,IAAI,CAAC,OAAO;GACV,MAAM,2BAAW,IAAI,IAA0B;GAG/C,MAAM,UAAU;GAChB,MAAM,OAAc;IAClB;IACA;IACA,MAAM,QAAQ,QAAQ,CAAC,CAAC,WAAW;KACjC,IAAI,KAAK,IAAI,MAAM,MAAM,MAAM,KAAK,OAAO,MAAM;KACjD,OAAO,IAAI,QAAQ,UAAU,OAAO;IACtC,CAAC;GACH;GACA,KAAK,IAAI,QAAS,QAAQ,IAAK;EACjC;EACA,MAAM,SAAS,IAAI,QAAQ,KAAK,OAAO;EACvC,OAAO,MAAM,KAAK,MAAM,YAAY,QAAQ,IAAI,QAAQ,GAAG,KAAK,IAAI;CACtE;CAEA,OAAO;EACL;EACA,QAAQ;GACN;GACA,MAAM,MAAM;EACd;EACA,OAAO,MAAM;GACX,MAAM,OAAO,IAAI,IAAI,IAAI;GACzB,KAAK,MAAM,OAAO,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,GAAG,GAAG,MAAM,OAAO,GAAG;EACtE;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ultra-text",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
4
4
  "description": "DOM to WebGPU/TSL: real HTML, laid out by the browser, rendered as live 3D text (Three.js, R3F, TresJS, Mini3, and vanilla JS).",
5
5
  "keywords": [
6
6
  "three",
@@ -134,7 +134,7 @@
134
134
  {
135
135
  "name": "public entry",
136
136
  "path": "dist/index.js",
137
- "limit": "38.5 kB",
137
+ "limit": "46 kB",
138
138
  "ignore": [
139
139
  "three",
140
140
  "@chenglou/pretext",
@@ -163,7 +163,7 @@
163
163
  {
164
164
  "name": "vanilla entry (Three-free)",
165
165
  "path": "dist/vanilla.js",
166
- "limit": "31 kB",
166
+ "limit": "37 kB",
167
167
  "ignore": [
168
168
  "@chenglou/pretext",
169
169
  "./dist/dom/browserShaping.js",
@@ -178,7 +178,7 @@
178
178
  {
179
179
  "name": "slug entry (Three.js)",
180
180
  "path": "dist/slug.js",
181
- "limit": "44 kB",
181
+ "limit": "52.5 kB",
182
182
  "ignore": [
183
183
  "three",
184
184
  "@chenglou/pretext",
@@ -198,7 +198,7 @@
198
198
  {
199
199
  "name": "slug-vanilla entry (Three-free)",
200
200
  "path": "dist/slug-vanilla.js",
201
- "limit": "38 kB",
201
+ "limit": "45 kB",
202
202
  "ignore": [
203
203
  "@chenglou/pretext",
204
204
  "./dist/dom/browserShaping.js",
@@ -216,7 +216,7 @@
216
216
  {
217
217
  "name": "optional Pretext layout",
218
218
  "path": "dist/dom/pretextLayout.js",
219
- "limit": "2.7 kB",
219
+ "limit": "4 kB",
220
220
  "ignore": [
221
221
  "@chenglou/pretext",
222
222
  "./dist/dom/clusters.js",
@@ -231,7 +231,7 @@
231
231
  {
232
232
  "name": "optional Windfoil backend",
233
233
  "path": "dist/windfoil/runtime.js",
234
- "limit": "16.5 kB",
234
+ "limit": "19 kB",
235
235
  "ignore": [
236
236
  "three",
237
237
  "@chenglou/pretext",
@@ -246,7 +246,7 @@
246
246
  {
247
247
  "name": "optional Slug backend",
248
248
  "path": "dist/slug/runtime.js",
249
- "limit": "16 kB",
249
+ "limit": "19.5 kB",
250
250
  "ignore": [
251
251
  "three",
252
252
  "@chenglou/pretext",
@@ -261,7 +261,7 @@
261
261
  {
262
262
  "name": "optional CPU fallback",
263
263
  "path": "dist/atlas/cpuAtlas.js",
264
- "limit": "3 kB",
264
+ "limit": "4.5 kB",
265
265
  "ignore": [
266
266
  "three"
267
267
  ]
@@ -403,7 +403,7 @@
403
403
  {
404
404
  "name": "optional atlas append",
405
405
  "path": "dist/atlas/appendAtlas.js",
406
- "limit": "4.5 kB",
406
+ "limit": "5.5 kB",
407
407
  "ignore": [
408
408
  "three",
409
409
  "./dist/atlas/rasterize.js",
@@ -415,7 +415,7 @@
415
415
  {
416
416
  "name": "optional traced outlines",
417
417
  "path": "dist/windfoil/tracedOutlines.js",
418
- "limit": "8.5 kB",
418
+ "limit": "12 kB",
419
419
  "ignore": [
420
420
  "three",
421
421
  "./dist/atlas/rasterize.js",
@@ -73,6 +73,6 @@ const copy = await DomSlug.create(renderer, source, { outlineProvider })
73
73
  ## Runtime updates & shared atlases
74
74
 
75
75
  - Motion uniforms update without rebuilding shaders or DOM: `copy.setMotion({ mode: 'offset', speed: 0.8 })`.
76
- - Width-only re-wrap: create with `{ reflowable: true }`, then call `copy.reflow(widthPx)` (`1.51 ms` median on 1,000 glyphs vs full DOM `rebuild()`).
77
- - Force rebuild: `await copy.rebuild()` (re-reads DOM, reuses retained atlas if glyph signature matches) or `await copy.rebuild({ atlas: true })`.
76
+ - Width-only re-wrap: create with `{ reflowable: true }`, then call `copy.reflow(widthPx)` (`0.041 ms` standalone CPU median in `benchmarks/reflow.js`, `1.46 ms` end-to-end with GPU completion on 1,000 glyphs vs full DOM `rebuild()`).
77
+ - Force rebuild: `await copy.rebuild()` (re-reads DOM, reuses retained atlas if glyph signature matches) or `await copy.rebuild({ atlas: true })`. Both SDF (`DomSdf`/`DomText`) and analytic (`DomSlug`, `DomSdf` with `textBackend: 'slug' | 'windfoil'`) allocate tight storage on `create()` and switch to headroom on the first unseen glyph so subsequent unseen glyphs append in place without recreating materials or pipelines.
78
78
  - Lower-level SDF stages (`collectDomSnapshot`, `rasterizeGlyphAtlas`, `buildSdfAtlas`, `createGlyphGeometry`, `SdfTextMaterial`, `createRectGeometry`, `createRectMaterial`, `reflowSnapshot`) let multiple meshes share one `SdfAtlas`; pass `sharedAtlas` (matching `quality` and `colorGlyphs` mode) and dispose `sharedAtlas` only after every consumer has been disposed.
@@ -34,6 +34,7 @@ domText.dispose()
34
34
  ```
35
35
 
36
36
  - **String helper**: `Text` (`VanillaText`) supports `await Text.create('Hello', { device: gpuDevice, css, cssClass, onChange })` as well as `setText()`, `setCss()`, and `setClass()`.
37
+ - **Lazy mipmaps**: `MIP_WGSL` (`r8unorm` / `rgba8unorm-srgb`) mip render pipelines compile lazily (`getDeviceMipPipeline`), decoupling CPU-atlas GPU mipmaps from JFA compute compilation.
37
38
  - **Lower-level exports**: `collectDomSnapshot`, `reflowSnapshot`, `buildVanillaSdfAtlas` (`buildSdfAtlas`), `buildVanillaGpuSdfAtlas`, `buildVanillaCpuSdfAtlas`, `rasterizeGlyphAtlas`, `packGlyphInstances`, `updateGlyphInstances`, `updateGlyphContentInstances`, `packRectInstances`, `updateRectInstances`, `packDecorationInstances`, `updateDecorationInstances`, `computeInstanceBounds`, `resolveDomTextTone`, `UNIT_QUAD_POSITIONS`, `UNIT_QUAD_NORMALS`, `UNIT_QUAD_INDICES`.
38
39
 
39
40
  ## Pure Slug WebGPU pipeline (`ultra-text/slug-vanilla`)
@@ -91,5 +92,5 @@ domSlug.dispose()
91
92
  pipeline.dispose()
92
93
  ```
93
94
 
94
- - **Buffer caution on rebuilds**: `gpuInstances.update(next)` calls `writeBuffer` into the existing vertex buffers; if a rebuild increases glyph capacity beyond the initial buffer sizes, recreate `gpuInstances = uploadSlugGlyphBuffers(gpuDevice, next)` after disposing the old one.
95
- - **Standalone lower-level Slug exports**: `buildVanillaSlugAtlas` (`buildSlugAtlas`), `packSlugGlyphInstances`, `updateSlugGlyphInstances`, `preprocessSlugGlyphs`, `createTrueTypeOutlineProvider`, `parseTrueTypeFont`, `createTracedOutlineProvider`, `createSvgEmojiOutlineProvider`, `svgToWindfoilOutlines`, `windfoilOutlineFromSvgPaths`, `SLUG_WGSL`.
95
+ - **Incremental rebuilds & buffer caution**: `DomSlug` (`VanillaDomSlug`) allocates tight curve/row `GPUBuffer`s on `create()` and switches to headroom on the first unseen glyph so subsequent unseen glyphs append via `device.queue.writeBuffer` without recreating storage buffers; `gpuInstances.update(next)` calls `writeBuffer` into the existing vertex buffers, so if a rebuild increases glyph capacity beyond initial sizes, recreate `gpuInstances = uploadSlugGlyphBuffers(gpuDevice, next)` after disposing the old one.
96
+ - **Standalone lower-level Slug exports**: `buildVanillaSlugAtlas` (`buildSlugAtlas`, which resolves missing `outlineProvider` requests concurrently via `Promise.all`), `packSlugGlyphInstances`, `updateSlugGlyphInstances`, `preprocessSlugGlyphs`, `createTrueTypeOutlineProvider`, `parseTrueTypeFont`, `createTracedOutlineProvider`, `createSvgEmojiOutlineProvider`, `svgToWindfoilOutlines`, `windfoilOutlineFromSvgPaths`, `SLUG_WGSL`.
@@ -1 +0,0 @@
1
- {"version":3,"file":"cpuSdf.worker-xS57yQbP.js","names":[],"sources":["../../src/atlas/cpuSdf.ts","../../src/atlas/cpuSdf.worker.ts"],"sourcesContent":["/**\n * A finite stand-in for infinity in the squared-distance grids.\n *\n * Keeping the sentinel finite avoids `Infinity - Infinity` while constructing\n * the lower envelope of parabolas. Its square root is far beyond any practical\n * atlas extent, so missing inside/outside pixels still saturate at the correct\n * encoded endpoint.\n */\nconst FAR_DISTANCE_SQUARED = 1e20\n\ntype AlphaPixels = Uint8Array | Uint8ClampedArray\n\n/** The alpha byte of each RGBA pixel, as the encoder reads coverage. */\nexport function alphaOfRgba(rgba: Uint8ClampedArray, pixelCount: number): Uint8Array {\n const alpha = new Uint8Array(pixelCount)\n for (let source = 3, target = 0; target < pixelCount; source += 4, target++) {\n alpha[target] = rgba[source]!\n }\n return alpha\n}\n\nfunction assertInputs(alpha: AlphaPixels, width: number, height: number, pxRange: number): number {\n if (!(alpha instanceof Uint8Array) && !(alpha instanceof Uint8ClampedArray)) {\n throw new TypeError('encodeSdfFromAlpha: alpha must be a Uint8Array or Uint8ClampedArray')\n }\n if (!Number.isInteger(width) || width <= 0) {\n throw new RangeError('encodeSdfFromAlpha: width must be a positive integer')\n }\n if (!Number.isInteger(height) || height <= 0) {\n throw new RangeError('encodeSdfFromAlpha: height must be a positive integer')\n }\n\n const pixelCount = width * height\n if (!Number.isSafeInteger(pixelCount)) {\n throw new RangeError('encodeSdfFromAlpha: width * height exceeds the safe integer range')\n }\n if (alpha.length !== pixelCount) {\n throw new RangeError(\n `encodeSdfFromAlpha: alpha length ${alpha.length} does not match width * height (${pixelCount})`,\n )\n }\n if (!Number.isFinite(pxRange) || pxRange <= 0) {\n throw new RangeError('encodeSdfFromAlpha: pxRange must be a positive finite number')\n }\n\n return pixelCount\n}\n\nlet edtMinOut = 0\nlet edtMaxOut = -1\n\n/**\n * Exact one-dimensional squared Euclidean distance transform.\n *\n * This is the lower-envelope algorithm from Felzenszwalb and Huttenlocher. It\n * runs in O(length), performs no allocations, and accepts non-zero seed costs\n * so fractional alpha coverage can place the glyph edge between pixel centres.\n * The envelope retains the original costs before writing back into the grid,\n * avoiding a copy of each column in both directions.\n */\nfunction edt1d(\n grid: Float32Array,\n startSeed: number,\n endSeed: number,\n outStart: number,\n outEnd: number,\n clampSqDist: number,\n maxRadius: number,\n): void {\n let first = startSeed\n while (first <= endSeed && grid[first]! >= clampSqDist) first++\n if (first > endSeed) {\n edtMinOut = outEnd + 1\n edtMaxOut = outStart - 1\n return\n }\n\n const firstCost = grid[first]!\n if (first === outStart) {\n let different = first + 1\n if (firstCost <= 1) {\n while (different <= endSeed && grid[different]! <= 1) different++\n } else {\n while (different <= endSeed && grid[different] === firstCost) different++\n }\n // A constant line or a line of immediate seeds (cost <= 1) is already its own distance transform.\n if (different > endSeed && endSeed >= outEnd) {\n edtMinOut = outStart\n edtMaxOut = outEnd\n return\n }\n }\n\n const parabolaIndices = scratchParabolaIndices\n const parabolaCosts = scratchParabolaCosts\n const parabolaOffsets = scratchParabolaOffsets\n const boundaries = scratchBoundaries\n let envelopeEnd = 0\n parabolaIndices[0] = first\n parabolaCosts[0] = firstCost\n parabolaOffsets[0] = firstCost + first * first\n\n for (let q = first + 1; q <= endSeed; q++) {\n let cost = grid[q]!\n if (cost >= clampSqDist) {\n while (q < endSeed && grid[q + 1]! >= clampSqDist) q++\n continue\n }\n if (cost <= 1 && grid[q - 1]! <= 1) {\n while (q < endSeed && grid[q + 1]! <= 1) q++\n cost = grid[q]!\n } else if (cost === grid[q - 1]!) {\n while (q < endSeed && grid[q + 1] === cost) q++\n }\n const costPlusQSquared = cost + q * q\n while (\n envelopeEnd > 0 &&\n costPlusQSquared - parabolaOffsets[envelopeEnd]! <=\n boundaries[envelopeEnd]! * (q - parabolaIndices[envelopeEnd]!)\n ) {\n envelopeEnd--\n }\n const twiceIntersection =\n (costPlusQSquared - parabolaOffsets[envelopeEnd]!) / (q - parabolaIndices[envelopeEnd]!)\n\n envelopeEnd++\n parabolaIndices[envelopeEnd] = q\n parabolaCosts[envelopeEnd] = cost\n parabolaOffsets[envelopeEnd] = costPlusQSquared\n boundaries[envelopeEnd] = twiceIntersection\n }\n\n const minOut = first - maxRadius > outStart ? first - maxRadius : outStart\n const lastSeed = parabolaIndices[envelopeEnd]!\n const maxOut = lastSeed + maxRadius < outEnd ? lastSeed + maxRadius : outEnd\n let b0 = minOut\n for (let e = 0; e <= envelopeEnd; e++) {\n const b1 = e === envelopeEnd ? maxOut : Math.floor(boundaries[e + 1]! * 0.5)\n if (b1 >= b0) {\n const nearest = parabolaIndices[e]!\n const cost = parabolaCosts[e]!\n const r0 = nearest - maxRadius\n const r1 = nearest + maxRadius\n const s1 = maxOut < b1 ? maxOut : b1\n const segStart = b0 > r0 ? b0 : r0\n const segEnd = s1 < r1 ? s1 : r1\n for (let q = segStart; q <= segEnd; q++) {\n const cur = grid[q]!\n if (cur <= 1) continue\n const delta = q - nearest\n const d = delta * delta + cost\n if (d < cur) grid[q] = d\n }\n b0 = b1 + 1\n if (b0 > maxOut) break\n }\n }\n edtMinOut = minOut\n edtMaxOut = maxOut\n}\n\nconst SEED_COST = Float32Array.from({ length: 256 }, (_, coverage) => {\n const edgeOffset = 0.5 - coverage / 255\n const sq = Math.fround(edgeOffset * edgeOffset)\n return coverage < 128 ? sq : -sq\n})\n\nlet scratchDistances = new Float32Array(0)\nlet scratchParabolaIndices = new Int32Array(0)\nlet scratchParabolaCosts = new Float32Array(0)\nlet scratchParabolaOffsets = new Float64Array(0)\nlet scratchBoundaries = new Float64Array(0)\nlet scratchInside = new Float32Array(0)\nlet scratchOutside = new Float32Array(0)\nlet scratchActiveRows = new Int32Array(0)\n\n/**\n * Alpha seeds cost less than 0.25. A closer seed therefore always beats a\n * farther seed in the same direction (squared integer distances differ by at\n * least one). Each empty or solid run is bounded by at most one seed on each\n * side, so one pass splits each run at its midpoint and fills both ends.\n */\nfunction horizontalRowDistances(\n alpha: AlphaPixels,\n alphaRow: number,\n distances: Float32Array,\n distRow: number,\n width: number,\n firstNonZero: number,\n maxRadius: number,\n): number {\n let lastNonZero = width - 1\n for (let x = 0; x < width; x++) {\n const coverage = alpha[alphaRow + x]!\n if (coverage === 0 || coverage === 255) {\n const a = x\n if (x === 0 && firstNonZero > 0) x = firstNonZero - 1\n else while (x + 1 < width && alpha[alphaRow + x + 1] === coverage) x++\n const isZero = coverage === 0\n if (isZero && x === width - 1) lastNonZero = a - 1\n const sign = isZero ? 1 : -1\n const lCov = a > 0 ? alpha[alphaRow + a - 1]! : -1\n const rCov = x + 1 < width ? alpha[alphaRow + x + 1]! : -1\n const lSc = lCov < 0 ? FAR_DISTANCE_SQUARED : sign * SEED_COST[lCov]!\n const rSc = rCov < 0 ? FAR_DISTANCE_SQUARED : sign * SEED_COST[rCov]!\n const lCost = lSc > 0 ? lSc : 0\n const rCost = rSc > 0 ? rSc : 0\n const mid = rCov < 0 ? x : lCov < 0 ? a - 1 : (a + x - (rCost < lCost ? 1 : 0)) >> 1\n const lEnd = lCov < 0 ? a - 1 : mid < a + maxRadius - 1 ? mid : a + maxRadius - 1\n const rStart = rCov < 0 ? x + 1 : mid + 1 > x - maxRadius + 1 ? mid + 1 : x - maxRadius + 1\n for (let p = a, d = 1; p <= lEnd; p++, d++) {\n distances[distRow + p] = sign * (d * d + lCost)\n }\n if (lEnd + 1 < rStart) {\n distances.fill(sign * FAR_DISTANCE_SQUARED, distRow + lEnd + 1, distRow + rStart)\n }\n for (let p = rStart, d = x + 1 - rStart; p <= x; p++, d--) {\n distances[distRow + p] = sign * (d * d + rCost)\n }\n } else {\n distances[distRow + x] = SEED_COST[coverage]!\n }\n }\n return lastNonZero\n}\n\n/**\n * Encode an alpha coverage mask as a single-channel signed distance field.\n *\n * The returned byte uses the conventional SDF encoding:\n *\n * - the edge is 0.5 (the nearest byte representation is 128),\n * - inside pixels are greater than 0.5,\n * - outside pixels are less than 0.5,\n * - `pxRange` pixels of signed distance span one encoded unit.\n *\n * Fractional source alpha is retained as a sub-pixel seed cost rather than\n * thresholded away. The two exact Euclidean distance transforms are O(width *\n * height); temporary storage is one grid plus O(height) scratch.\n */\nexport function encodeSdfFromAlpha(\n alpha: AlphaPixels,\n width: number,\n height: number,\n pxRange: number,\n): Uint8Array {\n const pixelCount = assertInputs(alpha, width, height, pxRange)\n const encoded = new Uint8Array(pixelCount)\n const scale255 = 255 / pxRange\n const clampSqDist = 0.25 * pxRange * pxRange * (1 + 1e-6)\n const skipEmptyRows = clampSqDist <= FAR_DISTANCE_SQUARED\n const maxRadius = skipEmptyRows ? Math.ceil(0.5 * pxRange + 1) : width > height ? width : height\n // Pad power-of-two widths by one 64-byte cache line (16 floats) so vertical\n // column gathers do not alias onto the same L1 cache set on every row.\n const distStride = (width & 63) === 0 ? width + 16 : width\n const requiredDistances = distStride * height\n if (scratchDistances.length < requiredDistances) {\n scratchDistances = new Float32Array(requiredDistances)\n }\n if (scratchParabolaIndices.length < height) {\n scratchParabolaIndices = new Int32Array(height)\n scratchParabolaCosts = new Float32Array(height)\n scratchParabolaOffsets = new Float64Array(height)\n scratchBoundaries = new Float64Array(height)\n scratchInside = new Float32Array(height)\n scratchOutside = new Float32Array(height)\n scratchActiveRows = new Int32Array(height)\n }\n const distances = scratchDistances\n const activeRows = scratchActiveRows\n const inside = scratchInside\n const outside = scratchOutside\n const sentinel = skipEmptyRows ? FAR_DISTANCE_SQUARED : clampSqDist\n inside.fill(sentinel, 0, height)\n outside.fill(0, 0, height)\n const lastRow = height - 1\n const u32 =\n (alpha.byteOffset & 3) === 0\n ? new Uint32Array(alpha.buffer, alpha.byteOffset, alpha.byteLength >>> 2)\n : null\n\n let anyNonZero = false\n let scanY = 0\n while (scanY < height) {\n let bandCount = 0\n let bandMinX = width\n let bandMaxX = -1\n let lastActiveY = -1\n for (; scanY < height; scanY++) {\n const alphaRow = scanY * width\n let firstNonZero = 0\n if (u32 !== null && (alphaRow & 3) === 0) {\n const wStart = alphaRow >>> 2\n const wEnd = wStart + (width >>> 2)\n let w = wStart\n while (w < wEnd && u32[w] === 0) w++\n firstNonZero = (w - wStart) << 2\n }\n while (firstNonZero < width && alpha[alphaRow + firstNonZero] === 0) firstNonZero++\n if (firstNonZero === width) {\n if (!skipEmptyRows) {\n const distRow = bandCount * distStride\n distances.fill(FAR_DISTANCE_SQUARED, distRow, distRow + width)\n activeRows[bandCount++] = scanY\n lastActiveY = scanY\n } else if (bandCount > 0 && scanY - lastActiveY >= 2 * maxRadius) {\n scanY++\n break\n }\n continue\n }\n anyNonZero = true\n const distRow = bandCount * distStride\n const lastNonZero = horizontalRowDistances(\n alpha,\n alphaRow,\n distances,\n distRow,\n width,\n firstNonZero,\n maxRadius,\n )\n activeRows[bandCount++] = scanY\n lastActiveY = scanY\n if (firstNonZero < bandMinX) bandMinX = firstNonZero\n if (lastNonZero > bandMaxX) bandMaxX = lastNonZero\n }\n\n if (bandCount === 0) break\n if (!anyNonZero) {\n const byte = 128 - Math.sqrt(FAR_DISTANCE_SQUARED) * scale255\n const fillByte = byte <= 0 ? 0 : byte | 0\n if (fillByte !== 0) encoded.fill(fillByte)\n if (scratchDistances.length > 4_500_000) scratchDistances = new Float32Array(0)\n return encoded\n }\n\n const firstActiveY = activeRows[0]!\n const bandMinY = skipEmptyRows ? (firstActiveY > maxRadius ? firstActiveY - maxRadius : 0) : 0\n const bandMaxY = skipEmptyRows\n ? lastActiveY + maxRadius < lastRow\n ? lastActiveY + maxRadius\n : lastRow\n : lastRow\n const bandHeight = bandMaxY - bandMinY + 1\n const colStart = skipEmptyRows ? (bandMinX > maxRadius ? bandMinX - maxRadius : 0) : 0\n const colEnd = skipEmptyRows\n ? bandMaxX + maxRadius < width - 1\n ? bandMaxX + maxRadius\n : width - 1\n : width - 1\n\n for (let x = colStart; x <= colEnd; x++) {\n let r = 0\n let offset = x\n while (r < bandCount && distances[offset]! >= clampSqDist) {\n r++\n offset += distStride\n }\n if (r === bandCount) continue\n const firstInSeed = activeRows[r]!\n let lastInSeed = firstInSeed\n let firstNeg = -1\n let lastNeg = -1\n let negCount = 0\n for (; r < bandCount; r++, offset += distStride) {\n const distance = distances[offset]!\n if (distance >= clampSqDist) continue\n const y = activeRows[r]!\n lastInSeed = y\n if (distance >= 0) {\n inside[y] = distance\n } else {\n inside[y] = 0\n outside[y] = -distance\n if (firstNeg < 0) firstNeg = y\n lastNeg = y\n negCount++\n }\n }\n let yStart = bandMinY\n let yEnd = bandMaxY\n if (negCount < bandHeight) {\n edt1d(inside, firstInSeed, lastInSeed, bandMinY, bandMaxY, clampSqDist, maxRadius)\n yStart = edtMinOut\n yEnd = edtMaxOut\n }\n const pureInEnd = firstNeg < 0 ? yEnd : firstNeg - 1\n let y = yStart\n let idx = y * width + x\n for (; y <= pureInEnd; y++, idx += width) {\n const inSq = inside[y]!\n if (inSq < clampSqDist) encoded[idx] = (128 - Math.sqrt(inSq) * scale255) | 0\n }\n if (firstNeg >= 0) {\n edt1d(\n outside,\n firstNeg > 0 ? firstNeg - 1 : 0,\n lastNeg < lastRow ? lastNeg + 1 : lastRow,\n firstNeg,\n lastNeg,\n clampSqDist,\n maxRadius,\n )\n for (; y <= lastNeg; y++, idx += width) {\n const inSq = inside[y]!\n if (inSq > 0) {\n if (inSq < clampSqDist) encoded[idx] = (128 - Math.sqrt(inSq) * scale255) | 0\n } else {\n const outSq = outside[y]!\n encoded[idx] = outSq >= clampSqDist ? 255 : (128 + Math.sqrt(outSq) * scale255) | 0\n }\n }\n for (; y <= yEnd; y++, idx += width) {\n const inSq = inside[y]!\n if (inSq < clampSqDist) encoded[idx] = (128 - Math.sqrt(inSq) * scale255) | 0\n }\n outside.fill(0, firstNeg, lastNeg + 1)\n }\n inside.fill(sentinel, yStart, yEnd + 1)\n }\n }\n\n if (scratchDistances.length > 4_500_000) scratchDistances = new Float32Array(0)\n return encoded\n}\n","import { alphaOfRgba, encodeSdfFromAlpha } from './cpuSdf.js'\n\nconst scope = globalThis as unknown as {\n onmessage: (\n event: MessageEvent<{\n rgba: Uint8ClampedArray\n width: number\n height: number\n pxRange: number\n }>,\n ) => void\n postMessage: (value: Uint8Array, transfer: ArrayBuffer[]) => void\n}\n\n// The page reads the canvas and sends the RGBA pixels: the alpha loop runs here.\nscope.onmessage = ({ data }) => {\n const alpha = alphaOfRgba(data.rgba, data.width * data.height)\n const result = encodeSdfFromAlpha(alpha, data.width, data.height, data.pxRange)\n scope.postMessage(result, [result.buffer as ArrayBuffer])\n}\n"],"mappings":";;;;;;;;;AAQA,MAAM,uBAAuB;;AAK7B,SAAgB,YAAY,MAAyB,YAAgC;CACnF,MAAM,QAAQ,IAAI,WAAW,UAAU;CACvC,KAAK,IAAI,SAAS,GAAG,SAAS,GAAG,SAAS,YAAY,UAAU,GAAG,UACjE,MAAM,UAAU,KAAK;CAEvB,OAAO;AACT;AAEA,SAAS,aAAa,OAAoB,OAAe,QAAgB,SAAyB;CAChG,IAAI,EAAE,iBAAiB,eAAe,EAAE,iBAAiB,oBACvD,MAAM,IAAI,UAAU,qEAAqE;CAE3F,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,SAAS,GACvC,MAAM,IAAI,WAAW,sDAAsD;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D"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"slug-vanilla.js","names":[],"sources":["../src/slug-vanilla.ts"],"sourcesContent":["import { layoutSignatureOf } from './dom/layoutSignature.js'\nimport { collectDomSnapshot } from './dom/snapshot.js'\nimport { classNames, copyTextOptions, createTextSource, cssDeclarations } from './dom/textHost.js'\nimport {\n backdropCurve,\n resolveDomTextTone,\n resolveTextTone,\n srgbEncode,\n toneCoverage,\n toneLightness,\n type ResolvedTextTone,\n type TextToneCapture,\n type TextToneContext,\n} from './dom/tone.js'\nimport { preprocessSlugGlyphs } from './slug/preprocessCore.js'\nimport {\n createTrueTypeOutlineProvider,\n parseTrueTypeFont,\n type TrueTypeFont,\n type TrueTypeFontSource,\n} from './slug/truetype.js'\nimport { reflowSnapshot, snapGlyph } from './text/reflow.js'\nimport type {\n ColorGlyphMode,\n DomLayoutSnapshot,\n DomSdfOptions,\n DomSdfStats,\n DomSvgOptions,\n DomTextBackend,\n DomTextLayoutEngine,\n DomTextStats,\n FontStyleSnapshot,\n GlyphBreak,\n GlyphLayout,\n GlyphRequest,\n GlyphShape,\n GlyphShapePath,\n GlyphShapeStroke,\n RectLayout,\n SdfAnimationMode,\n SdfMotionOptions,\n SvgEmojiOutlineProviderOptions,\n SvgToWindfoilOptions,\n TextBlockLayout,\n TextClass,\n TextCss,\n TextDecorationLayout,\n TextToneModel,\n TextToneOptions,\n WindfoilAffine,\n WindfoilBoundingBox,\n WindfoilColorStop,\n WindfoilEmBox,\n WindfoilExtendMode,\n WindfoilForegroundPaint,\n WindfoilGlyphOutline,\n WindfoilGradientBase,\n WindfoilGradientPaint,\n WindfoilLinearGradientPaint,\n WindfoilOutlineLayer,\n WindfoilOutlineProvider,\n WindfoilPaint,\n WindfoilQuadratic,\n WindfoilRadialGradientPaint,\n WindfoilSolidPaint,\n WindfoilSvgLayer,\n WindfoilSvgPaint,\n WindfoilSvgPath,\n WindfoilSvgResult,\n WindfoilSvgSource,\n WindfoilSvgWarning,\n WindfoilSvgWarningCode,\n WindfoilSweepGradientPaint,\n} from './types.js'\nimport { createSvgEmojiOutlineProvider } from './windfoil/emoji.js'\nimport type {\n WindfoilGlyphHeader,\n WindfoilGlyphSource,\n WindfoilLayerHeader,\n WindfoilPreprocessOptions,\n WindfoilPreprocessResult,\n WindfoilPreprocessStats,\n} from './windfoil/outlineValidation.js'\nimport { svgToWindfoilOutlines } from './windfoil/svg/convert.js'\nimport { windfoilOutlineFromSvgPaths } from './windfoil/svg/pathConverter.js'\nimport {\n createTracedOutlineProvider,\n type TracedOutlineOptions,\n type TracedOutlines,\n} from './windfoil/tracedOutlines.js'\n\nexport {\n backdropCurve,\n collectDomSnapshot,\n createSvgEmojiOutlineProvider,\n createTracedOutlineProvider,\n createTrueTypeOutlineProvider,\n layoutSignatureOf,\n parseTrueTypeFont,\n preprocessSlugGlyphs,\n reflowSnapshot,\n resolveDomTextTone,\n resolveTextTone,\n snapGlyph,\n srgbEncode,\n svgToWindfoilOutlines,\n toneCoverage,\n toneLightness,\n windfoilOutlineFromSvgPaths,\n}\n\nexport type {\n ColorGlyphMode,\n DomLayoutSnapshot,\n DomSdfStats,\n DomSvgOptions,\n DomTextBackend,\n DomTextLayoutEngine,\n DomTextStats,\n FontStyleSnapshot,\n GlyphBreak,\n GlyphLayout,\n GlyphRequest,\n GlyphShape,\n GlyphShapePath,\n GlyphShapeStroke,\n RectLayout,\n ResolvedTextTone,\n SdfAnimationMode,\n SdfMotionOptions,\n SvgEmojiOutlineProviderOptions,\n SvgToWindfoilOptions,\n TextBlockLayout,\n TextClass,\n TextCss,\n TextDecorationLayout,\n TextToneCapture,\n TextToneContext,\n TextToneModel,\n TextToneOptions,\n TracedOutlineOptions,\n TracedOutlines,\n TrueTypeFont,\n TrueTypeFontSource,\n WindfoilAffine,\n WindfoilBoundingBox,\n WindfoilColorStop,\n WindfoilEmBox,\n WindfoilExtendMode,\n WindfoilForegroundPaint,\n WindfoilGlyphHeader as SlugGlyphHeader,\n WindfoilGlyphOutline,\n WindfoilGlyphSource as SlugGlyphSource,\n WindfoilGradientBase,\n WindfoilGradientPaint,\n WindfoilLayerHeader as SlugLayerHeader,\n WindfoilLinearGradientPaint,\n WindfoilOutlineLayer,\n WindfoilOutlineProvider,\n WindfoilPaint,\n WindfoilPreprocessOptions as PreprocessSlugOptions,\n WindfoilPreprocessResult as PreparedSlugAtlas,\n WindfoilPreprocessStats as SlugPreprocessStats,\n WindfoilQuadratic,\n WindfoilRadialGradientPaint,\n WindfoilSolidPaint,\n WindfoilSvgLayer,\n WindfoilSvgPaint,\n WindfoilSvgPath,\n WindfoilSvgResult,\n WindfoilSvgSource,\n WindfoilSvgWarning,\n WindfoilSvgWarningCode,\n WindfoilSweepGradientPaint,\n}\n\n// ============================================================================\n// Structural WebGPU Handles (Zero Three.js, Zero @webgpu/types Required)\n// ============================================================================\n\nexport interface VanillaGpuBuffer {\n readonly label?: string\n readonly size?: number\n readonly usage?: number\n destroy(): void\n}\n\nexport interface VanillaSlugGpuRenderPass {\n setPipeline(pipeline: unknown): void\n setBindGroup(index: number, bindGroup: unknown): void\n setVertexBuffer(slot: number, buffer: VanillaGpuBuffer, offset?: number, size?: number): void\n draw(\n vertexCount: number,\n instanceCount?: number,\n firstVertex?: number,\n firstInstance?: number,\n ): void\n}\n\nexport interface VanillaSlugGpuDevice {\n readonly limits?: {\n readonly maxStorageBufferBindingSize?: number\n readonly maxBufferSize?: number\n readonly maxVertexBuffers?: number\n }\n createBuffer(descriptor: {\n label?: string\n size: number\n usage: number\n mappedAtCreation?: boolean\n }): VanillaGpuBuffer\n createShaderModule(descriptor: { label?: string; code: string }): unknown\n createRenderPipeline(descriptor: {\n label?: string\n layout: 'auto'\n vertex: {\n module: unknown\n entryPoint: string\n buffers?: readonly {\n arrayStride: number\n stepMode?: 'vertex' | 'instance'\n attributes: readonly {\n shaderLocation: number\n offset: number\n format: string\n }[]\n }[]\n }\n fragment: {\n module: unknown\n entryPoint: string\n targets: readonly {\n format: string\n blend?: {\n color: { srcFactor: string; dstFactor: string; operation?: string }\n alpha: { srcFactor: string; dstFactor: string; operation?: string }\n }\n }[]\n }\n primitive?: { topology?: string; cullMode?: string }\n depthStencil?: {\n format: string\n depthWriteEnabled?: boolean\n depthCompare?: string\n }\n multisample?: { count?: number }\n }): { getBindGroupLayout(index: number): unknown }\n createBindGroup(descriptor: {\n label?: string\n layout: unknown\n entries: readonly { binding: number; resource: unknown }[]\n }): unknown\n readonly queue: {\n writeBuffer(\n buffer: VanillaGpuBuffer,\n bufferOffset: number,\n data: ArrayBufferView,\n dataOffset?: number,\n size?: number,\n ): void\n }\n}\n\nexport type VanillaSlugGpuDeviceSource =\n | VanillaSlugGpuDevice\n | { readonly device?: VanillaSlugGpuDevice | null | undefined }\n | null\n | undefined\n\nfunction resolveSlugGpuDevice(source: VanillaSlugGpuDeviceSource): VanillaSlugGpuDevice | null {\n if (!source) return null\n if ('createBuffer' in source && typeof source.createBuffer === 'function') return source\n return 'device' in source ? (source.device ?? null) : null\n}\n\nconst DEFAULT_BUF_USAGE = {\n COPY_SRC: 4,\n COPY_DST: 8,\n INDEX: 16,\n VERTEX: 32,\n UNIFORM: 64,\n STORAGE: 128,\n}\nconst bufUsageOf = (): typeof DEFAULT_BUF_USAGE =>\n (globalThis as { GPUBufferUsage?: typeof DEFAULT_BUF_USAGE }).GPUBufferUsage ?? DEFAULT_BUF_USAGE\n\nfunction align4Bytes(byteLength: number): number {\n return Math.max(16, (byteLength + 3) & ~3)\n}\n\nfunction createStorageBuffer(\n device: VanillaSlugGpuDevice,\n label: string,\n data: Float32Array | Uint32Array,\n): VanillaGpuBuffer {\n const usage = bufUsageOf()\n const byteLength = align4Bytes(data.byteLength)\n const buffer = device.createBuffer({\n label,\n size: byteLength,\n usage: usage.STORAGE | usage.COPY_DST,\n })\n if (data.byteLength > 0) {\n device.queue.writeBuffer(buffer, 0, data)\n }\n return buffer\n}\n\n// ============================================================================\n// Pure CPU + WebGPU Slug Curve & Band Storage Builder\n// ============================================================================\n\nexport interface BuildVanillaSlugAtlasOptions {\n /**\n * Maps a captured CSS font request to quadratic outlines. When omitted and a\n * `document` is available, `buildVanillaSlugAtlas` traces glyphs from the\n * browser's Canvas 2D rendering using `createTracedOutlineProvider`.\n */\n outlineProvider?: WindfoilOutlineProvider\n /** Document used by the built-in Canvas 2D outline tracer when `outlineProvider` is omitted. */\n document?: Document\n /** How to handle `null` outlines: `'skip'` (default for traced outlines) or `'error'`. */\n missingGlyphs?: 'skip' | 'error'\n /** Target monotone-piece count per Slug band. Defaults to `2`. */\n targetPiecesPerBand?: number\n /** Trace resolution in pixels per em when using built-in traced outlines. Defaults to `256`. */\n traceSize?: number\n /** Quadratic curve fit tolerance in trace pixels when using built-in traced outlines. Defaults to `0.25`. */\n traceTolerance?: number\n /** Colour-glyph classification for built-in traced outlines. Defaults to `'emoji'`. */\n colorGlyphs?: ColorGlyphMode\n signal?: AbortSignal\n}\n\nexport interface VanillaSlugAtlas {\n /** Packed SoA `[p1, p3] | [p2]` `vec2f` control points (`Float32Array`). */\n readonly curves: Float32Array\n /** Packed single-word `uint32` Slug band headers (`Uint32Array`). */\n readonly rows: Uint32Array\n /** Retained GPU storage buffer for `curves` when built with a `GPUDevice`. */\n readonly curvesBuffer?: VanillaGpuBuffer\n /** Retained GPU storage buffer for `rows` when built with a `GPUDevice`. */\n readonly rowsBuffer?: VanillaGpuBuffer\n /** Glyph and shape headers keyed by `GlyphRequest.key`. */\n readonly glyphs: ReadonlyMap<string, WindfoilGlyphHeader>\n /** Keys skipped when `missingGlyphs: 'skip'` is active. */\n readonly skippedKeys: ReadonlySet<string>\n readonly layered: boolean\n readonly stats: WindfoilPreprocessStats\n /** Logical byte length of `curves` + `rows`. */\n readonly byteLength: number\n covers(key: string): boolean\n dispose(): void\n}\n\nfunction makeAbortError(message = 'The Slug operation was aborted'): Error {\n if (typeof DOMException !== 'undefined') return new DOMException(message, 'AbortError')\n const error = new Error(message)\n error.name = 'AbortError'\n return error\n}\n\nfunction isAbortError(error: unknown): boolean {\n return error instanceof Error && error.name === 'AbortError'\n}\n\nexport async function buildVanillaSlugAtlas(\n deviceOrRenderer: VanillaSlugGpuDeviceSource,\n requests: readonly GlyphRequest[],\n options: BuildVanillaSlugAtlasOptions = {},\n): Promise<VanillaSlugAtlas> {\n const signal = options.signal ?? new AbortController().signal\n signal.throwIfAborted()\n const device = resolveSlugGpuDevice(deviceOrRenderer)\n\n let provider = options.outlineProvider\n if (provider !== undefined && typeof provider !== 'function') {\n throw new TypeError('buildVanillaSlugAtlas: outlineProvider must be a function')\n }\n if (!provider) {\n const doc =\n options.document ??\n (typeof globalThis.document === 'undefined' ? undefined : globalThis.document)\n if (!doc) {\n throw new Error(\n 'buildVanillaSlugAtlas: provide an outlineProvider (e.g. createTrueTypeOutlineProvider) or a DOM document',\n )\n }\n const tracer = createTracedOutlineProvider(doc, {\n ...(options.colorGlyphs === undefined ? {} : { colorGlyphs: options.colorGlyphs }),\n ...(options.traceSize === undefined ? {} : { size: options.traceSize }),\n ...(options.traceTolerance === undefined ? {} : { tolerance: options.traceTolerance }),\n })\n provider = tracer.provider\n }\n\n const hasShapes = requests.some((request) => request.shape !== undefined)\n const resolved: { request: GlyphRequest; outline: WindfoilGlyphOutline | null }[] = []\n for (const request of requests) {\n signal.throwIfAborted()\n if (request.shape) {\n const shape = request.shape\n if (shape.bitmap || shape.paths.some((path) => path.stroke ?? path.clip)) {\n resolved.push({ request, outline: null })\n } else {\n const svg = svgToWindfoilOutlines(shape.paths, {\n em: { unitsPerEm: 1000, ascent: shape.box[1], descent: 0, advance: shape.box[0] },\n viewBox: [0, 0, shape.box[0], shape.box[1]],\n preserveAspectRatio: 'none',\n })\n resolved.push({\n request,\n outline: svg.warnings.some((w) => w.code === 'evenodd-ambiguous') ? null : svg.outline,\n })\n }\n continue\n }\n const out = await provider(request, signal)\n resolved.push({ request, outline: out })\n }\n signal.throwIfAborted()\n\n const missing = resolved.filter((item) => item.outline === null)\n const missingMode = options.missingGlyphs ?? (options.outlineProvider ? 'error' : 'skip')\n if (missing.length > 0 && missingMode === 'error') {\n throw new Error(\n `buildVanillaSlugAtlas: outlineProvider returned null for ${JSON.stringify(missing[0]!.request.character)} in ${missing[0]!.request.font.family}`,\n )\n }\n const skippedKeys = new Set(missing.map((item) => item.request.key))\n\n const needsLayers = resolved.some(\n (item) => item.outline?.layers !== undefined || item.outline?.clipBox !== undefined,\n )\n const layerModule = needsLayers ? await import('./windfoil/layerNormalization.js') : null\n signal.throwIfAborted()\n\n if (hasShapes) {\n // Inline SVG outlines already carry normalized em boxes.\n }\n\n const prepared = preprocessSlugGlyphs(\n resolved.filter(\n (item): item is { request: GlyphRequest; outline: WindfoilGlyphOutline } =>\n item.outline !== null,\n ),\n {\n signal,\n ...(layerModule ? { normalizeLayers: layerModule.normalizeLayers } : {}),\n ...(options.targetPiecesPerBand === undefined\n ? {}\n : { targetPiecesPerBand: options.targetPiecesPerBand }),\n },\n )\n\n let curvesBuffer: VanillaGpuBuffer | undefined\n let rowsBuffer: VanillaGpuBuffer | undefined\n if (device) {\n try {\n curvesBuffer = createStorageBuffer(device, 'ultra-slug-curves', prepared.curves)\n rowsBuffer = createStorageBuffer(device, 'ultra-slug-rows', prepared.rows)\n } catch (error) {\n curvesBuffer?.destroy()\n rowsBuffer?.destroy()\n throw error\n }\n }\n\n let disposed = false\n const byteLength = prepared.curves.byteLength + prepared.rows.byteLength\n return {\n curves: prepared.curves,\n rows: prepared.rows,\n ...(curvesBuffer ? { curvesBuffer } : {}),\n ...(rowsBuffer ? { rowsBuffer } : {}),\n glyphs: prepared.glyphs,\n skippedKeys,\n layered: prepared.layered,\n stats: prepared.stats,\n byteLength,\n covers(key: string): boolean {\n return prepared.glyphs.has(key) || skippedKeys.has(key)\n },\n dispose(): void {\n if (disposed) return\n disposed = true\n curvesBuffer?.destroy()\n rowsBuffer?.destroy()\n },\n }\n}\n\nexport { buildVanillaSlugAtlas as buildSlugAtlas }\n\n// ============================================================================\n// Pure Typed-Array Instance Packers & In-Place Updaters\n// ============================================================================\n\nexport const UNIT_QUAD_POSITIONS = new Float32Array([0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0])\nexport const UNIT_QUAD_NORMALS = new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1])\nexport const UNIT_QUAD_INDICES = new Uint16Array([0, 1, 2, 0, 2, 3])\n\nexport interface VanillaBounds {\n readonly min: readonly [x: number, y: number, z: number]\n readonly max: readonly [x: number, y: number, z: number]\n readonly center: readonly [x: number, y: number, z: number]\n readonly radius: number\n}\n\nexport function computeInstanceBounds(\n width: number,\n height: number,\n padding = 0,\n minZ = 0,\n maxZ = 0,\n): VanillaBounds {\n const minX = -padding\n const minY = -padding\n const minBoundZ = minZ - padding\n const maxX = width + padding\n const maxY = height + padding\n const maxBoundZ = maxZ + padding\n const cx = (minX + maxX) * 0.5\n const cy = (minY + maxY) * 0.5\n const cz = (minBoundZ + maxBoundZ) * 0.5\n const dx = maxX - cx\n const dy = maxY - cy\n const dz = maxBoundZ - cz\n return {\n min: [minX, minY, minBoundZ],\n max: [maxX, maxY, maxBoundZ],\n center: [cx, cy, cz],\n radius: Math.sqrt(dx * dx + dy * dy + dz * dz),\n }\n}\n\nexport interface VanillaSlugGlyphInstances {\n count: number\n drawableCount: number\n layered: boolean\n maxSequence: number\n /** `[x0, y0, x1, y1]` per instance in local capture units (`count * 4`). */\n rects: Float32Array\n /** `[x0, y0, x1, y1]` clip box per instance (`count * 4`). */\n clips: Float32Array\n /** Normalized `unorm8` `[r, g, b, a]` per instance (`count * 4`). */\n colors: Uint8Array\n /** `[sequence, z]` or `[sequence, z, switchEm]` per instance (`count * metaItemSize`). */\n metadata: Float32Array\n metaItemSize: 2 | 3\n /** `[b0, b1, b2, b3]` glyph outline box in font units (`count * 4`). */\n glyphBounds: Float32Array\n /** `[rowBase, packedCounts, vBandW, invHBandH]` Slug band parameters (`count * 4`). */\n bands: Float32Array\n /** `[originX, originY, ordinal, paint]` when `layered` is `true`, otherwise `null`. */\n layers: Float32Array | null\n /** `[x0, y0, x1, y1]` per drawable glyph (`drawableCount * 4`), used by decoration packers. */\n glyphRects: Float32Array\n bounds: VanillaBounds\n}\n\nexport interface VanillaRectInstances {\n count: number\n readonly receiveShadow: boolean\n rects: Float32Array\n colors: Uint8Array\n radii: Float32Array\n depths: Float32Array\n bounds: VanillaBounds\n}\n\nexport interface VanillaDecorationInstances {\n count: number\n rects: Float32Array\n decorationRects: Float32Array\n decorationIndices: Float32Array\n colors: Uint8Array\n clips: Float32Array\n metadata: Float32Array\n runMotion: Float32Array | null\n bounds: VanillaBounds\n}\n\nfunction byte(value: number): number {\n if (value <= 0) return 0\n if (value >= 1) return 255\n return (value * 255 + 0.5) | 0\n}\n\nfunction metaSize(snapshot: DomLayoutSnapshot): 2 | 3 {\n return snapshot.sizeSwitched || snapshot.glyphs.some((glyph) => glyph.switchEm !== undefined)\n ? 3\n : 2\n}\n\nconst scratchSlugRect: [number, number, number, number] = [0, 0, 0, 0]\n\nfunction fillSlugGlyphRect(\n glyph: GlyphLayout,\n header: WindfoilGlyphHeader,\n out: [number, number, number, number] = scratchSlugRect,\n): [number, number, number, number] {\n const scale = glyph.fontSize / header.unitsPerEm\n const baseline = glyph.lineBottom + (glyph.baselineOffset ?? -header.descent * scale)\n const bbox = header.bbox\n out[0] = glyph.originX + bbox[0] * scale\n out[1] = baseline + bbox[1] * scale\n out[2] = glyph.originX + bbox[2] * scale\n out[3] = baseline + bbox[3] * scale\n return out\n}\n\nfunction writeSlugLayer(\n glyph: GlyphLayout,\n header: WindfoilGlyphHeader,\n layer: WindfoilGlyphHeader | WindfoilLayerHeader,\n index: number,\n ordinal: number,\n target: VanillaSlugGlyphInstances,\n glyphRect?: readonly [number, number, number, number],\n): void {\n const offset = index * 4\n const scale = glyph.fontSize / header.unitsPerEm\n const baseline = glyph.lineBottom + (glyph.baselineOffset ?? -header.descent * scale)\n const ox = glyph.originX\n const lBox = layer.bbox\n const b0 = lBox[0],\n b1 = lBox[1],\n b2 = lBox[2],\n b3 = lBox[3]\n\n const rects = target.rects\n rects[offset] = ox + b0 * scale\n rects[offset + 1] = baseline + b1 * scale\n rects[offset + 2] = ox + b2 * scale\n rects[offset + 3] = baseline + b3 * scale\n\n const clips = target.clips\n const clip = glyph.clip\n clips[offset] = clip[0]\n clips[offset + 1] = clip[1]\n clips[offset + 2] = clip[2]\n clips[offset + 3] = clip[3]\n\n const paint = 'paintKind' in layer ? layer : null\n const rgb = paint?.paintKind === 1 ? paint.rgba : glyph.color\n const colors = target.colors\n colors[offset] = byte(rgb[0])\n colors[offset + 1] = byte(rgb[1])\n colors[offset + 2] = byte(rgb[2])\n colors[offset + 3] = byte(glyph.color[3] * (paint ? paint.rgba[3] : 1))\n\n const metaOffset = index * target.metaItemSize\n target.metadata[metaOffset] = glyph.sequence\n if (target.metaItemSize > 1) {\n target.metadata[metaOffset + 1] = glyph.z\n }\n if (target.metaItemSize === 3) {\n target.metadata[metaOffset + 2] = glyph.switchEm ?? 0\n }\n\n const bounds = target.glyphBounds\n bounds[offset] = b0\n bounds[offset + 1] = b1\n bounds[offset + 2] = b2\n bounds[offset + 3] = b3\n\n const bands = target.bands\n bands[offset] = layer.rowBase\n bands[offset + 1] = layer.bandCount\n bands[offset + 2] = layer.bandH\n bands[offset + 3] = layer.invH\n\n const layers = target.layers\n if (layers) {\n const rect = glyphRect ?? fillSlugGlyphRect(glyph, header, scratchSlugRect)\n const mo = glyph.motionOrigin\n layers[offset] = mo ? mo[0] : (rect[0] + rect[2]) * 0.5\n layers[offset + 1] = mo ? mo[1] : (rect[1] + rect[3]) * 0.5\n layers[offset + 2] = ordinal\n layers[offset + 3] =\n paint?.paintKind === 2 ? 2 + (paint.paintIndex ?? 0) : (paint?.paintKind ?? 0)\n }\n}\n\nfunction countSlugLayout(\n snapshot: DomLayoutSnapshot,\n glyphs: ReadonlyMap<string, WindfoilGlyphHeader>,\n layered: boolean,\n): { instances: number; drawable: number } {\n let instances = 0\n let drawable = 0\n for (const glyph of snapshot.glyphs) {\n const header = glyphs.get(glyph.glyphKey)\n if (header?.monotonePieceCount) {\n drawable++\n instances += layered ? (header.layers?.length ?? 1) : 1\n }\n }\n return { instances, drawable }\n}\n\nfunction populateSlugInstances(\n snapshot: DomLayoutSnapshot,\n glyphs: ReadonlyMap<string, WindfoilGlyphHeader>,\n target: VanillaSlugGlyphInstances,\n): { maxSequence: number; minZ: number; maxZ: number } {\n let instance = 0\n let drawable = 0\n let maxSequence = 0\n let minZ = 0\n let maxZ = 0\n for (const glyph of snapshot.glyphs) {\n const header = glyphs.get(glyph.glyphKey)\n if (!header?.monotonePieceCount) continue\n const ordinal = glyph.motionOrigin?.[2] ?? drawable\n const rect = fillSlugGlyphRect(glyph, header, scratchSlugRect)\n const rectOffset = drawable * 4\n target.glyphRects[rectOffset] = rect[0]\n target.glyphRects[rectOffset + 1] = rect[1]\n target.glyphRects[rectOffset + 2] = rect[2]\n target.glyphRects[rectOffset + 3] = rect[3]\n\n if (target.layers && header.layers) {\n for (const layer of header.layers) {\n writeSlugLayer(glyph, header, layer, instance++, ordinal, target, rect)\n }\n } else {\n writeSlugLayer(glyph, header, header.layers?.[0] ?? header, instance++, ordinal, target, rect)\n }\n drawable++\n if (glyph.sequence > maxSequence) maxSequence = glyph.sequence\n if (glyph.z < minZ) minZ = glyph.z\n if (glyph.z > maxZ) maxZ = glyph.z\n }\n return { maxSequence, minZ, maxZ }\n}\n\nexport function packSlugGlyphInstances(\n snapshot: DomLayoutSnapshot,\n atlas: Pick<VanillaSlugAtlas, 'glyphs' | 'layered'>,\n motionPadding = 0,\n): VanillaSlugGlyphInstances {\n const layered = atlas.layered || snapshot.glyphs.some((glyph) => !!glyph.motionOrigin)\n const { instances: count, drawable } = countSlugLayout(snapshot, atlas.glyphs, layered)\n const metaItemSize = metaSize(snapshot)\n const out: VanillaSlugGlyphInstances = {\n count,\n drawableCount: drawable,\n layered,\n maxSequence: 0,\n rects: new Float32Array(count * 4),\n clips: new Float32Array(count * 4),\n colors: new Uint8Array(count * 4),\n metadata: new Float32Array(count * metaItemSize),\n metaItemSize,\n glyphBounds: new Float32Array(count * 4),\n bands: new Float32Array(count * 4),\n layers: layered ? new Float32Array(count * 4) : null,\n glyphRects: new Float32Array(drawable * 4),\n bounds: computeInstanceBounds(snapshot.width, snapshot.height, motionPadding, 0, 0),\n }\n const { maxSequence, minZ, maxZ } = populateSlugInstances(snapshot, atlas.glyphs, out)\n out.maxSequence = maxSequence\n out.bounds = computeInstanceBounds(snapshot.width, snapshot.height, motionPadding, minZ, maxZ)\n return out\n}\n\nexport function updateSlugGlyphInstances(\n instances: VanillaSlugGlyphInstances,\n snapshot: DomLayoutSnapshot,\n atlas: Pick<VanillaSlugAtlas, 'glyphs' | 'layered'>,\n motionPadding = 0,\n): number | null {\n const layered = atlas.layered || snapshot.glyphs.some((glyph) => !!glyph.motionOrigin)\n if (layered !== instances.layered || metaSize(snapshot) !== instances.metaItemSize) return null\n const { instances: count, drawable } = countSlugLayout(snapshot, atlas.glyphs, layered)\n if (count !== instances.count || drawable !== instances.drawableCount) return null\n const { maxSequence, minZ, maxZ } = populateSlugInstances(snapshot, atlas.glyphs, instances)\n instances.maxSequence = maxSequence\n instances.bounds = computeInstanceBounds(\n snapshot.width,\n snapshot.height,\n motionPadding,\n minZ,\n maxZ,\n )\n return maxSequence\n}\n\nfunction rectCountFor(snapshot: DomLayoutSnapshot, receiveShadow: boolean): number {\n let count = 0\n for (const rect of snapshot.rects) if (rect.receiveShadow === receiveShadow) count++\n return count\n}\n\nfunction writeRectBatch(\n snapshot: DomLayoutSnapshot,\n receiveShadow: boolean,\n rects: Float32Array,\n colors: Uint8Array,\n radii: Float32Array,\n depths: Float32Array,\n): [number, number] {\n let index = 0\n let minZ = 0\n let maxZ = 0\n for (const item of snapshot.rects) {\n if (item.receiveShadow !== receiveShadow) continue\n const offset = index * 4\n rects[offset] = item.rect[0]\n rects[offset + 1] = item.rect[1]\n rects[offset + 2] = item.rect[2]\n rects[offset + 3] = item.rect[3]\n colors[offset] = byte(item.color[0])\n colors[offset + 1] = byte(item.color[1])\n colors[offset + 2] = byte(item.color[2])\n colors[offset + 3] = byte(item.color[3])\n radii[index] = item.radius\n depths[index] = item.z\n if (item.z < minZ) minZ = item.z\n if (item.z > maxZ) maxZ = item.z\n index++\n }\n return [minZ, maxZ]\n}\n\nexport function packRectInstances(\n snapshot: DomLayoutSnapshot,\n receiveShadow = false,\n): VanillaRectInstances | null {\n const count = rectCountFor(snapshot, receiveShadow)\n if (count === 0) return null\n const rects = new Float32Array(count * 4)\n const colors = new Uint8Array(count * 4)\n const radii = new Float32Array(count)\n const depths = new Float32Array(count)\n const [minZ, maxZ] = writeRectBatch(snapshot, receiveShadow, rects, colors, radii, depths)\n return {\n count,\n receiveShadow,\n rects,\n colors,\n radii,\n depths,\n bounds: computeInstanceBounds(snapshot.width, snapshot.height, 0, minZ, maxZ),\n }\n}\n\nexport function updateRectInstances(\n instances: VanillaRectInstances,\n snapshot: DomLayoutSnapshot,\n receiveShadow = instances.receiveShadow,\n): boolean {\n if (rectCountFor(snapshot, receiveShadow) !== instances.count) return false\n const [minZ, maxZ] = writeRectBatch(\n snapshot,\n receiveShadow,\n instances.rects,\n instances.colors,\n instances.radii,\n instances.depths,\n )\n instances.bounds = computeInstanceBounds(snapshot.width, snapshot.height, 0, minZ, maxZ)\n return true\n}\n\ntype DecorationRecord = readonly [\n stroke: readonly [number, number, number, number],\n rectIndex: number,\n motionIndex: number,\n color: readonly [number, number, number, number],\n clip: readonly [number, number, number, number],\n sequence: number,\n z: number,\n motionOrigin: readonly [number, number, number] | null,\n]\n\nfunction sameDecoration(a: TextDecorationLayout, b: TextDecorationLayout): boolean {\n return (\n a.line === b.line &&\n a.offset === b.offset &&\n a.thickness === b.thickness &&\n a.color.every((v, i) => v === b.color[i])\n )\n}\n\nfunction decorationRecords(\n snapshot: DomLayoutSnapshot,\n drawable: (key: string) => boolean,\n): readonly DecorationRecord[] {\n const glyphs = snapshot.glyphs\n const records: DecorationRecord[] = []\n if (!glyphs.some((glyph) => glyph.decorations?.length)) return records\n let glyphIndex = 0\n let motionIndex = -1\n let previousGroup: number | undefined\n for (let index = 0; index < glyphs.length; index++) {\n const glyph = glyphs[index]!\n if (!drawable(glyph.glyphKey)) continue\n if (glyph.shapeGroup === undefined || glyph.shapeGroup !== previousGroup) motionIndex++\n previousGroup = glyph.shapeGroup\n const decorations = glyph.decorations\n if (decorations) {\n for (const decoration of decorations) {\n if (decoration.thickness <= 0 || decoration.color[3] <= 0) continue\n const next = glyphs[index + 1]\n let right = glyph.originX + (glyph.decorationWidth ?? Math.abs(glyph.advance))\n if (\n next?.block === glyph.block &&\n next.lineBottom === glyph.lineBottom &&\n next.decorations?.some((candidate) => sameDecoration(decoration, candidate))\n ) {\n right = Math.max(right, next.originX)\n }\n const y = glyph.lineBottom + decoration.offset\n records.push([\n [glyph.originX, y - decoration.thickness / 2, right, y + decoration.thickness / 2],\n glyphIndex,\n glyph.motionOrigin?.[2] ?? motionIndex,\n decoration.color,\n glyph.clip,\n glyph.sequence,\n glyph.z,\n glyph.motionOrigin ?? null,\n ])\n }\n }\n glyphIndex++\n }\n return records\n}\n\nfunction writeDecorationBatch(\n records: readonly DecorationRecord[],\n sourceRects: ArrayLike<number>,\n rects: Float32Array,\n strokes: Float32Array,\n indices: Float32Array,\n colors: Uint8Array,\n clips: Float32Array,\n metadata: Float32Array,\n runMotion: Float32Array | null,\n): [number, number] {\n let minZ = 0\n let maxZ = 0\n for (let index = 0; index < records.length; index++) {\n const [stroke, rectIndex, motionIndex, color, clip, sequence, z, motionOrigin] = records[index]!\n const offset = index * 4\n const srcOffset = rectIndex * 4\n rects[offset] = sourceRects[srcOffset] ?? 0\n rects[offset + 1] = sourceRects[srcOffset + 1] ?? 0\n rects[offset + 2] = sourceRects[srcOffset + 2] ?? 0\n rects[offset + 3] = sourceRects[srcOffset + 3] ?? 0\n strokes.set(stroke, offset)\n clips.set(clip, offset)\n indices[index] = motionIndex\n colors[offset] = byte(color[0])\n colors[offset + 1] = byte(color[1])\n colors[offset + 2] = byte(color[2])\n colors[offset + 3] = byte(color[3])\n metadata[index * 2] = sequence\n metadata[index * 2 + 1] = z\n if (runMotion && motionOrigin) runMotion.set(motionOrigin, index * 3)\n if (z < minZ) minZ = z\n if (z > maxZ) maxZ = z\n }\n return [minZ, maxZ]\n}\n\nexport function packDecorationInstances(\n snapshot: DomLayoutSnapshot,\n sourceGlyphRects: ArrayLike<number>,\n drawable: (key: string) => boolean,\n motionPadding = 0,\n): VanillaDecorationInstances | null {\n const records = decorationRecords(snapshot, drawable)\n const count = records.length\n if (count === 0) return null\n const rects = new Float32Array(count * 4)\n const decorationRects = new Float32Array(count * 4)\n const decorationIndices = new Float32Array(count)\n const colors = new Uint8Array(count * 4)\n const clips = new Float32Array(count * 4)\n const metadata = new Float32Array(count * 2)\n const runMotion = records.some((record) => record[7] !== null)\n ? new Float32Array(count * 3)\n : null\n const [minZ, maxZ] = writeDecorationBatch(\n records,\n sourceGlyphRects,\n rects,\n decorationRects,\n decorationIndices,\n colors,\n clips,\n metadata,\n runMotion,\n )\n return {\n count,\n rects,\n decorationRects,\n decorationIndices,\n colors,\n clips,\n metadata,\n runMotion,\n bounds: computeInstanceBounds(snapshot.width, snapshot.height, motionPadding, minZ, maxZ),\n }\n}\n\nexport function updateDecorationInstances(\n instances: VanillaDecorationInstances,\n snapshot: DomLayoutSnapshot,\n sourceGlyphRects: ArrayLike<number>,\n drawable: (key: string) => boolean,\n motionPadding = 0,\n): boolean {\n const records = decorationRecords(snapshot, drawable)\n if (records.length === 0 || records.length !== instances.count) return false\n const wantsRun = records.some((record) => record[7] !== null)\n if (wantsRun !== (instances.runMotion !== null)) return false\n const [minZ, maxZ] = writeDecorationBatch(\n records,\n sourceGlyphRects,\n instances.rects,\n instances.decorationRects,\n instances.decorationIndices,\n instances.colors,\n instances.clips,\n instances.metadata,\n instances.runMotion,\n )\n instances.bounds = computeInstanceBounds(\n snapshot.width,\n snapshot.height,\n motionPadding,\n minZ,\n maxZ,\n )\n return true\n}\n\n// ============================================================================\n// Standalone Raw WGSL Dual-Ray Slug Shader & WebGPU Pipeline Helper\n// ============================================================================\n\n/**\n * Standalone WGSL vertex + fragment shader implementing Ultra-Text's dual-ray\n * SoA GPU Slug evaluator (`slugVert` + `slugFrag`) with perspective-safe\n * Jacobian quad skirting, single-word packed band headers, De Casteljau clipped\n * endpoint early-out, and Lengyel ray reliability weighting.\n *\n * Bind group 0 layout:\n * - `@binding(0) var<uniform> slugUniforms: SlugUniforms` (96 bytes: `mvp`, `viewportAndSkirt`, `tintAndFlags`)\n * - `@binding(1) var<storage, read> slugCurves: array<vec2f>`\n * - `@binding(2) var<storage, read> slugRows: array<u32>`\n *\n * Draw call: `pass.draw(6, instances.count)` (6 vertices generated procedurally per instance).\n */\nexport const SLUG_WGSL = /* wgsl */ `\nstruct SlugUniforms {\n mvp: mat4x4f,\n viewportAndSkirt: vec4f,\n tintAndFlags: vec4f,\n}\n\n@group(0) @binding(0) var<uniform> slugUniforms: SlugUniforms;\n@group(0) @binding(1) var<storage, read> slugCurves: array<vec2f>;\n@group(0) @binding(2) var<storage, read> slugRows: array<u32>;\n\nstruct SlugVSIn {\n @builtin(vertex_index) vertexIndex: u32,\n @location(0) rect: vec4f,\n @location(1) clip: vec4f,\n @location(2) color: vec4f,\n @location(3) glyphBounds: vec4f,\n @location(4) rawBand: vec4f,\n @location(5) sdfMeta: vec4f,\n}\n\nstruct SlugVSOut {\n @builtin(position) position: vec4f,\n @location(0) glyphPos: vec2f,\n @location(1) localPos: vec2f,\n @location(2) @interpolate(flat, either) clip: vec4f,\n @location(3) @interpolate(flat, either) color: vec4f,\n @location(4) @interpolate(flat, either) band: vec4f,\n @location(5) @interpolate(flat, either) bandOrigin: vec4f,\n}\n\nfn slug_vertex_skirt(\n mvp: mat4x4f,\n viewport: vec2f,\n quad: vec2f,\n position: vec2f,\n depth: f32,\n skirt: f32,\n) -> vec2f {\n let colX = mvp[0];\n let colY = mvp[1];\n let clip = mvp * vec4f(position, depth, 1.0);\n let safeW = max(clip.w, 1e-6);\n let sx = (colX.xy * safeW - clip.xy * colX.w) * viewport;\n let sy = (colY.xy * safeW - clip.xy * colY.w) * viewport;\n let absDet = max(abs(fma(sx.x, sy.y, -sx.y * sy.x)), 1e-20);\n let u = fma(quad, vec2f(2.0), vec2f(-1.0)) * vec2f(length(sy), length(sx)) * (skirt * 2.0 * safeW * safeW);\n let mult = max(clip.w, 0.0) / max(fma(-u.x, colX.w, fma(-u.y, colY.w, absDet * clip.w)), absDet * safeW * 0.0625);\n return u * mult;\n}\n\n@vertex\nfn slugVert(input: SlugVSIn) -> SlugVSOut {\n let vi = input.vertexIndex;\n let quad = vec2f(\n select(0.0, 1.0, (vi == 1u) || (vi == 2u) || (vi == 4u)),\n select(0.0, 1.0, (vi >= 2u) && (vi != 3u)),\n );\n let baseLocal = mix(input.rect.xy, input.rect.zw, quad);\n let depth = input.sdfMeta.y;\n let viewport = max(slugUniforms.viewportAndSkirt.xy, vec2f(1.0));\n let skirt = slugUniforms.viewportAndSkirt.z;\n let localOffset = slug_vertex_skirt(slugUniforms.mvp, viewport, quad, baseLocal, depth, skirt);\n let expandedLocal = baseLocal + localOffset;\n let localSize = max(input.rect.zw - input.rect.xy, vec2f(1e-6));\n let boundsSize = input.glyphBounds.zw - input.glyphBounds.xy;\n\n let packedCounts = u32(input.rawBand.y);\n let hBandCount = packedCounts & 255u;\n let vBandCount = packedCounts >> 8u;\n\n var out: SlugVSOut;\n out.position = slugUniforms.mvp * vec4f(expandedLocal, depth, 1.0);\n out.glyphPos = input.glyphBounds.xy + boundsSize * (quad + localOffset / localSize);\n out.localPos = expandedLocal;\n out.clip = input.clip;\n out.color = vec4f(input.color.rgb * slugUniforms.tintAndFlags.rgb, input.color.a * slugUniforms.viewportAndSkirt.w);\n out.band = vec4f(input.rawBand.x, input.rawBand.x + f32(hBandCount), input.rawBand.z, input.rawBand.w);\n out.bandOrigin = vec4f(\n -input.glyphBounds.y * input.rawBand.w,\n input.glyphBounds.z * input.rawBand.z,\n f32(max(hBandCount, 1u) - 1u),\n f32(max(vBandCount, 1u) - 1u),\n );\n return out;\n}\n\nfn slug_pixel_metrics_auto(p: vec2f) -> vec4f {\n let dx = dpdx(p);\n let dy = dpdy(p);\n let lenSq = max(vec2f(fma(dx.x, dx.x, dy.x * dy.x), fma(dx.y, dx.y, dy.y * dy.y)), vec2f(1e-18));\n let inv = inverseSqrt(lenSq);\n return vec4f(lenSq * (inv * 0.5), inv);\n}\n\nfn slug_band_active(packedRow: u32, span: vec2f) -> bool {\n return (packedRow & 63u) > 0u && span.x > f32((packedRow >> 6u) & 15u) && span.y > f32((packedRow >> 10u) & 3u);\n}\n\nfn slug_solve_straddle(c1: vec2f, c2: vec2f, c3: vec2f, xLo: f32, dy1: f32, s: f32, invDiam: f32) -> vec2f {\n let b = c1 - c2;\n let a = (c3 - c2) + b;\n let d = sqrt(max(fma(-a.y, dy1, b.y * b.y), 1e-24));\n let t = dy1 / fma(s, d, b.y);\n let u = saturate(fma(fma(a.x, t, -2.0 * b.x), t, c1.x - xLo) * invDiam);\n return vec2f(s * u, fma(-u, u, u));\n}\n\nfn slug_gather_ray(\n rowBase: u32,\n maxBand: f32,\n bf: f32,\n uSpan: vec2f,\n rc: vec2f,\n halfPx: f32,\n invDiam: f32,\n) -> vec2f {\n var cw = vec2f(0.0);\n if (bf >= -1e-4 && bf <= maxBand + 1.0001) {\n let bi = u32(clamp(bf, 0.0, maxBand));\n let packedRow = slugRows[rowBase + bi];\n if (slug_band_active(packedRow, uSpan)) {\n let count = packedRow & 63u;\n let start = packedRow >> 12u;\n let c2Base = start + (count << 1u);\n let xLo = rc.x - halfPx;\n let xHi = rc.x + halfPx;\n for (var i = 0u; i < count; i++) {\n let base = start + (i << 1u);\n let c1 = slugCurves[base];\n let c3 = slugCurves[base + 1u];\n if (max(c1.x, c3.x) <= xLo) {\n break;\n }\n let dy1 = c1.y - rc.y;\n let dy3 = c3.y - rc.y;\n let u1 = bitcast<u32>(dy1);\n let u3 = bitcast<u32>(dy3);\n if ((u1 ^ u3) < 0x80000000u) {\n continue;\n }\n let s = bitcast<f32>((u1 & 0x80000000u) | 0x3f800000u);\n if (min(c1.x, c3.x) >= xHi) {\n cw.x += s;\n continue;\n }\n let c2 = slugCurves[c2Base + i];\n let hit = slug_solve_straddle(c1, c2, c3, xLo, dy1, s, invDiam);\n cw.x += hit.x;\n cw.y = max(cw.y, hit.y);\n }\n }\n }\n return cw;\n}\n\nfn slug_combine_rays(xc: vec2f, yc: vec2f) -> f32 {\n let ax = abs(xc.x);\n let ay = abs(yc.x);\n let wx = xc.y * xc.y;\n let wy = yc.y * yc.y;\n let weighted = fma(ax, wx, ay * wy) / max(wx + wy, 1e-12);\n return saturate(max(weighted, min(ax, ay)));\n}\n\n@fragment\nfn slugFrag(input: SlugVSOut) -> @location(0) vec4f {\n if (\n input.localPos.x < input.clip.x ||\n input.localPos.x > input.clip.z ||\n input.localPos.y < input.clip.y ||\n input.localPos.y > input.clip.w\n ) {\n discard;\n }\n let metrics = slug_pixel_metrics_auto(input.glyphPos);\n let center = input.glyphPos;\n let bf = vec2f(\n fma(center.y, input.band.w, input.bandOrigin.x),\n input.bandOrigin.y - center.x * input.band.z,\n );\n let totalBands = input.bandOrigin.zw + vec2f(1.0);\n let scale4 = vec2f(4.0) / totalBands;\n let halfBand = vec2f(metrics.y * input.band.w, metrics.x * input.band.z) + vec2f(1e-4);\n let spanA = (bf + halfBand) * scale4;\n let spanB = (totalBands - bf + halfBand) * scale4;\n let xc = slug_gather_ray(\n u32(input.band.x),\n input.bandOrigin.z,\n bf.x,\n vec2f(spanB.y * 4.0, spanA.y),\n center,\n metrics.x,\n metrics.z,\n );\n let yc = slug_gather_ray(\n u32(input.band.y),\n input.bandOrigin.w,\n bf.y,\n vec2f(spanA.x * 4.0, spanB.x),\n vec2f(center.y, -center.x),\n metrics.y,\n metrics.w,\n );\n let coverage = slug_combine_rays(xc, yc);\n let alpha = coverage * input.color.a;\n if (alpha < 0.001953125) {\n discard;\n }\n return vec4f(input.color.rgb * alpha, alpha);\n}\n`\n\nexport interface VanillaSlugPipelineOptions {\n /** Color target format (e.g. `navigator.gpu.getPreferredCanvasFormat()`). Defaults to `'bgra8unorm'`. */\n format?: string\n /** Optional depth-stencil attachment format. */\n depthFormat?: string\n depthWriteEnabled?: boolean\n depthCompare?: string\n sampleCount?: number\n cullMode?: 'none' | 'front' | 'back'\n metaItemSize?: 1 | 2 | 3\n}\n\nexport interface VanillaSlugGpuInstances {\n readonly count: number\n readonly rects: VanillaGpuBuffer\n readonly clips: VanillaGpuBuffer\n readonly colors: VanillaGpuBuffer\n readonly glyphBounds: VanillaGpuBuffer\n readonly bands: VanillaGpuBuffer\n readonly metadata: VanillaGpuBuffer\n update(instances: VanillaSlugGlyphInstances): void\n dispose(): void\n}\n\nexport interface VanillaSlugDrawUniforms {\n /** Column-major `4x4` model-view-projection matrix (`Float32Array` of 16 floats). */\n mvp: ArrayLike<number>\n viewportWidth: number\n viewportHeight: number\n /** Quad AA skirt in device pixels. Defaults to `0.75`. */\n skirtPx?: number\n opacity?: number\n tint?: readonly [r: number, g: number, b: number]\n}\n\nexport interface VanillaSlugPipeline {\n readonly pipeline: { getBindGroupLayout(index: number): unknown }\n readonly uniformBuffer: VanillaGpuBuffer\n writeUniforms(uniforms: VanillaSlugDrawUniforms): void\n createBindGroup(atlas: Pick<VanillaSlugAtlas, 'curvesBuffer' | 'rowsBuffer'>): unknown\n draw(\n pass: VanillaSlugGpuRenderPass,\n bindGroup: unknown,\n gpuInstances: VanillaSlugGpuInstances,\n ): void\n dispose(): void\n}\n\n/** Uploads packed `VanillaSlugGlyphInstances` into 6 instanced `GPUBuffer`s for `SLUG_WGSL`. */\nexport function uploadSlugGlyphBuffers(\n device: VanillaSlugGpuDevice,\n instances: VanillaSlugGlyphInstances,\n): VanillaSlugGpuInstances {\n const usage = bufUsageOf()\n const vtxUsage = usage.VERTEX | usage.COPY_DST\n const make = (label: string, view: ArrayBufferView): VanillaGpuBuffer => {\n const buffer = device.createBuffer({\n label,\n size: align4Bytes(view.byteLength),\n usage: vtxUsage,\n })\n if (view.byteLength > 0) device.queue.writeBuffer(buffer, 0, view)\n return buffer\n }\n const expandMeta = (src: VanillaSlugGlyphInstances): Float32Array => {\n if (src.metaItemSize >= 2) return src.metadata\n const padded = new Float32Array(src.count * 2)\n for (let i = 0; i < src.count; i++) padded[i * 2] = src.metadata[i] ?? 0\n return padded\n }\n const rects = make('ultra-slug-rects', instances.rects)\n const clips = make('ultra-slug-clips', instances.clips)\n const colors = make('ultra-slug-colors', instances.colors)\n const glyphBounds = make('ultra-slug-bounds', instances.glyphBounds)\n const bands = make('ultra-slug-bands', instances.bands)\n const metadata = make('ultra-slug-meta', expandMeta(instances))\n let count = instances.count\n let disposed = false\n return {\n get count(): number {\n return count\n },\n rects,\n clips,\n colors,\n glyphBounds,\n bands,\n metadata,\n update(next: VanillaSlugGlyphInstances): void {\n if (disposed) return\n count = next.count\n if (next.rects.byteLength > 0) device.queue.writeBuffer(rects, 0, next.rects)\n if (next.clips.byteLength > 0) device.queue.writeBuffer(clips, 0, next.clips)\n if (next.colors.byteLength > 0) device.queue.writeBuffer(colors, 0, next.colors)\n if (next.glyphBounds.byteLength > 0)\n device.queue.writeBuffer(glyphBounds, 0, next.glyphBounds)\n if (next.bands.byteLength > 0) device.queue.writeBuffer(bands, 0, next.bands)\n const nextMeta = expandMeta(next)\n if (nextMeta.byteLength > 0) device.queue.writeBuffer(metadata, 0, nextMeta)\n },\n dispose(): void {\n if (disposed) return\n disposed = true\n rects.destroy()\n clips.destroy()\n colors.destroy()\n glyphBounds.destroy()\n bands.destroy()\n metadata.destroy()\n },\n }\n}\n\n/** Creates a ready-to-draw premultiplied-alpha WebGPU render pipeline for `SLUG_WGSL`. */\nexport function createVanillaSlugPipeline(\n device: VanillaSlugGpuDevice,\n options: VanillaSlugPipelineOptions = {},\n): VanillaSlugPipeline {\n const usage = bufUsageOf()\n const format = options.format ?? 'bgra8unorm'\n const metaStride = (options.metaItemSize ?? 2) * 4\n const module = device.createShaderModule({ label: 'ultra-slug-wgsl', code: SLUG_WGSL })\n const pipeline = device.createRenderPipeline({\n label: 'ultra-slug-pipeline',\n layout: 'auto',\n vertex: {\n module,\n entryPoint: 'slugVert',\n buffers: [\n {\n arrayStride: 16,\n stepMode: 'instance',\n attributes: [{ shaderLocation: 0, offset: 0, format: 'float32x4' }],\n },\n {\n arrayStride: 16,\n stepMode: 'instance',\n attributes: [{ shaderLocation: 1, offset: 0, format: 'float32x4' }],\n },\n {\n arrayStride: 4,\n stepMode: 'instance',\n attributes: [{ shaderLocation: 2, offset: 0, format: 'unorm8x4' }],\n },\n {\n arrayStride: 16,\n stepMode: 'instance',\n attributes: [{ shaderLocation: 3, offset: 0, format: 'float32x4' }],\n },\n {\n arrayStride: 16,\n stepMode: 'instance',\n attributes: [{ shaderLocation: 4, offset: 0, format: 'float32x4' }],\n },\n {\n arrayStride: metaStride,\n stepMode: 'instance',\n attributes: [\n {\n shaderLocation: 5,\n offset: 0,\n format: options.metaItemSize === 1 ? 'float32' : 'float32x2',\n },\n ],\n },\n ],\n },\n fragment: {\n module,\n entryPoint: 'slugFrag',\n targets: [\n {\n format,\n blend: {\n color: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' },\n alpha: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' },\n },\n },\n ],\n },\n primitive: { topology: 'triangle-list', cullMode: options.cullMode ?? 'none' },\n ...(options.depthFormat\n ? {\n depthStencil: {\n format: options.depthFormat,\n depthWriteEnabled: options.depthWriteEnabled ?? false,\n depthCompare: options.depthCompare ?? 'less-equal',\n },\n }\n : {}),\n ...(options.sampleCount === undefined ? {} : { multisample: { count: options.sampleCount } }),\n })\n\n const uniformData = new Float32Array(24)\n const uniformBuffer = device.createBuffer({\n label: 'ultra-slug-uniforms',\n size: uniformData.byteLength,\n usage: usage.UNIFORM | usage.COPY_DST,\n })\n let disposed = false\n\n return {\n pipeline,\n uniformBuffer,\n writeUniforms(uniforms: VanillaSlugDrawUniforms): void {\n if (disposed) return\n for (let i = 0; i < 16; i++) uniformData[i] = uniforms.mvp[i] ?? 0\n uniformData[16] = uniforms.viewportWidth\n uniformData[17] = uniforms.viewportHeight\n uniformData[18] = uniforms.skirtPx ?? 0.75\n uniformData[19] = uniforms.opacity ?? 1\n uniformData[20] = uniforms.tint?.[0] ?? 1\n uniformData[21] = uniforms.tint?.[1] ?? 1\n uniformData[22] = uniforms.tint?.[2] ?? 1\n uniformData[23] = 0\n device.queue.writeBuffer(uniformBuffer, 0, uniformData)\n },\n createBindGroup(atlas: Pick<VanillaSlugAtlas, 'curvesBuffer' | 'rowsBuffer'>): unknown {\n if (!atlas.curvesBuffer || !atlas.rowsBuffer) {\n throw new Error(\n 'createVanillaSlugPipeline.createBindGroup: atlas has no GPU storage buffers; pass a GPUDevice to buildVanillaSlugAtlas',\n )\n }\n return device.createBindGroup({\n label: 'ultra-slug-bind-group',\n layout: pipeline.getBindGroupLayout(0),\n entries: [\n { binding: 0, resource: { buffer: uniformBuffer } },\n { binding: 1, resource: { buffer: atlas.curvesBuffer } },\n { binding: 2, resource: { buffer: atlas.rowsBuffer } },\n ],\n })\n },\n draw(\n pass: VanillaSlugGpuRenderPass,\n bindGroup: unknown,\n gpuInstances: VanillaSlugGpuInstances,\n ): void {\n if (gpuInstances.count === 0) return\n pass.setPipeline(pipeline)\n pass.setBindGroup(0, bindGroup)\n pass.setVertexBuffer(0, gpuInstances.rects)\n pass.setVertexBuffer(1, gpuInstances.clips)\n pass.setVertexBuffer(2, gpuInstances.colors)\n pass.setVertexBuffer(3, gpuInstances.glyphBounds)\n pass.setVertexBuffer(4, gpuInstances.bands)\n pass.setVertexBuffer(5, gpuInstances.metadata)\n pass.draw(6, gpuInstances.count)\n },\n dispose(): void {\n if (disposed) return\n disposed = true\n uniformBuffer.destroy()\n },\n }\n}\n\n// ============================================================================\n// Retained Engine-Agnostic Controllers: VanillaDomSlug & VanillaSlugText\n// ============================================================================\n\nexport type VanillaSlugChangeReason = 'create' | 'rebuild' | 'reflow' | 'motion' | 'dispose'\n\nexport interface VanillaDomSlugRebuildOptions {\n outlines?: boolean\n atlas?: boolean\n signal?: AbortSignal\n}\n\nexport interface VanillaDomSlugOptions {\n colorGlyphs?: ColorGlyphMode\n svg?: boolean | DomSvgOptions\n tone?: TextToneOptions | false\n layoutEngine?: DomTextLayoutEngine\n textSelector?: string\n rectSelector?: string\n ignoreSelector?: string\n includeRootBackground?: boolean\n extraGlyphs?: string\n pixelsPerUnit?: number\n pixelSnap?: boolean\n textDepth?: number\n rectDepth?: number\n panelDepth?: number\n cjkLineBreaking?: boolean\n rtlReflow?: boolean\n reshape?: (text: string) => string\n selectable?: boolean\n motion?: SdfMotionOptions\n reflowable?: boolean\n observe?: boolean\n signal?: AbortSignal\n onError?: (error: unknown) => void\n outlineProvider?: WindfoilOutlineProvider\n missingGlyphs?: 'skip' | 'error'\n targetPiecesPerBand?: number\n traceSize?: number\n traceTolerance?: number\n /** Optional shared `VanillaSlugAtlas` across multiple `VanillaDomSlug` instances. */\n sharedAtlas?: VanillaSlugAtlas\n /** Called after initial creation, rebuild, reflow, motion update, or disposal. */\n onChange?: (instance: VanillaDomSlug, reason: VanillaSlugChangeReason) => void\n}\n\nfunction nowMs(): number {\n return typeof performance !== 'undefined' ? performance.now() : Date.now()\n}\n\nfunction linkAbortSignals(...signals: (AbortSignal | undefined)[]): [AbortController, () => void] {\n const controller = new AbortController()\n const active = signals.filter((signal): signal is AbortSignal => signal !== undefined)\n for (const signal of active) {\n if (signal.aborted) {\n controller.abort(signal.reason ?? makeAbortError())\n return [controller, (): void => undefined]\n }\n }\n const listeners = active.map((signal) => {\n const onAbort = (): void => {\n controller.abort(signal.reason ?? makeAbortError())\n }\n signal.addEventListener('abort', onAbort, { once: true })\n return [signal, onAbort] as const\n })\n return [\n controller,\n (): void => {\n for (const [signal, onAbort] of listeners) {\n signal.removeEventListener('abort', onAbort)\n }\n },\n ]\n}\n\nasync function waitForDocumentFonts(document: Document, signal?: AbortSignal): Promise<void> {\n signal?.throwIfAborted()\n const fonts = document.fonts as FontFaceSet | undefined\n if (!fonts) return\n if (!signal) {\n await Promise.resolve(fonts.ready)\n return\n }\n await new Promise<void>((resolve, reject) => {\n const onAbort = (): void => {\n reject(\n signal.reason instanceof Error\n ? signal.reason\n : makeAbortError(String(signal.reason ?? '')),\n )\n }\n signal.addEventListener('abort', onAbort, { once: true })\n void Promise.resolve(fonts.ready).then(\n () => {\n signal.removeEventListener('abort', onAbort)\n resolve()\n },\n (error: unknown) => {\n signal.removeEventListener('abort', onAbort)\n reject(error instanceof Error ? error : new Error(String(error)))\n },\n )\n })\n}\n\nexport class VanillaDomSlug {\n readonly element: HTMLElement\n readonly device: VanillaSlugGpuDevice | null\n readonly options: Readonly<VanillaDomSlugOptions>\n\n glyphs!: VanillaSlugGlyphInstances\n plainRects: VanillaRectInstances | null = null\n litRects: VanillaRectInstances | null = null\n decorations: VanillaDecorationInstances | null = null\n tone: ResolvedTextTone | null = null\n motion: Required<SdfMotionOptions>\n\n #a!: VanillaSlugAtlas\n #s: DomLayoutSnapshot | null = null\n #as = ''\n #ls = ''\n #o = true\n #st!: DomSdfStats\n #to: TracedOutlines | null = null\n #ro: ResizeObserver | null = null\n #mo: MutationObserver | null = null\n #uf: (() => void) | null = null\n #f: number | null = null\n #ac: AbortController | null = null\n #rv = 0\n #av = 0\n #sel = false\n #d = false\n #cbs = new Set<(instance: VanillaDomSlug, reason: VanillaSlugChangeReason) => void>()\n\n protected constructor(\n element: HTMLElement,\n deviceOrRenderer: VanillaSlugGpuDeviceSource,\n options: VanillaDomSlugOptions,\n ) {\n this.element = element\n this.device = resolveSlugGpuDevice(deviceOrRenderer)\n this.options = Object.freeze({ ...options })\n this.motion = {\n enabled: options.motion?.enabled ?? true,\n mode: options.motion?.mode ?? 'slide-up',\n strength: Math.max(0, options.motion?.strength ?? 18),\n speed: Math.max(0, options.motion?.speed ?? 1.35),\n stagger: Math.max(0, options.motion?.stagger ?? 0.045),\n }\n if (options.onChange) this.#cbs.add(options.onChange)\n }\n\n static async create(\n element: HTMLElement,\n deviceOrRenderer?: VanillaSlugGpuDeviceSource,\n options: VanillaDomSlugOptions = {},\n ): Promise<VanillaDomSlug> {\n if (!element.isConnected) {\n throw new Error('VanillaDomSlug.create requires a connected HTMLElement')\n }\n options.signal?.throwIfAborted()\n const instance = new VanillaDomSlug(element, deviceOrRenderer, options)\n try {\n instance.applySelectableAttribute()\n await instance.rebuild(options.signal ? { signal: options.signal } : {})\n instance.setupObservers()\n instance.notify('create')\n return instance\n } catch (error) {\n instance.dispose()\n throw error\n }\n }\n\n get atlas(): VanillaSlugAtlas {\n return this.#a\n }\n\n /** Alias for `element` matching `DomSlug.source`. */\n get source(): HTMLElement {\n return this.element\n }\n\n get stats(): Readonly<DomSdfStats> {\n return this.#st\n }\n\n get snapshot(): DomLayoutSnapshot | null {\n return this.#s\n }\n\n get width(): number {\n return this.#s?.width ?? 0\n }\n\n get height(): number {\n return this.#s?.height ?? 0\n }\n\n get isDisposed(): boolean {\n return this.#d\n }\n\n subscribe(\n listener: (instance: VanillaDomSlug, reason: VanillaSlugChangeReason) => void,\n ): () => void {\n this.#cbs.add(listener)\n return (): void => {\n this.#cbs.delete(listener)\n }\n }\n\n reflow(width: number): this {\n if (this.#d) throw new Error('Cannot reflow a disposed VanillaDomSlug instance')\n if (this.options.reflowable !== true || !this.#s) {\n throw new Error('VanillaDomSlug.reflow requires { reflowable: true } at creation time')\n }\n if (!Number.isFinite(width) || width <= 0) {\n throw new RangeError('VanillaDomSlug.reflow: width must be a positive finite number')\n }\n const geometryStart = nowMs()\n const nextSnapshot = reflowSnapshot(this.#s, width)\n const motionPadding = Math.max(0, this.motion.strength)\n if (updateSlugGlyphInstances(this.glyphs, nextSnapshot, this.#a, motionPadding) === null) {\n this.glyphs = packSlugGlyphInstances(nextSnapshot, this.#a, motionPadding)\n }\n if (this.decorations) {\n const drawable = (key: string): boolean =>\n (this.#a.glyphs.get(key)?.monotonePieceCount ?? 0) > 0\n if (\n !updateDecorationInstances(\n this.decorations,\n nextSnapshot,\n this.glyphs.glyphRects,\n drawable,\n motionPadding,\n )\n ) {\n this.decorations = packDecorationInstances(\n nextSnapshot,\n this.glyphs.glyphRects,\n drawable,\n motionPadding,\n )\n }\n }\n const geometryBuildMs = nowMs() - geometryStart\n this.#s = nextSnapshot\n this.#ls = ''\n const draws =\n (this.plainRects ? 1 : 0) +\n (this.litRects ? 1 : 0) +\n (this.glyphs.count > 0 ? 1 : 0) +\n (this.decorations ? 1 : 0)\n this.#st = Object.freeze({\n ...this.#st,\n atlasBuildMs: 0,\n layoutReadMs: 0,\n geometryBuildMs,\n lines: nextSnapshot.lineCount,\n draws,\n })\n this.notify('reflow')\n return this\n }\n\n setMotion(motion: SdfMotionOptions): this {\n if (this.#d) return this\n const previousStrength = this.motion.strength\n this.motion = {\n enabled: motion.enabled ?? this.motion.enabled,\n mode: motion.mode ?? this.motion.mode,\n strength: Math.max(0, motion.strength ?? this.motion.strength),\n speed: Math.max(0, motion.speed ?? this.motion.speed),\n stagger: Math.max(0, motion.stagger ?? this.motion.stagger),\n }\n if (this.motion.strength !== previousStrength && this.#s) {\n let minZ = 0\n let maxZ = 0\n for (const glyph of this.#s.glyphs) {\n if (glyph.z < minZ) minZ = glyph.z\n if (glyph.z > maxZ) maxZ = glyph.z\n }\n this.glyphs.bounds = computeInstanceBounds(\n this.#s.width,\n this.#s.height,\n this.motion.strength,\n minZ,\n maxZ,\n )\n }\n this.notify('motion')\n return this\n }\n\n async rebuild(rebuildOptions: VanillaDomSlugRebuildOptions = {}): Promise<this> {\n if (this.#d) throw new Error('Cannot rebuild a disposed VanillaDomSlug instance')\n if (!this.element.isConnected) {\n throw new Error('Cannot rebuild VanillaDomSlug when the source element is disconnected')\n }\n\n const version = ++this.#rv\n this.#ac?.abort(makeAbortError())\n const [controller, unlinkSignals] = linkAbortSignals(this.options.signal, rebuildOptions.signal)\n this.#ac = controller\n const { signal } = controller\n const forceOutlines = rebuildOptions.outlines === true || rebuildOptions.atlas === true\n\n let nextAtlas: VanillaSlugAtlas | undefined\n let nextOwnsAtlas = true\n\n try {\n await waitForDocumentFonts(this.element.ownerDocument, signal)\n signal.throwIfAborted()\n\n const opts = this.options\n const sharedAtlas = opts.sharedAtlas\n const currentAtlas = this.#a as VanillaSlugAtlas | undefined\n\n const layoutStart = nowMs()\n const snapshotOptions: DomSdfOptions = {\n ...(opts.colorGlyphs === undefined ? {} : { colorGlyphs: opts.colorGlyphs }),\n ...(opts.svg === undefined ? {} : { svg: opts.svg }),\n ...(opts.tone === undefined ? {} : { tone: opts.tone }),\n ...(opts.layoutEngine === undefined ? {} : { layoutEngine: opts.layoutEngine }),\n ...(opts.textSelector === undefined ? {} : { textSelector: opts.textSelector }),\n ...(opts.rectSelector === undefined ? {} : { rectSelector: opts.rectSelector }),\n ...(opts.ignoreSelector === undefined ? {} : { ignoreSelector: opts.ignoreSelector }),\n ...(opts.includeRootBackground === undefined\n ? {}\n : { includeRootBackground: opts.includeRootBackground }),\n ...(opts.extraGlyphs === undefined ? {} : { extraGlyphs: opts.extraGlyphs }),\n ...(opts.pixelsPerUnit === undefined ? {} : { pixelsPerUnit: opts.pixelsPerUnit }),\n ...(opts.pixelSnap === undefined ? {} : { pixelSnap: opts.pixelSnap }),\n ...(opts.textDepth === undefined ? {} : { textDepth: opts.textDepth }),\n ...(opts.rectDepth === undefined ? {} : { rectDepth: opts.rectDepth }),\n ...(opts.panelDepth === undefined ? {} : { panelDepth: opts.panelDepth }),\n ...(opts.cjkLineBreaking === undefined ? {} : { cjkLineBreaking: opts.cjkLineBreaking }),\n ...(opts.rtlReflow === undefined ? {} : { rtlReflow: opts.rtlReflow }),\n ...(opts.reshape === undefined ? {} : { reshape: opts.reshape }),\n ...(opts.reflowable === undefined ? {} : { reflowable: opts.reflowable }),\n signal,\n }\n const snapshot = await collectDomSnapshot(this.element, snapshotOptions)\n const layoutReadMs = nowMs() - layoutStart\n signal.throwIfAborted()\n const nextTone = this.resolveCaptureTone(snapshot)\n\n const canUseSharedAtlas = Boolean(\n !forceOutlines && sharedAtlas && snapshot.requests.every((r) => sharedAtlas.covers(r.key)),\n )\n const canReusePrivateAtlas = Boolean(\n !forceOutlines &&\n !canUseSharedAtlas &&\n currentAtlas &&\n this.#o &&\n (this.#as === snapshot.atlasSignature ||\n snapshot.requests.every((r) => currentAtlas.covers(r.key))),\n )\n\n const nextLayoutSignature = layoutSignatureOf(snapshot)\n if (this.#ls === '' && this.#s) {\n this.#ls = layoutSignatureOf(this.#s)\n }\n if (\n (canUseSharedAtlas || canReusePrivateAtlas) &&\n this.#ls !== '' &&\n nextLayoutSignature === this.#ls\n ) {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (version !== this.#rv || this.#d) throw makeAbortError()\n this.tone = nextTone\n this.#s = snapshot\n this.#st = Object.freeze({\n ...this.#st,\n atlasBuildMs: 0,\n layoutReadMs,\n geometryBuildMs: 0,\n })\n this.notify('rebuild')\n return this\n }\n\n const atlasStart = nowMs()\n if (canUseSharedAtlas && sharedAtlas) {\n nextAtlas = sharedAtlas\n nextOwnsAtlas = false\n } else if (canReusePrivateAtlas && currentAtlas) {\n nextAtlas = currentAtlas\n nextOwnsAtlas = true\n } else {\n let provider = opts.outlineProvider\n if (!provider) {\n if (!this.#to) {\n this.#to = createTracedOutlineProvider(this.element.ownerDocument, {\n ...(opts.colorGlyphs === undefined ? {} : { colorGlyphs: opts.colorGlyphs }),\n ...(opts.traceSize === undefined ? {} : { size: opts.traceSize }),\n ...(opts.traceTolerance === undefined ? {} : { tolerance: opts.traceTolerance }),\n })\n } else if (forceOutlines) {\n this.#to.clear()\n }\n provider = this.#to.provider\n }\n nextAtlas = await buildVanillaSlugAtlas(this.device, snapshot.requests, {\n outlineProvider: provider,\n missingGlyphs: opts.missingGlyphs ?? (opts.outlineProvider ? 'error' : 'skip'),\n ...(opts.targetPiecesPerBand === undefined\n ? {}\n : { targetPiecesPerBand: opts.targetPiecesPerBand }),\n signal,\n })\n nextOwnsAtlas = true\n }\n const atlasBuildMs = canUseSharedAtlas || canReusePrivateAtlas ? 0 : nowMs() - atlasStart\n signal.throwIfAborted()\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (version !== this.#rv || this.#d) throw makeAbortError()\n\n const resolvedAtlas = nextAtlas\n const geometryStart = nowMs()\n const motionPadding = Math.max(0, this.motion.strength)\n const drawable = (key: string): boolean =>\n (resolvedAtlas.glyphs.get(key)?.monotonePieceCount ?? 0) > 0\n\n const currentGlyphs = this.glyphs as VanillaSlugGlyphInstances | undefined\n if (\n !currentGlyphs ||\n updateSlugGlyphInstances(currentGlyphs, snapshot, resolvedAtlas, motionPadding) === null\n ) {\n this.glyphs = packSlugGlyphInstances(snapshot, resolvedAtlas, motionPadding)\n }\n\n if (!this.plainRects || !updateRectInstances(this.plainRects, snapshot, false)) {\n this.plainRects = packRectInstances(snapshot, false)\n }\n if (!this.litRects || !updateRectInstances(this.litRects, snapshot, true)) {\n this.litRects = packRectInstances(snapshot, true)\n }\n if (\n !this.decorations ||\n !updateDecorationInstances(\n this.decorations,\n snapshot,\n this.glyphs.glyphRects,\n drawable,\n motionPadding,\n )\n ) {\n this.decorations = packDecorationInstances(\n snapshot,\n this.glyphs.glyphRects,\n drawable,\n motionPadding,\n )\n }\n const geometryBuildMs = nowMs() - geometryStart\n\n const previousAtlas = this.#a as VanillaSlugAtlas | undefined\n const previousOwnsAtlas = this.#o\n this.#a = resolvedAtlas\n this.#o = nextOwnsAtlas\n this.tone = nextTone\n this.#s = snapshot\n if (!canUseSharedAtlas && !canReusePrivateAtlas) {\n this.#as = snapshot.atlasSignature\n }\n this.#ls = nextLayoutSignature\n this.#av = version\n this.#to?.retain(snapshot.requests.map((request) => request.key))\n\n let textGlyphs = 0\n let shapes = 0\n let skipped = 0\n for (const glyph of snapshot.glyphs) {\n if (glyph.shapeGroup !== undefined) shapes++\n else {\n textGlyphs++\n if (resolvedAtlas.skippedKeys.has(glyph.glyphKey)) skipped++\n }\n }\n const draws =\n (this.plainRects ? 1 : 0) +\n (this.litRects ? 1 : 0) +\n (this.glyphs.count > 0 ? 1 : 0) +\n (this.decorations ? 1 : 0)\n\n this.#st = Object.freeze({\n colorGlyphs: 0,\n shapes,\n fallbackGlyphs: skipped,\n switchableGlyphs: 0,\n atlasBuildMs,\n layoutReadMs,\n geometryBuildMs,\n glyphs: textGlyphs,\n rects: snapshot.rects.length,\n lines: snapshot.lineCount,\n draws,\n atlasWidth: 0,\n atlasHeight: 0,\n textBackend: 'slug',\n atlasMode: null,\n textStorageBytes: resolvedAtlas.byteLength,\n })\n\n if (previousAtlas && previousOwnsAtlas && previousAtlas !== resolvedAtlas) {\n previousAtlas.dispose()\n }\n if (this.#av > 1) this.notify('rebuild')\n return this\n } catch (error) {\n if (nextAtlas && nextOwnsAtlas && nextAtlas !== (this.#a as VanillaSlugAtlas | undefined)) {\n nextAtlas.dispose()\n }\n throw error\n } finally {\n unlinkSignals()\n if (this.#ac === controller) this.#ac = null\n }\n }\n\n dispose(): void {\n if (this.#d) return\n this.#d = true\n this.#ac?.abort(makeAbortError())\n this.#ac = null\n if (this.#f !== null && typeof cancelAnimationFrame === 'function') {\n cancelAnimationFrame(this.#f)\n this.#f = null\n }\n this.#ro?.disconnect()\n this.#ro = null\n this.#mo?.disconnect()\n this.#mo = null\n this.#uf?.()\n this.#uf = null\n this.#to?.clear()\n this.#to = null\n if (this.#sel) {\n this.element.classList.remove('sdf-selectable')\n this.#sel = false\n }\n const currentAtlas = this.#a as VanillaSlugAtlas | undefined\n if (currentAtlas && this.#o) {\n currentAtlas.dispose()\n }\n this.#s = null\n this.notify('dispose')\n this.#cbs.clear()\n }\n\n protected resolveCaptureTone(snapshot: DomLayoutSnapshot): ResolvedTextTone | null {\n return resolveDomTextTone(this.element, this.options.tone, {\n glyphs: snapshot.glyphs,\n rects: snapshot.rects,\n rootRect: this.options.includeRootBackground !== false,\n })\n }\n\n protected notify(reason: VanillaSlugChangeReason): void {\n for (const listener of this.#cbs) {\n listener(this, reason)\n }\n }\n\n protected applySelectableAttribute(): void {\n if (this.options.selectable !== true) return\n if (!this.element.classList.contains('sdf-selectable')) {\n this.element.classList.add('sdf-selectable')\n this.#sel = true\n }\n }\n\n protected setupObservers(): void {\n if (this.options.observe === false || this.#d) return\n const schedule = (forceOutlines = false): void => {\n if (this.#d || this.#f !== null) return\n if (typeof requestAnimationFrame === 'function') {\n this.#f = requestAnimationFrame(() => {\n this.#f = null\n if (this.#d || !this.element.isConnected) return\n void this.rebuild(forceOutlines ? { outlines: true } : {}).catch((error: unknown) => {\n if (!isAbortError(error)) this.options.onError?.(error)\n })\n })\n }\n }\n if (typeof ResizeObserver !== 'undefined') {\n this.#ro = new ResizeObserver(() => schedule(false))\n this.#ro.observe(this.element)\n }\n if (typeof MutationObserver !== 'undefined') {\n this.#mo = new MutationObserver(() => schedule(false))\n this.#mo.observe(this.element, {\n subtree: true,\n childList: true,\n characterData: true,\n attributes: true,\n attributeFilter: ['style', 'class', 'dir', 'lang', 'data-text-depth', 'data-sdf-depth'],\n })\n }\n const fonts = this.element.ownerDocument.fonts as FontFaceSet | undefined\n if (fonts && typeof fonts.addEventListener === 'function') {\n const onFonts = (): void => {\n this.#to?.clear()\n schedule(true)\n }\n fonts.addEventListener('loadingdone', onFonts)\n this.#uf = (): void => {\n fonts.removeEventListener('loadingdone', onFonts)\n }\n }\n }\n}\n\nexport { VanillaDomSlug as DomSlug, VanillaDomSlug as DomText, VanillaDomSlug as VanillaDomText }\n\nexport interface VanillaSlugTextOptions extends VanillaDomSlugOptions {\n device?: VanillaSlugGpuDeviceSource\n renderer?: VanillaSlugGpuDeviceSource\n css?: TextCss\n cssClass?: TextClass\n parent?: HTMLElement\n}\n\nfunction stripTextOnlyOptions(options: VanillaSlugTextOptions): VanillaDomSlugOptions {\n const domOptions: VanillaSlugTextOptions = { ...options }\n delete domOptions.css\n delete domOptions.cssClass\n delete domOptions.parent\n delete domOptions.device\n delete domOptions.renderer\n return domOptions\n}\n\nexport class VanillaSlugText extends VanillaDomSlug {\n readonly ready: Promise<this>\n readonly #host: HTMLElement\n #t: string\n\n constructor(text: string, options: VanillaSlugTextOptions = {}) {\n options.signal?.throwIfAborted()\n const [parent, host, source] = createTextSource(text, options)\n parent.append(host)\n try {\n super(\n source,\n options.device ?? options.renderer,\n stripTextOnlyOptions(copyTextOptions(options)),\n )\n } catch (error) {\n host.remove()\n throw error\n }\n this.#host = host\n this.#t = text\n this.ready = this.#p(options.signal)\n }\n\n async #p(signal?: AbortSignal): Promise<this> {\n try {\n await this.rebuild(signal ? { signal } : {})\n this.setupObservers()\n this.notify('create')\n return this\n } catch (error) {\n this.dispose()\n throw error\n }\n }\n\n static override create(text: string, options?: VanillaSlugTextOptions): Promise<VanillaSlugText>\n static override create(\n element: HTMLElement,\n deviceOrRenderer?: VanillaSlugGpuDeviceSource,\n options?: VanillaDomSlugOptions,\n ): Promise<VanillaDomSlug>\n static override async create(\n textOrElement: string | HTMLElement,\n optionsOrDevice?: VanillaSlugTextOptions | VanillaSlugGpuDeviceSource,\n maybeOptions?: VanillaDomSlugOptions,\n ): Promise<VanillaDomSlug> {\n if (typeof textOrElement === 'string') {\n const instance = new VanillaSlugText(\n textOrElement,\n (optionsOrDevice as VanillaSlugTextOptions | undefined) ?? {},\n )\n return instance.ready\n }\n return super.create(textOrElement, optionsOrDevice as VanillaSlugGpuDeviceSource, maybeOptions)\n }\n\n get text(): string {\n return this.#t\n }\n\n set text(value: string) {\n this.#t = value\n if (!this.isDisposed) this.element.textContent = value\n }\n\n async setText(value: string, options?: VanillaDomSlugRebuildOptions): Promise<this> {\n this.text = value\n return this.rebuild(options)\n }\n\n async setCss(css: TextCss | undefined, options?: VanillaDomSlugRebuildOptions): Promise<this> {\n if (!this.isDisposed) {\n this.element.style.cssText =\n css === undefined ? '' : cssDeclarations(this.element.ownerDocument, css)\n }\n return this.rebuild(options)\n }\n\n async setClass(\n cssClass: TextClass | undefined,\n options?: VanillaDomSlugRebuildOptions,\n ): Promise<this> {\n if (!this.isDisposed) {\n this.element.className = cssClass === undefined ? '' : classNames(cssClass)\n }\n return this.rebuild(options)\n }\n\n override dispose(): void {\n const wasDisposed = this.isDisposed\n super.dispose()\n if (!wasDisposed) this.#host.remove()\n }\n\n protected override resolveCaptureTone(snapshot: DomLayoutSnapshot): ResolvedTextTone | null {\n return resolveDomTextTone(this.element, this.options.tone, {\n glyphs: snapshot.glyphs,\n rects: snapshot.rects,\n rootRect: this.options.includeRootBackground !== false,\n page: false,\n })\n }\n}\n\nexport { VanillaSlugText as SlugText, VanillaSlugText as Text, VanillaSlugText as VanillaText }\n"],"mappings":";;;;;;;;;;;;AA6QA,SAAS,qBAAqB,QAAiE;CAC7F,IAAI,CAAC,QAAQ,OAAO;CACpB,IAAI,kBAAkB,UAAU,OAAO,OAAO,iBAAiB,YAAY,OAAO;CAClF,OAAO,YAAY,SAAU,OAAO,UAAU,OAAQ;AACxD;AAEA,IAAM,oBAAoB;CACxB,UAAU;CACV,UAAU;CACV,OAAO;CACP,QAAQ;CACR,SAAS;CACT,SAAS;AACX;AACA,IAAM,mBACH,WAA6D,kBAAkB;AAElF,SAAS,YAAY,YAA4B;CAC/C,OAAO,KAAK,IAAI,IAAK,aAAa,IAAK,EAAE;AAC3C;AAEA,SAAS,oBACP,QACA,OACA,MACkB;CAClB,MAAM,QAAQ,WAAW;CACzB,MAAM,aAAa,YAAY,KAAK,UAAU;CAC9C,MAAM,SAAS,OAAO,aAAa;EACjC;EACA,MAAM;EACN,OAAO,MAAM,UAAU,MAAM;CAC/B,CAAC;CACD,IAAI,KAAK,aAAa,GACpB,OAAO,MAAM,YAAY,QAAQ,GAAG,IAAI;CAE1C,OAAO;AACT;AAiDA,SAAS,eAAe,UAAU,kCAAyC;CACzE,IAAI,OAAO,iBAAiB,aAAa,OAAO,IAAI,aAAa,SAA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