From 1fe7a8bbc261b6b34641a5fd81ed7f7e48ecb051 Mon Sep 17 00:00:00 2001 From: Sylvia Crowe Date: Thu, 13 Feb 2025 14:56:33 -0800 Subject: [PATCH 1/2] feat: add form and label shadcn components --- frontend/app/shadcn/form.tsx | 144 ++++++++++++++++++++++++++++++++++ frontend/app/shadcn/label.tsx | 19 +++++ package.json | 4 + yarn.lock | 88 +++++++++++++++++++++ 4 files changed, 255 insertions(+) create mode 100644 frontend/app/shadcn/form.tsx create mode 100644 frontend/app/shadcn/label.tsx diff --git a/frontend/app/shadcn/form.tsx b/frontend/app/shadcn/form.tsx new file mode 100644 index 0000000000..7f9be80f3c --- /dev/null +++ b/frontend/app/shadcn/form.tsx @@ -0,0 +1,144 @@ +"use client"; + +import * as LabelPrimitive from "@radix-ui/react-label"; +import { Slot } from "@radix-ui/react-slot"; +import { Controller, ControllerProps, FieldPath, FieldValues, FormProvider, useFormContext } from "react-hook-form"; + +import * as React from "react"; +import { Label } from "./label"; + +import cn from "clsx"; + +const Form = FormProvider; + +type FormFieldContextValue< + TFieldValues extends FieldValues = FieldValues, + TName extends FieldPath = FieldPath, +> = { + name: TName; +}; + +const FormFieldContext = React.createContext({} as FormFieldContextValue); + +const FormField = < + TFieldValues extends FieldValues = FieldValues, + TName extends FieldPath = FieldPath, +>({ + ...props +}: ControllerProps) => { + return ( + + + + ); +}; + +const useFormField = () => { + const fieldContext = React.useContext(FormFieldContext); + const itemContext = React.useContext(FormItemContext); + const { getFieldState, formState } = useFormContext(); + + const fieldState = getFieldState(fieldContext.name, formState); + + if (!fieldContext) { + throw new Error("useFormField should be used within "); + } + + const { id } = itemContext; + + return { + id, + name: fieldContext.name, + formItemId: `${id}-form-item`, + formDescriptionId: `${id}-form-item-description`, + formMessageId: `${id}-form-item-message`, + ...fieldState, + }; +}; + +type FormItemContextValue = { + id: string; +}; + +const FormItemContext = React.createContext({} as FormItemContextValue); + +const FormItem = React.forwardRef>( + ({ className, ...props }, ref) => { + const id = React.useId(); + + return ( + +
+ + ); + } +); +FormItem.displayName = "FormItem"; + +const FormLabel = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => { + const { error, formItemId } = useFormField(); + + return