# Accordion

用标题展开和收起内容小节。

当人们需要一次展开一个内容小节来浏览时，用 Accordion（手风琴），比如答案、设置或课程大纲。每个标题都是一个按钮，用来打开它对应的面板。

```tsx title="basic.tsx"
import {
  Accordion,
  AccordionHeader,
  AccordionItem,
  AccordionPanel,
  AccordionTrigger,
} from "@ui-sdk/solid/accordion"
import { For } from "solid-js"

const items = [
  {
    value: "shipping",
    label: "What are your shipping options?",
    content: [
      "We offer standard (5 to 7 days), express (2 to 3 days) and overnight shipping.",
      "Every order ships with tracking, and orders over $50 ship free.",
    ],
  },
  {
    value: "returns",
    label: "What is your return policy?",
    content: [
      "Return any unused item in its original packaging within 30 days. Refunds arrive within 5 to 7 business days.",
    ],
  },
  {
    value: "support",
    label: "How can I reach support?",
    content: [
      "Write to us by email or chat, or call us. We answer within 24 hours on business days.",
    ],
  },
]

function Example() {
  return (
    <Accordion defaultValue={["shipping"]}>
      <For each={items}>
        {(item) => (
          <AccordionItem value={item.value}>
            <AccordionHeader>
              <AccordionTrigger>
                {item.label}
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <path d="m6 9 6 6 6-6" />
                </svg>
              </AccordionTrigger>
            </AccordionHeader>
            <AccordionPanel>
              <For each={item.content}>{(paragraph) => <p>{paragraph}</p>}</For>
            </AccordionPanel>
          </AccordionItem>
        )}
      </For>
    </Accordion>
  )
}

export { Example }
```

按“What is your return policy?”，它的回答会展开，配送的回答会收起。再按同一个标题就能把它收起。

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

## 组合
用下面的组合来构建 `Accordion`：

```text
Accordion
├── AccordionItem
│   ├── AccordionHeader
│   │   └── AccordionTrigger
│   └── AccordionPanel
└── AccordionItem
    ├── AccordionHeader
    │   └── AccordionTrigger
    └── AccordionPanel
```

给每个条目一个唯一的 `value`。把它的触发器放进标题里，然后加上它要打开的面板。手风琴的 `value` 始终是一个由已展开条目的 `value` 组成的数组，即使同时只能展开一个条目也是如此。

`AccordionHeader` 默认渲染成 `h3`。选用与周围文档相符的标题层级。Tab 在触发器之间移动；Enter 或 Space 展开和收起它们的面板。方向键、Home 和 End 在这里不起作用：APG 已把它们从模式中移除，而屏幕阅读器的标题导航已经能到达每个触发器。

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

```tsx
import {
  Accordion,
  AccordionHeader,
  AccordionItem,
  AccordionPanel,
  AccordionTrigger,
} from "@ui-sdk/solid/accordion"

function Example() {
  return (
    <Accordion>
      <AccordionItem value="shipping">
        <AccordionHeader>
          <AccordionTrigger>Shipping</AccordionTrigger>
        </AccordionHeader>
        <AccordionPanel>Orders arrive in five to seven days.</AccordionPanel>
      </AccordionItem>
    </Accordion>
  )
}

export { Example }
```

## 自己构建
`@ui-sdk/solid/accordion` 自带一个现成的 Accordion。如果你想用自己的名字构建一个，可以从 `@ui-sdk/core` 里的 `accordion` 原语（primitive）开始：

```ts title="faq.ts"
import { accordion } from "@ui-sdk/core/accordion"
import { createParts } from "@ui-sdk/solid/primitive"

const {
  Root: FaqList,
  Item: FaqItem,
  Header: FaqHeading,
  Trigger: FaqQuestion,
  Panel: FaqAnswer,
} = createParts(accordion, {
  root: "div",
  item: "div",
  header: "h3",
  trigger: "button",
  panel: "div",
})

export { FaqAnswer, FaqHeading, FaqItem, FaqList, FaqQuestion }
```

```tsx
<FaqList>
  <FaqItem value="shipping">
    <FaqHeading>
      <FaqQuestion>What are your shipping options?</FaqQuestion>
    </FaqHeading>
    <FaqAnswer>Standard, express and overnight.</FaqAnswer>
  </FaqItem>
</FaqList>
```

每个部件都保留其现成对应部件的行为、状态和数据属性。更多内容见[渲染原语](/docs/solid/rendering)和[自定义部件](/docs/solid/custom-parts)。

## 多个
加上 `multiple`，让多个条目可以同时保持展开。打开一个条目时，其余条目保持原样。

```tsx title="multiple.tsx"
import {
  Accordion,
  AccordionHeader,
  AccordionItem,
  AccordionPanel,
  AccordionTrigger,
} from "@ui-sdk/solid/accordion"
import { For } from "solid-js"

const items = [
  {
    value: "notifications",
    label: "Notification settings",
    content: "Choose what we email you about, and how often.",
  },
  {
    value: "privacy",
    label: "Privacy and security",
    content: "Turn on two-factor authentication and review signed-in devices.",
  },
  {
    value: "billing",
    label: "Billing and subscription",
    content: "Update your payment method and download past invoices.",
  },
]

function Example() {
  return (
    <Accordion multiple defaultValue={["notifications"]}>
      <For each={items}>
        {(item) => (
          <AccordionItem value={item.value}>
            <AccordionHeader>
              <AccordionTrigger>
                {item.label}
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <path d="m6 9 6 6 6-6" />
                </svg>
              </AccordionTrigger>
            </AccordionHeader>
            <AccordionPanel>{item.content}</AccordionPanel>
          </AccordionItem>
        )}
      </For>
    </Accordion>
  )
}

export { Example }
```

展开 Privacy and security。Notification settings 会保持展开；两个小节可以各自独立收起。

## 禁用
在条目或单个触发器上设置 `disabled` 来阻止变更，或者在手风琴上设置它来禁用每个条目。禁用的触发器仍留在 Tab 顺序里，人们仍然能发现它们。手风琴外层禁用的 `<fieldset>` 也会把它禁用。

```tsx title="disabled.tsx"
import {
  Accordion,
  AccordionHeader,
  AccordionItem,
  AccordionPanel,
  AccordionTrigger,
} from "@ui-sdk/solid/accordion"
import { For } from "solid-js"

const items = [
  {
    value: "access",
    label: "Can I access my account history?",
    content:
      "Yes. Every order and payment from the last five years is in your account.",
  },
  {
    value: "premium",
    label: "Premium feature information",
    content:
      "Premium includes priority support and early access to new features.",
    disabled: true,
  },
  {
    value: "email",
    label: "How do I update my email address?",
    content:
      "Open Settings, then Account, and change it there. We'll send a confirmation link.",
  },
]

function Example() {
  return (
    <Accordion>
      <For each={items}>
        {(item) => (
          <AccordionItem value={item.value} disabled={item.disabled}>
            <AccordionHeader>
              <AccordionTrigger>
                {item.label}
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <path d="m6 9 6 6 6-6" />
                </svg>
              </AccordionTrigger>
            </AccordionHeader>
            <AccordionPanel>{item.content}</AccordionPanel>
          </AccordionItem>
        )}
      </For>
    </Accordion>
  )
}

export { Example }
```

用 Tab 移到 Premium feature information。它保持可聚焦，按下它，它的小节仍是收起的。改试“How do I update my email address?”。

<span id="behavior-and-options" />

## 可折叠
当展开的条目应该一直保持展开，直到另一个条目替换它时，设置 `collapsible={false}`。再配合 `defaultValue={["overview"]}`，让某个面板一开始就展开。

处于展开状态的触发器会报告 `aria-disabled="true"`，因为按它之后它的小节仍然展开。

```tsx
<Accordion collapsible={false} defaultValue={["overview"]} />
```

```tsx title="collapsible.tsx"
import {
  Accordion,
  AccordionHeader,
  AccordionItem,
  AccordionPanel,
  AccordionTrigger,
} from "@ui-sdk/solid/accordion"
import { For } from "solid-js"

const items = [
  {
    value: "overview",
    label: "Overview",
    content: "A summary of the project, its goals and its owners.",
  },
  {
    value: "timeline",
    label: "Timeline",
    content: "Kickoff in March, beta in June and launch in September.",
  },
  {
    value: "budget",
    label: "Budget",
    content: "Approved for two engineers and one designer for six months.",
  },
]

function Example() {
  return (
    <Accordion collapsible={false} defaultValue={["overview"]}>
      <For each={items}>
        {(item) => (
          <AccordionItem value={item.value}>
            <AccordionHeader>
              <AccordionTrigger>
                {item.label}
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <path d="m6 9 6 6 6-6" />
                </svg>
              </AccordionTrigger>
            </AccordionHeader>
            <AccordionPanel>{item.content}</AccordionPanel>
          </AccordionItem>
        )}
      </For>
    </Accordion>
  )
}

export { Example }
```

展开 Timeline，再按一次。它会保持展开，直到你选择另一个标题。

## 受控
用 `value` 和 `onValueChange` 自己管理已展开的条目。[状态与事件](/docs/solid/state-and-events)介绍了这个通用模式。

条目可以拒绝变更：在它的 `onOpenChange` 回调里调用 `details.cancel()`。条目回调在手风琴的 `onValueChange` 之前运行，包括在另一个条目展开时将要收起的那个条目。取消其中任意一个，整个变更都会被取消。`onValueChange` 还会收到这次变更的[原因](https://ui-sdk.cn/docs/solid/components/accordion#reasons)。

```tsx title="controlled.tsx"
import { createAccordionController } from "@ui-sdk/core/accordion"
import {
  Accordion,
  AccordionHeader,
  AccordionItem,
  AccordionPanel,
  AccordionTrigger,
} from "@ui-sdk/solid/accordion"
import { createSignal, For } from "solid-js"

const items = [
  {
    value: "account",
    label: "Account",
    content: "Your name, email address and profile photo.",
  },
  {
    value: "security",
    label: "Security",
    content: "Your password, passkeys and two-factor authentication.",
  },
  {
    value: "sessions",
    label: "Sessions",
    content: "Devices signed in to your account in the last 30 days.",
  },
]

function Example() {
  const accordion = createAccordionController()
  const [value, setValue] = createSignal(["account"])

  return (
    <div>
      <div data-slot="controls">
        <button type="button" onClick={() => accordion.open("security")}>
          Review security
        </button>
      </div>
      <Accordion
        multiple
        value={value()}
        onValueChange={setValue}
        controller={accordion}
      >
        <For each={items}>
          {(item) => (
            <AccordionItem
              value={item.value}
              onOpenChange={(open, details) => {
                if (
                  !open &&
                  item.value === "security" &&
                  !window.confirm("Close the security settings?")
                ) {
                  details.cancel()
                }
              }}
            >
              <AccordionHeader>
                <AccordionTrigger>
                  {item.label}
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    aria-hidden="true"
                  >
                    <path d="m6 9 6 6 6-6" />
                  </svg>
                </AccordionTrigger>
              </AccordionHeader>
              <AccordionPanel>{item.content}</AccordionPanel>
            </AccordionItem>
          )}
        </For>
      </Accordion>
    </div>
  )
}

export { Example }
```

按 Security 展开它，然后再次按它。取消确认，Security 保持展开；确认后，这个小节就会收起。

## 保持挂载
收起的面板通常会卸载。给一个面板或整个手风琴加上 `keepMounted`，让它的内容隐藏着留在页面里。这样可以保留本地状态，比如输入框里的草稿。

```tsx title="keep-mounted.tsx"
import {
  Accordion,
  AccordionHeader,
  AccordionItem,
  AccordionPanel,
  AccordionTrigger,
} from "@ui-sdk/solid/accordion"
import { Field, FieldLabel } from "@ui-sdk/solid/field"
import { Textarea } from "@ui-sdk/solid/textarea"

function Example() {
  return (
    <Accordion defaultValue={["reply"]}>
      <AccordionItem value="reply">
        <AccordionHeader>
          <AccordionTrigger>
            Reply to this thread
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m6 9 6 6 6-6" />
            </svg>
          </AccordionTrigger>
        </AccordionHeader>
        <AccordionPanel keepMounted>
          <Field>
            <FieldLabel>Message</FieldLabel>
            <Textarea rows={3} placeholder="Write a reply…" />
          </Field>
        </AccordionPanel>
      </AccordionItem>
      <AccordionItem value="formatting">
        <AccordionHeader>
          <AccordionTrigger>
            Formatting
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m6 9 6 6 6-6" />
            </svg>
          </AccordionTrigger>
        </AccordionHeader>
        <AccordionPanel>
          <p>Use **bold**, _italics_ and `code`. Links paste as previews.</p>
        </AccordionPanel>
      </AccordionItem>
    </Accordion>
  )
}

export { Example }
```

写一段消息，切换到 Formatting，再回到 Reply to this thread。你的草稿还在。

## 在页面中查找
加上 `hiddenUntilFound`，让收起的面板仍能被浏览器的查找命令找到。一旦匹配，条目会立即展开，没有动画，[原因](https://ui-sdk.cn/docs/solid/components/accordion#reasons)是 `find-in-page`。

```tsx title="find-in-page.tsx"
import {
  Accordion,
  AccordionHeader,
  AccordionItem,
  AccordionPanel,
  AccordionTrigger,
} from "@ui-sdk/solid/accordion"
import { For } from "solid-js"

const items = [
  {
    value: "fruit",
    label: "Which fruit do you stock?",
    content: "Apples, pears, mangoes and, in summer, pineapple.",
  },
  {
    value: "organic",
    label: "Is it organic?",
    content: "Everything we stock is certified organic.",
  },
  {
    value: "delivery",
    label: "When do you deliver?",
    content: "Every weekday morning before 10.",
  },
]

function Example() {
  return (
    <Accordion hiddenUntilFound>
      <For each={items}>
        {(item) => (
          <AccordionItem value={item.value}>
            <AccordionHeader>
              <AccordionTrigger>
                {item.label}
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <path d="m6 9 6 6 6-6" />
                </svg>
              </AccordionTrigger>
            </AccordionHeader>
            <AccordionPanel>{item.content}</AccordionPanel>
          </AccordionItem>
        )}
      </For>
    </Accordion>
  )
}

export { Example }
```

用浏览器的查找命令搜索“pineapple”。收起的“Which fruit do you stock?”面板会展开，露出匹配的内容。

<span id="deep-links" />

指向收起面板内某个元素的链接也能把它露出来。给目标一个
`id`，再用哈希链接到它，比如 `href="#refund-timeline"`。

```tsx title="deep-link.tsx"
import {
  Accordion,
  AccordionHeader,
  AccordionItem,
  AccordionPanel,
  AccordionTrigger,
} from "@ui-sdk/solid/accordion"

function Example() {
  return (
    <div>
      <nav data-slot="controls" aria-label="Jump to">
        <a href="#refund-timeline">Jump to the refund timeline</a>
        <a href="#return-label">Print a return label</a>
      </nav>
      <Accordion hiddenUntilFound>
        <AccordionItem value="returns">
          <AccordionHeader>
            <AccordionTrigger>
              Returns
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                aria-hidden="true"
              >
                <path d="m6 9 6 6 6-6" />
              </svg>
            </AccordionTrigger>
          </AccordionHeader>
          <AccordionPanel>
            <div data-slot="stack">
              <p>
                Return any unused item in its original packaging within 30 days.
              </p>
              <p id="return-label">
                To print a return label, open the order and choose Return. The
                label is free.
              </p>
            </div>
          </AccordionPanel>
        </AccordionItem>
        <AccordionItem value="refunds">
          <AccordionHeader>
            <AccordionTrigger>
              Refunds
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                aria-hidden="true"
              >
                <path d="m6 9 6 6 6-6" />
              </svg>
            </AccordionTrigger>
          </AccordionHeader>
          <AccordionPanel>
            <div data-slot="stack">
              <p>Refunds go back to the card you paid with.</p>
              <p id="refund-timeline">
                Timeline: we inspect the item within 2 days of receiving it, and
                your bank shows the refund 5 to 7 business days later.
              </p>
            </div>
          </AccordionPanel>
        </AccordionItem>
        <AccordionItem value="exchanges">
          <AccordionHeader>
            <AccordionTrigger>
              Exchanges
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                aria-hidden="true"
              >
                <path d="m6 9 6 6 6-6" />
              </svg>
            </AccordionTrigger>
          </AccordionHeader>
          <AccordionPanel>
            <div data-slot="stack">
              <p>
                Start a return, choose Exchange and pick the new size. Shipping
                both ways is free.
              </p>
            </div>
          </AccordionPanel>
        </AccordionItem>
      </Accordion>
    </div>
  )
}

export { Example }
```

按 Jump to the refund timeline。收起的 Refunds 面板会展开，浏览器会移到链接指向的段落。

使用 `hiddenUntilFound` 时，Solid 的服务端渲染会写入 `hidden="until-found"`，所以收起的面板从一开始就能被找到。要处理初始 URL 哈希，请[显式打开该条目](https://ui-sdk.cn/docs/solid/components/accordion#url-hash)。

## 动画
每个部件都有一个 `data-slot`，比如 `accordion-panel`。面板把测量到的高度暴露为 `--accordion-panel-height`。用 `data-starting-style` 和 `data-ending-style` 把这个高度动画到零，或从零动画回来：

```css
[data-slot="accordion-panel"] {
  height: var(--accordion-panel-height);
  overflow: hidden;
  transition: height 0.15s;

  &:is([data-starting-style], [data-ending-style]) {
    height: 0;
  }
}
```

面板会保持挂载，直到它的退场动画结束。之后条目的 `onOpenChangeComplete` 带着展开状态运行。一开始就展开的面板会立即出现，没有动画，也没有完成回调。

```tsx title="animation.tsx"
import {
  Accordion,
  AccordionHeader,
  AccordionItem,
  AccordionPanel,
  AccordionTrigger,
} from "@ui-sdk/solid/accordion"
import { For } from "solid-js"

const items = [
  {
    value: "one",
    label: "Why animate the height?",
    content: "So the content below slides instead of jumping.",
  },
  {
    value: "two",
    label: "Where does the height come from?",
    content:
      "The panel measures itself and writes the result to a CSS variable while it animates.",
  },
  {
    value: "three",
    label: "Does it animate on first paint?",
    content: "No. Panels open on the server or on mount show at once.",
  },
]

function Example() {
  return (
    <Accordion defaultValue={["one"]}>
      <For each={items}>
        {(item) => (
          <AccordionItem value={item.value}>
            <AccordionHeader>
              <AccordionTrigger>
                {item.label}
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <path d="m6 9 6 6 6-6" />
                </svg>
              </AccordionTrigger>
            </AccordionHeader>
            <AccordionPanel>{item.content}</AccordionPanel>
          </AccordionItem>
        )}
      </For>
    </Accordion>
  )
}

export { Example }
```

展开或收起一个条目。它的面板会对高度做动画。

## 全部展开
在 `multiple` 下，控制器的 `openAll()` 会展开每个启用的条目。`closeAll()` 会收起每个允许收起的条目。[控制器](/docs/solid/controllers)说明了如何接入一个控制器。

```tsx title="expand-all.tsx"
import { createAccordionController } from "@ui-sdk/core/accordion"
import {
  Accordion,
  AccordionHeader,
  AccordionItem,
  AccordionPanel,
  AccordionTrigger,
} from "@ui-sdk/solid/accordion"
import { For } from "solid-js"

const weeks = [
  {
    value: "week-1",
    label: "Week 1: Foundations",
    content:
      "Set up your editor, meet the command line and write your first script.",
  },
  {
    value: "week-2",
    label: "Week 2: Data and types",
    content:
      "Strings, numbers, lists and objects, and how to tell them apart when a program runs.",
  },
  {
    value: "week-3",
    label: "Week 3: Control flow",
    content:
      "Conditions, loops and functions. The project this week is a small text adventure.",
  },
  {
    value: "week-4",
    label: "Week 4: Working with files",
    content:
      "Read and write files, parse CSV and JSON, and handle the errors that come with them.",
  },
  {
    value: "week-5",
    label: "Week 5: Final project",
    content:
      "Build a tool you'll use yourself, then present it to the group in a five-minute demo.",
  },
]

function Example() {
  const syllabus = createAccordionController()
  return (
    <div>
      <div data-slot="controls">
        <button type="button" onClick={() => syllabus.openAll()}>
          Expand all
        </button>
        <button type="button" onClick={() => syllabus.closeAll()}>
          Collapse all
        </button>
      </div>
      <div data-slot="scroll">
        <Accordion multiple controller={syllabus}>
          <For each={weeks}>{(week) => <Week week={week} />}</For>
        </Accordion>
      </div>
    </div>
  )
}

function Week(props: { week: (typeof weeks)[number] }) {
  let item: HTMLDivElement | undefined
  let pressed = false

  return (
    <AccordionItem
      ref={item}
      value={props.week.value}
      onOpenChange={(open, details) => {
        pressed = open && details.reason === "trigger-press"
      }}
      onOpenChangeComplete={(open) => {
        if (open && pressed) {
          item?.scrollIntoView({ block: "nearest", behavior: "smooth" })
        }
      }}
    >
      <AccordionHeader>
        <AccordionTrigger>
          {props.week.label}
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="m6 9 6 6 6-6" />
          </svg>
        </AccordionTrigger>
      </AccordionHeader>
      <AccordionPanel>{props.week.content}</AccordionPanel>
    </AccordionItem>
  )
}

export { Example }
```

按 Expand all 或 Collapse all。展开靠近底部的某一周，它的面板展开后会滚动到可见区域。

## 嵌套
当一个内容小节还有自己可展开的小节时，在面板里放另一个手风琴。每个手风琴各自管理自己的条目。内层标题的层级要比外层标题低。

```tsx title="nested.tsx"
import {
  Accordion,
  AccordionHeader,
  AccordionItem,
  AccordionPanel,
  AccordionTrigger,
} from "@ui-sdk/solid/accordion"
import { For } from "solid-js"

const sections: {
  value: string
  label: string
  content?: string
  topics?: { value: string; label: string; content: string }[]
}[] = [
  {
    value: "profile",
    label: "Profile",
    content: "Your name, photo and the email address people see.",
  },
  {
    value: "notifications",
    label: "Notifications",
    topics: [
      {
        value: "email",
        label: "Email",
        content: "A weekly digest, and mentions as they happen.",
      },
      {
        value: "push",
        label: "Push",
        content: "Direct messages and replies to your comments.",
      },
    ],
  },
  {
    value: "billing",
    label: "Billing",
    topics: [
      {
        value: "payment",
        label: "Payment methods",
        content: "A Visa card ending in 4242, used for every renewal.",
      },
      {
        value: "invoices",
        label: "Invoices",
        content: "Download a PDF of any invoice from the last two years.",
      },
    ],
  },
]

function Example() {
  return (
    <Accordion defaultValue={["notifications"]}>
      <For each={sections}>
        {(section) => (
          <AccordionItem value={section.value}>
            <AccordionHeader>
              <AccordionTrigger>
                {section.label}
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <path d="m6 9 6 6 6-6" />
                </svg>
              </AccordionTrigger>
            </AccordionHeader>
            <AccordionPanel>
              {section.topics ? (
                <Accordion multiple>
                  <For each={section.topics}>
                    {(topic) => (
                      <AccordionItem value={topic.value}>
                        <AccordionHeader render={(props) => <h4 {...props} />}>
                          <AccordionTrigger>
                            {topic.label}
                            <svg
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              stroke-width="2"
                              stroke-linecap="round"
                              stroke-linejoin="round"
                              aria-hidden="true"
                            >
                              <path d="m6 9 6 6 6-6" />
                            </svg>
                          </AccordionTrigger>
                        </AccordionHeader>
                        <AccordionPanel>{topic.content}</AccordionPanel>
                      </AccordionItem>
                    )}
                  </For>
                </Accordion>
              ) : (
                <div>{section.content}</div>
              )}
            </AccordionPanel>
          </AccordionItem>
        )}
      </For>
    </Accordion>
  )
}

export { Example }
```

展开 Billing，再展开其中的 Invoices。内层手风琴发生变化，Billing 不会收起。

## FAQ 搜索
<span id="faq-with-search" />

把搜索框和受控手风琴结合起来：筛选问题，并把 `value`
设为匹配的条目。示例还会高亮匹配内容，并在搜索期间保持触发器可用。

```tsx title="search.tsx"
import {
  Accordion,
  AccordionHeader,
  AccordionItem,
  AccordionPanel,
  AccordionTrigger,
} from "@ui-sdk/solid/accordion"
import { createSignal, For } from "solid-js"

const faq = [
  {
    value: "returns",
    question: "What is your return policy?",
    answer:
      "Return any unused item within 30 days. Once it reaches us, your refund is on its way.",
  },
  {
    value: "refunds",
    question: "How long do refunds take?",
    answer:
      "Refunds reach your card within 5 to 7 business days after we receive the item.",
  },
  {
    value: "shipping",
    question: "Do you ship internationally?",
    answer:
      "We ship to 40 countries. Duties are included in the price at checkout.",
  },
  {
    value: "tracking",
    question: "How do I track my order?",
    answer:
      "Every shipping email has a tracking link. You'll also find it under Orders.",
  },
  {
    value: "exchange",
    question: "Can I exchange an item for another size?",
    answer:
      "Yes. Start a return, choose Exchange and pick the new size. Shipping is free.",
  },
  {
    value: "gift",
    question: "Can I send an order as a gift?",
    answer:
      "Add a gift note at checkout and we'll leave the prices off the packing slip.",
  },
]

function matches(question: (typeof faq)[number], query: string) {
  const search = query.trim().toLowerCase()
  return (
    !search ||
    question.question.toLowerCase().includes(search) ||
    question.answer.toLowerCase().includes(search)
  )
}

function highlight(text: string, query: string) {
  const search = query.trim().toLowerCase()
  if (!search) {
    return [{ text, match: false }]
  }
  const parts: { text: string; match: boolean }[] = []
  let start = 0
  for (let index = text.toLowerCase().indexOf(search); index !== -1;) {
    if (index > start) {
      parts.push({ text: text.slice(start, index), match: false })
    }
    parts.push({ text: text.slice(index, index + search.length), match: true })
    start = index + search.length
    index = text.toLowerCase().indexOf(search, start)
  }
  if (start < text.length) {
    parts.push({ text: text.slice(start), match: false })
  }
  return parts
}

function Highlight(props: { text: string; query: string }) {
  return (
    <For each={highlight(props.text, props.query)}>
      {(part) => (part.match ? <mark>{part.text}</mark> : part.text)}
    </For>
  )
}

function Example() {
  const [query, setQuery] = createSignal("")
  const [value, setValue] = createSignal<string[]>([])
  const results = () => faq.filter((question) => matches(question, query()))

  return (
    <div>
      <div data-slot="controls">
        <input
          type="search"
          aria-label="Search questions"
          placeholder="Search questions…"
          value={query()}
          onInput={(event) => {
            const next = event.currentTarget.value
            setQuery(next)
            setValue(
              next.trim()
                ? faq
                    .filter((question) => matches(question, next))
                    .map((question) => question.value)
                : []
            )
          }}
        />
      </div>
      <Accordion multiple value={value()} onValueChange={setValue}>
        <For each={results()}>
          {(question) => (
            <AccordionItem value={question.value}>
              <AccordionHeader>
                <AccordionTrigger>
                  <span>
                    <Highlight text={question.question} query={query()} />
                  </span>
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    aria-hidden="true"
                  >
                    <path d="m6 9 6 6 6-6" />
                  </svg>
                </AccordionTrigger>
              </AccordionHeader>
              <AccordionPanel>
                <Highlight text={question.answer} query={query()} />
              </AccordionPanel>
            </AccordionItem>
          )}
        </For>
      </Accordion>
      <p data-slot="hint" role="status">
        {results().length === 0 ? `No questions match “${query()}”.` : ""}
      </p>
    </div>
  )
}

export { Example }
```

搜索“refund”，显示并展开匹配的回答。搜索“zzz”看看空结果，然后清空搜索，恢复所有问题。

## URL 哈希
<span id="open-the-item-in-the-url-hash" />

哈希也可以命名条目的 `value`，而不是面板里的某个元素。在挂载后和 `hashchange`
时读取它，然后通过控制器展开并聚焦匹配的条目：

```ts
const value = decodeURIComponent(location.hash.slice(1))
if (items.some((item) => item.value === value)) {
  accordion.open(value)
  accordion.focus(value)
}
```

先拿这个值和你的条目比对。即使没有条目渲染某个值，控制器也可以持有它。组件卸载时移除 `hashchange` 监听器。

## 查询字符串
<span id="keep-open-items-in-the-query-string" />

当多个条目需要可分享时，用 `open`
查询参数。在服务器上从路由器读取初始值，再把接受的变更写回 URL：

```ts
function saveOpenItems(value: string[]) {
  const url = new URL(location.href)
  url.searchParams.delete("open")
  for (const item of value) url.searchParams.append("open", item)
  history.replaceState(null, "", url)
}
```

更新状态后从 `onValueChange` 调用它。如果你的应用已经有路由器，就改用它的导航 API。

## 滚动到可见区域
<span id="scroll-an-item-into-view" />

在 `onOpenChangeComplete`
之后滚动，此时面板已有完整高度。在 `onOpenChange`
里滚动会在面板展开前测量它。[全部展开示例](https://ui-sdk.cn/docs/solid/components/accordion#expand-all)展示了完整的设置，并且只在有人展开单个条目时滚动。

## 自定义渲染
<span id="render-functions" />

用 `render`
选择另一个标题层级或元素。[部件与组合](https://ui-sdk.cn/docs/solid/parts-and-composition#choose-the-element)涵盖了自定义元素和部件状态。Accordion
的状态列在[状态](https://ui-sdk.cn/docs/solid/components/accordion#state)下。

```tsx title="render.tsx"
import {
  Accordion,
  AccordionHeader,
  AccordionItem,
  AccordionPanel,
  AccordionTrigger,
} from "@ui-sdk/solid/accordion"
import { For } from "solid-js"

const steps = [
  {
    value: "install",
    label: "Install the package",
    content: "Add it with your package manager. It has no dependencies.",
  },
  {
    value: "import",
    label: "Import the parts",
    content: "Import the accordion parts you need from the package.",
  },
  {
    value: "style",
    label: "Style it",
    content: "Every part renders its state as data attributes you can style.",
  },
]

export function Example() {
  return (
    <Accordion multiple defaultValue={["install"]}>
      <For each={steps}>
        {(step) => (
          <AccordionItem value={step.value}>
            <AccordionHeader render={(props) => <h4 {...props} />}>
              <AccordionTrigger
                render={(props, state) => (
                  <button {...props}>
                    {state.index >= 0 && (
                      <span data-slot="hint" aria-hidden="true">
                        {String(state.index + 1).padStart(2, "0")}
                      </span>
                    )}
                    <span>{props.children}</span>
                    <span data-slot="hint" aria-hidden="true">
                      {state.open ? "Hide" : "Show"}
                    </span>
                  </button>
                )}
              >
                {step.label}
              </AccordionTrigger>
            </AccordionHeader>
            <AccordionPanel>{step.content}</AccordionPanel>
          </AccordionItem>
        )}
      </For>
    </Accordion>
  )
}
```

每个步骤都是一个 h4，带有编号和一个跟随展开状态的 Show 或 Hide 提示。展开 Import the parts，看它更新。

## 样式
用下面的属性为部件设置样式。它会在面板展开时转动箭头，在从右到左（RTL）布局里用 `:dir(rtl)` 镜像箭头，并把禁用的触发器变暗：

```css
[data-slot="accordion-trigger"] {
  & > svg {
    rotate: -90deg;

    &:dir(rtl) {
      rotate: 90deg;
    }
  }

  &[data-open] > svg {
    rotate: 0deg;
  }

  &[data-disabled] {
    color: gray;
  }
}
```

### AccordionPanel
- `--accordion-panel-height`: The panel's content height in pixels while it animates, auto once open and 0px while closed.
- `--accordion-panel-width`: The panel's content width, the same way. For accordions that open sideways.

## 数据属性
### Accordion
`[data-slot="accordion"]`

- `data-disabled`: Present when the whole accordion is disabled.

### AccordionItem
`[data-slot="accordion-item"]`

- `data-open`: Present while the item is open.
- `data-closed`: Present while the item is closed, including while its panel animates out.
- `data-disabled`: Present when the item can't open or close.

### AccordionHeader
`[data-slot="accordion-header"]`

- `data-open`: Present while the item is open.
- `data-closed`: Present while the item is closed, including while its panel animates out.
- `data-disabled`: Present when the item can't open or close.

### AccordionTrigger
`[data-slot="accordion-trigger"]`

- `data-open`: Present while the item is open.
- `data-closed`: Present while the item is closed, including while its panel animates out.
- `data-disabled`: Present when the item can't open or close.

### AccordionPanel
`[data-slot="accordion-panel"]`

- `data-open`: Present while the item is open.
- `data-closed`: Present while the item is closed, including while its panel animates out.
- `data-disabled`: Present when the item can't open or close.
- `data-starting-style`: Present for a panel's first frame. Style the state you animate from.
- `data-ending-style`: Present while a panel animates closed. Style the state you animate to.

## API 参考
属性和回调与下面相同，作为 Solid props 传入。标题、触发器和面板从条目那里取得它的 `value`。

### Accordion
- `value?` (`T[]`): The open items' values. Pass it to control the accordion.
- `defaultValue?` (`T[]`): The items open at first, when uncontrolled.
- `onValueChange?` (`((value: T[], details: ChangeDetails<AccordionValueChangeReason>) => void)`): Runs when items want to open or close. `details.reason` says why, and `details.cancel()` stops it.
- `multiple?` (`boolean`): Whether several items can be open at once. Otherwise opening one closes the others.
- `collapsible?` (`boolean`): Whether the open item can close when only one may be open. With `false`, one item always stays open and its trigger reports it can't be pressed.
- `disabled?` (`boolean`): Stops every item from opening or closing. Triggers stay focusable.
- `keepMounted?` (`boolean`): Whether closed panels stay in the page, hidden.
- `hiddenUntilFound?` (`boolean`): Keeps closed panels in the page as `hidden="until-found"`, so the browser's find in page can match their text and open them.
- `controller?` (`object`): Opens and closes items from anywhere. Create one with `createAccordionController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### AccordionItem
- `disabled?` (`boolean`): Stops the item from opening or closing. Its trigger stays focusable.
- `onOpenChange?` (`((open: boolean, details: ChangeDetails<AccordionValueChangeReason>) => void)`): Runs before the item opens or closes, before the accordion's `onValueChange`. `details.cancel()` stops it.
- `onOpenChangeComplete?` (`((open: boolean) => void)`): Runs once the item's panel has finished opening or closing, after any animation.
- `value?` (`T`): Identifies the item. The accordion's value lists the open items' values. Defaults to a generated id.

### AccordionHeader
标题部件没有自己的选项，只有它渲染出的元素的 props。

### AccordionTrigger
- `disabled?` (`boolean`): Stops this trigger from opening or closing the item. It stays focusable.

### AccordionPanel
- `keepMounted?` (`boolean`): Whether the panel stays in the page, hidden, while closed. Overrides the accordion's.
- `hiddenUntilFound?` (`boolean`): Whether the panel stays findable with `hidden="until-found"` while closed. Overrides the accordion's.
### 状态
渲染函数、基于状态的类名和槽位按部件分别收到什么。

`Accordion`：

- `value` (`T[]`): The open items' values.
- `disabled` (`boolean`): Whether the whole accordion is disabled, by its `disabled` option or a disabled fieldset around it.
- `multiple` (`boolean`): Whether several items can be open at once.

`AccordionItem`、`AccordionHeader`、`AccordionTrigger` 和 `AccordionPanel`：

- `open` (`boolean`): Whether the accordion's `value` holds this item's value.
- `disabled` (`boolean`): Whether the item can't open or close.
- `index` (`number`): The item's position among the accordion's items, from 0. -1 until it's in the page.

### 原因
`details.reason` 说明条目为什么展开或收起，用于 `onValueChange` 和每个条目的 `onOpenChange`。

- `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`.
- `find-in-page` (`Event`): The browser's find in page matched hidden content.
- `imperative` (`none`): A controller or `api` call.

### 控制器
用 `createAccordionController()` 创建一个，并作为 `controller` 传入。

每个写入方法都接受可选的 `{ reason, event }`，像按压一样运行条目和手风琴的回调，并在变更被取消或没有任何效果时返回 `false`。

- `getValue()` (`() => T[]`): The open items' values.
- `setValue(value, options?)` (`(value: T[], options?: AccordionChangeOptions | undefined) => boolean`): Sets the open items. Only the first counts unless `multiple` is set. Returns false when canceled.
- `isOpen(value)` (`(value: T) => boolean`): Whether an item is open.
- `open(value, options?)` (`(value: T, options?: AccordionChangeOptions | undefined) => boolean`): Opens an item. With one item open at a time, closes the others.
- `close(value, options?)` (`(value: T, options?: AccordionChangeOptions | undefined) => boolean`): Closes an item, unless it's the one item that must stay open.
- `toggle(value, options?)` (`(value: T, options?: AccordionChangeOptions | undefined) => boolean`): Opens a closed item, or closes an open one.
- `openAll(options?)` (`(options?: AccordionChangeOptions | undefined) => boolean`): Opens every enabled item. Only when `multiple` is set.
- `closeAll(options?)` (`(options?: AccordionChangeOptions | undefined) => boolean`): Closes every item that may close.
- `focus(value?)` (`(value?: T | undefined) => void`): Moves focus to an item's trigger, or the first trigger.

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

| Prop                   | 所属部件        | 收到                                                   |
| ---------------------- | --------------- | ------------------------------------------------------ |
| `onValueChange`        | `Accordion`     | `(value, details)`：已展开的条目，以及[原因](https://ui-sdk.cn/docs/solid/components/accordion#reasons) |
| `onOpenChange`         | `AccordionItem` | `(open, details)`，在 `onValueChange` 之前             |
| `onOpenChangeComplete` | `AccordionItem` | `(open)`，在面板动画之后                               |

## 无障碍
手风琴遵循 [WAI-ARIA 手风琴模式](https://www.w3.org/WAI/ARIA/apg/patterns/accordion/)。下面每一行都是一个自动化测试。

**Expanding and collapsing**

- The default item is expanded and shows its panel.
- Clicking a collapsed trigger expands it and collapses the open one.
- Clicking an expanded trigger collapses it.
- Clicking a disabled trigger does nothing.
- A change can be canceled.
- Without a default value, every item starts collapsed.
- A default value can expand several items.

**Multiple**

- Items expand and collapse independently.
- Every item can be expanded at once.

**Disabled**

- A disabled item's trigger is marked disabled and stays focusable.
- A disabled accordion disables every trigger.

**Keyboard**

- Tab moves through every trigger in order, disabled ones included.
- Enter toggles the focused trigger's panel.
- Space toggles the focused trigger's panel.
- Enter on a disabled trigger does nothing.
- Tab moves from an expanded trigger into its panel.
- Keys pressed in quick succession are never lost.
- Arrow keys leave focus where it is.

**Structure**

- Each trigger sits in a heading.
- The trigger controls its panel, and the panel is labelled by its trigger.

**Mounting**

- Collapsed panels leave the page by default.
- With keepMounted, collapsed panels stay in the page, hidden.
- With keepMounted, a class that sets display doesn't show collapsed panels.
- With hiddenUntilFound, collapsed panels stay findable.
- Finding text in a collapsed panel expands it.
- Following a link into a collapsed panel expands it.
- The browser's own find expands a collapsed panel.

Runs in React、Vue 和 web components.

在模式基线之外：

**Enhancements**

- With collapsible off, the open trigger is marked disabled and stays open.
- Closing a panel that holds focus moves focus to its trigger.
- A canceled find in page keeps the panel hidden until found.
- An infinite exit animation still unmounts the panel.
- A controller expands and collapses items from anywhere.
- An item's onOpenChangeComplete runs once its panel has finished animating.
- Find in page opens a panel at once, without an animation.

Runs in React、Vue 和 web components.

每个面板都是一个由触发器命名的区域，所以屏幕阅读器可以把展开的面板列为地标。一次展开很多面板时，比如在 `multiple` 下使用 Expand all，请让条目数量保持适度，好让这个列表保持简短。

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

- Announcements while using the accordion with a keyboard.

Runs in React、Vue 和 web components.
