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