# Expanding button (Notchset): prompt.md (v1.1.0)

- id: `expanding-button` · version 1.1.0 · component · free
- category: Buttons
- build: one set of files for every shadcn style
- install: `npx shadcn@latest add https://notchset.dev/r/expanding-button.json`
- npm dependencies: lucide-react@^1
- registry dependencies: utils, https://notchset.dev/r/notchset-foundation.json, @notchset/button
- docs: https://notchset.dev/components/expanding-button
- The install command carries everything this item needs (files, CSS, tokens, npm and registry dependencies). Prefer it to copying source by hand.

One create button (New) that opens into its few kinds in place: the plus turns into a close mark as the kinds roll up beneath it, centred, each icon acting as it lands. Choose one and it slides home under New, turns green with its result, then the set folds and focus returns to New..

## Build it
- Stack: React 18.3 or 19, TypeScript, Tailwind CSS v4 utility classes on the foundation's roles, a components.json (imports use its aliases).
- Packages: `lucide-react@^1` beyond `react` and `react-dom`.
- Files: `components/ui/notchset/expanding-button.tsx`; shared code: `lib/notchset/button-class.ts`, `lib/notchset/button-look.ts`, `lib/notchset/button-move.ts`, `lib/notchset/feedback.ts`, `lib/notchset/hit-area.ts`, `lib/notchset/icons.ts`, `lib/notchset/motion.ts`.
- Registry dependencies, installed with it automatically: shadcn `utils` (cn), `notchset-foundation`, `button`.
- Builds: one set of files, the same for every shadcn style.
- Exports to keep: `ExpandingButton`, `TaskMark`, and every exported type.
- CSS: the install adds the notchset foundation (its roles, keyframes and motion switch, reading your shadcn tokens for colour) 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.
- Colours: every part reads the foundation's roles (`--ns-canvas`, `--ns-ink`, `--ns-line`, `--ns-signal` …), which read your shadcn tokens (`--background`, `--foreground`, `--border`, `--destructive` …), plus the optional `--success` and `--warning`. Retheme on `:root` or any container; never add Tailwind colour classes inside the component.
- This item reads `--ns-bad-ink`, `--ns-btn-bad`, `--ns-btn-bad-hover`, `--ns-btn-bad-line`, `--ns-btn-bezel`, `--ns-btn-gone`, `--ns-btn-ok`, `--ns-btn-roll`, `--ns-btn-tonal`, `--ns-btn-tonal-edge`, `--ns-btn-tonal-hover`, `--ns-button`, `--ns-button-icon`, `--ns-button-lg`, `--ns-button-sm`, `--ns-ease-move`, `--ns-font-body`, `--ns-hover`, `--ns-icon`, `--ns-ink`, `--ns-ink-3`, `--ns-ink-4`, `--ns-lift`, `--ns-press-min`, `--ns-primary-hover`, `--ns-primary-press`, `--ns-radius-button`, `--ns-radius-button-lg`, `--ns-radius-button-sm`, `--ns-raised`, `--ns-signal`, `--ns-text-control`, `--ns-text-control-lg`, `--ns-text-small`, `--ns-tracking-control`, `--ns-weight-medium`.
- Retune it (on any ancestor) with the foundation's roles and hooks: `--ns-agent-b`, `--ns-agent-c`, `--ns-agent-d`, `--ns-agent-drift`, `--ns-agent-fill`, `--ns-agent-h1`, `--ns-agent-h2`, `--ns-agent-h3`, `--ns-agent-shift`, `--ns-avatar-card`, `--ns-avatar-lg`, `--ns-avatar-md`, `--ns-avatar-sm`, `--ns-avatar-xs`, `--ns-bad`, `--ns-bad-ink`, `--ns-band`, `--ns-band-edge`, `--ns-band-grade`, `--ns-band-optimal`, `--ns-banner-beat`, `--ns-banner-radius`, `--ns-beat`, `--ns-beat-ease`, `--ns-bezel`, `--ns-bloom-close`, `--ns-bloom-open`, `--ns-bloom-rise`, `--ns-btn-bad`, `--ns-btn-bad-hover`, `--ns-btn-bad-line`, `--ns-btn-bezel`, `--ns-btn-chosen`, `--ns-btn-gone`, `--ns-btn-morph`, `--ns-btn-ok`, `--ns-btn-press`, `--ns-btn-release`, `--ns-btn-result`, `--ns-btn-roll`, `--ns-btn-stagger`, `--ns-btn-stagger-step`, `--ns-btn-tick`, `--ns-btn-tonal`, `--ns-btn-tonal-edge`, `--ns-btn-tonal-hover`, `--ns-bulk-clear`, `--ns-button`, `--ns-button-field-inset`, `--ns-button-lg`, `--ns-button-sm`, `--ns-canvas`, `--ns-card-tilt`, `--ns-cat-1`, `--ns-cat-2`, `--ns-cat-3`, `--ns-cat-4`, `--ns-cat-5`, `--ns-cat-6`, `--ns-check`, `--ns-check-round`, `--ns-cheer-1`, `--ns-cheer-2`, `--ns-cheer-3`, `--ns-cheer-edge`, `--ns-cheer-fold`, `--ns-cheer-glow`, `--ns-cheer-lift`, `--ns-chip`, `--ns-chip-pick`, `--ns-control`, `--ns-control-lg`, `--ns-control-pad`, `--ns-control-sm`, `--ns-corner`, `--ns-danger`, `--ns-deep`, `--ns-deep-ink`, `--ns-deep-ink-2`, `--ns-deep-line`, `--ns-depth-card`, `--ns-depth-lift`, `--ns-depth-surface`, `--ns-dialog`, `--ns-dialog-grow`, `--ns-dialog-lg`, `--ns-dialog-max`, `--ns-dialog-shrink`, `--ns-dialog-sm`, `--ns-dialog-top`, `--ns-dock-bottom`, `--ns-drop`, `--ns-ease`, `--ns-ease-arrive`, `--ns-ease-breathe`, `--ns-ease-drum`, `--ns-ease-exit`, `--ns-ease-fling`, `--ns-ease-glide`, `--ns-ease-grow`, `--ns-ease-move`, `--ns-ease-panel`, `--ns-ease-pop`, `--ns-ease-press`, `--ns-ease-spring`, `--ns-ebg-arm`, `--ns-ebg-lit`, `--ns-emoji`, `--ns-emoji-md`, `--ns-emoji-sm`, `--ns-field`, `--ns-field-edge`, `--ns-field-h`, `--ns-fill`, `--ns-fill-time`, `--ns-flood-arc`, `--ns-flood-aurora`, `--ns-flood-behind-1`, `--ns-flood-behind-2`, `--ns-flood-bloom`, `--ns-flood-deep`, `--ns-flood-dial-bloom`, `--ns-flood-glass`, `--ns-flood-grain`, `--ns-flood-image`, `--ns-flood-ink`, `--ns-flood-ink-low`, `--ns-flood-light`, `--ns-flood-mid`, `--ns-flood-pale`, `--ns-flood-pane`, `--ns-flood-pane-edge`, `--ns-flood-pill-ink`, `--ns-flood-ribbon`, `--ns-flood-ribbon-core`, `--ns-flood-shadow`, `--ns-flood-sheen`, `--ns-flood-wash`, `--ns-font-body`, `--ns-font-display`, `--ns-font-mono`, `--ns-font-script`, `--ns-glass`, `--ns-glass-blur`, `--ns-glass-shadow`, `--ns-glow`, `--ns-glyph-pad`, `--ns-grain`, `--ns-gutter`, `--ns-header`, `--ns-help-max`, `--ns-hit`, `--ns-hover`, `--ns-icon`, `--ns-icon-lg`, `--ns-icon-sm`, `--ns-icon-stroke`, `--ns-info`, `--ns-info-ink`, `--ns-ink`, `--ns-ink-2`, `--ns-ink-3`, `--ns-ink-4`, `--ns-layer-bar`, `--ns-layer-modal`, `--ns-layer-panel`, `--ns-layer-popup`, `--ns-layer-sticky`, `--ns-layer-tip`, `--ns-layer-toast`, `--ns-layer-zoom`, `--ns-lead-body`, `--ns-lead-figure`, `--ns-lead-large`, `--ns-lead-meta`, `--ns-lead-small`, `--ns-lead-sub`, `--ns-lead-title`, `--ns-leading`, `--ns-leading-prose`, `--ns-leading-title`, `--ns-lift`, `--ns-light-1`, `--ns-light-2`, `--ns-light-3`, `--ns-light-spread`, `--ns-light-strength`, `--ns-line`, `--ns-line-soft`, `--ns-lit-edge`, `--ns-map-grass`, `--ns-map-water`, `--ns-mark-edge`, `--ns-mark-lifted`, `--ns-mark-rest`, `--ns-mark-swap`, `--ns-marker`, `--ns-marker-ink`, `--ns-mc-place`, `--ns-mc-roll`, `--ns-measure`, `--ns-menu-dy`, `--ns-menu-lit`, `--ns-menu-pad`, `--ns-menu-row`, `--ns-menu-rule`, `--ns-mesh`, `--ns-mesh-frost`, `--ns-nest-inset`, `--ns-nest-outer`, `--ns-nest-r`, `--ns-notch-ease`, `--ns-ok`, `--ns-ok-ink`, `--ns-on-fill`, `--ns-orb-body`, `--ns-orb-cool`, `--ns-orb-core`, `--ns-orb-dawn`, `--ns-orb-deep`, `--ns-orb-edge`, `--ns-orb-grain`, `--ns-orb-ground`, `--ns-orb-halo`, `--ns-orb-inner`, `--ns-orb-key`, `--ns-orb-lift`, `--ns-orb-limb`, `--ns-orb-limb-from`, `--ns-orb-rim`, `--ns-orb-skin-hi`, `--ns-orb-skin-lo`, `--ns-orb-skin-mid`, `--ns-orb-warm`, `--ns-palette-min`, `--ns-panel`, `--ns-panel-room`, `--ns-panel-w`, `--ns-panel-w-lg`, `--ns-pick-slot`, `--ns-pill-prop`, `--ns-play-fill`, `--ns-play-fill-color`, `--ns-play-lift`, `--ns-play-lift-y`, `--ns-play-open`, `--ns-play-open-content`, `--ns-play-press`, `--ns-play-press-box`, `--ns-play-reduced`, `--ns-play-ring`, `--ns-play-roll`, `--ns-play-shake`, `--ns-play-spring`, `--ns-play-swap`, `--ns-play-swap-blur`, `--ns-press-min`, `--ns-press-scale`, `--ns-press-x`, `--ns-press-y`, `--ns-primary-hover`, `--ns-primary-press`, `--ns-prism-edge`, `--ns-prism-glint`, `--ns-prism-sheen`, `--ns-prism-tint`, `--ns-pulse`, `--ns-radius`, `--ns-radius-2xl`, `--ns-radius-button`, `--ns-radius-button-lg`, `--ns-radius-button-sm`, `--ns-radius-card`, `--ns-radius-check`, `--ns-radius-control`, `--ns-radius-control-sm`, `--ns-radius-float`, `--ns-radius-full`, `--ns-radius-lg`, `--ns-radius-mark`, `--ns-radius-menu-row`, `--ns-radius-modal`, `--ns-radius-pill`, `--ns-radius-sm`, `--ns-radius-xl`, `--ns-radius-xs`, `--ns-raised`, `--ns-ramp-1`, `--ns-ramp-2`, `--ns-ramp-3`, `--ns-ramp-4`, `--ns-ramp-5`, `--ns-ramp-shine`, `--ns-range`, `--ns-rest-1`, `--ns-rest-2`, `--ns-rest-3`, `--ns-rise`, `--ns-row`, `--ns-row-compact`, `--ns-row-hue`, `--ns-scrim`, `--ns-search-h`, `--ns-segment`, `--ns-segment-inset`, `--ns-segment-lift`, `--ns-segment-sm`, `--ns-selected`, `--ns-series`, `--ns-series-core`, `--ns-series-glint`, `--ns-series-tint`, `--ns-shadow-dialog`, `--ns-shadow-float`, `--ns-shadow-lift`, `--ns-shadow-panel`, `--ns-sheet`, `--ns-sheet-back`, `--ns-sheet-bottom`, `--ns-sheet-drop`, `--ns-sheet-rise`, `--ns-shift`, `--ns-side`, `--ns-signal`, `--ns-signal-ink`, `--ns-signal-wash`, `--ns-sk-figure`, `--ns-sk-land`, `--ns-sk-p`, `--ns-sk-p0`, `--ns-sk-p1`, `--ns-sk-p2`, `--ns-sk-p3`, `--ns-sk-p4`, `--ns-sk-p5`, `--ns-sk-p6`, `--ns-sk-p7`, `--ns-sk-read`, `--ns-sk-sweep`, `--ns-skeleton`, `--ns-skeleton-bone`, `--ns-skeleton-bone-light`, `--ns-skeleton-light`, `--ns-slab`, `--ns-slab-edge`, `--ns-slab-ink`, `--ns-sleep-awake`, `--ns-sleep-deep`, `--ns-sleep-light`, `--ns-sleep-rem`, `--ns-space-1`, `--ns-space-2`, `--ns-space-3`, `--ns-space-4`, `--ns-space-5`, `--ns-space-6`, `--ns-space-8`, `--ns-space-section`, `--ns-stack-fan`, `--ns-stack-fan-gap`, `--ns-stack-fan-lag`, `--ns-stack-on`, `--ns-stagger-item`, `--ns-stagger-mark`, `--ns-stagger-max`, `--ns-standing-critical`, `--ns-standing-in`, `--ns-standing-out`, `--ns-state-doing`, `--ns-state-done`, `--ns-state-review`, `--ns-state-todo`, `--ns-step`, `--ns-step-from`, `--ns-step-sign`, `--ns-swipe-surface`, `--ns-switch-h`, `--ns-switch-w`, `--ns-text-body`, `--ns-text-control`, `--ns-text-control-lg`, `--ns-text-display`, `--ns-text-editorial`, `--ns-text-empty`, `--ns-text-figure`, `--ns-text-giant`, `--ns-text-heading`, `--ns-text-headline`, `--ns-text-input`, `--ns-text-large`, `--ns-text-lede`, `--ns-text-meta`, `--ns-text-record`, `--ns-text-sentence`, `--ns-text-small`, `--ns-text-sub`, `--ns-text-title`, `--ns-theme-fade`, `--ns-tile-shadow`, `--ns-time-born`, `--ns-time-color`, `--ns-time-confirm`, `--ns-time-dialog`, `--ns-time-fling`, `--ns-time-flip`, `--ns-time-glide`, `--ns-time-grow`, `--ns-time-hold`, `--ns-time-menu`, `--ns-time-page`, `--ns-time-panel`, `--ns-time-quick`, `--ns-time-roll`, `--ns-time-settle`, `--ns-time-snap`, `--ns-time-spin`, `--ns-time-spring`, `--ns-time-sweep`, `--ns-time-toast`, `--ns-tint`, `--ns-tint-c`, `--ns-tint-ease`, `--ns-tint-fill`, `--ns-tint-gap`, `--ns-tint-h1`, `--ns-tint-h2`, `--ns-tint-h3`, `--ns-tint-ink`, `--ns-tint-row`, `--ns-tip-fold`, `--ns-tip-grow`, `--ns-toast-bottom`, `--ns-toast-gap`, `--ns-toast-left`, `--ns-toast-lift`, `--ns-toast-peek`, `--ns-toast-scale`, `--ns-toast-w`, `--ns-touch`, `--ns-tracking-body`, `--ns-tracking-caps`, `--ns-tracking-control`, `--ns-tracking-display`, `--ns-tracking-headline`, `--ns-tracking-sub`, `--ns-tracking-title`, `--ns-warn`, `--ns-warn-ink`, `--ns-wash-clay`, `--ns-wash-dusk`, `--ns-wash-graphite`, `--ns-wash-ink`, `--ns-wash-sage`, `--ns-wash-sand`, `--ns-weight-light`, `--ns-weight-medium`, `--ns-weight-regular`, `--ns-weight-strong`, `--ns-well`, `--ns-width-lg`, `--ns-width-md`, `--ns-width-sm`, `--ns-width-xl`.
- Never add Tailwind colour classes inside the component.

```tsx
import { ExpandingButton, TaskMark, type ExpandingKind } from "@/components/ui/notchset/expanding-button";
```

## Parts
- A single export that takes props.

## Match the original
- Read `components/ui/notchset/expanding-button.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
- One create action with two to four kinds a person picks between every time (a deal, a task, a note).

### Not when
- One verb with close variants is a SplitButton; actions on a thing are a Menu on its ⋯; five or more kinds are a Menu.

## Built from
- button (`button`), installed with it: reuse it, don't rebuild it
- Button class (shared helper, ships with it)
- Button look (shared helper, ships with it)
- Button move (shared helper, ships with it)
- Feedback (shared helper, ships with it)
- Hit area (shared helper, ships with it)
- Icons (shared helper, ships with it)
- Motion (shared helper, ships with it)

## Mistakes
- Five or more kinds: they belong in a Menu
- Kinds that are not one verb's objects (New deal beside Settings)
- Placing it where the room below is cut off: the kinds open down

## Usage

```tsx
"use client";
import * as React from "react";
import { Handshake, NotebookPen } from "@/lib/notchset/icons";
import { ExpandingButton, TaskMark, type ExpandingKind } from "@/components/ui/notchset/expanding-button";
import { useLessMotion } from "@/lib/notchset/motion";
import { pressIn, useSelfPlay } from "./self-play";

/*
 * A CRM's New, at rest and closed, centred: press it and the plus turns into a close mark as Deal, Task and Note roll
 * up beneath it, each icon acting as it lands (the hands squeeze, the check draws, the pen wiggles). Choose one and it
 * slides home under New, turns green and says what it did, then the set folds and focus is back on New. The room
 * below is held, so the page never moves as it opens. On arrival it opens once and folds again, resting closed (with
 * less motion it rests closed at once); then it is yours. `state` presses it for real: open (it stays open until a choice, Escape or a press outside) or a kind chosen (its result, then the fold).
 */
const KINDS: ExpandingKind[] = [
  { id: "deal", label: "New deal", short: "Deal", icon: Handshake, doneLabel: "Deal drafted", act: "squeeze" },
  { id: "task", label: "New task", short: "Task", icon: TaskMark, doneLabel: "Task added", act: "draw" },
  { id: "note", label: "New note", short: "Note", icon: NotebookPen, doneLabel: "Note started", act: "wiggle" },
];

export default function ExpandingButtonDemo() {
  const less = useLessMotion();
  const state = "rest" as "rest" | "open" | "done";
  const root = React.useRef<HTMLDivElement>(null);
  const play = useSelfPlay(root, { beats: [400, 1600], off: less, hold: state !== "rest" });
  React.useEffect(() => {
    /* opens down once, then folds: the same press both times */
    if (!play.mine && !less && play.step >= 0) pressIn(root.current, "[data-slot=expanding-button] button[aria-expanded]");
  }, [play.step, play.mine, less]);
  React.useEffect(() => {
    if (state === "rest") return;
    root.current?.querySelector<HTMLButtonElement>("[data-slot=expanding-button] button[aria-expanded]")?.click();
    if (state !== "done") return;
    /* the kinds roll up, then the first is chosen */
    const t = setTimeout(() => root.current?.querySelector<HTMLButtonElement>("[data-slot=expanding-button-kind] button")?.click(), 500);
    return () => clearTimeout(t);
  }, [state]);
  return (
    <div ref={root} onPointerDownCapture={play.handOver} onKeyDownCapture={play.handOver} className="flex w-full flex-col items-center py-12">
      <ExpandingButton kinds={KINDS}>
        New
      </ExpandingButton>
    </div>
  );
}
```

## Props

| Prop | Type | Default | What it does |
|---|---|---|---|
| `kinds` | `readonly ExpandingKind[]` |  | the few kinds it opens into, two to four |
| `onPick` | `(id: string) => void` |  | called with the kind chosen |
| `closeLabel` | `string` | `"Close"` | the button's name while open, for screen readers |
| `onFeedback` | `(e: FeedbackEvent) => void` |  | called once per move, for your sound or haptics |

Full docs: https://notchset.dev/components/expanding-button

## Customising
- Colours: every part reads the foundation's roles (`--ns-canvas`, `--ns-ink`, `--ns-line`, `--ns-signal` …), which read your shadcn tokens (`--background`, `--foreground`, `--border`, `--destructive` …), plus the optional `--success` and `--warning`. Retheme on `:root` or any container; never add Tailwind colour classes inside the component.
- Dark mode follows the `.dark` class or `data-theme="dark"` on an ancestor (the shadcn and next-themes conventions).
- Update later: Commit or stash local changes first (or copy the files), so the update can be undone. Read https://notchset.dev/r/changelog.json for the new versions: a major version, an entry marked breaking or a merge says what to change. Then re-run the install with `--overwrite`, on a branch. It replaces the component's files, the shared helper files they import, and the item's CSS rules in the global stylesheet, so review the whole diff (components, shared files, CSS), re-apply your own edits, and run the app's typecheck, tests and build.

## Keyboard

| Keys | Action |
|---|---|
| Enter or Space on New | open the kinds, or fold them |
| Tab | New, then each kind while open |
| Enter or Space on a kind | choose it |
| Escape | fold, back on New |

## Performance

- One button and its few kinds, drawn once; a ResizeObserver keeps where each kind lands; nothing runs at rest.

## Responsive

- phone and desktop
- dark (tokens)
- reduced motion: nothing travels or turns; the kinds fade in and out

## Motion inventory

| Interaction | What moves |
|---|---|
| the plus turns 45deg into a close mark | rotate, --ns-btn-roll, --ns-ease-move. Reduced motion: turns at once. |
| the kinds roll up from below the line, one after another, clipped 4px outside | translate and opacity, --ns-btn-roll, --ns-ease-move, --ns-btn-stagger apart. Reduced motion: they fade, nothing travels. |
| each icon acts as it lands: the hands squeeze, the check draws, the pen wiggles | ns-btn-squeeze, ns-btn-draw, ns-btn-wiggle on --ns-ease-move. Reduced motion: none. |
| the chosen kind slides home centred under New and rolls its result with the tick | translate 320ms --ns-ease-move; the roll on --ns-btn-roll; --ns-btn-tick. Reduced motion: the words crossfade. |
| after 1200ms the set rolls back down in reverse order | translate and opacity, --ns-btn-roll, --ns-ease-move. Reduced motion: they fade. |

## Accessibility contract (preserve when editing)
- New is a native button with aria-expanded, named by closeLabel while open.
- The kinds are native buttons, out of the tab order and hidden while closed; the chosen kind's result is read once from a polite live region.

## Install

```bash
# npm
npx shadcn@latest add https://notchset.dev/r/expanding-button.json
# pnpm
pnpm dlx shadcn@latest add https://notchset.dev/r/expanding-button.json
# yarn
yarn dlx shadcn@latest add https://notchset.dev/r/expanding-button.json
# bun
bunx --bun shadcn@latest add https://notchset.dev/r/expanding-button.json
```

Or add the `@notchset` registry to components.json and run `npx shadcn@latest add @notchset/expanding-button`. Every components.json style gets the same files.

### Manual

1. Install the packages: `npm install lucide-react@^1`.
2. Copy `components/ui/notchset/expanding-button.tsx`, `lib/notchset/button-class.ts`, `lib/notchset/button-look.ts`, `lib/notchset/button-move.ts`, `lib/notchset/feedback.ts`, `lib/notchset/hit-area.ts`, `lib/notchset/icons.ts`, `lib/notchset/motion.ts` from https://notchset.dev/r/expanding-button.json (each file's `content`, at its `target`), keeping the `@/` path alias of your tsconfig.
3. Add what it builds on: shadcn `utils` (cn), `notchset-foundation`, `button`.

## Continue the workflow

- [Action button](https://notchset.dev/components/action-button)
- [Action swap](https://notchset.dev/components/action-swap)
- [Button](https://notchset.dev/components/button)

## Source

### components/ui/notchset/expanding-button.tsx

```tsx
// Notchset expanding-button 1.1.0 · https://notchset.dev/changelog
"use client";
import * as React from "react";
import { Plus, type LucideIcon } from "@/lib/notchset/icons";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/notchset/button";
import { ButtonTick } from "@/lib/notchset/button-look";
import { buttonRollLayer, useButtonRoll } from "@/lib/notchset/button-move";
import { buttonBase, buttonIntents, buttonResults, buttonSizes } from "@/lib/notchset/button-class";
import { useLessMotion } from "@/lib/notchset/motion";
import type { FeedbackProps } from "@/lib/notchset/feedback";

const useIsomorphicLayoutEffect = typeof window === "undefined" ? React.useEffect : React.useLayoutEffect;

/*
 * Expanding button (Ink): one create button that opens into its few kinds, in place. Press New and
 * its plus turns into a close mark as the kinds roll up beneath it, centred, one after another, each icon acting as it
 * lands. Choose one: it slides home centred under New, turns green and rolls its result with the tick; after a beat the
 * set rolls back down and focus returns to New. Escape or a press outside folds it. New never moves, so nothing around
 * it does. In a narrow container the kinds say their short word (under 460px) and drop their icons (under 340px), so it
 * fills its container's width to measure it.
 *
 *   <ExpandingButton kinds={[{ id: "deal", label: "New deal", short: "Deal", icon: Handshake, doneLabel: "Deal drafted", act: "squeeze" }]} onPick={create}>New</ExpandingButton>
 */

/** One kind the button opens into. */
type ExpandingKind = {
  id: string;
  /** its words ("New deal") */
  label: React.ReactNode;
  /** its words when the container is narrow ("Deal") */
  short?: React.ReactNode;
  icon?: LucideIcon | React.ComponentType<React.SVGProps<SVGSVGElement>> | undefined;
  /** what it says once chosen ("Deal drafted"), in green with the tick */
  doneLabel: React.ReactNode;
  /** how its icon acts as it lands: the hands squeeze, a check draws (an icon with a data-ns-check path), a pen wiggles */
  act?: "squeeze" | "draw" | "wiggle" | undefined;
  onClick?: (() => void) | undefined;
};

type ExpandingButtonProps = {
  /** the create verb on the button ("New") */
  children: React.ReactNode;
  /** the few kinds it opens into, two to four */
  kinds: readonly ExpandingKind[];
  /** called with the kind chosen */
  onPick?: ((id: string) => void) | undefined;
  /** the button's name while open, for screen readers */
  closeLabel?: string | undefined;
  className?: string | undefined;
} & FeedbackProps;

const STAGGER = 30; // --ns-btn-stagger: ms between kinds
const REPORT = 1200; // ms the chosen kind shows its result before the set folds
const ROLL = 260; // --ns-btn-roll

/** A task's mark for a kind: a circle whose check draws as the kind lands (act "draw"). */
function TaskMark(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden {...props}>
      <circle cx="12" cy="12" r="10" />
      <path data-ns-check="" pathLength={1} d="m9 12 2 2 4-4" />
    </svg>
  );
}

const KIND = cn(buttonBase, buttonSizes.md, buttonIntents.secondary, buttonResults, "whitespace-nowrap");
const MASK = "-my-[3px] grid gap-[inherit] py-[3px] [mask-image:linear-gradient(transparent,#000_22%,#000_78%,transparent)]";

function KindWords({ kind }: { kind: ExpandingKind }) {
  const Icon = kind.icon;
  return (
    <>
      {Icon && (
        <span data-ns-kind-mark={kind.act} className="inline-grid origin-center @max-[340px]:hidden">
          <Icon aria-hidden />
        </span>
      )}
      {kind.short === undefined ? (
        <span>{kind.label}</span>
      ) : (
        <>
          <span className="@max-[460px]:hidden">{kind.label}</span>
          <span className="@min-[460px]:hidden">{kind.short}</span>
        </>
      )}
    </>
  );
}

function Kind({ kind, chosen, less, ...props }: { kind: ExpandingKind; chosen: boolean; less: boolean } & React.ComponentPropsWithoutRef<"button">) {
  const roll = useButtonRoll(chosen ? "done" : "rest");
  return (
    <button type="button" data-ns-press="" data-intent="secondary" data-state={chosen ? "done" : undefined} className={cn(KIND, chosen && "pointer-events-none")} {...props}>
      <span className={MASK}>
        <span aria-hidden={chosen || undefined} className={buttonRollLayer(roll("rest"), less)}>
          <KindWords kind={kind} />
        </span>
        <span aria-hidden={!chosen || undefined} className={buttonRollLayer(roll("done"), less)}>
          {/* the result is drawn only once chosen, so at rest each kind is exactly its resting width and none overlaps */}
          {chosen && <ButtonTick className="size-4" />}
          {chosen && kind.doneLabel}
        </span>
      </span>
    </button>
  );
}

function ExpandingButton({ children, kinds, onPick, closeLabel = "Close", className, onFeedback }: ExpandingButtonProps) {
  const less = useLessMotion();
  const [open, setOpen] = React.useState(false);
  const [chosen, setChosen] = React.useState<number | null>(null);
  const root = React.useRef<HTMLDivElement>(null);
  const main = React.useRef<HTMLButtonElement>(null);
  const slots = React.useRef<(HTMLSpanElement | null)[]>([]);
  const [shift, setShift] = React.useState<number[]>([]);

  /* how far each kind slides to land centred under New, measured on the row's axis */
  useIsomorphicLayoutEffect(() => {
    const read = () => setShift(slots.current.map((el) => (el ? ((el.parentElement?.offsetWidth ?? 0) - el.offsetWidth) / 2 - el.offsetLeft : 0)));
    read();
    if (typeof ResizeObserver === "undefined") return;
    const ro = new ResizeObserver(read);
    slots.current.forEach((el) => el && ro.observe(el));
    return () => ro.disconnect();
  }, [kinds.length]);

  const fold = React.useCallback((refocus: boolean) => {
    setOpen(false);
    if (refocus) main.current?.focus();
  }, []);

  /* the chosen kind reports, then the set folds; its result clears once the fold is done */
  React.useEffect(() => {
    if (chosen === null) return;
    const t = open ? setTimeout(() => fold(true), REPORT) : setTimeout(() => setChosen(null), 420 + STAGGER * kinds.length);
    return () => clearTimeout(t);
  }, [chosen, open, fold, kinds.length]);

  React.useEffect(() => {
    if (!open) return;
    const away = (e: PointerEvent) => {
      if (!root.current?.contains(e.target as Node)) fold(false);
    };
    document.addEventListener("pointerdown", away);
    return () => document.removeEventListener("pointerdown", away);
  }, [open, fold]);

  const n = kinds.length;
  return (
    <div
      ref={root}
      data-slot="expanding-button"
      data-land={(open && chosen === null) || undefined}
      data-ns-less={less || undefined}
      className={cn("@container flex w-full justify-center", className)}
      onKeyDown={(e) => {
        if (e.key === "Escape" && open) {
          e.preventDefault();
          fold(true);
        }
      }}
    >
      <div className="relative inline-flex">
        <Button
          ref={main}
          intent="primary"
          aria-expanded={open}
          aria-label={open ? closeLabel : undefined}
          onFeedback={onFeedback}
          onClick={() => {
            if (open) fold(false);
            else {
              setChosen(null);
              setOpen(true);
            }
          }}
          className="z-10"
        >
          <Plus aria-hidden data-slot="expanding-button-plus" className={cn(open && "rotate-45")} />
          {children}
        </Button>
        <div
          aria-hidden={!open || undefined}
          className={cn("absolute top-full left-1/2 z-10 mt-2 inline-flex -translate-x-1/2 items-center gap-1.5 whitespace-nowrap [overflow:clip] [overflow-clip-margin:4px]", !open && "pointer-events-none")}
        >
          {kinds.map((kind, i) => {
            const isChosen = chosen === i;
            const shown = open && (chosen === null || isChosen);
            const move = isChosen ? (shift[i] ?? 0) : 0;
            const delay = isChosen ? 0 : open ? i * STAGGER : (n - 1 - i) * STAGGER;
            return (
              <span
                key={kind.id}
                ref={(el) => {
                  slots.current[i] = el;
                }}
                className="relative inline-flex"
                style={{ "--ns-kind-land": `${i * STAGGER + ROLL - 60}ms` } as React.CSSProperties}
              >
                {/* holds the kind's resting width, so the set never reflows as one grows */}
                <span aria-hidden className={cn(KIND, "invisible")}>
                  <KindWords kind={kind} />
                </span>
                <span
                  data-slot="expanding-button-kind"
                  data-chosen={isChosen || undefined}
                  className="absolute inset-x-0 top-0 flex justify-center"
                  style={{ translate: shown ? `${move}px 0` : `${move}px calc(100% + 8px)`, opacity: shown ? 1 : 0, "--ns-kind-delay": `${delay}ms` } as React.CSSProperties}
                >
                  <Kind
                    kind={kind}
                    chosen={isChosen}
                    less={less}
                    tabIndex={open && chosen === null ? 0 : -1}
                    onClick={() => {
                      if (!open || chosen !== null) return;
                      onFeedback?.("press");
                      kind.onClick?.();
                      onPick?.(kind.id);
                      setChosen(i);
                    }}
                  />
                </span>
              </span>
            );
          })}
        </div>
      </div>
      <span className="sr-only" aria-live="polite">
        {chosen !== null ? kinds[chosen]?.doneLabel : ""}
      </span>
    </div>
  );
}

export { ExpandingButton, TaskMark, type ExpandingButtonProps, type ExpandingKind };
```

### lib/notchset/button-class.ts

```tsx
// Notchset expanding-button 1.1.0 · https://notchset.dev/changelog
import { cn } from "@/lib/utils";
import { HIT_AREA } from "@/lib/notchset/hit-area";

/*
 * Button's look as classes, shared without the component; QUIET_PILL is its ghost, small form for a link or plain button
 * that isn't a Button, so every quiet pill has one height (28px, 36px on touch), corner, padding, weight and colour.
 * On touch each hit area is at least --ns-hit (44px) through HIT_AREA. Elements drawn with these carry data-ns-press="".
 */

export const buttonBase = cn(
  "relative inline-flex shrink-0 cursor-pointer items-center justify-center gap-1.5 whitespace-nowrap select-none font-[family-name:var(--ns-font-body)] font-[number:var(--ns-weight-medium)] leading-none tracking-[var(--ns-tracking-control)] outline-hidden [-webkit-tap-highlight-color:transparent] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--ns-signal)] disabled:cursor-default disabled:opacity-45 aria-disabled:cursor-default aria-disabled:opacity-45 aria-busy:cursor-progress data-[state=done]:disabled:opacity-100! data-[state=done]:aria-disabled:opacity-100! [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-[var(--ns-button-icon,var(--ns-icon))]",
  HIT_AREA,
);

/* the primary is the ink button (near-white at night) with its own hover and press roles; the Signature never fills a button */
export const buttonIntents = {
  secondary:
    "bg-[var(--ns-raised)] text-[var(--ns-ink)] shadow-[var(--ns-btn-bezel)] data-popup-open:bg-[var(--ns-hover)] data-popup-open:shadow-[var(--ns-btn-bezel)] hover:not-disabled:not-aria-disabled:bg-[var(--ns-hover)] hover:not-disabled:not-aria-disabled:shadow-[var(--ns-btn-bezel),inset_0_0_0_1px_color-mix(in_oklab,var(--ns-ink)_8%,transparent)]",
  primary:
    "bg-[var(--primary)] text-[var(--primary-foreground)] shadow-[var(--ns-lift)] hover:not-disabled:not-aria-disabled:bg-[var(--ns-primary-hover)] not-disabled:not-aria-disabled:active:bg-[var(--ns-primary-press)]",
  ghost: "bg-transparent text-[var(--ns-ink-3)] data-popup-open:bg-[var(--ns-hover)] data-popup-open:text-[var(--ns-ink)] hover:not-disabled:not-aria-disabled:bg-[var(--ns-hover)] hover:not-disabled:not-aria-disabled:text-[var(--ns-ink)]",
  /* Ink: danger rests quiet, rose words on the raised surface; its hover is the family's one rose
     tint (--ns-btn-bad-hover), the same on every delete; from press to done and through its Undo a delete keeps the rose glass (--ns-btn-bad, foundation.css), never white */
  danger: "bg-[var(--ns-raised)] text-[var(--ns-bad-ink)] shadow-[var(--ns-btn-bezel)] data-popup-open:bg-[var(--ns-btn-bad-hover)] hover:not-disabled:not-aria-disabled:bg-[var(--ns-btn-bad-hover)]",
  /* the icon button at rest: ink at 6%, 10% on hover */
  tonal: "bg-[var(--ns-btn-tonal)] text-[var(--ns-ink)] shadow-[var(--ns-btn-tonal-edge)] data-popup-open:bg-[var(--ns-btn-tonal-hover)] hover:not-disabled:not-aria-disabled:bg-[var(--ns-btn-tonal-hover)]",
} as const;

/* Ink's heights 30 / 36 / 44 and corners 9 / 10 / 12; padding sm 12, md 14, lg 20; label 14/500, icons 16 at a 1.75
   stroke; gap 8 (sm 6). Touch screens take the family's finger sizes (foundation.css). */
export const buttonSizes = {
  md: "min-h-[var(--ns-button)] h-[var(--ns-button)] rounded-[var(--ns-radius-button)] px-3.5 gap-2 text-[length:var(--ns-text-control)] [&_svg]:stroke-[1.75]",
  sm: "min-h-[var(--ns-button-sm)] h-[var(--ns-button-sm)] rounded-[var(--ns-radius-button-sm)] px-3 gap-1.5 text-[length:var(--ns-text-small)] [&_svg]:stroke-[1.75]",
  lg: "min-h-[var(--ns-button-lg)] h-[var(--ns-button-lg)] rounded-[var(--ns-radius-button-lg)] px-5 gap-2 text-[length:var(--ns-text-control-lg)] [&_svg]:stroke-[1.75]",
} as const;

export const buttonSquare = { md: "w-[var(--ns-button)] min-w-[var(--ns-button)] px-0", sm: "w-[var(--ns-button-sm)] min-w-[var(--ns-button-sm)] px-0", lg: "w-[var(--ns-button-lg)] min-w-[var(--ns-button-lg)] px-0" } as const;

/* The family's result tones, as the button takes them by its data-state: done is green (a delete's stays rose glass), a
   failure the rose tint with rose words and a rose edge; a two-step confirm's armed step is solid rose with white words,
   so armed never shares a tone with a failure or the result. Important, so no intent's hover outranks them. */
export const buttonResults = cn(
  "data-[state=done]:bg-[var(--ns-btn-ok)]! data-[state=done]:text-white! data-[state=done]:shadow-none!",
  "data-[intent=danger]:data-[state=done]:bg-[var(--ns-btn-bad)]! data-[intent=danger]:data-[state=done]:text-[var(--ns-bad-ink)]! data-[intent=danger]:data-[state=done]:shadow-[inset_0_0_0_1px_var(--ns-btn-bad-line)]!",
  "data-[state=armed]:bg-[var(--ns-btn-gone)]! data-[state=armed]:text-white! data-[state=armed]:shadow-none!",
  "data-[state=failed]:bg-[var(--ns-btn-bad)]! data-[state=failed]:text-[var(--ns-bad-ink)]! data-[state=failed]:shadow-[inset_0_0_0_1px_var(--ns-btn-bad-line)]!",
);

/** The one quiet pill: Button's ghost at its small size, for an anchor or a bare button. */
export const QUIET_PILL = cn(buttonBase, buttonSizes.sm, buttonIntents.ghost, "no-underline");
```

### lib/notchset/button-look.ts

```tsx
// Notchset expanding-button 1.1.0 · https://notchset.dev/changelog
import * as React from "react";
import { cn } from "@/lib/utils";

/*
 * Button's look, whole: its classes (button-class.ts), its marks below and its moves (button-move.ts). A piece that
 * needs only one of them imports that file, so its install stays small; this one keeps every name where it was.
 */
export { buttonBase, buttonIntents, buttonResults, buttonSizes, buttonSquare, QUIET_PILL } from "@/lib/notchset/button-class";
export { buttonRollLayer, ButtonRoll, play, useButtonRoll, type ButtonRollState } from "@/lib/notchset/button-move";

/* ───── the family's atoms: every button-family piece draws its marks from these, never a second drawing ───── */

const h = React.createElement;

/** The drawn tick: a 16px check that draws itself once (--ns-btn-tick); success is the ok tone and this. */
export function ButtonTick({ className }: { className?: string | undefined }) {
  return h("svg", { "aria-hidden": true, "data-ns-tick": "", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: 1.9, strokeLinecap: "round", strokeLinejoin: "round", className },
    h("path", { d: "M3.5 8.6 6.6 11.6 12.6 4.6", pathLength: 1 }));
}

/** The paper plane (a send): leans on hover, launches up and right with two swoosh lines as its button goes busy, and
 *  boomerangs home when the send failed. Pass it as the button's leading icon. */
export function ButtonPlane() {
  return h("span", { "aria-hidden": true, "data-ns-plane": "", className: "size-4" },
    h("span", { "data-ns-streak": "", style: { translate: "-2px 2px" } }),
    h("span", { "data-ns-streak": "", style: { translate: "3px 5px", width: 20 } }),
    h("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeLinecap: "round", strokeLinejoin: "round", className: "size-4" },
      h("path", { d: "M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z" }),
      h("path", { d: "m21.854 2.147-10.94 10.939" })));
}

/** The bin (every delete): its lid lifts on hover, opens with a wobble ("open"), drops shut past level ("shut");
 *  `tilt` lifts it by degrees (a countdown's beats); `check` fades its bars and draws a tick inside: deleted. */
export function ButtonBin({ lid = "rest", tilt, check }: { lid?: "rest" | "open" | "shut" | undefined; tilt?: number | undefined; check?: boolean | undefined }) {
  return h("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true, "data-ns-bin": "", "data-lid": lid, "data-check": check || undefined, "data-ns-tilt": tilt !== undefined || undefined, style: tilt !== undefined ? ({ "--ns-bin-tilt": tilt } as React.CSSProperties) : undefined },
    h("g", { "data-ns-lid": "" }, h("path", { d: "M3 6h18" }), h("path", { d: "M8 6V4.5A1.5 1.5 0 0 1 9.5 3h5A1.5 1.5 0 0 1 16 4.5V6" })),
    h("path", { d: "M5 6l1 13.5A2 2 0 0 0 8 21.5h8a2 2 0 0 0 2-2L19 6" }),
    h("path", { "data-ns-bars": "", d: "M10 11v6M14 11v6" }),
    check ? h("path", { "data-ns-bintick": "", pathLength: 1, d: "M9 14.4l2.2 2.2 4-4.6" }) : null);
}

const EDGE_ANGLES = [-160, -122, -90, -58, -20];
/** A success's sparks: five 4px dots leave the button's outline and drift 11px outward once (not on a delete: a
 *  deletion is done, not celebrated). Place inside the button; it reads the button's box, so it follows its width. */
export function EdgeBurst() {
  return h("span", { "aria-hidden": true, "data-slot": "button-burst", className: "pointer-events-none absolute inset-0 z-10" },
    EDGE_ANGLES.map((deg) => {
      const r = (deg * Math.PI) / 180;
      const x = Math.cos(r);
      const y = Math.sin(r);
      return h("i", { key: deg, "data-ns-edge": "", style: { left: `calc(50% + ${x.toFixed(3)} * (50% + 5px))`, top: `calc(50% + ${y.toFixed(3)} * (50% + 5px))`, "--dx": `${(x * 11).toFixed(1)}px`, "--dy": `${(y * 11).toFixed(1)}px` } as React.CSSProperties });
    }));
}

/** The busy mark (B7): four small squares that pull in to 70% and turn a quarter as one, every 1100ms, only while
 *  busy; with less motion they stand still. It takes the icon's place and size. */
export function ButtonBusy({ className }: { className?: string | undefined }) {
  return h("span", { "aria-hidden": true, "data-slot": "button-busy", className: cn("inline-grid shrink-0 place-items-center", className), style: { width: "var(--ns-button-icon, 16px)", height: "var(--ns-button-icon, 16px)" } },
    h("svg", { viewBox: "0 0 16 16", fill: "currentColor", "data-ns-busy": "", className: "size-full overflow-visible" },
      [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([dx, dy], i) =>
        h("rect", { key: i, x: 6.2, y: 6.2, width: 3.6, height: 3.6, rx: 1, style: { "--dx": `${dx! * 3.4}px`, "--dy": `${dy! * 3.4}px`, opacity: i % 2 ? 0.72 : 1 } as React.CSSProperties }))));
}

/** A puff of small dots from one point (a slammed lid's dust, a plane bumping its slot): each leaves at its angle
 *  (degrees, 0 is right) and fades. Place it absolutely where the puff starts; `delay` in ms. */
export function ButtonPuff({ angles, distance = 10, delay = 0, color = "var(--ns-ink-4)", className, style }: { angles: number[]; distance?: number; delay?: number; color?: string; className?: string | undefined; style?: React.CSSProperties | undefined }) {
  return h("span", { "aria-hidden": true, "data-slot": "button-puff", className: cn("pointer-events-none absolute size-0", className), style },
    angles.map((deg, i) => {
      const r = (deg * Math.PI) / 180;
      const d = distance * (0.8 + ((i * 37) % 10) / 25);
      return h("i", { key: i, "data-ns-puff": "", style: { background: color, animationDelay: `${delay}ms`, "--dx": `${(Math.cos(r) * d).toFixed(1)}px`, "--dy": `${(Math.sin(r) * d).toFixed(1)}px` } as React.CSSProperties });
    }));
}

/** An even ring of sparks round a point (an upload landing): `count` dots fly from `from` to `to` px out and fade. */
export function ButtonSparks({ count = 8, from = 14, to = 26, delay = 60 }: { count?: number; from?: number; to?: number; delay?: number }) {
  return h("span", { "aria-hidden": true, "data-slot": "button-sparks", className: "pointer-events-none absolute top-1/2 start-1/2 size-0" },
    Array.from({ length: count }, (_, i) => {
      const r = (i / count) * Math.PI * 2 - Math.PI / 2;
      return h("i", { key: i, "data-ns-spark": "", style: { animationDelay: `${delay}ms`, "--x0": `${(Math.cos(r) * from).toFixed(1)}px`, "--y0": `${(Math.sin(r) * from).toFixed(1)}px`, "--x1": `${(Math.cos(r) * to).toFixed(1)}px`, "--y1": `${(Math.sin(r) * to).toFixed(1)}px` } as React.CSSProperties });
    }));
}
```

### lib/notchset/button-move.ts

```tsx
// Notchset expanding-button 1.1.0 · https://notchset.dev/changelog
import * as React from "react";
import { cn } from "@/lib/utils";

/* Button's body moves (play) and its rolling cell (ButtonRoll), shared without the component or its marks. */
const h = React.createElement;

const lessNow = () =>
  typeof window !== "undefined" &&
  (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches || !!document.documentElement.closest?.('[data-motion="reduced"], [data-motion="off"]'));

/** The action button's body moves (B7): squash (the beat before every act), settle (letting go of it), hop (sent),
 *  no (a head shake: not sent), land (a result arriving in place), thud (a lid slammed shut). */
type ButtonMove = "squash" | "settle" | "hop" | "no" | "land" | "thud";
const MOVES: Record<ButtonMove, [Keyframe[], KeyframeAnimationOptions]> = {
  squash: [[{ scale: "1 1" }, { scale: "1.06 .86", offset: 0.55 }, { scale: "1.06 .86" }], { duration: 110, easing: "cubic-bezier(.2,0,0,1)" }],
  settle: [[{ scale: "1.06 .86" }, { scale: ".98 1.03", offset: 0.45 }, { scale: "1 1" }], { duration: 380, easing: "cubic-bezier(.2,.8,.3,1)" }],
  hop: [[{ scale: "1 1", translate: "0 0" }, { scale: "1.04 .92", translate: "0 1px", offset: 0.14 }, { scale: ".97 1.05", translate: "0 -6px", offset: 0.42 }, { scale: "1.03 .96", translate: "0 0", offset: 0.7 }, { scale: "1 1", translate: "0 0" }], { duration: 520, easing: "cubic-bezier(.3,.7,.4,1)" }],
  no: [[{ translate: "0", rotate: "0deg" }, { translate: "-6px", rotate: "-1.6deg", offset: 0.16 }, { translate: "5px", rotate: "1.2deg", offset: 0.36 }, { translate: "-3px", rotate: "-.7deg", offset: 0.56 }, { translate: "1.5px", rotate: ".3deg", offset: 0.76 }, { translate: "0", rotate: "0deg" }], { duration: 520, easing: "ease-out" }],
  land: [[{ scale: "1 1" }, { scale: "1.03 .94", offset: 0.3 }, { scale: ".995 1.012", offset: 0.65 }, { scale: "1 1" }], { duration: 420, easing: "cubic-bezier(.3,.7,.4,1)" }],
  thud: [[{ translate: "0 0" }, { translate: "0 2px", scale: "1.012 .97", offset: 0.25 }, { translate: "0 0", scale: "1 1" }], { duration: 300, easing: "cubic-bezier(.2,0,0,1)" }],
};

/** One-shot reactions to the hand, on the element itself through the Web Animations API, so a press is never cut:
 *  sigh (a 1.5px drop, a cancel), bump (a failure's knock), shake (a refused press), plus (a pop), nudge (a step on). */
export function play(el: Element | null | undefined, kind: "sigh" | "bump" | "shake" | "plus" | "nudge" | ButtonMove) {
  if (!el || typeof el.animate !== "function" || lessNow()) return;
  const k: Record<typeof kind, [Keyframe[], KeyframeAnimationOptions]> = {
    sigh: [[{ translate: "0 0" }, { translate: "0 1.5px", offset: 0.3 }, { translate: "0 0" }], { duration: 420, easing: "cubic-bezier(.2,0,0,1)" }],
    bump: [[{ translate: "0" }, { translate: "-2px", offset: 0.3 }, { translate: "1px", offset: 0.65 }, { translate: "0" }], { duration: 320, easing: "cubic-bezier(.2,0,0,1)" }],
    shake: [[{ translate: "0" }, { translate: "-2px" }, { translate: "2px" }, { translate: "-1.5px" }, { translate: "1px" }, { translate: "0" }], { duration: 380, easing: "ease-out" }],
    plus: [[{ scale: 1 }, { scale: 1.3, offset: 0.35 }, { scale: 1 }], { duration: 300, easing: "cubic-bezier(.2,0,0,1)" }],
    nudge: [[{ translate: "0" }, { translate: "5px", offset: 0.35 }, { translate: "0" }], { duration: 340, easing: "cubic-bezier(.2,0,0,1)" }],
    ...MOVES,
  };
  const [frames, opts] = k[kind];
  el.animate(frames, opts);
}

/* ───── the roll (Ink's move): a changing label's forms share one cell; the one on shows, the one it replaced rolls up
   and out, the rest wait below unseen. With less motion nothing travels: the two crossfade. ───── */

export type ButtonRollState = "on" | "out" | "wait";

/** The classes of one form in a rolling cell, by its state. */
export const buttonRollLayer = (state: ButtonRollState, less: boolean) =>
  cn(
    "col-start-1 row-start-1 inline-flex min-w-0 max-w-full items-center justify-center gap-[inherit]",
    state === "wait" ? "transition-none" : "[transition:translate_var(--ns-btn-roll)_var(--ns-ease-move),opacity_var(--ns-btn-roll)_var(--ns-ease-move)]",
    state === "on" ? "translate-y-0 opacity-100" : cn("pointer-events-none opacity-0", !less && (state === "out" ? "-translate-y-[105%]" : "translate-y-[105%]")),
  );

/** Which form is on, and the one it replaced, so only that one rolls out. */
export function useButtonRoll(phase: string) {
  const [s, setS] = React.useState<{ cur: string; prev: string | null }>({ cur: phase, prev: null });
  if (s.cur !== phase) setS({ cur: phase, prev: s.cur });
  return (key: string): ButtonRollState => (key === phase ? "on" : key === s.prev ? "out" : "wait");
}

/** A roll for any words or number that change outside a Button's own states (a day, a stage, a count, a toolbar
 *  action's Assigned): when `k` changes the old content leaves and the new arrives through a masked cell, and the cell's
 *  width eases between the two. `way` "up" (the default) rolls the new in from below; "down" from above (a count going
 *  down). Less motion crossfades (foundation.css). */
export function ButtonRoll({ k, way = "up", className, children }: { k: string; way?: "up" | "down" | undefined; className?: string | undefined; children: React.ReactNode }) {
  const [s, setS] = React.useState<{ k: string; node: React.ReactNode; out: { k: string; node: React.ReactNode; way: "up" | "down" } | null }>({ k, node: children, out: null });
  if (s.k !== k) setS({ k, node: children, out: { k: s.k, node: s.node, way } });
  else if (s.node !== children) setS({ ...s, node: children });
  /* each new content measures itself as it mounts, so the cell eases from the old width to its own */
  const [w, setW] = React.useState<number>();
  const cur = React.useCallback((el: HTMLSpanElement | null) => void (el && setW(el.offsetWidth)), []);
  const leaving = s.out?.k;
  React.useEffect(() => {
    if (leaving === undefined) return;
    const t = setTimeout(() => setS((p) => (p.out?.k === leaving ? { ...p, out: null } : p)), 320);
    return () => clearTimeout(t);
  }, [leaving]);
  return h("span", { "data-ns-rollcell": "", className, style: w === undefined ? undefined : { width: w } },
    s.out ? h("span", { key: `o-${s.out.k}`, "aria-hidden": true, "data-ns-roll-out": s.out.way }, s.out.node) : null,
    h("span", { key: `c-${s.k}`, ref: cur, "data-ns-roll-in": s.out ? s.out.way : undefined }, s.node));
}
```

### lib/notchset/feedback.ts

```tsx
// Notchset expanding-button 1.1.0 · https://notchset.dev/changelog
export type FeedbackEvent = "press" | "toggle-on" | "toggle-off" | "open" | "close" | "select" | "success" | "error" | "add" | "remove" | "send";
export type FeedbackProps = {
  /** called once per move, for your sound or haptics */
  onFeedback?: ((e: FeedbackEvent) => void) | undefined;
};
```

### lib/notchset/hit-area.ts

```tsx
// Notchset expanding-button 1.1.0 · https://notchset.dev/changelog
/** Press area round the control (a centred ::after): --ns-press-min on every pointer, --ns-hit on touch. The identity
 * transform keeps the control its containing block. */
export const HIT_AREA =
  "[transform:translate(0)] after:absolute after:inset-[min(0px,calc(50%_-_var(--ns-press-min)/2))] after:content-['']";
```

### lib/notchset/icons.ts

```tsx
// Notchset expanding-button 1.1.0 · https://notchset.dev/changelog
/** Every piece imports its icons from here: swap the icon set in this one file. */
export * from "lucide-react";
```

### lib/notchset/motion.ts

```tsx
// Notchset expanding-button 1.1.0 · https://notchset.dev/changelog
"use client";
/*
 * Less motion, the one switch every piece reads, and a motion role's timing for a Web Animation. Split from
 * physics.ts so a piece that needs only these does not carry the springs.
 */
import * as React from "react";

/**
 * Less motion where `el` sits: the device's setting, then a data-motion="reduced" on `el` or any ancestor, falling
 * back to <html>'s when there is no element. The one copy: every piece reads this.
 */
const REDUCED = '[data-motion="reduced"],[data-motion="off"]';
export function lessMotion(el?: Element | null): boolean {
  if (typeof document === "undefined") return true;
  if (typeof matchMedia !== "undefined" && matchMedia("(prefers-reduced-motion: reduce)").matches) return true;
  return !!(el?.closest?.(REDUCED) ?? document.documentElement.matches(REDUCED));
}

/** Less motion, kept current as the setting changes; true on a server, so a piece starts in its still. */
export function useLessMotion(): boolean {
  return React.useSyncExternalStore(
    (f) => {
      if (typeof matchMedia === "undefined") return () => {};
      const q = matchMedia("(prefers-reduced-motion: reduce)");
      q.addEventListener("change", f);
      const mo = typeof MutationObserver === "undefined" ? null : new MutationObserver(f);
      mo?.observe(document.documentElement, { attributes: true, attributeFilter: ["data-motion"] });
      return () => {
        q.removeEventListener("change", f);
        mo?.disconnect();
      };
    },
    () => lessMotion(),
    () => true,
  );
}

/** A motion role's duration and curve (0 under less motion: the result at once), read from the foundation where `el` sits, for a Web Animation that glides
    something CSS can't transition (a width to `auto`, a node on its way out): `roleTiming(el, "--ns-time-menu")`. */
export function roleTiming(el: Element, time: string, ease = "--ns-ease"): KeyframeAnimationOptions {
  if (lessMotion(el)) return { duration: 0, easing: "linear" };
  const cs = getComputedStyle(el);
  const t = cs.getPropertyValue(time).trim();
  const ms = t.endsWith("ms") ? parseFloat(t) : parseFloat(t) * 1000;
  return { duration: Number.isFinite(ms) ? ms : 0, easing: cs.getPropertyValue(ease).trim() || "linear" };
}

/** The foundation's curves as literal strings, for a Web Animation (`element.animate`, `KeyframeEffect`,
    `updateTiming`): those take a literal easing and throw on a CSS var. Copied from foundation.css's `--ns-ease-*`;
    CSS transitions and keyframes keep the vars. */
export const EASE = {
  enter: "cubic-bezier(0.22, 1, 0.36, 1)",
  move: "cubic-bezier(.5, 0, .2, 1)",
  exit: "cubic-bezier(.6, 0, .9, .5)",
  panel: "cubic-bezier(0.32, 0.72, 0, 1)",
  press: "cubic-bezier(0.2, 0, 0, 1)",
  spring: "cubic-bezier(0.16, 1, 0.3, 1)",
  arrive: "cubic-bezier(.3, 1.22, .5, 1)",
  breathe: "cubic-bezier(.45, 0, .55, 1)",
} as const;
```

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