# Password Field (Notchset): prompt.md (v1.0.0)

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

A labelled 40px password field: a lock glyph, mono input tracked wide while masked, a CAPS chip while Caps Lock is on, a show/hide key whose slash draws away, a Forgot link, and a mechanical shake when an attempt is refused.

## 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/password-field.tsx`; shared code: `lib/beautiful-ui/notchset/password.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: `PasswordField`, `PasswordInput`, and every exported type.
- CSS: the install adds the notchset foundation (tokens, keyframes, motion levels) to your global stylesheet once. Nothing to import by hand.
- Re-running `add` (or `--overwrite`) re-applies those rules: put overrides in your own CSS, never in the installed rules.
- Tokens: retheme with the `--notchset-*` custom properties (`--notchset-check`, `--notchset-control-edge`, `--notchset-draw-from`, `--notchset-ease-bloom`, `--notchset-ease-glide`, `--notchset-ease-key-down`, `--notchset-ease-key-up`, `--notchset-ease-travel`, `--notchset-fade`, `--notchset-focus-color`, `--notchset-focus-inset`, `--notchset-grow-to`, `--notchset-key-down`, `--notchset-key-up`, `--notchset-life-from`, `--notchset-life-ms`, `--notchset-node-blink`, `--notchset-node-bloom`, `--notchset-node-delay`, `--notchset-plate-color`, `--notchset-rise-from`, `--notchset-rule`, `--notchset-scan-to`, `--notchset-scroll`, `--notchset-sheet-from`, `--notchset-signal`, `--notchset-sweep-to`, `--notchset-travel`). Never add Tailwind colour classes inside the component.

```tsx
import { PasswordField } from "@/components/ui/notchset/password-field";
```

## Parts

| Part | data-slot | What it is for |
|---|---|---|
| `PasswordField` | `password-field-root` | Label, field and help. |
| `field` | `password-field` | The 40px field. |

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

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

## Match the original
- Read `components/ui/notchset/password-field.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
- password field, password input, sign in, show password, caps lock warning, login form, Notchset
- Sign-in and re-authentication forms

### Not when
- Choosing a new password: use Password Strength

## Mistakes
- Clear the error as the user types, so the next refusal reads as new

## Usage

```tsx
"use client";

import * as React from "react";
import { PasswordField } from "@/components/ui/notchset/password-field";

export function SignInPassword({ signIn }: { signIn: (password: string) => Promise<boolean> }) {
  const [password, setPassword] = React.useState("");
  const [error, setError] = React.useState<string | undefined>();
  const [attempts, setAttempts] = React.useState(0);
  const [pending, setPending] = React.useState(false);
  // Only the latest attempt may report: a slow failure can't land after a later success.
  const attempt = React.useRef(0);
  return (
    <form
      onSubmit={async (e) => {
        e.preventDefault();
        if (pending) return;
        const id = ++attempt.current;
        setPending(true);
        setError(undefined);
        try {
          const ok = await signIn(password);
          if (id !== attempt.current || ok) return;
          setError("That password doesn't match.");
          setAttempts((a) => a + 1);
        } catch {
          if (id === attempt.current) setError("Couldn't reach sign-in. Try again.");
        } finally {
          if (id === attempt.current) setPending(false);
        }
      }}
    >
      <PasswordField
        value={password}
        onValueChange={(v) => {
          setPassword(v);
          setError(undefined);
        }}
        error={error}
        shake={attempts}
        forgotHref="/reset"
      />
      <button type="submit" disabled={pending}>
        {pending ? "Signing in…" : "Sign in"}
      </button>
    </form>
  );
}
```

## Props

| Prop | Type | Default | What it does |
|---|---|---|---|
| `value / onValueChange` | `string / fn` |  | Controlled. |
| `error` | `string` |  | Signal border and help line; sets aria-invalid. |
| `shake` | `number` |  | Bump it to shake on a refused attempt. |
| `revealable / capsLockHint` | `boolean` |  | The show/hide key and the CAPS chip (both on). |
| `forgotHref / onForgot` | `string / fn` |  | The Forgot link. |
| `help` | `ReactNode` |  | The help line when there is no error. |

Full docs: https://notchset.dev/components/password-field

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

## Keyboard

| Keys | Action |
|---|---|
| Enter | Submit the form |
| Tab | Reach show/hide |

## Performance

- A native input; the shake uses the Web Animations API on the field, so the input keeps focus.

## Responsive

- Fills its container; the show/hide key and CAPS chip keep their size.
- 44px tall on touch screens.

## Motion inventory

| Interaction | What moves |
|---|---|
| Show / hide | The slash draws away (280ms) and the pupil grows |
| Refused | Shakes ±3px in four 50ms steps |

## Accessibility contract (preserve when editing)
- A real label; the help line describes the input and is polite live text
- The show/hide key is type="button" with aria-pressed: it never submits the form
- Caps Lock is announced in the help line

## Install

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

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

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

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

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

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

## Source (Base UI build)

### components/ui/notchset/password-field.tsx

```tsx
"use client";

/**
 * Password Field (Notchset) v1.0.0 · Notchset
 * Docs: https://notchset.dev/components/password-field
 * MIT licensed: free to use, change and share.
 */

import * as React from "react";
import { cn } from "@/lib/utils";
import { NOTCHSET_ROOT, OWN_SOUND } from "@/lib/beautiful-ui/notchset/instrument";
import { PasswordInput, type PasswordInputProps } from "@/lib/beautiful-ui/notchset/password";

/*
 * Notchset Password Field (no primitive, one file for both builds). A labelled 40px field
 * with a lock glyph, mono input, a ⇪ CAPS chip while Caps Lock is on, and a show/hide key that never
 * submits the form. A Forgot link sits by the label; the help line under it carries the error, the
 * Caps Lock warning or your hint, and is what the input is described by. Bump `shake` to shake it on a
 * refused attempt.
 */

function PasswordField({
  id: idProp,
  label = "PASSWORD",
  error,
  help,
  forgotHref,
  onForgot,
  forgotLabel = "FORGOT",
  autoComplete = "current-password",
  className,
  ...props
}: Omit<PasswordInputProps, "invalid" | "onCapsLockChange"> & {
  label?: React.ReactNode;
  /** The error, in signal text; also sets aria-invalid. */
  error?: string;
  /** The help line when there is no error. */
  help?: React.ReactNode;
  forgotHref?: string;
  onForgot?: (e: React.MouseEvent<HTMLAnchorElement | HTMLButtonElement>) => void;
  forgotLabel?: string;
}) {
  const auto = React.useId();
  const id = idProp ?? `pw-${auto}`;
  const helpId = `${id}-help`;
  const [caps, setCaps] = React.useState(false);
  const message = error || (caps ? "CAPS LOCK IS ON" : help);
  const forgotClass = cn(`notchset-focus`, "[--notchset-focus-inset:-4px] font-mono text-[11px] tracking-[0.06em] text-muted-foreground underline underline-offset-[3px] hover:text-foreground");
  return (
    <div {...NOTCHSET_ROOT} data-slot="password-field-root" className={cn("flex flex-col gap-2", className)}>
      <div className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1">
        <label htmlFor={id} className="font-mono text-[11px] font-medium tracking-[0.1em] whitespace-nowrap text-foreground">
          {label}
        </label>
        {/* A link when there is somewhere to go; an action alone is a button (no "#" navigation). */}
        {forgotHref ? (
          <a {...OWN_SOUND} href={forgotHref} onClick={onForgot} className={forgotClass}>
            {forgotLabel}
          </a>
        ) : onForgot ? (
          <button {...OWN_SOUND} type="button" onClick={onForgot} className={cn(forgotClass, "cursor-pointer border-0 bg-transparent p-0")}>
            {forgotLabel}
          </button>
        ) : null}
      </div>
      {/* Your aria-describedby joins the field's own help line rather than replacing it. */}
      <PasswordInput id={id} autoComplete={autoComplete} invalid={!!error} onCapsLockChange={setCaps} {...props} aria-describedby={[helpId, props["aria-describedby"]].filter(Boolean).join(" ")} />
      <span
        id={helpId}
        aria-live="polite"
        className={cn("min-h-3 font-mono text-[11px] tracking-[0.04em] whitespace-nowrap", error || caps ? "text-[var(--notchset-signal-text,var(--destructive))]" : "text-muted-foreground")}
      >
        {message}
      </span>
    </div>
  );
}

export { PasswordField };
export { PasswordInput } from "@/lib/beautiful-ui/notchset/password";
```

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

```tsx
"use client";

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

/*
 * Notchset password parts, shared by Password Field and Password Strength: the 40px field
 * (a lock glyph, the input in mono, tracked .18em while masked and .02em when shown, a ⇪ CAPS chip, a
 * rule and the 40px show/hide key whose slash draws away and pupil grows), and the strength scoring.
 * The show/hide key is type="button": it never submits a form.
 */

export function LockGlyph() {
  return (
    <span aria-hidden className="flex w-[38px] flex-none items-center justify-center text-muted-foreground">
      <svg width="13" height="14" viewBox="0 0 13 14">
        <rect x="1.5" y="6" width="10" height="7" fill="none" stroke="currentColor" strokeWidth="1.2" />
        <path d="M3.8 6 V4.2 A2.7 2.7 0 0 1 9.2 4.2 V6" fill="none" stroke="currentColor" strokeWidth="1.2" />
      </svg>
    </span>
  );
}

export function EyeGlyph({ shown }: { shown: boolean }) {
  return (
    <svg aria-hidden width="16" height="12" viewBox="0 0 16 12" className="overflow-visible">
      <path d="M1 6 C3.5 1.8 12.5 1.8 15 6 C12.5 10.2 3.5 10.2 1 6 Z" fill="none" stroke="currentColor" strokeWidth="1.2" />
      <circle cx="8" cy="6" fill="currentColor" className={cn("transition-[r] duration-[260ms] ease-[cubic-bezier(.34,1.6,.5,1)]", shown ? "[r:2.2px]" : "[r:1.4px]")} />
      <path
        d="M2 11 L14 1"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.2"
        strokeDasharray="16"
        className="transition-[stroke-dashoffset] duration-[280ms] ease-[var(--notchset-ease-travel)]"
        style={{ strokeDashoffset: shown ? 16 : 0 }}
      />
    </svg>
  );
}

export type PasswordInputProps = Omit<React.ComponentProps<"input">, "type" | "value" | "onChange" | "size"> & {
  value: string;
  onValueChange: (value: string) => void;
  /** Show the show/hide key (true). */
  revealable?: boolean;
  shown?: boolean;
  onShownChange?: (shown: boolean) => void;
  /** Show ⇪ CAPS while Caps Lock is on (true). */
  capsLockHint?: boolean;
  onCapsLockChange?: (on: boolean) => void;
  invalid?: boolean;
  /** Changing this replays the shake (a refused attempt). */
  shake?: number;
  labels?: { show?: string; hide?: string; caps?: string };
  fieldClassName?: string;
};

/** The field: 40px, border edge at rest, ink focused, signal-text when invalid; it shakes on a refusal. */
export function PasswordInput({
  value,
  onValueChange,
  revealable = true,
  shown: shownProp,
  onShownChange,
  capsLockHint = true,
  onCapsLockChange,
  invalid,
  shake = 0,
  labels,
  fieldClassName,
  className,
  onKeyDown,
  onKeyUp,
  ...props
}: PasswordInputProps) {
  const [ownShown, setOwnShown] = React.useState(false);
  const shown = shownProp ?? ownShown;
  const [caps, setCaps] = React.useState(false);
  // A refusal shakes the field in place (the input keeps focus and caret).
  const field = React.useRef<HTMLDivElement>(null);
  React.useEffect(() => {
    const el = field.current;
    if (!shake || !el || motionOff(el)) return;
    // -3, +3, -3, +3, rest: 50ms each, held (step-end), as in the kit.
    const at = (x: number, offset: number): Keyframe => ({ transform: x ? `translateX(${x}px)` : "none", offset, easing: "step-end" });
    el.animate([at(-3, 0), at(3, 0.2), at(-3, 0.4), at(3, 0.6), at(0, 0.8), at(0, 1)], { duration: 250 });
  }, [shake]);
  const readCaps = (e: React.KeyboardEvent<HTMLInputElement>) => {
    const on = e.getModifierState?.("CapsLock") ?? false;
    if (on !== caps) {
      setCaps(on);
      onCapsLockChange?.(on);
    }
  };
  return (
    <div
      ref={field}
      data-slot="password-field"
      data-invalid={invalid || undefined}
      className={cn(
        "relative flex h-10 items-center border border-solid border-[var(--notchset-control-edge,var(--input))] bg-background text-foreground transition-[border-color] duration-(--notchset-fade) ease-(--notchset-ease-fade) focus-within:border-foreground data-[invalid]:border-[var(--notchset-signal-text,var(--destructive))] pointer-coarse:h-11",
        fieldClassName,
      )}
    >
      <LockGlyph />
      <input
        type={shown ? "text" : "password"}
        value={value}
        onChange={(e) => onValueChange(e.target.value)}
        onKeyDown={(e) => {
          onKeyDown?.(e);
          readCaps(e);
        }}
        onKeyUp={(e) => {
          onKeyUp?.(e);
          readCaps(e);
        }}
        spellCheck={false}
        aria-invalid={invalid || undefined}
        className={cn(
          "h-full min-w-0 flex-1 border-0 bg-transparent p-0 font-mono text-[13px] text-foreground outline-none placeholder:tracking-[0.02em] placeholder:text-muted-foreground",
          shown ? "tracking-[0.02em]" : "tracking-[0.18em]",
          className,
        )}
        {...props}
      />
      {capsLockHint && caps && (
        <span title="Caps Lock is on" className="me-0.5 flex h-5 flex-none items-center border border-solid border-[var(--notchset-signal-text,var(--destructive))] px-[5px] font-mono text-[10px] font-medium tracking-[0.1em] text-[var(--notchset-signal-text,var(--destructive))]">
          {labels?.caps ?? "⇪ CAPS"}
        </span>
      )}
      {revealable && (
        <>
          <span aria-hidden className="h-[22px] w-px flex-none bg-[var(--notchset-rule,var(--border))]" />
          <button
            {...OWN_SOUND}
            type="button"
            aria-pressed={shown}
            aria-label={shown ? (labels?.hide ?? "Hide password") : (labels?.show ?? "Show password")}
            // A disabled field's reveal is disabled with it.
            disabled={props.disabled}
            onClick={(e) => {
              if (props.disabled) return;
              playCue(e.currentTarget, "tick");
              setOwnShown(!shown);
              onShownChange?.(!shown);
            }}
            className={cn(
              `notchset-focus`,
              "[--notchset-focus-inset:-3px] flex h-[38px] w-10 flex-none cursor-pointer items-center justify-center border-0 bg-transparent p-0 text-foreground pointer-coarse:h-[42px] pointer-coarse:w-11 disabled:cursor-not-allowed disabled:text-muted-foreground",
            )}
          >
            <EyeGlyph shown={shown} />
          </button>
        </>
      )}
    </div>
  );
}

/** One rule a password passes or not. Checks describe the password; they don't measure its strength. */
export type PasswordCheck = { id: "length" | "long" | "mix" | "repeat" | "sequence"; label: string; ok: boolean };

/**
 * A strength verdict from a vetted estimator you plug in (zxcvbn-ts: `score`, its crack-time display
 * and its warning). Without one, the meter shows checks only and makes no strength claim.
 */
export type PasswordEstimate = { score: 0 | 1 | 2 | 3 | 4; crackTime?: string; warning?: string };

const SEQUENCES = ["abcdefghijklmnopqrstuvwxyz", "qwertyuiopasdfghjklzxcvbnm", "01234567890"];

/** Four characters in a row from the alphabet, the keyboard or the digits, either direction. */
function hasSequence(v: string) {
  const text = v.toLowerCase();
  for (let i = 0; i + 4 <= text.length; i++) {
    const run = text.slice(i, i + 4);
    const reversed = [...run].reverse().join("");
    if (SEQUENCES.some((seq) => seq.includes(run) || seq.includes(reversed))) return true;
  }
  return false;
}

/** The five checks the meter shows by default, in the order they're advised. */
export function passwordChecks(v: string): PasswordCheck[] {
  return [
    { id: "length", label: "12+ CHARACTERS", ok: v.length >= 12 },
    { id: "long", label: "16+ CHARACTERS", ok: v.length >= 16 },
    { id: "mix", label: "LETTERS WITH DIGITS OR SYMBOLS", ok: /[a-z]/i.test(v) && /[^a-z]/i.test(v) },
    { id: "repeat", label: "NO REPEATED RUNS", ok: v.length > 0 && !/(.)\1\1/.test(v) },
    { id: "sequence", label: "NO STRAIGHT SEQUENCES", ok: v.length > 0 && !hasSequence(v) },
  ];
}
```

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

```tsx
"use client";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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