Files
OpenCut/apps/web/src/components/ui/form.tsx
T

263 lines
5.9 KiB
TypeScript
Raw Normal View History

2025-06-22 10:02:50 +02:00
"use client";
import * as React from "react";
2026-01-31 00:20:04 +01:00
import { type Label as LabelPrimitive, Slot as SlotPrimitive } from "radix-ui";
2025-06-22 10:02:50 +02:00
import {
2026-01-31 00:20:04 +01:00
Controller,
type ControllerProps,
type DefaultValues,
2026-01-31 00:20:04 +01:00
type FieldPath,
type FieldValues,
FormProvider,
useFormContext,
type UseFormReturn,
2025-06-22 10:02:50 +02:00
} from "react-hook-form";
2026-01-31 00:20:04 +01:00
import { cn } from "@/utils/ui";
2025-06-22 10:02:50 +02:00
import { Label } from "./label";
const DRAFT_DEBOUNCE_MS = 500;
export interface DraftStorage {
getItem(key: string): string | null;
setItem(key: string, value: string): void;
removeItem(key: string): void;
}
type FormProps<
TFieldValues extends FieldValues = FieldValues,
TContext = unknown,
> = UseFormReturn<TFieldValues, TContext> & {
children: React.ReactNode;
persistKey?: string;
storage?: DraftStorage;
};
function Form<
TFieldValues extends FieldValues = FieldValues,
TContext = unknown,
>({
persistKey,
storage,
children,
...methods
}: FormProps<TFieldValues, TContext>) {
const { watch, reset } = methods;
// To change keys after mount, re-mount the component with key={persistKey}
const persistKeyOnMount = React.useRef(persistKey);
const storageOnMount = React.useRef(storage);
const resetRef = React.useRef(reset);
React.useEffect(() => {
if (!persistKeyOnMount.current) return;
const store = storageOnMount.current ?? window.localStorage;
try {
const stored = store.getItem(persistKeyOnMount.current);
if (stored) {
resetRef.current(
JSON.parse(stored) as DefaultValues<TFieldValues>,
);
}
} catch {
// Storage may be unavailable (private browsing, storage blocked)
}
}, []);
React.useEffect(() => {
if (!persistKey) return;
const store = storageOnMount.current ?? window.localStorage;
let timer: ReturnType<typeof setTimeout>;
const subscription = watch((values) => {
clearTimeout(timer);
timer = setTimeout(() => {
try {
store.setItem(persistKey, JSON.stringify(values));
} catch {
// Storage may be full or blocked
}
}, DRAFT_DEBOUNCE_MS);
});
return () => {
clearTimeout(timer);
subscription.unsubscribe();
};
}, [persistKey, watch]);
return <FormProvider {...methods}>{children}</FormProvider>;
}
export function clearFormDraft({
key,
storage,
}: {
key: string;
storage?: DraftStorage;
}): void {
const store = storage ?? window.localStorage;
try {
store.removeItem(key);
} catch {
// Storage may be unavailable
}
}
2025-06-22 10:02:50 +02:00
type FormFieldContextValue<
2026-01-31 00:20:04 +01:00
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
2025-06-22 10:02:50 +02:00
> = {
2026-01-31 00:20:04 +01:00
name: TName;
2025-06-22 10:02:50 +02:00
};
const FormFieldContext = React.createContext<FormFieldContextValue>(
2026-01-31 00:20:04 +01:00
{} as FormFieldContextValue,
2025-06-22 10:02:50 +02:00
);
const FormField = <
2026-01-31 00:20:04 +01:00
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
2025-06-22 10:02:50 +02:00
>({
2026-01-31 00:20:04 +01:00
...props
2025-06-22 10:02:50 +02:00
}: ControllerProps<TFieldValues, TName>) => {
2026-01-31 00:20:04 +01:00
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
);
2025-06-22 10:02:50 +02:00
};
const useFormField = () => {
2026-01-31 00:20:04 +01:00
const fieldContext = React.useContext(FormFieldContext);
const itemContext = React.useContext(FormItemContext);
const { getFieldState, formState } = useFormContext();
2025-06-22 10:02:50 +02:00
2026-01-31 00:20:04 +01:00
const fieldState = getFieldState(fieldContext.name, formState);
2025-06-22 10:02:50 +02:00
2026-01-31 00:20:04 +01:00
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>");
}
2025-06-22 10:02:50 +02:00
2026-01-31 00:20:04 +01:00
const { id } = itemContext;
2025-06-22 10:02:50 +02:00
2026-01-31 00:20:04 +01:00
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
};
2025-06-22 10:02:50 +02:00
};
type FormItemContextValue = {
2026-01-31 00:20:04 +01:00
id: string;
2025-06-22 10:02:50 +02:00
};
const FormItemContext = React.createContext<FormItemContextValue>(
2026-01-31 00:20:04 +01:00
{} as FormItemContextValue,
2025-06-22 10:02:50 +02:00
);
const FormItem = React.forwardRef<
2026-01-31 00:20:04 +01:00
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
2025-06-22 10:02:50 +02:00
>(({ className, ...props }, ref) => {
2026-01-31 00:20:04 +01:00
const id = React.useId();
2025-06-22 10:02:50 +02:00
2026-01-31 00:20:04 +01:00
return (
<FormItemContext.Provider value={{ id }}>
<div ref={ref} className={cn("space-y-2", className)} {...props} />
</FormItemContext.Provider>
);
2025-06-22 10:02:50 +02:00
});
FormItem.displayName = "FormItem";
const FormLabel = React.forwardRef<
2026-01-31 00:20:04 +01:00
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
2025-06-22 10:02:50 +02:00
>(({ className, ...props }, ref) => {
2026-01-31 00:20:04 +01:00
const { error, formItemId } = useFormField();
2025-06-22 10:02:50 +02:00
2026-01-31 00:20:04 +01:00
return (
<Label
ref={ref}
className={cn(error && "text-destructive", className)}
htmlFor={formItemId}
{...props}
/>
);
2025-06-22 10:02:50 +02:00
});
FormLabel.displayName = "FormLabel";
const FormControl = React.forwardRef<
2026-01-31 00:20:04 +01:00
React.ElementRef<typeof SlotPrimitive.Slot>,
React.ComponentPropsWithoutRef<typeof SlotPrimitive.Slot>
2025-06-22 10:02:50 +02:00
>(({ ...props }, ref) => {
2026-01-31 00:20:04 +01:00
const { error, formItemId, formDescriptionId, formMessageId } =
useFormField();
2025-06-22 10:02:50 +02:00
2026-01-31 00:20:04 +01:00
return (
<SlotPrimitive.Slot
ref={ref}
id={formItemId}
aria-describedby={
error ? `${formDescriptionId} ${formMessageId}` : `${formDescriptionId}`
}
aria-invalid={!!error}
{...props}
/>
);
2025-06-22 10:02:50 +02:00
});
FormControl.displayName = "FormControl";
const FormDescription = React.forwardRef<
2026-01-31 00:20:04 +01:00
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
2025-06-22 10:02:50 +02:00
>(({ className, ...props }, ref) => {
2026-01-31 00:20:04 +01:00
const { formDescriptionId } = useFormField();
2025-06-22 10:02:50 +02:00
2026-01-31 00:20:04 +01:00
return (
<p
ref={ref}
id={formDescriptionId}
className={cn("text-muted-foreground text-[0.8rem]", className)}
{...props}
/>
);
2025-06-22 10:02:50 +02:00
});
FormDescription.displayName = "FormDescription";
const FormMessage = React.forwardRef<
2026-01-31 00:20:04 +01:00
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
2025-06-22 10:02:50 +02:00
>(({ className, children, ...props }, ref) => {
2026-01-31 00:20:04 +01:00
const { error, formMessageId } = useFormField();
const body = error ? String(error?.message) : children;
2025-06-22 10:02:50 +02:00
2026-01-31 00:20:04 +01:00
if (!body) {
return null;
}
2025-06-22 10:02:50 +02:00
2026-01-31 00:20:04 +01:00
return (
<p
ref={ref}
id={formMessageId}
className={cn("text-destructive text-[0.8rem] font-medium", className)}
{...props}
>
{body}
</p>
);
2025-06-22 10:02:50 +02:00
});
FormMessage.displayName = "FormMessage";
export {
2026-01-31 00:20:04 +01:00
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
2025-06-22 10:02:50 +02:00
};