Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | import React, { CSSProperties, FC, ReactNode, useLayoutEffect, useRef, useState, } from "react"; import { Portal } from "./Portal"; type PinDirection = "top-left" | "bottom-left" | "top-right" | "bottom-right"; export type PositionedPortalProps = { children: ReactNode; x: number; y: number; offsetX?: number; offsetY?: number; zIndex?: number; } & ( | { pin?: PinDirection; } | { pin: "parent-edge"; parentWidth: number; } ); const pinStyles: Record<PinDirection, CSSProperties> = { "top-left": { position: "absolute", top: 0, left: 0, }, "top-right": { position: "absolute", top: 0, right: 0, }, "bottom-left": { position: "absolute", bottom: 0, left: 0, }, "bottom-right": { position: "absolute", bottom: 0, right: 0, }, }; const MIN_MARGIN = 10; export const PositionedPortal: FC<PositionedPortalProps> = ({ children, x: initialX, y: initialY, offsetX = 0, offsetY = 0, zIndex, ...props }) => { const contentsRef = useRef<HTMLDivElement>(null); const pin = props.pin ?? "top-left"; const [x, setX] = useState(0); const [y, setY] = useState(0); useLayoutEffect(() => { const update = () => { const contentsHeight = contentsRef.current?.offsetHeight || 0; const contentsWidth = contentsRef.current?.offsetWidth || 0; let newY = initialY + offsetY; let newX = initialX + offsetX; if (pin === "bottom-left" || pin === "bottom-right") { Iif (newY - contentsHeight - MIN_MARGIN < 0) { newY = contentsHeight + MIN_MARGIN; } } else { Iif (newY + contentsHeight + MIN_MARGIN > window.innerHeight) { newY = window.innerHeight - contentsHeight - MIN_MARGIN; } } if (pin === "bottom-right" || pin === "top-right") { Iif (newX - contentsWidth - MIN_MARGIN < 0) { newX = contentsWidth + MIN_MARGIN; } } else if (props.pin === "parent-edge") { Iif (newX + contentsWidth + MIN_MARGIN > window.innerWidth) { newX -= props.parentWidth + contentsWidth; } } else { Iif (newX + contentsWidth + MIN_MARGIN > window.innerWidth) { newX = window.innerWidth - contentsWidth - MIN_MARGIN; } } setY(newY); setX(newX); }; update(); const timer = setInterval(update, 100); return () => { clearInterval(timer); }; }, [offsetX, offsetY, pin, props.pin, props, initialY, initialX]); return ( <> <Portal> <div style={{ position: "fixed", left: x, top: y, zIndex, }} > <div ref={contentsRef} style={pin !== "parent-edge" ? pinStyles[pin] : undefined} > {children} </div> </div> </Portal> </> ); }; |