@redocly/theme
Version:
Shared UI components lib
46 lines • 2.07 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useTooltipFallbackPlacement = useTooltipFallbackPlacement;
const react_1 = require("react");
function useTooltipFallbackPlacement({ isOpened, placement, arrowPosition, fallbackPlacements, tooltipBodyRef, }) {
const [activePlacement, setActivePlacement] = (0, react_1.useState)(placement);
const wasOpenRef = (0, react_1.useRef)(false);
const candidateIndexRef = (0, react_1.useRef)(0);
(0, react_1.useLayoutEffect)(() => {
if (!isOpened) {
wasOpenRef.current = false;
candidateIndexRef.current = 0;
return;
}
if (!wasOpenRef.current) {
wasOpenRef.current = true;
candidateIndexRef.current = 0;
if (activePlacement !== placement) {
setActivePlacement(placement);
return;
}
}
if (!tooltipBodyRef.current || !(fallbackPlacements === null || fallbackPlacements === void 0 ? void 0 : fallbackPlacements.length))
return;
const candidates = [placement, ...fallbackPlacements];
if (candidateIndexRef.current >= candidates.length)
return;
const rect = tooltipBodyRef.current.getBoundingClientRect();
const overflows = rect.left < 0 ||
rect.top < 0 ||
rect.right > window.innerWidth ||
rect.bottom > window.innerHeight;
if (!overflows)
return;
candidateIndexRef.current++;
if (candidateIndexRef.current < candidates.length) {
setActivePlacement(candidates[candidateIndexRef.current]);
}
else if (activePlacement !== placement) {
setActivePlacement(placement);
}
}, [isOpened, activePlacement, placement, fallbackPlacements, tooltipBodyRef]);
const activeArrowPosition = activePlacement === placement ? arrowPosition : 'center';
return { activePlacement, activeArrowPosition };
}
//# sourceMappingURL=use-tooltip-fallback-placement.js.map