mirror of
https://github.com/lukevella/rallly.git
synced 2025-04-29 10:16:32 +02:00
99 lines
2.5 KiB
TypeScript
99 lines
2.5 KiB
TypeScript
import { Menu } from "@headlessui/react";
|
|
import { Placement } from "@popperjs/core";
|
|
import clsx from "clsx";
|
|
import * as React from "react";
|
|
import ReactDOM from "react-dom";
|
|
import { usePopper } from "react-popper";
|
|
export interface DropdownProps {
|
|
trigger?: React.ReactNode;
|
|
children?: React.ReactNode;
|
|
className?: string;
|
|
placement?: Placement;
|
|
}
|
|
|
|
const Dropdown: React.VoidFunctionComponent<DropdownProps> = ({
|
|
children,
|
|
className,
|
|
trigger,
|
|
placement,
|
|
}) => {
|
|
const [referenceElement, setReferenceElement] =
|
|
React.useState<HTMLDivElement | null>(null);
|
|
const [popperElement, setPopperElement] =
|
|
React.useState<HTMLDivElement | null>(null);
|
|
|
|
const { styles, attributes } = usePopper(referenceElement, popperElement, {
|
|
placement,
|
|
modifiers: [
|
|
{
|
|
name: "offset",
|
|
options: {
|
|
offset: [0, 5],
|
|
},
|
|
},
|
|
],
|
|
});
|
|
|
|
const portal = document.getElementById("portal");
|
|
return (
|
|
<Menu>
|
|
<Menu.Button
|
|
ref={setReferenceElement}
|
|
as="div"
|
|
className={clsx("inline-block", className)}
|
|
>
|
|
{trigger}
|
|
</Menu.Button>
|
|
{portal &&
|
|
ReactDOM.createPortal(
|
|
<Menu.Items
|
|
as="div"
|
|
ref={setPopperElement}
|
|
style={styles.popper}
|
|
{...attributes.popper}
|
|
className="z-30 p-1 bg-white divide-gray-100 rounded-md shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none"
|
|
>
|
|
{children}
|
|
</Menu.Items>,
|
|
portal,
|
|
)}
|
|
</Menu>
|
|
);
|
|
};
|
|
|
|
export const DropdownItem: React.VoidFunctionComponent<{
|
|
icon?: React.ComponentType<{ className?: string }>;
|
|
label?: React.ReactNode;
|
|
disabled?: boolean;
|
|
onClick?: () => void;
|
|
}> = ({ icon: Icon, label, onClick, disabled }) => {
|
|
return (
|
|
<Menu.Item disabled={disabled}>
|
|
{({ active }) => (
|
|
<button
|
|
onClick={onClick}
|
|
className={clsx(
|
|
"group flex rounded items-center w-full py-2 pl-2 pr-4",
|
|
{
|
|
"bg-indigo-500 text-white": active,
|
|
"text-gray-700": !active,
|
|
"opacity-50": disabled,
|
|
},
|
|
)}
|
|
>
|
|
{Icon && (
|
|
<Icon
|
|
className={clsx("w-5 h-5 mr-2", {
|
|
"text-white": active,
|
|
"text-indigo-500": !disabled,
|
|
})}
|
|
/>
|
|
)}
|
|
{label}
|
|
</button>
|
|
)}
|
|
</Menu.Item>
|
|
);
|
|
};
|
|
|
|
export default Dropdown;
|