30 lines
1.3 KiB
TypeScript
30 lines
1.3 KiB
TypeScript
"use client";
|
|
|
|
import { FormRuntime, type SubmitResult } from "@/components/runtime/FormRuntime";
|
|
import type { Field, FormSettings } from "@/lib/types";
|
|
import { pipe } from "@/lib/pipe";
|
|
|
|
export default function FormFiller({ formId, title, description, fields, settings, initialValues, hcaptchaSiteKey }: {
|
|
formId: string; title: string; description: string | null; fields: Field[]; settings: FormSettings;
|
|
initialValues?: Record<string, unknown>;
|
|
hcaptchaSiteKey?: string | null;
|
|
}) {
|
|
async function submit(values: Record<string, unknown>, meta: { hp: string; captcha?: string }): Promise<SubmitResult> {
|
|
const r = await fetch(`/api/forms/${formId}/submit`, {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify({ data: values, _h: meta.hp, _captcha: meta.captcha }),
|
|
});
|
|
if (r.ok) {
|
|
if (settings.redirectUrl) {
|
|
window.location.replace(pipe(settings.redirectUrl, values, fields));
|
|
return { ok: true };
|
|
}
|
|
return { ok: true };
|
|
}
|
|
const j = await r.json().catch(() => ({}));
|
|
return { ok: false, error: j.error ?? "Submission failed" };
|
|
}
|
|
return <FormRuntime title={title} description={description} fields={fields} settings={settings} onSubmit={submit} initialValues={initialValues} formId={formId} hcaptchaSiteKey={hcaptchaSiteKey ?? undefined} />;
|
|
}
|