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

ProviderSettingsForm.tsx

439 lines14.3 KB

1"use client";
2​
3import { useMemo, type ReactNode } from "react";
4import * as Option from "effect/Option";
5import * as Schema from "effect/Schema";
6import type {
7 ProviderSettingsFormAnnotation,
8 ProviderSettingsFormControl,
9 ProviderSettingsFormOption,
10 ProviderSettingsFormSchemaAnnotation,
11} from "@t3tools/contracts";
12​
13import { cn } from "../../lib/utils";
14import { DraftInput } from "../ui/draft-input";
15import { Input } from "../ui/input";
16import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
17import { Switch } from "../ui/switch";
18import { Textarea } from "../ui/textarea";
19import type { ProviderClientDefinition } from "./providerDriverMeta";
20import { SettingsRow } from "./settingsLayout";
21​
22export interface ProviderSettingsFieldModel {
23 readonly key: string;
24 readonly control: ProviderSettingsFormControl;
25 readonly label: string;
26 readonly description?: string | undefined;
27 readonly placeholder?: string | undefined;
28 readonly clearWhenEmpty: "omit" | "persist";
29 readonly defaultBooleanValue?: boolean | undefined;
30 /** Choices for a `select` control. The first entry is the default. */
31 readonly options?: ReadonlyArray<ProviderSettingsFormOption> | undefined;
33​
34function titleizeFieldKey(key: string): string {
35 return key
36 .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
37 .replace(/[-_]+/g, " ")
38 .replace(/^./, (char) => char.toUpperCase());
40​
41function readFieldAnnotations(
42 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
43) {
44 return Schema.resolveAnnotationsKey(fieldSchema) ?? Schema.resolveAnnotations(fieldSchema);
46​
47function readFieldAnnotationString(
48 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
49 key: "title" | "description",
50): string | undefined {
51 const annotations = readFieldAnnotations(fieldSchema);
52 const value = annotations?.[key];
53 return typeof value === "string" ? value : undefined;
55​
56function readProviderSettingsFormAnnotation(
57 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
58): ProviderSettingsFormAnnotation {
59 const annotation = readFieldAnnotations(fieldSchema)?.providerSettingsForm;
60 return annotation ?? {};
62​
63function readProviderSettingsFormSchemaAnnotation(
64 definition: ProviderClientDefinition,
65): ProviderSettingsFormSchemaAnnotation {
66 return Schema.resolveAnnotations(definition.settingsSchema)?.providerSettingsFormSchema ?? {};
68​
69function readFieldBooleanDefault(
70 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
71): boolean | undefined {
72 const decodeDefault = Schema.decodeUnknownOption(fieldSchema as Schema.Decoder<unknown>);
73 const decoded = decodeDefault(undefined);
74 return Option.isSome(decoded) && typeof decoded.value === "boolean" ? decoded.value : undefined;
76​
77export function deriveProviderSettingsFields(
78 definition: ProviderClientDefinition,
79): ReadonlyArray<ProviderSettingsFieldModel> {
80 const schemaAnnotation = readProviderSettingsFormSchemaAnnotation(definition);
81 const orderedKeys = new Map(
82 (schemaAnnotation.order ?? []).map((key, index) => [key, index] as const),
83 );
84 const orderFallbackOffset = orderedKeys.size;
85​
86 return Object.keys(definition.settingsSchema.fields)
87 .map((key, index) => ({ key, index }))
88 .toSorted((left, right) => {
89 return (
90 (orderedKeys.get(left.key) ?? orderFallbackOffset + left.index) -
91 (orderedKeys.get(right.key) ?? orderFallbackOffset + right.index)
92 );
93 })
94 .flatMap(({ key }) => {
95 const fieldSchema = definition.settingsSchema.fields[key]!;
96 const formAnnotation = readProviderSettingsFormAnnotation(fieldSchema);
97 if (formAnnotation.hidden) return [];
98​
99 const annotatedTitle = readFieldAnnotationString(fieldSchema, "title");
100 const annotatedDescription = readFieldAnnotationString(fieldSchema, "description");
101 return [
102 {
103 key,
104 control: formAnnotation.control ?? "text",
105 label: annotatedTitle ?? titleizeFieldKey(key),
106 ...(annotatedDescription !== undefined ? { description: annotatedDescription } : {}),
107 ...(formAnnotation.placeholder !== undefined
108 ? { placeholder: formAnnotation.placeholder }
109 : {}),
110 clearWhenEmpty: formAnnotation.clearWhenEmpty ?? "omit",
111 ...(formAnnotation.control === "switch"
112 ? { defaultBooleanValue: readFieldBooleanDefault(fieldSchema) }
113 : {}),
114 ...(formAnnotation.control === "select" && formAnnotation.options
115 ? { options: formAnnotation.options }
116 : {}),
117 } satisfies ProviderSettingsFieldModel,
118 ];
119 });
121​
122export function readProviderConfigString(config: unknown, key: string): string {
123 if (config === null || typeof config !== "object") return "";
124 const value = (config as Record<string, unknown>)[key];
125 return typeof value === "string" ? value : "";
127​
128export function readProviderConfigBoolean(
129 config: unknown,
130 key: string,
131 defaultValue = false,
132): boolean {
133 if (config === null || typeof config !== "object") return defaultValue;
134 const value = (config as Record<string, unknown>)[key];
135 return typeof value === "boolean" ? value : defaultValue;
137​
138export function nextProviderConfigWithFieldValue(
139 config: unknown,
140 field: ProviderSettingsFieldModel,
141 value: string | boolean,
142): Record<string, unknown> | undefined {
143 const base: Record<string, unknown> =
144 config !== null && typeof config === "object" ? { ...(config as Record<string, unknown>) } : {};
145​
146 if (typeof value === "boolean") {
147 const emptyBooleanValue = field.defaultBooleanValue ?? false;
148 if (field.clearWhenEmpty === "omit" && value === emptyBooleanValue) {
149 delete base[field.key];
150 } else {
151 base[field.key] = value;
152 }
153 return Object.keys(base).length > 0 ? base : undefined;
154 }
155​
156 const trimmed = value.trim();
157 if (field.clearWhenEmpty === "omit" && trimmed.length === 0) {
158 delete base[field.key];
159 } else {
160 base[field.key] = value;
161 }
162 return Object.keys(base).length > 0 ? base : undefined;
164​
165interface ProviderSettingsFormProps {
166 readonly definition: ProviderClientDefinition;
167 readonly value: unknown;
168 readonly idPrefix: string;
169 /**
170 * `card` stacks label over control, `dialog` is the compact wizard layout,
171 * and `settings` renders the shared settings row treatment.
172 */
173 readonly variant: "card" | "dialog" | "settings";
174 readonly onChange: (nextConfig: Record<string, unknown> | undefined) => void;
176​
177/** Stores the default choice as an omitted key so unchanged configs stay small. */
178function ProviderSettingsSelect({
179 field,
180 value,
181 inputId,
182 size,
183 className,
184 onChange,
185}: {
186 readonly field: ProviderSettingsFieldModel;
187 readonly value: unknown;
188 readonly inputId: string;
189 readonly size: "sm" | "xs";
190 readonly className?: string | undefined;
191 readonly onChange: ProviderSettingsFormProps["onChange"];
192}) {
193 const options = field.options ?? [];
194 const fallback = options[0]?.value ?? "";
195 const current = readProviderConfigString(value, field.key) || fallback;
196 const label = options.find((option) => option.value === current)?.label ?? current;
197 return (
198 <Select
199 value={current}
200 onValueChange={(next) => {
201 if (typeof next !== "string") return;
202 onChange(nextProviderConfigWithFieldValue(value, field, next === fallback ? "" : next));
203 }}
204 >
205 <SelectTrigger id={inputId} size={size} className={className} aria-label={field.label}>
206 <SelectValue>{label}</SelectValue>
207 </SelectTrigger>
208 <SelectPopup align="start" alignItemWithTrigger={false}>
209 {options.map((option) => (
210 <SelectItem key={option.value} value={option.value}>
211 {option.label}
212 </SelectItem>
213 ))}
214 </SelectPopup>
215 </Select>
216 );
218​
219function FieldFrame(props: {
220 readonly variant: ProviderSettingsFormProps["variant"];
221 readonly children: ReactNode;
222}) {
223 if (props.variant === "card") {
224 return <div>{props.children}</div>;
225 }
226 return <div className="grid gap-1.5">{props.children}</div>;
228​
229interface ProviderSettingsFieldRowProps {
230 readonly field: ProviderSettingsFieldModel;
231 readonly value: unknown;
232 readonly idPrefix: string;
233 readonly variant: ProviderSettingsFormProps["variant"];
234 readonly onChange: ProviderSettingsFormProps["onChange"];
236​
237function ProviderSettingsFieldRow({
238 field,
239 value,
240 idPrefix,
241 variant,
242 onChange,
243}: ProviderSettingsFieldRowProps) {
244 const inputId = `${idPrefix}-${field.key}`;
245 const descriptionClassName =
246 variant === "dialog"
247 ? "text-[11px] text-muted-foreground"
248 : "mt-1 block text-xs text-muted-foreground";
249 const label = <span className="text-xs font-medium text-foreground">{field.label}</span>;
250 const description = field.description ? (
251 <span className={descriptionClassName}>{field.description}</span>
252 ) : null;
253​
254 if (variant === "settings") {
255 const descriptionId = field.description ? `${inputId}-description` : undefined;
256 const control =
257 field.control === "switch" ? (
258 <Switch
259 checked={readProviderConfigBoolean(value, field.key, field.defaultBooleanValue)}
260 onCheckedChange={(checked) =>
261 onChange(nextProviderConfigWithFieldValue(value, field, Boolean(checked)))
262 }
263 aria-label={field.label}
264 aria-describedby={descriptionId}
265 />
266 ) : field.control === "select" ? (
267 <ProviderSettingsSelect
268 field={field}
269 value={value}
270 inputId={inputId}
271 size="sm"
272 className="w-full sm:w-56"
273 onChange={onChange}
274 />
275 ) : field.control === "textarea" ? (
276 <Textarea
277 id={inputId}
278 aria-describedby={descriptionId}
279 className="w-full sm:w-96"
280 value={readProviderConfigString(value, field.key)}
281 onChange={(event) =>
282 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
283 }
284 placeholder={field.placeholder}
285 spellCheck={false}
286 />
287 ) : (
288 <DraftInput
289 id={inputId}
290 aria-describedby={descriptionId}
291 size="sm"
292 className="w-full sm:w-56"
293 type={field.control === "password" ? "password" : undefined}
294 autoComplete={field.control === "password" ? "off" : undefined}
295 value={readProviderConfigString(value, field.key)}
296 onCommit={(next) => onChange(nextProviderConfigWithFieldValue(value, field, next))}
297 placeholder={field.placeholder}
298 spellCheck={false}
299 />
300 );
301​
302 return (
303 <SettingsRow
304 title={
305 field.control === "switch" ? field.label : <label htmlFor={inputId}>{field.label}</label>
306 }
307 description={
308 field.description ? <span id={descriptionId}>{field.description}</span> : undefined
309 }
310 control={control}
311 />
312 );
313 }
314​
315 if (field.control === "switch") {
316 return (
317 <FieldFrame variant={variant}>
318 <div className="flex items-center justify-between gap-3">
319 <div className="min-w-0">
320 {label}
321 {description}
322 </div>
323 <Switch
324 checked={readProviderConfigBoolean(value, field.key, field.defaultBooleanValue)}
325 onCheckedChange={(checked) =>
326 onChange(nextProviderConfigWithFieldValue(value, field, Boolean(checked)))
327 }
328 aria-label={field.label}
329 />
330 </div>
331 </FieldFrame>
332 );
333 }
334​
335 if (field.control === "select") {
336 return (
337 <FieldFrame variant={variant}>
338 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
339 {label}
340 <ProviderSettingsSelect
341 field={field}
342 value={value}
343 inputId={inputId}
344 size="sm"
345 className={cn("w-full", variant === "card" && "mt-1.5")}
346 onChange={onChange}
347 />
348 {description}
349 </label>
350 </FieldFrame>
351 );
352 }
353​
354 if (field.control === "textarea") {
355 return (
356 <FieldFrame variant={variant}>
357 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
358 {label}
359 <Textarea
360 id={inputId}
361 className={cn(variant === "card" && "mt-1.5")}
362 value={readProviderConfigString(value, field.key)}
363 onChange={(event) =>
364 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
365 }
366 placeholder={field.placeholder}
367 spellCheck={false}
368 />
369 {description}
370 </label>
371 </FieldFrame>
372 );
373 }
374​
375 const type = field.control === "password" ? "password" : undefined;
376 return (
377 <FieldFrame variant={variant}>
378 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
379 {label}
380 {variant === "card" ? (
381 <DraftInput
382 id={inputId}
383 size="sm"
384 className="mt-1.5"
385 type={type}
386 autoComplete={field.control === "password" ? "off" : undefined}
387 value={readProviderConfigString(value, field.key)}
388 onCommit={(next) => onChange(nextProviderConfigWithFieldValue(value, field, next))}
389 placeholder={field.placeholder}
390 spellCheck={false}
391 />
392 ) : (
393 <Input
394 id={inputId}
395 className="bg-background"
396 type={type}
397 autoComplete={field.control === "password" ? "off" : undefined}
398 value={readProviderConfigString(value, field.key)}
399 onChange={(event) =>
400 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
401 }
402 placeholder={field.placeholder}
403 spellCheck={false}
404 />
405 )}
406 {description}
407 </label>
408 </FieldFrame>
409 );
411​
412export function ProviderSettingsForm({
413 definition,
414 value,
415 idPrefix,
416 variant,
417 onChange,
418}: ProviderSettingsFormProps) {
419 const fields = useMemo(() => deriveProviderSettingsFields(definition), [definition]);
420​
421 if (fields.length === 0) {
422 return null;
423 }
424​
425 return (
426 <>
427 {fields.map((field) => (
428 <ProviderSettingsFieldRow
429 key={field.key}
430 field={field}
431 value={value}
432 idPrefix={idPrefix}
433 variant={variant}
434 onChange={onChange}
435 />
436 ))}
437 </>
438 );