import 'chat_stack_entry.dart'; import 'chat_stack_node.dart'; /// The open-chat order after the node at [from] moves to [to]. List chatStackMoved(List nodes, int from, int to) { final next = List.of(nodes); next.insert(to.clamp(0, nodes.length - 1), next.removeAt(from)); return chatStackOrder(next); } /// What dropping one node onto another does: [join] chats go into [group] /// (a new group when [created]), and the open chats take [order], the /// group's chats together where the target was. typedef ChatStackJoin = ({ List join, String group, bool created, List order, }); /// Dropping the node at [from] onto the one at [onto]: /// - a chat onto a chat makes a group of the two ([newName]), the target /// first; /// - a chat onto a group joins it, last; /// - a group onto a chat takes the chat in, last; /// - a group onto a group merges into the target. ChatStackJoin chatStackJoined( List nodes, int from, int onto, String Function() newName, ) { final dragged = nodes[from]; final target = nodes[onto]; final String group; final bool created; final List joining; final ChatStackNode host; switch ((dragged, target)) { case (ChatStackChatNode(), ChatStackChatNode()): group = newName(); created = true; joining = [...target.entries, ...dragged.entries]; host = target; case (_, ChatStackGroupNode(:final name)): group = name; created = false; joining = dragged.entries; host = target; case (ChatStackGroupNode(:final name), ChatStackChatNode()): group = name; created = false; joining = target.entries; host = dragged; } final members = [ ...host.entries, for (final entry in [...dragged.entries, ...target.entries]) if (!host.entries.contains(entry)) entry, ]; // The merged group stands where its host stood. final order = [ for (final node in nodes) if (identical(node, host)) ...members.map((entry) => entry.sessionId) else if (!identical(node, dragged) && !identical(node, target)) ...node.entries.map((entry) => entry.sessionId), ]; return ( join: [for (final entry in joining) entry.sessionId], group: group, created: created, order: order, ); } /// The open-chat order with [group]'s chats in [groupOrder] (session ids). List chatStackRegrouped( List nodes, String group, List groupOrder, ) => [ for (final node in nodes) if (node is ChatStackGroupNode && node.name == group) ...groupOrder else ...node.entries.map((entry) => entry.sessionId), ]; /// The open-chat order with [sessionId] taken out of [group] and placed /// right after it (on the top level, beside the group it left). List chatStackLeft( List nodes, String group, String sessionId, ) => [ for (final node in nodes) if (node is ChatStackGroupNode && node.name == group) ...[ for (final entry in node.entries) if (entry.sessionId != sessionId) entry.sessionId, sessionId, ] else ...node.entries.map((entry) => entry.sessionId), ];