Open History to see the last commit
1import { 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;
146/**
147 * Editable rows seeded from a configured value. `seen` is the value the rows
148 * were last reconciled against; `lastPublished` is what the rows last sent to
149 * the owner, so its echo does not reseed rows (and drop their ids) mid-edit.
150 */
151export interface RowsDraft<V, R> {
152 readonly rows: ReadonlyArray<R>;
153 readonly seen: V;
154 readonly lastPublished: V | undefined;
155}
156
157export function seedRowsDraft<V, R>(
158 value: V,
159 toRows: (value: V) => ReadonlyArray<R>,
160): RowsDraft<V, R> {
161 return { rows: toRows(value), seen: value, lastPublished: undefined };
162}
163
164/** Reseeds the rows when the configured value changes from outside this editor. */
165export function reconcileRowsDraft<V, R>(
166 draft: RowsDraft<V, R>,
167 incoming: V,
168 equal: (left: V, right: V) => boolean,
169 toRows: (value: V) => ReadonlyArray<R>,
170): RowsDraft<V, R> {
171 if (draft.seen === incoming || equal(draft.seen, incoming)) return draft;
172 const echo = draft.lastPublished !== undefined && equal(draft.lastPublished, incoming);
173 return { rows: echo ? draft.rows : toRows(incoming), seen: incoming, lastPublished: undefined };
174}
175
176const makeCommandArgumentDraftRow = (value: string) => ({
177 id: `provider-argument-${commandArgumentDraftId++}`,
178 value,
179});
180
181const toCommandArgumentRows = (args: ReadonlyArray<string>) =>
182 args.map(makeCommandArgumentDraftRow);
183
184function commandArgumentsEqual(left: ReadonlyArray<string>, right: ReadonlyArray<string>) {
185 return left.length === right.length && left.every((argument, index) => argument === right[index]);
186}
187
188function configuredCommandArgs(value: ProviderSettingsFormProps["value"]) {
189 const configured =
190 value !== null && typeof value === "object"
191 ? (value as Record<string, unknown>).commandArgs
192 : undefined;
193 return Array.isArray(configured)
194 ? configured.filter((argument): argument is string => typeof argument === "string")
195 : [];
196}
197
198function ProviderCommandArguments({
199 value,
200 onChange,
201}: Pick<ProviderSettingsFormProps, "value" | "onChange">) {
202 const args = configuredCommandArgs(value);
203 const [storedDraft, setDraft] = useState(() => seedRowsDraft(args, toCommandArgumentRows));
204 const draft = reconcileRowsDraft(storedDraft, args, commandArgumentsEqual, toCommandArgumentRows);
205 if (draft !== storedDraft) setDraft(draft);
206 const rows = draft.rows;
207
208 const updateArguments = (nextRows: typeof rows) => {
209 const next = nextRows.map((row) => row.value);
210 setDraft({ rows: nextRows, seen: draft.seen, lastPublished: next });
211 const config =
212 value !== null && typeof value === "object" ? { ...(value as Record<string, unknown>) } : {};
213 onChange({ ...config, commandArgs: next });
214 };
215
216 return (
217 <SettingsRow
218 title="Arguments"
219 description="One literal argument per row, in launch order."
220 control={
221 <Button
222 type="button"
223 size="sm"
224 variant="outline"
225 onClick={() => updateArguments([...rows, makeCommandArgumentDraftRow("")])}
226 >
227 <PlusIcon />
228 Add argument
229 </Button>
230 }
231 >
232 {rows.length > 0 ? (
233 <div className="mt-3 min-w-0 space-y-2 pb-2">
234 {rows.map((argument, index) => (
235 <div key={argument.id} className="flex min-w-0 items-center gap-1.5">
236 <DraftInput
237 size="sm"
238 font="mono"
239 value={argument.value}
240 onCommit={(next) =>
241 updateArguments(
242 rows.map((current) =>
243 current.id === argument.id ? { ...current, value: next } : current,
244 ),
245 )
246 }
247 aria-label={`Argument ${index + 1}`}
248 spellCheck={false}
249 />
250 <Button
251 type="button"
252 size="icon-micro"
253 variant="ghost-destructive"
254 onClick={() =>
255 updateArguments(rows.filter((current) => current.id !== argument.id))
256 }
257 aria-label={`Remove argument ${index + 1}`}
258 >
259 <XIcon />
260 </Button>
261 </div>
262 ))}
263 </div>
264 ) : null}
265 </SettingsRow>
266 );
267}
268
269function readProviderConfigString(config: unknown, key: string): string {
270 if (config === null || typeof config !== "object") return "";
271 const value = (config as Record<string, unknown>)[key];
272 return typeof value === "string" ? value : "";
273}
274
275function readProviderConfigBoolean(config: unknown, key: string, defaultValue = false): boolean {
276 if (config === null || typeof config !== "object") return defaultValue;
277 const value = (config as Record<string, unknown>)[key];
278 return typeof value === "boolean" ? value : defaultValue;
279}
280
281export function nextProviderConfigWithFieldValue(
282 config: unknown,
283 field: ProviderSettingsFieldModel,
284 value: string | boolean,
285): Record<string, unknown> | undefined {
286 const base: Record<string, unknown> =
287 config !== null && typeof config === "object" ? { ...(config as Record<string, unknown>) } : {};
288
289 if (typeof value === "boolean") {
290 const emptyBooleanValue = field.defaultBooleanValue ?? false;
291 if (field.clearWhenEmpty === "omit" && value === emptyBooleanValue) {
292 delete base[field.key];
293 } else {
294 base[field.key] = value;
295 }
296 return Object.keys(base).length > 0 ? base : undefined;
297 }
298
299 const trimmed = value.trim();
300 if (field.clearWhenEmpty === "omit" && trimmed.length === 0) {
301 delete base[field.key];
302 } else {
303 base[field.key] = value;
304 }
305 return Object.keys(base).length > 0 ? base : undefined;
306}
307
308interface ProviderSettingsFormProps {
309 readonly definition: SettingsFormDefinition;
310 readonly value: unknown;
311 readonly idPrefix: string;
312 readonly variant: "card" | "dialog" | "settings";
313 readonly onChange: (nextConfig: Record<string, unknown> | undefined) => void;
314}
315
316function ProviderSettingsSelect({
317 field,
318 value,
319 inputId,
320 size,
321 className,
322 onChange,
323}: {
324 readonly field: ProviderSettingsFieldModel;
325 readonly value: unknown;
326 readonly inputId: string;
327 readonly size: "sm" | "xs";
328 readonly className?: string | undefined;
329 readonly onChange: ProviderSettingsFormProps["onChange"];
330}) {
331 const options = field.options ?? [];
332 const fallback = options[0]?.value ?? "";
333 const current = readProviderConfigString(value, field.key) || fallback;
334 const label = options.find((option) => option.value === current)?.label ?? current;
335 return (
336 <Select
337 value={current}
338 onValueChange={(next) => {
339 if (typeof next !== "string") return;
340 onChange(nextProviderConfigWithFieldValue(value, field, next === fallback ? "" : next));
341 }}
342 >
343 <SelectTrigger id={inputId} size={size} className={className} aria-label={field.label}>
344 <SelectValue>{label}</SelectValue>
345 </SelectTrigger>
346 <SelectPopup align="start" alignItemWithTrigger={false}>
347 {options.map((option) => (
348 <SelectItem key={option.value} value={option.value}>
349 {option.label}
350 </SelectItem>
351 ))}
352 </SelectPopup>
353 </Select>
354 );
355}
356
357function FieldFrame(props: {
358 readonly variant: ProviderSettingsFormProps["variant"];
359 readonly children: ReactNode;
360}) {
361 if (props.variant === "card") {
362 return <div>{props.children}</div>;
363 }
364 return <div className="grid gap-1.5">{props.children}</div>;
365}
366
367interface ProviderSettingsFieldRowProps {
368 readonly field: ProviderSettingsFieldModel;
369 readonly value: unknown;
370 readonly idPrefix: string;
371 readonly variant: ProviderSettingsFormProps["variant"];
372 readonly onChange: ProviderSettingsFormProps["onChange"];
373}
374
375function ProviderSettingsFieldRow({
376 field,
377 value,
378 idPrefix,
379 variant,
380 onChange,
381}: ProviderSettingsFieldRowProps) {
382 const inputId = `${idPrefix}-${field.key}`;
383 const descriptionClassName =
384 variant === "dialog"
385 ? "text-2xs text-muted-foreground"
386 : "mt-1 block text-xs text-muted-foreground";
387 const label = <span className="text-xs font-medium text-foreground">{field.label}</span>;
388 const description = field.description ? (
389 <span className={descriptionClassName}>{field.description}</span>
390 ) : null;
391
392 if (variant === "settings") {
393 const descriptionId = field.description ? `${inputId}-description` : undefined;
394 const secretConfigured =
395 field.secret === true && readProviderConfigString(value, field.key).length > 0;
396 const control =
397 field.control === "switch" ? (
398 <Switch
399 checked={readProviderConfigBoolean(value, field.key, field.defaultBooleanValue)}
400 onCheckedChange={(checked) =>
401 onChange(nextProviderConfigWithFieldValue(value, field, Boolean(checked)))
402 }
403 aria-label={field.label}
404 aria-describedby={descriptionId}
405 />
406 ) : field.control === "select" ? (
407 <ProviderSettingsSelect
408 field={field}
409 value={value}
410 inputId={inputId}
411 size="sm"
412 className="w-full max-w-full @min-[32rem]/settings-row:w-56"
413 onChange={onChange}
414 />
415 ) : field.control === "textarea" ? (
416 <Textarea
417 id={inputId}
418 aria-describedby={descriptionId}
419 className="w-full max-w-full @min-[32rem]/settings-row:w-[min(24rem,50cqw)]"
420 value={readProviderConfigString(value, field.key)}
421 onChange={(event) =>
422 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
423 }
424 placeholder={field.placeholder}
425 spellCheck={false}
426 />
427 ) : field.secret ? (
428 <div className="flex w-full min-w-0 items-center gap-2 @min-[32rem]/settings-row:w-56">
429 <SecretInput
430 id={inputId}
431 aria-describedby={descriptionId}
432 size="sm"
433 className="min-w-0 flex-1"
434 configured={secretConfigured}
435 value=""
436 onCommit={(next) => onChange(nextProviderConfigWithFieldValue(value, field, next))}
437 />
438 {secretConfigured ? (
439 <Button
440 type="button"
441 size="icon-sm"
442 variant="ghost-destructive"
443 onClick={() => onChange(nextProviderConfigWithFieldValue(value, field, ""))}
444 aria-label={`Clear ${field.label}`}
445 >
446 <XIcon className="size-3.5" />
447 </Button>
448 ) : null}
449 </div>
450 ) : (
451 <DraftInput
452 id={inputId}
453 aria-describedby={descriptionId}
454 size="sm"
455 className="w-full max-w-full @min-[32rem]/settings-row:w-56"
456 type={field.control === "password" ? "password" : undefined}
457 autoComplete={field.control === "password" ? "off" : undefined}
458 value={readProviderConfigString(value, field.key)}
459 placeholder={field.placeholder}
460 onCommit={(next) => {
461 onChange(nextProviderConfigWithFieldValue(value, field, next));
462 }}
463 spellCheck={false}
464 />
465 );
466
467 return (
468 <SettingsRow
469 title={
470 field.control === "switch" ? field.label : <label htmlFor={inputId}>{field.label}</label>
471 }
472 description={
473 field.description ? <span id={descriptionId}>{field.description}</span> : undefined
474 }
475 control={control}
476 />
477 );
478 }
479
480 if (field.control === "switch") {
481 return (
482 <FieldFrame variant={variant}>
483 <div className="flex items-center justify-between gap-3">
484 <div className="min-w-0">
485 {label}
486 {description}
487 </div>
488 <Switch
489 checked={readProviderConfigBoolean(value, field.key, field.defaultBooleanValue)}
490 onCheckedChange={(checked) =>
491 onChange(nextProviderConfigWithFieldValue(value, field, Boolean(checked)))
492 }
493 aria-label={field.label}
494 />
495 </div>
496 </FieldFrame>
497 );
498 }
499
500 if (field.control === "select") {
501 return (
502 <FieldFrame variant={variant}>
503 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
504 {label}
505 <ProviderSettingsSelect
506 field={field}
507 value={value}
508 inputId={inputId}
509 size="sm"
510 className={cn("w-full", variant === "card" && "mt-1.5")}
511 onChange={onChange}
512 />
513 {description}
514 </label>
515 </FieldFrame>
516 );
517 }
518
519 if (field.control === "textarea") {
520 return (
521 <FieldFrame variant={variant}>
522 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
523 {label}
524 <Textarea
525 id={inputId}
526 className={cn(variant === "card" && "mt-1.5")}
527 value={readProviderConfigString(value, field.key)}
528 onChange={(event) =>
529 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
530 }
531 placeholder={field.placeholder}
532 spellCheck={false}
533 />
534 {description}
535 </label>
536 </FieldFrame>
537 );
538 }
539
540 const type = field.control === "password" ? "password" : undefined;
541 const BufferedInput = field.secret ? SecretInput : DraftInput;
542 const ControlledInput = field.secret ? SecretInput : Input;
543 return (
544 <FieldFrame variant={variant}>
545 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
546 {label}
547 {variant === "card" ? (
548 <BufferedInput
549 id={inputId}
550 size="sm"
551 className="mt-1.5"
552 type={field.secret ? undefined : type}
553 autoComplete={!field.secret && field.control === "password" ? "off" : undefined}
554 value={readProviderConfigString(value, field.key)}
555 onCommit={(next) => onChange(nextProviderConfigWithFieldValue(value, field, next))}
556 placeholder={field.placeholder}
557 spellCheck={false}
558 />
559 ) : (
560 <ControlledInput
561 id={inputId}
562 type={field.secret ? undefined : type}
563 autoComplete={!field.secret && field.control === "password" ? "off" : undefined}
564 value={readProviderConfigString(value, field.key)}
565 onChange={(event) =>
566 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
567 }
568 placeholder={field.placeholder}
569 spellCheck={false}
570 />
571 )}
572 {description}
573 </label>
574 </FieldFrame>
575 );
576}
577
578export function ProviderSettingsForm({
579 definition,
580 value,
581 idPrefix,
582 variant,
583 onChange,
584}: ProviderSettingsFormProps) {
585 const fields = deriveProviderSettingsFields(definition, value);
586 const isLocalAcp =
587 definition.driverKind === "acpRegistry" &&
588 readProviderConfigString(value, "source") === "local";
589
590 if (fields.length === 0) {
591 return null;
592 }
593
594 return (
595 <>
596 {fields.map((field) => (
597 <ProviderSettingsFieldRow
598 key={field.key}
599 field={field}
600 value={value}
601 idPrefix={idPrefix}
602 variant={variant}
603 onChange={onChange}
604 />
605 ))}
606 {isLocalAcp ? <ProviderCommandArguments value={value} onChange={onChange} /> : null}
607 </>
608 );
609}