asNodeSelector function

NodeSelector? asNodeSelector(
  1. Object? selector
)

Implementation

NodeSelector? asNodeSelector(Object? selector) {
  if (selector == null) return null;

  if (selector is NodeSelector) {
    return selector;
  } else if (selector is String) {
    var str = selector.trim();
    if (str.isEmpty) return null;

    var selectors = str.split(_selectorDelimiter);
    if (selectors.any((s) => s.isEmpty)) {
      selectors = selectors.where((s) => s.isNotEmpty).toList();
    }

    if (selectors.isEmpty) {
      return null;
    } else if (selectors.length == 1) {
      // id:
      if (str.startsWith('#')) {
        return (n) => n is DOMElement && n.id == str.substring(1);
      }
      // class
      else if (str.startsWith('.')) {
        var classes = str.substring(1).split('.');
        return (n) => n is DOMElement && n.containsAllClasses(classes);
      }
      // tag
      else {
        return (n) => n is DOMElement && n.tag == str;
      }
    } else {
      var multiSelector = selectors.map(asNodeSelector).toList();
      return (n) => multiSelector.nonNulls.any((f) => f(n));
    }
  } else if (selector is DOMNode) {
    return (n) => n == selector;
  } else if (selector is List) {
    if (selector.isEmpty) return null;
    if (selector.length == 1) return asNodeSelector(selector[0]);

    var multiSelector = selector.map(asNodeSelector).toList();
    return (n) => multiSelector.nonNulls.any((f) => f(n));
  }

  throw ArgumentError(
      "Can't use NodeSelector of type: [ ${selector.runtimeType}");
}