Hover a point to read its label. Move across to lean the globe. Click to spin it.
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 { AsciiGlobe } from '@/components/lilt/ascii/live/ascii-globe';
export function Hero() {
return (
<section style={{ height: 560 }}>
<AsciiGlobe />
</section>
);
}
Installation10
Source you own.
This is source, not a package: the shadcn CLI copies it into your project with the shared pieces it needs. Its only dependency is React.
npx shadcn@latest add https://liltui.vercel.app/r/globe.jsoncomponents/lilt/ascii/live/ascii-globe.tsx
ascii-globe.tsx
'use client';
import { AsciiCanvas, useSceneProps, type SceneProps } from '../react/ascii-canvas';
import { createGlobe, describeGlobe, type GlobeOptions } from './globe';
/** A turning Earth in type, with places that pulse and arcs that travel between them. */
export function AsciiGlobe(props: SceneProps<GlobeOptions>) {
const label = props.label ?? describeGlobe(props.points, props.arcs);
return <AsciiCanvas {...useSceneProps({ ...props, label }, createGlobe)} />;
}
components/lilt/ascii/live/globe.ts
globe.ts
import { ramp } from '../engine/glyphs';
import { approach, clamp, hash3, smoothstep } from '../engine/noise';
import { DOT, type GlyphSurface } from '../engine/surface';
import type { AsciiGrid, AsciiPointer, AsciiScene } from '../engine/types';
import { INSET, full, text } from '../charts/chart-kit';
import { landAt } from './land-mask';
export interface GlobePoint {
lat: number;
lon: number;
/** A number read out with the label on hover; larger values pulse wider. */
value?: number;
label?: string;
}
export interface GlobeArc {
/** Where the arc starts and ends, as `[lat, lon]` in degrees. */
from: readonly [number, number];
to: readonly [number, number];
}
export interface GlobeOptions {
/** Places that pulse while they face you. Without any, the globe marks a handful of cities. */
points?: readonly GlobePoint[];
/** Great-circle arcs lifted above the surface, each with a bright head travelling along it. */
arcs?: readonly GlobeArc[];
/** Colour of the land. Default violet. */
color?: string;
/** Colour of the points and arcs. Default rose. */
accent?: string;
/** Turns per minute. Default 1.5. */
spin?: number;
/** How far the north pole leans toward you, in degrees. Default 20. */
tilt?: number;
/** Share of the shorter side the globe fills. Default 0.82. */
size?: number;
}
const INK = 0;
const LAND = 1;
const ACCENT = 2;
const DEEP = 3;
/** Glyphs cut into the land: a fine dot where the light is full, denser toward the night side. */
const CUT = '...::-';
const COAST = '.:';
const RAD = Math.PI / 180;
/** How much of an arc the travelling head's tail covers. */
const TAIL = 0.3;
/** A handful of cities, with a made-up count of readers in each. */
export const DEMO_POINTS: readonly GlobePoint[] = [
{ lat: 51.51, lon: -0.13, label: 'London', value: 1284 },
{ lat: 40.71, lon: -74.01, label: 'New York', value: 1610 },
{ lat: 37.77, lon: -122.42, label: 'San Francisco', value: 972 },
{ lat: -23.55, lon: -46.63, label: 'São Paulo', value: 688 },
{ lat: 6.52, lon: 3.38, label: 'Lagos', value: 412 },
{ lat: -1.29, lon: 36.82, label: 'Nairobi', value: 236 },
{ lat: 19.08, lon: 72.88, label: 'Mumbai', value: 840 },
{ lat: 1.35, lon: 103.82, label: 'Singapore', value: 534 },
{ lat: 35.68, lon: 139.69, label: 'Tokyo', value: 1122 },
{ lat: -33.87, lon: 151.21, label: 'Sydney', value: 395 },
];
export const DEMO_ARCS: readonly GlobeArc[] = [
{ from: [51.51, -0.13], to: [40.71, -74.01] },
{ from: [40.71, -74.01], to: [-23.55, -46.63] },
{ from: [51.51, -0.13], to: [19.08, 72.88] },
{ from: [19.08, 72.88], to: [1.35, 103.82] },
{ from: [1.35, 103.82], to: [-33.87, 151.21] },
{ from: [37.77, -122.42], to: [35.68, 139.69] },
{ from: [51.51, -0.13], to: [6.52, 3.38] },
];
/** A unit vector for a latitude and longitude, y up through the north pole. */
function toVector(lat: number, lon: number): [number, number, number] {
const cl = Math.cos(lat * RAD);
return [cl * Math.sin(lon * RAD), Math.sin(lat * RAD), cl * Math.cos(lon * RAD)];
}
/** A one-line description of the globe's data for screen readers. */
export function describeGlobe(points?: readonly GlobePoint[], arcs?: readonly GlobeArc[]) {
const list = points ?? (arcs ? [] : DEMO_POINTS);
const routes = arcs ?? (points ? [] : DEMO_ARCS);
const named = list.filter((p) => p.label).map((p) => p.label);
const places = named.length
? `${list.length} places marked: ${named.join(', ')}`
: `${list.length} places marked`;
const lines = routes.length ? `, and ${routes.length} routes between them` : '';
return `A turning globe with ${places}${lines}.`;
}
/**
* A turning Earth drawn in type. Each cell is projected onto the sphere and looked up in a land
* mask: land is solid lit blocks with glyphs cut where the light falls away, the sea a sparse
* lattice of faint dots, and a thin atmosphere glows at the edge. Points pulse while they face
* you and arcs rise between them with a bright head travelling along each. Hovering a point reads
* out its label, the pointer leans the globe, and a click spins it.
*/
export function createGlobe(options: GlobeOptions = {}): AsciiScene {
const points = options.points ?? (options.arcs ? [] : DEMO_POINTS);
const arcs = options.arcs ?? (options.points ? [] : DEMO_ARCS);
const spin = ((options.spin ?? 1.5) * Math.PI * 2) / 60;
const tilt = (options.tilt ?? 20) * RAD;
const size = clamp(options.size ?? 0.82, 0.2, 1);
const cosT = Math.cos(tilt);
const sinT = Math.sin(tilt);
const maxValue = Math.max(1, ...points.map((p) => p.value ?? 0));
const pointVectors = points.map((p) => toVector(p.lat, p.lon));
// Each arc as samples along its great circle, already lifted off the surface.
const SAMPLES = 120;
const arcPaths = arcs.map((arc) => {
const a = toVector(arc.from[0], arc.from[1]);
const b = toVector(arc.to[0], arc.to[1]);
const dot = clamp(a[0] * b[0] + a[1] * b[1] + a[2] * b[2], -1, 1);
const angle = Math.acos(dot);
const lift = 0.08 + 0.3 * (angle / Math.PI);
const path = new Float32Array((SAMPLES + 1) * 3);
for (let i = 0; i <= SAMPLES; i++) {
const t = i / SAMPLES;
const s = Math.sin(angle) || 1;
const wa = angle < 1e-4 ? 1 - t : Math.sin((1 - t) * angle) / s;
const wb = angle < 1e-4 ? t : Math.sin(t * angle) / s;
const h = 1 + lift * Math.sin(Math.PI * t);
path[i * 3] = (a[0] * wa + b[0] * wb) * h;
path[i * 3 + 1] = (a[1] * wa + b[1] * wb) * h;
path[i * 3 + 2] = (a[2] * wa + b[2] * wb) * h;
}
return path;
});
let grid: AsciiGrid = { cols: 0, rows: 0, aspect: 2 };
let time = 0;
// Start with the Atlantic facing, Europe and Africa to the right of it.
let turn = 20 * RAD;
let push = 0;
let lean = 0;
let pace = 1;
let pointer: AsciiPointer = { x: 0, y: 0, active: false };
let hovered = -1;
// The disc on screen, in square units: its centre and radius.
let cx = 0;
let cy = 0;
let radius = 1;
/** A point on or above the sphere, turned and tilted into view: x right, y up, z toward you. */
function view(x: number, y: number, z: number, out: number[]) {
const r = turn + lean;
const c = Math.cos(r);
const s = Math.sin(r);
// Turning the globe east brings longitudes from the right.
const vx = x * c - z * s;
const vz = x * s + z * c;
out[0] = vx;
out[1] = y * cosT - vz * sinT;
out[2] = y * sinT + vz * cosT;
}
function layout() {
const { cols, rows, aspect } = grid;
const top = (INSET.top + 2) * aspect;
const bottom = (rows - INSET.bottom) * aspect;
radius = (Math.min(cols - INSET.x * 2, bottom - top) * size) / 2;
cx = cols / 2;
cy = (top + bottom) / 2;
}
const v: number[] = [0, 0, 0];
return {
palette: ['ink', options.color ?? '#8b6cff', options.accent ?? '#e5489c', '#0c0a14'],
lineHeight: 1.1,
settle: 1,
resize(next) {
grid = next;
layout();
},
step(dt, next) {
time += dt;
pointer = next;
push = approach(push, 0, 1.2, dt);
// Slow almost to a stop while a point is read, so its label holds still.
pace = approach(pace, hovered >= 0 ? 0.08 : 1, 4, dt);
// The Earth turns west to east: the longitude facing you falls as the day goes on.
turn -= (spin * pace + push) * dt;
const target = pointer.active ? clamp((pointer.x - cx) / Math.max(1, radius * 2), -1, 1) : 0;
lean = approach(lean, target * 0.6, 2, dt);
},
press() {
push += 3;
},
draw(surface: GlyphSurface) {
const { cols, rows, aspect } = grid;
if (cols < 12 || rows < 6) return;
const r = turn + lean;
const cr = Math.cos(r);
const sr = Math.sin(r);
// Light from the upper left, a little in front.
const lx = -0.55;
const ly = 0.5;
const lz = 0.67;
const r0 = Math.max(0, Math.floor((cy - radius * 1.15) / aspect));
const r1 = Math.min(rows - 1, Math.ceil((cy + radius * 1.15) / aspect));
const c0 = Math.max(0, Math.floor(cx - radius * 1.15));
const c1 = Math.min(cols - 1, Math.ceil(cx + radius * 1.15));
for (let row = r0; row <= r1; row++) {
for (let col = c0; col <= c1; col++) {
const sx = (col + 0.5 - cx) / radius;
const sy = -((row + 0.5) * aspect - cy) / radius;
const d2 = sx * sx + sy * sy;
if (d2 >= 1) {
// The atmosphere: a thin glow round the edge, brighter on the lit side.
const d = Math.sqrt(d2);
const reach = 0.12;
if (d < 1 + reach) {
const lit = clamp((sx * lx + sy * ly) / d + 0.45, 0, 1);
const glow = Math.pow(1 - (d - 1) / reach, 1.5) * (0.25 + 0.75 * lit);
if (glow > 0.08) surface.put(col, row, DOT, LAND, 0.15 + glow * 0.75);
}
continue;
}
const sz = Math.sqrt(1 - d2);
// Undo the tilt, then the turn, to find the point on the globe.
const y = sy * cosT + sz * sinT;
const vz = -sy * sinT + sz * cosT;
const x = sx * cr + vz * sr;
const z = -sx * sr + vz * cr;
const lat = Math.asin(clamp(y, -1, 1)) / RAD;
const lon = Math.atan2(x, z) / RAD;
const lambert = sx * lx + sy * ly + sz * lz;
// A soft terminator; the night side keeps a little light so the disc stays whole.
const light = 0.1 + 0.9 * smoothstep(-0.3, 0.75, lambert);
// The edge of the disc catches the atmosphere.
const rim = Math.pow(1 - sz, 3);
const land = landAt(lat, lon);
if (land > 0.6) {
const body = 0.14 + 0.78 * light;
surface.fill(col, row, LAND, body);
// The cut fades with its block, so the night side stays quiet on a light page too.
surface.put(col, row, ramp(CUT, 1 - light), DEEP, 0.55 * body);
continue;
}
if (land > 0.3) {
surface.put(col, row, ramp(COAST, (land - 0.3) / 0.3), LAND, 0.25 + 0.7 * light);
continue;
}
// The sea: an even field of faint dots, shaded like the land so the ball reads round.
if (col % 2) continue;
surface.put(col, row, DOT, rim > 0.3 ? LAND : INK, 0.05 + 0.22 * light + rim * 0.4);
}
}
// Arcs: a faint dotted path, and a bright head trailing a tail of fading blocks.
arcPaths.forEach((path, k) => {
const period = 4.6;
const u = (((time + k * 1.37) % period) / period) * 1.5;
let lastCol = -1;
let lastRow = -1;
for (let i = 0; i <= SAMPLES; i++) {
view(path[i * 3]!, path[i * 3 + 1]!, path[i * 3 + 2]!, v);
const behind = v[2]! < 0 && v[0]! * v[0]! + v[1]! * v[1]! < 1;
if (behind) continue;
const col = Math.floor(cx + v[0]! * radius);
const row = Math.floor((cy - v[1]! * radius) / aspect);
if (col === lastCol && row === lastRow) continue;
lastCol = col;
lastRow = row;
// Seen against the night side or the sea, the path fades a little with depth.
const depth = 0.6 + 0.4 * clamp(v[2]! + 0.4, 0, 1);
const tail = u - i / SAMPLES;
if (u <= 1.02 && tail >= 0 && tail < TAIL) {
const glow = 1 - tail / TAIL;
surface.fill(col, row, ACCENT, (0.55 + 0.45 * glow * glow) * depth);
continue;
}
surface.put(col, row, DOT, ACCENT, 0.7 * depth);
}
});
// Points: a bright marker and a ring that spreads across the surface around it.
let nearest = -1;
let nearestD = 3;
pointVectors.forEach((p, i) => {
view(p[0], p[1], p[2], v);
if (v[2]! < 0.08) return;
const fade = smoothstep(0.08, 0.3, v[2]!);
const col = Math.floor(cx + v[0]! * radius);
const row = Math.floor((cy - v[1]! * radius) / aspect);
const strength = (points[i]!.value ?? maxValue * 0.5) / maxValue;
const phase = (time * 0.5 + hash3(i, 3, 1)) % 1;
const angle = (0.03 + 0.07 * Math.sqrt(strength)) * (0.15 + 0.85 * phase) * Math.PI;
// The ring, foreshortened by the sphere: sample around the point on the surface.
const [px, py, pz] = p;
const ex = Math.hypot(pz, px) > 1e-6 ? [pz, 0, -px] : [1, 0, 0];
const el = Math.hypot(ex[0]!, ex[2]!) || 1;
const e1 = [ex[0]! / el, 0, ex[2]! / el];
const e2 = [py * e1[2]! - pz * 0, pz * e1[0]! - px * e1[2]!, px * 0 - py * e1[0]!];
const steps = 28;
for (let s = 0; s < steps; s++) {
const a = (s / steps) * Math.PI * 2;
const ca = Math.cos(angle);
const sa = Math.sin(angle);
const qx = px * ca + (e1[0]! * Math.cos(a) + e2[0]! * Math.sin(a)) * sa;
const qy = py * ca + (e1[1]! * Math.cos(a) + e2[1]! * Math.sin(a)) * sa;
const qz = pz * ca + (e1[2]! * Math.cos(a) + e2[2]! * Math.sin(a)) * sa;
view(qx, qy, qz, v);
if (v[2]! < 0) continue;
const rc = Math.floor(cx + v[0]! * radius);
const rr = Math.floor((cy - v[1]! * radius) / aspect);
if (rc === col && rr === row) continue;
surface.put(rc, rr, DOT, ACCENT, (0.25 + 0.75 * (1 - phase)) * fade);
}
surface.fill(col, row, ACCENT, fade);
surface.put(col, row, DOT, DEEP, 0.6 * fade);
if (pointer.active && v[2]! > 0.2) {
const d = Math.hypot(pointer.x - (col + 0.5), (pointer.y - (row + 0.5)) * aspect);
if (d < nearestD) {
nearestD = d;
nearest = i;
}
}
});
hovered = nearest;
if (nearest >= 0) {
const p = points[nearest]!;
view(pointVectors[nearest]![0], pointVectors[nearest]![1], pointVectors[nearest]![2], v);
const col = Math.floor(cx + v[0]! * radius);
const row = Math.floor((cy - v[1]! * radius) / aspect);
// A bracket round the point, and a readout above the globe.
surface.put(col - 1, row, '[', INK, 0.9);
surface.put(col + 1, row, ']', INK, 0.9);
const name = p.label ?? `${p.lat.toFixed(1)}, ${p.lon.toFixed(1)}`;
const value = p.value !== undefined ? full(p.value) : '';
const readout = value ? `${name} ${value}` : name;
const at = clamp(
col - Math.floor(readout.length / 2),
INSET.x,
cols - INSET.x - readout.length,
);
text(surface, at, INSET.top, name, INK, 0.75);
if (value) text(surface, at + readout.length - value.length, INSET.top, value, ACCENT, 1);
}
},
};
}
components/lilt/ascii/live/land-mask.ts
land-mask.ts
/**
* Where the land is, for the globe: a 360 by 180 grid of one-degree cells, row 0 at 90° north and
* column 0 at 180° west. Rasterised once from Natural Earth's 1:110m land polygons (public domain,
* naturalearthdata.com), sampling nine points a cell and keeping the majority.
*
* Encoded as alternating runs of sea and land, read row by row from the first sea cell. Each run is
* a number in base 32, most significant digit first, written in the base64 alphabet: a character
* at or past index 32 carries five bits and says another follows; one below 32 ends the number.
*/
const RUNS = [
'indMpNCBURYpDZEhIBIoVIBDBNDhThDCBDWChLGlHVIhPeIBFiEHkbFBDDECLDhVhAHiRFkICFBXKIhThBEEBiQCkFEIBIDC',
'FCKJhRiWDhBLkDLFDCCBMWhHiNGbYXIjGBWGBBZhFiLEbYjeIKBEDCFCCDCBDWhDiLDYhGFDjMQBDEEBCEJBEVhAiLENDJhQ',
'LFhDBhXDCOFDBDDQBBRhBiKEMEChXDBCCBNhQKhDNHEDUPdBBhPGhFGBiVhGYEPDPDDBEFFEKNCBbhKPcDDGBieCICBNhTHD',
'HCCGCEHHQYhMWOCDKCECjNMiMBGECCJKVhPbDCCZCjSGBCiPJMJShQVBGDcBjLBHFiQBBLGDCKNRJaKDKFkMGBIBDiJCEEMO',
'LSIaKDLCkNViGFCCBJHOKhSLCkdQiJICEBHDRHhRMDkePiIQGXGhQMEkICDCJWRChUQIYDhQNEkFHJbJCBKhNRJDCiFNHCBj',
'ZCEFDhHEQhNPKBEhaCJDCGHjVSDhICCBThJQPhYEOFFBBjURGhFCZhNLQhXDLDBEFjVSHhCCdhOIShXDKCBDHjTTHiDhRDWh',
'QDCDKBGDBjVTFiCBDhPDXhPDDDHkGBBNEiIhODXhPCCGDkLNCiKhQBXhUFDkJBBOBiKiECChTCEkMBCiZCBhZJDhWkNCCibB',
'BhWBDGGhRkQCBidhbJBBBhSkODBidhchehBBDDMDiVECichfhcfDCCLFiUjDhYCChfNDOJJEiVGBidhWheDDJDDDMMIDiUGE',
'ibhVheMIDEKNHFiOJEichVheLKEDJEFEIFiMKBifhSiBJICFDBFCBCVDiEBHLCiehSiBJIBHBDDEWEiCCCCDMCifhQiCJVDD',
'WFiAHDMBjAhPiDIOCGCEXEiBBCEDJDjBhOiGBGKLBGCBCCiVFDHFjChNiGBDNZiUGDEIjDhLiGRaiULGjJhHiHTYiWJEjNhF',
'iHYGCMiWJCjPCBhBiHaEHDBDiYIBjRBChAiHdBjFjcBCREBHCiHhaCiIjcBBQNCiGhbDiHjcCBOODiDhPCNEiEjeBCNPCiCh',
'QCOHhfkABCMQBiBhSCPHhckBCCKiThSCODDKhUCBkDJiShUDUJhRDBkFIOBBDhfhUDVJWBXFBkGISChchWCULRFQBCkPJHDJ',
'DhahWDSPOGOjBBhSJFDPDhWhVERPMJMDCkRJCFPECBhShWDQQLKMDBkVNiIhXDNSKLNNCkLLiIhXEKUJMOMCkRJiDhZDJWGS',
'LLCkSJiChaCGZGSLMBkUGiDhbBEcFSLNCkVEiChchAFSCCHlFCLBCBhVhbGCZETBDGNBCBkUDHKCBBBhOhbBGZEYDQBkYBDB',
'DEBKhPiBZDBBRBGBlLDCShPhfbBCBRCYCkZBCThOhfeCRBWBBDkcThPhcfBTCOCGBkeYhLKFhMhTDNDlEZhMBNhKhQCDCLEl',
'FahchGhSCCCKElFbhdhEhUCCCHHlDdhbhEhWDBBFJlCehbhChYEGJCEkcfhahBhaEFIPBkShEhWhBhbDGHCDJDkShFhVfhcF',
'EHCDKCCEkMhJhSdheEICDBBBEBGKkIhLhRciADQBNJkGhOhPbiBChAIECjfhOhPbiDDdKHBjchNhQaiEGZJkGhMhQaiLBCBC',
'BFBNDDCkFhLhRbiUBWCkFhKhRbnThIhTajGBkMhHhTcIBiRGFBkNhFhUcHCiQGGCkMhFhTdHCiMCCGGDkMhEhTcHDiKMGDkO',
'hChTcFFiKODFhBBjMhBhTaGFiJSBFkQehUYIFiJYkQehVWJFiIakPehVWJFiFfPBjddhXVJEiDhCQBjcchYWHFiChEkMZhbW',
'IEiChFkKYheUJDiChHkJXhfSiRhHkIWiASiRhHkIWiASiRhHkIWiBQiThHkHViDOiUhGkHWiDOiUhGkHViFMiWhFkITiGLiX',
'KISkITiHJiYJLCBNkJOBDiJCifDSOkIQmELXBjRQmFKYBjPRmFKZBjPOmKBBCcDjNLnMDjNMnNCjNJmSDYCBBjOKmRDXDjRI',
'mTBXDjRJnJDjSInKEjSInLCjTJqeJqfIkJBmXGrCGIDqYFrDGrEGrFBi6JB2JCrEDjTGhMEGEPGkcDjRMWiAkSDjMaKiHkKC',
'CFifGCdIiRkCDBGiEECKChMFiYjcHBGhSCBiMEjDiXChAHhQlYiDBSFDKEDFMhNlZhXKBDCHBBKhGhPlWhQiRhOlXhSiMhKm',
'AhGiThLmEhBCEiPdFImKhACLiIaINlfhUiKIFGIQlehNiaYmKhOieEmbhLqCLNUqFCfBh3I',
].join('');
export const MASK_WIDTH = 360;
export const MASK_HEIGHT = 180;
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
let mask: Uint8Array | null = null;
/** The land mask, one byte a cell, 1 for land. Decoded once, on first use. */
export function landMask(): Uint8Array {
if (mask) return mask;
const out = new Uint8Array(MASK_WIDTH * MASK_HEIGHT);
let at = 0;
let land = 0;
let value = 0;
for (let i = 0; i < RUNS.length; i++) {
const digit = ALPHABET.indexOf(RUNS[i]!);
value = value * 32 + (digit & 31);
if (digit >= 32) continue;
if (land) out.fill(1, at, at + value);
at += value;
land ^= 1;
value = 0;
}
mask = out;
return out;
}
/**
* How much land is at a latitude and longitude in degrees, from 0 to 1, blended between the four
* nearest cells so coastlines come out soft rather than stepped.
*/
export function landAt(lat: number, lon: number): number {
const m = landMask();
const x = ((((lon + 180) % 360) + 360) % 360) - 0.5;
const y = Math.min(MASK_HEIGHT - 1, Math.max(0, 90 - lat - 0.5));
const x0 = Math.floor(x);
const y0 = Math.floor(y);
const fx = x - x0;
const fy = y - y0;
const c0 = (x0 + MASK_WIDTH) % MASK_WIDTH;
const c1 = (x0 + 1) % MASK_WIDTH;
const r1 = Math.min(MASK_HEIGHT - 1, y0 + 1);
const a = m[y0 * MASK_WIDTH + c0]! + (m[y0 * MASK_WIDTH + c1]! - m[y0 * MASK_WIDTH + c0]!) * fx;
const b = m[r1 * MASK_WIDTH + c0]! + (m[r1 * MASK_WIDTH + c1]! - m[r1 * MASK_WIDTH + c0]!) * fx;
return a + (b - a) * fy;
}
components/lilt/ascii/engine/stage.tsascii-canvas
stage.ts
import { GlyphSurface, LEVELS } from './surface';
import type { AsciiPointer, AsciiScene } from './types';
const STEP = 1 / 60;
const MAX_STEPS = 8;
const FALLBACK_FONT = 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace';
export interface AsciiStageOptions {
/** Font size of each cell in CSS pixels. Smaller cells give finer pictures. Default 14. */
cellSize?: number;
/** Follow the pointer and answer clicks. Default true. */
interactive?: boolean;
/** How fast the scene's clock runs: 0.5 is half speed, 2 is double. Default 1. */
speed?: number;
}
/**
* Runs a scene on a canvas: a fixed-step clock, resizing, pointer input, pausing while off screen
* or in a hidden tab, a single still frame for reduced motion, and repainting when the font or the
* page theme changes. The canvas's CSS `font-family` and `color` set the type and the ink.
*/
export class AsciiStage {
private ctx: CanvasRenderingContext2D;
private surface = new GlyphSurface();
private styles: string[] = [];
private pointer: AsciiPointer = { x: 0, y: 0, active: false };
private cellSize: number;
private interactive: boolean;
private speed: number;
private font = '';
private cw = 8;
/** Whether every glyph advances one cell, so rows can be painted as strings. */
private mono = true;
private ch = 18;
private raf = 0;
private last = 0;
private acc = 0;
private time = 0;
private onScreen = true;
private disposed = false;
private reducedMotion: MediaQueryList;
private resizeObserver: ResizeObserver;
/** The grid the scene was last sized to. */
private grid = '';
private intersectionObserver: IntersectionObserver;
private themeObserver: MutationObserver;
constructor(
private canvas: HTMLCanvasElement,
private scene: AsciiScene,
options: AsciiStageOptions = {},
) {
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('AsciiStage needs a 2D canvas context.');
this.ctx = ctx;
this.cellSize = options.cellSize ?? 14;
this.interactive = options.interactive ?? true;
this.speed = options.speed ?? 1;
this.reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
this.resizeObserver = new ResizeObserver(() => this.resize());
this.resizeObserver.observe(canvas);
this.intersectionObserver = new IntersectionObserver(([entry]) => {
this.onScreen = entry?.isIntersecting ?? true;
this.schedule();
});
this.intersectionObserver.observe(canvas);
// Theme switches usually flip a class or attribute on the root; the ink follows.
this.themeObserver = new MutationObserver(() => this.restyle());
this.themeObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class', 'style', 'data-theme'],
});
this.reducedMotion.addEventListener('change', this.schedule);
document.addEventListener('visibilitychange', this.schedule);
window.addEventListener('pointermove', this.onPointerMove, { passive: true });
window.addEventListener('pointerdown', this.onPointerDown, { passive: true });
document.documentElement.addEventListener('pointerleave', this.onPointerLeave);
window.addEventListener('blur', this.onPointerLeave);
this.resize();
// Canvas text never asks for a webfont, so measure again once the page's fonts arrive.
document.fonts?.ready.then(() => {
if (this.disposed) return;
this.resize();
});
this.schedule();
}
destroy() {
this.disposed = true;
cancelAnimationFrame(this.raf);
this.resizeObserver.disconnect();
this.intersectionObserver.disconnect();
this.themeObserver.disconnect();
this.reducedMotion.removeEventListener('change', this.schedule);
document.removeEventListener('visibilitychange', this.schedule);
window.removeEventListener('pointermove', this.onPointerMove);
window.removeEventListener('pointerdown', this.onPointerDown);
document.documentElement.removeEventListener('pointerleave', this.onPointerLeave);
window.removeEventListener('blur', this.onPointerLeave);
}
/** Changes the stage's options in place, keeping the scene's world as it is. */
configure(options: AsciiStageOptions) {
this.speed = options.speed ?? this.speed;
if (options.interactive !== undefined) {
this.interactive = options.interactive;
if (!this.interactive) this.pointer.active = false;
}
if (options.cellSize !== undefined && options.cellSize !== this.cellSize) {
this.cellSize = options.cellSize;
this.resize();
}
}
/** Reads the canvas's `color` again, after the ink was changed by something other than a theme. */
refresh() {
this.restyle();
}
private get still() {
return this.reducedMotion.matches;
}
private resize() {
const rect = this.canvas.getBoundingClientRect();
if (rect.width < 1 || rect.height < 1) return;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
this.canvas.width = Math.round(rect.width * dpr);
this.canvas.height = Math.round(rect.height * dpr);
const family = getComputedStyle(this.canvas).fontFamily || FALLBACK_FONT;
this.font = `500 ${this.cellSize}px ${family}, ${FALLBACK_FONT}`;
const { ctx } = this;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.font = this.font;
this.cw = Math.max(4, ctx.measureText('M').width);
this.mono = Math.abs(ctx.measureText('i').width - this.cw) < 0.01;
this.ch = Math.round(this.cellSize * (this.scene.lineHeight ?? 1.25));
const cols = Math.ceil(rect.width / this.cw);
const rows = Math.ceil(rect.height / this.ch);
this.surface.resize(cols, rows);
// Fonts arriving or a pixel of layout can measure the same grid again; the scene keeps its world.
const grid = `${cols}x${rows}x${this.ch / this.cw}`;
if (grid !== this.grid) {
this.grid = grid;
this.scene.resize({ cols, rows, aspect: this.ch / this.cw });
}
this.restyle();
}
/** Resolves the palette to fill styles, one per colour and opacity step. */
private restyle() {
const { ctx } = this;
const ink = getComputedStyle(this.canvas).color;
this.styles = this.scene.palette.flatMap((colour) => {
ctx.fillStyle = '#000';
ctx.fillStyle = colour === 'ink' ? ink : colour;
const [r, g, b] = parseColour(String(ctx.fillStyle));
return Array.from({ length: LEVELS }, (_, i) => `rgba(${r},${g},${b},${(i + 1) / LEVELS})`);
});
if (this.still) this.drawStill();
}
private schedule = () => {
cancelAnimationFrame(this.raf);
if (this.disposed) return;
if (this.still) {
this.drawStill();
return;
}
if (!this.onScreen || document.hidden) return;
this.last = performance.now();
this.raf = requestAnimationFrame(this.frame);
};
private frame = (now: number) => {
const dt = Math.min(0.1, (now - this.last) / 1000) * this.speed;
this.last = now;
this.acc += dt;
let steps = 0;
while (this.acc >= STEP && steps < MAX_STEPS) {
this.scene.step(STEP, this.pointer);
this.time += STEP;
this.acc -= STEP;
steps++;
}
if (steps === MAX_STEPS) this.acc = 0;
this.paint();
this.raf = requestAnimationFrame(this.frame);
};
/** Lets the scene settle without the pointer, then shows that one frame. */
private drawStill() {
const settle = this.scene.settle ?? 3;
const idle: AsciiPointer = { x: 0, y: 0, active: false };
while (this.time < settle) {
this.scene.step(STEP, idle);
this.time += STEP;
}
this.paint();
}
private paint() {
const { ctx, canvas, surface } = this;
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.restore();
ctx.font = this.font;
ctx.textBaseline = 'middle';
surface.clear();
this.scene.draw(surface);
surface.paint(ctx, this.styles, this.cw, this.ch, this.mono);
}
private toCells(e: PointerEvent) {
const rect = this.canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const inside = x >= 0 && y >= 0 && x <= rect.width && y <= rect.height;
return { x: x / this.cw, y: y / this.ch, inside };
}
private onPointerMove = (e: PointerEvent) => {
if (!this.interactive) return;
const { x, y, inside } = this.toCells(e);
this.pointer.x = x;
this.pointer.y = y;
// A finger has no hover; it only presses.
this.pointer.active = inside && e.pointerType !== 'touch';
};
private onPointerDown = (e: PointerEvent) => {
const { x, y, inside } = this.toCells(e);
if (!inside || this.still || !this.interactive) return;
this.scene.press?.(x, y);
};
private onPointerLeave = () => {
this.pointer.active = false;
};
}
/** Reads the `#rrggbb` or `rgba(r, g, b, a)` a canvas reports back for any CSS colour. */
function parseColour(value: string): [number, number, number] {
if (value.startsWith('#')) {
const n = parseInt(value.slice(1, 7), 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
const parts = value.match(/[\d.]+/g)?.map(Number) ?? [];
return [parts[0] ?? 0, parts[1] ?? 0, parts[2] ?? 0];
}
components/lilt/ascii/react/ascii-canvas.tsxascii-canvas
ascii-canvas.tsx
'use client';
import { useEffect, useRef, type CSSProperties } from 'react';
import { AsciiStage } from '../engine/stage';
import type { AsciiScene } from '../engine/types';
export interface AsciiCanvasProps {
/** Builds the scene. Called again only when `sceneKey` changes. */
scene: () => AsciiScene;
/** Changes when the scene should be rebuilt, such as a JSON string of its options. */
sceneKey?: string;
/** Font size of each cell in CSS pixels. Default 14. */
cellSize?: number;
/** Follow the pointer and answer clicks. Default true. */
interactive?: boolean;
/** How fast the scene's clock runs: 0.5 is half speed, 2 is double. Default 1. */
speed?: number;
/**
* Describes the picture for screen readers. Without one the canvas is decorative and hidden
* from assistive technology, which suits a background.
*/
label?: string;
className?: string;
style?: CSSProperties;
}
/**
* A canvas that runs an ASCII scene. It fills its parent; give the parent a size. Set the type
* with CSS `font-family` (a monospace face) and the ink with `color`.
*/
export function AsciiCanvas({
scene,
sceneKey,
cellSize,
interactive,
speed,
label,
className,
style,
}: AsciiCanvasProps) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const stageRef = useRef<AsciiStage | null>(null);
const latest = useRef({ scene, cellSize, interactive, speed });
latest.current = { scene, cellSize, interactive, speed };
// A new scene starts a new world; everything else is tuned on the running stage.
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const { scene: build, ...options } = latest.current;
const stage = new AsciiStage(canvas, build(), options);
stageRef.current = stage;
return () => {
stage.destroy();
stageRef.current = null;
};
}, [sceneKey]);
useEffect(() => {
stageRef.current?.configure({ cellSize, interactive, speed });
}, [cellSize, interactive, speed]);
const ink = style?.color;
useEffect(() => {
stageRef.current?.refresh();
}, [ink]);
return (
<canvas
ref={canvasRef}
className={className ? `lilt-ascii ${className}` : 'lilt-ascii'}
style={{ display: 'block', width: '100%', height: '100%', ...style }}
{...(label ? { role: 'img', 'aria-label': label } : { 'aria-hidden': true })}
/>
);
}
export type SceneProps<Options> = Options & Omit<AsciiCanvasProps, 'scene' | 'sceneKey'>;
/** Splits a scene's own options from the canvas props. */
export function useSceneProps<Options extends object>(
props: SceneProps<Options>,
create: (options: Options) => AsciiScene,
): AsciiCanvasProps {
const { cellSize, interactive, speed, label, className, style, ...options } = props;
return {
scene: () => create(options as Options),
sceneKey: JSON.stringify(options),
cellSize,
interactive,
speed,
label,
className,
style,
};
}
components/lilt/ascii/engine/noise.tsascii-engine
noise.ts
/** A stable pseudo-random number in [0, 1) for an integer lattice point. */
export function hash3(x: number, y: number, z: number): number {
let h =
Math.imul(x | 0, 0x27d4eb2d) ^ Math.imul(y | 0, 0x165667b1) ^ Math.imul(z | 0, 0x9e3779b1);
h = Math.imul(h ^ (h >>> 15), 0x85ebca6b);
h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35);
return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
}
const fade = (t: number) => t * t * (3 - 2 * t);
const mix = (a: number, b: number, t: number) => a + (b - a) * t;
/** Smooth value noise in [0, 1). */
export function noise3(x: number, y: number, z: number): number {
const xi = Math.floor(x);
const yi = Math.floor(y);
const zi = Math.floor(z);
const u = fade(x - xi);
const v = fade(y - yi);
const w = fade(z - zi);
const a = mix(hash3(xi, yi, zi), hash3(xi + 1, yi, zi), u);
const b = mix(hash3(xi, yi + 1, zi), hash3(xi + 1, yi + 1, zi), u);
const c = mix(hash3(xi, yi, zi + 1), hash3(xi + 1, yi, zi + 1), u);
const d = mix(hash3(xi, yi + 1, zi + 1), hash3(xi + 1, yi + 1, zi + 1), u);
return mix(mix(a, b, v), mix(c, d, v), w);
}
/** Layered noise in [0, 1): each octave doubles the detail and halves the weight. */
export function fbm3(x: number, y: number, z: number, octaves = 4): number {
let sum = 0;
let weight = 0.5;
let total = 0;
for (let i = 0; i < octaves; i++) {
sum += noise3(x, y, z) * weight;
total += weight;
weight *= 0.5;
x *= 2.03;
y *= 2.03;
z *= 2.03;
}
return sum / total;
}
export const clamp = (value: number, min: number, max: number) =>
value < min ? min : value > max ? max : value;
export const smoothstep = (edge0: number, edge1: number, x: number) => {
const t = clamp((x - edge0) / (edge1 - edge0), 0, 1);
return t * t * (3 - 2 * t);
};
/** Frame-rate independent easing toward a target: `rate` is the share closed per second. */
export const approach = (current: number, target: number, rate: number, dt: number) =>
target + (current - target) * Math.exp(-rate * dt);
components/lilt/ascii/engine/glyphs.tsascii-engine
glyphs.ts
import { clamp } from './noise';
/** The glyph a share of the way along a ramp of glyphs, sparse to dense. */
export function ramp(glyphs: string, value: number): string {
return glyphs[clamp(Math.floor(value * glyphs.length), 0, glyphs.length - 1)]!;
}
/**
* The stroke that best follows a direction on screen. `dx` and `dy` are in square units (cell
* widths), y down. Used for tentacles, grass and anything else drawn as a line of type.
*/
export function stroke(dx: number, dy: number): string {
const angle = Math.atan2(dy, dx);
// Fold to [0, π): a stroke has no direction.
const a = angle < 0 ? angle + Math.PI : angle;
if (a < Math.PI / 8 || a >= (Math.PI * 7) / 8) return '-';
if (a < (Math.PI * 3) / 8) return '\\';
if (a < (Math.PI * 5) / 8) return '|';
return '/';
}
components/lilt/ascii/engine/surface.tsascii-engine
surface.ts
/** Opacity steps per colour. Cells sharing a colour and step are painted with one fill style. */
export const LEVELS = 8;
/** A glyph code for a small solid square: crisper than a full stop at every font size. */
export const DOT = 1;
/**
* One frame of type: a glyph, colour and opacity per cell, and optionally a solid block behind it.
* Scenes write into it; the stage paints it in batches, one fill style per colour and opacity, so a
* full screen costs a few dozen style changes rather than thousands.
*/
export class GlyphSurface {
cols = 0;
rows = 0;
glyph = new Uint16Array(0);
tone = new Uint8Array(0);
level = new Uint8Array(0);
/** The block behind each cell: its colour, and its opacity step, 0 for none. */
blockTone = new Uint8Array(0);
blockLevel = new Uint8Array(0);
private order = new Int32Array(0);
private counts = new Int32Array(0);
private starts = new Int32Array(0);
resize(cols: number, rows: number) {
this.cols = cols;
this.rows = rows;
const size = cols * rows;
this.glyph = new Uint16Array(size);
this.tone = new Uint8Array(size);
this.level = new Uint8Array(size);
this.blockTone = new Uint8Array(size);
this.blockLevel = new Uint8Array(size);
this.order = new Int32Array(size);
}
clear() {
this.glyph.fill(0);
this.blockLevel.fill(0);
}
/**
* Writes a glyph; later writes replace earlier ones, so draw back to front. `glyph` is a
* character, a char code, or `DOT`. Opacity at or below zero leaves the cell untouched.
*/
put(col: number, row: number, glyph: string | number, tone: number, opacity = 1) {
col = Math.floor(col);
row = Math.floor(row);
if (col < 0 || row < 0 || col >= this.cols || row >= this.rows || opacity <= 0) return;
const i = row * this.cols + col;
this.glyph[i] = typeof glyph === 'number' ? glyph : glyph.charCodeAt(0);
this.tone[i] = tone;
this.level[i] = Math.min(LEVELS, Math.ceil(opacity * LEVELS));
}
/**
* Fills a cell with a solid block of colour, painted behind its glyph. Solid shapes read as one
* mass this way, with a glyph cut into each block, the way a mosaic does. Opacity at or below
* zero removes the block.
*/
fill(col: number, row: number, tone: number, opacity = 1) {
col = Math.floor(col);
row = Math.floor(row);
if (col < 0 || row < 0 || col >= this.cols || row >= this.rows) return;
const i = row * this.cols + col;
this.blockTone[i] = tone;
this.blockLevel[i] = opacity <= 0 ? 0 : Math.min(LEVELS, Math.ceil(opacity * LEVELS));
}
/** True when a cell already holds a glyph or a block this frame. */
filled(col: number, row: number) {
col = Math.floor(col);
row = Math.floor(row);
if (col < 0 || row < 0 || col >= this.cols || row >= this.rows) return false;
const i = row * this.cols + col;
return this.glyph[i] !== 0 || this.blockLevel[i] !== 0;
}
/**
* Sorts cells into buckets of one fill style each, by counting: `bucketOf` gives a cell's bucket,
* or -1 to skip it. Leaves the cells in `order` and returns how many fall in each bucket.
*/
private sort(buckets: number, bucketOf: (i: number) => number) {
if (this.counts.length !== buckets) {
this.counts = new Int32Array(buckets);
this.starts = new Int32Array(buckets);
}
const { order, counts, starts } = this;
counts.fill(0);
const n = this.glyph.length;
for (let i = 0; i < n; i++) {
const b = bucketOf(i);
if (b >= 0 && b < buckets) counts[b]++;
}
let sum = 0;
for (let b = 0; b < buckets; b++) {
starts[b] = sum;
sum += counts[b]!;
}
for (let i = 0; i < n; i++) {
const b = bucketOf(i);
if (b >= 0 && b < buckets) order[starts[b]!++] = i;
}
return counts;
}
/**
* Paints the frame. `styles[tone * LEVELS + level - 1]` is the fill style for each bucket.
* With a monospace font, each bucket's glyphs on a row go out as one string with spaces in the
* gaps: a canvas pays per text call far more than per glyph, so this is many times faster.
*/
paint(
ctx: CanvasRenderingContext2D,
styles: readonly string[],
cw: number,
ch: number,
mono = true,
) {
const buckets = styles.length;
const { glyph, tone, level, blockTone, blockLevel, order, cols } = this;
// Blocks first, each inset a pixel so the grid of type still shows between them.
let counts = this.sort(buckets, (i) =>
blockLevel[i] ? blockTone[i]! * LEVELS + blockLevel[i]! - 1 : -1,
);
let k = 0;
for (let b = 0; b < buckets; b++) {
const count = counts[b]!;
if (!count) continue;
ctx.fillStyle = styles[b]!;
for (const end = k + count; k < end; k++) {
const i = order[k]!;
const col = i % cols;
const row = (i - col) / cols;
ctx.fillRect(col * cw + 0.5, row * ch + 0.5, cw - 1, ch - 1);
}
}
counts = this.sort(buckets, (i) => (glyph[i] ? tone[i]! * LEVELS + level[i]! - 1 : -1));
const dot = Math.max(1.5, Math.round(cw * 0.22));
ctx.textAlign = mono ? 'left' : 'center';
k = 0;
for (let b = 0; b < buckets; b++) {
const count = counts[b];
if (!count) continue;
ctx.fillStyle = styles[b]!;
// A run of text on one row: where it starts, and its characters so far.
let runRow = -1;
let runCol = 0;
let lastCol = 0;
let run = '';
for (const end = k + count; k < end; k++) {
const i = order[k]!;
const col = i % cols;
const row = (i - col) / cols;
const code = glyph[i]!;
if (code === DOT) {
ctx.fillRect(col * cw + cw / 2 - dot / 2, row * ch + ch / 2 - dot / 2, dot, dot);
continue;
}
if (!mono) {
ctx.fillText(String.fromCharCode(code), col * cw + cw / 2, row * ch + ch / 2);
continue;
}
if (row !== runRow) {
if (run) ctx.fillText(run, runCol * cw, runRow * ch + ch / 2);
runRow = row;
runCol = col;
run = '';
} else {
run += ' '.repeat(col - lastCol - 1);
}
run += String.fromCharCode(code);
lastCol = col;
}
if (run) ctx.fillText(run, runCol * cw, runRow * ch + ch / 2);
}
}
}
components/lilt/ascii/engine/types.tsascii-engine
types.ts
import type { GlyphSurface } from './surface';
/** The character grid a scene draws into. Positions are in cells; `aspect` is cell height over width. */
export interface AsciiGrid {
cols: number;
rows: number;
aspect: number;
}
export interface AsciiPointer {
/** Column under the pointer, fractional. */
x: number;
/** Row under the pointer, fractional. */
y: number;
/** False when the pointer is outside the canvas or is a finger that lifted. */
active: boolean;
}
/**
* A living picture made of type. The stage owns the canvas, the clock and input; a scene owns its
* world. `step` runs on a fixed 60 Hz clock and `draw` writes the current frame into the surface.
*/
export interface AsciiScene {
/**
* The scene's colours, addressed by index from `draw`. Any CSS colour works; `ink` is the
* canvas's own text colour, so a scene can follow the page's light or dark theme.
*/
readonly palette: readonly string[];
resize(grid: AsciiGrid): void;
step(dt: number, pointer: AsciiPointer): void;
draw(surface: GlyphSurface): void;
/** A click or tap at a cell. */
press?(x: number, y: number): void;
/**
* Height of a row as a multiple of the font size. Default 1.25. Scenes made of solid shapes ask
* for tighter rows, closer to square cells, so a body lying sideways still spans several rows.
*/
readonly lineHeight?: number;
/** Seconds to run before showing a single still frame when the reader prefers reduced motion. */
readonly settle?: number;
}
components/lilt/ascii/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 scene fills its parent, so give the parent a size. The canvas takes its type from CSS font-family and its ink from color. It pauses off screen and in hidden tabs, and shows one still frame when the reader prefers reduced motion.
Props11
Every option.
Pass these directly to AsciiGlobe.
| Prop | Type | Default | What it does |
|---|---|---|---|
points | { lat: number; lon: number; value?: number; label?: string }[] | ten world cities | Places that pulse while they face you. Larger values pulse wider; hovering reads out the label and value. |
arcs | { from: [lat, lon]; to: [lat, lon] }[] | seven routes between the cities | Great-circle arcs lifted above the surface, each with a bright head travelling from one end to the other. |
color | string | '#8b6cff' | Colour of the land and the atmosphere. |
accent | string | '#e5489c' | Colour of the points and arcs. |
spin | number | 1.5 | Turns per minute. 0 holds it still. |
tilt | number | 20 | How far the north pole leans toward you, in degrees. |
size | number | 0.82 | Share of the shorter side the globe fills. |
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 | a summary of the points | Describes the globe for screen readers. Without one it reads how many places are marked, their names and the number of routes. |