# ChoicePicker

> 在桌面浮层与移动端底部面板中提供一致的单选、多选和搜索体验。

网页来源：/components/choice-picker

版本：@quirekit/ui 0.3.1；源码修订：d79a6b48d00e+worktree。此文档对应当前源码构建，接入方式以开始使用为准。

接入前置：[开始使用](/raw/components/getting-started.md)（Vue、样式、主题与图标 Provider）。

ChoicePicker 将选项、搜索和确认组合成一个选择面板。桌面使用浮层，窄屏使用底部面板；选项数据与已保存值共享。

## 单选

通过 `items` 提供稳定的 `value`、可读的 `label` 和可选说明。`v-model` 使用值数组，单选保存一个值，空数组表示未选择。默认在激活选项后保存并关闭，方向键移动高亮。

### 示例：choice-picker/basic

文件：`basic.vue`

```vue
<script setup lang="ts">
import { computed, ref } from "vue";
import type { QuireKitChoicePickerItem } from "@quirekit/ui";
import { QuireButton, QuireChoicePicker } from "@quirekit/ui/vue";

const value = ref<readonly string[]>(["comfortable"]);
const items: readonly QuireKitChoicePickerItem[] = [
  { value: "compact", label: "紧凑", description: "在同一屏幕中展示更多内容" },
  { value: "comfortable", label: "舒适", description: "为文字与操作保留适当间距" },
  { value: "relaxed", label: "宽松", description: "适合触摸操作与长时间阅读" },
  { value: "custom", label: "自定义", description: "当前空间暂未开放", disabled: true }
];
const summary = computed(() => items.find(item => item.value === value.value[0])?.label ?? "未选择");
</script>

<template>
  <div class="grid justify-items-start gap-5 p-qk-surface">
    <QuireChoicePicker v-model="value" title="显示密度" description="选择适合当前屏幕的内容间距。" :items="items">
      <template #trigger><QuireButton variant="outline">显示密度：{{ summary }}</QuireButton></template>
    </QuireChoicePicker>
    <p role="status" class="m-0 text-qk-helper text-qk-text-secondary">当前密度：{{ summary }}</p>
  </div>
</template>
```

## 搜索与多选

`selectionMode="multiple"` 使用草稿选择，点击确认后统一保存。取消会丢弃本次修改。单选也可以使用 `commitMode="explicit"` 提供确认步骤。

开启 `searchable` 显示搜索框。搜索匹配名称和 `keywords`，过滤结果保留已选值。通过 `empty` 插槽提供适合当前场景的空结果内容。

### 示例：choice-picker/multiple

文件：`multiple.vue`

```vue
<script setup lang="ts">
import { computed, ref } from "vue";
import type { QuireKitChoicePickerItem } from "@quirekit/ui";
import { QuireButton, QuireChoicePicker } from "@quirekit/ui/vue";

const value = ref<readonly string[]>(["design"]);
const items: readonly QuireKitChoicePickerItem[] = [
  { value: "design", label: "设计", description: "视觉、交互与体验", keywords: ["design"] },
  { value: "research", label: "研究", description: "访谈与调研结论", keywords: ["research"] },
  { value: "engineering", label: "研发", description: "技术实现与协作", keywords: ["engineering"] },
  { value: "marketing", label: "市场", description: "内容推广与活动", keywords: ["marketing"] },
  { value: "archive", label: "归档", description: "当前不可添加", disabled: true }
];
const summary = computed(() => value.value.map(selected => items.find(item => item.value === selected)?.label ?? selected).join("、") || "未选择");
</script>

<template>
  <div class="grid justify-items-start gap-5 p-qk-surface">
    <QuireChoicePicker v-model="value" title="选择标签" description="可选择多个标签，完成后统一保存。"
      :items="items" selection-mode="multiple" searchable confirm-label="保存标签">
      <template #trigger><QuireButton color="primary" variant="solid">编辑标签</QuireButton></template>
      <template #empty><p class="m-0 py-8 text-center text-qk-text-secondary">没有匹配的标签，试试其他关键词。</p></template>
    </QuireChoicePicker>
    <p role="status" class="m-0 text-qk-helper text-qk-text-secondary">已保存：{{ summary }}</p>
  </div>
</template>
```

## 提交与重试

`submit` 接收完整候选值、上次保存值以及 `signal`。返回 Promise 时，组件保留草稿并防止重复提交；成功后更新模型并触发 `commit`，失败后显示 `errorText` 并允许重试。

下面的资料目录包含 30 个可搜索选项，首次保存会模拟失败，再次提交即可完成。处理期间保留搜索框和已选草稿；失败后点击“重试”继续。移动端的标题、搜索与操作区保持可见，长选项列表在正文区域内滚动。

### 示例：choice-picker/async

文件：`async.vue`

```vue
<script setup lang="ts">
import { computed, ref } from "vue";
import type { QuireKitChoicePickerItem, QuireKitChoiceSubmitRequest } from "@quirekit/ui";
import { QuireButton, QuireChoicePicker } from "@quirekit/ui/vue";

const value = ref<readonly string[]>(["resource-01"]);
const attempts = ref(0);
const completed = ref(0);
const items: readonly QuireKitChoicePickerItem[] = Array.from({ length: 30 }, (_, index) => {
  const number = String(index + 1).padStart(2, "0");
  return { value: `resource-${number}`, label: `资料 ${number}`, description: "加入本次资料清单，完成后统一保存。", keywords: [number, `resource ${number}`] };
});
const summary = computed(() => value.value.map(selected => items.find(item => item.value === selected)?.label ?? selected).join("、") || "未选择");

/**
 * Simulates a cancellable local submission with one failure followed by successful retry.
 * @param request - Selection snapshot and the owning task's cancellation signal.
 * @returns Completion after a short local delay; the first accepted attempt rejects.
 */
async function save(request: QuireKitChoiceSubmitRequest): Promise<void> {
  const attempt = ++attempts.value;
  await new Promise<void>((resolve, reject) => {
    const timer = setTimeout(() => {
      request.signal.removeEventListener("abort", cancel);
      resolve();
    }, 300);
    /** Cancels the unfinished local delay when the task no longer owns this request. */
    function cancel(): void {
      clearTimeout(timer);
      reject(new DOMException("Selection cancelled", "AbortError"));
    }
    if (request.signal.aborted) cancel();
    else request.signal.addEventListener("abort", cancel, { once: true });
  });
  if (request.signal.aborted) return;
  if (attempt === 1) throw new Error("Demonstrated selection failure");
  completed.value += 1;
}
</script>

<template>
  <div class="grid justify-items-start gap-4 p-qk-surface">
    <QuireChoicePicker v-model="value" title="选择资料" description="搜索并勾选资料，保存后统一更新清单。"
      :items="items" selection-mode="multiple" commit-mode="explicit" searchable confirm-label="保存资料"
      :submit="save" error-text="暂时未能保存，已选资料已保留，请重试。">
      <template #trigger><QuireButton variant="outline">编辑资料清单</QuireButton></template>
      <template #empty><p class="m-0 py-8 text-center text-qk-text-secondary">没有匹配的资料，试试编号 01–30。</p></template>
    </QuireChoicePicker>
    <p role="status" class="m-0 text-qk-helper text-qk-text-secondary">已保存：{{ summary }}</p>
    <p class="m-0 text-qk-helper text-qk-text-secondary">尝试 {{ attempts }} 次 · 已完成 {{ completed }} 次</p>
  </div>
</template>
```

## 远程搜索

远程搜索使用 `filter="none"`、`searchRequest`、`loading` 与 `searchError`。每个搜索请求携带独立的取消信号，宿主使用最新查询结果更新 `items`。暂时不在结果中的已选项仍然保留。

### 示例：choice-picker/remote

文件：`remote.vue`

```vue
<script setup lang="ts">
import { ref } from "vue";
import type { QuireKitTaskSearchRequest } from "@quirekit/ui";
import { QuireButton, QuireChoicePicker, QuireSwitch } from "@quirekit/ui/vue";
const value = ref<readonly string[]>([]);
const fail = ref(false);
const loading = ref(false);
const error = ref<string>();
const catalog = [
  { value: "design", label: "设计团队" },
  { value: "engineering", label: "研发团队" },
  { value: "support", label: "支持团队" }
];
const items = ref(catalog);
/** 模拟远程查询；新输入与关闭面板会取消旧请求。
 * @param request - 查询文本及请求取消信号。
 * @returns 当前结果应用或旧请求退出。
 */
async function search(request: QuireKitTaskSearchRequest): Promise<void> {
  loading.value = true;
  error.value = undefined;
  await new Promise<void>((resolve) => setTimeout(resolve, 300));
  if (request.signal.aborted) return;
  loading.value = false;
  if (fail.value) {
    error.value = "查询失败，关闭模拟失败后重新输入。";
    items.value = [];
    return;
  }
  items.value = catalog.filter((item) => item.label.includes(request.query));
}
</script>

<template>
  <div class="grid min-w-0 justify-items-start gap-4 p-qk-surface">
    <QuireSwitch v-model:checked="fail" label="模拟查询失败" />
    <QuireChoicePicker
      v-model="value"
      title="查找团队"
      :items="items"
      searchable
      filter="none"
      :loading="loading"
      :search-error="error"
      @search-request="search"
      @update:open="loading = false"
    >
      <template #trigger><QuireButton>打开团队搜索</QuireButton></template>
    </QuireChoicePicker>
    <output>已选择：{{ value.join("、") || "无" }}</output>
  </div>
</template>
```

## 呈现与键盘

`presentation="auto"` 在小于 768px 时使用底部面板，也可固定为 `desktop` 或 `bottom`。已打开的面板保持当前呈现方式。

选项列表使用方向键移动高亮，Enter 或 Space 选择。Tab 在搜索、列表和操作按钮间移动。Escape 或取消结束选择，焦点返回打开按钮。

## API

### QuireChoicePicker

#### Props

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| title | 是 | — | Visible task title and accessible dialog name. |
| items | 是 | — | Known candidates; remote filtering never implicitly removes selected values. |
| selectionMode | 否 | — | Single selection is the default.<br>Enables multiple draft selections. |
| commitMode | 否 | — | Immediate by default; explicit retains a draft until confirmation.<br>Multiple selection cannot commit on each activation. |
| description | 否 | — | Optional task explanation. |
| modelValue | 否 | undefined | Controlled selection; undefined enables local ownership. |
| defaultValue | 否 | — | Initial uncontrolled selection. |
| presentation | 否 | "auto" | Opening-time presentation strategy. |
| open | 否 | undefined | Controlled open request; explicit false takes priority over defaultOpen. |
| defaultOpen | 否 | false | Initial uncontrolled open request. |
| disabled | 否 | false | Prevents opening and ends any active selection session. |
| searchable | 否 | false | Shows a separately labelled search input. |
| query | 否 | undefined | Controlled query; undefined enables local session ownership. |
| defaultQuery | 否 | — | Initial query for each new uncontrolled session. |
| filter | 否 | — | Local matching strategy; none delegates matching to the host. |
| loading | 否 | false | Host-owned search progress; does not start a request automatically. |
| searchError | 否 | — | Host-owned readable search failure. |
| confirmLabel | 否 | — | Task-specific confirmation action name; defaults to the language pack's generic text. |
| errorText | 否 | — | Task-specific submission failure message; defaults to the language pack's generic text. |
| finalFocusEl | 否 | — | Explicit final focus destination; otherwise uses the stable trigger. |
| onCloseRequest | 否 | — | Synchronous cancellable user-close callback. |
| submit | 否 | — | Sole business submission entry; commit only reports success. |

**title**

```ts
string
```

**items**

```ts
readonly QuireKitChoicePickerItem[]
```

```ts
readonly ({
  /** Non-empty identity unique in the current collection. */
  value: string;
  /** Visible and accessible item name. */
  label: string;
  /** Optional secondary explanation. */
  description?: undefined | string;
  /** Prevents adding this item while retaining existing committed values. */
  disabled?: boolean | undefined;
  /** Optional visible group name. */
  group?: string | undefined;
  /** Additional terms consumed by local filtering. */
  keywords?: undefined | readonly (string)[];
})[]
```

**selectionMode**

```ts
"single" | "multiple" | undefined
```

```ts
undefined | "single" | "multiple"
```

**commitMode**

```ts
"immediate" | "explicit" | undefined
```

```ts
undefined | "immediate" | "explicit"
```

**description**

```ts
string | undefined
```

```ts
undefined | string
```

**modelValue**

```ts
readonly string[] | undefined
```

```ts
undefined | readonly (string)[]
```

**defaultValue**

```ts
readonly string[] | undefined
```

```ts
undefined | readonly (string)[]
```

**presentation**

```ts
QuireKitTaskPresentation | undefined
```

```ts
undefined | "auto" | "desktop" | "bottom"
```

**open**

```ts
boolean | undefined
```

**defaultOpen**

```ts
boolean | undefined
```

**disabled**

```ts
boolean | undefined
```

**searchable**

```ts
boolean | undefined
```

**query**

```ts
string | undefined
```

```ts
undefined | string
```

**defaultQuery**

```ts
string | undefined
```

```ts
undefined | string
```

**filter**

```ts
"contains" | "startsWith" | "none" | undefined
```

```ts
undefined | "contains" | "startsWith" | "none"
```

**loading**

```ts
boolean | undefined
```

**searchError**

```ts
string | undefined
```

```ts
undefined | string
```

**confirmLabel**

```ts
string | undefined
```

```ts
undefined | string
```

**errorText**

```ts
string | undefined
```

```ts
undefined | string
```

**finalFocusEl**

```ts
(() => HTMLElement | null) | undefined
```

```ts
undefined | { (): HTMLElement | null; }
```

**onCloseRequest**

```ts
((request: QuireKitTaskCloseRequest) => void) | undefined
```

```ts
undefined | { (request: QuireKitTaskCloseRequest): void; }
```

**submit**

```ts
((request: QuireKitChoiceSubmitRequest) => void | Promise<void>) | undefined
```

```ts
undefined | { (request: QuireKitChoiceSubmitRequest): void | Promise<void>; }
```

#### Events

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| update\:modelValue | 否 | — |  |
| update\:open | 否 | — |  |
| openChange | 否 | — |  |
| cancel | 否 | — |  |
| update\:query | 否 | — |  |
| commit | 否 | — |  |
| error | 否 | — |  |
| searchRequest | 否 | — |  |

**update:modelValue**

```ts
[value: readonly string[]]
```

**update:open**

```ts
[value: boolean]
```

**openChange**

```ts
[value: boolean]
```

**cancel**

```ts
[details: { readonly reason: QuireKitTaskCancelReason; readonly sessionId: string; }]
```

**update:query**

```ts
[value: string]
```

**commit**

```ts
[request: QuireKitChoiceSubmitRequest]
```

**error**

```ts
[details: { readonly error: unknown; readonly request: QuireKitChoiceSubmitRequest; }]
```

**searchRequest**

```ts
[request: QuireKitTaskSearchRequest]
```

#### Slots

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| trigger | 否 | — | One real button, with task ARIA and native behavior merged in place. |
| item | 否 | — | Replaces candidate decoration while Listbox retains option semantics. |
| empty | 否 | — | Empty result content, optionally including a host recovery action. |
| loading | 否 | — | Loading decoration without replacing the list or query input. |
| status | 否 | — | Replaces the readable message in the single live status lane. |

**trigger**

```ts
{ open: boolean; disabled: boolean; summary: string; presentation: QuireKitResolvedTaskPresentation | undefined; }
```

```ts
{
  open: boolean;
  disabled: boolean;
  summary: string;
  presentation: undefined | "desktop" | "bottom";
}
```

**item**

```ts
QuireKitChoicePickerItemSlotProps
```

```ts
{
  /** Current known item. */
  item: {
    /** Non-empty identity unique in the current collection. */
    value: string;
    /** Visible and accessible item name. */
    label: string;
    /** Optional secondary explanation. */
    description?: undefined | string;
    /** Prevents adding this item while retaining existing committed values. */
    disabled?: boolean | undefined;
    /** Optional visible group name. */
    group?: string | undefined;
    /** Additional terms consumed by local filtering. */
    keywords?: undefined | readonly (string)[];
  };
  /** Whether the item belongs to the current draft. */
  selected: boolean;
  /** Keyboard highlight, independent from selection. */
  highlighted: boolean;
  /** Whether the item is unavailable for activation. */
  disabled: boolean;
}
```

**empty**

```ts
any
```

**loading**

```ts
any
```

**status**

```ts
{ busy: boolean; error: string | undefined; selectedCount: number; }
```

```ts
{
  busy: boolean;
  error: undefined | string;
  selectedCount: number;
}
```

#### 公开实例成员

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| requestClose | 否 | — |  |

**requestClose**

```ts
(reason?: QuireKitTaskCloseReason | undefined) => boolean
```

```ts
{ (reason?: QuireKitTaskCloseReason | undefined): boolean; }
```

#### 相关类型

```ts
type QuireKitChoicePickerItem = {
  /** Non-empty identity unique in the current collection. */
  value: string;
  /** Visible and accessible item name. */
  label: string;
  /** Optional secondary explanation. */
  description?: undefined | string;
  /** Prevents adding this item while retaining existing committed values. */
  disabled?: boolean | undefined;
  /** Optional visible group name. */
  group?: string | undefined;
  /** Additional terms consumed by local filtering. */
  keywords?: undefined | readonly (string)[];
};
```

```ts
type QuireKitChoicePickerItemSlotProps = {
  /** Current known item. */
  item: {
    /** Non-empty identity unique in the current collection. */
    value: string;
    /** Visible and accessible item name. */
    label: string;
    /** Optional secondary explanation. */
    description?: string | undefined;
    /** Prevents adding this item while retaining existing committed values. */
    disabled?: boolean | undefined;
    /** Optional visible group name. */
    group?: string | undefined;
    /** Additional terms consumed by local filtering. */
    keywords?: readonly string[] | undefined;
  };
  /** Whether the item belongs to the current draft. */
  selected: boolean;
  /** Keyboard highlight, independent from selection. */
  highlighted: boolean;
  /** Whether the item is unavailable for activation. */
  disabled: boolean;
};
```
