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

ProviderSettingsForm.tsx

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