import 'package:flutter/foundation.dart'; /// The longest group name, in characters (the server's limit). const int chatStackGroupNameLimit = 80; /// [raw] as a group name: trimmed, without control characters, at most /// [chatStackGroupNameLimit] characters; null when nothing is left. String? chatStackGroupName(String raw) { final cleaned = raw.replaceAll(RegExp(r'[\u0000-\u001f\u007f]'), ' ').trim(); if (cleaned.isEmpty) return null; final runes = cleaned.runes.toList(); if (runes.length <= chatStackGroupNameLimit) return cleaned; return String.fromCharCodes(runes.take(chatStackGroupNameLimit)).trim(); } /// Which open chats belong to which named group in the chat stack. /// /// A group is the set of chats sharing a name; its order is the open-chat /// order. A group always has two chats or more: one left alone leaves its /// group. The server keeps the names with the open-chat set, so groups sync /// across devices; [replaceAll] applies the server's. class ChatStackGroups extends ChangeNotifier { final Map _bySession = {}; /// The group [sessionId] is in, or null. String? groupOf(String sessionId) => _bySession[sessionId]; /// Every grouped chat and its group. Map get assignments => Map.unmodifiable(_bySession); /// The group names in use. Set get names => _bySession.values.toSet(); /// The chats in [group]. List membersOf(String group) => [ for (final MapEntry(:key, :value) in _bySession.entries) if (value == group) key, ]; /// Takes the server's groups (or a restored set) as they are. void replaceAll(Map assignments) => _change( () => _bySession ..clear() ..addAll(assignments), ); /// Puts [sessionIds] in [group] (joining it, or making it). void assign(Iterable sessionIds, String group) => _change(() { for (final id in sessionIds) { _bySession[id] = group; } }); /// Takes [sessionIds] out of their groups. void unassign(Iterable sessionIds) => _change(() { sessionIds.forEach(_bySession.remove); }); /// Renames [from] to [to]; a name already in use merges the two groups. void rename(String from, String to) => _change(() { for (final entry in _bySession.entries.toList()) { if (entry.value == from) _bySession[entry.key] = to; } }); /// Dissolves [group]: its chats stay open, ungrouped. void ungroup(String group) => _change(() => _bySession.removeWhere((_, value) => value == group)); /// Drops chats that are no longer open. void retain(Set open) => _change(() => _bySession.removeWhere((id, _) => !open.contains(id))); /// The first "Group N" not in use. String nextName() { final used = names; for (var n = 1; ; n++) { final name = 'Group $n'; if (!used.contains(name)) return name; } } void _change(VoidCallback change) { final before = Map.of(_bySession); change(); // A group of one is no group. final counts = {}; for (final group in _bySession.values) { counts[group] = (counts[group] ?? 0) + 1; } _bySession.removeWhere((_, group) => (counts[group] ?? 0) < 2); if (!mapEquals(before, _bySession)) notifyListeners(); } }