# Chat Composer

> 从复杂工作区面板到文档内单行指令，组合输入、附件入口、左右工具与发送停止。

网页来源：/components/chat-composer

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

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

`v-model` 由宿主持有草稿。收到 `submit` 时读取原始 `details.text`；组件不裁剪或清空内容，不调用 AI 服务。默认 `panel` 将输入正文与底部操作分行；`inline` 让输入和发送并排，从一行自动增高。

## 工作区面板

`header` 放附件或上下文；`tools` 放左侧入口；`actions` 放右侧设置，发送始终在末端；`footer` 在框外放稳定的辅助说明或统计，瞬时反馈使用 Toast。输入、工具和发送共用一个表面与焦点边界。`variant="elevated"` 添加轻阴影，默认 `outline` 使用轻描边。

添加上下文使用 Popover Anchor 锚定整个输入面板，`width="anchor"` 的浮层在上方展开，与输入框等宽。内部复用 CommandList 的 `group` 和 `description` 组织添加入口与指令；不在快捷菜单中放完整上传表单。

FileUpload 默认插槽提供 `openFilePicker` 与校验状态，`header` 中的 FileUploadList 使用 `layout="strip"` 展示单行滚动的文件卡片、图片缩略图和移除操作。Escape 返回添加按钮，选中上下文或移除附件后回到输入。文件只在本地选择，不会上传；发送为模拟，语音按钮只触发入口反馈。

将 FileUpload 插槽的 `addTransferFiles` 传给 Composer 的同名属性，即可在整个输入表面粘贴或拖入文件。Composer 只识别文件手势、呈现短暂拖入边界并转交 `DataTransfer`；文件集合、校验和拒绝反馈仍只归 FileUpload。普通文字粘贴与文字拖放维持原生行为，已有草稿不会被文件操作覆盖。禁用或只读时不接受文件。

输入区设置 `:show-rejections="false"`，在 `fileReject` 中用 Toast 提示重复文件、大小和数量限制，不增加 Composer 的高度。普通 FileUpload 表单仍默认显示拒绝条目；校验结果不会因为隐藏展示而被忽略。

权限与模型设置复用 Menu 和 Select。`hasContent` 支持仅附件提交；`submitDisabled` 可表达附件尚未就绪，只阻止发送而不禁用编辑。

### 示例：chat-composer/workspace

文件：`workspace.vue`

```vue
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref, shallowRef } from 'vue';
import { QuireButton, QuireChatComposer, QuireCommandList, QuireFileUpload, QuireFileUploadList, QuireIcon, QuireIconButton, QuireMenu, QuireToaster,
  QuirePopoverRoot, QuirePopoverAnchor, QuirePopoverTrigger, QuirePopoverContent, QuireSelect, QuireTag } from '@quirekit/ui/vue';
import type { QuireKitCommandListItem } from '@quirekit/ui/vue';
import type { QuireKitChatComposerInstance, QuireKitChatSubmitDetails, QuireKitMenuEntry } from '@quirekit/ui';
import { useComposerFeedback } from './context/feedback';

const draft = ref('');
const files = ref<File[]>([]);
const documentContext = shallowRef<{ label: string }>();
const composer = ref<QuireKitChatComposerInstance>();
const contextOpen = ref(false);
const restoreContextFocus = ref(true);
const permission = ref('review');
const model = ref<string | undefined>('general');
const effort = ref<string | undefined>('deep');
const busy = ref(false);
const { toaster, reject } = useComposerFeedback();
let pending: ReturnType<typeof setTimeout> | undefined;
const models = [{ value: 'general', label: '通用模型' }, { value: 'code', label: '代码模型' }];
const efforts = [{ value: 'standard', label: '标准' }, { value: 'deep', label: '深度' }];
const permissions = computed<QuireKitMenuEntry[]>(() => [{ value: 'permission', label: '执行权限', kind: 'radio-group', selectedValue: permission.value,
  children: [{ value: 'review', label: '操作前确认', closeOnSelect: true }, { value: 'full', label: '完全访问', closeOnSelect: true }] }]);
const commands = computed<QuireKitCommandListItem[]>(() => [
  { key: 'files', group: '添加', label: '文件和图片', description: '从设备选择，不上传', disabled: files.value.length >= 4 },
  { key: 'document', group: '添加', label: '当前文档', description: '项目计划摘录', disabled: !!documentContext.value },
  { key: 'outline', group: '指令', label: '整理提纲', description: '插入示例指令' },
  { key: 'clear', group: '指令', label: '清空草稿', description: '移除文字与上下文', disabled: !draft.value && !files.value.length && !documentContext.value }
]);
const icons: Readonly<Record<string, string>> = { files: 'paperclip', document: 'fileText', outline: 'listTree', clear: 'trash' };

/** Capture this request only; later edits and added contexts remain a separate draft.
 * @param details - Unmodified text submitted by the UI.
 */
function submit(details: QuireKitChatSubmitDetails): void {
  const submittedFiles = [...files.value];
  const submittedDocument = documentContext.value;
  busy.value = true;
  pending = setTimeout(() => {
    busy.value = false;
    toaster.success({ title: `已完成演示：${details.text || '上下文任务'}${submittedFiles.length ? `（${submittedFiles.length} 个文件）` : ''}` });
    if (draft.value === details.text) draft.value = '';
    files.value = files.value.filter(file => !submittedFiles.includes(file));
    if (documentContext.value === submittedDocument) documentContext.value = undefined;
  }, 2000);
}
/** Cancel only this local demonstration; no microphone or AI service is called. */
function stop(): void { clearTimeout(pending); busy.value = false; toaster.info({ title: '已停止，草稿和附件已保留。' }); }
/** Resume typing through the public input API after a context operation. */
async function focusInput(): Promise<void> { await nextTick(); composer.value?.focus({ preventScroll: true }); }
/** Close the context list after a file selection; transient feedback lives outside the field. */
function finishPicking(): void {
  restoreContextFocus.value = false; contextOpen.value = false; void focusInput();
}
/** Run a local command; selection, validation and previews still belong to FileUpload.
 * @param key - Stable public command identity.
 * @param openFilePicker - FileUpload's guarded native selection entry.
 */
function selectContext(key: string, openFilePicker: () => void): void {
  if (key === 'files') { openFilePicker(); return; }
  if (key === 'document') documentContext.value = { label: '项目计划摘录' };
  if (key === 'outline') draft.value = '请根据当前上下文整理一份提纲。';
  if (key === 'clear') { draft.value = ''; files.value = []; documentContext.value = undefined; }
  finishPicking();
}
onBeforeUnmount(() => clearTimeout(pending));
</script>

<template>
  <div class="p-qk-surface" data-chat-workspace>
    <QuireFileUpload v-model="files" label="任务附件" multiple :max-files="4" :max-file-size="10485760"
      @file-accept="finishPicking" @file-reject="details => { reject(details); finishPicking(); }">
      <template #default="upload">
      <QuirePopoverRoot v-model:open="contextOpen" placement="top-start" :restore-focus="restoreContextFocus"
        @open-change="value => { if (value) restoreContextFocus = true; }">
        <QuirePopoverAnchor as-child>
        <QuireChatComposer ref="composer" v-model="draft" label="工作区指令" placeholder="描述任务，或添加文件作为上下文…"
          variant="elevated" :has-content="files.length > 0 || !!documentContext" :busy="busy"
          :add-transfer-files="upload.addTransferFiles"
          @submit="submit" @stop="stop">
          <template v-if="files.length || documentContext" #header>
            <div class="grid gap-qk-inline">
              <QuireFileUploadList v-if="files.length" layout="strip" :show-rejections="false" @remove="focusInput" />
              <div v-if="documentContext">
                <QuireTag closable @close="documentContext = undefined; focusInput()">
                  <QuireIcon name="fileText" :size="12" /> {{ documentContext.label }}
                </QuireTag>
              </div>
            </div>
          </template>
          <template #tools>
            <QuirePopoverTrigger as-child><QuireIconButton label="添加上下文" title="添加上下文" shape="circle"><QuireIcon name="plus" /></QuireIconButton></QuirePopoverTrigger>
            <QuireMenu :items="permissions" width="auto" max-width="16rem" @select="permission = $event">
              <template #trigger>
                <QuireButton variant="ghost" :color="permission === 'full' ? 'warning' : 'neutral'" aria-label="执行权限">
                  <template #leading><QuireIcon name="shield" /></template>{{ permission === 'full' ? '完全访问' : '操作前确认' }}
                  <template #trailing><QuireIcon name="chevronDown" /></template>
                </QuireButton>
              </template>
            </QuireMenu>
          </template>
          <template #actions>
            <QuireSelect v-model="model" :items="models" label="工作区模型" variant="text" width="auto" content-width="200px" />
            <QuireSelect v-model="effort" :items="efforts" label="推理强度" variant="text" width="auto" content-width="160px" />
            <QuireIconButton label="语音输入" title="语音输入" shape="circle" @click="toaster.info({ title: '语音入口已触发', description: '实际录音与转写由宿主接入，本示例未请求麦克风权限。' })">
              <QuireIcon name="mic" />
            </QuireIconButton>
          </template>
        </QuireChatComposer>
        </QuirePopoverAnchor>
        <QuirePopoverContent width="anchor" padding="none" :show-arrow="false" aria-label="添加上下文" data-chat-context-menu>
          <QuireCommandList label="上下文与指令" :items="commands" @select="selectContext($event, upload.openFilePicker)">
            <template #leading="{ item }"><QuireIcon :name="icons[item.key]" /></template>
          </QuireCommandList>
        </QuirePopoverContent>
      </QuirePopoverRoot>
      </template>
    </QuireFileUpload>
    <QuireToaster :toaster="toaster" />
  </div>
</template>
```

文件：`context/feedback.ts`

```ts
import { onBeforeUnmount } from 'vue';
import { createQuireKitToaster } from '@quirekit/ui/vue';
import { getQuireKitFileUploadErrorMessage } from '@quirekit/ui';
import type { QuireKitFileUploadRejectDetails } from '@quirekit/ui';

/** Keep transient feedback outside the draft and release the local toast store.
 * @returns A bounded notification store and validation feedback handler.
 */
export function useComposerFeedback() {
  const toaster = createQuireKitToaster({ placement: 'bottom-end', max: 2, duration: 4000 });
  /** @param details - Rejections from the existing FileUpload validator. */
  function reject(details: QuireKitFileUploadRejectDetails): void {
    const first = details.files[0];
    if (!first) return;
    toaster.create({ id: 'file-rejection', type: 'warning', title: getQuireKitFileUploadErrorMessage(first.errors),
      description: `${first.file.name}${details.files.length > 1 ? ` 等 ${details.files.length} 个文件` : ''}`, closable: true });
  }
  onBeforeUnmount(() => toaster.remove());
  return { toaster, reject };
}
```

## 图片与文件上下文

`header` 也可使用通用 [Attachments](/raw/components/attachments.md) 的 `strip` 布局，让图片以可点击缩略图呈现，文件保留类型图标、名称、大小和移除入口。更多附件横向滚动，不换行增加输入框高度。FileUpload 仍持有选择与校验，宿主将原生 File 映射为附件数据，并在移除或卸载时释放自己创建的 object URL。

### 示例：chat-composer/attachments

文件：`attachments.vue`

```vue
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { QuireAttachments, QuireChatComposer, QuireFileUpload, QuireIcon, QuireIconButton, QuireToaster } from '@quirekit/ui/vue';
import type { QuireKitAttachmentActionDetails, QuireKitAttachmentItem, QuireKitChatComposerInstance } from '@quirekit/ui';
import { useComposerFeedback } from './context/feedback';

const draft = ref('');
const files = ref<File[]>([]);
const composer = ref<QuireKitChatComposerInstance>();
const resources = new Map<File, QuireKitAttachmentItem>();
const items = ref<QuireKitAttachmentItem[]>([]);
const { toaster, reject } = useComposerFeedback();
let sequence = 0;

// The host creates each object URL exactly once and releases it only after that
// File leaves this draft. Attachment only reads the resulting resource projection.
watch(files, current => {
  for (const [file, item] of resources) {
    if (current.includes(file)) continue;
    if (item.url) URL.revokeObjectURL(item.url);
    resources.delete(file);
  }
  for (const file of current) {
    if (!resources.has(file)) resources.set(file, {
      id: `local-${++sequence}`, name: file.name, mediaType: file.type, size: file.size, source: 'local', actions: ['remove'],
      ...(file.type.startsWith('image/') ? { url: URL.createObjectURL(file) } : {})
    });
  }
  items.value = current.map(file => resources.get(file)!);
}, { flush: 'sync' });
const hasContent = computed(() => files.value.length > 0);
/** Resume editing after the native chooser or an inline removal. */
async function focusInput(): Promise<void> { await nextTick(); composer.value?.focus({ preventScroll: true }); }
/** @param details - Controlled removal of a File from the draft's source of truth. */
function action(details: QuireKitAttachmentActionDetails): void {
  if (details.action !== 'remove') return;
  files.value = files.value.filter(file => resources.get(file)?.id !== details.attachmentId);
  // Removing the entire conditional header also removes its focus fallback;
  // after that unmount, the host resumes its still-mounted input via the public API.
  if (!files.value.length) void focusInput();
}
onBeforeUnmount(() => { for (const item of resources.values()) if (item.url) URL.revokeObjectURL(item.url); });
</script>
<template>
  <div class="p-qk-surface" data-composer-attachments>
    <QuireFileUpload v-model="files" label="文档上下文附件" multiple :max-files="12" :max-file-size="10485760" @file-accept="focusInput" @file-reject="details => { reject(details); focusInput(); }">
      <template #default="upload">
        <QuireChatComposer ref="composer" v-model="draft" label="附件任务" placeholder="描述任务，或先添加图片与文件…" variant="elevated" :has-content="hasContent"
          :add-transfer-files="upload.addTransferFiles"
          @submit="toaster.info({ title: `收到指令与 ${files.length} 个附件`, description: '本示例保留草稿，不发起请求。' })">
          <template v-if="items.length" #header>
            <QuireAttachments :items="items" layout="strip" label="草稿附件" @action="action" />
          </template>
          <template #tools><QuireIconButton label="添加文件与图片" title="添加文件与图片" shape="circle" @click="upload.openFilePicker"><QuireIcon name="plus" /></QuireIconButton></template>
        </QuireChatComposer>
      </template>
    </QuireFileUpload>
    <QuireToaster :toaster="toaster" />
  </div>
</template>
```

文件：`context/feedback.ts`

```ts
import { onBeforeUnmount } from 'vue';
import { createQuireKitToaster } from '@quirekit/ui/vue';
import { getQuireKitFileUploadErrorMessage } from '@quirekit/ui';
import type { QuireKitFileUploadRejectDetails } from '@quirekit/ui';

/** Keep transient feedback outside the draft and release the local toast store.
 * @returns A bounded notification store and validation feedback handler.
 */
export function useComposerFeedback() {
  const toaster = createQuireKitToaster({ placement: 'bottom-end', max: 2, duration: 4000 });
  /** @param details - Rejections from the existing FileUpload validator. */
  function reject(details: QuireKitFileUploadRejectDetails): void {
    const first = details.files[0];
    if (!first) return;
    toaster.create({ id: 'file-rejection', type: 'warning', title: getQuireKitFileUploadErrorMessage(first.errors),
      description: `${first.file.name}${details.files.length > 1 ? ` 等 ${details.files.length} 个文件` : ''}`, closable: true });
  }
  onBeforeUnmount(() => toaster.remove());
  return { toaster, reject };
}
```

本例最多选择 12 个文件，单个不超过 10 MB，不上传文件；`hasContent` 允许只附文件就提交。校验和提交演示使用框外 Toast，草稿不变。远程附件或上传状态可以使用同一展示合同，上传中可用 `submitDisabled` 暂停发送。

## 简洁对话面板

不需要的区域直接省略。发送按钮默认使用主题主色，`submitColor="neutral"` 可显式选择中性外观。用量、速度等状态由宿主提供，不占据输入正文；示例中的数字是演示数据。

编辑器侧栏可以使用 `density="compact"`，缩紧表面留白并使用小号发送按钮。配合 `size="sm"`
和 `:rows="1"` 从一行开始输入，内容变长后自动增高；默认 `comfortable` 保持常规密度。

### 示例：chat-composer/conversation

文件：`conversation.vue`

```vue
<script setup lang="ts">
import { ref } from 'vue';
import { QuireButton, QuireChatComposer, QuireIcon, QuireMenu, QuireSelect } from '@quirekit/ui/vue';
const draft = ref('');
const model = ref<string | undefined>('balanced');
const search = ref(false);
const feedback = ref('');
const models = [{ value: 'balanced', label: '均衡模型' }, { value: 'reasoning', label: '推理模型' }];
</script>

<template>
  <div class="p-qk-surface" data-chat-conversation-composer>
    <QuireChatComposer v-model="draft" label="对话消息" placeholder="发消息，或开始一个新任务…" submit-color="primary"
      density="compact" size="sm" :rows="1"
      @submit="feedback = `已提交演示消息：${$event.text}`">
      <template #tools>
        <QuireMenu width="auto" :items="[{ value: 'search', label: '联网搜索', checked: search, closeOnSelect: false }]" @select="search = !search">
          <template #trigger><QuireButton variant="ghost" :aria-pressed="search">
            <template #leading><QuireIcon name="globe" /></template>{{ search ? '搜索已开启' : '工具' }}
            <template #trailing><QuireIcon name="chevronDown" /></template>
          </QuireButton></template>
        </QuireMenu>
      </template>
      <template #actions><QuireSelect v-model="model" :items="models" label="对话模型" width="auto" content-width="180px" variant="text" /></template>
      <template #footer>
        <div class="flex flex-wrap justify-center gap-x-qk-surface gap-y-qk-inline-tight text-qk-text-tertiary">
          <span>6 轮对话</span><span>46 tokens/s</span><span>上下文 61%</span><span>演示统计</span>
        </div>
        <div v-if="feedback" role="status" class="mt-qk-inline">{{ feedback }}</div>
      </template>
    </QuireChatComposer>
  </div>
</template>
```

## 单行指令

`layout="inline"` 从一行开始，前导图标、输入与操作按钮垂直居中；`maxRows` 控制自动增高上限。切换布局保留原生输入节点、草稿与选区。宽度不足时工具自然换行，不裁掉发送入口。

### 示例：chat-composer/inline

文件：`inline.vue`

```vue
<script setup lang="ts">
import { ref } from 'vue';
import { QuireButton, QuireChatComposer, QuireLocaleProvider, QuireSelect } from '@quirekit/ui/vue';
const draft = ref('');
const inline = ref(true);
const feedback = ref('');
const locale = ref('zh-CN');
</script>

<template>
  <div class="grid gap-qk-surface p-qk-surface" data-chat-inline>
    <QuireLocaleProvider :locale="locale">
      <QuireChatComposer v-model="draft" :layout="inline ? 'inline' : 'panel'" :max-rows="4" label="快速提问" placeholder="问一个问题…"
        @submit="feedback = `已提交：${$event.text}`" />
    </QuireLocaleProvider>
    <div class="flex flex-wrap items-center justify-between gap-qk-inline text-qk-helper text-qk-text-secondary">
      <span role="status">{{ feedback || '从一行开始，长内容自动增高。' }}</span>
      <div class="flex items-center gap-qk-inline">
        <QuireSelect v-model="locale" :items="[{ value: 'zh-CN', label: '从左到右' }, { value: 'ar', label: '从右到左' }]" label="输入方向" variant="text" width="auto" content-width="160px" />
        <QuireButton variant="ghost" @click="inline = !inline">{{ inline ? '切换为面板' : '切换为单行' }}</QuireButton>
      </div>
    </div>
  </div>
</template>
```

## 文档内嵌

`leading` 放轻量提示图标，`variant="soft"` 区分文档中的指令输入。公开实例 `focus(options?)` 聚焦默认输入，方便打开浮动或内嵌助手后接续输入。示例使用 Prose 展示上下文，不读取编辑器选区，也不写入文档。

### 示例：chat-composer/document

文件：`document.vue`

```vue
<script setup lang="ts">
import { nextTick, ref } from 'vue';
import { QuireButton, QuireChatComposer, QuireIcon, QuireIconButton, QuireProse } from '@quirekit/ui/vue';
import type { QuireKitChatComposerInstance, QuireKitChatSubmitDetails } from '@quirekit/ui';
const composer = ref<QuireKitChatComposerInstance>();
const draft = ref('');
const opened = ref(true);
const result = ref('');
const trigger = ref<HTMLElement>();

/** Focus the public input after mounting; no editor selection or document transaction is read. */
async function open(): Promise<void> { opened.value = true; await nextTick(); composer.value?.focus({ preventScroll: true }); }
/** Close the inline surface and return to its host-owned entry. */
async function close(): Promise<void> { opened.value = false; await nextTick(); trigger.value?.querySelector('button')?.focus(); }
/** Produce a local suggestion; actual document writes belong to the consuming editor.
 * @param details - Instruction submitted by the user.
 */
function submit(details: QuireKitChatSubmitDetails): void { result.value = `建议已生成（演示）：${details.text}。实际文档修改由宿主命令执行。`; }
</script>

<template>
  <div class="mx-auto grid w-full max-w-3xl gap-qk-surface p-qk-surface" data-chat-document>
    <QuireProse as="article" aria-label="项目计划摘录">
      <h3>让协作更清楚</h3><p>先确定共同目标，再逐步补充参与人、时间安排与完成条件。</p>
    </QuireProse>
    <div v-show="!opened" ref="trigger"><QuireButton variant="ghost" @click="open"><template #leading><QuireIcon name="sparkles" /></template>让 AI 帮忙</QuireButton></div>
    <QuireChatComposer v-if="opened" ref="composer" v-model="draft" layout="inline" variant="soft" :max-rows="4"
      label="文档内指令" placeholder="补充要点、调整语气，或继续写…" @submit="submit">
      <template #leading><QuireIcon name="sparkles" :size="16" /></template>
      <template #actions><QuireIconButton label="关闭文档助手" title="关闭" @click="close"><QuireIcon name="close" /></QuireIconButton></template>
    </QuireChatComposer>
    <p v-if="result" role="status" class="m-0 text-qk-helper text-qk-text-secondary">{{ result }}</p>
  </div>
</template>
```

## 一体化输入区

默认最大阅读宽度为 `48rem`，可在共同祖先设置 `--qk-chat-content-width`，与消息区域保持一致。正文非空白或 `hasContent` 为真才允许发送。需要文字按钮时使用 `submitAppearance="text"`。

### 示例：chat-composer/basic

文件：`basic.vue`

```vue
<script setup lang="ts">
import { ref } from 'vue';
import { QuireChatComposer, QuireSelect } from '@quirekit/ui/vue';
const draft = ref('');
const format = ref('outline');
const sent = ref('');
const formats = [{ value: 'outline', label: '整理提纲' }, { value: 'summary', label: '提炼摘要' }];
</script>

<template>
  <div class="p-qk-surface" data-chat-composer-basic>
    <QuireChatComposer v-model="draft" label="描述你的任务" placeholder="描述你的想法，或继续完善这份计划…"
      @submit="sent = `已提交${format === 'outline' ? '提纲' : '摘要'}任务：${$event.text}`">
      <template #tools><QuireSelect v-model="format" :items="formats" label="处理方式" width="auto" content-width="160px" variant="text" /></template>
      <template #footer><span role="status">{{ sent || 'Enter 发送 · Shift+Enter 换行' }}</span></template>
    </QuireChatComposer>
  </div>
</template>
```

## 发送、失败与停止

生成中，主按钮显示实心停止方块。默认输入框允许继续写草稿，Enter 换行，Esc 请求停止本轮生成。仅禁止发送时，Enter 同样保留换行。`input` 插槽可以将 `submitMode` 透传给富输入，并自行处理候选菜单的键盘操作。宿主收到 `stop` 后取消执行，保留已经输入的草稿。

### 示例：chat-composer/recovery

文件：`recovery.vue`

```vue
<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue';
import { QuireButton, QuireChatComposer, QuireCollapsible } from '@quirekit/ui/vue';
import type { QuireKitChatSubmitDetails } from '@quirekit/ui';
const draft = ref('请整理本周项目进展。'); const busy = ref(false); const failNext = ref(true);
const outcome = ref('示例首次发送会失败，草稿会保留。'); const error = ref(false);
let timer: ReturnType<typeof setTimeout> | undefined;
/** Simulate transport without putting its lifecycle in the public UI.
 * @param details - Exact submitted draft.
 */
function send(details: QuireKitChatSubmitDetails): void {
  busy.value = true; error.value = false; outcome.value = '正在发送，可以继续编辑下一份草稿。';
  const fail = failNext.value;
  timer = setTimeout(() => {
    busy.value = false; error.value = fail;
    outcome.value = fail ? '发送失败，草稿已保留。切换为成功后可直接重试。' : `已发送：${details.text}`;
    if (!fail && draft.value === details.text) draft.value = '';
  }, 800);
}
/** Cancel this example's pending operation and retain the current draft. */
function stop(): void {
  if (timer) clearTimeout(timer);
  busy.value = false; error.value = false; outcome.value = '已停止，草稿保留。';
}
onBeforeUnmount(() => { if (timer) clearTimeout(timer); });
</script>

<template>
  <div class="grid gap-qk-surface p-qk-surface" data-chat-recovery>
    <QuireChatComposer v-model="draft" label="会话草稿" :busy="busy" @submit="send" @stop="stop">
      <template #tools><span class="text-qk-helper text-qk-text-tertiary">{{ busy ? '正在发送…' : 'Shift+Enter 换行' }}</span></template>
      <template #footer><span :role="error ? 'alert' : 'status'" :class="error ? 'text-qk-danger-text' : undefined">{{ outcome }}</span></template>
    </QuireChatComposer>
    <QuireCollapsible title="发送状态演示" class="w-full max-w-3xl mx-auto">
      <QuireButton variant="outline" :disabled="busy" @click="failNext = !failNext">{{ failNext ? '下次模拟失败' : '下次模拟成功' }}</QuireButton>
    </QuireCollapsible>
  </div>
</template>
```

## 键盘与区域组合

默认 Enter 发送、Shift+Enter 换行，输入法确认不触发发送。`submitMode="button"` 保留 Enter 原生换行；`rows`/`maxRows` 控制自动增高的最小/最大行数。`disabled` 禁止全部动作；`readOnly` 保留复制但禁止修改与发送。

`header`、`tools`、`footer` 可插入宿主内容；`submit` 可替换操作区；`input` 可替换 Textarea。自定义输入需自行处理输入法、焦点和快捷键，通过 slot 的 `updateValue`/`submit` 接口通信。

使用 Textarea 替换输入时，设置 `variant="embedded"`，由 Composer 提供共同边界，避免双重输入框。`leading` 可放前导入口，`actions` 放发送前的设置；自定义工具通过 slot context 的 `disabled` / `readOnly` 同步可用状态。

### 示例：chat-composer/composition

文件：`composition.vue`

```vue
<script setup lang="ts">
import { ref } from 'vue';
import { QuireButton, QuireChatComposer, QuireCollapsible, QuireTextarea } from '@quirekit/ui/vue';
const draft = ref(''); const custom = ref(false); const locked = ref(false); const sent = ref('');
</script>

<template>
  <div class="grid gap-qk-surface p-qk-surface min-w-0" data-chat-composition>
    <QuireChatComposer v-model="draft" label="补充说明" submit-mode="button" :read-only="locked" :rows="2" :max-rows="4" @submit="sent = $event.text">
      <template #header><span class="text-qk-helper text-qk-text-secondary">给项目计划补充说明</span></template>
      <template v-if="custom" #input="{ value, label, updateValue, disabled, readOnly }">
        <QuireTextarea :model-value="value" :aria-label="label" :disabled="disabled" :read-only="readOnly" variant="embedded"
          width="100%" :rows="3" show-count :maxlength="200" @update:model-value="updateValue" />
      </template>
      <template #footer><span role="status">{{ sent ? `已发送：${sent}` : 'Enter 换行，使用发送按钮提交。' }}</span></template>
    </QuireChatComposer>
    <QuireCollapsible title="输入区域设置" class="w-full max-w-3xl mx-auto">
      <div class="flex flex-wrap gap-qk-inline">
        <QuireButton variant="outline" @click="custom = !custom">{{ custom ? '默认输入' : '替换输入' }}</QuireButton>
        <QuireButton variant="outline" @click="locked = !locked">{{ locked ? '恢复编辑' : '只读' }}</QuireButton>
      </div>
    </QuireCollapsible>
  </div>
</template>
```

`submit` 载荷只包含原始文本；附件列表由宿主持有，配合 `hasContent` 允许空文本提交。富文本 token 和 slash/@ 的协议由对应输入 adapter 持有。

## `@` 引用与 `/` 指令

`QuireChatRichInput` 可放入 Composer 的 `input` slot；原始草稿继续用 `modelValue`，解析后的引用和指令用受控 `tokens` 保存。token 记录稳定候选 key、出现位置 ID 和文本范围，提交时宿主同时读取草稿与 token，Composer 本身不解析业务引用。`resolveCandidates(query, signal)` 由宿主提供数据；输入变化、选区移动和卸载会取消旧请求，晚到结果不覆盖当前候选；当前请求失败发出 `candidateError`，反馈由宿主决定。候选列表复用公共 `CandidateList`，输入始终保有焦点和键盘操作。

候选默认与 Composer 外框等宽并从上方展开，适合底部固定的聊天输入框；只有上方空间不足才翻转到下方。

### 示例：chat-composer/rich-input

文件：`rich-input.vue`

```vue
<script setup lang="ts">
import { ref } from 'vue';
import { QuireChatComposer, QuireChatRichInput } from '@quirekit/ui/vue';
import type { QuireKitChatInputCandidate, QuireKitChatInputQuery, QuireKitChatInputToken } from '@quirekit/ui';

const draft = ref('');
const tokens = ref<readonly QuireKitChatInputToken[]>([]);
const sent = ref('');
const mentions: readonly QuireKitChatInputCandidate[] = [
  { key: 'file:project-plan', label: '项目计划.md', description: '项目文件' },
  { key: 'file:roadmap', label: '路线图.pdf', description: '项目文件' },
  { key: 'person:lin', label: '林同学', description: '参与人' }
];
const commands: readonly QuireKitChatInputCandidate[] = [
  { key: 'command:search', label: '搜索', description: '查找当前工作区' },
  { key: 'command:summarize', label: '总结', description: '提炼当前上下文' }
];

/** Resolve feature-owned references without putting a data service in the UI package.
 * @param query - Trigger and literal search text.
 * @param signal - Cancellation for a superseded query.
 * @returns Matching local example candidates.
 */
function resolveCandidates(query: QuireKitChatInputQuery, signal: AbortSignal): readonly QuireKitChatInputCandidate[] {
  if (signal.aborted) return [];
  const pool = query.kind === 'mention' ? mentions : commands;
  return pool.filter(item => item.label.toLocaleLowerCase().includes(query.search.toLocaleLowerCase()));
}

/** Record the text and token identities submitted through Composer.
 * @param details - Literal Composer submission.
 */
function onSubmit(details: { text: string }): void {
  sent.value = `${details.text} · ${tokens.value.map(token => token.key).join(', ') || '无引用'}`;
}
</script>

<template>
  <div class="grid min-w-0 gap-qk-inline p-qk-surface" data-chat-rich-input-demo>
    <div class="mx-auto grid min-h-40 w-full max-w-3xl content-start text-qk-body text-qk-text-secondary">
      <p class="m-0">已整理项目计划和路线图。需要我引用哪份文件继续？</p>
    </div>
    <QuireChatComposer v-model="draft" label="富输入消息" :rows="2" @submit="onSubmit">
      <template #input="{ value, label, disabled, readOnly, submitMode, updateValue, submit }">
        <QuireChatRichInput :model-value="value" :tokens="tokens" :label="label" :submit-mode="submitMode"
          placeholder="输入 @ 引用文件或参与人，输入 / 选择指令…"
          :disabled="disabled" :read-only="readOnly" :resolve-candidates="resolveCandidates"
          @update:model-value="updateValue" @update:tokens="tokens = $event" @submit="submit()" />
      </template>
    </QuireChatComposer>
    <p class="m-0 text-qk-helper text-qk-text-secondary">方向键选择候选、Enter 确认；Backspace 整体删除引用。发送后的 token 身份由宿主读取。</p>
    <p v-if="sent" class="m-0 text-qk-helper text-qk-text-secondary" role="status">已发送：{{ sent }}</p>
  </div>
</template>
```

这是保持原生 Textarea 选择、粘贴与自动增高的结构化文本适配器；token 的文字仍显示在输入中，不渲染成不可编辑的行内胶囊。编辑 token 内部会解除其结构化身份；在边界使用 Backspace/Delete 会整体删除。输入法合成为一次撤销事务，Enter 在候选打开时确认候选，否则依照 `submitMode` 发送或换行。调用方可通过 `change` 获取原子快照，或同步接收 `update:modelValue` 与 `update:tokens`。

### QuireChatRichInput

#### Props

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| modelValue | 是 | — | Controlled literal text. |
| tokens | 是 | — | Controlled structured tokens; changes are emitted separately and atomically in change. |
| label | 是 | — | Accessible field name. |
| resolveCandidates | 是 | — | Feature resolver; AbortSignal is canceled on query change and unmount. |
| placeholder | 否 | — | Host-specific empty field hint; the language pack supplies the default. |
| submitMode | 否 | "enter" | Enter submits unless a candidate list owns it. |
| rows | 否 | 2 | Minimum visible lines. |
| maxRows | 否 | 8 | Maximum auto-resized lines. |
| disabled | 否 | false | Suppress editing and candidate lookup. |
| readOnly | 否 | false | Allow selection and copy, but not editing or candidate lookup. |

**modelValue**

```ts
string
```

**tokens**

```ts
readonly QuireKitChatInputToken[]
```

```ts
readonly ({
  /** Stable identity of this occurrence, distinct from the referenced candidate. */
  id: string;
  /** Feature-owned identity to resolve when the draft is submitted. */
  key: string;
  /** Trigger family. */
  kind: "mention" | "command";
  /** Half-open UTF-16 range in the literal draft, including the trigger character. */
  from: number;
  /** Exclusive end of the token's visible text. */
  to: number;
  /** Visible text, including the trigger character. */
  text: string;
})[]
```

**label**

```ts
string
```

**resolveCandidates**

```ts
(query: QuireKitChatInputQuery, signal: AbortSignal) => readonly QuireKitChatInputCandidate[] | Promise<readonly QuireKitChatInputCandidate[]>
```

```ts
{ (query: QuireKitChatInputQuery, signal: AbortSignal): readonly QuireKitChatInputCandidate[] | Promise<readonly QuireKitChatInputCandidate[]>; }
```

**placeholder**

```ts
string | undefined
```

```ts
undefined | string
```

**submitMode**

```ts
"enter" | "button" | undefined
```

```ts
undefined | "enter" | "button"
```

**rows**

```ts
number | undefined
```

```ts
undefined | number
```

**maxRows**

```ts
number | undefined
```

```ts
undefined | number
```

**disabled**

```ts
boolean | undefined
```

**readOnly**

```ts
boolean | undefined
```

#### Events

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| selectionChange | 否 | — |  |
| update\:modelValue | 否 | — |  |
| submit | 否 | — |  |
| change | 否 | — |  |
| update\:tokens | 否 | — |  |
| candidateError | 否 | — |  |

**selectionChange**

```ts
[selection: QuireKitChatInputSelection]
```

**update:modelValue**

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

**submit**

```ts
[snapshot: QuireKitChatInputSnapshot]
```

**change**

```ts
[snapshot: QuireKitChatInputSnapshot]
```

**update:tokens**

```ts
[tokens: readonly QuireKitChatInputToken[]]
```

**candidateError**

```ts
[error: unknown]
```

#### Slots

无。

#### 公开实例成员

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| focus | 否 | — |  |
| getSnapshot | 否 | — |  |
| setSelection | 否 | — |  |

**focus**

```ts
(options?: FocusOptions | undefined) => void
```

```ts
{ (options?: FocusOptions | undefined): void; }
```

**getSnapshot**

```ts
() => QuireKitChatInputSnapshot
```

```ts
{ (): QuireKitChatInputSnapshot; }
```

**setSelection**

```ts
(next: QuireKitChatInputSelection) => void
```

```ts
{ (next: QuireKitChatInputSelection): void; }
```

#### 相关类型

```ts
type QuireKitChatInputToken = {
  /** Stable identity of this occurrence, distinct from the referenced candidate. */
  id: string;
  /** Feature-owned identity to resolve when the draft is submitted. */
  key: string;
  /** Trigger family. */
  kind: "mention" | "command";
  /** Half-open UTF-16 range in the literal draft, including the trigger character. */
  from: number;
  /** Exclusive end of the token's visible text. */
  to: number;
  /** Visible text, including the trigger character. */
  text: string;
};
```

## API

默认输入和提交也可以独立使用：[Composer Input](/raw/components/chat-composer-input.md) 负责轻量文本键盘合同，[Composer Submit](/raw/components/chat-composer-submit.md) 负责发送/停止状态。自定义 `input` slot 的富输入由宿主持有键盘与焦点，不会由根组件自动接管。

### QuireChatComposer

#### Props

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| modelValue | 是 | — | 受控原始文本。 |
| layout | 否 | "panel" | panel 正文独占上行；inline 输入和动作并排，默认从一行增高。 |
| density | 否 | "comfortable" | comfortable 保留常规内边距；compact 缩紧表面和发送按钮，适合编辑器侧栏。 |
| variant | 否 | "outline" | 表面外观，保持同一输入和焦点边界。 |
| busy | 否 | false | 显示停止动作并禁止再次提交；输入默认仍可编辑。 |
| disabled | 否 | false | 禁用输入、发送与停止；插槽内自定义动作使用 context.disabled 同步。 |
| readOnly | 否 | false | 保留复制但禁止修改与发送；仍允许停止。 |
| hasContent | 否 | false | 存在可提交的外部内容，例如宿主持有的附件，允许空文本提交。 |
| submitDisabled | 否 | false | 仅禁止发送，例如附件等待就绪；不影响编辑或停止。 |
| addTransferFiles | 否 | — | 可选的文件粘贴/拖入接缝；返回 true 表示已交给 FileUpload 等所有者处理，不拦截普通文字。 |
| submitAppearance | 否 | "icon" | 默认圆形图标提交；text 显示文字按钮。 |
| submitColor | 否 | "primary" | 默认 primary 主题主色，可选择其他公共 Button 语义色。 |
| label | 否 | — | 输入框可访问名称；省略时取语言包。 |
| placeholder | 否 | — | 宿主场景的空草稿提示；省略时取语言包。 |
| size | 否 | "md" | 输入文字和内间距的 Textarea 尺寸，默认 md；不改变工具控件尺寸。 |
| submitMode | 否 | "enter" | enter 发送、Shift+Enter 换行；button 保留原生 Enter。 |
| rows | 否 | — | 自动增高的最小行数。 |
| maxRows | 否 | 8 | 自动增高的最大行数。 |

**modelValue**

```ts
string
```

**layout**

```ts
"panel" | "inline" | undefined
```

```ts
undefined | "panel" | "inline"
```

**density**

```ts
"comfortable" | "compact" | undefined
```

```ts
undefined | "comfortable" | "compact"
```

**variant**

```ts
"outline" | "elevated" | "soft" | undefined
```

```ts
undefined | "outline" | "elevated" | "soft"
```

**busy**

```ts
boolean | undefined
```

**disabled**

```ts
boolean | undefined
```

**readOnly**

```ts
boolean | undefined
```

**hasContent**

```ts
boolean | undefined
```

**submitDisabled**

```ts
boolean | undefined
```

**addTransferFiles**

```ts
((transfer: DataTransfer) => boolean) | undefined
```

```ts
undefined | { (transfer: DataTransfer): boolean; }
```

**submitAppearance**

```ts
"icon" | "text" | undefined
```

```ts
undefined | "icon" | "text"
```

**submitColor**

```ts
QuireKitButtonColor | undefined
```

```ts
undefined | "primary" | "neutral" | "info" | "success" | "warning" | "danger"
```

**label**

```ts
string | undefined
```

```ts
undefined | string
```

**placeholder**

```ts
string | undefined
```

```ts
undefined | string
```

**size**

```ts
QuireKitControlSize | undefined
```

```ts
undefined | "sm" | "md" | "xs" | "lg" | "xl"
```

**submitMode**

```ts
"enter" | "button" | undefined
```

```ts
undefined | "enter" | "button"
```

**rows**

```ts
number | undefined
```

```ts
undefined | number
```

**maxRows**

```ts
number | undefined
```

```ts
undefined | number
```

#### Events

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| update\:modelValue | 否 | — |  |
| submit | 否 | — |  |
| stop | 否 | — |  |

**update:modelValue**

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

**submit**

```ts
[details: QuireKitChatSubmitDetails]
```

**stop**

```ts
[]
```

#### Slots

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| header | 否 | — | 附件或引用等上部内容。 |
| leading | 否 | — | 与输入并排的图标或上下文入口。 |
| input | 否 | — | 替换默认 Textarea；自行处理输入法和键盘。 |
| tools | 否 | — | 起始侧的附件、权限等宿主操作。 |
| actions | 否 | — | 结束侧、发送之前的模型、语音等宿主操作。 |
| submit | 否 | — | 替换默认发送/停止按钮。 |
| footer | 否 | — | 提示、错误或恢复操作。 |

**header**

```ts
QuireKitChatComposerContext
```

```ts
{
  /** 当前受控草稿。 */
  value: string;
  /** 输入框名称。 */
  label: string;
  /** 是否禁用。 */
  disabled: boolean;
  /** 是否只读。 */
  readOnly: boolean;
  /** 是否正在处理。 */
  busy: boolean;
  /** 当前可用的键盘提交方式，供自定义输入沿用。 */
  submitMode: "enter" | "button";
  /** 文本或外部内容非空，且所有提交门禁允许。 */
  canSubmit: boolean;
  /** 通知宿主更新草稿。 */
  updateValue: { (value: string): void; };
  /** 发出原始草稿的提交意图。 */
  submit: { (): void; };
  /** 发出停止意图。 */
  stop: { (): void; };
}
```

**leading**

```ts
QuireKitChatComposerContext
```

```ts
{
  /** 当前受控草稿。 */
  value: string;
  /** 输入框名称。 */
  label: string;
  /** 是否禁用。 */
  disabled: boolean;
  /** 是否只读。 */
  readOnly: boolean;
  /** 是否正在处理。 */
  busy: boolean;
  /** 当前可用的键盘提交方式，供自定义输入沿用。 */
  submitMode: "enter" | "button";
  /** 文本或外部内容非空，且所有提交门禁允许。 */
  canSubmit: boolean;
  /** 通知宿主更新草稿。 */
  updateValue: { (value: string): void; };
  /** 发出原始草稿的提交意图。 */
  submit: { (): void; };
  /** 发出停止意图。 */
  stop: { (): void; };
}
```

**input**

```ts
QuireKitChatComposerContext
```

```ts
{
  /** 当前受控草稿。 */
  value: string;
  /** 输入框名称。 */
  label: string;
  /** 是否禁用。 */
  disabled: boolean;
  /** 是否只读。 */
  readOnly: boolean;
  /** 是否正在处理。 */
  busy: boolean;
  /** 当前可用的键盘提交方式，供自定义输入沿用。 */
  submitMode: "enter" | "button";
  /** 文本或外部内容非空，且所有提交门禁允许。 */
  canSubmit: boolean;
  /** 通知宿主更新草稿。 */
  updateValue: { (value: string): void; };
  /** 发出原始草稿的提交意图。 */
  submit: { (): void; };
  /** 发出停止意图。 */
  stop: { (): void; };
}
```

**tools**

```ts
QuireKitChatComposerContext
```

```ts
{
  /** 当前受控草稿。 */
  value: string;
  /** 输入框名称。 */
  label: string;
  /** 是否禁用。 */
  disabled: boolean;
  /** 是否只读。 */
  readOnly: boolean;
  /** 是否正在处理。 */
  busy: boolean;
  /** 当前可用的键盘提交方式，供自定义输入沿用。 */
  submitMode: "enter" | "button";
  /** 文本或外部内容非空，且所有提交门禁允许。 */
  canSubmit: boolean;
  /** 通知宿主更新草稿。 */
  updateValue: { (value: string): void; };
  /** 发出原始草稿的提交意图。 */
  submit: { (): void; };
  /** 发出停止意图。 */
  stop: { (): void; };
}
```

**actions**

```ts
QuireKitChatComposerContext
```

```ts
{
  /** 当前受控草稿。 */
  value: string;
  /** 输入框名称。 */
  label: string;
  /** 是否禁用。 */
  disabled: boolean;
  /** 是否只读。 */
  readOnly: boolean;
  /** 是否正在处理。 */
  busy: boolean;
  /** 当前可用的键盘提交方式，供自定义输入沿用。 */
  submitMode: "enter" | "button";
  /** 文本或外部内容非空，且所有提交门禁允许。 */
  canSubmit: boolean;
  /** 通知宿主更新草稿。 */
  updateValue: { (value: string): void; };
  /** 发出原始草稿的提交意图。 */
  submit: { (): void; };
  /** 发出停止意图。 */
  stop: { (): void; };
}
```

**submit**

```ts
QuireKitChatComposerContext
```

```ts
{
  /** 当前受控草稿。 */
  value: string;
  /** 输入框名称。 */
  label: string;
  /** 是否禁用。 */
  disabled: boolean;
  /** 是否只读。 */
  readOnly: boolean;
  /** 是否正在处理。 */
  busy: boolean;
  /** 当前可用的键盘提交方式，供自定义输入沿用。 */
  submitMode: "enter" | "button";
  /** 文本或外部内容非空，且所有提交门禁允许。 */
  canSubmit: boolean;
  /** 通知宿主更新草稿。 */
  updateValue: { (value: string): void; };
  /** 发出原始草稿的提交意图。 */
  submit: { (): void; };
  /** 发出停止意图。 */
  stop: { (): void; };
}
```

**footer**

```ts
QuireKitChatComposerContext
```

```ts
{
  /** 当前受控草稿。 */
  value: string;
  /** 输入框名称。 */
  label: string;
  /** 是否禁用。 */
  disabled: boolean;
  /** 是否只读。 */
  readOnly: boolean;
  /** 是否正在处理。 */
  busy: boolean;
  /** 当前可用的键盘提交方式，供自定义输入沿用。 */
  submitMode: "enter" | "button";
  /** 文本或外部内容非空，且所有提交门禁允许。 */
  canSubmit: boolean;
  /** 通知宿主更新草稿。 */
  updateValue: { (value: string): void; };
  /** 发出原始草稿的提交意图。 */
  submit: { (): void; };
  /** 发出停止意图。 */
  stop: { (): void; };
}
```

#### 公开实例成员

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

**focus**

```ts
(options?: FocusOptions | undefined) => void
```

```ts
{ (options?: FocusOptions | undefined): void; }
```

#### 相关类型

```ts
type QuireKitChatComposerContext = {
  /** 当前受控草稿。 */
  value: string;
  /** 输入框名称。 */
  label: string;
  /** 是否禁用。 */
  disabled: boolean;
  /** 是否只读。 */
  readOnly: boolean;
  /** 是否正在处理。 */
  busy: boolean;
  /** 当前可用的键盘提交方式，供自定义输入沿用。 */
  submitMode: "enter" | "button";
  /** 文本或外部内容非空，且所有提交门禁允许。 */
  canSubmit: boolean;
  /** 通知宿主更新草稿。 */
  updateValue: { (value: string): void; };
  /** 发出原始草稿的提交意图。 */
  submit: { (): void; };
  /** 发出停止意图。 */
  stop: { (): void; };
};
```
