# Reason popover (Notchset): prompt.md (v2.0.0)

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

A step that needs one line of why before it runs (deny, decline, pause), asked right where it was pressed. Enter runs it; an empty reason says what to write. For steps Undo can take back; an irreversible one is a Dialog..

## 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: `@base-ui/react@^1`.
- Files: `components/ui/notchset/reason-popover.tsx`; shared code: `lib/notchset/popup.ts`, `lib/notchset/portal.ts`, `lib/notchset/return-focus.ts`.
- Registry dependencies, installed with it automatically: shadcn `utils` (cn), `notchset-foundation`, `button`, `text-field`.
- Builds: one set of files, the same for every shadcn style.
- Exports to keep: `ReasonPopover`, 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-ease`, `--ns-ease-panel`, `--ns-hover`, `--ns-ink`, `--ns-ink-3`, `--ns-line`, `--ns-menu-row`, `--ns-radius-lg`, `--ns-radius-xl`, `--ns-raised`, `--ns-shadow-float`, `--ns-sheet-bottom`, `--ns-text-body`, `--ns-text-small`, `--ns-time-menu`, `--ns-time-panel`, `--ns-weight-medium`.
- Retune it (on any ancestor) with the foundation's roles and hooks: `--ns-bad`, `--ns-bad-ink`, `--ns-band`, `--ns-band-edge`, `--ns-band-grade`, `--ns-band-optimal`, `--ns-beat`, `--ns-bezel`, `--ns-canvas`, `--ns-cat-1`, `--ns-cat-2`, `--ns-cat-3`, `--ns-cat-4`, `--ns-cat-5`, `--ns-cat-6`, `--ns-check`, `--ns-chip`, `--ns-control`, `--ns-control-pad`, `--ns-control-sm`, `--ns-deep`, `--ns-deep-ink`, `--ns-deep-ink-2`, `--ns-deep-line`, `--ns-dialog`, `--ns-dialog-lg`, `--ns-dialog-sm`, `--ns-ease`, `--ns-ease-in`, `--ns-ease-panel`, `--ns-ease-pop`, `--ns-field`, `--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-grain`, `--ns-gutter`, `--ns-header`, `--ns-heat`, `--ns-hover`, `--ns-ink`, `--ns-ink-2`, `--ns-ink-3`, `--ns-ink-4`, `--ns-leading`, `--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-menu-dy`, `--ns-menu-row`, `--ns-mesh`, `--ns-mesh-frost`, `--ns-ok`, `--ns-ok-ink`, `--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-panel`, `--ns-panel-w`, `--ns-prism-edge`, `--ns-prism-glint`, `--ns-prism-sheen`, `--ns-prism-tint`, `--ns-pulse`, `--ns-radius`, `--ns-radius-card`, `--ns-radius-full`, `--ns-radius-lg`, `--ns-radius-sm`, `--ns-radius-xl`, `--ns-raised`, `--ns-range`, `--ns-row`, `--ns-row-compact`, `--ns-segment`, `--ns-selected`, `--ns-series`, `--ns-series-core`, `--ns-series-lilac`, `--ns-series-tint`, `--ns-shadow-dialog`, `--ns-shadow-float`, `--ns-shadow-panel`, `--ns-sheet`, `--ns-sheet-bottom`, `--ns-side`, `--ns-signal`, `--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-on`, `--ns-standing-critical`, `--ns-standing-in`, `--ns-standing-out`, `--ns-state-doing`, `--ns-state-done`, `--ns-state-review`, `--ns-state-todo`, `--ns-switch-h`, `--ns-switch-w`, `--ns-text-body`, `--ns-text-control`, `--ns-text-display`, `--ns-text-figure`, `--ns-text-headline`, `--ns-text-hero`, `--ns-text-lede`, `--ns-text-meta`, `--ns-text-page`, `--ns-text-record`, `--ns-text-small`, `--ns-text-strong`, `--ns-text-sub`, `--ns-text-title`, `--ns-tile-shadow`, `--ns-time-born`, `--ns-time-color`, `--ns-time-dialog`, `--ns-time-menu`, `--ns-time-page`, `--ns-time-panel`, `--ns-time-toast`, `--ns-tint`, `--ns-tint-ink`, `--ns-toast-bottom`, `--ns-toast-left`, `--ns-touch`, `--ns-tracking-display`, `--ns-tracking-headline`, `--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`.
- Never add Tailwind colour classes inside the component.

```tsx
import { Button } from "@/components/ui/notchset/button";
```

## Parts
- A single export that takes props.

## Match the original
- Read `components/ui/notchset/reason-popover.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

### Not when

## Built from
- button (`button`), installed with it: reuse it, don't rebuild it
- text-field (`text-field`), installed with it: reuse it, don't rebuild it
- Popup placement (shared helper, ships with it)
- Portal (shared helper, ships with it)
- Focus return (shared helper, ships with it)

## Mistakes
- Recreating the component instead of installing it

## Usage

```tsx
"use client";
import * as React from "react";
import { Button } from "@/components/ui/notchset/button";
import { ReasonPopover } from "@/components/ui/notchset/reason-popover";

export default function ReasonPopoverDemo() {
  const [denied, setDenied] = React.useState<string | null>(null);
  return (
    <div className="flex items-center gap-3">
      <ReasonPopover
        trigger={<Button size="sm">Deny</Button>}
        title="Why deny Q-1047?"
        label="What would you approve instead?"
        placeholder="e.g. 15% with a 2-year term"
        verb="Deny"
        align="start"
        onSubmit={(reason) => setDenied(reason)}
      />
      {denied && <span className="text-[length:var(--ns-text-small)] text-[var(--ns-ink-3)]">Denied: {denied}</span>}
    </div>
  );
}
```

## Props

| Prop | Type | Default | What it does |
|---|---|---|---|
| `trigger` | `React.ReactElement` |  | The control that opens it: one element that takes a ref. |
| `title` | `React.ReactNode` |  | The question, as a short heading ("Why deny Q-1047?"). |
| `label` | `string` |  | The field's label. |
| `placeholder` | `string` |  |  |
| `verb` | `string` |  | The verb that runs it ("Deny"). |
| `required` | `string` | `"Say why, in a few words"` | Said when the field is empty and the verb is pressed. |
| `onSubmit` | `(reason: string) => string \| null \| undefined \| void` |  | Runs the step; return an error to show (and stay open), or nothing once it ran. |
| `align` | `"start" \| "center" \| "end"` | `"end"` |  |

Full docs: https://notchset.dev/components/reason-popover

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

## Accessibility contract (preserve when editing)

## Install

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

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

## Continue the workflow

- [Bottom sheet](https://notchset.dev/components/bottom-sheet)
- [Command menu](https://notchset.dev/components/command-menu)
- [Dialog](https://notchset.dev/components/dialog)

## Source

### components/ui/notchset/reason-popover.tsx

```tsx
// Notchset reason-popover 2.0.0 · https://notchset.dev/changelog
"use client";
import * as React from "react";
import { Popover } from "@base-ui/react/popover";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/notchset/button";
import { popupPositioner, popupSurface } from "@/lib/notchset/popup";
import { useReturnFocus } from "@/lib/notchset/return-focus";
import { TextField } from "@/components/ui/notchset/text-field";
import { usePortalContainer } from "@/lib/notchset/portal";

/*
 * Reason popover: a step that needs one line of why before it runs (deny a request, decline a quote, pause an
 * account), asked right where it was pressed instead of in a dialog. The question, one field, Cancel and the verb.
 * Enter runs it; an empty reason says what to write and keeps the popover open; a refused save keeps what was
 * typed. On a phone it rises as a sheet. Focus starts in the field and returns to the trigger.
 * A red, irreversible step belongs in a Dialog; this is for steps that Undo can take back.
 */
type ReasonPopoverProps = {
  /** The control that opens it: one element that takes a ref. */
  trigger: React.ReactElement;
  /** The question, as a short heading ("Why deny Q-1047?"). */
  title: React.ReactNode;
  /** The field's label. */
  label: string;
  placeholder?: string | undefined;
  /** The verb that runs it ("Deny"). */
  verb: string;
  /** Said when the field is empty and the verb is pressed. */
  required?: string | undefined;
  /** Runs the step; return an error to show (and stay open), or nothing once it ran. */
  onSubmit: (reason: string) => string | null | undefined | void;
  align?: "start" | "center" | "end" | undefined;
  className?: string | undefined;
};

function ReasonPopover({ trigger, title, label, placeholder, verb, required = "Say why, in a few words", onSubmit, align = "end", className }: ReasonPopoverProps) {
  const portalContainer = usePortalContainer();
  const [open, setOpen] = React.useState(false);
  const returnFocus = useReturnFocus();
  return (
    <Popover.Root open={open} onOpenChange={(o) => setOpen(o)}>
      <Popover.Trigger render={trigger} />
      <Popover.Portal container={portalContainer}>
        <Popover.Positioner side="bottom" align={align} sideOffset={6} collisionPadding={8} className={popupPositioner}>
          <Popover.Popup data-slot="reason-popover" data-ns-layer="" data-ns-moves="" finalFocus={returnFocus} className={cn(popupSurface, "w-[min(320px,calc(100vw-16px))] p-3 max-[600px]:w-auto max-[600px]:px-3 max-[600px]:pt-5 max-[600px]:pb-3", className)}>
            {/* mounted only while open, so each opening starts empty */}
            {open && <ReasonForm title={title} label={label} placeholder={placeholder} verb={verb} required={required} onSubmit={onSubmit} onDone={() => setOpen(false)} />}
          </Popover.Popup>
        </Popover.Positioner>
      </Popover.Portal>
    </Popover.Root>
  );
}

function ReasonForm({ title, label, placeholder, verb, required, onSubmit, onDone }: Omit<ReasonPopoverProps, "trigger" | "align" | "className"> & { onDone: () => void }) {
  const [text, setText] = React.useState("");
  const [err, setErr] = React.useState<string | null>(null);
  const run = () => {
    if (!text.trim()) return setErr(required ?? null);
    const e = onSubmit(text.trim());
    if (e) setErr(e);
    else onDone();
  };
  return (
    <form
      noValidate
      className="flex flex-col gap-3"
      onSubmit={(e) => {
        e.preventDefault();
        run();
      }}
    >
      <Popover.Title className="m-0 text-[length:var(--ns-text-body)] font-[number:var(--ns-weight-medium)] text-[var(--ns-ink)]">{title}</Popover.Title>
      <TextField label={label} placeholder={placeholder} value={text} error={err} autoFocus onChange={(e) => (setText(e.target.value), setErr(null))} />
      <div className="flex justify-end gap-2">
        <Popover.Close render={<Button size="sm">Cancel</Button>} />
        <Button size="sm" type="submit" variant="primary">
          {verb}
        </Button>
      </div>
    </form>
  );
}

export { ReasonPopover, type ReasonPopoverProps };
```

### lib/notchset/popup.ts

```tsx
// Notchset reason-popover 2.0.0 · https://notchset.dev/changelog
/*
 * The one popup surface every list that opens from a control uses (select, combobox, recipient picker, and
 * menus in batch 3): the prototype's .menu. It drops just below its control, and on a phone it becomes a
 * bottom sheet with a grab handle and finger-sized rows. Kept as class strings so each primitive's own parts
 * wear the same look.
 */

/** On the Positioner: above everything but dialogs; on a phone, pinned to the bottom edge as a sheet (above a tab bar
    when the app sets --ns-sheet-bottom to its height). */
export const popupPositioner =
  "z-50 outline-hidden max-[600px]:!fixed max-[600px]:!inset-x-2 max-[600px]:!top-auto max-[600px]:!bottom-[calc(var(--ns-sheet-bottom)+env(safe-area-inset-bottom,0px))] max-[600px]:!left-2 max-[600px]:!w-auto max-[600px]:!transform-none";

/** On the Popup. */
export const popupSurface =
  "min-w-[max(var(--anchor-width,0px),180px)] max-h-[min(420px,70vh,var(--available-height,70vh))] overflow-auto overscroll-contain rounded-[var(--ns-radius-lg)] bg-[var(--ns-raised)] p-[5px] text-[length:var(--ns-text-body)] text-[var(--ns-ink)] shadow-[0_0_0_1px_var(--ns-line),var(--ns-shadow-float)] outline-hidden origin-[var(--transform-origin)] " +
  "[animation:ns-menu-in_var(--ns-time-menu)_var(--ns-ease)] data-ending-style:opacity-0 data-ending-style:[transition:opacity_110ms_ease] " +
  "max-[600px]:w-auto max-[600px]:min-w-0 max-[600px]:max-h-[70dvh] max-[600px]:rounded-[var(--ns-radius-xl)] max-[600px]:px-1.5 max-[600px]:pt-3.5 max-[600px]:pb-1.5 max-[600px]:[animation:ns-sheet-up_var(--ns-time-panel)_var(--ns-ease-panel)] " +
  "max-[600px]:before:absolute max-[600px]:before:top-[5px] max-[600px]:before:left-1/2 max-[600px]:before:h-1 max-[600px]:before:w-9 max-[600px]:before:-translate-x-1/2 max-[600px]:before:rounded-full max-[600px]:before:bg-[var(--ns-line)] max-[600px]:before:content-['']";

/** On each item. Highlight (pointer or arrow keys) is the hover wash; the chosen item carries a check. */
export const popupItem =
  "flex w-full min-h-[var(--ns-menu-row)] cursor-default items-center gap-[9px] rounded-[7px] px-[9px] text-left outline-hidden select-none data-highlighted:bg-[var(--ns-hover)] data-disabled:opacity-45 [&_svg:not([data-slot=company-mark])]:size-3.5 [&_svg]:shrink-0";

/** The quiet line a list shows when nothing matches. */
export const popupEmpty = "px-[9px] py-2 text-[length:var(--ns-text-small)] text-[var(--ns-ink-3)] empty:hidden";
```

### lib/notchset/portal.ts

```tsx
// Notchset reason-popover 2.0.0 · https://notchset.dev/changelog
import * as React from "react";

/*
 * Where overlays (dialogs, menus, popovers, tooltips, toasts, sheets) portal to. By default the document body; a
 * host that themes or scopes a region (a preview stage, a shadow root, a tile in another theme) wraps it in
 * PortalContainer with an element inside that scope, so its overlays keep the region's roles and light or dark.
 */
const PortalContainerContext = React.createContext<HTMLElement | null>(null);

const PortalContainer = PortalContainerContext.Provider;

/** The element overlays portal into here, or undefined for the document body. */
function usePortalContainer(): HTMLElement | undefined {
  return React.useContext(PortalContainerContext) ?? undefined;
}

export { PortalContainer, PortalContainerContext, usePortalContainer };
```

### lib/notchset/return-focus.ts

```tsx
// Notchset reason-popover 2.0.0 · https://notchset.dev/changelog
"use client";
import * as React from "react";

/*
 * Focus goes back to whatever opened a layer when it closes, even when the layer is opened from state (a menu
 * item, a shortcut, a row) rather than its own trigger. One document listener remembers the last control
 * focused or pressed outside any layer (marked data-ns-layer); pressing counts too because Safari does not focus
 * a clicked button. Pass the result to a Base UI Popup's finalFocus.
 */
let last: HTMLElement | null = null;
let watching = false;

function watch() {
  if (watching || typeof document === "undefined") return;
  watching = true;
  const note = (e: Event) => {
    const t = e.target as HTMLElement | null;
    if (!t?.closest || t.closest("[data-ns-layer]")) return;
    /* a table row that opens on press is its own opener: it takes focus back (as a J/K row does), so closing
       what it opened never leaves focus on the page's body, where the next Tab can leave the app */
    const row = t.closest<HTMLElement>("tr[data-row]");
    const ctl = t.closest<HTMLElement>("button,a[href],input,select,textarea,[tabindex]");
    if (row && (!ctl || !row.contains(ctl)) && !row.hasAttribute("tabindex")) row.tabIndex = -1;
    last = (row && (!ctl || !row.contains(ctl)) ? row : ctl) ?? last;
  };
  document.addEventListener("focusin", note, true);
  document.addEventListener("pointerdown", note, true);
}

export function useReturnFocus() {
  React.useEffect(watch, []);
  return React.useCallback(() => (last && last.isConnected ? last : true), []);
}
```

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.
