Skip to content
Shaken UI
Sign in

Dot Loader

Save

A tiny 3x3 or 4x4 dot grid for agent thinking states, with scan, wave, orbit, pulse and scatter patterns, an optional shimmering label and elapsed timer, and dots that gather into a check or an x when the work ends.

Category
AI elements
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Dot Loader preview
Large loaderMedium loaderSmall loaderExtra small loader
Drafting the migration plan

Inline, it sits on the text baseline: checking 3 sources

Installation

npx @shakenui/cli add dot-loader

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add dot-loader --dry-run

Usage

dot-loader-example.tsx
"use client";

import { useEffect, useState } from "react";
import { DotGrid, DotLoader, type DotLoaderPattern } from "@/components/shaken/agent/dot-loader";

const patterns: { pattern: DotLoaderPattern; grid: 3 | 4; use: string }[] = [
  { pattern: "wave", grid: 3, use: "Thinking" },
  { pattern: "scan", grid: 4, use: "Reading files" },
  { pattern: "orbit", grid: 3, use: "Waiting on a tool" },
  { pattern: "pulse", grid: 4, use: "Planning" },
  { pattern: "scatter", grid: 4, use: "Searching" },
];

export default function DotLoaderExample() {
  // The second step finishes after a few seconds so the dots gather into a check.
  const [indexed, setIndexed] = useState(false);
  useEffect(() => {
    const id = setTimeout(() => setIndexed(true), 3200);
    return () => clearTimeout(id);
  }, []);

  return (
    <div className="grid w-full max-w-md gap-8">
      <div className="grid grid-cols-5 gap-2">
        {patterns.map((item) => (
          <div key={item.pattern} className="grid justify-items-center gap-3">
            <DotGrid pattern={item.pattern} grid={item.grid} size="lg" className="text-zinc-950 dark:text-white" />
            <span className="font-mono text-xs text-zinc-500">{item.pattern}</span>
          </div>
        ))}
      </div>

      <ul className="grid gap-2.5 border-t border-zinc-950/[0.07] pt-6 dark:border-white/[0.08]">
        <li>
          <DotLoader status="done" pattern="scan" grid={4} label="Read 14 files in src/billing" timer startedAt={Date.now() - 2100} endedAt={Date.now()} />
        </li>
        <li>
          <DotLoader
            status={indexed ? "done" : "running"}
            pattern="orbit"
            label="Indexing invoices.csv"
            doneLabel="Indexed 2,318 rows"
            timer
          />
        </li>
        <li>
          <DotLoader pattern="wave" label="Thinking about the refund policy" shimmer timer />
        </li>
      </ul>
    </div>
  );
}

API

PropTypeDefaultDescription
pattern"scan" | "wave" | "orbit" | "pulse" | "scatter""wave"How light travels across the grid while running.
grid3 | 43Dots per side.
size"xs" | "sm" | "md" | "lg""sm"12, 16, 24 or 40px. DotGrid also takes a number of pixels.
status"idle" | "running" | "done" | "failed""running"Running animates; done and failed gather the dots into a check or an x; idle holds them dim.
labelReactNode—Visible text beside the grid. Also the screen reader status.
doneLabel / failedLabelReactNodelabelText shown once the status is done or failed.
shimmerbooleanfalseA slow highlight travels across the label while running.
timerbooleanfalseShows the elapsed time in mono after the label; it stops when the status leaves running.
startedAt / endedAtnumber | Datemount time / when running stopsWhen the work started and ended.
ariaLabelstring—Screen reader text when there is no visible label.
DotGrid tone"status" | "inherit""status"DotGrid: color the dots by status, or use the current text color.
formatElapsed(ms) => string—The timer format on its own: 4.2s, 2m 05s, 1h 02m.

Accessibility

  • DotLoader is a polite status region (role="status"); its label, or ariaLabel, is announced when the status changes. The elapsed timer is aria-hidden so it is not read every tick.
  • The dot grid is decorative (aria-hidden); state is always carried by text.
  • Under reduced motion the grid holds one still pose, the label shimmer is off, and the check or x appears without the dots travelling. The timer keeps counting.
  • The animation pauses while the loader is off screen or the tab is hidden.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/agent/dot-loader.tsxdot-loader
  • npm packages: noneReact and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/dot-loader/0.1.0.json.

agent/dot-loader.tsxShow
agent/dot-loader.tsx
"use client";

import { type ComponentProps, type ReactNode, useEffect, useMemo, useRef, useState } from "react";

/*
 * Dot loader: a tiny grid of dots (3x3 or 4x4) where light travels in a pattern while an
 * agent works. When the work finishes, the same dots glide into a check (or an x on failure),
 * so the loader resolves into its result instead of being swapped for an icon.
 *
 * Brightness is computed per dot from one clock and written straight to the DOM; all loaders
 * share one requestAnimationFrame loop, and a loader only animates while it is on screen, the
 * tab is visible, and motion is allowed. Under reduced motion the grid holds one still pose and
 * the result appears without travel.
 */

export type DotLoaderPattern = "scan" | "wave" | "orbit" | "pulse" | "scatter";
export type DotLoaderStatus = "idle" | "running" | "done" | "failed";
export type DotLoaderSize = "xs" | "sm" | "md" | "lg";

export const dotLoaderPatterns: DotLoaderPattern[] = ["scan", "wave", "orbit", "pulse", "scatter"];

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

const pixelSizes: Record<DotLoaderSize, number> = { xs: 12, sm: 16, md: 24, lg: 40 };
const textSizes: Record<DotLoaderSize, string> = { xs: "text-xs", sm: "text-sm", md: "text-sm", lg: "text-[15px]" };
const gaps: Record<DotLoaderSize, string> = { xs: "gap-1.5", sm: "gap-2", md: "gap-2.5", lg: "gap-3" };

const statusColor: Record<DotLoaderStatus, string> = {
  idle: "text-zinc-500",
  running: "text-zinc-950 dark:text-white",
  done: "text-emerald-600 dark:text-emerald-400",
  failed: "text-red-600 dark:text-red-400",
};

// ---------------------------------------------------------------------------
// Geometry. Everything is drawn in a 16 x 16 box and scaled by the SVG.

const BOX = 16;
const DIM = 0.16;

type Dot = { x: number; y: number; col: number; row: number };

function gridDots(n: number): Dot[] {
  const cell = BOX / n;
  const dots: Dot[] = [];
  for (let row = 0; row < n; row++) {
    for (let col = 0; col < n; col++) dots.push({ x: (col + 0.5) * cell, y: (row + 0.5) * cell, col, row });
  }
  return dots;
}

type Pt = [number, number];

/** Evenly spaced points along a polyline, endpoints included. */
function along(path: Pt[], count: number): Pt[] {
  const lengths = path.slice(1).map((p, i) => Math.hypot(p[0] - path[i]![0], p[1] - path[i]![1]));
  const total = lengths.reduce((a, b) => a + b, 0);
  const out: Pt[] = [];
  for (let k = 0; k < count; k++) {
    let d = count === 1 ? total / 2 : (total * k) / (count - 1);
    let s = 0;
    while (s < lengths.length - 1 && d > lengths[s]!) d -= lengths[s++]!;
    const a = path[s]!;
    const b = path[s + 1]!;
    const f = lengths[s] ? Math.min(1, d / lengths[s]!) : 0;
    out.push([a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f]);
  }
  return out;
}

const checkPath: Pt[] = [
  [3.25, 8.6],
  [6.6, 11.9],
  [12.75, 4.4],
];

function crossPoints(count: number): Pt[] {
  const a = Math.ceil(count / 2);
  const b = count - a;
  // Fewer dots make a smaller x, so its beads still touch.
  const lo = count < 12 ? 5 : 4.25;
  const hi = BOX - lo;
  const first = along([[lo, lo], [hi, hi]], a);
  // The second arm skips the exact center when the first one already holds it.
  let second = along([[hi, lo], [lo, hi]], b + (a % 2));
  if (a % 2) second = second.filter((_, i) => i !== Math.floor(second.length / 2));
  return [...first, ...second];
}

/** Assigns each target point the nearest free dot, so the dots take short, uncrossed paths. */
function assign(dots: Dot[], targets: Pt[]): Pt[] {
  const free = new Set(dots.map((_, i) => i));
  const result: Pt[] = dots.map((d) => [d.x, d.y]);
  for (const target of targets) {
    let best = -1;
    let bestD = Infinity;
    for (const i of free) {
      const d = Math.hypot(dots[i]!.x - target[0], dots[i]!.y - target[1]);
      if (d < bestD) {
        bestD = d;
        best = i;
      }
    }
    if (best < 0) break;
    free.delete(best);
    result[best] = target;
  }
  return result;
}

// ---------------------------------------------------------------------------
// Patterns. Each dot gets a phase in [0, 1); light passes a dot when the cycle reaches it,
// with a quick rise and an exponential tail.

type PatternSpec = {
  /** Seconds per cycle. */
  cycle: number;
  /** How fast the tail fades; higher is a shorter tail. */
  decay: number;
  /** Discrete steps per cycle (0 = continuous). */
  steps: number;
  /** Cycle position used as the still pose under reduced motion. */
  still: number;
  phase: (dot: Dot, n: number, index: number) => number;
};

function ringIndex(dot: Dot, n: number): number {
  const last = n - 1;
  const { col, row } = dot;
  if (row !== 0 && row !== last && col !== 0 && col !== last) return -1;
  if (row === 0) return col;
  if (col === last) return last + row;
  if (row === last) return 2 * last + (last - col);
  return 3 * last + (last - row);
}

// A fixed shuffle, so "scatter" looks random but is identical on every render and server.
const scatterOrder = [5, 12, 2, 9, 14, 0, 7, 11, 3, 15, 6, 1, 10, 13, 4, 8];

const patterns: Record<DotLoaderPattern, PatternSpec> = {
  scan: { cycle: 1.6, decay: 9, steps: 0, still: 0.3, phase: (d, n) => (d.col / Math.max(1, n - 1)) * 0.42 },
  wave: { cycle: 1.5, decay: 7, steps: 0, still: 0.32, phase: (d, n) => ((d.col + d.row) / Math.max(1, 2 * (n - 1))) * 0.5 },
  orbit: {
    cycle: 1.2,
    decay: 3.6,
    steps: 0,
    still: 0.4,
    phase: (d, n) => {
      const k = ringIndex(d, n);
      return k < 0 ? -1 : k / (4 * (n - 1));
    },
  },
  pulse: {
    cycle: 1.8,
    decay: 8,
    steps: 0,
    still: 0.2,
    phase: (d) => (Math.hypot(d.x - BOX / 2, d.y - BOX / 2) / Math.hypot(BOX / 2, BOX / 2)) * 0.45,
  },
  scatter: {
    cycle: 1.6,
    decay: 10,
    steps: 0,
    still: 0.5,
    phase: (_, n, i) => {
      const order = scatterOrder.filter((v) => v < n * n);
      return order.indexOf(i) / (n * n);
    },
  },
};

function brightness(spec: PatternSpec, phase: number, t: number): number {
  if (phase < 0) return DIM;
  let p = t / spec.cycle;
  if (spec.steps) p = Math.floor(p * spec.steps) / spec.steps;
  const f = (((p - phase) % 1) + 1) % 1;
  const rise = 0.035;
  const light = f < rise ? f / rise : Math.exp(-(f - rise) * spec.decay);
  return DIM + (1 - DIM) * light;
}

// ---------------------------------------------------------------------------
// One shared animation loop.

const loops = new Set<(now: number) => void>();
let frame = 0;

function tick(now: number) {
  frame = 0;
  for (const loop of loops) loop(now);
  if (loops.size) frame = requestAnimationFrame(tick);
}

function addLoop(loop: (now: number) => void) {
  loops.add(loop);
  if (!frame) frame = requestAnimationFrame(tick);
}

function removeLoop(loop: (now: number) => void) {
  loops.delete(loop);
  if (!loops.size && frame) {
    cancelAnimationFrame(frame);
    frame = 0;
  }
}

/** Reads prefers-reduced-motion and follows changes. */
function useReducedMotionPreference() {
  const [reduce, setReduce] = useState(false);
  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduce(query.matches);
    update();
    query.addEventListener("change", update);
    return () => query.removeEventListener("change", update);
  }, []);
  return reduce;
}

// ---------------------------------------------------------------------------
// The grid mark.

export interface DotGridProps extends Omit<ComponentProps<"svg">, "children"> {
  /** How light travels across the grid while running. */
  pattern?: DotLoaderPattern;
  /** Dots per side. */
  grid?: 3 | 4;
  /** 12, 16, 24, or 40px, or a number of pixels. */
  size?: DotLoaderSize | number;
  /** `running` animates; `done` and `failed` gather the dots into a check or an x; `idle` holds them dim. */
  status?: DotLoaderStatus;
  /** `status` colors the dots by status (emerald when done, red when failed); `inherit` uses the current text color. */
  tone?: "status" | "inherit";
}

/** The dot grid on its own, decorative. Use DotLoader for a labeled status. */
export function DotGrid({
  pattern = "wave",
  grid = 3,
  size = "sm",
  status = "running",
  tone = "status",
  className,
  style,
  ...props
}: DotGridProps) {
  const px = typeof size === "number" ? size : pixelSizes[size];
  const dots = useMemo(() => gridDots(grid), [grid]);
  const shapes = useMemo(() => {
    const count = grid * grid;
    return {
      done: assign(dots, along(checkPath, count)),
      failed: assign(dots, crossPoints(count)),
    };
  }, [dots, grid]);
  const reduce = useReducedMotionPreference();
  const svgRef = useRef<SVGSVGElement>(null);
  const spec = patterns[pattern];
  const radius = grid === 3 ? 1.4 : 1.1;
  const resolved = status === "done" || status === "failed";
  // Smaller beads once gathered, so the check reads as one stroke about 2 units wide.
  const gathered = grid === 3 ? (status === "failed" ? 0.86 : 0.74) : 0.86;

  useEffect(() => {
    const svg = svgRef.current;
    if (!svg) return;
    const circles = Array.from(svg.querySelectorAll<SVGCircleElement>("circle"));
    const phases = dots.map((d, i) => spec.phase(d, grid, i));

    const paint = (t: number) => {
      circles.forEach((c, i) => {
        c.style.opacity = brightness(spec, phases[i]!, t).toFixed(3);
      });
    };

    if (status !== "running") {
      circles.forEach((c) => {
        c.style.opacity = status === "idle" ? "0.32" : "1";
      });
      return;
    }
    if (reduce) {
      paint(spec.still * spec.cycle);
      return;
    }

    let visible = true;
    let running = false;
    const loop = (now: number) => paint(now / 1000);
    const update = () => {
      const animate = visible && !document.hidden;
      if (animate && !running) {
        running = true;
        addLoop(loop);
      } else if (!animate && running) {
        running = false;
        removeLoop(loop);
      }
    };
    paint(performance.now() / 1000);
    const observer =
      typeof IntersectionObserver === "undefined"
        ? null
        : new IntersectionObserver((entries) => {
            visible = entries.some((entry) => entry.isIntersecting);
            update();
          });
    observer?.observe(svg);
    document.addEventListener("visibilitychange", update);
    update();
    return () => {
      running = false;
      removeLoop(loop);
      observer?.disconnect();
      document.removeEventListener("visibilitychange", update);
    };
  }, [status, reduce, spec, dots, grid]);

  return (
    <svg
      ref={svgRef}
      aria-hidden="true"
      viewBox={`0 0 ${BOX} ${BOX}`}
      fill="currentColor"
      data-status={status}
      data-pattern={pattern}
      className={cx("shrink-0 overflow-visible transition-colors duration-300 motion-reduce:transition-none", tone === "status" && statusColor[status], className)}
      style={{ width: px, height: px, ...style }}
      {...props}
    >
      {dots.map((dot, i) => {
        const target = resolved ? shapes[status as "done" | "failed"][i]! : null;
        const dx = target ? target[0] - dot.x : 0;
        const dy = target ? target[1] - dot.y : 0;
        // Dots leave in reading order, about 16ms apart; gathering back to the grid is quicker.
        const delay = resolved && !reduce ? (dot.col + dot.row) * 16 : 0;
        return (
          <circle
            key={i}
            cx={dot.x}
            cy={dot.y}
            r={radius}
            style={{
              transformBox: "fill-box",
              transformOrigin: "center",
              transform: `translate(${dx.toFixed(2)}px, ${dy.toFixed(2)}px) scale(${resolved ? gathered : 1})`,
              transition: reduce
                ? "none"
                : resolved
                  ? `transform 420ms cubic-bezier(0.23, 1, 0.32, 1) ${delay}ms, opacity 200ms ease-out`
                  : "transform 260ms cubic-bezier(0.23, 1, 0.32, 1), opacity 160ms ease-out",
            }}
          />
        );
      })}
    </svg>
  );
}

// ---------------------------------------------------------------------------
// Elapsed time

export function formatElapsed(ms: number): string {
  const s = Math.max(0, ms) / 1000;
  if (s < 60) return `${s.toFixed(1)}s`;
  const m = Math.floor(s / 60);
  if (m < 60) return `${m}m ${String(Math.floor(s % 60)).padStart(2, "0")}s`;
  return `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, "0")}m`;
}

function toMs(value: number | Date | undefined): number | undefined {
  return value instanceof Date ? value.getTime() : value;
}

/** Writes the elapsed time into a span ten times a second, without re-rendering React. */
function ElapsedTime({ startedAt, endedAt, running }: { startedAt: number; endedAt?: number; running: boolean }) {
  const ref = useRef<HTMLSpanElement>(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const write = () => {
      el.textContent = formatElapsed((running ? Date.now() : (endedAt ?? Date.now())) - startedAt);
    };
    write();
    if (!running) return;
    const id = setInterval(write, 100);
    return () => clearInterval(id);
  }, [startedAt, endedAt, running]);
  return (
    <span ref={ref} aria-hidden="true" className="font-mono text-xs text-zinc-500 tabular-nums">
      {formatElapsed((endedAt ?? startedAt) - startedAt)}
    </span>
  );
}

// ---------------------------------------------------------------------------
// The labeled loader.

export interface DotLoaderProps extends Omit<ComponentProps<"span">, "children" | "role"> {
  pattern?: DotLoaderPattern;
  grid?: 3 | 4;
  size?: DotLoaderSize;
  status?: DotLoaderStatus;
  /** Visible text beside the grid, for example "Thinking". Also the screen reader status. */
  label?: ReactNode;
  /** Text shown once `status` is `done`. Defaults to `label`. */
  doneLabel?: ReactNode;
  /** Text shown once `status` is `failed`. Defaults to `label`. */
  failedLabel?: ReactNode;
  /** A slow highlight travels across the label while running. Off under reduced motion. */
  shimmer?: boolean;
  /** Shows the elapsed time in mono after the label. It stops when the status leaves `running`. */
  timer?: boolean;
  /** When the work started, as epoch milliseconds or a Date. Defaults to when the loader mounted. */
  startedAt?: number | Date;
  /** When the work ended. Defaults to the moment the status left `running`. */
  endedAt?: number | Date;
  /** Screen reader text when there is no visible label. */
  ariaLabel?: string;
}

const defaultAria: Record<DotLoaderStatus, string> = {
  idle: "Queued",
  running: "Working",
  done: "Done",
  failed: "Failed",
};

/**
 * A dot-grid loader with an optional label, shimmer, and elapsed timer. It is a polite status
 * region, so the label is announced when the status changes; the timer is not announced.
 */
export function DotLoader({
  pattern = "wave",
  grid = 3,
  size = "sm",
  status = "running",
  label,
  doneLabel,
  failedLabel,
  shimmer = false,
  timer = false,
  startedAt,
  endedAt,
  ariaLabel,
  className,
  ...props
}: DotLoaderProps) {
  const [mountedAt] = useState(() => Date.now());
  const [stoppedAt, setStoppedAt] = useState<number | undefined>(undefined);
  const running = status === "running";
  useEffect(() => {
    setStoppedAt(running ? undefined : Date.now());
  }, [running]);

  const text = status === "done" ? (doneLabel ?? label) : status === "failed" ? (failedLabel ?? label) : label;
  const start = toMs(startedAt) ?? mountedAt;
  const end = toMs(endedAt) ?? stoppedAt;
  const reduce = useReducedMotionPreference();

  return (
    <span
      role="status"
      data-status={status}
      className={cx("inline-flex max-w-full items-center align-middle", gaps[size], className)}
      {...props}
    >
      <DotGrid pattern={pattern} grid={grid} size={size} status={status} />
      {text != null ? (
        <span className={cx("min-w-0 truncate leading-5", textSizes[size])}>
          <ShimmerText active={shimmer && running && !reduce} tone={status}>
            {text}
          </ShimmerText>
        </span>
      ) : (
        <span className="sr-only">{ariaLabel ?? defaultAria[status]}</span>
      )}
      {timer && status !== "idle" ? <ElapsedTime startedAt={start} endedAt={end} running={running} /> : null}
    </span>
  );
}

const toneText: Record<DotLoaderStatus, string> = {
  idle: "text-zinc-500",
  running: "text-zinc-600 dark:text-zinc-400",
  done: "text-zinc-600 dark:text-zinc-400",
  failed: "text-red-600 dark:text-red-400",
};

/**
 * The label twice: the base copy in the secondary color, and a primary-color copy on top that
 * is only visible through a soft band moving left to right. Plain text when inactive.
 */
function ShimmerText({ active, tone, children }: { active: boolean; tone: DotLoaderStatus; children: ReactNode }) {
  const overlay = useRef<HTMLSpanElement>(null);
  useEffect(() => {
    const el = overlay.current;
    if (!active || !el || typeof el.animate !== "function") return;
    const animation = el.animate(
      [
        { maskPosition: "100% 0", WebkitMaskPosition: "100% 0" },
        { maskPosition: "0% 0", WebkitMaskPosition: "0% 0" },
      ] as Keyframe[],
      { duration: 2600, iterations: Infinity, easing: "cubic-bezier(0.45, 0, 0.55, 1)" },
    );
    return () => animation.cancel();
  }, [active]);

  const band = "linear-gradient(90deg, transparent 0%, transparent 38%, #000 50%, transparent 62%, transparent 100%)";
  return (
    <span className={cx("relative inline-block transition-colors duration-200 motion-reduce:transition-none", toneText[tone])}>
      {children}
      {active ? (
        <span
          ref={overlay}
          aria-hidden="true"
          className="pointer-events-none absolute inset-0 text-zinc-950 select-none dark:text-white"
          style={{
            maskImage: band,
            WebkitMaskImage: band,
            maskSize: "300% 100%",
            WebkitMaskSize: "300% 100%",
            maskRepeat: "no-repeat",
            WebkitMaskRepeat: "no-repeat",
            maskPosition: "100% 0",
            WebkitMaskPosition: "100% 0",
          }}
        >
          {children}
        </span>
      ) : null}
    </span>
  );
}