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