@kiwicom/orbit-components
Version:
Orbit-components is a React component library which provides developers with the easiest possible way of building Kiwi.com’s products.
96 lines (95 loc) • 2.91 kB
JavaScript
"use client";
import * as React from "react";
import cx from "clsx";
import Heading from "../Heading";
import Stack from "../Stack";
import ButtonLink from "../ButtonLink";
import ChevronDown from "../icons/ChevronDown";
import Slide from "../utils/Slide";
import { useRandomIdSeed } from "../hooks/useRandomId";
import useBoundingRect from "../hooks/useBoundingRect";
const AnimatedIcon = ({
expanded
}) => {
return /*#__PURE__*/React.createElement(ChevronDown, {
className: cx("duration-fast transition-transform ease-in-out", expanded && "rotate-180 "),
color: "secondary"
});
};
const Collapse = ({
initialExpanded = false,
customLabel,
expanded: expandedProp,
label,
children,
dataTest,
id,
onClick,
actions
}) => {
const isControlledComponent = expandedProp != null;
const [expandedState, setExpandedState] = React.useState(isControlledComponent ? expandedProp : initialExpanded);
const expanded = isControlledComponent ? expandedProp : expandedState;
const [{
height
}, node] = useBoundingRect({
height: expanded ? null : 0
});
const randomId = useRandomIdSeed();
const slideID = randomId("slideID");
const labelID = randomId("labelID");
const handleClick = React.useCallback(event => {
if (!isControlledComponent) {
if (onClick) {
onClick(event, !expanded);
}
setExpandedState(!expanded);
} else if (onClick) {
onClick(event, !expanded);
}
}, [expanded, isControlledComponent, onClick]);
return /*#__PURE__*/React.createElement("div", {
className: "border-b-cloud-normal pb-sm mb-md block w-full border-b border-solid last:m-0 last:border-none",
"data-test": dataTest,
id: id
}, /*#__PURE__*/React.createElement("div", {
className: "block w-full cursor-pointer",
onClick: handleClick,
role: "button",
tabIndex: -1,
id: labelID
}, /*#__PURE__*/React.createElement(Stack, {
justify: "between",
align: "center"
}, label && !customLabel && /*#__PURE__*/React.createElement(Heading, {
type: "title4"
}, label), customLabel, /*#__PURE__*/React.createElement(Stack, {
inline: true,
grow: false,
align: "center",
spacing: "small"
}, /*#__PURE__*/React.createElement("div", {
className: "flex items-center",
onClick: ev => {
ev.stopPropagation();
}
}, actions), /*#__PURE__*/React.createElement(ButtonLink, {
iconLeft: /*#__PURE__*/React.createElement(AnimatedIcon, {
expanded: expanded
}),
size: "small",
type: "secondary",
ariaLabelledby: labelID,
ariaExpanded: expanded,
ariaControls: slideID
})))), /*#__PURE__*/React.createElement(Slide, {
maxHeight: height,
expanded: expanded,
id: slideID,
ariaLabelledBy: labelID
}, /*#__PURE__*/React.createElement("div", {
className: "my-sm mx-0",
ref: node
}, children)));
};
export default Collapse;