FezVrasta/popper.js

View on GitHub
packages/dom/src/utils/getCssDimensions.ts

Summary

Maintainability
A
0 mins
Test Coverage
import type {Dimensions} from '@floating-ui/core';
import {round} from '@floating-ui/utils';
import {getComputedStyle, isHTMLElement} from '@floating-ui/utils/dom';

export function getCssDimensions(element: Element): Dimensions & {$: boolean} {
  const css = getComputedStyle(element);
  // In testing environments, the `width` and `height` properties are empty
  // strings for SVG elements, returning NaN. Fallback to `0` in this case.
  let width = parseFloat(css.width) || 0;
  let height = parseFloat(css.height) || 0;
  const hasOffset = isHTMLElement(element);
  const offsetWidth = hasOffset ? element.offsetWidth : width;
  const offsetHeight = hasOffset ? element.offsetHeight : height;
  const shouldFallback =
    round(width) !== offsetWidth || round(height) !== offsetHeight;

  if (shouldFallback) {
    width = offsetWidth;
    height = offsetHeight;
  }

  return {
    width,
    height,
    $: shouldFallback,
  };
}