import 'dart:async'; import 'dart:math' as math; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import '../../../core/api_gateway.dart'; import '../../../ui/input/keyboard_owner.dart'; import '../shell/chat_shell_terminal_find_bar.dart'; import '../ui/transcript/chat_find_highlight.dart'; import 'chat_find_bar.dart'; import 'chat_find_controller.dart'; import 'chat_thread_controller.dart'; import 'chat_thread_view.dart'; import 'composer_focus_request.dart'; /// Whether [event] is find's key: Cmd+F on Apple platforms, Ctrl+F /// elsewhere, without Shift or Alt. bool chatFindShortcut(KeyEvent event, HardwareKeyboard keyboard) { if (event is! KeyDownEvent || event.logicalKey != LogicalKeyboardKey.keyF) { return false; } final apple = defaultTargetPlatform == TargetPlatform.macOS || defaultTargetPlatform == TargetPlatform.iOS; final ctrl = keyboard.isControlPressed; final meta = keyboard.isMetaPressed; if (keyboard.isAltPressed || keyboard.isShiftPressed) return false; return apple ? meta && !ctrl : ctrl && !meta; } /// Find in one open chat: Ctrl+F (Cmd+F) opens the bar over the transcript, /// matches are highlighted, the current one is scrolled into view (reading /// older pages until it is loaded), and Esc closes the bar and returns the /// keyboard to the composer. mixin ChatFindHost on State { ScrollController get findScroll; ChatThreadController get findThread; /// Stops the transcript following its end while find moves it. void findReleaseFollow(); /// Lets the transcript decide again whether it follows its end. void findSettleFollow(); final findTargets = ChatFindTargets(); final FocusNode _findFocus = FocusNode(debugLabel: 'chat-find'); ChatFindController? _find; int _revealed = 0; Map _rowIndex = const {}; ChatFindController? get find => _find; void disposeFind() { _find?.dispose(); _findFocus.dispose(); } /// The pane's key handler: find's shortcut from anywhere in this chat, /// except a terminal (where Ctrl+F is the shell's) and its own find bar. KeyEventResult findKey(FocusNode node, KeyEvent event) { if (!chatFindShortcut(event, HardwareKeyboard.instance)) { return KeyEventResult.ignored; } if (primaryFocusIsTypingSurface()) return KeyEventResult.ignored; final focused = FocusManager.instance.primaryFocus?.context; if (focused?.findAncestorWidgetOfExactType() != null) { return KeyEventResult.ignored; } openFind(); return KeyEventResult.handled; } /// Opens the find bar, or focuses its field when it is open. void openFind() { if (_find == null) { final find = ChatFindController( gateway: widget.gateway, sessionId: widget.sessionId, history: () => (hasMore: findThread.hasMore, cursor: findThread.cursor), )..addListener(_findChanged); setState(() => _find = find); } // The field's autofocus would not take the keyboard from the composer, // which holds it in the same scope. WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted && _find != null) _findFocus.requestFocus(); }); } void closeFind() { final find = _find; if (find == null) return; setState(() => _find = null); find.dispose(); findSettleFollow(); ChatComposerFocusScope.maybeOf(context)?.requests.request(widget.sessionId); } void _findChanged() { final find = _find; if (find == null || find.revealToken == _revealed) return; _revealed = find.revealToken; unawaited(_reveal(find, _revealed)); } /// Hands the transcript as built to an open find. void findTranscript(List rows, List keys) { final find = _find; if (find == null) return; _rowIndex = {for (var i = 0; i < keys.length; i++) keys[i]: i}; find.updateTranscript(rows, keys, [ for (final message in findThread.messages) if ('${message['id'] ?? ''}'.isNotEmpty) '${message['id']}', ]); } /// [transcript] inside find's scope. Widget findScope(Widget transcript) => ChatFindScope(controller: _find, targets: findTargets, child: transcript); /// The bar over the transcript's top end while find is open. Widget? findBar({required double top, required double end}) { final find = _find; if (find == null) return null; return PositionedDirectional( top: top, start: 8, end: end, child: Align( alignment: AlignmentDirectional.topEnd, child: ChatFindBar( find: find, focus: _findFocus, onStep: find.step, onClose: closeFind, ), ), ); } /// Brings find's current match into view: reads older pages until it is /// loaded, scrolls toward its row until the row is built, then centres the /// match. A newer move ([token]) abandons this one. Future _reveal(ChatFindController find, int token) async { bool stale() => !mounted || _find != find || find.revealToken != token; findReleaseFollow(); for (var attempt = 0; attempt < 120; attempt++) { if (stale()) return; if (find.currentRemote != null) { if (!findThread.hasMore) return; if (!findThread.loading) await findThread.loadOlder(); await WidgetsBinding.instance.endOfFrame; continue; } final match = find.current; if (match == null || !findScroll.hasClients) return; final rects = findTargets.textFor(match.rowKey, match.unit.text); final row = findTargets.rows[match.rowKey]; if (rects != null && row != null && row.mounted) { if (_centre(row, rects, match.start, match.end)) break; } else if (!_stepToward(match.unit.rowIndex)) { return; } await WidgetsBinding.instance.endOfFrame; } if (!stale()) findSettleFollow(); } /// Scrolls so the match is in the middle of the viewport when it is not /// already comfortably in view; true once it is placed. bool _centre(BuildContext row, ChatFindRects rects, int start, int end) { final object = row.findRenderObject(); if (object == null || !object.attached) return false; final viewport = RenderAbstractViewport.maybeOf(object); if (viewport is! RenderBox || !(viewport as RenderBox).hasSize) { return false; } final box = viewport as RenderBox; final boxes = rects(start, end, box); if (boxes.isEmpty) { unawaited(Scrollable.ensureVisible(row, alignment: 0.5)); return false; } final match = boxes.reduce((a, b) => a.expandToInclude(b)); final height = box.size.height; final margin = math.min(64.0, height / 4); if (match.top >= margin && match.bottom <= height - margin) return true; final position = findScroll.position; final target = (position.pixels + match.center.dy - height / 2).clamp( position.minScrollExtent, position.maxScrollExtent, ); if ((target - position.pixels).abs() < 1) return true; position.jumpTo(target); return false; } /// Moves the transcript a screen toward row [index] when it is not built; /// false when it cannot move further. bool _stepToward(int index) { final built = [ for (final entry in findTargets.rows.entries) if (entry.value.mounted && _rowIndex[entry.key] != null) _rowIndex[entry.key]!, ]; final position = findScroll.position; final older = built.isEmpty || index < built.reduce(math.min); final distance = position.viewportDimension * 0.8; final target = (position.pixels + (older ? -distance : distance)).clamp( position.minScrollExtent, position.maxScrollExtent, ); if ((target - position.pixels).abs() < 1) return false; position.jumpTo(target); return true; } }