/
index.tsx
116 lines (105 loc) · 2.89 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import {
Dispatch,
FC,
MouseEvent,
ReactNode,
createContext,
useContext,
useId,
useState,
} from 'react';
import {
Placement,
FloatingFocusManager,
FloatingPortal,
flip,
offset,
shift,
useClick,
useDismiss,
useFloating,
useInteractions,
useRole,
useTransitionStyles,
autoUpdate,
Strategy as FloatingStrategy,
} from '@floating-ui/react';
import { cn } from 'utils/helpers';
export interface MenuButtonProps {
onClick: (e: MouseEvent) => void;
}
type Props = {
button: (attr: MenuButtonProps) => ReactNode;
children: ReactNode;
isOpen?: boolean;
setIsOpen?: Dispatch<boolean>;
className?: string;
placement?: Placement;
offset?: number;
strategy?: FloatingStrategy;
};
interface MenuCtx {
setMenuOpen: Dispatch<boolean>;
}
const MenuContext = createContext<MenuCtx>({
setMenuOpen: () => undefined,
});
export const useMenuCtx = () => useContext(MenuContext);
export const DropdownMenu: FC<Props> = ({
children,
button,
isOpen,
setIsOpen,
placement,
strategy = 'absolute',
className = '',
offset: offsetValue = 8,
}) => {
const tooltipId = useId();
// Open can be managed by the parent or inside this component
const [open, setOpen] = useState(false);
const outsideState = setIsOpen !== undefined && isOpen !== undefined;
const menuOpen = (outsideState && isOpen) || (!outsideState && open);
// Get properties to calculate positioning
const { refs, floatingStyles, context } = useFloating({
placement: placement ?? 'bottom',
strategy: strategy,
open: menuOpen,
onOpenChange: outsideState ? setIsOpen : setOpen,
middleware: [offset(offsetValue), flip(), shift()],
whileElementsMounted: strategy === 'fixed' ? autoUpdate : undefined,
});
// Default transition provides a fadein on enter
const { isMounted, styles: transition } = useTransitionStyles(context);
// Generate props to manage reference button & floating element
const { getReferenceProps, getFloatingProps } = useInteractions([
useClick(context),
useDismiss(context),
useRole(context),
]);
const buttonProps = getReferenceProps({ ref: refs.setReference }) as any;
return (
<MenuContext.Provider value={{ setMenuOpen: setOpen }}>
{button(buttonProps)}
<FloatingPortal>
{isMounted && menuOpen && (
<FloatingFocusManager context={context} modal={false}>
<div
id={tooltipId}
ref={refs.setFloating}
className={cn(
// z-index is above header/footer
'bg-background-800 z-50 min-w-[200px] rounded shadow-lg backdrop-blur-2xl',
className
)}
style={{ ...floatingStyles, ...transition }}
{...getFloatingProps()}
>
{children}
</div>
</FloatingFocusManager>
)}
</FloatingPortal>
</MenuContext.Provider>
);
};