"use client"; import { useEffect, useMemo, useRef, useState, type ReactNode } from "react"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import type { ProviderSettingsFormAnnotation, ProviderSettingsFormControl, ProviderSettingsFormOption, ProviderSettingsFormSchemaAnnotation, } from "@t3tools/contracts"; import { PlusIcon, XIcon } from "lucide-react"; import { cn } from "../../lib/utils"; import { Button } from "../ui/button"; import { DraftInput } from "../ui/draft-input"; import { Input } from "../ui/input"; import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; import { Switch } from "../ui/switch"; import { Textarea } from "../ui/textarea"; import type { ProviderClientDefinition } from "@t3tools/provider-core/client"; import { SettingsRow } from "./settingsLayout"; export interface ProviderSettingsFieldModel { readonly key: string; readonly control: ProviderSettingsFormControl; readonly label: string; readonly description?: string | undefined; readonly placeholder?: string | undefined; readonly clearWhenEmpty: "omit" | "persist"; readonly defaultBooleanValue?: boolean | undefined; /** Choices for a `select` control. The first entry is the default. */ readonly options?: ReadonlyArray | undefined; } function titleizeFieldKey(key: string): string { return key .replace(/([a-z0-9])([A-Z])/g, "$1 $2") .replace(/[-_]+/g, " ") .replace(/^./, (char) => char.toUpperCase()); } function readFieldAnnotations( fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string], ) { return Schema.resolveAnnotationsKey(fieldSchema) ?? Schema.resolveAnnotations(fieldSchema); } function readFieldAnnotationString( fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string], key: "title" | "description", ): string | undefined { const annotations = readFieldAnnotations(fieldSchema); const value = annotations?.[key]; return typeof value === "string" ? value : undefined; } function readProviderSettingsFormAnnotation( fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string], ): ProviderSettingsFormAnnotation { const annotation = readFieldAnnotations(fieldSchema)?.providerSettingsForm; return annotation ?? {}; } function readProviderSettingsFormSchemaAnnotation( definition: ProviderClientDefinition, ): ProviderSettingsFormSchemaAnnotation { return Schema.resolveAnnotations(definition.settingsSchema)?.providerSettingsFormSchema ?? {}; } function readFieldBooleanDefault( fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string], ): boolean | undefined { const decodeDefault = Schema.decodeUnknownOption(fieldSchema as Schema.Decoder); const decoded = decodeDefault(undefined); return Option.isSome(decoded) && typeof decoded.value === "boolean" ? decoded.value : undefined; } export function deriveProviderSettingsFields( definition: ProviderClientDefinition, value?: unknown, ): ReadonlyArray { const isLocalAcp = definition.driverKind === "acpRegistry" && readProviderConfigString(value, "source") === "local"; const schemaAnnotation = readProviderSettingsFormSchemaAnnotation(definition); const orderedKeys = new Map( (schemaAnnotation.order ?? []).map((key, index) => [key, index] as const), ); const orderFallbackOffset = orderedKeys.size; return Object.keys(definition.settingsSchema.fields) .map((key, index) => ({ key, index })) .toSorted((left, right) => { return ( (orderedKeys.get(left.key) ?? orderFallbackOffset + left.index) - (orderedKeys.get(right.key) ?? orderFallbackOffset + right.index) ); }) .flatMap(({ key }) => { const fieldSchema = definition.settingsSchema.fields[key]!; const formAnnotation = readProviderSettingsFormAnnotation(fieldSchema); if (formAnnotation.hidden) return []; if (isLocalAcp && key !== "source" && key !== "commandPath") return []; const annotatedTitle = readFieldAnnotationString(fieldSchema, "title"); const annotatedDescription = readFieldAnnotationString(fieldSchema, "description"); return [ { key, control: formAnnotation.control ?? "text", label: isLocalAcp && key === "commandPath" ? "Executable" : (annotatedTitle ?? titleizeFieldKey(key)), ...(isLocalAcp && key === "commandPath" ? { description: "Executable name or path on this environment." } : annotatedDescription !== undefined ? { description: annotatedDescription } : {}), ...(isLocalAcp && key === "commandPath" ? { placeholder: "e.g. dsh" } : formAnnotation.placeholder !== undefined ? { placeholder: formAnnotation.placeholder } : {}), clearWhenEmpty: formAnnotation.clearWhenEmpty ?? "omit", ...(formAnnotation.control === "switch" ? { defaultBooleanValue: readFieldBooleanDefault(fieldSchema) } : {}), ...(formAnnotation.control === "select" && formAnnotation.options ? { options: formAnnotation.options } : {}), } satisfies ProviderSettingsFieldModel, ]; }); } let commandArgumentDraftId = 0; const makeCommandArgumentDraftRow = (value: string) => ({ id: `provider-argument-${commandArgumentDraftId++}`, value, }); function commandArgumentsEqual(left: ReadonlyArray, right: ReadonlyArray) { return left.length === right.length && left.every((argument, index) => argument === right[index]); } function ProviderCommandArguments({ value, onChange, }: Pick) { const args = useMemo(() => { const configured = value !== null && typeof value === "object" ? (value as Record).commandArgs : undefined; return Array.isArray(configured) ? configured.filter((argument): argument is string => typeof argument === "string") : []; }, [value]); const [rows, setRows] = useState(() => args.map(makeCommandArgumentDraftRow)); const rowsRef = useRef(rows); const previousArgsRef = useRef(args); const lastPublishedArgsRef = useRef | undefined>(undefined); useEffect(() => { const previousArgs = previousArgsRef.current; const lastPublishedArgs = lastPublishedArgsRef.current; previousArgsRef.current = args; lastPublishedArgsRef.current = undefined; if ( commandArgumentsEqual(previousArgs, args) || (lastPublishedArgs !== undefined && commandArgumentsEqual(lastPublishedArgs, args)) ) return; const nextRows = args.map(makeCommandArgumentDraftRow); rowsRef.current = nextRows; setRows(nextRows); }, [args]); const updateArguments = (nextRows: typeof rows) => { rowsRef.current = nextRows; setRows(nextRows); const next = nextRows.map((row) => row.value); lastPublishedArgsRef.current = next; const config = value !== null && typeof value === "object" ? { ...(value as Record) } : {}; onChange({ ...config, commandArgs: next }); }; return ( updateArguments([...rowsRef.current, makeCommandArgumentDraftRow("")])} > Add argument } > {rows.length > 0 ? (
{rows.map((argument, index) => (
updateArguments( rowsRef.current.map((current) => current.id === argument.id ? { ...current, value: next } : current, ), ) } aria-label={`Argument ${index + 1}`} spellCheck={false} />
))}
) : null}
); } function readProviderConfigString(config: unknown, key: string): string { if (config === null || typeof config !== "object") return ""; const value = (config as Record)[key]; return typeof value === "string" ? value : ""; } function readProviderConfigBoolean(config: unknown, key: string, defaultValue = false): boolean { if (config === null || typeof config !== "object") return defaultValue; const value = (config as Record)[key]; return typeof value === "boolean" ? value : defaultValue; } export function nextProviderConfigWithFieldValue( config: unknown, field: ProviderSettingsFieldModel, value: string | boolean, ): Record | undefined { const base: Record = config !== null && typeof config === "object" ? { ...(config as Record) } : {}; if (typeof value === "boolean") { const emptyBooleanValue = field.defaultBooleanValue ?? false; if (field.clearWhenEmpty === "omit" && value === emptyBooleanValue) { delete base[field.key]; } else { base[field.key] = value; } return Object.keys(base).length > 0 ? base : undefined; } const trimmed = value.trim(); if (field.clearWhenEmpty === "omit" && trimmed.length === 0) { delete base[field.key]; } else { base[field.key] = value; } return Object.keys(base).length > 0 ? base : undefined; } interface ProviderSettingsFormProps { readonly definition: ProviderClientDefinition; readonly value: unknown; readonly idPrefix: string; /** * `card` stacks label over control, `dialog` is the compact wizard layout, * and `settings` renders the shared settings row treatment. */ readonly variant: "card" | "dialog" | "settings"; readonly onChange: (nextConfig: Record | undefined) => void; } /** Stores the default choice as an omitted key so unchanged configs stay small. */ function ProviderSettingsSelect({ field, value, inputId, size, className, onChange, }: { readonly field: ProviderSettingsFieldModel; readonly value: unknown; readonly inputId: string; readonly size: "sm" | "xs"; readonly className?: string | undefined; readonly onChange: ProviderSettingsFormProps["onChange"]; }) { const options = field.options ?? []; const fallback = options[0]?.value ?? ""; const current = readProviderConfigString(value, field.key) || fallback; const label = options.find((option) => option.value === current)?.label ?? current; return ( ); } function FieldFrame(props: { readonly variant: ProviderSettingsFormProps["variant"]; readonly children: ReactNode; }) { if (props.variant === "card") { return
{props.children}
; } return
{props.children}
; } interface ProviderSettingsFieldRowProps { readonly field: ProviderSettingsFieldModel; readonly value: unknown; readonly idPrefix: string; readonly variant: ProviderSettingsFormProps["variant"]; readonly onChange: ProviderSettingsFormProps["onChange"]; } function ProviderSettingsFieldRow({ field, value, idPrefix, variant, onChange, }: ProviderSettingsFieldRowProps) { const inputId = `${idPrefix}-${field.key}`; const descriptionClassName = variant === "dialog" ? "text-2xs text-muted-foreground" : "mt-1 block text-xs text-muted-foreground"; const label = {field.label}; const description = field.description ? ( {field.description} ) : null; if (variant === "settings") { const descriptionId = field.description ? `${inputId}-description` : undefined; const control = field.control === "switch" ? ( onChange(nextProviderConfigWithFieldValue(value, field, Boolean(checked))) } aria-label={field.label} aria-describedby={descriptionId} /> ) : field.control === "select" ? ( ) : field.control === "textarea" ? (