getComputedStyle function

CSSStyleDeclaration getComputedStyle({
  1. Element? parent,
  2. HTMLElement? element,
  3. String? classes,
  4. String? style,
  5. bool? hidden,
})

Returns a CSSStyleDeclaration from an element.

Implementation

CSSStyleDeclaration getComputedStyle({
  Element? parent,
  HTMLElement? element,
  String? classes,
  String? style,
  bool? hidden,
}) {
  parent ??= document.body;
  hidden ??= true;

  element ??= HTMLDivElement();

  var prevHidden = element.hidden;

  element.hidden = hidden.toJS;

  if (classes != null && classes.isNotEmpty) {
    var allClasses = classes
        .split(RegExp(r'\s+'))
        .where((s) => s.isNotEmpty)
        .toList();
    for (var c in allClasses) {
      element.classList.add(c);
    }
  }

  if (style != null && style.isNotEmpty) {
    element.style.cssText = style;
  }

  parent!.appendChild(element);

  var computedStyle = window.getComputedStyle(element);

  // Copy property by property: a computed style's `cssText` is empty in
  // Chromium (and Firefox).
  var computedStyle2 = newCSSStyleDeclaration();
  for (var i = 0; i < computedStyle.length; ++i) {
    var name = computedStyle.item(i);
    computedStyle2.setProperty(name, computedStyle.getPropertyValue(name));
  }

  element.remove();

  element.hidden = prevHidden;

  return computedStyle2;
}