Skip to content
Charts55Components12Visuals14ASCII45
GitHubGet startedGet started
All ASCIILogoLettering
PreviousNext: Flag

Move across the letters to knock cells loose. Click to send a shockwave through them.

Logo

Lettering

A word set in big type, built from lit slabs of colour, with a sheen that passes now and then and snow if you want it.

Customize 8

Colours
800
0.0
0.00
14px
1.00
Install & copy sourceInstall & copy sourceSee propsSee props12

Live code

As tuned above.

Every control in the inspector updates this snippet directly. Defaults are omitted to keep your markup minimal.

hero.tsx

import { AsciiLogo } from '@/components/lilt/ascii/text/ascii-logo';

export function Hero() {
  return (
    <section style={{ height: 560 }}>
      <AsciiLogo />
    </section>
  );
}

Installation10

Source you own.

This is source, not a package: the shadcn CLI copies it into your project with the shared pieces it needs. Its only dependency is React.

$npx shadcn@latest add https://liltui.vercel.app/r/logo.json
components/lilt/ascii/text/ascii-logo.tsx

ascii-logo.tsx

'use client';

import { AsciiCanvas, useSceneProps, type SceneProps } from '../react/ascii-canvas';
import { createLogo, type LogoOptions } from './logo';

export type AsciiLogoProps = SceneProps<LogoOptions>;

/**
 * A word set in big type, drawn as lit slabs of colour, for the top of a page. The pointer knocks
 * cells loose and a click sends a shockwave. Pass `label` (usually the word) so screen readers
 * hear it; without one the canvas is decorative.
 */
export function AsciiLogo(props: AsciiLogoProps) {
  return <AsciiCanvas {...useSceneProps(props, createLogo)} />;
}
components/lilt/ascii/text/campfire.ts

campfire.ts

import { approach, clamp, hash3, noise3 } from '../engine/noise';
import { DOT, type GlyphSurface } from '../engine/surface';

/** A campfire's colours, from the cool edge of a flame to its core, then the logs. */
export const FIRE_COLORS = ['#a3201a', '#f2621f', '#ffb22e', '#fff1c7', '#7a5640'] as const;

// Thin glyphs at the cool tips, heavy ones in the core.
const FLAME = '.:;+*%#@';
const DARK_RED = 0;
const ORANGE = 1;
const AMBER = 2;
const PALE = 3;
const LOG = 4;

interface Spark {
  x: number;
  y: number;
  vx: number;
  vy: number;
  life: number;
  age: number;
}

export interface Campfire {
  /** Where the fire sits: the centre of its base in cells, and its size in cells. */
  place(col: number, base: number, width: number, height: number): void;
  /**
   * One step. `lean` tips the flames, -1 to 1: a host leans them toward a warm hand. `aspect` is
   * the grid's cell height over width, so sparks rise at the same speed whatever the font.
   */
  step(dt: number, lean: number, aspect: number): void;
  /** A poke with a stick: the fire flares and throws sparks. */
  stoke(): void;
  /** Draws the fire, its sparks and its logs; `tone` is the palette index of FIRE_COLORS[0]. */
  draw(surface: GlyphSurface, tone: number): void;
  /** The centre of the flames, in cells, for measuring warmth. */
  readonly centre: { x: number; y: number };
  readonly width: number;
  readonly height: number;
}

/**
 * A small campfire for a scene to set on its ground: a heat field fed from the logs rises, drifts
 * and cools through noise, so the flames lick and fork. Sparks break off and wander up. Built for
 * hosts that place several: each keeps its own little field, so a fire costs only its own cells.
 */
export function createCampfire(seed = 0): Campfire {
  let w = 0;
  let h = 0;
  let x0 = 0;
  let y0 = 0;
  let heat = new Float32Array(0);
  let next = new Float32Array(0);
  const sparks: Spark[] = [];
  let time = seed * 7.3;
  let tick = 0;
  let lean = 0;
  let flare = 0;
  let owed = 0;
  const centre = { x: 0, y: 0 };

  const at = (col: number, row: number) => row * w + col;

  function feed() {
    const mid = (w - 1) / 2;
    for (let col = 0; col < w; col++) {
      const edge = clamp(1 - Math.abs(col - mid) / (w * 0.42), 0, 1);
      const flicker = 0.5 + 0.6 * noise3(col * 0.5, time * 4, seed + 1);
      const value = Math.pow(edge, 0.55) * flicker * (1 + flare * 0.5);
      heat[at(col, h - 1)] = value;
      heat[at(col, h - 2)] = Math.max(heat[at(col, h - 2)]!, value * 0.92);
    }
  }

  function rise() {
    const cooling = 2.1 / (h * 0.92);
    for (let row = 0; row < h - 2; row++) {
      for (let col = 0; col < w; col++) {
        const drift = (noise3(col * 0.2, row * 0.2 - time * 1.4, seed + 4) - 0.5) * 1.6 + lean;
        const from = clamp(Math.round(col - drift), 1, w - 2);
        const below = at(from, row + 1);
        const twoBelow = at(from, Math.min(h - 1, row + 2));
        const v = (heat[below - 1]! + heat[below]! * 2 + heat[below + 1]! + heat[twoBelow]!) / 5;
        const cool =
          cooling * (0.15 + 2 * noise3(col * 0.35, row * 0.25 + time * 3.2, seed + 9) ** 2);
        next[at(col, row)] = Math.max(0, v - cool);
      }
    }
    for (let row = h - 2; row < h; row++)
      for (let col = 0; col < w; col++) next[at(col, row)] = heat[at(col, row)]!;
    [heat, next] = [next, heat];
  }

  function spark(burst = 1) {
    sparks.push({
      x: x0 + w / 2 + (Math.random() - 0.5) * w * 0.5,
      y: y0 + h * (0.45 + Math.random() * 0.3),
      vx: (Math.random() - 0.5) * 4 * burst,
      vy: -(4 + Math.random() * 7) * burst,
      life: 0.7 + Math.random() * 1.2,
      age: 0,
    });
  }

  return {
    centre,
    get width() {
      return w;
    },
    get height() {
      return h;
    },
    place(col, base, width, height) {
      const nw = Math.max(5, Math.round(width) | 1);
      const nh = Math.max(4, Math.round(height));
      x0 = Math.round(col - nw / 2);
      y0 = Math.round(base - nh + 1);
      if (nw !== w || nh !== h) {
        w = nw;
        h = nh;
        heat = new Float32Array(w * h);
        next = new Float32Array(w * h);
        sparks.length = 0;
      }
      centre.x = x0 + w / 2;
      centre.y = y0 + h * 0.6;
    },
    step(dt, target, aspect) {
      if (!w) return;
      time += dt;
      flare = approach(flare, 0, 1.6, dt);
      lean = approach(lean, clamp(target, -1, 1) * 1.1, 3, dt);
      tick += dt;
      while (tick >= 1 / 30) {
        tick -= 1 / 30;
        feed();
        rise();
      }
      owed += dt * (2.5 + flare * 14);
      while (owed >= 1) {
        owed -= 1;
        spark();
      }
      for (let i = sparks.length - 1; i >= 0; i--) {
        const s = sparks[i]!;
        s.age += dt;
        if (s.age > s.life) {
          sparks.splice(i, 1);
          continue;
        }
        const wobble = (noise3(s.x * 0.3, s.y * 0.3, time + i) - 0.5) * 10;
        s.vx = approach(s.vx, wobble + lean * 4, 1.5, dt);
        s.vy = approach(s.vy, -6, 0.8, dt);
        s.x += s.vx * dt;
        s.y += (s.vy * dt) / aspect;
      }
    },
    stoke() {
      flare = 1;
      for (let i = 0; i < 18; i++) spark(1.5);
    },
    draw(surface, tone) {
      if (!w) return;
      for (let row = 0; row < h; row++) {
        for (let col = 0; col < w; col++) {
          const v = heat[at(col, row)]!;
          if (v < 0.07) continue;
          const glyph = FLAME[Math.min(FLAME.length - 1, Math.floor(v * FLAME.length * 1.05))]!;
          const shade = v > 0.78 ? PALE : v > 0.5 ? AMBER : v > 0.24 ? ORANGE : DARK_RED;
          surface.put(x0 + col, y0 + row, glyph, tone + shade, clamp(0.3 + v * 0.9, 0, 1));
        }
      }
      for (const s of sparks) {
        const fade = 1 - s.age / s.life;
        surface.put(s.x, s.y, fade > 0.6 ? '*' : DOT, tone + (fade > 0.5 ? AMBER : ORANGE), fade);
      }
      // Two logs under the flames, with embers glowing between them.
      const first = x0 + 1;
      const last = x0 + w - 2;
      for (let col = first; col <= last; col++) {
        const glyph = col === first ? '(' : col === last ? ')' : '=';
        surface.put(col, y0 + h, glyph, tone + LOG, 0.75);
        const ember = noise3(col * 0.6, time * 1.5, seed + 2);
        if (hash3(col, seed, 5) < 0.5 && ember > 0.5)
          surface.put(col, y0 + h, DOT, tone + AMBER, ember);
      }
    },
  };
}
components/lilt/ascii/text/logo.ts

logo.ts

import { ramp } from '../engine/glyphs';
import { clamp, hash3 } from '../engine/noise';
import type { GlyphSurface } from '../engine/surface';
import type { AsciiGrid, AsciiPointer, AsciiScene } from '../engine/types';
import { bitmapInk } from './bitmap-font';
import { createCampfire, FIRE_COLORS } from './campfire';

export interface LogoOptions {
  /** The word, set in type. Default 'lilt'. */
  text?: string;
  /** Gradient stops as hex colours, left to right. Default violet to rose. */
  colors?: readonly string[];
  /** Font weight of the lettering, 100 to 900. Default 800. */
  weight?: number;
  /** CSS font family for the lettering. Default the system's sans serif. */
  font?: string;
  /**
   * How hard it snows, 0 to 2. Snow drifts down, settles in caps on the letters, melts from the
   * pointer, and falls off any letter that is knocked loose. Default 0.
   */
  snow?: number;
  /** Colour of the snow. Default a cool white. */
  snowColor?: string;
  /**
   * Share of the height kept clear below the word, 0 to 0.7, for content laid over the lower part.
   * The snow still falls the full height. Default 0.
   */
  clearBelow?: number;
  /**
   * Campfires on the ground (at `FIRE_GROUND` of the height), each a share of the width from 0 to
   * 1, such as `[0.2, 0.8]`. Their flames reach toward a hand held near, snow that drifts in
   * hisses into steam, and a click on a fire stokes it. Pair with `CursorWarmth` for a pointer
   * that frosts over in the cold and thaws by the fire. Default none.
   */
  fires?: readonly number[];
}

export const DEFAULT_LOGO_COLORS: readonly string[] = ['#7c5cff', '#e5489c'];
const SANS = 'system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';

/** Hues along the gradient, and shades of each from shadow to highlight. */
const HUES = 8;
const SHADES = 7;
const DEEP = HUES * SHADES;
const INK = DEEP + 1;
const SNOW = DEEP + 2;
const FIRE = DEEP + 3;
/**
 * Where the fires stand, as a share of the height from the top: the row they burn on. A page that
 * marks its fires for CursorWarmth can place the marks from this.
 */
export const FIRE_GROUND = 0.9;
/** Seconds a puff of steam lasts after snow falls into a fire. */
const STEAM_LIFE = 0.9;

interface Steam {
  x: number;
  y: number;
  age: number;
}

/** Glyphs cut into the faces: clean where the light falls, denser in shadow. */
const ENGRAVE = '.:-=';
const EDGE = '.:';
const SCRAMBLE = '01<>/\\{}[]#$%&*+=?~';
/** Light from the upper left, toward the viewer: x, y (down), z. */
const LIGHT = [-0.5, -0.6, 0.62].map((v, _, a) => v / Math.hypot(...a));

/** Seconds the lettering takes to build in from the left. */
const ENTRANCE = 1.3;
/** A sheen crosses the word every this many seconds. */
const SHEEN_EVERY = 6.5;
const SHEEN_FIRST = 2.4;
const SHEEN_SWEEP = 1.5;

/** The spring that brings loose cells home, and the gravity they fall under while loose. */
const SPRING = 38;
const DAMPING = 7.5;
const GRAVITY = 70;
const REACH = 5.5;
const RING_SPEED = 55;

interface Ring {
  x: number;
  y: number;
  age: number;
}

function parseHex(value: string): [number, number, number] | null {
  const m = value.trim().match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i);
  if (!m) return null;
  let hex = m[1]!;
  if (hex.length === 3) hex = hex.replace(/./g, (c) => c + c);
  const n = parseInt(hex, 16);
  return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}

const toHex = (rgb: number[]) =>
  '#' + rgb.map((v) => clamp(Math.round(v), 0, 255).toString(16).padStart(2, '0')).join('');

const mixRgb = (a: number[], b: number[], t: number) => a.map((v, i) => v + (b[i]! - v) * t);

/** The palette: each hue along the gradient in shades, then the engraving dark and the ink. */
function buildPalette(colors: readonly string[]) {
  const stops = colors.map(parseHex).filter((c): c is [number, number, number] => !!c);
  const use = stops.length ? stops : DEFAULT_LOGO_COLORS.map((c) => parseHex(c)!);
  const out: string[] = [];
  for (let h = 0; h < HUES; h++) {
    const at = (h / (HUES - 1)) * (use.length - 1);
    const k = Math.min(use.length - 2, Math.floor(at));
    const base = use.length === 1 ? use[0]! : mixRgb(use[k]!, use[k + 1]!, at - k);
    for (let s = 0; s < SHADES; s++) {
      const v = s / (SHADES - 1);
      // Shadows fall toward a deep violet-black; highlights lift toward white.
      out.push(
        toHex(
          v < 0.55
            ? mixRgb(base, [18, 12, 30], ((0.55 - v) / 0.55) * 0.5)
            : mixRgb(base, [255, 255, 255], ((v - 0.55) / 0.45) * 0.5),
        ),
      );
    }
  }
  out.push('#0c0a14', 'ink');
  return out;
}

/** Samples of ink per square unit when the lettering is drawn. */
const P = 4;

/**
 * The lettering as a field of ink, drawn with the browser's own type on a canvas at `P` samples a
 * square unit. Null where there is no canvas to draw on, such as on a server or in a test.
 */
function rasterise(
  text: string,
  width: number,
  height: number,
  font: string,
  weight: number,
): Float32Array | null {
  if (typeof document === 'undefined') return null;
  const canvas = document.createElement('canvas');
  let ctx: CanvasRenderingContext2D | null = null;
  try {
    ctx = canvas.getContext('2d', { willReadFrequently: true });
  } catch {
    return null;
  }
  if (!ctx) return null;
  canvas.width = Math.ceil(width * P);
  canvas.height = Math.ceil(height * P);
  const box = fitBox(width, height);

  ctx.font = `${weight} 100px ${font}`;
  // A little air between letters, so each stays its own slab on a coarse grid.
  const spaced = ctx as CanvasRenderingContext2D & { letterSpacing?: string };
  const spacing = 'letterSpacing' in ctx;
  if (spacing) spaced.letterSpacing = '6px';
  const m = ctx.measureText(text);
  const w = m.actualBoundingBoxLeft + m.actualBoundingBoxRight;
  const h = m.actualBoundingBoxAscent + m.actualBoundingBoxDescent;
  if (!(w > 0 && h > 0)) return null;
  const scale = Math.min((box.w * P) / w, (box.h * P) / h);
  ctx.font = `${weight} ${100 * scale}px ${font}`;
  if (spacing) spaced.letterSpacing = `${6 * scale}px`;
  ctx.textBaseline = 'alphabetic';
  ctx.fillStyle = '#fff';
  const x = canvas.width / 2 - ((m.actualBoundingBoxRight - m.actualBoundingBoxLeft) * scale) / 2;
  const y =
    canvas.height / 2 + ((m.actualBoundingBoxAscent - m.actualBoundingBoxDescent) * scale) / 2;
  ctx.fillText(text, x, y);
  const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
  const ink = new Float32Array(canvas.width * canvas.height);
  for (let i = 0; i < ink.length; i++) ink[i] = data[i * 4 + 3]! / 255;
  return ink;
}

/** A box blur of radius `r` along each row, or down each column, in place. */
function boxBlur(field: Float32Array, w: number, h: number, r: number, vertical: boolean) {
  const lines = vertical ? w : h;
  const len = vertical ? h : w;
  const stride = vertical ? w : 1;
  const jump = vertical ? 1 : w;
  const line = new Float32Array(len);
  for (let l = 0; l < lines; l++) {
    const base = l * jump;
    for (let k = 0; k < len; k++) line[k] = field[base + k * stride]!;
    let sum = 0;
    for (let k = -r; k <= r; k++) sum += line[clamp(k, 0, len - 1)]!;
    for (let k = 0; k < len; k++) {
      field[base + k * stride] = sum / (2 * r + 1);
      sum += line[Math.min(len - 1, k + r + 1)]! - line[Math.max(0, k - r)]!;
    }
  }
}

/** Where the word may sit, in square units: centred, with generous room around it. */
export function fitBox(width: number, height: number) {
  const padX = Math.max(4, width * 0.09);
  const padY = Math.max(4, height * 0.18);
  return { w: Math.max(1, width - padX * 2), h: Math.max(1, height - padY * 2) };
}

/**
 * Big lettering set in type, for the top of a page. Each letter is a solid, bevelled slab: blocks
 * shaded by a light from the upper left, a single family of glyphs cut into the faces that turn
 * from the light, and soft edges in light glyphs. A sheen crosses it now and then. The pointer
 * knocks cells loose; they tumble and spring back home. A click sends a shockwave through it.
 */
export function createLogo(options: LogoOptions = {}): AsciiScene {
  const text = (options.text ?? 'lilt').trim() || 'lilt';
  const weight = clamp(Math.round(options.weight ?? 800), 100, 900);
  const font = options.font || SANS;
  const palette = [
    ...buildPalette(options.colors ?? DEFAULT_LOGO_COLORS),
    options.snowColor ?? '#e6ecfb',
    ...FIRE_COLORS,
  ];
  const snowfall = clamp(options.snow ?? 0, 0, 2);
  const clearBelow = clamp(options.clearBelow ?? 0, 0, 0.7);
  const firePlaces = (options.fires ?? []).map((x) => clamp(x, 0.02, 0.98));
  const fires = firePlaces.map((_, k) => createCampfire(k + 1));
  /** The row each fire burns on; its logs lie on the row below and the ground below that. */
  let fireBase = 0;
  const steam: Steam[] = [];

  let grid: AsciiGrid = { cols: 0, rows: 0, aspect: 2 };
  let cover: Float32Array = new Float32Array(0);
  /** Shade and hue of each cell at rest, and the glyph cut into it. */
  let shade = new Float32Array(0);
  let hue = new Uint8Array(0);
  /** Cells the lettering touches, as indices, and the reveal time of each. */
  let cells = new Int32Array(0);
  let reveal = new Float32Array(0);
  // Loose cells: offset from home and velocity in square units, and how loose (gravity wins).
  let ox = new Float32Array(0);
  let oy = new Float32Array(0);
  let vx = new Float32Array(0);
  let vy = new Float32Array(0);
  let loose = new Float32Array(0);
  let active = new Uint8Array(0);
  let moving: number[] = [];
  /** A shockwave's kick for each cell: when it lands, and how hard. */
  let kickAt = new Float32Array(0);
  let kick = new Float32Array(0);
  const rings: Ring[] = [];
  let time = 0;
  let px = 0;
  let py = 0;
  let pointerOn = false;
  let pointerSpeed = 0;
  let bounds = { x0: 0, x1: 0 };
  // Snow: flakes in flight, in cells, and how deep it lies on each letter's top.
  let fx: number[] = [];
  let fy: number[] = [];
  let fvx: number[] = [];
  let fvy: number[] = [];
  let fseed: number[] = [];
  /** For each cell, its place among the tops of the letters, or -1. */
  let ledgeOf = new Int32Array(0);
  let ledges = new Int32Array(0);
  let cap = new Float32Array(0);
  /** The tops either side of each top, or -1, so snow can spread along a letter. */
  let leftTop = new Int32Array(0);
  let rightTop = new Int32Array(0);
  let wind = 0;

  function wake(i: number) {
    if (active[i]) return;
    active[i] = 1;
    moving.push(i);
  }

  function build() {
    const { cols, rows, aspect } = grid;
    const size = cols * rows;
    const width = cols;
    const tall = rows * aspect;
    const fw = Math.ceil(width * P);
    const fh = Math.ceil(tall * P);
    // The word is set in the band above any room kept clear, and the rest of the field is empty.
    const band = tall * (1 - clearBelow);
    const set =
      rasterise(text, width, band, font, weight) ?? bitmapInk(text, width, band, P, fitBox);
    const ink = new Float32Array(fw * fh);
    ink.set(set.subarray(0, Math.min(set.length, ink.length)));

    // How much of each cell the ink covers.
    cover = new Float32Array(size);
    for (let row = 0; row < rows; row++) {
      const y0 = Math.floor(row * aspect * P);
      const y1 = Math.min(fh, Math.floor((row + 1) * aspect * P));
      for (let col = 0; col < cols; col++) {
        let sum = 0;
        let n = 0;
        for (let py = y0; py < y1; py++) {
          for (let px = col * P; px < (col + 1) * P && px < fw; px++) {
            sum += ink[py * fw + px]!;
            n++;
          }
        }
        cover[row * cols + col] = n ? sum / n : 0;
      }
    }
    shade = new Float32Array(size);
    hue = new Uint8Array(size);
    ox = new Float32Array(size);
    oy = new Float32Array(size);
    vx = new Float32Array(size);
    vy = new Float32Array(size);
    loose = new Float32Array(size);
    active = new Uint8Array(size);
    kickAt = new Float32Array(size).fill(-1);
    kick = new Float32Array(size);
    moving = [];

    // The height of the slab: the ink blurred, so its rim rounds over smoothly into a flat face.
    // The bevel's width follows the size of the type.
    let top = fh;
    let foot = 0;
    for (let py = 0; py < fh; py++) {
      for (let px = 0; px < fw; px += 2) {
        if (ink[py * fw + px]! > 0.5) {
          top = Math.min(top, py);
          foot = Math.max(foot, py);
          break;
        }
      }
    }
    const bevel = clamp(((foot - top) / P) * 0.05, 1.2, 3.5);
    const height = Float32Array.from(ink);
    const r = Math.max(1, Math.round(bevel * P * 0.7));
    for (let pass = 0; pass < 2; pass++) {
      boxBlur(height, fw, fh, r, false);
      boxBlur(height, fw, fh, r, true);
    }
    const heightAt = (x: number, y: number) =>
      height[clamp(Math.round(y * P), 0, fh - 1) * fw + clamp(Math.round(x * P), 0, fw - 1)]!;

    let x0 = cols;
    let x1 = 0;
    let y0 = rows;
    let y1 = 0;
    const list: number[] = [];
    for (let i = 0; i < size; i++) {
      if (cover[i]! < 0.08) continue;
      list.push(i);
      const col = i % cols;
      const row = (i - col) / cols;
      x0 = Math.min(x0, col);
      x1 = Math.max(x1, col);
      y0 = Math.min(y0, row);
      y1 = Math.max(y1, row);
    }
    cells = Int32Array.from(list);
    bounds = { x0, x1 };
    reveal = new Float32Array(size);
    const span = Math.max(1, x1 - x0);
    const tallRows = Math.max(1, y1 - y0);
    const lift = bevel * 1.3;
    for (const i of cells) {
      const col = i % cols;
      const row = (i - col) / cols;
      const at = (col - x0) / span;
      // The gradient runs left to right, leaning a little with the light.
      hue[i] = clamp(
        Math.round((at * 0.9 + ((row - y0) / tallRows) * 0.1) * (HUES - 1)),
        0,
        HUES - 1,
      );
      const x = col + 0.5;
      const y = (row + 0.5) * aspect;
      const nx = (-(heightAt(x + 0.75, y) - heightAt(x - 0.75, y)) / 1.5) * lift;
      const ny = (-(heightAt(x, y + 0.75) - heightAt(x, y - 0.75)) / 1.5) * lift;
      const nl = Math.hypot(nx, ny, 1);
      const lit = (nx * LIGHT[0]! + ny * LIGHT[1]! + LIGHT[2]!) / nl;
      // Flat faces sit in the middle; the bevel catches or loses the light; the top of the word
      // is a touch brighter than its foot.
      const flat = LIGHT[2]!;
      const v = 0.62 + (lit - flat) * 1.35 + (0.5 - (row - y0) / tallRows) * 0.16;
      shade[i] = clamp(v, 0, 1);
      reveal[i] = 0.1 + at * (ENTRANCE - 0.45) + hash3(col, row, 3) * 0.25;
    }
    if (snowfall > 0) settleSnow();
  }

  /** Finds the tops of the letters and lays a first fall of snow, so it reads as winter at once. */
  function settleSnow() {
    const { cols, rows } = grid;
    ledgeOf = new Int32Array(cols * rows).fill(-1);
    const list: number[] = [];
    for (const i of cells) {
      if (cover[i]! < 0.5 || i < cols || cover[i - cols]! >= 0.5) continue;
      ledgeOf[i] = list.length;
      list.push(i);
    }
    ledges = Int32Array.from(list);
    cap = new Float32Array(list.length);
    leftTop = new Int32Array(list.length);
    rightTop = new Int32Array(list.length);
    list.forEach((i, k) => {
      const col = i % cols;
      cap[k] = 0.7 + 0.25 * Math.sin(col * 0.37 + 1.3) + 0.15 * Math.sin(col * 1.1);
      leftTop[k] = col > 0 ? ledgeOf[i - 1]! : -1;
      rightTop[k] = col < cols - 1 ? ledgeOf[i + 1]! : -1;
    });
    fx = [];
    fy = [];
    fvx = [];
    fvy = [];
    fseed = [];
    const count = flakesWanted();
    for (let k = 0; k < count; k++) spawn(hash3(k, 1, 2) * cols, hash3(k, 2, 3) * rows, 0, 2);
  }

  const flakesWanted = () => Math.round(((grid.cols * grid.rows) / 120) * snowfall);

  function spawn(x: number, y: number, vx0: number, vy0: number) {
    fx.push(x);
    fy.push(y);
    fvx.push(vx0);
    fvy.push(vy0);
    fseed.push(Math.random());
  }

  /** Throws the snow off a letter's top as loose flakes. */
  function shed(k: number, vx0: number, vy0: number) {
    const depth = cap[k]!;
    if (depth < 0.05) return;
    const i = ledges[k]!;
    const col = i % grid.cols;
    const row = (i - col) / grid.cols;
    const n = Math.min(4, Math.ceil(depth * 2.5));
    for (let j = 0; j < n; j++) {
      spawn(
        col + Math.random(),
        row - 0.5 - Math.random(),
        vx0 + (Math.random() - 0.5) * 6,
        vy0 - Math.random() * 6,
      );
    }
    cap[k] = 0;
  }

  function removeFlake(n: number) {
    const last = fx.length - 1;
    fx[n] = fx[last]!;
    fy[n] = fy[last]!;
    fvx[n] = fvx[last]!;
    fvy[n] = fvy[last]!;
    fseed[n] = fseed[last]!;
    fx.pop();
    fy.pop();
    fvx.pop();
    fvy.pop();
    fseed.pop();
  }

  function stepSnow(dt: number) {
    const { cols, rows, aspect } = grid;
    wind = 0.6 * Math.sin(time * 0.13) + 0.35 * Math.sin(time * 0.41 + 1);
    // The pointer is a warm breath: it melts the caps it passes, and a quick pass blows them off.
    if (pointerOn) {
      for (let k = 0; k < ledges.length; k++) {
        if (cap[k]! <= 0) continue;
        const i = ledges[k]!;
        const col = i % cols;
        const row = (i - col) / cols;
        const d = Math.hypot(col + 0.5 - px, (row - 0.5) * aspect - py);
        if (d >= REACH) continue;
        if (pointerSpeed > 25) shed(k, (col + 0.5 - px) * 2, -4);
        else cap[k] = Math.max(0, cap[k]! - dt * 1.6 * (1 - d / REACH));
      }
    }
    // A letter knocked loose drops its snow.
    for (const i of moving) {
      const k = ledgeOf[i]!;
      if (k >= 0 && cap[k]! > 0 && (Math.abs(ox[i]!) > 0.4 || Math.abs(oy[i]!) > 0.4)) {
        shed(k, vx[i]! * 0.3, (vy[i]! * 0.2) / aspect);
      }
    }
    const target = flakesWanted();
    for (let n = 0; n < fx.length; n++) {
      const seed = fseed[n]!;
      const fall = 2.6 + seed * 3.2;
      const sway = Math.sin(time * (0.8 + seed) + seed * 40) * 0.9 + wind * 2;
      fvx[n] = fvx[n]! + (sway - fvx[n]!) * Math.min(1, dt * 1.5);
      fvy[n] = fvy[n]! + (fall - fvy[n]!) * Math.min(1, dt * 1.2);
      if (pointerOn) {
        const dx = fx[n]! - px;
        const dy = fy[n]! * aspect - py;
        const d = Math.hypot(dx, dy);
        if (d < REACH && d > 0.01) {
          const f = (1 - d / REACH) * 30 * dt;
          fvx[n] = fvx[n]! + (dx / d) * f;
          fvy[n] = fvy[n]! + ((dy / d) * f) / aspect;
        }
      }
      fx[n] = fx[n]! + fvx[n]! * dt;
      fy[n] = fy[n]! + fvy[n]! * dt;
      const col = Math.floor(fx[n]!);
      const row = Math.floor(fy[n]!);
      let landed = false;
      if (col >= 0 && col < cols && row >= 0 && row + 1 < rows && fvy[n]! > 0) {
        const below = (row + 1) * cols + col;
        const k = ledgeOf[below]!;
        if (k >= 0 && !active[below] && time > reveal[below]!) {
          if (cap[k]! < 1.8) cap[k] = cap[k]! + 0.09 + seed * 0.06;
          landed = true;
        } else if (cover[row * cols + col]! >= 0.5) {
          landed = true;
        }
      }
      if (!landed && fx[n]! > -3 && fx[n]! < cols + 3 && fy[n]! < rows + 1) continue;
      // A flake that lands or leaves is replaced high up, while the sky wants more.
      if (fx.length > target) {
        removeFlake(n);
        n--;
        continue;
      }
      fx[n] = Math.random() * (cols + 8) - 4 - wind * 4;
      fy[n] = -1 - Math.random() * 4;
      fvx[n] = 0;
      fvy[n] = 2;
      fseed[n] = Math.random();
    }
    // Lying snow evens out along each letter's top, so caps read as one drift rather than tufts.
    const rate = Math.min(1, dt * 3);
    for (let k = 0; k < cap.length; k++) {
      const l = leftTop[k]!;
      const r = rightTop[k]!;
      let sum = 0;
      let n = 0;
      if (l >= 0 && !active[ledges[l]!]) {
        sum += cap[l]!;
        n++;
      }
      if (r >= 0 && !active[ledges[r]!]) {
        sum += cap[r]!;
        n++;
      }
      if (n) cap[k] = cap[k]! + (sum / n - cap[k]!) * rate * 0.5;
    }
    // Lying snow slowly sublimes, so caps breathe rather than fill for ever.
    for (let k = 0; k < cap.length; k++) cap[k] = Math.max(0, cap[k]! - dt * 0.012);
  }

  function drawSnow(surface: GlyphSurface) {
    const { cols } = grid;
    for (let k = 0; k < ledges.length; k++) {
      const depth = cap[k]!;
      if (depth < 0.06) continue;
      const i = ledges[k]!;
      if (time < reveal[i]! + 0.25) continue;
      if (active[i] && (Math.abs(ox[i]!) > 0.4 || Math.abs(oy[i]!) > 0.4)) continue;
      const col = i % cols;
      const row = (i - col) / cols;
      layer(surface, col, row - 1, depth);
      if (depth > 1) layer(surface, col, row - 2, depth - 1);
    }
    for (let n = 0; n < fx.length; n++) {
      const col = Math.floor(fx[n]!);
      const row = Math.floor(fy[n]!);
      if (surface.filled(col, row)) continue;
      const seed = fseed[n]!;
      surface.put(col, row, seed > 0.82 ? '*' : seed > 0.45 ? '+' : '.', SNOW, 0.45 + seed * 0.5);
    }
  }

  /** A cell of lying snow, `depth` of a cell deep: a dusting, then a solid block. */
  function layer(surface: GlyphSurface, col: number, row: number, depth: number) {
    if (row < 0 || depth < 0.08) return;
    if (depth >= 0.3) surface.fill(col, row, SNOW, 0.5 + 0.45 * Math.min(1, depth));
    else surface.put(col, row, '.', SNOW, 0.5 + depth);
  }

  /** Sets the fires on the ground line, sized to the sky. */
  function placeFires() {
    const { cols, rows } = grid;
    const width = clamp(Math.round(cols * 0.075), 9, 17);
    const height = Math.round(width * 1.05);
    fireBase = Math.round(rows * FIRE_GROUND);
    fires.forEach((fire, k) => fire.place(firePlaces[k]! * cols, fireBase, width, height));
  }

  function stepFires(dt: number, pointer: AsciiPointer) {
    const { aspect } = grid;
    // Flames reach toward a hand held near them.
    for (const fire of fires) {
      const d = Math.hypot(pointer.x - fire.centre.x, (pointer.y - fire.centre.y) * aspect);
      const near = pointer.active ? clamp(1 - d / (fire.width * 4), 0, 1) : 0;
      fire.step(dt, clamp((pointer.x - fire.centre.x) / (fire.width * 1.5), -1, 1) * near, aspect);
    }
    // Snow that drifts into a fire hisses into steam.
    for (let n = fx.length - 1; n >= 0; n--) {
      for (const fire of fires) {
        if (Math.abs(fx[n]! - fire.centre.x) > fire.width * 0.45) continue;
        if (Math.abs(fy[n]! - fire.centre.y) > fire.height * 0.55) continue;
        steam.push({ x: fx[n]!, y: fy[n]!, age: 0 });
        removeFlake(n);
        break;
      }
    }
    for (let i = steam.length - 1; i >= 0; i--) {
      const puff = steam[i]!;
      puff.age += dt;
      if (puff.age > STEAM_LIFE) steam.splice(i, 1);
      else puff.y -= dt * 3;
    }
  }

  function drawFires(surface: GlyphSurface) {
    const { cols } = grid;
    // A low drift of snow either side of each fire, melted back into a clearing round it.
    for (const fire of fires) {
      const span = fire.width * 2.2;
      for (let col = Math.floor(fire.centre.x - span); col <= fire.centre.x + span; col++) {
        if (col < 0 || col >= cols) continue;
        const dx = Math.abs(col + 0.5 - fire.centre.x);
        if (dx < fire.width * 0.6) continue;
        const depth = Math.pow(Math.max(0, 1 - dx / span), 0.7);
        if (depth < 0.05) continue;
        surface.put(col, fireBase + 1, depth > 0.5 ? ':' : '.', SNOW, 0.2 + depth * 0.5);
        if (depth > 0.75) surface.put(col, fireBase, '.', SNOW, (depth - 0.75) * 1.6);
      }
      fire.draw(surface, FIRE);
    }
    for (const puff of steam) {
      const t = puff.age / STEAM_LIFE;
      surface.put(puff.x, puff.y, t < 0.5 ? '~' : '.', SNOW, (1 - t) * 0.7);
    }
  }

  function sheenAt(x: number, y: number) {
    if (time < SHEEN_FIRST) return 0;
    const phase = (time - SHEEN_FIRST) % SHEEN_EVERY;
    if (phase > SHEEN_SWEEP) return 0;
    // A slanted band crossing from just before the word to just past it.
    const t = phase / SHEEN_SWEEP;
    const eased = t * t * (3 - 2 * t);
    const from = bounds.x0 - 14;
    const to = bounds.x1 + 14 + grid.rows * grid.aspect * 0.6;
    const pos = from + (to - from) * eased;
    const d = (x + y * 0.6 - pos) / 5;
    return Math.exp(-d * d);
  }

  return {
    palette,
    lineHeight: 0.9,
    settle: ENTRANCE + 0.4,
    resize(next) {
      grid = next;
      rings.length = 0;
      build();
      if (fires.length) placeFires();
    },
    step(dt, pointer: AsciiPointer) {
      if (!grid.cols) return;
      time += dt;
      const { cols, rows, aspect } = grid;
      const nx = pointer.x;
      const ny = pointer.y * aspect;
      const moved = pointerOn && pointer.active ? Math.hypot(nx - px, ny - py) / dt : 0;
      pointerSpeed = pointerSpeed + (moved - pointerSpeed) * Math.min(1, dt * 12);
      pointerOn = pointer.active;
      px = nx;
      py = ny;

      // The pointer pushes cells away around it, and a quick pass knocks them loose.
      if (pointerOn && time > ENTRANCE * 0.6) {
        const r0 = Math.max(0, Math.floor((py - REACH) / aspect));
        const r1 = Math.min(rows - 1, Math.ceil((py + REACH) / aspect));
        const c0 = Math.max(0, Math.floor(px - REACH));
        const c1 = Math.min(cols - 1, Math.ceil(px + REACH));
        const knock = clamp(pointerSpeed / 40, 0, 1);
        for (let row = r0; row <= r1; row++) {
          for (let col = c0; col <= c1; col++) {
            const i = row * cols + col;
            if (cover[i]! < 0.5) continue;
            const dx = col + 0.5 + ox[i]! - px;
            const dy = (row + 0.5) * aspect + oy[i]! - py;
            const d = Math.hypot(dx, dy);
            if (d >= REACH || d < 1e-3) continue;
            const f = 1 - d / REACH;
            wake(i);
            vx[i] = vx[i]! + (dx / d) * f * f * 420 * dt;
            vy[i] = vy[i]! + ((dy / d) * f * f * 420 - f * 60 * knock) * dt;
            loose[i] = Math.max(loose[i]!, f * knock);
          }
        }
      }

      // The shockwave lands on each cell as the ring passes it.
      if (rings.length) {
        for (const i of cells) {
          const at = kickAt[i]!;
          if (at < 0 || at > time) continue;
          kickAt[i] = -1;
          const col = i % cols;
          const row = (i - col) / cols;
          const ring = rings[rings.length - 1]!;
          const dx = col + 0.5 - ring.x;
          const dy = (row + 0.5) * aspect - ring.y;
          const d = Math.hypot(dx, dy) || 1;
          const s = kick[i]!;
          wake(i);
          vx[i] = vx[i]! + (dx / d) * s * 60;
          vy[i] = vy[i]! + ((dy / d) * s * 60 - s * 30);
          loose[i] = Math.max(loose[i]!, s);
        }
        for (const ring of rings) ring.age += dt;
        while (rings.length && rings[0]!.age > 2.2) rings.shift();
      }

      // Loose cells fly and fall, then the spring takes over and brings them home.
      const keep: number[] = [];
      for (const i of moving) {
        const l = loose[i]!;
        const pull = SPRING * (1 - l) * (1 - l);
        vx[i] = vx[i]! + (-ox[i]! * pull - vx[i]! * DAMPING * (1 - l * 0.7)) * dt;
        vy[i] = vy[i]! + (-oy[i]! * pull + GRAVITY * l - vy[i]! * DAMPING * (1 - l * 0.7)) * dt;
        ox[i] = ox[i]! + vx[i]! * dt;
        oy[i] = oy[i]! + vy[i]! * dt;
        loose[i] = Math.max(0, l - dt / 0.75);
        const still =
          !loose[i] &&
          Math.abs(ox[i]!) + Math.abs(oy[i]!) < 0.03 &&
          Math.abs(vx[i]!) + Math.abs(vy[i]!) < 0.2;
        if (still) {
          ox[i] = oy[i] = vx[i] = vy[i] = 0;
          active[i] = 0;
        } else keep.push(i);
      }
      moving = keep;
      if (snowfall > 0) stepSnow(dt);
      if (fires.length) stepFires(dt, pointer);
    },
    press(x, y) {
      if (!grid.cols) return;
      const { cols, aspect } = grid;
      // A click on a fire stokes it.
      const poked = fires.find(
        (fire) => Math.hypot(x - fire.centre.x, (y - fire.centre.y) * aspect) < fire.width * 1.3,
      );
      if (poked) {
        poked.stoke();
        return;
      }
      const cx = x;
      const cy = y * aspect;
      rings.push({ x: cx, y: cy, age: 0 });
      // The blast throws the snow off every letter near it.
      for (let k = 0; k < ledges.length; k++) {
        const i = ledges[k]!;
        const d = Math.hypot((i % cols) + 0.5 - cx, Math.floor(i / cols) * aspect - cy);
        if (d < 30) shed(k, ((i % cols) - cx) * 0.4, -10 * (1 - d / 30));
      }
      if (rings.length > 3) rings.shift();
      const reach = Math.max(grid.cols, grid.rows * aspect) * 0.6;
      for (const i of cells) {
        if (cover[i]! < 0.5) continue;
        const col = i % cols;
        const row = (i - col) / cols;
        const d = Math.hypot(col + 0.5 - cx, (row + 0.5) * aspect - cy);
        if (d > reach) continue;
        kickAt[i] = time + d / RING_SPEED;
        kick[i] = Math.pow(1 - d / reach, 1.6) * (0.7 + 0.3 * hash3(col, row, 9));
      }
    },
    draw(surface: GlyphSurface) {
      if (!grid.cols) return;
      const { cols, aspect } = grid;
      // Homes first: the lettering at rest, with holes where cells have flown.
      for (const i of cells) {
        const col = i % cols;
        const row = (i - col) / cols;
        const c = cover[i]!;
        const since = time - reveal[i]!;
        if (since < 0) continue;
        const h = hue[i]! * SHADES;
        if (active[i] && (Math.abs(ox[i]!) > 0.5 || Math.abs(oy[i]!) > aspect * 0.5)) continue;
        if (since < 0.22) {
          // Arriving: a glyph or two of scramble before the block lands.
          const tick = Math.floor(time * 20);
          const glyph = SCRAMBLE[Math.floor(hash3(col, row, tick) * SCRAMBLE.length)]!;
          surface.put(col, row, glyph, h + 4, 0.55 + c * 0.4);
          continue;
        }
        const x = col + 0.5;
        const y = (row + 0.5) * aspect;
        const gleam = sheenAt(x, y);
        if (c < 0.5) {
          surface.put(
            col,
            row,
            ramp(EDGE, c * 2),
            h + SHADES - 3 + Math.round(gleam * 2),
            0.2 + c * 0.75,
          );
          continue;
        }
        const v = clamp(shade[i]! + gleam * 0.75, 0, 1);
        surface.fill(col, row, h + Math.round(v * (SHADES - 1)), 1);
        // Faces turned from the light carry engraving; lit faces stay clean.
        const dark = 1 - v;
        if (dark > 0.5 && gleam < 0.4)
          surface.put(col, row, ramp(ENGRAVE, (dark - 0.5) / 0.4), DEEP, 0.25 + dark * 0.4);
      }

      // Loose cells, wherever they have got to, as flecks of their colour.
      for (const i of moving) {
        const dxc = ox[i]!;
        const dyc = oy[i]!;
        if (Math.abs(dxc) <= 0.5 && Math.abs(dyc) <= aspect * 0.5) continue;
        const col = i % cols;
        const row = (i - col) / cols;
        const c2 = Math.floor(col + 0.5 + dxc);
        const r2 = Math.floor((row + 0.5) * 1 + dyc / aspect);
        const speed = Math.hypot(vx[i]!, vy[i]!);
        const h = hue[i]! * SHADES;
        if (!loose[i] && speed < 10 && cover[i]! >= 0.5) {
          // Settling home: a block again, ready to slot back in.
          surface.fill(c2, r2, h + Math.round(shade[i]! * (SHADES - 1)), 1);
          continue;
        }
        surface.put(c2, r2, speed > 24 ? '*' : speed > 8 ? '+' : ':', h + 5, 0.95);
      }

      if (snowfall > 0) drawSnow(surface);
      if (fires.length) drawFires(surface);

      // The shockwave's ring, faint in the empty space around the word.
      for (const ring of rings) {
        const r = ring.age * RING_SPEED;
        const fade = 1 - ring.age / 2.2;
        if (fade <= 0) continue;
        const steps = Math.ceil(r * 2 * Math.PI);
        for (let k = 0; k < steps; k++) {
          const a = (k / steps) * Math.PI * 2;
          const col = Math.floor(ring.x + Math.cos(a) * r);
          const row = Math.floor((ring.y + Math.sin(a) * r) / aspect);
          if (surface.filled(col, row)) continue;
          surface.put(col, row, '.', INK, fade * 0.45);
        }
      }
    },
  };
}
components/lilt/ascii/engine/stage.tsascii-canvas

stage.ts

import { GlyphSurface, LEVELS } from './surface';
import type { AsciiPointer, AsciiScene } from './types';

const STEP = 1 / 60;
const MAX_STEPS = 8;
const FALLBACK_FONT = 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace';

export interface AsciiStageOptions {
  /** Font size of each cell in CSS pixels. Smaller cells give finer pictures. Default 14. */
  cellSize?: number;
  /** Follow the pointer and answer clicks. Default true. */
  interactive?: boolean;
  /** How fast the scene's clock runs: 0.5 is half speed, 2 is double. Default 1. */
  speed?: number;
}

/**
 * Runs a scene on a canvas: a fixed-step clock, resizing, pointer input, pausing while off screen
 * or in a hidden tab, a single still frame for reduced motion, and repainting when the font or the
 * page theme changes. The canvas's CSS `font-family` and `color` set the type and the ink.
 */
export class AsciiStage {
  private ctx: CanvasRenderingContext2D;
  private surface = new GlyphSurface();
  private styles: string[] = [];
  private pointer: AsciiPointer = { x: 0, y: 0, active: false };
  private cellSize: number;
  private interactive: boolean;
  private speed: number;
  private font = '';
  private cw = 8;
  /** Whether every glyph advances one cell, so rows can be painted as strings. */
  private mono = true;
  private ch = 18;
  private raf = 0;
  private last = 0;
  private acc = 0;
  private time = 0;
  private onScreen = true;
  private disposed = false;
  private reducedMotion: MediaQueryList;
  private resizeObserver: ResizeObserver;
  /** The grid the scene was last sized to. */
  private grid = '';
  private intersectionObserver: IntersectionObserver;
  private themeObserver: MutationObserver;

  constructor(
    private canvas: HTMLCanvasElement,
    private scene: AsciiScene,
    options: AsciiStageOptions = {},
  ) {
    const ctx = canvas.getContext('2d');
    if (!ctx) throw new Error('AsciiStage needs a 2D canvas context.');
    this.ctx = ctx;
    this.cellSize = options.cellSize ?? 14;
    this.interactive = options.interactive ?? true;
    this.speed = options.speed ?? 1;
    this.reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');

    this.resizeObserver = new ResizeObserver(() => this.resize());
    this.resizeObserver.observe(canvas);
    this.intersectionObserver = new IntersectionObserver(([entry]) => {
      this.onScreen = entry?.isIntersecting ?? true;
      this.schedule();
    });
    this.intersectionObserver.observe(canvas);
    // Theme switches usually flip a class or attribute on the root; the ink follows.
    this.themeObserver = new MutationObserver(() => this.restyle());
    this.themeObserver.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ['class', 'style', 'data-theme'],
    });

    this.reducedMotion.addEventListener('change', this.schedule);
    document.addEventListener('visibilitychange', this.schedule);
    window.addEventListener('pointermove', this.onPointerMove, { passive: true });
    window.addEventListener('pointerdown', this.onPointerDown, { passive: true });
    document.documentElement.addEventListener('pointerleave', this.onPointerLeave);
    window.addEventListener('blur', this.onPointerLeave);

    this.resize();
    // Canvas text never asks for a webfont, so measure again once the page's fonts arrive.
    document.fonts?.ready.then(() => {
      if (this.disposed) return;
      this.resize();
    });
    this.schedule();
  }

  destroy() {
    this.disposed = true;
    cancelAnimationFrame(this.raf);
    this.resizeObserver.disconnect();
    this.intersectionObserver.disconnect();
    this.themeObserver.disconnect();
    this.reducedMotion.removeEventListener('change', this.schedule);
    document.removeEventListener('visibilitychange', this.schedule);
    window.removeEventListener('pointermove', this.onPointerMove);
    window.removeEventListener('pointerdown', this.onPointerDown);
    document.documentElement.removeEventListener('pointerleave', this.onPointerLeave);
    window.removeEventListener('blur', this.onPointerLeave);
  }

  /** Changes the stage's options in place, keeping the scene's world as it is. */
  configure(options: AsciiStageOptions) {
    this.speed = options.speed ?? this.speed;
    if (options.interactive !== undefined) {
      this.interactive = options.interactive;
      if (!this.interactive) this.pointer.active = false;
    }
    if (options.cellSize !== undefined && options.cellSize !== this.cellSize) {
      this.cellSize = options.cellSize;
      this.resize();
    }
  }

  /** Reads the canvas's `color` again, after the ink was changed by something other than a theme. */
  refresh() {
    this.restyle();
  }

  private get still() {
    return this.reducedMotion.matches;
  }

  private resize() {
    const rect = this.canvas.getBoundingClientRect();
    if (rect.width < 1 || rect.height < 1) return;
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    this.canvas.width = Math.round(rect.width * dpr);
    this.canvas.height = Math.round(rect.height * dpr);

    const family = getComputedStyle(this.canvas).fontFamily || FALLBACK_FONT;
    this.font = `500 ${this.cellSize}px ${family}, ${FALLBACK_FONT}`;
    const { ctx } = this;
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    ctx.font = this.font;
    this.cw = Math.max(4, ctx.measureText('M').width);
    this.mono = Math.abs(ctx.measureText('i').width - this.cw) < 0.01;
    this.ch = Math.round(this.cellSize * (this.scene.lineHeight ?? 1.25));

    const cols = Math.ceil(rect.width / this.cw);
    const rows = Math.ceil(rect.height / this.ch);
    this.surface.resize(cols, rows);
    // Fonts arriving or a pixel of layout can measure the same grid again; the scene keeps its world.
    const grid = `${cols}x${rows}x${this.ch / this.cw}`;
    if (grid !== this.grid) {
      this.grid = grid;
      this.scene.resize({ cols, rows, aspect: this.ch / this.cw });
    }
    this.restyle();
  }

  /** Resolves the palette to fill styles, one per colour and opacity step. */
  private restyle() {
    const { ctx } = this;
    const ink = getComputedStyle(this.canvas).color;
    this.styles = this.scene.palette.flatMap((colour) => {
      ctx.fillStyle = '#000';
      ctx.fillStyle = colour === 'ink' ? ink : colour;
      const [r, g, b] = parseColour(String(ctx.fillStyle));
      return Array.from({ length: LEVELS }, (_, i) => `rgba(${r},${g},${b},${(i + 1) / LEVELS})`);
    });
    if (this.still) this.drawStill();
  }

  private schedule = () => {
    cancelAnimationFrame(this.raf);
    if (this.disposed) return;
    if (this.still) {
      this.drawStill();
      return;
    }
    if (!this.onScreen || document.hidden) return;
    this.last = performance.now();
    this.raf = requestAnimationFrame(this.frame);
  };

  private frame = (now: number) => {
    const dt = Math.min(0.1, (now - this.last) / 1000) * this.speed;
    this.last = now;
    this.acc += dt;
    let steps = 0;
    while (this.acc >= STEP && steps < MAX_STEPS) {
      this.scene.step(STEP, this.pointer);
      this.time += STEP;
      this.acc -= STEP;
      steps++;
    }
    if (steps === MAX_STEPS) this.acc = 0;
    this.paint();
    this.raf = requestAnimationFrame(this.frame);
  };

  /** Lets the scene settle without the pointer, then shows that one frame. */
  private drawStill() {
    const settle = this.scene.settle ?? 3;
    const idle: AsciiPointer = { x: 0, y: 0, active: false };
    while (this.time < settle) {
      this.scene.step(STEP, idle);
      this.time += STEP;
    }
    this.paint();
  }

  private paint() {
    const { ctx, canvas, surface } = this;
    ctx.save();
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.restore();
    ctx.font = this.font;
    ctx.textBaseline = 'middle';
    surface.clear();
    this.scene.draw(surface);
    surface.paint(ctx, this.styles, this.cw, this.ch, this.mono);
  }

  private toCells(e: PointerEvent) {
    const rect = this.canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    const inside = x >= 0 && y >= 0 && x <= rect.width && y <= rect.height;
    return { x: x / this.cw, y: y / this.ch, inside };
  }

  private onPointerMove = (e: PointerEvent) => {
    if (!this.interactive) return;
    const { x, y, inside } = this.toCells(e);
    this.pointer.x = x;
    this.pointer.y = y;
    // A finger has no hover; it only presses.
    this.pointer.active = inside && e.pointerType !== 'touch';
  };

  private onPointerDown = (e: PointerEvent) => {
    const { x, y, inside } = this.toCells(e);
    if (!inside || this.still || !this.interactive) return;
    this.scene.press?.(x, y);
  };

  private onPointerLeave = () => {
    this.pointer.active = false;
  };
}

/** Reads the `#rrggbb` or `rgba(r, g, b, a)` a canvas reports back for any CSS colour. */
function parseColour(value: string): [number, number, number] {
  if (value.startsWith('#')) {
    const n = parseInt(value.slice(1, 7), 16);
    return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
  }
  const parts = value.match(/[\d.]+/g)?.map(Number) ?? [];
  return [parts[0] ?? 0, parts[1] ?? 0, parts[2] ?? 0];
}
components/lilt/ascii/react/ascii-canvas.tsxascii-canvas

ascii-canvas.tsx

'use client';

import { useEffect, useRef, type CSSProperties } from 'react';
import { AsciiStage } from '../engine/stage';
import type { AsciiScene } from '../engine/types';

export interface AsciiCanvasProps {
  /** Builds the scene. Called again only when `sceneKey` changes. */
  scene: () => AsciiScene;
  /** Changes when the scene should be rebuilt, such as a JSON string of its options. */
  sceneKey?: string;
  /** Font size of each cell in CSS pixels. Default 14. */
  cellSize?: number;
  /** Follow the pointer and answer clicks. Default true. */
  interactive?: boolean;
  /** How fast the scene's clock runs: 0.5 is half speed, 2 is double. Default 1. */
  speed?: number;
  /**
   * Describes the picture for screen readers. Without one the canvas is decorative and hidden
   * from assistive technology, which suits a background.
   */
  label?: string;
  className?: string;
  style?: CSSProperties;
}

/**
 * A canvas that runs an ASCII scene. It fills its parent; give the parent a size. Set the type
 * with CSS `font-family` (a monospace face) and the ink with `color`.
 */
export function AsciiCanvas({
  scene,
  sceneKey,
  cellSize,
  interactive,
  speed,
  label,
  className,
  style,
}: AsciiCanvasProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const stageRef = useRef<AsciiStage | null>(null);
  const latest = useRef({ scene, cellSize, interactive, speed });
  latest.current = { scene, cellSize, interactive, speed };

  // A new scene starts a new world; everything else is tuned on the running stage.
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const { scene: build, ...options } = latest.current;
    const stage = new AsciiStage(canvas, build(), options);
    stageRef.current = stage;
    return () => {
      stage.destroy();
      stageRef.current = null;
    };
  }, [sceneKey]);

  useEffect(() => {
    stageRef.current?.configure({ cellSize, interactive, speed });
  }, [cellSize, interactive, speed]);

  const ink = style?.color;
  useEffect(() => {
    stageRef.current?.refresh();
  }, [ink]);

  return (
    <canvas
      ref={canvasRef}
      className={className ? `lilt-ascii ${className}` : 'lilt-ascii'}
      style={{ display: 'block', width: '100%', height: '100%', ...style }}
      {...(label ? { role: 'img', 'aria-label': label } : { 'aria-hidden': true })}
    />
  );
}

export type SceneProps<Options> = Options & Omit<AsciiCanvasProps, 'scene' | 'sceneKey'>;

/** Splits a scene's own options from the canvas props. */
export function useSceneProps<Options extends object>(
  props: SceneProps<Options>,
  create: (options: Options) => AsciiScene,
): AsciiCanvasProps {
  const { cellSize, interactive, speed, label, className, style, ...options } = props;
  return {
    scene: () => create(options as Options),
    sceneKey: JSON.stringify(options),
    cellSize,
    interactive,
    speed,
    label,
    className,
    style,
  };
}
components/lilt/ascii/engine/noise.tsascii-engine

noise.ts

/** A stable pseudo-random number in [0, 1) for an integer lattice point. */
export function hash3(x: number, y: number, z: number): number {
  let h =
    Math.imul(x | 0, 0x27d4eb2d) ^ Math.imul(y | 0, 0x165667b1) ^ Math.imul(z | 0, 0x9e3779b1);
  h = Math.imul(h ^ (h >>> 15), 0x85ebca6b);
  h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35);
  return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
}

const fade = (t: number) => t * t * (3 - 2 * t);
const mix = (a: number, b: number, t: number) => a + (b - a) * t;

/** Smooth value noise in [0, 1). */
export function noise3(x: number, y: number, z: number): number {
  const xi = Math.floor(x);
  const yi = Math.floor(y);
  const zi = Math.floor(z);
  const u = fade(x - xi);
  const v = fade(y - yi);
  const w = fade(z - zi);
  const a = mix(hash3(xi, yi, zi), hash3(xi + 1, yi, zi), u);
  const b = mix(hash3(xi, yi + 1, zi), hash3(xi + 1, yi + 1, zi), u);
  const c = mix(hash3(xi, yi, zi + 1), hash3(xi + 1, yi, zi + 1), u);
  const d = mix(hash3(xi, yi + 1, zi + 1), hash3(xi + 1, yi + 1, zi + 1), u);
  return mix(mix(a, b, v), mix(c, d, v), w);
}

/** Layered noise in [0, 1): each octave doubles the detail and halves the weight. */
export function fbm3(x: number, y: number, z: number, octaves = 4): number {
  let sum = 0;
  let weight = 0.5;
  let total = 0;
  for (let i = 0; i < octaves; i++) {
    sum += noise3(x, y, z) * weight;
    total += weight;
    weight *= 0.5;
    x *= 2.03;
    y *= 2.03;
    z *= 2.03;
  }
  return sum / total;
}

export const clamp = (value: number, min: number, max: number) =>
  value < min ? min : value > max ? max : value;

export const smoothstep = (edge0: number, edge1: number, x: number) => {
  const t = clamp((x - edge0) / (edge1 - edge0), 0, 1);
  return t * t * (3 - 2 * t);
};

/** Frame-rate independent easing toward a target: `rate` is the share closed per second. */
export const approach = (current: number, target: number, rate: number, dt: number) =>
  target + (current - target) * Math.exp(-rate * dt);
components/lilt/ascii/engine/glyphs.tsascii-engine

glyphs.ts

import { clamp } from './noise';

/** The glyph a share of the way along a ramp of glyphs, sparse to dense. */
export function ramp(glyphs: string, value: number): string {
  return glyphs[clamp(Math.floor(value * glyphs.length), 0, glyphs.length - 1)]!;
}

/**
 * The stroke that best follows a direction on screen. `dx` and `dy` are in square units (cell
 * widths), y down. Used for tentacles, grass and anything else drawn as a line of type.
 */
export function stroke(dx: number, dy: number): string {
  const angle = Math.atan2(dy, dx);
  // Fold to [0, π): a stroke has no direction.
  const a = angle < 0 ? angle + Math.PI : angle;
  if (a < Math.PI / 8 || a >= (Math.PI * 7) / 8) return '-';
  if (a < (Math.PI * 3) / 8) return '\\';
  if (a < (Math.PI * 5) / 8) return '|';
  return '/';
}
components/lilt/ascii/engine/surface.tsascii-engine

surface.ts

/** Opacity steps per colour. Cells sharing a colour and step are painted with one fill style. */
export const LEVELS = 8;

/** A glyph code for a small solid square: crisper than a full stop at every font size. */
export const DOT = 1;

/**
 * One frame of type: a glyph, colour and opacity per cell, and optionally a solid block behind it.
 * Scenes write into it; the stage paints it in batches, one fill style per colour and opacity, so a
 * full screen costs a few dozen style changes rather than thousands.
 */
export class GlyphSurface {
  cols = 0;
  rows = 0;
  glyph = new Uint16Array(0);
  tone = new Uint8Array(0);
  level = new Uint8Array(0);
  /** The block behind each cell: its colour, and its opacity step, 0 for none. */
  blockTone = new Uint8Array(0);
  blockLevel = new Uint8Array(0);
  private order = new Int32Array(0);
  private counts = new Int32Array(0);
  private starts = new Int32Array(0);

  resize(cols: number, rows: number) {
    this.cols = cols;
    this.rows = rows;
    const size = cols * rows;
    this.glyph = new Uint16Array(size);
    this.tone = new Uint8Array(size);
    this.level = new Uint8Array(size);
    this.blockTone = new Uint8Array(size);
    this.blockLevel = new Uint8Array(size);
    this.order = new Int32Array(size);
  }

  clear() {
    this.glyph.fill(0);
    this.blockLevel.fill(0);
  }

  /**
   * Writes a glyph; later writes replace earlier ones, so draw back to front. `glyph` is a
   * character, a char code, or `DOT`. Opacity at or below zero leaves the cell untouched.
   */
  put(col: number, row: number, glyph: string | number, tone: number, opacity = 1) {
    col = Math.floor(col);
    row = Math.floor(row);
    if (col < 0 || row < 0 || col >= this.cols || row >= this.rows || opacity <= 0) return;
    const i = row * this.cols + col;
    this.glyph[i] = typeof glyph === 'number' ? glyph : glyph.charCodeAt(0);
    this.tone[i] = tone;
    this.level[i] = Math.min(LEVELS, Math.ceil(opacity * LEVELS));
  }

  /**
   * Fills a cell with a solid block of colour, painted behind its glyph. Solid shapes read as one
   * mass this way, with a glyph cut into each block, the way a mosaic does. Opacity at or below
   * zero removes the block.
   */
  fill(col: number, row: number, tone: number, opacity = 1) {
    col = Math.floor(col);
    row = Math.floor(row);
    if (col < 0 || row < 0 || col >= this.cols || row >= this.rows) return;
    const i = row * this.cols + col;
    this.blockTone[i] = tone;
    this.blockLevel[i] = opacity <= 0 ? 0 : Math.min(LEVELS, Math.ceil(opacity * LEVELS));
  }

  /** True when a cell already holds a glyph or a block this frame. */
  filled(col: number, row: number) {
    col = Math.floor(col);
    row = Math.floor(row);
    if (col < 0 || row < 0 || col >= this.cols || row >= this.rows) return false;
    const i = row * this.cols + col;
    return this.glyph[i] !== 0 || this.blockLevel[i] !== 0;
  }

  /**
   * Sorts cells into buckets of one fill style each, by counting: `bucketOf` gives a cell's bucket,
   * or -1 to skip it. Leaves the cells in `order` and returns how many fall in each bucket.
   */
  private sort(buckets: number, bucketOf: (i: number) => number) {
    if (this.counts.length !== buckets) {
      this.counts = new Int32Array(buckets);
      this.starts = new Int32Array(buckets);
    }
    const { order, counts, starts } = this;
    counts.fill(0);
    const n = this.glyph.length;
    for (let i = 0; i < n; i++) {
      const b = bucketOf(i);
      if (b >= 0 && b < buckets) counts[b]++;
    }
    let sum = 0;
    for (let b = 0; b < buckets; b++) {
      starts[b] = sum;
      sum += counts[b]!;
    }
    for (let i = 0; i < n; i++) {
      const b = bucketOf(i);
      if (b >= 0 && b < buckets) order[starts[b]!++] = i;
    }
    return counts;
  }

  /**
   * Paints the frame. `styles[tone * LEVELS + level - 1]` is the fill style for each bucket.
   * With a monospace font, each bucket's glyphs on a row go out as one string with spaces in the
   * gaps: a canvas pays per text call far more than per glyph, so this is many times faster.
   */
  paint(
    ctx: CanvasRenderingContext2D,
    styles: readonly string[],
    cw: number,
    ch: number,
    mono = true,
  ) {
    const buckets = styles.length;
    const { glyph, tone, level, blockTone, blockLevel, order, cols } = this;

    // Blocks first, each inset a pixel so the grid of type still shows between them.
    let counts = this.sort(buckets, (i) =>
      blockLevel[i] ? blockTone[i]! * LEVELS + blockLevel[i]! - 1 : -1,
    );
    let k = 0;
    for (let b = 0; b < buckets; b++) {
      const count = counts[b]!;
      if (!count) continue;
      ctx.fillStyle = styles[b]!;
      for (const end = k + count; k < end; k++) {
        const i = order[k]!;
        const col = i % cols;
        const row = (i - col) / cols;
        ctx.fillRect(col * cw + 0.5, row * ch + 0.5, cw - 1, ch - 1);
      }
    }

    counts = this.sort(buckets, (i) => (glyph[i] ? tone[i]! * LEVELS + level[i]! - 1 : -1));
    const dot = Math.max(1.5, Math.round(cw * 0.22));
    ctx.textAlign = mono ? 'left' : 'center';
    k = 0;
    for (let b = 0; b < buckets; b++) {
      const count = counts[b];
      if (!count) continue;
      ctx.fillStyle = styles[b]!;
      // A run of text on one row: where it starts, and its characters so far.
      let runRow = -1;
      let runCol = 0;
      let lastCol = 0;
      let run = '';
      for (const end = k + count; k < end; k++) {
        const i = order[k]!;
        const col = i % cols;
        const row = (i - col) / cols;
        const code = glyph[i]!;
        if (code === DOT) {
          ctx.fillRect(col * cw + cw / 2 - dot / 2, row * ch + ch / 2 - dot / 2, dot, dot);
          continue;
        }
        if (!mono) {
          ctx.fillText(String.fromCharCode(code), col * cw + cw / 2, row * ch + ch / 2);
          continue;
        }
        if (row !== runRow) {
          if (run) ctx.fillText(run, runCol * cw, runRow * ch + ch / 2);
          runRow = row;
          runCol = col;
          run = '';
        } else {
          run += ' '.repeat(col - lastCol - 1);
        }
        run += String.fromCharCode(code);
        lastCol = col;
      }
      if (run) ctx.fillText(run, runCol * cw, runRow * ch + ch / 2);
    }
  }
}
components/lilt/ascii/engine/types.tsascii-engine

types.ts

import type { GlyphSurface } from './surface';

/** The character grid a scene draws into. Positions are in cells; `aspect` is cell height over width. */
export interface AsciiGrid {
  cols: number;
  rows: number;
  aspect: number;
}

export interface AsciiPointer {
  /** Column under the pointer, fractional. */
  x: number;
  /** Row under the pointer, fractional. */
  y: number;
  /** False when the pointer is outside the canvas or is a finger that lifted. */
  active: boolean;
}

/**
 * A living picture made of type. The stage owns the canvas, the clock and input; a scene owns its
 * world. `step` runs on a fixed 60 Hz clock and `draw` writes the current frame into the surface.
 */
export interface AsciiScene {
  /**
   * The scene's colours, addressed by index from `draw`. Any CSS colour works; `ink` is the
   * canvas's own text colour, so a scene can follow the page's light or dark theme.
   */
  readonly palette: readonly string[];
  resize(grid: AsciiGrid): void;
  step(dt: number, pointer: AsciiPointer): void;
  draw(surface: GlyphSurface): void;
  /** A click or tap at a cell. */
  press?(x: number, y: number): void;
  /**
   * Height of a row as a multiple of the font size. Default 1.25. Scenes made of solid shapes ask
   * for tighter rows, closer to square cells, so a body lying sideways still spans several rows.
   */
  readonly lineHeight?: number;
  /** Seconds to run before showing a single still frame when the reader prefers reduced motion. */
  readonly settle?: number;
}
components/lilt/ascii/text/bitmap-font.tsascii-bitmap-font

bitmap-font.ts

/**
 * A bold 5 by 7 capital font, for lettering where the browser's type is out of reach (a server,
 * a test). Each glyph is seven rows of five bits, top to bottom.
 */
const FONT: Record<string, readonly string[]> = {
  A: ['01110', '10001', '10001', '11111', '10001', '10001', '10001'],
  B: ['11110', '10001', '10001', '11110', '10001', '10001', '11110'],
  C: ['01111', '10000', '10000', '10000', '10000', '10000', '01111'],
  D: ['11110', '10001', '10001', '10001', '10001', '10001', '11110'],
  E: ['11111', '10000', '10000', '11110', '10000', '10000', '11111'],
  F: ['11111', '10000', '10000', '11110', '10000', '10000', '10000'],
  G: ['01111', '10000', '10000', '10011', '10001', '10001', '01111'],
  H: ['10001', '10001', '10001', '11111', '10001', '10001', '10001'],
  I: ['11111', '00100', '00100', '00100', '00100', '00100', '11111'],
  J: ['00111', '00010', '00010', '00010', '00010', '10010', '01100'],
  K: ['10001', '10010', '10100', '11000', '10100', '10010', '10001'],
  L: ['10000', '10000', '10000', '10000', '10000', '10000', '11111'],
  M: ['10001', '11011', '10101', '10101', '10001', '10001', '10001'],
  N: ['10001', '11001', '10101', '10011', '10001', '10001', '10001'],
  O: ['01110', '10001', '10001', '10001', '10001', '10001', '01110'],
  P: ['11110', '10001', '10001', '11110', '10000', '10000', '10000'],
  Q: ['01110', '10001', '10001', '10001', '10101', '10010', '01101'],
  R: ['11110', '10001', '10001', '11110', '10100', '10010', '10001'],
  S: ['01111', '10000', '10000', '01110', '00001', '00001', '11110'],
  T: ['11111', '00100', '00100', '00100', '00100', '00100', '00100'],
  U: ['10001', '10001', '10001', '10001', '10001', '10001', '01110'],
  V: ['10001', '10001', '10001', '10001', '10001', '01010', '00100'],
  W: ['10001', '10001', '10001', '10101', '10101', '11011', '10001'],
  X: ['10001', '10001', '01010', '00100', '01010', '10001', '10001'],
  Y: ['10001', '10001', '01010', '00100', '00100', '00100', '00100'],
  Z: ['11111', '00001', '00010', '00100', '01000', '10000', '11111'],
  '0': ['01110', '10011', '10101', '10101', '10101', '11001', '01110'],
  '1': ['00100', '01100', '00100', '00100', '00100', '00100', '01110'],
  '2': ['01110', '10001', '00001', '00010', '00100', '01000', '11111'],
  '3': ['11110', '00001', '00001', '01110', '00001', '00001', '11110'],
  '4': ['00010', '00110', '01010', '10010', '11111', '00010', '00010'],
  '5': ['11111', '10000', '11110', '00001', '00001', '10001', '01110'],
  '6': ['01110', '10000', '10000', '11110', '10001', '10001', '01110'],
  '7': ['11111', '00001', '00010', '00100', '01000', '01000', '01000'],
  '8': ['01110', '10001', '10001', '01110', '10001', '10001', '01110'],
  '9': ['01110', '10001', '10001', '01111', '00001', '00001', '01110'],
  '!': ['00100', '00100', '00100', '00100', '00100', '00000', '00100'],
  '?': ['01110', '10001', '00001', '00010', '00100', '00000', '00100'],
  '.': ['00000', '00000', '00000', '00000', '00000', '00000', '00100'],
  '-': ['00000', '00000', '00000', '01110', '00000', '00000', '00000'],
  ' ': ['00000', '00000', '00000', '00000', '00000', '00000', '00000'],
};

/**
 * The text in the bitmap font as a field of ink, `P` samples a square unit across a `width` by
 * `height` area, fitted to the box `fit` gives and centred.
 */
export function bitmapInk(
  text: string,
  width: number,
  height: number,
  P: number,
  fit: (width: number, height: number) => { w: number; h: number },
): Float32Array {
  const glyphs = Array.from(text.toUpperCase()).map((ch) => FONT[ch] ?? FONT['?']!);
  // Five columns a letter and one between.
  const unitsW = glyphs.length * 6 - 1;
  const unitsH = 7;
  const box = fit(width, height);
  const unit = Math.min(box.w / unitsW, box.h / unitsH);
  const left = (width - unitsW * unit) / 2;
  const top = (height - unitsH * unit) / 2;
  const w = Math.ceil(width * P);
  const h = Math.ceil(height * P);
  const ink = new Float32Array(w * h);
  for (let py = 0; py < h; py++) {
    const v = Math.floor(((py + 0.5) / P - top) / unit);
    if (v < 0 || v >= unitsH) continue;
    for (let px = 0; px < w; px++) {
      const u = Math.floor(((px + 0.5) / P - left) / unit);
      if (u < 0 || u >= unitsW || u % 6 === 5) continue;
      if (glyphs[Math.floor(u / 6)]![v]![u % 6] === '1') ink[py * w + px] = 1;
    }
  }
  return ink;
}

Usage

How it behaves.

The scene fills its parent, so give the parent a size. The canvas takes its type from CSS font-family and its ink from color. It pauses off screen and in hidden tabs, and shows one still frame when the reader prefers reduced motion.

Props12

Every option.

Pass these directly to AsciiLogo.

PropTypeDefaultWhat it does
firesnumber[][]Campfires on the ground, each a share of the width, such as [0.2, 0.8]. Snow hisses into steam in them and a click stokes one. With fires the pointer has a temperature: it frosts over out in the snow, thaws and glows by a fire, and a small readout says how it is doing.
snowColorstring'#e6ecfb'Colour of the snow.
fontstringthe system's sans serifCSS font family for the lettering. A web font must have loaded before the canvas draws.
textstring'lilt'The word. It is fitted to the canvas with room to spare, so keep it short.
colorsstring[]['#7c5cff', '#e5489c']Gradient stops as hex colours, left to right.
weightnumber800Font weight of the lettering. Heavy weights make the fullest slabs.
snownumber0How hard it snows. Snow settles in caps on the letters, melts where the pointer rests, and falls off any letter knocked loose.
clearBelownumber0Share of the height kept clear under the word, for a headline or buttons laid over it.
cellSizenumber14Font size of each cell in pixels. Smaller cells draw a finer picture.
speednumber1How fast the clock runs: 0.5 is half speed, 2 is double.
interactivebooleantrueFollow the pointer and answer clicks.
labelstring—Describes the canvas for screen readers; usually the word itself. Without one it is decorative.
Next sceneFlag

Ready when your data is. Start with one install.

Install a package, import the stylesheet once, and drop in a card or a scene.

Read the guideRead the guideView on GitHubView on GitHub
ChartsAll chartsAll chartsFinanceFinanceCustomizeCustomizeFeaturesFeatures
ComponentsAll componentsAll componentsAIAIStatusStatusActionsActionsDataData
VisualsAll visualsAll visualsAIAIDataDataSecuritySecurityProductProduct
ASCIIAll scenesAll scenesTextTextInterfaceInterfaceBackgroundsBackgroundsMediaMediaDataData
DocsGetting startedGetting startedAPI referenceAPI referenceMotion & accessibilityMotion & accessibilityllms.txtllms.txt
React components with a little lilt.GitHubGitHubnpmnpm