Files
triggershell/src/components/forms/dynamic-form.tsx
T

122 lines
3.8 KiB
TypeScript
Raw Normal View History

2026-08-15 18:37:30 +02:00
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
2026-08-16 00:32:30 +02:00
import { Play, Loader2, Info } from "lucide-react";
2026-08-15 18:37:30 +02:00
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Form } from "@/components/ui/form";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { buildVariableSchemaFromList } from "@/lib/validation/variable-schema";
import type { ClientScript } from "@/lib/config/serialize";
import { FieldRenderer } from "./field-renderer";
function emptyValueFor(variable: ClientScript["variables"][number]): unknown {
if (variable.type === "boolean") return false;
if (variable.type === "multiselect") return [];
return "";
}
2026-08-16 00:32:30 +02:00
/** `initialValues` comes from a previous run's (already-redacted) variables when re-running -
* secret fields are deliberately excluded there (their stored value is just "***", not the real
* one), so those always fall through to the normal empty/default state and have to be re-entered. */
function defaultValuesFor(
script: ClientScript,
initialValues?: Record<string, unknown>,
): Record<string, unknown> {
2026-08-15 18:37:30 +02:00
const values: Record<string, unknown> = {};
for (const variable of script.variables) {
2026-08-16 00:32:30 +02:00
const fromPreviousRun =
initialValues && !variable.secret
? initialValues[variable.name]
: undefined;
values[variable.name] =
fromPreviousRun ?? variable.default ?? emptyValueFor(variable);
2026-08-15 18:37:30 +02:00
}
return values;
}
2026-08-16 00:32:30 +02:00
export function DynamicForm({
script,
initialValues,
}: {
script: ClientScript;
initialValues?: Record<string, unknown>;
}) {
2026-08-15 18:37:30 +02:00
const router = useRouter();
const [submitError, setSubmitError] = useState<string | null>(null);
const schema = buildVariableSchemaFromList(script.variables);
2026-08-16 00:32:30 +02:00
const hasSecretVariable = script.variables.some((v) => v.secret);
2026-08-15 18:37:30 +02:00
const form = useForm({
resolver: zodResolver(schema),
2026-08-16 00:32:30 +02:00
defaultValues: defaultValuesFor(script, initialValues),
2026-08-15 18:37:30 +02:00
});
async function onSubmit(values: Record<string, unknown>) {
setSubmitError(null);
const response = await fetch(`/api/scripts/${script.id}/runs`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ variables: values }),
});
if (!response.ok) {
const data = await response.json().catch(() => ({}));
setSubmitError(data.error ?? "Failed to start run");
return;
}
const data = await response.json();
toast.success(`${script.name} started`);
router.push(`/runs/${data.runId}`);
}
return (
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="flex flex-col gap-5"
>
{submitError && (
<Alert variant="destructive">
<AlertDescription>{submitError}</AlertDescription>
</Alert>
)}
2026-08-16 00:32:30 +02:00
{initialValues && (
<Alert>
<Info />
<AlertDescription>
Pre-filled from a previous run.
{hasSecretVariable &&
" Secret fields aren't carried over and need to be entered again."}
</AlertDescription>
</Alert>
)}
2026-08-15 18:37:30 +02:00
{script.variables.length === 0 && (
<p className="text-muted-foreground text-sm">
This script takes no parameters.
</p>
)}
{script.variables.map((variable) => (
<FieldRenderer key={variable.name} variable={variable} />
))}
<Button
type="submit"
disabled={form.formState.isSubmitting}
className="w-fit"
>
{form.formState.isSubmitting ? (
<Loader2 className="animate-spin" />
) : (
<Play />
)}
Run
</Button>
</form>
</Form>
);
}