TypeScript
revert: "fix(clients): show question option previews" (#21933) (#22229)
Theo Browne8eafe058ca77
diff --git a/apps/mobile/src/features/threads/PendingUserInputCard.tsx b/apps/mobile/src/features/threads/PendingUserInputCard.tsxindex b7fb9a107df..6be28f295d6 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, useState } from "react";+import { useCallback, useRef } from "react";import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native";import Animated, {Easing,@@ -79,22 +79,6 @@ 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;@@ -254,19 +238,6 @@ 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">@@ -274,16 +245,14 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {</Text><QuestionText markdown={question.question} /><View className="gap-2">- {question.options.map((option, optionIndex) => {+ {question.options.map((option) => {const optionValue = option.value ?? option.label.trim();const selected = isPendingUserInputOptionSelected(question, draft, optionValue);const description =option.description !== option.label ? option.description : undefined;return (<Pressable- // 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}`}+ key={optionValue}accessibilityRole={question.multiSelect ? "checkbox" : "radio"}accessibilityState={{ checked: selected, disabled: responseDisabled }}disabled={responseDisabled}@@ -291,18 +260,13 @@ 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={() => {- setFocusedOption({- requestId: props.pendingUserInput.requestId,- questionId: question.id,- optionIndex,- });+ onPress={() =>props.onSelectOption(props.pendingUserInput.requestId,question,optionValue,- );- }}+ )+ }><View className="min-w-0 flex-1 gap-0.5"><Text@@ -323,14 +287,6 @@ 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}@@ -338,14 +294,9 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {questions={props.pendingUserInput.questions}disabled={responseDisabled}value={draft?.customAnswer ?? ""}- onChangeText={(value) => {- setFocusedOption(null);- props.onChangeCustomAnswer(- props.pendingUserInput.requestId,- question.id,- value,- );- }}+ onChangeText={(value) =>+ 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 1dc2a99a41c..b0d14d50472 100644--- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx+++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx@@ -11,11 +11,9 @@ 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()),@@ -42,48 +40,17 @@ const prompt = {})),};-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;-}) {+function Questions({ initialIndex = 0 }: { initialIndex?: number }) {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={[pendingPrompt]}+ pendingUserInputs={[prompt]}cwd="/repo"threadRef={threadRef}disabled={false}@@ -92,7 +59,7 @@ function Questions({questionIndex={questionIndex}onAdvance={advance}onToggleOption={(questionId, value) => {- const question = pendingPrompt.questions.find((entry) => entry.id === questionId)!;+ const question = prompt.questions.find((entry) => entry.id === questionId)!;setAnswers((existing) => ({...existing,[questionId]: togglePendingUserInputOptionSelection(@@ -325,94 +292,3 @@ 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 f35e1c5b0c2..bfcfa490506 100644--- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx+++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx@@ -91,10 +91,6 @@ 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);@@ -106,23 +102,6 @@ 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 (@@ -148,9 +127,8 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(return clearAutoAdvance;}, [activeQuestion?.id, disabled]);- const handleOptionSelection = (questionId: string, optionValue: string, optionIndex: number) => {+ const handleOptionSelection = (questionId: string, optionValue: string) => {if (disabled || isResponding) return;- setFocusedOption({ questionId, optionIndex });if (activeQuestion?.multiSelect) {onToggleOption(questionId, optionValue);return;@@ -189,7 +167,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(const option = activeQuestion.options[optionIndex];if (!option) return;event.preventDefault();- selectOptionFromShortcut(activeQuestion.id, option.value ?? option.label, optionIndex);+ selectOptionFromShortcut(activeQuestion.id, option.value ?? option.label);};document.addEventListener("keydown", handler);return () => document.removeEventListener("keydown", handler);@@ -305,19 +283,11 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard();return (<button- // 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}`}+ key={`${activeQuestion.id}:${optionValue}`}type="button"disabled={disabled || isResponding}- onMouseEnter={() =>- setFocusedOption({ questionId: activeQuestion.id, optionIndex: index })- }- onFocus={() =>- setFocusedOption({ questionId: activeQuestion.id, optionIndex: index })- }onClick={() => {- handleOptionSelection(activeQuestion.id, optionValue, index);+ handleOptionSelection(activeQuestion.id, optionValue);}}className={className}>@@ -326,23 +296,6 @@ 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 7f14db16cc6..fb159426b5f 100644--- a/apps/web/src/pendingUserInput.ts+++ b/apps/web/src/pendingUserInput.ts@@ -1,5 +1,4 @@-import type { ThreadContextRecord } from "@t3tools/contracts";-import type { ThreadUserInputQuestion as UserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";+import type { ThreadContextRecord, UserInputQuestion } from "@t3tools/contracts";import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";import { formatThreadLink } from "@t3tools/shared/threadLinks";