import '../../../core/api_gateway.dart'; import 'chat_sessions.dart'; /// The chats the quick switcher (Ctrl+K on the Chat destination) offers with /// no query: every open chat in the order the list draws them, starred first /// (by name), then Chats by directory in server recency. Closed chats are left /// out, and a folded section does not hide its rows here. List chatQuickSwitchCandidates(List sessions) => chatSessionsInListOrder( chatSessionSections( sessions .where((row) => row['closed_at'] == null && row['closed'] != true) .toList(), ), isOpen: (_) => true, ); /// The harness a row runs, as the list's icon reads it (an unnamed one is /// OpenCode). String chatQuickSwitchHarness(JsonMap session) { final backend = '${session['backend'] ?? ''}'.trim(); return backend.isEmpty ? 'opencode' : backend; } /// [candidates] narrowed to [query] and ranked, best first. /// /// Every whitespace-separated word of the query must occur, ignoring case, in /// the chat's title, directory, workspace, harness or machine name /// ([serverName]; federated rows name their machine there). A word ranks by /// where it matched, best first: the start of the title, the start of a word /// in the title, the start of a word in the other fields, anywhere in the /// title, anywhere else. A chat's rank is the sum over the query's words, and /// equal ranks keep [candidates]' order. List chatQuickSwitchMatches( List candidates, String query, { String? Function(JsonMap session)? serverName, }) { final words = query.toLowerCase().split(RegExp(r'\s+')) ..removeWhere((word) => word.isEmpty); if (words.isEmpty) return candidates; final ranked = <({int rank, int index, JsonMap row})>[]; for (var index = 0; index < candidates.length; index++) { final row = candidates[index]; final title = chatSessionTitle(row).toLowerCase(); final other = [ row['directory'], row['workspace'], chatQuickSwitchHarness(row), serverName?.call(row) ?? row['_server_name'], ].where((value) => value != null).join('\u0000').toLowerCase(); var rank = 0; for (final word in words) { final tier = _tier(word, title, other); if (tier == null) { rank = -1; break; } rank += tier; } if (rank >= 0) ranked.add((rank: rank, index: index, row: row)); } ranked.sort((a, b) => a.rank != b.rank ? a.rank - b.rank : a.index - b.index); return [for (final hit in ranked) hit.row]; } int? _tier(String word, String title, String other) { if (title.startsWith(word)) return 0; if (_startsWord(title, word)) return 1; if (_startsWord(other, word)) return 2; if (title.contains(word)) return 3; if (other.contains(word)) return 4; return null; } /// Whether [word] occurs in [text] at the start of one of its words (after /// anything that is not a letter or digit). bool _startsWord(String text, String word) { for (var at = text.indexOf(word); at >= 0; at = text.indexOf(word, at + 1)) { if (at == 0 || !_alphanumeric.hasMatch(text[at - 1])) return true; } return false; } final _alphanumeric = RegExp(r'[\p{L}\p{N}]', unicode: true);