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

ProviderSettingsForm.tsx

373 lines12.6 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 ProviderSettingsFormSchemaAnnotation,
10} from "@t3tools/contracts";
11​
12import { cn } from "../../lib/utils";
13import { DraftInput } from "../ui/draft-input";
14import { Input } from "../ui/input";
15import { Switch } from "../ui/switch";
16import { Textarea } from "../ui/textarea";
17import type { ProviderClientDefinition } from "./providerDriverMeta";
18​
19export interface ProviderSettingsFieldModel {
20 readonly key: string;
21 readonly control: ProviderSettingsFormControl;
22 readonly label: string;
23 readonly description?: string | undefined;
24 readonly placeholder?: string | undefined;
25 readonly clearWhenEmpty: "omit" | "persist";
26 readonly defaultBooleanValue?: boolean | undefined;
28​
29function titleizeFieldKey(key: string): string {
30 return key
31 .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
32 .replace(/[-_]+/g, " ")
33 .replace(/^./, (char) => char.toUpperCase());
35​
36function readFieldAnnotations(
37 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
38) {
39 return Schema.resolveAnnotationsKey(fieldSchema) ?? Schema.resolveAnnotations(fieldSchema);
41​
42function readFieldAnnotationString(
43 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
44 key: "title" | "description",
45): string | undefined {
46 const annotations = readFieldAnnotations(fieldSchema);
47 const value = annotations?.[key];
48 return typeof value === "string" ? value : undefined;
50​
51function readProviderSettingsFormAnnotation(
52 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
53): ProviderSettingsFormAnnotation {
54 const annotation = readFieldAnnotations(fieldSchema)?.providerSettingsForm;
55 return annotation ?? {};
57​
58function readProviderSettingsFormSchemaAnnotation(
59 definition: ProviderClientDefinition,
60): ProviderSettingsFormSchemaAnnotation {
61 return Schema.resolveAnnotations(definition.settingsSchema)?.providerSettingsFormSchema ?? {};
63​
64function readFieldBooleanDefault(
65 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
66): boolean | undefined {
67 const decodeDefault = Schema.decodeUnknownOption(fieldSchema as Schema.Decoder<unknown>);
68 const decoded = decodeDefault(undefined);
69 return Option.isSome(decoded) && typeof decoded.value === "boolean" ? decoded.value : undefined;
71​
72export function deriveProviderSettingsFields(
73 definition: ProviderClientDefinition,
74): ReadonlyArray<ProviderSettingsFieldModel> {
75 const schemaAnnotation = readProviderSettingsFormSchemaAnnotation(definition);
76 const orderedKeys = new Map(
77 (schemaAnnotation.order ?? []).map((key, index) => [key, index] as const),
78 );
79 const orderFallbackOffset = orderedKeys.size;
80​
81 return Object.keys(definition.settingsSchema.fields)
82 .map((key, index) => ({ key, index }))
83 .toSorted((left, right) => {
84 return (
85 (orderedKeys.get(left.key) ?? orderFallbackOffset + left.index) -
86 (orderedKeys.get(right.key) ?? orderFallbackOffset + right.index)
87 );
88 })
89 .flatMap(({ key }) => {
90 const fieldSchema = definition.settingsSchema.fields[key]!;
91 const formAnnotation = readProviderSettingsFormAnnotation(fieldSchema);
92 if (formAnnotation.hidden) return [];
93​
94 const annotatedTitle = readFieldAnnotationString(fieldSchema, "title");
95 const annotatedDescription = readFieldAnnotationString(fieldSchema, "description");
96 return [
97 {
98 key,
99 control: formAnnotation.control ?? "text",
100 label: annotatedTitle ?? titleizeFieldKey(key),
101 ...(annotatedDescription !== undefined ? { description: annotatedDescription } : {}),
102 ...(formAnnotation.placeholder !== undefined
103 ? { placeholder: formAnnotation.placeholder }
104 : {}),
105 clearWhenEmpty: formAnnotation.clearWhenEmpty ?? "omit",
106 ...(formAnnotation.control === "switch"
107 ? { defaultBooleanValue: readFieldBooleanDefault(fieldSchema) }
108 : {}),
109 } satisfies ProviderSettingsFieldModel,
110 ];
111 });
113​
114export function readProviderConfigString(config: unknown, key: string): string {
115 if (config === null || typeof config !== "object") return "";
116 const value = (config as Record<string, unknown>)[key];
117 return typeof value === "string" ? value : "";
119​
120export function readProviderConfigBoolean(
121 config: unknown,
122 key: string,
123 defaultValue = false,
124): boolean {
125 if (config === null || typeof config !== "object") return defaultValue;
126 const value = (config as Record<string, unknown>)[key];
127 return typeof value === "boolean" ? value : defaultValue;
129​
130export function nextProviderConfigWithFieldValue(
131 config: unknown,
132 field: ProviderSettingsFieldModel,
133 value: string | boolean,
134): Record<string, unknown> | undefined {
135 const base: Record<string, unknown> =
136 config !== null && typeof config === "object" ? { ...(config as Record<string, unknown>) } : {};
137​
138 if (typeof value === "boolean") {
139 const emptyBooleanValue = field.defaultBooleanValue ?? false;
140 if (field.clearWhenEmpty === "omit" && value === emptyBooleanValue) {
141 delete base[field.key];
142 } else {
143 base[field.key] = value;
144 }
145 return Object.keys(base).length > 0 ? base : undefined;
146 }
147​
148 const trimmed = value.trim();
149 if (field.clearWhenEmpty === "omit" && trimmed.length === 0) {
150 delete base[field.key];
151 } else {
152 base[field.key] = value;
153 }
154 return Object.keys(base).length > 0 ? base : undefined;
156​
157interface ProviderSettingsFormProps {
158 readonly definition: ProviderClientDefinition;
159 readonly value: unknown;
160 readonly idPrefix: string;
161 /**
162 * `card` stacks label over control, `dialog` is the compact wizard layout,
163 * `grid` emits a label cell and a control cell per field for a parent
164 * two-column grid (label column left, control right), with the description
165 * beside a fixed-width control so each field stays on one line.
166 */
167 readonly variant: "card" | "dialog" | "grid";
168 readonly onChange: (nextConfig: Record<string, unknown> | undefined) => void;
170​
171function FieldFrame(props: {
172 readonly variant: ProviderSettingsFormProps["variant"];
173 readonly children: ReactNode;
174}) {
175 if (props.variant === "card") {
176 return <div>{props.children}</div>;
177 }
178 return <div className="grid gap-1.5">{props.children}</div>;
180​
181interface ProviderSettingsFieldRowProps {
182 readonly field: ProviderSettingsFieldModel;
183 readonly value: unknown;
184 readonly idPrefix: string;
185 readonly variant: ProviderSettingsFormProps["variant"];
186 readonly onChange: ProviderSettingsFormProps["onChange"];
188​
189function ProviderSettingsFieldRow({
190 field,
191 value,
192 idPrefix,
193 variant,
194 onChange,
195}: ProviderSettingsFieldRowProps) {
196 const inputId = `${idPrefix}-${field.key}`;
197 const descriptionClassName =
198 variant === "dialog"
199 ? "text-[11px] text-muted-foreground"
200 : "mt-1 block text-xs text-muted-foreground";
201 const label = <span className="text-xs font-medium text-foreground">{field.label}</span>;
202 const description = field.description ? (
203 <span className={descriptionClassName}>{field.description}</span>
204 ) : null;
205​
206 if (variant === "grid") {
207 // Label cell, then a control cell where the description sits beside a
208 // fixed-width control and wraps under it when the pane is narrow. The
209 // description is outside the label, so the control points at it instead.
210 const descriptionId = field.description ? `${inputId}-description` : undefined;
211 return (
212 <>
213 {field.control === "switch" ? (
214 <span className="pt-1.5 text-xs font-medium text-foreground">{field.label}</span>
215 ) : (
216 <label htmlFor={inputId} className="pt-1.5 text-xs font-medium text-foreground">
217 {field.label}
218 </label>
219 )}
220 <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1">
221 {field.control === "switch" ? (
222 <span className="flex h-8 items-center sm:h-7">
223 <Switch
224 checked={readProviderConfigBoolean(value, field.key, field.defaultBooleanValue)}
225 onCheckedChange={(checked) =>
226 onChange(nextProviderConfigWithFieldValue(value, field, Boolean(checked)))
227 }
228 aria-label={field.label}
229 aria-describedby={descriptionId}
230 />
231 </span>
232 ) : field.control === "textarea" ? (
233 <Textarea
234 id={inputId}
235 aria-describedby={descriptionId}
236 className="w-full max-w-sm"
237 value={readProviderConfigString(value, field.key)}
238 onChange={(event) =>
239 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
240 }
241 placeholder={field.placeholder}
242 spellCheck={false}
243 />
244 ) : (
245 <DraftInput
246 id={inputId}
247 aria-describedby={descriptionId}
248 size="sm"
249 className="w-56"
250 type={field.control === "password" ? "password" : undefined}
251 autoComplete={field.control === "password" ? "off" : undefined}
252 value={readProviderConfigString(value, field.key)}
253 onCommit={(next) => onChange(nextProviderConfigWithFieldValue(value, field, next))}
254 placeholder={field.placeholder}
255 spellCheck={false}
256 />
257 )}
258 {field.description ? (
259 <span id={descriptionId} className="text-[11px] leading-snug text-muted-foreground">
260 {field.description}
261 </span>
262 ) : null}
263 </div>
264 </>
265 );
266 }
267​
268 if (field.control === "switch") {
269 return (
270 <FieldFrame variant={variant}>
271 <div className="flex items-center justify-between gap-3">
272 <div className="min-w-0">
273 {label}
274 {description}
275 </div>
276 <Switch
277 checked={readProviderConfigBoolean(value, field.key, field.defaultBooleanValue)}
278 onCheckedChange={(checked) =>
279 onChange(nextProviderConfigWithFieldValue(value, field, Boolean(checked)))
280 }
281 aria-label={field.label}
282 />
283 </div>
284 </FieldFrame>
285 );
286 }
287​
288 if (field.control === "textarea") {
289 return (
290 <FieldFrame variant={variant}>
291 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
292 {label}
293 <Textarea
294 id={inputId}
295 className={cn(variant === "card" && "mt-1.5")}
296 value={readProviderConfigString(value, field.key)}
297 onChange={(event) =>
298 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
299 }
300 placeholder={field.placeholder}
301 spellCheck={false}
302 />
303 {description}
304 </label>
305 </FieldFrame>
306 );
307 }
308​
309 const type = field.control === "password" ? "password" : undefined;
310 return (
311 <FieldFrame variant={variant}>
312 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
313 {label}
314 {variant === "card" ? (
315 <DraftInput
316 id={inputId}
317 size="sm"
318 className="mt-1.5"
319 type={type}
320 autoComplete={field.control === "password" ? "off" : undefined}
321 value={readProviderConfigString(value, field.key)}
322 onCommit={(next) => onChange(nextProviderConfigWithFieldValue(value, field, next))}
323 placeholder={field.placeholder}
324 spellCheck={false}
325 />
326 ) : (
327 <Input
328 id={inputId}
329 className="bg-background"
330 type={type}
331 autoComplete={field.control === "password" ? "off" : undefined}
332 value={readProviderConfigString(value, field.key)}
333 onChange={(event) =>
334 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
335 }
336 placeholder={field.placeholder}
337 spellCheck={false}
338 />
339 )}
340 {description}
341 </label>
342 </FieldFrame>
343 );
345​
346export function ProviderSettingsForm({
347 definition,
348 value,
349 idPrefix,
350 variant,
351 onChange,
352}: ProviderSettingsFormProps) {
353 const fields = useMemo(() => deriveProviderSettingsFields(definition), [definition]);
354​
355 if (fields.length === 0) {
356 return null;
357 }
358​
359 return (
360 <>
361 {fields.map((field) => (
362 <ProviderSettingsFieldRow
363 key={field.key}
364 field={field}
365 value={value}
366 idPrefix={idPrefix}
367 variant={variant}
368 onChange={onChange}
369 />
370 ))}
371 </>
372 );