Move across the stage to leave a trail. Click to open a ring. Away, it draws a loop of its own.
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 { AsciiCursorTrail } from '@/components/lilt/ascii/interface/ascii-cursor-trail';
// Add the trail once, near the root: it lies over the page and lets clicks through.
export function Layout({ children }: { children: React.ReactNode }) {
return (
<>
{children}
<AsciiCursorTrail />
</>
);
}
Installation9
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/cursor-trail.jsoncomponents/lilt/ascii/interface/ascii-cursor-trail.tsx
ascii-cursor-trail.tsx
'use client';
import { useEffect, useRef } from 'react';
import { GlyphSurface, LEVELS } from '../engine/surface';
import { AsciiCanvas, useSceneProps, type SceneProps } from '../react/ascii-canvas';
import { createCursorTrail, type CursorTrailOptions } from './cursor-trail';
import { MONO_STACK, fitCanvas, useReducedMotion } from './motion';
export type AsciiCursorTrailScope = 'window' | 'parent';
export type AsciiCursorTrailProps = SceneProps<CursorTrailOptions> & {
/**
* `window` lays the trail over the whole page, fixed and click-through, the usual way to use
* it. `parent` fills the parent element, like any other scene. Default `window`.
*/
scope?: AsciiCursorTrailScope;
};
const STEP = 1 / 60;
/**
* Glyphs shed behind the pointer that drift, slow and fade. Over the whole page it runs only while
* marks are alive: a still pointer costs nothing. With reduced motion it draws nothing.
*/
export function AsciiCursorTrail({ scope = 'window', ...props }: AsciiCursorTrailProps) {
const canvasProps = useSceneProps(props, createCursorTrail);
const reduced = useReducedMotion();
if (scope === 'parent') return <AsciiCanvas {...canvasProps} />;
if (reduced) return null;
return <WindowTrail {...props} />;
}
/** The page-wide trail: a fixed canvas and a loop that sleeps whenever the trail is empty. */
function WindowTrail({
cellSize = 14,
interactive = true,
speed = 1,
className,
style,
label: _label,
...options
}: SceneProps<CursorTrailOptions>) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const key = JSON.stringify(options);
const latest = useRef({ options, speed, cellSize, interactive });
latest.current = { options, speed, cellSize, interactive };
useEffect(() => {
const canvas = canvasRef.current;
const ctx = canvas?.getContext('2d');
if (!canvas || !ctx) return;
const scene = createCursorTrail(latest.current.options);
const surface = new GlyphSurface();
const pointer = { x: 0, y: 0, active: false };
let styles: string[] = [];
let font = '';
let cw = 8;
let ch = 18;
let raf = 0;
let last = 0;
let acc = 0;
let moved = false;
const restyle = () => {
const ink = getComputedStyle(canvas).color;
styles = scene.palette.flatMap((colour) => {
ctx.fillStyle = '#000';
ctx.fillStyle = colour === 'ink' ? ink : colour;
const [r, g, b] = parse(String(ctx.fillStyle));
return Array.from({ length: LEVELS }, (_, i) => `rgba(${r},${g},${b},${(i + 1) / LEVELS})`);
});
};
const resize = () => {
const width = window.innerWidth;
const height = window.innerHeight;
const dpr = fitCanvas(canvas, width, height);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
const size = latest.current.cellSize;
const family = getComputedStyle(canvas).fontFamily || MONO_STACK;
font = `500 ${size}px ${family}, ${MONO_STACK}`;
ctx.font = font;
cw = Math.max(4, ctx.measureText('M').width);
ch = Math.round(size * 1.25);
const cols = Math.ceil(width / cw);
const rows = Math.ceil(height / ch);
surface.resize(cols, rows);
scene.resize({ cols, rows, aspect: ch / cw });
restyle();
};
const paint = () => {
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.restore();
ctx.font = font;
ctx.textBaseline = 'middle';
surface.clear();
scene.draw(surface);
surface.paint(ctx, styles, cw, ch, true);
};
const frame = (now: number) => {
acc += Math.min(0.1, (now - last) / 1000) * latest.current.speed;
last = now;
let steps = 0;
while (acc >= STEP && steps < 8) {
scene.step(STEP, pointer);
acc -= STEP;
steps++;
}
paint();
// Rest once the last mark has faded and the pointer has stopped moving.
if (scene.alive === 0 && !moved) {
raf = 0;
pointer.active = false;
// One step with no pointer forgets where it was, so the next move starts clean.
scene.step(STEP, pointer);
return;
}
moved = false;
raf = requestAnimationFrame(frame);
};
const wake = () => {
if (raf || document.hidden) return;
last = performance.now();
acc = 0;
raf = requestAnimationFrame(frame);
};
const onMove = (e: PointerEvent) => {
if (!latest.current.interactive || e.pointerType === 'touch') return;
pointer.x = e.clientX / cw;
pointer.y = e.clientY / ch;
pointer.active = true;
moved = true;
wake();
};
const onDown = (e: PointerEvent) => {
if (!latest.current.interactive) return;
scene.press?.(e.clientX / cw, e.clientY / ch);
wake();
};
const onLeave = () => {
pointer.active = false;
};
resize();
window.addEventListener('resize', resize);
window.addEventListener('pointermove', onMove, { passive: true });
window.addEventListener('pointerdown', onDown, { passive: true });
document.documentElement.addEventListener('pointerleave', onLeave);
window.addEventListener('blur', onLeave);
const themeObserver = new MutationObserver(restyle);
themeObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class', 'style', 'data-theme'],
});
return () => {
cancelAnimationFrame(raf);
window.removeEventListener('resize', resize);
window.removeEventListener('pointermove', onMove);
window.removeEventListener('pointerdown', onDown);
document.documentElement.removeEventListener('pointerleave', onLeave);
window.removeEventListener('blur', onLeave);
themeObserver.disconnect();
};
}, [key, cellSize]);
return (
<canvas
ref={canvasRef}
aria-hidden="true"
className={className ? `lilt-ascii ${className}` : 'lilt-ascii'}
style={{
position: 'fixed',
inset: 0,
width: '100vw',
height: '100vh',
pointerEvents: 'none',
zIndex: 2147483000,
...style,
}}
/>
);
}
/** Reads the `#rrggbb` or `rgba(r, g, b, a)` a canvas reports back for any CSS colour. */
function parse(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/interface/cursor-trail.ts
cursor-trail.ts
import { ramp } from '../engine/glyphs';
import { clamp, hash3 } from '../engine/noise';
import type { GlyphSurface } from '../engine/surface';
import type { AsciiGrid, AsciiPointer, AsciiScene } from '../engine/types';
import { mixHex } from './motion';
export interface CursorTrailOptions {
/** Glyphs each mark wears as it ages, newest first. Default `*+:.`. */
characters?: string;
/** Colours the trail runs through from its head to its tail, as hex. Default violet to rose. */
colors?: readonly string[];
/** Seconds a mark lasts before it fades out. Default 1.2. */
life?: number;
/**
* When the pointer is away, an unseen pointer draws a slow loop, so a stage never sits empty.
* Default false.
*/
autopilot?: boolean;
}
/** A cursor trail scene, which also says how many marks are alive so a runner can rest. */
export interface CursorTrailScene extends AsciiScene {
readonly alive: number;
}
const CAPACITY = 600;
/** Cells of pointer travel, in cell widths, between two marks. */
const SPACING = 1;
/** Steps through the colours, head to tail: the palette holds this many blends. */
const SHADES = 12;
/**
* Glyphs shed behind the pointer that drift, slow and fade, each wearing lighter glyphs as it ages.
* Marks are shed by distance travelled, not by time, so a still pointer sheds nothing and an idle
* trail draws nothing at all.
*/
export function createCursorTrail(options: CursorTrailOptions = {}): CursorTrailScene {
const characters = options.characters?.length ? options.characters : '*+:.';
const stops = options.colors?.length ? options.colors : ['#7c5cff', '#e5489c'];
const life = clamp(options.life ?? 1.2, 0.2, 6);
const autopilot = options.autopilot ?? false;
// Blends between the stops, so the trail's colour flows rather than steps.
const shades = Array.from({ length: stops.length > 1 ? SHADES : 1 }, (_, i) => {
const t = (i / Math.max(1, SHADES - 1)) * (stops.length - 1);
const k = Math.min(stops.length - 2, Math.floor(t));
return stops.length > 1 ? mixHex(stops[k]!, stops[k + 1]!, t - k) : stops[0]!;
});
let grid: AsciiGrid = { cols: 0, rows: 0, aspect: 2 };
let time = 0;
let count = 0;
let seed = 0;
let carry = 0;
let lastActive = -10;
let prev: { x: number; y: number } | null = null;
const x = new Float32Array(CAPACITY);
const y = new Float32Array(CAPACITY);
const vx = new Float32Array(CAPACITY);
const vy = new Float32Array(CAPACITY);
const age = new Float32Array(CAPACITY);
const span = new Float32Array(CAPACITY);
const random = () => hash3(seed++, 17, 91);
/** A mark at a point, carried a little by the pointer's own motion. */
const shed = (px: number, py: number, mx: number, my: number, spread = 1) => {
if (count >= CAPACITY) return;
const i = count++;
x[i] = px + (random() - 0.5) * 0.6;
y[i] = py + (random() - 0.5) * 0.3;
const angle = random() * Math.PI * 2;
const speed = (1.2 + random() * 2.8) * spread;
// Rows are taller than columns wide, so vertical speeds are divided by the cell's aspect.
// A little of the pointer's own speed, capped, so a flick leaves a wake and not a spray.
const carried = Math.hypot(mx, my * grid.aspect);
const keep = carried > 0 ? Math.min(carried * 0.12, 5) / carried : 0;
vx[i] = mx * keep + Math.cos(angle) * speed;
vy[i] = my * keep + (Math.sin(angle) * speed) / grid.aspect;
age[i] = 0;
span[i] = life * (0.7 + random() * 0.6);
};
const ghost = (): AsciiPointer => {
const t = time * 0.8;
return {
x: grid.cols / 2 + Math.sin(t) * grid.cols * 0.32,
y: grid.rows / 2 + Math.sin(t * 2) * grid.rows * 0.24,
active: true,
};
};
return {
palette: ['ink', ...shades],
get alive() {
return count;
},
// With reduced motion a stage shows one frame: on autopilot, a moment of the loop.
settle: autopilot ? 3.2 : 0,
resize(next) {
grid = next;
prev = null;
},
step(dt, pointer) {
time += dt;
if (pointer.active) lastActive = time;
const p = pointer.active
? pointer
: autopilot && time - lastActive > 1.5 && grid.cols > 0
? ghost()
: null;
if (p) {
if (prev) {
const dx = p.x - prev.x;
const dy = p.y - prev.y;
const travel = Math.hypot(dx, dy * grid.aspect);
// A jump (the pointer coming back, or the ghost handing over) sheds nothing.
if (travel < 30) {
carry += travel / SPACING;
const marks = Math.min(6, Math.floor(carry));
carry -= marks;
const mx = dt > 0 ? dx / dt : 0;
const my = dt > 0 ? dy / dt : 0;
for (let k = 1; k <= marks; k++) {
const f = k / marks;
shed(prev.x + dx * f, prev.y + dy * f, mx, my);
}
}
}
prev = { x: p.x, y: p.y };
} else {
prev = null;
carry = 0;
}
// Drift: drag slows each mark, and a faint lift carries it upward like warm air.
const drag = Math.exp(-1.8 * dt);
for (let i = 0; i < count; i++) {
age[i]! += dt;
if (age[i]! >= span[i]!) {
count--;
x[i] = x[count]!;
y[i] = y[count]!;
vx[i] = vx[count]!;
vy[i] = vy[count]!;
age[i] = age[count]!;
span[i] = span[count]!;
i--;
continue;
}
vx[i]! *= drag;
vy[i] = vy[i]! * drag - (0.5 / grid.aspect) * dt;
x[i]! += vx[i]! * dt;
y[i]! += vy[i]! * dt;
}
},
draw(surface: GlyphSurface) {
const last = shades.length;
// In the order they were shed, so newer marks mostly sit on top. Colour follows age, so
// the trail runs through the colours from its head to its tail.
for (let i = 0; i < count; i++) {
const a = age[i]! / span[i]!;
const shade = 1 + Math.min(last - 1, Math.floor(a * last));
surface.put(x[i]!, y[i]!, ramp(characters, a), shade, Math.pow(1 - a, 1.1));
}
},
press(px, py) {
// A ring of marks from a click, opening outward and settling as drag takes hold.
const n = 16;
const turn = random() * Math.PI * 2;
for (let k = 0; k < n && count < CAPACITY; k++) {
const i = count++;
const angle = turn + (k / n) * Math.PI * 2;
const speed = 22 + random() * 4;
x[i] = px;
y[i] = py;
vx[i] = Math.cos(angle) * speed;
vy[i] = (Math.sin(angle) * speed) / grid.aspect;
age[i] = 0;
span[i] = life * (0.9 + random() * 0.3);
}
},
};
}
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/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.
Add AsciiCursorTrail once, near the root of the page. It lies over everything, fixed and click-through, and only runs while marks are alive: a still pointer costs nothing. Marks are shed by distance travelled, so a slow hand leaves a light trail and a quick one a longer wake. Set scope="parent" to keep it inside an element instead. Touch has no trail, and with reduced motion it draws nothing.
Props9
Every option.
Pass these directly to AsciiCursorTrail.
| Prop | Type | Default | What it does |
|---|---|---|---|
scope | 'window' | 'parent' | 'window' | Lay the trail over the whole page, or fill the parent element. The demo fills its parent. |
autopilot | boolean | false | While the pointer is away, an unseen pointer draws a slow loop. The demo turns it on. |
characters | string | '*+:.' | Glyphs each mark wears as it ages, newest first. |
colors | string[] | ['#7c5cff', '#e5489c'] | Colours the trail runs through from its head to its tail, as hex. |
life | number | 1.2 | Seconds a mark lasts before it fades out. |
cellSize | number | 14 | Font size of each cell in pixels. Smaller cells draw a finer picture. |
speed | number | 1 | How fast the clock runs: 0.5 is half speed, 2 is double. |
interactive | boolean | true | Follow the pointer and answer clicks. |
label | string | — | Describes the picture for screen readers. Without one it is a hidden background. |