|
1
|
import { useRef, useState, useEffect } from "react" |
|
2
|
import { IconButton } from "@medusajs/ui" |
|
3
|
import { Plus, XMark } from "@medusajs/icons" |
|
4
|
import { useCombinedRefs } from "../../../hooks/use-combined-refs" |
|
5
|
import { Form } from "../../../components/common/form" |
|
6
|
import { TieredPriceInputProps } from "./types" |
|
7
|
|
|
8
|
export const TieredPriceInput = ({ |
|
9
|
field, |
|
10
|
label, |
|
11
|
toggleValues, |
|
12
|
renderInput, |
|
13
|
}: TieredPriceInputProps) => { |
|
14
|
const innerRef = useRef<HTMLInputElement>(null) |
|
15
|
const [isActive, setIsActive] = useState(false) |
|
16
|
|
|
17
|
const { value, onChange, ref } = field |
|
18
|
|
|
19
|
const refs = useCombinedRefs(innerRef, ref) |
|
20
|
|
|
21
|
useEffect(() => { |
|
22
|
setIsActive(value !== toggleValues.inactive) |
|
23
|
}, [value, toggleValues.inactive]) |
|
24
|
|
|
25
|
const action = () => { |
|
26
|
if (!isActive) { |
|
27
|
onChange(toggleValues.active) |
|
28
|
setIsActive(true) |
|
29
|
requestAnimationFrame(() => { |
|
30
|
innerRef.current?.focus() |
|
31
|
}) |
|
32
|
} else { |
|
33
|
onChange(toggleValues.inactive) |
|
34
|
setIsActive(false) |
|
35
|
} |
|
36
|
} |
|
37
|
|
|
38
|
return ( |
|
39
|
<Form.Item> |
|
40
|
<div className="grid grid-cols-2 items-start gap-x-2 p-3"> |
|
41
|
<div className="flex h-8 items-center gap-x-1"> |
|
42
|
<IconButton size="2xsmall" variant="transparent" onClick={action}> |
|
43
|
{!isActive ? <Plus /> : <XMark />} |
|
44
|
</IconButton> |
|
45
|
<Form.Label>{label}</Form.Label> |
|
46
|
</div> |
|
47
|
{isActive && ( |
|
48
|
<div className="flex flex-col gap-y-1"> |
|
49
|
<Form.Control> |
|
50
|
{renderInput({ field: { ...field, ref: refs }, value })} |
|
51
|
</Form.Control> |
|
52
|
<Form.ErrorMessage /> |
|
53
|
</div> |
|
54
|
)} |
|
55
|
</div> |
|
56
|
</Form.Item> |
|
57
|
) |
|
58
|
} |