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