Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProviderSettingsForm.tsx

587 lines19.8 KB

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