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

ProviderSettingsForm.tsx

595 lines20.0 KB

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;
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());
50​
51function readFieldAnnotations(
52 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
53) {
54 return Schema.resolveAnnotationsKey(fieldSchema) ?? Schema.resolveAnnotations(fieldSchema);
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;
65​
66function readProviderSettingsFormAnnotation(
67 fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
68): ProviderSettingsFormAnnotation {
69 const annotation = readFieldAnnotations(fieldSchema)?.providerSettingsForm;
70 return annotation ?? {};
72​
73function readProviderSettingsFormSchemaAnnotation(
74 definition: SettingsFormDefinition,
75): ProviderSettingsFormSchemaAnnotation {
76 return Schema.resolveAnnotations(definition.settingsSchema)?.providerSettingsFormSchema ?? {};
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;
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 });
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]);
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 : [];
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 );
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 : "";
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;
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;
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;
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 );
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>;
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"];
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 secretConfigured =
381 field.secret === true && readProviderConfigString(value, field.key).length > 0;
382 const control =
383 field.control === "switch" ? (
384 <Switch
385 checked={readProviderConfigBoolean(value, field.key, field.defaultBooleanValue)}
386 onCheckedChange={(checked) =>
387 onChange(nextProviderConfigWithFieldValue(value, field, Boolean(checked)))
388 }
389 aria-label={field.label}
390 aria-describedby={descriptionId}
391 />
392 ) : field.control === "select" ? (
393 <ProviderSettingsSelect
394 field={field}
395 value={value}
396 inputId={inputId}
397 size="sm"
398 className="w-full max-w-full @min-[32rem]/settings-row:w-56"
399 onChange={onChange}
400 />
401 ) : field.control === "textarea" ? (
402 <Textarea
403 id={inputId}
404 aria-describedby={descriptionId}
405 className="w-full max-w-full @min-[32rem]/settings-row:w-[min(24rem,50cqw)]"
406 value={readProviderConfigString(value, field.key)}
407 onChange={(event) =>
408 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
409 }
410 placeholder={field.placeholder}
411 spellCheck={false}
412 />
413 ) : field.secret ? (
414 <div className="flex w-full min-w-0 items-center gap-2 @min-[32rem]/settings-row:w-56">
415 <SecretInput
416 id={inputId}
417 aria-describedby={descriptionId}
418 size="sm"
419 className="min-w-0 flex-1"
420 configured={secretConfigured}
421 value=""
422 onCommit={(next) => onChange(nextProviderConfigWithFieldValue(value, field, next))}
423 />
424 {secretConfigured ? (
425 <Button
426 type="button"
427 size="icon-sm"
428 variant="ghost-destructive"
429 onClick={() => onChange(nextProviderConfigWithFieldValue(value, field, ""))}
430 aria-label={`Clear ${field.label}`}
431 >
432 <XIcon className="size-3.5" />
433 </Button>
434 ) : null}
435 </div>
436 ) : (
437 <DraftInput
438 id={inputId}
439 aria-describedby={descriptionId}
440 size="sm"
441 className="w-full max-w-full @min-[32rem]/settings-row:w-56"
442 type={field.control === "password" ? "password" : undefined}
443 autoComplete={field.control === "password" ? "off" : undefined}
444 value={readProviderConfigString(value, field.key)}
445 placeholder={field.placeholder}
446 onCommit={(next) => {
447 onChange(nextProviderConfigWithFieldValue(value, field, next));
448 }}
449 spellCheck={false}
450 />
451 );
452​
453 return (
454 <SettingsRow
455 title={
456 field.control === "switch" ? field.label : <label htmlFor={inputId}>{field.label}</label>
457 }
458 description={
459 field.description ? <span id={descriptionId}>{field.description}</span> : undefined
460 }
461 control={control}
462 />
463 );
464 }
465​
466 if (field.control === "switch") {
467 return (
468 <FieldFrame variant={variant}>
469 <div className="flex items-center justify-between gap-3">
470 <div className="min-w-0">
471 {label}
472 {description}
473 </div>
474 <Switch
475 checked={readProviderConfigBoolean(value, field.key, field.defaultBooleanValue)}
476 onCheckedChange={(checked) =>
477 onChange(nextProviderConfigWithFieldValue(value, field, Boolean(checked)))
478 }
479 aria-label={field.label}
480 />
481 </div>
482 </FieldFrame>
483 );
484 }
485​
486 if (field.control === "select") {
487 return (
488 <FieldFrame variant={variant}>
489 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
490 {label}
491 <ProviderSettingsSelect
492 field={field}
493 value={value}
494 inputId={inputId}
495 size="sm"
496 className={cn("w-full", variant === "card" && "mt-1.5")}
497 onChange={onChange}
498 />
499 {description}
500 </label>
501 </FieldFrame>
502 );
503 }
504​
505 if (field.control === "textarea") {
506 return (
507 <FieldFrame variant={variant}>
508 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
509 {label}
510 <Textarea
511 id={inputId}
512 className={cn(variant === "card" && "mt-1.5")}
513 value={readProviderConfigString(value, field.key)}
514 onChange={(event) =>
515 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
516 }
517 placeholder={field.placeholder}
518 spellCheck={false}
519 />
520 {description}
521 </label>
522 </FieldFrame>
523 );
524 }
525​
526 const type = field.control === "password" ? "password" : undefined;
527 const BufferedInput = field.secret ? SecretInput : DraftInput;
528 const ControlledInput = field.secret ? SecretInput : Input;
529 return (
530 <FieldFrame variant={variant}>
531 <label htmlFor={inputId} className={cn(variant === "card" && "block")}>
532 {label}
533 {variant === "card" ? (
534 <BufferedInput
535 id={inputId}
536 size="sm"
537 className="mt-1.5"
538 type={field.secret ? undefined : type}
539 autoComplete={!field.secret && field.control === "password" ? "off" : undefined}
540 value={readProviderConfigString(value, field.key)}
541 onCommit={(next) => onChange(nextProviderConfigWithFieldValue(value, field, next))}
542 placeholder={field.placeholder}
543 spellCheck={false}
544 />
545 ) : (
546 <ControlledInput
547 id={inputId}
548 type={field.secret ? undefined : type}
549 autoComplete={!field.secret && field.control === "password" ? "off" : undefined}
550 value={readProviderConfigString(value, field.key)}
551 onChange={(event) =>
552 onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
553 }
554 placeholder={field.placeholder}
555 spellCheck={false}
556 />
557 )}
558 {description}
559 </label>
560 </FieldFrame>
561 );
563​
564export function ProviderSettingsForm({
565 definition,
566 value,
567 idPrefix,
568 variant,
569 onChange,
570}: ProviderSettingsFormProps) {
571 const fields = deriveProviderSettingsFields(definition, value);
572 const isLocalAcp =
573 definition.driverKind === "acpRegistry" &&
574 readProviderConfigString(value, "source") === "local";
575​
576 if (fields.length === 0) {
577 return null;
578 }
579​
580 return (
581 <>
582 {fields.map((field) => (
583 <ProviderSettingsFieldRow
584 key={field.key}
585 field={field}
586 value={value}
587 idPrefix={idPrefix}
588 variant={variant}
589 onChange={onChange}
590 />
591 ))}
592 {isLocalAcp ? <ProviderCommandArguments value={value} onChange={onChange} /> : null}
593 </>
594 );