Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Fixes render validation and use controller for forms

Ian MacCallumfd1305af7528
diff --git a/apps/web/ui/partners/groups/design/fields/form-control.tsx b/apps/web/ui/partners/groups/design/fields/form-control.tsx
index 878af46230..06dc7970bc 100644
--- a/apps/web/ui/partners/groups/design/fields/form-control.tsx
+++ b/apps/web/ui/partners/groups/design/fields/form-control.tsx
@@ -1,23 +1,47 @@
+import { cn } from "@dub/utils";
import { PropsWithChildren } from "react";
export type FormControlProps = PropsWithChildren<{
label: string;
required?: boolean;
-}>
+ helperText?: string;
+ error?: string;
+}>;
-export const FormControl = ({ label, required, children }: FormControlProps) => {
+export const FormControl = ({
+ label,
+ required,
+ children,
+ error,
+ helperText,
+}: FormControlProps) => {
return (
<label>
<div className="flex items-center gap-1.5">
- <span className="text-sm font-medium text-content-emphasis">{label}</span>
+ <span className="text-content-emphasis text-sm font-medium">
+ {label}
+ </span>
{required && (
- <span className="rounded-md text-xs font-semibold text-orange-600 bg-orange-100 px-1 min-h-4">Required</span>
+ <span className="min-h-4 rounded-md bg-orange-100 px-1 text-xs font-semibold text-orange-600">
+ Required
+ </span>
)}
</div>
<div className="mt-2">
{children}
+
+ {(error || helperText) && (
+ <div
+ className={cn(
+ "mt-2 text-xs",
+ error ? "text-red-500" : "text-neutral-500",
+ )}
+ >
+ {error || helperText}
+ </div>
+ )}
</div>
</label>
);
-}
+};
diff --git a/apps/web/ui/partners/groups/design/fields/multiple-choice-field.tsx b/apps/web/ui/partners/groups/design/fields/multiple-choice-field.tsx
index e5ff098a93..5af5a7e347 100644
--- a/apps/web/ui/partners/groups/design/fields/multiple-choice-field.tsx
+++ b/apps/web/ui/partners/groups/design/fields/multiple-choice-field.tsx
@@ -1,124 +1,133 @@
import { programApplicationFormMultipleChoiceFieldSchema } from "@/lib/zod/schemas/program-application-form";
+import { Checkbox, RadioGroup, RadioGroupItem } from "@dub/ui";
+import { Controller, useFormContext } from "react-hook-form";
import { z } from "zod";
import { FormControl } from "./form-control";
-import { cn } from "@dub/utils";
-import { useFormContext } from "react-hook-form";
-import { RadioGroup, RadioGroupItem, Checkbox } from "@dub/ui";
-import { useCallback } from "react";
-type MultipleChoiceFieldData = z.infer<typeof programApplicationFormMultipleChoiceFieldSchema>
+type MultipleChoiceFieldData = z.infer<
+ typeof programApplicationFormMultipleChoiceFieldSchema
+>;
type MultipleChoiceFieldProps = {
field: MultipleChoiceFieldData;
keyPath?: string;
preview?: boolean;
-}
+};
-export function MultipleChoiceField({ field, keyPath: keyPathProp, preview }: MultipleChoiceFieldProps) {
- const { getFieldState, watch, setValue } = useFormContext<any>();
+export function MultipleChoiceField({
+ field,
+ keyPath: keyPathProp,
+ preview,
+}: MultipleChoiceFieldProps) {
+ const { getFieldState, watch, setValue, control } = useFormContext<any>();
const keyPath = keyPathProp ? `${keyPathProp}.value` : "value";
const state = getFieldState(keyPath);
const value = watch(keyPath);
- const error = !!state.error
-
- const isOptionSelected = useCallback((optionValue: string) => {
- if (field.data.multiple) {
- return value?.includes(optionValue);
- }
- return value === optionValue;
- }, [field.data.multiple, value]);
-
- const selectOption = useCallback((optionValue: string) => {
- if (field.data.multiple) {
- setValue(keyPath, [...(value || []), optionValue]);
- } else {
- setValue(keyPath, optionValue);
- }
- }, [field.data.multiple, setValue, keyPath, value]);
-
- const deselectOption = useCallback((optionValue: string) => {
- if (field.data.multiple) {
- if (Array.isArray(value) && value.includes(optionValue)) {
- setValue(keyPath, value.filter((v) => v !== optionValue));
- }
- } else {
- if (value === optionValue) {
- setValue(keyPath, "");
- }
- }
- }, [field.data.multiple, value, setValue, keyPath]);
+ const options = field.data.options;
let content: React.ReactNode;
if (field.data.multiple) {
content = (
- <div>
- <div className="space-y-2">
- {field.data.options.map((option) => {
- const isSelected = isOptionSelected(option.value);
+ <Controller
+ control={control}
+ name={keyPath}
+ rules={{
+ validate: (val: any) => {
+ if ((field.required && !Array.isArray(val)) || !val.length) {
+ return "Select all that apply";
+ }
+ return true;
+ },
+ }}
+ render={({ field }) => (
+ <div className="space-y-2">
+ {options.map((option) => {
+ const isSelected = value?.includes(option.value);
- return (
+ return (
+ <label
+ key={option.id}
+ className="flex w-full items-center gap-2.5 text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ >
+ <Checkbox
+ id={option.id}
+ checked={isSelected}
+ className="border-border-default size-4 rounded focus:border-[var(--brand)] focus:ring-[var(--brand)] focus-visible:border-[var(--brand)] focus-visible:ring-[var(--brand)] data-[state=checked]:bg-black data-[state=indeterminate]:bg-black"
+ onCheckedChange={(checked) => {
+ if (checked) {
+ setValue(keyPath, [...(value || []), option.value]);
+ } else {
+ if (
+ Array.isArray(value) &&
+ value.includes(option.value)
+ ) {
+ setValue(
+ keyPath,
+ value.filter((v) => v !== option.value),
+ );
+ }
+ }
+ }}
+ />
+
+ <span className="text-content-emphasis text-sm">
+ {option.value}
+ </span>
+ </label>
+ );
+ })}
+ </div>
+ )}
+ />
+ );
+ } else {
+ content = (
+ <Controller
+ control={control}
+ name={keyPath}
+ rules={{
+ validate: (val: any) => {
+ if (field.required && (!val || val === "")) {
+ return "Please select an option";
+ }
+ return true;
+ },
+ }}
+ render={({ field }) => (
+ <RadioGroup
+ value={typeof value === "string" ? value : ""}
+ onValueChange={(newValue) => setValue(keyPath, newValue)}
+ className="space-y-2"
+ >
+ {options.map((option) => (
<label
key={option.id}
- className="w-full flex items-center gap-2.5 text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ className="flex items-center gap-2.5 leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
- <Checkbox
+ <RadioGroupItem
+ value={option.value}
id={option.id}
- checked={isSelected}
- className="border-border-default size-4 rounded data-[state=checked]:bg-black data-[state=indeterminate]:bg-black focus:border-[var(--brand)] focus:ring-[var(--brand)] focus-visible:border-[var(--brand)] focus-visible:ring-[var(--brand)]"
- onCheckedChange={(checked) => {
- if (checked) {
- selectOption(option.value);
- } else {
- deselectOption(option.value);
- }
- }}
+ className="focus:border-[var(--brand)] focus:ring-[var(--brand)]"
/>
- <span className="text-sm text-content-emphasis">
+ <span className="text-content-emphasis text-sm">
{option.value}
</span>
</label>
- );
- })}
- </div>
-
- <div className={cn(
- "transition-colors duration-75 text-xs mt-2",
- error ? "text-red-500" : "text-neutral-500"
- )}>Select all that apply</div>
- </div>
- )
- } else {
- content = (
- <div>
- <RadioGroup
- value={typeof value === "string" ? value : ""}
- onValueChange={(newValue) => setValue(keyPath, newValue)}
- className="space-y-2"
- >
- {field.data.options.map((option) => (
- <label key={option.id} className="flex items-center gap-2.5 leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
- <RadioGroupItem value={option.value} id={option.id} className="focus:border-[var(--brand)] focus:ring-[var(--brand)]" />
-
- <span className="text-sm text-content-emphasis">
- {option.value}
- </span>
- </label>
- ))}
- </RadioGroup>
-
- {error && (
- <div className="text-red-500 text-xs mt-2">Select an option</div>
+ ))}
+ </RadioGroup>
)}
- </div>
- )
+ />
+ );
}
return (
<FormControl
label={field.label}
required={field.required}
+ helperText={field.data.multiple ? "Select all that apply" : undefined}
+ error={state.error?.message}
>
{content}
</FormControl>
diff --git a/apps/web/ui/partners/groups/design/fields/select-field.tsx b/apps/web/ui/partners/groups/design/fields/select-field.tsx
index 405f44e64d..4a61a81717 100644
--- a/apps/web/ui/partners/groups/design/fields/select-field.tsx
+++ b/apps/web/ui/partners/groups/design/fields/select-field.tsx
@@ -1,11 +1,11 @@
+import { programApplicationFormSelectFieldSchema } from "@/lib/zod/schemas/program-application-form";
import { Combobox } from "@dub/ui";
-import { programApplicationFormSelectFieldSchema, programApplicationFormSelectFieldWithValueSchema } from "@/lib/zod/schemas/program-application-form";
+import { cn } from "@dub/utils";
+import { Controller, useFormContext } from "react-hook-form";
import { z } from "zod";
import { FormControl } from "./form-control";
-import { useFormContext } from "react-hook-form";
-import { cn } from "@dub/utils";
-type SelectFieldData = z.infer<typeof programApplicationFormSelectFieldSchema>
+type SelectFieldData = z.infer<typeof programApplicationFormSelectFieldSchema>;
export function SelectField({
keyPath: keyPathProp,
@@ -16,42 +16,56 @@ export function SelectField({
field: SelectFieldData;
preview?: boolean;
}) {
- const { watch, getFieldState, setValue } = useFormContext<any>();
+ const { getFieldState, control } = useFormContext<any>();
const keyPath = keyPathProp ? `${keyPathProp}.value` : "value";
const state = getFieldState(keyPath);
- const error = !!state.error
- const value = watch(keyPath);
+ const error = !!state.error;
const options = field.data.options.map((option) => ({
label: option.value,
value: option.value,
- }))
+ }));
return (
<FormControl
label={field.label}
required={field.required}
+ error={state.error?.message}
>
- <Combobox
- selected={options.find((o) => o.value === value) ?? null}
- setSelected={(option) => {
- if (!option) return;
- setValue(keyPath, option.value);
- }}
- options={options}
- caret={true}
- placeholder="Select"
- matchTriggerWidth
- buttonProps={{
- className: cn(
- "mt-1.5 w-full justify-start border-neutral-300 px-3",
- "data-[state=open]:ring-1 data-[state=open]:ring-neutral-500 data-[state=open]:border-neutral-500",
- "focus:ring-1 focus:ring-neutral-500 focus:border-neutral-500 focus:border-[var(--brand)] focus:ring-[var(--brand)] transition-none",
- !value && "text-neutral-400",
- error && "border-red-500 ring-red-500 ring-1",
- ),
+ <Controller
+ control={control}
+ name={keyPath}
+ rules={{
+ validate: (val: any) => {
+ if (field.required && (!val || val === "")) {
+ return "Please select an option";
+ }
+ return true;
+ },
}}
- hideSearch
+ render={({ field }) => (
+ <Combobox
+ selected={options.find((o) => o.value === field.value) ?? null}
+ setSelected={(option) => {
+ if (!option) return;
+ field.onChange(option.value);
+ }}
+ options={options}
+ caret={true}
+ placeholder="Select"
+ matchTriggerWidth
+ buttonProps={{
+ className: cn(
+ "mt-1.5 w-full justify-start border-neutral-300 px-3",
+ "data-[state=open]:ring-1 data-[state=open]:ring-neutral-500 data-[state=open]:border-neutral-500",
+ "focus:ring-1 focus:ring-neutral-500 focus:border-neutral-500 focus:border-[var(--brand)] focus:ring-[var(--brand)] transition-none",
+ !field.value && "text-neutral-400",
+ error && "border-red-500 ring-red-500 ring-1",
+ ),
+ }}
+ hideSearch
+ />
+ )}
/>
</FormControl>
);
diff --git a/apps/web/ui/partners/groups/design/program-application-form.tsx b/apps/web/ui/partners/groups/design/program-application-form.tsx
index 20067abb49..a5ff8be03c 100644
--- a/apps/web/ui/partners/groups/design/program-application-form.tsx
+++ b/apps/web/ui/partners/groups/design/program-application-form.tsx
@@ -1,7 +1,24 @@
"use client";
-import { createProgramApplicationAction, PartnerData } from "@/lib/actions/partners/create-program-application";
-import { GroupWithFormDataProps, ProgramApplicationFormDataWithValues, ProgramProps } from "@/lib/types";
+import {
+ createProgramApplicationAction,
+ PartnerData,
+} from "@/lib/actions/partners/create-program-application";
+import {
+ GroupWithFormDataProps,
+ ProgramApplicationFormDataWithValues,
+ ProgramProps,
+} from "@/lib/types";
+import z from "@/lib/zod";
+import {
+ programApplicationFormFieldSchema,
+ programApplicationFormLongTextFieldWithValueSchema,
+ programApplicationFormMultipleChoiceFieldSchema,
+ programApplicationFormMultipleChoiceFieldWithValueSchema,
+ programApplicationFormSelectFieldWithValueSchema,
+ programApplicationFormShortTextFieldWithValueSchema,
+ programApplicationFormWebsiteAndSocialsFieldWithValueSchema,
+} from "@/lib/zod/schemas/program-application-form";
import { Button, useLocalStorage, useMediaQuery } from "@dub/ui";
import { cn } from "@dub/utils";
import { useSession } from "next-auth/react";
@@ -10,22 +27,21 @@ import { useRouter } from "next/navigation";
import { useEffect } from "react";
import { Controller, FormProvider, useForm } from "react-hook-form";
import { toast } from "sonner";
-import { programApplicationFormFieldSchema, programApplicationFormLongTextFieldWithValueSchema, programApplicationFormMultipleChoiceFieldSchema, programApplicationFormMultipleChoiceFieldWithValueSchema, programApplicationFormSelectFieldWithValueSchema, programApplicationFormShortTextFieldWithValueSchema, programApplicationFormWebsiteAndSocialsFieldWithValueSchema } from "@/lib/zod/schemas/program-application-form";
-import z from "@/lib/zod";
import { CountryCombobox } from "../../country-combobox";
import { ProgramApplicationFormField } from "./fields";
-
type FormData = {
name: string;
email: string;
country: string;
ageVerification: boolean;
termsAgreement: boolean;
- formData: ProgramApplicationFormDataWithValues
+ formData: ProgramApplicationFormDataWithValues;
};
-const formDataForApplicationFormData = (fields: z.infer<typeof programApplicationFormFieldSchema>[]): Data => {
+const formDataForApplicationFormData = (
+ fields: z.infer<typeof programApplicationFormFieldSchema>[],
+): ProgramApplicationFormDataWithValues => {
return {
fields: fields.map((field: any) => {
switch (field.type) {
@@ -33,23 +49,31 @@ const formDataForApplicationFormData = (fields: z.infer<typeof programApplicatio
return {
...field,
value: "",
- } as z.infer<typeof programApplicationFormShortTextFieldWithValueSchema>;
+ } as z.infer<
+ typeof programApplicationFormShortTextFieldWithValueSchema
+ >;
case "long-text":
return {
...field,
value: "",
- } as z.infer<typeof programApplicationFormLongTextFieldWithValueSchema>;
+ } as z.infer<
+ typeof programApplicationFormLongTextFieldWithValueSchema
+ >;
case "select":
return {
...field,
value: "",
} as z.infer<typeof programApplicationFormSelectFieldWithValueSchema>;
case "multiple-choice":
- const multipleChoiceField = field as z.infer<typeof programApplicationFormMultipleChoiceFieldSchema>;
+ const multipleChoiceField = field as z.infer<
+ typeof programApplicationFormMultipleChoiceFieldSchema
+ >;
return {
...field,
value: multipleChoiceField.data.multiple ? [] : "",
- } as z.infer<typeof programApplicationFormMultipleChoiceFieldWithValueSchema>;
+ } as z.infer<
+ typeof programApplicationFormMultipleChoiceFieldWithValueSchema
+ >;
case "website-and-socials":
return {
...field,
@@ -57,11 +81,13 @@ const formDataForApplicationFormData = (fields: z.infer<typeof programApplicatio
...data,
value: "",
})),
- } as z.infer<typeof programApplicationFormWebsiteAndSocialsFieldWithValueSchema>;
+ } as z.infer<
+ typeof programApplicationFormWebsiteAndSocialsFieldWithValueSchema
+ >;
}
- })
+ }),
} as any;
-}
+};
export function ProgramApplicationForm({
program,
@@ -86,7 +112,9 @@ export function ProgramApplicationForm({
country: "",
ageVerification: false,
termsAgreement: false,
- formData: formDataForApplicationFormData(group.applicationFormData?.fields ?? []),
+ formData: formDataForApplicationFormData(
+ group.applicationFormData?.fields ?? [],
+ ),
},
});
@@ -97,7 +125,7 @@ export function ProgramApplicationForm({
setError,
setValue,
formState: { errors, isSubmitting, isSubmitSuccessful },
- } = form
+ } = form;
useEffect(() => {
if (preview || !session?.user) return;
@@ -124,7 +152,10 @@ export function ProgramApplicationForm({
const { programApplicationId, programEnrollmentId, partnerData } = data;
- setSubmissionInfo({ name: partnerData.name, country: partnerData.country });
+ setSubmissionInfo({
+ name: partnerData.name,
+ country: partnerData.country,
+ });
const searchParams = new URLSearchParams({
applicationId: programApplicationId,
@@ -152,7 +183,7 @@ export function ProgramApplicationForm({
const result = await executeAsync({
...data,
programId: program.id,
- groupId: group.id
+ groupId: group.id,
});
if (!result || result.serverError || result.validationErrors) {
@@ -201,9 +232,7 @@ export function ProgramApplicationForm({
</label>
<label className="flex flex-col">
- <span className="text-sm font-medium text-neutral-800">
- Country
- </span>
+ <span className="text-sm font-medium text-neutral-800">Country</span>
<Controller
control={control}
name="country"
@@ -220,7 +249,13 @@ export function ProgramApplicationForm({
</label>
{group?.applicationFormData?.fields.map((field, index) => {
- return <ProgramApplicationFormField key={field.id} field={field} keyPath={`formData.fields.${index}`} />;
+ return (
+ <ProgramApplicationFormField
+ key={field.id}
+ field={field}
+ keyPath={`formData.fields.${index}`}
+ />
+ );
})}
{program.ageVerification && (
@@ -236,7 +271,10 @@ export function ProgramApplicationForm({
required: true,
})}
/>
- <label htmlFor="ageVerification" className="text-sm text-neutral-800">
+ <label
+ htmlFor="ageVerification"
+ className="text-sm text-neutral-800"
+ >
I'm {program.ageVerification} years or older
</label>
</div>
@@ -253,7 +291,10 @@ export function ProgramApplicationForm({
)}
{...register("termsAgreement", { required: true })}
/>
- <label htmlFor="termsAgreement" className="text-sm text-neutral-800">
+ <label
+ htmlFor="termsAgreement"
+ className="text-sm text-neutral-800"
+ >
I agree to the{" "}
<a
href={program.termsUrl}