All files / src/components/ui/layout RelativePortal.tsx

16.33% Statements 8/49
0% Branches 0/56
0% Functions 0/5
14.58% Lines 7/48

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 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 1872x               2x 2x                                             2x                                             2x   2x                               2x                                                                                                                                                                                                                                  
import React, {
  CSSProperties,
  FC,
  ReactNode,
  useLayoutEffect,
  useRef,
  useState,
} from "react";
import { Portal } from "./Portal";
import styled from "styled-components";
 
export type PinDirection =
  | "top-left"
  | "bottom-left"
  | "top-right"
  | "bottom-right";
 
type RelativePortalProps = {
  children: ReactNode;
  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;
 
const Pin = styled.div`
  background: transparent;
  width: 1px;
  height: 1px;
  margin-right: -1px;
  margin-bottom: -1px;
`;
 
type PortalState =
  | { type: "idle" }
  | {
      type: "ready";
      x: number;
      y: number;
    };
 
export const RelativePortal: FC<RelativePortalProps> = ({
  children,
  offsetX = 0,
  offsetY = 0,
  zIndex,
  ...props
}) => {
  const pinRef = useRef<HTMLDivElement>(null);
  const contentsRef = useRef<HTMLDivElement>(null);
  const pin = props.pin ?? "top-left";
 
  const [portalState, setPortalState] = useState<PortalState>({ type: "idle" });
  const parentWidth = props.pin === "parent-edge" ? props.parentWidth : 0;
 
  useLayoutEffect(() => {
    const update = () => {
      const rect = pinRef.current?.getBoundingClientRect();
      const contentsHeight = contentsRef.current?.offsetHeight ?? 0;
      const contentsWidth = contentsRef.current?.offsetWidth ?? 0;
 
      Iif (!rect) {
        return;
      }
 
      let newY = rect.top + offsetY;
      let newX = rect.left + 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) {
          // Not enough room on the right of parent for child content
          if (newX > parentWidth + contentsWidth + MIN_MARGIN) {
            // Enough room to place left of parent instead
            newX -= parentWidth + contentsWidth + MIN_MARGIN;
          } else if (newX - parentWidth > window.innerWidth * 0.3) {
            // If parent location was to right of screen
            // place child on the far left
            newX = MIN_MARGIN;
          } else {
            // Otherwise place at far right of screen
            newX = window.innerWidth - (contentsWidth + MIN_MARGIN);
          }
        }
      } else Iif (newX + contentsWidth + MIN_MARGIN > window.innerWidth) {
        newX = window.innerWidth - contentsWidth - MIN_MARGIN;
      }
 
      newX = Math.max(10, newX);
 
      setPortalState((prev) => {
        Iif (prev.type === "ready" && prev.x === newX && prev.y === newY) {
          return prev;
        }
 
        return {
          type: "ready",
          x: newX,
          y: newY,
        };
      });
    };
 
    update();
    const timer = window.setInterval(update, 1);
 
    return () => {
      window.clearInterval(timer);
    };
  }, [offsetX, offsetY, pin, props.pin, parentWidth]);
 
  return (
    <>
      <Pin ref={pinRef} />
      <Portal>
        <div
          style={
            portalState.type === "ready"
              ? {
                  position: "fixed",
                  left: portalState.x,
                  top: portalState.y,
                  zIndex,
                }
              : {
                  position: "fixed",
                  left: 0,
                  top: 0,
                  zIndex,
                }
          }
        >
          <div
            ref={contentsRef}
            style={pin !== "parent-edge" ? pinStyles[pin] : undefined}
          >
            {children}
          </div>
        </div>
      </Portal>
    </>
  );
};