Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

pendingUserInput.ts

216 lines7.2 KB

1import type { ThreadContextRecord, UserInputQuestion } from "@t3tools/contracts";
2import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
3import { formatThreadLink } from "@t3tools/shared/threadLinks";
4​
5export function projectPendingUserInputAnswer(
6 answer: unknown,
7 threadContexts: ReadonlyArray<ThreadContextRecord>,
8) {
9 if (typeof answer !== "string" || threadContexts.length === 0) return answer;
10 const recordsById = new Map(threadContexts.map((record) => [record.contextId, record]));
11 return replaceComposerContextReferences(answer, (reference) => {
12 const record = reference.kind === "thread" ? recordsById.get(reference.contextId) : undefined;
13 return record ? formatThreadLink(record.threadId, reference.label) : reference.source;
14 });
16​
17export interface PendingUserInputDraftAnswer {
18 selectedOptionValues?: string[];
19 customAnswer?: string;
20 attachmentCount?: number;
21 attachmentsBlocked?: boolean;
23​
24export interface PendingUserInputProgress {
25 questionIndex: number;
26 activeQuestion: UserInputQuestion | null;
27 activeDraft: PendingUserInputDraftAnswer | undefined;
28 selectedOptionValues: string[];
29 customAnswer: string;
30 resolvedAnswer: string | string[] | null;
31 usingCustomAnswer: boolean;
32 answeredQuestionCount: number;
33 isLastQuestion: boolean;
34 isComplete: boolean;
35 canAdvance: boolean;
37​
38function normalizeDraftAnswer(value: string | undefined): string | null {
39 if (typeof value !== "string") {
40 return null;
41 }
42​
43 const trimmed = value.trim();
44 return trimmed.length > 0 ? trimmed : null;
46​
47function normalizeSelectedOptionValues(value: string[] | undefined): string[] {
48 if (!Array.isArray(value)) {
49 return [];
50 }
51​
52 // Provider option IDs must stay unchanged, including whitespace.
53 return Array.from(new Set(value.filter((entry) => typeof entry === "string")));
55​
56export function resolvePendingUserInputAnswer(
57 question: UserInputQuestion,
58 draft: PendingUserInputDraftAnswer | undefined,
59): string | string[] | null {
60 if (draft?.attachmentsBlocked) return null;
61 const customAnswer =
62 question.allowCustomAnswer === false
63 ? null
64 : question.initialAnswer !== undefined
65 ? (draft?.customAnswer ?? null)
66 : normalizeDraftAnswer(draft?.customAnswer);
67 if (customAnswer !== null && customAnswer.length > 0) {
68 return customAnswer;
69 }
70​
71 const selectedOptionValues = normalizeSelectedOptionValues(draft?.selectedOptionValues).filter(
72 (value) => question.options.some((option) => (option.value ?? option.label) === value),
73 );
74 if (question.multiSelect) {
75 return selectedOptionValues.length > 0
76 ? selectedOptionValues
77 : (customAnswer ??
78 (question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0 ? "" : null));
79 }
80​
81 return (
82 selectedOptionValues[0] ??
83 customAnswer ??
84 (question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0 ? "" : null)
85 );
87​
88export function setPendingUserInputCustomAnswer(
89 draft: PendingUserInputDraftAnswer | undefined,
90 customAnswer: string,
91 question?: Pick<UserInputQuestion, "initialAnswer">,
92): PendingUserInputDraftAnswer {
93 const selectedOptionValues =
94 question?.initialAnswer !== undefined || customAnswer.trim().length > 0
95 ? undefined
96 : normalizeSelectedOptionValues(draft?.selectedOptionValues);
97​
98 return {
99 customAnswer,
100 ...(selectedOptionValues && selectedOptionValues.length > 0 ? { selectedOptionValues } : {}),
101 };
103​
104const DISPLACED_ANSWER_SEPARATOR = "\n\n";
105​
106export function carryDisplacedCustomAnswerIntoPrompt(
107 prompt: string,
108 customAnswer: string | undefined,
109): string {
110 const displaced = customAnswer?.trim() ?? "";
111 if (displaced.length === 0) {
112 return prompt;
113 }
114 if (prompt.trim().length === 0) {
115 return displaced;
116 }
117 return `${prompt.trimEnd()}${DISPLACED_ANSWER_SEPARATOR}${displaced}`;
119​
120export function togglePendingUserInputOptionSelection(
121 question: UserInputQuestion,
122 draft: PendingUserInputDraftAnswer | undefined,
123 optionValue: string,
124): PendingUserInputDraftAnswer {
125 if (question.multiSelect) {
126 const selectedOptionValues = normalizeSelectedOptionValues(draft?.selectedOptionValues);
127 const nextSelectedOptionValues = selectedOptionValues.includes(optionValue)
128 ? selectedOptionValues.filter((value) => value !== optionValue)
129 : [...selectedOptionValues, optionValue];
130​
131 return {
132 customAnswer: "",
133 ...(nextSelectedOptionValues.length > 0
134 ? { selectedOptionValues: nextSelectedOptionValues }
135 : {}),
136 };
137 }
138​
139 return {
140 customAnswer: "",
141 selectedOptionValues: [optionValue],
142 };
144​
145export function buildPendingUserInputAnswers(
146 questions: ReadonlyArray<UserInputQuestion>,
147 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
148): Record<string, string | string[]> | null {
149 const answers: Record<string, string | string[]> = {};
150​
151 for (const question of questions) {
152 const answer = resolvePendingUserInputAnswer(question, draftAnswers[question.id]);
153 if (answer === null) {
154 return null;
155 }
156 answers[question.id] = answer;
157 }
158​
159 return answers;
161​
162export function countAnsweredPendingUserInputQuestions(
163 questions: ReadonlyArray<UserInputQuestion>,
164 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
165): number {
166 return questions.reduce((count, question) => {
167 return resolvePendingUserInputAnswer(question, draftAnswers[question.id]) !== null
168 ? count + 1
169 : count;
170 }, 0);
172​
173export function findFirstUnansweredPendingUserInputQuestionIndex(
174 questions: ReadonlyArray<UserInputQuestion>,
175 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
176): number {
177 const unansweredIndex = questions.findIndex(
178 (question) => resolvePendingUserInputAnswer(question, draftAnswers[question.id]) === null,
179 );
180​
181 return unansweredIndex === -1 ? Math.max(questions.length - 1, 0) : unansweredIndex;
183​
184export function derivePendingUserInputProgress(
185 questions: ReadonlyArray<UserInputQuestion>,
186 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
187 questionIndex: number,
188): PendingUserInputProgress {
189 const normalizedQuestionIndex =
190 questions.length === 0 ? 0 : Math.max(0, Math.min(questionIndex, questions.length - 1));
191 const activeQuestion = questions[normalizedQuestionIndex] ?? null;
192 const activeDraft = activeQuestion ? draftAnswers[activeQuestion.id] : undefined;
193 const resolvedAnswer = activeQuestion
194 ? resolvePendingUserInputAnswer(activeQuestion, activeDraft)
195 : null;
196 const customAnswer =
197 activeQuestion?.allowCustomAnswer === false ? "" : (activeDraft?.customAnswer ?? "");
198 const answeredQuestionCount = countAnsweredPendingUserInputQuestions(questions, draftAnswers);
199 const isLastQuestion =
200 questions.length === 0 ? true : normalizedQuestionIndex >= questions.length - 1;
201​
202 return {
203 questionIndex: normalizedQuestionIndex,
204 activeQuestion,
205 activeDraft,
206 selectedOptionValues: normalizeSelectedOptionValues(activeDraft?.selectedOptionValues),
207 customAnswer,
208 resolvedAnswer,
209 usingCustomAnswer:
210 (activeQuestion?.initialAnswer !== undefined ? customAnswer : customAnswer.trim()).length > 0,
211 answeredQuestionCount,
212 isLastQuestion,
213 isComplete: buildPendingUserInputAnswers(questions, draftAnswers) !== null,
214 canAdvance: resolvedAnswer !== null,
215 };