Open History to see the last commit
1"use client";
2
3import { useMemo, type ReactNode } from "react";
4import { Schema } from "effect";
5import type {
6 ProviderSettingsFormAnnotation,
7 ProviderSettingsFormControl,
8 ProviderSettingsFormSchemaAnnotation,
9} from "@t3tools/contracts";
10
11import { cn } from "../../lib/utils";
12import { DraftInput } from "../ui/draft-input";
13import { Input } from "../ui/input";
14import { Switch } from "../ui/switch";
15import { Textarea } from "../ui/textarea";
16import type { ProviderClientDefinition } from "./providerDriverMeta";
17
18export interface ProviderSettingsFieldModel {
19 readonly key: string;
20 readonly control: ProviderSettingsFormControl;
21 readonly label: string;
22 readonly description?: string | undefined;
23 readonly placeholder?: string | undefined;
24 readonly clearWhenEmpty: "omit" | "persist";
25 readonly defaultBooleanValue?: boolean | undefined;
26}
27
28function titleizeFieldKey(key: string): string {
29 return key
30 .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
31 .replace(/[-_]+/g, " ")
32 .replace(/^./, (char) => char.toUpperCase());
33}
34
35function readFieldAnnotations(
36 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
37) {
38 return Schema.resolveAnnotationsKey(fieldSchema) ?? Schema.resolveAnnotations(fieldSchema);
39}
40
41function readFieldAnnotationString(
42 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
43 key: "title" | "description",
44): string | undefined {
45 const annotations = readFieldAnnotations(fieldSchema);
46 const value = annotations?.[key];
47 return typeof value === "string" ? value : undefined;
48}
49
50function readProviderSettingsFormAnnotation(
51 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
52): ProviderSettingsFormAnnotation {
53 const annotation = readFieldAnnotations(fieldSchema)?.providerSettingsForm;
54 return annotation ?? {};
55}
56
57function readProviderSettingsFormSchemaAnnotation(
58 definition: ProviderClientDefinition,
59): ProviderSettingsFormSchemaAnnotation {
60 return Schema.resolveAnnotations(definition.settingsSchema)?.providerSettingsFormSchema ?? {};
61}
62
63function readFieldBooleanDefault(
64 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
65): boolean | undefined {
66 try {
67 const decoded = Schema.decodeUnknownSync(fieldSchema as Schema.Decoder<unknown>)(undefined);
68 return typeof decoded === "boolean" ? decoded : undefined;
69 } catch {
70 return undefined;
71 }
72}
73
74export function deriveProviderSettingsFields(
75 definition: ProviderClientDefinition,
76): ReadonlyArray<ProviderSettingsFieldModel> {
77 const schemaAnnotation = readProviderSettingsFormSchemaAnnotation(definition);
78 const orderedKeys = new Map(
79 (schemaAnnotation.order ?? []).map((key, index) => [key, index] as const),
80 );
81 const orderFallbackOffset = orderedKeys.size;
82
83 return Object.keys(definition.settingsSchema.fields)
84 .map((key, index) => ({ key, index }))
85 .toSorted((left, right) => {
86 return (
87 (orderedKeys.get(left.key) ?? orderFallbackOffset + left.index) -
88 (orderedKeys.get(right.key) ?? orderFallbackOffset + right.index)
89 );
90 })
91 .flatMap(({ key }) => {
92 const fieldSchema = definition.settingsSchema.fields[key]!;
93 const formAnnotation = readProviderSettingsFormAnnotation(fieldSchema);
94 if (formAnnotation.hidden) return [];
95
96 const annotatedTitle = readFieldAnnotationString(fieldSchema, "title");
97 const annotatedDescription = readFieldAnnotationString(fieldSchema, "description");
98 return [
99 {
100 key,
101 control: formAnnotation.control ?? "text",
102 label: annotatedTitle ?? titleizeFieldKey(key),
103 ...(annotatedDescription !== undefined ? { description: annotatedDescription } : {}),
104 ...(formAnnotation.placeholder !== undefined
105 ? { placeholder: formAnnotation.placeholder }
106 : {}),
107 clearWhenEmpty: formAnnotation.clearWhenEmpty ?? "omit",
108 ...(formAnnotation.control === "switch"
109 ? { defaultBooleanValue: readFieldBooleanDefault(fieldSchema) }
110 : {}),
111 } satisfies ProviderSettingsFieldModel,
112 ];
113 });
114}
115
116export function readProviderConfigString(config: unknown, key: string): string {
117 if (config === null || typeof config !== "object") return "";
118 const value = (config as Record<string, unknown>)[key];
119 return typeof value === "string" ? value : "";
120}
121
122export function readProviderConfigBoolean(
123 config: unknown,
124 key: string,
125 defaultValue = false,
126): boolean {
127 if (config === null || typeof config !== "object") return defaultValue;
128 const value = (config as Record<string, unknown>)[key];
129 return typeof value === "boolean" ? value : defaultValue;
130}
131
132export function nextProviderConfigWithFieldValue(
133 config: unknown,
134 field: ProviderSettingsFieldModel,
135 value: string | boolean,
136): Record<string, unknown> | undefined {
137 const base: Record<string, unknown> =
138 config !== null && typeof config === "object" ? { ...(config as Record<string, unknown>) } : {};
139
140 if (typeof value === "boolean") {
141 const emptyBooleanValue = field.defaultBooleanValue ?? false;
142 if (field.clearWhenEmpty === "omit" && value === emptyBooleanValue) {
143 delete base[field.key];
144 } else {
145 base[field.key] = value;
146 }
147 return Object.keys(base).length > 0 ? base : undefined;
148 }
149
150 const trimmed = value.trim();
151 if (field.clearWhenEmpty === "omit" && trimmed.length === 0) {
152 delete base[field.key];
153 } else {
154 base[field.key] = value;
155 }
156 return Object.keys(base).length > 0 ? base : undefined;
157}
158
159interface ProviderSettingsFormProps {
160 readonly definition: ProviderClientDefinition;
161 readonly value: unknown;
162 readonly idPrefix: string;
163 readonly variant: "card" | "dialog";
164 readonly onChange: (nextConfig: Record<string, unknown> | undefined) => void;
165}
166
167function FieldFrame(props: {
168 readonly variant: ProviderSettingsFormProps["variant"];
169 readonly children: ReactNode;
170}) {
171 if (props.variant === "card") {
172 return <div className="border-t border-border/60 px-4 py-3 sm:px-5">{props.children}</div>;
173 }
174 return <div className="grid gap-1.5">{props.children}</div>;
175}
176
177interface ProviderSettingsFieldRowProps {
178 readonly field: ProviderSettingsFieldModel;
179 readonly value: unknown;
180 readonly idPrefix: string;
181 readonly variant: ProviderSettingsFormProps["variant"];
182 readonly onChange: ProviderSettingsFormProps["onChange"];
183}
184
185function ProviderSettingsFieldRow({
186 field,
187 value,
188 idPrefix,
189 variant,
190 onChange,
191}: ProviderSettingsFieldRowProps) {
192 const inputId = `${idPrefix}-${field.key}`;
193 const descriptionClassName =
194 variant === "card"
195 ? "mt-1 block text-xs text-muted-foreground"
196 : "text-[11px] text-muted-foreground";
197 const label = <span className="text-xs font-medium text-foreground">{field.label}</span>;
198 const description = field.description ? (
199 <span className={descriptionClassName}>{field.description}</span>
200 ) : null;
201
202 if (field.control === "switch") {
203 return (
204 <FieldFrame variant={variant}>
205 <div className="flex items-center justify-between gap-3">
206 <div className="min-w-0">
207 {label}
208 {description}
209 </div>
210 <Switch
211 checked={readProviderConfigBoolean(value, field.key, field.defaultBooleanValue)}
212 onCheckedChange={(checked) =>
213 onChange(nextProviderConfigWithFieldValue(value, field, Boolean(checked)))
214 }
215 aria-label={field.label}
216 />
217 </div>
218 </FieldFrame>
219 );
220 }
221
222 if (field.control === "textarea") {
223 return (
224 <FieldFrame variant={variant}>
225 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
226 {label}
227 <Textarea
228 id={inputId}
229 className={cn(variant === "card" && "mt-1.5")}
230 value={readProviderConfigString(value, field.key)}
231 onChange={(event) =>
232 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
233 }
234 placeholder={field.placeholder}
235 spellCheck={false}
236 />
237 {description}
238 </label>
239 </FieldFrame>
240 );
241 }
242
243 const type = field.control === "password" ? "password" : undefined;
244 return (
245 <FieldFrame variant={variant}>
246 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
247 {label}
248 {variant === "card" ? (
249 <DraftInput
250 id={inputId}
251 className="mt-1.5"
252 type={type}
253 autoComplete={field.control === "password" ? "off" : undefined}
254 value={readProviderConfigString(value, field.key)}
255 onCommit={(next) => onChange(nextProviderConfigWithFieldValue(value, field, next))}
256 placeholder={field.placeholder}
257 spellCheck={false}
258 />
259 ) : (
260 <Input
261 id={inputId}
262 className="bg-background"
263 type={type}
264 autoComplete={field.control === "password" ? "off" : undefined}
265 value={readProviderConfigString(value, field.key)}
266 onChange={(event) =>
267 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
268 }
269 placeholder={field.placeholder}
270 spellCheck={false}
271 />
272 )}
273 {description}
274 </label>
275 </FieldFrame>
276 );
277}
278
279export function ProviderSettingsForm({
280 definition,
281 value,
282 idPrefix,
283 variant,
284 onChange,
285}: ProviderSettingsFormProps) {
286 const fields = useMemo(() => deriveProviderSettingsFields(definition), [definition]);
287
288 if (fields.length === 0) {
289 return null;
290 }
291
292 return (
293 <>
294 {fields.map((field) => (
295 <ProviderSettingsFieldRow
296 key={field.key}
297 field={field}
298 value={value}
299 idPrefix={idPrefix}
300 variant={variant}
301 onChange={onChange}
302 />
303 ))}
304 </>
305 );
306}