diff --git a/app/lib/features/chat/chat_screen_float.dart b/app/lib/features/chat/chat_screen_float.dart index afc224e3..d2ae80a5 100644 --- a/app/lib/features/chat/chat_screen_float.dart +++ b/app/lib/features/chat/chat_screen_float.dart @@ -8,7 +8,8 @@ mixin _ChatScreenFloat on State, _ChatScreenWorkspace { void _bindWindows() { final windows = widget.windows; if (windows == null) return; - _workspace.showOutside = windows.show; + _workspace.showOutside = _showOutside; + windows.manager.addListener(_windowsChanged); windows.tiling = _tiling = ChatTiling( holds: _workspace.holdsSession, dock: _dockSession, @@ -35,9 +36,99 @@ mixin _ChatScreenFloat on State, _ChatScreenWorkspace { if (windows != null && identical(windows.tiling, _tiling)) { windows.tiling = null; } + windows?.manager.removeListener(_windowsChanged); _workspace.showOutside = null; } + /// A chat out in a window comes to the top on a wide layout. A phone + /// ignores floating: the chat leaves its (hidden) window and opens as a + /// pane, still floating in the server's set. + bool _showOutside(String sessionId) { + final windows = widget.windows; + if (windows == null) return false; + if (!_phoneIgnoresFloat) return windows.show(sessionId); + _holdForPhone(windows, sessionId); + return false; + } + + /// Takes [sessionId] out of its window, to be tiled on this phone layout. + void _holdForPhone(ChatWindows windows, String sessionId) { + final window = windows.windows + .where((window) => window.contentId == sessionId) + .firstOrNull; + if (window == null) return; + _phoneDocked.add(sessionId); + windows.manager.close(window.id); + } + + /// Whether the last build was a phone's layout, which tiles floating chats. + bool? _builtPhoneFloat; + bool _followingFloat = false; + + /// Called from build: a change between a phone and a wide layout moves + /// the floating chats between panes and windows after the frame. + void _trackFloatLayout() { + if (widget.windows == null) return; + final phone = _phoneIgnoresFloat; + if (phone == _builtPhoneFloat) return; + _builtPhoneFloat = phone; + _followFloatLayoutSoon(); + } + + void _windowsChanged() { + if (_builtPhoneFloat == true && + (widget.windows?.windows.isNotEmpty ?? false)) { + _followFloatLayoutSoon(); + } + } + + void _followFloatLayoutSoon() { + if (_followingFloat) return; + _followingFloat = true; + WidgetsBinding.instance.addPostFrameCallback((_) { + _followingFloat = false; + if (mounted) _followFloatLayout(); + }); + } + + /// On a phone every floating chat becomes a pane (the chat on screen + /// stays); on a wide layout the chats held that way float again. + void _followFloatLayout() { + final windows = widget.windows; + if (windows == null) return; + final phone = _phoneIgnoresFloat; + final ids = phone + ? windows.floatingSessionIds.toList() + : _phoneDocked.toList(); + if (ids.isEmpty) return; + // One write for the whole move: the chats stay floating in the set. + _applyingServerWorkspace = true; + try { + if (phone) { + final active = _workspace.activePaneId; + for (final id in ids) { + _holdForPhone(windows, id); + _workspace.dock(id); + } + if (active != null) _workspace.activate(active); + } else { + for (final id in ids) { + final pane = _workspace.panes + .where((pane) => pane.sessionId == id) + .firstOrNull; + if (pane == null) continue; + _workspace.detach(pane.id); + windows.float(id); + } + _phoneDocked.clear(); + } + } finally { + _applyingServerWorkspace = false; + } + _syncOpenWorkspace(); + if (!phone && _workspace.paneCount == 0) _back(); + } + /// Panes float only on a wide layout, beside the chat list. bool get _floatsHere => widget.windows != null && !_pageOpen && showsListBesideDetail(context); diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart index 16cbbc7a..6bff87db 100644 --- a/app/lib/features/chat/chat_screen_workspace.dart +++ b/app/lib/features/chat/chat_screen_workspace.dart @@ -113,9 +113,18 @@ mixin _ChatScreenWorkspace on State { ChatWorkspaceBinding? _workspaceBinding; String? _workspaceScope; + /// Chats that float in windows on a wide layout, held as ordinary panes + /// while the layout is a phone's (see `_ChatScreenFloat`). They stay + /// floating in the server's set, so a wide layout floats them again. + final Set _phoneDocked = {}; + + /// Whether this layout ignores floating: a phone's, where windows are + /// hidden and the chats are navigated one at a time. + bool get _phoneIgnoresFloat => + mounted && widget.windows != null && !showsListBesideDetail(context); + Iterable _serverWorkspaceEntries() sync* { - final floating = - widget.windows?.floatingSessionIds.toSet() ?? const {}; + final floating = {...?widget.windows?.floatingSessionIds, ..._phoneDocked}; for (final pane in _workspace.panes) { yield ChatOpenWorkspaceEntry( pane.sessionId, @@ -231,9 +240,24 @@ mixin _ChatScreenWorkspace on State { ]); } _applyingServerWorkspace = true; + final phone = _phoneIgnoresFloat; try { final windows = widget.windows; - if (windows != null) { + for (final entry in snapshot.entries) { + if (!entry.floating) _phoneDocked.remove(entry.sessionId); + } + if (windows != null && phone) { + // A phone tiles the floating chats too; they float again when the + // layout is wide. + for (final entry in snapshot.entries.where((e) => e.floating)) { + _phoneDocked.add(entry.sessionId); + final window = windows.windows + .where((window) => window.contentId == entry.sessionId) + .firstOrNull; + if (window != null) windows.manager.close(window.id); + } + } + if (windows != null && !phone) { final entriesBySession = { for (final entry in snapshot.entries) entry.sessionId: entry, }; @@ -259,7 +283,7 @@ mixin _ChatScreenWorkspace on State { } _workspace.reconcileSessions( snapshot.entries - .where((entry) => !entry.floating) + .where((entry) => phone || !entry.floating) .map((entry) => entry.sessionId), ); if (keepInitial) { @@ -364,6 +388,8 @@ mixin _ChatScreenWorkspace on State { '${_workspace.activePaneId}:${_workspace.panes.map((p) => '${p.id}=${p.sessionId}').join(',')}'; if (_workspaceSignature == signature) return; _workspaceSignature = signature; + // A phone-held floating chat the operator closed is no longer open. + _phoneDocked.removeWhere((id) => !_workspace.holdsSession(id)); _syncOpenWorkspace(); _touchActiveChat(); void update() { diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index b41c0cee..6599be8b 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -550,6 +550,7 @@ class _ChatScreenState extends State (_) => _publishWorkspaceRoute(), ); } + _trackFloatLayout(); _offeredNext = selected != null && _nextAfter(selected) != null; // A phone opens a chat as a real Navigator page with stock Back. A wide // window keeps the destination rail and the chat list beside the open diff --git a/app/test/features/chat/chat_floating_phone_test.dart b/app/test/features/chat/chat_floating_phone_test.dart new file mode 100644 index 00000000..2bcd43bf --- /dev/null +++ b/app/test/features/chat/chat_floating_phone_test.dart @@ -0,0 +1,287 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/servers/server_scope.dart'; +import 'package:pipelines_app/features/chat/chat_runtime.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/features/chat/screen.dart'; +import 'package:pipelines_app/features/chat/stack/mobile_chat_navigation.dart'; +import 'package:pipelines_app/features/chat/windows/chat_windows.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; +import 'package:pipelines_app/shell/windows/window_host.dart'; +import 'package:pipelines_app/shell/windows/window_kind.dart'; +import 'package:pipelines_app/shell/windows/window_manager.dart'; +import 'package:pipelines_app/shell/windows/window_store.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'conversation/chat_thread_fixtures.dart'; + +/// A chat server with an open-chat set whose entries may float. +class _Server extends FakeChatGateway { + _Server(this.open, this.floating); + List open; + Set floating; + int revision = 1; + + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type == 'chat_sessions') { + return Future.value({ + 'chat_sessions': [ + for (final id in ['a', 'b', 'c']) + {'id': id, 'title': 'Chat $id', 'directory': '/home/$id'}, + ], + }); + } + if (type == 'chat_shells') return Future.value({'chat_shells': []}); + if (type == 'chat_open_workspace') { + final request = fields['chat_open_workspace_request'] as Map?; + var rejected = false; + if (request != null && request['seed'] != true) { + if (request['base_revision'] != revision) { + rejected = true; + } else { + final entries = (request['entries'] as List).cast(); + open = [for (final e in entries) '${e['session_id']}']; + floating = { + for (final e in entries) + if (e['floating'] == true) '${e['session_id']}', + }; + revision++; + } + } + return Future.value({ + 'type': 'chat_open_workspace', + 'chat_open_workspace': _body(rejected), + }); + } + return super.call(type, fields); + } + + JsonMap _body([bool rejected = false]) => { + 'revision': revision, + 'entries': [ + for (final id in open) + {'session_id': id, if (floating.contains(id)) 'floating': true}, + ], + if (rejected) 'rejected': true, + }; + + void change(List ids, Set floats) { + open = ids; + floating = floats; + revision++; + emitRaw({ + 'type': 'chat_open_workspace_changed', + 'chat_open_workspace': _body(), + }); + } +} + +class _Store implements WindowStore { + String? value; + @override + Future read() async => value; + @override + Future write(String record) async { + value = record; + return true; + } +} + +const _wide = Size(1800, 1000); +const _phone = Size(390, 844); + +class _App { + late final _Server server; + late final ChatRuntime runtime; + late final WindowManager manager; + late final ChatWindows windows; + + Future start(WidgetTester tester, {Size size = _wide}) async { + SharedPreferences.setMockInitialValues({}); + _resize(tester, size); + addTearDown(tester.view.reset); + server = _Server(['a', 'b'], {'b'})..history = (_) async => chatPage([]); + bindServerIdentity(server, 'server-a'); + runtime = ChatRuntime(gateway: server, serverKey: 'server-a'); + manager = WindowManager( + kinds: WindowKinds(), + store: _Store(), + server: 'server-a', + ); + windows = ChatWindows( + manager: manager, + runtime: runtime, + openInChat: (_) {}, + )..start(); + await manager.restore(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Stack( + fit: StackFit.expand, + children: [ + ChatScreen( + gateway: server, + persistWorkspace: true, + runtime: runtime, + windows: windows, + ), + Positioned.fill(child: WindowHost(manager: manager)), + ], + ), + ), + ), + ); + await tester.pumpAndSettle(); + } + + Future stop(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox.shrink()); + windows.dispose(); + runtime.dispose(); + manager.dispose(); + server.close(); + } + + List get floatingWindows => [ + for (final w in windows.windows) w.contentId, + ]; +} + +void _resize(WidgetTester tester, Size size) { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; +} + +List _panes(WidgetTester tester) { + final workspace = find.byType(ChatWorkspace, skipOffstage: false); + if (workspace.evaluate().isEmpty) return const []; + return tester + .widget(workspace) + .controller + .panes + .map((pane) => pane.sessionId) + .toList(); +} + +Finder _shownThread(String id) => find + .byWidgetPredicate((w) => w is ChatThreadView && w.sessionId == id) + .hitTestable(); + +void main() { + final navigation = MobileChatNavigationController.instance; + tearDown(() { + unawaited(navigation.setValue(MobileChatNavigation.quickSwitch)); + }); + + testWidgets('a phone tiles a floating chat; a wide layout floats it again', ( + tester, + ) async { + final app = _App(); + await app.start(tester); + expect(app.floatingWindows, ['b']); + + _resize(tester, _phone); + await tester.pumpAndSettle(); + // No window at phone width: the chat is an open chat like the others, + // and the server still has it floating. + expect(app.floatingWindows, isEmpty); + expect(app.server.floating, {'b'}); + + // The list opens it full screen. + await tester.tap(find.byKey(const Key('chat-row-b'))); + await tester.pumpAndSettle(); + expect(_shownThread('b'), findsOneWidget); + expect(_panes(tester), ['a', 'b']); + + _resize(tester, _wide); + await tester.pumpAndSettle(); + expect(app.floatingWindows, ['b']); + expect(_panes(tester), ['a']); + expect(_shownThread('a'), findsOneWidget); + expect(app.server.floating, {'b'}); + expect(app.server.open, ['a', 'b']); + expect(tester.takeException(), isNull); + await app.stop(tester); + }); + + testWidgets('a floating chat opens from the list on a phone from the start', ( + tester, + ) async { + final app = _App(); + await app.start(tester, size: _phone); + expect(app.floatingWindows, isEmpty); + await tester.tap(find.byKey(const Key('chat-row-b'))); + await tester.pumpAndSettle(); + expect(_shownThread('b'), findsOneWidget); + expect(_panes(tester), ['a', 'b']); + expect(app.server.floating, {'b'}); + await app.stop(tester); + }); + + testWidgets('quick switch reaches a floating chat on a phone', ( + tester, + ) async { + final app = _App(); + await app.start(tester, size: _phone); + await tester.tap(find.byKey(const Key('chat-row-a'))); + await tester.pumpAndSettle(); + expect(_shownThread('a'), findsOneWidget); + final controller = tester + .widget(find.byType(ChatWorkspace)) + .controller; + final b = controller.panes.firstWhere((pane) => pane.sessionId == 'b'); + await tester.tap(find.byKey(ValueKey('chat-peek-${b.id}'))); + await tester.pumpAndSettle(); + expect(_shownThread('b'), findsOneWidget); + expect(app.floatingWindows, isEmpty); + await app.stop(tester); + }); + + testWidgets('the chat stack reaches a floating chat on a phone', ( + tester, + ) async { + unawaited(navigation.setValue(MobileChatNavigation.chatStack)); + final app = _App(); + await app.start(tester, size: _phone); + await tester.tap(find.byKey(const Key('chat-row-a'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('chat-stack'))); + await tester.pumpAndSettle(); + final controller = tester + .widget(find.byType(ChatWorkspace)) + .controller; + final b = controller.panes.firstWhere((pane) => pane.sessionId == 'b'); + await tester.tap(find.byKey(ValueKey('chat-stack-button-${b.id}'))); + await tester.pumpAndSettle(); + expect(_shownThread('b'), findsOneWidget); + await app.stop(tester); + }); + + testWidgets('a chat another device floats stays tiled on a phone', ( + tester, + ) async { + final app = _App(); + await app.start(tester, size: _phone); + await tester.tap(find.byKey(const Key('chat-row-a'))); + await tester.pumpAndSettle(); + app.server.change(['a', 'b', 'c'], {'b', 'c'}); + await tester.pumpAndSettle(); + expect(app.floatingWindows, isEmpty); + expect(_panes(tester), ['a', 'b', 'c']); + + // Removing a held chat on the phone drops it from the open chats. + final controller = tester + .widget(find.byType(ChatWorkspace, skipOffstage: false)) + .controller; + controller.close(controller.panes.last.id); + await tester.pumpAndSettle(); + expect(app.server.open, ['a', 'b']); + expect(app.server.floating, {'b'}); + await app.stop(tester); + }); +}