Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+328
@@ -0,0 +1,328 @@
|
||||
import type * as React from "react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useFetcher } from "react-router";
|
||||
import {
|
||||
filterVisibleFields,
|
||||
HONEYPOT_FIELD_KEY,
|
||||
type FormDefinition,
|
||||
type FormField,
|
||||
type FormTheme,
|
||||
} from "@hivegrid/form-widget";
|
||||
import Captcha from "~/components/captcha/Captcha";
|
||||
|
||||
export type PublicFormRendererProps = {
|
||||
formKey: string;
|
||||
definition: FormDefinition;
|
||||
theme: FormTheme;
|
||||
captcha: { enabled: boolean; provider?: "mcaptcha" | "cap"; instanceUrl: string | undefined; sitekey: string | undefined };
|
||||
};
|
||||
|
||||
function themeCssVars(theme: FormTheme): React.CSSProperties {
|
||||
const vars: Record<string, string> = {};
|
||||
if (theme.primaryColor) vars["--tcform-primary"] = theme.primaryColor;
|
||||
if (theme.backgroundColor) vars["--tcform-bg"] = theme.backgroundColor;
|
||||
if (theme.textColor) vars["--tcform-text"] = theme.textColor;
|
||||
if (theme.fontFamily) vars["--tcform-font"] = theme.fontFamily;
|
||||
if (theme.borderRadius) vars["--tcform-radius"] = theme.borderRadius;
|
||||
return vars as React.CSSProperties;
|
||||
}
|
||||
|
||||
function postToParent(message: Record<string, unknown>): void {
|
||||
if (typeof window === "undefined" || !window.parent || window.parent === window) return;
|
||||
try {
|
||||
window.parent.postMessage(message, "*");
|
||||
} catch {
|
||||
/* ignore - sandboxed parent without same-origin scripting */
|
||||
}
|
||||
}
|
||||
|
||||
function FieldRenderer({
|
||||
field,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
field: FormField;
|
||||
value: string | boolean | string[];
|
||||
onChange: (next: string | boolean | string[]) => void;
|
||||
}): React.JSX.Element | null {
|
||||
const inputId = `tcform-${field.key}`;
|
||||
if (field.type === "honeypot") {
|
||||
return (
|
||||
<input
|
||||
type="text"
|
||||
name={field.key}
|
||||
tabIndex={-1}
|
||||
aria-hidden="true"
|
||||
autoComplete="off"
|
||||
value={typeof value === "string" ? value : ""}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
style={{ position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0 }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const labelEl = (
|
||||
<label htmlFor={inputId} className="tcform-label">
|
||||
{field.label}
|
||||
{field.required ? <span aria-hidden="true"> *</span> : null}
|
||||
</label>
|
||||
);
|
||||
const helpEl = field.helpText ? (
|
||||
<div className="tcform-help" id={`${inputId}-help`}>
|
||||
{field.helpText}
|
||||
</div>
|
||||
) : null;
|
||||
if (field.type === "textarea") {
|
||||
return (
|
||||
<div className="tcform-row">
|
||||
{labelEl}
|
||||
<textarea
|
||||
id={inputId}
|
||||
name={field.key}
|
||||
required={field.required}
|
||||
placeholder={field.placeholder}
|
||||
maxLength={field.maxLength}
|
||||
minLength={field.minLength}
|
||||
aria-describedby={helpEl ? `${inputId}-help` : undefined}
|
||||
value={typeof value === "string" ? value : ""}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
rows={4}
|
||||
/>
|
||||
{helpEl}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (field.type === "select" || field.type === "multiselect") {
|
||||
const options = field.options ?? [];
|
||||
return (
|
||||
<div className="tcform-row">
|
||||
{labelEl}
|
||||
<select
|
||||
id={inputId}
|
||||
name={field.key}
|
||||
required={field.required}
|
||||
multiple={field.type === "multiselect"}
|
||||
value={Array.isArray(value) ? value : typeof value === "string" ? value : ""}
|
||||
onChange={(e) =>
|
||||
onChange(
|
||||
field.type === "multiselect"
|
||||
? Array.from(e.currentTarget.selectedOptions).map((opt) => opt.value)
|
||||
: e.currentTarget.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
{field.type === "select" ? <option value="">{field.placeholder ?? ""}</option> : null}
|
||||
{options.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{helpEl}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (field.type === "boolean") {
|
||||
return (
|
||||
<div className="tcform-row tcform-checkbox">
|
||||
<label className="tcform-label">
|
||||
<input
|
||||
type="checkbox"
|
||||
name={field.key}
|
||||
checked={value === true}
|
||||
onChange={(e) => onChange(e.target.checked)}
|
||||
required={field.required}
|
||||
/>
|
||||
<span>{field.label}</span>
|
||||
</label>
|
||||
{helpEl}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (field.type === "file" || field.type === "photo") {
|
||||
return (
|
||||
<div className="tcform-row">
|
||||
{labelEl}
|
||||
<input
|
||||
id={inputId}
|
||||
type="file"
|
||||
name={field.key}
|
||||
required={field.required}
|
||||
accept={field.type === "photo" ? "image/*" : field.validationRules?.acceptedFileTypes?.join(",")}
|
||||
aria-describedby={helpEl ? `${inputId}-help` : undefined}
|
||||
/>
|
||||
{helpEl}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const inputType =
|
||||
field.type === "email"
|
||||
? "email"
|
||||
: field.type === "number"
|
||||
? "number"
|
||||
: field.type === "date"
|
||||
? "date"
|
||||
: field.type === "time"
|
||||
? "time"
|
||||
: field.type === "phone"
|
||||
? "tel"
|
||||
: "text";
|
||||
return (
|
||||
<div className="tcform-row">
|
||||
{labelEl}
|
||||
<input
|
||||
id={inputId}
|
||||
type={inputType}
|
||||
name={field.key}
|
||||
required={field.required}
|
||||
placeholder={field.placeholder}
|
||||
maxLength={field.maxLength}
|
||||
minLength={field.minLength}
|
||||
aria-describedby={helpEl ? `${inputId}-help` : undefined}
|
||||
value={typeof value === "string" ? value : ""}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
{helpEl}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PublicFormRenderer({ formKey, definition, theme, captcha }: PublicFormRendererProps): React.JSX.Element {
|
||||
const fetcher = useFetcher<{ ok?: boolean; error?: string }>();
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
const [values, setValues] = useState<Record<string, string | boolean | string[]>>(() => {
|
||||
const init: Record<string, string | boolean | string[]> = {};
|
||||
for (const f of definition.fields) {
|
||||
init[f.key] = f.type === "boolean" ? false : f.type === "multiselect" ? [] : "";
|
||||
}
|
||||
return init;
|
||||
});
|
||||
const isSubmitting = fetcher.state !== "idle";
|
||||
const submittedOk = fetcher.data?.ok === true;
|
||||
|
||||
const styleVars = useMemo(() => themeCssVars(theme), [theme]);
|
||||
const idempotencyKey = useMemo(() => {
|
||||
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
return `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === "undefined") return;
|
||||
function emitResize() {
|
||||
const h = containerRef.current?.offsetHeight ?? 0;
|
||||
postToParent({ type: "tcform:resize", height: h, formKey });
|
||||
}
|
||||
emitResize();
|
||||
const observer = typeof ResizeObserver !== "undefined" ? new ResizeObserver(emitResize) : null;
|
||||
if (observer && containerRef.current) observer.observe(containerRef.current);
|
||||
return () => observer?.disconnect();
|
||||
}, [formKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (fetcher.state === "idle" && fetcher.data) {
|
||||
if (fetcher.data.ok) {
|
||||
postToParent({ type: "tcform:submitted", formKey });
|
||||
} else if (fetcher.data.error) {
|
||||
postToParent({ type: "tcform:error", formKey, error: fetcher.data.error });
|
||||
}
|
||||
}
|
||||
}, [fetcher.state, fetcher.data, formKey]);
|
||||
|
||||
function handleSubmit(event: React.FormEvent<HTMLFormElement>): void {
|
||||
event.preventDefault();
|
||||
const formData = new FormData(event.currentTarget);
|
||||
const captchaToken = formData.get("cap-token") ?? formData.get("mcaptcha__token");
|
||||
const visibleFields = filterVisibleFields(definition.fields, values);
|
||||
const visibleValues = Object.fromEntries(
|
||||
visibleFields.map((field) => {
|
||||
if (field.type === "file" || field.type === "photo") {
|
||||
const file = formData.get(field.key);
|
||||
return [field.key, file instanceof File && file.size > 0 ? file.name : ""];
|
||||
}
|
||||
return [field.key, values[field.key]];
|
||||
}),
|
||||
);
|
||||
const submitData = new FormData();
|
||||
submitData.set(
|
||||
"__payload",
|
||||
JSON.stringify({
|
||||
values: visibleValues,
|
||||
gdprAccepted: values.__gdprAccepted === true,
|
||||
captchaToken: typeof captchaToken === "string" ? captchaToken : undefined,
|
||||
idempotencyKey,
|
||||
}),
|
||||
);
|
||||
for (const field of visibleFields) {
|
||||
if (field.type !== "file" && field.type !== "photo") continue;
|
||||
const file = formData.get(field.key);
|
||||
if (file instanceof File && file.size > 0) {
|
||||
submitData.append(field.key, file);
|
||||
}
|
||||
}
|
||||
fetcher.submit(submitData, {
|
||||
method: "post",
|
||||
action: `/api/embed/forms/${encodeURIComponent(formKey)}/submit`,
|
||||
encType: "multipart/form-data",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="tcform-root" style={styleVars}>
|
||||
<style>{`
|
||||
.tcform-root { font-family: var(--tcform-font, system-ui, sans-serif); background: var(--tcform-bg, #fff); color: var(--tcform-text, #111); padding: 16px; box-sizing: border-box; }
|
||||
.tcform-root h1 { font-size: 1.25rem; margin: 0 0 0.25em; }
|
||||
.tcform-root p.tcform-description { margin: 0 0 1em; opacity: 0.8; }
|
||||
.tcform-row { display: block; margin-bottom: 12px; }
|
||||
.tcform-root .tcform-label { display: block; font-weight: 500; margin-bottom: 4px; }
|
||||
.tcform-root input[type=text], .tcform-root input[type=email], .tcform-root input[type=number], .tcform-root textarea, .tcform-root select { width: 100%; padding: 8px 10px; border: 1px solid #ccc; border-radius: var(--tcform-radius, 6px); font: inherit; color: inherit; background: #fff; box-sizing: border-box; }
|
||||
.tcform-root textarea { min-height: 100px; resize: vertical; }
|
||||
.tcform-root .tcform-help { font-size: 0.85em; opacity: 0.7; margin-top: 4px; }
|
||||
.tcform-root button { background: var(--tcform-primary, #2563eb); color: #fff; border: 0; padding: 10px 16px; border-radius: var(--tcform-radius, 6px); cursor: pointer; font: inherit; }
|
||||
.tcform-root button[disabled] { opacity: 0.6; cursor: progress; }
|
||||
.tcform-root .tcform-success { padding: 12px; border-radius: var(--tcform-radius, 6px); background: #ecfdf5; color: #065f46; }
|
||||
.tcform-root .tcform-error { padding: 12px; border-radius: var(--tcform-radius, 6px); background: #fef2f2; color: #991b1b; margin-bottom: 12px; }
|
||||
`}</style>
|
||||
<h1>{definition.title}</h1>
|
||||
{definition.description ? <p className="tcform-description">{definition.description}</p> : null}
|
||||
{submittedOk ? (
|
||||
<div className="tcform-success" role="status">
|
||||
{definition.successMessage}
|
||||
</div>
|
||||
) : (
|
||||
<form onSubmit={handleSubmit} noValidate={false}>
|
||||
{fetcher.data?.error ? (
|
||||
<div className="tcform-error" role="alert">
|
||||
{fetcher.data.error}
|
||||
</div>
|
||||
) : null}
|
||||
{filterVisibleFields(definition.fields, values).map((field) => (
|
||||
<FieldRenderer
|
||||
key={field.key}
|
||||
field={field}
|
||||
value={values[field.key] ?? (field.type === "boolean" ? false : field.type === "multiselect" ? [] : "")}
|
||||
onChange={(next) => setValues((prev) => ({ ...prev, [field.key]: next }))}
|
||||
/>
|
||||
))}
|
||||
<div className="tcform-row tcform-checkbox">
|
||||
<label className="tcform-label">
|
||||
<input
|
||||
type="checkbox"
|
||||
name="__gdprAccepted"
|
||||
checked={values.__gdprAccepted === true}
|
||||
onChange={(e) => setValues((prev) => ({ ...prev, __gdprAccepted: e.target.checked }))}
|
||||
required
|
||||
/>
|
||||
<span>{definition.gdprConsentLabel}</span>
|
||||
</label>
|
||||
</div>
|
||||
<Captcha enabled={captcha.enabled} provider={captcha.provider} instanceUrl={captcha.instanceUrl} sitekey={captcha.sitekey} />
|
||||
<input type="hidden" name="__hp_key" value={HONEYPOT_FIELD_KEY} />
|
||||
<button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting ? "..." : definition.submitLabel}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
import { CatalogError, foundationErrors, requirePermission } from "@hivegrid/foundation";
|
||||
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
|
||||
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
|
||||
export const FORMS_MODULE_KEY = "forms";
|
||||
|
||||
export type FormsRouteContext = {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
permissions: readonly string[];
|
||||
hasModule: boolean;
|
||||
};
|
||||
|
||||
export async function loadFormsContext({
|
||||
request,
|
||||
params,
|
||||
requireModule = false,
|
||||
}: {
|
||||
request: Request;
|
||||
params: Record<string, string | undefined>;
|
||||
requireModule?: boolean;
|
||||
}): Promise<FormsRouteContext> {
|
||||
await requireAuth({ request, params });
|
||||
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
|
||||
if (!tenantId || !userInfo.userId) {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
const [hasModule, permissions] = await Promise.all([
|
||||
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: FORMS_MODULE_KEY }),
|
||||
getPermissionsByUser(userInfo.userId, tenantId),
|
||||
]);
|
||||
if (requireModule && !hasModule) {
|
||||
throw new CatalogError(foundationErrors.notFound, { module: FORMS_MODULE_KEY });
|
||||
}
|
||||
return { tenantId, userId: userInfo.userId, permissions, hasModule };
|
||||
}
|
||||
|
||||
export function requireFormsPermission(ctx: FormsRouteContext, permission: "forms.basic" | "forms.builder" | "forms.publisher" | "forms.admin"): void {
|
||||
requirePermission({ tenantId: ctx.tenantId, userId: ctx.userId, permissions: ctx.permissions }, permission);
|
||||
}
|
||||
|
||||
export function formsOwnerWhere(ctx: FormsRouteContext): { createdByUserId?: string } {
|
||||
return ctx.permissions.includes("forms.admin") ? {} : { createdByUserId: ctx.userId };
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildShkFormTemplateDefinition, SHK_FORM_TEMPLATES } from "./shkFormTemplates.server";
|
||||
|
||||
describe("SHK form templates", () => {
|
||||
it("builds valid localized form definitions for every SHK template", () => {
|
||||
const t = (key: string) => `translated:${key}`;
|
||||
|
||||
const definitions = SHK_FORM_TEMPLATES.map((template) => buildShkFormTemplateDefinition(template, t));
|
||||
|
||||
expect(definitions).toHaveLength(2);
|
||||
expect(definitions[0].title).toBe("SHK Angebotsanfrage");
|
||||
expect(definitions[0].fields.some((field) => field.type === "honeypot")).toBe(true);
|
||||
expect(definitions[0].fields[0]).toEqual(expect.objectContaining({ label: "translated:settings.forms.admin.defaults.fields.fullName" }));
|
||||
expect(definitions[1].title).toBe("SHK Abnahmeprotokoll");
|
||||
expect(definitions[1].fields.some((field) => field.key === "accepted")).toBe(true);
|
||||
});
|
||||
});
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
import { FormDefinitionSchema, HONEYPOT_FIELD_KEY } from "@hivegrid/form-widget";
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
export const SHK_FORM_TEMPLATES = [
|
||||
{
|
||||
name: "SHK Angebotsanfrage",
|
||||
slug: "shk-angebotsanfrage",
|
||||
subtype: "standard",
|
||||
fields: [
|
||||
{ key: "full_name", type: "text", labelKey: "settings.forms.admin.defaults.fields.fullName", required: true },
|
||||
{ key: "email", type: "email", labelKey: "settings.forms.admin.defaults.fields.email", required: true },
|
||||
{ key: "phone", type: "phone", labelKey: "settings.forms.admin.defaults.fields.phone", required: false },
|
||||
{
|
||||
key: "service_type",
|
||||
type: "select",
|
||||
labelKey: "settings.forms.admin.defaults.fields.serviceType",
|
||||
required: true,
|
||||
options: [
|
||||
{ value: "heizung", labelKey: "settings.forms.admin.defaults.options.heating" },
|
||||
{ value: "sanitaer", labelKey: "settings.forms.admin.defaults.options.sanitary" },
|
||||
{ value: "bad", labelKey: "settings.forms.admin.defaults.options.bathroom" },
|
||||
],
|
||||
},
|
||||
{ key: "message", type: "textarea", labelKey: "settings.forms.admin.defaults.fields.description", required: true },
|
||||
{ key: HONEYPOT_FIELD_KEY, type: "honeypot", labelKey: "settings.forms.admin.defaults.fields.honeypot" },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "SHK Abnahmeprotokoll",
|
||||
slug: "shk-abnahmeprotokoll",
|
||||
subtype: "acceptance_form",
|
||||
fields: [
|
||||
{ key: "project_number", type: "text", labelKey: "settings.forms.admin.defaults.fields.projectNumber", required: true },
|
||||
{ key: "customer_name", type: "text", labelKey: "settings.forms.admin.defaults.fields.customerName", required: true },
|
||||
{ key: "accepted", type: "boolean", labelKey: "settings.forms.admin.defaults.fields.accepted", required: true },
|
||||
{ key: "defects", type: "textarea", labelKey: "settings.forms.admin.defaults.fields.defects", required: false },
|
||||
{ key: "photo", type: "photo", labelKey: "settings.forms.admin.defaults.fields.photo", required: false },
|
||||
{ key: HONEYPOT_FIELD_KEY, type: "honeypot", labelKey: "settings.forms.admin.defaults.fields.honeypot" },
|
||||
],
|
||||
},
|
||||
] as const;
|
||||
|
||||
type TemplateField = (typeof SHK_FORM_TEMPLATES)[number]["fields"][number];
|
||||
export type FormTemplateTranslationFn = (key: string) => string;
|
||||
|
||||
function localizeTemplateField(field: TemplateField, t: FormTemplateTranslationFn) {
|
||||
const { labelKey, ...rest } = field;
|
||||
return {
|
||||
...rest,
|
||||
label: t(labelKey),
|
||||
...("options" in field && field.options
|
||||
? { options: field.options.map(({ labelKey: optionLabelKey, ...option }) => ({ ...option, label: t(optionLabelKey) })) }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildShkFormTemplateDefinition(template: (typeof SHK_FORM_TEMPLATES)[number], t: FormTemplateTranslationFn) {
|
||||
return FormDefinitionSchema.parse({
|
||||
title: template.name,
|
||||
submitLabel: t("settings.forms.admin.defaults.submitLabel"),
|
||||
successMessage: t("settings.forms.admin.defaults.successMessage"),
|
||||
gdprConsentLabel: t("settings.forms.admin.defaults.gdprConsentLabel"),
|
||||
fields: template.fields.map((field) => localizeTemplateField(field, t)),
|
||||
});
|
||||
}
|
||||
|
||||
export async function seedShkFormTemplates(input: { tenantId: string; userId: string; t: FormTemplateTranslationFn }): Promise<{ upserted: number }> {
|
||||
let upserted = 0;
|
||||
for (const template of SHK_FORM_TEMPLATES) {
|
||||
const definition = buildShkFormTemplateDefinition(template, input.t);
|
||||
await db.form.upsert({
|
||||
where: { tenantId_slug: { tenantId: input.tenantId, slug: template.slug } },
|
||||
create: {
|
||||
tenantId: input.tenantId,
|
||||
createdByUserId: input.userId,
|
||||
name: template.name,
|
||||
slug: template.slug,
|
||||
subtype: template.subtype,
|
||||
status: "draft",
|
||||
definition: definition as object,
|
||||
allowedOrigins: [],
|
||||
config: { honeypotEnabled: true, captchaEnabled: true } as object,
|
||||
isDemoData: true,
|
||||
},
|
||||
update: {
|
||||
name: template.name,
|
||||
subtype: template.subtype,
|
||||
definition: definition as object,
|
||||
isDemoData: true,
|
||||
},
|
||||
});
|
||||
upserted += 1;
|
||||
}
|
||||
return { upserted };
|
||||
}
|
||||
Reference in new issue
Block a user