Skip to content
Charts55Components12Visuals14ASCII45
GitHubGet startedGet started
All ASCIITransitionInterface
PreviousNext: Cursor trail

The slides change every few seconds. Click to change them sooner.

Transition

Interface

Content that changes behind a curtain of type, sweeping across and resolving away.

Customize 4

0.90
#8b6cff
3.5
Install & copy sourceInstall & copy sourceSee propsSee props5

Live code

As tuned above.

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

example.tsx

import { useState } from 'react';
import { AsciiTransition } from '@/components/lilt/ascii/interface/ascii-transition';

const steps = ['Connect', 'Configure', 'Launch'];

export function Steps() {
  const [step, setStep] = useState(0);
  return (
    <button type="button" onClick={() => setStep((step + 1) % steps.length)}>
      <AsciiTransition id={steps[step]}>
        <h3>{steps[step]}</h3>
      </AsciiTransition>
    </button>
  );
}

Installation7

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/transition.json
components/lilt/ascii/interface/ascii-transition.tsx

ascii-transition.tsx

'use client';

import {
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type CSSProperties,
  type ReactNode,
} from 'react';
import { clamp } from '../engine/noise';
import { frontAt, paintCurtain, type CurtainDirection } from './curtain-paint';
import { fitCanvas, monoFont, useReducedMotion } from './motion';

export type AsciiTransitionDirection = CurtainDirection;

export interface AsciiTransitionProps {
  /** Names what is shown. When it changes, the glyphs sweep across and the new children appear. */
  id: string;
  children?: ReactNode;
  /** Which way the sweep travels; `radial` opens from the centre. Default `right`. */
  direction?: AsciiTransitionDirection;
  /** Seconds for the whole change, covering and revealing. Default 0.9. */
  duration?: number;
  /** Colour of the glyphs at the front of the sweep. Default violet. */
  color?: string;
  className?: string;
  style?: CSSProperties;
}

const toward = (d: AsciiTransitionDirection) =>
  d === 'right' ? 'to right' : d === 'left' ? 'to left' : d === 'down' ? 'to bottom' : 'to top';

/**
 * Swaps content behind a curtain of type. When `id` changes a front of scrambling glyphs sweeps
 * across, hiding the old content; at the midpoint the new children take its place, and a second
 * front sweeps after it, resolving the glyphs away. With reduced motion the content swaps at once.
 */
export function AsciiTransition({
  id,
  children,
  direction = 'right',
  duration = 0.9,
  color = '#8b6cff',
  className,
  style,
}: AsciiTransitionProps) {
  const reduced = useReducedMotion();
  const rootRef = useRef<HTMLDivElement>(null);
  const contentRef = useRef<HTMLDivElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [shownId, setShownId] = useState(id);
  // What the shown id last rendered, kept on screen until the sweep has covered it.
  const held = useRef(children);
  if (id === shownId || reduced) held.current = children;
  const latest = useRef({ id, direction, duration, color });
  latest.current = { id, direction, duration, color };
  const run = useRef({ raf: 0, start: 0, swapped: false, seed: 0 });

  useLayoutEffect(() => {
    if (reduced) {
      if (id !== shownId) setShownId(id);
      return;
    }
    if (id === shownId) return;
    const state = run.current;
    // Already sweeping toward an older id: the midpoint will pick up this one instead.
    if (state.raf && !state.swapped) return;
    cancelAnimationFrame(state.raf);
    state.start = performance.now();
    state.swapped = false;
    state.seed++;

    const root = rootRef.current;
    const content = contentRef.current;
    const canvas = canvasRef.current;
    const ctx = canvas?.getContext('2d');
    if (!root || !content || !canvas || !ctx) {
      setShownId(id);
      return;
    }

    // A rounded card keeps its corners: the curtain takes the radius of what it covers.
    const first = content.firstElementChild;
    canvas.style.borderRadius = first ? getComputedStyle(first).borderRadius : '';

    const frame = (now: number) => {
      const { duration: seconds, direction: way, color: accent } = latest.current;
      const t = clamp((now - state.start) / 1000 / Math.max(0.1, seconds), 0, 1);
      const rect = root.getBoundingClientRect();
      const dpr = fitCanvas(canvas, rect.width, rect.height);
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      ctx.clearRect(0, 0, rect.width, rect.height);

      // Two fronts, one after the other: the first covers, the second reveals.
      const f1 = frontAt(t / 0.5);
      const f2 = frontAt((t - 0.5) / 0.5);
      if (t >= 0.5 && !state.swapped) {
        state.swapped = true;
        setShownId(latest.current.id);
      }

      const mask = (front: number, show: 'after' | 'before') => {
        const at = front * 100;
        const [a, b] = show === 'after' ? ['transparent', 'black'] : ['black', 'transparent'];
        const stops = `${a} ${at - 2}%, ${b} ${at + 4}%`;
        return way === 'radial'
          ? `radial-gradient(circle farthest-corner at 50% 50%, ${stops})`
          : `linear-gradient(${toward(way)}, ${stops})`;
      };
      const image = t >= 1 ? '' : state.swapped ? mask(f2, 'before') : mask(f1, 'after');
      content.style.maskImage = image;
      content.style.setProperty('-webkit-mask-image', image);

      if (t < 1) {
        const { font, size, cw } = monoFont(ctx, root);
        paintCurtain(ctx, {
          width: rect.width,
          height: rect.height,
          cw,
          ch: size * 1.25,
          font,
          accent,
          ink: getComputedStyle(root).color,
          background: null,
          way,
          covering: f1,
          revealing: f2,
          seed: state.seed,
          now,
        });
      }

      state.raf = t < 1 ? requestAnimationFrame(frame) : 0;
    };
    state.raf = requestAnimationFrame(frame);
  }, [id, shownId, reduced]);

  useEffect(
    () => () => {
      cancelAnimationFrame(run.current.raf);
    },
    [],
  );

  return (
    <div
      ref={rootRef}
      className={className ? `lilt-ascii-transition ${className}` : 'lilt-ascii-transition'}
      style={{ position: 'relative', ...style }}
    >
      <div ref={contentRef}>{id === shownId || reduced ? children : held.current}</div>
      <canvas
        ref={canvasRef}
        aria-hidden="true"
        style={{
          position: 'absolute',
          inset: 0,
          width: '100%',
          height: '100%',
          pointerEvents: 'none',
        }}
      />
    </div>
  );
}
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/interface/curtain-paint.tsascii-curtain-paint

curtain-paint.ts

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

export type CurtainDirection = 'left' | 'right' | 'up' | 'down' | 'radial';

/** Glyphs at the front of the sweep, scrambling fast. */
const FRONT = '01<>/\\+=';
/** Glyphs left behind it while the content is hidden: quieter, slower. */
const BODY = '01';
/** Opacity of the curtain's tiles while it rests over the content. */
const REST = 0.14;
/** Share of the sweep, in the direction it travels, that one front spans. */
const BAND = 0.16;
const JITTER = 0.07;

const ease = (x: number) => x * x * (3 - 2 * x);

/** Where a front is, in shares of the sweep, `t` of the way through its half. */
export function frontAt(t: number) {
  return -BAND - JITTER + ease(clamp(t, 0, 1)) * (1 + 2 * (BAND + JITTER));
}

export interface CurtainFrame {
  width: number;
  height: number;
  /** The rows to draw, in pixels from the top, for a curtain taller than the screen. */
  from?: number;
  to?: number;
  cw: number;
  ch: number;
  font: string;
  accent: string;
  ink: string;
  /** Painted under the tiles so the curtain hides what is behind it, or null to leave it clear. */
  background: string | null;
  way: CurtainDirection;
  /** The covering front and the revealing front, in shares of the sweep. */
  covering: number;
  revealing: number;
  seed: number;
  now: number;
}

/**
 * Paints a curtain of type: a mosaic of accent tiles with digits cut into them, a bright
 * scrambling band at each front, quiet behind them. Cells are covered once the first front has
 * passed them and uncovered once the second has.
 */
export function paintCurtain(ctx: CanvasRenderingContext2D, f: CurtainFrame) {
  const { width, height, cw, ch, way } = f;
  const cols = Math.ceil(width / cw);
  const r0 = Math.max(0, Math.floor((f.from ?? 0) / ch));
  const r1 = Math.min(Math.ceil(height / ch), Math.ceil((f.to ?? height) / ch));
  const tick = Math.floor(f.now / 50);
  const slow = Math.floor(f.now / 160);
  const cx = width / 2;
  const cy = height / 2;
  const reach = Math.hypot(cx, cy) || 1;
  const backs: number[] = [];
  const tiles: number[] = [];
  const marks: [number, number, string, number][] = [];
  for (let r = r0; r < r1; r++) {
    for (let c = 0; c < cols; c++) {
      const x = (c + 0.5) * cw;
      const y = (r + 0.5) * ch;
      const along =
        way === 'right'
          ? x / width
          : way === 'left'
            ? 1 - x / width
            : way === 'down'
              ? y / height
              : way === 'up'
                ? 1 - y / height
                : Math.hypot(x - cx, y - cy) / reach;
      const u = along + (hash3(c, r, f.seed) - 0.5) * 2 * JITTER;
      const covered = f.covering - u;
      if (covered <= 0) continue;
      const revealed = f.revealing - u;
      // How bright the tile is: a flash at each front, a low glow between them.
      let tile: number;
      let ink: number;
      let back: number;
      let fast: boolean;
      if (revealed > 0) {
        if (revealed > BAND) continue;
        const k = revealed / BAND;
        tile = REST * (1 - k) + 0.35 * Math.max(0, 1 - k * 3);
        ink = 0.85 * (1 - k);
        back = 1 - k;
        fast = k < 0.5;
      } else if (covered < BAND) {
        const k = covered / BAND;
        tile = REST + (0.55 - REST) * (1 - k);
        ink = 0.9 - 0.55 * k;
        back = Math.min(1, k * 1.6);
        fast = true;
      } else {
        tile = REST;
        ink = 0.24;
        back = 1;
        fast = false;
      }
      backs.push(c, r, back);
      tiles.push(c, r, tile);
      // Behind the fronts only some tiles carry a digit, so the curtain stays calm.
      if (!fast && hash3(c, r, f.seed + 5) > 0.2) continue;
      const glyph = fast
        ? FRONT[Math.floor(hash3(c, r, tick) * FRONT.length)]!
        : BODY[Math.floor(hash3(c, r, slow) * BODY.length)]!;
      marks.push([x, y, glyph, ink]);
    }
  }
  if (f.background) {
    // Whole cells, so the hidden content cannot show between them.
    ctx.fillStyle = f.background;
    for (let i = 0; i < backs.length; i += 3) {
      ctx.globalAlpha = backs[i + 2]!;
      ctx.fillRect(backs[i]! * cw, backs[i + 1]! * ch, cw, ch);
    }
  }
  ctx.fillStyle = f.accent;
  for (let i = 0; i < tiles.length; i += 3) {
    ctx.globalAlpha = tiles[i + 2]!;
    ctx.fillRect(tiles[i]! * cw + 0.5, tiles[i + 1]! * ch + 0.5, cw - 1, ch - 1);
  }
  ctx.font = f.font;
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillStyle = f.ink;
  for (const [x, y, glyph, alpha] of marks) {
    ctx.globalAlpha = alpha;
    ctx.fillText(glyph, x, y);
  }
  ctx.globalAlpha = 1;
}
components/lilt/ascii/interface/motion.tsascii-motion

motion.ts

import { useEffect, useState } from 'react';

/** True when the reader asks for less motion. False on the server and before the first effect. */
export function useReducedMotion() {
  const [reduced, setReduced] = useState(false);
  useEffect(() => {
    if (typeof window.matchMedia !== 'function') return;
    const query = window.matchMedia('(prefers-reduced-motion: reduce)');
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener('change', update);
    return () => query.removeEventListener('change', update);
  }, []);
  return reduced;
}

/**
 * Seconds since the clock started, re-rendering at most `fps` times a second while `running`.
 * Stopped, it costs nothing and holds its last value.
 */
export function useClock(running: boolean, fps = 30) {
  const [time, setTime] = useState(0);
  useEffect(() => {
    if (!running) return;
    let raf = 0;
    let last = -1;
    const start = performance.now();
    const tick = (now: number) => {
      // A frame's timestamp can fall a little before the clock started; time never runs back.
      const t = Math.max(0, (now - start) / 1000);
      const frame = Math.floor(t * fps);
      if (frame !== last) {
        last = frame;
        setTime(t);
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [running, fps]);
  return time;
}

/** A monospace stack for components that set their own type. */
export const MONO_STACK =
  'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace';

/**
 * The font a canvas overlay draws its glyphs in: the element's own family when it is monospace,
 * otherwise a monospace stack at the element's size, so glyphs always sit on a grid.
 */
export function monoFont(ctx: CanvasRenderingContext2D, element: Element, weight = 500) {
  const css = getComputedStyle(element);
  const size = parseFloat(css.fontSize) || 14;
  const own = `${weight} ${size}px ${css.fontFamily || 'monospace'}`;
  ctx.font = own;
  const mono = Math.abs(ctx.measureText('i').width - ctx.measureText('M').width) < 0.01;
  const font = mono ? own : `${weight} ${size}px ${MONO_STACK}`;
  ctx.font = font;
  return { font, size, cw: Math.max(4, ctx.measureText('M').width) };
}

/** Sizes a canvas's backing store to its box at the device's pixel ratio, capped at 2. */
export function fitCanvas(canvas: HTMLCanvasElement, width: number, height: number) {
  const dpr = Math.min(window.devicePixelRatio || 1, 2);
  const w = Math.max(1, Math.round(width * dpr));
  const h = Math.max(1, Math.round(height * dpr));
  if (canvas.width !== w) canvas.width = w;
  if (canvas.height !== h) canvas.height = h;
  return dpr;
}

/** Mixes two `#rrggbb` colours; anything else returns the nearer one unchanged. */
export function mixHex(a: string, b: string, t: number) {
  const pa = /^#([0-9a-f]{6})$/i.exec(a);
  const pb = /^#([0-9a-f]{6})$/i.exec(b);
  if (!pa || !pb) return t < 0.5 ? a : b;
  const na = parseInt(pa[1]!, 16);
  const nb = parseInt(pb[1]!, 16);
  const ch = (shift: number) =>
    Math.round(((na >> shift) & 255) * (1 - t) + ((nb >> shift) & 255) * t);
  return `#${((1 << 24) | (ch(16) << 16) | (ch(8) << 8) | ch(0)).toString(16).slice(1)}`;
}

Usage

How it behaves.

Wrap content in AsciiTransition and give it an id that names what is shown, such as the tab or step. When the id changes, a front of scrambling glyphs sweeps across and hides the old content; at the midpoint the new children take its place, and a second front resolves the curtain away. The curtain is a canvas over the content, sized to it, and it only runs during a change. With reduced motion the content swaps at once. For changes you run yourself, such as moving between routes, AsciiCurtain raises and lowers the same curtain: set covered, swap the content in onCovered, then clear covered once it is ready. Every page on this site changes behind one.

Props5

Every option.

Pass these directly to AsciiTransition.

PropTypeDefaultWhat it does
idstring—Names what AsciiTransition shows. A new id plays the change.
childrenReactNode—The content for the current id.
directionstring'right'Which way the curtain travels; radial opens from the centre.
durationnumber0.9Seconds for the whole change, covering and revealing.
colorstring'#8b6cff'Colour of the curtain.
Previous sceneLoaderNext sceneCursor trail

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