# Scroll Reveal Heading (Notchset): prompt.md (v1.0.0)

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

A section title that plays once as it scrolls into view: each line's baseline traces, its words rise, the baseline cools to a rule, and the body fades up after.

## 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/scroll-reveal-heading.tsx`, `components/ui/notchset/text-reveal.tsx`; shared code: `lib/beautiful-ui/notchset/instrument.tsx`, `lib/beautiful-ui/notchset/root.ts`.
- Registry dependencies, installed with it automatically: shadcn `utils` (cn), `text-reveal`, `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: `ScrollRevealHeading`, `TextReveal`, `headlineClass`, `useReplay`, 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-signal`, `--notchset-sweep-to`, `--notchset-travel`). Never add Tailwind colour classes inside the component.

```tsx
import { ScrollRevealHeading } from "@/components/ui/notchset/scroll-reveal-heading";
```

## Parts

| Part | data-slot | What it is for |
|---|---|---|
| `ScrollRevealHeading` | `scroll-reveal-heading` | The title block. |

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://beautiful-ui.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/scroll-reveal-heading.tsx`, `components/ui/notchset/text-reveal.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
- in view title, scroll reveal, section heading, intersection observer, release notes heading, Notchset
- Section headings on long pages: release notes, changelogs, marketing

### Not when
- Above the fold: use Text Reveal on mount

## Mistakes
- Give each line its own string; lines never wrap

## Usage

```tsx
import { ScrollRevealHeading } from "@/components/ui/notchset/scroll-reveal-heading";

export function ScrollRevealHeadingExample() {
  return (
    <ScrollRevealHeading eyebrow="RELEASE NOTES" lines={["EVERY DEPLOY", "IS MEASURED"]}>Body copy.</ScrollRevealHeading>
  );
}
```

## Props

| Prop | Type | Default | What it does |
|---|---|---|---|
| `lines` | `string[]` |  | Explicit lines. |
| `eyebrow` | `ReactNode` |  | A mono line above. |
| `children` | `ReactNode` |  | Body copy under it. |
| `once / threshold` | `boolean / number` |  | Play once (default) at 60% visible. |
| `replayKey` | `number` |  | Change it to replay. |

Full docs: https://beautiful-ui.dev/components/scroll-reveal-heading

## 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://beautiful-ui.dev/r/changelog.json

## Keyboard

| Keys | Action |
|---|---|
| — | Not interactive |

## Performance

- One IntersectionObserver, disconnected after it fires.

## Responsive

- Size the title to fit its column.

## Motion inventory

| Interaction | What moves |
|---|---|
| Baselines | Trace in (420ms), 140ms a line, then cool from ink to rule (500ms, +900ms) |
| Words | Rise from 110% (680ms), +220ms after their line, 55ms apart |
| Body | Fades and settles 8px (+820ms) |

## Accessibility contract (preserve when editing)
- The heading carries the full title as its label
- Reduced motion shows everything at once

## Install

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

```bash
npx shadcn@latest add https://beautiful-ui.dev/r/scroll-reveal-heading.json
```

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

```bash
npx shadcn@latest add https://beautiful-ui.dev/r/radix-nova/scroll-reveal-heading.json
```

Or add the `@beautiful-ui` registry to components.json and run `npx shadcn@latest add @beautiful-ui/scroll-reveal-heading`: the CLI picks the build from your style.

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

## Source (Base UI build)

### components/ui/notchset/scroll-reveal-heading.tsx

```tsx
"use client";

/**
 * Scroll Reveal Heading (Notchset) v1.0.0 · Beautiful UI
 * Docs: https://beautiful-ui.dev/components/scroll-reveal-heading
 * MIT licensed: free to use, change and share.
 */

import * as React from "react";
import { cn } from "@/lib/utils";
import { NOTCHSET_ROOT, motionOff, playCue, frames, wait } from "@/lib/beautiful-ui/notchset/instrument";
import { headlineClass } from "@/components/ui/notchset/text-reveal";

/*
 * Notchset Scroll Reveal Heading (no primitive, one file for both builds). A headline that plays
 * once when 60% of it scrolls into view: each line's 1px baseline traces (420ms, 140ms a line), its
 * words rise out of the line (680ms), the baseline cools from ink to rule, and the body fades up 8px.
 * replayKey plays it again from a still start.
 */

const ROLL = "cubic-bezier(.34,1.15,.5,1)";
const TRACE = "cubic-bezier(.7,0,.25,1)";

function ScrollRevealHeading({
  lines,
  eyebrow,
  children,
  once = true,
  threshold = 0.6,
  replayKey,
  as: Tag = "h2",
  className,
  titleClassName,
}: {
  /** Explicit lines. */
  lines: readonly string[];
  eyebrow?: React.ReactNode;
  /** Body copy under the title. */
  children?: React.ReactNode;
  once?: boolean;
  threshold?: number;
  /** Change it to replay. */
  replayKey?: number;
  as?: "h1" | "h2" | "h3";
  className?: string;
  titleClassName?: string;
}) {
  const root = React.useRef<HTMLDivElement>(null);
  const [phase, setPhase] = React.useState<"pre" | "go">("pre");
  React.useEffect(() => {
    const el = root.current;
    if (!el) return;
    const io = new IntersectionObserver(
      ([e]) => {
        if (!e) return;
        // The first callback fires for any overlap: wait until the requested share is really in view.
        if (e.isIntersecting && e.intersectionRatio >= Math.min(threshold, 0.999)) {
          playCue(el, "tick");
          setPhase("go");
          if (once) io.disconnect();
        } else if (!once) setPhase("pre");
      },
      { threshold },
    );
    io.observe(el);
    return () => io.disconnect();
  }, [once, threshold]);
  const first = React.useRef(true);
  React.useEffect(() => {
    if (first.current) {
      first.current = false;
      return;
    }
    if (replayKey == null) return;
    // Motion off: nothing to replay, the title is simply shown (no race between a frame and a timer).
    if (motionOff(root.current)) {
      const a = requestAnimationFrame(() => setPhase("go"));
      return () => cancelAnimationFrame(a);
    }
    return frames(() => setPhase("pre"), wait, wait, wait, wait, () => setPhase("go"));
  }, [replayKey]);
  const go = phase === "go";
  const still = !go;

  return (
    <div {...NOTCHSET_ROOT} ref={root} data-slot="scroll-reveal-heading" data-state={phase} className={cn("text-foreground", className)}>
      {eyebrow && <div className="mb-3.5 font-mono text-[11px] tracking-[0.1em] text-muted-foreground">{eyebrow}</div>}
      <Tag aria-label={lines.join(" ")} className={cn(headlineClass, "m-0", titleClassName)}>
        {lines.map((l, li) => (
          <span key={li} aria-hidden className="relative block overflow-hidden pt-[.04em] pb-[.1em] whitespace-nowrap">
            {l.split(" ").map((w, wi) => (
              <span
                key={wi}
                className="me-[.2em] inline-block"
                style={{ transform: go ? "none" : "translateY(110%)", transition: still ? "none" : `transform 680ms ${ROLL} ${li * 140 + 220 + wi * 55}ms` }}
              >
                {w}
              </span>
            ))}
            <span
              className="absolute inset-x-0 bottom-0 h-px origin-left"
              style={{
                transform: go ? "scaleX(1)" : "scaleX(0)",
                background: go ? "var(--notchset-rule,var(--border))" : "var(--foreground)",
                transition: still ? "none" : `transform 420ms ${TRACE} ${li * 140}ms, background-color 500ms linear ${li * 140 + 900}ms`,
              }}
            />
          </span>
        ))}
      </Tag>
      {children && (
        <div
          className="mt-4 font-sans text-sm leading-[1.6] text-muted-foreground"
          style={{ opacity: go ? 1 : 0, transform: go ? "none" : "translateY(8px)", transition: still ? "none" : `opacity 300ms linear 820ms, transform 520ms cubic-bezier(.34,1.3,.5,1) 820ms` }}
        >
          {children}
        </div>
      )}
    </div>
  );
}

export { ScrollRevealHeading };
```

### components/ui/notchset/text-reveal.tsx

```tsx
"use client";

/**
 * Scroll Reveal Heading (Notchset) v1.0.0 · Beautiful UI
 * Docs: https://beautiful-ui.dev/components/scroll-reveal-heading
 * MIT licensed: free to use, change and share.
 */

import * as React from "react";
import { cn } from "@/lib/utils";
import { NOTCHSET_ROOT, motionOff, frames, wait } from "@/lib/beautiful-ui/notchset/instrument";

/*
 * Notchset Text Reveal (no primitive, one file for both builds). A condensed headline in
 * explicit lines, revealed five ways: ROLL (letters rise out of their cells, 26ms apart), LINES (each
 * line's words rise together, 150ms a line), TRACE (an ink rule draws under each word, the word wipes
 * open behind it, the rule fades), STRETCH (words narrow from 125% to their width), DECODE (letters
 * cycle glyphs and land left to right). Replays render a still "pre" state, then play two frames later.
 */

const ROLL = "cubic-bezier(.34,1.15,.5,1)";
const TRACE = "cubic-bezier(.7,0,.25,1)";
const UNROLL = "cubic-bezier(.16,1,.3,1)";
const GLYPHS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#/+";

export type RevealMode = "roll" | "lines" | "trace" | "stretch" | "decode";
export const headlineClass = "font-sans text-[58px] leading-[.94] font-extrabold uppercase [font-stretch:62%]";

/** pre → go: run on mount, when in view, or when replayKey changes. Returns the phase and decode clock. */
export function useReplay({ trigger, replayKey, decode, decodeMs = 0, root }: { trigger: "mount" | "inView" | "manual"; replayKey?: number; decode?: boolean; /** When the last decoded letter lands; the clock stops there. */ decodeMs?: number; root: React.RefObject<HTMLElement | null> }) {
  const [phase, setPhase] = React.useState<"pre" | "go" | "done">(trigger === "manual" ? "done" : "pre");
  const [t, setT] = React.useState(0);
  const [inView, setInView] = React.useState(trigger !== "inView");
  React.useEffect(() => {
    if (trigger !== "inView" || !root.current) return;
    const io = new IntersectionObserver(
      ([e]) => {
        // Only once 60% is really in view (the first callback fires for any overlap).
        if (e?.isIntersecting && e.intersectionRatio >= 0.6) {
          setInView(true);
          io.disconnect();
        }
      },
      { threshold: 0.6 },
    );
    io.observe(root.current);
    return () => io.disconnect();
  }, [trigger, root]);
  React.useEffect(() => {
    if (!inView || (trigger === "manual" && replayKey == null)) return;
    if (motionOff(root.current)) {
      const id = requestAnimationFrame(() => setPhase("done"));
      return () => cancelAnimationFrame(id);
    }
    return frames(
      () => {
        setPhase("pre");
        setT(0);
      },
      wait,
      () => setPhase("go"),
    );
  }, [inView, replayKey, trigger, root]);
  React.useEffect(() => {
    if (!decode || phase !== "go") return;
    const start = performance.now();
    const iv = setInterval(() => {
      const elapsed = performance.now() - start;
      setT(elapsed);
      // Every letter has landed: stop re-rendering.
      if (elapsed >= decodeMs) {
        clearInterval(iv);
        setPhase("done");
      }
    }, 45);
    return () => clearInterval(iv);
  }, [decode, decodeMs, phase]);
  return { phase, t };
}

function TextReveal({
  lines,
  mode = "roll",
  trigger = "mount",
  replayKey,
  as: Tag = "h2",
  className,
}: {
  /** Explicit lines of words. */
  lines: readonly (readonly string[])[];
  mode?: RevealMode;
  trigger?: "mount" | "inView" | "manual";
  /** Change it to replay. */
  replayKey?: number;
  as?: "h1" | "h2" | "h3" | "p" | "div";
  className?: string;
}) {
  const root = React.useRef<HTMLElement>(null);
  // Decode lands letter i at 160 + i × 55ms; the clock runs until the last one.
  const letterCount = lines.reduce((n, l) => n + l.reduce((m, w) => m + [...w].length, 0), 0);
  const { phase, t } = useReplay({ trigger, replayKey, decode: mode === "decode", decodeMs: 160 + Math.max(0, letterCount - 1) * 55 + 45, root });
  const pre = phase === "pre";
  const still = phase !== "go";
  let letter = 0;
  let word = 0;
  const sentence = lines.map((l) => l.join(" ")).join(" ");

  return (
    <Tag {...NOTCHSET_ROOT} ref={root as React.Ref<never>} data-slot="text-reveal" data-mode={mode} className={cn(headlineClass, "text-foreground", className)}>
      {/* The words, read once in order (the animated letters below are hidden from assistive tech). */}
      <span className="sr-only">{sentence}</span>
      {lines.map((l, li) => (
        <span key={li} aria-hidden className={cn("block whitespace-nowrap", mode === "lines" && "overflow-hidden")}>
          {l.map((w, wi) => {
            const k = word++;
            const chars = [...w];
            const wordStyle: React.CSSProperties =
              mode === "lines"
                ? { transform: pre ? "translateY(108%)" : "none", transition: still ? "none" : `transform 680ms ${ROLL} ${li * 150 + wi * 40}ms` }
                : mode === "stretch"
                  ? { fontStretch: pre ? "125%" : "62%", opacity: pre ? 0 : 1, transition: still ? "none" : `font-stretch 760ms ${UNROLL} ${k * 80}ms, opacity 280ms linear ${k * 80}ms` }
                  : mode === "trace"
                    ? { clipPath: pre ? "inset(-12% 100% -12% 0)" : "inset(-12% 0 -12% 0)", transition: still ? "none" : `clip-path 380ms ${TRACE} ${k * 120 + 200}ms` }
                    : {};
            return (
              <span key={wi} className="relative me-[.2em] inline-block">
                <span className="inline-block" style={wordStyle}>
                  {chars.map((ch, ci) => {
                    const i = letter++;
                    if (mode === "roll")
                      return (
                        <span key={ci} className="inline-block overflow-hidden align-bottom">
                          <span className="inline-block" style={{ transform: pre ? "translateY(105%)" : "none", transition: still ? "none" : `transform 620ms ${ROLL} ${i * 26}ms` }}>
                            {ch}
                          </span>
                        </span>
                      );
                    if (mode === "decode") {
                      const landed = phase === "done" || (phase === "go" && t >= 160 + i * 55);
                      return (
                        <span key={ci} className={landed ? undefined : "text-[var(--notchset-control-edge,var(--input))]"}>
                          {landed ? ch : GLYPHS[(Math.floor(t / 45) * 7 + i * 13) % GLYPHS.length]}
                        </span>
                      );
                    }
                    return <React.Fragment key={ci}>{ch}</React.Fragment>;
                  })}
                </span>
                {mode === "trace" && (
                  <span
                    className="pointer-events-none absolute inset-x-0 bottom-[.04em] h-[3px] origin-left bg-foreground"
                    style={{
                      transform: pre ? "scaleX(0)" : "scaleX(1)",
                      opacity: pre ? 1 : 0,
                      transition: still ? "none" : `transform 300ms ${TRACE} ${k * 120}ms, opacity 240ms linear ${k * 120 + 640}ms`,
                    }}
                  />
                )}
              </span>
            );
          })}
        </span>
      ))}
    </Tag>
  );
}

export { TextReveal };
```

### 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://beautiful-ui.dev/r/notchset-foundation.json.
