76 lines
2.5 KiB
TypeScript
76 lines
2.5 KiB
TypeScript
import _ from "lodash";
|
|
import React from "react";
|
|
import { TWUIPopoverStyles } from "../../elements/Modal";
|
|
import twuiNumberfy from "../../utils/numberfy";
|
|
|
|
type Params = {
|
|
targetElRef: React.RefObject<HTMLElement | null>;
|
|
position: (typeof TWUIPopoverStyles)[number];
|
|
};
|
|
|
|
export default function twuiGrabPopoverStyles({
|
|
position,
|
|
targetElRef,
|
|
}: Params): React.CSSProperties {
|
|
if (!targetElRef.current) return {};
|
|
const rect = targetElRef.current.getBoundingClientRect();
|
|
|
|
const targetElCurrStyles = window.getComputedStyle(targetElRef.current);
|
|
|
|
const targetElRightPadding = twuiNumberfy(targetElCurrStyles.paddingRight);
|
|
|
|
let popoverStyle: React.CSSProperties = {
|
|
position: "absolute",
|
|
zIndex: 100,
|
|
};
|
|
|
|
const defaultBottomStyle: React.CSSProperties = {
|
|
top: rect.bottom + window.scrollY + 8,
|
|
left: rect.left + window.scrollX + rect.width / 2,
|
|
transform: "translateX(-50%)",
|
|
};
|
|
|
|
const defaultTopStyleStyle: React.CSSProperties = {
|
|
bottom: window.innerHeight - (rect.top + window.scrollY) + 8,
|
|
left: rect.left + window.scrollX + rect.width / 2,
|
|
transform: "translateX(-50%)",
|
|
};
|
|
|
|
if (position === "bottom") {
|
|
popoverStyle = _.merge(popoverStyle, defaultBottomStyle);
|
|
} else if (position === "bottom-left") {
|
|
popoverStyle = _.merge(
|
|
popoverStyle,
|
|
_.omit(defaultBottomStyle, ["transform"]),
|
|
{
|
|
left: rect.left,
|
|
} as React.CSSProperties
|
|
);
|
|
} else if (position === "bottom-right") {
|
|
popoverStyle = _.merge(
|
|
popoverStyle,
|
|
_.omit(defaultBottomStyle, ["left", "transform"]),
|
|
{
|
|
right:
|
|
window.innerWidth -
|
|
(rect.left + window.scrollX) -
|
|
rect.width -
|
|
targetElRightPadding,
|
|
} as React.CSSProperties
|
|
);
|
|
} else if (position === "top") {
|
|
popoverStyle = _.merge(popoverStyle, defaultTopStyleStyle);
|
|
} else if (position === "right") {
|
|
popoverStyle.top = rect.top + window.scrollY + rect.height / 2;
|
|
popoverStyle.left = rect.right + window.scrollX + 8;
|
|
popoverStyle.transform = "translateY(-50%)";
|
|
} else if (position === "left") {
|
|
popoverStyle.top = rect.top + window.scrollY + rect.height / 2;
|
|
popoverStyle.right =
|
|
window.innerWidth - (rect.left + window.scrollX) + 8;
|
|
popoverStyle.transform = "translateY(-50%)";
|
|
}
|
|
|
|
return popoverStyle;
|
|
}
|