|
1
|
"use client" |
|
2
|
|
|
3
|
import React from "react" |
|
4
|
import { useRef, useState } from "react" |
|
5
|
import { Button } from "@/components/Button" |
|
6
|
import { Menu } from "@/components/Menu" |
|
7
|
import { useClickOutside } from "@/hooks/use-click-outside" |
|
8
|
import { MenuItem } from "types" |
|
9
|
import clsx from "clsx" |
|
10
|
|
|
11
|
type DropdownMenuProps = { |
|
12
|
dropdownButtonContent: React.ReactNode |
|
13
|
dropdownButtonClassName?: string |
|
14
|
menuComponent?: React.ReactNode |
|
15
|
menuItems?: MenuItem[] |
|
16
|
menuClassName?: string |
|
17
|
className?: string |
|
18
|
open?: boolean |
|
19
|
setOpen?: (open: boolean) => void |
|
20
|
} |
|
21
|
|
|
22
|
export const DropdownMenu = ({ |
|
23
|
dropdownButtonContent, |
|
24
|
dropdownButtonClassName, |
|
25
|
menuComponent, |
|
26
|
menuItems, |
|
27
|
menuClassName, |
|
28
|
className, |
|
29
|
open: externalOpen = false, |
|
30
|
setOpen: externalSetOpen, |
|
31
|
}: DropdownMenuProps) => { |
|
32
|
const [open, setOpen] = useState(externalOpen) |
|
33
|
const ref = useRef<HTMLButtonElement | null>(null) |
|
34
|
function changeOpenState(newOpenState: boolean) { |
|
35
|
if (externalSetOpen) { |
|
36
|
externalSetOpen(newOpenState) |
|
37
|
} else { |
|
38
|
setOpen(newOpenState) |
|
39
|
} |
|
40
|
} |
|
41
|
useClickOutside({ |
|
42
|
elmRef: ref, |
|
43
|
onClickOutside: () => { |
|
44
|
changeOpenState(false) |
|
45
|
}, |
|
46
|
}) |
|
47
|
|
|
48
|
if (!menuComponent && !menuItems) { |
|
49
|
return null |
|
50
|
} |
|
51
|
|
|
52
|
return ( |
|
53
|
<div className={clsx("relative", className)} data-testid="dropdown-wrapper"> |
|
54
|
<Button |
|
55
|
variant="transparent" |
|
56
|
onClick={() => changeOpenState(!open)} |
|
57
|
className={clsx( |
|
58
|
"!p-[6px] text-medusa-fg-subtle", |
|
59
|
dropdownButtonClassName |
|
60
|
)} |
|
61
|
buttonRef={ref} |
|
62
|
data-testid="dropdown-button" |
|
63
|
> |
|
64
|
{dropdownButtonContent} |
|
65
|
</Button> |
|
66
|
{menuComponent} |
|
67
|
{!menuComponent && menuItems && ( |
|
68
|
<Menu |
|
69
|
items={menuItems} |
|
70
|
className={clsx( |
|
71
|
"absolute right-0 top-[calc(100%+8px)] w-max", |
|
72
|
!open && "hidden", |
|
73
|
menuClassName |
|
74
|
)} |
|
75
|
/> |
|
76
|
)} |
|
77
|
</div> |
|
78
|
) |
|
79
|
} |