import 'package:flutter/foundation.dart'; import 'chat_stack_entry.dart'; /// One item of the open column's top level: a chat, or a group of chats. @immutable sealed class ChatStackNode { const ChatStackNode(); /// Stable across rebuilds and reorders: keys widgets and drag state. String get key; /// The chats it stands for, in order. List get entries; /// Whether the chat on screen is in it. bool get current => entries.any((entry) => entry.current); /// Unanswered approvals and questions across its chats. int get awaitingOperator => entries.fold(0, (sum, entry) => sum + entry.awaitingOperator); } /// A chat on its own. class ChatStackChatNode extends ChatStackNode { const ChatStackChatNode(this.entry); final ChatStackEntry entry; @override String get key => 'chat:${entry.paneId}'; @override List get entries => [entry]; } /// A named group of chats. class ChatStackGroupNode extends ChatStackNode { const ChatStackGroupNode(this.name, this.entries); final String name; @override final List entries; @override String get key => 'group:$name'; } /// [entries] (in the open-chat order) as the top level shows them: each /// group where its first chat is, holding its chats in order, and the /// ungrouped chats on their own. List chatStackNodes(List entries) { final groups = >{}; for (final entry in entries) { final group = entry.group; if (group != null) (groups[group] ??= []).add(entry); } final nodes = []; final placed = {}; for (final entry in entries) { final group = entry.group; final members = group == null ? null : groups[group]; if (group == null || members == null || members.length < 2) { nodes.add(ChatStackChatNode(entry)); } else if (placed.add(group)) { nodes.add(ChatStackGroupNode(group, List.unmodifiable(members))); } } return nodes; } /// The open-chat order (session ids) [nodes] stand for, each group's chats /// together. List chatStackOrder(Iterable nodes) => [ for (final node in nodes) for (final entry in node.entries) entry.sessionId, ];