Skip to content
Charts55Components12Visuals14ASCII45
GitHubGet startedGet started
All ASCIIImageMedia
PreviousNext: Video

Move to stir the picture into code. Click to send a ring through it.

Image

Media

Any image drawn in type, each cell taking the colour of the pixels beneath it.

Customize 9

1.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 { AsciiImage } from '@/components/lilt/ascii/media/ascii-image';

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

Installation16

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/image.json
components/lilt/ascii/media/ascii-image.tsx

ascii-image.tsx

'use client';

import { useEffect, useMemo, useRef, useState } from 'react';
import type { AsciiScene } from '../engine/types';
import { AsciiCanvas, type SceneProps } from '../react/ascii-canvas';
import type { Rgb } from './colour';
import { canvasFeed, type MediaFeed } from './feed';
import { createMediaScene, type Backdrop, type MediaColor, type MediaMode } from './media-scene';
import { pictureFeed } from './picture';
import { pictureColours } from './picture-colours';
import type { MediaFit } from './sample';
import { useBackdrop } from './use-backdrop';

export interface ImageOptions {
  /**
   * The image's URL. It must be on the same origin or served with CORS, since its pixels are read.
   * Without one, a picture of three lit spheres is drawn.
   */
  src?: string;
  /** `glyphs` draws a density ramp of type; `blocks` draws solid lit blocks with a glyph cut in. Default `glyphs`. */
  mode?: MediaMode;
  /** `source` takes each cell's colour from the image; `mono` draws in one ink. Default `source`. */
  color?: MediaColor;
  /** The ink for `mono`, as a CSS colour. Default the text colour. */
  tint?: string;
  /** `contain` shows the whole image with room around it; `cover` fills the frame. Default `contain`. */
  fit?: MediaFit;
  /** Swap which end of the tones gets the dense glyphs, for dark pictures on a light ground. Default false. */
  invert?: boolean;
  /** Above 1 pushes tones apart, below 1 pulls them together. Default 1. */
  contrast?: number;
  /** Characters the pointer stirs the picture into. */
  scramble?: string;
}

export type AsciiImageProps = SceneProps<ImageOptions>;

/** Options for building an image scene by hand, from any feed. */
export interface ImageSceneOptions extends Omit<ImageOptions, 'src'> {
  /** Where the pixels come from. Default the picture of three spheres. */
  feed?: MediaFeed;
  /** Colours for `source`; read from the feed when not given. */
  palette?: { dark: readonly Rgb[]; light: readonly Rgb[] };
  /** The backdrop, read every frame. Default dark. */
  backdrop?: Backdrop;
}

let defaultPalette: { dark: Rgb[]; light: Rgb[] } | null = null;

/**
 * An image drawn in type, as a scene. Without a feed it draws the default picture of three lit
 * spheres; use `canvasFeed` to draw an image you've loaded yourself.
 */
export function createImage(options: ImageSceneOptions = {}): AsciiScene {
  const feed = options.feed ?? pictureFeed();
  let palette = options.palette;
  if (!palette && options.color !== 'mono') {
    if (!options.feed) palette = defaultPalette ??= pictureColours(feed)!;
    else palette = pictureColours(feed) ?? undefined;
  }
  return createMediaScene({ ...options, feed, palette, live: false });
}

type Loaded =
  | { src: string; status: 'loading' }
  | { src: string; status: 'ready'; feed: MediaFeed; palette: { dark: Rgb[]; light: Rgb[] } }
  | { src: string; status: 'error'; message: string };

/**
 * Any image, drawn in type. Each cell averages the pixels beneath it and takes their colour; the
 * picture scrambles in as it appears, the pointer stirs it into code, and a click sends a ring of
 * code through it. On a light backdrop it draws as ink on paper. Without a `src` it draws three
 * lit spheres.
 */
export function AsciiImage(props: AsciiImageProps) {
  const {
    cellSize,
    interactive,
    speed,
    label,
    className,
    style,
    src,
    mode,
    color,
    tint,
    fit,
    invert,
    contrast,
    scramble,
  } = props;
  const box = useRef<HTMLDivElement>(null);
  const backdrop = useBackdrop(box, typeof style?.color === 'string' ? style.color : undefined);
  const [loaded, setLoaded] = useState<Loaded | null>(null);
  const url = src?.trim() || '';

  useEffect(() => {
    if (!url) return;
    let cancelled = false;
    const image = new Image();
    image.crossOrigin = 'anonymous';
    image.decoding = 'async';
    image.onload = () => {
      if (cancelled) return;
      const feed = canvasFeed(
        image,
        () => [image.naturalWidth, image.naturalHeight],
        () => 1,
      );
      const palette = pictureColours(feed);
      setLoaded(
        palette
          ? { src: url, status: 'ready', feed, palette }
          : {
              src: url,
              status: 'error',
              message: "This image can't be read. Serve it from the same origin, or with CORS.",
            },
      );
    };
    image.onerror = () => {
      if (!cancelled) setLoaded({ src: url, status: 'error', message: "This image didn't load." });
    };
    setLoaded({ src: url, status: 'loading' });
    image.src = url;
    return () => {
      cancelled = true;
      image.onload = null;
      image.onerror = null;
    };
  }, [url]);

  const current = url && loaded?.src === url ? loaded : null;
  const status = url ? (current?.status ?? 'loading') : 'ready';
  const options = { mode, color, tint, fit, invert, contrast, scramble };
  const sceneKey = JSON.stringify({ ...options, url, status });

  const scene = useMemo(
    () => () => {
      const shared = { ...options, backdrop };
      if (!url) return createImage(shared);
      if (current?.status === 'ready')
        return createImage({ ...shared, feed: current.feed, palette: current.palette });
      return createMediaScene({
        ...shared,
        feed: null,
        message: current?.status === 'error' ? current.message : undefined,
      });
    },
    // The key holds every option the scene is built from.
    [sceneKey, current],
  );

  return (
    <div
      ref={box}
      className={className}
      style={{ position: 'relative', width: '100%', height: '100%', color: style?.color }}
    >
      <AsciiCanvas
        scene={scene}
        sceneKey={sceneKey}
        cellSize={cellSize}
        interactive={interactive}
        speed={speed}
        label={label}
        style={style}
      />
    </div>
  );
}
components/lilt/ascii/media/picture-colours.ts

picture-colours.ts

import type { Rgb } from './colour';
import type { MediaFeed } from './feed';
import { chromaOnDark, chromaOnLight, kMeans } from './palette';

/** Colours a picture is cut down to. The stage builds eight fill styles for each. */
export const PICTURE_COLOURS = 24;

/**
 * The colours that best stand for a picture, for a dark backdrop and for a light one, from a
 * small copy of it. Each pixel counts by how much ink it puts down, so a few bright details aren't
 * outvoted by a large dim background. Null when the picture can't be read.
 */
export function pictureColours(
  feed: MediaFeed,
  k = PICTURE_COLOURS,
): { dark: Rgb[]; light: Rgb[] } | null {
  const { width, height } = feed;
  if (width < 1 || height < 1) return null;
  const scale = 72 / Math.max(width, height);
  const w = Math.max(1, Math.round(width * scale));
  const h = Math.max(1, Math.round(height * scale));
  const data = feed.read(0, 0, width, height, w, h);
  if (!data) return null;
  const n = w * h;
  const darkPoints = new Float32Array(n * 3);
  const lightPoints = new Float32Array(n * 3);
  const darkWeights = new Float32Array(n);
  const lightWeights = new Float32Array(n);
  const c: Rgb = [0, 0, 0];
  for (let i = 0; i < n; i++) {
    const a = data[i * 4 + 3]! / 255;
    const r = data[i * 4]! / 255;
    const g = data[i * 4 + 1]! / 255;
    const b = data[i * 4 + 2]! / 255;
    darkWeights[i] = chromaOnDark(r, g, b, c) * a + 1e-4;
    darkPoints.set(c, i * 3);
    lightWeights[i] = chromaOnLight(r, g, b, c) * a + 1e-4;
    lightPoints.set(c, i * 3);
  }
  return {
    dark: kMeans(darkPoints, darkWeights, k),
    light: kMeans(lightPoints, lightWeights, k),
  };
}
components/lilt/ascii/media/picture.ts

picture.ts

import type { Rgb } from './colour';
import { functionFeed, type MediaFeed } from './feed';

/*
 * The picture an image shows when it's given none: three glossy spheres in the brand's violet and
 * rose, lit from the upper left, on nothing. It's drawn from a formula rather than shipped as a
 * file, so it is sharp at any size and the background is truly transparent.
 */

export const PICTURE_WIDTH = 640;
export const PICTURE_HEIGHT = 420;

interface Ball {
  x: number;
  y: number;
  /** Height toward the viewer. */
  z: number;
  r: number;
  /** Colour toward the light, and toward the shadow. */
  lit: Rgb;
  shade: Rgb;
  gloss: number;
}

const BALLS: Ball[] = [
  { x: 270, y: 215, z: 0, r: 158, lit: [0.62, 0.5, 1], shade: [0.42, 0.2, 0.86], gloss: 1 },
  { x: 452, y: 288, z: 120, r: 84, lit: [1, 0.48, 0.72], shade: [0.84, 0.16, 0.5], gloss: 1 },
  { x: 478, y: 104, z: -40, r: 40, lit: [0.84, 0.78, 1], shade: [0.46, 0.38, 0.82], gloss: 0.9 },
];

const norm = (v: number[]) => {
  const l = Math.hypot(...v);
  return v.map((c) => c / l) as Rgb;
};
/** Toward the key light: up, left and in front. Image y runs down. */
const KEY = norm([-0.55, -0.62, 0.56]);
/** A rose rim light from behind on the right. */
const RIM = norm([0.8, 0.2, -0.3]);
const RIM_COLOUR: Rgb = [1, 0.36, 0.66];
/** The half vector between the key and the viewer, for the highlight. */
const HALF = norm([KEY[0], KEY[1], KEY[2] + 1]);

/** Whether a ray from a point toward the key light hits another ball. */
function shadowed(px: number, py: number, pz: number, self: Ball) {
  for (const b of BALLS) {
    if (b === self) continue;
    const ox = px - b.x;
    const oy = py - b.y;
    const oz = pz - b.z;
    const along = ox * KEY[0] + oy * KEY[1] + oz * KEY[2];
    if (along > 0) continue;
    const d2 = ox * ox + oy * oy + oz * oz - along * along;
    if (d2 < b.r * b.r) return 1 - Math.sqrt(d2) / b.r;
  }
  return 0;
}

/** The default picture's colour at a pixel, into `out` as r, g, b, a from 0 to 1. */
export function picturePixel(x: number, y: number, out: Float32Array) {
  let hit: Ball | null = null;
  let top = -Infinity;
  let nz = 0;
  for (const b of BALLS) {
    const dx = (x - b.x) / b.r;
    const dy = (y - b.y) / b.r;
    const d2 = dx * dx + dy * dy;
    if (d2 >= 1) continue;
    const z = Math.sqrt(1 - d2);
    if (b.z + z * b.r > top) {
      top = b.z + z * b.r;
      hit = b;
      nz = z;
    }
  }
  if (!hit) {
    out[0] = out[1] = out[2] = out[3] = 0;
    return;
  }
  const nx = (x - hit.x) / hit.r;
  const ny = (y - hit.y) / hit.r;
  const lambert = Math.max(0, nx * KEY[0] + ny * KEY[1] + nz * KEY[2]);
  const shadow = shadowed(x, y, top, hit);
  const diffuse = lambert * (1 - 0.85 * Math.min(1, shadow * 3));
  const spec = Math.pow(Math.max(0, nx * HALF[0] + ny * HALF[1] + nz * HALF[2]), 48) * hit.gloss;
  const rim =
    Math.pow(Math.max(0, nx * RIM[0] + ny * RIM[1] + nz * RIM[2]), 2) *
    Math.pow(1 - nz, 1.2) *
    0.35;
  // A little light bounced from below, so the shadow side still has form.
  const fill = 0.04 + 0.06 * Math.max(0, ny);
  const t = Math.min(1, diffuse * 1.1);
  for (let c = 0; c < 3; c++) {
    const base = hit.shade[c]! + (hit.lit[c]! - hit.shade[c]!) * t;
    out[c] = Math.min(1, base * (fill + diffuse * 0.95) + spec * 0.9 + rim * RIM_COLOUR[c]!);
  }
  // Anti-aliased rim: the last sliver of the ball fades out.
  out[3] = Math.min(1, nz * 5);
}

/** The default picture as a feed. */
export const pictureFeed = (): MediaFeed =>
  functionFeed(PICTURE_WIDTH, PICTURE_HEIGHT, picturePixel);
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/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/media/colour.tsascii-colour

colour.ts

/** An RGB colour with channels from 0 to 1. */
export type Rgb = [number, number, number];

/** Reads `#rgb`, `#rrggbb` or `rgb(r, g, b)`; anything else gives the fallback. */
export function parseColour(value: string | undefined, fallback: Rgb): Rgb {
  if (!value) return fallback;
  const v = value.trim();
  if (v.startsWith('#')) {
    let h = v.slice(1);
    if (h.length === 3 || h.length === 4) h = [...h.slice(0, 3)].map((c) => c + c).join('');
    if (!/^[0-9a-f]{6}/i.test(h)) return fallback;
    const n = parseInt(h.slice(0, 6), 16);
    return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
  }
  const parts = v
    .match(/^rgba?\(([^)]*)\)$/i)?.[1]
    ?.split(/[\s,/]+/)
    .filter(Boolean);
  if (parts && parts.length >= 3) {
    const rgb = parts
      .slice(0, 3)
      .map((p) => (p.endsWith('%') ? parseFloat(p) / 100 : parseFloat(p) / 255));
    if (rgb.every((c) => Number.isFinite(c)))
      return rgb.map((c) => Math.min(1, Math.max(0, c))) as Rgb;
  }
  return fallback;
}

/** A colour as `#rrggbb`. */
export function toHex([r, g, b]: Rgb): string {
  const c = (v: number) =>
    Math.round(Math.min(1, Math.max(0, v)) * 255)
      .toString(16)
      .padStart(2, '0');
  return `#${c(r)}${c(g)}${c(b)}`;
}

export const mixRgb = (a: Rgb, b: Rgb, t: number): Rgb => [
  a[0] + (b[0] - a[0]) * t,
  a[1] + (b[1] - a[1]) * t,
  a[2] + (b[2] - a[2]) * t,
];

/** Relative luminance of sRGB values, without linearising: close enough to judge light and dark. */
export const luma = (r: number, g: number, b: number) => 0.2126 * r + 0.7152 * g + 0.0722 * b;

/** Whether a CSS colour is light, such as the ink on a dark page. Unknown colours count as light. */
export const isLight = (value: string | undefined) => {
  const [r, g, b] = parseColour(value, [1, 1, 1]);
  return luma(r, g, b) > 0.5;
};
components/lilt/ascii/media/feed.tsascii-media

feed.ts

/**
 * Where a picture's pixels come from: an image, a video, the camera, or a function. The scene asks
 * for a part of the source at the size it needs, and draws whatever comes back.
 */
export interface MediaFeed {
  /** The source's size in pixels, 0 until it has a picture. */
  readonly width: number;
  readonly height: number;
  /** Counts up whenever the source shows a new picture, such as a video's next frame. */
  readonly frame: number;
  /**
   * The part of the source from (`sx`, `sy`), `sw` × `sh` pixels, scaled to `w` × `h`, as RGBA
   * bytes. Null when it can't be read, such as an image from another origin without CORS.
   */
  read(
    sx: number,
    sy: number,
    sw: number,
    sh: number,
    w: number,
    h: number,
  ): Uint8ClampedArray | null;
}

/** A picture from a function of a pixel position, at any size. Each output pixel takes its centre. */
export function functionFeed(
  width: number,
  height: number,
  pixel: (x: number, y: number, out: Float32Array) => void,
): MediaFeed {
  const rgba = new Float32Array(4);
  return {
    width,
    height,
    frame: 1,
    read(sx, sy, sw, sh, w, h) {
      const out = new Uint8ClampedArray(w * h * 4);
      for (let j = 0; j < h; j++) {
        const y = sy + ((j + 0.5) / h) * sh;
        for (let i = 0; i < w; i++) {
          pixel(sx + ((i + 0.5) / w) * sw, y, rgba);
          const p = (j * w + i) * 4;
          out[p] = rgba[0]! * 255;
          out[p + 1] = rgba[1]! * 255;
          out[p + 2] = rgba[2]! * 255;
          out[p + 3] = rgba[3]! * 255;
        }
      }
      return out;
    },
  };
}

/**
 * A feed from anything a canvas can draw: an image, a video or another canvas. It draws into a
 * small canvas of its own at the size asked for and reads the pixels back, once per call.
 */
export function canvasFeed(
  source: CanvasImageSource,
  size: () => [number, number],
  frame: () => number,
  mirror = false,
): MediaFeed {
  let canvas: HTMLCanvasElement | null = null;
  let ctx: CanvasRenderingContext2D | null = null;
  let failed = false;
  return {
    get width() {
      return size()[0];
    },
    get height() {
      return size()[1];
    },
    get frame() {
      return frame();
    },
    read(sx, sy, sw, sh, w, h) {
      if (failed || w < 1 || h < 1) return null;
      if (!canvas) {
        canvas = document.createElement('canvas');
        ctx = canvas.getContext('2d', { willReadFrequently: true });
      }
      if (!ctx) return null;
      if (canvas.width !== w || canvas.height !== h) {
        canvas.width = w;
        canvas.height = h;
      }
      ctx.imageSmoothingEnabled = true;
      ctx.imageSmoothingQuality = 'high';
      ctx.clearRect(0, 0, w, h);
      ctx.save();
      if (mirror) {
        ctx.translate(w, 0);
        ctx.scale(-1, 1);
      }
      try {
        ctx.drawImage(source, sx, sy, sw, sh, 0, 0, w, h);
        return ctx.getImageData(0, 0, w, h).data;
      } catch {
        // A tainted canvas: the source is from another origin and didn't allow reading.
        failed = true;
        return null;
      } finally {
        ctx.restore();
      }
    },
  };
}
components/lilt/ascii/media/palette.tsascii-media

palette.ts

import { hash3 } from '../engine/noise';
import type { Rgb } from './colour';

/*
 * Colour in type. The stage paints with one fill style per palette colour and opacity step, so a
 * picture's colours are cut down to a few dozen. Brightness rides on opacity rather than on the
 * colour: on a dark page a colour scaled to full brightness, laid on at the pixel's brightness,
 * gives the pixel back; on a light page the same holds for darkness. That leaves only hue and
 * saturation to the palette, and a small palette covers them well.
 */

/**
 * A pixel's colour with its brightness taken out, for a dark backdrop: scaled until its brightest
 * channel is full. Its brightness, the opacity to lay it on at, is that channel's value.
 */
export function chromaOnDark(r: number, g: number, b: number, out: Rgb): number {
  const m = Math.max(r, g, b);
  if (m < 1e-3) {
    out[0] = out[1] = out[2] = 1;
    return 0;
  }
  out[0] = r / m;
  out[1] = g / m;
  out[2] = b / m;
  return m;
}

/** The same for a light backdrop: the colour's darkness scaled to full, as ink on paper. */
export function chromaOnLight(r: number, g: number, b: number, out: Rgb): number {
  const m = Math.max(1 - r, 1 - g, 1 - b);
  if (m < 1e-3) {
    out[0] = out[1] = out[2] = 0;
    return 0;
  }
  out[0] = 1 - (1 - r) / m;
  out[1] = 1 - (1 - g) / m;
  out[2] = 1 - (1 - b) / m;
  return m;
}

/** HSV to RGB, all from 0 to 1. */
export function hsv(h: number, s: number, v: number): Rgb {
  const f = (n: number) => {
    const k = (n + h * 6) % 6;
    return v - v * s * Math.max(0, Math.min(k, 4 - k, 1));
  };
  return [f(5), f(3), f(1)];
}

/**
 * A palette for any picture on a dark backdrop: hues round the wheel at a few saturations, plus
 * white. Used for video, whose colours change from frame to frame.
 */
export function wheelPalette(hues = 16, saturations: readonly number[] = [0.22, 0.5, 0.85]): Rgb[] {
  const out: Rgb[] = [[1, 1, 1]];
  for (const s of saturations) {
    for (let h = 0; h < hues; h++) out.push(hsv(h / hues, s, 1));
  }
  return out;
}

/** A dark-backdrop palette turned for a light one: each colour's complement. */
export const forPaper = (palette: readonly Rgb[]): Rgb[] =>
  palette.map(([r, g, b]) => [1 - r, 1 - g, 1 - b]);

/**
 * Picks `k` colours that best stand for a set of weighted colours, by k-means seeded with
 * k-means++. `points` holds r, g, b triples. Deterministic: the seeding draws from a hash.
 */
export function kMeans(points: Float32Array, weights: Float32Array, k: number, rounds = 10): Rgb[] {
  const n = Math.floor(points.length / 3);
  let total = 0;
  for (let i = 0; i < n; i++) total += weights[i]!;
  if (!n || total <= 0) return [[1, 1, 1]];
  const centres: number[] = [];
  const near = new Float32Array(n).fill(Infinity);

  // k-means++: each new centre is drawn in proportion to how far a point is from the nearest one.
  let pick = 0;
  let target = hash3(1, 2, 3) * total;
  for (let i = 0; i < n; i++) {
    target -= weights[i]!;
    if (target <= 0) {
      pick = i;
      break;
    }
  }
  for (let c = 0; c < k; c++) {
    centres.push(points[pick * 3]!, points[pick * 3 + 1]!, points[pick * 3 + 2]!);
    let sum = 0;
    for (let i = 0; i < n; i++) {
      const dr = points[i * 3]! - centres[c * 3]!;
      const dg = points[i * 3 + 1]! - centres[c * 3 + 1]!;
      const db = points[i * 3 + 2]! - centres[c * 3 + 2]!;
      near[i] = Math.min(near[i]!, dr * dr + dg * dg + db * db);
      sum += near[i]! * weights[i]!;
    }
    if (sum <= 1e-9) break;
    target = hash3(c, 7, 11) * sum;
    pick = n - 1;
    for (let i = 0; i < n; i++) {
      target -= near[i]! * weights[i]!;
      if (target <= 0) {
        pick = i;
        break;
      }
    }
  }

  const count = centres.length / 3;
  const acc = new Float64Array(count * 4);
  for (let round = 0; round < rounds; round++) {
    acc.fill(0);
    for (let i = 0; i < n; i++) {
      const c = nearestOf(centres, count, points[i * 3]!, points[i * 3 + 1]!, points[i * 3 + 2]!);
      const w = weights[i]!;
      acc[c * 4] += points[i * 3]! * w;
      acc[c * 4 + 1] += points[i * 3 + 1]! * w;
      acc[c * 4 + 2] += points[i * 3 + 2]! * w;
      acc[c * 4 + 3] += w;
    }
    for (let c = 0; c < count; c++) {
      const w = acc[c * 4 + 3]!;
      if (w <= 0) continue;
      centres[c * 3] = acc[c * 4]! / w;
      centres[c * 3 + 1] = acc[c * 4 + 1]! / w;
      centres[c * 3 + 2] = acc[c * 4 + 2]! / w;
    }
  }
  const out: Rgb[] = [];
  for (let c = 0; c < count; c++)
    out.push([centres[c * 3]!, centres[c * 3 + 1]!, centres[c * 3 + 2]!]);
  return out;
}

function nearestOf(centres: readonly number[], count: number, r: number, g: number, b: number) {
  let best = 0;
  let bestD = Infinity;
  for (let c = 0; c < count; c++) {
    const dr = r - centres[c * 3]!;
    const dg = g - centres[c * 3 + 1]!;
    const db = b - centres[c * 3 + 2]!;
    // Weighted toward green, as the eye is.
    const d = dr * dr * 0.3 + dg * dg * 0.59 + db * db * 0.11;
    if (d < bestD) {
      bestD = d;
      best = c;
    }
  }
  return best;
}

const BITS = 5;
const SIDE = 1 << BITS;

/**
 * Finds the nearest palette colour fast, through a table of every 15-bit colour, filled in as
 * colours are asked for.
 */
export class Quantiser {
  private flat: number[];
  private table = new Uint8Array(SIDE * SIDE * SIDE).fill(255);

  constructor(readonly palette: readonly Rgb[]) {
    this.flat = palette.flat();
  }

  /** The index of the nearest palette colour to a colour with channels from 0 to 1. */
  index(r: number, g: number, b: number): number {
    const q = (v: number) => Math.min(SIDE - 1, Math.max(0, Math.floor(v * SIDE)));
    const key = (q(r) << (BITS * 2)) | (q(g) << BITS) | q(b);
    let hit = this.table[key]!;
    if (hit === 255) {
      // The middle of the table cell stands for every colour in it.
      const s = 1 / SIDE;
      hit = nearestOf(
        this.flat,
        this.palette.length,
        (q(r) + 0.5) * s,
        (q(g) + 0.5) * s,
        (q(b) + 0.5) * s,
      );
      this.table[key] = hit;
    }
    return hit;
  }
}
components/lilt/ascii/media/sample.tsascii-media

sample.ts

import { clamp } from '../engine/noise';
import type { AsciiGrid } from '../engine/types';

/** How a picture sits in its frame: whole with room around it, or filling it and cropped. */
export type MediaFit = 'cover' | 'contain';

/** Where a picture lands on the grid, in cells, and the part of the source it shows. */
export interface Placement {
  col: number;
  row: number;
  cols: number;
  rows: number;
  sx: number;
  sy: number;
  sw: number;
  sh: number;
}

/** Space kept clear around a contained picture, in cells. */
export const PAD = { x: 3, y: 1 };

/**
 * Places a `width` × `height` source on the grid. Cells are taller than they are wide, so a cell
 * covers `aspect` times as much of the picture down as across: the picture keeps its shape.
 */
export function place(width: number, height: number, grid: AsciiGrid, fit: MediaFit): Placement {
  const { cols, rows, aspect } = grid;
  if (fit === 'cover') {
    const w = cols;
    const h = rows * aspect;
    const scale = Math.max(w / width, h / height);
    const sw = Math.min(width, w / scale);
    const sh = Math.min(height, h / scale);
    return { col: 0, row: 0, cols, rows, sx: (width - sw) / 2, sy: (height - sh) / 2, sw, sh };
  }
  const w = Math.max(1, cols - PAD.x * 2);
  const h = Math.max(1, rows - PAD.y * 2) * aspect;
  const scale = Math.min(w / width, h / height);
  const boxCols = clamp(Math.round(width * scale), 1, cols);
  const boxRows = clamp(Math.round((height * scale) / aspect), 1, rows);
  return {
    col: Math.floor((cols - boxCols) / 2),
    row: Math.floor((rows - boxRows) / 2),
    cols: boxCols,
    rows: boxRows,
    sx: 0,
    sy: 0,
    sw: width,
    sh: height,
  };
}

/** A picture at grid resolution: colour from 0 to 1 per cell, and how opaque it is. */
export interface CellPixels {
  cols: number;
  rows: number;
  r: Float32Array;
  g: Float32Array;
  b: Float32Array;
  a: Float32Array;
}

export function cellPixels(cols: number, rows: number): CellPixels {
  const size = cols * rows;
  return {
    cols,
    rows,
    r: new Float32Array(size),
    g: new Float32Array(size),
    b: new Float32Array(size),
    a: new Float32Array(size),
  };
}

/**
 * Averages blocks of `factor` × `factor` pixels into one cell each: every pixel under a cell
 * counts, so fine detail turns to tone instead of flickering in and out. Colour is weighted by
 * opacity, so a transparent pixel's colour never bleeds into its neighbours.
 */
export function boxAverage(
  rgba: Uint8ClampedArray | Uint8Array,
  width: number,
  height: number,
  factor: number,
  out: CellPixels,
) {
  const { cols, rows } = out;
  const inv = 1 / 255;
  for (let row = 0; row < rows; row++) {
    for (let col = 0; col < cols; col++) {
      let r = 0;
      let g = 0;
      let b = 0;
      let a = 0;
      let n = 0;
      const y0 = row * factor;
      const x0 = col * factor;
      for (let y = y0; y < Math.min(height, y0 + factor); y++) {
        let p = (y * width + x0) * 4;
        for (let x = x0; x < Math.min(width, x0 + factor); x++, p += 4) {
          const alpha = rgba[p + 3]! * inv;
          r += rgba[p]! * alpha;
          g += rgba[p + 1]! * alpha;
          b += rgba[p + 2]! * alpha;
          a += alpha;
          n++;
        }
      }
      const i = row * cols + col;
      const k = a > 0 ? inv / a : 0;
      out.r[i] = r * k;
      out.g[i] = g * k;
      out.b[i] = b * k;
      out.a[i] = n ? a / n : 0;
    }
  }
}

/**
 * The darkest and brightest values worth spreading across the ramp: the 2nd and 99th percentiles,
 * so a few stray pixels can't flatten the picture. Values are from 0 to 1, weighted.
 */
export function levels(values: Float32Array, weights: Float32Array): [number, number] {
  const bins = new Float32Array(256);
  let total = 0;
  for (let i = 0; i < values.length; i++) {
    const w = weights[i]!;
    if (w <= 0.02) continue;
    bins[clamp(Math.floor(values[i]! * 255), 0, 255)] += w;
    total += w;
  }
  if (total <= 0) return [0, 1];
  const find = (share: number) => {
    let sum = 0;
    for (let k = 0; k < 256; k++) {
      sum += bins[k]!;
      if (sum >= total * share) return k / 255;
    }
    return 1;
  };
  const lo = find(0.02);
  const hi = Math.max(find(0.99), lo + 0.15);
  return [lo, Math.min(1, hi)];
}

/**
 * Stretches a value between the levels, then bends it: `contrast` above 1 pushes tones apart
 * from the middle, below 1 pulls them together, and `gamma` lifts or sinks the mid-tones.
 */
export function shape(v: number, lo: number, hi: number, contrast: number, gamma: number) {
  const t = clamp((v - lo) / (hi - lo || 1), 0, 1);
  const x = t * 2 - 1;
  const s = (Math.sign(x) * Math.pow(Math.abs(x), 1 / Math.max(0.1, contrast)) + 1) / 2;
  return Math.pow(s, gamma);
}
components/lilt/ascii/media/media-scene.tsascii-media

media-scene.ts

import { scrambled, text } from '../charts/chart-kit';
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 { luma, toHex, type Rgb } from './colour';
import type { MediaFeed } from './feed';
import { chromaOnDark, chromaOnLight, Quantiser } from './palette';
import {
  boxAverage,
  cellPixels,
  levels,
  PAD,
  place,
  shape,
  type CellPixels,
  type MediaFit,
  type Placement,
} from './sample';

/** How a picture is drawn: a density ramp of glyphs, or solid lit blocks with a glyph cut in. */
export type MediaMode = 'glyphs' | 'blocks';
/** Colour from the picture itself, or one ink. */
export type MediaColor = 'source' | 'mono';

/** The backdrop the scene sits on, read every frame: a light one turns the picture to ink on paper. */
export interface Backdrop {
  light: boolean;
}

export interface MediaSceneOptions {
  /** The pixels. Null, or a feed without a picture yet, leaves the frame empty. */
  feed: MediaFeed | null;
  mode?: MediaMode;
  color?: MediaColor;
  /** The ink for `mono`, as any CSS colour. Default the canvas's own ink. */
  tint?: string;
  fit?: MediaFit;
  invert?: boolean;
  /** Above 1 pushes tones apart, below 1 pulls them together. Default 1. */
  contrast?: number;
  /** Colours for `source` on a dark backdrop, and on a light one. */
  palette?: { dark: readonly Rgb[]; light: readonly Rgb[] };
  backdrop?: Backdrop;
  /** Read the feed again whenever it has a new frame, as for video. Default false. */
  live?: boolean;
  /** Scramble the picture in as it first appears. Default true. */
  reveal?: boolean;
  /** Characters the pointer stirs the picture into. */
  scramble?: string;
  /** A short line shown in the middle of the frame instead of a picture, such as an error. */
  message?: string;
  /** Corner marks around the frame while there's no picture, as for a camera that's off. */
  viewfinder?: boolean;
}

const INK = 0;
const TINT = 1;
const CUT_DARK = 2;
const CUT_LIGHT = 3;
const FIRST = 4;

/** Sparse to dense. Each step adds ink without changing the glyph's character much. */
const RAMP = ' .:-=+*#%@';
/** Cut into lit blocks: none where the light falls full, denser into the shadow. */
const CUTS = '.:-=+*';
const EDGE = '.:';
const CODE = '01<>/\\{}[]#$%&*+=?~';

/** How long a cell scrambles before it settles, in seconds. */
const SCRAMBLE_TIME = 0.32;
/** How long the reveal sweep takes to cross the picture. */
const SWEEP = 1.15;

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

/**
 * A picture drawn in type, from any feed: an image, a video or the camera. It reads the feed at
 * the grid's resolution, averaging every pixel under each cell; spreads its tones so it reads; and
 * draws each cell as a glyph from a density ramp, or as a lit block with a glyph cut in. It
 * scrambles in as it first appears, the pointer stirs it into code, and a click sends a ring of
 * code through it.
 */
export function createMediaScene(options: MediaSceneOptions): AsciiScene {
  const { feed } = options;
  const mode = options.mode ?? 'glyphs';
  const colour = options.color ?? 'source';
  const fit = options.fit ?? 'contain';
  const invert = options.invert ?? false;
  const contrast = clamp(options.contrast ?? 1, 0.25, 4);
  const backdrop = options.backdrop ?? { light: false };
  const live = options.live ?? false;
  const reveal = options.reveal ?? true;
  const code = options.scramble || CODE;
  const dark = options.palette?.dark ?? [];
  const light = options.palette?.light ?? [];
  const quantiseDark = new Quantiser(dark.length ? dark : [[1, 1, 1]]);
  const quantiseLight = new Quantiser(light.length ? light : [[0, 0, 0]]);

  let grid: AsciiGrid = { cols: 0, rows: 0, aspect: 2 };
  let time = 0;
  let placement: Placement | null = null;
  let pixels: CellPixels = cellPixels(0, 0);
  /** The shaped value of each cell of the picture, and its palette colour. */
  let value = new Float32Array(0);
  let raw = new Float32Array(0);
  let tone = new Uint8Array(0);
  let stir = new Float32Array(0);
  let sampledFrame = -1;
  let sampledLight = false;
  let revealFrom = -1;
  let lo = 0;
  let hi = 1;
  let lastX = -1;
  let lastY = -1;
  const rings: Ring[] = [];
  const chroma: Rgb = [0, 0, 0];

  function sample() {
    if (!feed || feed.width < 1 || feed.height < 1 || grid.cols < 1) return;
    const pl = place(feed.width, feed.height, grid, fit);
    // A still picture is read once, finely; video every frame, so more cheaply.
    const factor = live ? 2 : 4;
    const data = feed.read(pl.sx, pl.sy, pl.sw, pl.sh, pl.cols * factor, pl.rows * factor);
    if (!data) return;
    if (pixels.cols !== pl.cols || pixels.rows !== pl.rows) {
      pixels = cellPixels(pl.cols, pl.rows);
      value = new Float32Array(pl.cols * pl.rows);
      raw = new Float32Array(pl.cols * pl.rows);
      tone = new Uint8Array(pl.cols * pl.rows);
    }
    boxAverage(data, pl.cols * factor, pl.rows * factor, factor, pixels);
    const onLight = backdrop.light;
    // On a dark page bright parts get the dense glyphs; on paper, dark parts do, as in a print.
    const darkness = onLight !== invert;
    const size = pl.cols * pl.rows;
    for (let i = 0; i < size; i++) {
      const r = pixels.r[i]!;
      const g = pixels.g[i]!;
      const b = pixels.b[i]!;
      const y = luma(r, g, b);
      raw[i] = darkness
        ? 1 - (0.6 * y + 0.4 * Math.min(r, g, b))
        : 0.6 * y + 0.4 * Math.max(r, g, b);
      if (colour !== 'source') {
        tone[i] = TINT;
      } else if (onLight) {
        chromaOnLight(r, g, b, chroma);
        tone[i] = FIRST + dark.length + quantiseLight.index(chroma[0], chroma[1], chroma[2]);
      } else {
        chromaOnDark(r, g, b, chroma);
        tone[i] = FIRST + quantiseDark.index(chroma[0], chroma[1], chroma[2]);
      }
    }
    const [l, h] = levels(raw, pixels.a);
    // Video eases its levels so the picture doesn't pump as the view changes.
    const ease = live && placement ? 0.12 : 1;
    // Ink on paper is heavier than light on night: ease the mid-tones so only the deepest go dense.
    const gamma = darkness && mode === 'glyphs' ? 1.35 : 0.9;
    lo += (l - lo) * ease;
    hi += (h - hi) * ease;
    for (let i = 0; i < size; i++) {
      value[i] = shape(raw[i]!, lo, hi, contrast, gamma) * pixels.a[i]!;
    }
    placement = pl;
    sampledFrame = feed.frame;
    sampledLight = onLight;
    // A still picture is there from the start, so the reveal runs on the scene's own clock (and a
    // reduced-motion still, drawn after it settles, shows it whole). Video reveals on its first frame.
    if (revealFrom < 0) revealFrom = live ? time : 0;
  }

  /** Raises the stir around a point, in square units. */
  function stamp(px: number, py: number, radius: number, amount: number) {
    const { cols, rows, aspect } = grid;
    const r0 = Math.max(0, Math.floor((py - radius) / aspect));
    const r1 = Math.min(rows - 1, Math.ceil((py + radius) / aspect));
    const c0 = Math.max(0, Math.floor(px - radius));
    const c1 = Math.min(cols - 1, Math.ceil(px + radius));
    for (let row = r0; row <= r1; row++) {
      for (let col = c0; col <= c1; col++) {
        const ox = col + 0.5 - px;
        const oy = (row + 0.5) * aspect - py;
        const d = Math.sqrt(ox * ox + oy * oy);
        if (d > radius) continue;
        const i = row * cols + col;
        // Strong in the middle of its reach, fading to nothing at the edge.
        const fall = 1 - d / radius;
        stir[i] = Math.min(1, stir[i]! + amount * fall * fall);
      }
    }
  }

  function drawFrameMarks(surface: GlyphSurface) {
    const { cols, rows } = grid;
    const x0 = PAD.x;
    const x1 = cols - PAD.x - 1;
    const y0 = PAD.y;
    const y1 = rows - PAD.y - 1;
    if (x1 - x0 < 8 || y1 - y0 < 4) return;
    const arm = Math.max(2, Math.min(6, Math.floor((x1 - x0) / 10)));
    const down = Math.max(1, Math.min(3, Math.floor((y1 - y0) / 8)));
    const corners: [number, number, number, number][] = [
      [x0, y0, 1, 1],
      [x1, y0, -1, 1],
      [x0, y1, 1, -1],
      [x1, y1, -1, -1],
    ];
    for (const [x, y, sx, sy] of corners) {
      surface.put(x, y, '+', INK, 0.5);
      for (let k = 1; k <= arm; k++) surface.put(x + k * sx, y, '-', INK, 0.4 - k * 0.03);
      for (let k = 1; k <= down; k++) surface.put(x, y + k * sy, '|', INK, 0.4 - k * 0.06);
    }
  }

  function drawMessage(surface: GlyphSurface, message: string) {
    const { cols, rows } = grid;
    const width = Math.max(10, cols - PAD.x * 2 - 4);
    const lines: string[] = [];
    let line = '';
    for (const word of message.split(/\s+/)) {
      if (line && line.length + 1 + word.length > width) {
        lines.push(line);
        line = word;
      } else line = line ? `${line} ${word}` : word;
    }
    if (line) lines.push(line);
    const top = Math.floor(rows / 2 - lines.length / 2);
    lines.forEach((l, k) => text(surface, Math.floor((cols - l.length) / 2), top + k, l, INK, 0.7));
  }

  return {
    palette: [
      'ink',
      options.tint || 'ink',
      '#08080c',
      '#f7f5f0',
      ...dark.map(toHex),
      ...light.map(toHex),
    ],
    lineHeight: 1,
    settle: reveal ? SWEEP + SCRAMBLE_TIME + 0.6 : 0.2,
    resize(next) {
      grid = next;
      stir = new Float32Array(grid.cols * grid.rows);
      placement = null;
    },
    step(dt, pointer: AsciiPointer) {
      time += dt;
      const decay = Math.exp(-dt * 1.6);
      for (let i = 0; i < stir.length; i++) stir[i]! *= decay;
      if (pointer.active && grid.cols) {
        const px = pointer.x;
        const py = pointer.y * grid.aspect;
        // Stir along the whole path, so a quick stroke leaves an unbroken wake.
        const moved = lastX < 0 ? 0 : Math.hypot(px - lastX, py - lastY);
        const steps = Math.min(12, Math.ceil(moved / 1.5));
        const reach = Math.max(3, Math.min(grid.cols, grid.rows * grid.aspect) * 0.07);
        for (let s = 0; s <= steps; s++) {
          const t = steps ? s / steps : 1;
          const x = lastX < 0 ? px : lastX + (px - lastX) * t;
          const y = lastY < 0 ? py : lastY + (py - lastY) * t;
          stamp(x, y, reach, steps ? 0.3 / Math.sqrt(steps) : 0.08);
        }
        lastX = px;
        lastY = py;
      } else {
        lastX = -1;
      }
      for (let k = rings.length - 1; k >= 0; k--) {
        rings[k]!.age += dt;
        if (rings[k]!.age > 3) rings.splice(k, 1);
      }
    },
    press(x, y) {
      rings.push({ x, y: y * grid.aspect, age: 0 });
    },
    draw(surface: GlyphSurface) {
      const { cols, rows, aspect } = grid;
      if (cols < 4 || rows < 2) return;
      if (options.message) {
        drawMessage(surface, options.message);
        return;
      }
      if (
        feed &&
        (!placement || sampledLight !== backdrop.light || (live && feed.frame !== sampledFrame))
      ) {
        sample();
      }
      const pl = placement;
      if (!pl) {
        if (options.viewfinder) drawFrameMarks(surface);
        return;
      }
      const since = reveal ? time - revealFrom : Infinity;
      const tick = Math.floor(time * 18);
      const stirTick = Math.floor(time * 12);
      const blocks = mode === 'blocks';
      const cut = backdrop.light ? CUT_LIGHT : CUT_DARK;

      for (let r = 0; r < pl.rows; r++) {
        const row = pl.row + r;
        if (row < 0 || row >= rows) continue;
        for (let c = 0; c < pl.cols; c++) {
          const col = pl.col + c;
          if (col < 0 || col >= cols) continue;
          const i = r * pl.cols + c;
          const v = value[i]!;
          const alpha = pixels.a[i]!;
          // Glyphs leave the darkest parts empty; blocks keep every opaque cell, however dim.
          if (blocks ? alpha < 0.1 : v < 0.05) continue;
          const t = tone[i]!;

          // The reveal sweeps from the top left, each cell scrambling a moment before it lands.
          const jitter = hash3(col, row, 5);
          const at = ((c / pl.cols) * 0.75 + (r / pl.rows) * 0.25) * SWEEP + jitter * 0.25;
          if (since < at) continue;
          const revealing = since < at + SCRAMBLE_TIME;
          let ringed = false;
          if (!revealing && rings.length) {
            const x = col + 0.5;
            const y = (row + 0.5) * aspect;
            for (const ring of rings) {
              const d = Math.sqrt((x - ring.x) ** 2 + (y - ring.y) ** 2);
              const band = 2.2 + ring.age * 2;
              if (Math.abs(d - ring.age * 42) < band * (0.6 + 0.4 * jitter)) ringed = true;
            }
          }
          const s = stir[row * cols + col]!;
          const stirred = s > 0.06 && s > jitter * 0.7;

          if (revealing || ((ringed || stirred) && !(blocks && alpha >= 0.5))) {
            // Arriving, or stirred: the cell is code for a moment.
            const g = revealing
              ? scrambled(col, row, tick)
              : code[Math.floor(hash3(col, row, ringed ? tick : stirTick) * code.length)]!;
            surface.put(col, row, g, t, clamp(0.4 + v * 0.55 + (stirred ? s * 0.3 : 0), 0, 1));
            continue;
          }
          if (ringed || stirred) {
            // On blocks the mosaic holds, and the code is cut into it: dark into bright blocks,
            // bright into dim ones.
            const g = code[Math.floor(hash3(col, row, ringed ? tick : stirTick) * code.length)]!;
            surface.fill(col, row, t, Math.max(0.13, v * 0.85));
            if (v > 0.55) surface.put(col, row, g, cut, 0.75);
            else surface.put(col, row, g, t, 1);
            continue;
          }

          if (!blocks) {
            const g = ramp(RAMP, v);
            if (g !== ' ') surface.put(col, row, g, t, 0.3 + 0.7 * v);
            continue;
          }
          if (alpha < 0.5) {
            // The soft edge of a cut-out picture: a fine grain rather than a ragged block.
            surface.put(col, row, ramp(EDGE, alpha * 2), t, 0.3 + v);
            continue;
          }
          // Dark parts stay dim blocks, so the picture reads as one mosaic to its edges.
          surface.fill(col, row, t, Math.max(0.13, v));
          if (v < 0.86) surface.put(col, row, ramp(CUTS, (0.86 - v) / 0.66), cut, 0.3 + 0.35 * v);
        }
      }
    },
  };
}
components/lilt/ascii/media/use-backdrop.tsascii-media

use-backdrop.ts

'use client';

import { useEffect, useRef, type RefObject } from 'react';
import { isLight } from './colour';
import type { Backdrop } from './media-scene';

/**
 * Whether a picture sits on a light backdrop, judged from its ink: dark ink means a light page.
 * The answer is an object the scene reads every frame, so a theme change redraws the picture as
 * ink on paper without rebuilding it. `ink` is the colour passed in `style`, when there is one;
 * otherwise the element's own text colour is read, and read again when the theme changes.
 */
export function useBackdrop(element: RefObject<HTMLElement | null>, ink?: string): Backdrop {
  const backdrop = useRef<Backdrop>({ light: ink ? !isLight(ink) : false }).current;
  if (ink) backdrop.light = !isLight(ink);

  useEffect(() => {
    if (ink) return;
    const read = () => {
      const el = element.current;
      if (el) backdrop.light = !isLight(getComputedStyle(el).color);
    };
    read();
    const observer = new MutationObserver(read);
    observer.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ['class', 'style', 'data-theme'],
    });
    // A parent's colour can change without the root noticing; a slow check catches it.
    const timer = window.setInterval(read, 1500);
    return () => {
      observer.disconnect();
      window.clearInterval(timer);
    };
  }, [element, ink, backdrop]);

  return backdrop;
}
components/lilt/ascii/charts/chart-kit.tsascii-chart-kit

chart-kit.ts

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

/** Space kept clear around a chart, in cells, so it never runs into the edge of its frame. */
export const INSET = { x: 4, top: 1, bottom: 2 };

/** Characters data scrambles through on its way in. */
export const SCRAMBLE = '01<>/\\{}[]#$%&*+=?~';

/** The glyph at a cell on a given tick of the scramble. */
export const scrambled = (col: number, row: number, tick: number) =>
  SCRAMBLE[Math.floor(hash3(col, row, tick) * SCRAMBLE.length)]!;

/** Writes a run of text from a cell, left to right. Spaces leave their cells as they are. */
export function text(
  surface: GlyphSurface,
  col: number,
  row: number,
  value: string,
  tone: number,
  opacity = 1,
) {
  for (let i = 0; i < value.length; i++) {
    const ch = value[i]!;
    if (ch !== ' ') surface.put(col + i, row, ch, tone, opacity);
  }
}

const compactFormat = new Intl.NumberFormat('en', {
  notation: 'compact',
  maximumFractionDigits: 1,
});
const fullFormat = new Intl.NumberFormat('en', { maximumFractionDigits: 2 });

/** A short number for an axis: 1.2K, 48, 3M. */
export const compact = (value: number) => compactFormat.format(value);

/** A number in full for a readout: 12,480. */
export const full = (value: number) => fullFormat.format(value);

/** Round steps for an axis from `min` to `max`: 1, 2 or 5 times a power of ten. */
export function ticks(min: number, max: number, count: number): number[] {
  if (!(max > min)) return [min];
  const raw = (max - min) / Math.max(1, count);
  const power = Math.pow(10, Math.floor(Math.log10(raw)));
  const step = [1, 2, 5, 10].map((m) => m * power).find((s) => s >= raw) ?? raw;
  const out: number[] = [];
  for (let v = Math.floor(min / step) * step; v <= max + step * 0.5; v += step) {
    out.push(Math.round(v / step) * step);
    if (v >= max) break;
  }
  return out;
}

/** An entrance easing: quick out of the gate, settling softly. */
export const easeOut = (t: number) => 1 - Math.pow(1 - clamp(t, 0, 1), 3);

/** A believable daily series for demos: a gentle trend, a weekly rhythm and some noise. */
export function demoSeries(length: number, seed = 1): number[] {
  return Array.from({ length }, (_, i) => {
    const trend = 2200 + i * 16 + Math.sin(i / 11 + seed) * 420 + Math.sin(i / 4.3) * 120;
    const week = i % 7 === 5 || i % 7 === 6 ? -160 : 40;
    const noise = (hash3(i, seed, 7) - 0.5) * 140;
    return Math.max(0, Math.round(trend + week + noise));
  });
}

const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

export const monthName = (date: Date) => MONTHS[date.getMonth()]!;
export const dayName = (date: Date) => DAYS[date.getDay()]!;
export const shortDate = (date: Date) => `${monthName(date)} ${date.getDate()}`;

/** A date a whole number of days from another, at local midnight. */
export function addDays(date: Date, days: number) {
  const out = new Date(date.getFullYear(), date.getMonth(), date.getDate());
  out.setDate(out.getDate() + days);
  return out;
}

/** Parses `YYYY-MM-DD` as a local date; anything else falls back to today. */
export function parseDay(value: string | undefined): Date {
  const match = value?.match(/^(\d{4})-(\d{2})-(\d{2})$/);
  const today = new Date();
  if (!match) return new Date(today.getFullYear(), today.getMonth(), today.getDate());
  return new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3]));
}

/** The labels demo data uses: one date a day, ending on `end`. */
export const dayLabels = (length: number, end: Date) =>
  Array.from({ length }, (_, i) => shortDate(addDays(end, i - length + 1)));

/** A one-line description of a series for screen readers. */
export function describe(kind: string, data: readonly number[], labels?: readonly string[]) {
  if (!data.length) return `${kind} with no data.`;
  let lo = 0;
  let hi = 0;
  data.forEach((v, i) => {
    if (v < data[lo]!) lo = i;
    if (v > data[hi]!) hi = i;
  });
  const at = (i: number) => (labels?.[i] ? ` (${labels[i]})` : '');
  const last = data.length - 1;
  return (
    `${kind} of ${data.length} values: lowest ${full(data[lo]!)}${at(lo)}, ` +
    `highest ${full(data[hi]!)}${at(hi)}, latest ${full(data[last]!)}${at(last)}.`
  );
}

/**
 * The label a chart gets when none is given: a chart is information, so unlike a scene it is never
 * hidden from screen readers.
 */
export const chartLabel = (kind: string, data?: readonly number[], labels?: readonly string[]) =>
  data?.length ? describe(kind, data, labels) : `${kind} of demo data.`;

Usage

How it behaves.

The image’s pixels are read, so it must come from the same origin as the page or be served with CORS headers; anything else shows a short note instead. Each cell averages every pixel beneath it. The picture scrambles in when it first appears. On a light backdrop it draws as ink on paper, with the dark parts dense, and it follows a theme change without reloading. Give it a label when the picture carries meaning; without one it is hidden from screen readers.

Props12

Every option.

Pass these directly to AsciiImage.

PropTypeDefaultWhat it does
tintstringthe text colourThe ink for mono, as any CSS colour.
scramblestringcode: 01<>/{}[]#$%&*+=?~Characters the pointer stirs the picture into.
srcstring''The image to draw. Same origin, or served with CORS. Empty draws three lit spheres.
modestring'glyphs'Glyphs draws a density ramp of type. Blocks draws solid lit blocks with a glyph cut in.
colorstring'source'Source takes each cell’s colour from the picture. Mono draws in one ink.
fitstring'contain'Contain shows the whole picture with room around it. Cover fills the frame.
contrastnumber1Above 1 pushes tones apart; below 1 pulls them together.
invertbooleanfalseSwap which end of the tones gets the dense glyphs, for dark pictures on light.
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 picture for screen readers.
Previous sceneStarfieldNext sceneVideo

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