Raw
1 import { InformationCircleSolid } from "@medusajs/icons";
2 import {
3 Hint as HintComponent,
4 Label as LabelComponent,
5 Text,
6 Tooltip,
7 clx,
8 } from "@medusajs/ui";
9 import { Label as RadixLabel, Slot } from "radix-ui";
10 import React, {
11 ReactNode,
12 createContext,
13 forwardRef,
14 useContext,
15 useId,
16 } from "react";
17 import {
18 Controller,
19 ControllerProps,
20 FieldPath,
21 FieldValues,
22 FormProvider,
23 useFormContext,
24 useFormState,
25 } from "react-hook-form";
26
27 const Provider = FormProvider;
28
29 type FormFieldContextValue<
30 TFieldValues extends FieldValues = FieldValues,
31 TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
32 > = {
33 name: TName;
34 };
35
36 const FormFieldContext = createContext<FormFieldContextValue>(
37 {} as FormFieldContextValue
38 );
39
40 const Field = <
41 TFieldValues extends FieldValues = FieldValues,
42 TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
43 >({
44 ...props
45 }: ControllerProps<TFieldValues, TName>) => {
46 return (
47 <FormFieldContext.Provider value={{ name: props.name }}>
48 <Controller {...props} />
49 </FormFieldContext.Provider>
50 );
51 };
52
53 type FormItemContextValue = {
54 id: string;
55 };
56
57 const FormItemContext = createContext<FormItemContextValue>(
58 {} as FormItemContextValue
59 );
60
61 const useFormField = () => {
62 const fieldContext = useContext(FormFieldContext);
63 const itemContext = useContext(FormItemContext);
64 const { getFieldState } = useFormContext();
65
66 const formState = useFormState({ name: fieldContext.name });
67 const fieldState = getFieldState(fieldContext.name, formState);
68
69 if (!fieldContext) {
70 throw new Error("useFormField should be used within a FormField");
71 }
72
73 const { id } = itemContext;
74
75 return {
76 id,
77 name: fieldContext.name,
78 formItemId: `${id}-form-item`,
79 formLabelId: `${id}-form-item-label`,
80 formDescriptionId: `${id}-form-item-description`,
81 formErrorMessageId: `${id}-form-item-message`,
82 ...fieldState,
83 };
84 };
85
86 const Item = forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
87 ({ className, ...props }, ref) => {
88 const id = useId();
89
90 return (
91 <FormItemContext.Provider value={{ id }}>
92 <div
93 ref={ref}
94 className={clx("flex flex-col space-y-2", className)}
95 {...props}
96 />
97 </FormItemContext.Provider>
98 );
99 }
100 );
101 Item.displayName = "Form.Item";
102
103 const Label = forwardRef<
104 React.ElementRef<typeof RadixLabel.Root>,
105 React.ComponentPropsWithoutRef<typeof RadixLabel.Root> & {
106 variant?: "default" | "subtle";
107 optional?: boolean;
108 tooltip?: ReactNode;
109 icon?: ReactNode;
110 }
111 >(
112 (
113 {
114 className,
115 optional = false,
116 tooltip,
117 icon,
118 variant = "default",
119 ...props
120 },
121 ref
122 ) => {
123 const { formLabelId, formItemId } = useFormField();
124
125 return (
126 <div className="flex items-center gap-x-1">
127 <LabelComponent
128 id={formLabelId}
129 ref={ref}
130 className={clx(
131 {
132 "text-ui-fg-subtle": variant === "subtle",
133 },
134 className
135 )}
136 htmlFor={formItemId}
137 size="small"
138 weight={variant === "default" ? "plus" : "regular"}
139 {...props}
140 />
141 {tooltip && (
142 <Tooltip content={tooltip}>
143 <InformationCircleSolid className="text-ui-fg-muted" />
144 </Tooltip>
145 )}
146 {icon}
147 {optional && (
148 <Text size="small" leading="compact" className="text-ui-fg-muted">
149 (Optional)
150 </Text>
151 )}
152 </div>
153 );
154 }
155 );
156 Label.displayName = "Form.Label";
157
158 const Control = forwardRef<
159 React.ElementRef<typeof Slot.Root>,
160 React.ComponentPropsWithoutRef<typeof Slot.Root>
161 >(({ ...props }, ref) => {
162 const {
163 error,
164 formItemId,
165 formDescriptionId,
166 formErrorMessageId,
167 formLabelId,
168 } = useFormField();
169
170 return (
171 <Slot.Root
172 ref={ref}
173 id={formItemId}
174 aria-describedby={
175 !error
176 ? `${formDescriptionId}`
177 : `${formDescriptionId} ${formErrorMessageId}`
178 }
179 aria-invalid={!!error}
180 aria-labelledby={formLabelId}
181 {...props}
182 />
183 );
184 });
185 Control.displayName = "Form.Control";
186
187 const Hint = forwardRef<
188 HTMLParagraphElement,
189 React.HTMLAttributes<HTMLParagraphElement>
190 >(({ className, ...props }, ref) => {
191 const { formDescriptionId } = useFormField();
192
193 return (
194 <HintComponent
195 ref={ref}
196 id={formDescriptionId}
197 className={className}
198 {...props}
199 />
200 );
201 });
202 Hint.displayName = "Form.Hint";
203
204 const ErrorMessage = forwardRef<
205 HTMLParagraphElement,
206 React.HTMLAttributes<HTMLParagraphElement>
207 >(({ className, children, ...props }, ref) => {
208 const { error, formErrorMessageId } = useFormField();
209 const msg = error ? String(error?.message) : children;
210
211 if (!msg || msg === "undefined") {
212 return null;
213 }
214
215 return (
216 <HintComponent
217 ref={ref}
218 id={formErrorMessageId}
219 className={className}
220 variant={error ? "error" : "info"}
221 {...props}
222 >
223 {msg}
224 </HintComponent>
225 );
226 });
227 ErrorMessage.displayName = "Form.ErrorMessage";
228
229 const Form = Object.assign(Provider, {
230 Item,
231 Label,
232 Control,
233 Hint,
234 ErrorMessage,
235 Field,
236 });
237
238 export { Form };