62 lines
2.1 KiB
TypeScript
62 lines
2.1 KiB
TypeScript
/**
|
|
* Embedded form renderer route.
|
|
*
|
|
* The route resolves a public form by opaque key; rendering lives in
|
|
* `PublicFormRenderer` so the iframe embed route and the public slug route
|
|
* share one implementation.
|
|
*/
|
|
import { useLoaderData } from "react-router";
|
|
import { FormDefinitionSchema, FormThemeSchema, type FormDefinition, type FormTheme } from "@hivegrid/form-widget";
|
|
import { getSitekey, resolveCaptchaConfig } from "@hivegrid/captcha";
|
|
import { PublicFormRenderer } from "~/modules/forms/public/PublicFormRenderer";
|
|
import { db } from "~/utils/db.server";
|
|
|
|
type LoaderResult = {
|
|
formKey: string;
|
|
definition: FormDefinition;
|
|
theme: FormTheme;
|
|
captcha: { enabled: boolean; provider: "mcaptcha" | "cap"; instanceUrl: string | undefined; sitekey: string | undefined };
|
|
};
|
|
|
|
export async function loader({ params }: { params: { formKey?: string } }): Promise<Response> {
|
|
const formKey = params.formKey;
|
|
if (!formKey) {
|
|
throw new Response(null, { status: 404 });
|
|
}
|
|
const form = await db.form.findUnique({
|
|
where: { key: formKey },
|
|
select: { key: true, isEnabled: true, definition: true, theme: true },
|
|
});
|
|
if (!form || !form.isEnabled) {
|
|
throw new Response(null, { status: 404 });
|
|
}
|
|
const def = FormDefinitionSchema.safeParse(form.definition);
|
|
if (!def.success) {
|
|
throw new Response(null, { status: 500 });
|
|
}
|
|
const theme = FormThemeSchema.safeParse(form.theme ?? {});
|
|
const captcha = resolveCaptchaConfig(process.env);
|
|
const headers = new Headers({
|
|
"x-frame-options": "ALLOWALL",
|
|
"cache-control": "private, max-age=60",
|
|
});
|
|
return Response.json(
|
|
{
|
|
formKey: form.key,
|
|
definition: def.data,
|
|
theme: theme.success ? theme.data : {},
|
|
captcha: {
|
|
enabled: def.data.captchaEnabled === true,
|
|
provider: captcha.provider,
|
|
instanceUrl: captcha.instanceUrl,
|
|
sitekey: getSitekey(captcha, "forms"),
|
|
},
|
|
} satisfies LoaderResult,
|
|
{ headers },
|
|
);
|
|
}
|
|
|
|
export default function EmbeddedForm(): React.JSX.Element {
|
|
return <PublicFormRenderer {...(useLoaderData() as LoaderResult)} />;
|
|
}
|