import { isHTMLElement } from '@fluentui/react-utilities'; import type { ClippingBoundary, PositioningRect, Strategy } from '../types'; type Scale = { x: number; y: number }; type CoordinateSpace = Scale & { scale: Scale; parent?: HTMLElement | null }; // Expression-bodied helpers keep the minified output compact. export const getDocument = (node: Node): Document => node.ownerDocument!; export const getWindow = (node: Node): Window => getDocument(node).defaultView!; export const getRoot = (node: Node): HTMLElement => getDocument(node).documentElement; export const getStyle = (element: Element): CSSStyleDeclaration => getWindow(element).getComputedStyle(element); /** A CSS pixel value, an empty string removes the inline style */ export const px = (value: number | undefined): string => (value === undefined ? '' : `${value}px`); // Properties that are not supported are empty strings (i.e. in jsdom) const isSet = (value: string | undefined): boolean => !!value && value !== 'none'; /** Uses `CSS.supports()` of the element's window, which is unavailable in some environments (e.g. jsdom) */ const isWebKit = (element: Element): boolean => !!(getWindow(element) as Window & typeof globalThis).CSS?.supports?.('-webkit-backdrop-filter', 'none'); /** Shared and never mutated */ export const NO_OFFSET: Scale = { x: 0, y: 0 }; const getVisualOffsets = (element: Element): Scale => { const viewport = getWindow(element).visualViewport; return isWebKit(element) && viewport ? { x: viewport.offsetLeft, y: viewport.offsetTop } : NO_OFFSET; }; const getBounds = (target: { getBoundingClientRect(): DOMRect | PositioningRect }) => target.getBoundingClientRect() as DOMRect; export const rect = (x: number, y: number, width: number, height: number): PositioningRect => ({ x, y, width, height }); /** Whether size query containers form containing blocks, measured once by `probeSizeContainer` */ let sizeContainerContains: boolean | undefined; /** * Engines applying layout containment to size query containers (Chromium < 129) offset the fixed child by the * container. Reset both elements so page CSS cannot contaminate the cached result. Use geometry: Chromium 118 * returns a null offsetParent even when the child is contained. Without layout (e.g. jsdom) both overlap. */ const probeSizeContainer = (element: Element): boolean => { const container = getRoot(element).appendChild(getDocument(element).createElement('div')); container.style.cssText = 'all:initial;position:fixed;left:1px;container-type:size'; // Cloned inline styles skip the CSP check of parsed style attributes const contains = getBounds(container.appendChild(container.cloneNode()) as Element).x > getBounds(container).x; container.remove(); return contains; }; export const intersect = (a: PositioningRect, b: PositioningRect): PositioningRect => { const x = Math.max(a.x, b.x); const y = Math.max(a.y, b.y); return rect(x, y, Math.min(a.x + a.width, b.x + b.width) - x, Math.min(a.y + a.height, b.y + b.height) - y); }; /** * Whether a boxed element is the containing block of its fixed descendants, and of its absolute descendants * when `absolute` is set. Boxless (`display: contents`) elements never are, `findAncestor` skips them. */ export const isContainingBlock = (element: Element, style: CSSStyleDeclaration, absolute?: boolean): boolean => (absolute && !/^(static)?$/.test(style.position)) || // `will-change` forms the containing block before the property itself is applied (unsupported in jsdom) ('transform translate scale rotate perspective'.split(' ') as 'scale'[]).some( property => isSet(style[property]) || String(style.willChange).includes(property), ) || // WebKit ignores filters ((isSet(style.filter) || isSet(style.backdropFilter)) && !isWebKit(element)) || /auto|hidden/.test(style.contentVisibility) || (/size/.test(style.containerType) && (sizeContainerContains ??= probeSizeContainer(element))) || /filter/.test(style.willChange) || /paint|layout|strict|content/.test(style.contain); /** The parent element, through slot assignments and shadow roots but not virtual parents */ export const getPhysicalParent = (element: Element): Element | null => { if (isTopLayer(element)) { return null; } let parent: Node | null = element.assignedSlot || element.parentNode; if (parent && parent.nodeType === 11) { parent = (parent as ShadowRoot).host; } return parent && parent.nodeType === 1 ? (parent as Element) : null; }; /** Open popovers and modal dialogs escape the clipping and containing blocks of their ancestors */ const isTopLayer = (element: Element): boolean => { try { // A single forgiving `:is()` match per ancestor: unsupported pseudo-classes never match, and environments // without `:is()` (e.g. jsdom) throw return element.matches(':is(:popover-open, :modal)'); } catch { return false; } }; /** * Walks the physical ancestors (including SVG elements) of an element up to (excluding) the root element, * stops when the callback returns true and returns that ancestor. Boxless (`display: contents`) ancestors are * skipped: without a box they can't scroll, clip, be positioned or form a containing block. */ export const findAncestor = ( element: Element, callback: (node: Element, style: CSSStyleDeclaration) => unknown, ): Element | null => { const root = getRoot(element); for (let node = getPhysicalParent(element); node && node !== root; node = getPhysicalParent(node)) { const style = getStyle(node); if (style.display !== 'contents' && callback(node, style)) { return node; } } return null; }; /** The ancestors that can clip the element, the closest first */ export const getScrollAncestors = (element: Element): HTMLElement[] => { const ancestors: HTMLElement[] = []; // The position of an out-of-flow box, which escapes the overflow of the ancestors inside its containing block const escaping = (position: string) => (position === 'fixed' || position === 'absolute' ? position : ''); let strategy = escaping(getStyle(element).position); findAncestor(element, (node, style) => { // Positioned descendants escape overflow between themselves and their containing block. if (strategy && isContainingBlock(node, style, strategy === 'absolute')) { strategy = ''; } // The overflow of the body propagates to the viewport, which is always part of the clipping rect if ( !strategy && node !== getDocument(element).body && isHTMLElement(node) && style.display !== 'inline' && /auto|scroll|overlay|hidden|clip/.test(style.overflow + style.overflowX + style.overflowY) ) { ancestors.push(node); } strategy ||= escaping(style.position); }); return ancestors; }; /** CSS dimensions, or the rounded layout dimensions when they differ after rounding */ export const getDimensions = (element: Element): { width: number; height: number; rounded: boolean } => { const css = getStyle(element); const width = parseFloat(css.width) || 0; const height = parseFloat(css.height) || 0; const rounded = isHTMLElement(element) && (Math.round(width) !== element.offsetWidth || Math.round(height) !== element.offsetHeight); return { width: rounded ? (element as HTMLElement).offsetWidth : width, height: rounded ? (element as HTMLElement).offsetHeight : height, rounded, }; }; export const getScale = (element: HTMLElement): Scale => { const bounds = getBounds(element); const { width, height, rounded } = getDimensions(element); // Zero, infinite and NaN scales (e.g. of hidden elements) fall back to 1 const finite = (value: number) => (value && Number.isFinite(value) ? value : 1); return { x: finite((rounded ? Math.round(bounds.width) : bounds.width) / width), y: finite((rounded ? Math.round(bounds.height) : bounds.height) / height), }; }; /** The viewport rect of the element's padding box, in CSS pixels of its own window */ const getClientRect = (element: HTMLElement): PositioningRect & { scale: Scale } => { const bounds = getBounds(element); const scale = getScale(element); return { ...rect( bounds.left + element.clientLeft * scale.x, bounds.top + element.clientTop * scale.y, element.clientWidth * scale.x, element.clientHeight * scale.y, ), scale, }; }; /** The offset and scale of a window's viewport within the top-most same-origin window */ const getWindowSpace = (win: Window): CoordinateSpace => { const space = { x: 0, y: 0, scale: { x: 1, y: 1 } }; for (let frame = win.frameElement; isHTMLElement(frame); frame = getWindow(frame).frameElement) { const bounds = getBounds(frame); const scale = getScale(frame); const css = getStyle(frame); space.x = bounds.left + (frame.clientLeft + (parseFloat(css.paddingLeft) || 0) + space.x) * scale.x; space.y = bounds.top + (frame.clientTop + (parseFloat(css.paddingTop) || 0) + space.y) * scale.y; space.scale.x *= scale.x; space.scale.y *= scale.y; } return space; }; /** Converts a viewport rect of one window to a viewport rect of another (same-origin) window */ const convertWindowRect = (value: PositioningRect, from: Window, to: Window): PositioningRect => { if (from === to) { return value; } const { x, y, scale } = getWindowSpace(from); const target = getWindowSpace(to); const targetScale = target.scale; return rect( (x + value.x * scale.x - target.x) / targetScale.x, (y + value.y * scale.y - target.y) / targetScale.y, (value.width * scale.x) / targetScale.x, (value.height * scale.y) / targetScale.y, ); }; const isStatic = (element: Element) => getStyle(element).position === 'static'; export const getOffsetParent = (element: HTMLElement): HTMLElement | null => { if (isTopLayer(element)) { return null; } const fixed = getStyle(element).position === 'fixed'; let parent = fixed ? null : element.offsetParent; while (isHTMLElement(parent) && /^(TABLE|TD|TH)$/.test(parent.tagName) && isStatic(parent)) { parent = parent.offsetParent; } // Firefox returns a positioned root element, which is normalized to the body like in other browsers const { body } = getDocument(element); if (parent === getRoot(element)) { parent = body; } return isHTMLElement(parent) && (parent !== body || !isStatic(parent)) ? parent : // The element that forms the containing block, `null` is the viewport or the initial containing block (findAncestor( element, (node, style) => isHTMLElement(node) && isContainingBlock(node, style, !fixed), ) as HTMLElement | null); }; /** The viewport offset and scale of the coordinate space used to position the element */ export const getCoordinateSpace = (element: HTMLElement, strategy: Strategy): CoordinateSpace => { const parent = getOffsetParent(element); if (parent) { const { x, y, scale } = getClientRect(parent); return { parent, scale, x: x - parent.scrollLeft * scale.x, y: y - parent.scrollTop * scale.y }; } const bounds = getBounds(getRoot(element)); return { scale: { x: 1, y: 1 }, x: strategy === 'fixed' ? 0 : bounds.left, y: strategy === 'fixed' ? 0 : bounds.top, }; }; /** * The reference rect in the floating element's coordinate space, `context` is the reference element or the element * that a virtual reference is relative to (the floating element's root element by default). */ export const getReferenceRect = ( reference: { getBoundingClientRect(): DOMRect | PositioningRect }, context: Element, floating: HTMLElement, space: CoordinateSpace, strategy: Strategy, ): PositioningRect => { const floatingWindow = getWindow(floating); const referenceWindow = getWindow(context); const clientRect = reference.getBoundingClientRect(); // Virtual rects can have inconsistent x/y; preserve the DOM left/top precedence before converting windows. const bounds = convertWindowRect( 'left' in clientRect ? rect(clientRect.left, clientRect.top, clientRect.width, clientRect.height) : clientRect, referenceWindow, floatingWindow, ); const visual = strategy === 'fixed' && referenceWindow === floatingWindow && !space.parent ? getVisualOffsets(floating) : NO_OFFSET; const { x, y, scale } = space; return rect( (bounds.x + visual.x - x) / scale.x, (bounds.y + visual.y - y) / scale.y, bounds.width / scale.x, bounds.height / scale.y, ); }; /** The visible area of the element within the boundary, in viewport pixels of `floatingWindow` */ export const getClippingRect = ( element: Element, boundary: ClippingBoundary, floatingWindow = getWindow(element), strategy?: Strategy, ): PositioningRect => { const win = getWindow(element); const root = getRoot(element); const viewport = win.visualViewport; // WebKit lays out absolute elements relative to the layout viewport, rect boundaries are in its coordinates too const visual = getVisualOffsets(element); const layout = strategy === 'fixed' ? NO_OFFSET : visual; const clippingAncestors = boundary === 'clippingAncestors'; let clip = viewport ? rect(viewport.offsetLeft - layout.x, viewport.offsetTop - layout.y, viewport.width, viewport.height) : rect(0, 0, root.clientWidth, root.clientHeight); for (const item of clippingAncestors ? getScrollAncestors(element) : ([] as unknown[]).concat(boundary)) { if (item && typeof item === 'object') { const { x, y, width, height } = item as PositioningRect; clip = intersect( clip, 'nodeType' in item ? convertWindowRect(getClientRect(item as HTMLElement), getWindow(item as Node), win) : rect(x - visual.x, y - visual.y, width, height), ); } } const result = convertWindowRect(clip, win, floatingWindow); const frame = win.frameElement; return clippingAncestors && win !== floatingWindow && isHTMLElement(frame) ? intersect(result, getClippingRect(frame, boundary, floatingWindow, strategy)) : result; };