Open History to see the last commit
1"use client";
2
3import { useEffect, useMemo, useRef, useState, 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";
12import { PlusIcon, XIcon } from "lucide-react";
13
14import { cn } from "../../lib/utils";
15import { Button } from "../ui/button";
16import { DraftInput } from "../ui/draft-input";
17import { Input } from "../ui/input";
18import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
19import { Switch } from "../ui/switch";
20import { Textarea } from "../ui/textarea";
21import type { ProviderClientDefinition } from "@t3tools/provider-core/client";
22import { SettingsRow } from "./settingsLayout";
23
24export interface ProviderSettingsFieldModel {
25 readonly key: string;
26 readonly control: ProviderSettingsFormControl;
27 readonly label: string;
28 readonly description?: string | undefined;
29 readonly placeholder?: string | undefined;
30 readonly clearWhenEmpty: "omit" | "persist";
31 readonly defaultBooleanValue?: boolean | undefined;
32 /** Choices for a `select` control. The first entry is the default. */
33 readonly options?: ReadonlyArray<ProviderSettingsFormOption> | undefined;
34}
35
36function titleizeFieldKey(key: string): string {
37 return key
38 .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
39 .replace(/[-_]+/g, " ")
40 .replace(/^./, (char) => char.toUpperCase());
41}
42
43function readFieldAnnotations(
44 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
45) {
46 return Schema.resolveAnnotationsKey(fieldSchema) ?? Schema.resolveAnnotations(fieldSchema);
47}
48
49function readFieldAnnotationString(
50 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
51 key: "title" | "description",
52): string | undefined {
53 const annotations = readFieldAnnotations(fieldSchema);
54 const value = annotations?.[key];
55 return typeof value === "string" ? value : undefined;
56}
57
58function readProviderSettingsFormAnnotation(
59 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
60): ProviderSettingsFormAnnotation {
61 const annotation = readFieldAnnotations(fieldSchema)?.providerSettingsForm;
62 return annotation ?? {};
63}
64
65function readProviderSettingsFormSchemaAnnotation(
66 definition: ProviderClientDefinition,
67): ProviderSettingsFormSchemaAnnotation {
68 return Schema.resolveAnnotations(definition.settingsSchema)?.providerSettingsFormSchema ?? {};
69}
70
71function readFieldBooleanDefault(
72 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
73): boolean | undefined {
74 const decodeDefault = Schema.decodeUnknownOption(fieldSchema as Schema.Decoder<unknown>);
75 const decoded = decodeDefault(undefined);
76 return Option.isSome(decoded) && typeof decoded.value === "boolean" ? decoded.value : undefined;
77}
78
79export function deriveProviderSettingsFields(
80 definition: ProviderClientDefinition,
81 value?: unknown,
82): ReadonlyArray<ProviderSettingsFieldModel> {
83 const isLocalAcp =
84 definition.driverKind === "acpRegistry" &&
85 readProviderConfigString(value, "source") === "local";
86 const schemaAnnotation = readProviderSettingsFormSchemaAnnotation(definition);
87 const orderedKeys = new Map(
88 (schemaAnnotation.order ?? []).map((key, index) => [key, index] as const),
89 );
90 const orderFallbackOffset = orderedKeys.size;
91
92 return Object.keys(definition.settingsSchema.fields)
93 .map((key, index) => ({ key, index }))
94 .toSorted((left, right) => {
95 return (
96 (orderedKeys.get(left.key) ?? orderFallbackOffset + left.index) -
97 (orderedKeys.get(right.key) ?? orderFallbackOffset + right.index)
98 );
99 })
100 .flatMap(({ key }) => {
101 const fieldSchema = definition.settingsSchema.fields[key]!;
102 const formAnnotation = readProviderSettingsFormAnnotation(fieldSchema);
103 if (formAnnotation.hidden) return [];
104 if (isLocalAcp && key !== "source" && key !== "commandPath") return [];
105
106 const annotatedTitle = readFieldAnnotationString(fieldSchema, "title");
107 const annotatedDescription = readFieldAnnotationString(fieldSchema, "description");
108 return [
109 {
110 key,
111 control: formAnnotation.control ?? "text",
112 label:
113 isLocalAcp && key === "commandPath"
114 ? "Executable"
115 : (annotatedTitle ?? titleizeFieldKey(key)),
116 ...(isLocalAcp && key === "commandPath"
117 ? { description: "Executable name or path on this environment." }
118 : annotatedDescription !== undefined
119 ? { description: annotatedDescription }
120 : {}),
121 ...(isLocalAcp && key === "commandPath"
122 ? { placeholder: "e.g. dsh" }
123 : formAnnotation.placeholder !== undefined
124 ? { placeholder: formAnnotation.placeholder }
125 : {}),
126 clearWhenEmpty: formAnnotation.clearWhenEmpty ?? "omit",
127 ...(formAnnotation.control === "switch"
128 ? { defaultBooleanValue: readFieldBooleanDefault(fieldSchema) }
129 : {}),
130 ...(formAnnotation.control === "select" && formAnnotation.options
131 ? { options: formAnnotation.options }
132 : {}),
133 } satisfies ProviderSettingsFieldModel,
134 ];
135 });
136}
137
138let commandArgumentDraftId = 0;
139const makeCommandArgumentDraftRow = (value: string) => ({
140 id: `provider-argument-${commandArgumentDraftId++}`,
141 value,
142});
143
144function commandArgumentsEqual(left: ReadonlyArray<string>, right: ReadonlyArray<string>) {
145 return left.length === right.length && left.every((argument, index) => argument === right[index]);
146}
147
148function ProviderCommandArguments({
149 value,
150 onChange,
151}: Pick<ProviderSettingsFormProps, "value" | "onChange">) {
152 const args = useMemo(() => {
153 const configured =
154 value !== null && typeof value === "object"
155 ? (value as Record<string, unknown>).commandArgs
156 : undefined;
157 return Array.isArray(configured)
158 ? configured.filter((argument): argument is string => typeof argument === "string")
159 : [];
160 }, [value]);
161 const [rows, setRows] = useState(() => args.map(makeCommandArgumentDraftRow));
162 const rowsRef = useRef(rows);
163 const previousArgsRef = useRef(args);
164 const lastPublishedArgsRef = useRef<ReadonlyArray<string> | undefined>(undefined);
165
166 useEffect(() => {
167 const previousArgs = previousArgsRef.current;
168 const lastPublishedArgs = lastPublishedArgsRef.current;
169 previousArgsRef.current = args;
170 lastPublishedArgsRef.current = undefined;
171 if (
172 commandArgumentsEqual(previousArgs, args) ||
173 (lastPublishedArgs !== undefined && commandArgumentsEqual(lastPublishedArgs, args))
174 )
175 return;
176 const nextRows = args.map(makeCommandArgumentDraftRow);
177 rowsRef.current = nextRows;
178 setRows(nextRows);
179 }, [args]);
180
181 const updateArguments = (nextRows: typeof rows) => {
182 rowsRef.current = nextRows;
183 setRows(nextRows);
184 const next = nextRows.map((row) => row.value);
185 lastPublishedArgsRef.current = next;
186 const config =
187 value !== null && typeof value === "object" ? { ...(value as Record<string, unknown>) } : {};
188 onChange({ ...config, commandArgs: next });
189 };
190
191 return (
192 <SettingsRow
193 title="Arguments"
194 description="One literal argument per row, in launch order."
195 control={
196 <Button
197 type="button"
198 size="sm"
199 variant="outline"
200 onClick={() => updateArguments([...rowsRef.current, makeCommandArgumentDraftRow("")])}
201 >
202 <PlusIcon />
203 Add argument
204 </Button>
205 }
206 >
207 {rows.length > 0 ? (
208 <div className="mt-3 min-w-0 space-y-2 pb-2">
209 {rows.map((argument, index) => (
210 <div key={argument.id} className="flex min-w-0 items-center gap-1.5">
211 <DraftInput
212 size="sm"
213 font="mono"
214 value={argument.value}
215 onCommit={(next) =>
216 updateArguments(
217 rowsRef.current.map((current) =>
218 current.id === argument.id ? { ...current, value: next } : current,
219 ),
220 )
221 }
222 aria-label={`Argument ${index + 1}`}
223 spellCheck={false}
224 />
225 <Button
226 type="button"
227 size="icon-micro"
228 variant="ghost-destructive"
229 onClick={() =>
230 updateArguments(rowsRef.current.filter((current) => current.id !== argument.id))
231 }
232 aria-label={`Remove argument ${index + 1}`}
233 >
234 <XIcon />
235 </Button>
236 </div>
237 ))}
238 </div>
239 ) : null}
240 </SettingsRow>
241 );
242}
243
244function readProviderConfigString(config: unknown, key: string): string {
245 if (config === null || typeof config !== "object") return "";
246 const value = (config as Record<string, unknown>)[key];
247 return typeof value === "string" ? value : "";
248}
249
250function readProviderConfigBoolean(config: unknown, key: string, defaultValue = false): boolean {
251 if (config === null || typeof config !== "object") return defaultValue;
252 const value = (config as Record<string, unknown>)[key];
253 return typeof value === "boolean" ? value : defaultValue;
254}
255
256export function nextProviderConfigWithFieldValue(
257 config: unknown,
258 field: ProviderSettingsFieldModel,
259 value: string | boolean,
260): Record<string, unknown> | undefined {
261 const base: Record<string, unknown> =
262 config !== null && typeof config === "object" ? { ...(config as Record<string, unknown>) } : {};
263
264 if (typeof value === "boolean") {
265 const emptyBooleanValue = field.defaultBooleanValue ?? false;
266 if (field.clearWhenEmpty === "omit" && value === emptyBooleanValue) {
267 delete base[field.key];
268 } else {
269 base[field.key] = value;
270 }
271 return Object.keys(base).length > 0 ? base : undefined;
272 }
273
274 const trimmed = value.trim();
275 if (field.clearWhenEmpty === "omit" && trimmed.length === 0) {
276 delete base[field.key];
277 } else {
278 base[field.key] = value;
279 }
280 return Object.keys(base).length > 0 ? base : undefined;
281}
282
283interface ProviderSettingsFormProps {
284 readonly definition: ProviderClientDefinition;
285 readonly value: unknown;
286 readonly idPrefix: string;
287 /**
288 * `card` stacks label over control, `dialog` is the compact wizard layout,
289 * and `settings` renders the shared settings row treatment.
290 */
291 readonly variant: "card" | "dialog" | "settings";
292 readonly onChange: (nextConfig: Record<string, unknown> | undefined) => void;
293}
294
295/** Stores the default choice as an omitted key so unchanged configs stay small. */
296function ProviderSettingsSelect({
297 field,
298 value,
299 inputId,
300 size,
301 className,
302 onChange,
303}: {
304 readonly field: ProviderSettingsFieldModel;
305 readonly value: unknown;
306 readonly inputId: string;
307 readonly size: "sm" | "xs";
308 readonly className?: string | undefined;
309 readonly onChange: ProviderSettingsFormProps["onChange"];
310}) {
311 const options = field.options ?? [];
312 const fallback = options[0]?.value ?? "";
313 const current = readProviderConfigString(value, field.key) || fallback;
314 const label = options.find((option) => option.value === current)?.label ?? current;
315 return (
316 <Select
317 value={current}
318 onValueChange={(next) => {
319 if (typeof next !== "string") return;
320 onChange(nextProviderConfigWithFieldValue(value, field, next === fallback ? "" : next));
321 }}
322 >
323 <SelectTrigger id={inputId} size={size} className={className} aria-label={field.label}>
324 <SelectValue>{label}</SelectValue>
325 </SelectTrigger>
326 <SelectPopup align="start" alignItemWithTrigger={false}>
327 {options.map((option) => (
328 <SelectItem key={option.value} value={option.value}>
329 {option.label}
330 </SelectItem>
331 ))}
332 </SelectPopup>
333 </Select>
334 );
335}
336
337function FieldFrame(props: {
338 readonly variant: ProviderSettingsFormProps["variant"];
339 readonly children: ReactNode;
340}) {
341 if (props.variant === "card") {
342 return <div>{props.children}</div>;
343 }
344 return <div className="grid gap-1.5">{props.children}</div>;
345}
346
347interface ProviderSettingsFieldRowProps {
348 readonly field: ProviderSettingsFieldModel;
349 readonly value: unknown;
350 readonly idPrefix: string;
351 readonly variant: ProviderSettingsFormProps["variant"];
352 readonly onChange: ProviderSettingsFormProps["onChange"];
353}
354
355function ProviderSettingsFieldRow({
356 field,
357 value,
358 idPrefix,
359 variant,
360 onChange,
361}: ProviderSettingsFieldRowProps) {
362 const inputId = `${idPrefix}-${field.key}`;
363 const descriptionClassName =
364 variant === "dialog"
365 ? "text-2xs text-muted-foreground"
366 : "mt-1 block text-xs text-muted-foreground";
367 const label = <span className="text-xs font-medium text-foreground">{field.label}</span>;
368 const description = field.description ? (
369 <span className={descriptionClassName}>{field.description}</span>
370 ) : null;
371
372 if (variant === "settings") {
373 const descriptionId = field.description ? `${inputId}-description` : undefined;
374 const control =
375 field.control === "switch" ? (
376 <Switch
377 checked={readProviderConfigBoolean(value, field.key, field.defaultBooleanValue)}
378 onCheckedChange={(checked) =>
379 onChange(nextProviderConfigWithFieldValue(value, field, Boolean(checked)))
380 }
381 aria-label={field.label}
382 aria-describedby={descriptionId}
383 />
384 ) : field.control === "select" ? (
385 <ProviderSettingsSelect
386 field={field}
387 value={value}
388 inputId={inputId}
389 size="sm"
390 className="w-full max-w-full @min-[32rem]/settings-row:w-56"
391 onChange={onChange}
392 />
393 ) : field.control === "textarea" ? (
394 <Textarea
395 id={inputId}
396 aria-describedby={descriptionId}
397 className="w-full max-w-full @min-[32rem]/settings-row:w-[min(24rem,50cqw)]"
398 value={readProviderConfigString(value, field.key)}
399 onChange={(event) =>
400 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
401 }
402 placeholder={field.placeholder}
403 spellCheck={false}
404 />
405 ) : (
406 <DraftInput
407 id={inputId}
408 aria-describedby={descriptionId}
409 size="sm"
410 className="w-full max-w-full @min-[32rem]/settings-row:w-56"
411 type={field.control === "password" ? "password" : undefined}
412 autoComplete={field.control === "password" ? "off" : undefined}
413 value={readProviderConfigString(value, field.key)}
414 onCommit={(next) => onChange(nextProviderConfigWithFieldValue(value, field, next))}
415 placeholder={field.placeholder}
416 spellCheck={false}
417 />
418 );
419
420 return (
421 <SettingsRow
422 title={
423 field.control === "switch" ? field.label : <label htmlFor={inputId}>{field.label}</label>
424 }
425 description={
426 field.description ? <span id={descriptionId}>{field.description}</span> : undefined
427 }
428 control={control}
429 />
430 );
431 }
432
433 if (field.control === "switch") {
434 return (
435 <FieldFrame variant={variant}>
436 <div className="flex items-center justify-between gap-3">
437 <div className="min-w-0">
438 {label}
439 {description}
440 </div>
441 <Switch
442 checked={readProviderConfigBoolean(value, field.key, field.defaultBooleanValue)}
443 onCheckedChange={(checked) =>
444 onChange(nextProviderConfigWithFieldValue(value, field, Boolean(checked)))
445 }
446 aria-label={field.label}
447 />
448 </div>
449 </FieldFrame>
450 );
451 }
452
453 if (field.control === "select") {
454 return (
455 <FieldFrame variant={variant}>
456 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
457 {label}
458 <ProviderSettingsSelect
459 field={field}
460 value={value}
461 inputId={inputId}
462 size="sm"
463 className={cn("w-full", variant === "card" && "mt-1.5")}
464 onChange={onChange}
465 />
466 {description}
467 </label>
468 </FieldFrame>
469 );
470 }
471
472 if (field.control === "textarea") {
473 return (
474 <FieldFrame variant={variant}>
475 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
476 {label}
477 <Textarea
478 id={inputId}
479 className={cn(variant === "card" && "mt-1.5")}
480 value={readProviderConfigString(value, field.key)}
481 onChange={(event) =>
482 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
483 }
484 placeholder={field.placeholder}
485 spellCheck={false}
486 />
487 {description}
488 </label>
489 </FieldFrame>
490 );
491 }
492
493 const type = field.control === "password" ? "password" : undefined;
494 return (
495 <FieldFrame variant={variant}>
496 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
497 {label}
498 {variant === "card" ? (
499 <DraftInput
500 id={inputId}
501 size="sm"
502 className="mt-1.5"
503 type={type}
504 autoComplete={field.control === "password" ? "off" : undefined}
505 value={readProviderConfigString(value, field.key)}
506 onCommit={(next) => onChange(nextProviderConfigWithFieldValue(value, field, next))}
507 placeholder={field.placeholder}
508 spellCheck={false}
509 />
510 ) : (
511 <Input
512 id={inputId}
513 type={type}
514 autoComplete={field.control === "password" ? "off" : undefined}
515 value={readProviderConfigString(value, field.key)}
516 onChange={(event) =>
517 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
518 }
519 placeholder={field.placeholder}
520 spellCheck={false}
521 />
522 )}
523 {description}
524 </label>
525 </FieldFrame>
526 );
527}
528
529export function ProviderSettingsForm({
530 definition,
531 value,
532 idPrefix,
533 variant,
534 onChange,
535}: ProviderSettingsFormProps) {
536 const fields = useMemo(
537 () => deriveProviderSettingsFields(definition, value),
538 [definition, value],
539 );
540 const isLocalAcp =
541 definition.driverKind === "acpRegistry" &&
542 readProviderConfigString(value, "source") === "local";
543
544 if (fields.length === 0) {
545 return null;
546 }
547
548 return (
549 <>
550 {fields.map((field) => (
551 <ProviderSettingsFieldRow
552 key={field.key}
553 field={field}
554 value={value}
555 idPrefix={idPrefix}
556 variant={variant}
557 onChange={onChange}
558 />
559 ))}
560 {isLocalAcp ? <ProviderCommandArguments value={value} onChange={onChange} /> : null}
561 </>
562 );
563}