Open History to see the last commit
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;
27}
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());
34}
35
36function readFieldAnnotations(
37 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
38) {
39 return Schema.resolveAnnotationsKey(fieldSchema) ?? Schema.resolveAnnotations(fieldSchema);
40}
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;
49}
50
51function readProviderSettingsFormAnnotation(
52 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
53): ProviderSettingsFormAnnotation {
54 const annotation = readFieldAnnotations(fieldSchema)?.providerSettingsForm;
55 return annotation ?? {};
56}
57
58function readProviderSettingsFormSchemaAnnotation(
59 definition: ProviderClientDefinition,
60): ProviderSettingsFormSchemaAnnotation {
61 return Schema.resolveAnnotations(definition.settingsSchema)?.providerSettingsFormSchema ?? {};
62}
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;
70}
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 });
112}
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 : "";
118}
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;
128}
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;
155}
156
157interface ProviderSettingsFormProps {
158 readonly definition: ProviderClientDefinition;
159 readonly value: unknown;
160 readonly idPrefix: string;
161 readonly variant: "card" | "dialog";
162 readonly onChange: (nextConfig: Record<string, unknown> | undefined) => void;
163}
164
165function FieldFrame(props: {
166 readonly variant: ProviderSettingsFormProps["variant"];
167 readonly children: ReactNode;
168}) {
169 if (props.variant === "card") {
170 return <div>{props.children}</div>;
171 }
172 return <div className="grid gap-1.5">{props.children}</div>;
173}
174
175interface ProviderSettingsFieldRowProps {
176 readonly field: ProviderSettingsFieldModel;
177 readonly value: unknown;
178 readonly idPrefix: string;
179 readonly variant: ProviderSettingsFormProps["variant"];
180 readonly onChange: ProviderSettingsFormProps["onChange"];
181}
182
183function ProviderSettingsFieldRow({
184 field,
185 value,
186 idPrefix,
187 variant,
188 onChange,
189}: ProviderSettingsFieldRowProps) {
190 const inputId = `${idPrefix}-${field.key}`;
191 const descriptionClassName =
192 variant === "card"
193 ? "mt-1 block text-xs text-muted-foreground"
194 : "text-[11px] text-muted-foreground";
195 const label = <span className="text-xs font-medium text-foreground">{field.label}</span>;
196 const description = field.description ? (
197 <span className={descriptionClassName}>{field.description}</span>
198 ) : null;
199
200 if (field.control === "switch") {
201 return (
202 <FieldFrame variant={variant}>
203 <div className="flex items-center justify-between gap-3">
204 <div className="min-w-0">
205 {label}
206 {description}
207 </div>
208 <Switch
209 checked={readProviderConfigBoolean(value, field.key, field.defaultBooleanValue)}
210 onCheckedChange={(checked) =>
211 onChange(nextProviderConfigWithFieldValue(value, field, Boolean(checked)))
212 }
213 aria-label={field.label}
214 />
215 </div>
216 </FieldFrame>
217 );
218 }
219
220 if (field.control === "textarea") {
221 return (
222 <FieldFrame variant={variant}>
223 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
224 {label}
225 <Textarea
226 id={inputId}
227 className={cn(variant === "card" && "mt-1.5")}
228 value={readProviderConfigString(value, field.key)}
229 onChange={(event) =>
230 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
231 }
232 placeholder={field.placeholder}
233 spellCheck={false}
234 />
235 {description}
236 </label>
237 </FieldFrame>
238 );
239 }
240
241 const type = field.control === "password" ? "password" : undefined;
242 return (
243 <FieldFrame variant={variant}>
244 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
245 {label}
246 {variant === "card" ? (
247 <DraftInput
248 id={inputId}
249 className="mt-1.5"
250 type={type}
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 <Input
259 id={inputId}
260 className="bg-background"
261 type={type}
262 autoComplete={field.control === "password" ? "off" : undefined}
263 value={readProviderConfigString(value, field.key)}
264 onChange={(event) =>
265 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
266 }
267 placeholder={field.placeholder}
268 spellCheck={false}
269 />
270 )}
271 {description}
272 </label>
273 </FieldFrame>
274 );
275}
276
277export function ProviderSettingsForm({
278 definition,
279 value,
280 idPrefix,
281 variant,
282 onChange,
283}: ProviderSettingsFormProps) {
284 const fields = useMemo(() => deriveProviderSettingsFields(definition), [definition]);
285
286 if (fields.length === 0) {
287 return null;
288 }
289
290 return (
291 <>
292 {fields.map((field) => (
293 <ProviderSettingsFieldRow
294 key={field.key}
295 field={field}
296 value={value}
297 idPrefix={idPrefix}
298 variant={variant}
299 onChange={onChange}
300 />
301 ))}
302 </>
303 );
304}