{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "shad-fx-ascii",
  "title": "shad-fx: ASCII renderer",
  "author": "Piergiorgio Gonni <https://www.sekei.design>",
  "description": "AsciiCanvas: fills its positioned parent with a canvas that draws any effect as coloured glyphs, in the system monospace or a font you pass.",
  "registryDependencies": [
    "sekeidesign/shad-fx/shad-fx-engine",
    "sekeidesign/shad-fx/use-prefers-reduced-motion",
    "utils"
  ],
  "files": [
    {
      "path": "registry/shad-fx/ascii/painter.ts",
      "content": "import { blendOver, clamp01, type Renderer, type Rgb, type Surface } from \"../engine\";\n\n/** The system monospace, so nothing is downloaded. Tailwind's `font-mono` stack. */\nexport const SYSTEM_MONO =\n\t'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \"Liberation Mono\", \"Courier New\", monospace';\n\n/** Lightest to densest, for a glyph whose two halves are about equally lit. */\nexport const ASCII_RAMP = \".:-=+*#%@\";\n\n// Atlas slots: 0 is blank, then the half-lit shapes, the two glints, and the ramp.\nconst SHAPES = \"'\\\"._+*\";\nconst TOP_LIGHT = 1;\nconst TOP_HEAVY = 2;\nconst BOTTOM_LIGHT = 3;\nconst BOTTOM_HEAVY = 4;\nconst GLINT_SMALL = 5;\nconst GLINT_BIG = 6;\nconst RAMP_START = 7;\n\nconst glyphString = (ramp: string) => ` ${SHAPES}${ramp}`;\n\n/**\n * Glyph opacity by coverage. The glyph already carries density, so a square\n * root keeps faint glyphs readable while still fading to nothing.\n */\nconst OPACITY = Uint8Array.from({ length: 256 }, (_, a) => Math.round(255 * Math.sqrt(a / 255)));\n\n/**\n * Glyph index for every pair of half coverages, each quantised to 16 levels:\n * `lut[(top >> 4) << 4 | (bottom >> 4)]`.\n */\nexport function glyphTable(ramp: string): Uint8Array {\n\tconst n = ramp.length;\n\tconst lut = new Uint8Array(256);\n\tconst level = (q: number) => (q === 0 ? 0 : (q + 0.5) / 16);\n\tfor (let qt = 0; qt < 16; qt++) {\n\t\tfor (let qb = 0; qb < 16; qb++) {\n\t\t\tconst t = level(qt);\n\t\t\tconst b = level(qb);\n\t\t\tconst hi = Math.max(t, b);\n\t\t\tif (hi === 0) continue;\n\t\t\tlet k: number;\n\t\t\tif (Math.min(t, b) < hi * 0.25) {\n\t\t\t\t// One half carries the cell, so say which: `'` above the middle, `.` below.\n\t\t\t\tk = t > b ? (hi < 0.5 ? TOP_LIGHT : TOP_HEAVY) : hi < 0.5 ? BOTTOM_LIGHT : BOTTOM_HEAVY;\n\t\t\t} else {\n\t\t\t\tk = RAMP_START + Math.min(n - 1, Math.floor(((t + b) / 2) * n));\n\t\t\t}\n\t\t\tlut[(qt << 4) | qb] = k;\n\t\t}\n\t}\n\treturn lut;\n}\n\n/**\n * The surface an effect paints into, at two square samples per glyph, one\n * per half. Glyphs are about twice as tall as wide, so this keeps the\n * effect's cells square, and the two halves let a glyph take a shape.\n */\nexport class AsciiPainter implements Surface {\n\t/** Sample rows: two per glyph row. */\n\treadonly rows: number;\n\treadonly px: Uint32Array;\n\t/** A `glint`'s glyph per glyph cell, 0 where there is none. */\n\treadonly marks: Uint8Array;\n\n\tconstructor(\n\t\treadonly cols: number,\n\t\t/** Glyph rows. */\n\t\treadonly lines: number,\n\t) {\n\t\tthis.rows = lines * 2;\n\t\tthis.px = new Uint32Array(cols * this.rows);\n\t\tthis.marks = new Uint8Array(cols * lines);\n\t}\n\n\tclear() {\n\t\tthis.px.fill(0);\n\t\tthis.marks.fill(0);\n\t}\n\n\t/** Source-over onto whatever is already in the sample. */\n\tblend(x: number, y: number, color: Rgb, alpha: number) {\n\t\tif (x < 0 || y < 0 || x >= this.cols || y >= this.rows || alpha <= 0) return;\n\t\tblendOver(this.px, y * this.cols + x, color, alpha);\n\t}\n\n\t/** Density is coverage: the glyph ramp does the dithering. */\n\tdither(x: number, y: number, density: number, color: Rgb, gain = 1) {\n\t\tif (density <= 0.004) return;\n\t\tthis.blend(x, y, color, clamp01(density) * gain);\n\t}\n\n\t/** A sparkle is a glyph: as the arms flare it turns into `+`, then `*`. */\n\tglint(x: number, y: number, color: Rgb, alpha: number, arms = 0) {\n\t\tthis.blend(x, y, color, alpha);\n\t\tif (arms <= 0 || x < 0 || y < 0 || x >= this.cols || y >= this.rows) return;\n\t\tconst i = (y >> 1) * this.cols + x;\n\t\tconst k = arms > 0.5 ? GLINT_BIG : GLINT_SMALL;\n\t\tif (k > this.marks[i]) this.marks[i] = k;\n\t}\n\n\t/**\n\t * Folds each pair of samples into a glyph from `lut` and one colour, the\n\t * halves mixed by coverage. Blank cells leave `colors` untouched. Returns\n\t * how many cells are lit.\n\t */\n\tcompose(lut: Uint8Array, glyphs: Uint8Array, colors: Uint32Array): number {\n\t\tconst { cols, lines, px, marks } = this;\n\t\tlet lit = 0;\n\t\tfor (let gy = 0, i = 0; gy < lines; gy++) {\n\t\t\tlet s = gy * 2 * cols;\n\t\t\tfor (let gx = 0; gx < cols; gx++, i++, s++) {\n\t\t\t\tconst top = px[s];\n\t\t\t\tconst bottom = px[s + cols];\n\t\t\t\tconst at = top >>> 24;\n\t\t\t\tconst ab = bottom >>> 24;\n\t\t\t\tlet k = lut[((at >> 4) << 4) | (ab >> 4)];\n\t\t\t\tif (k === 0) {\n\t\t\t\t\tglyphs[i] = 0;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (marks[i]) k = marks[i];\n\t\t\t\tglyphs[i] = k;\n\t\t\t\tlit++;\n\t\t\t\tlet rgb: number;\n\t\t\t\tif (ab === 0) rgb = top & 0xffffff;\n\t\t\t\telse if (at === 0) rgb = bottom & 0xffffff;\n\t\t\t\telse {\n\t\t\t\t\tconst sum = at + ab;\n\t\t\t\t\tconst r = ((top & 255) * at + (bottom & 255) * ab) / sum;\n\t\t\t\t\tconst g = (((top >>> 8) & 255) * at + ((bottom >>> 8) & 255) * ab) / sum;\n\t\t\t\t\tconst b = (((top >>> 16) & 255) * at + ((bottom >>> 16) & 255) * ab) / sum;\n\t\t\t\t\trgb = (b << 16) | (g << 8) | r;\n\t\t\t\t}\n\t\t\t\tcolors[i] = ((OPACITY[at > ab ? at : ab] << 24) | rgb) >>> 0;\n\t\t\t}\n\t\t}\n\t\treturn lit;\n\t}\n}\n\nexport interface AsciiOptions {\n\t/** CSS px. A glyph cell is one advance wide and two tall. */\n\tfontSize?: number;\n\t/** A resolved family: no `var()`. */\n\tfontFamily?: string;\n\t/** Lightest to densest. */\n\tramp?: string;\n\tmaxCols?: number;\n\tmaxRows?: number;\n}\n\n/**\n * Draws an `AsciiPainter` as glyphs. Each glyph is rendered once, white, into\n * an atlas; a frame blits one slot per lit cell, then tints them all at once\n * with a one-pixel-per-glyph colour canvas scaled over them, `source-in`.\n */\nexport class AsciiRenderer implements Renderer {\n\tprivate painter: AsciiPainter | null = null;\n\tprivate readonly ctx: CanvasRenderingContext2D;\n\tprivate readonly atlas: HTMLCanvasElement;\n\tprivate readonly atlasCtx: CanvasRenderingContext2D;\n\tprivate readonly tint: HTMLCanvasElement;\n\tprivate readonly tintCtx: CanvasRenderingContext2D;\n\tprivate colors: ImageData | null = null;\n\tprivate colors32 = new Uint32Array(0);\n\tprivate glyphs = new Uint8Array(0);\n\tprivate lut: Uint8Array = new Uint8Array(0);\n\tprivate ramp = \"\";\n\tprivate fontFamily: string;\n\tprivate fontSize: number;\n\tprivate readonly maxCols: number;\n\tprivate readonly maxRows: number;\n\t/** Glyph cell in device px, and the ratio it was measured at. 0 until measured. */\n\tprivate cw = 0;\n\tprivate ch = 0;\n\tprivate dpr = 0;\n\n\tconstructor(\n\t\tprivate readonly canvas: HTMLCanvasElement,\n\t\t{ fontSize = 10, fontFamily = SYSTEM_MONO, ramp = \"\", maxCols = 320, maxRows = 160 }: AsciiOptions = {},\n\t) {\n\t\tthis.atlas = document.createElement(\"canvas\");\n\t\tthis.tint = document.createElement(\"canvas\");\n\t\tconst ctx = canvas.getContext(\"2d\");\n\t\tconst atlasCtx = this.atlas.getContext(\"2d\");\n\t\tconst tintCtx = this.tint.getContext(\"2d\");\n\t\tif (!ctx || !atlasCtx || !tintCtx) throw new Error(\"AsciiRenderer: 2d context unavailable\");\n\t\tthis.ctx = ctx;\n\t\tthis.atlasCtx = atlasCtx;\n\t\tthis.tintCtx = tintCtx;\n\t\tthis.fontSize = fontSize;\n\t\tthis.fontFamily = fontFamily;\n\t\tthis.maxCols = maxCols;\n\t\tthis.maxRows = maxRows;\n\t\tthis.setRamp(ramp);\n\t}\n\n\t/** The CSS font string, for `document.fonts`. */\n\tget font() {\n\t\treturn `${this.fontSize}px ${this.fontFamily}`;\n\t}\n\n\tresize(width: number, height: number) {\n\t\tconst dpr = globalThis.devicePixelRatio || 1;\n\t\tconst measured = dpr !== this.dpr || !this.cw;\n\t\tif (measured) {\n\t\t\tthis.dpr = dpr;\n\t\t\tthis.measure();\n\t\t}\n\t\t// Rounded up: the last glyph overhangs the box and is clipped, not a gap.\n\t\tconst cols = Math.min(this.maxCols, Math.max(2, Math.ceil((width * dpr) / this.cw)));\n\t\tconst lines = Math.min(this.maxRows, Math.max(2, Math.ceil((height * dpr) / this.ch)));\n\t\tconst same = this.painter?.cols === cols && this.painter.lines === lines;\n\t\tif (measured || !same) this.fit(cols, lines);\n\t\tif (same) {\n\t\t\t// The effect keeps its state; repaint the canvas `fit` just cleared.\n\t\t\tif (measured) this.present();\n\t\t\treturn null;\n\t\t}\n\t\tthis.painter = new AsciiPainter(cols, lines);\n\t\tthis.glyphs = new Uint8Array(cols * lines);\n\t\tthis.tint.width = cols;\n\t\tthis.tint.height = lines;\n\t\tthis.colors = this.tintCtx.createImageData(cols, lines);\n\t\tthis.colors32 = new Uint32Array(this.colors.data.buffer);\n\t\treturn this.painter;\n\t}\n\n\t/** Re-measures on the next `resize` if the font changed, or with `force` once a web font loads. */\n\tsetFont(family: string, size: number, force = false) {\n\t\tif (!force && family === this.fontFamily && size === this.fontSize) return;\n\t\tthis.fontFamily = family;\n\t\tthis.fontSize = size;\n\t\tthis.cw = 0;\n\t}\n\n\tsetRamp(ramp: string) {\n\t\tconst next = ramp || ASCII_RAMP;\n\t\tif (next === this.ramp) return;\n\t\tthis.ramp = next;\n\t\tthis.lut = glyphTable(next);\n\t\tthis.draw();\n\t\tthis.present();\n\t}\n\n\tpresent() {\n\t\tconst p = this.painter;\n\t\tconst colors = this.colors;\n\t\tif (!p || !colors) return;\n\t\tconst { ctx, atlas, cw, ch, glyphs } = this;\n\t\tconst w = p.cols * cw;\n\t\tconst h = p.lines * ch;\n\t\tctx.globalCompositeOperation = \"source-over\";\n\t\tctx.clearRect(0, 0, w, h);\n\t\tif (p.compose(this.lut, glyphs, this.colors32) === 0) return;\n\t\tfor (let i = 0, y = 0; y < h; y += ch) {\n\t\t\tfor (let x = 0; x < w; x += cw, i++) {\n\t\t\t\tconst k = glyphs[i];\n\t\t\t\tif (k) ctx.drawImage(atlas, k * cw, 0, cw, ch, x, y, cw, ch);\n\t\t\t}\n\t\t}\n\t\tthis.tintCtx.putImageData(colors, 0, 0);\n\t\tctx.globalCompositeOperation = \"source-in\";\n\t\tctx.imageSmoothingEnabled = false;\n\t\tctx.drawImage(this.tint, 0, 0, w, h);\n\t\tctx.globalCompositeOperation = \"source-over\";\n\t}\n\n\tprivate get deviceFont() {\n\t\treturn `${this.fontSize * this.dpr}px ${this.fontFamily}`;\n\t}\n\n\t/** Snaps the glyph cell to whole device px, so every blit lands on the grid. */\n\tprivate measure() {\n\t\tthis.atlasCtx.font = this.deviceFont;\n\t\tthis.cw = Math.max(1, Math.round(this.atlasCtx.measureText(\"M\").width));\n\t\tthis.ch = this.cw * 2;\n\t\tthis.draw();\n\t}\n\n\t/** Every glyph once, centred and clipped to its own slot. */\n\tprivate draw() {\n\t\tconst { atlas, atlasCtx: ctx, cw, ch } = this;\n\t\tif (!cw) return;\n\t\tconst glyphs = glyphString(this.ramp);\n\t\tatlas.width = glyphs.length * cw; // resets the context\n\t\tatlas.height = ch;\n\t\tctx.font = this.deviceFont;\n\t\tctx.fillStyle = \"#fff\";\n\t\tctx.textAlign = \"center\";\n\t\tctx.textBaseline = \"middle\";\n\t\tfor (let k = 1; k < glyphs.length; k++) {\n\t\t\tctx.save();\n\t\t\tctx.beginPath();\n\t\t\tctx.rect(k * cw, 0, cw, ch);\n\t\t\tctx.clip();\n\t\t\tctx.fillText(glyphs[k], k * cw + cw / 2, ch / 2);\n\t\t\tctx.restore();\n\t\t}\n\t}\n\n\t/** Sizing the backing store clears it. */\n\tprivate fit(cols: number, lines: number) {\n\t\tconst w = cols * this.cw;\n\t\tconst h = lines * this.ch;\n\t\tthis.canvas.width = w;\n\t\tthis.canvas.height = h;\n\t\tthis.canvas.style.width = `${w / this.dpr}px`;\n\t\tthis.canvas.style.height = `${h / this.dpr}px`;\n\t}\n}\n",
      "type": "registry:lib",
      "target": "@components/shad-fx/ascii/painter.ts"
    },
    {
      "path": "registry/shad-fx/ascii/ascii-canvas.tsx",
      "content": "\"use client\";\n\nimport { useEffect } from \"react\";\nimport { usePrefersReducedMotion } from \"@/hooks/use-prefers-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\nimport type { Fx } from \"../engine\";\nimport { useFxEngine } from \"../use-fx-engine\";\nimport { AsciiRenderer, SYSTEM_MONO } from \"./painter\";\n\nexport interface AsciiCanvasProps {\n\t/** From `useFx`. A different effect starts from scratch; the canvas is kept. */\n\teffect: Fx;\n\t/** Eases the effect in and out. Defaults to on. */\n\tactive?: boolean;\n\t/**\n\t * Any CSS `font-family`, `var()` included. Defaults to the system monospace.\n\t * Load a web font as the page already does; the canvas redraws once it lands.\n\t */\n\tfontFamily?: string;\n\t/** CSS px. A glyph cell is one advance wide and two tall. */\n\tfontSize?: number;\n\t/** Lightest to densest, for evenly lit glyphs. Defaults to `.:-=+*#%@`. */\n\tramp?: string;\n\tseed?: number;\n\t/** Ceiling on the glyph grid, so a large box can't cost a large frame. */\n\tmaxCols?: number;\n\tmaxRows?: number;\n\tclassName?: string;\n}\n\n// A canvas font can't hold `var()`, so the family is read back computed from the wrapper.\nconst computedFamily = (wrap: HTMLElement) => getComputedStyle(wrap).fontFamily || SYSTEM_MONO;\n\n/** Fills its positioned parent with a canvas drawing `effect` as coloured glyphs. */\nexport function AsciiCanvas({\n\teffect,\n\tactive = true,\n\tfontFamily = SYSTEM_MONO,\n\tfontSize = 10,\n\tramp,\n\tseed = 1,\n\tmaxCols,\n\tmaxRows,\n\tclassName,\n}: AsciiCanvasProps) {\n\tconst reduced = usePrefersReducedMotion();\n\tconst { wrapRef, canvasRef, engineRef, rendererRef } = useFxEngine(\n\t\t(canvas, wrap) =>\n\t\t\tnew AsciiRenderer(canvas, { fontFamily: computedFamily(wrap), fontSize, ramp, maxCols, maxRows }),\n\t\t{ effect, active, reduced, seed },\n\t\t[maxCols, maxRows],\n\t);\n\n\tuseEffect(() => {\n\t\trendererRef.current?.setRamp(ramp ?? \"\");\n\t}, [ramp, rendererRef]);\n\n\t// Re-runs after a rebuild, so a web font still loading reaches the new renderer.\n\t// biome-ignore lint/correctness/useExhaustiveDependencies: see above\n\tuseEffect(() => {\n\t\tconst wrap = wrapRef.current;\n\t\tconst renderer = rendererRef.current;\n\t\tconst engine = engineRef.current;\n\t\tif (!wrap || !renderer || !engine) return;\n\t\tlet live = true;\n\t\tconst family = computedFamily(wrap);\n\t\tconst apply = (force: boolean) => {\n\t\t\trenderer.setFont(family, fontSize, force);\n\t\t\tengine.resize(wrap.clientWidth, wrap.clientHeight);\n\t\t};\n\t\tapply(false);\n\t\tconst fonts = document.fonts;\n\t\tif (fonts && !fonts.check(renderer.font)) {\n\t\t\tfonts.load(renderer.font).then(() => live && apply(true), () => {});\n\t\t}\n\t\treturn () => {\n\t\t\tlive = false;\n\t\t};\n\t}, [fontFamily, fontSize, seed, maxCols, maxRows]);\n\n\treturn (\n\t\t<div\n\t\t\tref={wrapRef}\n\t\t\taria-hidden\n\t\t\tclassName={cn(\"pointer-events-none absolute inset-0 overflow-hidden\", className)}\n\t\t\tstyle={{ fontFamily }}\n\t\t>\n\t\t\t<canvas ref={canvasRef} className=\"absolute top-0 left-0\" />\n\t\t</div>\n\t);\n}\n",
      "type": "registry:ui",
      "target": "@components/shad-fx/ascii/ascii-canvas.tsx"
    },
    {
      "path": "registry/shad-fx/ascii/index.ts",
      "content": "export { AsciiCanvas, type AsciiCanvasProps } from \"./ascii-canvas\";\nexport {\n\tASCII_RAMP,\n\ttype AsciiOptions,\n\tAsciiPainter,\n\tAsciiRenderer,\n\tglyphTable,\n\tSYSTEM_MONO,\n} from \"./painter\";\n",
      "type": "registry:lib",
      "target": "@components/shad-fx/ascii/index.ts"
    }
  ],
  "docs": "Pair it with any effect: `const fx = useFx(fire, { height: 0.6 })`, then `<AsciiCanvas effect={fx} />`. The font defaults to the system monospace, so nothing is downloaded; pass a font-family name as `fontFamily`, as in CSS, to use your own. Options passed to useFx update in place without restarting the simulation.",
  "categories": [
    "shad-fx",
    "ascii",
    "canvas"
  ],
  "type": "registry:ui"
}