# Dialog (Notchset): prompt.md (v1.0.0)

- id: `dialog` · version 1.0.0 · component · free
- category: Overlays
- build: Base UI (this item also ships a Radix build)
- install (this build): `npx shadcn@latest add https://beautiful-ui.dev/r/dialog.json`
- npm dependencies: @base-ui/react@^1
- registry dependencies: utils, @beautiful-ui/button, https://beautiful-ui.dev/r/notchset-foundation.json
- docs: https://beautiful-ui.dev/components/dialog
- The install command carries everything this item needs (files, CSS, tokens, npm and registry dependencies). Prefer it to copying source by hand.

shadcn's Dialog in Notchset: the panel unrolls from the top over a scrim and rolls back up, a 32px close key and a ruled header. Plus a kicker, a before/after comparison table, and a confirm key that runs your action, traces its check and closes the dialog.

## Build it
- Stack: React 19 (`ref` is a plain prop), TypeScript, Tailwind CSS v4 utilities, a shadcn-initialised project with the `@/*` alias.
- Packages: `@base-ui/react@^1` (Base UI build); `radix-ui@^1` (Radix build).
- Files: `components/ui/notchset/dialog.tsx`; shared code: `lib/beautiful-ui/notchset/dialog.tsx`, `lib/beautiful-ui/notchset/instrument.tsx`, `lib/beautiful-ui/notchset/root.ts`.
- Registry dependencies, installed with it automatically: shadcn `utils` (cn), `button`, `notchset-foundation`.
- Builds: separate Base UI and Radix files. 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: `Dialog`, `DialogClose`, `DialogCompare`, `DialogConfirm`, `DialogContent`, `DialogDescription`, `DialogFooter`, `DialogHeader`, `DialogKicker`, `DialogOverlay`, `DialogPortal`, `DialogTitle`, `DialogTrigger`, 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-travel`, `--notchset-fade`, `--notchset-focus-color`, `--notchset-focus-inset`, `--notchset-life-from`, `--notchset-life-ms`, `--notchset-node-blink`, `--notchset-node-bloom`, `--notchset-node-delay`, `--notchset-plate-color`, `--notchset-rise-from`, `--notchset-rule`, `--notchset-scroll`, `--notchset-signal`, `--notchset-sweep-to`). Never add Tailwind colour classes inside the component.

```tsx
import { Dialog, DialogCompare, DialogConfirm, DialogContent, DialogHeader, DialogKicker, DialogTitle, DialogTrigger } from "@/components/ui/notchset/dialog";
```

## Parts

| Part | data-slot | What it is for |
|---|---|---|
| `DialogContent` | `dialog-content` | The panel. |
| `DialogOverlay` | `dialog-overlay` | The scrim. |
| `DialogCompare` | `dialog-compare` | The comparison table. |
| `DialogKicker` | `dialog-kicker` | The kicker. |

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/dialog.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
- dialog, modal, confirm, promote, compare before after, shadcn dialog, Notchset
- Confirming a consequential change with the evidence beside it
- A drop-in for shadcn's Dialog (same parts)

### Not when
- Destructive confirmations: use Alert Dialog when it lands
- Long forms: use a page or a sheet

## Mistakes
- Return a Promise from onConfirm, or the key can't show its progress

## Usage

```tsx
"use client";

import { Dialog, DialogCompare, DialogConfirm, DialogContent, DialogHeader, DialogKicker, DialogTitle, DialogTrigger } from "@/components/ui/notchset/dialog";

const rows = [
  { metric: "Pass rate", before: "81.4%", after: "88.9%", delta: "+7.5" },
  { metric: "P50 latency", before: "3.2s", after: "1.9s", delta: "−1.3s" },
];

export function PromoteDialog({ promote }: { promote: () => Promise<void> }) {
  return (
    <Dialog>
      <DialogTrigger>Promote to prod</DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogKicker>Planner-v14 · staging → prod</DialogKicker>
          <DialogTitle>Promote to production?</DialogTitle>
        </DialogHeader>
        <DialogCompare rows={rows} population="1,200 cases" beforeLabel="Atlas 2" afterLabel="Atlas 3 Flash" />
        <DialogConfirm onConfirm={promote} loadingLabel="Promoting" successLabel="Live">
          Promote
        </DialogConfirm>
      </DialogContent>
    </Dialog>
  );
}
```

## Props

| Prop | Type | Default | What it does |
|---|---|---|---|
| `Dialog` | `as the primitive` |  | open, defaultOpen, onOpenChange. |
| `DialogContent showCloseButton / closeLabel / container` | `boolean / string / element` |  | As shadcn, plus where it portals. |
| `DialogKicker` | `p` |  | The mono line above the title. |
| `DialogCompare` | `{ rows, population, beforeLabel, afterLabel, changeLabel? }` |  | The comparison table; deltas in signal. |
| `DialogConfirm` | `Button props + onConfirm, closeDelay` |  | Runs onConfirm (a Promise), shows loading then done, closes after closeDelay (1000ms). Focus lands here. |

Full docs: https://beautiful-ui.dev/components/dialog

## 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 |
|---|---|
| Esc | Close |
| Tab | Cycle within the dialog |

## Performance

- Mounts only while open; the unroll is clip-path, which the compositor handles.
- The confirm key's scanner runs only while its action is pending.

## Responsive

- 392px wide, never wider than the screen less 32px; actions stack full width on phones.

## Motion inventory

| Interaction | What moves |
|---|---|
| Open | The scrim fades in 260ms; the panel unrolls (clip-path) over 420ms after 60ms and settles 8px; the new values settle in 90ms apart |
| Close | The panel rolls back up over 200ms; the scrim fades out 200ms |

## Accessibility contract (preserve when editing)
- The Base UI or Radix dialog: aria-modal, labelled by the title, focus trapped, Esc and the scrim close it, focus returns to the trigger
- Focus lands on DialogConfirm (or anything with data-autofocus)
- The comparison is a real table with column and row headers

## Install

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

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

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

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

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

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

## Source (Base UI build)

### components/ui/notchset/dialog.tsx

```tsx
"use client";

/**
 * Dialog (Notchset) v1.0.0 · Beautiful UI, by Chimpy (https://x.com/stochastichimp)
 * Docs: https://beautiful-ui.dev/components/dialog · Agent prompt: https://beautiful-ui.dev/md/dialog.md
 * MIT licensed: free to use, change and share.
 */

import * as React from "react";
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/notchset/button";
import { NOTCHSET_ROOT, OWN_SOUND, playCue, useNotchsetPortal } from "@/lib/beautiful-ui/notchset/instrument";
import {
  CloseGlyph,
  DialogCloseContext,
  DialogCompare,
  DialogKicker,
  dialogCloseClass,
  dialogContentClass,
  dialogDescriptionClass,
  dialogFooterClass,
  dialogHeaderClass,
  dialogOverlayClass,
  dialogTitleClass,
} from "@/lib/beautiful-ui/notchset/dialog";

/*
 * Notchset Dialog (Base UI build). shadcn's Dialog, same parts, in Notchset: a scrim that fades,
 * a panel that unrolls from the top and rolls back up, a 32px close key, and a ruled header.
 * Notchset adds DialogKicker, DialogCompare (a before/after table) and DialogConfirm, a key that
 * runs your action (scanner, then a traced check) and closes the dialog when it is done. Focus
 * lands on DialogConfirm (or anything marked data-autofocus), is trapped, and returns to the trigger.
 */

const withClass =
  <S,>(base: string, className: string | ((state: S) => string | undefined) | undefined) =>
  (state: S) =>
    cn(base, typeof className === "function" ? className(state) : className);

function Dialog({ onOpenChange, actionsRef, ...props }: DialogPrimitive.Root.Props) {
  const own = React.useRef<DialogPrimitive.Root.Actions | null>(null);
  const actions = (actionsRef ?? own) as React.RefObject<DialogPrimitive.Root.Actions | null>;
  // DialogConfirm closes through the primitive's own close(), so onOpenChange reports it as usual.
  const close = () => actions.current?.close();
  return (
    <DialogCloseContext value={close}>
      <DialogPrimitive.Root
        data-slot="dialog"
        actionsRef={actions}
        onOpenChange={(next, details) => {
          onOpenChange?.(next, details);
          if (next && !details.isCanceled) playCue(document.activeElement, "tick");
        }}
        {...props}
      />
    </DialogCloseContext>
  );
}

function DialogTrigger(props: DialogPrimitive.Trigger.Props) {
  return <DialogPrimitive.Trigger {...OWN_SOUND} data-slot="dialog-trigger" {...props} />;
}

function DialogPortal({ container, ...props }: DialogPrimitive.Portal.Props) {
  const scoped = useNotchsetPortal();
  return <DialogPrimitive.Portal data-slot="dialog-portal" container={container ?? scoped} {...props} />;
}

function DialogClose(props: DialogPrimitive.Close.Props) {
  return <DialogPrimitive.Close {...OWN_SOUND} data-slot="dialog-close" {...props} />;
}

function DialogOverlay({ className, ...props }: DialogPrimitive.Backdrop.Props) {
  return <DialogPrimitive.Backdrop {...NOTCHSET_ROOT} data-slot="dialog-overlay" className={withClass(dialogOverlayClass, className)} {...props} />;
}

function DialogContent({
  className,
  children,
  showCloseButton = true,
  closeLabel = "Close",
  container,
  ...props
}: DialogPrimitive.Popup.Props & { showCloseButton?: boolean; closeLabel?: string; container?: DialogPrimitive.Portal.Props["container"] }) {
  const popup = React.useRef<HTMLDivElement>(null);
  return (
    <DialogPortal container={container}>
      <DialogOverlay />
      <DialogPrimitive.Popup
        {...NOTCHSET_ROOT}
        ref={popup}
        data-slot="dialog-content"
        initialFocus={() => popup.current?.querySelector<HTMLElement>("[data-autofocus]") ?? true}
        className={withClass(dialogContentClass, className)}
        {...props}
      >
        {children}
        {showCloseButton && (
          <DialogPrimitive.Close {...OWN_SOUND} data-slot="dialog-close" aria-label={closeLabel} className={dialogCloseClass}>
            <CloseGlyph />
          </DialogPrimitive.Close>
        )}
      </DialogPrimitive.Popup>
    </DialogPortal>
  );
}

function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
  return <div data-slot="dialog-header" className={cn(dialogHeaderClass, className)} {...props} />;
}

function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
  return <div data-slot="dialog-footer" className={cn(dialogFooterClass, className)} {...props} />;
}

function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {
  return <DialogPrimitive.Title data-slot="dialog-title" className={withClass(dialogTitleClass, className)} {...props} />;
}

function DialogDescription({ className, ...props }: DialogPrimitive.Description.Props) {
  return <DialogPrimitive.Description data-slot="dialog-description" className={withClass(dialogDescriptionClass, className)} {...props} />;
}

/**
 * The confirm key: runs `onConfirm` (return a Promise) with the scanner and `loadingLabel`, traces
 * its check with `successLabel`, then closes the dialog after `closeDelay` (1000ms). Focus lands here.
 */
function DialogConfirm({
  onConfirm,
  loadingLabel = "Working",
  successLabel = "Done",
  closeDelay = 1000,
  children,
  ...props
}: Omit<React.ComponentProps<typeof Button>, "onClick"> & { onConfirm?: () => unknown; closeDelay?: number }) {
  const close = React.useContext(DialogCloseContext);
  // The close belongs to this dialog session: dismissing (unmounting) cancels it, so a confirmation that
  // settles later can't close the dialog after it was reopened.
  const session = React.useRef({ alive: true, timer: 0 as ReturnType<typeof setTimeout> | 0 });
  React.useEffect(() => {
    const s = session.current;
    s.alive = true;
    return () => {
      s.alive = false;
      if (s.timer) clearTimeout(s.timer);
    };
  }, []);
  return (
    <Button
      data-autofocus=""
      size="lg"
      loadingLabel={loadingLabel}
      successLabel={successLabel}
      className="min-w-[132px]"
      onClick={() => {
        const done = Promise.resolve(onConfirm?.());
        done.then(
          () => {
            if (session.current.alive) session.current.timer = setTimeout(() => session.current.alive && close?.(), closeDelay);
          },
          () => {},
        );
        return done;
      }}
      {...props}
    >
      {children}
    </Button>
  );
}

export { Dialog, DialogClose, DialogCompare, DialogConfirm, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogKicker, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger };
```

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

```tsx
"use client";

import * as React from "react";
import { cn } from "@/lib/utils";
import { Node } from "@/lib/beautiful-ui/notchset/instrument";

/*
 * Notchset Dialog, shared by both builds (handoff 1.5): the classes for the scrim and the panel
 * (it unrolls from the top with clip-path and settles 8px; it rolls back up on close), the header
 * kicker, the comparison table and the context that lets DialogConfirm close the dialog when its
 * action has finished.
 */

export const dialogOverlayClass =
  "fixed inset-0 z-50 bg-[var(--notchset-scrim,rgba(17,17,16,.42))] transition-opacity duration-[260ms] ease-linear data-[starting-style]:opacity-0 data-[ending-style]:opacity-0 data-[ending-style]:duration-200 motion-safe:data-[state=open]:animate-[notchset-fade-in_260ms_linear] motion-safe:data-[state=closed]:animate-[notchset-fade-out_200ms_linear]";

export const dialogContentClass = cn(
  "fixed top-1/2 left-1/2 z-50 flex w-[392px] max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 flex-col border border-solid border-foreground bg-background text-foreground outline-none",
  "[clip-path:inset(0)] transition-[clip-path,translate] duration-[420ms,520ms] ease-[var(--notchset-ease-unfold),cubic-bezier(.34,1.4,.5,1)] delay-[60ms,0ms]",
  "data-[starting-style]:[clip-path:inset(0_0_100%_0)] data-[starting-style]:translate-y-[calc(-50%-8px)]",
  "data-[ending-style]:[clip-path:inset(0_0_100%_0)] data-[ending-style]:delay-0 data-[ending-style]:duration-200 data-[ending-style]:ease-[var(--notchset-ease-travel)]",
  "motion-safe:data-[state=open]:animate-[notchset-unroll_420ms_var(--notchset-ease-unfold)_60ms_both] motion-safe:data-[state=closed]:animate-[notchset-rollup_200ms_var(--notchset-ease-travel)_both]",
  "max-sm:w-[calc(100%-2rem)]",
);

export const dialogCloseClass = cn(
  `notchset-focus`,
  "absolute end-3 top-3 flex size-8 cursor-pointer items-center justify-center border-0 bg-transparent p-0 text-foreground transition-colors duration-[120ms] hover:bg-accent pointer-coarse:size-11",
);

export function CloseGlyph() {
  return (
    <svg aria-hidden width="12" height="12" viewBox="0 0 12 12">
      <path d="M2 2 L10 10 M10 2 L2 10" stroke="currentColor" strokeWidth="1.4" />
    </svg>
  );
}

export const dialogHeaderClass = "flex flex-col gap-1.5 border-b border-solid border-[var(--notchset-rule,var(--border))] ps-5 pe-14 pt-5 pb-4 text-start";
export const dialogFooterClass = "flex flex-col-reverse gap-2.5 px-5 pt-1 pb-5 sm:flex-row sm:justify-end [&>*]:max-sm:w-full";
export const dialogTitleClass = "m-0 font-sans text-lg leading-tight font-medium";
export const dialogDescriptionClass = "m-0 px-5 pt-4 font-sans text-sm leading-[1.5] text-muted-foreground";

/** The small mono line above the title ("PLANNER-V14 · STAGING → PROD"). */
export function DialogKicker({ className, ...props }: React.ComponentProps<"p">) {
  return <p data-slot="dialog-kicker" className={cn("m-0 font-mono text-[8px] tracking-[0.14em] text-muted-foreground uppercase", className)} {...props} />;
}

export type CompareRow = { metric: React.ReactNode; before: React.ReactNode; after: React.ReactNode; delta?: React.ReactNode };

/**
 * The comparison table: a header row (the population, then the before and after columns marked
 * with a hollow and a filled node, then the change), 32px rows, the new values settling in.
 */
export function DialogCompare({
  rows,
  population,
  beforeLabel,
  afterLabel,
  changeLabel = "CHANGE",
  className,
  ...props
}: Omit<React.ComponentProps<"table">, "children"> & { rows: readonly CompareRow[]; population: React.ReactNode; beforeLabel: React.ReactNode; afterLabel: React.ReactNode; changeLabel?: React.ReactNode }) {
  const cell = "h-8 px-2 text-start font-mono text-[10px] tracking-[0.04em] whitespace-nowrap tabular-nums first:ps-0 last:pe-0 last:text-end";
  return (
    <div className="mx-5 mt-4 overflow-x-auto">
      <table data-slot="dialog-compare" className={cn("w-full border-collapse border-t border-solid border-foreground", className)} {...props}>
        <thead>
          <tr className="border-b border-solid border-[var(--notchset-rule,var(--border))]">
            <th scope="col" className={cn(cell, "font-normal text-muted-foreground")}>
              {population}
            </th>
            <th scope="col" className={cn(cell, "font-normal text-muted-foreground")}>
              <span className="inline-flex items-center gap-1.5">
                <Node state="off" />
                {beforeLabel}
              </span>
            </th>
            <th scope="col" className={cn(cell, "font-normal text-foreground")}>
              <span className="inline-flex items-center gap-1.5">
                <Node state="on" />
                {afterLabel}
              </span>
            </th>
            <th scope="col" className={cn(cell, "font-normal text-muted-foreground")}>
              {changeLabel}
            </th>
          </tr>
        </thead>
        <tbody>
          {rows.map((r, i) => (
            <tr key={i} className="border-b border-solid border-[var(--notchset-rule,var(--border))] last:border-b-0">
              <th scope="row" className={cn(cell, "font-medium text-foreground")}>
                {r.metric}
              </th>
              <td className={cn(cell, "text-muted-foreground")}>{r.before}</td>
              <td className={cn(cell, "text-foreground motion-safe:animate-[notchset-settle_380ms_var(--notchset-ease-settle)_both]")} style={{ animationDelay: `${480 + i * 90}ms` }}>
                {r.after}
              </td>
              <td className={cn(cell, "text-[var(--notchset-signal-text,var(--destructive))] motion-safe:animate-[notchset-settle_380ms_var(--notchset-ease-settle)_both]")} style={{ animationDelay: `${520 + i * 90}ms` }}>
                {r.delta}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

/** Lets DialogConfirm close its dialog when its action is done. */
export const DialogCloseContext = React.createContext<(() => void) | null>(null);
```

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

```tsx
"use client";

import * as React from "react";
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
// ---------------------------------------------------------------------------------------------

/** True under prefers-reduced-motion or inside a data-motion="off" scope. Checked when an effect runs. */
/**
 * 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);
      },
    );
  });
}

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;
  };
}

/** 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 ours after theirs, unless theirs called preventDefault. */
export function composeHandler<E extends { defaultPrevented: boolean }>(theirs: ((e: E) => void) | undefined, ours: (e: E) => void) {
  return (e: E) => {
    theirs?.(e);
    if (!e.defaultPrevented) ours(e);
  };
}

/** 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;
}

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([" ", "·", "/", ".", ":"]);

export function scramble(text: string, elapsed: number) {
  let out = "";
  for (let i = 0; i < text.length; i++) {
    const ch = text[i]!;
    out += STILL.has(ch) || elapsed >= 110 + i * 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 + text.length * 14 + 40;
    const step = (now: number) => {
      const elapsed = now - t0;
      if (elapsed >= end) return setFrame(null);
      setFrame({ for: text, shown: scramble(text, elapsed) });
      raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [text, off, el]);
  return 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, ...props }: Omit<React.ComponentProps<"span">, "children"> & { children: string; off?: boolean }) {
  const ref = React.useRef<HTMLSpanElement>(null);
  const shown = useGlyphFlip(children, { off, el: ref });
  return (
    <span ref={ref} data-slot="flip-text" className={cn("relative whitespace-nowrap", className)} {...props}>
      <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;
}

/**
 * A number that rolls: each digit is a 0–9 strip; the ones digit moves first and each digit to its left
 * 40ms later (620ms, a small overshoot). `delay` offsets the whole number (rows 60ms apart). Non-digits
 * (",", "$", "%") sit still. Screen readers get the plain value.
 */
function RollingNumber({ value, height = 32, delay = 0, className }: { value: string | number; height?: number; delay?: number; className?: string }) {
  const text = String(value);
  const digits = text.split("");
  const lastDigit = digits.reduce((n, d, i) => (/\d/.test(d) ? i : n), -1);
  return (
    <span className={cn("relative inline-flex overflow-hidden tabular-nums", className)} style={{ height, lineHeight: `${height}px` }}>
      <span className="sr-only">{text}</span>
      <span aria-hidden className="flex">
        {digits.map((d, i) =>
          /\d/.test(d) ? (
            <span
              key={digits.length - i}
              className="flex flex-col transition-transform duration-[620ms] ease-[cubic-bezier(.34,1.15,.5,1)]"
              style={{ transform: `translateY(${-Number(d) * height}px)`, transitionDelay: `${delay + (lastDigit - i) * 40}ms` }}
            >
              {Array.from({ length: 10 }, (_, n) => (
                <span key={n} style={{ height }}>
                  {n}
                </span>
              ))}
            </span>
          ) : (
            <span key={`s${digits.length - i}`}>{d}</span>
          ),
        )}
      </span>
    </span>
  );
}

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.
