# Run Button (Notchset): prompt.md (v1.0.0)

- id: `run-button` · version 1.0.0 · component · free
- category: Actions
- build: Base UI (one set of files; its dependencies follow the build)
- install (this build): `npx shadcn@latest add https://notchset.dev/r/run-button.json`
- npm dependencies: none
- registry dependencies: utils, https://notchset.dev/r/notchset-foundation.json
- docs: https://notchset.dev/components/run-button
- The install command carries everything this item needs (files, CSS, tokens, npm and registry dependencies). Prefer it to copying source by hand.

One key that becomes its own stop control: ink with a play glyph and its shortcut, then signal with an elapsed-time readout and a blinking node while the agent runs, a signal outline when stopped, a traced check when complete. A step track and a flipping status line sit under it.

## Build it
- Stack: React 19 (`ref` is a plain prop), TypeScript, Tailwind CSS v4 utilities, a shadcn-initialised project with the `@/*` alias.
- Packages: none beyond React.
- Files: `components/ui/notchset/run-button.tsx`; shared code: `lib/beautiful-ui/notchset/instrument.tsx`, `lib/beautiful-ui/notchset/root.ts`.
- Registry dependencies, installed with it automatically: shadcn `utils` (cn), `notchset-foundation`.
- Builds: one set of files for both, but its dependencies come in Base UI and Radix builds. Install the one that matches the project (see Install): a free item's bare URL installs the Base UI build of it and its dependencies.
- Exports to keep: `RunButton`, and every exported type.
- CSS: the install adds the notchset foundation (tokens, keyframes, motion levels) to your global stylesheet once. Nothing to import by hand.
- Re-running `add` (or `--overwrite`) re-applies those rules: put overrides in your own CSS, never in the installed rules.
- Tokens: retheme with the `--notchset-*` custom properties (`--notchset-check`, `--notchset-control-edge`, `--notchset-draw-from`, `--notchset-ease-bloom`, `--notchset-ease-glide`, `--notchset-ease-key-down`, `--notchset-ease-key-up`, `--notchset-ease-travel`, `--notchset-fade`, `--notchset-focus-color`, `--notchset-focus-inset`, `--notchset-grow-to`, `--notchset-key-down`, `--notchset-key-up`, `--notchset-life-from`, `--notchset-life-ms`, `--notchset-node-blink`, `--notchset-node-bloom`, `--notchset-node-delay`, `--notchset-plate-color`, `--notchset-rise-from`, `--notchset-rule`, `--notchset-scan-to`, `--notchset-scroll`, `--notchset-sheet-from`, `--notchset-signal`, `--notchset-sweep-to`, `--notchset-travel`). Never add Tailwind colour classes inside the component.

```tsx
import { RunButton } from "@/components/ui/notchset/run-button";
```

## Parts

| Part | data-slot | What it is for |
|---|---|---|
| `RunButton` | `run-button` | The key, its legend, the step track and the status line. |
| `Key` | `run-button-key` | The button itself. |
| `Track` | `run-button-track` | The step nodes and their trace. |

Style a part with `[data-slot="<slot>"]` selectors or its `className`; keep the attributes when editing.

## Sound
- Keep every `data-slot` and `data-sound` attribute: the sound layer reads them.
- Installing this item adds no audio. Nothing plays until the app mounts `SoundProvider` once (install: `npx shadcn@latest add https://notchset.dev/r/notchset-sound.json`, import from `@/components/ui/notchset/sound-provider`); `useSound()` gives `muted` and `setMuted` for a mute control. Without a provider the audio engine never loads.

## Match the original
- Read `components/ui/notchset/run-button.tsx` as the reference implementation before changing or recreating anything, and match it: sizes, colours per theme, motion timings, copy and behaviour.
- If you deviate (a prop you can't honour, a style you changed, a dependency you swapped), say so in your reply, part by part.
- Keep the accessibility contract, the keyboard map and the motion levels listed below.

## Use it when
- run agent, stop run, start stop button, run button, agent run control, elapsed time, step progress, Notchset
- Starting and stopping an agent or job from one place
- Showing which step a run is on without a separate progress bar

### Not when
- A one-shot action that finishes instantly: use Button
- Long background jobs the user leaves: use a status row or Progress

## Mistakes
- Pass `step` from your run's events; uncontrolled it stays on the first step
- Bind the shortcut yourself: `kbd` is only the hint

## Usage

```tsx
"use client";

import * as React from "react";
import { RunButton } from "@/components/ui/notchset/run-button";

const STEPS = ["plan", "search_docs", "read_file", "run_sql", "draft", "verify"];

/** onRun returns a promise: the key shows running until it settles, and the abort signal stops it. */
export function RunPlanner({ runAgent }: { runAgent: (signal: AbortSignal, onStep: (i: number) => void) => Promise<void> }) {
  const [step, setStep] = React.useState(0);
  return <RunButton legend="F4 · RUN" name="PLANNER" steps={STEPS} step={step} onRun={(signal) => runAgent(signal, setStep)} />;
}
```

## Props

| Prop | Type | Default | What it does |
|---|---|---|---|
| `onRun` | `(signal: AbortSignal) => unknown` |  | Starts the run. Return a Promise and the button tracks it; Stop aborts the signal. |
| `onStop` | `() => void` |  | Called when the user stops the run. |
| `state` | `"idle" \| "running" \| "stopped" \| "complete"` |  | Controlled state. Uncontrolled, Stopped and Complete hold 2.8s, then return to idle. |
| `steps` | `string[]` |  | The run's steps, drawn as nodes under the key. |
| `step` | `number` |  | The current step index. |
| `elapsedMs` | `number` |  | Elapsed time while running; counted by the button when omitted. |
| `kbd` | `string` |  | The shortcut shown while idle (display only). Default "R". |
| `legend / name` | `string` |  | The legend above the key; the first word of the idle status. |
| `status` | `string` |  | Overrides the status line. |
| `labels` | `Partial<RunButtonLabels>` |  | Every word, for other languages. |

Full docs: https://notchset.dev/components/run-button

## Customising
- Colours: the component reads your shadcn tokens (`--background`, `--foreground`, `--border` …), refined by the `--notchset-*` tokens. The signal colour is `--notchset-signal` (it falls back to `--destructive`). Set tokens on `:root`, or on any container to retheme one area.
- Dark mode follows the `.dark` class on an ancestor (the shadcn and next-themes convention).
- Update later by re-running the install with `--overwrite` (review the diff if you edited it). Changelog: https://notchset.dev/r/changelog.json

## Keyboard

| Keys | Action |
|---|---|
| Enter / Space | Run, or stop a running run |

## Performance

- The elapsed readout ticks on one interval only while running; idle and stopped do no work.
- Step changes swap text through the glyph flip, throttled to one frame at a time.

## Responsive

- The key keeps its width while the label changes, so the row never reflows.
- Touch screens get a 44px key.

## Motion inventory

| Interaction | What moves |
|---|---|
| Press | The key drops 1px in 40ms and springs back in 200ms cubic-bezier(.34,1.5,.5,1) |
| Running | The node blinks (r 3.25 ↔ 1.1 every 420ms); the readout ticks every 100ms; the trace fills the step track |
| Complete | The check traces in over 260ms; the step nodes pulse in order, 70ms apart |
| Labels | Glyph flip: characters cycle and land left to right, 14ms apart. Off under reduced motion |

## Accessibility contract (preserve when editing)
- A native button with aria-pressed while running; its name switches between Run and Stop run
- The status line is a polite live region; flipping glyphs are hidden from screen readers, which hear the final text
- State reads from shape as well as colour: play, a filled stop square, an outline when stopped, a check when complete

## Install

Base UI project (a base-* style in components.json):

```bash
npx shadcn@latest add https://notchset.dev/r/run-button.json
```

Radix project (a radix-*, new-york or default style):

```bash
npx shadcn@latest add https://notchset.dev/r/radix-nova/run-button.json
```

Or add the `@notchset` registry to components.json and run `npx shadcn@latest add @notchset/run-button`: the CLI picks the build from your style.

## Credits
- Built on shadcn/ui (https://ui.shadcn.com)

## Source (Base UI build)

### components/ui/notchset/run-button.tsx

```tsx
"use client";

/**
 * Run Button (Notchset) v1.0.0 · Notchset
 * Docs: https://notchset.dev/components/run-button
 * MIT licensed: free to use, change and share.
 */

import * as React from "react";
import { cn } from "@/lib/utils";
import { Check, FlipText, Legend, motionOff, OWN_SOUND, playCue, NOTCHSET_ROOT, useComposedRefs } from "@/lib/beautiful-ui/notchset/instrument";

/*
 * Notchset Run Button: one key that becomes its own stop control. Idle it is ink with a play glyph
 * and its shortcut; running it turns signal, the shortcut box becomes an elapsed-time readout and
 * the node blinks; stopped it turns to a signal outline; complete it traces a check. Under the key a
 * step track fills as the run advances and a status line flips as it changes.
 *
 * Give `onRun` a function that returns a Promise and the button runs itself: it shows running until
 * the Promise settles (complete) and Stop aborts the signal it was given (stopped). Or control it
 * with `state`, `step` and `elapsedMs`.
 */

export type RunState = "idle" | "running" | "stopped" | "complete";

export type RunButtonLabels = {
  run: string;
  stop: string;
  stopped: string;
  complete: string;
  /** The button's accessible names. */
  runAria: string;
  stopAria: string;
  /** Status lines; `{n}` steps, `{i}` the step number, `{step}` its name, `{s}` seconds. */
  statusIdle: string;
  statusRunning: string;
  statusStopped: string;
  statusComplete: string;
};

const DEFAULT_LABELS: RunButtonLabels = {
  run: "RUN AGENT",
  stop: "STOP",
  stopped: "STOPPED",
  complete: "COMPLETE",
  runAria: "Run",
  stopAria: "Stop run",
  statusIdle: "{n} STEPS",
  statusRunning: "{i}/{n} · {step}",
  statusStopped: "STOPPED AT {step}",
  statusComplete: "{s}S",
};

const fill = (t: string, v: Record<string, string | number>) => t.replace(/\{(\w+)\}/g, (_, k: string) => String(v[k] ?? ""));
const elapsedText = (ms: number) => {
  const s = Math.max(0, ms) / 1000;
  const m = Math.floor(s / 60);
  const rest = s - m * 60;
  return `${String(m).padStart(2, "0")}:${rest < 10 ? "0" : ""}${rest.toFixed(1)}`;
};

/** How long Stopped and Complete hold before the key returns to idle (ms). */
const SETTLE_MS = 2800;

export type RunButtonProps = Omit<React.ComponentProps<"button">, "onClick" | "children"> & {
  /** Starts the run. Return a Promise to let the button track it; the signal aborts on Stop. */
  onRun?: (signal: AbortSignal) => unknown;
  onStop?: () => void;
  /** Controlled state. */
  state?: RunState;
  /** The run's steps, drawn as nodes under the key. */
  steps?: readonly string[];
  /** The current step (index). Uncontrolled runs leave it at 0 unless `step` is passed. */
  step?: number;
  /** Elapsed time while running; counted by the button when omitted. */
  elapsedMs?: number;
  /** The shortcut shown while idle (display only; bind it with your own hotkey). */
  kbd?: string;
  /** The legend above the key and its first status word (e.g. "PLANNER"). */
  legend?: string;
  name?: string;
  /** Overrides the status line. */
  status?: string;
  labels?: Partial<RunButtonLabels>;
};

function RunButton({ onRun, onStop, state: stateProp, steps = [], step: stepProp, elapsedMs, kbd = "R", legend, name, status, labels: labelsProp, className, disabled, ref, ...props }: RunButtonProps) {
  const L = { ...DEFAULT_LABELS, ...labelsProp };
  const [own, setOwn] = React.useState<RunState>("idle");
  const state = stateProp ?? own;
  // The clock: while running, the elapsed time ticks every 100ms from when the run started (a click
  // or a parent setting `state`); stopped or complete, it keeps the last reading.
  const [clock, setClock] = React.useState(0);
  const abort = React.useRef<AbortController | null>(null);
  const keyRef = React.useRef<HTMLButtonElement>(null);
  const composedRef = useComposedRefs(ref, keyRef);
  const [swell, setSwell] = React.useState(-1);

  React.useEffect(() => {
    if (state !== "running" || elapsedMs !== undefined) return;
    const t0 = performance.now();
    const tick = () => setClock(performance.now() - t0);
    const raf = requestAnimationFrame(tick);
    const iv = setInterval(tick, 100);
    return () => {
      cancelAnimationFrame(raf);
      clearInterval(iv);
    };
  }, [state, elapsedMs]);

  // Stopped and Complete hold, then return to idle (uncontrolled only).
  React.useEffect(() => {
    if (stateProp !== undefined || (own !== "stopped" && own !== "complete")) return;
    const t = setTimeout(() => setOwn("idle"), SETTLE_MS);
    return () => clearTimeout(t);
  }, [own, stateProp]);

  // On completion the step nodes pulse in order (70ms apart); not when motion is off.
  React.useEffect(() => {
    if (state !== "complete" || !steps.length || motionOff(keyRef.current)) return;
    const timers = steps.map((_, i) => setTimeout(() => setSwell(i), 160 + i * 70));
    timers.push(setTimeout(() => setSwell(-1), 160 + steps.length * 70));
    return () => timers.forEach(clearTimeout);
  }, [state, steps]);

  const elapsed = elapsedMs ?? clock;
  const running = state === "running";

  const run = () => {
    const controller = new AbortController();
    abort.current = controller;
    setOwn("running");
    playCue(keyRef.current, "tap");
    let result: unknown;
    try {
      result = onRun?.(controller.signal);
    } catch {
      setOwn("stopped");
      return;
    }
    if (result && typeof (result as Promise<unknown>).then === "function") {
      (result as Promise<unknown>).then(
        () => {
          if (controller.signal.aborted || abort.current !== controller) return;
          playCue(keyRef.current, "done");
          setOwn("complete");
        },
        () => {
          if (abort.current !== controller) return;
          setOwn("stopped");
        },
      );
    }
  };
  const stop = () => {
    abort.current?.abort();
    abort.current = null;
    setOwn("stopped");
    playCue(keyRef.current, "signal");
    onStop?.();
  };
  React.useEffect(() => () => abort.current?.abort(), []);

  const n = steps.length;
  const step = Math.min(Math.max(0, stepProp ?? 0), Math.max(0, n - 1));
  const stepName = (steps[step] ?? "").toUpperCase();
  const statusText =
    status ??
    (state === "idle"
      ? [name, fill(L.statusIdle, { n })].filter(Boolean).join(" · ")
      : state === "running"
        ? fill(L.statusRunning, { i: step + 1, n, step: stepName })
        : state === "stopped"
          ? fill(L.statusStopped, { step: stepName })
          : fill(L.statusComplete, { s: (elapsed / 1000).toFixed(1) }));
  const label = { idle: L.run, running: L.stop, stopped: L.stopped, complete: L.complete }[state];
  const progress = state === "idle" ? 0 : state === "complete" ? 1 : n ? Math.min(1, (step + (running ? 0.5 : 0)) / n) : 0;
  const trackW = Math.max(10, (n - 1) * 12 + 10);

  return (
    <div {...NOTCHSET_ROOT} data-slot="run-button" data-state={state} className={cn("flex w-[236px] max-w-full flex-col gap-[9px]", className)}>
      {legend !== undefined && <Legend label={legend} node={running ? "live" : state === "complete" ? "on" : state === "stopped" ? "signal" : "off"} />}
      <button {...OWN_SOUND}
        {...props}
        ref={composedRef}
        type="button"
        data-slot="run-button-key"
        data-state={state}
        aria-pressed={running}
        aria-label={running ? L.stopAria : L.runAria}
        disabled={disabled}
        onClick={() => (running ? stop() : stateProp === undefined || state === "idle" ? run() : undefined)}
        className={cn(
          `notchset-focus`,
          "flex h-10 w-full cursor-pointer items-center gap-[9px] border-0 py-0 pe-2 ps-[14px] font-mono select-none pointer-coarse:h-11",
          "bg-primary text-primary-foreground hover:bg-[var(--notchset-primary-hover,color-mix(in_oklab,var(--primary)_86%,var(--background)))]",
          "transition-[background-color,color,translate] duration-[140ms,140ms,var(--notchset-key-up)] ease-[linear,linear,var(--notchset-ease-key-up)] active:translate-y-px active:duration-[var(--notchset-key-down)] active:ease-linear",
          "data-[state=running]:bg-[var(--notchset-signal,var(--destructive))] data-[state=running]:text-[color:var(--notchset-on-signal,white)] data-[state=running]:hover:bg-[var(--notchset-signal-hover,var(--destructive))]",
          "data-[state=stopped]:border data-[state=stopped]:border-solid data-[state=stopped]:border-[var(--notchset-signal-text,var(--destructive))] data-[state=stopped]:bg-background data-[state=stopped]:text-[color:var(--notchset-signal-text,var(--destructive))] data-[state=stopped]:hover:bg-background",
          "data-[state=running]:[--notchset-focus-color:var(--notchset-signal-text,var(--destructive))] disabled:cursor-not-allowed disabled:opacity-40",
        )}
      >
        <span aria-hidden className="flex size-4 flex-none items-center justify-center">
          {running ? (
            <svg width="16" height="16" viewBox="0 0 24 24">
              <rect x="6.5" y="6.5" width="11" height="11" fill="currentColor" />
            </svg>
          ) : state === "complete" ? (
            <Check />
          ) : (
            <svg width="16" height="16" viewBox="0 0 24 24">
              <path d="M7 4 V20 L19 12 Z" fill="none" stroke="currentColor" strokeWidth="1.5" />
            </svg>
          )}
        </span>
        <FlipText className="text-[12px] font-medium tracking-[0.07em]">{label}</FlipText>
        <span
          aria-hidden
          className={cn(
            "ms-auto flex h-5 min-w-5 items-center justify-center border border-solid px-1.5 text-[11px] tracking-[0.02em] tabular-nums transition-[border-color] duration-(--notchset-fade) ease-(--notchset-ease-fade)",
            running
              ? "border-[var(--notchset-on-signal-line,color-mix(in_oklab,currentColor_35%,transparent))]"
              : state === "stopped"
                ? "border-[var(--notchset-tint,color-mix(in_oklab,var(--destructive)_20%,transparent))]"
                : "border-[var(--notchset-on-ink-line,color-mix(in_oklab,var(--primary-foreground)_30%,transparent))]",
          )}
        >
          {state === "idle" ? kbd : elapsedText(elapsed)}
        </span>
      </button>
      <div className="mt-1 flex h-[26px] items-center gap-3">
        {n > 0 && (
          <svg aria-hidden data-slot="run-button-track" width={trackW} height="10" viewBox={`0 0 ${trackW} 10`} className="flex-none overflow-visible">
            <line x1="5" y1="5" x2={trackW - 5} y2="5" stroke="var(--notchset-rule,var(--border))" strokeWidth="1" />
            <line
              x1="5"
              y1="5"
              x2={trackW - 5}
              y2="5"
              stroke={state === "stopped" ? "var(--notchset-signal,var(--destructive))" : "var(--foreground)"}
              strokeWidth="1"
              style={{ transform: `scaleX(${progress})`, transformBox: "view-box", transformOrigin: "5px 5px", transition: state === "idle" ? "none" : "transform 100ms linear" }}
            />
            {steps.map((s, i) => {
              const done = i < step || state === "complete";
              const current = (running || state === "stopped") && i === step;
              const halted = current && state === "stopped";
              return (
                <circle
                  key={`${s}-${i}`}
                  cx={5 + i * 12}
                  cy="5"
                  strokeWidth="1"
                  fill={halted ? "var(--notchset-signal,var(--destructive))" : done ? "var(--foreground)" : "var(--background)"}
                  stroke={halted ? "var(--notchset-signal,var(--destructive))" : done || current ? "var(--foreground)" : "var(--notchset-control-edge,var(--input))"}
                  style={{
                    r: swell === i ? "4px" : current ? "3.2px" : done ? "2.5px" : "2.2px",
                    transition: "r var(--notchset-node-bloom) var(--notchset-ease-bloom), fill 100ms linear, stroke 100ms linear",
                  }}
                />
              );
            })}
          </svg>
        )}
        <span
          aria-live="polite"
          data-slot="run-button-status"
          className={cn(
            "min-w-0 overflow-hidden font-mono text-[11px] tracking-[0.04em] whitespace-nowrap tabular-nums",
            state === "idle" ? "text-muted-foreground" : state === "stopped" ? "text-[var(--notchset-signal-text,var(--destructive))]" : "text-foreground",
          )}
        >
          <FlipText>{statusText}</FlipText>
        </span>
      </div>
    </div>
  );
}

export { RunButton };
```

### lib/beautiful-ui/notchset/instrument.tsx

```tsx
"use client";

import * as React from "react";
import { createPortal } from "react-dom";
import { cn } from "@/lib/utils";

/*
 * Notchset instrument parts, shared by every member of a pack: the node (a round light that reports
 * state), the legend printed above a control, the plate a key presses onto, the traced check, the
 * five-tick scanner, and the glyph flip that lands a changed label left to right. Nodes and checks
 * are inline SVG (round at every DPR); the CSS lives in the Notchset foundation. Also: the one motion
 * policy (reduced motion or a data-motion="off" ancestor), ref composition, the portal container
 * and the sound attributes every Notchset root carries.
 */

// ---------------------------------------------------------------------------------------------
// Motion, refs, portals, sound
// ---------------------------------------------------------------------------------------------

/**
 * Whether motion is off for an element, kept live: it follows the OS reduced-motion setting and any
 * data-motion attribute change above it, so a preference switched mid-playback stops decoration at once.
 */
export function useMotionOff(ref: React.RefObject<Element | null>) {
  const [off, setOff] = React.useState(false);
  React.useEffect(() => {
    const read = () => setOff(motionOff(ref.current));
    const r = requestAnimationFrame(read);
    const mq = window.matchMedia?.("(prefers-reduced-motion: reduce)");
    mq?.addEventListener?.("change", read);
    const mo = new MutationObserver(read);
    mo.observe(document.documentElement, { attributes: true, attributeFilter: ["data-motion"], subtree: true });
    return () => {
      cancelAnimationFrame(r);
      mq?.removeEventListener?.("change", read);
      mo.disconnect();
    };
  }, [ref]);
  return off;
}

/**
 * The microphone, or a rejection after `timeoutMs` (a prompt left open, a denied permission). A stream
 * that arrives after the timeout is stopped at once, so a late "Allow" never leaves the mic on.
 */
export function requestMic(timeoutMs = 5000): Promise<MediaStream> {
  if (typeof navigator === "undefined" || !navigator.mediaDevices?.getUserMedia) return Promise.reject(new Error("no mic"));
  const ask = navigator.mediaDevices.getUserMedia({ audio: true });
  return new Promise((resolve, reject) => {
    let late = false;
    const t = setTimeout(() => {
      late = true;
      reject(new Error("timeout"));
    }, timeoutMs);
    ask.then(
      (stream) => {
        clearTimeout(t);
        if (late) stream.getTracks().forEach((track) => track.stop());
        else resolve(stream);
      },
      (err) => {
        clearTimeout(t);
        reject(err);
      },
    );
  });
}

/** True under prefers-reduced-motion or inside a data-motion="off" scope. Checked when an effect runs. */
export function motionOff(el: Element | null | undefined) {
  if (typeof window === "undefined") return true;
  if (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches) return true;
  return Boolean(el?.closest('[data-motion="off"]'));
}

function assignRef<T>(ref: React.Ref<T> | undefined, node: T | null): () => void {
  if (typeof ref === "function") {
    const cleanup = ref(node);
    return typeof cleanup === "function" ? cleanup : () => ref(null);
  }
  if (ref) (ref as React.RefObject<T | null>).current = node;
  return () => {
    if (ref) (ref as React.RefObject<T | null>).current = null;
  };
}

/**
 * Puts text on the clipboard. Resolves true once it is there and false when the browser refuses (no
 * permission, an insecure page, no clipboard API), so a "copied" state is only ever shown for a copy.
 */
export async function copyText(text: string): Promise<boolean> {
  try {
    await navigator.clipboard.writeText(text);
    return true;
  } catch {
    return false;
  }
}

/** The glide easing shared by travelling marks (selection blocks, highlights, runs). */
export const GLIDE = "cubic-bezier(.65,0,.35,1)";

/** Base UI's className may be a function of state: merges ours with it in either form. */
export const withClass =
  <S,>(base: string, className: string | ((state: S) => string | undefined) | undefined) =>
  (state: S) =>
    cn(base, typeof className === "function" ? className(state) : className);

/** Composes two refs, keeping React 19 ref cleanups. */
export function useComposedRefs<T>(a: React.Ref<T> | undefined, b: React.Ref<T> | undefined): React.RefCallback<T> {
  return React.useCallback(
    (node: T | null) => {
      const release = [assignRef(a, node), assignRef(b, node)];
      return () => release.forEach((f) => f());
    },
    [a, b],
  );
}

/**
 * Runs each step on its own animation frame, in order (the first on the next frame), and returns one
 * cancel that stops whichever frame is pending. A no-op step just waits a frame: frames(set pre, wait,
 * go) lets the browser paint the start state before the transition begins.
 */
export function frames(...steps: (() => void)[]): () => void {
  let id = 0;
  let i = 0;
  const tick = () => {
    steps[i++]?.();
    if (i < steps.length) id = requestAnimationFrame(tick);
  };
  id = requestAnimationFrame(tick);
  return () => cancelAnimationFrame(id);
}
export const wait = () => {};

let idSeq = 0;
/** A unique id for something the user creates (a milestone, a note): random where the browser can, else a counter. */
export const newId = () => (typeof crypto !== "undefined" && "randomUUID" in crypto ? crypto.randomUUID() : `id-${Date.now()}-${++idSeq}`);

/**
 * True while an input method (Japanese, Chinese, Korean…) is composing: Enter, Tab and delimiters
 * then belong to the composition, not to the component. keyCode 229 covers Safari's late flag.
 */
export function composing(e: React.KeyboardEvent | KeyboardEvent) {
  const native = "nativeEvent" in e ? e.nativeEvent : e;
  return native.isComposing || native.keyCode === 229;
}

const hotkeyOwners = new Map<string, number[]>();
let hotkeySeq = 0;
/**
 * A page-wide shortcut ("/" or "mod+k", mod being ⌘ or Ctrl) with a single owner: when several
 * components claim the same key, only the one mounted last answers, so one press never opens two.
 * A plain key is ignored while typing in a field.
 */
export function useHotkey(combo: string | undefined, run: () => void) {
  const latest = useLatest(run);
  React.useEffect(() => {
    if (!combo) return;
    const me = ++hotkeySeq;
    const stack = hotkeyOwners.get(combo) ?? [];
    stack.push(me);
    hotkeyOwners.set(combo, stack);
    const mod = combo.startsWith("mod+");
    const key = (mod ? combo.slice(4) : combo).toLowerCase();
    const onKey = (e: KeyboardEvent) => {
      if (hotkeyOwners.get(combo)?.at(-1) !== me || e.key.toLowerCase() !== key) return;
      if (mod ? !(e.metaKey || e.ctrlKey) : e.metaKey || e.ctrlKey || e.altKey) return;
      if (!mod && (e.target as HTMLElement | null)?.closest("input, textarea, select, [contenteditable=true]")) return;
      e.preventDefault();
      latest.current();
    };
    window.addEventListener("keydown", onKey);
    return () => {
      window.removeEventListener("keydown", onKey);
      const s = hotkeyOwners.get(combo) ?? [];
      s.splice(s.indexOf(me), 1);
    };
  }, [combo, latest]);
}

/** Keeps the latest value in a ref, for callbacks read inside timers and animation frames. */
export function useLatest<T>(value: T) {
  const ref = React.useRef(value);
  React.useLayoutEffect(() => {
    ref.current = value;
  });
  return ref;
}

/*
 * Where Notchset overlays (menus, popovers, tooltips) portal to. Unset, document.body, as shadcn's
 * do. Provide an element to keep them inside a scoped theme: a preview, a widget, a shadow root.
 */
export const NotchsetPortalContext = React.createContext<HTMLElement | null>(null);
export function useNotchsetPortal(): HTMLElement | undefined {
  return React.useContext(NotchsetPortalContext) ?? undefined;
}

const subscribeNothing = () => () => {};

/**
 * A scope that turns motion or sound off for everything inside it, popups included. A plain
 * data-motion="off" wrapper can't reach a menu that portals to the body; this one also gives its
 * overlays a portal host carrying the same preferences (inside any outer scope's host), so motionOff
 * and the cues see them there too.
 */
export function NotchsetScope({ motion, sound, children, ...props }: React.ComponentProps<"div"> & { motion?: "off"; sound?: "off" }) {
  const outer = React.useContext(NotchsetPortalContext);
  const [host, setHost] = React.useState<HTMLElement | null>(null);
  const client = React.useSyncExternalStore(subscribeNothing, () => true, () => false);
  return (
    <div data-motion={motion} data-sound={sound} {...props}>
      <NotchsetPortalContext value={host ?? outer}>{children}</NotchsetPortalContext>
      {client && createPortal(<div ref={setHost} data-slot="notchset-scope-host" data-motion={motion} data-sound={sound} />, outer ?? document.body)}
    </div>
  );
}

export { NOTCHSET_ROOT, OWN_SOUND } from "@/lib/beautiful-ui/notchset/root";

// ---------------------------------------------------------------------------------------------
// Parts
// ---------------------------------------------------------------------------------------------

export type NodeState = "off" | "on" | "live" | "signal";

/** The node: a 9×9 ring whose dot blooms on (`on`), blinks (`live`) or turns signal. */
function Node({ state = "off", delay, className, style, ...props }: Omit<React.ComponentProps<"svg">, "children"> & { state?: NodeState; delay?: number }) {
  return (
    <svg
      aria-hidden
      data-slot="indicator"
      data-state={state}
      width="9"
      height="9"
      viewBox="0 0 9 9"
      className={cn(`notchset-node`, className)}
      style={delay ? ({ "--notchset-node-delay": `${delay}ms`, ...style } as React.CSSProperties) : style}
      {...props}
    >
      <circle data-slot="indicator-ring" cx="4.5" cy="4.5" r="3.25" fill="none" strokeWidth="1" />
      <circle data-slot="indicator-dot" cx="4.5" cy="4.5" />
    </svg>
  );
}

/** A small solid round mark (the node where a leader meets a popup, a pointer): SVG, round at every DPR. */
function Dot({ size = 7, className, style }: { size?: number; className?: string; style?: React.CSSProperties }) {
  return (
    <svg aria-hidden width={size} height={size} viewBox={`0 0 ${size} ${size}`} className={cn("pointer-events-none absolute overflow-visible", className)} style={style}>
      <circle cx={size / 2} cy={size / 2} r={size / 2} fill="currentColor" />
    </svg>
  );
}

/** The legend: a mono label above a control, with an optional node (or any trailing reading). */
function Legend({ label, node, children, className, ...props }: React.ComponentProps<"div"> & { label?: React.ReactNode; node?: NodeState }) {
  return (
    <div data-slot="legend" className={cn(`notchset-legend`, className)} {...props}>
      <span data-slot="legend-label">{label}</span>
      {(children != null || node) && (
        <span data-slot="legend-reading" className="flex items-center gap-2">
          {children}
          {node && <Node state={node} />}
        </span>
      )}
    </div>
  );
}

/** A key on its plate: the plate is an offset frame behind the child; `--notchset-plate-color` tints it. */
function Plated({ className, children, ...props }: React.ComponentProps<"span">) {
  return (
    <span data-slot="plated" className={cn("relative inline-flex", className)} {...props}>
      <span aria-hidden data-slot="plate" className={`notchset-plate`} />
      {children}
    </span>
  );
}

/**
 * The success check. Mounted, it traces itself in over --notchset-check (instant under reduced
 * motion); pass `drawn` to drive the trace yourself.
 */
function Check({ drawn, size = 16 }: { drawn?: boolean; size?: number }) {
  return (
    <svg aria-hidden data-slot="check" width={size} height={size} viewBox="0 0 24 24">
      <path
        d="M4 12.5 L9.5 18 L20 6"
        fill="none"
        stroke="currentColor"
        strokeWidth={1.75}
        strokeLinecap="square"
        pathLength={1}
        strokeDasharray={1}
        className={drawn === undefined ? `notchset-check-draw` : undefined}
        style={drawn === undefined ? undefined : { strokeDashoffset: drawn ? 0 : 1, transition: "stroke-dashoffset var(--notchset-check) var(--notchset-ease-travel)" }}
      />
    </svg>
  );
}

/** The scanner: five 1px ticks fading in turn while something works (static, centre lit, when motion is off). */
function Scanner({ height = 12 }: { height?: number }) {
  return (
    <span aria-hidden data-slot="scanner" className={cn(`notchset-scanner`, "inline-flex items-end gap-[2px]")} style={{ height }}>
      {[0.82, 0.66, 1, 0.66, 0.82].map((h, i) => (
        <span key={i} className="w-px bg-current" style={{ height: height * h, animationDelay: `${i * 140 - 700}ms` }} />
      ))}
    </span>
  );
}

// ---------------------------------------------------------------------------------------------
// Glyph flip: each character cycles through glyphs and lands at 110 + i·14ms, left to right
// ---------------------------------------------------------------------------------------------

const GLYPHS = "ABCDEFGHJKLMNPRSTUVWXYZ0123456789#/+=";
const STILL = new Set([" ", "·", "/", ".", ":"]);
const FLIP_CHARS = 24;

export function scramble(text: string, elapsed: number) {
  let out = "";
  for (let i = 0; i < text.length; i++) {
    const ch = text[i]!;
    // Characters past the 24th land with the 24th, so a long label flips as briefly as a short one.
    out += STILL.has(ch) || elapsed >= 110 + Math.min(i, FLIP_CHARS) * 14 ? ch : GLYPHS[(Math.floor(elapsed / 36) * 5 + i * 11) % GLYPHS.length];
  }
  return out;
}

/**
 * The text to show for `text`: when it changes, a few frames of glyphs that land left to right.
 * Runs on requestAnimationFrame only while a flip is active; the settled text is never state. Off
 * under reduced motion, inside data-motion="off" (pass the element) or with `off`.
 */
export function useGlyphFlip(text: string, { off = false, el }: { off?: boolean; el?: React.RefObject<Element | null> } = {}) {
  const [frame, setFrame] = React.useState<{ for: string; shown: string } | null>(null);
  const first = React.useRef(true);
  React.useEffect(() => {
    if (first.current) {
      first.current = false;
      return;
    }
    if (off || motionOff(el?.current)) return;
    let raf = 0;
    const t0 = performance.now();
    const end = 110 + Math.min(text.length, FLIP_CHARS) * 14 + 40;
    const step = (now: number) => {
      const elapsed = now - t0;
      if (elapsed >= end) {
        setFrame(null);
        return;
      }
      setFrame({ for: text, shown: scramble(text, elapsed) });
      raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [text, off, el]);
  // Turned off mid-flip, the label shows its text at once (the cancelled frame never lingers).
  return !off && frame && frame.for === text ? frame.shown : text;
}

/** A label that flips when its text changes; screen readers read the final text only. */
function FlipText({ children, off, className, ref: refProp, ...props }: Omit<React.ComponentProps<"span">, "children"> & { children: string; off?: boolean }) {
  const ref = React.useRef<HTMLSpanElement>(null);
  const refs = useComposedRefs<HTMLSpanElement>(refProp, ref);
  const shown = useGlyphFlip(children, { off, el: ref });
  return (
    <span {...props} ref={refs} data-slot="flip-text" className={cn("relative whitespace-nowrap", className)}>
      <span aria-hidden>{shown}</span>
      <span className="sr-only">{children}</span>
    </span>
  );
}

// ---------------------------------------------------------------------------------------------
// Sound: Notchset components announce cues; the page's beautiful-ui-sound layer (opt-in) plays them.
// ---------------------------------------------------------------------------------------------

/** The Notchset cues, in the shared sound layer's names (played in the mechanical voice). */
export const NOTCHSET_CUES = { tap: "tap", latch: "lock", signal: "destructive", confirm: "halt", done: "success", tick: "tick" } as const;
export type NotchsetCue = keyof typeof NOTCHSET_CUES;

export function playCue(el: Element | null, cue: NotchsetCue) {
  if (!el || typeof CustomEvent === "undefined" || el.closest('[data-sound="off"]')) return;
  el.dispatchEvent(new CustomEvent("beautiful-ui:sound", { bubbles: true, detail: { cue: NOTCHSET_CUES[cue] } }));
}

// ---------------------------------------------------------------------------------------------
// Shortcuts: "⌘↵" → "Meta+Enter Control+Enter" (aria-keyshortcuts)
// ---------------------------------------------------------------------------------------------

const KEY_NAMES: Record<string, string> = { "⌘": "Meta", "⌃": "Control", "⌥": "Alt", "⇧": "Shift", "↵": "Enter", "⏎": "Enter", "⎋": "Escape", "⌫": "Backspace", "⇥": "Tab", "␣": "Space" };

export function kbdToShortcut(kbd: string | undefined): string | undefined {
  if (!kbd) return undefined;
  const parts = [...kbd.replace(/\s+/g, "")].map((c) => KEY_NAMES[c] ?? c.toUpperCase());
  if (!parts.length) return undefined;
  const combo = parts.join("+");
  // ⌘ on a Mac is Ctrl elsewhere: announce both.
  return combo.includes("Meta") ? `${combo} ${combo.replace("Meta", "Control")}` : combo;
}

/**
 * Digits that roll: each digit is a 0–9 strip; the ones digit moves first and each digit to its left
 * 40ms later, counting digits only (620ms, a small overshoot). `delay` offsets the whole text. Other
 * characters (",", "$", "%", letters) sit still. Screen readers get the plain text. The one
 * implementation behind RollingNumber and the calendar's RollingLabel.
 */
export function DigitRoll({ text, height, delay = 0, className }: { text: string; height: number; delay?: number; className?: string }) {
  const chars = [...text];
  let k = 0;
  const order = chars.map((_, i) => (/\d/.test(chars[chars.length - 1 - i]!) ? k++ : 0)).reverse();
  return (
    <span className={cn("relative inline-flex flex-none overflow-hidden tabular-nums", className)} style={{ height, lineHeight: `${height}px` }}>
      <span className="sr-only">{text}</span>
      <span aria-hidden className="flex">
        {chars.map((d, i) =>
          /\d/.test(d) ? (
            <span
              key={chars.length - i}
              className="flex flex-col transition-transform duration-[620ms] ease-[cubic-bezier(.34,1.15,.5,1)] motion-reduce:transition-none"
              style={{ transform: `translateY(${-Number(d) * height}px)`, transitionDelay: `${delay + order[i]! * 40}ms` }}
            >
              {Array.from({ length: 10 }, (_, n) => (
                <span key={n} style={{ height }}>
                  {n}
                </span>
              ))}
            </span>
          ) : (
            <span key={`s${chars.length - i}`}>{d}</span>
          ),
        )}
      </span>
    </span>
  );
}

/** A number that rolls (DigitRoll at the readout's own size). `delay` offsets it (rows 60ms apart). */
function RollingNumber({ value, height = 32, delay = 0, className }: { value: string | number; height?: number; delay?: number; className?: string }) {
  return <DigitRoll text={String(value)} height={height} delay={delay} {...(className ? { className } : {})} />;
}

export { Check, Dot, FlipText, Legend, Node, Plated, RollingNumber, Scanner };
```

### lib/beautiful-ui/notchset/root.ts

```tsx
/*
 * Notchset's root attributes, server-safe (no client directive), so server components can spread
 * them too. Every Notchset root (and portalled popup) carries data-notchset (the motion policy's
 * scope), plays its own cues in the mechanical voice, and keeps the page's click layer out.
 */
export const NOTCHSET_ROOT = { "data-notchset": "", "data-sound": "none", "data-sound-voice": "analogue" } as const;

/** On every interactive element: it plays its own cues, so the page's click layer adds no tap. */
export const OWN_SOUND = { "data-sound": "none" } as const;
```

The notchset foundation (the tokens listed above, keyframes and motion levels) installs once with the first component; its CSS is public at https://notchset.dev/r/notchset-foundation.json.
