Loaders
Thirty-five loading states on one shared clock, so a page full of them never drifts. Drag the clock and every one scrubs with it.
npx shadcn@latest add https://uimaxxer.com/r/loaders.jsonPasskeysLoading states
- Thinking
- Reading
- Searching
- Planning
- Delegating
- Waiting on you
- Scramble
- Typewriter
- Shimmer
- Anagram
- Counter
- Braille
- Dot field
- Orbit
- Breathing grid
- Halftone
- ASCII
- Flow field
- Flock
- Dither
- Bloom
- Liquid
- Pendulum wave
- Glass beads
- Paper fold
- Ink
- Squircle
- Polygons
- Line
- Inchworm
- Skeleton
- Dial
- Mesh
- Glass
- Grain
0.00s
"use client";
// uimaxxer · Loaders, MIT. Thirty-five loading states on one shared clock, so a page full of them never drifts: mount one late, scroll one away, and it still lands on the beat. Delight: drag the clock and all thirty-five scrub together, backwards too.
import { useEffect, useRef, useSyncExternalStore, type CSSProperties, type ReactElement } from "react";
import { mount, pageClock, sizeOf, type Instance, type LoaderClock, type LoaderDef, type LoaderProps } from "@/registry/captain/ui/loaders-core";
import * as D from "@/registry/captain/ui/loaders-defs";
export { createLoaderClock, pageClock, type LoaderClock, type LoaderProps, type LoaderDef, type Easing, type Motion } from "@/registry/captain/ui/loaders-core";
export interface LoaderComponentProps extends LoaderProps {
/** Show the label as visible text beside the loader. It is always there for screen readers. */
showLabel?: boolean;
className?: string;
style?: CSSProperties;
id?: string;
}
const SR: CSSProperties = { position: "absolute", width: 1, height: 1, margin: -1, padding: 0, overflow: "hidden", clip: "rect(0 0 0 0)", whiteSpace: "nowrap", border: 0 };
/** Turns any loader definition into a component. The server renders a sized, labelled box; the motion mounts on the client, so nothing shifts. */
export function makeLoader<S>(def: LoaderDef<S>) {
function Loader(props: LoaderComponentProps): ReactElement {
const { className, style, id, showLabel, ...rest } = props;
const art = useRef<HTMLSpanElement>(null);
const inst = useRef<Instance | null>(null);
const latest = useRef<LoaderProps>(rest);
latest.current = rest;
useEffect(() => {
const el = art.current;
if (!el) return;
const i = mount(el, def, latest.current);
inst.current = i;
return () => { i.destroy(); inst.current = null; };
}, []);
const { clock, ...plain } = rest;
const key = JSON.stringify(plain);
useEffect(() => { inst.current?.update(latest.current); }, [key, clock]);
const { w, h, text } = sizeOf(def, rest);
const label = (rest.done && rest.doneLabel) || rest.label || def.label || "Loading";
const words = rest.text == null ? label : Array.isArray(rest.text) ? rest.text.reduce((a, b) => (b.length > a.length ? b : a), "") : rest.text;
const box: CSSProperties = text
? { display: "inline-block", fontSize: h / 2, lineHeight: 1, minWidth: `${words.length * 0.62}em`, minHeight: "1em" }
: { display: "inline-block", width: w, height: h, flex: "none" };
return (
<span role="status" aria-live="polite" id={id} className={className ? `cl ${className}` : "cl"}
style={{ display: "inline-flex", alignItems: "center", gap: ".5em", position: "relative", verticalAlign: "middle", ...style }}>
<span ref={art} aria-hidden="true" className="cl-art" style={{ position: "relative", ...box }} />
{showLabel ? <span className="cl-label">{label}</span> : <span style={SR}>{label}</span>}
</span>
);
}
Loader.displayName = def.name.replace(/(^|-)(\w)/g, (_, __, c: string) => c.toUpperCase());
return Loader;
}
/** The clock's time and state, for your own controls. Re-renders on play, pause and set, not every frame. */
export function useLoaderClock(clock: LoaderClock = pageClock) {
const playing = useSyncExternalStore(clock.subscribe, () => clock.playing, () => true);
return { clock, playing };
}
/** A spark walking a lattice, lighting what it touches. */
export const Thinking = /*#__PURE__*/ makeLoader(D.thinking);
/** Lines of a page, read word by word. */
export const Reading = /*#__PURE__*/ makeLoader(D.reading);
/** A lens drifting over a field of dots. */
export const Searching = /*#__PURE__*/ makeLoader(D.searching);
/** A tree grows its options, then picks a route. */
export const Planning = /*#__PURE__*/ makeLoader(D.planning);
/** Work fans out to a ring of agents and comes back. */
export const Delegating = /*#__PURE__*/ makeLoader(D.delegating);
/** Two eyes look around, blink, then look at you. */
export const Waiting = /*#__PURE__*/ makeLoader(D.waiting);
/** Letters decode from glyphs, left to right. */
export const Scramble = /*#__PURE__*/ makeLoader(D.scramble);
/** Types, pauses like a person, backspaces, types the next. */
export const Typewriter = /*#__PURE__*/ makeLoader(D.typewriter);
/** A wave passes through the letters, one at a time. */
export const Shimmer = /*#__PURE__*/ makeLoader(D.shimmer);
/** The word shuffles itself and finds its way back. */
export const Anagram = /*#__PURE__*/ makeLoader(D.anagram);
/** Odometer digits rolling up in bursts. */
export const Counter = /*#__PURE__*/ makeLoader(D.counter);
/** A worm of braille dots for inline text. */
export const Braille = /*#__PURE__*/ makeLoader(D.braille);
/** Two ripples crossing a grid of dots. */
export const Dotfield = /*#__PURE__*/ makeLoader(D.dotfield);
/** Three tilted orbits with comet tails, in depth. */
export const Orbit = /*#__PURE__*/ makeLoader(D.orbit);
/** Squares that breathe and turn on a slow noise. */
export const Breathe = /*#__PURE__*/ makeLoader(D.breathe);
/** A halftone screen with two lights moving under it. */
export const Halftone = /*#__PURE__*/ makeLoader(D.halftone);
/** Interference drawn in characters. */
export const Ascii = /*#__PURE__*/ makeLoader(D.ascii);
/** Particles riding a turning current. */
export const Flow = /*#__PURE__*/ makeLoader(D.flow);
/** A tiny swarm following one bright leader. */
export const Flock = /*#__PURE__*/ makeLoader(D.flock);
/** A pulse of light, ordered-dithered to pixels. */
export const Dither = /*#__PURE__*/ makeLoader(D.dither);
/** A sunflower of dots, pulsing outward. */
export const Bloom = /*#__PURE__*/ makeLoader(D.bloom);
/** A vessel filling, sloshing, draining. */
export const Liquid = /*#__PURE__*/ makeLoader(D.liquid);
/** Fifteen pendulums drifting in and out of phase. */
export const Pendulum = /*#__PURE__*/ makeLoader(D.pendulum);
/** Three glass beads bouncing, squashing on landing. */
export const Beads = /*#__PURE__*/ makeLoader(D.beads);
/** A sheet folding in half, in half again, and open. */
export const Fold = /*#__PURE__*/ makeLoader(D.fold);
/** Drops of ink spreading in water. */
export const Ink = /*#__PURE__*/ makeLoader(D.ink);
/** One shape morphing from circle to squircle to flower. */
export const Squircle = /*#__PURE__*/ makeLoader(D.squircle);
/** Nested polygons stepping round, one vertex at a time. */
export const Polygon = /*#__PURE__*/ makeLoader(D.polygon);
/** A line drawing itself, then letting go. */
export const Draw = /*#__PURE__*/ makeLoader(D.draw);
/** An indeterminate bar that moves like it means it. */
export const Inchworm = /*#__PURE__*/ makeLoader(D.inchworm);
/** A card skeleton breathing in reading order. */
export const Skeleton = /*#__PURE__*/ makeLoader(D.skeleton);
/** A comet of lit ticks around a dial. */
export const Ticks = /*#__PURE__*/ makeLoader(D.ticks);
/** A 4×4 mesh of squares the palette flows across, one beat per diagonal. */
export const Mesh = /*#__PURE__*/ makeLoader(D.mesh);
/** A wobbling glass drop bending the stripes behind it. */
export const Glass = /*#__PURE__*/ makeLoader(D.glass);
/** A lit sphere made of film grain. */
export const Grain = /*#__PURE__*/ makeLoader(D.grain);
export type Group = "Agents" | "Text" | "Generative" | "Physical" | "Shapes" | "Progress" | "Shaders";
export type Knob = "palette" | "density" | "stroke" | "easing" | "text" | "progress";
export interface CatalogEntry { name: keyof typeof D.DEFS; title: string; group: Group; blurb: string; knobs: Knob[]; hero?: boolean; Component: ReturnType<typeof makeLoader> }
/** All thirty-five, in gallery order, with what each one is and which props mean something for it. */
export const CATALOG: CatalogEntry[] = [
{ name: "thinking", title: "Thinking", group: "Agents", blurb: "A spark walking a lattice, lighting what it touches.", knobs: ["palette", "density", "stroke"], hero: true, Component: Thinking },
{ name: "reading", title: "Reading", group: "Agents", blurb: "Lines of a page, read word by word.", knobs: ["palette", "density", "easing"], Component: Reading },
{ name: "searching", title: "Searching", group: "Agents", blurb: "A lens drifting over a field of dots.", knobs: ["palette", "density", "stroke"], Component: Searching },
{ name: "planning", title: "Planning", group: "Agents", blurb: "A tree grows its options, then picks a route.", knobs: ["palette", "density", "stroke", "easing"], Component: Planning },
{ name: "delegating", title: "Delegating", group: "Agents", blurb: "Work fans out to a ring of agents and comes back.", knobs: ["palette", "density", "stroke", "easing"], Component: Delegating },
{ name: "waiting", title: "Waiting on you", group: "Agents", blurb: "Two eyes look around, blink, then look at you.", knobs: ["easing"], Component: Waiting },
{ name: "scramble", title: "Scramble", group: "Text", blurb: "Letters decode from glyphs, left to right.", knobs: ["palette", "text"], Component: Scramble },
{ name: "typewriter", title: "Typewriter", group: "Text", blurb: "Types, pauses like a person, backspaces, types the next.", knobs: ["palette", "text"], Component: Typewriter },
{ name: "shimmer", title: "Shimmer", group: "Text", blurb: "A wave passes through the letters, one at a time.", knobs: ["density", "text", "easing"], Component: Shimmer },
{ name: "anagram", title: "Anagram", group: "Text", blurb: "The word shuffles itself and finds its way back.", knobs: ["palette", "text", "easing"], Component: Anagram },
{ name: "counter", title: "Counter", group: "Text", blurb: "Odometer digits rolling up in bursts.", knobs: ["palette", "easing", "progress"], Component: Counter },
{ name: "braille", title: "Braille", group: "Text", blurb: "A worm of braille dots for inline text.", knobs: ["density", "text"], Component: Braille },
{ name: "dotfield", title: "Dot field", group: "Generative", blurb: "Two ripples crossing a grid of dots.", knobs: ["palette", "density"], Component: Dotfield },
{ name: "orbit", title: "Orbit", group: "Generative", blurb: "Three tilted orbits with comet tails, in depth.", knobs: ["palette", "density", "stroke"], hero: true, Component: Orbit },
{ name: "breathe", title: "Breathing grid", group: "Generative", blurb: "Squares that breathe and turn on a slow noise.", knobs: ["palette", "density"], Component: Breathe },
{ name: "halftone", title: "Halftone", group: "Generative", blurb: "A halftone screen with two lights moving under it.", knobs: ["palette", "density"], Component: Halftone },
{ name: "ascii", title: "ASCII", group: "Generative", blurb: "Interference drawn in characters.", knobs: ["density"], Component: Ascii },
{ name: "flow", title: "Flow field", group: "Generative", blurb: "Particles riding a turning current.", knobs: ["palette", "density", "stroke"], Component: Flow },
{ name: "flock", title: "Flock", group: "Generative", blurb: "A tiny swarm following one bright leader.", knobs: ["palette", "density"], Component: Flock },
{ name: "dither", title: "Dither", group: "Generative", blurb: "A pulse of light, ordered-dithered to pixels.", knobs: ["palette", "density"], Component: Dither },
{ name: "bloom", title: "Bloom", group: "Generative", blurb: "A sunflower of dots, pulsing outward.", knobs: ["palette", "density"], Component: Bloom },
{ name: "liquid", title: "Liquid", group: "Physical", blurb: "A vessel filling, sloshing, draining.", knobs: ["palette", "stroke", "easing", "progress"], Component: Liquid },
{ name: "pendulum", title: "Pendulum wave", group: "Physical", blurb: "Fifteen pendulums drifting in and out of phase.", knobs: ["palette", "density"], hero: true, Component: Pendulum },
{ name: "beads", title: "Glass beads", group: "Physical", blurb: "Three glass beads bouncing, squashing on landing.", knobs: ["palette", "easing"], Component: Beads },
{ name: "fold", title: "Paper fold", group: "Physical", blurb: "A sheet folding in half, in half again, and open.", knobs: ["palette", "easing"], Component: Fold },
{ name: "ink", title: "Ink", group: "Physical", blurb: "Drops of ink spreading in water.", knobs: ["palette", "density"], Component: Ink },
{ name: "squircle", title: "Squircle", group: "Shapes", blurb: "One shape morphing from circle to squircle to flower.", knobs: ["palette", "easing"], Component: Squircle },
{ name: "polygon", title: "Polygons", group: "Shapes", blurb: "Nested polygons stepping round, one vertex at a time.", knobs: ["palette", "density", "stroke", "easing"], Component: Polygon },
{ name: "draw", title: "Line", group: "Shapes", blurb: "A line drawing itself, then letting go.", knobs: ["palette", "stroke", "easing", "progress"], Component: Draw },
{ name: "inchworm", title: "Inchworm", group: "Progress", blurb: "An indeterminate bar that moves like it means it.", knobs: ["palette", "easing", "progress"], Component: Inchworm },
{ name: "skeleton", title: "Skeleton", group: "Progress", blurb: "A card skeleton breathing in reading order.", knobs: ["density"], Component: Skeleton },
{ name: "ticks", title: "Dial", group: "Progress", blurb: "A comet of lit ticks around a dial.", knobs: ["palette", "density", "stroke", "progress"], Component: Ticks },
{ name: "mesh", title: "Mesh", group: "Shapes", blurb: "A 4×4 mesh of squares the palette flows across, one beat per diagonal.", knobs: ["palette", "density", "easing"], hero: true, Component: Mesh },
{ name: "glass", title: "Glass", group: "Shaders", blurb: "A wobbling glass drop bending the stripes behind it.", knobs: ["palette", "density"], Component: Glass },
{ name: "grain", title: "Grain", group: "Shaders", blurb: "A lit sphere made of film grain.", knobs: ["palette", "density"], Component: Grain },
];// uimaxxer · Loaders core, MIT. One clock for every loader on the page: each frame a loader draws is a function of the clock's time,
// so loaders mounted at different moments, scrolled off screen or slowed down still land on the same beat. Scrub the clock and every one follows.
// Also: seeded randomness, easings, mount() and the WebGL helper. Nothing touches window until mount() runs, so importing it on the server is safe.
export type Easing = 'smooth' | 'spring' | 'snap' | 'out' | 'linear';
export type Motion = 'user' | 'always' | 'never';
export interface LoaderProps {
/** Height in px. Square loaders are size × size; bars and text scale from it. */
size?: number;
/** Ink for the neutral parts. Defaults to currentColor, so it follows your text colour and theme. */
color?: string;
/** Accent colours, used in order. */
palette?: string[];
/** 1 is the designed speed. */
speed?: number;
/** 0 to 1: how many dots, particles, lines or cells. */
density?: number;
easing?: Easing;
/** Line width in px. Defaults to a width that scales with size. */
stroke?: number;
/** Same seed, same loader. Leave it out and each instance varies a little. */
seed?: number;
/** What a screen reader hears. Text loaders also show it unless `text` is set. */
label?: string;
/** Visible words for text loaders. An array cycles. */
text?: string | string[];
/** 'user' follows prefers-reduced-motion; 'always' shows the still pose; 'never' always moves. */
reducedMotion?: Motion;
paused?: boolean;
/** Eases the motion to a stop and announces doneLabel. */
done?: boolean;
doneLabel?: string;
/** 0 to 1, on loaders that can show real progress. Leave it out for indeterminate. */
progress?: number;
/** Seconds ahead of the clock, to stagger a list on purpose. */
phase?: number;
/** The clock it follows. Leave it out to share the page clock with every other loader. */
clock?: LoaderClock;
}
export interface Resolved {
size: number; w: number; h: number;
/** the resolved ink colour, a real CSS colour even when color is currentColor */
ink: string;
palette: string[];
speed: number; density: number; stroke: number; seed: number;
ease: (x: number) => number;
label: string; words: string[];
progress: number | undefined;
}
export interface Ctx<S> {
el: HTMLElement;
p: Resolved;
/** seeded random in [0, 1) */
rnd: () => number;
/** the 2D context for canvas loaders, null for dom loaders (and in environments with no canvas) */
g: CanvasRenderingContext2D | null;
s: S;
}
export interface LoaderDef<S = unknown> {
name: string;
kind: 'canvas' | 'dom';
/** width ÷ height */
aspect?: number;
/** default size in px */
size?: number;
palette?: string[];
/** default stroke as a fraction of size */
stroke?: number;
easing?: Easing;
label?: string;
/** text loaders size to their words, not to a box */
text?: boolean;
/** the time, in seconds, of the designed still pose shown under reduced motion */
still?: number;
setup(c: Ctx<S>): S;
frame(c: Ctx<S>, t: number, dt: number): void;
destroy?(c: Ctx<S>): void;
}
export interface Instance { update(props: LoaderProps): void; destroy(): void }
export const PALETTE = ['#2E5BFF', '#C2410C', '#1E8A4C', '#6B4BD6', '#C98A0B', '#0E7C86'];
export const EASE: Record<Easing, (x: number) => number> = {
linear: x => x,
smooth: x => (x < .5 ? 4 * x * x * x : 1 - (2 - 2 * x) ** 3 / 2),
out: x => (x >= 1 ? 1 : 1 - 2 ** (-10 * x)),
snap: x => (x < .5 ? 16 * x ** 5 : 1 - (2 - 2 * x) ** 5 / 2),
spring: x => (x >= 1 ? 1 : 1 - Math.exp(-6.5 * x) * Math.cos(x * Math.PI * 3.5)),
};
export const TAU = Math.PI * 2;
export const clamp = (x: number, a = 0, b = 1) => (x < a ? a : x > b ? b : x);
export const lerp = (a: number, b: number, k: number) => a + (b - a) * k;
/** the fractional part, always in [0, 1) */
export const fract = (x: number) => x - Math.floor(x);
/** pick from a list by index, wrapping */
export const pick = <T>(a: readonly T[], i: number): T => a[((i % a.length) + a.length) % a.length] as T;
/** mixes two hex colours (#rgb or #rrggbb); anything else comes back as `a` */
export function mix(a: string, b: string, k: number): string {
const rgb = (c: string) => {
const m = /^#([\da-f]{3}|[\da-f]{6})$/i.exec(c.trim());
if (!m || !m[1]) return null;
const h = m[1].length === 3 ? m[1].replace(/./g, x => x + x) : m[1], n = parseInt(h, 16);
return [n >> 16, (n >> 8) & 255, n & 255];
};
const x = rgb(a), y = rgb(b);
if (!x || !y) return a;
return `rgb(${x.map((v, i) => Math.round(v + ((y[i] ?? v) - v) * k)).join(',')})`;
}
/** a filled circle */
export function dot(g: CanvasRenderingContext2D, x: number, y: number, r: number) {
g.beginPath();
g.arc(x, y, Math.max(0, r), 0, TAU);
g.fill();
}
/** a rounded rectangle path (call fill or stroke after) */
export function rr(g: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number) {
r = Math.max(0, Math.min(r, w / 2, h / 2));
g.beginPath();
g.moveTo(x + r, y);
g.arcTo(x + w, y, x + w, y + h, r);
g.arcTo(x + w, y + h, x, y + h, r);
g.arcTo(x, y + h, x, y, r);
g.arcTo(x, y, x + w, y, r);
g.closePath();
}
/** index of the segment that contains t in a cumulative list of end times */
export function seek(ends: ArrayLike<number>, t: number): number {
let lo = 0, hi = ends.length - 1;
while (lo < hi) { const m = (lo + hi) >> 1; if ((ends[m] ?? 0) <= t) lo = m + 1; else hi = m; }
return lo;
}
/** mulberry32: small, fast, good enough for motion */
export function rng(seed: number): () => number {
let a = seed | 0;
return () => {
a = (a + 0x6d2b79f5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
/** smooth value noise in 3D, about -1..1 */
export function noise(x: number, y: number, z = 0): number {
const h = (i: number, j: number, k: number) => {
let n = Math.imul(i, 374761393) + Math.imul(j, 668265263) + Math.imul(k, 2147483647);
n = Math.imul(n ^ (n >>> 13), 1274126177);
return ((n ^ (n >>> 16)) & 0xffff) / 32767.5 - 1;
};
const xi = Math.floor(x), yi = Math.floor(y), zi = Math.floor(z);
const s = (v: number) => v * v * (3 - 2 * v);
const u = s(x - xi), v = s(y - yi), w = s(z - zi);
const l = (a: number, b: number, k: number) => a + (b - a) * k;
const p = (k: number) => l(l(h(xi, yi, k), h(xi + 1, yi, k), u), l(h(xi, yi + 1, k), h(xi + 1, yi + 1, k), u), v);
return l(p(zi), p(zi + 1), w);
}
/* ---------- the shared clock ---------- */
/**
* Time for a set of loaders, in seconds. Every loader reads it on the same animation frame, so two loaders on one
* clock are always at the same instant, whenever they mounted. Pause, play, set or nudge it and they all follow.
*/
export interface LoaderClock {
/** Seconds, at `ms` (a performance.now() time) or now. */
now(ms?: number): number;
/** Jump to a time. Scrubbing backwards plays every loader backwards. */
set(seconds: number): void;
play(): void;
pause(): void;
readonly playing: boolean;
/** 1 is real time. */
rate: number;
/** Called on play, pause, set and rate changes (not every frame). */
subscribe(fn: () => void): () => void;
}
const perf = () => (typeof performance !== 'undefined' ? performance.now() : 0);
/** A clock of your own, for a set of loaders that should keep their own time (or a demo that pauses it). */
export function createLoaderClock(start = 0): LoaderClock {
let base = start, at = perf(), rate = 1;
const subs = new Set<() => void>();
const emit = () => subs.forEach(f => f());
const c: LoaderClock = {
now: (ms = perf()) => (at < 0 ? base : base + Math.max(0, ms - at) / 1000 * rate),
set(s) { base = s; if (at >= 0) at = perf(); emit(); },
play() { if (at < 0) { at = perf(); emit(); } },
pause() { if (at >= 0) { base = c.now(); at = -1; emit(); } },
get playing() { return at >= 0; },
get rate() { return rate; },
set rate(r) { base = c.now(); if (at >= 0) at = perf(); rate = r; emit(); },
subscribe(f) { subs.add(f); return () => { subs.delete(f); }; },
};
return c;
}
/** The page clock every loader follows unless you give it another. */
export const pageClock: LoaderClock = /*#__PURE__*/ createLoaderClock();
/* one animation frame loop for every loader on the page */
const frameSubs = new Set<(now: number) => void>();
let raf = 0;
const loop = (now: number) => {
raf = 0;
for (const f of Array.from(frameSubs)) f(now);
if (frameSubs.size && !raf) raf = requestAnimationFrame(loop);
};
function subscribe(f: (now: number) => void) {
frameSubs.add(f);
if (!raf) raf = requestAnimationFrame(loop);
return () => { frameSubs.delete(f); };
}
/* ---------- styles, injected once ---------- */
const sheets = new Set<string>();
/** adds a stylesheet to the document once per id */
export function css(id: string, text: string) {
if (typeof document === 'undefined' || sheets.has(id)) return;
sheets.add(id);
const s = document.createElement('style');
s.dataset.loader = id;
s.textContent = text;
document.head.appendChild(s);
}
const BASE = '@keyframes cl-breathe{50%{opacity:.66}}.cl-still{animation:cl-breathe 2.4s ease-in-out infinite}.cl-art>canvas{display:block;width:100%;height:100%}';
/** the box a loader takes before it mounts, so the server render reserves the same space */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function sizeOf(def: LoaderDef<any>, q: LoaderProps) {
const h = q.size ?? def.size ?? 48;
return { w: Math.round(h * (def.aspect ?? 1)), h, text: !!def.text };
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function resolve(def: LoaderDef<any>, q: LoaderProps, seed: number, ink: string): Resolved {
const { w, h } = sizeOf(def, q);
const words = q.text == null ? [q.label ?? def.label ?? 'Loading'] : Array.isArray(q.text) ? q.text : [q.text];
return {
size: h, w, h, ink,
palette: q.palette && q.palette.length ? q.palette : def.palette ?? PALETTE,
speed: q.speed ?? 1,
density: clamp(q.density ?? .5),
stroke: q.stroke ?? Math.max(1, h * (def.stroke ?? 1 / 32)),
seed,
ease: EASE[q.easing ?? def.easing ?? 'smooth'] ?? EASE.smooth,
label: q.label ?? def.label ?? 'Loading',
words: words.length ? words : ['Loading'],
progress: q.progress == null ? undefined : clamp(q.progress),
};
}
/** runs a loader inside `el` (the art box, which should be aria-hidden). Returns update and destroy. */
export function mount<S>(el: HTMLElement, def: LoaderDef<S>, props: LoaderProps = {}): Instance {
css('cl', BASE);
let q = props;
const seed = q.seed ?? ((Math.random() * 2 ** 31) | 0);
const inkOf = () => getComputedStyle(el).color || '#111214';
const ctx = { el, g: null } as Ctx<S>;
const clockOf = () => q.clock ?? pageClock;
// t is always phase + offset + clock × speed. offset only moves to keep the pose still when speed changes,
// and resets when the loader rejoins the clock after done or paused, so it never drifts from its neighbours.
let offset = 0, speed = q.speed ?? 1, t = 0, frames = 0, k = 1, off: (() => void) | null = null, visible = true, built = '', drawn = NaN;
const onClock = (ms?: number) => (q.phase ?? 0) + offset + clockOf().now(ms) * speed;
t = onClock();
const mq = typeof matchMedia === 'function' ? matchMedia('(prefers-reduced-motion: reduce)') : null;
const still = () => q.reducedMotion === 'always' || (q.reducedMotion !== 'never' && !!mq && mq.matches);
const build = () => {
el.style.color = q.color && q.color !== 'currentColor' ? q.color : '';
const p = resolve(def, q, q.seed ?? seed, inkOf());
const key = [p.w, p.h, p.palette, p.density, p.stroke, p.seed, p.words, q.easing].join('|');
ctx.p = p;
if (key === built) return false;
built = key;
if (def.destroy && ctx.s !== undefined) def.destroy(ctx);
el.textContent = '';
if (def.text) { el.style.fontSize = p.h / 2 + 'px'; el.style.lineHeight = '1'; }
else { el.style.width = p.w + 'px'; el.style.height = p.h + 'px'; }
ctx.g = null;
if (def.kind === 'canvas') {
const c = document.createElement('canvas'), r = Math.min(2, window.devicePixelRatio || 1);
c.width = Math.round(p.w * r); c.height = Math.round(p.h * r);
el.appendChild(c);
let g: CanvasRenderingContext2D | null = null;
try { g = c.getContext('2d'); } catch { g = null; }
if (g) g.setTransform(r, 0, 0, r, 0, 0);
ctx.g = g;
}
ctx.rnd = rng(p.seed);
ctx.s = def.setup(ctx);
drawn = NaN;
return true;
};
const draw = (dt: number) => {
const g = ctx.g;
if (g) { g.save(); g.setTransform(1, 0, 0, 1, 0, 0); g.clearRect(0, 0, g.canvas.width, g.canvas.height); g.restore(); }
def.frame(ctx, t, dt);
drawn = t;
};
const tick = (now: number) => {
const fresh = ++frames % 24 === 0;
if (fresh) ctx.p.ink = inkOf();
if (q.done) {
// done eases this one to a stop on its own time; it rejoins the clock when it starts again
k = Math.max(0, k - 1 / 60 / .7);
const step = (1 / 60) * speed * clockOf().rate * EASE.smooth(k) * (clockOf().playing ? 1 : 0);
t += step;
draw(step);
if (!k) sync();
return;
}
const next = onClock(now);
// nothing moved (a paused clock): skip the draw, except now and then so a theme change still repaints
if (next === drawn && !fresh) return;
// integrating loaders (flock, flow, liquid, counter) step forward only; scrubbing back holds them
const dt = Math.min(.064, Math.max(0, next - t));
t = next;
draw(dt);
};
const sync = () => {
const s = still();
el.classList.toggle('cl-still', s && !q.done);
const run = visible && !q.paused && !s && !(q.done && !k);
if (run && !off) { ctx.p.ink = inkOf(); if (!q.done) { offset = 0; t = onClock(); } off = subscribe(tick); }
else if (!run && off) { off(); off = null; }
if (s) { t = def.still ?? 1; draw(0); }
};
const io = typeof IntersectionObserver === 'function'
? new IntersectionObserver(es => { const e = es[es.length - 1]; if (e) { visible = e.isIntersecting; sync(); } }, { rootMargin: '64px' })
: null;
build();
draw(0);
io?.observe(el);
mq?.addEventListener?.('change', sync);
sync();
return {
update(next) {
if (!next.done) k = 1;
const ns = next.speed ?? 1;
// a new speed keeps the current pose: shift the offset by what the clock time would have added
if (ns !== speed) { const c = (next.clock ?? pageClock).now(); offset += c * (speed - ns); speed = ns; }
q = next;
// a rebuilt loader draws at once, so it never shows an empty frame
if (build() || !off) draw(0);
sync();
},
destroy() {
off?.(); off = null;
io?.disconnect();
mq?.removeEventListener?.('change', sync);
def.destroy?.(ctx);
el.textContent = '';
},
};
}
/** vanilla: turns `el` into a labelled status with the loader inside. This is what the plain HTML export calls. */
export function loader<S>(el: HTMLElement, def: LoaderDef<S>, props: LoaderProps = {}): Instance {
el.setAttribute('role', 'status');
el.setAttribute('aria-live', 'polite');
el.style.cssText += ';display:inline-flex;align-items:center;gap:.5em;position:relative;vertical-align:middle';
const art = document.createElement('span'), sr = document.createElement('span');
art.setAttribute('aria-hidden', 'true');
art.className = 'cl-art';
art.style.cssText = 'display:inline-block;flex:none;position:relative';
sr.style.cssText = 'position:absolute;width:1px;height:1px;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap';
el.replaceChildren(art, sr);
const say = (q: LoaderProps) => { sr.textContent = (q.done && q.doneLabel) || q.label || def.label || 'Loading'; };
say(props);
const i = mount(art, def, props);
return { update(q) { say(q); i.update(q); }, destroy() { i.destroy(); el.replaceChildren(); } };
}
/* ---------- WebGL, for the three shader loaders ----------
One full-screen triangle and one fragment shader. Uniforms: R (resolution px), T (seconds), D (density 0..1), Z (seed 0..1),
I (ink rgb), C0..C3 (palette rgb). Without WebGL it falls back to a flat disc in the first colour. */
export interface GS { gl: WebGLRenderingContext | null; u: Record<string, WebGLUniformLocation | null>; canvas: HTMLCanvasElement | null }
const rgb = (c: string): [number, number, number] => {
let m = /^#([\da-f]{3}|[\da-f]{6})$/i.exec(c.trim());
if (m && m[1]) {
const h = m[1].length === 3 ? m[1].replace(/./g, x => x + x) : m[1], n = parseInt(h, 16);
return [(n >> 16) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
}
m = /rgba?\(([^)]+)\)/.exec(c);
const v = m && m[1] ? m[1].split(/[\s,/]+/).map(Number) : [];
return [(v[0] ?? 128) / 255, (v[1] ?? 128) / 255, (v[2] ?? 128) / 255];
};
export function shader(name: string, frag: string, opts: Partial<LoaderDef<GS>> = {}): LoaderDef<GS> {
return {
name, kind: 'dom', size: 48, still: 1, label: 'Loading', ...opts,
setup({ el, p }: Ctx<GS>): GS {
const canvas = document.createElement('canvas'), r = Math.min(1.5, window.devicePixelRatio || 1);
canvas.width = Math.round(p.w * r); canvas.height = Math.round(p.h * r);
el.appendChild(canvas);
let gl: WebGLRenderingContext | null = null;
try { gl = canvas.getContext('webgl', { premultipliedAlpha: true, antialias: false, preserveDrawingBuffer: false }); } catch { gl = null; }
const fail = (): GS => {
canvas.remove();
el.style.background = pick(p.palette, 0);
el.style.borderRadius = '50%';
return { gl: null, u: {}, canvas: null };
};
if (!gl) return fail();
const sh = (type: number, src: string) => { const s = gl!.createShader(type)!; gl!.shaderSource(s, src); gl!.compileShader(s); return s; };
const prog = gl.createProgram()!;
gl.attachShader(prog, sh(gl.VERTEX_SHADER, 'attribute vec2 a;void main(){gl_Position=vec4(a,0.,1.);}'));
gl.attachShader(prog, sh(gl.FRAGMENT_SHADER, 'precision highp float;uniform vec2 R;uniform float T,D,Z;uniform vec3 I,C0,C1,C2,C3;float h(vec2 p){return fract(sin(dot(p,vec2(12.9898,78.233)))*43758.5453);}' + frag));
gl.linkProgram(prog);
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) return fail();
gl.useProgram(prog);
const buf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
const loc = gl.getAttribLocation(prog, 'a');
gl.enableVertexAttribArray(loc);
gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
const u: GS['u'] = {};
for (const k of ['R', 'T', 'D', 'Z', 'I', 'C0', 'C1', 'C2', 'C3']) u[k] = gl.getUniformLocation(prog, k);
return { gl, u, canvas };
},
frame({ p, s }, t) {
const { gl, u, canvas } = s;
if (!gl || !canvas) return;
gl.viewport(0, 0, canvas.width, canvas.height);
gl.uniform2f(u.R ?? null, canvas.width, canvas.height);
gl.uniform1f(u.T ?? null, t);
gl.uniform1f(u.D ?? null, p.density);
gl.uniform1f(u.Z ?? null, (p.seed % 1000) / 1000);
gl.uniform3fv(u.I ?? null, rgb(p.ink));
['C0', 'C1', 'C2', 'C3'].forEach((k, i) => gl.uniform3fv(u[k] ?? null, rgb(pick(p.palette, i))));
gl.drawArrays(gl.TRIANGLES, 0, 3);
},
destroy({ s }) {
s.gl?.getExtension('WEBGL_lose_context')?.loseContext();
},
};
}// uimaxxer · Loaders, the definitions, MIT. Thirty-five loading states as plain objects: setup() builds the art once, frame(t) draws one instant.
// Every frame is a function of the shared clock's time, so a page full of them never drifts. Ported from captain-loaders (github.com/jawadjalal/loaders).
import { EASE, TAU, clamp, dot, fract, lerp, mix, noise, pick, rng, rr, seek, shader, type LoaderDef } from "@/registry/captain/ui/loaders-core";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type Def = LoaderDef<any>;
/* ---------- agents ---------- */
/** A spark walking a lattice, lighting what it touches. */
export const thinking: Def = /*#__PURE__*/ (() => {
interface S { n: number; path: number[]; ends: Float32Array; total: number }
/** a spark walks a lattice of dots, pausing now and then; the nodes it passed glow and fade */
const thinking: LoaderDef<S> = {
name: 'thinking', kind: 'canvas', size: 48, stroke: 1 / 40, still: 3.3, label: 'Thinking',
setup({ p, rnd }) {
const n = Math.round(lerp(4, 7, p.density)), path = [Math.floor(rnd() * n * n)];
for (let i = 1, prev = -1; i < 400; i++) {
const c = path[i - 1] ?? 0, x = c % n, y = (c / n) | 0, opts: number[] = [];
for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [-1, -1], [1, -1], [-1, 1]] as const) {
const nx = x + dx, ny = y + dy, id = ny * n + nx;
if (nx >= 0 && ny >= 0 && nx < n && ny < n && id !== prev) opts.push(id);
}
prev = c;
path.push(pick(opts, Math.floor(rnd() * opts.length)));
}
const ends = new Float32Array(path.length);
let acc = 0;
path.forEach((_, i) => { acc += rnd() < .14 ? .46 : .15; ends[i] = acc; });
return { n, path, ends, total: acc };
},
frame({ g, p, s }, t) {
if (!g) return;
const { n, path, ends, total } = s, S = p.h, m = S * .17, step = (S - 2 * m) / (n - 1);
const pos = (id: number) => [m + (id % n) * step + (p.w - S) / 2, m + ((id / n) | 0) * step] as const;
const tt = fract(t / total) * total, i = seek(ends, tt);
const start = i ? ends[i - 1] ?? 0 : 0, dur = (ends[i] ?? 1) - start;
const f = p.ease(Math.min(1, (tt - start) / Math.min(dur, .15)));
g.fillStyle = p.ink;
g.globalAlpha = .16;
for (let id = 0; id < n * n; id++) { const [x, y] = pos(id); dot(g, x, y, S * .024); }
const accent = pick(p.palette, 0), at = (k: number) => pos(path[(i - k + path.length) % path.length] ?? 0);
g.strokeStyle = accent;
g.fillStyle = accent;
g.lineCap = 'round';
g.lineWidth = p.stroke;
for (let k = Math.min(7, i); k >= 1; k--) {
const a = at(k), b = at(k - 1), fade = 1 - (k - f) / 7;
g.globalAlpha = Math.max(0, fade) * .55;
g.beginPath();
g.moveTo(a[0], a[1]);
g.lineTo(k === 1 ? lerp(a[0], b[0], f) : b[0], k === 1 ? lerp(a[1], b[1], f) : b[1]);
g.stroke();
g.globalAlpha = Math.max(0, fade) * .8;
dot(g, a[0], a[1], S * .036 * (.5 + fade * .5));
}
const a = i ? at(1) : at(0), b = at(0);
g.globalAlpha = 1;
dot(g, lerp(a[0], b[0], f), lerp(a[1], b[1], f), S * .055);
g.globalAlpha = 1;
},
};
return thinking;
})();
/** Lines of a page, read word by word. */
export const reading: Def = /*#__PURE__*/ (() => {
interface Word { x: number; y: number; w: number }
interface S { words: Word[]; ends: Float32Array; total: number }
/** lines of a page read word by word: read words darken, the current word fills in the accent */
const reading: LoaderDef<S> = {
name: 'reading', kind: 'canvas', size: 48, aspect: 1.25, still: 2.2, label: 'Reading',
setup({ p, rnd }) {
const lines = Math.round(lerp(3, 6, p.density)), mx = p.w * .14, my = p.h * .2, lw = p.w - 2 * mx;
const gap = (p.h - 2 * my) / (lines - 1), words: Word[] = [];
for (let l = 0; l < lines; l++) {
const end = l === lines - 1 ? lw * lerp(.4, .7, rnd()) : lw;
for (let x = 0; x < end - lw * .08;) {
const w = Math.min(end - x, lw * lerp(.12, .34, rnd()));
words.push({ x: mx + x, y: my + l * gap, w });
x += w + lw * .05;
}
}
const ends = new Float32Array(words.length);
let acc = 0;
words.forEach((w, i) => { acc += .1 + (w.w / lw) * .55; ends[i] = acc; });
return { words, ends, total: acc + .9 };
},
frame({ g, p, s }, t) {
if (!g) return;
const tt = t % s.total, i = tt >= (s.ends[s.ends.length - 1] ?? 0) ? s.words.length : seek(s.ends, tt);
const start = i ? s.ends[i - 1] ?? 0 : 0, f = i < s.words.length ? p.ease(clamp((tt - start) / ((s.ends[i] ?? 1) - start))) : 0;
const reset = clamp((tt - (s.total - .35)) / .35), h = p.h * .085;
s.words.forEach((w, k) => {
g.fillStyle = p.ink;
g.globalAlpha = k < i ? lerp(.5, .14, reset) : .14;
rr(g, w.x, w.y - h / 2, w.w, h, h / 2);
g.fill();
if (k === i) {
g.globalAlpha = 1;
g.fillStyle = pick(p.palette, 0);
rr(g, w.x, w.y - h / 2, Math.max(h, w.w * f), h, h / 2);
g.fill();
}
});
g.globalAlpha = 1;
},
};
return reading;
})();
/** A lens drifting over a field of dots. */
export const searching: Def = /*#__PURE__*/ (() => {
interface S { n: number; ph: number }
/** a lens drifts over a grid of dots and magnifies what is under it */
const searching: LoaderDef<S> = {
name: 'searching', kind: 'canvas', size: 48, stroke: 1 / 30, still: .8, label: 'Searching',
setup: ({ p, rnd }) => ({ n: Math.round(lerp(7, 13, p.density)) | 1, ph: rnd() * 6 }),
frame({ g, p, s }, t) {
if (!g) return;
const S = p.h, ox = (p.w - S) / 2, m = S * .12, step = (S - 2 * m) / (s.n - 1), R = S * .2;
const lx = ox + S * (.46 + .2 * Math.sin(t * .9 + s.ph)), ly = S * (.46 + .2 * Math.sin(t * 1.37 + s.ph * 2));
const accent = pick(p.palette, 0);
for (let j = 0; j < s.n; j++) for (let i = 0; i < s.n; i++) {
let x = ox + m + i * step, y = m + j * step;
const dx = x - lx, dy = y - ly, d = Math.hypot(dx, dy), u = d / R;
let r = S * .016;
if (u < 1) {
const k = Math.pow(u, .62) / (u || 1);
x = lx + dx * k; y = ly + dy * k;
r *= 1 + 1.6 * (1 - u);
g.fillStyle = accent; g.globalAlpha = .9;
} else { g.fillStyle = p.ink; g.globalAlpha = .22; }
dot(g, x, y, r);
}
g.globalAlpha = .85;
g.strokeStyle = p.ink;
g.lineWidth = p.stroke;
g.beginPath();
g.arc(lx, ly, R, 0, Math.PI * 2);
g.stroke();
g.lineWidth = p.stroke * 2.2;
g.lineCap = 'round';
g.beginPath();
g.moveTo(lx + R * .74, ly + R * .74);
g.lineTo(lx + R * 1.34, ly + R * 1.34);
g.stroke();
g.globalAlpha = 1;
},
};
return searching;
})();
/** A tree grows its options, then picks a route. */
export const planning: Def = /*#__PURE__*/ (() => {
interface Node { x: number; y: number; parent: number; depth: number }
interface S { cycle: number; nodes: Node[]; route: Set<number> }
const T = 3.6;
function grow(p: { w: number; h: number; density: number; seed: number }, cycle: number): S {
const r = rng(p.seed * 31 + cycle * 977), nodes: Node[] = [{ x: p.w * .14, y: p.h * .5, parent: -1, depth: 0 }];
const kids = Math.round(lerp(2, 3, p.density));
for (let d = 1; d <= 2; d++) {
const level = nodes.filter(n => n.depth === d - 1), list: number[] = [];
for (const n of level) {
const c = d === 1 ? kids : 1 + Math.floor(r() * (1 + p.density * 2));
for (let k = 0; k < c; k++) list.push(nodes.indexOf(n));
}
list.forEach((parent, k) => nodes.push({ x: p.w * (d === 1 ? .46 : .82), y: p.h * lerp(.16, .84, list.length < 2 ? .5 : k / (list.length - 1)), parent, depth: d }));
}
const leaves = nodes.map((n, i) => (n.depth === 2 ? i : -1)).filter(i => i >= 0);
const route = new Set<number>();
for (let i = leaves[Math.floor(r() * leaves.length)] ?? 0; i >= 0; i = nodes[i]?.parent ?? -1) route.add(i);
return { cycle, nodes, route };
}
/** a tree grows its options left to right, then lights one route through it */
const planning: LoaderDef<S> = {
name: 'planning', kind: 'canvas', size: 48, aspect: 1.2, stroke: 1 / 36, still: 2.4, label: 'Planning',
setup: ({ p }) => grow(p, 0),
frame(c, t) {
const { g, p } = c;
if (!g) return;
const cycle = Math.floor(t / T), u = t - cycle * T;
if (c.s.cycle !== cycle) c.s = grow(p, cycle);
const { nodes, route } = c.s, accent = pick(p.palette, 0), out = 1 - clamp((u - 3.15) / .45), pickK = p.ease(clamp((u - 1.45) / .8));
g.lineCap = 'round';
nodes.forEach((n, i) => {
const par = nodes[n.parent], k = p.ease(clamp((u - (n.depth - 1) * .55) / .6)), on = route.has(i);
if (par && k > 0) {
const mx = (par.x + n.x) / 2, steps = 18;
const bez = (q: number) => {
const a = 1 - q;
return [a * a * a * par.x + 3 * a * a * q * mx + 3 * a * q * q * mx + q * q * q * n.x, a * a * a * par.y + 3 * a * a * q * par.y + 3 * a * q * q * n.y + q * q * q * n.y] as const;
};
const line = (to: number, color: string, w: number, alpha: number) => {
g.strokeStyle = color; g.lineWidth = w; g.globalAlpha = alpha * out;
g.beginPath();
for (let s = 0; s <= steps; s++) { const [x, y] = bez((s / steps) * to); s ? g.lineTo(x, y) : g.moveTo(x, y); }
g.stroke();
};
line(k, p.ink, p.stroke, on ? .3 : lerp(.3, .1, pickK));
if (on && pickK > 0) line(clamp(pickK * 3 - (n.depth - 1) * 1.2, 0, 1), accent, p.stroke * 1.8, 1);
}
const pop = n.depth ? clamp((u - (n.depth - 1) * .55 - .5) / .18) : clamp(u / .2), z = p.h * .07 * p.ease(pop);
if (z <= 0) return;
const lit = on && pickK >= Math.min(1, (n.depth + .2) / 2.2);
g.fillStyle = lit ? accent : p.ink;
g.globalAlpha = (lit ? 1 : on || !pickK ? .75 : lerp(.75, .25, pickK)) * out;
rr(g, n.x - z / 2, n.y - z / 2, z, z, z * .22);
g.fill();
});
g.globalAlpha = 1;
},
};
return planning;
})();
/** Work fans out to a ring of agents and comes back. */
export const delegating: Def = /*#__PURE__*/ (() => {
interface S { n: number; rot: number }
const T = 2.8;
/** work fans out from the lead to a ring of agents, each works, then reports back */
const delegating: LoaderDef<S> = {
name: 'delegating', kind: 'canvas', size: 48, stroke: 1 / 36, still: 1.15, label: 'Delegating',
palette: ['#0E7C86', '#2E5BFF', '#1E8A4C', '#6B4BD6', '#C2410C', '#A63A9C', '#C98A0B', '#8A6A12'],
setup: ({ p, rnd }) => ({ n: Math.round(lerp(4, 8, p.density)), rot: rnd() * TAU }),
frame({ g, p, s }, t) {
if (!g) return;
const S = p.h, cx = p.w / 2, cy = S / 2, R = S * .36, u = t % T;
let flash = 0;
g.lineWidth = p.stroke;
for (let i = 0; i < s.n; i++) {
const a = s.rot + (i / s.n) * TAU + Math.sin(t * .4) * .05, ax = cx + Math.cos(a) * R, ay = cy + Math.sin(a) * R;
const color = pick(p.palette, i), t0 = i * (.5 / s.n);
const go = clamp((u - t0) / .5), work = clamp((u - t0 - .5) / .75), back = clamp((u - t0 - 1.3) / .5);
const bend = (q: number, from: number) => {
const k = from ? 1 - q : q, side = (from ? -1 : 1) * R * .35;
return [lerp(cx, ax, k) + Math.cos(a + Math.PI / 2) * side * Math.sin(k * Math.PI), lerp(cy, ay, k) + Math.sin(a + Math.PI / 2) * side * Math.sin(k * Math.PI)] as const;
};
g.fillStyle = color;
if (go > 0 && go < 1) { const [x, y] = bend(p.ease(go), 0); g.globalAlpha = 1; dot(g, x, y, S * .026); }
if (back > 0 && back < 1) { const [x, y] = bend(p.ease(back), 1); g.globalAlpha = 1; dot(g, x, y, S * .026); }
if (back >= 1) flash = Math.max(flash, 1 - clamp((u - t0 - 1.8) / .4));
const busy = go >= 1 && back <= 0;
g.globalAlpha = busy ? 1 : .28;
dot(g, ax, ay, S * (busy ? .05 : .04));
if (busy) {
g.strokeStyle = color; g.globalAlpha = .9;
g.beginPath();
g.arc(ax, ay, S * .085, -Math.PI / 2, -Math.PI / 2 + TAU * p.ease(work));
g.stroke();
}
}
const z = S * (.13 + .02 * flash);
g.globalAlpha = 1;
g.fillStyle = p.ink;
rr(g, cx - z / 2, cy - z / 2, z, z, z * .28);
g.fill();
},
};
return delegating;
})();
/** Two eyes look around, blink, then look at you. */
export const waiting: Def = /*#__PURE__*/ (() => {
interface S { eyes: SVGRectElement[]; keys: [number, number, number][]; blinks: number[]; total: number }
const NS = 'http://www.w3.org/2000/svg';
/** two eyes glance around, blink, then settle on you and wait */
const waiting: LoaderDef<S> = {
name: 'waiting', kind: 'dom', size: 48, easing: 'snap', still: 4.2, label: 'Waiting on you',
setup({ el, p, rnd }) {
const svg = document.createElementNS(NS, 'svg');
svg.setAttribute('viewBox', `0 0 ${p.w} ${p.h}`);
svg.setAttribute('width', String(p.w));
svg.setAttribute('height', String(p.h));
svg.style.overflow = 'visible';
const eyes = [0, 1].map(() => { const r = document.createElementNS(NS, 'rect'); r.setAttribute('fill', 'currentColor'); svg.appendChild(r); return r; });
el.appendChild(svg);
const side = rnd() < .5 ? -1 : 1;
// [time, gaze x, gaze y] in -1..1; the last key looks straight at you and holds
const keys: [number, number, number][] = [[0, 0, 0], [.5, side, .1], [1.3, -side, .25], [2.1, -side * .4, -.7], [2.9, 0, 0], [5.2, 0, 0]];
return { eyes, keys, blinks: [1.9, 4.5 + rnd() * .3], total: 5.2 };
},
frame({ p, s }, t) {
const u = t % s.total, S = p.h;
let i = 0;
while (i < s.keys.length - 2 && (s.keys[i + 1]?.[0] ?? 0) <= u) i++;
const a = s.keys[i] ?? [0, 0, 0], b = s.keys[i - 1] ?? a, k = p.ease(clamp((u - a[0]) / .28));
const gx = lerp(b[1], a[1], k), gy = lerp(b[2], a[2], k);
let lid = 1;
for (const at of s.blinks) { const d = Math.abs(u - at); if (d < .09) lid = Math.min(lid, .12 + d / .09 * .88); }
const near = i >= s.keys.length - 2 ? 1 + .06 * clamp((u - (s.keys[s.keys.length - 2]?.[0] ?? 0)) / .3) : 1;
const w = S * .17 * near, h = S * .34 * near * lid;
s.eyes.forEach((e, n) => {
const x = p.w / 2 + (n ? 1 : -1) * S * .15 + gx * S * .1 - w / 2, y = S / 2 + gy * S * .09 - h / 2;
e.setAttribute('x', x.toFixed(2));
e.setAttribute('y', y.toFixed(2));
e.setAttribute('width', w.toFixed(2));
e.setAttribute('height', h.toFixed(2));
e.setAttribute('rx', (w / 2).toFixed(2));
});
},
};
return waiting;
})();
/* ---------- text ---------- */
/** Letters decode from glyphs, left to right. */
export const scramble: Def = /*#__PURE__*/ (() => {
interface S { spans: HTMLSpanElement[]; jit: number[] }
const GLYPHS = '01<>/\\[]{}=+*^?#%&';
const MONO = 'var(--captain-font-mono, ui-monospace, SFMono-Regular, Menlo, monospace)';
/** each word decodes from glyphs left to right, holds, then scrambles away for the next */
const scramble: LoaderDef<S> = {
name: 'scramble', kind: 'dom', text: true, size: 32, still: 1.9, label: 'Decoding',
setup({ el, p, rnd }) {
el.style.fontFamily = MONO;
el.style.whiteSpace = 'pre';
const n = Math.max(...p.words.map(w => w.length));
const spans = Array.from({ length: n }, () => el.appendChild(document.createElement('span')));
return { spans, jit: spans.map(() => rnd() * .08) };
},
frame({ p, s }, t) {
const cyc = (w: string) => .35 + w.length * .055 + 1.5 + .45;
let u = t % p.words.reduce((a, w) => a + cyc(w), 0), wi = 0;
while (u >= cyc(pick(p.words, wi))) u -= cyc(pick(p.words, wi++));
const word = pick(p.words, wi), L = word.length, bucket = Math.floor(t / .05), out = .35 + L * .055 + 1.5;
s.spans.forEach((sp, i) => {
const ch = word[i] ?? '', on = .08 + i * .055 + (s.jit[i] ?? 0), off = out + (L - 1 - i) * (.4 / Math.max(1, L));
let text = ch, glyph = false;
if (!ch || ch === ' ') text = ch;
else if (u < on || u >= off) {
const gone = u >= off + .12 || u < on - .25;
text = gone ? ' ' : GLYPHS[(i * 7 + bucket * 13 + p.seed) % GLYPHS.length] ?? '#';
glyph = true;
}
if (sp.textContent !== text) sp.textContent = text;
sp.style.display = i < L ? '' : 'none';
sp.style.color = glyph ? pick(p.palette, 0) : '';
sp.style.opacity = glyph ? String(.55 + .45 * clamp(1 - Math.abs(u - on) / .25)) : '';
});
},
};
return scramble;
})();
/** Types, pauses like a person, backspaces, types the next. */
export const typewriter: Def = /*#__PURE__*/ (() => {
interface Beat { at: number[]; hold: number; end: number }
interface S { text: Text; caret: HTMLSpanElement; beats: Beat[]; total: number }
/** types each word with a person's rhythm, holds with a blinking caret, backspaces, types the next */
const typewriter: LoaderDef<S> = {
name: 'typewriter', kind: 'dom', text: true, size: 32, still: 2, label: 'Writing',
setup({ el, p, rnd }) {
el.style.whiteSpace = 'pre';
const text = el.appendChild(document.createTextNode('')), caret = el.appendChild(document.createElement('span'));
caret.style.cssText = `display:inline-block;width:.09em;height:1.05em;margin-left:.06em;vertical-align:-.16em;border-radius:.03em;background:${pick(p.palette, 0)}`;
let acc = 0;
const beats = p.words.map(w => {
const at: number[] = [];
for (const ch of w) { acc += ch === ' ' ? .16 : .045 + rnd() * .07 + (rnd() < .08 ? .22 : 0); at.push(acc); }
const hold = acc + 1.2;
acc = hold + w.length * .03 + .35;
return { at, hold, end: acc };
});
return { text, caret, beats, total: acc };
},
frame({ p, s }, t) {
const u = t % s.total, i = Math.max(0, s.beats.findIndex(b => u < b.end)), b = s.beats[i], word = pick(p.words, i);
if (!b) return;
let n = 0;
if (u < b.hold) for (const at of b.at) { if (u >= at) n++; }
else n = Math.max(0, word.length - Math.floor((u - b.hold) / .03));
const shown = word.slice(0, n);
if (s.text.data !== shown) s.text.data = shown;
const typing = u < b.hold - 1.2 || u > b.hold;
s.caret.style.opacity = typing || (u * 2) % 1 < .55 ? '1' : '0';
},
};
return typewriter;
})();
/** A wave passes through the letters, one at a time. */
export const shimmer: Def = /*#__PURE__*/ (() => {
interface S { spans: HTMLSpanElement[] }
/** a wave passes through the letters one at a time: each lifts and brightens as it goes by (no gradient text) */
const shimmer: LoaderDef<S> = {
name: 'shimmer', kind: 'dom', text: true, size: 32, still: .55, label: 'Thinking',
setup({ el, p }) {
el.style.whiteSpace = 'pre';
const word = pick(p.words, 0);
return { spans: Array.from(word, ch => { const s = el.appendChild(document.createElement('span')); s.textContent = ch; s.style.display = 'inline-block'; return s; }) };
},
frame({ p, s }, t) {
const n = s.spans.length, band = lerp(1.2, 4.5, p.density), cycle = 1.1 + n * .045;
const x = p.ease(Math.min(1, (t % (cycle + .5)) / cycle)) * (n + band * 2) - band;
s.spans.forEach((sp, i) => {
const k = Math.exp(-(((i - x) / band) ** 2) * 2.2);
sp.style.opacity = (.34 + .66 * k).toFixed(3);
sp.style.transform = `translateY(${(-.07 * k).toFixed(3)}em)`;
});
},
};
return shimmer;
})();
/** The word shuffles itself and finds its way back. */
export const anagram: Def = /*#__PURE__*/ (() => {
interface S { spans: HTMLSpanElement[]; perms: number[][] }
const MONO = 'var(--captain-font-mono, ui-monospace, SFMono-Regular, Menlo, monospace)';
const STEP = .62, HOLD = 1.1;
/** the word shuffles its letters, three times, then every letter finds its way home */
const anagram: LoaderDef<S> = {
name: 'anagram', kind: 'dom', text: true, size: 32, easing: 'spring', still: .2, label: 'Rearranging',
setup({ el, p, rnd }) {
const word = pick(p.words, 0), n = word.length;
el.style.cssText += `;font-family:${MONO};position:relative;display:inline-block;width:${n}ch;height:1em;white-space:pre`;
const spans = Array.from(word, ch => {
const s = el.appendChild(document.createElement('span'));
s.textContent = ch;
s.style.cssText = 'position:absolute;left:0;top:0;width:1ch;text-align:center';
return s;
});
const id = Array.from(word, (_, i) => i), perms = [id];
for (let k = 0; k < 3; k++) {
const q = id.slice();
for (let i = n - 1; i > 0; i--) { const j = Math.floor(rnd() * (i + 1)); [q[i], q[j]] = [q[j] ?? 0, q[i] ?? 0]; }
perms.push(q);
}
perms.push(id);
return { spans, perms };
},
frame({ p, s }, t) {
const steps = s.perms.length - 1, total = HOLD + steps * STEP, u = t % total;
const k = clamp(Math.floor((u - HOLD) / STEP), 0, steps - 1), f = u < HOLD ? 0 : p.ease(clamp((u - HOLD - k * STEP) / (STEP * .8)));
const from = u < HOLD ? s.perms[0] : s.perms[k], to = u < HOLD ? s.perms[0] : s.perms[k + 1];
if (!from || !to) return;
s.spans.forEach((sp, i) => {
const a = from[i] ?? i, b = to[i] ?? i, x = lerp(a, b, f), lift = Math.sin(clamp(f) * Math.PI) * .32 * Math.sign(b - a);
sp.style.transform = `translate(${x.toFixed(3)}ch, ${(-lift).toFixed(3)}em)`;
sp.style.color = a === i && b === i ? '' : pick(p.palette, 0);
});
},
};
return anagram;
})();
/** Odometer digits rolling up in bursts. */
export const counter: Def = /*#__PURE__*/ (() => {
interface S { cols: HTMLSpanElement[]; strips: HTMLSpanElement[]; suffix: HTMLSpanElement; v: number; goal: number; bursts: number[] }
const MONO = 'var(--captain-font-mono, ui-monospace, SFMono-Regular, Menlo, monospace)';
const N = 4, T = 4.6;
/** odometer digits rolling up in bursts; with `progress` it rolls to the percentage */
const counter: LoaderDef<S> = {
name: 'counter', kind: 'dom', text: true, size: 32, easing: 'out', still: 3.4, label: 'Counting',
setup({ el, p, rnd }) {
el.style.cssText += `;font-family:${MONO};font-variant-numeric:tabular-nums;white-space:pre;display:inline-flex;align-items:baseline`;
const cols: HTMLSpanElement[] = [], strips: HTMLSpanElement[] = [];
for (let i = 0; i < N; i++) {
const c = el.appendChild(document.createElement('span')), s = c.appendChild(document.createElement('span'));
c.style.cssText = 'display:inline-block;height:1em;overflow:hidden;line-height:1;vertical-align:bottom';
s.style.cssText = 'display:block;white-space:pre';
s.textContent = '0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0';
cols.push(c); strips.push(s);
}
const suffix = el.appendChild(document.createElement('span'));
suffix.style.cssText = 'margin-left:.3em;opacity:.55';
const bursts = [0, .18, .4, .55, .78, 1].map((x, i, a) => (i && i < a.length - 1 ? clamp(x + (rnd() - .5) * .12) : x));
return { cols, strips, suffix, v: 0, goal: Math.floor(lerp(1200, 9800, rnd())), bursts };
},
frame({ p, s }, t, dt) {
let v: number, busy: number;
if (p.progress != null) {
const goal = p.progress * 100;
s.v = dt ? s.v + (goal - s.v) * (1 - Math.exp(-dt * 7)) : s.v || goal;
v = s.v; busy = clamp(Math.abs(goal - v) / 4);
} else {
const u = t % T, k = Math.min(4, Math.floor(u / .62)), f = p.ease(clamp((u - k * .62) / .5));
const a = s.bursts[k] ?? 0, b = s.bursts[k + 1] ?? 1;
v = u > 3.9 ? s.goal * (1 - p.ease(clamp((u - 3.9) / .6))) : s.goal * lerp(a, b, f);
busy = u > 3.9 ? 1 : 1 - clamp((u - k * .62) / .62);
}
const lead = Math.floor(Math.log10(Math.max(1, v))) + 1;
s.strips.forEach((st, i) => {
const place = N - 1 - i, q = v / 10 ** place;
let pos = q % 10;
if (place) {
const lower = (v / 10 ** (place - 1)) % 10;
pos = Math.floor(q) % 10 + (lower > 9 ? lower - 9 : 0);
}
st.style.transform = `translateY(${(-pos).toFixed(3)}em)`;
const c = s.cols[i];
if (c) {
c.style.opacity = place >= lead ? '.28' : '1';
c.style.color = place === 0 && busy > .05 ? pick(p.palette, 0) : '';
}
});
const sfx = p.progress != null ? '%' : p.words.length && p.words[0] !== p.label ? p.words[0] ?? '' : '';
if (s.suffix.textContent !== sfx) s.suffix.textContent = sfx;
s.suffix.style.marginLeft = sfx === '%' ? '.05em' : '.3em';
},
};
return counter;
})();
/** A worm of braille dots for inline text. */
export const braille: Def = /*#__PURE__*/ (() => {
interface S { glyphs: Text; word: HTMLSpanElement; ring: [number, number][]; len: number }
const BIT = [[0x01, 0x08], [0x02, 0x10], [0x04, 0x20], [0x40, 0x80]];
/** a worm of braille dots running round three cells, for inline text */
const braille: LoaderDef<S> = {
name: 'braille', kind: 'dom', text: true, size: 32, still: .3, label: 'Working',
setup({ el, p }) {
el.style.whiteSpace = 'pre';
const glyphs = el.appendChild(document.createTextNode('')), word = el.appendChild(document.createElement('span'));
word.style.cssText = 'margin-left:.45em;opacity:.7';
word.textContent = p.words[0] === p.label ? '' : pick(p.words, 0);
const ring: [number, number][] = [];
for (let x = 0; x < 6; x++) ring.push([x, 0]);
for (let y = 1; y < 4; y++) ring.push([5, y]);
for (let x = 4; x >= 0; x--) ring.push([x, 3]);
for (let y = 2; y > 0; y--) ring.push([0, y]);
return { glyphs, word, ring, len: Math.round(lerp(3, 8, p.density)) };
},
frame({ s }, t) {
const head = Math.floor(t / .07), cells = [0, 0, 0];
for (let k = 0; k < s.len; k++) {
const [x, y] = pick(s.ring, head - k), c = x >> 1;
cells[c] = (cells[c] ?? 0) | (BIT[y]?.[x & 1] ?? 0);
}
const txt = String.fromCharCode(...cells.map(b => 0x2800 + b));
if (s.glyphs.data !== txt) s.glyphs.data = txt;
},
};
return braille;
})();
/* ---------- generative ---------- */
/** Two ripples crossing a grid of dots. */
export const dotfield: Def = /*#__PURE__*/ (() => {
interface S { n: number; ph: number }
/** two ripples cross a grid of dots; where they meet, the dots swell into the accent */
const dotfield: LoaderDef<S> = {
name: 'dotfield', kind: 'canvas', size: 48, still: 1.1, label: 'Loading',
setup: ({ p, rnd }) => ({ n: Math.round(lerp(9, 17, p.density)), ph: rnd() * 6.28 }),
frame({ g, p, s }, t) {
if (!g) return;
const S = p.h, ox = (p.w - S) / 2, m = S * .1, step = (S - 2 * m) / (s.n - 1), k = 10 / S;
const ax = ox + S * (.5 + .3 * Math.cos(t * .5 + s.ph)), ay = S * (.5 + .3 * Math.sin(t * .5 + s.ph));
const bx = ox + S * (.5 + .3 * Math.cos(t * .37 + s.ph + 3)), by = S * (.5 + .3 * Math.sin(t * .41 + s.ph + 3));
const accent = pick(p.palette, 0), hot: number[] = [];
g.fillStyle = p.ink;
g.globalAlpha = .3;
for (let j = 0; j < s.n; j++) for (let i = 0; i < s.n; i++) {
const x = ox + m + i * step, y = m + j * step;
const v = (Math.sin(Math.hypot(x - ax, y - ay) * k - t * 3.2) + Math.sin(Math.hypot(x - bx, y - by) * k - t * 2.7)) / 4 + .5;
const r = step * lerp(.06, .42, v * v * v);
if (v > .78) hot.push(x, y, r); else dot(g, x, y, r);
}
g.fillStyle = accent;
g.globalAlpha = 1;
for (let i = 0; i < hot.length; i += 3) dot(g, hot[i] ?? 0, hot[i + 1] ?? 0, hot[i + 2] ?? 0);
},
};
return dotfield;
})();
/** Three tilted orbits with comet tails, in depth. */
export const orbit: Def = /*#__PURE__*/ (() => {
interface Ring { r: number; b: number; tilt: number; w: number; ph: number; color: string }
/** three tilted orbits around a core, drawn in depth: planets behind the core pass under it */
const orbit: LoaderDef<Ring[]> = {
name: 'orbit', kind: 'canvas', size: 48, stroke: 1 / 48, still: 1.4,
setup({ p, rnd }) {
const n = Math.round(lerp(2, 5, p.density));
return Array.from({ length: n }, (_, i) => ({
r: lerp(.2, .44, n < 2 ? 1 : i / (n - 1)),
b: lerp(.28, .5, rnd()),
tilt: (i / n) * Math.PI + (rnd() - .5) * .5,
w: (TAU / lerp(1.5, 3.1, rnd())) * (i % 2 ? -1 : 1),
ph: rnd() * TAU,
color: pick(p.palette, i),
}));
},
frame({ g, p, s }, t) {
if (!g) return;
const S = p.h, cx = p.w / 2, cy = p.h / 2;
const at = (o: Ring, a: number) => {
const x = Math.cos(a) * o.r * S, y = Math.sin(a) * o.r * o.b * S, c = Math.cos(o.tilt), sn = Math.sin(o.tilt);
return { x: cx + x * c - y * sn, y: cy + x * sn + y * c, z: Math.sin(a) };
};
g.lineWidth = p.stroke;
g.strokeStyle = p.ink;
g.globalAlpha = .14;
for (const o of s) {
g.beginPath();
g.ellipse(cx, cy, o.r * S, o.r * o.b * S, o.tilt, 0, TAU);
g.stroke();
}
const body = (o: Ring, front: boolean) => {
const a = o.ph + t * o.w;
for (let k = 22; k >= 0; k--) {
const q = at(o, a - Math.sign(o.w) * k * .045);
if ((q.z > 0) !== front) continue;
const depth = .78 + .22 * q.z, f = 1 - k / 23;
g.globalAlpha = k ? f * f * .5 : 1;
g.fillStyle = o.color;
g.beginPath();
g.arc(q.x, q.y, S * (k ? .03 * f : .05) * depth, 0, TAU);
g.fill();
}
};
for (const o of s) body(o, false);
g.globalAlpha = 1;
g.fillStyle = p.ink;
g.beginPath();
g.arc(cx, cy, S * .085, 0, TAU);
g.fill();
for (const o of s) body(o, true);
g.globalAlpha = 1;
},
};
return orbit;
})();
/** Squares that breathe and turn on a slow noise. */
export const breathe: Def = /*#__PURE__*/ (() => {
interface S { n: number; hot: Set<number>; z: number }
/** a grid of squares breathing and turning on a slow noise field */
const breathe: LoaderDef<S> = {
name: 'breathe', kind: 'canvas', size: 48, still: 2, label: 'Loading',
setup({ p, rnd }) {
const n = Math.round(lerp(4, 8, p.density)), hot = new Set<number>();
while (hot.size < Math.max(1, Math.round(n * n * .08))) hot.add(Math.floor(rnd() * n * n));
return { n, hot, z: rnd() * 100 };
},
frame({ g, p, s }, t) {
if (!g) return;
const S = p.h, m = S * .1, cell = (S - 2 * m) / s.n, ox = (p.w - S) / 2;
for (let j = 0; j < s.n; j++) for (let i = 0; i < s.n; i++) {
const v = noise(i * .42, j * .42, s.z + t * .55), k = .5 + .5 * v, z = cell * lerp(.18, .86, k * k);
const hot = s.hot.has(j * s.n + i);
g.save();
g.translate(ox + m + (i + .5) * cell, m + (j + .5) * cell);
g.rotate(v * 1.1);
g.fillStyle = hot ? pick(p.palette, i + j) : p.ink;
g.globalAlpha = hot ? 1 : lerp(.25, .9, k);
rr(g, -z / 2, -z / 2, z, z, z * .2);
g.fill();
g.restore();
}
},
};
return breathe;
})();
/** A halftone screen with two lights moving under it. */
export const halftone: Def = /*#__PURE__*/ (() => {
interface S { n: number; ph: number }
/** two halftone screens at print angles, each lit by its own moving light, overprinted */
const halftone: LoaderDef<S> = {
name: 'halftone', kind: 'canvas', size: 48, still: 1.6, label: 'Loading',
palette: ['#2E5BFF', '#FF5A1F'],
setup: ({ p, rnd }) => ({ n: Math.round(lerp(9, 17, p.density)), ph: rnd() * 6.28 }),
frame({ g, p, s }, t) {
if (!g) return;
const S = p.h, cx = p.w / 2, cy = S / 2, cell = S / s.n;
[.26, 1.31].forEach((ang, layer) => {
const lx = cx + S * .2 * Math.cos(t * (layer ? -.9 : .7) + s.ph + layer * 2.4), ly = cy + S * .2 * Math.sin(t * (layer ? .8 : -1.1) + s.ph + layer * 2.4);
const c = Math.cos(ang), sn = Math.sin(ang), R = s.n * .75;
g.fillStyle = pick(p.palette, layer);
g.globalCompositeOperation = layer ? 'multiply' : 'source-over';
for (let v = -R; v <= R; v++) for (let u = -R; u <= R; u++) {
const x = cx + (u * c - v * sn) * cell, y = cy + (u * sn + v * c) * cell, r = Math.hypot(x - cx, y - cy) / (S * .46);
if (r > 1) continue;
const light = Math.exp(-((Math.hypot(x - lx, y - ly) / (S * .26)) ** 2)), edge = 1 - r * r;
dot(g, x, y, cell * .56 * Math.sqrt(lerp(.04, 1, light) * edge));
}
});
g.globalCompositeOperation = 'source-over';
},
};
return halftone;
})();
/** Interference drawn in characters. */
export const ascii: Def = /*#__PURE__*/ (() => {
interface S { pre: HTMLPreElement; cols: number; rows: number; ph: number }
const RAMP = ' .·:-=+*#%@';
/** interference between two moving sources, drawn in characters */
const ascii: LoaderDef<S> = {
name: 'ascii', kind: 'dom', size: 48, still: .9, label: 'Loading',
setup({ el, p, rnd }) {
const cols = Math.round(lerp(10, 22, p.density)), fs = p.w / cols / .6, rows = Math.max(3, Math.floor(p.h / fs));
const pre = el.appendChild(document.createElement('pre'));
pre.style.cssText = `margin:0;padding:0;border:0;background:none;max-height:none;white-space:pre;color:inherit;font:${fs.toFixed(2)}px/1 var(--captain-font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);letter-spacing:0;height:100%;display:flex;flex-direction:column;justify-content:center;overflow:hidden;user-select:none`;
return { pre, cols, rows, ph: rnd() * 6.28 };
},
frame({ s }, t) {
const { cols, rows } = s, asp = .6;
const ax = cols * (.5 + .32 * Math.cos(t * .8 + s.ph)), ay = rows * (.5 + .4 * Math.sin(t * 1.1 + s.ph));
const bx = cols * (.5 + .32 * Math.cos(t * .63 + s.ph + 2.5)), by = rows * (.5 + .4 * Math.sin(t * .71 + s.ph + 1));
let out = '';
for (let y = 0; y < rows; y++) {
for (let x = 0; x < cols; x++) {
const da = Math.hypot((x - ax) * asp, y - ay), db = Math.hypot((x - bx) * asp, y - by);
const v = (Math.sin(da * 1.3 - t * 4) + Math.sin(db * 1.3 - t * 3.3)) / 4 + .5;
out += RAMP[Math.min(RAMP.length - 1, Math.floor(v * v * RAMP.length))] ?? ' ';
}
if (y < rows - 1) out += '\n';
}
if (s.pre.textContent !== out) s.pre.textContent = out;
},
};
return ascii;
})();
/** Particles riding a turning current. */
export const flow: Def = /*#__PURE__*/ (() => {
const LEN = 12;
interface P { x: Float32Array; y: Float32Array; life: number; hot: boolean }
interface S { ps: P[]; z: number; rnd: () => number; t: number }
function spawn(q: P, rnd: () => number) {
const a = rnd() * TAU, r = Math.sqrt(rnd()) * .44;
q.x.fill(.5 + Math.cos(a) * r);
q.y.fill(.5 + Math.sin(a) * r);
q.life = 1.5 + rnd() * 3;
}
function step(s: S, dt: number) {
s.t += dt;
for (const q of s.ps) {
q.x.copyWithin(1, 0);
q.y.copyWithin(1, 0);
const x = q.x[0] ?? .5, y = q.y[0] ?? .5, a = noise(x * 2.4, y * 2.4, s.z + s.t * .22) * TAU * 1.2 + s.t * .3;
q.x[0] = x + Math.cos(a) * dt * .2;
q.y[0] = y + Math.sin(a) * dt * .2;
q.life -= dt;
if (q.life < 0 || Math.hypot((q.x[0] ?? 0) - .5, (q.y[0] ?? 0) - .5) > .46) spawn(q, s.rnd);
}
}
/** particles riding a slowly turning current, with fading tails */
const flow: LoaderDef<S> = {
name: 'flow', kind: 'canvas', size: 48, stroke: 1 / 36, still: 0, label: 'Loading',
setup({ p, rnd }) {
const ps = Array.from({ length: Math.round(lerp(30, 110, p.density)) }, (_, i) => {
const q: P = { x: new Float32Array(LEN), y: new Float32Array(LEN), life: 0, hot: i % 7 === 0 };
spawn(q, rnd);
q.life *= rnd();
return q;
});
const s: S = { ps, z: rnd() * 50, rnd, t: 0 };
for (let i = 0; i < 60; i++) step(s, 1 / 60);
return s;
},
frame({ g, p, s }, _t, dt) {
if (dt) step(s, Math.min(dt, .05));
if (!g) return;
const S = p.h, ox = (p.w - S) / 2;
g.lineWidth = p.stroke;
g.lineCap = 'round';
for (const hot of [false, true]) {
g.strokeStyle = hot ? pick(p.palette, 0) : p.ink;
for (let k = 0; k < LEN - 1; k++) {
g.globalAlpha = (1 - k / (LEN - 1)) * (hot ? 1 : .55);
g.beginPath();
for (const q of s.ps) {
if (q.hot !== hot) continue;
const x0 = q.x[k] ?? 0, y0 = q.y[k] ?? 0, x1 = q.x[k + 1] ?? 0, y1 = q.y[k + 1] ?? 0;
if (Math.abs(x0 - x1) + Math.abs(y0 - y1) > .1) continue;
g.moveTo(ox + x0 * S, y0 * S);
g.lineTo(ox + x1 * S, y1 * S);
}
g.stroke();
}
}
g.globalAlpha = 1;
},
};
return flow;
})();
/** A tiny swarm following one bright leader. */
export const flock: Def = /*#__PURE__*/ (() => {
interface B { x: number; y: number; vx: number; vy: number; r: number; a: number; w: number }
interface S { bs: B[]; t: number; ph: number }
const lead = (s: S) => [.5 + .27 * Math.sin(s.t * .9 + s.ph), .5 + .27 * Math.sin(s.t * 1.4 + s.ph * 2)] as const;
function step(s: S, dt: number) {
s.t += dt;
const [lx, ly] = lead(s);
for (const b of s.bs) {
// each one chases its own place in a loose ring round the leader, on a spring, and keeps its distance
const a = b.a + s.t * b.w, tx = lx + Math.cos(a) * b.r, ty = ly + Math.sin(a) * b.r;
let fx = (tx - b.x) * 9 - b.vx * 3.2, fy = (ty - b.y) * 9 - b.vy * 3.2;
for (const o of s.bs) {
const dx = b.x - o.x, dy = b.y - o.y, d2 = dx * dx + dy * dy;
if (o !== b && d2 < .0025) { fx += dx / (d2 + .0004) * .05; fy += dy / (d2 + .0004) * .05; }
}
b.vx += fx * dt; b.vy += fy * dt;
b.x += b.vx * dt; b.y += b.vy * dt;
}
}
/** a tiny swarm following one bright leader, each on a spring to its own place near it */
const flock: LoaderDef<S> = {
name: 'flock', kind: 'canvas', size: 48, still: 0, label: 'Loading',
setup({ p, rnd }) {
const s: S = {
t: 0, ph: rnd() * TAU,
bs: Array.from({ length: Math.round(lerp(14, 40, p.density)) }, () => ({ x: .5, y: .5, vx: 0, vy: 0, r: lerp(.05, .17, Math.sqrt(rnd())), a: rnd() * TAU, w: (rnd() < .5 ? -1 : 1) * lerp(.6, 1.6, rnd()) })),
};
for (let i = 0; i < 150; i++) step(s, 1 / 60);
return s;
},
frame({ g, p, s }, _t, dt) {
for (let left = Math.min(dt, .05); left > 1e-6; left -= 1 / 60) step(s, Math.min(left, 1 / 60));
if (!g) return;
const S = p.h, ox = (p.w - S) / 2, [lx, ly] = lead(s);
g.strokeStyle = p.ink;
g.lineWidth = Math.max(1, Math.min(S * .02, 1.5 + S * .006));
g.lineCap = 'round';
g.globalAlpha = .8;
g.beginPath();
for (const b of s.bs) {
const v = Math.hypot(b.vx, b.vy) || 1, len = S * Math.min(.07, .02 + v * .08), x = ox + b.x * S, y = b.y * S;
g.moveTo(x, y);
g.lineTo(x - (b.vx / v) * len, y - (b.vy / v) * len);
}
g.stroke();
g.globalAlpha = 1;
g.fillStyle = pick(p.palette, 0);
dot(g, ox + lx * S, ly * S, S * .045);
},
};
return flock;
})();
/** A pulse of light, ordered-dithered to pixels. */
export const dither: Def = /*#__PURE__*/ (() => {
interface S { n: number }
const BAYER = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5];
/** a pulse of light, ordered-dithered to square pixels: a core that breathes and rings that leave it */
const dither: LoaderDef<S> = {
name: 'dither', kind: 'canvas', size: 48, still: .5, label: 'Loading',
setup: ({ p }) => ({ n: Math.round(lerp(12, 28, p.density)) }),
frame({ g, p, s }, t) {
if (!g) return;
const S = p.h, n = s.n, cell = S / n, ox = (p.w - S) / 2, gap = cell > 4 ? cell * .14 : 0;
const core = .26 + .07 * Math.sin(t * 2.4), ring = (t % 1.7) / 1.7, accent = pick(p.palette, 0);
for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) {
const r = Math.hypot(i + .5 - n / 2, j + .5 - n / 2) / (n / 2);
const a = clamp(1 - r / core) ** .8, b = Math.exp(-(((r - ring * .95) / .09) ** 2)) * (1 - ring) * .9;
const th = ((BAYER[(j % 4) * 4 + (i % 4)] ?? 0) + .5) / 16;
if (a > th) { g.fillStyle = accent; g.globalAlpha = 1; }
else if (b > th) { g.fillStyle = p.ink; g.globalAlpha = .8; }
else continue;
g.fillRect(ox + i * cell + gap / 2, j * cell + gap / 2, cell - gap, cell - gap);
}
g.globalAlpha = 1;
},
};
return dither;
})();
/** A sunflower of dots, pulsing outward. */
export const bloom: Def = /*#__PURE__*/ (() => {
interface S { n: number; arm: number }
const GOLD = Math.PI * (3 - Math.sqrt(5));
/** a sunflower of dots; a spiral arm of light winds outward while a pulse breathes through it */
const bloom: LoaderDef<S> = {
name: 'bloom', kind: 'canvas', size: 48, still: .7, label: 'Loading',
setup: ({ p, rnd }) => ({ n: Math.round(lerp(70, 240, p.density)), arm: rnd() < .5 ? 13 : 21 }),
frame({ g, p, s }, t) {
if (!g) return;
const S = p.h, cx = p.w / 2, cy = S / 2, c = (S * .45) / Math.sqrt(s.n), rot = t * .25, head = Math.floor(t * 9);
const accent = pick(p.palette, 0);
for (let i = 1; i < s.n; i++) {
const r = c * Math.sqrt(i), a = i * GOLD + rot, w = .5 + .5 * Math.sin(Math.sqrt(i) * 1.15 - t * 3.4);
const lit = (i + head) % s.arm === 0, size = c * (lit ? .42 : lerp(.12, .3, w)) * (.6 + .4 * (i / s.n));
g.fillStyle = lit ? accent : p.ink;
g.globalAlpha = lit ? 1 : lerp(.18, .6, w);
dot(g, cx + Math.cos(a) * r, cy + Math.sin(a) * r, size);
}
g.globalAlpha = 1;
},
};
return bloom;
})();
/* ---------- physical ---------- */
/** A vessel filling, sloshing, draining. */
export const liquid: Def = /*#__PURE__*/ (() => {
const NS = 'http://www.w3.org/2000/svg';
let uid = 0;
interface S { back: SVGPathElement; front: SVGPathElement; rim: SVGPathElement; bubbles: SVGCircleElement[]; level: number; last: number; vel: number }
const squircle = (cx: number, cy: number, r: number) => {
let d = '';
for (let i = 0; i <= 64; i++) {
const a = (i / 64) * TAU, c = Math.cos(a), s = Math.sin(a);
d += `${i ? 'L' : 'M'}${(cx + Math.sign(c) * Math.abs(c) ** .5 * r).toFixed(2)} ${(cy + Math.sign(s) * Math.abs(s) ** .5 * r).toFixed(2)}`;
}
return d + 'Z';
};
/** a squircle vessel filling, sloshing and draining; with `progress` it fills to that level */
const liquid: LoaderDef<S> = {
name: 'liquid', kind: 'dom', size: 48, stroke: 1 / 30, still: 1.9, label: 'Loading',
setup({ el, p }) {
const id = `cl-liquid-${++uid}`, S = p.h, cx = p.w / 2, cy = S / 2, r = S * .38;
const svg = document.createElementNS(NS, 'svg');
svg.setAttribute('viewBox', `0 0 ${p.w} ${S}`);
svg.setAttribute('width', String(p.w));
svg.setAttribute('height', String(S));
svg.innerHTML = `<defs><clipPath id="${id}"><path d="${squircle(cx, cy, r - p.stroke / 2)}"/></clipPath></defs><g clip-path="url(#${id})"><path/><path/></g><path fill="none" stroke="currentColor"/>`;
const [back, front] = Array.from(svg.querySelectorAll('g path')) as SVGPathElement[];
const rim = svg.lastElementChild as SVGPathElement;
rim.setAttribute('d', squircle(cx, cy, r));
rim.setAttribute('stroke-width', String(p.stroke));
const g = svg.querySelector('g') as SVGGElement;
const bubbles = [0, 1, 2].map(() => { const c = document.createElementNS(NS, 'circle'); g.appendChild(c); return c; });
el.appendChild(svg);
return { back: back as SVGPathElement, front: front as SVGPathElement, rim, bubbles, level: .1, last: .1, vel: 0 };
},
frame({ p, s }, t, dt) {
const S = p.h, top = S * .12, bottom = S * .88, accent = pick(p.palette, 0);
let level: number;
if (p.progress != null) { s.level = dt ? s.level + (p.progress - s.level) * (1 - Math.exp(-dt * 5)) : p.progress; level = s.level; }
else {
const u = t % 4.2;
level = u < 2.6 ? lerp(.08, .86, p.ease(u / 2.6)) : u < 3 ? .86 : lerp(.86, .08, p.ease(clamp((u - 3) / 1.2)));
}
if (dt) { s.vel = lerp(s.vel, Math.abs(level - s.last) / dt, .1); s.last = level; }
const y = lerp(bottom, top, level), amp = S * (.018 + clamp(s.vel) * .05);
const wave = (ph: number, a: number) => {
let d = `M0 ${S}`;
for (let i = 0; i <= 24; i++) {
const x = (i / 24) * p.w;
d += `L${x.toFixed(2)} ${(y + Math.sin(x / S * 7 + t * 3.1 + ph) * a + Math.sin(x / S * 13 - t * 2.3 + ph) * a * .4).toFixed(2)}`;
}
return d + `L${p.w} ${S}Z`;
};
s.back.setAttribute('d', wave(2.1, amp * 1.2));
s.back.setAttribute('fill', accent);
s.back.setAttribute('opacity', '.4');
s.front.setAttribute('d', wave(0, amp));
s.front.setAttribute('fill', accent);
s.rim.setAttribute('stroke-opacity', '.85');
s.bubbles.forEach((b, i) => {
const k = fract(t * .45 + i / 3), by = lerp(bottom, y, k);
b.setAttribute('cx', (p.w / 2 + Math.sin(i * 2.4 + t * 2) * S * .1 + (i - 1) * S * .12).toFixed(2));
b.setAttribute('cy', by.toFixed(2));
b.setAttribute('r', (S * .022 * (.6 + k * .6)).toFixed(2));
b.setAttribute('fill', '#fff');
b.setAttribute('opacity', (level > .15 ? .55 * (1 - k * k) : 0).toFixed(2));
});
},
};
return liquid;
})();
/** Fifteen pendulums drifting in and out of phase. */
export const pendulum: Def = /*#__PURE__*/ (() => {
interface S { n: number; colors: string[] }
const CYCLE = 14, BASE = 9;
/** a pendulum wave: each bob swings one more time per cycle than the one above, so they drift in and out of phase */
const pendulum: LoaderDef<S> = {
name: 'pendulum', kind: 'canvas', size: 48, still: 7, label: 'Loading',
palette: ['#2E5BFF', '#C2410C'],
setup({ p }) {
const n = Math.round(lerp(9, 21, p.density));
return { n, colors: Array.from({ length: n }, (_, i) => mix(pick(p.palette, 0), pick(p.palette, 1), i / (n - 1))) };
},
frame({ g, p, s }, t) {
if (!g) return;
const S = p.h, cx = p.w / 2, m = S * .12, step = (S - 2 * m) / (s.n - 1), A = S * .36, r = Math.min(step * .42, S * .05);
g.strokeStyle = p.ink;
g.lineWidth = 1;
g.globalAlpha = .1;
g.beginPath();
g.moveTo(cx, m - step * .6);
g.lineTo(cx, S - m + step * .6);
g.stroke();
s.colors.forEach((c, i) => {
const f = (BASE + i) / CYCLE, y = m + i * step;
const x = (k: number) => cx + A * Math.cos(TAU * f * (t - k * .008));
// a tapered tail whose length is the bob's own speed, then the bob
g.strokeStyle = c;
g.lineCap = 'round';
for (let k = 1; k <= 6; k++) {
g.globalAlpha = .3 * (1 - k / 7);
g.lineWidth = r * 2 * (1 - k / 7);
g.beginPath(); g.moveTo(x(k - 1), y); g.lineTo(x(k), y); g.stroke();
}
g.globalAlpha = 1;
g.fillStyle = c;
dot(g, x(0), y, r);
});
g.globalAlpha = 1;
},
};
return pendulum;
})();
/** Three glass beads bouncing, squashing on landing. */
export const beads: Def = /*#__PURE__*/ (() => {
interface S { fills: { base: string; hi: string; lo: string }[] }
const P = 1.05;
/** three glass beads bouncing in turn, squashing as they land, with shadows on the floor */
const beads: LoaderDef<S> = {
name: 'beads', kind: 'canvas', size: 48, aspect: 1.4, easing: 'spring', still: .45, label: 'Loading',
palette: ['#2E5BFF', '#1E8A4C', '#C2410C'],
setup: ({ p }) => ({ fills: [0, 1, 2].map(i => { const c = pick(p.palette, i); return { base: c, hi: mix(c, '#ffffff', .62), lo: mix(c, '#000000', .35) }; }) }),
frame({ g, p, s }, t) {
if (!g) return;
const S = p.h, floor = S * .8, R = S * .11, H = S * .48;
s.fills.forEach((f, i) => {
const u = ((t + i * P / 5) % P) / P, h = 4 * u * (1 - u);
const since = Math.min(u, 1 - u) * P, sq = (1 - p.ease(clamp(since / .16))) * .3;
const x = p.w * (.26 + i * .24), sy = 1 - sq, sx = 1 + sq * .8, y = floor - R * sy - h * H;
g.globalAlpha = .16 * (1 - h * .6);
g.fillStyle = p.ink;
g.beginPath();
g.ellipse(x, floor + R * .12, R * (1.05 - h * .45) * sx, R * .22 * (1 - h * .5), 0, 0, TAU);
g.fill();
g.globalAlpha = 1;
g.save();
g.translate(x, y);
g.scale(sx, sy);
const body = g.createRadialGradient(-R * .35, -R * .4, R * .1, 0, 0, R);
body.addColorStop(0, f.hi);
body.addColorStop(.55, f.base);
body.addColorStop(1, f.lo);
g.fillStyle = body;
g.beginPath();
g.arc(0, 0, R, 0, TAU);
g.fill();
g.fillStyle = '#fff';
g.globalAlpha = .85;
g.beginPath();
g.ellipse(-R * .36, -R * .44, R * .26, R * .15, -.6, 0, TAU);
g.fill();
g.globalAlpha = .35;
g.beginPath();
g.arc(0, 0, R * .78, .2, 1.3);
g.lineWidth = R * .1;
g.strokeStyle = '#fff';
g.lineCap = 'round';
g.stroke();
g.restore();
g.globalAlpha = 1;
});
},
};
return beads;
})();
/** A sheet folding in half, in half again, and open. */
export const fold: Def = /*#__PURE__*/ (() => {
interface Tile { el: HTMLDivElement; front: HTMLDivElement; back: HTMLDivElement }
interface S { tiles: Tile[]; face: string; rear: string }
const T = 3.4;
/** a sheet folds its right half over, then its bottom half up, holds, and opens again */
const fold: LoaderDef<S> = {
name: 'fold', kind: 'dom', size: 48, easing: 'smooth', still: 1.5, label: 'Loading',
setup({ el, p }) {
const S = p.h, half = Math.round(S * .29), paper = document.createElement('div');
paper.style.cssText = `position:absolute;left:${(p.w - half * 2) / 2}px;top:${(S - half * 2) / 2}px;width:${half * 2}px;height:${half * 2}px;transform-style:preserve-3d;perspective:none`;
el.style.perspective = `${S * 4}px`;
const c = pick(p.palette, 0);
const tiles = [[0, 0], [1, 0], [0, 1], [1, 1]].map(([x, y]) => {
const t = document.createElement('div'), front = document.createElement('div'), back = document.createElement('div');
t.style.cssText = `position:absolute;left:${(x ?? 0) * half}px;top:${(y ?? 0) * half}px;width:${half}px;height:${half}px;transform-style:preserve-3d;transform-origin:0 0`;
const r = ['3px 0 0 0', '0 3px 0 0', '0 0 0 3px', '0 0 3px 0'][(y ?? 0) * 2 + (x ?? 0)];
for (const f of [front, back]) { f.style.cssText = `position:absolute;inset:0;backface-visibility:hidden;-webkit-backface-visibility:hidden;border-radius:${r}`; t.appendChild(f); }
back.style.transform = x ? 'rotateY(180deg)' : 'rotateX(180deg)';
paper.appendChild(t);
return { el: t, front, back };
});
el.appendChild(paper);
return { tiles, face: c, rear: mix(c, '#ffffff', .45) };
},
frame({ p, s }, t) {
const u = t % T, e = p.ease;
const a = u < .6 ? e(u / .6) : u < 2.3 ? 1 : 1 - e(clamp((u - 2.75) / .55));
const b = u < .75 ? 0 : u < 2.1 ? e(clamp((u - .75) / .6)) : 1 - e(clamp((u - 2.1) / .55));
const shade = (x: number) => Math.abs(Math.sin(x * Math.PI)) * .3;
s.tiles.forEach((tile, i) => {
const right = i % 2 === 1, low = i > 1, ay = right ? a : 0, bx = low ? b : 0;
const lift = (right ? ay : 0) + (low ? bx * 2 : 0);
tile.el.style.transform = `translateZ(${(lift * .6).toFixed(2)}px) rotateX(${(180 * bx).toFixed(2)}deg) rotateY(${(-180 * ay).toFixed(2)}deg)`;
const k = Math.max(shade(ay), shade(bx));
tile.front.style.background = mix(s.face, '#000000', k);
tile.back.style.background = mix(s.rear, '#000000', k * .6);
});
},
};
return fold;
})();
/** Drops of ink spreading in water. */
export const ink: Def = /*#__PURE__*/ (() => {
interface Drop { x: number; y: number; r: number; at: number; color: string; z: number }
interface S { cycle: number; drops: Drop[] }
const T = 3.8;
function drops(p: { w: number; h: number; density: number; seed: number; palette: string[] }, cycle: number): S {
const r = rng(p.seed * 17 + cycle * 131), n = Math.round(lerp(3, 7, p.density));
return {
cycle,
drops: Array.from({ length: n }, (_, i) => {
const a = r() * TAU, d = Math.sqrt(r()) * p.h * .2;
return { x: p.w / 2 + Math.cos(a) * d, y: p.h / 2 + Math.sin(a) * d, r: p.h * lerp(.16, .3, r()), at: (i / n) * 1.6 + r() * .2, color: pick(p.palette, i), z: r() * 40 };
}),
};
}
/** drops of ink landing in water, spreading with ragged edges, overprinting where they meet */
const ink: LoaderDef<S> = {
name: 'ink', kind: 'canvas', size: 48, still: 2.3, label: 'Loading',
palette: ['#2E5BFF', '#6B4BD6', '#0E7C86'],
setup: ({ p }) => drops(p, 0),
frame(c, t) {
const { g, p } = c;
if (!g) return;
const cycle = Math.floor(t / T), u = t - cycle * T;
if (c.s.cycle !== cycle) c.s = drops(p, cycle);
const fade = 1 - clamp((u - 3.1) / .7);
g.globalCompositeOperation = 'multiply';
for (const d of c.s.drops) {
const k = clamp((u - d.at) / 1.8);
if (k <= 0) continue;
const grow = 1 - (1 - k) ** 3;
g.fillStyle = d.color;
const R = d.r * grow, a = fade * (1 - k * .4);
g.beginPath();
for (let i = 0; i <= 48; i++) {
const t2 = (i / 48) * TAU, q = R * (1 + .14 * noise(Math.cos(t2) * 1.7 + d.z, Math.sin(t2) * 1.7, k * 1.3));
const x = d.x + Math.cos(t2) * q, y = d.y + Math.sin(t2) * q;
i ? g.lineTo(x, y) : g.moveTo(x, y);
}
const fill = g.createRadialGradient(d.x, d.y, 0, d.x, d.y, R * 1.14);
fill.addColorStop(0, d.color);
fill.addColorStop(.6, d.color);
fill.addColorStop(1, d.color);
g.globalAlpha = .28 * a;
g.fillStyle = d.color;
g.fill();
g.save();
g.clip();
g.globalAlpha = .5 * a;
g.lineWidth = R * .22;
g.strokeStyle = d.color;
g.stroke();
g.globalAlpha = .35 * a;
g.beginPath();
g.arc(d.x, d.y, R * .42, 0, TAU);
g.fillStyle = fill;
g.fill();
g.restore();
}
g.globalCompositeOperation = 'source-over';
g.globalAlpha = 1;
},
};
return ink;
})();
/* ---------- shapes ---------- */
/** One shape morphing from circle to squircle to flower. */
export const squircle: Def = /*#__PURE__*/ (() => {
const NS = 'http://www.w3.org/2000/svg', SAMPLES = 96;
// superformula keys: m, n1, n2, n3
const KEYS: [number, number, number, number][] = [[4, 2, 2, 2], [4, 5, 5, 5], [6, 3.2, 6, 6], [4, 5, 5, 5], [3, 4.5, 7, 7], [4, 2, 2, 2]];
interface S { path: SVGPathElement; shapes: Float32Array[] }
function shape([m, n1, n2, n3]: [number, number, number, number]) {
const r = new Float32Array(SAMPLES);
let max = 0;
for (let i = 0; i < SAMPLES; i++) {
const a = (i / SAMPLES) * TAU, v = (Math.abs(Math.cos((m * a) / 4)) ** n2 + Math.abs(Math.sin((m * a) / 4)) ** n3) ** (-1 / n1);
r[i] = v; max = Math.max(max, v);
}
return r.map(v => v / max);
}
/** one shape morphing through circle, squircle, flower and a soft triangle, turning as it changes */
const squircle: LoaderDef<S> = {
name: 'squircle', kind: 'dom', size: 48, easing: 'spring', still: .9, label: 'Loading',
palette: ['#2E5BFF', '#6B4BD6', '#C2410C', '#1E8A4C'],
setup({ el, p }) {
const svg = document.createElementNS(NS, 'svg'), path = document.createElementNS(NS, 'path');
svg.setAttribute('viewBox', `0 0 ${p.w} ${p.h}`);
svg.setAttribute('width', String(p.w));
svg.setAttribute('height', String(p.h));
svg.appendChild(path);
el.appendChild(svg);
return { path, shapes: KEYS.map(shape) };
},
frame({ p, s }, t) {
const seg = 1.1, n = KEYS.length - 1, u = t % (seg * n), k = Math.floor(u / seg), f = p.ease(clamp((u - k * seg) / (seg * .7)));
const a = s.shapes[k], b = s.shapes[k + 1];
if (!a || !b) return;
const R = p.h * .4, cx = p.w / 2, cy = p.h / 2, rot = t * .5 + (k + f) * (TAU / 8);
let d = '';
for (let i = 0; i < SAMPLES; i++) {
const ang = (i / SAMPLES) * TAU, r = R * ((a[i] ?? 1) + ((b[i] ?? 1) - (a[i] ?? 1)) * f);
d += `${i ? 'L' : 'M'}${(cx + Math.cos(ang + rot) * r).toFixed(2)} ${(cy + Math.sin(ang + rot) * r).toFixed(2)}`;
}
s.path.setAttribute('d', d + 'Z');
s.path.setAttribute('fill', mix(pick(p.palette, k), pick(p.palette, k + 1), clamp(f)));
},
};
return squircle;
})();
/** Nested polygons stepping round, one vertex at a time. */
export const polygon: Def = /*#__PURE__*/ (() => {
interface S { n: number; dir: number }
/** nested polygons, each stepping round by one vertex at a time, slightly out of step with the next */
const polygon: LoaderDef<S> = {
name: 'polygon', kind: 'canvas', size: 48, stroke: 1 / 32, easing: 'spring', still: .5, label: 'Loading',
setup: ({ p, rnd }) => ({ n: Math.round(lerp(3, 6, p.density)), dir: rnd() < .5 ? 1 : -1 }),
frame({ g, p, s }, t) {
if (!g) return;
const S = p.h, cx = p.w / 2, cy = S / 2, P = 1.3;
g.lineJoin = 'round';
for (let i = 0; i < s.n; i++) {
const sides = 3 + i, R = S * lerp(.12, .44, s.n < 2 ? 1 : i / (s.n - 1)), u = t - i * .09;
const k = Math.floor(u / P), f = p.ease(clamp((u - k * P) / (P * .6)));
const rot = s.dir * (i % 2 ? -1 : 1) * (k + f) * (TAU / sides) - Math.PI / 2;
g.beginPath();
for (let v = 0; v <= sides; v++) {
const a = rot + (v / sides) * TAU, x = cx + Math.cos(a) * R, y = cy + Math.sin(a) * R;
v ? g.lineTo(x, y) : g.moveTo(x, y);
}
g.closePath();
if (i === 0) { g.fillStyle = pick(p.palette, 0); g.globalAlpha = 1; g.fill(); }
else { g.strokeStyle = p.ink; g.lineWidth = p.stroke; g.globalAlpha = lerp(.85, .35, i / s.n); g.stroke(); }
}
g.globalAlpha = 1;
},
};
return polygon;
})();
/** A line drawing itself, then letting go. */
export const draw: Def = /*#__PURE__*/ (() => {
interface S { pts: Float32Array; n: number }
const CURVES: [number, number][] = [[3, 2], [5, 4], [3, 4], [5, 6], [1, 2]];
/** a line drawing itself along a seeded Lissajous knot, then letting go from the tail; with `progress` it draws to that point */
const draw: LoaderDef<S> = {
name: 'draw', kind: 'canvas', size: 48, stroke: 1 / 18, easing: 'smooth', still: 1.05, label: 'Loading',
setup({ p, rnd }) {
const [a, b] = pick(CURVES, Math.floor(rnd() * CURVES.length)), ph = rnd() * Math.PI, n = 360, pts = new Float32Array(n * 2 + 2);
for (let i = 0; i <= n; i++) {
const u = (i / n) * TAU;
pts[i * 2] = p.w / 2 + Math.sin(a * u + ph) * p.h * .38;
pts[i * 2 + 1] = p.h / 2 + Math.sin(b * u) * p.h * .38;
}
return { pts, n };
},
frame({ g, p, s }, t) {
if (!g) return;
let head: number, tail: number;
if (p.progress != null) { head = p.progress; tail = 0; }
else {
const u = t % 2.6;
head = p.ease(clamp(u / 1.25));
tail = p.ease(clamp((u - 1.45) / 1.05));
}
const i0 = Math.floor(tail * s.n), i1 = Math.ceil(head * s.n), accent = pick(p.palette, 0);
g.strokeStyle = p.ink;
g.globalAlpha = .08;
g.lineWidth = p.stroke;
g.lineCap = g.lineJoin = 'round';
const path = (a: number, b: number) => {
g.beginPath();
for (let i = a; i <= b; i++) { const x = s.pts[i * 2] ?? 0, y = s.pts[i * 2 + 1] ?? 0; i === a ? g.moveTo(x, y) : g.lineTo(x, y); }
g.stroke();
};
path(0, s.n);
if (i1 > i0) {
g.globalAlpha = 1;
g.strokeStyle = accent;
path(i0, i1);
g.fillStyle = accent;
dot(g, s.pts[i1 * 2] ?? 0, s.pts[i1 * 2 + 1] ?? 0, p.stroke * 1.1);
}
g.globalAlpha = 1;
},
};
return draw;
})();
/* ---------- progress ---------- */
/** An indeterminate bar that moves like it means it. */
export const inchworm: Def = /*#__PURE__*/ (() => {
interface S { v: number }
const P = 1.4, HOP = .34;
/** an indeterminate bar that moves like an inchworm: the head reaches, the tail catches up, the body humps */
const inchworm: LoaderDef<S> = {
name: 'inchworm', kind: 'canvas', size: 20, aspect: 7, still: .55, label: 'Loading',
setup: () => ({ v: 0 }),
frame({ g, p, s }, t, dt) {
if (!g) return;
const W = p.w, H = p.h, th = Math.max(2, H * .26), y = H * .62, x0 = th, x1 = W - th, L = x1 - x0;
g.lineCap = 'round';
g.lineWidth = th;
g.strokeStyle = p.ink;
g.globalAlpha = .12;
g.beginPath(); g.moveTo(x0, y); g.lineTo(x1, y); g.stroke();
g.globalAlpha = 1;
g.strokeStyle = pick(p.palette, 0);
if (p.progress != null) {
s.v = dt ? s.v + (p.progress - s.v) * (1 - Math.exp(-dt * 6)) : p.progress;
g.beginPath(); g.moveTo(x0, y); g.lineTo(x0 + L * s.v, y); g.stroke();
return;
}
const k = Math.floor(t / P), u = (t - k * P) / P;
const head = k * HOP + HOP * p.ease(clamp(u / .55)) + .12, tail = k * HOP + HOP * EASE.smooth(clamp((u - .3) / .6));
const hump = (1 - clamp((head - tail - .12) / HOP)) * H * .4;
const seg = (a: number, b: number) => {
const len = 1.12, A = ((a % len) + len) % len - .12, B = A + (b - a);
const px = (q: number) => x0 + clamp(q, 0, 1) * L;
if (B <= 0 || A >= 1) return;
const xa = px(A), xb = px(B), mid = (xa + xb) / 2;
g.beginPath();
g.moveTo(xa, y);
g.quadraticCurveTo(mid, y - hump * 2 * ((xb - xa) / Math.max(1, (b - a) * L)), xb, y);
g.stroke();
};
seg(tail, head);
},
};
return inchworm;
})();
/** A card skeleton breathing in reading order. */
export const skeleton: Def = /*#__PURE__*/ (() => {
interface S { blocks: HTMLDivElement[] }
/** a card skeleton that breathes in reading order: avatar, name, lines, then the picture */
const skeleton: LoaderDef<S> = {
name: 'skeleton', kind: 'dom', size: 96, aspect: 1.6, still: .8, label: 'Loading content',
setup({ el, p, rnd }) {
const W = p.w, H = p.h, u = H / 12, lines = Math.round(lerp(2, 5, p.density)), blocks: HTMLDivElement[] = [];
const add = (x: number, y: number, w: number, h: number, r: number) => {
const b = el.appendChild(document.createElement('div'));
b.style.cssText = `position:absolute;left:${x}px;top:${y}px;width:${w}px;height:${h}px;border-radius:${r}px;background:currentColor`;
blocks.push(b);
};
add(u, u, u * 2.4, u * 2.4, u * 1.2);
add(u * 4.2, u * 1.2, W * .38, u * .8, u * .4);
add(u * 4.2, u * 2.5, W * .22, u * .7, u * .35);
const top = u * 4.6, gap = (H * .52 - u) / Math.max(1, lines);
for (let i = 0; i < lines; i++) add(u, top + i * gap, (W - 2 * u) * (i === lines - 1 ? lerp(.45, .7, rnd()) : lerp(.86, 1, rnd())), u * .7, u * .35);
add(W - u - W * .26, H - u - u * 2.6, W * .26, u * 2.6, u * .5);
return { blocks };
},
frame({ s }, t) {
s.blocks.forEach((b, i) => {
const k = .5 + .5 * Math.sin((t - i * .11) * 3.6);
b.style.opacity = lerp(.07, .19, k * k).toFixed(3);
});
},
};
return skeleton;
})();
/** A comet of lit ticks around a dial. */
export const ticks: Def = /*#__PURE__*/ (() => {
interface S { n: number; v: number }
/** a dial of ticks with a comet of light running round it, faster mid-lap; with `progress` it fills the dial */
const ticks: LoaderDef<S> = {
name: 'ticks', kind: 'canvas', size: 48, stroke: 1 / 28, easing: 'smooth', still: .6, label: 'Loading',
palette: ['#2E5BFF', '#6B4BD6'],
setup: ({ p }) => ({ n: Math.round(lerp(24, 64, p.density)), v: 0 }),
frame({ g, p, s }, t, dt) {
if (!g) return;
const S = p.h, cx = p.w / 2, cy = S / 2, r0 = S * .3, r1 = S * .43, lap = 1.5;
const k = Math.floor(t / lap), head = (k + p.ease((t - k * lap) / lap)) * TAU;
const a0 = pick(p.palette, 0), a1 = pick(p.palette, 1);
if (p.progress != null) s.v = dt ? s.v + (p.progress - s.v) * (1 - Math.exp(-dt * 6)) : p.progress;
g.lineCap = 'round';
g.lineWidth = p.stroke;
for (let i = 0; i < s.n; i++) {
const a = (i / s.n) * TAU - Math.PI / 2;
let lit: number;
if (p.progress != null) lit = i / s.n < s.v ? 1 : 0;
else { const d = (((head - (i / s.n) * TAU) % TAU) + TAU) % TAU; lit = Math.exp(-d / 1.1); }
const ext = r1 + S * .045 * lit;
g.strokeStyle = lit > .04 ? mix(a1, a0, lit) : p.ink;
g.globalAlpha = lit > .04 ? lerp(.3, 1, lit) : .16;
g.beginPath();
g.moveTo(cx + Math.cos(a) * r0, cy + Math.sin(a) * r0);
g.lineTo(cx + Math.cos(a) * ext, cy + Math.sin(a) * ext);
g.stroke();
}
g.globalAlpha = 1;
},
};
return ticks;
})();
/* ---------- shaders ---------- */
/** A 4×4 mesh of squares the palette flows across, one beat per diagonal. */
export const mesh: Def = /*#__PURE__*/ (() => {
interface S { n: number; ph: number }
/** a 4×4 mesh of squares; the palette flows across it as one colour field on the clock, each square stepping a beat behind its neighbour */
const mesh: LoaderDef<S> = {
name: 'mesh', kind: 'canvas', size: 48, still: 2.2, label: 'Loading', palette: ['#2E5BFF', '#C2410C', '#6B4BD6', '#C98A0B'],
setup: ({ p, rnd }) => ({ n: p.density > .7 ? 5 : 4, ph: rnd() * .5 }),
frame({ g, p, s }, t) {
if (!g) return;
const S = p.h, n = s.n, m = S * .1, gap = S * .05, c = (S - 2 * m - gap * (n - 1)) / n, ox = (p.w - S) / 2, k = p.palette.length;
for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) {
// a diagonal wave: the further along the diagonal, the later the square in the cycle
const u = t * .55 - (x + y) / (2 * n - 2) * .9 + s.ph, i = Math.floor(u), f = p.ease(fract(u));
g.fillStyle = mix(pick(p.palette, ((i % k) + k) % k), pick(p.palette, (((i + 1) % k) + k) % k), f);
const pulse = .82 + .18 * Math.sin((u - i) * Math.PI);
const w = c * pulse, cx = ox + m + x * (c + gap) + c / 2, cy = m + y * (c + gap) + c / 2;
rr(g, cx - w / 2, cy - w / 2, w, w, w * .22);
g.fill();
}
},
};
return mesh;
})();
/** A wobbling glass drop bending the stripes behind it. */
export const glass: Def = /*#__PURE__*/ shader('glass', `
float f(vec2 p){
vec2 a=.12*vec2(cos(T*1.1),sin(T*1.3)),b=.12*vec2(cos(T*.8+2.),sin(T*1.7+1.)),c=.1*vec2(cos(T*1.4+4.),sin(T*.9+3.));
return .03/dot(p-a,p-a)+.022/dot(p-b,p-b)+.016/dot(p-c,p-c);
}
vec3 stripes(vec2 p){
float k=fract((p.x+p.y)*(4.+5.*D)+Z*3.),i=floor(k*3.);
return i<1.?C0:i<2.?C1:C2;
}
void main(){
vec2 p=(gl_FragCoord.xy-.5*R)/min(R.x,R.y);
float v=f(p),e=1.5/min(R.x,R.y);
vec2 n=vec2(f(p+vec2(.003,0))-f(p-vec2(.003,0)),f(p+vec2(0,.003))-f(p-vec2(0,.003)));
n/=v*v;
float inside=smoothstep(1.-.04,1.+.04,v);
vec3 bg=stripes(p),gl=stripes(p+n*.09);
float rim=smoothstep(1.,1.35,v)*(1.-smoothstep(1.35,2.4,v));
float spec=pow(max(0.,dot(normalize(vec3(-n*2.5,1.)),normalize(vec3(-.5,.6,.8)))),24.);
float edge=1.-smoothstep(1.,1.25,v);vec3 c=mix(bg,gl*(1.-edge*.35),inside)+inside*(rim*.25+spec*.6);
float disc=smoothstep(.46+e,.46-e,length(p));
float a=max(disc*.16,inside);
gl_FragColor=vec4(c*a,a);
}`, { palette: ['#2E5BFF', '#9DB6FF', '#EEF1F6'], still: 1.3 });
/** a sphere lit by a moving light and drawn only in film grain: brighter means more grains */
/** A lit sphere made of film grain. */
export const grain: Def = /*#__PURE__*/ shader('grain', `
void main(){
float px=floor(1.+D*2.5);
vec2 cell=floor(gl_FragCoord.xy/px)*px;
vec2 p=(cell-.5*R)/min(R.x,R.y);
float r=.33+.02*sin(T*2.),l=length(p);
vec3 L=normalize(vec3(cos(T*.9+Z*6.),sin(T*.7)*.6,.75));
float z=sqrt(max(0.,r*r-l*l))/r;
vec3 n=normalize(vec3(p/r,z));
float lit=l<r?clamp(dot(n,L),0.,1.)*.95+.05:.12*smoothstep(r+.12,r,l);
float g=h(cell+floor(T*24.)*vec2(17.,31.));
float on=step(g,lit*lit);
vec3 c=mix(C1,C0,lit);
gl_FragColor=vec4(c*on,on);
}`, { palette: ['#FFB020', '#C2410C'], still: .8 });
/** Every definition, in catalogue order. */
export const DEFS = { thinking, reading, searching, planning, delegating, waiting, scramble, typewriter, shimmer, anagram, counter, braille, dotfield, orbit, breathe, halftone, ascii, flow, flock, dither, bloom, liquid, pendulum, beads, fold, ink, squircle, polygon, draw, inchworm, skeleton, ticks, mesh, glass, grain } as const;Usage
import { Orbit, Thinking, createLoaderClock } from "@/components/ui/loaders"
<Thinking size={24} />
// Your own clock: pause it, set it, scrub it, and every loader on it follows.
const clock = createLoaderClock()
<Orbit clock={clock} size={64} />Props
| Prop | Type | Default | What it does |
|---|---|---|---|
| size | number | 48 | Height in px. Text loaders use half of it as their font size. |
| color | string | currentColor | Ink for the neutral parts, so it follows your text colour and theme. |
| palette | string[] | Accent colours, used in order. | |
| speed | number | 1 | 1 is the designed speed. Changing it keeps the current pose. |
| clock | LoaderClock | pageClock | The clock it follows. createLoaderClock() makes one you can pause, set and scrub. |
| phase | number | 0 | Seconds ahead of the clock, to stagger a list on purpose. |
| progress | number | 0 to 1 on liquid, ticks, inchworm, counter and line. Leave it out for indeterminate. | |
| done | boolean | Eases the motion to a stop and announces doneLabel. | |
| text | string | string[] | Words for the text loaders. An array cycles. | |
| reducedMotion | "user" | "always" | "never" | "user" | user follows the OS and shows a designed still pose. |
Keyboard
- Left / Right
- Scrub the demo clock a tenth of a second
- Shift + arrows
- A whole second
- Home
- Back to zero
Accessibility
- Each loader is role=status with a stable label; the moving art is aria-hidden.
- Under reduced motion each one holds a designed still pose.
- A loader off screen stops drawing and picks the beat up again when it returns.