Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -0,0 +1,123 @@
import "@testing-library/jest-dom";
import { fireEvent, render, screen } from "@testing-library/react";
import { createRoutesStub } from "react-router";
import { describe, expect, it, vi } from "vitest";
import type { FormDefinition, FormTheme } from "@hivegrid/form-widget";
import type { FormSettingsValue } from "~/modules/formWidget/builder/SettingsTab";
import { FormEditorPage } from "./FormEditorPage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
// The tab bodies have their own concerns (dnd, drawers, previews); the
// shell test focuses on header state, tab routing and the action ops.
vi.mock("./editor/QuestionsTab", () => ({
QuestionsTab: () => <div data-testid="questions-tab" />,
}));
vi.mock("./editor/DesignTab", () => ({
DesignTab: () => <div data-testid="design-tab" />,
}));
vi.mock("./editor/ResponsesTab", () => ({
ResponsesTab: () => <div data-testid="responses-tab" />,
}));
vi.mock("./editor/LeadMappingView", () => ({
LeadMappingView: () => <div data-testid="lead-mapping" />,
}));
vi.mock("~/modules/formWidget/builder/PreviewTab", () => ({
PreviewTab: () => <div data-testid="preview-tab" />,
}));
vi.mock("~/modules/formWidget/builder/SettingsTab", () => ({
SettingsTab: () => <div data-testid="settings-tab" />,
}));
const definition: FormDefinition = {
title: "Contact",
submitLabel: "Submit",
successMessage: "Thanks",
gdprConsentLabel: "I agree",
captchaEnabled: true,
fields: [{ key: "email", type: "email", label: "Email", required: true, conditionalLogic: [], validationRules: {} }],
};
const theme: FormTheme = {};
const settings: FormSettingsValue = {
allowedOrigins: [],
notifyEmails: [],
webhookUrl: "",
targetType: "generic",
fieldMapping: {},
actions: [],
};
function renderEditor(capturedOps: Array<Record<string, unknown>>) {
const Stub = createRoutesStub([
{
path: "/acme/forms/:id",
Component: () => (
<FormEditorPage
form={{ id: "form_1", key: "k1", slug: "contact", status: "draft", isPublic: false, subtype: "standard" }}
initialName="Contact"
initialDefinition={definition}
initialTheme={theme}
initialSettings={settings}
submissions={[]}
columns={[{ key: "email", label: "Email", type: "email" }]}
statusFilter=""
embedScriptBase="https://cdn.example.test"
publicFormUrl="https://app.example.test/f/acme/contact"
csrf="csrf-token"
formatDateTime={(value) => value}
formatNumber={(value) => String(value)}
/>
),
action: async ({ request }) => {
const body = await request.formData();
capturedOps.push(Object.fromEntries(body.entries()));
return { success: "ok" };
},
},
]);
return render(<Stub initialEntries={["/acme/forms/form_1"]} />);
}
describe("FormEditorPage", () => {
it("renders the header with name, draft badge and autosave state", () => {
renderEditor([]);
expect(screen.getByDisplayValue("Contact")).toBeInTheDocument();
expect(screen.getByText("settings.forms.status.draft")).toBeInTheDocument();
expect(screen.getByText("settings.forms.editor.header.autosave.saved")).toBeInTheDocument();
expect(screen.getByTestId("questions-tab")).toBeInTheDocument();
});
it("switches tabs via the ?tab= search param", () => {
renderEditor([]);
fireEvent.click(screen.getByText("settings.forms.editor.tabs.design"));
expect(screen.getByTestId("design-tab")).toBeInTheDocument();
fireEvent.click(screen.getByText("settings.forms.editor.tabs.responses"));
expect(screen.getByTestId("responses-tab")).toBeInTheDocument();
fireEvent.click(screen.getByText("settings.forms.editor.tabs.actions"));
expect(screen.getByTestId("settings-tab")).toBeInTheDocument();
fireEvent.click(screen.getByText("settings.forms.editor.tabs.questions"));
expect(screen.getByTestId("questions-tab")).toBeInTheDocument();
});
// NOTE: fetcher-driven assertions (publish op, debounced autosave POST)
// are intentionally not exercised here: react-router's fetcher.submit
// constructs a `Request` from a jsdom `URLSearchParams`, which trips the
// known local undici realm mismatch (see project memory: "Web-Test
// undici/Node-Version"). The save contract itself is covered by
// forms.$id.action.test.ts against the route action.
it("marks the draft dirty after edits", () => {
renderEditor([]);
fireEvent.change(screen.getByDisplayValue("Contact"), { target: { value: "Contact v2" } });
expect(screen.getByText("settings.forms.editor.header.autosave.unsaved")).toBeInTheDocument();
});
});
@@ -0,0 +1,554 @@
/**
* Subframe form-detail editor (WF-P16, screens S02/S02L/S03/S05 with
* E03/E04/E05 states). Replaces the legacy FormBuilder surface on
* `app.$tenant/forms.$id`.
*
* The route loader/action stay the data source: this screen keeps the
* whole form draft (name/definition/theme/settings) in local state and
* autosaves it (debounced ~1.2s) through the route's existing
* `op=save` contract via useFetcher. Publish/duplicate/delete/rerun
* reuse the other route ops.
*
* The app shell (sidebar) comes from the parent layout — this
* component intentionally renders content only (no DefaultPageLayout).
*/
import { useEffect, useRef, useState } from "react";
import { useFetcher, useLocation, useNavigate, useSearchParams } from "react-router";
import { useTranslation } from "react-i18next";
import { QRCodeSVG } from "qrcode.react";
import {
FeatherAlertCircle,
FeatherCheck,
FeatherClipboardList,
FeatherClock,
FeatherCopy,
FeatherEye,
FeatherInbox,
FeatherLink,
FeatherListChecks,
FeatherMoreHorizontal,
FeatherPalette,
FeatherQrCode,
FeatherRefreshCw,
FeatherTrash2,
FeatherUpload,
FeatherX,
FeatherZap,
} from "@subframe/core";
import * as SubframeCore from "@subframe/core";
import type { FormDefinition, FormTheme } from "@hivegrid/form-widget";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Dialog } from "~/ui/components/Dialog";
import { DropdownMenu } from "~/ui/components/DropdownMenu";
import { IconButton } from "~/ui/components/IconButton";
import { Tabs } from "~/ui/components/Tabs";
import { TextInput } from "~/ui/components/TextInput";
import { FormDialog } from "../shared/FormDialog";
import { SettingsTab, type FormSettingsValue } from "~/modules/formWidget/builder/SettingsTab";
import { PreviewTab } from "~/modules/formWidget/builder/PreviewTab";
import { QuestionsTab } from "./editor/QuestionsTab";
import { LeadMappingView } from "./editor/LeadMappingView";
import { DesignTab } from "./editor/DesignTab";
import { ResponsesTab, type SubmissionColumn, type SubmissionRowVM } from "./editor/ResponsesTab";
import { useCopyToast } from "~/hooks/use-copy-toast";
import { useSaveToast } from "~/hooks/use-save-toast";
export type FormEditorMeta = {
id: string;
key: string;
slug: string | null;
status: string;
isPublic: boolean;
subtype: string;
};
export type FormEditorPageProps = {
form: FormEditorMeta;
initialName: string;
initialDefinition: FormDefinition;
initialTheme: FormTheme;
initialSettings: FormSettingsValue;
submissions: SubmissionRowVM[];
columns: SubmissionColumn[];
statusFilter: string;
embedScriptBase: string;
publicFormUrl: string | null;
csrf: string;
formatDateTime: (value: string) => string;
formatNumber: (value: number) => string;
};
type SaveResult = {
error?: string;
success?: string;
ok?: true;
intent?: string;
messageKey?: string;
duplicatedId?: string;
redirectTo?: string;
};
type EditorTab = "fragen" | "design" | "responses" | "aktionen";
const AUTOSAVE_DELAY_MS = 1200;
export function FormEditorPage({
form,
initialName,
initialDefinition,
initialTheme,
initialSettings,
submissions,
columns,
statusFilter,
embedScriptBase,
publicFormUrl,
csrf,
formatDateTime,
formatNumber,
}: FormEditorPageProps): React.JSX.Element {
const { t } = useTranslation();
const navigate = useNavigate();
const location = useLocation();
const [searchParams, setSearchParams] = useSearchParams();
const copyText = useCopyToast();
const [name, setName] = useState(initialName);
const [definition, setDefinition] = useState<FormDefinition>(initialDefinition);
const [theme, setTheme] = useState<FormTheme>(initialTheme);
const [settings, setSettings] = useState<FormSettingsValue>(initialSettings);
const [leadMappingOpen, setLeadMappingOpen] = useState(false);
const [previewOpen, setPreviewOpen] = useState(false);
const [embedOpen, setEmbedOpen] = useState(false);
// ---- Autosave (debounced) --------------------------------------
const saveFetcher = useFetcher<SaveResult>();
const [revision, setRevision] = useState(0);
const savedRevisionRef = useRef(0);
const inFlightRevisionRef = useRef(0);
const snapshotRef = useRef({ name, definition, theme, settings });
snapshotRef.current = { name, definition, theme, settings };
const submitSaveRef = useRef<() => void>(() => {});
submitSaveRef.current = () => {
const snapshot = snapshotRef.current;
const formData = new FormData();
formData.set("csrf", csrf);
formData.set("op", "save");
formData.set("name", snapshot.name);
formData.set("definition", JSON.stringify(snapshot.definition));
formData.set("theme", JSON.stringify(snapshot.theme));
formData.set("allowedOrigins", snapshot.settings.allowedOrigins.join("\n"));
formData.set("notifyEmails", snapshot.settings.notifyEmails.join("\n"));
formData.set("webhookUrl", snapshot.settings.webhookUrl);
formData.set("targetType", snapshot.settings.targetType);
formData.set("fieldMapping", JSON.stringify(snapshot.settings.fieldMapping));
formData.set("actions", JSON.stringify(snapshot.settings.actions));
saveFetcher.submit(formData, { method: "post" });
};
useEffect(() => {
if (revision === 0 || revision <= savedRevisionRef.current) return;
const timer = setTimeout(() => {
inFlightRevisionRef.current = revision;
submitSaveRef.current();
}, AUTOSAVE_DELAY_MS);
return () => clearTimeout(timer);
}, [revision]);
useEffect(() => {
if (saveFetcher.state === "idle" && saveFetcher.data?.success) {
savedRevisionRef.current = Math.max(savedRevisionRef.current, inFlightRevisionRef.current);
}
}, [saveFetcher.state, saveFetcher.data]);
const touch = () => setRevision((value) => value + 1);
const updateName = (next: string) => {
setName(next);
touch();
};
const updateDefinition = (next: FormDefinition) => {
setDefinition(next);
touch();
};
const updateTheme = (next: FormTheme) => {
setTheme(next);
touch();
};
const updateSettings = (next: FormSettingsValue) => {
setSettings(next);
touch();
};
const saveState: "saving" | "error" | "dirty" | "saved" =
saveFetcher.state !== "idle"
? "saving"
: saveFetcher.data?.error
? "error"
: revision > savedRevisionRef.current
? "dirty"
: "saved";
// ---- Route ops (publish / duplicate / delete) -------------------
const opFetcher = useFetcher<SaveResult>();
useSaveToast(opFetcher.data?.ok ? opFetcher.data : undefined);
function postOp(op: string, extra: Record<string, string> = {}): void {
const formData = new FormData();
formData.set("csrf", csrf);
formData.set("op", op);
for (const [key, value] of Object.entries(extra)) formData.set(key, value);
opFetcher.submit(formData, { method: "post" });
}
const basePath = location.pathname.replace(/\/[^/]+$/u, "");
useEffect(() => {
if (opFetcher.state === "idle" && opFetcher.data?.duplicatedId) {
navigate(`${basePath}/${opFetcher.data.duplicatedId}`);
} else if (opFetcher.state === "idle" && opFetcher.data?.redirectTo) {
navigate(opFetcher.data.redirectTo);
}
}, [opFetcher.state, opFetcher.data, navigate, basePath]);
// Same confirm the list uses — deleting a form takes its responses with it.
const [deleteOpen, setDeleteOpen] = useState(false);
const deleteSubmitting = opFetcher.state !== "idle" && opFetcher.formData?.get("op") === "delete";
function copyPublicLink(): void {
if (publicFormUrl) {
void copyText(publicFormUrl, { successKey: "settings.forms.admin.messages.linkCopied" });
}
}
// ---- Derived view state -----------------------------------------
const isPublished = form.isPublic && form.status === "published";
const tabParam = searchParams.get("tab");
const tab: EditorTab =
tabParam === "design" ? "design" : tabParam === "responses" ? "responses" : tabParam === "aktionen" ? "aktionen" : "fragen";
function setTab(next: EditorTab): void {
setSearchParams(
(prev) => {
const params = new URLSearchParams(prev);
if (next === "fragen") params.delete("tab");
else params.set("tab", next);
return params;
},
{ replace: true },
);
setLeadMappingOpen(false);
}
function openPreview(): void {
if (isPublished && publicFormUrl) {
window.open(publicFormUrl, "_blank", "noreferrer");
return;
}
setPreviewOpen(true);
}
const iframeSnippet = publicFormUrl ? `<iframe src="${publicFormUrl}" width="100%" height="720" style="border:0"></iframe>` : "";
const embedSnippet = `<script src="${embedScriptBase}/embed/widget.js" data-form-key="${form.key}" async></script>`;
const actionError = opFetcher.state === "idle" ? opFetcher.data?.error : undefined;
const saveError = saveState === "error" ? saveFetcher.data?.error : undefined;
// Plain document flow: the app shell's <main> scrolls; an inner h-full/basis-0
// scroll area collapses to 0px inside its block-level wrapper.
return (
<div className="flex w-full flex-col items-start bg-surface-neutral-primary">
{/* Header */}
<div className="flex w-full items-center gap-4 border-b border-solid border-border-default bg-surface-neutral-secondary px-6 py-2.5 mobile:flex-col mobile:items-start mobile:px-4">
<div className="flex grow shrink-0 basis-0 items-center gap-2 min-w-0">
<FeatherClipboardList className="text-heading- font-heading- text-icon-neutral-tertiary" />
<TextInput variant="filled" borderless aria-label={t("settings.forms.admin.detail.formName")}>
<TextInput.Input
className="font-body-large text-text-neutral-primary"
placeholder={t("settings.forms.admin.detail.formName")}
value={name}
onChange={(event: React.ChangeEvent<HTMLInputElement>) => updateName(event.target.value)}
/>
</TextInput>
<BadgeFeedback farbe={isPublished ? "subtle-positive" : "subtle-neutral"}>
{isPublished ? t("settings.forms.status.published") : t("settings.forms.status.draft")}
</BadgeFeedback>
</div>
<div className="flex items-center gap-2 mobile:w-full mobile:flex-none mobile:flex-wrap">
<div className="flex items-center gap-1.5 pr-1">
{saveState === "saving" ? (
<>
<FeatherRefreshCw className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary animate-spin" />
<span className="whitespace-nowrap text-body-extra-small-medium-0 font-body-extra-small-medium-0 text-text-neutral-tertiary">
{t("settings.forms.editor.header.autosave.saving")}
</span>
</>
) : saveState === "error" ? (
<>
<FeatherAlertCircle className="text-body-small-regular-0 font-body-small-regular-0 text-icon-feedback-negative" />
<span className="whitespace-nowrap text-body-extra-small-medium-0 font-body-extra-small-medium-0 text-text-feedback-negative">
{t("settings.forms.editor.header.autosave.error")}
</span>
</>
) : saveState === "dirty" ? (
<>
<FeatherClock className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
<span className="whitespace-nowrap text-body-extra-small-medium-0 font-body-extra-small-medium-0 text-text-neutral-tertiary">
{t("settings.forms.editor.header.autosave.unsaved")}
</span>
</>
) : (
<>
<FeatherCheck className="text-body-small-regular-0 font-body-small-regular-0 text-icon-feedback-positive" />
<span className="whitespace-nowrap text-body-extra-small-medium-0 font-body-extra-small-medium-0 text-text-neutral-tertiary">
{t("settings.forms.editor.header.autosave.saved")}
</span>
</>
)}
</div>
<Button variant="tertiary" size="small" icon={<FeatherEye />} onClick={openPreview}>
{t("settings.forms.builder.tabs.preview")}
</Button>
<Button
size="small"
icon={<FeatherUpload />}
disabled={opFetcher.state !== "idle"}
onClick={() => postOp("publish", { isPublic: isPublished ? "false" : "true" })}
>
{isPublished ? t("settings.forms.admin.detail.unpublish") : t("settings.forms.admin.detail.publish")}
</Button>
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
<IconButton variant="tertiary" size="small" icon={<FeatherMoreHorizontal />} aria-label={t("settings.forms.admin.detail.actions")} />
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="end" sideOffset={4} asChild>
<DropdownMenu>
<DropdownMenu.DropdownItem icon={<FeatherCopy />} onSelect={() => postOp("duplicate")}>
{t("settings.forms.admin.list.actions.duplicate")}
</DropdownMenu.DropdownItem>
{publicFormUrl ? (
<DropdownMenu.DropdownItem icon={<FeatherLink />} onSelect={copyPublicLink}>
{t("settings.forms.admin.list.actions.copyLink")}
</DropdownMenu.DropdownItem>
) : null}
<DropdownMenu.DropdownItem icon={<FeatherQrCode />} onSelect={() => setEmbedOpen(true)}>
{t("settings.forms.editor.header.menu.embed")}
</DropdownMenu.DropdownItem>
<DropdownMenu.DropdownDivider />
<DropdownMenu.DropdownItem className="text-text-feedback-negative" icon={<FeatherTrash2 />} onSelect={() => setDeleteOpen(true)}>
{t("settings.forms.editor.header.menu.delete")}
</DropdownMenu.DropdownItem>
</DropdownMenu>
</SubframeCore.DropdownMenu.Content>
</SubframeCore.DropdownMenu.Portal>
</SubframeCore.DropdownMenu.Root>
</div>
</div>
{/* Error banners (plain-language, dismiss by next action) */}
{saveError ? (
<div className="flex w-full items-center gap-2 border-b border-solid border-border-negative-subtle bg-surface-feedback-subtle-negative px-6 py-2 mobile:px-4">
<FeatherAlertCircle className="text-body-small-regular-0 font-body-small-regular-0 text-icon-feedback-negative" />
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-feedback-negative">{saveError}</span>
</div>
) : null}
{actionError ? (
<div className="flex w-full items-center gap-2 border-b border-solid border-border-negative-subtle bg-surface-feedback-subtle-negative px-6 py-2 mobile:px-4">
<FeatherAlertCircle className="text-body-small-regular-0 font-body-small-regular-0 text-icon-feedback-negative" />
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-feedback-negative">{actionError}</span>
</div>
) : null}
{/* Tab bar */}
<div className="flex w-full items-center justify-center border-b border-solid border-border-default bg-surface-neutral-secondary px-6 overflow-x-auto">
<div className="flex grow shrink-0 basis-0 items-center max-w-[760px]">
<Tabs>
<Tabs.Item active={tab === "fragen"} icon={<FeatherListChecks />} onClick={() => setTab("fragen")}>
{t("settings.forms.editor.tabs.questions")}
</Tabs.Item>
<Tabs.Item active={tab === "design"} icon={<FeatherPalette />} onClick={() => setTab("design")}>
{t("settings.forms.editor.tabs.design")}
</Tabs.Item>
<Tabs.Item active={tab === "responses"} icon={<FeatherInbox />} onClick={() => setTab("responses")}>
{t("settings.forms.editor.tabs.responses")}
</Tabs.Item>
<Tabs.Item active={tab === "aktionen"} icon={<FeatherZap />} onClick={() => setTab("aktionen")}>
{t("settings.forms.editor.tabs.actions")}
</Tabs.Item>
</Tabs>
</div>
</div>
{/* Tab content */}
<div className="flex w-full flex-col items-center bg-surface-neutral-primary self-stretch">
{tab === "fragen" ? (
leadMappingOpen ? (
<LeadMappingView
definition={definition}
settings={settings}
onSettingsChange={updateSettings}
onBack={() => setLeadMappingOpen(false)}
/>
) : (
<QuestionsTab
definition={definition}
settings={settings}
subtype={form.subtype}
onDefinitionChange={updateDefinition}
onSettingsChange={updateSettings}
onOpenLeadMapping={() => setLeadMappingOpen(true)}
/>
)
) : tab === "design" ? (
<DesignTab definition={definition} theme={theme} onDefinitionChange={updateDefinition} onThemeChange={updateTheme} />
) : tab === "aktionen" ? (
// Full post-submit action configuration (all action types, field
// mapping, delivery settings). Persists through the same debounced
// op=save contract as the other tabs — no extra route op.
<div className="w-full max-w-[760px] px-6 py-6 mobile:px-4">
<SettingsTab value={settings} fields={definition.fields} onChange={updateSettings} />
</div>
) : (
<ResponsesTab
submissions={submissions}
columns={columns}
statusFilter={statusFilter}
csrf={csrf}
formatDateTime={formatDateTime}
formatNumber={formatNumber}
onOpenPreview={openPreview}
/>
)}
</div>
{/* Preview dialog (unpublished forms / explicit preview) */}
{previewOpen ? (
<Dialog open onOpenChange={(open: boolean) => (open ? undefined : setPreviewOpen(false))}>
<Dialog.Content className="w-[640px] max-w-full gap-0">
<div className="flex w-full items-center gap-3 border-b border-solid border-border-default px-6 py-4">
<FeatherEye className="text-body-default-regular-0 font-body-default-regular-0 text-icon-neutral-tertiary" />
<span className="grow shrink-0 basis-0 text-body-default-semibold-150 font-body-default-semibold-150 text-text-neutral-primary">
{t("settings.forms.builder.tabs.preview")}
</span>
<IconButton variant="ghost" size="small" icon={<FeatherX />} aria-label={t("shared.close")} onClick={() => setPreviewOpen(false)} />
</div>
<div className="flex w-full flex-col items-start px-6 py-5">
<div className="w-full">
<PreviewTab definition={definition} theme={theme} />
</div>
</div>
</Dialog.Content>
</Dialog>
) : null}
{/* Embed & QR dialog */}
{embedOpen ? (
<Dialog open onOpenChange={(open: boolean) => (open ? undefined : setEmbedOpen(false))}>
<Dialog.Content className="w-[640px] max-w-full gap-0">
<div className="flex w-full items-center gap-3 border-b border-solid border-border-default px-6 py-4">
<FeatherQrCode className="text-body-default-regular-0 font-body-default-regular-0 text-icon-neutral-tertiary" />
<span className="grow shrink-0 basis-0 text-body-default-semibold-150 font-body-default-semibold-150 text-text-neutral-primary">
{t("settings.forms.editor.header.menu.embed")}
</span>
<IconButton variant="ghost" size="small" icon={<FeatherX />} aria-label={t("shared.close")} onClick={() => setEmbedOpen(false)} />
</div>
<div className="flex w-full flex-col items-start gap-5 px-6 py-5">
{publicFormUrl ? (
<>
<div className="flex w-full items-start gap-4 mobile:flex-col">
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-2 min-w-0">
<span className="text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 text-text-neutral-tertiary uppercase tracking-wide">
{t("settings.forms.editor.embed.publicUrl")}
</span>
<a href={publicFormUrl} target="_blank" rel="noreferrer" className="break-all text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-link-default">
{publicFormUrl}
</a>
<Button variant="tertiary" size="small" icon={<FeatherCopy />} onClick={copyPublicLink}>
{t("shared.copy")}
</Button>
</div>
<div className="flex flex-none flex-col items-center gap-2 rounded-md border border-solid border-border-default bg-surface-neutral-primary p-3">
<QRCodeSVG value={publicFormUrl} size={128} />
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t("settings.forms.editor.embed.qr")}
</span>
</div>
</div>
<div className="flex w-full flex-col items-start gap-2">
<span className="text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 text-text-neutral-tertiary uppercase tracking-wide">
{t("settings.forms.editor.embed.iframe")}
</span>
<pre className="w-full overflow-x-auto rounded-md border border-solid border-border-default bg-surface-neutral-tertiary px-3 py-2 text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-secondary">
{iframeSnippet}
</pre>
<Button
variant="tertiary"
size="small"
icon={<FeatherCopy />}
onClick={() => void copyText(iframeSnippet, { successKey: "settings.forms.admin.messages.iframeCopied" })}
>
{t("shared.copy")}
</Button>
</div>
</>
) : (
<div className="flex w-full items-center gap-2 rounded-md border border-solid border-border-warning-subtle bg-surface-feedback-subtle-warning px-3 py-2.5">
<FeatherAlertCircle className="text-body-small-regular-0 font-body-small-regular-0 text-icon-feedback-warning" />
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-feedback-warning">
{t("settings.forms.editor.embed.notPublic")}
</span>
</div>
)}
<div className="flex w-full flex-col items-start gap-2">
<span className="text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 text-text-neutral-tertiary uppercase tracking-wide">
{t("settings.forms.admin.detail.embedSnippet")}
</span>
<pre className="w-full overflow-x-auto rounded-md border border-solid border-border-default bg-surface-neutral-tertiary px-3 py-2 text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-secondary">
{embedSnippet}
</pre>
<Button
variant="tertiary"
size="small"
icon={<FeatherCopy />}
onClick={() => void copyText(embedSnippet, { successKey: "settings.forms.admin.messages.embedCodeCopied" })}
>
{t("shared.copy")}
</Button>
</div>
</div>
</Dialog.Content>
</Dialog>
) : null}
{deleteOpen ? (
<FormDialog
open
onOpenChange={(open: boolean) => (open ? undefined : setDeleteOpen(false))}
size="xs"
uiId="ui.forms.detail.deleteConfirm"
title={t("settings.forms.admin.delete.title")}
footer={
<>
<Button className="mobile:w-full" type="button" variant="tertiary" onClick={() => setDeleteOpen(false)}>
{t("shared.cancel")}
</Button>
<Button
className="mobile:w-full"
variant="destructive"
icon={<FeatherTrash2 />}
loading={deleteSubmitting}
disabled={deleteSubmitting}
onClick={() => postOp("delete")}
data-ui-id="ui.forms.detail.deleteConfirm.submit"
>
{t("shared.delete")}
</Button>
</>
}
>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
{t("settings.forms.admin.delete.body", { name })}
</span>
</FormDialog>
) : null}
</div>
);
}
@@ -0,0 +1,104 @@
import { useState } from "react";
import { Form as RouterForm, Link } from "react-router";
import { useTranslation } from "react-i18next";
import {
FeatherArrowRight,
FeatherBuilding2,
FeatherClipboardList,
FeatherGlobe,
FeatherUserPlus,
} from "@subframe/core";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { IconWithBackground } from "~/ui/components/IconWithBackground";
import { LinkButton } from "~/ui/components/LinkButton";
export type FormNewSubtype = "standard" | "lead" | "survey" | "internal";
export type FormNewPageProps = {
csrf: string;
actionError?: string;
};
const SUBTYPE_CARDS: Array<{ subtype: FormNewSubtype; icon: React.ReactNode; recommended?: boolean }> = [
{ subtype: "standard", icon: <FeatherGlobe /> },
{ subtype: "lead", icon: <FeatherUserPlus />, recommended: true },
{ subtype: "survey", icon: <FeatherClipboardList /> },
{ subtype: "internal", icon: <FeatherBuilding2 /> },
];
export function FormNewPage({ csrf, actionError }: FormNewPageProps): React.JSX.Element {
const { t } = useTranslation();
const [subtype, setSubtype] = useState<FormNewSubtype>("lead");
return (
<div className="flex h-full w-full flex-col items-center bg-surface-neutral-primary overflow-y-auto">
<div className="flex w-full flex-col items-start gap-8 px-6 py-10 max-w-[880px] mobile:gap-6 mobile:px-4 mobile:py-6">
<div className="flex w-full flex-col items-start gap-2">
<h1 className="text-subtitle font-subtitle text-text-neutral-primary mobile:text-heading- mobile:font-heading-">
{t("settings.forms.admin.new.title")}
</h1>
<p className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-tertiary">
{t("settings.forms.admin.new.subtitle")}
</p>
{actionError ? (
<p className="text-body-small-regular-150 font-body-small-regular-150 text-text-feedback-negative">{actionError}</p>
) : null}
</div>
<div className="w-full gap-4 items-stretch grid grid-cols-2 mobile:items-stretch mobile:grid mobile:grid-cols-1">
{SUBTYPE_CARDS.map((card) => {
const selected = subtype === card.subtype;
return (
<button
key={card.subtype}
type="button"
onClick={() => setSubtype(card.subtype)}
aria-pressed={selected}
className={
selected
? "flex flex-col items-start gap-3 rounded-lg border-2 border-solid border-brand-brand-secondary-border-solid-default bg-surface-neutral-secondary px-5 py-5 shadow-sm min-h-[132px] cursor-pointer text-left hover:border-brand-brand-secondary-border-solid-hover"
: "flex flex-col items-start gap-3 rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-5 py-5 min-h-[132px] cursor-pointer text-left hover:border-border-strong"
}
>
<div className="flex w-full items-start gap-3">
<IconWithBackground variant={selected ? "information" : "neutral"} size="large" icon={card.icon} />
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-1">
<div className="flex w-full items-center gap-2">
<span className="grow shrink-0 basis-0 text-body-default-semibold-150 font-body-default-semibold-150 text-text-neutral-primary">
{t(`settings.forms.admin.new.types.${card.subtype}.title`)}
</span>
{card.recommended ? (
<BadgeFeedback farbe="subtle-brand-secondary" size="small">
{t("settings.forms.admin.new.recommended")}
</BadgeFeedback>
) : null}
</div>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t(`settings.forms.admin.new.types.${card.subtype}.description`)}
</span>
</div>
</div>
</button>
);
})}
</div>
<RouterForm
method="post"
className="flex w-full items-center justify-end gap-3 border-t border-solid border-border-default pt-6 mobile:flex-col-reverse mobile:items-stretch"
>
<input type="hidden" name="csrf" value={csrf} readOnly />
<input type="hidden" name="op" value="create" />
<input type="hidden" name="subtype" value={subtype} readOnly />
<Link to=".." className="inline-flex">
<LinkButton type="button" size="small">
{t("shared.cancel")}
</LinkButton>
</Link>
<Button type="submit" className="mobile:w-full" iconRight={<FeatherArrowRight />}>
{t("shared.continue")}
</Button>
</RouterForm>
</div>
</div>
);
}
@@ -0,0 +1,147 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { createMemoryRouter, RouterProvider } from "react-router";
import { describe, expect, it, vi } from "vitest";
import { FormsAdminPage } from "./FormsAdminPage";
import { readRepoFile } from "~/utils/testing/repoPaths";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
describe("FormsAdminPage", () => {
it("keeps the empty-list summary at the bottom-left desktop edge", () => {
const router = createMemoryRouter(
[
{
path: "*",
element: (
<FormsAdminPage
forms={[]}
csrf="csrf"
embedScriptBase="https://app.example.test"
publicPathPrefix="/f/demo"
formatDate={(value) => value}
formatNumber={(value) => String(value)}
/>
),
},
],
{ initialEntries: ["/settings/forms"] },
);
const { container } = render(<RouterProvider router={router} />);
const page = container.firstElementChild;
const summary = screen.getByText("settings.forms.admin.list.summaryEmpty").parentElement;
const content = summary?.parentElement;
const contentRegion = content?.parentElement;
expect(page).toHaveClass("sm:min-h-[calc(100svh-4rem)]");
expect(summary).toHaveClass("sm:mt-auto");
expect(content).toHaveClass("sm:flex-1");
expect(contentRegion).toHaveClass("sm:flex-1");
});
it("submits the template import and exposes its pending state", async () => {
let releaseAction: (() => void) | undefined;
const actionPending = new Promise<void>((resolve) => {
releaseAction = resolve;
});
let submittedOperation: FormDataEntryValue | null = null;
const action = vi.fn(async ({ request }: { request: Request }) => {
submittedOperation = (await request.formData()).get("op");
await actionPending;
return null;
});
const router = createMemoryRouter(
[
{
path: "*",
action,
element: (
<FormsAdminPage
forms={[]}
csrf="csrf"
embedScriptBase="https://app.example.test"
publicPathPrefix="/f/demo"
formatDate={(value) => value}
formatNumber={(value) => String(value)}
/>
),
},
],
{ initialEntries: ["/settings/forms"] },
);
render(<RouterProvider router={router} />);
const templatesButton = screen.getByRole("button", { name: "settings.forms.admin.list.templates" });
fireEvent.click(templatesButton);
await waitFor(() => expect(action).toHaveBeenCalledTimes(1));
expect(submittedOperation).toBe("seed-shk-templates");
expect(templatesButton).toBeDisabled();
await act(async () => releaseAction?.());
await waitFor(() => expect(templatesButton).toBeEnabled());
});
it("deletes through the app's own confirm dialog, not the browser one", () => {
// The row menu lives in a Radix portal that does not open under jsdom's
// pointer events, so the guard is on the source: no window.confirm, and the
// delete op only leaves through the dialog's submit. The dialog itself is
// covered by the FormDialog tests and was walked through in the browser.
const source = readRepoFile("apps/web/app/components/screens/forms/FormsAdminPage.tsx");
expect(source).not.toContain("if (confirm(");
expect(source).not.toContain("window.confirm");
expect(source).toContain("ui.forms.list.deleteConfirm");
expect(source).toContain('data-ui-id="ui.forms.list.deleteConfirm.submit"');
expect(source).toContain('postOp("delete", { id: deleteTarget.id })');
expect(source).toContain("settings.forms.admin.delete.body");
});
it("shows a busy state while the list is being refreshed", async () => {
let releaseRefresh: (() => void) | undefined;
const refreshPending = new Promise<void>((resolve) => {
releaseRefresh = resolve;
});
const loader = vi
.fn<() => Promise<null>>()
.mockResolvedValueOnce(null)
.mockImplementationOnce(async () => {
await refreshPending;
return null;
});
const router = createMemoryRouter(
[
{
path: "*",
loader,
element: (
<FormsAdminPage
forms={[]}
csrf="csrf"
embedScriptBase="https://app.example.test"
publicPathPrefix="/f/demo"
formatDate={(value) => value}
formatNumber={(value) => String(value)}
/>
),
},
],
{ initialEntries: ["/settings/forms"] },
);
render(<RouterProvider router={router} />);
const refreshButton = await screen.findByRole("button", { name: "settings.forms.admin.list.refresh" });
fireEvent.click(refreshButton);
await waitFor(() => expect(loader).toHaveBeenCalledTimes(2));
expect(refreshButton).toBeDisabled();
await act(async () => releaseRefresh?.());
await waitFor(() => expect(refreshButton).toBeEnabled());
});
});
@@ -0,0 +1,700 @@
import { useEffect, useMemo, useState } from "react";
import { Form as RouterForm, Link, useNavigate, useNavigation, useRevalidator, useSubmit } from "react-router";
import { useTranslation } from "react-i18next";
import {
FeatherArrowUpDown,
FeatherClipboardList,
FeatherCopy,
FeatherEye,
FeatherFilter,
FeatherFlame,
FeatherGlobe,
FeatherInbox,
FeatherInfo,
FeatherLayoutTemplate,
FeatherLink,
FeatherLock,
FeatherMoreHorizontal,
FeatherPackage,
FeatherPencil,
FeatherPlus,
FeatherRotateCcw,
FeatherSearchX,
FeatherStar,
FeatherTrash2,
FeatherUpload,
} from "@subframe/core";
import * as SubframeCore from "@subframe/core";
import { FacetFilterBar } from "../shared/FacetFilterBar";
import { DropdownMenuMultiSelect } from "~/ui/components/DropdownMenuMultiSelect";
import { FilterBar } from "~/ui/components/FilterBar";
import { FormDialog } from "../shared/FormDialog";
import { PAGE_HEADER_ICON_CLASS, PageHeader } from "../shared/PageShell";
import { RefreshIconButton } from "../shared/RefreshIconButton";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { DropdownMenu } from "~/ui/components/DropdownMenu";
import { IconButton } from "~/ui/components/IconButton";
import { IconWithBackground } from "~/ui/components/IconWithBackground";
import { Table } from "~/ui/components/Table";
import { Tag_Label } from "~/ui/components/Tag_Label";
import { useCopyToast } from "~/hooks/use-copy-toast";
export type FormsAdminRow = {
id: string;
key: string;
slug: string | null;
name: string;
subtype: string;
status: string;
isEnabled: boolean;
isPublic: boolean;
submissions: number;
createdAt: string;
updatedAt: string;
};
export type FormsAdminPageProps = {
forms: FormsAdminRow[];
csrf: string;
embedScriptBase: string;
/** Path prefix of the public form route, e.g. `/f/acme`. */
publicPathPrefix: string;
actionError?: string;
formatDate: (value: string) => string;
formatNumber: (value: number) => string;
};
type ListStatus = "published" | "draft" | "unpublished";
type StatusFilter = "all" | "notPublished" | ListStatus;
type SubtypeFilter = "all" | "standard" | "lead" | "survey" | "internal";
type SortKey = "updated" | "name" | "submissions" | "created";
function listStatus(form: FormsAdminRow): ListStatus {
if (form.isPublic && form.status === "published") return "published";
if (!form.isEnabled) return "unpublished";
return "draft";
}
export function FormsAdminPage({
forms,
csrf,
embedScriptBase,
publicPathPrefix,
actionError,
formatDate,
formatNumber,
}: FormsAdminPageProps): React.JSX.Element {
const { t } = useTranslation();
const submit = useSubmit();
const navigate = useNavigate();
const navigation = useNavigation();
const revalidator = useRevalidator();
const [query, setQuery] = useState("");
const [statusFilter, setStatusFilter] = useState<StatusFilter>("all");
const [subtypeFilter, setSubtypeFilter] = useState<SubtypeFilter>("all");
const [sortKey, setSortKey] = useState<SortKey>("updated");
// Deleting a form is irreversible, so it asks first — in the app's own dialog,
// not the browser dialog this used to raise.
const [deleteTarget, setDeleteTarget] = useState<FormsAdminRow | null>(null);
const templatesSubmitting = navigation.state !== "idle" && navigation.formData?.get("op") === "seed-shk-templates";
const deleteSubmitting = navigation.state !== "idle" && navigation.formData?.get("op") === "delete";
const refreshing = revalidator.state !== "idle";
const copyText = useCopyToast();
const counts = useMemo(() => {
const byStatus = { published: 0, draft: 0, unpublished: 0 };
const bySubtype: Record<string, number> = { standard: 0, lead: 0, survey: 0, internal: 0 };
for (const form of forms) {
byStatus[listStatus(form)] += 1;
if (form.subtype in bySubtype) bySubtype[form.subtype] += 1;
}
return { byStatus, bySubtype };
}, [forms]);
const visibleForms = useMemo(() => {
const needle = query.trim().toLowerCase();
const filtered = forms.filter((form) => {
const status = listStatus(form);
if (statusFilter === "notPublished" && status === "published") return false;
if (statusFilter !== "all" && statusFilter !== "notPublished" && status !== statusFilter) return false;
if (subtypeFilter !== "all" && form.subtype !== subtypeFilter) return false;
if (needle) {
const haystack = `${form.name} ${form.slug ?? ""} ${form.key}`.toLowerCase();
if (!haystack.includes(needle)) return false;
}
return true;
});
const sorted = [...filtered];
if (sortKey === "name") sorted.sort((a, b) => a.name.localeCompare(b.name));
else if (sortKey === "submissions") sorted.sort((a, b) => b.submissions - a.submissions);
else if (sortKey === "created") sorted.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
else sorted.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
return sorted;
}, [forms, query, statusFilter, subtypeFilter, sortKey]);
const lastUpdatedAt = useMemo(() => {
let latest: string | null = null;
for (const form of forms) {
if (!latest || form.updatedAt > latest) latest = form.updatedAt;
}
return latest;
}, [forms]);
const postOp = (op: string, extra: Record<string, string> = {}) => {
const formData = new FormData();
formData.set("csrf", csrf);
formData.set("op", op);
for (const [key, value] of Object.entries(extra)) formData.set(key, value);
void submit(formData, { method: "post" });
};
// The confirm closes when the row is actually gone. A rejected delete leaves
// it open, next to the error banner that explains why.
useEffect(() => {
if (deleteTarget && !forms.some((form) => form.id === deleteTarget.id)) setDeleteTarget(null);
}, [forms, deleteTarget]);
const publicUrl = (form: FormsAdminRow) => (form.slug ? `${publicPathPrefix}/${form.slug}` : null);
const copyPublicLink = (form: FormsAdminRow) => {
const path = publicUrl(form);
if (!path) return;
const base = typeof window !== "undefined" ? window.location.origin : embedScriptBase;
void copyText(`${base}${path}`, { successKey: "settings.forms.admin.messages.linkCopied" });
};
// Plain document flow: the app shell's <main> scrolls; an inner h-full/basis-0
// scroll area collapses to 0px inside its block-level wrapper.
return (
<div data-ui-id="ui.forms.list" className="flex w-full flex-col items-start bg-surface-neutral-primary sm:min-h-[calc(100svh-4rem)]">
<PageHeader
icon={<FeatherClipboardList className={PAGE_HEADER_ICON_CLASS} />}
title={t("settings.forms.admin.title")}
subtitle={t("settings.forms.admin.description")}
actions={
<>
<RouterForm method="post">
<input type="hidden" name="csrf" value={csrf} readOnly />
<input type="hidden" name="op" value="seed-shk-templates" />
<Button type="submit" variant="secondary" icon={<FeatherLayoutTemplate />} loading={templatesSubmitting} disabled={templatesSubmitting}>
{t("settings.forms.admin.list.templates")}
</Button>
</RouterForm>
<Link to="new" className="mobile:w-full">
<Button type="button" icon={<FeatherPlus />} className="mobile:w-full">
{t("settings.forms.admin.list.newForm")}
</Button>
</Link>
</>
}
/>
{actionError ? (
<div className="flex w-full items-center gap-2 border-b border-solid border-border-negative-subtle bg-surface-feedback-subtle-negative px-6 py-2.5 mobile:px-4">
<FeatherInfo className="text-body-small-regular-0 font-body-small-regular-0 text-icon-feedback-negative" />
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-feedback-negative">{actionError}</span>
</div>
) : null}
{forms.length > 0 ? (
<div className="flex w-full flex-col items-start gap-3 border-b border-solid border-border-default bg-surface-neutral-secondary px-6 py-3 mobile:px-4">
<div className="flex w-full items-center gap-3 mobile:flex-col mobile:items-start">
<span className="w-16 flex-none text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 text-text-neutral-tertiary uppercase tracking-wide">
{t("settings.forms.admin.list.filters.status")}
</span>
<div className="flex flex-wrap items-center gap-2">
<FilterPill
label={t("settings.forms.admin.list.filters.created")}
count={forms.length}
countTone="subtle-neutral"
active={statusFilter === "all"}
onClick={() => setStatusFilter("all")}
/>
<FilterPill
label={t("settings.forms.status.published")}
count={counts.byStatus.published}
countTone="subtle-positive"
active={statusFilter === "published"}
onClick={() => setStatusFilter(statusFilter === "published" ? "all" : "published")}
/>
<FilterPill
label={t("shared.unpublished")}
count={counts.byStatus.draft + counts.byStatus.unpublished}
countTone="subtle-warning"
active={statusFilter === "notPublished"}
onClick={() => setStatusFilter(statusFilter === "notPublished" ? "all" : "notPublished")}
/>
</div>
</div>
<div className="flex w-full items-center gap-3 mobile:flex-col mobile:items-start">
<span className="w-16 flex-none text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 text-text-neutral-tertiary uppercase tracking-wide">
{t("settings.forms.admin.list.filters.type")}
</span>
<div className="flex flex-wrap items-center gap-2">
{(["standard", "lead", "survey", "internal"] as const).map((subtype) => (
<FilterPill
key={subtype}
label={t(`settings.forms.subtype.${subtype}`)}
count={counts.bySubtype[subtype]}
countTone={subtypeCountTone(subtype)}
active={subtypeFilter === subtype}
onClick={() => setSubtypeFilter(subtypeFilter === subtype ? "all" : subtype)}
/>
))}
</div>
</div>
</div>
) : null}
{/* The filter strip every list screen wears (Boards, Pipelines, Projekte):
free-text box, facet dropdowns with chips for what is active, one
reset. Sorting rides along at the right end - it orders the list, it
does not narrow it, so it stays out of the chips. */}
<FacetFilterBar
uiId="ui.forms.list.filter"
facets={[
{
key: "status",
label: t("settings.forms.admin.list.filters.status"),
icon: <FeatherFilter />,
tone: "blue-subtle",
options: [
{ value: "published", label: t("settings.forms.status.published") },
{ value: "draft", label: t("settings.forms.status.draft") },
{ value: "unpublished", label: t("shared.unpublished") },
{ value: "notPublished", label: t("settings.forms.admin.list.statusFilter.notPublished") },
],
selected: new Set(statusFilter === "all" ? [] : [statusFilter]),
},
{
key: "subtype",
label: t("settings.forms.admin.list.filters.type"),
icon: <FeatherPackage />,
tone: "violet-subtle",
options: (["standard", "lead", "survey", "internal"] as const).map((subtype) => ({
value: subtype,
label: t(`settings.forms.subtype.${subtype}`),
})),
selected: new Set(subtypeFilter === "all" ? [] : [subtypeFilter]),
},
]}
onToggle={(facetKey, value) => {
// Single-select facets: picking the active option again clears it,
// which is what the chip's X does too.
if (facetKey === "status") setStatusFilter((current) => (current === value ? "all" : (value as StatusFilter)));
if (facetKey === "subtype") setSubtypeFilter((current) => (current === value ? "all" : (value as SubtypeFilter)));
}}
search={query}
onSearchChange={setQuery}
searchPlaceholder={t("settings.forms.admin.searchPlaceholder")}
onReset={() => {
setQuery("");
setStatusFilter("all");
setSubtypeFilter("all");
}}
labels={{ reset: t("shared.reset"), removeChip: t("settings.members.filters.removeChip") }}
afterFacets={
<FilterBar.StatusFilterButton
icon={<FeatherArrowUpDown />}
label={t(`settings.forms.admin.list.sort.${sortKey}`)}
data-ui-id="ui.forms.list.sort"
dropdown={
<DropdownMenuMultiSelect>
{(["updated", "name", "submissions", "created"] as const).map((key) => (
<DropdownMenuMultiSelect.DropdownItem
key={key}
showCheckbox
selected={sortKey === key}
onClick={() => setSortKey(key)}
data-ui-id={`ui.forms.list.sort.${key}`}
>
{t(`settings.forms.admin.list.sort.${key}`)}
</DropdownMenuMultiSelect.DropdownItem>
))}
</DropdownMenuMultiSelect>
}
/>
}
/>
<div className="flex w-full flex-col items-center self-stretch bg-surface-neutral-primary sm:flex-1">
<div className="flex w-full flex-col items-start gap-4 px-6 py-6 mobile:px-4 sm:flex-1">
<div className="flex w-full items-center gap-2">
<span className="grow shrink-0 basis-0 text-body-small-semibold-150 font-body-small-semibold-150 text-text-neutral-primary">
{t("settings.forms.admin.list.count", { count: visibleForms.length, formattedCount: formatNumber(visibleForms.length) })}
</span>
<RefreshIconButton
busy={refreshing}
onRefresh={() => void revalidator.revalidate()}
label={t("settings.forms.admin.list.refresh")}
dataUiId="ui.forms.admin.list.refresh"
/>
</div>
{forms.length === 0 ? (
<div className="flex w-full flex-col items-center justify-center px-6 py-12 mobile:px-4 mobile:py-8">
<div className="flex w-full flex-col items-center gap-6 max-w-[420px]">
<IconWithBackground variant="neutral" size="large" icon={<FeatherClipboardList />} />
<div className="flex w-full flex-col items-center gap-2">
<span className="w-full text-heading- font-heading- text-text-neutral-primary text-center">
{t("settings.forms.admin.list.empty.title")}
</span>
<span className="w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary text-center">
{t("settings.forms.admin.list.empty.body")}
</span>
</div>
<div className="flex items-center gap-2 mobile:w-full mobile:flex-none mobile:flex-col">
<Link to="new" className="mobile:w-full">
<Button type="button" className="mobile:w-full" icon={<FeatherPlus />}>
{t("settings.forms.admin.list.newForm")}
</Button>
</Link>
<RouterForm method="post" className="mobile:w-full">
<input type="hidden" name="csrf" value={csrf} readOnly />
<input type="hidden" name="op" value="seed-shk-templates" />
<Button
type="submit"
className="mobile:w-full"
variant="tertiary"
icon={<FeatherLayoutTemplate />}
loading={templatesSubmitting}
disabled={templatesSubmitting}
>
{t("settings.forms.admin.list.empty.viewTemplates")}
</Button>
</RouterForm>
</div>
</div>
</div>
) : visibleForms.length === 0 ? (
<div className="flex w-full flex-col items-center justify-center gap-6 rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-6 py-16 shadow-sm mobile:py-10">
<div className="flex h-14 w-14 flex-none flex-col items-center justify-center rounded-round border border-solid border-border-default bg-surface-neutral-tertiary">
<FeatherSearchX className="text-heading- font-heading- text-icon-neutral-tertiary" />
</div>
<div className="flex w-full flex-col items-center gap-2 max-w-[420px]">
<span className="text-body-large font-body-large text-text-neutral-primary text-center">
{t("settings.forms.admin.list.noMatches.title")}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary text-center">
{t("settings.forms.admin.list.noMatches.body")}
</span>
</div>
<div className="flex items-center gap-2 mobile:w-full mobile:flex-none mobile:flex-col">
<Button
type="button"
className="mobile:w-full"
icon={<FeatherRotateCcw />}
onClick={() => {
setQuery("");
setStatusFilter("all");
setSubtypeFilter("all");
}}
>
{t("settings.forms.admin.list.noMatches.resetFilters")}
</Button>
<Link to="new" className="mobile:w-full">
<Button type="button" className="mobile:w-full" variant="secondary" icon={<FeatherPlus />}>
{t("settings.forms.admin.list.newForm")}
</Button>
</Link>
</div>
</div>
) : (
<div className="flex w-full flex-col items-start overflow-hidden rounded-lg border border-solid border-border-default shadow-sm overflow-x-auto">
<Table
header={
<Table.HeaderRow>
<Table.HeaderCell>{t("settings.forms.admin.list.columns.form")}</Table.HeaderCell>
<Table.HeaderCell>{t("settings.forms.admin.list.columns.type")}</Table.HeaderCell>
<Table.HeaderCell>{t("settings.forms.admin.existing.status")}</Table.HeaderCell>
<Table.HeaderCell>{t("settings.forms.admin.list.columns.submissions")}</Table.HeaderCell>
<Table.HeaderCell>{t("settings.forms.admin.list.columns.lastChanged")}</Table.HeaderCell>
<Table.HeaderCell>{t("settings.forms.admin.list.columns.link")}</Table.HeaderCell>
<Table.HeaderCell>{t("settings.forms.admin.detail.actions")}</Table.HeaderCell>
</Table.HeaderRow>
}
>
{visibleForms.map((form) => {
const status = listStatus(form);
const url = publicUrl(form);
const SubtypeIcon = subtypeIcon(form.subtype);
return (
<Table.Row key={form.id} clickable>
<Table.Cell>
<div className="flex items-center gap-3">
<div className="flex h-8 w-8 flex-none flex-col items-center justify-center rounded-md border border-solid border-border-default bg-surface-neutral-tertiary">
<SubtypeIcon className="text-body-default-regular-0 font-body-default-regular-0 text-icon-neutral-tertiary" />
</div>
<div className="flex flex-col items-start">
<Link
to={form.id}
className="whitespace-nowrap text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-primary hover:text-text-feedback-link-default"
>
{form.name}
</Link>
<span className="whitespace-nowrap text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t("settings.forms.admin.existing.key")}: {form.key}
</span>
</div>
</div>
</Table.Cell>
<Table.Cell>
<Tag_Label tone={formSubtypeTone(form.subtype)} noAction size="small">
{t(`settings.forms.subtype.${normalizedSubtype(form.subtype)}`)}
</Tag_Label>
</Table.Cell>
<Table.Cell>
<StatusBadge status={status} />
</Table.Cell>
<Table.Cell>
<span className="whitespace-nowrap text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{formatNumber(form.submissions)}
</span>
</Table.Cell>
<Table.Cell>
<span className="whitespace-nowrap text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{formatDate(form.updatedAt)}
</span>
</Table.Cell>
<Table.Cell>
{form.subtype === "internal" ? (
<div className="flex items-center gap-1.5">
<FeatherLock className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-subtle" />
<span className="whitespace-nowrap text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-subtle">
{t("settings.forms.admin.list.internalOnly")}
</span>
</div>
) : status === "published" && url ? (
<div className="flex items-center gap-1.5">
<FeatherLink className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
<a
href={url}
target="_blank"
rel="noreferrer"
className="whitespace-nowrap text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-link-default"
>
/f/{form.slug}
</a>
</div>
) : (
<span className="whitespace-nowrap text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-subtle">
{t("settings.forms.admin.list.noLink")}
</span>
)}
</Table.Cell>
<Table.Cell>
<div className="flex w-full items-center justify-end gap-1">
<Link to={form.id} className="inline-flex">
<Button type="button" variant="tertiary" size="small" icon={<FeatherPencil />}>
{t("settings.forms.admin.list.actions.edit")}
</Button>
</Link>
{url && status === "published" ? (
<a href={url} target="_blank" rel="noreferrer" className="inline-flex">
<IconButton variant="ghost" size="small" icon={<FeatherEye />} />
</a>
) : null}
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
<IconButton
variant="ghost"
size="small"
icon={<FeatherMoreHorizontal />}
aria-label={`${t("shared.actions")}: ${form.name}`}
data-ui-id="ui.forms.list.rowMenu"
/>
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="end" sideOffset={4} asChild>
<DropdownMenu>
{status !== "published" ? (
<DropdownMenu.DropdownItem
icon={<FeatherUpload />}
onSelect={() => postOp("publish", { id: form.id, isPublic: "true" })}
>
{t("settings.forms.admin.detail.publish")}
</DropdownMenu.DropdownItem>
) : null}
<DropdownMenu.DropdownItem icon={<FeatherCopy />} onSelect={() => postOp("duplicate", { id: form.id })}>
{t("settings.forms.admin.list.actions.duplicate")}
</DropdownMenu.DropdownItem>
{status === "published" && url ? (
<DropdownMenu.DropdownItem icon={<FeatherLink />} onSelect={() => copyPublicLink(form)}>
{t("settings.forms.admin.list.actions.copyLink")}
</DropdownMenu.DropdownItem>
) : null}
<DropdownMenu.DropdownItem
icon={<FeatherInbox />}
onSelect={() => navigate(`${form.id}?tab=responses`)}
>
{t("settings.forms.admin.list.actions.viewResponses")}
</DropdownMenu.DropdownItem>
<DropdownMenu.DropdownDivider />
<DropdownMenu.DropdownItem
className="text-text-feedback-negative"
icon={<FeatherTrash2 />}
onSelect={() => setDeleteTarget(form)}
>
{t("settings.forms.admin.list.actions.delete")}
</DropdownMenu.DropdownItem>
</DropdownMenu>
</SubframeCore.DropdownMenu.Content>
</SubframeCore.DropdownMenu.Portal>
</SubframeCore.DropdownMenu.Root>
</div>
</Table.Cell>
</Table.Row>
);
})}
</Table>
</div>
)}
<div className="flex w-full items-center gap-3 sm:mt-auto">
<FeatherInfo className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
<span className="grow shrink-0 basis-0 text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{forms.length === 0
? t("settings.forms.admin.list.summaryEmpty")
: visibleForms.length === 0
? t("settings.forms.admin.list.summaryFiltered", {
shown: formatNumber(0),
total: formatNumber(forms.length),
})
: lastUpdatedAt
? t("settings.forms.admin.list.summaryWithDate", {
shown: formatNumber(visibleForms.length),
total: formatNumber(forms.length),
date: formatDate(lastUpdatedAt),
})
: t("settings.forms.admin.list.summary", {
shown: formatNumber(visibleForms.length),
total: formatNumber(forms.length),
})}
</span>
</div>
</div>
</div>
{deleteTarget ? (
<FormDialog
open
onOpenChange={(open: boolean) => (open ? undefined : setDeleteTarget(null))}
size="xs"
uiId="ui.forms.list.deleteConfirm"
title={t("settings.forms.admin.delete.title")}
footer={
<>
<Button className="mobile:w-full" type="button" variant="tertiary" onClick={() => setDeleteTarget(null)}>
{t("shared.cancel")}
</Button>
<Button
className="mobile:w-full"
variant="destructive"
icon={<FeatherTrash2 />}
loading={deleteSubmitting}
disabled={deleteSubmitting}
onClick={() => postOp("delete", { id: deleteTarget.id })}
data-ui-id="ui.forms.list.deleteConfirm.submit"
>
{t("shared.delete")}
</Button>
</>
}
>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
{t("settings.forms.admin.delete.body", { name: deleteTarget.name })}
</span>
</FormDialog>
) : null}
</div>
);
}
function FilterPill({
label,
count,
active = false,
countTone = "subtle-neutral",
onClick,
}: {
label: string;
count: number;
active?: boolean;
countTone?: React.ComponentProps<typeof BadgeFeedback>["farbe"];
onClick?: () => void;
}) {
return (
<button
type="button"
onClick={onClick}
className={
active
? "flex items-center gap-1.5 rounded-md border border-solid border-brand-brand-border-solid-default bg-brand-brand-secondary-surface-subtle px-3 py-1.5"
: "flex items-center gap-1.5 rounded-md border border-solid border-border-default bg-surface-neutral-primary px-3 py-1.5 hover:bg-surface-neutral-tertiary"
}
>
<span
className={
active
? "text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary"
: "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary"
}
>
{label}
</span>
<BadgeFeedback farbe={countTone} size="small">
{count}
</BadgeFeedback>
</button>
);
}
function StatusBadge({ status }: { status: ListStatus }) {
const { t } = useTranslation();
if (status === "published") {
return (
<BadgeFeedback farbe="subtle-positive" size="small">
{t("settings.forms.status.published")}
</BadgeFeedback>
);
}
if (status === "draft") {
return (
<BadgeFeedback farbe="subtle-neutral" size="small">
{t("settings.forms.status.draft")}
</BadgeFeedback>
);
}
return (
<BadgeFeedback farbe="subtle-warning" size="small">
{t("shared.unpublished")}
</BadgeFeedback>
);
}
const KNOWN_SUBTYPES = ["standard", "lead", "survey", "internal", "acceptance_form", "onboarding", "booking_intake", "hr_request"] as const;
function normalizedSubtype(subtype: string): (typeof KNOWN_SUBTYPES)[number] {
return (KNOWN_SUBTYPES as readonly string[]).includes(subtype) ? (subtype as (typeof KNOWN_SUBTYPES)[number]) : "standard";
}
function subtypeIcon(subtype: string): React.ComponentType<{ className?: string }> {
if (subtype === "lead") return FeatherFlame;
if (subtype === "survey") return FeatherStar;
if (subtype === "internal") return FeatherPackage;
return FeatherGlobe;
}
function subtypeCountTone(subtype: string): React.ComponentProps<typeof BadgeFeedback>["farbe"] {
if (subtype === "standard") return "subtle-information";
if (subtype === "lead") return "subtle-brand-secondary";
return "subtle-neutral";
}
function formSubtypeTone(subtype: string): React.ComponentProps<typeof Tag_Label>["tone"] {
if (subtype === "lead") return "violet-subtle";
if (subtype === "survey") return "teal-subtle";
if (subtype === "internal") return "sand-subtle";
return "blue-subtle";
}
@@ -0,0 +1,269 @@
/**
* S03 "Design" tab of the Subframe form editor (WF-P16).
*
* Maps directly onto the backend FormTheme (primaryColor,
* backgroundColor, fontFamily, borderRadius) and the definition copy
* fields (submitLabel, gdprConsentLabel, successMessage,
* captchaEnabled). The S03 mock's logo upload and form-width controls
* have no backend counterpart and are intentionally omitted.
*
* The live preview reuses the PreviewTab renderer so what the operator
* sees matches the embedded/public form (same tcform CSS variables).
*/
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherEye, FeatherMonitor, FeatherMousePointerClick, FeatherType } from "@subframe/core";
import type { FormDefinition, FormTheme } from "@hivegrid/form-widget";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Select } from "~/ui/components/Select";
import { Switch } from "~/ui/components/Switch";
import { TextArea } from "~/ui/components/TextArea";
import { TextInput } from "~/ui/components/TextInput";
import { PreviewTab } from "~/modules/formWidget/builder/PreviewTab";
const ACCENT_COLORS = ["#2563eb", "#0891b2", "#16a34a", "#f59e0b", "#dc2626", "#7c3aed"] as const;
const TINTED_BACKGROUND = "#f6f7f9";
const HEX_PATTERN = /^#[0-9a-fA-F]{3,8}$/u;
const FONT_OPTIONS = [
{ value: "system", stack: undefined, labelKey: "settings.forms.editor.design.appearance.fontSystem" },
{ value: "inter", stack: "Inter, system-ui, sans-serif", labelKey: "settings.forms.editor.design.appearance.fontInter" },
{ value: "roboto", stack: "Roboto, Helvetica, Arial, sans-serif", labelKey: "settings.forms.editor.design.appearance.fontRoboto" },
{ value: "serif", stack: "Georgia, 'Times New Roman', serif", labelKey: "settings.forms.editor.design.appearance.fontSerif" },
] as const;
const RADIUS_OPTIONS = [
{ value: "square", radius: "0px", labelKey: "settings.forms.editor.design.appearance.radiusSquare" },
{ value: "default", radius: undefined, labelKey: "settings.forms.editor.design.appearance.radiusDefault" },
{ value: "rounded", radius: "12px", labelKey: "settings.forms.editor.design.appearance.radiusRounded" },
] as const;
function fontValue(theme: FormTheme): string {
if (!theme.fontFamily) return "system";
if (theme.fontFamily.includes("Inter")) return "inter";
if (theme.fontFamily.includes("Roboto")) return "roboto";
if (theme.fontFamily.toLowerCase().includes("serif") || theme.fontFamily.includes("Georgia")) return "serif";
return "system";
}
function radiusValue(theme: FormTheme): string {
if (theme.borderRadius === "0px") return "square";
if (theme.borderRadius === "12px") return "rounded";
return "default";
}
export type DesignTabProps = {
definition: FormDefinition;
theme: FormTheme;
onDefinitionChange: (next: FormDefinition) => void;
onThemeChange: (next: FormTheme) => void;
};
export function DesignTab({ definition, theme, onDefinitionChange, onThemeChange }: DesignTabProps): React.JSX.Element {
const { t } = useTranslation();
const [customHex, setCustomHex] = useState("");
const activeColor = theme.primaryColor?.toLowerCase() ?? null;
function setPrimaryColor(color: string | undefined): void {
const next = { ...theme };
if (color) next.primaryColor = color;
else delete next.primaryColor;
onThemeChange(next);
}
return (
<div className="flex w-full flex-col items-start gap-6 px-8 py-8 max-w-[1080px] mobile:px-4 mobile:py-6">
<div className="flex w-full flex-col items-start gap-1">
<span className="text-subtitle font-subtitle text-text-neutral-primary mobile:text-heading- mobile:font-heading-">
{t("settings.forms.editor.design.title")}
</span>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-tertiary">
{t("settings.forms.editor.design.description")}
</span>
</div>
<div className="flex w-full items-start gap-8 mobile:flex-col mobile:gap-6">
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-6 min-w-0">
{/* Accent color */}
<div className="flex w-full flex-col items-start gap-4 rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-5 py-5 shadow-sm">
<span className="text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 text-text-neutral-tertiary uppercase tracking-wide">
{t("settings.forms.editor.design.accent.title")}
</span>
<div className="flex w-full flex-wrap items-center gap-3">
{ACCENT_COLORS.map((color) => (
<button
key={color}
type="button"
aria-label={color}
aria-pressed={activeColor === color}
style={{ backgroundColor: color }}
onClick={() => setPrimaryColor(activeColor === color ? undefined : color)}
className={
activeColor === color
? "flex h-9 w-9 flex-none flex-col items-center justify-center rounded-round ring-2 ring-brand-brand-border-solid-default ring-offset-2 cursor-pointer"
: "flex h-9 w-9 flex-none flex-col items-center justify-center rounded-round cursor-pointer"
}
/>
))}
<TextInput className="h-auto w-40 flex-none" size="small" aria-label={t("settings.forms.editor.design.accent.custom")}>
<TextInput.Input
variant="small"
placeholder={t("settings.forms.editor.design.accent.customPlaceholder")}
value={customHex}
onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
const raw = event.target.value.trim();
setCustomHex(raw);
if (HEX_PATTERN.test(raw)) setPrimaryColor(raw);
}}
/>
</TextInput>
</div>
</div>
{/* Appearance */}
<div className="flex w-full flex-col items-start gap-4 rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-5 py-5 shadow-sm">
<span className="text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 text-text-neutral-tertiary uppercase tracking-wide">
{t("settings.forms.editor.design.appearance.title")}
</span>
<div className="flex w-full items-start gap-4 mobile:flex-col">
<Select
className="h-auto grow shrink-0 basis-0"
variant="outline"
label={t("settings.forms.editor.design.appearance.font")}
icon={<FeatherType />}
value={fontValue(theme)}
onValueChange={(value: string) => {
const option = FONT_OPTIONS.find((entry) => entry.value === value);
const next = { ...theme };
if (option?.stack) next.fontFamily = option.stack;
else delete next.fontFamily;
onThemeChange(next);
}}
>
{FONT_OPTIONS.map((option) => (
<Select.Item key={option.value} value={option.value}>
{t(option.labelKey)}
</Select.Item>
))}
</Select>
<Select
className="h-auto grow shrink-0 basis-0"
variant="outline"
label={t("settings.forms.editor.design.appearance.radius")}
value={radiusValue(theme)}
onValueChange={(value: string) => {
const option = RADIUS_OPTIONS.find((entry) => entry.value === value);
const next = { ...theme };
if (option?.radius) next.borderRadius = option.radius;
else delete next.borderRadius;
onThemeChange(next);
}}
>
{RADIUS_OPTIONS.map((option) => (
<Select.Item key={option.value} value={option.value}>
{t(option.labelKey)}
</Select.Item>
))}
</Select>
</div>
<div className="flex w-full items-center justify-between rounded-md border border-solid border-border-default bg-surface-neutral-primary px-3 py-2.5">
<div className="flex flex-col items-start">
<span className="text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-primary">
{t("settings.forms.editor.design.appearance.tinted.title")}
</span>
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t("settings.forms.editor.design.appearance.tinted.description")}
</span>
</div>
<Switch
checked={!!theme.backgroundColor}
onCheckedChange={(checked: boolean) => {
const next = { ...theme };
if (checked) next.backgroundColor = TINTED_BACKGROUND;
else delete next.backgroundColor;
onThemeChange(next);
}}
/>
</div>
</div>
{/* Content */}
<div className="flex w-full flex-col items-start gap-4 rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-5 py-5 shadow-sm">
<span className="text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 text-text-neutral-tertiary uppercase tracking-wide">
{t("settings.forms.editor.design.content.title")}
</span>
<TextInput
className="h-auto w-full flex-none"
fillContainer
showLabel
label={t("settings.forms.editor.design.content.submitLabel")}
icon={<FeatherMousePointerClick />}
>
<TextInput.Input
placeholder={t("settings.forms.editor.design.content.submitLabelPlaceholder")}
value={definition.submitLabel}
onChange={(event: React.ChangeEvent<HTMLInputElement>) => onDefinitionChange({ ...definition, submitLabel: event.target.value })}
/>
</TextInput>
<TextArea
className="h-auto w-full flex-none"
showLabel
label={t("settings.forms.editor.design.content.gdpr")}
helpText={t("settings.forms.editor.design.content.gdprHelp")}
>
<TextArea.Input
className="min-h-[72px]"
value={definition.gdprConsentLabel}
onChange={(event: React.ChangeEvent<HTMLTextAreaElement>) => onDefinitionChange({ ...definition, gdprConsentLabel: event.target.value })}
/>
</TextArea>
<TextArea className="h-auto w-full flex-none" showLabel label={t("settings.forms.editor.design.content.successMessage")}>
<TextArea.Input
className="min-h-[72px]"
value={definition.successMessage}
onChange={(event: React.ChangeEvent<HTMLTextAreaElement>) => onDefinitionChange({ ...definition, successMessage: event.target.value })}
/>
</TextArea>
<div className="flex w-full items-center justify-between rounded-md border border-solid border-border-default bg-surface-neutral-primary px-3 py-2.5">
<div className="flex flex-col items-start">
<span className="text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-primary">
{t("settings.forms.editor.design.content.captcha.title")}
</span>
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t("settings.forms.editor.design.content.captcha.description")}
</span>
</div>
<Switch
checked={definition.captchaEnabled}
onCheckedChange={(checked: boolean) => onDefinitionChange({ ...definition, captchaEnabled: checked })}
/>
</div>
</div>
</div>
{/* Live preview (customer view) */}
<div className="flex flex-col items-start gap-3 w-[480px] sticky top-4 mobile:w-full mobile:flex-none">
<div className="flex w-full items-center gap-2">
<FeatherEye className="text-body-default-regular-0 font-body-default-regular-0 text-icon-neutral-tertiary" />
<span className="grow shrink-0 basis-0 text-body-small-semibold-150 font-body-small-semibold-150 text-text-neutral-primary">
{t("settings.forms.editor.design.preview.title")}
</span>
<BadgeFeedback farbe="subtle-neutral" size="small">
{t("settings.forms.editor.design.preview.badge")}
</BadgeFeedback>
</div>
<div className="flex w-full flex-col items-center gap-4 rounded-lg border border-solid border-border-default bg-surface-neutral-tertiary px-6 py-6 shadow-sm mobile:px-4">
<div className="w-full">
<PreviewTab definition={definition} theme={theme} />
</div>
<div className="flex w-full items-center justify-center gap-2">
<FeatherMonitor className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t("settings.forms.editor.design.preview.hint")}
</span>
</div>
</div>
</div>
</div>
</div>
);
}
@@ -0,0 +1,311 @@
/**
* S02L "Lead Felder zuweisen" sub-view of the Fragen tab (WF-P16).
*
* Maps form questions onto the lead targets the create_lead worker
* supports (vorname, nachname, email, telefon, message — source is set
* automatically). Saving writes `{ formFieldKey: leadTargetKey }` into
* the create_lead FormAction and hands control back to the questions
* view; persistence flows through the parent's autosave.
*/
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import {
FeatherAlertCircle,
FeatherAlignLeft,
FeatherArrowLeft,
FeatherArrowLeftRight,
FeatherArrowRight,
FeatherAtSign,
FeatherCheck,
FeatherGlobe,
FeatherLock,
FeatherPhone,
FeatherUser,
FeatherUserPlus,
FeatherWand2,
} from "@subframe/core";
import type { FormDefinition, FormField } from "@hivegrid/form-widget";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Select } from "~/ui/components/Select";
import { Switch } from "~/ui/components/Switch";
import type { FormSettingsValue } from "~/modules/formWidget/builder/SettingsTab";
import { findLeadAction, LEAD_TARGET_KEYS, type LeadTargetKey } from "./fieldMeta";
const NONE_VALUE = "__none";
const TARGET_ICONS: Record<LeadTargetKey, React.ComponentType<{ className?: string }>> = {
vorname: FeatherUser,
nachname: FeatherUser,
email: FeatherAtSign,
telefon: FeatherPhone,
message: FeatherAlignLeft,
};
export type LeadMappingViewProps = {
definition: FormDefinition;
settings: FormSettingsValue;
onSettingsChange: (next: FormSettingsValue) => void;
onBack: () => void;
};
function initialMapping(settings: FormSettingsValue): Record<LeadTargetKey, string> {
const mapping: Record<LeadTargetKey, string> = { vorname: "", nachname: "", email: "", telefon: "", message: "" };
const action = findLeadAction(settings.actions);
if (action) {
for (const [formKey, target] of Object.entries(action.fieldMapping)) {
if ((LEAD_TARGET_KEYS as readonly string[]).includes(target)) {
mapping[target as LeadTargetKey] = formKey;
}
}
}
return mapping;
}
export function LeadMappingView({ definition, settings, onSettingsChange, onBack }: LeadMappingViewProps): React.JSX.Element {
const { t } = useTranslation();
const [mapping, setMapping] = useState<Record<LeadTargetKey, string>>(() => initialMapping(settings));
const leadAction = findLeadAction(settings.actions);
const leadEnabled = leadAction?.enabled === true;
const visibleFields = useMemo(() => definition.fields.filter((field) => field.type !== "honeypot"), [definition.fields]);
const missingContact = !mapping.email && !mapping.telefon;
function assign(target: LeadTargetKey, formKey: string): void {
setMapping((prev) => {
const next = { ...prev };
if (formKey) {
// A question can feed only one lead target — clear other usages.
for (const key of LEAD_TARGET_KEYS) {
if (next[key] === formKey) next[key] = "";
}
}
next[target] = formKey;
return next;
});
}
function autoAssign(): void {
setMapping((prev) => {
const next = { ...prev };
const taken = () => new Set(Object.values(next).filter(Boolean));
const emailField = visibleFields.find((field) => field.type === "email");
if (emailField) next.email = emailField.key;
const phoneField = visibleFields.find((field) => field.type === "phone");
if (phoneField) next.telefon = phoneField.key;
const textFields = visibleFields.filter((field) => field.type === "text");
const matches = (field: FormField, pattern: RegExp) => pattern.test(`${field.key} ${field.label}`);
const vorname = textFields.find((field) => matches(field, /vor|first/i) && !taken().has(field.key));
if (vorname) next.vorname = vorname.key;
const nachname = textFields.find((field) => matches(field, /nach|last|name/i) && !taken().has(field.key));
if (nachname) next.nachname = nachname.key;
const messageField = visibleFields.find((field) => field.type === "textarea" && !taken().has(field.key));
if (messageField) next.message = messageField.key;
return next;
});
}
function toggleLeadEnabled(checked: boolean): void {
if (leadAction) {
onSettingsChange({
...settings,
actions: settings.actions.map((action) => (action === leadAction ? { ...action, enabled: checked } : action)),
});
return;
}
if (checked) {
onSettingsChange({
...settings,
actions: [
...settings.actions,
{ actionType: "create_lead", name: t("settings.forms.admin.defaults.leadActionName"), enabled: true, fieldMapping: {}, actionConfig: {} },
],
});
}
}
function save(): void {
const fieldMapping: Record<string, string> = {};
for (const target of LEAD_TARGET_KEYS) {
if (mapping[target]) fieldMapping[mapping[target]] = target;
}
if (leadAction) {
onSettingsChange({
...settings,
actions: settings.actions.map((action) => (action === leadAction ? { ...action, fieldMapping } : action)),
});
} else {
onSettingsChange({
...settings,
actions: [
...settings.actions,
{ actionType: "create_lead", name: t("settings.forms.admin.defaults.leadActionName"), enabled: true, fieldMapping, actionConfig: {} },
],
});
}
onBack();
}
return (
<div className="flex w-full flex-col items-start gap-4 px-6 py-6 max-w-[820px] mobile:px-4">
{/* Lead banner */}
<div className="flex w-full items-center gap-3 rounded-md border border-solid border-border-information-subtle bg-surface-feedback-subtle-information px-4 py-3 mobile:flex-col mobile:items-start">
<div className="flex h-8 w-8 flex-none items-center justify-center rounded-round bg-surface-neutral-secondary">
<FeatherUserPlus className="text-body-default-regular-0 font-body-default-regular-0 text-icon-feedback-information" />
</div>
<div className="flex grow shrink-0 basis-0 flex-col items-start">
<div className="flex items-center gap-2 mobile:flex-wrap">
<span className="text-body-small-semibold-150 font-body-small-semibold-150 text-text-neutral-primary">
{t("settings.forms.editor.lead.banner.title")}
</span>
<BadgeFeedback farbe={leadEnabled ? "subtle-information" : "subtle-neutral"} size="small">
{leadEnabled ? t("settings.forms.editor.lead.banner.active") : t("settings.forms.editor.lead.banner.inactive")}
</BadgeFeedback>
</div>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{leadEnabled ? t("settings.forms.editor.lead.banner.description") : t("settings.forms.editor.lead.banner.descriptionInactive")}
</span>
</div>
<Button variant="tertiary" size="small" icon={<FeatherArrowLeft />} onClick={onBack}>
{t("settings.forms.editor.leadMapping.backToQuestions")}
</Button>
</div>
{/* "Nach Absenden" card with the lead toggle */}
<div className="flex w-full flex-col items-start gap-3 rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-5 py-4 shadow-sm">
<div className="flex w-full items-center gap-2">
<span className="grow shrink-0 basis-0 text-body-small-semibold-150 font-body-small-semibold-150 text-text-neutral-primary">
{t("settings.forms.editor.afterSubmit.title")}
</span>
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t("settings.forms.editor.afterSubmit.subtitle")}
</span>
</div>
<div className="flex w-full items-center gap-3 rounded-md border border-solid border-border-positive-subtle bg-surface-feedback-subtle-positive px-4 py-3 mobile:flex-col mobile:items-start">
<div className="flex h-8 w-8 flex-none items-center justify-center rounded-round bg-surface-neutral-secondary">
<FeatherUserPlus className="text-body-default-regular-0 font-body-default-regular-0 text-icon-feedback-positive" />
</div>
<div className="flex grow shrink-0 basis-0 flex-col items-start">
<div className="flex items-center gap-2">
<span className="text-body-small-semibold-150 font-body-small-semibold-150 text-text-neutral-primary">
{t("settings.forms.admin.defaults.leadActionName")}
</span>
<BadgeFeedback farbe={leadEnabled ? "subtle-positive" : "subtle-neutral"} size="small">
{leadEnabled ? t("settings.forms.editor.lead.banner.active") : t("settings.forms.editor.lead.banner.inactive")}
</BadgeFeedback>
</div>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("settings.forms.editor.afterSubmit.leadDescription")}
</span>
</div>
<Switch checked={leadEnabled} onCheckedChange={toggleLeadEnabled} />
</div>
</div>
{/* Mapping card */}
<div className="flex w-full flex-col items-start rounded-lg border border-solid border-border-default bg-surface-neutral-secondary shadow-sm">
<div className="flex w-full items-center gap-3 border-b border-solid border-border-default px-5 py-4 mobile:flex-col mobile:items-start">
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-0.5">
<div className="flex items-center gap-2">
<FeatherArrowLeftRight className="text-body-large font-body-large text-icon-neutral-tertiary" />
<span className="text-body-default-semibold-150 font-body-default-semibold-150 text-text-neutral-primary">
{t("settings.forms.editor.leadMapping.title")}
</span>
</div>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("settings.forms.editor.leadMapping.description")}
</span>
</div>
<Button variant="tertiary" size="small" icon={<FeatherWand2 />} onClick={autoAssign}>
{t("settings.forms.editor.leadMapping.autoAssign")}
</Button>
</div>
<div className="flex w-full flex-col items-start gap-2 px-5 py-4">
{LEAD_TARGET_KEYS.map((target) => {
const Icon = TARGET_ICONS[target];
return (
<div
key={target}
className="flex w-full items-center gap-4 rounded-md border border-solid border-border-default bg-surface-neutral-primary px-4 py-3 mobile:flex-col mobile:items-start mobile:gap-3"
>
<div className="flex w-52 flex-none items-start gap-2.5 mobile:w-full mobile:flex-none">
<Icon className="text-body-default-regular-0 font-body-default-regular-0 text-icon-neutral-tertiary" />
<div className="flex flex-col items-start gap-0.5">
<span className="text-body-small-semibold-150 font-body-small-semibold-150 text-text-neutral-primary">
{t(`settings.forms.editor.leadMapping.fields.${target}.title`)}
</span>
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t(`settings.forms.editor.leadMapping.fields.${target}.description`)}
</span>
</div>
</div>
<FeatherArrowRight className="text-body-default-regular-0 font-body-default-regular-0 text-icon-neutral-subtle mobile:hidden" />
<Select
className="h-auto grow shrink-0 basis-0"
variant="filled"
placeholder={t("settings.forms.editor.leadMapping.selectQuestion")}
value={mapping[target] || NONE_VALUE}
onValueChange={(value: string) => assign(target, value === NONE_VALUE ? "" : value)}
>
<Select.Item value={NONE_VALUE}>{t("settings.forms.editor.leadMapping.notAssigned")}</Select.Item>
{visibleFields.map((field) => (
<Select.Item key={field.key} value={field.key}>
{field.label}
</Select.Item>
))}
</Select>
</div>
);
})}
{/* Source is set by the backend automatically. */}
<div className="flex w-full items-center gap-4 rounded-md border border-solid border-border-default bg-surface-neutral-primary px-4 py-3 mobile:flex-col mobile:items-start mobile:gap-3">
<div className="flex w-52 flex-none items-start gap-2.5 mobile:w-full mobile:flex-none">
<FeatherGlobe className="text-body-default-regular-0 font-body-default-regular-0 text-icon-neutral-tertiary" />
<div className="flex flex-col items-start gap-0.5">
<span className="text-body-small-semibold-150 font-body-small-semibold-150 text-text-neutral-primary">
{t("settings.forms.editor.leadMapping.source.title")}
</span>
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t("settings.forms.editor.leadMapping.source.description")}
</span>
</div>
</div>
<FeatherArrowRight className="text-body-default-regular-0 font-body-default-regular-0 text-icon-neutral-subtle mobile:hidden" />
<div className="flex grow shrink-0 basis-0 items-center gap-2 rounded-md border border-solid border-border-default bg-surface-neutral-secondary px-3 py-2">
<FeatherLock className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
<span className="grow shrink-0 basis-0 text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
{t("settings.forms.editor.leadMapping.source.value")}
</span>
</div>
</div>
</div>
</div>
{/* E05: warn when no contact channel is mapped (non-blocking) */}
{missingContact ? (
<div className="flex w-full items-center gap-3 rounded-md border border-solid border-border-warning-subtle bg-surface-feedback-subtle-warning px-4 py-3 mobile:flex-col mobile:items-start">
<FeatherAlertCircle className="text-body-default-regular-0 font-body-default-regular-0 text-icon-feedback-warning" />
<div className="flex grow shrink-0 basis-0 flex-col items-start">
<span className="text-body-small-semibold-150 font-body-small-semibold-150 text-text-feedback-warning">
{t("settings.forms.editor.leadMapping.warning.title")}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-feedback-warning">
{t("settings.forms.editor.leadMapping.warning.body")}
</span>
</div>
</div>
) : null}
<div className="flex w-full items-center gap-2 pb-2 mobile:flex-col mobile:items-stretch">
<Button variant="tertiary" icon={<FeatherArrowLeft />} onClick={onBack}>
{t("settings.forms.editor.leadMapping.backToQuestions")}
</Button>
<div className="flex grow shrink-0 basis-0 items-center justify-end mobile:justify-stretch">
<Button icon={<FeatherCheck />} onClick={save}>
{t("shared.save")}
</Button>
</div>
</div>
</div>
);
}
@@ -0,0 +1,552 @@
/**
* S05 "Antworten" tab of the Subframe form editor (WF-P16), including
* the E03 empty state, the E04 export-error banner and the submission
* detail drawer (values, metadata, files, action log + rerun).
*
* The loader ships the latest 50 submissions; search and the time
* range filter are client-side, the status filter navigates via the
* existing `?status=` loader contract. Exports stream via fetch() from
* the loader's `?export=csv|pdf` endpoints.
*/
import { useMemo, useState } from "react";
import { useFetcher, useLocation, useSearchParams, Link } from "react-router";
import { useTranslation } from "react-i18next";
import {
FeatherAlertCircle,
FeatherCalendar,
FeatherChevronLeft,
FeatherChevronRight,
FeatherClock,
FeatherDownload,
FeatherEye,
FeatherFileText,
FeatherFilter,
FeatherImage,
FeatherInbox,
FeatherInfo,
FeatherRefreshCw,
FeatherX,
} from "@subframe/core";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Drawer } from "~/ui/components/Drawer";
import { IconButton } from "~/ui/components/IconButton";
import { IconWithBackground } from "~/ui/components/IconWithBackground";
import { SearchInput } from "~/ui/components/SearchInput";
import { Select } from "~/ui/components/Select";
import { Table } from "~/ui/components/Table";
import { useSaveToast, type SaveActionResult } from "~/hooks/use-save-toast";
import { displaySubmissionValue } from "./fieldMeta";
export type SubmissionRowVM = {
id: string;
status: string;
sourceOrigin: string | null;
userAgent: string | null;
createdAt: string;
values: Record<string, unknown>;
preview: string;
files: Array<{ fieldKey: string; fileId: string; kind: string }>;
actionLogs: Array<{
id: string;
actionType: string;
status: string;
targetType: string | null;
targetId: string | null;
errorMessage: string | null;
}>;
};
export type SubmissionColumn = { key: string; label: string; type: string };
export type ResponsesTabProps = {
submissions: SubmissionRowVM[];
columns: SubmissionColumn[];
statusFilter: string;
csrf: string;
formatDateTime: (value: string) => string;
formatNumber: (value: number) => string;
onOpenPreview: () => void;
};
const PAGE_SIZE = 10;
const MAX_TABLE_COLUMNS = 6;
const ALL_VALUE = "__all";
type TimeRange = "all" | "today" | "last7" | "thisMonth" | "lastMonth" | "last3Months" | "lastYear";
function rangeBounds(range: TimeRange): { start: Date | null; end: Date | null } {
const now = new Date();
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
switch (range) {
case "today":
return { start: startOfToday, end: null };
case "last7":
return { start: new Date(startOfToday.getTime() - 7 * 24 * 60 * 60 * 1000), end: null };
case "thisMonth":
return { start: new Date(now.getFullYear(), now.getMonth(), 1), end: null };
case "lastMonth":
return { start: new Date(now.getFullYear(), now.getMonth() - 1, 1), end: new Date(now.getFullYear(), now.getMonth(), 1) };
case "last3Months":
return { start: new Date(now.getFullYear(), now.getMonth() - 3, 1), end: null };
case "lastYear":
return { start: new Date(now.getFullYear() - 1, now.getMonth(), now.getDate()), end: null };
default:
return { start: null, end: null };
}
}
function statusBadge(status: string, t: (key: string) => string): { farbe: React.ComponentProps<typeof BadgeFeedback>["farbe"]; label: string } {
if (status === "received") return { farbe: "subtle-neutral", label: t("settings.forms.admin.detail.filters.received") };
if (status === "processed" || status === "routed-to-crm" || status === "routed-to-entity") {
return { farbe: "subtle-positive", label: t("settings.forms.admin.detail.filters.processed") };
}
if (status === "route-failed") return { farbe: "subtle-negative", label: t("settings.forms.admin.detail.filters.failed") };
if (status === "spam") return { farbe: "subtle-warning", label: t("settings.forms.editor.responses.status.spam") };
return { farbe: "subtle-neutral", label: status };
}
function isNew(createdAt: string): boolean {
return Date.now() - new Date(createdAt).getTime() < 24 * 60 * 60 * 1000;
}
export function ResponsesTab({
submissions,
columns,
statusFilter,
csrf,
formatDateTime,
formatNumber,
onOpenPreview,
}: ResponsesTabProps): React.JSX.Element {
const { t } = useTranslation();
const location = useLocation();
const [, setSearchParams] = useSearchParams();
const [query, setQuery] = useState("");
const [range, setRange] = useState<TimeRange>("all");
const [page, setPage] = useState(0);
const [exportError, setExportError] = useState<"csv" | "pdf" | null>(null);
const [exportingKind, setExportingKind] = useState<"csv" | "pdf" | null>(null);
const [exportResult, setExportResult] = useState<SaveActionResult>();
const [detailId, setDetailId] = useState<string | null>(null);
const rerunFetcher = useFetcher<{ error?: string; success?: string }>();
useSaveToast(exportResult);
const tableColumns = columns.slice(0, MAX_TABLE_COLUMNS);
const filtered = useMemo(() => {
const needle = query.trim().toLowerCase();
const { start, end } = rangeBounds(range);
return submissions.filter((submission) => {
const created = new Date(submission.createdAt);
if (start && created < start) return false;
if (end && created >= end) return false;
if (needle) {
const haystack = [
...columns.map((column) => displaySubmissionValue(submission.values[column.key])),
submission.sourceOrigin ?? "",
]
.join(" ")
.toLowerCase();
if (!haystack.includes(needle)) return false;
}
return true;
});
}, [submissions, columns, query, range]);
const pageCount = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
const safePage = Math.min(page, pageCount - 1);
const pageRows = filtered.slice(safePage * PAGE_SIZE, safePage * PAGE_SIZE + PAGE_SIZE);
const detail = detailId ? submissions.find((submission) => submission.id === detailId) ?? null : null;
function setStatus(next: string): void {
setSearchParams(
(prev) => {
const params = new URLSearchParams(prev);
if (next) params.set("status", next);
else params.delete("status");
params.set("tab", "responses");
return params;
},
{ replace: true },
);
setPage(0);
}
async function runExport(kind: "csv" | "pdf"): Promise<void> {
setExportError(null);
setExportingKind(kind);
const params = new URLSearchParams();
params.set("export", kind);
if (statusFilter) params.set("status", statusFilter);
try {
const response = await fetch(`${location.pathname}?${params.toString()}`);
if (!response.ok) throw new Error(String(response.status));
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = `form-submissions.${kind}`;
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
URL.revokeObjectURL(url);
setExportResult({
ok: true,
messageKey:
kind === "csv"
? "settings.forms.editor.responses.exportCsvReady"
: "settings.forms.editor.responses.exportPdfReady",
});
} catch {
setExportError(kind);
} finally {
setExportingKind(null);
}
}
function rerunSubmission(submissionId: string): void {
const formData = new FormData();
formData.set("csrf", csrf);
formData.set("op", "rerun-submission");
formData.set("submissionId", submissionId);
rerunFetcher.submit(formData, { method: "post" });
}
const hasAnySubmissions = submissions.length > 0 || Boolean(statusFilter);
return (
<div className="flex w-full flex-col items-start gap-6 px-6 py-6 mobile:px-4">
<div className="flex w-full items-start gap-4 mobile:flex-col">
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-1">
<span className="text-subtitle font-subtitle text-text-neutral-primary">{t("settings.forms.editor.responses.title")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("settings.forms.editor.responses.description")}
</span>
</div>
</div>
{/* E04: export failed banner */}
{exportError ? (
<div className="flex w-full items-start gap-3 rounded-md border border-solid border-border-negative-subtle bg-surface-feedback-subtle-negative px-4 py-3.5 mobile:flex-col">
<FeatherAlertCircle className="text-body-large font-body-large text-icon-feedback-negative" />
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-1">
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-feedback-negative">
{t("settings.forms.editor.responses.exportError.title")}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{t("settings.forms.editor.responses.exportError.body")}
</span>
</div>
<div className="flex items-center gap-2 mobile:w-full mobile:flex-none">
<Button variant="tertiary" size="small" icon={<FeatherRefreshCw />} onClick={() => void runExport(exportError)}>
{t("settings.forms.editor.responses.exportError.retry")}
</Button>
<IconButton variant="ghost" size="small" icon={<FeatherX />} aria-label={t("shared.close")} onClick={() => setExportError(null)} />
</div>
</div>
) : null}
{!hasAnySubmissions ? (
/* E03: no responses yet */
<div className="flex w-full flex-col items-center justify-center gap-6 rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-6 py-16 shadow-sm">
<IconWithBackground variant="neutral" size="large" icon={<FeatherInbox />} />
<div className="flex w-full flex-col items-center gap-2 max-w-[420px]">
<span className="w-full text-heading- font-heading- text-text-neutral-primary text-center">
{t("settings.forms.editor.responses.empty.title")}
</span>
<span className="w-full text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-tertiary text-center">
{t("settings.forms.editor.responses.empty.body")}
</span>
<span className="w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary text-center">
{t("settings.forms.editor.responses.empty.shareHint")}
</span>
</div>
<Button variant="secondary" icon={<FeatherEye />} onClick={onOpenPreview}>
{t("settings.forms.editor.responses.empty.openPreview")}
</Button>
</div>
) : (
<>
{/* Toolbar */}
<div className="flex w-full items-center gap-3 mobile:flex-col mobile:items-stretch">
<SearchInput
className="h-8 w-72 flex-none mobile:w-full"
size="small"
hideShortcut
aria-label={t("settings.forms.editor.responses.searchPlaceholder")}
placeholder={t("settings.forms.editor.responses.searchPlaceholder")}
value={query}
onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
setQuery(event.target.value);
setPage(0);
}}
/>
<Select
className="h-8 w-48 flex-none mobile:w-full"
variant="filled"
size="small"
placeholder={t("settings.forms.editor.responses.range.label")}
icon={<FeatherCalendar />}
value={range}
onValueChange={(value: string) => {
setRange(value as TimeRange);
setPage(0);
}}
>
<Select.Item value="today">{t("settings.forms.editor.responses.range.today")}</Select.Item>
<Select.Item value="last7">{t("settings.forms.editor.responses.range.last7")}</Select.Item>
<Select.Item value="thisMonth">{t("settings.forms.editor.responses.range.thisMonth")}</Select.Item>
<Select.Item value="lastMonth">{t("settings.forms.editor.responses.range.lastMonth")}</Select.Item>
<Select.Item value="last3Months">{t("settings.forms.editor.responses.range.last3Months")}</Select.Item>
<Select.Item value="lastYear">{t("settings.forms.editor.responses.range.lastYear")}</Select.Item>
<Select.Item value="all">{t("settings.forms.editor.responses.range.all")}</Select.Item>
</Select>
<Select
className="h-8 w-44 flex-none mobile:w-full"
variant="filled"
size="small"
placeholder={t("settings.forms.admin.detail.filters.allStatuses")}
icon={<FeatherFilter />}
value={statusFilter || ALL_VALUE}
onValueChange={(value: string) => setStatus(value === ALL_VALUE ? "" : value)}
>
<Select.Item value={ALL_VALUE}>{t("settings.forms.admin.detail.filters.allStatuses")}</Select.Item>
<Select.Item value="received">{t("settings.forms.admin.detail.filters.received")}</Select.Item>
<Select.Item value="processed">{t("settings.forms.admin.detail.filters.processed")}</Select.Item>
<Select.Item value="route-failed">{t("settings.forms.admin.detail.filters.failed")}</Select.Item>
</Select>
<div className="flex grow shrink-0 basis-0 items-center justify-end gap-2 mobile:justify-start">
<Button size="small" icon={<FeatherDownload />} disabled={exportingKind !== null} onClick={() => void runExport("csv")}>
{t("settings.forms.editor.responses.exportCsv")}
</Button>
<Button variant="secondary" size="small" icon={<FeatherFileText />} disabled={exportingKind !== null} onClick={() => void runExport("pdf")}>
{t("settings.forms.editor.responses.exportPdf")}
</Button>
</div>
</div>
{filtered.length === 0 ? (
<div className="flex w-full flex-col items-center justify-center gap-3 rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-6 py-12 shadow-sm">
<FeatherInbox className="text-heading- font-heading- text-icon-neutral-tertiary" />
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary text-center">
{t("settings.forms.editor.responses.noMatches")}
</span>
</div>
) : (
<div className="flex w-full flex-col items-start overflow-hidden rounded-lg border border-solid border-border-default shadow-sm overflow-x-auto">
<Table
header={
<Table.HeaderRow className="bg-surface-neutral-tertiary">
<Table.HeaderCell icon={<FeatherClock />}>{t("settings.forms.editor.responses.columns.receivedAt")}</Table.HeaderCell>
{tableColumns.map((column) => (
<Table.HeaderCell key={column.key}>{column.label}</Table.HeaderCell>
))}
<Table.HeaderCell>{t("settings.forms.editor.responses.columns.file")}</Table.HeaderCell>
<Table.HeaderCell>{t("settings.forms.admin.detail.status")}</Table.HeaderCell>
</Table.HeaderRow>
}
>
{pageRows.map((submission) => {
const badge = statusBadge(submission.status, (key) => t(key));
const firstFile = submission.files[0];
return (
<Table.Row key={submission.id} clickable className="cursor-pointer" onClick={() => setDetailId(submission.id)}>
<Table.Cell>
<div className="flex items-center gap-2">
{isNew(submission.createdAt) ? (
<div className="flex h-1.5 w-1.5 flex-none flex-col items-center rounded-round bg-surface-feedback-solid-positive-default" />
) : null}
<time dateTime={submission.createdAt} className="whitespace-nowrap text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary">
{formatDateTime(submission.createdAt)}
</time>
</div>
</Table.Cell>
{tableColumns.map((column) => (
<Table.Cell key={column.key}>
<span className="line-clamp-1 max-w-[220px] text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">
{displaySubmissionValue(submission.values[column.key]) || t("shared.notSet")}
</span>
</Table.Cell>
))}
<Table.Cell>
{firstFile ? (
<div className="flex items-center gap-1.5">
{firstFile.kind === "photo" ? (
<FeatherImage className="text-body-small-regular-0 font-body-small-regular-0 text-icon-feedback-information" />
) : (
<FeatherFileText className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
)}
<span className="whitespace-nowrap text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{firstFile.fieldKey}
</span>
</div>
) : (
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-subtle">{"—"}</span>
)}
</Table.Cell>
<Table.Cell>
<BadgeFeedback farbe={badge.farbe} size="small">
{badge.label}
</BadgeFeedback>
</Table.Cell>
</Table.Row>
);
})}
</Table>
</div>
)}
{/* Footer: pagination + latest-50 hint */}
<div className="flex w-full items-center gap-3 mobile:flex-col mobile:items-start">
<span className="grow shrink-0 basis-0 text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{filtered.length > 0
? t("settings.forms.editor.responses.pagination.summary", {
from: formatNumber(safePage * PAGE_SIZE + 1),
to: formatNumber(Math.min((safePage + 1) * PAGE_SIZE, filtered.length)),
total: formatNumber(filtered.length),
})
: null}
{" · "}
{t("settings.forms.admin.detail.submissionsLatest")}
</span>
<div className="flex items-center gap-2">
<Button variant="tertiary" size="small" icon={<FeatherChevronLeft />} disabled={safePage === 0} onClick={() => setPage(Math.max(0, safePage - 1))}>
{t("shared.back")}
</Button>
<Button
variant="tertiary"
size="small"
iconRight={<FeatherChevronRight />}
disabled={safePage >= pageCount - 1}
onClick={() => setPage(Math.min(pageCount - 1, safePage + 1))}
>
{t("settings.forms.editor.responses.pagination.next")}
</Button>
</div>
</div>
</>
)}
{/* Detail drawer */}
<Drawer open={detail !== null} onOpenChange={(open: boolean) => (!open ? setDetailId(null) : undefined)}>
{detail ? (
<Drawer.Content className="w-[480px] max-w-full gap-0 overflow-y-auto mobile:w-full">
<div className="flex w-full items-center gap-3 border-b border-solid border-border-default px-6 py-4">
<div className="flex grow shrink-0 basis-0 flex-col items-start">
<span className="text-body-default-semibold-150 font-body-default-semibold-150 text-text-neutral-primary">
{t("settings.forms.editor.responses.drawer.title")}
</span>
<time dateTime={detail.createdAt} className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{formatDateTime(detail.createdAt)}
</time>
</div>
<BadgeFeedback farbe={statusBadge(detail.status, (key) => t(key)).farbe} size="small">
{statusBadge(detail.status, (key) => t(key)).label}
</BadgeFeedback>
<IconButton variant="ghost" size="small" icon={<FeatherX />} aria-label={t("shared.close")} onClick={() => setDetailId(null)} />
</div>
<div className="flex w-full flex-col items-start gap-5 px-6 py-5">
{/* Field values */}
<div className="flex w-full flex-col items-start gap-2">
<span className="text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 text-text-neutral-tertiary uppercase tracking-wide">
{t("settings.forms.editor.responses.drawer.values")}
</span>
{columns.map((column) => (
<div key={column.key} className="flex w-full flex-col items-start rounded-md border border-solid border-border-default bg-surface-neutral-primary px-3 py-2">
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">{column.label}</span>
<span className="whitespace-pre-wrap break-words text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-primary">
{displaySubmissionValue(detail.values[column.key]) || t("shared.notSet")}
</span>
</div>
))}
</div>
{/* Files */}
{detail.files.length > 0 ? (
<div className="flex w-full flex-col items-start gap-2">
<span className="text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 text-text-neutral-tertiary uppercase tracking-wide">
{t("settings.forms.admin.detail.files")}
</span>
{detail.files.map((file) => (
<Link
key={`${file.fieldKey}:${file.fileId}`}
to={`../media/${file.fileId}/original`}
className="flex items-center gap-1.5 text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-link-default"
>
{file.kind === "photo" ? <FeatherImage className="text-body-small-regular-0 font-body-small-regular-0" /> : <FeatherFileText className="text-body-small-regular-0 font-body-small-regular-0" />}
{file.fieldKey}
</Link>
))}
</div>
) : null}
{/* Metadata */}
<div className="flex w-full flex-col items-start gap-1">
<span className="text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 text-text-neutral-tertiary uppercase tracking-wide">
{t("settings.forms.editor.responses.drawer.metadata")}
</span>
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t("settings.forms.admin.detail.origin", { origin: detail.sourceOrigin ?? t("shared.notSet") })}
</span>
<span className="break-all text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t("settings.forms.admin.detail.userAgent")}: {detail.userAgent ?? t("shared.notSet")}
</span>
</div>
{/* Action log + rerun */}
<div className="flex w-full flex-col items-start gap-2">
<span className="text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 text-text-neutral-tertiary uppercase tracking-wide">
{t("settings.forms.editor.responses.drawer.actionLog")}
</span>
{detail.actionLogs.length === 0 ? (
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("settings.forms.editor.responses.drawer.noActionLogs")}
</span>
) : (
detail.actionLogs.map((log) => (
<div key={log.id} className="flex w-full flex-col items-start rounded-md border border-solid border-border-default bg-surface-neutral-primary px-3 py-2">
<div className="flex w-full items-center gap-2">
<code className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-secondary">{log.actionType}</code>
<BadgeFeedback farbe={log.status === "failed" ? "subtle-negative" : "subtle-neutral"} size="small">
{log.status}
</BadgeFeedback>
</div>
{log.targetId ? (
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{log.targetType}: {log.targetId}
</span>
) : null}
{log.errorMessage ? (
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-feedback-negative">{log.errorMessage}</span>
) : null}
</div>
))
)}
{rerunFetcher.data?.error ? (
<div className="flex w-full items-center gap-2 rounded-md border border-solid border-border-negative-subtle bg-surface-feedback-subtle-negative px-3 py-2">
<FeatherInfo className="text-body-small-regular-0 font-body-small-regular-0 text-icon-feedback-negative" />
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-feedback-negative">{rerunFetcher.data.error}</span>
</div>
) : null}
{rerunFetcher.data?.success ? (
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-feedback-positive">{rerunFetcher.data.success}</span>
) : null}
<Button
variant="secondary"
size="small"
icon={<FeatherRefreshCw />}
disabled={rerunFetcher.state !== "idle"}
onClick={() => rerunSubmission(detail.id)}
>
{t("settings.forms.admin.detail.rerunSubmission")}
</Button>
</div>
</div>
</Drawer.Content>
) : null}
</Drawer>
</div>
);
}
@@ -0,0 +1,145 @@
/**
* Shared metadata + tiny helpers for the Subframe form editor screens
* (WF-P16 S02/S02L/S03/S05). Keeps the field-type catalogue (icons +
* i18n label keys) and value-formatting helpers in one place so the
* editor tabs stay terse.
*/
import type * as React from "react";
import {
FeatherAlignLeft,
FeatherAtSign,
FeatherCalendar,
FeatherCheckSquare,
FeatherCircleDot,
FeatherClock,
FeatherHash,
FeatherImage,
FeatherListChecks,
FeatherPaperclip,
FeatherPhone,
FeatherType,
} from "@subframe/core";
import type { FormField, FormFieldType } from "@hivegrid/form-widget";
import { uniqueKey } from "~/modules/formWidget/builder/types";
import type { FormActionJsonObject, FormActionJsonValue, FormActionSetting } from "~/modules/formWidget/builder/SettingsTab";
/** The 12 operator-editable field types (honeypot stays system-managed). */
export const EDITABLE_FIELD_TYPES = [
"text",
"textarea",
"select",
"multiselect",
"boolean",
"email",
"phone",
"number",
"date",
"time",
"file",
"photo",
] as const satisfies readonly FormFieldType[];
export type EditableFieldType = (typeof EDITABLE_FIELD_TYPES)[number];
const FIELD_TYPE_ICONS: Record<EditableFieldType, React.ComponentType<{ className?: string }>> = {
text: FeatherType,
textarea: FeatherAlignLeft,
number: FeatherHash,
date: FeatherCalendar,
time: FeatherClock,
select: FeatherCircleDot,
multiselect: FeatherListChecks,
boolean: FeatherCheckSquare,
email: FeatherAtSign,
phone: FeatherPhone,
file: FeatherPaperclip,
photo: FeatherImage,
};
export function fieldTypeIcon(type: string): React.ComponentType<{ className?: string }> {
return FIELD_TYPE_ICONS[type as EditableFieldType] ?? FeatherType;
}
/** Reuses the existing builder palette label keys (all 12 types exist). */
export function fieldTypeLabelKey(type: string): string {
return `settings.forms.builder.palette.${type}.label`;
}
/** Derives a schema-safe (^[a-zA-Z][a-zA-Z0-9_]*$), unique field key from a label. */
export function slugFieldKey(label: string, existing: Set<string>): string {
const base = label
.toLowerCase()
.replace(/[äöüß]/g, (c) => ({ ä: "ae", ö: "oe", ü: "ue", ß: "ss" })[c] ?? c)
.replace(/\s+/g, "_");
return uniqueKey(base, existing);
}
const DEFAULT_OPTIONS = (t: (key: string) => string) => [
{ value: "option_a", label: t("settings.forms.builder.defaults.options.option_a") },
{ value: "option_b", label: t("settings.forms.builder.defaults.options.option_b") },
];
/** Fresh field for the "add question" affordances. */
export function makeField(type: EditableFieldType, t: (key: string) => string, existingKeys: Set<string>): FormField {
const label = t(fieldTypeLabelKey(type));
const field: FormField = {
key: slugFieldKey(label, existingKeys),
type,
label,
required: false,
conditionalLogic: [],
validationRules: {},
};
if (type === "select" || type === "multiselect") {
field.options = DEFAULT_OPTIONS(t);
}
return field;
}
/** Ensures option-shape consistency when the operator switches a field's type. */
export function withFieldType(field: FormField, type: EditableFieldType, t: (key: string) => string): FormField {
const next: FormField = { ...field, type };
if (type === "select" || type === "multiselect") {
if (!next.options || next.options.length === 0) next.options = DEFAULT_OPTIONS(t);
} else {
delete next.options;
}
return next;
}
/** Human-readable rendering for submission payload values. */
export function displaySubmissionValue(value: unknown): string {
if (Array.isArray(value)) return value.join(", ");
if (value === true) return "true";
if (value === false) return "false";
if (value === null || value === undefined || value === "") return "";
if (typeof value === "object") return JSON.stringify(value);
return String(value);
}
function isJsonValue(value: unknown): value is FormActionJsonValue {
if (value === null) return true;
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return true;
if (Array.isArray(value)) return value.every(isJsonValue);
if (typeof value !== "object") return false;
return Object.values(value as Record<string, unknown>).every(isJsonValue);
}
/** Parses a JSON object literal; returns null when the text is not (yet) valid. */
export function parseJsonObjectDraft(raw: string): FormActionJsonObject | null {
if (!raw.trim()) return {};
try {
const parsed = JSON.parse(raw) as unknown;
return parsed && typeof parsed === "object" && !Array.isArray(parsed) && isJsonValue(parsed) ? (parsed as FormActionJsonObject) : null;
} catch {
return null;
}
}
/** Lead targets supported by the create_lead worker (source is set automatically). */
export const LEAD_TARGET_KEYS = ["vorname", "nachname", "email", "telefon", "message"] as const;
export type LeadTargetKey = (typeof LEAD_TARGET_KEYS)[number];
export function findLeadAction(actions: FormActionSetting[]): FormActionSetting | undefined {
return actions.find((action) => action.actionType === "create_lead");
}