$htmlRoot function

DOMElement? $htmlRoot(
  1. Object? html, {
  2. String? defaultRootTag,
  3. bool? defaultTagDisplayInlineBlock,
})

Implementation

DOMElement? $htmlRoot(Object? html,
    {String? defaultRootTag, bool? defaultTagDisplayInlineBlock}) {
  var nodes = $html(html);
  if (nodes.isEmpty) return null;

  if (nodes.length > 1) {
    nodes.removeWhere((e) => e is TextNode && e.text.trim().isEmpty);
    if (nodes.length == 1) {
      return nodes[0] as DOMElement;
    } else {
      Map<String, String>? attributes;
      if (defaultRootTag == null) {
        var onlyText = listMatchesAll(nodes,
            (e) => e is TextNode || (e is DOMElement && _isTextTag(e.tag)));
        defaultRootTag = onlyText ? 'span' : 'div';
      }

      if (!_isTextTag(defaultRootTag) &&
          (defaultTagDisplayInlineBlock ?? true)) {
        attributes = {'style': 'display: inline-block'};
      }

      return $tag(defaultRootTag, content: nodes, attributes: attributes);
    }
  } else {
    var node = nodes.single;
    if (node is DOMElement) {
      return node;
    } else {
      return $span(content: node);
    }
  }
}