collectJsonSearchHits function

List<JsonSearchHit> collectJsonSearchHits(
  1. dynamic data,
  2. String query
)

Depth-first search hits, in the same order the tree paints them.

Implementation

List<JsonSearchHit> collectJsonSearchHits(dynamic data, String query) {
  if (query.isEmpty) return const [];

  final hits = <JsonSearchHit>[];
  final pattern = RegExp(RegExp.escape(query), caseSensitive: false);

  void add(List<Object> path, bool inKey, String text) {
    var occurrence = 0;
    for (final _ in pattern.allMatches(text)) {
      hits.add(
        JsonSearchHit(
          path: List<Object>.from(path),
          inKey: inKey,
          occurrence: occurrence,
        ),
      );
      occurrence++;
    }
  }

  void walk(dynamic node, List<Object> path) {
    if (node is Map<String, dynamic>) {
      for (final entry in node.entries) {
        final childPath = [...path, entry.key];
        add(childPath, true, '"${entry.key}"');
        final value = entry.value;
        if (value is Map<String, dynamic> || value is List) {
          walk(value, childPath);
        } else {
          add(childPath, false, formatJsonLeaf(value));
        }
      }
    } else if (node is List) {
      for (var i = 0; i < node.length; i++) {
        final childPath = [...path, i];
        add(childPath, true, '[$i]');
        final value = node[i];
        if (value is Map<String, dynamic> || value is List) {
          walk(value, childPath);
        } else {
          add(childPath, false, formatJsonLeaf(value));
        }
      }
    }
  }

  if (data is Map<String, dynamic> || data is List) {
    walk(data, const []);
  } else {
    add(const [], false, data == null ? 'null' : data.toString());
  }
  return hits;
}