Open History to see the last commit
1import type { UserInputQuestion } from "@t3tools/contracts";
2
3export interface PendingUserInputDraftAnswer {
4 selectedOptionValues?: string[];
5 customAnswer?: string;
6 attachmentCount?: number;
7 attachmentsBlocked?: boolean;
8}
9
10export interface PendingUserInputProgress {
11 questionIndex: number;
12 activeQuestion: UserInputQuestion | null;
13 activeDraft: PendingUserInputDraftAnswer | undefined;
14 selectedOptionValues: string[];
15 customAnswer: string;
16 resolvedAnswer: string | string[] | null;
17 usingCustomAnswer: boolean;
18 answeredQuestionCount: number;
19 isLastQuestion: boolean;
20 isComplete: boolean;
21 canAdvance: boolean;
22}
23
24function normalizeDraftAnswer(value: string | undefined): string | null {
25 if (typeof value !== "string") {
26 return null;
27 }
28
29 const trimmed = value.trim();
30 return trimmed.length > 0 ? trimmed : null;
31}
32
33function normalizeSelectedOptionValues(value: string[] | undefined): string[] {
34 if (!Array.isArray(value)) {
35 return [];
36 }
37
38 // Provider option IDs must stay unchanged, including whitespace.
39 return Array.from(new Set(value.filter((entry) => typeof entry === "string")));
40}
41
42export function resolvePendingUserInputAnswer(
43 question: UserInputQuestion,
44 draft: PendingUserInputDraftAnswer | undefined,
45): string | string[] | null {
46 if (draft?.attachmentsBlocked) return null;
47 const customAnswer =
48 question.allowCustomAnswer === false ? null : normalizeDraftAnswer(draft?.customAnswer);
49 if (customAnswer) {
50 return customAnswer;
51 }
52
53 const selectedOptionValues = normalizeSelectedOptionValues(draft?.selectedOptionValues).filter(
54 (value) => question.options.some((option) => (option.value ?? option.label) === value),
55 );
56 if (question.multiSelect) {
57 return selectedOptionValues.length > 0
58 ? selectedOptionValues
59 : question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0
60 ? ""
61 : null;
62 }
63
64 return (
65 selectedOptionValues[0] ??
66 (question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0 ? "" : null)
67 );
68}
69
70export function setPendingUserInputCustomAnswer(
71 draft: PendingUserInputDraftAnswer | undefined,
72 customAnswer: string,
73): PendingUserInputDraftAnswer {
74 const selectedOptionValues =
75 customAnswer.trim().length > 0
76 ? undefined
77 : normalizeSelectedOptionValues(draft?.selectedOptionValues);
78
79 return {
80 customAnswer,
81 ...(selectedOptionValues && selectedOptionValues.length > 0 ? { selectedOptionValues } : {}),
82 };
83}
84
85const DISPLACED_ANSWER_SEPARATOR = "\n\n";
86
87/**
88 * Selecting an option replaces the custom answer, because a non-empty custom
89 * answer outranks selected options in `resolvePendingUserInputAnswer`. Text the
90 * user typed into the answer field must not vanish on that click: it moves back
91 * into the thread draft, after whatever was already waiting there.
92 */
93export function carryDisplacedCustomAnswerIntoPrompt(
94 prompt: string,
95 customAnswer: string | undefined,
96): string {
97 const displaced = customAnswer?.trim() ?? "";
98 if (displaced.length === 0) {
99 return prompt;
100 }
101 if (prompt.trim().length === 0) {
102 return displaced;
103 }
104 return `${prompt.trimEnd()}${DISPLACED_ANSWER_SEPARATOR}${displaced}`;
105}
106
107export function togglePendingUserInputOptionSelection(
108 question: UserInputQuestion,
109 draft: PendingUserInputDraftAnswer | undefined,
110 optionValue: string,
111): PendingUserInputDraftAnswer {
112 if (question.multiSelect) {
113 const selectedOptionValues = normalizeSelectedOptionValues(draft?.selectedOptionValues);
114 const nextSelectedOptionValues = selectedOptionValues.includes(optionValue)
115 ? selectedOptionValues.filter((value) => value !== optionValue)
116 : [...selectedOptionValues, optionValue];
117
118 return {
119 customAnswer: "",
120 ...(nextSelectedOptionValues.length > 0
121 ? { selectedOptionValues: nextSelectedOptionValues }
122 : {}),
123 };
124 }
125
126 return {
127 customAnswer: "",
128 selectedOptionValues: [optionValue],
129 };
130}
131
132export function buildPendingUserInputAnswers(
133 questions: ReadonlyArray<UserInputQuestion>,
134 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
135): Record<string, string | string[]> | null {
136 const answers: Record<string, string | string[]> = {};
137
138 for (const question of questions) {
139 const answer = resolvePendingUserInputAnswer(question, draftAnswers[question.id]);
140 if (answer === null) {
141 return null;
142 }
143 answers[question.id] = answer;
144 }
145
146 return answers;
147}
148
149export function countAnsweredPendingUserInputQuestions(
150 questions: ReadonlyArray<UserInputQuestion>,
151 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
152): number {
153 return questions.reduce((count, question) => {
154 return resolvePendingUserInputAnswer(question, draftAnswers[question.id]) !== null
155 ? count + 1
156 : count;
157 }, 0);
158}
159
160export function derivePendingUserInputProgress(
161 questions: ReadonlyArray<UserInputQuestion>,
162 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
163 questionIndex: number,
164): PendingUserInputProgress {
165 const normalizedQuestionIndex =
166 questions.length === 0 ? 0 : Math.max(0, Math.min(questionIndex, questions.length - 1));
167 const activeQuestion = questions[normalizedQuestionIndex] ?? null;
168 const activeDraft = activeQuestion ? draftAnswers[activeQuestion.id] : undefined;
169 const resolvedAnswer = activeQuestion
170 ? resolvePendingUserInputAnswer(activeQuestion, activeDraft)
171 : null;
172 const customAnswer =
173 activeQuestion?.allowCustomAnswer === false ? "" : (activeDraft?.customAnswer ?? "");
174 const answeredQuestionCount = countAnsweredPendingUserInputQuestions(questions, draftAnswers);
175 const isLastQuestion =
176 questions.length === 0 ? true : normalizedQuestionIndex >= questions.length - 1;
177
178 return {
179 questionIndex: normalizedQuestionIndex,
180 activeQuestion,
181 activeDraft,
182 selectedOptionValues: normalizeSelectedOptionValues(activeDraft?.selectedOptionValues),
183 customAnswer,
184 resolvedAnswer,
185 usingCustomAnswer: customAnswer.trim().length > 0,
186 answeredQuestionCount,
187 isLastQuestion,
188 isComplete: buildPendingUserInputAnswers(questions, draftAnswers) !== null,
189 canAdvance: resolvedAnswer !== null,
190 };
191}