@seasketch/geoprocessing
Version:
Geoprocessing and reporting framework for SeaSketch 2.0
75 lines (74 loc) • 2.73 kB
JavaScript
import React, { useState, useRef } from "react";
import { styled } from "styled-components";
import { usePopper } from "react-popper";
import useClickOutside from "../hooks/useClickOutside.js";
export const DropdownContainer = styled.div `
visibility: ${({ open }) => (open ? "visible" : "hidden")};
display: ${({ open }) => (open ? "flex" : "none")};
width: 100%;
flex-direction: column;
background-color: #fff;
border-radius: 5px;
box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.14);
`;
export const DropdownItem = styled.div `
font-family: sans-serif;
justify-content: flex-start;
padding: 5px;
&:hover {
background-color: #efefef;
}
&:active {
color: #777;
}
a[aria-disabled="true"] {
color: currentColor;
text-decoration: none;
cursor: not-allowed;
& button {
cursor: not-allowed;
}
}
`;
export const DropdownTrigger = styled.button `
border: none;
background: none;
font-family: sans-serif;
cursor: pointer;
`;
export const Dropdown = ({ titleElement = React.createElement(React.Fragment, null), placement = "auto", offset = { horizontal: 0, vertical: 0 }, children, }) => {
const [open, setOpen] = useState(false);
/** Used for updates */
const referenceRef = useRef(null);
const popperRef = useRef(null);
/* Listens for click outside the source element that opens the dropdown
* and toggles accordingly */
const toggle = () => setOpen(!open);
const { ref: DropownRef } = useClickOutside(setOpen);
const { horizontal, vertical } = offset;
const { styles, attributes } = usePopper(referenceRef.current, popperRef.current, {
placement,
modifiers: [
{
name: "offset",
enabled: true,
options: {
offset: [horizontal, vertical],
},
},
],
});
function handleDropdownClick(e) {
e.preventDefault();
toggle();
}
return (React.createElement("div", { ref: DropownRef, "aria-label": "Dropdown" },
React.createElement(DropdownTrigger, { ref: referenceRef, onClick: handleDropdownClick, "aria-label": `${open ? "Close" : "Open"} dropdown menu`, "aria-expanded": open }, titleElement),
React.createElement("div", { ref: popperRef, style: { zIndex: 1000, ...styles.popper }, ...attributes.popper },
React.createElement(DropdownContainer, { style: styles.offset, open: open, "aria-label": "Dropdown Menu" }, children &&
React.Children.map(children, (child) => {
return React.createElement(DropdownItem, null, child);
})))));
};
export default Dropdown;
//# sourceMappingURL=Dropdown.js.map