Refactor cookie banner forms to react-hook-form

Signed-off-by: Émile Ré <emile@getprobo.com>
This commit is contained in:
Émile Ré
2026-04-30 14:05:45 +04:00
parent edcb5ba9c7
commit 0d257977a1
10 changed files with 223 additions and 162 deletions

View File

@@ -22,8 +22,7 @@ import { graphql } from "relay-runtime";
import type { CookieBannerCookiesPageDeleteMutation } from "#/__generated__/core/CookieBannerCookiesPageDeleteMutation.graphql";
import type { CookieBannerCookiesPageQuery } from "#/__generated__/core/CookieBannerCookiesPageQuery.graphql";
import { CategoryDialog } from "../_components/CategoryDialog";
import { CategoryDialog } from "./_components/CategoryDialog";
import { CategorySection } from "./_components/CategorySection";
export const cookieBannerCookiesPageQuery = graphql`

View File

@@ -15,10 +15,16 @@
import { toMaxAgeSeconds } from "@probo/helpers";
import { useTranslate } from "@probo/i18n";
import { Button, DurationInput, Input, Td, Tr } from "@probo/ui";
import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import type { CookieEntry } from "./CategorySection";
interface CookieFormValues {
name: string;
duration: { value: string; unit: string };
description: string;
}
interface AddCookieRowProps {
isUpdating: boolean;
onSave: (cookie: CookieEntry) => void;
@@ -31,16 +37,20 @@ export function AddCookieRow({
onCancel,
}: AddCookieRowProps) {
const { __ } = useTranslate();
const [name, setName] = useState("");
const [durationValue, setDurationValue] = useState("");
const [durationUnit, setDurationUnit] = useState("days");
const [description, setDescription] = useState("");
const handleSave = () => {
const { register, handleSubmit, control } = useForm<CookieFormValues>({
defaultValues: {
name: "",
duration: { value: "", unit: "days" },
description: "",
},
});
const onSubmit = (data: CookieFormValues) => {
onSave({
name,
maxAgeSeconds: toMaxAgeSeconds(durationValue, durationUnit),
description,
name: data.name,
maxAgeSeconds: toMaxAgeSeconds(data.duration.value, data.duration.unit),
description: data.description,
});
};
@@ -48,30 +58,34 @@ export function AddCookieRow({
<Tr>
<Td className="pr-3">
<Input
value={name}
onChange={e => setName(e.target.value)}
{...register("name")}
placeholder={__("Cookie name")}
/>
</Td>
<Td className="pr-3">
<DurationInput
value={durationValue}
unit={durationUnit}
onValueChange={setDurationValue}
onUnitChange={setDurationUnit}
<Controller
name="duration"
control={control}
render={({ field }) => (
<DurationInput
value={field.value.value}
unit={field.value.unit}
onValueChange={v => field.onChange({ ...field.value, value: v })}
onUnitChange={u => field.onChange({ ...field.value, unit: u })}
/>
)}
/>
</Td>
<Td className="pr-3">
<Input
value={description}
onChange={e => setDescription(e.target.value)}
{...register("description")}
placeholder={__("Description")}
/>
</Td>
<Td>
<div className="flex items-center gap-2">
<Button
onClick={handleSave}
onClick={() => void handleSubmit(onSubmit)()}
disabled={isUpdating}
>
{__("Save")}

View File

@@ -24,7 +24,8 @@ import {
Textarea,
useToast,
} from "@probo/ui";
import { useState } from "react";
import { useEffect } from "react";
import { useForm, useWatch } from "react-hook-form";
import { useMutation } from "react-relay";
import { graphql } from "relay-runtime";
@@ -60,6 +61,12 @@ const createMutation = graphql`
}
`;
interface CategoryFormValues {
name: string;
slug: string;
description: string;
}
interface CategoryDialogProps {
cookieBannerId: string;
connectionId: string;
@@ -78,38 +85,33 @@ export function CategoryDialog({
const [create, isCreating] = useMutation<CategoryDialogCreateMutation>(createMutation);
const [name, setName] = useState("");
const [slug, setSlug] = useState("");
const [slugTouched, setSlugTouched] = useState(false);
const [description, setDescription] = useState("");
const { register, handleSubmit, setValue, control, formState } = useForm<CategoryFormValues>({
defaultValues: { name: "", slug: "", description: "" },
});
const handleNameChange = (value: string) => {
setName(value);
if (!slugTouched) {
setSlug(
value
const nameValue = useWatch({ control, name: "name" });
useEffect(() => {
if (!formState.dirtyFields.slug) {
setValue(
"slug",
nameValue
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-|-$/g, ""),
{ shouldDirty: false },
);
}
};
const handleSlugChange = (value: string) => {
setSlugTouched(true);
setSlug(value);
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
}, [nameValue, formState.dirtyFields.slug, setValue]);
const onSubmit = (data: CategoryFormValues) => {
create({
variables: {
input: {
cookieBannerId,
name,
slug,
description,
name: data.name,
slug: data.slug,
description: data.description,
rank: nextRank,
},
connections: [connectionId],
@@ -131,18 +133,23 @@ export function CategoryDialog({
title={__("Add Category")}
className="max-w-lg"
>
<form onSubmit={handleSubmit}>
<form onSubmit={e => void handleSubmit(onSubmit)(e)}>
<DialogContent padded className="space-y-4">
<Field label={__("Name")}>
<Input value={name} onChange={e => handleNameChange(e.target.value)} required />
<Input {...register("name")} required />
</Field>
<Field label={__("Slug")} help={__("Used as the data-cookie-consent attribute value")}>
<Input value={slug} onChange={e => handleSlugChange(e.target.value)} required pattern="[a-z0-9]+(-[a-z0-9]+)*" />
<Input
{...register("slug", {
pattern: /^[a-z0-9]+(-[a-z0-9]+)*$/,
})}
required
/>
</Field>
<Field label={__("Description")}>
<Textarea value={description} onChange={e => setDescription(e.target.value)} required rows={2} />
<Textarea {...register("description")} required rows={2} />
</Field>
</DialogContent>

View File

@@ -14,7 +14,7 @@
import { useTranslate } from "@probo/i18n";
import { Button, Input, Textarea } from "@probo/ui";
import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
const GCM_CONSENT_TYPES = [
"analytics_storage",
@@ -26,6 +26,14 @@ const GCM_CONSENT_TYPES = [
"security_storage",
] as const;
interface CategoryFormValues {
name: string;
slug: string;
description: string;
gcmConsentTypes: string[];
posthogConsent: boolean;
}
interface EditCategoryFormProps {
name: string;
slug: string;
@@ -50,36 +58,35 @@ export function EditCategoryForm({
onCancel,
}: EditCategoryFormProps) {
const { __ } = useTranslate();
const [editName, setEditName] = useState(name);
const [editSlug, setEditSlug] = useState(slug);
const [editDescription, setEditDescription] = useState(description);
const [editGcmTypes, setEditGcmTypes] = useState<string[]>(gcmConsentTypes);
const [editPosthogConsent, setEditPosthogConsent] = useState(posthogConsent);
const toggleGcmType = (type: string) => {
setEditGcmTypes(prev =>
prev.includes(type)
? prev.filter(t => t !== type)
: [...prev, type],
);
const { register, handleSubmit, control } = useForm<CategoryFormValues>({
defaultValues: {
name,
slug,
description,
gcmConsentTypes,
posthogConsent,
},
});
const onSubmit = (data: CategoryFormValues) => {
onSave(data.name, data.slug, data.description, data.gcmConsentTypes, data.posthogConsent);
};
return (
<div className="space-y-3">
<Input
value={editName}
onChange={e => setEditName(e.target.value)}
{...register("name")}
placeholder={__("Category name")}
/>
<Input
value={editSlug}
onChange={e => setEditSlug(e.target.value)}
{...register("slug", {
pattern: /^[a-z0-9]+(-[a-z0-9]+)*$/,
})}
placeholder={__("Category slug")}
pattern="[a-z0-9]+(-[a-z0-9]+)*"
/>
<Textarea
value={editDescription}
onChange={e => setEditDescription(e.target.value)}
{...register("description")}
placeholder={__("Category description")}
rows={2}
/>
@@ -91,20 +98,33 @@ export function EditCategoryForm({
{__("Select the Google Consent Mode signals this category controls.")}
</p>
<div className="flex flex-wrap gap-2">
{GCM_CONSENT_TYPES.map(type => (
<label
key={type}
className="flex items-center gap-1.5 text-xs cursor-pointer"
>
<input
type="checkbox"
checked={editGcmTypes.includes(type)}
onChange={() => toggleGcmType(type)}
className="rounded"
/>
<code className="font-mono">{type}</code>
</label>
))}
<Controller
name="gcmConsentTypes"
control={control}
render={({ field }) => (
<>
{GCM_CONSENT_TYPES.map(type => (
<label
key={type}
className="flex items-center gap-1.5 text-xs cursor-pointer"
>
<input
type="checkbox"
checked={field.value.includes(type)}
onChange={() => {
const next = field.value.includes(type)
? field.value.filter(t => t !== type)
: [...field.value, type];
field.onChange(next);
}}
className="rounded"
/>
<code className="font-mono">{type}</code>
</label>
))}
</>
)}
/>
</div>
</div>
{kind === "NORMAL" && (
@@ -118,8 +138,7 @@ export function EditCategoryForm({
<label className="flex items-center gap-1.5 text-xs cursor-pointer">
<input
type="checkbox"
checked={editPosthogConsent}
onChange={() => setEditPosthogConsent(prev => !prev)}
{...register("posthogConsent")}
className="rounded"
/>
<span>{__("Opt in/out of PostHog tracking")}</span>
@@ -128,10 +147,7 @@ export function EditCategoryForm({
)}
<div className="flex items-center gap-2">
<Button
onClick={() => {
if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(editSlug)) return;
onSave(editName, editSlug, editDescription, editGcmTypes, editPosthogConsent);
}}
onClick={() => void handleSubmit(onSubmit)()}
disabled={isUpdating}
>
{isUpdating ? __("Saving...") : __("Save")}

View File

@@ -15,7 +15,7 @@
import { fromMaxAgeSeconds, toMaxAgeSeconds } from "@probo/helpers";
import { useTranslate } from "@probo/i18n";
import { Button, DurationInput, Input, Td, Tr } from "@probo/ui";
import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { useFragment } from "react-relay";
import { graphql } from "relay-runtime";
@@ -31,6 +31,12 @@ export const editCookieRowFragment = graphql`
}
`;
interface CookieFormValues {
name: string;
duration: { value: string; unit: string };
description: string;
}
interface EditCookieRowProps {
cookieKey: EditCookieRowFragment$key;
isUpdating: boolean;
@@ -47,16 +53,20 @@ export function EditCookieRow({
const { __ } = useTranslate();
const cookie = useFragment(editCookieRowFragment, cookieKey);
const initial = fromMaxAgeSeconds(cookie.maxAgeSeconds ?? null);
const [name, setName] = useState(cookie.displayName);
const [durationValue, setDurationValue] = useState(initial.value);
const [durationUnit, setDurationUnit] = useState(initial.unit);
const [description, setDescription] = useState(cookie.description);
const handleSave = () => {
const { register, handleSubmit, control } = useForm<CookieFormValues>({
defaultValues: {
name: cookie.displayName,
duration: initial,
description: cookie.description,
},
});
const onSubmit = (data: CookieFormValues) => {
onSave({
name,
maxAgeSeconds: toMaxAgeSeconds(durationValue, durationUnit),
description,
name: data.name,
maxAgeSeconds: toMaxAgeSeconds(data.duration.value, data.duration.unit),
description: data.description,
});
};
@@ -64,30 +74,34 @@ export function EditCookieRow({
<Tr>
<Td className="pr-3">
<Input
value={name}
onChange={e => setName(e.target.value)}
{...register("name")}
placeholder={__("Cookie name")}
/>
</Td>
<Td className="pr-3">
<DurationInput
value={durationValue}
unit={durationUnit}
onValueChange={setDurationValue}
onUnitChange={setDurationUnit}
<Controller
name="duration"
control={control}
render={({ field }) => (
<DurationInput
value={field.value.value}
unit={field.value.unit}
onValueChange={v => field.onChange({ ...field.value, value: v })}
onUnitChange={u => field.onChange({ ...field.value, unit: u })}
/>
)}
/>
</Td>
<Td className="pr-3">
<Input
value={description}
onChange={e => setDescription(e.target.value)}
{...register("description")}
placeholder={__("Description")}
/>
</Td>
<Td>
<div className="flex items-center gap-1">
<Button
onClick={handleSave}
onClick={() => void handleSubmit(onSubmit)()}
disabled={isUpdating}
>
{__("Save")}

View File

@@ -17,8 +17,7 @@ import { graphql } from "relay-runtime";
import type { CookieBannerDisplayPageQuery } from "#/__generated__/core/CookieBannerDisplayPageQuery.graphql";
import { CategoryList } from "../_components/CategoryList";
import { CategoryList } from "./_components/CategoryList";
import { ThemePreview } from "./_components/ThemePreview";
export const cookieBannerDisplayPageQuery = graphql`

View File

@@ -17,8 +17,7 @@ import { graphql } from "relay-runtime";
import type { CookieBannerSettingsPageQuery } from "#/__generated__/core/CookieBannerSettingsPageQuery.graphql";
import { BannerSettingsForm } from "../_components/BannerSettingsForm";
import { BannerSettingsForm } from "./_components/BannerSettingsForm";
import { CodeSnippets } from "./_components/CodeSnippets";
export const cookieBannerSettingsPageQuery = graphql`

View File

@@ -15,7 +15,7 @@
import { formatError, type GraphQLError } from "@probo/helpers";
import { useTranslate } from "@probo/i18n";
import { Button, Card, Field, Input, Label, Option, Select, useToast } from "@probo/ui";
import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { useFragment, useMutation } from "react-relay";
import { graphql } from "relay-runtime";
@@ -56,6 +56,15 @@ const updateBannerMutation = graphql`
}
`;
interface BannerSettingsFormValues {
name: string;
cookiePolicyUrl: string;
privacyPolicyUrl: string;
consentExpiryDays: string;
consentMode: "OPT_IN" | "OPT_OUT";
defaultLanguage: string;
}
interface BannerSettingsFormProps {
cookieBannerKey: BannerSettingsForm_cookieBanner$key;
}
@@ -68,26 +77,28 @@ export function BannerSettingsForm({ cookieBannerKey }: BannerSettingsFormProps)
const [updateBanner, isUpdating] = useMutation<BannerSettingsFormMutation>(updateBannerMutation);
const [name, setName] = useState(banner.name);
const [cookiePolicyUrl, setCookiePolicyUrl] = useState(banner.cookiePolicyUrl);
const [privacyPolicyUrl, setPrivacyPolicyUrl] = useState(banner.privacyPolicyUrl ?? "");
const [consentExpiryDays, setConsentExpiryDays] = useState(String(banner.consentExpiryDays));
const [consentMode, setConsentMode] = useState(banner.consentMode);
const [defaultLanguage, setDefaultLanguage] = useState(banner.defaultLanguage);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
const { register, handleSubmit, control } = useForm<BannerSettingsFormValues>({
defaultValues: {
name: banner.name,
cookiePolicyUrl: banner.cookiePolicyUrl,
privacyPolicyUrl: banner.privacyPolicyUrl ?? "",
consentExpiryDays: String(banner.consentExpiryDays),
consentMode: banner.consentMode,
defaultLanguage: banner.defaultLanguage,
},
});
const onSubmit = (data: BannerSettingsFormValues) => {
updateBanner({
variables: {
input: {
cookieBannerId: banner.id,
name,
cookiePolicyUrl,
privacyPolicyUrl: privacyPolicyUrl || undefined,
consentExpiryDays: parseInt(consentExpiryDays, 10),
consentMode: consentMode,
defaultLanguage,
name: data.name,
cookiePolicyUrl: data.cookiePolicyUrl,
privacyPolicyUrl: data.privacyPolicyUrl || undefined,
consentExpiryDays: parseInt(data.consentExpiryDays, 10),
consentMode: data.consentMode,
defaultLanguage: data.defaultLanguage,
},
},
onCompleted() {
@@ -103,9 +114,9 @@ export function BannerSettingsForm({ cookieBannerKey }: BannerSettingsFormProps)
<div className="space-y-4">
<h3 className="font-medium">{__("Settings")}</h3>
<Card className="border p-4">
<form className="space-y-4" onSubmit={handleSubmit}>
<form className="space-y-4" onSubmit={e => void handleSubmit(onSubmit)(e)}>
<Field label={__("Name")}>
<Input value={name} onChange={e => setName(e.target.value)} required />
<Input {...register("name")} required />
</Field>
<Field label={__("Origin URL")}>
@@ -113,11 +124,11 @@ export function BannerSettingsForm({ cookieBannerKey }: BannerSettingsFormProps)
</Field>
<Field label={__("Cookie Policy URL")}>
<Input value={cookiePolicyUrl} onChange={e => setCookiePolicyUrl(e.target.value)} required />
<Input {...register("cookiePolicyUrl")} required />
</Field>
<Field label={__("Privacy Policy URL")}>
<Input value={privacyPolicyUrl} onChange={e => setPrivacyPolicyUrl(e.target.value)} />
<Input {...register("privacyPolicyUrl")} />
</Field>
<div className="grid grid-cols-3 gap-4">
@@ -125,27 +136,38 @@ export function BannerSettingsForm({ cookieBannerKey }: BannerSettingsFormProps)
<Label>{__("Consent Expiry (days)")}</Label>
<Input
type="number"
value={consentExpiryDays}
onChange={e => setConsentExpiryDays(e.target.value)}
{...register("consentExpiryDays")}
min="1"
required
/>
</div>
<div className="space-y-2">
<Label>{__("Consent Mode")}</Label>
<Select value={consentMode} onValueChange={v => setConsentMode(v as "OPT_IN" | "OPT_OUT")}>
<Option value="OPT_IN">{__("Opt-in")}</Option>
<Option value="OPT_OUT">{__("Opt-out")}</Option>
</Select>
<Controller
name="consentMode"
control={control}
render={({ field }) => (
<Select value={field.value} onValueChange={field.onChange}>
<Option value="OPT_IN">{__("Opt-in")}</Option>
<Option value="OPT_OUT">{__("Opt-out")}</Option>
</Select>
)}
/>
</div>
<div className="space-y-2">
<Label>{__("Default Language")}</Label>
<Select value={defaultLanguage} onValueChange={setDefaultLanguage}>
<Option value="en">{__("English")}</Option>
<Option value="fr">{__("French")}</Option>
<Option value="de">{__("German")}</Option>
<Option value="es">{__("Spanish")}</Option>
</Select>
<Controller
name="defaultLanguage"
control={control}
render={({ field }) => (
<Select value={field.value} onValueChange={field.onChange}>
<Option value="en">{__("English")}</Option>
<Option value="fr">{__("French")}</Option>
<Option value="de">{__("German")}</Option>
<Option value="es">{__("Spanish")}</Option>
</Select>
)}
/>
</div>
</div>

View File

@@ -12,31 +12,22 @@
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
const UNITS: [number, string, string][] = [
[365 * 24 * 3600, "year", "years"],
[30 * 24 * 3600, "month", "months"],
[7 * 24 * 3600, "week", "weeks"],
[24 * 3600, "day", "days"],
[3600, "hour", "hours"],
[60, "minute", "minutes"],
];
export const DURATION_UNITS: { value: string; label: string; seconds: number }[] = [
{ value: "seconds", label: "seconds", seconds: 1 },
{ value: "minutes", label: "minutes", seconds: 60 },
{ value: "hours", label: "hours", seconds: 3600 },
{ value: "days", label: "days", seconds: 86400 },
{ value: "weeks", label: "weeks", seconds: 604800 },
{ value: "months", label: "months", seconds: 2592000 },
{ value: "years", label: "years", seconds: 31536000 },
export const DURATION_UNITS: { value: string; label: string; singular: string; seconds: number }[] = [
{ value: "seconds", label: "seconds", singular: "second", seconds: 1 },
{ value: "minutes", label: "minutes", singular: "minute", seconds: 60 },
{ value: "hours", label: "hours", singular: "hour", seconds: 3600 },
{ value: "days", label: "days", singular: "day", seconds: 86400 },
{ value: "weeks", label: "weeks", singular: "week", seconds: 604800 },
{ value: "months", label: "months", singular: "month", seconds: 2592000 },
{ value: "years", label: "years", singular: "year", seconds: 31536000 },
];
export function humanizeSeconds(seconds: number | null): string {
if (seconds === null || seconds <= 0) return "session";
for (const [unit, singular, plural] of UNITS) {
if (seconds >= unit && seconds % unit === 0) {
const count = seconds / unit;
return `${count} ${count === 1 ? singular : plural}`;
for (const u of [...DURATION_UNITS].reverse()) {
if (seconds >= u.seconds && seconds % u.seconds === 0) {
const count = seconds / u.seconds;
return `${count} ${count === 1 ? u.singular : u.label}`;
}
}
return `${seconds} ${seconds === 1 ? "second" : "seconds"}`;