# Popover

编辑或查看触发器旁边的内容。

popover 让一个小任务贴近它所属的东西。把字段、按钮或其他可交互内容放进去；放置位置、焦点和关闭都由它处理。

```tsx title="basic.tsx"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import { Input } from "@ui-sdk/react/input"
import {
  Popover,
  PopoverClose,
  PopoverContent,
  PopoverDescription,
  PopoverTitle,
  PopoverTrigger,
} from "@ui-sdk/react/popover"

function Example() {
  return (
    <Popover>
      <PopoverTrigger>Share</PopoverTrigger>
      <PopoverContent>
        <PopoverTitle>Share this document</PopoverTitle>
        <PopoverDescription>
          Anyone with the link can view it.
        </PopoverDescription>
        <Field>
          <FieldLabel>Link</FieldLabel>
          <Input readOnly defaultValue="acme.app/d/q3-roadmap" />
        </Field>
        <div data-slot="row">
          <PopoverClose>Cancel</PopoverClose>
          <PopoverClose data-variant="solid">Copy Link</PopoverClose>
        </div>
      </PopoverContent>
    </Popover>
  )
}

export { Example }
```

按 Share 打开 popover，然后用 Cancel、Copy Link、Escape 或外部按压关闭它。焦点会回到 Share。

## 安装
```bash
npm install @ui-sdk/react @ui-sdk/core
```

## 组合
用下面的组合构建 `Popover`：

```text
Popover
├── PopoverTrigger
└── PopoverContent
    ├── PopoverArrow
    ├── PopoverTitle
    ├── PopoverDescription
    └── PopoverClose
```

内容带有 dialog 角色。标题为它命名，描述补充上下文。箭头是可选的，一个 popover 可以有多个 Close 部件。触发器可以放在 popover 里面，也可以[从别处连接](https://ui-sdk.cn/docs/react/components/popover#triggers-outside-the-popover)。

## 用法
导入部件并把它们组合起来：

```tsx
import {
  Popover,
  PopoverClose,
  PopoverContent,
  PopoverDescription,
  PopoverTitle,
  PopoverTrigger,
} from "@ui-sdk/react/popover"

function Example() {
  return (
    <Popover>
      <PopoverTrigger>Share</PopoverTrigger>
      <PopoverContent>
        <PopoverTitle>Share this document</PopoverTitle>
        <PopoverDescription>
          Anyone with the link can view it.
        </PopoverDescription>
        <PopoverClose>Done</PopoverClose>
      </PopoverContent>
    </Popover>
  )
}

export { Example }
```

## 表单
普通表单可以保存一个值，然后关闭 popover。焦点从第一个字段开始，任务完成时回到触发器。带 `method="dialog"` 的表单在提交时关闭，并返回提交按钮的值；[行编辑器](https://ui-sdk.cn/docs/react/components/popover#triggers-outside-the-popover)展示了这种写法。放在另一个表单内部时，传入 `container`，这样 popover 的表单不会嵌套在里面。

```tsx title="form.tsx"
"use client"

import * as React from "react"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import { Input } from "@ui-sdk/react/input"
import {
  Popover,
  PopoverClose,
  PopoverContent,
  PopoverDescription,
  PopoverTitle,
  PopoverTrigger,
} from "@ui-sdk/react/popover"
import { useLog } from "./log"

function Example() {
  const log = useLog()
  const [open, setOpen] = React.useState(false)

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger>Edit Profile</PopoverTrigger>
      <PopoverContent>
        <PopoverTitle>Edit profile</PopoverTitle>
        <PopoverDescription>Your name shows on your posts.</PopoverDescription>
        <form
          data-slot="stack"
          onSubmit={(event) => {
            event.preventDefault()
            log(`Saved ${new FormData(event.currentTarget).get("name")}`)
            setOpen(false)
          }}
        >
          <Field>
            <FieldLabel>Name</FieldLabel>
            <Input name="name" required defaultValue="Hollis Grant" />
          </Field>
          <div data-slot="row">
            <PopoverClose>Cancel</PopoverClose>
            <button type="submit" data-variant="solid">
              Save
            </button>
          </div>
        </form>
      </PopoverContent>
    </Popover>
  )
}

export { Example }
```

打开 Edit Profile，修改名称，然后按 Save。popover 关闭，控制台会记录保存的名称。

## 编辑时保持打开
有未保存的改动时，把 `dismissible` 设为 false。此时 Escape 和外部按压会让 popover 保持打开，并报告 `onDismissAttempt`，你可以借此询问是否丢弃。焦点离开会被静默拒绝。触发器、Close 部件和控制器仍然可以关闭它。

```tsx title="draft.tsx"
"use client"

import * as React from "react"
import { Field, FieldControl, FieldLabel } from "@ui-sdk/react/field"
import {
  Popover,
  PopoverClose,
  PopoverContent,
  PopoverDescription,
  PopoverTitle,
  PopoverTrigger,
} from "@ui-sdk/react/popover"
import { useLog } from "./log"

function Example() {
  const log = useLog()
  const [open, setOpen] = React.useState(false)
  const [note, setNote] = React.useState("")
  const [asking, setAsking] = React.useState(false)
  const field = React.useRef<HTMLTextAreaElement>(null)
  const close = () => {
    setOpen(false)
    setNote("")
    setAsking(false)
  }

  return (
    <Popover
      open={open}
      onOpenChange={(next) => (next ? setOpen(true) : close())}
      dismissible={note === ""}
      onDismissAttempt={(details) => {
        log(`Kept open (${details.reason})`)
        setAsking(true)
      }}
    >
      <PopoverTrigger>Add Note</PopoverTrigger>
      <PopoverContent>
        <PopoverTitle>Add a note</PopoverTitle>
        <PopoverDescription>Only your team can see it.</PopoverDescription>
        <Field>
          <FieldLabel>Note</FieldLabel>
          <FieldControl
            render={
              <textarea
                ref={field}
                placeholder="Call the printer about the proofs."
              />
            }
            value={note}
            onChange={(event) => setNote(event.currentTarget.value)}
          />
        </Field>
        {asking ? (
          <div data-slot="row" role="alert">
            Discard your note?
            <div data-slot="row">
              <button
                type="button"
                data-size="sm"
                onClick={() => {
                  setAsking(false)
                  field.current?.focus()
                }}
              >
                Keep Editing
              </button>
              <button
                type="button"
                data-size="sm"
                data-variant="solid"
                onClick={() => {
                  log("Discarded the note")
                  close()
                }}
              >
                Discard
              </button>
            </div>
          </div>
        ) : (
          <div data-slot="row">
            <PopoverClose>Cancel</PopoverClose>
            <button
              type="button"
              data-variant="solid"
              onClick={() => {
                log(note ? "Saved the note" : "Nothing to save")
                close()
              }}
            >
              Save
            </button>
          </div>
        )}
      </PopoverContent>
    </Popover>
  )
}

export { Example }
```

打开 Add Note，输入一些内容，然后按 Escape 或点击外部。Keep Editing 回到字段；Discard 关闭 popover 并清空便签。

## 放置位置
`side` 选择触发器的一条边，默认是 `bottom`；`align` 让 popover 与它的 start、center 或 end 对齐。start 和 end 跟随文本方向。请求的位置放不下时，popover 会翻转或平移，`data-side` 和 `data-align` 报告它最终落在哪里。[浮层指南](https://ui-sdk.cn/docs/react/popups#place-the-content)介绍了共享的定位选项。

```tsx title="placement.tsx"
"use client"

import * as React from "react"
import {
  Popover,
  PopoverContent,
  PopoverDescription,
  PopoverTitle,
  PopoverTrigger,
} from "@ui-sdk/react/popover"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemIndicator,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/react/select"
import { CheckIcon, ChevronDownIcon } from "lucide-react"

const sides = [
  { value: "top", label: "Top" },
  { value: "right", label: "Right" },
  { value: "bottom", label: "Bottom" },
  { value: "left", label: "Left" },
]
const aligns = [
  { value: "start", label: "Start" },
  { value: "center", label: "Center" },
  { value: "end", label: "End" },
]
type Side = "top" | "right" | "bottom" | "left"
type Align = "start" | "center" | "end"

function Example() {
  const [side, setSide] = React.useState<Side>("bottom")
  const [align, setAlign] = React.useState<Align>("center")

  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <Select
          items={sides}
          value={side}
          onValueChange={(next) => next && setSide(next as Side)}
        >
          <SelectLabel>Side</SelectLabel>
          <SelectTrigger>
            <SelectValue />
            <ChevronDownIcon aria-hidden="true" />
          </SelectTrigger>
          <SelectContent>
            {sides.map((option) => (
              <SelectItem key={option.value} value={option.value}>
                {option.label}
                <SelectItemIndicator>
                  <CheckIcon aria-hidden="true" />
                </SelectItemIndicator>
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Select
          items={aligns}
          value={align}
          onValueChange={(next) => next && setAlign(next as Align)}
        >
          <SelectLabel>Align</SelectLabel>
          <SelectTrigger>
            <SelectValue />
            <ChevronDownIcon aria-hidden="true" />
          </SelectTrigger>
          <SelectContent>
            {aligns.map((option) => (
              <SelectItem key={option.value} value={option.value}>
                {option.label}
                <SelectItemIndicator>
                  <CheckIcon aria-hidden="true" />
                </SelectItemIndicator>
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
      <Popover>
        <PopoverTrigger>Delivery</PopoverTrigger>
        <PopoverContent side={side} align={align} sideOffset={8}>
          <PopoverTitle>Delivery window</PopoverTitle>
          <PopoverDescription>
            Arrives Tuesday between 9 AM and noon.
          </PopoverDescription>
        </PopoverContent>
      </Popover>
    </div>
  )
}

export { Example }
```

选择一个方向和一种对齐，然后打开 Delivery。靠近窗口边缘时，popover 会翻转或平移以保持可见。

## 偏移
`sideOffset` 是与触发器之间的间距，默认 4 像素。`alignOffset` 沿触发器的边平移 popover，`collisionPadding` 是离窗口边缘保留的空间。

```tsx title="offsets.tsx"
"use client"

import * as React from "react"
import {
  Popover,
  PopoverContent,
  PopoverDescription,
  PopoverTitle,
  PopoverTrigger,
} from "@ui-sdk/react/popover"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemIndicator,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/react/select"
import { CheckIcon, ChevronDownIcon } from "lucide-react"

const choices = {
  sideOffset: { label: "Side offset", values: ["4", "8", "16", "24"] },
  alignOffset: { label: "Align offset", values: ["-16", "0", "16"] },
  collisionPadding: { label: "Collision padding", values: ["8", "24", "48"] },
}
type Name = keyof typeof choices

function Example() {
  const [offsets, setOffsets] = React.useState<Record<Name, string>>({
    sideOffset: "8",
    alignOffset: "0",
    collisionPadding: "8",
  })

  return (
    <div data-slot="stack">
      <div data-slot="controls">
        {(Object.keys(choices) as Name[]).map((name) => (
          <Select
            key={name}
            items={choices[name].values}
            value={offsets[name]}
            onValueChange={(next) =>
              next && setOffsets({ ...offsets, [name]: next })
            }
          >
            <SelectLabel>{choices[name].label}</SelectLabel>
            <SelectTrigger>
              <SelectValue />
              <ChevronDownIcon aria-hidden="true" />
            </SelectTrigger>
            <SelectContent>
              {choices[name].values.map((value) => (
                <SelectItem key={value} value={value}>
                  {value}px
                  <SelectItemIndicator>
                    <CheckIcon aria-hidden="true" />
                  </SelectItemIndicator>
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        ))}
      </div>
      <Popover>
        <PopoverTrigger>Delivery</PopoverTrigger>
        <PopoverContent
          align="start"
          sideOffset={Number(offsets.sideOffset)}
          alignOffset={Number(offsets.alignOffset)}
          collisionPadding={Number(offsets.collisionPadding)}
        >
          <PopoverTitle>Delivery window</PopoverTitle>
          <PopoverDescription>
            Arrives Tuesday between 9 AM and noon.
          </PopoverDescription>
        </PopoverContent>
      </Popover>
    </div>
  )
}

export { Example }
```

修改偏移和边距，然后打开 Delivery。popover 会远离触发器，并沿它的方向移动。

## 箭头
`PopoverArrow` 跟随 popover 实际使用的一侧，翻转之后也是如此，并得到相同的 `data-side`。`arrowPadding` 让它与边角保持距离；`data-arrow-clamped` 告诉你它什么时候无法指向触发器的中间。这个示例会在你按它两侧的按钮时取消关闭，好让打开的箭头可以移动。

```tsx title="arrow.tsx"
"use client"

import * as React from "react"
import {
  Popover,
  PopoverArrow,
  PopoverContent,
  PopoverDescription,
  PopoverTitle,
  PopoverTrigger,
} from "@ui-sdk/react/popover"
import { CircleQuestionMarkIcon } from "lucide-react"

const sides = [
  { value: "top", label: "Top" },
  { value: "right", label: "Right" },
  { value: "bottom", label: "Bottom" },
  { value: "left", label: "Left" },
] as const
type Side = (typeof sides)[number]["value"]

function Example() {
  const [open, setOpen] = React.useState(false)
  const [side, setSide] = React.useState<Side>("bottom")
  const controls = React.useRef<HTMLDivElement>(null)

  return (
    <div data-slot="stack">
      <div data-slot="controls" role="group" aria-label="Side" ref={controls}>
        {sides.map((option) => (
          <button
            key={option.value}
            type="button"
            data-size="sm"
            aria-pressed={side === option.value}
            onClick={() => setSide(option.value)}
          >
            {option.label}
          </button>
        ))}
      </div>
      <Popover
        open={open}
        onOpenChange={(next, details) => {
          const target = details.event?.target
          const inControls =
            target instanceof Node && controls.current?.contains(target)
          if (inControls && details.reason !== "escape-key") {
            return details.cancel()
          }
          setOpen(next)
        }}
      >
        <PopoverTrigger aria-label="Help">
          <CircleQuestionMarkIcon aria-hidden="true" />
        </PopoverTrigger>
        <PopoverContent side={side} sideOffset={10} arrowPadding={12}>
          <PopoverArrow />
          <PopoverTitle>Keyboard shortcuts</PopoverTitle>
          <PopoverDescription>
            Press ? anywhere to see them all.
          </PopoverDescription>
        </PopoverContent>
      </Popover>
    </div>
  )
}

export { Example }
```

打开 Help，然后按 Top、Right、Bottom 或 Left。popover 和它的箭头会移到那一侧，并保持打开。

箭头伸出面板之外时，让它周围的溢出保持可见。如果 body 需要滚动，把滚动放在内层元素上。你也可以用 `::before` 画箭头，用 `data-side` 和 `--arrow-offset` 来定位。

## 锚点
设置 `anchor`，让 popover 贴着触发器以外的东西定位。它接受元素、选择器、像 `{ x, y }` 这样的点，或带 `getBoundingClientRect()` 的对象，比如文本选区的 range。锚点移动时会重新读取位置。如果 popover 打开期间锚点停止渲染，比如断点隐藏了触发器，popover 会以 `anchor-hidden` 原因关闭。

```tsx title="anchor.tsx"
"use client"

import * as React from "react"
import { Checkbox, CheckboxIndicator } from "@ui-sdk/react/checkbox"
import {
  Popover,
  PopoverClose,
  PopoverContent,
  PopoverDescription,
  PopoverTitle,
  PopoverTrigger,
} from "@ui-sdk/react/popover"
import { CheckIcon, SlidersHorizontalIcon } from "lucide-react"

const types = [
  { label: "Documents", checked: true },
  { label: "Images", checked: false },
  { label: "Shared with me", checked: true },
]

function Example() {
  const [anchor, setAnchor] = React.useState<HTMLInputElement | null>(null)

  return (
    <div data-slot="row">
      <input
        ref={setAnchor}
        type="search"
        placeholder="Search files…"
        aria-label="Search files"
      />
      <Popover>
        <PopoverTrigger aria-label="Search filters">
          <SlidersHorizontalIcon aria-hidden="true" />
        </PopoverTrigger>
        <PopoverContent anchor={anchor} align="start" sideOffset={8}>
          <PopoverTitle>Filters</PopoverTitle>
          <PopoverDescription>
            Show only these kinds of files.
          </PopoverDescription>
          <div data-slot="stack">
            {types.map((type) => (
              <label data-slot="label" key={type.label}>
                <Checkbox defaultChecked={type.checked}>
                  <CheckboxIndicator>
                    <CheckIcon aria-hidden="true" />
                  </CheckboxIndicator>
                </Checkbox>
                {type.label}
              </label>
            ))}
          </div>
          <div data-slot="row">
            <PopoverClose>Cancel</PopoverClose>
            <PopoverClose data-variant="solid">Apply</PopoverClose>
          </div>
        </PopoverContent>
      </Popover>
    </div>
  )
}

export { Example }
```

按下过滤器按钮。popover 与搜索字段对齐，而不是它旁边的小按钮。

## 模态
`modal` 控制 popover 如何与页面共存：

- `false` 是默认值，页面保持可用，焦点离开 popover 会关闭它。
- `"trap-focus"` 把 Tab 留在内部，同时页面仍然可以滚动和接收点击。
- `true` 还会让页面其余部分不可交互（inert），并锁定滚动。

```tsx title="modal.tsx"
"use client"

import * as React from "react"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import { Textarea } from "@ui-sdk/react/textarea"
import {
  Popover,
  PopoverClose,
  PopoverContent,
  PopoverDescription,
  PopoverTitle,
  PopoverTrigger,
} from "@ui-sdk/react/popover"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemIndicator,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@ui-sdk/react/select"
import { CheckIcon, ChevronDownIcon } from "lucide-react"

const modes = [
  { value: "false", label: "Non-modal" },
  { value: "trap-focus", label: "Trap focus" },
  { value: "true", label: "Modal" },
]

type Mode = "false" | "trap-focus" | "true"

const notes = {
  false: "Tab can leave, and focus leaving closes it.",
  "trap-focus": "Tab stays inside. The page still scrolls and takes clicks.",
  true: "Tab stays inside. The page is inert and doesn't scroll.",
}

function Example() {
  const [mode, setMode] = React.useState<Mode>("false")
  const modal = mode === "true" ? true : mode === "false" ? false : "trap-focus"

  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <Select
          items={modes}
          value={mode}
          onValueChange={(next) => next && setMode(next as Mode)}
        >
          <SelectLabel>Modal</SelectLabel>
          <SelectTrigger>
            <SelectValue />
            <ChevronDownIcon aria-hidden="true" />
          </SelectTrigger>
          <SelectContent>
            {modes.map((option) => (
              <SelectItem key={option.value} value={option.value}>
                {option.label}
                <SelectItemIndicator>
                  <CheckIcon aria-hidden="true" />
                </SelectItemIndicator>
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
      <Popover modal={modal}>
        <PopoverTrigger>Add Comment</PopoverTrigger>
        <PopoverContent>
          <PopoverTitle>Add a comment</PopoverTitle>
          <PopoverDescription>{notes[mode]}</PopoverDescription>
          <Field>
            <FieldLabel>Comment</FieldLabel>
            <Textarea defaultValue="Looks good to me." />
          </Field>
          <div data-slot="row">
            <PopoverClose>Cancel</PopoverClose>
            <PopoverClose data-variant="solid">Comment</PopoverClose>
          </div>
        </PopoverContent>
      </Popover>
    </div>
  )
}

export { Example }
```

选择一种模式，打开 Add Comment，然后试试 Tab 或点击页面。

## 焦点
用 `initialFocus` 选择第一个获得焦点的元素，或用 `"none"` 让焦点留在原处。`finalFocus` 控制焦点返回到哪里。悬停打开不会移动焦点；触摸打开会聚焦面板本身，这样不会弹出屏幕键盘，除非你设置了 `initialFocus`。共享的焦点规则见[浮层焦点](https://ui-sdk.cn/docs/react/popups#focus)。

```tsx title="focus.tsx"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import { Input } from "@ui-sdk/react/input"
import {
  Popover,
  PopoverClose,
  PopoverContent,
  PopoverDescription,
  PopoverTitle,
  PopoverTrigger,
} from "@ui-sdk/react/popover"

function Example() {
  return (
    <div data-slot="row">
      <Popover>
        <PopoverTrigger>Rename</PopoverTrigger>
        <PopoverContent>
          <PopoverTitle>Rename file</PopoverTitle>
          <PopoverDescription>
            Focus starts in the first field.
          </PopoverDescription>
          <Field>
            <FieldLabel>Name</FieldLabel>
            <Input defaultValue="Q3 roadmap.pdf" />
          </Field>
          <div data-slot="row">
            <PopoverClose>Cancel</PopoverClose>
            <PopoverClose data-variant="solid">Save</PopoverClose>
          </div>
        </PopoverContent>
      </Popover>
      <Popover>
        <PopoverTrigger>Publish</PopoverTrigger>
        <PopoverContent initialFocus="[data-autofocus]">
          <PopoverTitle>Publish changes?</PopoverTitle>
          <PopoverDescription>
            Focus starts on Publish, not Cancel.
          </PopoverDescription>
          <div data-slot="row">
            <PopoverClose>Cancel</PopoverClose>
            <PopoverClose data-autofocus="" data-variant="solid">
              Publish
            </PopoverClose>
          </div>
        </PopoverContent>
      </Popover>
      <Popover>
        <PopoverTrigger>Status</PopoverTrigger>
        <PopoverContent initialFocus="none" finalFocus="none">
          <PopoverTitle>All systems normal</PopoverTitle>
          <PopoverDescription>Focus stays on the trigger.</PopoverDescription>
        </PopoverContent>
      </Popover>
    </div>
  )
}

export { Example }
```

逐个打开：Rename 聚焦它的字段，Publish 聚焦它的 Publish 按钮，Status 把焦点留在触发器上。

## 悬停打开
`openOnHover` 增加指针打开，同时保留点击、键盘和触摸激活。`delay` 和 `closeDelay` 控制打开和关闭前的停顿。你可以越过间隙进入内容并与其交互。另一个 popover 或 hover card 通过悬停打开时，会关闭当前这个，除非它在当前 popover 内部，所以一排悬停触发器一次只显示一个。

```tsx title="hover.tsx"
"use client"

import {
  Popover,
  PopoverArrow,
  PopoverContent,
  PopoverDescription,
  PopoverTitle,
  PopoverTrigger,
} from "@ui-sdk/react/popover"
import { useLog } from "./log"

function Example() {
  const log = useLog()
  return (
    <Popover openOnHover delay={200} closeDelay={150}>
      <PopoverTrigger>@kofi</PopoverTrigger>
      <PopoverContent sideOffset={8}>
        <PopoverArrow />
        <PopoverTitle>Kofi Mensah</PopoverTitle>
        <PopoverDescription>
          Engineering manager, platform team.
        </PopoverDescription>
        <div data-slot="row">
          <button
            type="button"
            data-size="sm"
            data-variant="solid"
            onClick={() => log("Followed @kofi")}
          >
            Follow
          </button>
        </div>
      </PopoverContent>
    </Popover>
  )
}

export { Example }
```

悬停 @kofi，然后移入 popover 并按 Follow。你也可以按压触发器来打开它。

## 受控
传入 `open`，并在 `onOpenChange` 中更新它。用 `details.cancel()` 拒绝一项拟议的变更。常见的变更约定见[状态与事件](/docs/react/state-and-events)。

```tsx title="controlled.tsx"
"use client"

import * as React from "react"
import { Checkbox, CheckboxIndicator } from "@ui-sdk/react/checkbox"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import { Input } from "@ui-sdk/react/input"
import {
  Popover,
  PopoverClose,
  PopoverContent,
  PopoverDescription,
  PopoverTitle,
  PopoverTrigger,
} from "@ui-sdk/react/popover"
import { CheckIcon } from "lucide-react"
import { useLog } from "./log"

function Example() {
  const log = useLog()
  const [open, setOpen] = React.useState(false)
  const controls = React.useRef<HTMLDivElement>(null)

  return (
    <div data-slot="stack">
      <div data-slot="controls" ref={controls}>
        <label data-slot="label">
          <Checkbox
            checked={open}
            onCheckedChange={(next) => setOpen(next === true)}
          >
            <CheckboxIndicator>
              <CheckIcon aria-hidden="true" />
            </CheckboxIndicator>
          </Checkbox>
          Open
        </label>
      </div>
      <Popover
        open={open}
        onOpenChange={(next, details) => {
          const target = details.event?.target
          const inControls =
            target instanceof Node && controls.current?.contains(target)
          if (inControls && details.reason !== "escape-key") {
            return details.cancel()
          }
          setOpen(next)
          log(`${next ? "Opened" : "Closed"} (${details.reason})`)
        }}
      >
        <PopoverTrigger>Set Status</PopoverTrigger>
        <PopoverContent>
          <PopoverTitle>Set a status</PopoverTitle>
          <PopoverDescription>
            Your team sees it next to your name.
          </PopoverDescription>
          <Field>
            <FieldLabel>Status</FieldLabel>
            <Input defaultValue="In a meeting" />
          </Field>
          <div data-slot="row">
            <PopoverClose>Cancel</PopoverClose>
            <PopoverClose data-variant="solid">Save</PopoverClose>
          </div>
        </PopoverContent>
      </Popover>
    </div>
  )
}

export { Example }
```

勾选 Open 或按 Set Status，然后关闭 popover。控制台会记录每次变更及其原因。

## 键盘快捷键
设置触发器的 `shortcut`，用键盘切换 popover。`mod+i` 在 Apple 平台上是 Command+I，在其他平台上是 Control+I。Shortcut 部件显示当前平台的按键，触发器通过 `aria-keyshortcuts` 声明它们。

```tsx title="shortcut.tsx"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import { Input } from "@ui-sdk/react/input"
import {
  Popover,
  PopoverClose,
  PopoverContent,
  PopoverDescription,
  PopoverShortcut,
  PopoverTitle,
  PopoverTrigger,
} from "@ui-sdk/react/popover"

function Example() {
  return (
    <Popover>
      <PopoverTrigger shortcut="mod+i">
        Invite
        <PopoverShortcut />
      </PopoverTrigger>
      <PopoverContent>
        <PopoverTitle>Invite people</PopoverTitle>
        <PopoverDescription>
          They'll get an email with a link to join.
        </PopoverDescription>
        <Field>
          <FieldLabel>Email</FieldLabel>
          <Input type="email" placeholder="wren@example.com" />
        </Field>
        <div data-slot="row">
          <PopoverClose>Cancel</PopoverClose>
          <PopoverClose data-variant="solid">Send Invite</PopoverClose>
        </div>
      </PopoverContent>
    </Popover>
  )
}

export { Example }
```

按 Command+I 或 Control+I 打开 Invite。再次按同一快捷键，或按 Escape，关闭它。

## Popover 之外的触发器
把触发器和 popover 连接到同一个 `createPopoverController<Member>()`。每个触发器把自己的行作为 `payload` 传入；内容从状态里读取当前活动的行。只有活动的触发器会展开并接收返回的焦点。从另一行打开会更新同一个面板，所以一个编辑器就能服务整个列表。

`controller.open({ payload, anchor })` 从代码打开它，并返回一个 promise，带有关闭原因和可选的 `returnValue`。payload 在退出动画期间仍然可用。共享的模式见[控制器](/docs/react/controllers)。

```tsx title="payload.tsx"
"use client"

import * as React from "react"
import { Field, FieldControl, FieldLabel } from "@ui-sdk/react/field"
import {
  createPopoverController,
  Popover,
  PopoverContent,
  PopoverDescription,
  PopoverTitle,
  PopoverTrigger,
} from "@ui-sdk/react/popover"
import { useLog } from "./log"

type Member = { name: string; role: string }

const roles = ["Admin", "Editor", "Viewer"]

function Example() {
  const log = useLog()
  const [popover] = React.useState(() => createPopoverController<Member>())
  const [members, setMembers] = React.useState<Member[]>([
    { name: "Hollis Grant", role: "Owner" },
    { name: "Inès Moreau", role: "Editor" },
    { name: "Kofi Mensah", role: "Viewer" },
    { name: "Wren Takahashi", role: "Viewer" },
  ])
  const newest = members[members.length - 1]

  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <button
          type="button"
          onClick={async (event) => {
            const result = await popover.open({
              payload: newest,
              anchor: event.currentTarget,
            })
            log(
              `Closed (${result.reason}), returned ${result.returnValue ?? "nothing"}`
            )
          }}
        >
          Edit Newest Member
        </button>
      </div>
      <ul data-slot="list">
        {members.map((member) => (
          <li data-slot="row" key={member.name}>
            {member.name}
            <span data-slot="hint">{member.role}</span>
            <PopoverTrigger
              controller={popover}
              payload={member}
              disabled={member.role === "Owner"}
              data-size="sm"
              data-variant="ghost"
              aria-label={`Edit ${member.name}`}
            >
              Edit
            </PopoverTrigger>
          </li>
        ))}
      </ul>
      <Popover
        controller={popover}
        onPayloadChange={(payload) => {
          const member = payload as Member | undefined
          if (member) {
            log(`Editing ${member.name}`)
          }
        }}
      >
        <PopoverContent<Member> align="end" sideOffset={8}>
          {(state) => {
            const member = state.payload
            return (
              <>
                <PopoverTitle>{member?.name}</PopoverTitle>
                <PopoverDescription>
                  Roles decide what they can change.
                </PopoverDescription>
                <form
                  data-slot="stack"
                  method="dialog"
                  onSubmit={(event) => {
                    const submitter = (event.nativeEvent as SubmitEvent)
                      .submitter as HTMLButtonElement
                    if (submitter.value !== "save" || !member) {
                      return
                    }
                    const role = String(
                      new FormData(event.currentTarget).get("role")
                    )
                    setMembers((current) =>
                      current.map((entry) =>
                        entry.name === member.name ? { ...entry, role } : entry
                      )
                    )
                  }}
                >
                  <Field>
                    <FieldLabel>Role</FieldLabel>
                    <FieldControl
                      key={member?.name}
                      name="role"
                      defaultValue={member?.role}
                      render={
                        <select>
                          {roles.map((role) => (
                            <option key={role}>{role}</option>
                          ))}
                        </select>
                      }
                    />
                  </Field>
                  <div data-slot="row">
                    <button type="submit" value="cancel" formNoValidate>
                      Cancel
                    </button>
                    <button type="submit" value="save" data-variant="solid">
                      Save
                    </button>
                  </div>
                </form>
              </>
            )
          }}
        </PopoverContent>
      </Popover>
    </div>
  )
}

export { Example }
```

编辑 Inès Moreau 或 Kofi Mensah 并保存新角色。所有者不能编辑。Edit Newest Member 从代码打开同一个编辑器，控制台会记录它是如何关闭的。

## 动画
内容打开时带有 `data-starting-style`，关闭时带有 `data-ending-style`。从这些状态做过渡，popover 会保持挂载，直到退场结束。`onOpenChangeComplete` 在过渡之后运行，`keepMounted` 让关闭的内容留在页面里，保持隐藏。常见的生命周期见[样式与动画](/docs/react/styling-and-animation)。

```tsx title="animation.tsx"
"use client"

import {
  Popover,
  PopoverClose,
  PopoverContent,
  PopoverDescription,
  PopoverTitle,
  PopoverTrigger,
} from "@ui-sdk/react/popover"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  return (
    <Popover
      onOpenChange={(open) => log(open ? "Opening" : "Closing")}
      onOpenChangeComplete={(open) => log(open ? "Open" : "Closed")}
    >
      <PopoverTrigger>What's New</PopoverTrigger>
      <PopoverContent keepMounted>
        <PopoverTitle>What's new</PopoverTitle>
        <PopoverDescription>
          Comments now support threads and reactions.
        </PopoverDescription>
        <div data-slot="row">
          <PopoverClose data-variant="solid">Got It</PopoverClose>
        </div>
      </PopoverContent>
    </Popover>
  )
}

export { Example }
```

打开 What's New，然后按 Got It。控制台会记录 Opening、Open、Closing 和 Closed。

## 呈现方式
`presentation="sheet"` 把任务显示为底部面板（sheet）；`"auto"` 在每次打开时，于小尺寸触摸屏上选择底部面板。底部面板默认是模态的，可以向下滑动关闭。如果关闭被禁用，它会弹回并报告这次尝试。

为两种布局都设置 `data-presentation` 的样式。底部面板管理自己的位置和移动，所以不要动它的位移，也避免使用浮动面板的固定宽度。`--sheet-backdrop` 设置它后面的遮罩。

```tsx title="presentation.tsx"
"use client"

import { Field, FieldLabel } from "@ui-sdk/react/field"
import { Input } from "@ui-sdk/react/input"
import {
  Popover,
  PopoverClose,
  PopoverContent,
  PopoverDescription,
  PopoverTitle,
  PopoverTrigger,
} from "@ui-sdk/react/popover"

function Example() {
  return (
    <Popover presentation="sheet">
      <PopoverTrigger>Add Reminder</PopoverTrigger>
      <PopoverContent>
        <PopoverTitle>New reminder</PopoverTitle>
        <PopoverDescription>
          We'll notify you at the time you pick.
        </PopoverDescription>
        <Field>
          <FieldLabel>Remind me to</FieldLabel>
          <Input defaultValue="Send the Q3 roadmap" />
        </Field>
        <div data-slot="row">
          <PopoverClose>Cancel</PopoverClose>
          <PopoverClose data-variant="solid">Save</PopoverClose>
        </div>
      </PopoverContent>
    </Popover>
  )
}

export { Example }
```

以底部面板打开 Add Reminder。用 Cancel、Save、Escape、变暗的区域，或在触摸屏上向下滑动来关闭它。

## 容器
popover 默认就地渲染，并使用浏览器的顶层。`container` 把它们的 DOM 移到另一个元素，同时键盘顺序仍然跟随触发器。共享的容器行为见[浮层](https://ui-sdk.cn/docs/react/popups#mounting-and-containers)。

```tsx
const [container, setContainer] = React.useState<HTMLDivElement | null>(null)

<div ref={setContainer} />
<Popover>
  <PopoverTrigger>Details</PopoverTrigger>
  <PopoverContent container={container}>...</PopoverContent>
</Popover>
```

## 就地渲染
popover 打开在页面之上。在内容上设置 `inline`，让它在原处渲染，位于父级的布局和层叠之中，就像从角落控件里展开的面板。位置由你的 CSS 决定，所以 `side`、`align` 和偏移都不适用。

```tsx title="inline.tsx"
import {
  Popover,
  PopoverClose,
  PopoverContent,
  PopoverDescription,
  PopoverTitle,
  PopoverTrigger,
} from "@ui-sdk/react/popover"

function Example() {
  return (
    <div data-slot="popover-frame">
      <div data-slot="popover-corner">
        <Popover>
          <PopoverTrigger>Feedback</PopoverTrigger>
          <PopoverContent inline>
            <PopoverTitle>Send feedback</PopoverTitle>
            <PopoverDescription>
              The panel sits in the corner box, above its trigger.
            </PopoverDescription>
            <div data-slot="row">
              <PopoverClose>Close</PopoverClose>
            </div>
          </PopoverContent>
        </Popover>
      </div>
    </div>
  )
}

export { Example }
```

打开 Feedback。面板在按钮上方打开，位于角落的盒子内。

## 自定义渲染
每个部件都接受 `render`。传入一个元素，它的属性会与部件的属性合并；或者传入一个函数，接收属性（props）和部件的状态。内容的渲染函数可以读取它的 payload，行编辑器就是这样做的。

```tsx title="custom-rendering.tsx"
import {
  Popover,
  PopoverClose,
  PopoverContent,
  PopoverDescription,
  PopoverShortcut,
  PopoverTitle,
  PopoverTrigger,
} from "@ui-sdk/react/popover"

function Example() {
  return (
    <Popover>
      <PopoverTrigger
        shortcut="mod+u"
        render={(props, state) => (
          <button {...props}>
            {state.open ? "Hide Updates" : "Show Updates"}
            <PopoverShortcut>{(shortcut) => shortcut.text}</PopoverShortcut>
          </button>
        )}
      />
      <PopoverContent>
        <PopoverTitle render={<h3 />}>Updates</PopoverTitle>
        <PopoverDescription>
          Version 2.4 adds threaded comments.
        </PopoverDescription>
        <PopoverClose render={<a href="#" />}>Read the Changelog</PopoverClose>
      </PopoverContent>
    </Popover>
  )
}

export { Example }
```

打开 Show Updates。触发器的标签来自它的状态，标题渲染为 h3，Close 渲染为链接。

## 样式
popover 显示期间，用触发器上的 `data-open` 标记它；用 `data-side` 和 `data-align` 为内容和箭头按最终位置设置样式。把 `transform-origin: var(--transform-origin)` 放在内容上，缩放动画就会从触发器开始。

每个部件都有一个 `data-slot`，比如 `popover-content`，它的状态属性列在[数据属性](https://ui-sdk.cn/docs/react/components/popover#data-attributes)下。

### PopoverContent
- `--anchor-width`: Width of the anchor, usually the trigger. Use it to match widths.
- `--anchor-height`: Height of the anchor.
- `--available-width`: Space beside the popup, up to the viewport edge. Not inherited either.
- `--available-height`: Space between the anchor and the viewport edge. Use it for max-height. Not inherited, so a child that needs it copies it on the popup, like `[--list-height:var(--available-height)]`, and reads `max-h-(--list-height)`. The first popup registers both names for the whole page with `CSS.registerProperty`, so they don't inherit anywhere. A page that needs them to inherit calls it first, with `inherits: true`. An `@property` rule can't, since a registration in script wins.
- `--transform-origin`: The point on the anchor the popup opens from. Use it to scale from the right place.
- `--arrow-offset`: Where the anchor's center falls along the popup's edge, kept `arrowPadding` from the corners. Position a ::before arrow with it.
- `--drawer-progress`: While it presents as a sheet: how far open the sheet is, from 0 closed to 1 at its largest snap point. Never past 1.
- `--drawer-dim`: While it presents as a sheet: how dim the page behind is, from 0 to 1. The backdrop's opacity follows it.
- `--drawer-expand`: While it presents as a sheet: 0 at the second-largest snap point and below, 1 at the largest. With one snap point, the whole travel.
- `--drawer-stack`: While it presents as a sheet: how many sheets opened from inside this one are open above it, rising smoothly as each one opens. Push it back with it.
- `--sheet-backdrop`: Set it yourself: the color the page dims to while it presents as a sheet. Black at 0.2 by default.

### Viewport
- `--keyboard-inset`: While it presents as a sheet: how many pixels of the page the on-screen keyboard covers, 0 without one.
- `--visual-viewport-width`: While it presents as a sheet: the width of the part of the page you can see.
- `--visual-viewport-height`: While it presents as a sheet: the height of the part of the page you can see, above the keyboard.
- `--visual-viewport-top`: While it presents as a sheet: how far the part of the page you can see is scrolled from the top of the layout, as when the keyboard pushes it up.

## 数据属性
`PopoverTitle`、`PopoverDescription` 和 `PopoverClose` 没有状态属性。

### PopoverTrigger
`[data-slot="popover-trigger"]`

- `data-closed`: Present while the popover is closed, including while it animates out.
- `data-disabled`: Present when the trigger is disabled.
- `data-open`: Present while the popover is open. On a trigger, while it's open from that trigger.

### PopoverContent
`[data-slot="popover-content"]`

- `data-closed`: Present while the popover is closed, including while it animates out.
- `data-presentation` (`popover`, `sheet`): How the popover presents this time it's open.
- `data-open`: Present while the popover is open. On a trigger, while it's open from that trigger.
- `data-starting-style`: Present for the first frame. Style the state you animate from.
- `data-ending-style`: Present while the popover animates out. Style the state you animate to.
- `data-side` (`top`, `right`, `bottom`, `left`): Where the popover ended up, after flipping away from edges. Set on the arrow too.
- `data-align` (`start`, `center`, `end`): How the popover lines up with its trigger.

### PopoverArrow
`[data-slot="popover-arrow"]`

- `data-closed`: Present while the popover is closed, including while it animates out.
- `data-open`: Present while the popover is open. On a trigger, while it's open from that trigger.
- `data-side` (`top`, `right`, `bottom`, `left`): Where the popover ended up, after flipping away from edges. Set on the arrow too.
- `data-align` (`start`, `center`, `end`): How the popover lines up with its trigger.
- `data-arrow-clamped`: Present on the arrow when it stops short of the middle of the trigger, held back by `arrowPadding`.

## API 参考
属性和回调与下面相同，都作为 React props。

### Popover
- `container?` (`DocumentFragment | Element | null`): Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.
- `open?` (`boolean`): Whether the popover is open. Pass it to control the popover.
- `defaultOpen?` (`boolean`): Whether the popover starts open, when uncontrolled.
- `onOpenChange?` (`((open: boolean, details: ChangeDetails<PopoverOpenChangeReason>) => void)`): Runs when the popover wants to open or close. `details.reason` says why, and `details.cancel()` stops it.
- `onOpenChangeComplete?` (`((open: boolean) => void)`): Runs once the popover has finished opening or closing, after any animation.
- `onPayloadChange?` (`((payload: unknown, details: ChangeDetails<PopoverPayloadChangeReason>) => void)`): Runs when the payload the content shows changes: a trigger with another payload opens the popover, or takes the open popover over, which fires no `onOpenChange`, and so does a controller's `open({ payload })` on the open popover. `details.cancel()` keeps the previous payload.
- `modal?` (`"trap-focus" | boolean`): `false`: the rest of the page stays usable, and focus leaving the popover closes it. `true`: also traps focus, locks scroll and makes the rest of the page inert, and an outside press only closes the popover. `"trap-focus"`: traps focus but leaves the page scrollable and clickable.
- `openOnHover?` (`boolean`): Whether resting the pointer on the trigger opens the popover. Pressing the trigger still opens it, so keyboard and touch users can too.
- `delay?` (`number`): Milliseconds the pointer rests on the trigger before the popover opens, with `openOnHover`.
- `closeDelay?` (`number`): Milliseconds before the popover closes once the pointer leaves it and its trigger, with `openOnHover`.
- `presentation?` (`PresentationSetting<"popover">`): How the popover presents. `"sheet"` slides it up from the bottom of the screen, where it can be swiped away, and `"auto"` does that on small touch screens. Decided each time it opens; the server renders `"popover"` for `"auto"`.
- `controller?` (`PopupController<any, PopoverOpenChangeReason, {}, string, PopoverPayloadChangeReason>`): Opens, closes and inspects the popover from anywhere, and connects triggers outside it. Create one with `createPopoverController()`.
- `dismissible?` (`boolean`): Whether Escape, an outside press, focus or the window leaving, Android's back gesture and a sheet's swipe can close it. Triggers, Close parts and the controller always can. Pass `false` while it holds unsaved work, and ask in `onDismissAttempt`.
- `onDismissAttempt?` (`function`): Runs when `dismissible` refused a dismissal made on purpose: Escape, an outside press, back or a swipe. Focus or the window leaving is refused without it. Ask "Discard changes?" here.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### PopoverTrigger
popover 之外的触发器还接受 `controller`。

- `disabled?` (`boolean`): Stops the trigger from opening the popover. A native button can't be focused or pressed, unless `focusableWhenDisabled` is set.
- `focusableWhenDisabled?` (`boolean`): Keeps a disabled trigger in the tab order with `aria-disabled` instead of the native attribute, so it can host a tooltip that says why. Presses still do nothing.
- `payload?` (`unknown`): Data for the content to render when this trigger opens the popover, like the row it belongs to.
- `shortcut?` (`string`): A keyboard shortcut that presses the trigger, like `"mod+i"`. `mod` is Command on Apple platforms and Control elsewhere. Sets `aria-keyshortcuts`.
- `controller?` (`PopupController<any, PopoverOpenChangeReason, {}, string, PopoverPayloadChangeReason>`): Connects a trigger outside the popover, like one per table row, to the popover with this controller.

### PopoverContent
- `side?` (`Side`): Which side of the anchor the popup opens on. Flips to the other side when there isn't room. Which side of the trigger the popover opens on.
- `align?` (`Align`): How the popup lines up with the anchor along that side. `start` and `end` follow the reading direction. How the popover lines up with the trigger along that side.
- `sideOffset?` (`number`): Gap between the anchor and the popup, in pixels. Gap between the trigger and the popover, in pixels.
- `alignOffset?` (`number`): Shift along the anchor, in pixels. Shift along the trigger, in pixels.
- `collisionPadding?` (`number`): Space to keep from the viewport edges, in pixels.
- `arrowPadding?` (`number`): Space to keep between the arrow and the popup's corners, in pixels.
- `anchor?` (`string | Anchor | null`): Positions the popup against this instead of its trigger: an element, a CSS selector, a point like `{ x, y }`, or anything with `getBoundingClientRect()`. It's read on every check, so it can move. A controller's `open({ anchor })` wins for that open.
- `container?` (`DocumentFragment | Element | null`): Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.
- `initialFocus?` (`PopoverInitialFocus`): Where focus goes when the popover opens. Opening on hover never moves focus, and opening with touch focuses the popover itself so no on-screen keyboard appears, unless this is set to something other than `"auto"`.
- `finalFocus?` (`PopupFocusTarget`): Where focus goes when the popover closes while focus is inside it.
- `keepMounted?` (`boolean`): Whether the popover stays in the page, hidden, while closed. Its content keeps its state between opens.
- `inline?` (`boolean`): Renders the popover where it is in the page instead of above it, inside its parent's layout and stacking, and leaves placing it to your CSS: `side`, `align` and the offsets don't apply.

### PopoverArrow
从 popover 最终所在的一侧指向触发器。渲染一个 `div`。

### PopoverTitle
为 popover 命名。渲染一个 `h2`。

### PopoverDescription
在渲染期间描述 popover。渲染一个 `p`。

### PopoverClose
关闭 popover。渲染一个 `button`。

### PopoverShortcut
- `shortcut?` (`string`): The keys to show. Inside a trigger, its `shortcut`.

### 状态
每个部件的渲染函数、基于状态的类名和槽位会收到什么。

`PopoverTrigger`：

- `open` (`boolean`): Whether the popover is open from this trigger.
- `disabled` (`boolean`): Set by the trigger's `disabled` prop, which stops it opening the popover.

`PopoverContent`：

- `open` (`boolean`): Whether the popover is open. False while it animates out.
- `modal` (`boolean | "trap-focus"`): The `modal` setting.
- `presentation` (`"popover" | "sheet"`): How it presents this time it's open.
- `payload` (`Payload | undefined`): The payload of the last open, from the trigger that opened it or a controller, typed as the controller's `Payload`.

`PopoverArrow`：

- `open` (`boolean`): Whether the popover is open. False as soon as it starts closing, while it still animates out.

`PopoverShortcut`：

- `text` (`string`): The shortcut formatted for this platform: `⌘I` on Apple platforms and `Ctrl+I` elsewhere. Empty without one.

### 原因
`details.reason` 说明 popover 为什么打开或关闭。

- `trigger-press` (`MouseEvent | KeyboardEvent | TouchEvent`): Click, tap, Enter or Space on the part that opens, closes or toggles. Arrow keys that open a menu or submenu count too. A tap on a combobox's input that opens a sheet reports its `touchend`.
- `trigger-hover` (`PointerEvent`): The pointer rested on a trigger, or left it, with hover opening.
- `outside-press` (`MouseEvent`): A press outside the layer.
- `escape-key` (`KeyboardEvent`): Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
- `focus-out` (`KeyboardEvent | FocusEvent`): Focus left the layer, or Tab moved it out.
- `window-blur` (`FocusEvent`): The window lost focus.
- `close-press` (`MouseEvent | KeyboardEvent | SubmitEvent`): A Close part was pressed, or a form with `method="dialog"` was submitted.
- `back` (`Event`): Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
- `shortcut` (`KeyboardEvent`): A keyboard shortcut, like a trigger's `shortcut`.
- `swipe` (`TouchEvent | PointerEvent`): A swipe gesture: a finger, mouse or pen dragged it.
- `anchor-hidden` (`none`): The element the popup sits beside stopped rendering, like a trigger a breakpoint hides.
- `imperative` (`none`): A controller or `api` call.

payload 变更时，它说明是什么打开了 popover 或接管了它。

- `trigger-press` (`MouseEvent | KeyboardEvent | TouchEvent`): Click, tap, Enter or Space on the part that opens, closes or toggles. Arrow keys that open a menu or submenu count too. A tap on a combobox's input that opens a sheet reports its `touchend`.
- `trigger-hover` (`PointerEvent`): The pointer rested on a trigger, or left it, with hover opening.
- `shortcut` (`KeyboardEvent`): A keyboard shortcut, like a trigger's `shortcut`.
- `imperative` (`none`): A controller or `api` call.

`dismissible` 为 false 时，`onDismissAttempt` 报告的、被拒绝的关闭尝试：

- `outside-press` (`MouseEvent`): A press outside the layer.
- `escape-key` (`KeyboardEvent`): Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
- `back` (`Event`): Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
- `swipe` (`TouchEvent | PointerEvent`): A swipe gesture: a finger, mouse or pen dragged it.

### 控制器
用 `createPopoverController<Payload>()` 创建一个，并作为 `controller` 传给 popover 以及它之外的所有触发器。`Payload` 是触发器和 `open()` 传入数据的类型。

每个写入方法都接受一个可选的 `{ reason, event }`，传给 `onOpenChange`。

- `isOpen()` (`() => boolean`): Whether it's open. False as soon as it starts closing, while it still animates out.
- `setOpen(open, options?)` (`(open: boolean, options?: PopupChangeOptions<PopoverOpenChangeReason> | undefined) => boolean`): Opens or closes it. Returns false when the change was canceled or it was already open or closed.
- `open(options?)` (`(options?: (PopupChangeOptions<PopoverPayloadChangeReason> & { payload?: Payload | undefined; anchor?: Anchor | undefined; signal?: AbortSignal | undefined; }) | undefined) => Promise<...>`): Opens it, and resolves once it closes, with why, how and any return value. Resolves exactly once and never rejects: on the next close from any source, when `signal` aborts, or with reason `"unmount"` when the component leaves the page.
- `close(options?)` (`(options?: (PopupChangeOptions<PopoverOpenChangeReason> & { returnValue?: Result | undefined; }) | undefined) => boolean`): Closes it. `returnValue` is passed to the promise `open()` returned. Returns false when the close was canceled or it was already closed.
- `toggle(options?)` (`(options?: PopupChangeOptions<PopoverOpenChangeReason> | undefined) => boolean`): Opens it when it's closed, and closes it when it's open. Returns false when the change was canceled.
- `getPayload()` (`() => Payload | undefined`): The payload of the last open, from a controller or the trigger that opened it.
- `focus()` (`() => void`): Moves focus to the trigger that opened it last, or the first trigger.

### 事件
回调先收到新状态，然后收到详情。

| 属性                   | 所属      | 收到                                                         |
| ---------------------- | --------- | ------------------------------------------------------------ |
| `onOpenChange`         | `Popover` | `(open, details)`：新状态，以及[原因](https://ui-sdk.cn/docs/react/components/popover#reasons)              |
| `onOpenChangeComplete` | `Popover` | `(open)`，在动画之后                                         |
| `onPayloadChange`      | `Popover` | `(payload, details)`：内容的新 payload，以及[原因](https://ui-sdk.cn/docs/react/components/popover#reasons) |
| `onDismissAttempt`     | `Popover` | `({ reason, event })`，在关闭尝试被拒绝时                    |

## 无障碍
触发器是一个打开对话框的按钮，内部的焦点遵循 [WAI-ARIA 对话框模式](https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/)。

### 经过测试的行为
下面每一行都是一个自动化测试。

**Trigger**

- Reflects the open state.
- Click opens the popover.
- Click on the open trigger closes the popover.
- Enter opens the popover.
- Space opens the popover.
- The popover closes when its trigger stops rendering, and stays closed when it's back.
- Points to the popover it controls while open.

**Focus**

- Opening moves focus to the first focusable element.
- Each time focus moves in, the popover is named by its title and described by its description.
- Tab moves through the popover in order.
- Shift+Tab from the first element returns focus to the trigger.
- Tab from the last element moves focus to the element after the trigger.
- Focus leaving the popover closes it.
- Escape closes the popover and returns focus to the trigger.
- An ancestor hears Escape already handled.
- Escape after a click returns focus to the trigger.
- The close button closes the popover and returns focus to the trigger.
- With initial focus none, opening leaves focus on the trigger.
- A virtual click from a screen reader moves focus into the popover.
- A touch press focuses the popover itself, so no on-screen keyboard appears.
- Closing after the trigger is gone moves focus to the element after where it was.
- Pressing a button inside keeps the popover open.

**Dismissal**

- Clicking outside closes the popover.
- Clicking inside the popover keeps it open.
- An outside press reaches what it hits.
- A press on empty space returns focus to the trigger.
- Escape while an input method is composing text leaves the popover open.
- Pressing a scrollbar outside the popover leaves it open.
- Pressing a button in a shadow root inside keeps the popover open.
- Tab into a button in a shadow root inside keeps the popover open.
- Escape on a button in a shadow root inside returns focus to the trigger.
- Switching windows leaves the popover open.

**Modal**

- With modal true, Tab stays inside the popover.
- With modal trap-focus, Tab stays inside the popover.
- With modal true, an outside press only closes the popover.
- With modal true, the page doesn't scroll while open.

**Hover**

- Resting the pointer on the trigger opens the popover.
- Moving the pointer into the popover keeps it open.
- Moving the pointer away closes the popover.
- Opening on hover leaves focus where it was.
- Keyboard focus on the trigger doesn't open the popover.
- Escape on a popover opened by hover leaves focus where it was.
- Pressing the trigger still opens the popover.

**Nested popovers**

- Using a nested popover keeps both open.
- Escape closes only the nested popover and returns focus to its trigger.
- Clicking outside closes every popover.

Runs in React、Vue 和 web components.

其他行为：

**Enhancements**

- The popup writes --arrow-offset, where the trigger's center falls along its edge.
- Without a title, the trigger names the popover.
- Tab from the trigger of a popover opened by hover moves into it.
- A controller opens the popover from anywhere and moves focus in.
- With no trigger, Shift+Tab from the first field goes back to where it opened from.
- Tab past the last control closes the popover when nothing on the page follows.
- A control that turns disabled after Tab reaches it keeps the popover open.
- A popover open from the start leaves focus alone.
- Modal popovers make the rest of the page inert and restore it exactly.
- Live regions keep announcing while a modal popover makes the page inert.
- Clicking into an iframe closes the popover.
- An infinite exit animation still unmounts.

**Shortcuts**

- A trigger's shortcut opens and closes the popover.
- The trigger advertises its shortcut, and its Shortcut part shows the keys to sighted users only.
- A Shortcut part shows its own keys.
- A trigger connected through a controller shows and binds its own shortcut.

**Web components**

- A title added after the popover connects names it. Web components only.
- Changing an attribute updates the part. Web components only.

Runs in React、Vue 和 web components.

在每个经过测试的框架里，屏幕阅读器听到的内容相同，由虚拟屏幕阅读器记录：

- Announcements while using the popover with a keyboard.

Runs in React、Vue 和 web components.
