# Integrate `Ledger` from Motion Garden

You are helping me add the **Ledger** component to an existing project.
Everything you need is below — full source, dependencies, props and the
behavioural contract. Read it all before writing anything.

- **Component:** Ledger
- **Category:** Power-User Systems
- **Summary:** A live activity log for a working agent. Consecutive events from the same source fold into one block instead of stacking as identical rows, the window holds a fixed number and lets the rest fall off the top, and the scroll stays pinned to the newest line only until you scroll away from it. After that it keeps running and tells you how far behind you are.
- **Reference:** https://motion-garden.netlify.app/components/ledger
- **Full catalog (for you, the agent):** https://motion-garden.netlify.app/llms.txt

## Stack this source assumes

- React 19 with the Next.js App Router (never the `pages/` directory)
- TypeScript, strict
- Tailwind CSS v4, CSS-first config (utilities are inline; no `tailwind.config` needed)

If my project differs, adapt the integration — but do not rewrite the animation math to suit a different stack. Ask me first.

## Dependencies

```bash
bun add motion clsx tailwind-merge
```

## Design tokens this source uses

Some classes in the source are Motion Garden theme tokens, not stock Tailwind (`text-ink`, `bg-panel`, `font-display` and the like). Without them, parts of the component render unstyled. Add this to my global CSS, after the Tailwind import:

```css
@theme {
  --font-display: "Space Mono", ui-monospace, "SFMono-Regular", monospace;
}

@theme inline {
  --color-panel: var(--sg-panel);
  --color-hairline: var(--sg-hairline);
  --color-ink-dim: var(--sg-ink-dim);
  --color-ink-mute: var(--sg-ink-mute);
  --color-accent: var(--sg-accent);
}

:root {
  --sg-panel: #ffffff;
  --sg-hairline: #dde2e7;
  --sg-ink-dim: #545b64;
  --sg-ink-mute: #878e97;
  --sg-accent: #7e22ce;
}

.dark {
  --sg-panel: #101215;
  --sg-hairline: #2a2f36;
  --sg-ink-dim: #bcc2c8;
  --sg-ink-mute: #6c737c;
  --sg-accent: #a855f7;
}
```

The values are Motion Garden's own light and dark themes. If my project already has tokens for these roles, point the `--sg-*` variables at mine instead and tell me which you mapped. `.dark` assumes class-based dark mode — adapt the selector to how my project switches themes.

`font-display` expects Space Mono, and this CSS only names it. Load the font (with `next/font/google`, for example) or put my own display face first in the stack; until then it falls back to the system monospace.

## Files to create

3 files — all of them are required. Paths are as shipped; the component may live anywhere in my project, but keep every peer file at the exact path shown so the import aliases resolve.

### 1. `components/registry/ledger/ledger.tsx`

```tsx
"use client";

import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { AnimatePresence, motion } from "motion/react";
import { cn } from "@/lib/utils";
import { useAnimationLoop } from "@/hooks/use-animation-loop";

export type LedgerSeverity = "info" | "ok" | "warn" | "deny";

export interface LedgerEntry {
  id: string;
  source: string;
  severity: LedgerSeverity;
  text: string;
}

export interface LedgerProps {
  entries?: LedgerEntry[];
  speed?: number;
  charsPerSecond?: number;
  entryGap?: number;
  jitter?: number;
  maxEntries?: number;
  group?: boolean;
  showTimestamps?: boolean;
  caret?: boolean;
  loop?: boolean;
  density?: "comfortable" | "compact";
  accentColor?: string;
  warnColor?: string;
  denyColor?: string;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

function makeRandom(seed: number) {
  let state = seed >>> 0 || 1;
  return () => {
    state ^= state << 13;
    state >>>= 0;
    state ^= state >>> 17;
    state ^= state << 5;
    state >>>= 0;
    return state / 0xffffffff;
  };
}

const RANK: Record<LedgerSeverity, number> = { info: 0, ok: 1, warn: 2, deny: 3 };

interface Row {
  key: string;
  entry: LedgerEntry;
  stamp: number;
  run: number;
}

export default function Ledger({
  entries = [],
  speed = 1,
  charsPerSecond = 90,
  entryGap = 520,
  jitter = 0.35,
  maxEntries = 9,
  group = true,
  showTimestamps = true,
  caret = true,
  loop = true,
  density = "comfortable",
  accentColor = "#a855f7",
  warnColor = "#f0a830",
  denyColor = "#f87171",
  paused = false,
  reducedMotion = false,
  className,
}: LedgerProps) {
  const rootRef = useRef<HTMLDivElement>(null);
  const scrollerRef = useRef<HTMLDivElement>(null);

  const [rows, setRows] = useState<Row[]>([]);
  const [chars, setChars] = useState(0);
  const [behind, setBehind] = useState(0);
  const [done, setDone] = useState(false);

  const compact = density === "compact";
  const halted = paused || reducedMotion;

  const live = useRef({
    entries,
    speed,
    charsPerSecond,
    entryGap,
    jitter,
    maxEntries,
    loop,
    reducedMotion,
  });
  live.current = {
    entries,
    speed,
    charsPerSecond,
    entryGap,
    jitter,
    maxEntries,
    loop,
    reducedMotion,
  };

  const stuck = useRef(true);

  const fresh = () => ({
    total: 0,
    chars: 0,
    wait: 0,
    clock: 0,
    phase: "gap" as "type" | "gap",
    rate: 1,
    run: 0,
    source: "",
    random: makeRandom(0x5eed),
  });

  const stream = useRef(fresh());

  useEffect(() => {
    if (!reducedMotion) return;
    const visible = entries.slice(-maxEntries);
    let run = 0;
    let source = "";
    setRows(
      visible.map((entry, i) => {
        if (entry.source !== source) {
          run += 1;
          source = entry.source;
        }
        return { key: `r${i}`, entry, stamp: i * (entryGap / 1000), run };
      }),
    );
    setChars(visible.length ? visible[visible.length - 1].text.length : 0);
    setBehind(0);
    setDone(true);
  }, [reducedMotion, entries, maxEntries, entryGap]);

  useEffect(() => {
    if (reducedMotion) return;
    stream.current = fresh();
    setRows([]);
    setChars(0);
    setBehind(0);
    setDone(false);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [entries, reducedMotion]);

  useEffect(() => {
    if (loop) setDone(false);
  }, [loop]);

  const drawRef = useRef<((dt: number) => void | false) | null>(null);
  drawRef.current = (dt: number) => {
    const p = live.current;
    if (p.entries.length === 0) return false;
    if (p.reducedMotion) return false;

    const s = stream.current;
    const step = dt * p.speed;
    s.clock += step;

    if (s.phase === "type") {
      const text = p.entries[(s.total - 1) % p.entries.length].text;
      s.chars = Math.min(text.length, s.chars + p.charsPerSecond * s.rate * step);
      if (s.chars >= text.length) {
        s.phase = "gap";
        s.wait = (p.entryGap / 1000) * (2 - s.rate);
      }
      setChars(Math.floor(s.chars));
      return;
    }

    s.wait -= step;
    if (s.wait > 0) return;

    if (!p.loop && s.total >= p.entries.length) {
      setDone(true);
      return false;
    }

    const entry = p.entries[s.total % p.entries.length];
    s.total += 1;
    s.chars = 0;
    s.phase = "type";
    s.rate = Math.max(0.15, 1 + (s.random() * 2 - 1) * p.jitter);
    if (entry.source !== s.source) {
      s.run += 1;
      s.source = entry.source;
    }

    const row: Row = { key: `e${s.total}`, entry, stamp: s.clock, run: s.run };
    setRows((prev) => {
      const next = prev.slice(Math.max(0, prev.length + 1 - p.maxEntries));
      next.push(row);
      return next;
    });
    setChars(0);
    if (!stuck.current) setBehind((n) => n + 1);
  };

  const runtime = useAnimationLoop({
    target: rootRef,
    halted,
    onFrame: ({ dt }) => (drawRef.current ? drawRef.current(dt) : false),
  });

  useEffect(() => {
    if (!halted && !done) runtime.start();
  }, [halted, done, entries, loop, runtime]);

  const onScroll = () => {
    const el = scrollerRef.current;
    if (!el) return;
    const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 24;
    stuck.current = atEnd;
    if (atEnd) setBehind(0);
  };

  useLayoutEffect(() => {
    const el = scrollerRef.current;
    if (!el || !stuck.current) return;
    el.scrollTop = el.scrollHeight;
  }, [rows, chars]);

  const catchUp = () => {
    const el = scrollerRef.current;
    if (!el) return;
    stuck.current = true;
    setBehind(0);
    el.scrollTop = el.scrollHeight;
  };

  const tone = (severity: LedgerSeverity) =>
    severity === "deny"
      ? denyColor
      : severity === "warn"
        ? warnColor
        : severity === "ok"
          ? accentColor
          : "var(--sg-ink-mute)";

  const blocks = useMemo(() => {
    const out: Array<{ key: string; source: string; severity: LedgerSeverity; rows: Row[] }> =
      [];
    for (const row of rows) {
      const head = out[out.length - 1];
      if (group && head && head.key === `g${row.run}`) {
        head.rows.push(row);
        if (RANK[row.entry.severity] > RANK[head.severity]) {
          head.severity = row.entry.severity;
        }
        continue;
      }
      out.push({
        key: group ? `g${row.run}` : row.key,
        source: row.entry.source,
        severity: row.entry.severity,
        rows: [row],
      });
    }
    return out;
  }, [rows, group]);

  const newest = rows[rows.length - 1];
  const running = !halted && !done && rows.length > 0;

  return (
    <div
      ref={rootRef}
      className={cn(
        "flex h-full w-full min-h-0 flex-col overflow-hidden rounded-lg border border-hairline bg-panel",
        className,
      )}
    >
      <div className="flex shrink-0 items-center gap-2.5 border-b border-hairline px-3 py-2">
        <motion.span
          className="size-1.5 rounded-full"
          style={{ backgroundColor: running ? accentColor : "var(--sg-ink-mute)" }}
          animate={running ? { opacity: [1, 0.25, 1], scale: [1, 0.72, 1] } : { opacity: 1, scale: 1 }}
          transition={
            running
              ? { duration: 1.6, repeat: Infinity, ease: "easeInOut" }
              : { duration: 0 }
          }
          aria-hidden
        />
        <span className="font-display text-[10px] tracking-[0.24em] text-ink-mute uppercase">
          {running ? "live" : done ? "complete" : "held"}
        </span>
        <span className="ml-auto font-mono text-[10px] tabular-nums text-ink-mute/70">
          {rows.length} shown
        </span>
      </div>

      <div className="relative min-h-0 flex-1">
        <div
          className="pointer-events-none absolute inset-x-0 top-0 z-10 h-6 bg-linear-to-b from-panel to-transparent"
          aria-hidden
        />

        <div
          ref={scrollerRef}
          onScroll={onScroll}
          className={cn(
            "h-full overflow-y-auto overscroll-contain",
            compact ? "px-3 py-2" : "px-4 py-3",
          )}
          style={{ overflowAnchor: "none" }}
          aria-live="polite"
          aria-label="Agent activity"
        >
          {blocks.map((block) => (
            <motion.div
              key={block.key}
              initial={reducedMotion ? false : { opacity: 0, y: 8 }}
              animate={{ opacity: 1, y: 0 }}
              transition={
                reducedMotion
                  ? { duration: 0 }
                  : { duration: 0.24, ease: [0.22, 1, 0.36, 1] }
              }
              className={cn("border-l-2 pl-2.5", compact ? "mb-1.5" : "mb-2.5")}
              style={{ borderColor: tone(block.severity) }}
            >
              <div className="flex items-baseline gap-2">
                <span
                  className={cn(
                    "font-display tracking-[0.18em] uppercase",
                    compact ? "text-[9px]" : "text-[10px]",
                  )}
                  style={{ color: tone(block.severity) }}
                >
                  {block.source}
                </span>
                {block.rows.length > 1 ? (
                  <span className="font-mono text-[10px] tabular-nums text-ink-mute/70">
                    &times;{block.rows.length}
                  </span>
                ) : null}
                {showTimestamps ? (
                  <span className="ml-auto font-mono text-[10px] tabular-nums text-ink-mute/60">
                    +{block.rows[0].stamp.toFixed(1)}s
                  </span>
                ) : null}
              </div>

              {block.rows.map((row) => {
                const typing = !done && row.key === newest?.key;
                const text = typing ? row.entry.text.slice(0, chars) : row.entry.text;
                return (
                  <p
                    key={row.key}
                    className={cn(
                      "font-mono leading-relaxed wrap-break-word text-ink-dim",
                      compact ? "text-[11px]" : "text-[12px]",
                    )}
                  >
                    {text}
                    {typing && text.length < row.entry.text.length ? (
                      <span className="sr-only">{row.entry.text.slice(chars)}</span>
                    ) : null}
                    {typing && caret && !halted ? (
                      <motion.span
                        className="ml-px inline-block h-[1em] w-[0.5em] translate-y-[0.15em]"
                        style={{ backgroundColor: accentColor }}
                        animate={{ opacity: [1, 1, 0, 0] }}
                        transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
                        aria-hidden
                      />
                    ) : null}
                  </p>
                );
              })}
            </motion.div>
          ))}
        </div>

        <AnimatePresence>
          {behind > 0 ? (
            <motion.button
              type="button"
              onClick={catchUp}
              initial={reducedMotion ? false : { opacity: 0, y: 6 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: 6 }}
              transition={reducedMotion ? { duration: 0 } : { duration: 0.2 }}
              className="absolute inset-x-0 bottom-2 z-20 mx-auto w-fit rounded-full px-3 py-1 font-display text-[10px] tracking-[0.16em] text-on-accent uppercase shadow-lg outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-panel"
              style={{ backgroundColor: accentColor }}
            >
              {behind} new &darr;
            </motion.button>
          ) : null}
        </AnimatePresence>
      </div>
    </div>
  );
}
```

### 2. `hooks/use-animation-loop.ts` — peer hook, required

```tsx
"use client";

import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react";

export interface Metrics {
  width: number;
  height: number;
  dpr: number;
  bufferWidth: number;
  bufferHeight: number;
}

export interface FrameInfo {
  now: number;
  dt: number;
  elapsed: number;
  frame: number;
}

export interface AnimationLoopHandle {
  start(): void;
  stop(): void;
  paint(): void;
  resize(): void;
  readonly running: boolean;
}

export interface AnimationLoopOptions {
  target: React.RefObject<HTMLElement | null>;
  halted?: boolean;
  dpr?: number | "auto";
  onResize?(metrics: Metrics): void;
  onFrame?(info: FrameInfo): void | false;
  paintWhenHalted?: boolean;
  resizeDebounceMs?: number;
  gl?(): WebGLRenderingContext | WebGL2RenderingContext | null | undefined;
  onDispose?(): void;
  deps?: unknown[];
}

const MAX_DT = 1 / 15;

export function useAnimationLoop(
  options: AnimationLoopOptions,
): AnimationLoopHandle {
  const opts = useRef(options);
  useLayoutEffect(() => {
    opts.current = options;
  });

  const raf = useRef<number | null>(null);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const running = useRef(false);
  const disposed = useRef(false);
  const startedAt = useRef(0);
  const last = useRef(0);
  const frame = useRef(0);

  const measure = useCallback((): Metrics | null => {
    const el = opts.current.target.current;
    if (!el) return null;
    const rect = el.getBoundingClientRect();
    const cap = opts.current.dpr ?? "auto";
    const limit = cap === "auto" ? 2 : cap;
    const dpr = Math.min(
      typeof window === "undefined" ? 1 : window.devicePixelRatio || 1,
      limit,
    );
    return {
      width: rect.width,
      height: rect.height,
      dpr,
      bufferWidth: Math.max(1, Math.round(rect.width * dpr)),
      bufferHeight: Math.max(1, Math.round(rect.height * dpr)),
    };
  }, []);

  const tick = useCallback(function tick(now: number) {
    if (disposed.current) return;

    if (startedAt.current === 0) startedAt.current = now;
    const dt = last.current === 0 ? 0 : Math.min((now - last.current) / 1000, MAX_DT);
    last.current = now;

    const info: FrameInfo = {
      now,
      dt,
      elapsed: (now - startedAt.current) / 1000,
      frame: frame.current++,
    };

    const verdict = opts.current.onFrame?.(info);

    if (disposed.current) return;

    if (verdict === false || opts.current.halted) {
      running.current = false;
      raf.current = null;
      return;
    }
    raf.current = requestAnimationFrame(tick);
  }, []);

  const start = useCallback(() => {
    if (disposed.current || running.current) return;
    running.current = true;
    last.current = 0;
    raf.current = requestAnimationFrame(tick);
  }, [tick]);

  const stop = useCallback(() => {
    running.current = false;
    if (raf.current !== null) {
      cancelAnimationFrame(raf.current);
      raf.current = null;
    }
  }, []);

  const paint = useCallback(() => start(), [start]);

  const resize = useCallback(() => {
    const metrics = measure();
    if (!metrics) return;
    opts.current.onResize?.(metrics);
    if (opts.current.paintWhenHalted !== false) paint();
    else if (!opts.current.halted) start();
  }, [measure, paint, start]);

  const deps = options.deps ?? [];

  useEffect(() => {
    disposed.current = false;
    const el = opts.current.target.current;
    if (!el) return;

    const run = () => {
      if (disposed.current) return;
      resize();
    };

    const observer = new ResizeObserver(() => {
      const wait = opts.current.resizeDebounceMs ?? 0;
      if (wait <= 0) {
        run();
        return;
      }
      if (timer.current !== null) clearTimeout(timer.current);
      timer.current = setTimeout(() => {
        timer.current = null;
        run();
      }, wait);
    });
    observer.observe(el);

    resize();
    if (!opts.current.halted) start();

    return () => {
      disposed.current = true;
      running.current = false;
      if (raf.current !== null) {
        cancelAnimationFrame(raf.current);
        raf.current = null;
      }
      if (timer.current !== null) {
        clearTimeout(timer.current);
        timer.current = null;
      }
      observer.disconnect();
      opts.current.onDispose?.();
      const context = opts.current.gl?.();
      context?.getExtension("WEBGL_lose_context")?.loseContext();
      startedAt.current = 0;
      last.current = 0;
      frame.current = 0;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);

  const halted = options.halted ?? false;
  useEffect(() => {
    if (!halted) start();
  }, [halted, start]);

  return useMemo<AnimationLoopHandle>(
    () => ({
      start,
      stop,
      paint,
      resize,
      get running() {
        return running.current;
      },
    }),
    [start, stop, paint, resize],
  );
}
```

### 3. `lib/utils.ts` — peer util, required

```tsx
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `speed` | `number` | `1` | Multiplier on the whole cadence — typing and the gaps between events together. Range 0.1–3 ×. |
| `charsPerSecond` | `number` | `90` | Typing rate before jitter. The full text of an event is in the accessibility tree from the moment it arrives, so only the eye waits for this. Range 10–400. |
| `entryGap` | `number` | `520` | Pause between one event landing and the next starting. Range 0–3000 ms. |
| `jitter` | `number` | `0.35` | Spread on the per-event rate, metronome to wildly uneven. A fast burst draws a longer breath after it, so the unevenness reads as work rather than as noise. Seeded, not random — the same run is reproducible every mount. Range 0–1. |
| `maxEntries` | `number` | `9` | Events retained before the oldest falls off the top, under a fade that keeps the window reading as a view onto a longer log. Range 3–24. |
| `group` | `boolean` | `true` | Fold consecutive same-source events into one block with a count. The block wears the worst severity in it, so a denial folded in among routine reads still shows red. |
| `showTimestamps` | `boolean` | `true` | Elapsed stream time beside each block. Measured from the component's own clock, never from the wall clock, so it is identical on every replay. |
| `caret` | `boolean` | `true` | Blinking block caret on the line currently being written. |
| `loop` | `boolean` | `true` | Wrap to the first event when the source list runs out. Off lets the stream halt itself once, and the header reads complete. |
| `density` | `"comfortable" | "compact"` | `"comfortable"` | Row height and type size throughout. |
| `accentColor` | `string (hex)` | `"#a855f7"` | Live indicator, caret, catch-up pill and the ok severity. |
| `warnColor` | `string (hex)` | `"#f0a830"` | The warn severity. |
| `denyColor` | `string (hex)` | `"#f87171"` | The deny severity. |

## Usage

```tsx
import Ledger from "@/components/registry/ledger/ledger";

<Ledger
  speed={1}
  charsPerSecond={90}
  entryGap={520}
  jitter={0.35}
  maxEntries={9}
  group={true}
  showTimestamps={true}
  caret={true}
  loop={true}
  density="comfortable"
  accentColor="#a855f7"
  warnColor="#f0a830"
  denyColor="#f87171"
/>
```

The import path matches the file path above; change it if you move the component. Every value shown is the documented default — pass only what you actually want to change. The snippet lists the tunable props only: if the component's props type in the source requires others (content, handlers, data), pass those too.

## Integration rules

- Keep the `"use client"` directive. This is a client component and will not render as a Server Component.
- It fills its parent. Give the wrapper an explicit height (or a definite grid area) — against a height-auto parent it collapses to nothing.
- It takes a `reducedMotion` prop and quiesces when true. Wire it to a `prefers-reduced-motion` listener rather than hardcoding `false`.
- It runs a free-running animation loop. Halt it when off-screen or backgrounded if you care about battery.
- The peer hook is required, not optional. Copy it to `hooks/use-animation-loop.ts` so the component's `@/hooks/use-animation-loop` import resolves.
- `lib/utils.ts` is required, not optional. It exports the `cn` helper the component imports from `@/lib/utils` — keep it at that path, or rewrite every `cn` import to wherever you already keep yours. If your project is shadcn-based you almost certainly have this file already; keep yours and drop mine.
- It owns a GPU/canvas context and releases it on unmount. Preserve the cleanup return — leaking contexts kills the tab after a few navigations.

## Your task

1. Tell me where in my project this should live and why.
2. Create the files above verbatim.
3. Add the design tokens to my global CSS, or map them to tokens I already have.
4. Wire the component into the place I point you at, with sensible props for that context.
5. Flag anything in my setup that conflicts with the stack assumptions above.

Do not restyle the component or alter the animation math unless I ask.
