# Chat Question

> 在消息中发起结构化提问，并由宿主决定内嵌或独立作答。

网页来源：/components/chat-question

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

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

`QuireChatQuestion` 接收稳定 `requestId` 和有序 `questions`。`presentation="prompt"` 是消息里的轻量入口，发出 `open` 意图，由宿主决定在哪里打开完整表单；默认 `presentation="form"` 复用 RadioGroup、CheckboxGroup 与 Textarea 作答。必答项在提交时提示，`submit` 只发出回答意图；宿主校验、发送并投影 `pending`、`submitting`、`failed`、`answered` 或 `expired`。失败不清空输入；已回答的 prompt 默认收起答案，可在历史消息中展开查看，过期不可编辑。

## 消息内入口与独立作答

将 `kind: 'question'`、`presentation: 'prompt'` 作为 MessagePart 放进消息，点击“回答问题”后，`questionOpen` 经 Message / MessageList 转发，携带 `messageId`、`partId` 和 `requestId`。宿主可在独立区域打开 `presentation="form"` 的同一请求；普通 Composer 始终可以继续聊天。问题草稿和普通聊天草稿由宿主分别保存，两条提交路径互不覆盖。

默认示例展示这套“消息内入口 + 独立作答”组合，也可切换为消息内完整表单或输入区接管。三种都是页面组合，不是组件自行控制 Composer。

### 示例：chat-question/takeover

文件：`takeover.vue`

```vue
<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue';
import type { QuireKitChatQuestionAnswer, QuireKitChatQuestionItem, QuireKitChatQuestionState, QuireKitChatQuestionSubmitDetails } from '@quirekit/ui';
import { QuireButton, QuireChatComposer, QuireChatQuestion } from '@quirekit/ui/vue';
import DesktopExample from './desktop.vue';
import InlineExample from './inline.vue';

const mode = ref<'desktop' | 'inline' | 'takeover'>('desktop');
const composerDraft = ref('请根据文档评估迁移范围');
const questionDraft = ref<readonly QuireKitChatQuestionAnswer[]>([]);
const confirmed = ref<readonly QuireKitChatQuestionAnswer[]>([]);
const active = ref(false);
const state = ref<QuireKitChatQuestionState>('pending');
const failNext = ref(true);
let timer: ReturnType<typeof setTimeout> | undefined;
const questions: QuireKitChatQuestionItem[] = [
  { id: 'scope', title: '先处理哪个范围？', kind: 'single', options: [{ value: 'ui', label: '组件库' }, { value: 'docs', label: '文档站' }] },
  { id: 'checks', title: '需要哪些验收？', kind: 'multiple', options: [{ value: 'type', label: '类型与测试' }, { value: 'visual', label: '视觉与交互' }],
    customOption: { value: 'other', label: '其他验收', placeholder: '补充其他验收内容…' } },
  { id: 'note', title: '补充说明', kind: 'text', required: false, placeholder: '可选' }
];

/** Present a host-owned question without discarding the Composer draft. */
function open(): void { active.value = true; state.value = 'pending'; }

/** Simulate submit failure once, then a successful host response. */
function submit(details: QuireKitChatQuestionSubmitDetails): void {
  state.value = 'submitting';
  timer = setTimeout(() => {
    if (failNext.value) { state.value = 'failed'; failNext.value = false; }
    else { confirmed.value = details.answers; state.value = 'answered'; }
  }, 500);
}

/** Let the host retire the request and restore the unchanged Composer. */
function finish(): void {
  if (timer) clearTimeout(timer);
  active.value = false;
}
onBeforeUnmount(() => { if (timer) clearTimeout(timer); });
</script>

<template>
  <div class="grid min-w-0 max-w-[44rem] gap-qk-group" data-chat-question-modes>
    <div class="flex flex-wrap items-center gap-qk-control px-qk-surface pt-qk-surface" role="group" aria-label="提问布局">
      <QuireButton size="sm" :variant="mode === 'desktop' ? 'soft' : 'ghost'" @click="mode = 'desktop'">消息内入口</QuireButton>
      <QuireButton size="sm" :variant="mode === 'inline' ? 'soft' : 'ghost'" @click="mode = 'inline'">消息内表单</QuireButton>
      <QuireButton size="sm" :variant="mode === 'takeover' ? 'soft' : 'ghost'" @click="mode = 'takeover'">输入区接管</QuireButton>
    </div>
    <DesktopExample v-if="mode === 'desktop'" />
    <InlineExample v-else-if="mode === 'inline'" />
    <div v-else class="grid min-w-0 max-w-[38rem] gap-qk-group p-qk-surface" data-chat-question-takeover>
      <div v-if="!active"><QuireButton size="sm" color="primary" variant="soft" @click="open">模拟待回答问题</QuireButton></div>
      <QuireChatQuestion v-if="active" request-id="question-demo" title="确认任务范围" description="回答后继续当前会话。"
        :questions="questions" :state="state" :draft="questionDraft" :answers="confirmed" error="发送失败，回答仍保留，请重试。"
        @update:draft="questionDraft = $event" @submit="submit" />
      <div v-if="active && (state === 'answered' || state === 'expired')"><QuireButton size="sm" variant="ghost" @click="finish">继续聊天</QuireButton></div>
      <QuireChatComposer v-if="!active" v-model="composerDraft" label="继续聊天" placeholder="继续输入…" />
      <p class="m-0 text-qk-helper text-qk-text-tertiary">聊天草稿：{{ composerDraft }}</p>
    </div>
  </div>
</template>
```

文件：`desktop.vue`

```vue
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref } from 'vue';
import type { QuireKitChatMessageListItem, QuireKitChatQuestionAnswer, QuireKitChatQuestionItem, QuireKitChatQuestionOpenPartDetails, QuireKitChatQuestionState, QuireKitChatQuestionSubmitDetails, QuireKitChatSubmitDetails } from '@quirekit/ui';
import { QuireButton, QuireChatComposer, QuireChatMessageList, QuireChatQuestion } from '@quirekit/ui/vue';

const requestId = 'desktop-scope-question';
const questions: readonly QuireKitChatQuestionItem[] = [
  { id: 'scope', title: '下一轮先验收哪部分？', kind: 'single', options: [
    { value: 'message', label: '消息与交互', description: '先验证消息内提问、回答与后续回复。' },
    { value: 'composer', label: '输入与附件', description: '先验证输入、上下文与附件。' }
  ], customOption: { value: 'other', label: '其他方向', placeholder: '写下你希望优先验收的部分…' } }
];
const state = ref<QuireKitChatQuestionState>('pending');
const questionDraft = ref<readonly QuireKitChatQuestionAnswer[]>([]);
const confirmed = ref<readonly QuireKitChatQuestionAnswer[]>([]);
const composerDraft = ref('我先补充一下验收背景。');
const followUps = ref<readonly string[]>([]);
const answering = ref(false);
const answerHost = ref<HTMLElement>();
let previousFocus: HTMLElement | null = null;
let timer: ReturnType<typeof setTimeout> | undefined;

const messages = computed<readonly QuireKitChatMessageListItem[]>(() => [
  { messageId: 'desktop-user-request', author: '你', align: 'end', variant: 'soft', parts: [
    { id: 'body', kind: 'text', text: '安排下一轮组件验收。' }
  ] },
  { messageId: 'desktop-assistant-question', author: '助手', parts: [
    { id: 'intro', kind: 'text', text: '可以。下一轮你更希望先看哪一部分？也可以继续在下面补充背景。' },
    { id: 'scope', kind: 'question', requestId, title: '确认验收范围', questions,
      presentation: 'prompt', state: state.value, answers: confirmed.value }
  ] },
  ...followUps.value.map((text, index): QuireKitChatMessageListItem => ({
    messageId: `desktop-follow-up-${index}`, author: '你', align: 'end', variant: 'soft',
    parts: [{ id: 'body', kind: 'text', text }]
  }))
]);

/** Open the answer form without replacing the ordinary chat Composer. */
async function openQuestion(details: QuireKitChatQuestionOpenPartDetails): Promise<void> {
  if (details.requestId !== requestId || details.partId !== 'scope') return;
  previousFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
  answering.value = true;
  await nextTick();
  answerHost.value?.focus();
}

/** Preserve the host-owned answer draft across closing and reopening the form. */
function updateQuestionDraft(answers: readonly QuireKitChatQuestionAnswer[]): void {
  questionDraft.value = answers;
}

/** Dismiss only the answer surface; the request and Composer remain available. */
async function closeAnswer(): Promise<void> {
  answering.value = false;
  await nextTick();
  if (previousFocus?.isConnected) previousFocus.focus();
}

/** Simulate the host acknowledging a structured answer. */
function submitQuestion(details: QuireKitChatQuestionSubmitDetails): void {
  if (details.requestId !== requestId) return;
  if (timer) clearTimeout(timer);
  state.value = 'submitting';
  timer = setTimeout(() => {
    confirmed.value = details.answers;
    state.value = 'answered';
    answering.value = false;
  }, 450);
}

/** Send an ordinary message independently of the pending question. */
function sendMessage(details: QuireKitChatSubmitDetails): void {
  if (!details.text.trim()) return;
  followUps.value = [...followUps.value, details.text];
  if (composerDraft.value === details.text) composerDraft.value = '';
}

onBeforeUnmount(() => { if (timer) clearTimeout(timer); });
</script>

<template>
  <div class="grid min-w-0 max-w-[44rem] gap-qk-group p-qk-surface" data-chat-question-desktop>
    <QuireChatMessageList :messages="messages" height="21rem" label="验收讨论" @question-open="openQuestion" />
    <div v-if="answering" ref="answerHost" class="grid min-w-0 gap-qk-control" tabindex="-1" data-question-reply>
      <div class="flex justify-end"><QuireButton size="sm" variant="text" @click="closeAnswer">收起作答</QuireButton></div>
      <QuireChatQuestion :request-id="requestId" title="确认验收范围" :questions="questions" :state="state"
        :draft="questionDraft" :answers="confirmed" @update:draft="updateQuestionDraft" @submit="submitQuestion" />
    </div>
    <QuireChatComposer v-model="composerDraft" label="继续聊天" placeholder="继续补充，或提出其他问题…" @submit="sendMessage" />
  </div>
</template>
```

文件：`inline.vue`

```vue
<script setup lang="ts">
import { computed, onBeforeUnmount, ref } from 'vue';
import type { QuireKitChatMessageListItem, QuireKitChatQuestionAnswer, QuireKitChatQuestionDraftDetails, QuireKitChatQuestionItem, QuireKitChatQuestionState, QuireKitChatQuestionSubmitPartDetails, QuireKitChatSubmitDetails } from '@quirekit/ui';
import { QuireChatComposer, QuireChatMessageList } from '@quirekit/ui/vue/chat';

const requestId = 'scope-question';
const questions: readonly QuireKitChatQuestionItem[] = [
  { id: 'scope', title: '先确认哪一部分？', kind: 'single', options: [
    { value: 'message', label: '消息与交互', description: '先核对消息内的提问、回答与后续回复。' },
    { value: 'composer', label: '输入与附件', description: '先核对输入框、上下文与附件。' }
  ], customOption: { value: 'other', label: '其他范围', placeholder: '写下你希望先确认的范围…' } }
];
const state = ref<QuireKitChatQuestionState>('pending');
const questionDraft = ref<readonly QuireKitChatQuestionAnswer[]>([]);
const confirmed = ref<readonly QuireKitChatQuestionAnswer[]>([]);
const composerDraft = ref('这个问题我稍后回答，先补充一下背景。');
const followUps = ref<readonly string[]>([]);
let timer: ReturnType<typeof setTimeout> | undefined;

const messages = computed<readonly QuireKitChatMessageListItem[]>(() => [
  { messageId: 'user-request', author: '你', align: 'end', variant: 'soft', parts: [
    { id: 'body', kind: 'text', text: '我们先安排下一轮组件验收。' }
  ] },
  { messageId: 'assistant-question', author: '助手', parts: [
    { id: 'intro', kind: 'text', text: '可以。开始之前想确认优先范围，你也可以继续在下面补充背景。' },
    { id: 'scope', kind: 'question', requestId, title: '确认验收范围', questions, state: state.value,
      draft: questionDraft.value, answers: confirmed.value, error: '提交未成功，原有选择已保留。' }
  ] },
  ...followUps.value.map((text, index): QuireKitChatMessageListItem => ({
    messageId: `follow-up-${index}`, author: '你', align: 'end', variant: 'soft',
    parts: [{ id: 'body', kind: 'text', text }]
  }))
]);

/** Keep the answer draft independent from the ordinary chat draft. */
function updateQuestionDraft(details: QuireKitChatQuestionDraftDetails): void {
  if (details.messageId === 'assistant-question' && details.partId === 'scope') questionDraft.value = details.answers;
}

/** Simulate a host-owned response without hiding the Composer. */
function submitQuestion(details: QuireKitChatQuestionSubmitPartDetails): void {
  if (details.requestId !== requestId || details.messageId !== 'assistant-question') return;
  if (timer) clearTimeout(timer);
  state.value = 'submitting';
  timer = setTimeout(() => { confirmed.value = details.answers; state.value = 'answered'; }, 450);
}

/** Add an ordinary message while the question is still pending. */
function sendMessage(details: QuireKitChatSubmitDetails): void {
  if (!details.text.trim()) return;
  followUps.value = [...followUps.value, details.text];
  if (composerDraft.value === details.text) composerDraft.value = '';
}

onBeforeUnmount(() => { if (timer) clearTimeout(timer); });
</script>

<template>
  <div class="grid min-w-0 max-w-[44rem] gap-qk-group p-qk-surface" data-chat-question-inline>
    <QuireChatMessageList :messages="messages" height="23rem" label="验收讨论"
      @question-draft-change="updateQuestionDraft" @question-submit="submitQuestion" />
    <QuireChatComposer v-model="composerDraft" label="继续聊天" placeholder="补充背景，或继续提出问题…" @submit="sendMessage" />
  </div>
</template>
```

## 选项与自定义回答

单选、多选问题可在 `options` 之外设置 `customOption: { value, label, placeholder? }`。`value` 必须与同题的预设选项值不同；组件把它作为最后一个可选项。选中后显示文本输入：单选时与其他选项互斥，多选时可与预设选项并存。即使问题标记为可选，只要选了自定义项，提交前仍须填写非空文本。

受控 `draft` 的对应答案使用 `value` 表示选中的选项，并用 `custom` 保存自定义文本。切换到其他选项或暂时取消自定义项时，草稿中的文本保留以便重新选回；`submit` 只在自定义项仍被选中时附带 `custom`，不会提交未选中的旧文本。已回答摘要展示输入内容，而不是自定义项的内部 `value`。

## 内嵌表单与可选的输入接管

`draft` / `update:draft` 让宿主持有问题草稿。`presentation="form"` 也可直接作为 MessagePart 内嵌，满足不打开独立作答区的场景。如果产品需要用问题暂时接管输入区，宿主可以隐藏 Composer；结束后恢复原聊天草稿。这只是可选的页面组合，`QuireChatQuestion` 不会自行隐藏输入框。

问题身份、业务校验、请求发送与网络重试仍归宿主。

## API

### QuireChatQuestion

#### Props

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| requestId | 是 | — | Stable request identity; a change resets only the component's uncontrolled draft. |
| title | 是 | — | Request title. |
| questions | 是 | — | Ordered, stable questions. |
| state | 是 | — | Host-owned lifecycle. |
| description | 否 | — | Optional introductory text. |
| presentation | 否 | — | Render answer controls or a compact transcript prompt; defaults to form. |
| draft | 否 | — | Controlled answer draft, independent of the ordinary Composer draft. |
| defaultDraft | 否 | — | Initial uncontrolled answer draft. |
| answers | 否 | — | Confirmed answers shown in the answered state. |
| error | 否 | — | Submission error, shown without clearing the draft. |

**requestId**

```ts
string
```

**title**

```ts
string
```

**questions**

```ts
readonly QuireKitChatQuestionItem[]
```

```ts
readonly ({
  /** Stable identity within the request. */
  id: string;
  /** Visible and accessible prompt. */
  title: string;
  /** Supporting explanation. */
  description?: undefined | string;
  /** Input type. */
  kind: "text" | "single" | "multiple";
  /** Predefined choices for single/multiple questions; unused for text. */
  options?: undefined | readonly ({
    /** Stable option value. */
    value: string;
    /** Visible option text. */
    label: string;
    /** Optional detail below the label. */
    description?: string | undefined;
    /** Whether this option cannot be selected. */
    disabled?: boolean | undefined;
  })[];
  /** Optional free-text choice for single/multiple questions; its value must not occur in options. */
  customOption?: undefined | {
    /** Stable value distinct from every predefined option value in this question. */
    value: string;
    /** Visible choice label, such as “其他”. */
    label: string;
    /** Prompt shown only while this choice is selected; the language pack supplies the default. */
    placeholder?: string | undefined;
  };
  /** Whether a response is required; defaults to true. */
  required?: boolean | undefined;
  /** Text input placeholder. */
  placeholder?: string | undefined;
})[]
```

**state**

```ts
QuireKitChatQuestionState
```

```ts
"pending" | "submitting" | "expired" | "failed" | "answered"
```

**description**

```ts
string | undefined
```

```ts
undefined | string
```

**presentation**

```ts
QuireKitChatQuestionPresentation | undefined
```

```ts
undefined | "form" | "prompt"
```

**draft**

```ts
readonly QuireKitChatQuestionAnswer[] | undefined
```

```ts
undefined | readonly ({
  /** Question identity. */
  questionId: string;
  /** Single/text answers use a string, multiple answers use an ordered array. */
  value: string | readonly (string)[];
  /** Text belonging to the selected custom option; omitted from a submitted answer when not selected. */
  custom?: undefined | string;
})[]
```

**defaultDraft**

```ts
readonly QuireKitChatQuestionAnswer[] | undefined
```

```ts
undefined | readonly ({
  /** Question identity. */
  questionId: string;
  /** Single/text answers use a string, multiple answers use an ordered array. */
  value: string | readonly (string)[];
  /** Text belonging to the selected custom option; omitted from a submitted answer when not selected. */
  custom?: undefined | string;
})[]
```

**answers**

```ts
readonly QuireKitChatQuestionAnswer[] | undefined
```

```ts
undefined | readonly ({
  /** Question identity. */
  questionId: string;
  /** Single/text answers use a string, multiple answers use an ordered array. */
  value: string | readonly (string)[];
  /** Text belonging to the selected custom option; omitted from a submitted answer when not selected. */
  custom?: undefined | string;
})[]
```

**error**

```ts
string | undefined
```

```ts
undefined | string
```

#### Events

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

**submit**

```ts
[details: QuireKitChatQuestionSubmitDetails]
```

**open**

```ts
[details: QuireKitChatQuestionOpenDetails]
```

**update:draft**

```ts
[answers: readonly QuireKitChatQuestionAnswer[]]
```

#### Slots

无。

#### 公开实例成员

无。

#### 相关类型

```ts
type QuireKitChatQuestionItem = {
  /** Stable identity within the request. */
  id: string;
  /** Visible and accessible prompt. */
  title: string;
  /** Supporting explanation. */
  description?: undefined | string;
  /** Input type. */
  kind: "text" | "single" | "multiple";
  /** Predefined choices for single/multiple questions; unused for text. */
  options?: undefined | readonly ({
    /** Stable option value. */
    value: string;
    /** Visible option text. */
    label: string;
    /** Optional detail below the label. */
    description?: string | undefined;
    /** Whether this option cannot be selected. */
    disabled?: boolean | undefined;
  })[];
  /** Optional free-text choice for single/multiple questions; its value must not occur in options. */
  customOption?: undefined | {
    /** Stable value distinct from every predefined option value in this question. */
    value: string;
    /** Visible choice label, such as “其他”. */
    label: string;
    /** Prompt shown only while this choice is selected; the language pack supplies the default. */
    placeholder?: string | undefined;
  };
  /** Whether a response is required; defaults to true. */
  required?: boolean | undefined;
  /** Text input placeholder. */
  placeholder?: string | undefined;
};
```

```ts
type QuireKitChatQuestionKind = "text" | "single" | "multiple";
```

```ts
type QuireKitChatQuestionOption = {
  /** Stable option value. */
  value: string;
  /** Visible option text. */
  label: string;
  /** Optional detail below the label. */
  description?: string | undefined;
  /** Whether this option cannot be selected. */
  disabled?: boolean | undefined;
};
```

```ts
type QuireKitChatQuestionCustomOption = {
  /** Stable value distinct from every predefined option value in this question. */
  value: string;
  /** Visible choice label, such as “其他”. */
  label: string;
  /** Prompt shown only while this choice is selected; the language pack supplies the default. */
  placeholder?: string | undefined;
};
```

```ts
type QuireKitChatQuestionState = "pending" | "submitting" | "expired" | "failed" | "answered";
```

```ts
type QuireKitChatQuestionAnswer = {
  /** Question identity. */
  questionId: string;
  /** Single/text answers use a string, multiple answers use an ordered array. */
  value: string | readonly (string)[];
  /** Text belonging to the selected custom option; omitted from a submitted answer when not selected. */
  custom?: undefined | string;
};
```
