@violetprotocol/nudge-components
Version:
Components for Nudge's websites and applications.
110 lines (109 loc) • 3.42 kB
JavaScript
import { jsxs, Fragment, jsx } from "react/jsx-runtime";
import { useState, useRef, useEffect } from "react";
import { Icon } from "../Icon/Icon.esm.js";
import { clsx } from "clsx";
import { Typography } from "../Typography/Typography.esm.js";
const TokenDropdown = ({
tokens,
selectedToken,
ImageComponent,
onSelectToken,
className
}) => {
const [isOpen, setIsOpen] = useState(false);
const dropdownRef = useRef(null);
const ulRef = useRef(null);
useEffect(() => {
if (dropdownRef.current && ulRef.current) {
ulRef.current.style.width = `${dropdownRef.current.offsetWidth}px`;
}
}, [isOpen]);
useEffect(() => {
document.addEventListener("pointerdown", handleClickOutside);
return () => {
document.removeEventListener("pointerdown", handleClickOutside);
};
}, []);
if (!Array.isArray(tokens) || tokens.length === 0)
return null;
const hasMoreThanOneToken = tokens.length > 1;
const handleClickOutside = (event) => {
if (dropdownRef.current && !dropdownRef.current.contains(event.target) && ulRef.current && !ulRef.current.contains(event.target.parentElement)) {
setIsOpen(false);
}
};
const handleTokenSelect = (token) => {
setIsOpen(false);
if (onSelectToken)
onSelectToken(token);
};
return /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsx(
"div",
{
className: clsx(
"relative inline-flex items-center bg-neutral-50 rounded-lg",
{ "cursor-pointer": hasMoreThanOneToken },
className
),
ref: dropdownRef,
onClick: () => hasMoreThanOneToken && setIsOpen(!isOpen),
children: /* @__PURE__ */ jsxs("div", { className: "flex mx-auto items-center px-4 py-[22px]", children: [
/* @__PURE__ */ jsx(
ImageComponent,
{
src: selectedToken == null ? void 0 : selectedToken.iconUri,
height: 32,
width: 32,
className: "mr-2"
}
),
/* @__PURE__ */ jsx(Typography, { variant: "p", className: "font-medium text-neutral-950", children: selectedToken == null ? void 0 : selectedToken.symbol }),
hasMoreThanOneToken && /* @__PURE__ */ jsx(
Icon,
{
name: "chevron-down",
height: 24,
width: 24,
className: clsx(
"ml-2 transition-transform duration-300",
isOpen && "rotate-180"
)
}
)
] })
}
),
isOpen && /* @__PURE__ */ jsx(
"ul",
{
className: "absolute mt-2 bg-neutral-50 rounded-md shadow-lg z-10",
ref: ulRef,
children: tokens.map((token) => /* @__PURE__ */ jsxs(
"li",
{
className: "flex items-center p-2 cursor-pointer hover:bg-neutral-100",
onClick: () => handleTokenSelect(token),
children: [
/* @__PURE__ */ jsx(
ImageComponent,
{
src: token.iconUri,
height: 32,
width: 32,
className: "mr-2"
}
),
token.symbol
]
},
token.symbol
))
}
)
] });
};
export {
TokenDropdown
};
//# sourceMappingURL=TokenDropdown.esm.js.map