TypeScript
fix(clients): show question option previews (#21933)
Julius Marminge36641146c9c0
diff --git a/apps/mobile/src/features/threads/PendingUserInputCard.tsx b/apps/mobile/src/features/threads/PendingUserInputCard.tsxindex 6be28f295d6..b7fb9a107df 100644--- a/apps/mobile/src/features/threads/PendingUserInputCard.tsx+++ b/apps/mobile/src/features/threads/PendingUserInputCard.tsx@@ -2,7 +2,7 @@ import { Button } from "../../components/ui/Button";import { QuestionAttachments } from "./QuestionAttachments";import type { RuntimeRequestId } from "@t3tools/contracts";import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";-import { useCallback, useRef } from "react";+import { useCallback, useRef, useState } from "react";import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native";import Animated, {Easing,@@ -79,6 +79,22 @@ function QuestionText(props: { readonly markdown: string }) {}export function PendingUserInputCard(props: PendingUserInputCardProps) {+ const [focusedOption, setFocusedOption] = useState<{+ requestId: RuntimeRequestId;+ questionId: string;+ optionIndex: number;+ } | null>(null);+ const focusedQuestion = props.pendingUserInput.questions.find(+ (question) => question.id === focusedOption?.questionId,+ );+ if (+ focusedOption &&+ (focusedOption.requestId !== props.pendingUserInput.requestId ||+ !focusedQuestion ||+ (props.drafts[focusedQuestion.id]?.customAnswer?.trim().length ?? 0) > 0)+ ) {+ setFocusedOption(null);+ }const questionCount = props.pendingUserInput.questions.length;const canRespond = props.pendingUserInput.responseCapability !== "not_resumable";const isResponding = props.respondingUserInputId === props.pendingUserInput.requestId;@@ -238,6 +254,19 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {) : null}{props.pendingUserInput.questions.map((question) => {const draft = props.drafts[question.id];+ const customAnswerActive = (draft?.customAnswer?.trim().length ?? 0) > 0;+ const selectedOptionValue = draft?.selectedOptionValues?.at(-1);+ const savedOptionMatches = question.options.filter(+ (option) => (option.value ?? option.label.trim()) === selectedOptionValue,+ );+ const previewOption = customAnswerActive+ ? undefined+ : focusedOption?.requestId === props.pendingUserInput.requestId &&+ focusedOption.questionId === question.id+ ? question.options[focusedOption.optionIndex]+ : savedOptionMatches.length === 1+ ? savedOptionMatches[0]+ : undefined;return (<View key={question.id} className="gap-2 pt-1"><Text className="font-t3-bold text-xs uppercase tracking-[1px] text-foreground-muted">@@ -245,14 +274,16 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {</Text><QuestionText markdown={question.question} /><View className="gap-2">- {question.options.map((option) => {+ {question.options.map((option, optionIndex) => {const optionValue = option.value ?? option.label.trim();const selected = isPendingUserInputOptionSelected(question, draft, optionValue);const description =option.description !== option.label ? option.description : undefined;return (<Pressable- key={optionValue}+ // Options keep their positions within a question and may share answer values.+ // oxlint-disable-next-line react/no-array-index-key+ key={`${question.id}:${optionIndex}`}accessibilityRole={question.multiSelect ? "checkbox" : "radio"}accessibilityState={{ checked: selected, disabled: responseDisabled }}disabled={responseDisabled}@@ -260,13 +291,18 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {"min-h-12 w-full rounded-2xl border px-3.5 py-3",selected ? "border-primary bg-primary/10" : "border-border bg-input",)}- onPress={() =>+ onPress={() => {+ setFocusedOption({+ requestId: props.pendingUserInput.requestId,+ questionId: question.id,+ optionIndex,+ });props.onSelectOption(props.pendingUserInput.requestId,question,optionValue,- )- }+ );+ }}><View className="min-w-0 flex-1 gap-0.5"><Text@@ -287,6 +323,14 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {);})}</View>+ {previewOption?.preview?.trim() ? (+ <View className="gap-1.5 rounded-2xl border border-border bg-input p-3.5">+ <Text className="font-t3-bold text-xs text-foreground-muted">+ Preview · {previewOption.label}+ </Text>+ <QuestionText markdown={previewOption.preview} />+ </View>+ ) : null}{question.allowCustomAnswer !== false ? (<QuestionAttachmentsrequestId={props.pendingUserInput.requestId}@@ -294,9 +338,14 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {questions={props.pendingUserInput.questions}disabled={responseDisabled}value={draft?.customAnswer ?? ""}- onChangeText={(value) =>- props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)- }+ onChangeText={(value) => {+ setFocusedOption(null);+ props.onChangeCustomAnswer(+ props.pendingUserInput.requestId,+ question.id,+ value,+ );+ }}onInputFocusChange={props.onInputFocusChange}/>) : null}diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsxindex b0d14d50472..1dc2a99a41c 100644--- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx+++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx@@ -11,9 +11,11 @@ import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";import {+ setPendingUserInputCustomAnswer,togglePendingUserInputOptionSelection,type PendingUserInputDraftAnswer,} from "../../pendingUserInput";+import type { PendingUserInput } from "../../session-logic";vi.mock(import("../ChatMarkdown"), async (importOriginal) => ({...(await importOriginal()),@@ -40,17 +42,48 @@ const prompt = {})),};-function Questions({ initialIndex = 0 }: { initialIndex?: number }) {+const previewPrompt = {+ ...prompt,+ questions: prompt.questions.map((question, index) => ({+ ...question,+ options: ["First", "Second"].map((label) => ({+ label,+ value: index === 1 ? label : "same-answer",+ description: "",+ preview: `Preview body: ${label}, question ${index + 1}`,+ })),+ })),+};++function Questions({+ initialIndex = 0,+ pendingPrompt = prompt,+}: {+ initialIndex?: number;+ pendingPrompt?: PendingUserInput;+}) {const [questionIndex, setQuestionIndex] = useState(initialIndex);const [answers, setAnswers] = useState<Record<string, PendingUserInputDraftAnswer>>({});+ const question = pendingPrompt.questions[questionIndex]!;const advance = () => setQuestionIndex(questionIndex + 1);return (<><output>{questionIndex}</output><button onClick={advance}>Next</button><button onClick={() => setQuestionIndex(questionIndex - 1)}>Previous</button>+ <input+ aria-label="Custom answer"+ value={answers[question.id]?.customAnswer ?? ""}+ onChange={(event) => {+ const value = event.currentTarget.value;+ setAnswers((existing) => ({+ ...existing,+ [question.id]: setPendingUserInputCustomAnswer(existing[question.id], value, question),+ }));+ }}+ /><ComposerPendingUserInputPanel- pendingUserInputs={[prompt]}+ pendingUserInputs={[pendingPrompt]}cwd="/repo"threadRef={threadRef}disabled={false}@@ -59,7 +92,7 @@ function Questions({ initialIndex = 0 }: { initialIndex?: number }) {questionIndex={questionIndex}onAdvance={advance}onToggleOption={(questionId, value) => {- const question = prompt.questions.find((entry) => entry.id === questionId)!;+ const question = pendingPrompt.questions.find((entry) => entry.id === questionId)!;setAnswers((existing) => ({...existing,[questionId]: togglePendingUserInputOptionSelection(@@ -292,3 +325,94 @@ it("isolates drafts by environment, thread and request and discards only resolve);}});++function expectPreview(text: string | null) {+ const previews = [...container.querySelectorAll("p")]+ .map((element) => element.textContent)+ .filter((content) => content?.startsWith("Preview body:"));+ expect(previews).toEqual(text === null ? [] : [`Preview body: ${text}`]);+}++async function typeCustomAnswer(value: string) {+ const input = container.querySelector("input")!;+ await act(async () => {+ input.focus();+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);+ input.dispatchEvent(new Event("input", { bubbles: true }));+ });+}++it("previews options by focus, click, and shortcut index but only restores unambiguous saved selections", async () => {+ await act(async () => root.render(<Questions pendingPrompt={previewPrompt} />));+ expectPreview("First, question 1");++ await act(async () => buttonWithText("Second").focus());+ expectPreview("Second, question 1");+ await act(async () => buttonWithText("First").focus());+ expectPreview("First, question 1");++ await act(async () => buttonWithText("Second").click());+ expectPreview("Second, question 1");+ await act(async () => document.dispatchEvent(new KeyboardEvent("keydown", { key: "1" })));+ expectPreview("First, question 1");+ await act(async () => document.dispatchEvent(new KeyboardEvent("keydown", { key: "2" })));+ expectPreview("Second, question 1");++ await act(async () => vi.advanceTimersByTime(200));+ expect(activeIndex()).toBe("1");+ expectPreview("First, question 2");++ await act(async () => buttonWithText("Second").focus());+ expectPreview("Second, question 2");+ await act(async () =>+ root.render(+ <Questions+ pendingPrompt={{ ...previewPrompt, requestId: RuntimeRequestId.make("replacement") }}+ />,+ ),+ );+ expectPreview("First, question 2");++ await act(async () => buttonWithText("Second").click());+ expectPreview("Second, question 2");+ await navigate("Next");+ expectPreview("First, question 3");+ await navigate("Previous");+ expectPreview("Second, question 2");++ await navigate("Previous");+ expectPreview(null);+ await act(async () =>+ root.render(+ <Questions+ pendingPrompt={{ ...previewPrompt, requestId: RuntimeRequestId.make("remounted") }}+ />,+ ),+ );+ expectPreview(null);+ await act(async () => buttonWithText("Second").click());+ expectPreview("Second, question 1");+});++it("hides and clears hovered or focused previews while a custom answer is active", async () => {+ await act(async () => root.render(<Questions pendingPrompt={previewPrompt} />));+ await act(async () =>+ buttonWithText("Second").dispatchEvent(new MouseEvent("mouseover", { bubbles: true })),+ );+ expectPreview("Second, question 1");++ await typeCustomAnswer("Use a different approach");+ expectPreview(null);+ await typeCustomAnswer("");+ expectPreview("First, question 1");++ await typeCustomAnswer("Use a different approach");+ await act(async () => buttonWithText("Second").focus());+ expectPreview(null);+ await act(async () =>+ buttonWithText("Second").dispatchEvent(new MouseEvent("mouseover", { bubbles: true })),+ );+ expectPreview(null);+ await typeCustomAnswer("");+ expectPreview("First, question 1");+});diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsxindex bfcfa490506..f35e1c5b0c2 100644--- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx+++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx@@ -91,6 +91,10 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(questionId: string;optionValue: string;} | null>(null);+ const [focusedOption, setFocusedOption] = useState<{+ questionId: string;+ optionIndex: number;+ } | null>(null);const [collapsedQuestionId, setCollapsedQuestionId] = useState<string | null>(null);// The active question keys the shortcut listener, so it must keep its identity across renders.const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);@@ -102,6 +106,23 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(!customAnswerActive && progress.selectedOptionValues.includes(option.value ?? option.label),);const isCollapsed = collapsedQuestionId !== null && collapsedQuestionId === activeQuestion?.id;+ const selectedOptionValue = progress.selectedOptionValues.at(-1);+ const savedOptionMatches = activeQuestion?.options.filter(+ (option) => (option.value ?? option.label) === selectedOptionValue,+ );+ const previewOption = customAnswerActive+ ? undefined+ : focusedOption && focusedOption.questionId === activeQuestion?.id+ ? activeQuestion?.options[focusedOption.optionIndex]+ : selectedOptionValue === undefined+ ? activeQuestion?.options[0]+ : savedOptionMatches?.length === 1+ ? savedOptionMatches[0]+ : undefined;++ if (focusedOption && (focusedOption.questionId !== activeQuestion?.id || customAnswerActive)) {+ setFocusedOption(null);+ }// The optimistic pick is dropped once the draft confirms it or the question moves on.if (@@ -127,8 +148,9 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(return clearAutoAdvance;}, [activeQuestion?.id, disabled]);- const handleOptionSelection = (questionId: string, optionValue: string) => {+ const handleOptionSelection = (questionId: string, optionValue: string, optionIndex: number) => {if (disabled || isResponding) return;+ setFocusedOption({ questionId, optionIndex });if (activeQuestion?.multiSelect) {onToggleOption(questionId, optionValue);return;@@ -167,7 +189,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(const option = activeQuestion.options[optionIndex];if (!option) return;event.preventDefault();- selectOptionFromShortcut(activeQuestion.id, option.value ?? option.label);+ selectOptionFromShortcut(activeQuestion.id, option.value ?? option.label, optionIndex);};document.addEventListener("keydown", handler);return () => document.removeEventListener("keydown", handler);@@ -283,11 +305,19 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard();return (<button- key={`${activeQuestion.id}:${optionValue}`}+ // Options keep their positions within a question and may share answer values.+ // oxlint-disable-next-line react/no-array-index-key+ key={`${activeQuestion.id}:${index}`}type="button"disabled={disabled || isResponding}+ onMouseEnter={() =>+ setFocusedOption({ questionId: activeQuestion.id, optionIndex: index })+ }+ onFocus={() =>+ setFocusedOption({ questionId: activeQuestion.id, optionIndex: index })+ }onClick={() => {- handleOptionSelection(activeQuestion.id, optionValue);+ handleOptionSelection(activeQuestion.id, optionValue, index);}}className={className}>@@ -296,6 +326,23 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard();})}</div>+ {previewOption?.preview?.trim() ? (+ <section+ aria-label={`Preview: ${previewOption.label}`}+ className="mt-2 min-w-0 rounded-md border border-border/60 bg-muted/25 p-2.5"+ >+ <p className="mb-1.5 text-3xs font-medium text-muted-foreground">+ Preview · {previewOption.label}+ </p>+ <ChatMarkdown+ key={`${activeQuestion.id}:${activeQuestion.options.indexOf(previewOption)}`}+ text={previewOption.preview}+ cwd={cwd}+ threadRef={threadRef}+ parseRawHtml={false}+ />+ </section>+ ) : null}</ComposerBanner.Body></ComposerBanner.Scroll></CollapsiblePanel>diff --git a/apps/web/src/pendingUserInput.ts b/apps/web/src/pendingUserInput.tsindex fb159426b5f..7f14db16cc6 100644--- a/apps/web/src/pendingUserInput.ts+++ b/apps/web/src/pendingUserInput.ts@@ -1,4 +1,5 @@-import type { ThreadContextRecord, UserInputQuestion } from "@t3tools/contracts";+import type { ThreadContextRecord } from "@t3tools/contracts";+import type { ThreadUserInputQuestion as UserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";import { formatThreadLink } from "@t3tools/shared/threadLinks";