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

ProviderSettingsForm.tsx

434 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​
122function 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​
128function readProviderConfigBoolean(config: unknown, key: string, defaultValue = false): boolean {
129 if (config === null || typeof config !== "object") return defaultValue;
130 const value = (config as Record<string, unknown>)[key];
131 return typeof value === "boolean" ? value : defaultValue;
133​
134export function nextProviderConfigWithFieldValue(
135 config: unknown,
136 field: ProviderSettingsFieldModel,
137 value: string | boolean,
138): Record<string, unknown> | undefined {
139 const base: Record<string, unknown> =
140 config !== null && typeof config === "object" ? { ...(config as Record<string, unknown>) } : {};
141​
142 if (typeof value === "boolean") {
143 const emptyBooleanValue = field.defaultBooleanValue ?? false;
144 if (field.clearWhenEmpty === "omit" && value === emptyBooleanValue) {
145 delete base[field.key];
146 } else {
147 base[field.key] = value;
148 }
149 return Object.keys(base).length > 0 ? base : undefined;
150 }
151​
152 const trimmed = value.trim();
153 if (field.clearWhenEmpty === "omit" && trimmed.length === 0) {
154 delete base[field.key];
155 } else {
156 base[field.key] = value;
157 }
158 return Object.keys(base).length > 0 ? base : undefined;
160​
161interface ProviderSettingsFormProps {
162 readonly definition: ProviderClientDefinition;
163 readonly value: unknown;
164 readonly idPrefix: string;
165 /**
166 * `card` stacks label over control, `dialog` is the compact wizard layout,
167 * and `settings` renders the shared settings row treatment.
168 */
169 readonly variant: "card" | "dialog" | "settings";
170 readonly onChange: (nextConfig: Record<string, unknown> | undefined) => void;
172​
173/** Stores the default choice as an omitted key so unchanged configs stay small. */
174function ProviderSettingsSelect({
175 field,
176 value,
177 inputId,
178 size,
179 className,
180 onChange,
181}: {
182 readonly field: ProviderSettingsFieldModel;
183 readonly value: unknown;
184 readonly inputId: string;
185 readonly size: "sm" | "xs";
186 readonly className?: string | undefined;
187 readonly onChange: ProviderSettingsFormProps["onChange"];
188}) {
189 const options = field.options ?? [];
190 const fallback = options[0]?.value ?? "";
191 const current = readProviderConfigString(value, field.key) || fallback;
192 const label = options.find((option) => option.value === current)?.label ?? current;
193 return (
194 <Select
195 value={current}
196 onValueChange={(next) => {
197 if (typeof next !== "string") return;
198 onChange(nextProviderConfigWithFieldValue(value, field, next === fallback ? "" : next));
199 }}
200 >
201 <SelectTrigger id={inputId} size={size} className={className} aria-label={field.label}>
202 <SelectValue>{label}</SelectValue>
203 </SelectTrigger>
204 <SelectPopup align="start" alignItemWithTrigger={false}>
205 {options.map((option) => (
206 <SelectItem key={option.value} value={option.value}>
207 {option.label}
208 </SelectItem>
209 ))}
210 </SelectPopup>
211 </Select>
212 );
214​
215function FieldFrame(props: {
216 readonly variant: ProviderSettingsFormProps["variant"];
217 readonly children: ReactNode;
218}) {
219 if (props.variant === "card") {
220 return <div>{props.children}</div>;
221 }
222 return <div className="grid gap-1.5">{props.children}</div>;
224​
225interface ProviderSettingsFieldRowProps {
226 readonly field: ProviderSettingsFieldModel;
227 readonly value: unknown;
228 readonly idPrefix: string;
229 readonly variant: ProviderSettingsFormProps["variant"];
230 readonly onChange: ProviderSettingsFormProps["onChange"];
232​
233function ProviderSettingsFieldRow({
234 field,
235 value,
236 idPrefix,
237 variant,
238 onChange,
239}: ProviderSettingsFieldRowProps) {
240 const inputId = `${idPrefix}-${field.key}`;
241 const descriptionClassName =
242 variant === "dialog"
243 ? "text-[11px] text-muted-foreground"
244 : "mt-1 block text-xs text-muted-foreground";
245 const label = <span className="text-xs font-medium text-foreground">{field.label}</span>;
246 const description = field.description ? (
247 <span className={descriptionClassName}>{field.description}</span>
248 ) : null;
249​
250 if (variant === "settings") {
251 const descriptionId = field.description ? `${inputId}-description` : undefined;
252 const control =
253 field.control === "switch" ? (
254 <Switch
255 checked={readProviderConfigBoolean(value, field.key, field.defaultBooleanValue)}
256 onCheckedChange={(checked) =>
257 onChange(nextProviderConfigWithFieldValue(value, field, Boolean(checked)))
258 }
259 aria-label={field.label}
260 aria-describedby={descriptionId}
261 />
262 ) : field.control === "select" ? (
263 <ProviderSettingsSelect
264 field={field}
265 value={value}
266 inputId={inputId}
267 size="sm"
268 className="w-full max-w-full @min-[32rem]/settings-row:w-56"
269 onChange={onChange}
270 />
271 ) : field.control === "textarea" ? (
272 <Textarea
273 id={inputId}
274 aria-describedby={descriptionId}
275 className="w-full max-w-full @min-[32rem]/settings-row:w-[min(24rem,50cqw)]"
276 value={readProviderConfigString(value, field.key)}
277 onChange={(event) =>
278 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
279 }
280 placeholder={field.placeholder}
281 spellCheck={false}
282 />
283 ) : (
284 <DraftInput
285 id={inputId}
286 aria-describedby={descriptionId}
287 size="sm"
288 className="w-full max-w-full @min-[32rem]/settings-row:w-56"
289 type={field.control === "password" ? "password" : undefined}
290 autoComplete={field.control === "password" ? "off" : undefined}
291 value={readProviderConfigString(value, field.key)}
292 onCommit={(next) => onChange(nextProviderConfigWithFieldValue(value, field, next))}
293 placeholder={field.placeholder}
294 spellCheck={false}
295 />
296 );
297​
298 return (
299 <SettingsRow
300 title={
301 field.control === "switch" ? field.label : <label htmlFor={inputId}>{field.label}</label>
302 }
303 description={
304 field.description ? <span id={descriptionId}>{field.description}</span> : undefined
305 }
306 control={control}
307 />
308 );
309 }
310​
311 if (field.control === "switch") {
312 return (
313 <FieldFrame variant={variant}>
314 <div className="flex items-center justify-between gap-3">
315 <div className="min-w-0">
316 {label}
317 {description}
318 </div>
319 <Switch
320 checked={readProviderConfigBoolean(value, field.key, field.defaultBooleanValue)}
321 onCheckedChange={(checked) =>
322 onChange(nextProviderConfigWithFieldValue(value, field, Boolean(checked)))
323 }
324 aria-label={field.label}
325 />
326 </div>
327 </FieldFrame>
328 );
329 }
330​
331 if (field.control === "select") {
332 return (
333 <FieldFrame variant={variant}>
334 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
335 {label}
336 <ProviderSettingsSelect
337 field={field}
338 value={value}
339 inputId={inputId}
340 size="sm"
341 className={cn("w-full", variant === "card" && "mt-1.5")}
342 onChange={onChange}
343 />
344 {description}
345 </label>
346 </FieldFrame>
347 );
348 }
349​
350 if (field.control === "textarea") {
351 return (
352 <FieldFrame variant={variant}>
353 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
354 {label}
355 <Textarea
356 id={inputId}
357 className={cn(variant === "card" && "mt-1.5")}
358 value={readProviderConfigString(value, field.key)}
359 onChange={(event) =>
360 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
361 }
362 placeholder={field.placeholder}
363 spellCheck={false}
364 />
365 {description}
366 </label>
367 </FieldFrame>
368 );
369 }
370​
371 const type = field.control === "password" ? "password" : undefined;
372 return (
373 <FieldFrame variant={variant}>
374 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
375 {label}
376 {variant === "card" ? (
377 <DraftInput
378 id={inputId}
379 size="sm"
380 className="mt-1.5"
381 type={type}
382 autoComplete={field.control === "password" ? "off" : undefined}
383 value={readProviderConfigString(value, field.key)}
384 onCommit={(next) => onChange(nextProviderConfigWithFieldValue(value, field, next))}
385 placeholder={field.placeholder}
386 spellCheck={false}
387 />
388 ) : (
389 <Input
390 id={inputId}
391 type={type}
392 autoComplete={field.control === "password" ? "off" : undefined}
393 value={readProviderConfigString(value, field.key)}
394 onChange={(event) =>
395 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
396 }
397 placeholder={field.placeholder}
398 spellCheck={false}
399 />
400 )}
401 {description}
402 </label>
403 </FieldFrame>
404 );
406​
407export function ProviderSettingsForm({
408 definition,
409 value,
410 idPrefix,
411 variant,
412 onChange,
413}: ProviderSettingsFormProps) {
414 const fields = useMemo(() => deriveProviderSettingsFields(definition), [definition]);
415​
416 if (fields.length === 0) {
417 return null;
418 }
419​
420 return (
421 <>
422 {fields.map((field) => (
423 <ProviderSettingsFieldRow
424 key={field.key}
425 field={field}
426 value={value}
427 idPrefix={idPrefix}
428 variant={variant}
429 onChange={onChange}
430 />
431 ))}
432 </>
433 );