# ActionMenu

> 同一组操作在桌面呈现菜单，在窄屏呈现底部面板，支持层级、上下文入口与异步恢复。

网页来源：/components/action-menu

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

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

ActionMenu 为同一组操作提供桌面菜单和移动端底部面板。动作、可用状态与执行回调共享，打开按钮保持不变。

## 呈现方式

`presentation="auto"` 在小于 768px 的窗口中使用底部面板，其余使用桌面菜单。也可以指定 `desktop` 或 `bottom`。呈现方式在一次打开期间保持稳定，下次打开时再读取窗口大小。

通过 `actions` 提供动作，通过 `trigger` 插槽放置一个按钮。动作使用稳定且唯一的 `value`、可读的 `label`；`description` 补充说明，`disabled` 表示当前不可用。

### 示例：action-menu/basic

文件：`basic.vue`

```vue
<script setup lang="ts">
import { ref } from "vue";
import { quireIconRegistry } from "@quirekit/ui";
import type { QuireKitActionMenuActionDetails, QuireKitActionMenuEntry } from "@quirekit/ui";
import { QuireActionMenu, QuireButton, QuireIconProvider, QuireSegmented } from "@quirekit/ui/vue";

const presentation = ref<string | null>("auto");
const modes = [{ value: "auto", label: "自动" }, { value: "desktop", label: "桌面菜单" }, { value: "bottom", label: "底部面板" }];
const actions: readonly QuireKitActionMenuEntry[] = [
  { kind: "command", value: "details", label: "查看详细信息", description: "查看资源大小、格式与更新时间", icon: "fileText" },
  { kind: "command", value: "copy", label: "创建副本", description: "生成一份独立的资源副本", icon: "copy" },
  { kind: "command", value: "share", label: "分享资源", description: "当前资源仅对自己可见", icon: "link", disabled: true }
];
const count = ref(0);
const result = ref("尚未选择动作");

/** @param details - Successful local action notification. */
function recordAction(details: QuireKitActionMenuActionDetails): void {
  count.value += 1;
  result.value = actions.find(action => action.value === details.value)?.label ?? details.value;
}
</script>

<template>
  <QuireIconProvider :registry="quireIconRegistry">
    <div class="grid justify-items-start gap-5 p-qk-surface">
      <QuireSegmented v-model="presentation" label="操作菜单呈现方式" :items="modes" />
      <QuireActionMenu title="资源操作" description="选择与当前资料相关的操作。" :actions="actions"
        :presentation="presentation === 'desktop' ? 'desktop' : presentation === 'bottom' ? 'bottom' : 'auto'"
        @action="recordAction">
        <template #trigger><QuireButton color="primary" variant="solid">打开资源操作</QuireButton></template>
      </QuireActionMenu>
      <p class="m-0 text-qk-helper text-qk-text-secondary" role="status">最近动作：{{ result }} · 执行 {{ count }} 次</p>
    </div>
  </QuireIconProvider>
</template>
```

## 分层与上下文操作

`kind="branch"` 配合 `children` 定义下一层，`kind="command"` 执行动作。桌面使用子菜单，底部面板在当前面板中进入下一层，并通过返回按钮回到上一级。

使用 `context` 插槽提供可聚焦的内容区域，并通过 `contextLabel` 命名。该区域支持右键、ContextMenu 键和 Shift + F10，与更多按钮打开同一个操作目录。

`group` 按相邻的组名组织动作，`danger` 突出需要谨慎处理的操作。实际业务需要确认时，由执行回调完成确认流程。

### 示例：action-menu/layers

文件：`layers.vue`

```vue
<script setup lang="ts">
import { ref } from "vue";
import { quireIconRegistry } from "@quirekit/ui";
import type { QuireKitActionMenuActionDetails, QuireKitActionMenuEntry } from "@quirekit/ui";
import { QuireActionMenu, QuireButton, QuireIconProvider } from "@quirekit/ui/vue";

const actions: readonly QuireKitActionMenuEntry[] = [
  { kind: "command", value: "copy", label: "创建副本", group: "资源", icon: "copy" },
  { kind: "branch", value: "move", label: "移动到", description: "选择一个归档位置", group: "资源", children: [
    { kind: "command", value: "personal", label: "个人资料" },
    { kind: "branch", value: "team", label: "团队空间", children: [
      { kind: "command", value: "design", label: "设计素材" },
      { kind: "command", value: "research", label: "调研资料" }
    ] },
    { kind: "branch", value: "empty", label: "新建空间", children: [] }
  ] },
  { kind: "command", value: "archive", label: "归档资源", group: "管理", description: "将资料移入归档列表", danger: true },
  { kind: "branch", value: "locked", label: "管理访问权限", group: "管理", disabled: true, children: [] }
];
const result = ref("尚未选择位置");
const count = ref(0);

/** @param details - Successful leaf selection with its captured ancestor path. */
function recordAction(details: QuireKitActionMenuActionDetails): void {
  count.value += 1;
  result.value = [...details.path, details.value].join(" / ");
}
</script>

<template>
  <QuireIconProvider :registry="quireIconRegistry">
    <div class="grid justify-items-start gap-4 p-qk-surface">
      <QuireActionMenu title="整理资料" :actions="actions" context-label="项目资料" @action="recordAction">
        <template #trigger><QuireButton variant="outline">更多整理操作</QuireButton></template>
        <template #context>
          <div class="mt-4 grid gap-2 rounded-qk-control border border-qk-border-subtle p-5">
            <strong class="text-qk-body">项目资料</strong>
            <span class="text-qk-helper text-qk-text-secondary">右键打开操作；聚焦后也可按 Shift + F10。</span>
          </div>
        </template>
      </QuireActionMenu>
      <p class="m-0 text-qk-helper text-qk-text-secondary" role="status">{{ result }}</p>
      <p data-action-count class="m-0 text-qk-helper text-qk-text-secondary">执行 {{ count }} 次</p>
    </div>
  </QuireIconProvider>
</template>
```

## 底部网格与搜索

`layout="grid"` 将底部目录展示为两列按钮，`searchable` 提供当前层级的名称、身份、分组和描述搜索。禁用项保留展示且不可执行。搜索不会自动聚焦；桌面菜单保持其方向键与 typeahead 行为。

需要在目录后编辑日期或表单时，使用 [TaskPanel](/raw/components/task-panel.md) 与公共 `QuireActionDirectory` 组合参数页。

`QuireActionDirectory` 的 `searchPlaceholder` 可提供“搜索图片、表格…”等查询示例；
可访问标签仍由语言包提供。组件内置搜索图标、组间留白和 48px 网格按钮。
`icon` 插槽只装饰动作，颜色使用主题的语义 token，动作身份、按钮和禁用状态仍由组件拥有。

## 异步与重试

`execute` 接收动作值、所在路径和请求上下文。返回 Promise 时，组件保留当前内容并阻止重复执行；成功后关闭，失败后显示 `errorText`，用户可以重试。

回调通过 `signal` 响应取消，并在修改业务数据前检查它。`action` 在执行成功后通知结果，可用于记录最近操作。

### 示例：action-menu/async

文件：`async.vue`

```vue
<script setup lang="ts">
import { ref } from "vue";
import type { QuireKitActionMenuEntry, QuireKitActionMenuRequest } from "@quirekit/ui";
import { QuireActionMenu, QuireButton } from "@quirekit/ui/vue";

const attempts = ref(0);
const completed = ref(0);
const actions: readonly QuireKitActionMenuEntry[] = [
  { kind: "command", value: "save", label: "保存到资源库", description: "第一次演示失败，重试后完成保存" }
];

/**
 * Demonstrates a cancellable host operation with deterministic local failure and recovery.
 * @param request - Task identity and abort signal, also checked before committing the result.
 * @returns Local simulated operation; no remote resource is written.
 */
async function save(request: QuireKitActionMenuRequest): Promise<void> {
  const attempt = ++attempts.value;
  await new Promise<void>((resolve, reject) => {
    const timer = setTimeout(() => {
      request.signal.removeEventListener("abort", cancel);
      resolve();
    }, 500);
    /** Cancels the pending local delay when its task no longer owns the request. */
    function cancel(): void {
      clearTimeout(timer);
      reject(new DOMException("Task 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 save failure");
  completed.value += 1;
}
</script>

<template>
  <div class="grid justify-items-start gap-4 p-qk-surface">
    <QuireActionMenu title="保存资料" :actions="actions" :execute="save" error-text="暂时无法保存，请再次选择保存操作。">
      <template #trigger><QuireButton variant="outline">打开保存操作</QuireButton></template>
    </QuireActionMenu>
    <p class="m-0 text-qk-helper text-qk-text-secondary" role="status">尝试 {{ attempts }} 次 · 已保存 {{ completed }} 次</p>
  </div>
</template>
```

## 状态与键盘

`v-model:open` 控制打开状态，`defaultOpen` 设置非受控初始状态。`onCloseRequest` 可同步拒绝用户关闭；宿主直接更新 `open` 仍能结束任务。

桌面遵循 Menu 的方向键、子菜单和 typeahead 操作；底部面板使用 Tab 移动焦点、Enter 或 Space 执行。Escape 和取消关闭当前任务，焦点返回实际入口。

## API

### QuireActionMenu

#### Props

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| title | 是 | — | Visible task title and accessible name. |
| actions | 是 | — | Immutable action tree with globally unique non-empty values. |
| description | 否 | — | Optional explanation of the task. |
| layout | 否 | — | Bottom directory layout; desktop keeps native menu navigation. |
| searchable | 否 | — | Shows a bottom-directory search field without autofocus. |
| presentation | 否 | "auto" | Opening-time presentation strategy. |
| open | 否 | undefined | Controlled open request; undefined enables local ownership. |
| defaultOpen | 否 | false | Initial uncontrolled open request. |
| disabled | 否 | false | Prevents opening and authoritatively ends any current task. |
| errorText | 否 | — | Task-specific explanation shown after execute rejects; defaults to the language pack's generic text. |
| contextLabel | 否 | — | Accessible name of an optional non-interactive context region. |
| finalFocusEl | 否 | — | Explicit final focus; otherwise returns to this session's real opener. |
| onCloseRequest | 否 | — | Synchronous cancellable user-close callback. |
| execute | 否 | — | Sole business execution entry; action is a success notification. |

**title**

```ts
string
```

**actions**

```ts
readonly QuireKitActionMenuEntry[]
```

```ts
readonly ({
  /** A command runs the task's execute callback. */
  kind: "command";
  /** Commands never own a child directory. */
  children?: undefined;
  /** 动作执行时返回的唯一值。 */
  value: string;
  /** 动作的可见名称与可访问名称。 */
  label: string;
  /** 动作说明，可用于解释禁用原因。 */
  description?: undefined | string;
  /** 由 QuireIconProvider 提供的图标名。 */
  icon?: string | undefined;
  /** 是否禁用动作。 */
  disabled?: boolean | undefined;
  /** 是否以危险色突出动作。 */
  danger?: boolean | undefined;
  /** 相邻同组动作的分组标题。 */
  group?: string | undefined;
} | {
  /** A branch reveals its child actions. */
  kind: "branch";
  /** Ordered child directory; an empty directory retains a return path. */
  children: readonly QuireKitActionMenuEntry[];
  /** 动作执行时返回的唯一值。 */
  value: string;
  /** 动作的可见名称与可访问名称。 */
  label: string;
  /** 动作说明，可用于解释禁用原因。 */
  description?: string | undefined;
  /** 由 QuireIconProvider 提供的图标名。 */
  icon?: string | undefined;
  /** 是否禁用动作。 */
  disabled?: boolean | undefined;
  /** 是否以危险色突出动作。 */
  danger?: boolean | undefined;
  /** 相邻同组动作的分组标题。 */
  group?: string | undefined;
})[]
```

**description**

```ts
string | undefined
```

```ts
undefined | string
```

**layout**

```ts
"list" | "grid" | undefined
```

```ts
undefined | "list" | "grid"
```

**searchable**

```ts
boolean | undefined
```

**presentation**

```ts
QuireKitTaskPresentation | undefined
```

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

**open**

```ts
boolean | undefined
```

**defaultOpen**

```ts
boolean | undefined
```

**disabled**

```ts
boolean | undefined
```

**errorText**

```ts
string | undefined
```

```ts
undefined | string
```

**contextLabel**

```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; }
```

**execute**

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

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

#### Events

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

**update:open**

```ts
[open: boolean]
```

**openChange**

```ts
[open: boolean]
```

**cancel**

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

**action**

```ts
[details: QuireKitActionMenuActionDetails]
```

**error**

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

#### Slots

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| trigger | 否 | — | One real button; the task merges behavior and ARIA. |
| context | 否 | — | Non-interactive content region supporting contextmenu and ContextMenu/Shift+F10. |
| icon | 否 | — | Replaces only an action's decorative icon. |

**trigger**

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

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

**context**

```ts
any
```

**icon**

```ts
QuireKitActionMenuIconSlotProps
```

```ts
{
  /** Current immutable command or branch. */
  action: {
    /** A command runs the task's execute callback. */
    kind: "command";
    /** Commands never own a child directory. */
    children?: undefined;
    /** 动作执行时返回的唯一值。 */
    value: string;
    /** 动作的可见名称与可访问名称。 */
    label: string;
    /** 动作说明，可用于解释禁用原因。 */
    description?: undefined | string;
    /** 由 QuireIconProvider 提供的图标名。 */
    icon?: string | undefined;
    /** 是否禁用动作。 */
    disabled?: boolean | undefined;
    /** 是否以危险色突出动作。 */
    danger?: boolean | undefined;
    /** 相邻同组动作的分组标题。 */
    group?: string | undefined;
  } | {
    /** A branch reveals its child actions. */
    kind: "branch";
    /** Ordered child directory; an empty directory retains a return path. */
    children: readonly (QuireKitActionMenuEntry)[];
    /** 动作执行时返回的唯一值。 */
    value: string;
    /** 动作的可见名称与可访问名称。 */
    label: string;
    /** 动作说明，可用于解释禁用原因。 */
    description?: string | undefined;
    /** 由 QuireIconProvider 提供的图标名。 */
    icon?: string | undefined;
    /** 是否禁用动作。 */
    disabled?: boolean | undefined;
    /** 是否以危险色突出动作。 */
    danger?: boolean | undefined;
    /** 相邻同组动作的分组标题。 */
    group?: string | undefined;
  };
}
```

#### 公开实例成员

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

**requestClose**

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

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

#### 相关类型

```ts
type QuireKitActionMenuEntry = {
  /** A command runs the task's execute callback. */
  kind: "command";
  /** Commands never own a child directory. */
  children?: undefined;
  /** 动作执行时返回的唯一值。 */
  value: string;
  /** 动作的可见名称与可访问名称。 */
  label: string;
  /** 动作说明，可用于解释禁用原因。 */
  description?: undefined | string;
  /** 由 QuireIconProvider 提供的图标名。 */
  icon?: string | undefined;
  /** 是否禁用动作。 */
  disabled?: boolean | undefined;
  /** 是否以危险色突出动作。 */
  danger?: boolean | undefined;
  /** 相邻同组动作的分组标题。 */
  group?: string | undefined;
} | {
  /** A branch reveals its child actions. */
  kind: "branch";
  /** Ordered child directory; an empty directory retains a return path. */
  children: readonly (QuireKitActionMenuEntry)[];
  /** 动作执行时返回的唯一值。 */
  value: string;
  /** 动作的可见名称与可访问名称。 */
  label: string;
  /** 动作说明，可用于解释禁用原因。 */
  description?: string | undefined;
  /** 由 QuireIconProvider 提供的图标名。 */
  icon?: string | undefined;
  /** 是否禁用动作。 */
  disabled?: boolean | undefined;
  /** 是否以危险色突出动作。 */
  danger?: boolean | undefined;
  /** 相邻同组动作的分组标题。 */
  group?: string | undefined;
};
```

```ts
type QuireKitActionMenuCommand = {
  /** A command runs the task's execute callback. */
  kind: "command";
  /** Commands never own a child directory. */
  children?: undefined;
  /** 动作执行时返回的唯一值。 */
  value: string;
  /** 动作的可见名称与可访问名称。 */
  label: string;
  /** 动作说明，可用于解释禁用原因。 */
  description?: undefined | string;
  /** 由 QuireIconProvider 提供的图标名。 */
  icon?: string | undefined;
  /** 是否禁用动作。 */
  disabled?: boolean | undefined;
  /** 是否以危险色突出动作。 */
  danger?: boolean | undefined;
  /** 相邻同组动作的分组标题。 */
  group?: string | undefined;
};
```

```ts
type QuireKitActionMenuBranch = {
  /** A branch reveals its child actions. */
  kind: "branch";
  /** Ordered child directory; an empty directory retains a return path. */
  children: readonly (QuireKitActionMenuEntry)[];
  /** 动作执行时返回的唯一值。 */
  value: string;
  /** 动作的可见名称与可访问名称。 */
  label: string;
  /** 动作说明，可用于解释禁用原因。 */
  description?: string | undefined;
  /** 由 QuireIconProvider 提供的图标名。 */
  icon?: string | undefined;
  /** 是否禁用动作。 */
  disabled?: boolean | undefined;
  /** 是否以危险色突出动作。 */
  danger?: boolean | undefined;
  /** 相邻同组动作的分组标题。 */
  group?: string | undefined;
};
```

```ts
type QuireKitActionMenuIconSlotProps = {
  /** Current immutable command or branch. */
  action: {
    /** A command runs the task's execute callback. */
    kind: "command";
    /** Commands never own a child directory. */
    children?: undefined;
    /** 动作执行时返回的唯一值。 */
    value: string;
    /** 动作的可见名称与可访问名称。 */
    label: string;
    /** 动作说明，可用于解释禁用原因。 */
    description?: string | undefined;
    /** 由 QuireIconProvider 提供的图标名。 */
    icon?: string | undefined;
    /** 是否禁用动作。 */
    disabled?: boolean | undefined;
    /** 是否以危险色突出动作。 */
    danger?: boolean | undefined;
    /** 相邻同组动作的分组标题。 */
    group?: string | undefined;
  } | {
    /** A branch reveals its child actions. */
    kind: "branch";
    /** Ordered child directory; an empty directory retains a return path. */
    children: readonly QuireKitActionMenuEntry[];
    /** 动作执行时返回的唯一值。 */
    value: string;
    /** 动作的可见名称与可访问名称。 */
    label: string;
    /** 动作说明，可用于解释禁用原因。 */
    description?: string | undefined;
    /** 由 QuireIconProvider 提供的图标名。 */
    icon?: string | undefined;
    /** 是否禁用动作。 */
    disabled?: boolean | undefined;
    /** 是否以危险色突出动作。 */
    danger?: boolean | undefined;
    /** 相邻同组动作的分组标题。 */
    group?: string | undefined;
  };
};
```
