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
49 ? null
50 : question.initialAnswer !== undefined
51 ? (draft?.customAnswer ?? null)
52 : normalizeDraftAnswer(draft?.customAnswer);
53 if (customAnswer !== null && customAnswer.length > 0) {
54 return customAnswer;
55 }
56
57 const selectedOptionValues = normalizeSelectedOptionValues(draft?.selectedOptionValues).filter(
58 (value) => question.options.some((option) => (option.value ?? option.label) === value),
59 );
60 if (question.multiSelect) {
61 return selectedOptionValues.length > 0
62 ? selectedOptionValues
63 : (customAnswer ??
64 (question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0 ? "" : null));
65 }
66
67 return (
68 selectedOptionValues[0] ??
69 customAnswer ??
70 (question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0 ? "" : null)
71 );
72}
73
74export function setPendingUserInputCustomAnswer(
75 draft: PendingUserInputDraftAnswer | undefined,
76 customAnswer: string,
77 question?: Pick<UserInputQuestion, "initialAnswer">,
78): PendingUserInputDraftAnswer {
79 const selectedOptionValues =
80 question?.initialAnswer !== undefined || customAnswer.trim().length > 0
81 ? undefined
82 : normalizeSelectedOptionValues(draft?.selectedOptionValues);
83
84 return {
85 customAnswer,
86 ...(selectedOptionValues && selectedOptionValues.length > 0 ? { selectedOptionValues } : {}),
87 };
88}
89
90const DISPLACED_ANSWER_SEPARATOR = "\n\n";
91
92/**
93 * Selecting an option replaces the custom answer, because a non-empty custom
94 * answer outranks selected options in `resolvePendingUserInputAnswer`. Text the
95 * user typed into the answer field must not vanish on that click: it moves back
96 * into the thread draft, after whatever was already waiting there.
97 */
98export function carryDisplacedCustomAnswerIntoPrompt(
99 prompt: string,
100 customAnswer: string | undefined,
101): string {
102 const displaced = customAnswer?.trim() ?? "";
103 if (displaced.length === 0) {
104 return prompt;
105 }
106 if (prompt.trim().length === 0) {
107 return displaced;
108 }
109 return `${prompt.trimEnd()}${DISPLACED_ANSWER_SEPARATOR}${displaced}`;
110}
111
112export function togglePendingUserInputOptionSelection(
113 question: UserInputQuestion,
114 draft: PendingUserInputDraftAnswer | undefined,
115 optionValue: string,
116): PendingUserInputDraftAnswer {
117 if (question.multiSelect) {
118 const selectedOptionValues = normalizeSelectedOptionValues(draft?.selectedOptionValues);
119 const nextSelectedOptionValues = selectedOptionValues.includes(optionValue)
120 ? selectedOptionValues.filter((value) => value !== optionValue)
121 : [...selectedOptionValues, optionValue];
122
123 return {
124 customAnswer: "",
125 ...(nextSelectedOptionValues.length > 0
126 ? { selectedOptionValues: nextSelectedOptionValues }
127 : {}),
128 };
129 }
130
131 return {
132 customAnswer: "",
133 selectedOptionValues: [optionValue],
134 };
135}
136
137export function buildPendingUserInputAnswers(
138 questions: ReadonlyArray<UserInputQuestion>,
139 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
140): Record<string, string | string[]> | null {
141 const answers: Record<string, string | string[]> = {};
142
143 for (const question of questions) {
144 const answer = resolvePendingUserInputAnswer(question, draftAnswers[question.id]);
145 if (answer === null) {
146 return null;
147 }
148 answers[question.id] = answer;
149 }
150
151 return answers;
152}
153
154export function countAnsweredPendingUserInputQuestions(
155 questions: ReadonlyArray<UserInputQuestion>,
156 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
157): number {
158 return questions.reduce((count, question) => {
159 return resolvePendingUserInputAnswer(question, draftAnswers[question.id]) !== null
160 ? count + 1
161 : count;
162 }, 0);
163}
164
165export function findFirstUnansweredPendingUserInputQuestionIndex(
166 questions: ReadonlyArray<UserInputQuestion>,
167 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
168): number {
169 const unansweredIndex = questions.findIndex(
170 (question) => resolvePendingUserInputAnswer(question, draftAnswers[question.id]) === null,
171 );
172
173 return unansweredIndex === -1 ? Math.max(questions.length - 1, 0) : unansweredIndex;
174}
175
176export function derivePendingUserInputProgress(
177 questions: ReadonlyArray<UserInputQuestion>,
178 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
179 questionIndex: number,
180): PendingUserInputProgress {
181 const normalizedQuestionIndex =
182 questions.length === 0 ? 0 : Math.max(0, Math.min(questionIndex, questions.length - 1));
183 const activeQuestion = questions[normalizedQuestionIndex] ?? null;
184 const activeDraft = activeQuestion ? draftAnswers[activeQuestion.id] : undefined;
185 const resolvedAnswer = activeQuestion
186 ? resolvePendingUserInputAnswer(activeQuestion, activeDraft)
187 : null;
188 const customAnswer =
189 activeQuestion?.allowCustomAnswer === false ? "" : (activeDraft?.customAnswer ?? "");
190 const answeredQuestionCount = countAnsweredPendingUserInputQuestions(questions, draftAnswers);
191 const isLastQuestion =
192 questions.length === 0 ? true : normalizedQuestionIndex >= questions.length - 1;
193
194 return {
195 questionIndex: normalizedQuestionIndex,
196 activeQuestion,
197 activeDraft,
198 selectedOptionValues: normalizeSelectedOptionValues(activeDraft?.selectedOptionValues),
199 customAnswer,
200 resolvedAnswer,
201 usingCustomAnswer:
202 (activeQuestion?.initialAnswer !== undefined ? customAnswer : customAnswer.trim()).length > 0,
203 answeredQuestionCount,
204 isLastQuestion,
205 isComplete: buildPendingUserInputAnswers(questions, draftAnswers) !== null,
206 canAdvance: resolvedAnswer !== null,
207 };
208}