fromComments static method

List<SocialCommentNode> fromComments(
  1. List<Comment> comments
)

Implementation

static List<SocialCommentNode> fromComments(List<Comment> comments) {
  final unique = <String, Comment>{};
  for (final comment in comments) {
    unique[comment.id] = comment;
  }

  final children = <String, List<Comment>>{};
  final roots = <Comment>[];

  for (final comment in unique.values) {
    final parentId = comment.parentCommentId;
    if (parentId == null || parentId == comment.id || !unique.containsKey(parentId)) {
      roots.add(comment);
    } else {
      children.putIfAbsent(parentId, () => <Comment>[]).add(comment);
    }
  }

  int compareNewestFirst(Comment left, Comment right) {
    final byDate = right.createdAt.compareTo(left.createdAt);
    return byDate != 0 ? byDate : right.id.compareTo(left.id);
  }

  roots.sort(compareNewestFirst);
  for (final list in children.values) {
    list.sort(compareNewestFirst);
  }

  final visited = <String>{};
  SocialCommentNode build(Comment comment) {
    // The server only permits replying to an existing comment, so cycles
    // should not be produced by valid data. This guard also makes the local
    // projection safe if a malformed response is encountered.
    if (!visited.add(comment.id)) {
      return SocialCommentNode(comment: comment, replies: const []);
    }

    final replies = (children[comment.id] ?? const <Comment>[])
        .where((reply) => !visited.contains(reply.id))
        .map(build)
        .toList(growable: false);
    return SocialCommentNode(comment: comment, replies: replies);
  }

  final tree = roots.map(build).toList(growable: true);

  // Defensive fallback: malformed cyclic components have no root. Preserve
  // their comments as standalone nodes rather than dropping them.
  for (final comment in unique.values) {
    if (visited.add(comment.id)) {
      tree.add(SocialCommentNode(comment: comment, replies: const []));
    }
  }

  return List.unmodifiable(tree);
}