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

ProviderSettingsForm.tsx

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