import 'dart:async'; import 'package:flutter/widgets.dart'; import '../../../core/api_gateway.dart'; import '../domain/chat_find.dart'; /// A highlighted range in one rendered text, and whether it is the current /// match. typedef ChatFindHighlight = ({int start, int end, bool current}); /// Find in one chat: the query, whether case matters, the matches in the /// loaded transcript and, through the server's scoped search, those in older /// history not loaded yet. /// /// Matches are numbered from the newest: "1 of N" is the newest match and /// stepping on (Enter) goes back in time, so finding never starts by jumping /// to the start of a long history. The loaded matches come first; the /// server's hits in unloaded messages, all older, follow in its order, so a /// match keeps its number when the page holding it loads. class ChatFindController extends ChangeNotifier { ChatFindController({ required this.gateway, required this.sessionId, required this.history, this.debounce = const Duration(milliseconds: 250), }); final ApiGateway gateway; final String sessionId; final Duration debounce; /// Whether the transcript has older history it has not loaded, and the /// cursor its next older page would be read with. final ({bool hasMore, String cursor}) Function() history; String _query = ''; bool _caseSensitive = false; List _units = const []; Set _loadedIds = const {}; /// Loaded matches, newest first. List _local = const []; List _remoteAll = const []; List _remote = const []; bool _remoteMore = false; bool _searching = false; int _index = -1; ChatFindMatch? _currentLocal; int _generation = 0; Timer? _timer; Map>> _byRow = const {}; bool _disposed = false; String get query => _query; bool get caseSensitive => _caseSensitive; /// How many matches are known: loaded ones and the server's in history /// that is not loaded. int get count => _local.length + _remote.length; /// Whether there may be more matches than [count] (the server's search /// stopped at its cap, or is still running). bool get capped => _remoteMore || _searching || _local.length >= chatFindLocalCap; /// The current match's number from the newest (0-based), -1 with none. int get index => _index; /// The current match when it is in the loaded transcript. ChatFindMatch? get current => _index >= 0 && _index < _local.length ? _local[_index] : null; /// The current match when it is in history not loaded yet. ChatFindRemoteHit? get currentRemote { final at = _index - _local.length; return at >= 0 && at < _remote.length ? _remote[at] : null; } /// Bumped whenever the current match moves, so the view reveals it once. int get revealToken => _revealToken; int _revealToken = 0; /// The highlights in [text] of row [rowKey]. List highlightsFor(String rowKey, String text) => _byRow[rowKey]?[text] ?? const []; set query(String value) { if (value == _query) return; _query = value; _restart(); } void toggleCase() { _caseSensitive = !_caseSensitive; _restart(); } /// Moves to an older match ([step] 1) or a newer one (-1), wrapping. void step(int step) { if (count == 0) return; _select((_index + step) % count); } /// Takes the transcript as it is now. The current loaded match stays /// current; otherwise the current number does. Listeners hear of a change /// after this frame, since the transcript calls this while it builds. void updateTranscript( List rows, List keys, Iterable loadedMessageIds, ) { final units = chatFindUnits(rows, keys); _loadedIds = {...loadedMessageIds}; final sameUnits = _sameUnits(units); _units = units; if (sameUnits && _remote.length == _filterRemote().length) return; _recompute(keepCurrent: true); WidgetsBinding.instance.addPostFrameCallback((_) => _notify()); } bool _sameUnits(List units) { if (units.length != _units.length) return false; for (var i = 0; i < units.length; i++) { if (units[i].rowKey != _units[i].rowKey || !identical(units[i].text, _units[i].text) && units[i].text != _units[i].text) { return false; } } return true; } List _filterRemote() => [ for (final hit in _remoteAll) if (!_loadedIds.contains(hit.messageId)) hit, ]; void _restart() { _generation++; _timer?.cancel(); _remoteAll = const []; _remote = const []; _remoteMore = false; _searching = false; _currentLocal = null; _index = -1; _recompute(keepCurrent: false); _searchHistory(); _notify(); } void _recompute({required bool keepCurrent}) { final previous = keepCurrent ? _currentLocal : null; final previousIndex = _index; _local = _query.isEmpty ? const [] : chatFindMatches( _units, _query, caseSensitive: _caseSensitive, ).reversed.toList(); _remote = _filterRemote(); var index = -1; if (previous != null) { index = _local.indexWhere(previous.sameAs); } if (index < 0 && keepCurrent && previousIndex >= 0 && count > 0) { index = previousIndex.clamp(0, count - 1); } if (index < 0 && count > 0) index = 0; _setIndex(index, reveal: !keepCurrent || index != previousIndex); _rebuildHighlights(); } void _select(int index) { _setIndex(index, reveal: true); _rebuildHighlights(); _notify(); } void _setIndex(int index, {required bool reveal}) { _index = index; _currentLocal = current; if (reveal && index >= 0) _revealToken++; } void _rebuildHighlights() { final byRow = >>{}; final now = current; for (final match in _local) { byRow .putIfAbsent(match.rowKey, () => {}) .putIfAbsent(match.unit.text, () => []) .add(( start: match.start, end: match.end, current: identical(match, now), )); } _byRow = byRow; } /// Asks the server for matches in the history before the transcript's /// loaded pages, after a short pause in typing. Without older history /// there is nothing to ask. void _searchHistory() { final older = history(); if (_query.isEmpty || !older.hasMore) return; final generation = _generation; _searching = true; _timer = Timer(debounce, () { unawaited(_fetch(generation, '0|${older.cursor}')); }); } Future _fetch(int generation, String cursor) async { var next = cursor; final hits = []; try { while (true) { final reply = await gateway.call('search', { 'search': { 'query': _query, 'kind': 'chat', 'scope': 'chat:$sessionId', 'cursor': next, 'case_sensitive': _caseSensitive, 'limit': 200, }, }); if (_disposed || generation != _generation) return; hits.addAll(ChatFindRemoteHit.fromReply(reply)); final results = reply['search_results']; next = results is Map ? '${results['next_cursor'] ?? ''}' : ''; _remoteAll = List.unmodifiable(hits); _remoteMore = next.isNotEmpty && hits.length >= chatFindRemoteCap; _recompute(keepCurrent: true); _notify(); if (next.isEmpty || hits.length >= chatFindRemoteCap) break; } } catch (_) { // An older server without scoped search, or a dropped socket: the // loaded transcript's matches still stand. if (_disposed || generation != _generation) return; } _searching = false; _notify(); } void _notify() { if (!_disposed) notifyListeners(); } @override void dispose() { _disposed = true; _timer?.cancel(); super.dispose(); } }