1 import { Switch } from "@medusajs/ui"
2 import { ReactNode } from "react"
3 import { ControllerProps, FieldPath, FieldValues } from "react-hook-form"
4
5 import { Form } from "../../common/form"
6
7 interface HeadlessControllerProps<
8 TFieldValues extends FieldValues = FieldValues,
9 TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
10 > extends Omit<ControllerProps<TFieldValues, TName>, "render"> {}
11
12 interface SwitchBoxProps<
13 TFieldValues extends FieldValues = FieldValues,
14 TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
15 > extends HeadlessControllerProps<TFieldValues, TName> {
16 label: string
17 description: string
18 optional?: boolean
19 tooltip?: ReactNode
20 /**
21 * Callback for performing additional actions when the checked state changes.
22 * This does not intercept the form control, it is only used for injecting side-effects.
23 */
24 onCheckedChange?: (checked: boolean) => void
25 }
26
27 /**
28 * Wrapper for the Switch component to be used with `react-hook-form`.
29 *
30 * Use this component whenever a design calls for wrapping the Switch component
31 * in a container with a label and description.
32 */
33 export const SwitchBox = <
34 TFieldValues extends FieldValues = FieldValues,
35 TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
36 >({
37 label,
38 description,
39 optional = false,
40 tooltip,
41 onCheckedChange,
42 ...props
43 }: SwitchBoxProps<TFieldValues, TName>) => {
44 return (
45 <Form.Field
46 {...props}
47 render={({ field: { value, onChange, ...field } }) => {
48 return (
49 <Form.Item>
50 <div className="bg-ui-bg-component shadow-elevation-card-rest flex items-start gap-x-3 rounded-lg p-3">
51 <Form.Control>
52 <Switch
53 className="rtl:rotate-180"
54 dir="ltr"
55 {...field}
56 checked={value}
57 onCheckedChange={(e) => {
58 onCheckedChange?.(e)
59 onChange(e)
60 }}
61 />
62 </Form.Control>
63 <div>
64 <Form.Label optional={optional} tooltip={tooltip}>
65 {label}
66 </Form.Label>
67 <Form.Hint>{description}</Form.Hint>
68 </div>
69 </div>
70 <Form.ErrorMessage />
71 </Form.Item>
72 )
73 }}
74 />
75 )
76 }