---
title: UI kit - Overlays
summary: The @spacemix/ui floating layers - Tooltip, Popover, HoverCard, DropdownMenu, Dialog, Drawer, Gallery and Lightbox, CommandMenu and CommandDialog - and the floating helpers useFloating, computePosition, Portal, PortalContainer and useDismiss, with their props, focus handling and keyboard behaviour.
audience: both
stability: experimental
since: protocol 1
---

# Overlays

Layers that float over the page: tooltips, popovers, menus, dialogs, drawers, an image viewer and a command palette, plus the helpers they are built on, for a floating layer of your own. Source: `packages/ui/src/popovers.tsx`, `packages/ui/src/floating.ts` and `packages/ui/src/host.ts`. [`ConfirmDialog`](../ui.md#confirmdialog) and [`ContextMenu`](../ui.md#contextmenu-menuentry-menuanchor-anchorfrom) are on the kit's main page; the dropdown and date controls are in [Pickers](pickers.md).

Every layer renders through `Portal`, so no scroll area or `overflow-hidden` parent clips it, stays inside the window (flipping and shifting), and closes through the [dismiss stack](../ui.md#escape-and-the-dismiss-stack): Escape closes only the newest layer. Menus and popovers sit at z-index 70, dialogs and drawers at 60, so a popover opened from a dialog is above it. The [conventions](../ui.md#conventions) apply.

**Stability:** experimental, every export on this page: new in this release, and names and props may still be adjusted before they are promised.

## Triggers

```ts
type TriggerElement = ReactElement<HTMLAttributes<HTMLElement> & { ref?: Ref<HTMLElement> }>;
interface OverlayApi { close: () => void }
```

A `trigger` is one element that passes `ref`, event handlers and `aria-*` on to a DOM node: a `Button`, a `<button>`, or a `Tooltip` around one. The layer clones it with its own props; the trigger's own handlers run first and can call `preventDefault()` to stop the layer's. Because `Tooltip` passes its props on too, a button can have a tooltip and open a popover or menu at once.

`OverlayApi` is what a `Popover`, `Dialog` or `Drawer` hands a function child (or `footer`), so content can close it: `{({ close }) => <Button onClick={close}>Done</Button>}`.

## `Tooltip`

A short label that appears on hover (after a delay) and on keyboard focus, and hides on Escape, a press or the pointer leaving. The other props and `ref` go to the trigger. Phones have no hover: don't put anything only a tooltip says, and for links or buttons use `HoverCard` or `Popover`.

| Prop | Type | Default | What it does |
|---|---|---|---|
| `content` | `ReactNode` | required | What it says. Keep it short. |
| `children` | `TriggerElement` | required | The trigger. |
| `side` | `Side` | `"top"` | Which side it opens on. |
| `align` | `Align` | `"center"` | Where along that side. |
| `offset` | `number` | `6` | Gap to the trigger, in px. |
| `delay` | `number` | `500` | Wait before showing on hover, in ms; skipped right after another tooltip closed. |
| `closeDelay` | `number` | `100` | Wait before hiding after the pointer leaves, in ms. |
| `open`, `defaultOpen`, `onOpenChange` | `boolean`, `boolean`, `(open: boolean) => void` | `defaultOpen` `false` | The open state. |
| `disabled` | `boolean` | none | Never shows; the trigger still renders. |
| `className` | `string` | none | Classes for the bubble. |

`TooltipProps` is the props type.

## `Popover`

A panel of anything (a form, filters, details) that opens from a trigger on click. Focus moves in when it opens and back to the trigger on Escape; a press outside or focus leaving closes it.

| Prop | Type | Default | What it does |
|---|---|---|---|
| `trigger` | `TriggerElement` | required | What opens it on click. |
| `children` | `ReactNode \| ((api: OverlayApi) => ReactNode)` | required | The content; a function gets `{ close }`. |
| `open`, `defaultOpen`, `onOpenChange` | `boolean`, `boolean`, `(open: boolean) => void` | `defaultOpen` `false` | The open state. |
| `side` | `Side` | `"bottom"` | Which side it opens on. |
| `align` | `Align` | `"start"` | Where along that side. |
| `offset` | `number` | `6` | Gap to the trigger, in px. |
| `initialFocus` | `RefObject<HTMLElement \| null> \| false` | the first focusable element, else the panel | What gets focus on open; `false` leaves focus on the trigger. |
| `className` | `string` | none | Classes for the panel; the default width is `w-72`. |

`ref` goes to the panel's positioned element. `PopoverProps` is the props type.

## `HoverCard`

A preview card that opens while the pointer rests on a trigger (or the trigger has keyboard focus) and stays open while the pointer is on the card; it may hold links and buttons. Extra detail only: phones have no hover, so the trigger must work on its own (a link that opens the full page).

| Prop | Type | Default | What it does |
|---|---|---|---|
| `trigger` | `TriggerElement` | required | The element it previews, usually a link or a name. |
| `children` | `ReactNode` | required | The card. |
| `open`, `defaultOpen`, `onOpenChange` | `boolean`, `boolean`, `(open: boolean) => void` | `defaultOpen` `false` | The open state. |
| `side` | `Side` | `"bottom"` | Which side it opens on. |
| `align` | `Align` | `"start"` | Where along that side. |
| `offset` | `number` | `6` | Gap to the trigger, in px. |
| `openDelay` | `number` | `600` | Wait before showing, in ms. |
| `closeDelay` | `number` | `200` | Wait before hiding once the pointer leaves the trigger and the card, in ms. |
| `className` | `string` | none | Classes for the card; the default width is `w-72`. |

`HoverCardProps` is the props type.

## `DropdownMenu`

A menu that opens from a button: actions with icons, shortcuts and descriptions, checkbox and radio rows, submenus, labels, separators and destructive rows. Actions close the menu; checkboxes and radios leave it open so several can be changed. The keyboard follows the WAI-ARIA menu button pattern: Enter, Space or the arrows open it, the arrows move, Right and Left open and close submenus, typing jumps to a row, Escape closes one level.

```ts
interface DropdownMenuRadioOption { value: string; label: string; icon?: ReactNode; shortcut?: string; disabled?: boolean }

type DropdownMenuItem =
  | { kind?: "item"; label: string; icon?: ReactNode; shortcut?: string; description?: string; onSelect: () => void; danger?: boolean; disabled?: boolean }
  | { kind: "checkbox"; label: string; icon?: ReactNode; shortcut?: string; checked: boolean; onChange: (checked: boolean) => void; disabled?: boolean }
  | { kind: "radio-group"; label?: string; value: string; onChange: (value: string) => void; options: DropdownMenuRadioOption[] }
  | { kind: "submenu"; label: string; icon?: ReactNode; items: DropdownMenuItem[]; disabled?: boolean }
  | { kind: "separator" }
  | { kind: "label"; label: string };
```

| Prop | Type | Default | What it does |
|---|---|---|---|
| `trigger` | `TriggerElement` | required | What opens it. |
| `items` | `DropdownMenuItem[]` | required | The rows, top to bottom. |
| `open`, `defaultOpen`, `onOpenChange` | `boolean`, `boolean`, `(open: boolean) => void` | `defaultOpen` `false` | The open state. |
| `side` | `Side` | `"bottom"` | Which side it opens on. |
| `align` | `Align` | `"start"` | Where along that side. |
| `offset` | `number` | `4` | Gap to the trigger, in px. |
| `aria-label` | `string` | none | The menu's accessible name when the trigger's text doesn't say it. |
| `className` | `string` | none | Classes for the menu panel. |

```tsx
<DropdownMenu
  trigger={<IconButton aria-label="More"><Ellipsis /></IconButton>}
  items={[
    { label: "Rename", icon: <Pencil />, onSelect: rename },
    { kind: "checkbox", label: "Pinned", checked: pinned, onChange: setPinned },
    { kind: "separator" },
    { label: "Delete", danger: true, onSelect: remove },
  ]}
/>
```

`ref` goes to the menu's positioned element. `DropdownMenuProps` is the props type. For a menu at the pointer, use [`ContextMenu`](../ui.md#contextmenu-menuentry-menuanchor-anchorfrom).

## `Dialog`, `Drawer`

`Dialog` is a modal window with a title, an optional description, a scrolling body and a footer; on phones it rises from the bottom at full width. `Drawer` is a panel that slides in from an edge over the page, for details, filters or an edit form beside a list; on phones it is a bottom sheet that can be dragged down by its handle to close.

Both are modal: focus moves in, Tab stays inside, Escape and a press on the backdrop close them (unless `dismissible` is `false`), focus goes back to where it was, and the page behind doesn't scroll. The title is the accessible name and the description the accessible description.

They share these props:

| Prop | Type | Default | What it does |
|---|---|---|---|
| `open`, `defaultOpen`, `onOpenChange` | `boolean`, `boolean`, `(open: boolean) => void` | `defaultOpen` `false` | The open state. |
| `trigger` | `TriggerElement` | none | An element that opens it on click, for the uncontrolled case. |
| `title` | `ReactNode` | required | The heading. |
| `description` | `ReactNode` | none | A line under the title. |
| `children` | `ReactNode \| ((api: OverlayApi) => ReactNode)` | none | The body, which scrolls when it is tall. |
| `footer` | `ReactNode \| ((api: OverlayApi) => ReactNode)` | none | Buttons along the bottom, primary last. |
| `dismissible` | `boolean` | `true` | Escape and the backdrop close it; `false` for a step the person must finish or cancel with a button. |
| `showClose` | `boolean` | `true` | The ✕ in the corner. |
| `closeLabel` | `string` | `"Close"` | The ✕'s accessible label. |
| `initialFocus` | `RefObject<HTMLElement \| null>` | the first focusable element in the body, else the panel | What gets focus on open. |
| `as` | `"div" \| "form"` | `"div"` | `"form"` puts the body and the footer inside one `<form>`, so a `type="submit"` button in the footer submits it and Enter in a field does too. |
| `onSubmit` | `(event: FormEvent<HTMLFormElement>) => void` | none | With `as="form"`, called on submit; call `preventDefault()` to handle it yourself. |
| `className` | `string` | none | Classes for the panel. |

`ref` goes to the panel.

| `Dialog` prop | Type | Default | What it does |
|---|---|---|---|
| `size` | `Size \| "full"` | `"md"` | Width: `sm` 384 px, `md` 512 px, `lg` 768 px, `full` the whole window less a margin. |
| `role` | `"dialog" \| "alertdialog"` | `"dialog"` | `"alertdialog"` for one that interrupts with a question. |

| `Drawer` prop | Type | Default | What it does |
|---|---|---|---|
| `side` | `"left" \| "right" \| "bottom"` | `"right"` | The edge it slides in from. |
| `size` | `Size` | `"md"` | Width of a side drawer: `sm` 320 px, `md` 448 px, `lg` 640 px. Bottom sheets are as wide as the window. |
| `sheetOnPhone` | `boolean` | `true` | On phones, opens left and right drawers as a bottom sheet. |

```tsx
<Dialog
  trigger={<Button variant="primary">New project</Button>}
  title="New project"
  as="form"
  onSubmit={(e) => { e.preventDefault(); void create(name); }}
  footer={({ close }) => <><Button onClick={close}>Cancel</Button><Button variant="primary" type="submit">Create</Button></>}
>
  <Field label="Name"><Input value={name} onChange={(e) => setName(e.target.value)} /></Field>
</Dialog>
```

`DialogProps` and `DrawerProps` are the props types.

## `Gallery`, `Lightbox`, `GalleryImage`

`Gallery` shows images as thumbnails with their captions, in order; each thumbnail is a button that opens the `Lightbox` at that image. `layout="strip"` (the default) is one row that scrolls sideways and snaps to each thumbnail, `"grid"` wraps into as many columns as fit. `Lightbox` shows the images one at a time over the page, as large as the window allows, with the caption and "2 of 5" under it: Previous and Next buttons, the arrow keys (Home and End for the first and last) and a swipe on touch screens move between them; Escape, the ✕ or a press beside the image close it. It is modal like `Dialog`.

```ts
interface GalleryImage {
  src: string;      // "" shows a placeholder of the same size, for one still loading
  alt?: string;     // default the caption
  caption?: string;
  width?: number;   // the image's own size, so the lightbox keeps its shape while it loads
  height?: number;
}
```

| `Gallery` prop | Type | Default | What it does |
|---|---|---|---|
| `images` | `GalleryImage[]` | required | The images, in order. |
| `layout` | `"strip" \| "grid"` | `"strip"` | One row that scrolls sideways, or wrapping columns. |
| `aspectRatio` | `number` | `16 / 10` | The thumbnails' shape, width over height. |
| `label` | `string` | `"Images"` | The accessible name of the list and of the lightbox. |
| `hideCaptions` | `boolean` | `false` | Leave the captions out under the thumbnails; the lightbox still shows them. |
| `closeLabel`, `previousLabel`, `nextLabel`, `loadingLabel` | `string` | as on `Lightbox` | Passed to its lightbox. |
| `openLabel` | `string` | `"open larger"` | A thumbnail's accessible label after its caption. |

Other props go to the wrapping `<div>`.

| `Lightbox` prop | Type | Default | What it does |
|---|---|---|---|
| `images` | `GalleryImage[]` | required | The images. |
| `index` | `number \| null` | required | The image shown, or `null` when closed. |
| `onIndexChange` | `(index: number \| null) => void` | required | Called with the next index on Previous and Next, and with `null` to close. |
| `label` | `string` | `"Images"` | The viewer's accessible name. |
| `closeLabel` | `string` | `"Close"` | The close button's accessible label. |
| `previousLabel` | `string` | `"Previous"` | The Previous button's accessible label. |
| `nextLabel` | `string` | `"Next"` | The Next button's accessible label. |
| `loadingLabel` | `string` | `"Loading the image"` | What the spinner says while an image loads. |

Other props and `ref` go to the panel.

```tsx
<Gallery label="Screenshots" images={shots.map((s) => ({ src: s.url, caption: s.caption, width: s.width, height: s.height }))} />
```

`GalleryProps` and `LightboxProps` are the props types.

## `CommandMenu`, `CommandDialog`, `CommandItem`

```ts
interface CommandItem {
  id: string;            // stable and unique
  label: string;
  group?: string;        // items with the same group are listed together under it, in first-seen order
  icon?: ReactNode;
  shortcut?: string;     // shown as keys on the right, split on "+" ("Ctrl+Shift+P")
  description?: string;  // a second, quieter line
  keywords?: string[];   // extra words the search matches (synonyms, ids)
  disabled?: boolean;
  onSelect: () => void;
}
```

`CommandMenu` is a search field over a list of commands, the way the app's own palette works: type to filter, the arrows move, Enter runs, grouped with icons and shortcuts. It is inline (in a panel or a page); `CommandDialog` puts it in a modal near the top of the window, with focus in the search, Escape or the backdrop closing it, and focus going back afterwards. Bind your own shortcut to `open`.

| `CommandMenu` prop | Type | Default | What it does |
|---|---|---|---|
| `items` | `CommandItem[]` | required | The commands. |
| `query` | `string` | none | The search text (controlled), to search a server as the person types. |
| `defaultQuery` | `string` | `""` | The starting text when uncontrolled. |
| `onQueryChange` | `(query: string) => void` | none | Called with the text. |
| `filter` | `((item: CommandItem, query: string) => boolean) \| false` | every word in the label, group, description or keywords | Which items match. `false` shows `items` as given. |
| `placeholder` | `string` | `"Search…"` | The field's placeholder. |
| `empty` | `ReactNode` | `"No results"` | Shown when nothing matches. |
| `loading` | `boolean` | none | A searching row. |
| `autoFocus` | `boolean` | `true` | Focuses the search field on mount. |
| `footer` | `ReactNode` | none | A line under the list (hints, a link). |
| `label` | `string` | `"Commands"` | The list's accessible name. |

`CommandDialog` takes the `CommandMenu` props except `autoFocus`, and:

| `CommandDialog` prop | Type | Default | What it does |
|---|---|---|---|
| `open`, `defaultOpen`, `onOpenChange` | `boolean`, `boolean`, `(open: boolean) => void` | `defaultOpen` `false` | The open state. |
| `trigger` | `TriggerElement` | none | An element that opens it on click. |
| `closeOnSelect` | `boolean` | `true` | Closes after a command runs. |

`CommandMenuProps` and `CommandDialogProps` are the props types. The app's own `Ctrl/⌘ K` palette belongs to the app; a `CommandDialog` is one of your view's own.

## Floating helpers

The pieces every layer above is built from, for a floating layer of your own (a custom picker, an inline suggestion list). Source: `packages/ui/src/floating.ts`.

### Floating types

```ts
type Side = "top" | "right" | "bottom" | "left";
type Align = "start" | "center" | "end";
interface FloatingPoint { x: number; y: number }   // viewport coordinates, such as a right-click's clientX, clientY

/** An element, a ref to one, a point, or anything with getBoundingClientRect (a text range, a virtual box). */
type FloatingAnchor = Element | RefObject<Element | null> | FloatingPoint | { getBoundingClientRect(): DOMRect };

interface FloatingOptions {
  side?: Side;       // default "bottom"
  align?: Align;     // default "start"
  offset?: number;   // gap to the anchor in px, default 4
  padding?: number;  // space kept free at the viewport's edges in px, default 6
  flip?: boolean;    // open on the other side when the chosen one doesn't fit and the other has more room, default true
  shift?: boolean;   // slide along the anchor to stay inside the viewport, default true
}

interface FloatingPosition {
  left: number;
  top: number;
  side: Side;              // the side it ended up on, after flipping
  align: Align;
  availableWidth: number;  // room on that side, for a max-width
  availableHeight: number; // room on that side, for a max-height that keeps a long list on screen
}
```

`Side`, `Align`, `FloatingPoint`, `FloatingAnchor`, `FloatingOptions` and `FloatingPosition` are exported.

### `useFloating`

```ts
function useFloating<T extends HTMLElement = HTMLElement>(anchor: FloatingAnchor | null, options?: UseFloatingOptions): UseFloatingResult<T>;

interface UseFloatingOptions extends FloatingOptions {
  open?: boolean;      // keep it placed only while true; default true
  sameWidth?: boolean; // at least as wide as an element anchor (select lists); default false
  zIndex?: number;     // default 70, the layer menus use (dialogs are 60)
}

interface UseFloatingResult<T extends HTMLElement> {
  ref: (el: T | null) => void;  // put on the floating element
  style: CSSProperties;         // position: fixed with left/top (and minWidth with sameWidth); hidden until measured
  side: Side;                   // where it ended up, for a transform origin or an arrow
  align: Align;
  availableWidth: number;
  availableHeight: number;
  update: () => void;           // measure and place again now
}
```

Keeps a floating element placed against an anchor while it is open: before the first paint, and again on scroll (in any scroll parent), on window resize, and when the element or an element anchor change size. It is hidden until the first measurement, so it never flashes at 0,0. Render the element through `Portal` and give it `ref` and `style`. Call `update()` after the content changed size without a resize.

### `computePosition`

```ts
function computePosition(anchor: { left: number; top: number; right: number; bottom: number; width: number; height: number }, size: { width: number; height: number }, options?: FloatingOptions, viewport?: { width: number; height: number }): FloatingPosition;
```

The pure math under `useFloating`: places a box of `size` against `anchor` (a viewport rect) on `side` and `align`, flipping and shifting so it stays inside `viewport` (default the window's `innerWidth` and `innerHeight`).

### `Portal`

```ts
function Portal(props: { children: ReactNode; container?: Element | null }): ReactPortal;
```

Renders its children at the end of `document.body`, or into `container`, else into a surrounding `PortalContainer`, so a scrolling or `overflow-hidden` parent can't clip what floats.

### `PortalContainer`

```ts
const PortalContainer: React.Context<Element | null>;
```

Where `Portal` renders and which document the kit's floating layers work in. Render `<PortalContainer value={element}>` around kit components, and their dialogs, menus, popovers and toasts go into `element`; dismissal, scroll lock, focus handling and positioning use `element.ownerDocument` and its window instead of the globals. For rendering into another document (a preview frame, a pop-out window). Without it, `document.body` and `window`. `ConfirmDialog` and `ContextMenu` follow it too.

### `useDismiss`

```ts
type DismissReason = "outside" | "escape";

interface UseDismissOptions {
  enabled?: boolean;       // listen only while true, normally the open state; default true
  outsidePress?: boolean;  // close on a press outside; default true
  escape?: boolean;        // close on Escape; default true
}

function useDismiss(guard: Array<RefObject<Element | null> | Element | null | undefined>, onDismiss: (reason: DismissReason) => void, options?: UseDismissOptions): void;
```

Closes a floating layer on a press outside the elements in `guard` or on Escape, as a layer of the kit's [dismiss stack](../ui.md#escape-and-the-dismiss-stack). Pass the floating element and its trigger, so a press on the trigger can toggle it instead of closing and reopening. Escape closes only the newest enabled layer (and stops the key there), and a press inside a layer opened later doesn't close the ones under it. A modal sets `outsidePress: false` and closes from its backdrop's own click.

```tsx
const [open, setOpen] = useState(false);
const trigger = useRef<HTMLButtonElement>(null);
const [anchor, setAnchor] = useState<HTMLElement | null>(null);
const float = useFloating<HTMLDivElement>(anchor, { open, side: "bottom", align: "start", sameWidth: true });
const panel = useRef<HTMLDivElement | null>(null);
useDismiss([trigger, panel], () => setOpen(false), { enabled: open });

<button ref={(el) => { trigger.current = el; setAnchor(el); }} onClick={() => setOpen((o) => !o)}>Pick</button>
{open && <Portal><div ref={(el) => { panel.current = el; float.ref(el); }} style={float.style} className="rounded-lg bg-elevated shadow-pop">…</div></Portal>}
```
