# Popover
A panel anchored to a trigger, opened by a person or an agent.
Source page: https://dinachi.dev/docs/components/popover

## Installation
```bash
npx @dinachi/cli@latest add popover
```
Adds to your project:
- `components/ui/popover/popover.tsx`
- `components/ui/popover/index.ts`
Installs:
- `@base-ui/react` ^1.9.0

## Usage
```tsx
import {
  Popover,
  PopoverContent,
  PopoverDescription,
  PopoverTitle,
  PopoverTrigger,
} from "@/components/ui/popover"
import { Button } from "@/components/ui/button"

export function Filters() {
  return (
    <Popover>
      <PopoverTrigger render={<Button variant="outline" />}>Filters</PopoverTrigger>
      <PopoverContent>
        <PopoverTitle>Filters</PopoverTitle>
        <PopoverDescription>Narrow the list by status and owner.</PopoverDescription>
      </PopoverContent>
    </Popover>
  )
}
```

## Anatomy
```tsx
<Popover>
  <PopoverTrigger />
  <PopoverPortal>
    <PopoverBackdrop />
    <PopoverPositioner>
      <PopoverPopup>
        <PopoverArrow />
        <PopoverViewport>
          <PopoverTitle />
          <PopoverDescription />
          <PopoverClose />
        </PopoverViewport>
      </PopoverPopup>
    </PopoverPositioner>
  </PopoverPortal>
</Popover>
```
- `Popover`: Holds the open state.
- `PopoverTrigger`: Opens the popup. Names it for agents while closed.
- `PopoverContent`: The portal, positioner and popup in one.
- `PopoverPortal`: Renders its children into the body.
- `PopoverPositioner`: Places the popup against the trigger.
- `PopoverPopup`: The panel. Agents see it while open.
- `PopoverArrow`: A pointer from the popup to the trigger.
- `PopoverViewport`: Animates content when a shared popup switches triggers.
- `PopoverTitle`: The heading; names the popup.
- `PopoverDescription`: Describes the popup.
- `PopoverClose`: A button that closes the popup.
- `PopoverBackdrop`: A dimmed layer under the popup.
- `createPopoverHandle`: Links detached triggers to one Popover.

## Examples

### With close
Settings with a close button and controls inside.
```tsx
import { 
  Popover, 
  PopoverTrigger, 
  PopoverContent,
  PopoverTitle,
  PopoverDescription,
  PopoverClose
} from '@/components/ui/popover';
import { Settings, X } from 'lucide-react';
import { Button } from '@/components/ui/button';

export function Example() {
  return (
    <Popover>
      <PopoverTrigger render={<Button variant="outline" />}>
        <Settings className="mr-2 h-4 w-4" />
        Settings
      </PopoverTrigger>
      <PopoverContent className="w-80">
        <div className="flex items-start justify-between mb-2">
          <PopoverTitle>Settings</PopoverTitle>
          <PopoverClose render={<button className="rounded-sm opacity-70 hover:opacity-100" />}>
            <X className="h-4 w-4" />
          </PopoverClose>
        </div>
        <PopoverDescription>
          Configure your application settings here.
        </PopoverDescription>
        <div className="mt-4 space-y-2">
          <div className="flex items-center justify-between">
            <label className="text-sm">Enable notifications</label>
            <input type="checkbox" className="rounded" />
          </div>
          <div className="flex items-center justify-between">
            <label className="text-sm">Auto-save</label>
            <input type="checkbox" className="rounded" defaultChecked />
          </div>
        </div>
      </PopoverContent>
    </Popover>
  );
}
```

### Default
A title and description behind an icon button.
```tsx
import { 
  Popover, 
  PopoverTrigger, 
  PopoverContent, 
  PopoverArrow,
  PopoverTitle,
  PopoverDescription
} from '@/components/ui/popover';
import { Bell } from 'lucide-react';
import { Button } from '@/components/ui/button';

export function Example() {
  return (
    <Popover>
      <PopoverTrigger render={<Button variant="outline" size="icon" />}>
        <Bell className="h-4 w-4" />
      </PopoverTrigger>
      <PopoverContent>
        <PopoverArrow />
        <PopoverTitle>Notifications</PopoverTitle>
        <PopoverDescription>
          You are all caught up. Good job!
        </PopoverDescription>
      </PopoverContent>
    </Popover>
  );
}
```

### Sides
The popup on each side of its trigger.
```tsx
import { 
  Popover, 
  PopoverTrigger, 
  PopoverContent, 
  PopoverArrow,
  PopoverTitle,
  PopoverDescription
} from '@/components/ui/popover';
import { Button } from '@/components/ui/button';

export function Example() {
  return (
    <div className="flex gap-4 flex-wrap">
      <Popover>
        <PopoverTrigger render={<Button variant="outline" />}>Top</PopoverTrigger>
        <PopoverContent side="top">
          <PopoverArrow />
          <PopoverTitle>Top Position</PopoverTitle>
          <PopoverDescription>Opens at the top.</PopoverDescription>
        </PopoverContent>
      </Popover>
      
      <Popover>
        <PopoverTrigger render={<Button variant="outline" />}>Bottom</PopoverTrigger>
        <PopoverContent side="bottom">
          <PopoverArrow />
          <PopoverTitle>Bottom Position</PopoverTitle>
          <PopoverDescription>Opens at the bottom.</PopoverDescription>
        </PopoverContent>
      </Popover>
    </div>
  );
}
```

### On hover
Opens when the pointer rests on the trigger.
```tsx
import { 
  Popover, 
  PopoverTrigger, 
  PopoverContent, 
  PopoverArrow,
  PopoverTitle,
  PopoverDescription
} from '@/components/ui/popover';
import { Button } from '@/components/ui/button';

export function Example() {
  return (
    <Popover>
      <PopoverTrigger openOnHover delay={200} closeDelay={100} render={<Button variant="outline" />}>Hover me</PopoverTrigger>
      <PopoverContent>
        <PopoverArrow />
        <PopoverTitle>Hover Popover</PopoverTitle>
        <PopoverDescription>
          Opens when you hover over the trigger.
        </PopoverDescription>
      </PopoverContent>
    </Popover>
  );
}
```

### Shared popup
Several triggers share one popup through a handle.
```tsx
import {
  Popover,
  PopoverTrigger,
  PopoverPortal,
  PopoverPositioner,
  PopoverPopup,
  PopoverArrow,
  PopoverViewport,
  PopoverTitle,
  PopoverDescription,
  createPopoverHandle,
} from '@/components/ui/popover';
import { Button } from '@/components/ui/button';

const tabs = [
  { id: 'profile', label: 'Profile', title: 'Your Profile', description: 'Manage your display name, avatar, and public bio.' },
  { id: 'account', label: 'Account', title: 'Account Settings', description: 'Update your email, password, and two-factor authentication.' },
  { id: 'billing', label: 'Billing', title: 'Billing & Plans', description: 'View invoices, update payment methods, and change your plan.' },
];

export function Example() {
  const handle = createPopoverHandle();

  return (
    <div className="flex gap-2">
      {tabs.map((tab) => (
        <PopoverTrigger
          key={tab.id}
          handle={handle}
          payload={tab}
          openOnHover
          delay={200}
          closeDelay={150}
          render={(props) => (
            <Button variant="outline" size="sm" {...props}>{tab.label}</Button>
          )}
        />
      ))}
      <Popover handle={handle}>
        {({ payload }) => {
          const tab = payload as (typeof tabs)[number] | undefined;
          return (
            <PopoverPortal>
              <PopoverPositioner sideOffset={8}>
                <PopoverPopup>
                  <PopoverArrow />
                  <PopoverViewport>
                    {tab && (
                      <>
                        <PopoverTitle>{tab.title}</PopoverTitle>
                        <PopoverDescription>{tab.description}</PopoverDescription>
                      </>
                    )}
                  </PopoverViewport>
                </PopoverPopup>
              </PopoverPositioner>
            </PopoverPortal>
          );
        }}
      </Popover>
    </div>
  );
}
```

## Notes

### Inside a Dialog or Drawer
`PopoverContent` portals into the body by default. Pass `portal={false}` inside a `Dialog` or `Drawer` to stay in their stacking and focus scope.

### One popup, many triggers
Pass one `createPopoverHandle()` to the `Popover` and each `PopoverTrigger`, and give each trigger a `payload`. The children function receives it; `PopoverViewport` animates between contents. Agents see triggers outside the `Popover` as plain buttons.

## API reference
Props marked **agent** change what an agent reads or may do.

### Popover
Holds the open state.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `open` | `boolean` | - | Controlled open state. |
| `defaultOpen` | `boolean` | `false` | Starting state when uncontrolled. |
| `onOpenChange` **agent** | `(open, details) => void` | - | Runs for people and agents. `details.cancel()` refuses the change. |
| `onOpenChangeComplete` | `(open) => void` | - | Runs once the open or close animation ends. |
| `modal` | `boolean \| "trap-focus"` | `false` | Locks page scroll and outside clicks while open. "trap-focus" only traps focus. |
| `handle` | `PopoverHandle` | - | Links triggers rendered elsewhere. Make one with `createPopoverHandle()`. |
| `children` | `ReactNode \| ({ payload }) => ReactNode` | - | A function receives the opening trigger's payload. |

### PopoverTrigger
Opens the popup. Names it for agents while closed.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `render` | `ReactElement \| (props) => ReactElement` | - | Swap the element, keep the behaviour. |
| `openOnHover` | `boolean` | `false` | Also opens when the pointer rests on it. |
| `delay` | `number` | `300` | Milliseconds before opening on hover. |
| `closeDelay` | `number` | `0` | Milliseconds before closing after the pointer leaves. |
| `handle` | `PopoverHandle` | - | Ties a trigger outside the Popover to it. |
| `payload` | `unknown` | - | Passed to the Popover's children function when this trigger opens. |

### PopoverContent
The portal, positioner and popup in one.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `side` | `"top" \| "right" \| "bottom" \| "left"` | `"bottom"` | Which side of the trigger to open on. |
| `align` | `"start" \| "center" \| "end"` | `"center"` | Alignment along that side. |
| `sideOffset` | `number` | `8` | Gap to the trigger, in pixels. |
| `alignOffset` | `number` | - | Shift along the alignment axis, in pixels. |
| `collisionPadding` | `number` | `5` | Space kept from the viewport edge. |
| `collisionBoundary` | `Element \| "clipping-ancestors"` | `"clipping-ancestors"` | What the popup avoids overflowing. |
| `sticky` | `boolean` | `false` | Stays in view when the trigger scrolls away. |
| `portal` | `boolean` | `true` | Renders into the body. Set false inside a Dialog or Drawer. |

### PopoverPortal
Renders its children into the body.

Takes the props of the element it renders.

### PopoverPositioner
Places the popup against the trigger.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `side` | `"top" \| "right" \| "bottom" \| "left"` | `"bottom"` | Which side of the trigger to open on. |
| `sideOffset` | `number` | `8` | Gap to the trigger, in pixels. |
| `align` | `"start" \| "center" \| "end"` | `"center"` | Alignment along that side. |

### PopoverPopup
The panel. Agents see it while open.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `initialFocus` | `RefObject \| boolean` | - | What takes focus when it opens. |

### PopoverArrow
A pointer from the popup to the trigger.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` | `ReactNode` | - | Replaces the built-in arrow. |

### PopoverViewport
Animates content when a shared popup switches triggers.

Takes the props of the element it renders.

### PopoverTitle
The heading; names the popup.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` **agent** | `ReactNode` | - | Also the name the agent reads while open. |

### PopoverDescription
Describes the popup.

Takes the props of the element it renders.

### PopoverClose
A button that closes the popup.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `render` | `ReactElement \| (props) => ReactElement` | - | Swap the element, keep the behaviour. |

### PopoverBackdrop
A dimmed layer under the popup.

Takes the props of the element it renders.

### createPopoverHandle
Links detached triggers to one Popover.

Takes the props of the element it renders.

## Agent
Inside an `AgentProvider`, Popover appears in `agent.snapshot()` as `popover`.
Reads:
- `label`: The trigger's name while closed; while open, the `PopoverTitle`, falling back to the trigger's name.
- `open`: Whether the popup is showing.
Actions:
- `open()`: Opens the popup. Only while closed.
- `close()`: Closes the popup. Only while open.
While open, the popover and its contents are listed before the page. An agent's change runs through `onOpenChange`; `isAgentChange(details)` is true for it, and `details.cancel()` refuses it. The agent is told the app refused.
```ts
await agent.act({
  steps: [{ ref: "Settings", action: "open" }],
})
```

## Accessibility
- The popup is a dialog, named by `PopoverTitle` and described by `PopoverDescription`.
- The trigger reports whether the popup is open.
- Give an icon-only trigger an aria-label. The agent reads the same name.
- Focus moves into the popup on open and back to the trigger on close.
### Keyboard
| Keys | Does |
| --- | --- |
| `Space` / `Enter` | Opens or closes the popup from the trigger |
| `Tab` | Moves focus through the popup's content |
| `Esc` | Closes and returns focus to the trigger |

## Source
`components/ui/popover/popover.tsx`
```tsx
"use client"

import * as React from "react"
import { Popover as PopoverPrimitive } from "@base-ui/react/popover"
import { cn } from "@/lib/utils"
import { type AgentOpenParts, useAgentOpen, useHasAgent, useMergedRef } from "@/components/ui/agent"

const PopoverAgentContext = React.createContext<AgentOpenParts | null>(null)

/** Base UI's root, holding its own open state so an agent can open and close it. */
function Popover<Payload>({ open, defaultOpen, onOpenChange, ...props }: PopoverPrimitive.Root.Props<Payload>) {
  const [state, change, parts] = useAgentOpen("popover", open, defaultOpen, onOpenChange)
  return (
    <PopoverAgentContext.Provider value={useHasAgent() ? parts : null}>
      <PopoverPrimitive.Root<Payload> {...props} open={state} onOpenChange={change} />
    </PopoverAgentContext.Provider>
  )
}

function PopoverTrigger<Payload>({ ref, ...props }: PopoverPrimitive.Trigger.Props<Payload> & React.RefAttributes<HTMLElement>) {
  const parts = React.useContext(PopoverAgentContext)
  return <PopoverPrimitive.Trigger<Payload> ref={useMergedRef(ref, parts?.trigger)} data-slot="popover-trigger" {...props} />
}

function PopoverPortal(props: React.ComponentProps<typeof PopoverPrimitive.Portal>) {
  return <PopoverPrimitive.Portal data-slot="popover-portal" {...props} />
}

function PopoverClose(props: React.ComponentProps<typeof PopoverPrimitive.Close>) {
  return <PopoverPrimitive.Close data-slot="popover-close" {...props} />
}

const createPopoverHandle = PopoverPrimitive.createHandle

const PopoverPositioner = React.forwardRef<
  React.ComponentRef<typeof PopoverPrimitive.Positioner>,
  React.ComponentProps<typeof PopoverPrimitive.Positioner>
>(({ className, sideOffset = 8, ...props }, ref) => (
  <PopoverPrimitive.Positioner
    ref={ref}
    sideOffset={sideOffset}
    className={cn("z-50", className)}
    data-slot="popover-positioner"
    {...props}
  />
))
PopoverPositioner.displayName = "PopoverPositioner"

const PopoverPopup = React.forwardRef<
  React.ComponentRef<typeof PopoverPrimitive.Popup>,
  React.ComponentProps<typeof PopoverPrimitive.Popup>
>(({ className, ...props }, ref) => (
  <PopoverPrimitive.Popup
    ref={useMergedRef(ref, React.useContext(PopoverAgentContext)?.popup)}
    className={cn(
      "rounded-lg border bg-popover px-6 py-4 text-popover-foreground shadow-lg outline-none",
      "origin-[var(--transform-origin)]",
      "transition-[transform,scale,opacity] duration-[var(--motion-duration-fast,150ms)] ease-[var(--motion-ease-out,cubic-bezier(0.23,1,0.32,1))]",
      "data-[starting-style]:scale-95 data-[starting-style]:opacity-0",
      "data-[ending-style]:scale-95 data-[ending-style]:opacity-0",
      "motion-reduce:data-[starting-style]:scale-100 motion-reduce:data-[ending-style]:scale-100",
      className
    )}
    data-slot="popover-popup"
    {...props}
  />
))
PopoverPopup.displayName = "PopoverPopup"

const PopoverContent = React.forwardRef<
  React.ComponentRef<typeof PopoverPrimitive.Popup>,
  React.ComponentProps<typeof PopoverPrimitive.Popup> & {
    readonly side?: React.ComponentProps<typeof PopoverPrimitive.Positioner>["side"]
    readonly align?: React.ComponentProps<typeof PopoverPrimitive.Positioner>["align"]
    readonly sideOffset?: number
    readonly alignOffset?: number
    readonly collisionBoundary?: React.ComponentProps<typeof PopoverPrimitive.Positioner>["collisionBoundary"]
    readonly collisionPadding?: React.ComponentProps<typeof PopoverPrimitive.Positioner>["collisionPadding"]
    readonly sticky?: boolean
    readonly portal?: boolean
  }
>(({
  className,
  side = "bottom",
  align = "center",
  sideOffset = 8,
  alignOffset,
  collisionBoundary,
  collisionPadding,
  sticky,
  portal = true,
  ...props
}, ref) => {
  const content = (
    <PopoverPositioner
      side={side}
      align={align}
      sideOffset={sideOffset}
      alignOffset={alignOffset}
      collisionBoundary={collisionBoundary}
      collisionPadding={collisionPadding}
      sticky={sticky}
    >
      <PopoverPopup ref={ref} className={className} data-slot="popover-content" {...props} />
    </PopoverPositioner>
  )

  if (!portal) return content

  return <PopoverPortal>{content}</PopoverPortal>
})
PopoverContent.displayName = "PopoverContent"

const PopoverArrow = React.forwardRef<
  React.ComponentRef<typeof PopoverPrimitive.Arrow>,
  React.ComponentProps<typeof PopoverPrimitive.Arrow>
>(({ className, children, ...props }, ref) => (
  <PopoverPrimitive.Arrow
    ref={ref}
    className={cn(
      "data-[side=bottom]:top-[-8px]",
      "data-[side=left]:right-[-13px] data-[side=left]:rotate-90",
      "data-[side=right]:left-[-13px] data-[side=right]:-rotate-90",
      "data-[side=top]:bottom-[-8px] data-[side=top]:rotate-180",
      className
    )}
    data-slot="popover-arrow"
    {...props}
  >
    {children || (
      <svg width="20" height="10" viewBox="0 0 20 10" fill="none">
        <path
          d="M9.66437 2.60207L4.80758 6.97318C4.07308 7.63423 3.11989 8 2.13172 8H0V10H20V8H18.5349C17.5468 8 16.5936 7.63423 15.8591 6.97318L11.0023 2.60207C10.622 2.2598 10.0447 2.25979 9.66437 2.60207Z"
          className="fill-popover"
        />
        <path
          d="M8.99542 1.85876C9.75604 1.17425 10.9106 1.17422 11.6713 1.85878L16.5281 6.22989C17.0789 6.72568 17.7938 7.00001 18.5349 7.00001L15.89 7L11.0023 2.60207C10.622 2.2598 10.0447 2.2598 9.66436 2.60207L4.77734 7L2.13171 7.00001C2.87284 7.00001 3.58774 6.72568 4.13861 6.22989L8.99542 1.85876Z"
          className="fill-border"
        />
        <path
          d="M10.3333 3.34539L5.47654 7.71648C4.55842 8.54279 3.36693 9 2.13172 9H0V8H2.13172C3.11989 8 4.07308 7.63423 4.80758 6.97318L9.66437 2.60207C10.0447 2.25979 10.622 2.2598 11.0023 2.60207L15.8591 6.97318C16.5936 7.63423 17.5468 8 18.5349 8H20V9H18.5349C17.2998 9 16.1083 8.54278 15.1901 7.71648L10.3333 3.34539Z"
          className="fill-border"
        />
      </svg>
    )}
  </PopoverPrimitive.Arrow>
))
PopoverArrow.displayName = "PopoverArrow"

const PopoverViewport = React.forwardRef<
  React.ComponentRef<typeof PopoverPrimitive.Viewport>,
  React.ComponentProps<typeof PopoverPrimitive.Viewport>
>(({ className, ...props }, ref) => (
  <PopoverPrimitive.Viewport
    ref={ref}
    className={cn("flex flex-col gap-2", className)}
    data-slot="popover-viewport"
    {...props}
  />
))
PopoverViewport.displayName = "PopoverViewport"

const PopoverTitle = React.forwardRef<
  React.ComponentRef<typeof PopoverPrimitive.Title>,
  React.ComponentProps<typeof PopoverPrimitive.Title>
>(({ className, ...props }, ref) => (
  <PopoverPrimitive.Title
    ref={ref}
    className={cn("mb-2 text-base font-medium leading-none", className)}
    data-slot="popover-title"
    {...props}
  />
))
PopoverTitle.displayName = "PopoverTitle"

const PopoverDescription = React.forwardRef<
  React.ComponentRef<typeof PopoverPrimitive.Description>,
  React.ComponentProps<typeof PopoverPrimitive.Description>
>(({ className, ...props }, ref) => (
  <PopoverPrimitive.Description
    ref={ref}
    className={cn("text-base text-muted-foreground", className)}
    data-slot="popover-description"
    {...props}
  />
))
PopoverDescription.displayName = "PopoverDescription"

const PopoverBackdrop = React.forwardRef<
  React.ComponentRef<typeof PopoverPrimitive.Backdrop>,
  React.ComponentProps<typeof PopoverPrimitive.Backdrop>
>(({ className, ...props }, ref) => (
  <PopoverPrimitive.Backdrop
    ref={ref}
    className={cn(
      "fixed inset-0 z-40 bg-black/50",
      "data-[starting-style]:opacity-0 data-[ending-style]:opacity-0",
      "transition-opacity duration-[var(--motion-duration-fast,150ms)] ease-[var(--motion-ease-out,cubic-bezier(0.23,1,0.32,1))]",
      className
    )}
    data-slot="popover-backdrop"
    {...props}
  />
))
PopoverBackdrop.displayName = "PopoverBackdrop"

export {
  Popover,
  PopoverTrigger,
  PopoverContent,
  PopoverPositioner,
  PopoverPopup,
  PopoverArrow,
  PopoverViewport,
  PopoverTitle,
  PopoverDescription,
  PopoverClose,
  PopoverPortal,
  PopoverBackdrop,
  createPopoverHandle,
}
```
