# Float Rail (Notchset): prompt.md (v1.0.0)

- id: `float-rail` · 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://beautiful-ui.dev/r/float-rail.json`
- npm dependencies: none
- registry dependencies: utils, https://beautiful-ui.dev/r/notchset-foundation.json
- docs: https://beautiful-ui.dev/components/float-rail
- The install command carries everything this item needs (files, CSS, tokens, npm and registry dependencies). Prefer it to copying source by hand.

A toolbar that floats over a canvas, as a bar or a vertical rail: a deeper plate, groups cut apart by signal notches, readouts that roll (the undo step, the zoom), icon keys whose names drop on leader lines, latching keys, and a labelled key that goes live in signal with a running clock.

## 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/float-rail.tsx`; shared code: `lib/beautiful-ui/notchset/roving.tsx`, `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: `FloatRail`, `FloatRailButton`, `FloatRailKey`, `FloatRailNotch`, `FloatRailReadout`, 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 { FloatRail, FloatRailButton, FloatRailKey, FloatRailNotch, FloatRailReadout } from "@/components/ui/notchset/float-rail";
```

## Parts

| Part | data-slot | What it is for |
|---|---|---|
| `FloatRail` | `float-rail` | The floating toolbar on its plate. |
| `FloatRailKey / FloatRailButton` | `float-rail-key` | Icon keys with tags, and labelled keys that can go live. |
| `FloatRailReadout` | `float-rail-readout` | A rolling reading. |
| `FloatRailNotch` | `float-rail-notch` | A group divider with its notch. |

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/float-rail.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
- floating toolbar, floating button group, canvas toolbar, editor toolbar, vertical tool rail, zoom controls, present button, Notchset
- A canvas, board or editor toolbar with undo, share and present
- A vertical tool rail with zoom and view toggles

### Not when
- A toolbar fixed in the page flow: use Toolbar
- Choosing one view: use Segmented Control
- More actions than fit in one bar: put the rest in a Dropdown Menu

## Mistakes
- Keep a latching key's label constant: the pressed state is announced, the name shouldn't flip
- Bind the shortcuts you show
- Position the rail yourself (absolute over your canvas); it doesn't place itself

## Usage

```tsx
"use client";

import * as React from "react";
import { FloatRail, FloatRailButton, FloatRailKey, FloatRailNotch, FloatRailReadout } from "@/components/ui/notchset/float-rail";

export function BoardBar({ undo, redo, step, steps }: { undo: () => void; redo: () => void; step: number; steps: number }) {
  const [presenting, setPresenting] = React.useState(false);
  return (
    <FloatRail aria-label="Board">
      <FloatRailKey label="Undo" kbd="⌘Z" icon={<span>↶</span>} disabled={step === 0} onClick={undo} />
      <FloatRailReadout label="STEP" value={step} />
      <FloatRailKey label="Redo" kbd="⇧⌘Z" icon={<span>↷</span>} disabled={step === steps} onClick={redo} />
      <FloatRailNotch />
      <FloatRailButton live={presenting} onClick={() => setPresenting((p) => !p)}>
        {presenting ? "LIVE" : "PRESENT"}
      </FloatRailButton>
    </FloatRail>
  );
}
```

## Props

| Prop | Type | Default | What it does |
|---|---|---|---|
| `FloatRail orientation` | `"horizontal" \| "vertical"` |  | A bar (tags drop below) or a rail (tags sit beside it; ↑ ↓ move focus). |
| `FloatRailKey label / icon / kbd` | `string / ReactNode / string` |  | An icon key: its name (accessible name and tag), the icon, and a shortcut shown and announced (bind it yourself). |
| `FloatRailKey pressed` | `boolean` |  | A latching key: stays down while true (aria-pressed). |
| `FloatRailButton children / icon` | `string / ReactNode` |  | A labelled key; the label flips when it changes ("SHARE" → "LINK COPIED"). |
| `FloatRailButton live / reading` | `boolean / ReactNode` |  | Live: signal fill, a blinking node and a reading such as a clock (presenting, recording). |
| `FloatRailReadout label / value` | `string / string \| number` |  | A reading on the rail; digits roll when it changes. |
| `FloatRailNotch` | `-` |  | Cuts the rail into groups. |

Full docs: https://beautiful-ui.dev/components/float-rail

## 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 |
|---|---|
| ← → / ↑ ↓ | Move between keys (bar / rail) |
| Home / End | First or last key |
| Esc | Hide the tags until the pointer moves |

## Performance

- Plain buttons and CSS; readouts animate with transforms only.

## Responsive

- A bar of seven keys is about 320px; on narrow screens prefer the vertical rail or fewer labelled keys.
- 44px keys on touch screens.

## Motion inventory

| Interaction | What moves |
|---|---|
| Tag | The leader draws after 300ms on hover (at once on keyboard focus); the tag fades and settles 3px after 390ms (90ms on focus) |
| Readout | Digits roll 620ms, the ones digit first |
| Live | The key fills with signal, its node blinks and its label flips |
| Press | The icon drops 1px and scales to .9, springing back over 240ms |

## Accessibility contract (preserve when editing)
- A toolbar with its orientation and one tab stop; ← → (or ↑ ↓ on a rail), Home and End move between keys
- Icon keys are named by their label; latching keys and the live key report aria-pressed
- Readouts are polite status regions; tags are decoration for sighted users (the name is on the key); Esc hides them

## Install

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

```bash
npx shadcn@latest add https://beautiful-ui.dev/r/float-rail.json
```

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

```bash
npx shadcn@latest add https://beautiful-ui.dev/r/radix-nova/float-rail.json
```

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

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

## Source (Base UI build)

### components/ui/notchset/float-rail.tsx

```tsx
"use client";

/**
 * Float Rail (Notchset) v1.0.0 · Beautiful UI
 * Docs: https://beautiful-ui.dev/components/float-rail
 * MIT licensed: free to use, change and share.
 */

import * as React from "react";
import { cn } from "@/lib/utils";
import { Dot, FlipText, kbdToShortcut, Node, OWN_SOUND, playCue, NOTCHSET_ROOT, RollingNumber, useComposedRefs } from "@/lib/beautiful-ui/notchset/instrument";
import { useRoving } from "@/lib/beautiful-ui/notchset/roving";

/*
 * Notchset Float Rail: a toolbar that floats over a canvas, horizontal or as a vertical rail. It sits
 * on a deeper plate than a key (it is off the page), groups are cut apart by notches (a rule with a
 * signal notch at its end), and it carries readouts as well as keys: a zoom level or an undo step that
 * rolls when it changes. Icon keys show their name and shortcut on a leader line (below the bar, or
 * beside the rail); latching keys stay down while on; a labelled key can go live in signal with a
 * blinking node (presenting, recording). Escape hides the tags until the pointer moves.
 */

type Orientation = "horizontal" | "vertical";
const RailContext = React.createContext<Orientation>("horizontal");

function FloatRail({ orientation = "horizontal", className, children, onKeyDown, onFocusCapture, ref, ...props }: React.ComponentProps<"div"> & { orientation?: Orientation }) {
  const bar = React.useRef<HTMLDivElement>(null);
  const refs = useComposedRefs<HTMLDivElement>(ref, bar);
  const roving = useRoving(bar, "[data-slot=float-rail-key]", orientation);
  const vertical = orientation === "vertical";
  return (
    <RailContext value={orientation}>
      <span {...NOTCHSET_ROOT} data-slot="float-rail-frame" className={cn("relative inline-flex", className)}>
        {/* Floating: the plate sits further off than a key's. */}
        <span aria-hidden data-slot="plate" className={cn(`notchset-plate`, "[transform:translate(4px,4px)]")} />
        <div
          ref={refs}
          role="toolbar"
          aria-orientation={orientation}
          data-slot="float-rail"
          data-orientation={orientation}
          onKeyDown={(e) => {
            onKeyDown?.(e);
            if (e.defaultPrevented) return;
            if (e.key === "Escape") {
              e.currentTarget.dataset.tipsHidden = "";
              return;
            }
            roving.onKeyDown(e);
          }}
          onPointerMove={(e) => delete e.currentTarget.dataset.tipsHidden}
          onFocusCapture={(e) => {
            onFocusCapture?.(e);
            delete e.currentTarget.dataset.tipsHidden;
            roving.onFocus(e);
          }}
          className={cn("group/rail relative flex items-center gap-1 border border-solid border-foreground bg-background p-1", vertical && "flex-col")}
          {...props}
        >
          {children}
        </div>
      </span>
    </RailContext>
  );
}

/** The name tag on a leader line: below the bar, beside the rail. */
function Tag({ label, kbd }: { label: string; kbd?: string }) {
  const vertical = React.use(RailContext) === "vertical";
  return (
    <>
      <span
        aria-hidden
        className={cn(
          "pointer-events-none absolute bg-foreground transition-transform duration-[80ms] group-hover/key:delay-300 group-hover/key:duration-[120ms] group-has-[:focus-visible]/key:delay-0 group-data-[tips-hidden]/rail:!scale-0",
          vertical
            ? "top-1/2 left-[calc(100%+5px)] h-px w-[9px] origin-left scale-x-0 group-hover/key:scale-x-100 group-has-[:focus-visible]/key:scale-x-100"
            : "top-[calc(100%+5px)] left-1/2 h-[9px] w-px origin-top scale-y-0 group-hover/key:scale-y-100 group-has-[:focus-visible]/key:scale-y-100",
        )}
      />
      <span
        aria-hidden
        data-slot="float-rail-tag"
        className={cn(
          "pointer-events-none absolute z-10 flex h-[24px] items-center gap-[9px] bg-primary pe-1 ps-[9px] font-mono text-[11px] font-medium tracking-[0.08em] whitespace-nowrap text-primary-foreground uppercase opacity-0 transition-[opacity,translate] duration-[80ms] group-hover/key:opacity-100 group-hover/key:delay-[390ms] group-hover/key:duration-[140ms,300ms] group-hover/key:ease-[linear,cubic-bezier(.34,1.5,.5,1)] group-has-[:focus-visible]/key:opacity-100 group-has-[:focus-visible]/key:delay-[90ms] group-data-[tips-hidden]/rail:!opacity-0",
          vertical
            ? "top-1/2 left-[calc(100%+14px)] -translate-x-[3px] -translate-y-1/2 group-hover/key:translate-x-0 group-has-[:focus-visible]/key:translate-x-0"
            : "top-[calc(100%+14px)] left-1/2 -translate-x-1/2 -translate-y-[3px] group-hover/key:translate-y-0 group-has-[:focus-visible]/key:translate-y-0",
        )}
      >
        <Dot size={6} className={cn("text-primary", vertical ? "top-1/2 -left-[3px] -mt-[3px]" : "-top-[3px] left-1/2 -ml-[3px]")} />
        {label}
        {kbd && <span className="flex h-[16px] min-w-[16px] items-center justify-center border border-solid border-[var(--notchset-on-ink-line,color-mix(in_oklab,var(--primary-foreground)_30%,transparent))] px-1 text-[10px] font-normal">{kbd}</span>}
      </span>
    </>
  );
}

const KEY = cn(
  `notchset-focus`,
  "[--notchset-focus-inset:-3px] relative flex h-8 min-w-8 cursor-pointer items-center justify-center gap-2 border-0 bg-transparent p-0 font-mono text-foreground transition-colors duration-(--notchset-fade) ease-(--notchset-ease-fade) hover:bg-accent pointer-coarse:h-11 pointer-coarse:min-w-11 disabled:cursor-not-allowed disabled:opacity-35",
  "aria-pressed:bg-primary aria-pressed:text-primary-foreground",
);
const GLYPH = "flex transition-transform duration-[240ms] ease-[cubic-bezier(.34,1.8,.5,1)] group-active/key:translate-y-px group-active/key:scale-90 group-active/key:duration-[var(--notchset-key-down)] group-active/key:ease-linear [&_svg]:size-4";

export type FloatRailKeyProps = Omit<React.ComponentProps<"button">, "children"> & {
  /** The key's name: its accessible name and the tag. */
  label: string;
  icon: React.ReactNode;
  /** Shown on the tag and announced ("⌘Z"). Bind it yourself. */
  kbd?: string;
  /** A latching key: stays down while true. */
  pressed?: boolean;
};

/** An icon key with its tag. */
function FloatRailKey({ label, icon, kbd, pressed, className, onClick, ...props }: FloatRailKeyProps) {
  return (
    <span className="group/key relative flex">
      <button
        {...OWN_SOUND}
        type="button"
        tabIndex={-1}
        data-slot="float-rail-key"
        aria-label={label}
        aria-pressed={pressed}
        aria-keyshortcuts={kbdToShortcut(kbd)}
        onClick={(e) => {
          playCue(e.currentTarget, pressed === undefined ? "tap" : "latch");
          onClick?.(e);
        }}
        className={cn(KEY, "w-8 pointer-coarse:w-11", className)}
        {...props}
      >
        <span aria-hidden className={GLYPH}>
          {icon}
        </span>
      </button>
      <Tag label={label} kbd={kbd} />
    </span>
  );
}

export type FloatRailButtonProps = Omit<React.ComponentProps<"button">, "children"> & {
  /** The visible label; it flips when it changes ("SHARE" → "LINK COPIED"). */
  children: string;
  icon?: React.ReactNode;
  /** Live: signal fill and a blinking node (presenting, recording). */
  live?: boolean;
  /** A reading after the label while live ("00:07"). */
  reading?: React.ReactNode;
};

/** A labelled key: for the actions that need their word (Share, Present). */
function FloatRailButton({ children, icon, live, reading, className, onClick, ...props }: FloatRailButtonProps) {
  return (
    <span className="group/key relative flex">
      <button
        {...OWN_SOUND}
        type="button"
        tabIndex={-1}
        data-slot="float-rail-key"
        data-live={live || undefined}
        aria-pressed={live === undefined ? undefined : live}
        onClick={(e) => {
          playCue(e.currentTarget, live === undefined ? "tap" : live ? "tick" : "signal");
          onClick?.(e);
        }}
        className={cn(
          KEY,
          "px-2.5 text-[11px] font-medium tracking-[0.08em] uppercase",
          "data-[live]:bg-[var(--notchset-signal,var(--destructive))] data-[live]:text-[color:var(--notchset-on-signal,var(--primary-foreground))] data-[live]:[--notchset-focus-color:var(--notchset-signal-text,var(--destructive))]",
          className,
        )}
        {...props}
      >
        {live ? <Node state="live" className="[--notchset-node-color:currentColor]" /> : icon && <span aria-hidden className={GLYPH}>{icon}</span>}
        <FlipText>{children}</FlipText>
        {live && reading != null && <span className="font-normal tabular-nums opacity-85">{reading}</span>}
      </button>
    </span>
  );
}

/** A reading on the rail: a mono label over a number that rolls when it changes. */
function FloatRailReadout({ label, value, className, ...props }: Omit<React.ComponentProps<"span">, "children"> & { label?: string; value: string | number }) {
  return (
    <span data-slot="float-rail-readout" role="status" className={cn("flex min-w-11 flex-col items-center justify-center px-1.5 font-mono leading-none", className)} {...props}>
      {label && <span className="text-[10px] tracking-[0.12em] text-muted-foreground">{label}</span>}
      <RollingNumber value={value} height={14} className="text-[12px] font-medium" />
    </span>
  );
}

/** Cuts the rail into groups: a rule with a signal notch at its end. */
function FloatRailNotch({ className }: { className?: string }) {
  const vertical = React.use(RailContext) === "vertical";
  return (
    <span role="separator" aria-orientation={vertical ? "horizontal" : "vertical"} data-slot="float-rail-notch" className={cn("relative flex-none bg-[var(--notchset-rule,var(--border))]", vertical ? "mx-1 h-px w-6" : "my-1 h-6 w-px", className)}>
      <svg aria-hidden width="5" height="4" viewBox="0 0 5 4" className={cn("absolute text-[var(--notchset-signal,var(--destructive))]", vertical ? "top-1/2 -left-[5px] -mt-[2px] rotate-90" : "-top-[5px] left-1/2 -ml-[2.5px]")}>
        <path d="M0 0 H5 L2.5 4 Z" fill="currentColor" />
      </svg>
    </span>
  );
}

export { FloatRail, FloatRailButton, FloatRailKey, FloatRailNotch, FloatRailReadout };
```

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

```tsx
"use client";

import * as React from "react";

/*
 * Roving focus for a toolbar: one enabled key holds the tab stop (the last focused, else the first),
 * kept true as keys come and go; ← → (mirrored in RTL), or ↑ ↓ when vertical, Home and End move
 * between keys. Shared by Toolbar, the Rich Text Editor's toolbars and the key groups.
 */
export function useRoving<T extends HTMLElement>(ref: React.RefObject<T | null>, selector: string, orientation: "horizontal" | "vertical" = "horizontal") {
  const keysOf = React.useCallback((el: HTMLElement) => [...el.querySelectorAll<HTMLButtonElement>(selector)].filter((k) => !k.disabled), [selector]);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const reconcile = () => {
      const keys = [...el.querySelectorAll<HTMLButtonElement>(selector)];
      const enabled = keys.filter((k) => !k.disabled);
      const stop = enabled.find((k) => k.tabIndex === 0) ?? enabled[0];
      keys.forEach((k) => (k.tabIndex = k === stop ? 0 : -1));
    };
    reconcile();
    const mo = new MutationObserver(reconcile);
    mo.observe(el, { childList: true, subtree: true, attributes: true, attributeFilter: ["disabled"] });
    return () => mo.disconnect();
  }, [ref, selector]);
  /** Moves focus for an arrow, Home or End; returns whether it took the key. */
  const onKeyDown = (e: React.KeyboardEvent<HTMLElement>) => {
    const rtl = getComputedStyle(e.currentTarget).direction === "rtl";
    const next = orientation === "vertical" ? "ArrowDown" : rtl ? "ArrowLeft" : "ArrowRight";
    const prev = orientation === "vertical" ? "ArrowUp" : rtl ? "ArrowRight" : "ArrowLeft";
    const d = e.key === next ? 1 : e.key === prev ? -1 : 0;
    const keys = keysOf(e.currentTarget);
    const i = keys.indexOf(document.activeElement as HTMLButtonElement);
    const to = e.key === "Home" ? 0 : e.key === "End" ? keys.length - 1 : d && i >= 0 ? (i + d + keys.length) % keys.length : -1;
    if (to < 0) return false;
    e.preventDefault();
    keys[to]?.focus();
    return true;
  };
  /** The stop follows focus, pointer or keyboard. */
  const onFocus = (e: React.FocusEvent<HTMLElement>) => {
    const key = (e.target as HTMLElement).closest<HTMLButtonElement>(selector);
    if (key) keysOf(e.currentTarget).forEach((k) => (k.tabIndex = k === key ? 0 : -1));
  };
  return { onKeyDown, onFocus };
}
```

### 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.
