Skip to content

Open source alternative to Semrush and Ahrefs

Add form fields on createFormHook and use the shadcn Select and Combobox on four forms (EVE-295) (#732)

Carter Smith96b39f33b66f
diff --git a/src/client/components/FormDialog.tsx b/src/client/components/FormDialog.tsx
index 92c39404..1a09d5ae 100644
--- a/src/client/components/FormDialog.tsx
+++ b/src/client/components/FormDialog.tsx
@@ -24,23 +24,3 @@ export function FormDialog({
</Modal>
);
}
-
-export function DialogField({
- label,
- help,
- children,
-}: {
- label: string;
- help?: string;
- children: ReactNode;
-}) {
- return (
- <label className="flex flex-col gap-1.5">
- <span className="text-sm font-medium">{label}</span>
- {children}
- {help ? (
- <span className="text-xs text-base-content/60">{help}</span>
- ) : null}
- </label>
- );
-}
diff --git a/src/client/components/form/formContext.ts b/src/client/components/form/formContext.ts
new file mode 100644
index 00000000..f82c9991
--- /dev/null
+++ b/src/client/components/form/formContext.ts
@@ -0,0 +1,6 @@
+import { createFormHookContexts } from "@tanstack/react-form";
+
+// Its own module so the field components and `useAppForm` can both import the
+// contexts without a cycle.
+export const { fieldContext, formContext, useFieldContext, useFormContext } =
+ createFormHookContexts();
diff --git a/src/client/components/form/useAppForm.tsx b/src/client/components/form/useAppForm.tsx
new file mode 100644
index 00000000..fc8d32ab
--- /dev/null
+++ b/src/client/components/form/useAppForm.tsx
@@ -0,0 +1,287 @@
+import { useId, type ComponentProps, type ReactNode } from "react";
+import { createFormHook } from "@tanstack/react-form";
+import { Button } from "@/client/components/ui/button";
+import { Checkbox } from "@/client/components/ui/checkbox";
+import {
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+} from "@/client/components/ui/field";
+import { Input } from "@/client/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/client/components/ui/select";
+import { Switch } from "@/client/components/ui/switch";
+import { Textarea } from "@/client/components/ui/textarea";
+import {
+ fieldContext,
+ formContext,
+ useFieldContext,
+ useFormContext,
+} from "@/client/components/form/formContext";
+import { getFieldError } from "@/client/lib/forms";
+
+type FieldText = {
+ label: ReactNode;
+ /** The hint under the control. The control's aria-describedby points at it. */
+ description?: ReactNode;
+};
+
+// Props the field components own. Everything else passes through to the control.
+type BoundProps =
+ | "id"
+ | "name"
+ | "value"
+ | "onChange"
+ | "onBlur"
+ | "aria-invalid"
+ | "aria-describedby";
+
+/** One id, label, hint and error wiring for every field component. */
+function useFieldControl(description: ReactNode) {
+ const field = useFieldContext<unknown>();
+ const id = useId();
+ const error = getFieldError(field.state.meta.errors);
+ const descriptionId = description ? `${id}-description` : undefined;
+ const errorId = error ? `${id}-error` : undefined;
+ const describedBy = [descriptionId, errorId].filter(Boolean).join(" ");
+ const invalid = error ? true : undefined;
+
+ return {
+ invalid,
+ messages: (
+ <>
+ {description ? (
+ <FieldDescription id={descriptionId}>{description}</FieldDescription>
+ ) : null}
+ {error ? <FieldError id={errorId}>{error}</FieldError> : null}
+ </>
+ ),
+ controlProps: {
+ id,
+ onBlur: field.handleBlur,
+ "aria-invalid": invalid,
+ "aria-describedby": describedBy || undefined,
+ },
+ };
+}
+
+function TextField({
+ label,
+ description,
+ ...inputProps
+}: FieldText & Omit<ComponentProps<typeof Input>, BoundProps>) {
+ const field = useFieldContext<string>();
+ const control = useFieldControl(description);
+
+ return (
+ <Field data-invalid={control.invalid}>
+ <FieldLabel htmlFor={control.controlProps.id}>{label}</FieldLabel>
+ <Input
+ {...inputProps}
+ {...control.controlProps}
+ name={field.name}
+ value={field.state.value}
+ onChange={(event) => field.handleChange(event.target.value)}
+ />
+ {control.messages}
+ </Field>
+ );
+}
+
+function TextareaField({
+ label,
+ description,
+ ...textareaProps
+}: FieldText & Omit<ComponentProps<typeof Textarea>, BoundProps>) {
+ const field = useFieldContext<string>();
+ const control = useFieldControl(description);
+
+ return (
+ <Field data-invalid={control.invalid}>
+ <FieldLabel htmlFor={control.controlProps.id}>{label}</FieldLabel>
+ <Textarea
+ {...textareaProps}
+ {...control.controlProps}
+ name={field.name}
+ value={field.state.value}
+ onChange={(event) => field.handleChange(event.target.value)}
+ />
+ {control.messages}
+ </Field>
+ );
+}
+
+type SelectOption<TValue> = { value: TValue; label: string };
+
+function SelectField<TValue>({
+ label,
+ description,
+ items,
+ disabled,
+}: FieldText & {
+ items: readonly SelectOption<TValue>[];
+ disabled?: boolean;
+}) {
+ const field = useFieldContext<TValue>();
+ const control = useFieldControl(description);
+
+ return (
+ <Field data-invalid={control.invalid} data-disabled={disabled}>
+ <FieldLabel htmlFor={control.controlProps.id}>{label}</FieldLabel>
+ <Select
+ name={field.name}
+ items={items}
+ value={field.state.value}
+ onValueChange={(value) => {
+ if (value !== null) field.handleChange(value);
+ }}
+ disabled={disabled}
+ >
+ <SelectTrigger {...control.controlProps} className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {items.map((item) => (
+ <SelectItem key={String(item.value)} value={item.value}>
+ {item.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {control.messages}
+ </Field>
+ );
+}
+
+function CheckboxField({
+ label,
+ description,
+ disabled,
+}: FieldText & { disabled?: boolean }) {
+ const field = useFieldContext<boolean>();
+ const control = useFieldControl(description);
+
+ return (
+ <Field
+ orientation="horizontal"
+ data-invalid={control.invalid}
+ data-disabled={disabled}
+ >
+ <Checkbox
+ {...control.controlProps}
+ name={field.name}
+ checked={field.state.value}
+ onCheckedChange={(checked) => field.handleChange(checked)}
+ disabled={disabled}
+ />
+ <FieldContent>
+ <FieldLabel htmlFor={control.controlProps.id}>{label}</FieldLabel>
+ {control.messages}
+ </FieldContent>
+ </Field>
+ );
+}
+
+function SwitchField({
+ label,
+ description,
+ disabled,
+}: FieldText & { disabled?: boolean }) {
+ const field = useFieldContext<boolean>();
+ const control = useFieldControl(description);
+
+ return (
+ <Field
+ orientation="horizontal"
+ data-invalid={control.invalid}
+ data-disabled={disabled}
+ >
+ <FieldContent>
+ <FieldLabel htmlFor={control.controlProps.id}>{label}</FieldLabel>
+ {control.messages}
+ </FieldContent>
+ <Switch
+ {...control.controlProps}
+ name={field.name}
+ checked={field.state.value}
+ onCheckedChange={(checked) => field.handleChange(checked)}
+ disabled={disabled}
+ />
+ </Field>
+ );
+}
+
+/** A submit button whose pending state comes from the form's `isSubmitting`. */
+function SubmitButton(
+ props: Omit<ComponentProps<typeof Button>, "type" | "pending">,
+) {
+ const form = useFormContext();
+
+ return (
+ <form.Subscribe selector={(state) => state.isSubmitting}>
+ {(isSubmitting) => (
+ <Button {...props} type="submit" pending={isSubmitting} />
+ )}
+ </form.Subscribe>
+ );
+}
+
+/**
+ * The `<form>` element for an app form. `noValidate` makes the Zod schema the
+ * only validator. A failed submit moves focus to the first invalid field,
+ * which the browser did before `noValidate` turned its validation off.
+ */
+function Form({
+ children,
+ ...props
+}: Omit<ComponentProps<"form">, "onSubmit" | "noValidate">) {
+ const form = useFormContext();
+
+ return (
+ <form
+ {...props}
+ noValidate
+ onSubmit={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ const element = event.currentTarget;
+ form.handleSubmit().then(
+ () => {
+ if (form.state.isValid) return;
+ // Wait a frame so the fields render their aria-invalid state.
+ requestAnimationFrame(() => {
+ element
+ .querySelector<HTMLElement>('[aria-invalid="true"]')
+ ?.focus();
+ });
+ },
+ // `onSubmit` handlers run mutations, and the mutation cache already
+ // toasts a failed mutation.
+ () => {},
+ );
+ }}
+ >
+ {children}
+ </form>
+ );
+}
+
+export const { useAppForm } = createFormHook({
+ fieldContext,
+ formContext,
+ fieldComponents: {
+ TextField,
+ TextareaField,
+ SelectField,
+ CheckboxField,
+ SwitchField,
+ },
+ formComponents: { Form, SubmitButton },
+});
diff --git a/src/client/components/ui/combobox.tsx b/src/client/components/ui/combobox.tsx
index 7c910e61..2ba35098 100644
--- a/src/client/components/ui/combobox.tsx
+++ b/src/client/components/ui/combobox.tsx
@@ -63,6 +63,11 @@ function ComboboxInput({
<ComboboxPrimitive.Input
render={<InputGroupInput disabled={disabled} />}
{...props}
+ onKeyDown={(event) => {
+ // Enter picks the highlighted item. It never submits the form.
+ if (event.key === "Enter") event.preventDefault();
+ props.onKeyDown?.(event);
+ }}
/>
<InputGroupAddon align="inline-end">
{showTrigger && (
@@ -70,6 +75,8 @@ function ComboboxInput({
size="icon-xs"
variant="ghost"
render={<ComboboxTrigger />}
+ // The input opens the list, so the chevron is not a Tab stop.
+ tabIndex={-1}
data-slot="input-group-button"
className="group-has-data-[slot=combobox-clear]/input-group:hidden data-pressed:bg-transparent"
disabled={disabled}
diff --git a/src/client/components/ui/field.tsx b/src/client/components/ui/field.tsx
index 5577f20c..a19df6d3 100644
--- a/src/client/components/ui/field.tsx
+++ b/src/client/components/ui/field.tsx
@@ -131,7 +131,7 @@ function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
<p
data-slot="field-description"
className={cn(
- "text-left text-sm leading-normal font-normal text-muted-foreground group-has-data-horizontal/field:text-balance [[data-variant=legend]+&]:-mt-1.5",
+ "text-left text-xs leading-normal font-normal text-muted-foreground group-has-data-horizontal/field:text-balance [[data-variant=legend]+&]:-mt-1.5",
"last:mt-0 nth-last-2:-mt-1",
"[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
className,
diff --git a/src/client/features/keywords/hooks/useKeywordControlsForm.ts b/src/client/features/keywords/hooks/useKeywordControlsForm.ts
index 3b3f0cf5..fd6ed30b 100644
--- a/src/client/features/keywords/hooks/useKeywordControlsForm.ts
+++ b/src/client/features/keywords/hooks/useKeywordControlsForm.ts
@@ -1,5 +1,5 @@
import { useEffect } from "react";
-import { useForm } from "@tanstack/react-form";
+import { useAppForm } from "@/client/components/form/useAppForm";
import {
createFormValidationErrors,
shouldValidateFieldOnChange,
@@ -62,7 +62,7 @@ export function useKeywordControlsForm(
input: UseKeywordControlsFormInput,
onSubmit: (value: KeywordControlsValues) => void,
) {
- const form = useForm({
+ const form = useAppForm({
defaultValues: {
keyword: input.keywordInput,
locationCode: input.locationCode,
diff --git a/src/client/features/keywords/page/KeywordSearchOptions.tsx b/src/client/features/keywords/page/KeywordSearchOptions.tsx
index 15b4f443..5dd14969 100644
--- a/src/client/features/keywords/page/KeywordSearchOptions.tsx
+++ b/src/client/features/keywords/page/KeywordSearchOptions.tsx
@@ -1,11 +1,17 @@
-import { useState } from "react";
+import { useId, useState } from "react";
import { SlidersHorizontal } from "lucide-react";
-import { DialogField, FormDialog } from "@/client/components/FormDialog";
+import { FormDialog } from "@/client/components/FormDialog";
import {
- isResultLimit,
- normalizeKeywordMode,
-} from "@/client/features/keywords/keywordSearchParams";
-import { RESULT_LIMITS } from "@/client/features/keywords/keywordResearchTypes";
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldLabel,
+} from "@/client/components/ui/field";
+import { Switch } from "@/client/components/ui/switch";
+import {
+ RESULT_LIMITS,
+ type KeywordMode,
+} from "@/client/features/keywords/keywordResearchTypes";
import { isLabsLocationCode } from "@/client/features/keywords/locations";
import type { KeywordResearchControllerState } from "./types";
@@ -13,6 +19,18 @@ type Props = {
controller: KeywordResearchControllerState;
};
+const RESULT_ITEMS = RESULT_LIMITS.map((limit) => ({
+ value: limit,
+ label: `${limit} results`,
+}));
+
+const MODE_ITEMS: { value: KeywordMode; label: string }[] = [
+ { value: "auto", label: "Auto" },
+ { value: "suggestions", label: "Phrase match" },
+ { value: "ideas", label: "Category ideas" },
+ { value: "related", label: "People also search for" },
+];
+
const GOOGLE_ADS_ONLY_NOTE =
"Not available for countries served from Google Ads data.";
@@ -58,51 +76,22 @@ export function KeywordSearchOptions({ controller }: Props) {
</button>
}
>
- <controlsForm.Field name="resultLimit">
+ <controlsForm.AppField name="resultLimit">
{(field) => (
- <DialogField label="Results">
- <select
- className="select select-bordered w-full"
- value={field.state.value}
- onChange={(event) => {
- const next = Number(event.target.value);
- field.handleChange(isResultLimit(next) ? next : 150);
- }}
- >
- {RESULT_LIMITS.map((limit) => (
- <option key={limit} value={limit}>
- {limit} results
- </option>
- ))}
- </select>
- </DialogField>
+ <field.SelectField label="Results" items={RESULT_ITEMS} />
)}
- </controlsForm.Field>
+ </controlsForm.AppField>
- <controlsForm.Field name="mode">
+ <controlsForm.AppField name="mode">
{(field) => (
- <DialogField
+ <field.SelectField
label="Keyword source"
- help={labs ? undefined : GOOGLE_ADS_ONLY_NOTE}
- >
- <select
- className="select select-bordered w-full"
- value={field.state.value}
- disabled={!labs}
- onChange={(event) =>
- field.handleChange(
- normalizeKeywordMode(event.target.value),
- )
- }
- >
- <option value="auto">Auto</option>
- <option value="suggestions">Phrase match</option>
- <option value="ideas">Category ideas</option>
- <option value="related">People also search for</option>
- </select>
- </DialogField>
+ description={labs ? undefined : GOOGLE_ADS_ONLY_NOTE}
+ items={MODE_ITEMS}
+ disabled={!labs}
+ />
)}
- </controlsForm.Field>
+ </controlsForm.AppField>
<controlsForm.Field name="clickstream">
{(field) => (
@@ -152,28 +141,23 @@ function ToggleRow({
disabled: boolean;
onChange: (checked: boolean) => void;
}) {
+ const id = useId();
+
return (
- <label
- className={`flex items-start justify-between gap-4 ${disabled ? "cursor-not-allowed" : "cursor-pointer"}`}
- >
- <span className="flex flex-col gap-0.5">
- <span
- className={`text-sm font-medium ${disabled ? "text-base-content/40" : ""}`}
- >
- {label}
- </span>
+ <Field orientation="horizontal" data-disabled={disabled}>
+ <FieldContent>
+ <FieldLabel htmlFor={id}>{label}</FieldLabel>
{help ? (
- <span className="text-xs text-base-content/60">{help}</span>
+ <FieldDescription id={`${id}-description`}>{help}</FieldDescription>
) : null}
- </span>
- <input
- type="checkbox"
- role="switch"
- className="toggle toggle-sm toggle-primary mt-0.5 shrink-0"
+ </FieldContent>
+ <Switch
+ id={id}
+ aria-describedby={help ? `${id}-description` : undefined}
checked={checked}
disabled={disabled}
- onChange={(event) => onChange(event.target.checked)}
+ onCheckedChange={onChange}
/>
- </label>
+ </Field>
);
}
diff --git a/src/client/features/projects/ProjectGeneralSettings.tsx b/src/client/features/projects/ProjectGeneralSettings.tsx
index dfda4f53..9e71b139 100644
--- a/src/client/features/projects/ProjectGeneralSettings.tsx
+++ b/src/client/features/projects/ProjectGeneralSettings.tsx
@@ -3,6 +3,9 @@ import { projectsQueryOptions } from "@/client/features/projects/projectQueries"
import { useNavigate } from "@tanstack/react-router";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
+import { z } from "zod";
+import { revalidateLogic } from "@tanstack/react-form";
+import { useAppForm } from "@/client/components/form/useAppForm";
import { QueryError, QueryState } from "@/client/components/QueryState";
import { ProjectMarketFields } from "@/client/features/projects/ProjectMarketFields";
import {
@@ -37,23 +40,23 @@ export function ProjectGeneralSettings({ projectId }: { projectId: string }) {
);
}
+const generalSchema = z.object({
+ name: z.string().trim().min(1, "Enter a project name."),
+ domain: z.string(),
+ market: z.object({ locationCode: z.number(), languageCode: z.string() }),
+});
+
function GeneralSection({ project }: { project: ProjectSummary }) {
const queryClient = useQueryClient();
- const [name, setName] = React.useState(project.name);
- const [domain, setDomain] = React.useState(project.domain ?? "");
- const [market, setMarket] = React.useState({
- locationCode: project.locationCode,
- languageCode: project.languageCode,
- });
const updateMutation = useMutation({
- mutationFn: () =>
+ mutationFn: (values: z.infer<typeof generalSchema>) =>
updateProject({
data: {
projectId: project.id,
- name: name.trim(),
- domain: domain.trim() || undefined,
- ...market,
+ name: values.name.trim(),
+ domain: values.domain.trim() || undefined,
+ ...values.market,
},
}),
onSuccess: async () => {
@@ -64,69 +67,80 @@ function GeneralSection({ project }: { project: ProjectSummary }) {
},
});
- const isDirty =
- name.trim() !== project.name ||
- (domain.trim() || "") !== (project.domain ?? "") ||
- market.locationCode !== project.locationCode ||
- market.languageCode !== project.languageCode;
-
- const handleSubmit = (event: React.FormEvent) => {
- event.preventDefault();
- if (updateMutation.isPending) return;
- if (!name.trim()) {
- toast.error("Project name is required");
- return;
- }
- updateMutation.mutate();
- };
+ const form = useAppForm({
+ defaultValues: {
+ name: project.name,
+ domain: project.domain ?? "",
+ market: {
+ locationCode: project.locationCode,
+ languageCode: project.languageCode,
+ },
+ },
+ validationLogic: revalidateLogic(),
+ validators: { onDynamic: generalSchema },
+ onSubmit: async ({ value, formApi }) => {
+ await updateMutation.mutateAsync(value);
+ // The saved values are the new baseline, so Save disables again. An edit
+ // made while the save ran replaces the values object, and then the form
+ // keeps that edit and Save stays on.
+ if (formApi.state.values === value) formApi.reset(value);
+ },
+ });
return (
<section className="space-y-3">
<h2 className="text-sm font-medium text-base-content/50">General</h2>
- <form onSubmit={handleSubmit} className="space-y-4">
- <label className="flex flex-col gap-1.5 text-sm">
- <span className="font-medium">Name</span>
- <input
- type="text"
- value={name}
- onChange={(event) => setName(event.target.value)}
- maxLength={120}
- className="input input-bordered w-full"
- />
- </label>
+ <form.AppForm>
+ <form.Form className="flex flex-col gap-4">
+ <form.AppField name="name">
+ {(field) => (
+ <field.TextField label="Name" maxLength={120} required />
+ )}
+ </form.AppField>
- <label className="flex flex-col gap-1.5 text-sm">
- <span className="font-medium">
- Domain <span className="text-base-content/50">(optional)</span>
- </span>
- <input
- type="text"
- value={domain}
- onChange={(event) => setDomain(event.target.value)}
- placeholder="example.com"
- maxLength={255}
- className="input input-bordered w-full"
- />
- </label>
+ <form.AppField name="domain">
+ {(field) => (
+ <field.TextField
+ label={
+ <>
+ Domain{" "}
+ <span className="font-normal text-muted-foreground">
+ (optional)
+ </span>
+ </>
+ }
+ placeholder="example.com"
+ maxLength={255}
+ />
+ )}
+ </form.AppField>
- <div className="flex flex-col gap-1.5">
- <ProjectMarketFields value={market} onChange={setMarket} />
- <span className="text-xs text-base-content/50">
- Keyword, SERP, and domain data uses this country and language unless
- a call asks for a different one.
- </span>
- </div>
+ <div className="flex flex-col gap-1.5">
+ <form.Field name="market">
+ {(field) => (
+ <ProjectMarketFields
+ value={field.state.value}
+ onChange={field.handleChange}
+ />
+ )}
+ </form.Field>
+ <span className="text-xs text-base-content/50">
+ Keyword, SERP, and domain data uses this country and language
+ unless a call asks for a different one.
+ </span>
+ </div>
- <div className="flex justify-end">
- <button
- type="submit"
- className="btn btn-primary btn-sm"
- disabled={updateMutation.isPending || !isDirty}
- >
- Save changes
- </button>
- </div>
- </form>
+ <div className="flex justify-end">
+ <form.Subscribe selector={(state) => state.isDefaultValue}>
+ {(isDefaultValue) => (
+ <form.SubmitButton disabled={isDefaultValue}>
+ Save changes
+ </form.SubmitButton>
+ )}
+ </form.Subscribe>
+ </div>
+ </form.Form>
+ </form.AppForm>
</section>
);
}
diff --git a/src/client/features/projects/ProjectMarketFields.tsx b/src/client/features/projects/ProjectMarketFields.tsx
index e94e7477..8e91ba42 100644
--- a/src/client/features/projects/ProjectMarketFields.tsx
+++ b/src/client/features/projects/ProjectMarketFields.tsx
@@ -1,9 +1,40 @@
-import { LocationSelect } from "@/client/components/LocationSelect";
+import { useId } from "react";
+import {
+ Combobox,
+ ComboboxContent,
+ ComboboxEmpty,
+ ComboboxInput,
+ ComboboxItem,
+ ComboboxList,
+} from "@/client/components/ui/combobox";
+import { Field, FieldLabel } from "@/client/components/ui/field";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/client/components/ui/select";
import {
getLanguageCode,
getLanguageOptions,
} from "@/client/features/keywords/locations";
import type { ProjectMarket } from "@/client/features/projects/types";
+import { LOCATION_OPTIONS } from "@/shared/keyword-locations";
+
+type LocationOption = (typeof LOCATION_OPTIONS)[number];
+
+// Matches the start of the name or of any word in it, so "uni" finds United
+// States, not Tunisia, and "united states" still finds United States.
+function matchesCountry(option: LocationOption, query: string) {
+ const needle = query.trim().toLowerCase();
+ const label = option.label.toLowerCase();
+ return (
+ label.startsWith(needle) ||
+ label.split(/[\s-]+/).some((word) => word.startsWith(needle)) ||
+ option.shortLabel.toLowerCase().startsWith(needle)
+ );
+}
/**
* The project's default market: country plus the language served for it.
@@ -20,43 +51,78 @@ export function ProjectMarketFields({
onChange: (market: ProjectMarket) => void;
hideLanguageOnMobile?: boolean;
}) {
- const languageOptions = getLanguageOptions(value.locationCode);
+ const countryId = useId();
+ const languageId = useId();
+ const country =
+ LOCATION_OPTIONS.find((option) => option.code === value.locationCode) ??
+ null;
+ const languageItems = getLanguageOptions(value.locationCode).map(
+ (option) => ({ value: option.code, label: option.label }),
+ );
+ // Most countries have exactly one language DataForSEO serves, so the
+ // select is only a real choice where there's more than one.
+ const languageDisabled = languageItems.length <= 1;
return (
<div className="grid gap-4 sm:grid-cols-2">
- <label className="flex flex-col gap-1.5 text-sm">
- <span className="font-medium">Country</span>
- <LocationSelect
- value={value.locationCode}
- onChange={(locationCode) =>
+ <Field>
+ <FieldLabel htmlFor={countryId}>Country</FieldLabel>
+ <Combobox
+ items={LOCATION_OPTIONS}
+ value={country}
+ itemToStringLabel={(option) => option.label}
+ autoHighlight
+ filter={matchesCountry}
+ onValueChange={(option) => {
+ if (!option) return;
onChange({
- locationCode,
- languageCode: getLanguageCode(locationCode),
- })
- }
- />
- </label>
- <label
- className={`${hideLanguageOnMobile ? "hidden sm:flex" : "flex"} flex-col gap-1.5 text-sm`}
+ locationCode: option.code,
+ languageCode: getLanguageCode(option.code),
+ });
+ }}
+ >
+ <ComboboxInput
+ id={countryId}
+ className="w-full"
+ placeholder="Search countries"
+ />
+ <ComboboxContent>
+ <ComboboxEmpty>No countries match.</ComboboxEmpty>
+ <ComboboxList>
+ {(option: LocationOption) => (
+ <ComboboxItem key={option.code} value={option}>
+ {option.label}
+ </ComboboxItem>
+ )}
+ </ComboboxList>
+ </ComboboxContent>
+ </Combobox>
+ </Field>
+ <Field
+ className={hideLanguageOnMobile ? "hidden sm:flex" : undefined}
+ data-disabled={languageDisabled}
>
- <span className="font-medium">Language</span>
- <select
+ <FieldLabel htmlFor={languageId}>Language</FieldLabel>
+ <Select
+ items={languageItems}
value={value.languageCode}
- onChange={(event) =>
- onChange({ ...value, languageCode: event.target.value })
- }
- // Most countries have exactly one language DataForSEO serves, so the
- // select is only a real choice where there's more than one.
- disabled={languageOptions.length <= 1}
- className="select select-bordered w-full"
+ onValueChange={(languageCode) => {
+ if (languageCode) onChange({ ...value, languageCode });
+ }}
+ disabled={languageDisabled}
>
- {languageOptions.map((option) => (
- <option key={option.code} value={option.code}>
- {option.label}
- </option>
- ))}
- </select>
- </label>
+ <SelectTrigger id={languageId} className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {languageItems.map((item) => (
+ <SelectItem key={item.value} value={item.value}>
+ {item.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
</div>
);
}
diff --git a/src/client/features/reports/ReportTemplateForm.tsx b/src/client/features/reports/ReportTemplateForm.tsx
index 52fe4f8f..8aae3649 100644
--- a/src/client/features/reports/ReportTemplateForm.tsx
+++ b/src/client/features/reports/ReportTemplateForm.tsx
@@ -1,17 +1,16 @@
-import { useForm } from "@tanstack/react-form";
+import { revalidateLogic } from "@tanstack/react-form";
import { useMutation } from "@tanstack/react-query";
-import { Loader2 } from "lucide-react";
import { toast } from "sonner";
import { z } from "zod";
+import { useAppForm } from "@/client/components/form/useAppForm";
import { Modal } from "@/client/components/Modal";
-import { getStandardErrorMessage } from "@/client/lib/error-messages";
-import { getFieldError } from "@/client/lib/forms";
+import { Button } from "@/client/components/ui/button";
import { captureClientEvent } from "@/client/lib/posthog";
import { saveReportTemplate } from "@/serverFunctions/reportTemplates";
import type { ReportTemplate } from "@/types/schemas/report-templates";
// One form for create and edit. Shape only, as at every other boundary: the
-// caps come back from the service with their copy and show in the alert.
+// caps come back from the service with their copy and show in a toast.
const formSchema = z.object({
name: z.string().trim().min(1, "Give the template a name."),
description: z
@@ -43,10 +42,9 @@ export function ReportTemplateForm({
onSaved: () => void;
}) {
const saveMutation = useMutation({
- meta: { errorToast: false },
// A refusal (duplicate name, the cap) comes back as `{ ok: false }` rather
// than an error, because thrown errors reach the client stripped to their
- // code. Rethrowing it here gives the form one error branch.
+ // code. Rethrowing it here lets the mutation cache toast its message.
mutationFn: async (values: z.infer<typeof formSchema>) => {
const result = await saveReportTemplate({
data: { projectId, templateId: template?.id, ...values },
@@ -65,18 +63,15 @@ export function ReportTemplateForm({
},
});
- const error = saveMutation.error
- ? getStandardErrorMessage(saveMutation.error, "Failed to save the template")
- : null;
-
- const form = useForm({
+ const form = useAppForm({
defaultValues: {
name: template?.name ?? "",
description: template?.description ?? "",
instructions: template?.instructions ?? "",
},
- validators: { onSubmit: formSchema },
- onSubmit: ({ value }) => saveMutation.mutate(value),
+ validationLogic: revalidateLogic(),
+ validators: { onDynamic: formSchema },
+ onSubmit: ({ value }) => saveMutation.mutateAsync(value),
});
return (
@@ -85,113 +80,51 @@ export function ReportTemplateForm({
{template ? "Edit template" : "New template"}
</h3>
- <form
- className="space-y-4"
- onSubmit={(event) => {
- event.preventDefault();
- void form.handleSubmit();
- }}
- >
- <form.Field name="name">
- {(field) => (
- <Labelled
- label="Name"
- error={getFieldError(field.state.meta.errors)}
- >
- <input
- type="text"
- className="input input-bordered w-full"
+ <form.AppForm>
+ <form.Form className="flex flex-col gap-4">
+ <form.AppField name="name">
+ {(field) => (
+ <field.TextField
+ label="Name"
placeholder="Monthly client check-in"
- value={field.state.value}
- onChange={(event) => field.handleChange(event.target.value)}
+ required
/>
- </Labelled>
- )}
- </form.Field>
+ )}
+ </form.AppField>
- <form.Field name="description">
- {(field) => (
- <Labelled
- label="Description"
- hint="One line saying when to use it. This is what an agent reads to decide."
- error={getFieldError(field.state.meta.errors)}
- >
- <input
- type="text"
- className="input input-bordered w-full"
+ <form.AppField name="description">
+ {(field) => (
+ <field.TextField
+ label="Description"
+ description="One line saying when to use it. This is what an agent reads to decide."
placeholder="The monthly update we send retainer clients."
- value={field.state.value}
- onChange={(event) => field.handleChange(event.target.value)}
+ required
/>
- </Labelled>
- )}
- </form.Field>
+ )}
+ </form.AppField>
- <form.Field name="instructions">
- {(field) => (
- <Labelled
- label="Instructions"
- hint="Brand voice for the whole project lives in Context › Writing preferences."
- error={getFieldError(field.state.meta.errors)}
- >
- <textarea
- className="textarea textarea-bordered h-56 w-full font-mono text-xs leading-relaxed"
+ <form.AppField name="instructions">
+ {(field) => (
+ <field.TextareaField
+ label="Instructions"
+ description="Brand voice for the whole project lives in Context › Writing preferences."
+ className="h-56 font-mono leading-relaxed md:text-xs"
placeholder={INSTRUCTIONS_PLACEHOLDER}
- value={field.state.value}
- onChange={(event) => field.handleChange(event.target.value)}
+ required
/>
- </Labelled>
- )}
- </form.Field>
+ )}
+ </form.AppField>
- {error ? (
- <div className="alert alert-error">
- <span className="text-sm">{error}</span>
+ <div className="flex justify-end gap-2">
+ <Button type="button" variant="ghost" onClick={onClose}>
+ Cancel
+ </Button>
+ <form.SubmitButton>
+ {template ? "Save changes" : "Create template"}
+ </form.SubmitButton>
</div>
- ) : null}
-
- <div className="flex justify-end gap-2">
- <button
- type="button"
- className="btn btn-ghost btn-sm"
- onClick={onClose}
- >
- Cancel
- </button>
- <button
- type="submit"
- className="btn btn-primary btn-sm gap-1"
- disabled={saveMutation.isPending}
- >
- {saveMutation.isPending ? (
- <Loader2 className="size-3 animate-spin" />
- ) : null}
- {template ? "Save changes" : "Create template"}
- </button>
- </div>
- </form>
+ </form.Form>
+ </form.AppForm>
</Modal>
);
}
-
-function Labelled({
- label,
- hint,
- error,
- children,
-}: {
- label: string;
- hint?: string;
- error: string | null;
- children: React.ReactNode;
-}) {
- return (
- // The wrapping label associates the text with the control, so no id plumbing.
- <label className="block space-y-1.5">
- <span className="block text-sm font-medium">{label}</span>
- {children}
- {hint ? <p className="text-xs text-base-content/60">{hint}</p> : null}
- {error ? <p className="text-sm text-error">{error}</p> : null}
- </label>
- );
-}
diff --git a/src/client/styles/app.css b/src/client/styles/app.css
index 634732aa..1a3249d8 100644
--- a/src/client/styles/app.css
+++ b/src/client/styles/app.css
@@ -242,10 +242,13 @@ body {
overflow: hidden;
}
-/* Prevent Safari mobile from zooming on input focus (requires 16px minimum) */
-input,
-textarea,
-select {
+/* Prevent Safari mobile from zooming on input focus (requires 16px minimum).
+ This rule is outside a layer, so it beats every utility. shadcn controls
+ (the ones with data-slot) are left out: they are 16px below md and 14px
+ from md up through their own utilities. */
+input:not([data-slot]),
+textarea:not([data-slot]),
+select:not([data-slot]) {
@apply text-base;
}