Pick a variant below. Give it a value and the bar fills to it.
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 { AsciiLoader } from '@/components/lilt/ascii/interface/ascii-loader';
export function Saving() {
return (
<p style={{ fontSize: 14 }}>
<AsciiLoader />
</p>
);
}
Installation6
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/loader.jsoncomponents/lilt/ascii/interface/ascii-loader.tsx
ascii-loader.tsx
'use client';
import { useEffect, useRef, useState, type CSSProperties, type ReactNode } from 'react';
import { approach, clamp, hash3 } from '../engine/noise';
import { MONO_STACK, useClock, useReducedMotion } from './motion';
export type AsciiLoaderVariant = 'spinner' | 'dots' | 'bar' | 'scramble';
export interface AsciiLoaderProps {
/** How it loads: a turning stroke, counting dots, a bar of type, or its label scrambling. Default `bar`. */
variant?: AsciiLoaderVariant;
/** Progress from 0 to 1. Given, the bar fills to it and reads out a percentage; without it, the bar sweeps. */
value?: number;
/** What is loading, read by screen readers and shown beside the spinner, dots and scramble. Default `Loading`. */
label?: string;
/** Characters across the bar, between its brackets. Default 24. */
width?: number;
/** Colour of the bar's fill and the moving parts. Default the inherited text colour. */
color?: string;
className?: string;
style?: CSSProperties;
}
const SPINNER = ['|', '/', '-', '\\'];
/** What the label shimmers through: quiet, narrow strokes rather than heavy symbols. */
const SHIMMER = '/\\|=+<>:;*~';
const hidden: CSSProperties = {
position: 'absolute',
width: 1,
height: 1,
margin: -1,
padding: 0,
border: 0,
overflow: 'hidden',
clip: 'rect(0 0 0 0)',
whiteSpace: 'nowrap',
};
/** Eases a shown value toward a target, so a jump in progress fills rather than snaps. */
function useEased(target: number, animate: boolean) {
const [shown, setShown] = useState(target);
const current = useRef(target);
useEffect(() => {
if (!animate) {
current.current = target;
setShown(target);
return;
}
let raf = 0;
let last = performance.now();
const tick = (now: number) => {
const dt = Math.min(0.1, (now - last) / 1000);
last = now;
current.current = approach(current.current, target, 9, dt);
if (Math.abs(current.current - target) < 0.002) current.current = target;
setShown(current.current);
if (current.current !== target) raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
}, [target, animate]);
return shown;
}
const ease = (t: number) => (t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2);
/**
* A loader made of type: a turning stroke, counting dots, a progress bar, or its label scrambling
* like a skeleton. Real text in a monospace face, so its width never jitters. Determinate bars are
* progress bars to assistive technology; everything else is a status that reads its label.
*/
export function AsciiLoader({
variant = 'bar',
value,
label = 'Loading',
width = 24,
color,
className,
style,
}: AsciiLoaderProps) {
const reduced = useReducedMotion();
const determinate = variant === 'bar' && typeof value === 'number' && Number.isFinite(value);
const target = determinate ? clamp(value, 0, 1) : 0;
const shown = useEased(target, determinate && !reduced);
const fps = variant === 'spinner' ? 10 : variant === 'dots' ? 4 : 30;
const time = useClock(!reduced && !determinate, fps);
const cells = Math.max(4, Math.round(width));
const accent = color ?? 'currentColor';
const base: CSSProperties = {
display: 'inline-flex',
alignItems: 'baseline',
gap: '1ch',
fontFamily: `var(--lilt-ascii-font, ${MONO_STACK})`,
fontVariantNumeric: 'tabular-nums',
whiteSpace: 'pre',
lineHeight: 1.4,
...style,
};
const dim = (opacity: number): CSSProperties => ({ opacity });
const name = className ? `lilt-ascii-loader ${className}` : 'lilt-ascii-loader';
if (determinate) {
const percent = Math.round(target * 100);
// The fill eases toward its value and can overshoot a little; the track always holds it.
const filled = Math.max(0, Math.min(cells, Math.round(shown * cells)));
return (
<span
className={name}
style={base}
role="progressbar"
aria-label={label}
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={percent}
>
<span aria-hidden="true">
<span style={dim(0.45)}>[</span>
<span style={{ color: accent }}>{'#'.repeat(filled)}</span>
<span style={dim(0.28)}>{'-'.repeat(cells - filled)}</span>
<span style={dim(0.45)}>]</span>
</span>
<span aria-hidden="true" style={dim(0.7)}>
{`${String(Math.round(shown * 100)).padStart(3, ' ')}%`}
</span>
</span>
);
}
let picture: ReactNode;
let caption = true;
if (variant === 'spinner') {
const glyph = reduced ? '*' : SPINNER[Math.floor(time * 10) % SPINNER.length]!;
picture = <span style={{ color: accent }}>{glyph}</span>;
} else if (variant === 'dots') {
const count = reduced ? 3 : Math.floor(time * 4) % 4;
picture = (
<span>
<span style={dim(0.7)}>{label}</span>
<span style={{ color: accent }}>{'.'.repeat(count).padEnd(3, ' ')}</span>
</span>
);
caption = false;
} else if (variant === 'bar') {
// An indeterminate sweep: a segment easing back and forth along the track.
const segment = Math.max(3, Math.round(cells * 0.28));
const phase = (time / 1.5) % 2;
const along = ease(phase < 1 ? phase : 2 - phase);
const start = reduced ? -segment : Math.round(along * (cells - segment));
const glyphs = Array.from({ length: cells }, (_, i) => i >= start && i < start + segment);
picture = (
<span>
<span style={dim(0.45)}>[</span>
{runs(glyphs).map(([on, length], i) =>
on ? (
<span key={i} style={{ color: accent }}>
{'#'.repeat(length)}
</span>
) : (
<span key={i} style={dim(0.28)}>
{'-'.repeat(length)}
</span>
),
)}
<span style={dim(0.45)}>]</span>
</span>
);
} else {
// The label as a skeleton: dim letters, with a band of scrambling glyphs washing through
// and the letters it passes lighting up behind it.
const n = label.length;
const period = n + 10;
const head = ((time * 14) % period) - 3;
const tick = Math.floor(time * 18);
picture = (
<span>
{Array.from(label, (ch, i) => {
if (reduced || ch === ' ') {
return (
<span key={i} style={dim(0.45)}>
{ch}
</span>
);
}
const d = head - i;
if (d >= 0 && d < 2.5) {
const g = SHIMMER[Math.floor(hash3(i, tick, 3) * SHIMMER.length)]!;
return (
<span key={i} style={{ color: accent, opacity: 0.95 }}>
{g}
</span>
);
}
const glow = d < 0 ? 0 : Math.max(0, 1 - (d - 2.5) / 5);
return (
<span key={i} style={dim(0.32 + 0.6 * glow)}>
{ch}
</span>
);
})}
</span>
);
caption = false;
}
return (
<span className={name} style={base} role="status" aria-live="polite">
<span style={hidden}>{label}</span>
<span aria-hidden="true">{picture}</span>
{caption ? (
<span aria-hidden="true" style={dim(0.7)}>
{label}
</span>
) : null}
</span>
);
}
/** Groups a row of on and off cells into runs, so a bar is a handful of spans. */
function runs(cells: readonly boolean[]): [boolean, number][] {
const out: [boolean, number][] = [];
for (const on of cells) {
const last = out[out.length - 1];
if (last && last[0] === on) last[1]++;
else out.push([on, 1]);
}
return out;
}
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/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.
The loader is real text in a monospace face with tabular numbers, so its width never jitters as it moves. It takes its colour and size from the text around it. With a value from 0 to 1 the bar is a progress bar to assistive technology, with the percentage read out; without one it sweeps, and every variant is a status that reads its label. With reduced motion it holds still.
Props5
Every option.
Pass these directly to AsciiLoader.
| Prop | Type | Default | What it does |
|---|---|---|---|
value | number | — | Progress from 0 to 1. The bar fills to it and shows a percentage; without one it sweeps. |
color | string | the text colour | Colour of the fill and the moving parts. |
variant | string | 'bar' | How it loads: a bar of type, a turning stroke, counting dots, or the label scrambling. |
label | string | 'Loading' | What is loading. Screen readers always hear it; the spinner, dots and scramble show it too. |
width | number | 24 | Characters across the bar, between its brackets. |