import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../../../core/api_gateway.dart'; import '../../../ui/adaptive/app_popups.dart'; import '../domain/chat_quick_switch.dart'; import '../domain/chat_quick_switch_order.dart'; import '../ui/sessions/chat_sessions_controller.dart'; import 'chat_quick_switch_keys.dart'; import 'chat_quick_switch_row.dart'; /// Shows the chat quick switcher over the Chat destination: a search field /// with the keyboard in it above the open chats ([chatQuickSwitchCandidates]), /// most recently used first ([recent]), narrowed and ranked as the operator /// types ([chatQuickSwitchMatches]). With no query the chat used before /// [currentId] is selected, so the shortcut and then Enter go back to it; /// with one, the best match. A query also lists the closed chats it matches /// under "Closed", after the open ones. Ctrl+N / Ctrl+P and Down / Up move /// the selection, wrapping, and Enter or a click chooses it. Esc closes it. /// /// A centred dialog on a wide app, a full-width bottom sheet on a phone, on /// the root navigator either way. Returns the route so a second press of the /// shortcut can close it; [onSelected] gets the chosen row once it closed (a /// closed row is still closed: the caller reopens it). ModalRoute showChatQuickSwitch( BuildContext context, { required ChatSessionsController sessions, required ValueChanged onSelected, String? Function(JsonMap session)? serverName, List Function()? recent, String? currentId, }) { final navigator = Navigator.of(context, rootNavigator: true); Widget content(BuildContext context) => ChatQuickSwitch( sessions: sessions, serverName: serverName, recent: recent?.call() ?? const [], currentId: currentId, ); final ModalRoute route = usesDesktopPopups(context) ? DialogRoute( context: context, themes: InheritedTheme.capture(from: context, to: navigator.context), barrierLabel: 'Close the chat switcher', builder: (context) => Dialog( alignment: const Alignment(0, -0.6), clipBehavior: Clip.antiAlias, child: ConstrainedBox( constraints: BoxConstraints( maxWidth: 560, maxHeight: MediaQuery.sizeOf(context).height * 0.7, ), child: content(context), ), ), ) : ModalBottomSheetRoute( builder: content, isScrollControlled: true, showDragHandle: true, useSafeArea: true, capturedThemes: InheritedTheme.capture( from: context, to: navigator.context, ), barrierLabel: 'Close the chat switcher', modalBarrierColor: Theme.of( context, ).bottomSheetTheme.modalBarrierColor, ); navigator.push(route).then((row) { if (row != null) onSelected(row); }); return route; } /// Closes a quick switcher [showChatQuickSwitch] opened, if it is still open. void closeChatQuickSwitch(ModalRoute route) { final navigator = route.navigator; if (navigator == null || !route.isActive) return; if (route.isCurrent) { navigator.pop(); } else { navigator.removeRoute(route); } } /// The switcher's content: the field and the matching chats. class ChatQuickSwitch extends StatefulWidget { const ChatQuickSwitch({ super.key, required this.sessions, this.serverName, this.recent = const [], this.currentId, }); final ChatSessionsController sessions; final String? Function(JsonMap session)? serverName; /// The chats used on this device, most recent first. final List recent; /// The chat shown when the switcher opened, if any. final String? currentId; @override State createState() => _ChatQuickSwitchState(); } class _ChatQuickSwitchState extends State { final _query = TextEditingController(); final _rowKeys = {}; /// The row the operator moved to; null keeps the initial selection /// ([chatQuickSwitchInitialSelection]). int? _moved; List _shown = const []; /// How many of [_shown] are open chats; the closed ones follow. int _openCount = 0; @override void dispose() { _query.dispose(); super.dispose(); } void _queryChanged(String _) => setState(() => _moved = null); int get _selected => _moved ?? chatQuickSwitchInitialSelection( _shown, currentId: widget.currentId, emptyQuery: _query.text.trim().isEmpty, ); /// The open matches, then (with a query) the closed ones. void _match() { final query = _query.text; final open = chatQuickSwitchMatches( chatQuickSwitchByRecency( chatQuickSwitchCandidates(widget.sessions.sessions), widget.recent, ), query, serverName: widget.serverName, ); final closed = query.trim().isEmpty ? const [] : chatQuickSwitchMatches( chatQuickSwitchClosed(widget.sessions.sessions), query, serverName: widget.serverName, ); _openCount = open.length; _shown = [...open, ...closed]; } /// Moves the selection [step] rows, wrapping, and scrolls it into view at /// the edge it moved towards. void _step(int step) { if (_shown.isEmpty) return; final from = _selected.clamp(0, _shown.length - 1); final index = (from + step) % _shown.length; setState(() => _moved = index); final id = '${_shown[index]['id'] ?? ''}'; final policy = step < 0 ? ScrollPositionAlignmentPolicy.keepVisibleAtStart : ScrollPositionAlignmentPolicy.keepVisibleAtEnd; WidgetsBinding.instance.addPostFrameCallback((_) { final row = _rowKeys[id]?.currentContext; if (row != null) Scrollable.ensureVisible(row, alignmentPolicy: policy); }); } void _choose([JsonMap? row]) { final chosen = row ?? (_shown.isEmpty ? null : _shown[_selected.clamp(0, _shown.length - 1)]); if (chosen != null) Navigator.of(context).pop(chosen); } @override Widget build(BuildContext context) { final field = Padding( padding: const EdgeInsets.fromLTRB(16, 16, 16, 8), child: Focus( canRequestFocus: false, skipTraversal: true, onKeyEvent: (_, event) => chatQuickSwitchKey( event, HardwareKeyboard.instance, onStep: _step, onChoose: _choose, ), child: TextField( key: const Key('chat-quick-switch-field'), controller: _query, autofocus: true, onChanged: _queryChanged, textInputAction: TextInputAction.go, decoration: const InputDecoration( hintText: 'Switch to a chat', prefixIcon: Icon(Icons.search), border: OutlineInputBorder(), isDense: true, ), ), ), ); final list = ListenableBuilder( listenable: widget.sessions, builder: (context, _) { _match(); if (_shown.isEmpty) { return Padding( padding: const EdgeInsets.all(24), child: Text( widget.sessions.loading && widget.sessions.sessions.isEmpty ? 'Loading chats…' : _query.text.trim().isEmpty ? 'No open chats.' : 'No chats match.', key: const Key('chat-quick-switch-empty'), textAlign: TextAlign.center, ), ); } final selected = _selected.clamp(0, _shown.length - 1); // Every row is built (open chats are few), so a wrap from the last // row to the first can scroll to it. return SingleChildScrollView( padding: const EdgeInsets.only(bottom: 8), child: Column( mainAxisSize: MainAxisSize.min, children: [ for (final (index, row) in _shown.indexed) ...[ if (index == _openCount) const ChatQuickSwitchSectionHeader(title: 'Closed'), ChatQuickSwitchRow( key: _rowKeys.putIfAbsent( '${row['id'] ?? ''}', GlobalKey.new, ), session: row, serverName: widget.serverName?.call(row), selected: index == selected, closed: index >= _openCount, markers: index >= _openCount ? const [] : chatQuickSwitchMarkers( row, unread: widget.sessions.isUnseen(row), ), onTap: () => _choose(row), ), ], ], ), ); }, ); return Semantics( label: 'Switch chat', explicitChildNodes: true, child: Material( type: MaterialType.transparency, child: Padding( padding: EdgeInsets.only( bottom: MediaQuery.viewInsetsOf(context).bottom, ), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ field, Flexible(child: list), ], ), ), ), ); } }