# Phone Input (Notchset): prompt.md (v1.0.0)

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

A phone number field: a country key, the national number grouped as you type, a validity node, and a searchable list of 22 countries; it reports E.164 once complete.

## 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/phone-input.tsx`; shared code: `lib/beautiful-ui/notchset/instrument.tsx`, `lib/beautiful-ui/notchset/root.ts`.
- Registry dependencies, installed with it automatically: shadcn `utils` (cn), `notchset-foundation`.
- Builds: one set of files for both, but its dependencies come in Base UI and Radix builds. Install the one that matches the project (see Install): a free item's bare URL installs the Base UI build of it and its dependencies.
- Exports to keep: `PhoneInput`, `PHONE_COUNTRIES`, 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 { PhoneInput } from "@/components/ui/notchset/phone-input";
```

## Parts

| Part | data-slot | What it is for |
|---|---|---|
| `PhoneInput` | `phone-input` | The field. |
| `list` | `phone-input-root` | Field, help and list. |

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/phone-input.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
- phone input, phone number, country code, tel, E.164, Notchset
- Collecting a mobile number for pages, 2FA or contact

### Not when
- International address forms with many fields: use a dedicated library

## Mistakes
- Store the E.164 value, not the formatted text

## Usage

```tsx
"use client";

import * as React from "react";
import { PhoneInput } from "@/components/ui/notchset/phone-input";

export function OnCallPhone() {
  const [phone, setPhone] = React.useState("");
  return (
    <form action="/api/on-call" method="post">
      <PhoneInput defaultCountry="PT" onValueChange={setPhone} />
      <input type="hidden" name="phone" value={phone} />
    </form>
  );
}
```

## Props

| Prop | Type | Default | What it does |
|---|---|---|---|
| `defaultCountry / defaultValue` | `string / E.164` |  | Where to start. |
| `onValueChange` | `(e164, country) => void` |  | E.164 once complete, "" until then. |
| `countries` | `{ iso, name, dial, groups }[]` |  | Your list (22 by default). |
| `error` | `string` |  | A server's rejection, in place of the help line. |

Full docs: https://notchset.dev/components/phone-input

## 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 |
|---|---|
| + | Open the country list |
| ↑ / ↓ | Move |
| Enter | Pick |
| Esc | Close |

## Performance

- Formatting and filtering are synchronous string work; the list mounts with the field.

## Responsive

- Fills its container; the list is 260px. 44px field on touch screens.

## Motion inventory

| Interaction | What moves |
|---|---|
| Valid | The node's centre pops in (300ms) |
| List | Unrolls (360ms); the highlight glides between rows (140ms) |

## Accessibility contract (preserve when editing)
- type=tel with autocomplete tel-national; the help line describes it
- The country key is a listbox button; the list's search field leads it with aria-activedescendant
- Short numbers are flagged on blur, not while typing

## Install

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

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

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

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

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

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

## Source (Base UI build)

### components/ui/notchset/phone-input.tsx

```tsx
"use client";

/**
 * Phone Input (Notchset) v1.0.0 · Notchset
 * Docs: https://notchset.dev/components/phone-input
 * MIT licensed: free to use, change and share.
 */

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

/*
 * Notchset Phone Input (no primitive, one file for both builds). A 40px field: a country
 * key (ISO, dial code, a chevron that turns), the national number in mono (type="tel", grouped per
 * country as you type, extra digits cut), and a validity node that fills once the number is complete
 * or turns signal when it was left short. Typing + opens the country list filtered by dial code. The
 * list (260px) has a search row and 22 countries under one gliding highlight: ↑↓ move and keep it in
 * view, Enter picks, Esc closes. It reports E.164 ("+351912345678") once valid, "" until then.
 */

export type PhoneCountry = { iso: string; name: string; dial: string; groups: readonly number[] };

export const PHONE_COUNTRIES: PhoneCountry[] = [
  { iso: "PT", name: "Portugal", dial: "+351", groups: [3, 3, 3] },
  { iso: "US", name: "United States", dial: "+1", groups: [3, 3, 4] },
  { iso: "GB", name: "United Kingdom", dial: "+44", groups: [4, 6] },
  { iso: "DE", name: "Germany", dial: "+49", groups: [3, 8] },
  { iso: "FR", name: "France", dial: "+33", groups: [1, 2, 2, 2, 2] },
  { iso: "ES", name: "Spain", dial: "+34", groups: [3, 3, 3] },
  { iso: "IT", name: "Italy", dial: "+39", groups: [3, 3, 4] },
  { iso: "NL", name: "Netherlands", dial: "+31", groups: [1, 4, 4] },
  { iso: "IE", name: "Ireland", dial: "+353", groups: [2, 3, 4] },
  { iso: "SE", name: "Sweden", dial: "+46", groups: [2, 3, 2, 2] },
  { iso: "CH", name: "Switzerland", dial: "+41", groups: [2, 3, 2, 2] },
  { iso: "IN", name: "India", dial: "+91", groups: [5, 5] },
  { iso: "JP", name: "Japan", dial: "+81", groups: [2, 4, 4] },
  { iso: "KR", name: "South Korea", dial: "+82", groups: [2, 4, 4] },
  { iso: "SG", name: "Singapore", dial: "+65", groups: [4, 4] },
  { iso: "AU", name: "Australia", dial: "+61", groups: [3, 3, 3] },
  { iso: "AE", name: "United Arab Emirates", dial: "+971", groups: [2, 3, 4] },
  { iso: "BR", name: "Brazil", dial: "+55", groups: [2, 5, 4] },
  { iso: "MX", name: "Mexico", dial: "+52", groups: [2, 4, 4] },
  { iso: "CA", name: "Canada", dial: "+1", groups: [3, 3, 4] },
  { iso: "ZA", name: "South Africa", dial: "+27", groups: [2, 3, 4] },
  { iso: "NG", name: "Nigeria", dial: "+234", groups: [3, 3, 4] },
];

const ROW = 32;

function PhoneInput({
  label = "MOBILE NUMBER",
  defaultCountry = "PT",
  defaultValue,
  onValueChange,
  countries: countriesProp = PHONE_COUNTRIES,
  error,
  validate,
  className,
  labels,
}: {
  label?: React.ReactNode;
  defaultCountry?: string;
  /** A starting E.164 number; its country is found from the dial code. */
  defaultValue?: string;
  /** E.164 once the number is complete, "" until then. */
  onValueChange?: (e164: string, country: PhoneCountry) => void;
  countries?: readonly PhoneCountry[];
  /** An error to show instead of the help line (a server rejected it, say). */
  error?: string;
  /**
   * Whether a complete number is a real one (libphonenumber-js's isValidPhoneNumber, say). Without it,
   * "valid" only means the number has every digit its country's format shows; countries whose numbers
   * vary in length need a validator.
   */
  validate?: (e164: string, country: PhoneCountry) => boolean;
  className?: string;
  labels?: { hint?: string; short?: (n: number) => string; valid?: (country: string) => string; invalid?: string; search?: string; none?: string };
}) {
  const uid = React.useId();
  // An empty list means the built-in one; the choice is held by ISO code, so a list that changes keeps it (or falls back to the first).
  const countries = countriesProp.length ? countriesProp : PHONE_COUNTRIES;
  const initial = React.useMemo(() => {
    if (defaultValue?.startsWith("+")) {
      const c = [...countries].sort((a, b) => b.dial.length - a.dial.length).find((k) => defaultValue.startsWith(k.dial));
      if (c) return { cc: countries.indexOf(c), d: defaultValue.slice(c.dial.length).replace(/\D/g, "") };
    }
    return { cc: Math.max(0, countries.findIndex((k) => k.iso === defaultCountry)), d: "" };
  }, [countries, defaultCountry, defaultValue]);
  const [iso, setIso] = React.useState(countries[initial.cc]?.iso);
  const cc = Math.max(0, countries.findIndex((k) => k.iso === iso));
  const [digits, setDigits] = React.useState(initial.d);
  const [focus, setFocus] = React.useState(false);
  const [touched, setTouched] = React.useState(false);
  const [open, setOpen] = React.useState(false);
  const [cq, setCq] = React.useState("");
  const [h, setH] = React.useState(0);
  const input = React.useRef<HTMLInputElement>(null);
  const search = React.useRef<HTMLInputElement>(null);
  const list = React.useRef<HTMLDivElement>(null);
  const root = React.useRef<HTMLDivElement>(null);

  const C = countries[cc]!;
  const max = C.groups.reduce((a, b) => a + b, 0);
  const complete = digits.length === max;
  const valid = complete && (validate ? validate(`${C.dial}${digits}`, C) : true);
  const bad = !!error || (touched && !focus && digits.length > 0 && !valid);
  const fmt = (d: string) => {
    let o = "";
    let i = 0;
    for (const g of C.groups) {
      if (i >= d.length) break;
      o += (o ? " " : "") + d.slice(i, i + g);
      i += g;
    }
    return o;
  };
  const report = (d: string, country: PhoneCountry) => {
    const m = country.groups.reduce((a, b) => a + b, 0);
    const e164 = `${country.dial}${d}`;
    onValueChange?.(d.length === m && (!validate || validate(e164, country)) ? e164 : "", country);
  };
  // After reformatting, the caret goes back after the same number of digits it was after.
  const caretDigits = React.useRef<number | null>(null);
  React.useLayoutEffect(() => {
    const el = input.current;
    const want = caretDigits.current;
    if (!el || want === null) return;
    caretDigits.current = null;
    let seen = 0;
    let at = 0;
    while (at < el.value.length && seen < want) if (/\d/.test(el.value[at++]!)) seen++;
    el.setSelectionRange(at, at);
  });

  const q = cq.trim().toLowerCase().replace(/^\+/, "");
  const shown = countries.map((k, i) => ({ k, i })).filter(({ k }) => !q || k.name.toLowerCase().includes(q) || k.iso.toLowerCase().startsWith(q) || k.dial.slice(1).startsWith(q));
  const hi = Math.min(h, Math.max(0, shown.length - 1));

  const openList = (query: string, highlight: number) => {
    setCq(query);
    setH(highlight);
    setOpen(true);
    playCue(root.current, "tick");
    setTimeout(() => {
      search.current?.focus({ preventScroll: true });
      if (list.current) list.current.scrollTop = Math.max(0, highlight * ROW - 64);
    }, 20);
  };
  const pick = (i: number) => {
    playCue(root.current, "tick");
    const k = countries[i]!;
    const d = digits.slice(0, k.groups.reduce((a, b) => a + b, 0));
    setIso(k.iso);
    setDigits(d);
    setOpen(false);
    setCq("");
    report(d, k);
    setTimeout(() => input.current?.focus({ preventScroll: true }), 30);
  };
  React.useEffect(() => {
    if (!open) return;
    const onDown = (e: PointerEvent) => {
      if (!root.current?.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener("pointerdown", onDown);
    return () => document.removeEventListener("pointerdown", onDown);
  }, [open]);

  const help = error ?? (bad ? (complete ? (labels?.invalid ?? "NOT A VALID NUMBER") : (labels?.short?.(max - digits.length) ?? `${max - digits.length} DIGIT${max - digits.length > 1 ? "S" : ""} SHORT`)) : valid ? (labels?.valid?.(C.name) ?? `VALID · ${C.name.toUpperCase()}`) : (labels?.hint ?? "TYPE + TO SEARCH BY CODE"));

  return (
    <div {...NOTCHSET_ROOT} ref={root} data-slot="phone-input-root" className={cn("relative flex flex-col gap-2", className)}>
      <label htmlFor={`${uid}-n`} className="font-mono text-[11px] font-medium tracking-[0.1em] whitespace-nowrap text-foreground">
        {label}
      </label>
      <div
        data-slot="phone-input"
        data-invalid={bad || undefined}
        className={cn(
          "flex h-10 items-center border border-solid bg-background transition-[border-color] duration-(--notchset-fade) ease-(--notchset-ease-fade) pointer-coarse:h-11",
          bad ? "border-[var(--notchset-signal-text,var(--destructive))]" : focus || open ? "border-foreground" : "border-[var(--notchset-control-edge,var(--input))]",
        )}
      >
        <button
          {...OWN_SOUND}
          type="button"
          aria-haspopup="listbox"
          aria-expanded={open}
          aria-controls={`${uid}-list`}
          aria-label={`Country: ${C.name}, ${C.dial}`}
          onClick={() => (open ? setOpen(false) : openList("", cc))}
          className={cn(
            `notchset-focus`,
            "[--notchset-focus-inset:-3px] flex h-[38px] flex-none cursor-pointer items-center gap-2 border-0 border-e border-solid border-[var(--notchset-rule,var(--border))] ps-3 pe-2.5 text-foreground transition-[background-color] duration-(--notchset-fade) ease-(--notchset-ease-fade) pointer-coarse:h-[42px]",
            open ? "bg-accent" : "bg-transparent",
          )}
        >
          <span className="font-mono text-[11px] font-semibold tracking-[0.06em]">{C.iso}</span>
          <span className="font-mono text-[11px] text-muted-foreground">{C.dial}</span>
          <svg aria-hidden width="9" height="9" viewBox="0 0 12 12" className={cn("transition-transform duration-300 ease-[cubic-bezier(.34,1.5,.5,1)]", open && "rotate-180")}>
            <path d="M2.5 4.5 L6 8 L9.5 4.5" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="square" />
          </svg>
        </button>
        <input
          ref={input}
          id={`${uid}-n`}
          type="tel"
          inputMode="tel"
          autoComplete="tel-national"
          value={fmt(digits)}
          placeholder={fmt("0".repeat(max))}
          aria-invalid={bad || undefined}
          aria-describedby={`${uid}-help`}
          onChange={(e) => {
            const raw = e.target.value;
            if (raw.trim().startsWith("+")) {
              openList(raw.trim().slice(1), 0);
              return;
            }
            caretDigits.current = raw.slice(0, e.target.selectionStart ?? raw.length).replace(/\D/g, "").length;
            const d = raw.replace(/\D/g, "").slice(0, max);
            setDigits(d);
            report(d, C);
          }}
          onPaste={(e) => {
            // A whole international number (+44 20 7946 0958, or 0044…) picks its country and keeps the rest.
            const text = e.clipboardData.getData("text").trim();
            const intl = text.startsWith("+") ? text : text.startsWith("00") ? `+${text.slice(2)}` : null;
            if (!intl) return;
            const plain = `+${intl.replace(/\D/g, "")}`;
            const country = [...countries].sort((a, b) => b.dial.length - a.dial.length).find((k) => plain.startsWith(k.dial));
            if (!country) return;
            e.preventDefault();
            const m = country.groups.reduce((a, b) => a + b, 0);
            const d = plain.slice(country.dial.length).slice(0, m);
            playCue(root.current, "tick");
            setIso(country.iso);
            setDigits(d);
            report(d, country);
          }}
          onFocus={() => setFocus(true)}
          onBlur={() => {
            setFocus(false);
            setTouched(true);
          }}
          className="h-full min-w-0 flex-1 border-0 bg-transparent ps-3 pe-2.5 font-mono text-[13px] tracking-[0.02em] text-foreground tabular-nums outline-none placeholder:text-muted-foreground"
        />
        <span aria-hidden className="flex w-9 flex-none items-center justify-center">
          <svg width="11" height="11" viewBox="0 0 11 11" className={cn("overflow-visible transition-colors duration-(--notchset-fade) ease-(--notchset-ease-fade)", valid ? "text-foreground" : bad ? "text-[var(--notchset-signal-text,var(--destructive))]" : "text-[var(--notchset-control-edge,var(--input))]")}>
            <circle cx="5.5" cy="5.5" r="4" fill="none" stroke="currentColor" strokeWidth="1" />
            <circle cx="5.5" cy="5.5" fill="currentColor" className={cn("transition-[r] duration-300 ease-[var(--notchset-ease-bloom)]", valid ? "[r:2.2px]" : "[r:0px]")} />
          </svg>
        </span>
      </div>
      <div className="flex flex-wrap items-baseline justify-between gap-2.5 font-mono text-[10px] tracking-[0.04em] whitespace-nowrap gap-y-1">
        <span id={`${uid}-help`} aria-live="polite" className={bad ? "text-[var(--notchset-signal-text,var(--destructive))]" : valid ? "text-foreground" : "text-muted-foreground"}>
          {help}
        </span>
        <span className="text-muted-foreground tabular-nums">
          {digits.length}/{max}
        </span>
      </div>
      <div
        id={`${uid}-list`}
        role="listbox"
        aria-label="Country"
        aria-hidden={!open || undefined}
        inert={!open || undefined}
        className={cn(
          "absolute start-0 top-[66px] z-40 grid w-[260px] border border-solid border-foreground bg-background transition-[grid-template-rows,visibility]",
          open ? "visible grid-rows-[1fr] duration-[360ms] ease-[var(--notchset-ease-unfold)]" : "invisible grid-rows-[0fr] duration-[160ms] ease-[var(--notchset-ease-travel)]",
        )}
      >
        <div className="flex min-h-0 flex-col overflow-hidden">
          <div className="flex h-9 flex-none items-center gap-2 border-b border-solid border-[var(--notchset-rule,var(--border))] px-3 text-muted-foreground">
            <svg aria-hidden width="11" height="11" viewBox="0 0 13 13">
              <circle cx="5.5" cy="5.5" r="4.2" fill="none" stroke="currentColor" strokeWidth="1.2" />
              <path fill="none" d="M8.6 8.6 L12 12" stroke="currentColor" strokeWidth="1.2" />
            </svg>
            <input
              ref={search}
              value={cq}
              aria-label="Search countries"
              aria-controls={`${uid}-list`}
              aria-activedescendant={shown.length ? `${uid}-c-${hi}` : undefined}
              placeholder={labels?.search ?? "Country or +code"}
              onChange={(e) => {
                setCq(e.target.value);
                setH(0);
              }}
              onKeyDown={(e) => {
                if (e.key === "Escape") {
                  e.preventDefault();
                  setOpen(false);
                  input.current?.focus();
                } else if (e.key === "ArrowDown" || e.key === "ArrowUp") {
                  e.preventDefault();
                  if (!shown.length) return;
                  const n = (hi + (e.key === "ArrowDown" ? 1 : -1) + shown.length) % shown.length;
                  setH(n);
                  const L = list.current;
                  if (L) {
                    const top = 4 + n * ROW;
                    if (top < L.scrollTop) L.scrollTop = top - 4;
                    else if (top + ROW > L.scrollTop + L.clientHeight) L.scrollTop = top + ROW + 4 - L.clientHeight;
                  }
                } else if (e.key === "Enter" && !e.nativeEvent.isComposing) {
                  e.preventDefault();
                  if (shown[hi]) pick(shown[hi].i);
                }
              }}
              className="min-w-0 flex-1 border-0 bg-transparent p-0 font-mono text-[12px] text-foreground outline-none placeholder:text-muted-foreground"
            />
            <span className="font-mono text-[10px] tracking-[0.06em] whitespace-nowrap">
              {shown.length} OF {countries.length}
            </span>
          </div>
          <div ref={list} className="max-h-[224px] overflow-y-auto [scrollbar-color:var(--notchset-control-edge,var(--input))_transparent] [scrollbar-width:thin]">
            <div className="relative py-1">
              <span aria-hidden className="absolute inset-x-0 h-8 bg-[var(--notchset-faceplate,var(--card))] transition-[top,opacity] duration-[var(--notchset-travel),var(--notchset-fade)] ease-[var(--notchset-ease-glide),var(--notchset-ease-fade)]" style={{ top: 4 + hi * ROW, opacity: shown.length ? 1 : 0 }} />
              {shown.map(({ k, i }, j) => (
                <div
                  key={k.iso}
                  id={`${uid}-c-${j}`}
                  role="option"
                  aria-selected={i === cc}
                  onMouseDown={(e) => {
                    e.preventDefault();
                    pick(i);
                  }}
                  onMouseEnter={() => setH(j)}
                  className="relative flex h-8 cursor-pointer items-center gap-2.5 px-3 font-mono text-[11px] tracking-[0.04em] text-foreground"
                >
                  <span className="w-[22px] font-semibold">{k.iso}</span>
                  <span className="min-w-0 flex-1 truncate font-sans text-[13px] font-medium">{k.name}</span>
                  <span className="text-muted-foreground">{k.dial}</span>
                  <svg aria-hidden width="9" height="9" viewBox="0 0 9 9" className="flex-none overflow-visible">
                    <circle cx="4.5" cy="4.5" className={cn("fill-foreground transition-[r] duration-[220ms] ease-[cubic-bezier(.34,1.6,.5,1)]", i === cc ? "[r:2.2px]" : "[r:0px]")} />
                  </svg>
                </div>
              ))}
              {!shown.length && <div className="flex h-8 items-center px-3 font-mono text-[11px] text-muted-foreground">{labels?.none ?? "NO COUNTRY MATCHES"}</div>}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export { PhoneInput };
```

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