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