# Integrate `Keycast` from Motion Garden

You are helping me add the **Keycast** 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:** Keycast
- **Category:** Power-User Systems
- **Summary:** A streamer-style keyboard HUD: every chord you press appears as a row of keycaps and ages away, with a hammered key folding into one cap wearing a ×n badge. The listener is display-only by contract. It never prevents or stops an event, bails inside editable targets and mid-IME composition, and ignores lone modifiers, so the page underneath keeps every shortcut it had and the HUD merely reports what the hands did. Entry timestamps ride the loop clock rather than the wall clock, so pausing the bench freezes the stack mid-fade instead of evicting it all on resume, and a scripted demo reel keeps the pane alive whenever the real keyboard goes quiet.
- **Reference:** https://motion-garden.netlify.app/components/keycast
- **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
# Keycast needs no npm packages
```

## Files to create

2 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/keycast/keycast.tsx`

```tsx
"use client";

import { useEffect, useRef, useState } from "react";
import { useAnimationLoop } from "@/hooks/use-animation-loop";

export type KeycastCorner = "bottom-left" | "bottom-center" | "bottom-right";
export type KeycastPlatform = "mac" | "pc";

export interface KeycastProps {
  lifetime?: number;
  maxVisible?: number;
  corner?: KeycastCorner;
  combineRepeats?: boolean;
  platform?: KeycastPlatform;
  demo?: boolean;
  capSize?: number;
  accent?: string;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

type Mod = "ctrl" | "alt" | "shift" | "meta";

interface Entry {
  id: number;
  mods: Mod[];
  key: string;
  count: number;
  born: number;
}

const MOD_ORDER: Mod[] = ["ctrl", "alt", "shift", "meta"];
const MOD_GLYPHS: Record<KeycastPlatform, Record<Mod, string>> = {
  mac: { ctrl: "⌃", alt: "⌥", shift: "⇧", meta: "⌘" },
  pc: { ctrl: "Ctrl", alt: "Alt", shift: "Shift", meta: "Win" },
};

const KEY_LABELS: Record<string, string> = {
  " ": "Space",
  Escape: "Esc",
  Enter: "⏎",
  Backspace: "⌫",
  Delete: "⌦",
  Tab: "⇥",
  ArrowUp: "↑",
  ArrowDown: "↓",
  ArrowLeft: "←",
  ArrowRight: "→",
  CapsLock: "⇪",
};

const MODIFIER_KEYS = new Set(["Control", "Alt", "Shift", "Meta"]);

const DEMO: Array<{ mods: Mod[]; key: string }> = [
  { mods: ["meta"], key: "K" },
  { mods: ["shift", "meta"], key: "P" },
  { mods: [], key: "G" },
  { mods: [], key: "G" },
  { mods: [], key: "D" },
  { mods: [], key: "D" },
  { mods: ["alt"], key: "⇥" },
  { mods: ["meta"], key: "Z" },
];

const DEMO_AFTER = 3.5;

const signature = (mods: Mod[], key: string) => `${mods.join("+")}·${key}`;

const Keycast = ({
  lifetime = 2.4,
  maxVisible = 5,
  corner = "bottom-center",
  combineRepeats = true,
  platform = "mac",
  demo = true,
  capSize = 34,
  accent = "#c4b5fd",
  paused = false,
  reducedMotion = false,
  className = "",
}: KeycastProps) => {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const rowRefs = useRef(new Map<number, HTMLDivElement>());

  const [entries, setEntries] = useState<Entry[]>([]);
  const entriesRef = useRef(entries);
  entriesRef.current = entries;

  const live = useRef({ lifetime, maxVisible, combineRepeats, demo, paused, reducedMotion });
  live.current = { lifetime, maxVisible, combineRepeats, demo, paused, reducedMotion };

  const clock = useRef({ t: 0, quiet: 0, demoIdx: 0, demoWait: 1.2, nextId: 1 });

  const addChord = (mods: Mod[], key: string) => {
    const c = clock.current;
    const cfg = live.current;
    setEntries((prev) => {
      const last = prev[prev.length - 1];
      if (cfg.combineRepeats && last && signature(last.mods, last.key) === signature(mods, key)) {
        return [...prev.slice(0, -1), { ...last, count: last.count + 1, born: c.t }];
      }
      const next = [...prev, { id: c.nextId++, mods, key, count: 1, born: c.t }];
      return next.length > cfg.maxVisible ? next.slice(next.length - cfg.maxVisible) : next;
    });
    loop.start();
  };

  const loop = useAnimationLoop({
    target: containerRef,
    halted: paused,
    onFrame: ({ dt }) => {
      const c = clock.current;
      const cfg = live.current;
      c.t += dt;
      c.quiet += dt;

      if (cfg.demo && c.quiet > DEMO_AFTER) {
        c.demoWait -= dt;
        if (c.demoWait <= 0) {
          const chord = DEMO[c.demoIdx % DEMO.length];
          c.demoIdx++;
          c.demoWait = 0.85 + (c.demoIdx % 3) * 0.4;
          addChord(chord.mods, chord.key);
        }
      }

      const list = entriesRef.current;
      let expired = false;
      for (const entry of list) {
        const el = rowRefs.current.get(entry.id);
        const age = c.t - entry.born;
        if (age > cfg.lifetime) {
          expired = true;
          continue;
        }
        if (!el) continue;
        if (cfg.reducedMotion) {
          if (el.style.opacity !== "1") {
            el.style.opacity = "1";
            el.style.transform = "none";
          }
          continue;
        }
        const enter = Math.min(age / 0.16, 1);
        const exit = Math.min(Math.max((cfg.lifetime - age) / 0.45, 0), 1);
        const opacity = Math.min(enter, exit);
        const scale = 0.85 + 0.15 * (1 - (1 - enter) * (1 - enter));
        const rise = (1 - exit) * -6;
        const o = opacity.toFixed(3);
        if (el.style.opacity !== o) {
          el.style.opacity = o;
          el.style.transform = `translateY(${rise.toFixed(1)}px) scale(${scale.toFixed(3)})`;
        }
      }

      if (expired) {
        setEntries((prev) => prev.filter((entry) => c.t - entry.born <= cfg.lifetime));
      }

      if (list.length === 0 && !cfg.demo) return false;
    },
  });

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.isComposing) return;
      if (MODIFIER_KEYS.has(e.key)) return;
      if (e.repeat && !live.current.combineRepeats) return;
      const target = e.target;
      if (target instanceof HTMLElement) {
        const tag = target.tagName;
        if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || target.isContentEditable)
          return;
      }
      const mods = MOD_ORDER.filter((m) =>
        m === "ctrl" ? e.ctrlKey : m === "alt" ? e.altKey : m === "shift" ? e.shiftKey : e.metaKey,
      );
      const label =
        KEY_LABELS[e.key] ?? (e.key.length === 1 ? e.key.toUpperCase() : e.key);
      clock.current.quiet = 0;
      addChord(mods, label);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    loop.start();
  }, [paused, demo, loop]);

  const align =
    corner === "bottom-left"
      ? "items-start"
      : corner === "bottom-right"
        ? "items-end"
        : "items-center";

  const cap = (text: string, isMod: boolean, key: string) => (
    <span
      key={key}
      className="inline-flex items-center justify-center rounded-md border font-mono"
      style={{
        height: capSize,
        minWidth: capSize * 0.92,
        paddingInline: capSize * 0.22,
        fontSize: capSize * 0.4,
        color: isMod ? accent : "#d6d3e4",
        borderColor: isMod ? `color-mix(in oklab, ${accent} 45%, transparent)` : "#3a3a46",
        background: "linear-gradient(180deg, #26262f 0%, #1a1a21 100%)",
        borderBottomWidth: 3,
        boxShadow: "0 2px 0 rgba(0,0,0,0.4)",
      }}
    >
      {text}
    </span>
  );

  return (
    <div ref={containerRef} className={`relative h-full w-full overflow-hidden ${className}`.trim()}>
      <div
        aria-hidden="true"
        className={`absolute inset-x-6 bottom-6 flex flex-col justify-end gap-2 ${align}`}
      >
        {entries.map((entry, i) => (
          <div
            key={entry.id}
            ref={(el) => {
              if (el) rowRefs.current.set(entry.id, el);
              else rowRefs.current.delete(entry.id);
            }}
            className="flex items-center gap-1.5 rounded-lg px-2 py-1.5"
            style={{
              opacity: reducedMotion ? 1 : 0,
              background: "rgba(10,10,14,0.55)",
              boxShadow:
                i === entries.length - 1
                  ? `0 0 0 1px color-mix(in oklab, ${accent} 35%, transparent)`
                  : "0 0 0 1px rgba(58,58,70,0.5)",
            }}
          >
            {entry.mods.map((m) => cap(MOD_GLYPHS[platform][m], true, `${entry.id}-${m}`))}
            {cap(entry.key, false, `${entry.id}-key`)}
            {entry.count > 1 && (
              <span
                className="ml-0.5 font-mono text-[11px] tabular-nums"
                style={{ color: accent }}
              >
                ×{entry.count}
              </span>
            )}
          </div>
        ))}
      </div>
    </div>
  );
};

export default Keycast;
```

### 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],
  );
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `lifetime` | `number` | `2.4` | How long a chord stays on the HUD before it fades out. Range 0.8–6 s. |
| `maxVisible` | `number` | `5` | History depth; older entries are evicted early. Range 1–10. |
| `corner` | `"bottom-left" | "bottom-center" | "bottom-right"` | `"bottom-center"` | Where the stack anchors in its pane. |
| `combineRepeats` | `boolean` | `true` | Fold a hammered key into one cap with a ×n badge. |
| `platform` | `"mac" | "pc"` | `"mac"` | ⌘⌥⇧⌃ glyphs or Ctrl / Alt / Shift words. |
| `demo` | `boolean` | `true` | Replay a scripted set of chords whenever the keyboard goes quiet. |
| `capSize` | `number` | `34` | Keycap height; legends scale with it. Range 24–56 px. |
| `accent` | `string (hex)` | `"#c4b5fd"` | Modifier caps and the ring on the newest chord. |

## Usage

```tsx
import Keycast from "@/components/registry/keycast/keycast";

<Keycast
  lifetime={2.4}
  maxVisible={5}
  corner="bottom-center"
  combineRepeats={true}
  platform="mac"
  demo={true}
  capSize={34}
  accent="#c4b5fd"
/>
```

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.
- 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. Wire the component into the place I point you at, with sensible props for that context.
4. 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.
