dsh-better-chat/src/client/TurnQuestionCard.tsx

927 lines
33 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { memo, useCallback, useEffect, useState } from 'react';
import type { SessionPendingInteraction } from '@deepseek-ai/dsh-client-ui-session/client';
import type { SessionId } from '@deepseek-ai/dsh-session/types';
import { OFFICIAL_SEATS } from './official-slots.js';
import type { ReaderInjected, ReaderProps } from './types.js';
import {
answerDisplayValues,
formatQuestionFollowUpReply,
type QuestionAnswerItem,
type QuestionItem,
type TurnQuestionEntry,
type TurnQuestionStatus,
} from './turn-questions.js';
import css from './Reader.module.css';
interface QuestionDraft {
readonly id: string;
readonly selected: string[];
readonly custom: string;
}
interface PendingQuestionSnapshotView {
readonly state?: string;
readonly channel?: string;
readonly closed?: boolean;
readonly countdown?: {
readonly remainingMs: number;
readonly running: boolean;
};
}
export interface InteractivePendingQuestion {
readonly key: string;
readonly kind: string;
readonly questions?: readonly QuestionItem[];
readonly review?: readonly QuestionAnswerItem[];
answer(payload: { answers: QuestionAnswerItem[] }): Promise<unknown>;
dismiss?(): Promise<unknown>;
snapshot?(): PendingQuestionSnapshotView;
getSnapshot?(): PendingQuestionSnapshotView;
subscribe?(listener: () => void): () => void;
holdFocus?(): void;
releaseFocus?(): void;
engage?(): void;
}
export function asInteractivePending(
pending: SessionPendingInteraction | undefined,
): InteractivePendingQuestion | undefined {
if (!pending || pending.kind !== 'question') return undefined;
const candidate = pending as unknown as Partial<InteractivePendingQuestion>;
if (typeof candidate.answer !== 'function') return undefined;
if (candidate.review !== undefined) return undefined;
return candidate as InteractivePendingQuestion;
}
function buildInitialDrafts(
questions: readonly QuestionItem[],
answers: readonly QuestionAnswerItem[],
): QuestionDraft[] {
const byId = new Map(answers.map(item => [item.id, item]));
return questions.map(question => {
const prev = byId.get(question.id);
return {
id: question.id,
selected: prev ? [...prev.selected] : [],
custom: prev?.custom ?? '',
};
});
}
function statusBadgeLabel(status: TurnQuestionStatus): string {
switch (status) {
case 'open':
return '待回答';
case 'continued':
return '已继续工作 · 仍可回答';
case 'queued':
return '回答已排队 · 等待接收';
case 'answered':
return '已回答';
case 'cancelled':
return '已取消';
case 'interrupted':
return '已中断';
case 'closed':
return '未作答';
}
}
function summaryLineForEntry(entry: TurnQuestionEntry): string {
const first = entry.questions[0];
if (!first) return statusBadgeLabel(entry.status);
const title = first.header && first.header !== first.question ? first.header : first.question;
const firstAnswer = entry.answers.find(item => item.id === first.id);
const values = answerDisplayValues(firstAnswer);
const tail = entry.questions.length > 1 ? ` · 共 ${entry.questions.length} 题` : '';
if (entry.status === 'answered' || entry.status === 'queued') {
const answerText = values.length > 0 ? values.join('、') : '已跳过';
return `${title}:${answerText}${tail}`;
}
return `${title}${tail}`;
}
export const HostedOfficialQuestion = memo(function HostedOfficialQuestion({
callId,
sessionId,
pending,
useSession,
renderSlotChain,
}: {
callId: string;
sessionId: SessionId;
pending: SessionPendingInteraction;
useSession: ReaderProps['useSession'];
renderSlotChain: ReaderProps['renderSlotChain'];
}) {
const session = useSession(snapshot => snapshot);
const fallback = (
<div className={css.attention} role="alert" data-reader-attention>
<strong>需要你回答一个问题</strong>
<span>请在下方原生操作区处理。此提示不会收进执行过程。</span>
</div>
);
return (
<div
className={css.inlineInteraction}
data-reader-inline-interaction
data-reader-question-call={callId}
data-reader-anchor
>
{renderSlotChain(OFFICIAL_SEATS.composer, {
sessionId,
session,
pendingInteraction: pending,
}, { fallback })}
</div>
);
});
/**
* Native Muse-style flat-in-bubble UI for live pending `ask_user_question` interactions.
* Single-question single-select options render as full-width dashed buttons that
* submit on one click directly inside the AI reply bubble.
*/
export const MuseLiveQuestion = memo(function MuseLiveQuestion({
callId,
pending,
fallbackQuestions,
}: {
callId: string;
pending: InteractivePendingQuestion;
fallbackQuestions?: readonly QuestionItem[];
}) {
const questions = (pending.questions && pending.questions.length > 0)
? pending.questions
: (fallbackQuestions ?? []);
const [step, setStep] = useState(0);
const [drafts, setDrafts] = useState<QuestionDraft[]>(() => buildInitialDrafts(questions, []));
const [customOpen, setCustomOpen] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const [snapshot, setSnapshot] = useState<PendingQuestionSnapshotView>(
() => pending.snapshot?.() ?? pending.getSnapshot?.() ?? {},
);
useEffect(() => {
const sync = () => {
setSnapshot(pending.snapshot?.() ?? pending.getSnapshot?.() ?? {});
};
sync();
return pending.subscribe?.(sync);
}, [pending]);
useEffect(() => {
setDrafts(current => {
if (
current.length === questions.length
&& current.every((item, idx) => item.id === questions[idx]?.id)
) {
return current;
}
return buildInitialDrafts(questions, []);
});
setStep(current => (questions.length > 0 ? Math.min(current, questions.length - 1) : 0));
}, [questions]);
useEffect(() => () => {
pending.releaseFocus?.();
}, [pending]);
const submitPayload = useCallback(async (answers: QuestionAnswerItem[]) => {
if (submitting) return;
setSubmitting(true);
setError(null);
try {
const channel = (pending.snapshot?.() ?? pending.getSnapshot?.())?.channel;
await pending.answer({ answers });
if (channel === 'rpc') {
await pending.dismiss?.();
}
} catch (cause) {
setError(cause instanceof Error ? cause.message : '提交回答失败,请重试。');
} finally {
setSubmitting(false);
}
}, [submitting, pending]);
const activeIndex = Math.min(step, Math.max(0, questions.length - 1));
const currentQuestion = questions[activeIndex];
if (!currentQuestion) return null;
const isSingleQuickPick = questions.length === 1
&& currentQuestion.multiSelect !== true
&& (currentQuestion.options?.length ?? 0) > 0;
const draft = drafts[activeIndex] ?? { id: currentQuestion.id, selected: [], custom: '' };
const channelReady = snapshot.channel !== 'none';
const remainingSec = snapshot.countdown?.running
? Math.ceil(snapshot.countdown.remainingMs / 1000)
: undefined;
const handleOptionClick = (label: string) => {
if (submitting || !channelReady) return;
pending.engage?.();
setError(null);
if (isSingleQuickPick && !customOpen) {
void submitPayload([{ id: currentQuestion.id, selected: [label] }]);
return;
}
const multi = currentQuestion.multiSelect === true;
const nextDrafts = drafts.map((item, idx) => {
if (idx !== activeIndex) return item;
if (multi) {
const exists = item.selected.includes(label);
return {
...item,
selected: exists ? item.selected.filter(x => x !== label) : [...item.selected, label],
};
}
const already = item.selected.length === 1 && item.selected[0] === label;
return { ...item, selected: already ? [] : [label], custom: '' };
});
setDrafts(nextDrafts);
if (!multi && activeIndex < questions.length - 1) {
setStep(activeIndex + 1);
}
};
const handleSubmitDrafts = () => {
const answers: QuestionAnswerItem[] = questions.map((item, idx) => {
const value = drafts[idx] ?? { id: item.id, selected: [], custom: '' };
const custom = value.custom.trim();
return {
id: item.id,
selected: custom === '' || item.multiSelect === true ? [...value.selected] : [],
...(custom !== '' ? { custom } : {}),
};
});
const missingIndex = answers.findIndex(
item => item.selected.length === 0 && (item.custom?.length ?? 0) === 0,
);
if (missingIndex >= 0) {
setStep(missingIndex);
setError('请先选择选项或输入自定义回答。');
return;
}
void submitPayload(answers);
};
const showSubmitBar = !isSingleQuickPick || customOpen;
return (
<div
className={css.museQuestionBlock}
data-reader-inline-interaction
data-reader-turn-question={callId}
data-question-status="open"
data-reader-anchor
onMouseEnter={() => { pending.holdFocus?.(); }}
onMouseLeave={() => { pending.releaseFocus?.(); }}
onFocusCapture={() => { pending.holdFocus?.(); }}
onBlurCapture={event => {
if (!event.currentTarget.contains(event.relatedTarget)) {
pending.releaseFocus?.();
}
}}
>
{questions.length > 1 && (
<div className={css.questionStepTabs} role="tablist" aria-label="问题列表">
{questions.map((item, idx) => {
const done = (drafts[idx]?.selected.length ?? 0) > 0
|| (drafts[idx]?.custom.trim().length ?? 0) > 0;
return (
<button
key={item.id}
type="button"
role="tab"
aria-selected={idx === activeIndex}
className={css.questionStepTab}
data-active={idx === activeIndex || undefined}
data-done={done || undefined}
onClick={() => { setStep(idx); setError(null); }}
>
{`${idx + 1}. ${item.header ?? `问题 ${idx + 1}`}`}
</button>
);
})}
</div>
)}
<div className={css.questionPromptText}>
{currentQuestion.header && currentQuestion.header !== currentQuestion.question && questions.length === 1 && (
<span className={css.questionHeaderChip}>{currentQuestion.header}</span>
)}
<span>{currentQuestion.question}</span>
{currentQuestion.multiSelect === true && <span className={css.questionMultiHint}>多选</span>}
{remainingSec !== undefined && (
<span className={css.questionMultiHint}>{`${remainingSec}s`}</span>
)}
</div>
{currentQuestion.options && currentQuestion.options.length > 0 && (
<div className={css.questionOptionGrid}>
{currentQuestion.options.map(option => {
const selected = draft.selected.includes(option.label);
return (
<button
key={option.label}
type="button"
className={css.questionOptionBtn}
disabled={submitting || !channelReady}
data-selected={selected || undefined}
aria-pressed={selected}
onClick={() => { handleOptionClick(option.label); }}
>
<span className={css.questionOptionRowHead}>
<span className={css.questionOptionLabel}>{option.label}</span>
{selected && <span className={css.questionOptionCheck} aria-hidden="true">✓</span>}
</span>
{option.description && (
<span className={css.questionOptionDesc}>{option.description}</span>
)}
</button>
);
})}
</div>
)}
{(customOpen || (currentQuestion.options?.length ?? 0) === 0) && (
<input
type="text"
className={css.questionCustomInput}
placeholder="输入你的回答…"
value={draft.custom}
disabled={submitting || !channelReady}
onChange={event => {
pending.engage?.();
setError(null);
const value = event.target.value;
setDrafts(current => current.map((item, idx) => (
idx === activeIndex
? { ...item, custom: value, selected: currentQuestion.multiSelect ? item.selected : [] }
: item
)));
}}
onKeyDown={event => {
if (event.key === 'Enter' && (!isSingleQuickPick || event.ctrlKey || event.metaKey || valueOrSubmitReady(draft))) {
if (!currentQuestion.multiSelect && questions.length === 1 && draft.custom.trim()) {
event.preventDefault();
handleSubmitDrafts();
}
}
}}
/>
)}
{error && <p className={css.questionFormError} role="alert">{error}</p>}
<div className={css.questionInlineFoot}>
<div className={css.questionInlineLinks}>
{(currentQuestion.options?.length ?? 0) > 0 && (
<button
type="button"
className={css.questionGhostBtn}
disabled={submitting}
onClick={() => { setCustomOpen(v => !v); }}
>
{customOpen ? '收起输入' : '+ 自定义回答'}
</button>
)}
<button
type="button"
className={css.questionGhostBtn}
disabled={submitting || !channelReady}
onClick={() => {
void submitPayload(questions.map(item => ({ id: item.id, selected: [] })));
}}
>
跳过
</button>
</div>
{showSubmitBar && (
<div className={css.questionCardActions}>
{activeIndex > 0 && (
<button
type="button"
className={css.questionActionBtn}
disabled={submitting}
onClick={() => { setStep(activeIndex - 1); }}
>
上一题
</button>
)}
{activeIndex < questions.length - 1 ? (
<button
type="button"
className={`${css.questionActionBtn} ${css.questionActionPrimary}`}
disabled={submitting}
onClick={() => { setStep(activeIndex + 1); }}
>
下一题
</button>
) : (
<button
type="button"
className={`${css.questionActionBtn} ${css.questionActionPrimary}`}
disabled={submitting || !channelReady}
onClick={handleSubmitDrafts}
>
{submitting ? '正在提交…' : '提交回答'}
</button>
)}
</div>
)}
</div>
</div>
);
});
function valueOrSubmitReady(draft: QuestionDraft): boolean {
return draft.selected.length > 0 || draft.custom.trim().length > 0;
}
export interface TurnQuestionCardProps {
entry: TurnQuestionEntry;
sessionId: SessionId;
pending: SessionPendingInteraction | undefined;
inlineClaimed: boolean;
useSession: ReaderProps['useSession'];
renderSlotChain: ReaderProps['renderSlotChain'];
revealQuestion?: ReaderInjected['revealQuestion'];
reviewQuestion?: ReaderInjected['reviewQuestion'];
answerContinuedQuestion?: ReaderInjected['answerContinuedQuestion'];
sendFollowUp?: ReaderInjected['sendFollowUp'];
fillComposer?: ReaderInjected['fillComposer'];
}
export const TurnQuestionCard = memo(function TurnQuestionCard({
entry,
sessionId,
pending,
inlineClaimed,
useSession,
renderSlotChain,
revealQuestion,
reviewQuestion,
answerContinuedQuestion,
sendFollowUp,
fillComposer,
}: TurnQuestionCardProps) {
const [formOpen, setFormOpen] = useState(false);
const [customOpen, setCustomOpen] = useState(false);
const [detailsOpen, setDetailsOpen] = useState(false);
const [drafts, setDrafts] = useState<QuestionDraft[]>(() =>
buildInitialDrafts(entry.questions, entry.answers),
);
const [submitting, setSubmitting] = useState(false);
const [formError, setFormError] = useState<string | null>(null);
useEffect(() => {
if (entry.status === 'queued' || entry.status === 'answered') {
setFormOpen(false);
setCustomOpen(false);
setFormError(null);
}
}, [entry.status]);
const openForm = useCallback(() => {
setDrafts(buildInitialDrafts(entry.questions, entry.answers));
setFormError(null);
setDetailsOpen(false);
setFormOpen(true);
}, [entry.questions, entry.answers]);
const submitPayload = useCallback(async (payload: QuestionAnswerItem[]) => {
if (submitting) return;
setSubmitting(true);
setFormError(null);
try {
if (entry.status === 'continued' && answerContinuedQuestion) {
const accepted = await answerContinuedQuestion(entry.callId, payload);
if (accepted) {
setFormOpen(false);
setCustomOpen(false);
return;
}
}
const mode = entry.status === 'answered' ? 'revise' : 'answer';
const text = formatQuestionFollowUpReply(entry.questions, payload, mode);
if (sendFollowUp && await sendFollowUp(text)) {
setFormOpen(false);
setCustomOpen(false);
return;
}
if (fillComposer?.(text)) {
setFormOpen(false);
setCustomOpen(false);
return;
}
setFormError('暂时无法提交回答,请稍后再试。');
} catch {
setFormError('暂时无法提交回答,请稍后再试。');
} finally {
setSubmitting(false);
}
}, [submitting, entry.status, entry.callId, entry.questions, answerContinuedQuestion, sendFollowUp, fillComposer]);
const toggleOption = useCallback((
question: QuestionItem,
label: string,
quickSubmitSingle: boolean,
) => {
if (submitting) return;
setFormError(null);
if (quickSubmitSingle && !customOpen) {
void submitPayload([{ id: question.id, selected: [label] }]);
return;
}
const multi = question.multiSelect === true;
setDrafts(current => current.map(draft => {
if (draft.id !== question.id) return draft;
if (multi) {
const exists = draft.selected.includes(label);
return {
...draft,
selected: exists
? draft.selected.filter(item => item !== label)
: [...draft.selected, label],
};
}
const alreadyOnly = draft.selected.length === 1 && draft.selected[0] === label;
return {
...draft,
selected: alreadyOnly ? [] : [label],
};
}));
}, [submitting, customOpen, submitPayload]);
const updateCustom = useCallback((questionId: string, custom: string) => {
setFormError(null);
setDrafts(current => current.map(draft => (
draft.id === questionId ? { ...draft, custom } : draft
)));
}, []);
const buildPayload = useCallback((): QuestionAnswerItem[] | null => {
const items: QuestionAnswerItem[] = drafts.map(draft => {
const custom = draft.custom.trim();
return {
id: draft.id,
selected: [...draft.selected],
...(custom.length > 0 ? { custom } : {}),
};
});
const hasAny = items.some(item => item.selected.length > 0 || (item.custom?.length ?? 0) > 0);
if (!hasAny) {
setFormError('请至少选择一个选项或填写自定义回答。');
return null;
}
return items;
}, [drafts]);
const followUpMode = entry.status === 'answered' ? 'revise' : 'answer';
const handleFillComposer = useCallback(() => {
const payload = buildPayload();
if (!payload) return;
const text = formatQuestionFollowUpReply(entry.questions, payload, followUpMode);
if (fillComposer?.(text)) {
setFormOpen(false);
} else {
setFormError('未能写入底部输入框,请稍后重试。');
}
}, [buildPayload, entry.questions, followUpMode, fillComposer]);
const handleSubmit = useCallback(async () => {
const payload = buildPayload();
if (!payload) return;
await submitPayload(payload);
}, [buildPayload, submitPayload]);
// 1. Active pending interaction: prefer native Muse bubble layout; fall back to slot host if needed.
if (pending !== undefined && inlineClaimed) {
const interactive = asInteractivePending(pending);
if (interactive) {
return (
<MuseLiveQuestion
callId={entry.callId}
pending={interactive}
fallbackQuestions={entry.questions}
/>
);
}
return (
<HostedOfficialQuestion
callId={entry.callId}
sessionId={sessionId}
pending={pending}
useSession={useSession}
renderSlotChain={renderSlotChain}
/>
);
}
const isActive = entry.status === 'open' || entry.status === 'continued';
const isQueued = entry.status === 'queued';
const answersById = new Map(entry.answers.map(item => [item.id, item]));
const isQuickSingleActive = isActive
&& entry.questions.length === 1
&& entry.questions[0]?.multiSelect !== true
&& (entry.questions[0]?.options?.length ?? 0) > 0;
// 2. Active/continued unanswered question inside the bubble: show Muse dashed options directly!
if (isActive && entry.questions.length > 0) {
const useFormDraft = !isQuickSingleActive || customOpen;
return (
<div
className={css.museQuestionBlock}
data-reader-turn-question={entry.callId}
data-question-status={entry.status}
data-reader-anchor
>
{entry.questions.map(question => {
const draft = drafts.find(item => item.id === question.id) ?? {
id: question.id,
selected: [],
custom: '',
};
const multi = question.multiSelect === true;
return (
<div key={question.id} className={css.questionFormBlock}>
<div className={css.questionPromptText}>
{question.header && question.header !== question.question && (
<span className={css.questionHeaderChip}>{question.header}</span>
)}
<span>{question.question}</span>
{multi && <span className={css.questionMultiHint}>多选</span>}
<span className={css.questionStatusBadge}>{statusBadgeLabel(entry.status)}</span>
</div>
{question.options && question.options.length > 0 && (
<div className={css.questionOptionGrid}>
{question.options.map(option => {
const selected = useFormDraft && draft.selected.includes(option.label);
return (
<button
key={option.label}
type="button"
className={css.questionOptionBtn}
disabled={submitting}
data-selected={selected || undefined}
aria-pressed={selected}
onClick={() => {
if (!useFormDraft && revealQuestion?.(entry.callId)) return;
toggleOption(question, option.label, isQuickSingleActive);
}}
>
<span className={css.questionOptionRowHead}>
<span className={css.questionOptionLabel}>{option.label}</span>
{selected && <span className={css.questionOptionCheck} aria-hidden="true">✓</span>}
</span>
{option.description && (
<span className={css.questionOptionDesc}>{option.description}</span>
)}
</button>
);
})}
</div>
)}
{(customOpen || (question.options?.length ?? 0) === 0) && (
<input
type="text"
className={css.questionCustomInput}
placeholder="自定义回答或补充说明…"
value={draft.custom}
disabled={submitting}
onChange={event => { updateCustom(question.id, event.target.value); }}
onKeyDown={event => {
if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
event.preventDefault();
void handleSubmit();
}
}}
/>
)}
</div>
);
})}
{formError && <p className={css.questionFormError} role="alert">{formError}</p>}
<div className={css.questionInlineFoot}>
<div className={css.questionInlineLinks}>
<button
type="button"
className={css.questionGhostBtn}
disabled={submitting}
onClick={() => { setCustomOpen(value => !value); }}
>
{customOpen ? '收起输入' : '+ 自定义回答'}
</button>
</div>
{useFormDraft && (
<div className={css.questionCardActions}>
<button
type="button"
className={css.questionActionBtn}
disabled={submitting}
onClick={handleFillComposer}
>
填入输入框
</button>
<button
type="button"
className={`${css.questionActionBtn} ${css.questionActionPrimary}`}
disabled={submitting}
onClick={() => { void handleSubmit(); }}
>
{submitting ? '正在发送…' : '提交回答'}
</button>
</div>
)}
</div>
</div>
);
}
// 3. Settled/queued/cancelled/interrupted historical question inside the bubble.
return (
<div
className={css.questionCard}
data-reader-turn-question={entry.callId}
data-question-status={entry.status}
>
<div className={css.questionCardHeader}>
{entry.questions.length > 0 && !isQueued ? (
<button
type="button"
className={css.questionSummaryBtn}
aria-expanded={detailsOpen}
onClick={() => { setDetailsOpen(value => !value); }}
title={detailsOpen ? '收起问题详情' : '展开查看全部问题与回答'}
>
<span className={css.questionStatusBadge}>{statusBadgeLabel(entry.status)}</span>
<span className={css.questionSummaryText}>{summaryLineForEntry(entry)}</span>
</button>
) : (
<div className={css.questionSummaryStatic}>
<span className={css.questionStatusBadge}>{statusBadgeLabel(entry.status)}</span>
<span className={css.questionSummaryText}>{summaryLineForEntry(entry)}</span>
</div>
)}
<div className={css.questionCardActions}>
{!isQueued && entry.reviewRecord !== undefined && reviewQuestion !== undefined && (
<button
type="button"
className={css.questionGhostBtn}
onClick={() => {
setFormOpen(false);
reviewQuestion(entry.callId, entry.reviewRecord!);
}}
>
查看原卡
</button>
)}
{!isQueued && entry.questions.length > 0 && (
<button
type="button"
className={css.questionGhostBtn}
data-reader-question-reanswer
aria-expanded={formOpen}
onClick={() => {
if (formOpen) setFormOpen(false);
else openForm();
}}
>
{formOpen ? '收起' : entry.status === 'answered' ? '重新回答' : '补充回答'}
</button>
)}
</div>
</div>
{!formOpen && (detailsOpen || isQueued) && entry.questions.length > 0 && (
<dl className={css.questionHistoryList}>
{entry.questions.map(question => {
const values = answerDisplayValues(answersById.get(question.id));
return (
<div key={question.id} className={css.questionHistoryItem}>
<dt className={css.questionHistoryPrompt}>
{question.header && question.header !== question.question && (
<span className={css.questionHeaderChip}>{question.header}</span>
)}
<span>{question.question}</span>
</dt>
<dd className={css.questionHistoryAnswer}>
{values.length > 0
? values.join(' · ')
: question.options && question.options.length > 0
? `可选项:${question.options.map(opt => opt.label).join(' / ')}`
: '(未填写)'}
</dd>
</div>
);
})}
</dl>
)}
{formOpen && (
<div className={css.questionReanswerForm} data-reader-question-form>
{entry.questions.map(question => {
const draft = drafts.find(item => item.id === question.id) ?? {
id: question.id,
selected: [],
custom: '',
};
const multi = question.multiSelect === true;
return (
<div key={question.id} className={css.questionFormBlock}>
<div className={css.questionFormPrompt}>
{question.header && question.header !== question.question && (
<span className={css.questionHeaderChip}>{question.header}</span>
)}
<span>{question.question}</span>
{multi && <span className={css.questionMultiHint}>多选</span>}
</div>
{question.options && question.options.length > 0 && (
<div className={css.questionOptionGrid}>
{question.options.map(option => {
const selected = draft.selected.includes(option.label);
return (
<button
key={option.label}
type="button"
className={css.questionOptionBtn}
data-selected={selected || undefined}
aria-pressed={selected}
onClick={() => { toggleOption(question, option.label, false); }}
>
<span className={css.questionOptionRowHead}>
<span className={css.questionOptionLabel}>{option.label}</span>
{selected && <span className={css.questionOptionCheck} aria-hidden="true">✓</span>}
</span>
{option.description && (
<span className={css.questionOptionDesc}>{option.description}</span>
)}
</button>
);
})}
</div>
)}
<input
type="text"
className={css.questionCustomInput}
placeholder="自定义回答或补充说明…"
value={draft.custom}
disabled={submitting}
onChange={event => { updateCustom(question.id, event.target.value); }}
onKeyDown={event => {
if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
event.preventDefault();
void handleSubmit();
}
}}
/>
</div>
);
})}
{formError && <p className={css.questionFormError} role="alert">{formError}</p>}
<div className={css.questionFormFooter}>
<button
type="button"
className={css.questionActionBtn}
disabled={submitting}
onClick={() => { setFormOpen(false); }}
>
取消
</button>
<button
type="button"
className={css.questionActionBtn}
disabled={submitting}
onClick={handleFillComposer}
>
填入输入框
</button>
<button
type="button"
className={`${css.questionActionBtn} ${css.questionActionPrimary}`}
disabled={submitting}
onClick={() => { void handleSubmit(); }}
>
{submitting ? '正在发送…' : entry.status === 'answered' ? '发送新回答' : '提交回答'}
</button>
</div>
</div>
)}
</div>
);
});