/**
 * Gets the first ancestor element that would affect the positioning of an absolutely
 * positioned child element.
 *
 * This returns the first ancestor that has a position value other than 'static',
 * which is the default. Elements with position 'relative', 'absolute', 'fixed', or 'sticky'
 * will create a new positioning context for absolutely positioned children.
 *
 * @param element The element to find the positioning ancestor for
 * @returns The first positioned ancestor, or document.body if none is found
 */
export default function getPositioningAncestor(
  element: HTMLElement
): HTMLElement {
  let current: HTMLElement | null = element.parentElement;

  while (current && current !== document.documentElement) {
    const position = window.getComputedStyle(current).position;

    if (position !== 'static') {
      return current;
    }

    current = current.parentElement;
  }

  // If no positioned ancestors are found, the positioning context
  // is the document body or documentElement (depending on browser)
  return document.body;
}
