From bb669afacec0f25ee3eab512f84d155eaa047b6f Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Tue, 10 Nov 2026 12:56:39 +0000 Subject: [PATCH] Float one chat pane over the app and toggle it with Ctrl+Y / Cmd+Y --- app/lib/features/chat/chat_screen_float.dart | 85 +++++++ .../features/chat/chat_screen_workspace.dart | 18 +- app/lib/features/chat/screen.dart | 17 +- .../chat/workspace/chat_float_binding.dart | 120 +++++++++ .../chat/workspace/chat_float_host.dart | 236 ++++++++++++++++++ .../chat/workspace/chat_float_shortcut.dart | 39 +++ .../chat/workspace/chat_float_store.dart | 121 +++++++++ .../chat/workspace/chat_float_window.dart | 217 ++++++++++++++++ .../chat/workspace/chat_workspace.dart | 121 ++++++--- .../workspace/chat_workspace_controller.dart | 18 +- .../chat/workspace/chat_workspace_float.dart | 137 ++++++++++ app/lib/features/terminal/terminal_stage.dart | 28 ++- app/lib/ui/floating/floating_layer.dart | 99 ++++++++ app/notes/chat-floating-pane.md | 70 ++++++ .../chat/chat_floating_pane_test.dart | 187 ++++++++++++++ .../workspace/chat_float_shortcut_test.dart | 229 +++++++++++++++++ .../workspace/chat_workspace_float_test.dart | 191 ++++++++++++++ app/test/ui/floating/floating_layer_test.dart | 80 ++++++ 18 files changed, 1957 insertions(+), 56 deletions(-) create mode 100644 app/lib/features/chat/chat_screen_float.dart create mode 100644 app/lib/features/chat/workspace/chat_float_binding.dart create mode 100644 app/lib/features/chat/workspace/chat_float_host.dart create mode 100644 app/lib/features/chat/workspace/chat_float_shortcut.dart create mode 100644 app/lib/features/chat/workspace/chat_float_store.dart create mode 100644 app/lib/features/chat/workspace/chat_float_window.dart create mode 100644 app/lib/features/chat/workspace/chat_workspace_float.dart create mode 100644 app/lib/ui/floating/floating_layer.dart create mode 100644 app/notes/chat-floating-pane.md create mode 100644 app/test/features/chat/chat_floating_pane_test.dart create mode 100644 app/test/features/chat/workspace/chat_float_shortcut_test.dart create mode 100644 app/test/features/chat/workspace/chat_workspace_float_test.dart create mode 100644 app/test/ui/floating/floating_layer_test.dart diff --git a/app/lib/features/chat/chat_screen_float.dart b/app/lib/features/chat/chat_screen_float.dart new file mode 100644 index 00000000..6695fb00 --- /dev/null +++ b/app/lib/features/chat/chat_screen_float.dart @@ -0,0 +1,85 @@ +part of 'screen.dart'; + +/// The floating chat for one Chat destination visit: its menu choices, its +/// window frame and its persistence (see `notes/chat-floating-pane.md`). +mixin _ChatScreenFloat on State, _ChatScreenWorkspace { + @override + final ChatFloatFrame _floatFrame = ChatFloatFrame(); + ChatFloatBinding? _floatBinding; + + /// Restores and saves the floating chat in [store] once [restored] (the + /// workspace layout's own restore) completes. + @override + void _bindFloat(ChatFloatStore store, Future restored) { + _floatBinding?.dispose(); + final binding = _floatBinding = ChatFloatBinding( + controller: _workspace, + frame: _floatFrame, + store: store, + ); + unawaited( + restored.then((_) { + if (mounted && identical(_floatBinding, binding)) { + return binding.start(); + } + }), + ); + } + + @override + void _unbindFloat() { + _floatBinding?.dispose(); + _floatBinding = null; + } + + void _disposeFloat() { + _unbindFloat(); + _floatFrame.dispose(); + } + + /// Panes float only on a wide layout, beside the chat list. + bool get _floatsHere => !_pageOpen && showsListBesideDetail(context); + + void _dockFloat() { + final pane = _workspace.floatingPane; + _workspace.dock(); + if (pane != null) _composerFocus.request(pane.sessionId); + } + + /// The pane menu's floating choices: Float on a tiled pane that can, and + /// Dock, Hide and Close on the floating chat. + List _floatControls(ChatWorkspacePane pane) { + final shortcut = chatFloatShortcutLabel(); + if (_workspace.floatingPane?.id == pane.id) { + return [ + ChatBarAction( + label: 'Dock', + onPressed: _dockFloat, + materialIcon: Icons.vertical_split_outlined, + cupertinoIcon: CupertinoIcons.rectangle_split_3x1, + ), + ChatBarAction( + label: 'Hide floating chat ($shortcut)', + onPressed: () => _workspace.setFloatShown(false), + materialIcon: Icons.visibility_off_outlined, + cupertinoIcon: CupertinoIcons.eye_slash, + ), + ChatBarAction( + label: 'Close pane', + onPressed: () => _closePane(pane.id), + materialIcon: Icons.close, + cupertinoIcon: CupertinoIcons.xmark, + ), + ]; + } + if (!_floatsHere || !_workspace.canFloat(pane.id)) return const []; + return [ + ChatBarAction( + label: 'Float ($shortcut)', + onPressed: () => _workspace.float(pane.id), + materialIcon: Icons.picture_in_picture_alt_outlined, + cupertinoIcon: CupertinoIcons.rectangle_on_rectangle, + ), + ]; + } +} diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart index 804be480..a3d3d287 100644 --- a/app/lib/features/chat/chat_screen_workspace.dart +++ b/app/lib/features/chat/chat_screen_workspace.dart @@ -11,6 +11,9 @@ mixin _ChatScreenWorkspace on State { JsonMap? _rowFor(String id); void _back(); bool get _pageOpen; + ChatFloatFrame get _floatFrame; + void _bindFloat(ChatFloatStore store, Future restored); + void _unbindFloat(); Widget _thread( String selected, VoidCallback onBack, { @@ -114,8 +117,17 @@ mixin _ChatScreenWorkspace on State { _publishWorkspaceRoute(); }, ); - unawaited( - _workspaceBinding!.start(initialSessionId: widget.initialSessionId), + final restored = _workspaceBinding!.start( + initialSessionId: widget.initialSessionId, + ); + unawaited(restored); + _bindFloat( + SharedPreferencesChatFloatStore( + serverScope: widget.gateway is FederatedChatGateway + ? 'all-saved-servers' + : scope, + ), + restored, ); } @@ -127,6 +139,7 @@ mixin _ChatScreenWorkspace on State { } _workspaceBinding?.dispose(); _workspaceBinding = null; + _unbindFloat(); if (_workspaceScope != null && scope != _workspaceScope) { _workspace.restoreLayout(ChatWorkspaceSnapshot.fromLayout(null, null)!); _forgetRecentSessions(); @@ -297,6 +310,7 @@ mixin _ChatScreenWorkspace on State { controller: _workspace, onVisibleSessionIdsChanged: _workspaceVisibilityChanged, shortcutsEnabled: _workspaceVisible, + floatFrame: _floatFrame, singlePane: !showsListBesideDetail(context), mobilePeeks: true, paneTitle: (pane) => diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index 6d8dcbbb..f22a8156 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -20,6 +20,9 @@ import 'package:flutter/services.dart'; import '../../core/api_gateway.dart'; import '../../core/servers/server_scope.dart'; +import 'workspace/chat_float_binding.dart'; +import 'workspace/chat_float_shortcut.dart'; +import 'workspace/chat_float_store.dart'; import 'workspace/chat_workspace_binding.dart'; import 'workspace/chat_workspace_snapshot.dart'; import 'workspace/chat_workspace_store.dart'; @@ -50,6 +53,7 @@ import 'ui/sessions/chat_sessions_controller.dart'; import 'ui/sessions/chat_sessions_screen.dart'; import '../../ui/input/keyboard_owner.dart'; +part 'chat_screen_float.dart'; part 'chat_screen_keys.dart'; part 'chat_screen_workspace.dart'; @@ -94,7 +98,7 @@ class ChatScreen extends StatefulWidget { } class _ChatScreenState extends State - with _ChatScreenWorkspace, _ChatScreenKeys { + with _ChatScreenWorkspace, _ChatScreenKeys, _ChatScreenFloat { /// The list's controller, shared with the mounted list screen. The list /// screen refreshes it on mount and swaps its repository when the socket is /// replaced; this destination lists created rows and re-reads after a @@ -273,10 +277,7 @@ class _ChatScreenState extends State /// Another device started a new session in a chat: only an open chat /// follows it; the list already swapped the row. void _replacedElsewhere(String previousId, JsonMap session) { - if (!mounted || - !_workspace.panes.any((pane) => pane.sessionId == previousId)) { - return; - } + if (!mounted || !_workspace.holdsSession(previousId)) return; _followNewSession(previousId, session, chatNewSessionElsewhereNotice); } @@ -314,6 +315,8 @@ class _ChatScreenState extends State .toList()) { _closePane(pane.id); } + final floating = _workspace.floatingPane; + if (floating?.sessionId == sessionId) _closePane(floating!.id); unawaited(_sessions.refresh()); } @@ -452,6 +455,7 @@ class _ChatScreenState extends State HardwareKeyboard.instance.removeHandler(_slashFocusKey); _page.dispose(); _workspaceBinding?.dispose(); + _disposeFloat(); _workspace.removeListener(_workspaceChanged); _workspace.dispose(); _sessions.removeListener(_nextChanged); @@ -505,6 +509,8 @@ class _ChatScreenState extends State : _page.open || !showsListBesideDetail(context), paneControls: pane == null ? const [] + : _workspace.floatingPane?.id == pane.id + ? _floatControls(pane) : [ ChatBarAction( label: 'Add chat pane', @@ -526,6 +532,7 @@ class _ChatScreenState extends State materialIcon: Icons.close, cupertinoIcon: CupertinoIcons.xmark, ), + ..._floatControls(pane), ], ); return ChatComposerFocusScope( diff --git a/app/lib/features/chat/workspace/chat_float_binding.dart b/app/lib/features/chat/workspace/chat_float_binding.dart new file mode 100644 index 00000000..14c3cab8 --- /dev/null +++ b/app/lib/features/chat/workspace/chat_float_binding.dart @@ -0,0 +1,120 @@ +import 'dart:async'; +import 'dart:ui'; + +import 'package:flutter/foundation.dart'; + +import 'chat_float_store.dart'; +import 'chat_workspace_controller.dart'; + +/// The floating chat window's frame. A drag moves it every pointer event +/// without saving; [commit] marks the end of the drag. +class ChatFloatFrame extends ChangeNotifier { + ChatFloatFrame([this._rect = chatFloatDefaultRect]); + Rect _rect; + Rect get rect => _rect; + int _commits = 0; + + /// Advances when a move or resize ends (the binding saves then). + int get commits => _commits; + + void move(Rect rect) { + if (rect == _rect) return; + _rect = rect; + notifyListeners(); + } + + void commit() { + _commits++; + notifyListeners(); + } +} + +/// Saves which chat floats, whether it shows and the window's frame, and +/// restores them once the workspace layout itself has been restored. +class ChatFloatBinding { + ChatFloatBinding({ + required this.controller, + required this.frame, + required this.store, + this.debounce = const Duration(milliseconds: 250), + }) { + controller.addListener(_changed); + frame.addListener(_frameChanged); + } + + final ChatWorkspaceController controller; + final ChatFloatFrame frame; + final ChatFloatStore store; + final Duration debounce; + ChatFloatRecord? _saved; + bool _loading = true; + bool _disposed = false; + int _commits = 0; + Timer? _timer; + Future _writes = Future.value(); + + ChatFloatRecord get _current => ChatFloatRecord( + pane: controller.floatingPane, + shown: controller.floatShown, + rect: frame.rect, + ); + + /// Call after the workspace layout restored, so a saved float can tell + /// whether its chat is already open in the tiling. + Future start() async { + ChatFloatRecord? record; + try { + record = await store.read(); + } on Object { + // Unavailable preferences leave the default frame and no float. + } + if (_disposed) return; + if (record != null) { + _saved = record; + _commits = frame.commits; + frame.move(record.rect); + final pane = record.pane; + if (pane != null && controller.floatingPane == null) { + controller.restoreFloat(pane, shown: record.shown); + } + } + _loading = false; + _changed(); + } + + void _frameChanged() { + if (frame.commits == _commits) return; + _commits = frame.commits; + _changed(); + } + + void _changed() { + if (_disposed || _loading || _current == _saved) return; + _timer?.cancel(); + _timer = Timer(debounce, flush); + } + + Future flush() { + _timer?.cancel(); + _timer = null; + final record = _current; + if (_loading || record == _saved) return _writes; + _saved = record; + _writes = _writes.then((_) async { + try { + await store.write(record); + } on Object { + // A storage failure must not interrupt the chat. + } + }); + return _writes; + } + + void dispose() { + if (_disposed) return; + controller.removeListener(_changed); + frame.removeListener(_frameChanged); + unawaited(flush()); + _disposed = true; + } +} diff --git a/app/lib/features/chat/workspace/chat_float_host.dart b/app/lib/features/chat/workspace/chat_float_host.dart new file mode 100644 index 00000000..b550aebe --- /dev/null +++ b/app/lib/features/chat/workspace/chat_float_host.dart @@ -0,0 +1,236 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../../../ui/floating/floating_layer.dart'; +import '../../../ui/motion/motion.dart'; +import '../ui/sessions/chat_adaptive.dart'; +import 'chat_float_binding.dart'; +import 'chat_float_shortcut.dart'; +import 'chat_float_window.dart'; +import 'chat_workspace_controller.dart'; + +/// The split workspace ([child]) with its floating chat over the app: the +/// window, its show and hide motion, its focus and its shortcut (see +/// [chatFloatShortcut]). [content] is the floating pane's live view, moved +/// here from the tiling rather than rebuilt. +/// +/// The window shows only while [enabled] (a wide layout) and the Chat +/// destination is current; otherwise the floating chat is kept, unpainted. +class ChatFloatHost extends StatefulWidget { + const ChatFloatHost({ + super.key, + required this.controller, + required this.frame, + required this.enabled, + required this.title, + required this.content, + required this.scope, + required this.focusedPane, + required this.onFocusPane, + required this.child, + }); + + final ChatWorkspaceController controller; + final ChatFloatFrame frame; + final bool enabled; + final String title; + final Widget? content; + + /// The floating pane's focus scope. + final FocusScopeNode? scope; + + /// The tiled pane with the keyboard, which the shortcut floats when no + /// chat floats yet. + final ChatWorkspacePane? Function() focusedPane; + final ValueChanged? onFocusPane; + final Widget child; + + @override + State createState() => _ChatFloatHostState(); +} + +class _ChatFloatHostState extends State + with SingleTickerProviderStateMixin { + late final AnimationController _reveal = AnimationController( + vsync: this, + duration: Motion.standard, + ); + late final CurvedAnimation _curve = CurvedAnimation( + parent: _reveal, + curve: Motion.curve, + reverseCurve: Curves.easeInCubic, + ); + bool _current = true; + bool _visible = false; + String? _paneId; + FocusNode? _previous; + + @override + void initState() { + super.initState(); + FocusManager.instance.addEarlyKeyEventHandler(_key); + widget.controller.addListener(_sync); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + // Another destination mutes this one's tickers and takes its focus. + _current = TickerMode.valuesOf(context).enabled; + WidgetsBinding.instance.addPostFrameCallback((_) => _sync()); + } + + @override + void didUpdateWidget(covariant ChatFloatHost oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.controller != widget.controller) { + oldWidget.controller.removeListener(_sync); + widget.controller.addListener(_sync); + } + if (oldWidget.enabled != widget.enabled) { + WidgetsBinding.instance.addPostFrameCallback((_) => _sync()); + } + } + + @override + void dispose() { + FocusManager.instance.removeEarlyKeyEventHandler(_key); + widget.controller.removeListener(_sync); + _curve.dispose(); + _reveal.dispose(); + super.dispose(); + } + + bool get _presentable => widget.enabled && _current; + + void _sync() { + if (!mounted) return; + final pane = widget.controller.floatingPane; + final visible = _presentable && widget.controller.floatShown; + _reveal.duration = Motion.of(context, Motion.standard); + if (pane == null) { + // Docked or closed: the view went back to the tiling, so no motion. + _previous = null; + _reveal.value = 0; + } else if (visible != _visible) { + if (visible) { + _remember(); + unawaited(_reveal.forward()); + _focusSoon(pane); + } else { + _release(); + unawaited(_reveal.reverse()); + } + } else if (visible && pane.id != _paneId) { + // Another chat replaced the floating one. + _focusSoon(pane); + } + _paneId = pane?.id; + if (visible != _visible) setState(() => _visible = visible); + } + + bool _inside(FocusNode node) { + final scope = widget.scope; + return scope != null && + (identical(node, scope) || node.ancestors.contains(scope)); + } + + void _remember() { + final current = FocusManager.instance.primaryFocus; + if (current == null || _inside(current)) return; + _previous = identical(current, FocusManager.instance.rootScope) + ? null + : current; + } + + void _focusSoon(ChatWorkspacePane pane) { + WidgetsBinding.instance + ..addPostFrameCallback((_) { + if (!mounted || widget.controller.floatingPane?.id != pane.id) return; + final focus = widget.onFocusPane; + if (focus != null) { + focus(pane); + } else { + widget.scope?.requestFocus(); + } + }) + ..ensureVisualUpdate(); + } + + /// Gives the keyboard back to what had it before the chat showed, if the + /// floating chat has it now. + void _release() { + final previous = _previous; + _previous = null; + final scope = widget.scope; + if (scope == null || !scope.hasFocus) return; + if (previous != null && + previous.context != null && + previous.canRequestFocus) { + previous.requestFocus(); + } else { + scope.unfocus(); + } + } + + /// Handled before any focused widget sees the key, so it works from a + /// composer or the terminal; ignored (left to them) when it does nothing. + KeyEventResult _key(KeyEvent event) { + if (!mounted || + !_presentable || + !chatFloatShortcut(event, HardwareKeyboard.instance)) { + return KeyEventResult.ignored; + } + final controller = widget.controller; + if (controller.floatingPane == null) { + final pane = widget.focusedPane(); + if (pane == null || !controller.canFloat(pane.id)) { + return KeyEventResult.ignored; + } + if (event is KeyDownEvent) controller.float(pane.id); + return KeyEventResult.handled; + } + if (event is KeyDownEvent) controller.toggleFloatShown(); + return KeyEventResult.handled; + } + + @override + Widget build(BuildContext context) { + final content = widget.content; + return Stack( + fit: StackFit.expand, + children: [ + widget.child, + if (content != null) + Positioned.fill( + child: FloatingLayer( + open: _visible, + coverOverlay: true, + builder: (context, bounds) => [ + ListenableBuilder( + listenable: Listenable.merge([widget.frame, _reveal]), + builder: (context, _) => ChatFloatWindow( + frame: widget.frame, + bounds: bounds, + title: widget.title, + cupertino: + chatControlsStyleOf(context) == + ChatControlsStyle.cupertino, + reveal: _curve, + hiding: !_visible, + offstage: !_visible && _reveal.isDismissed, + shortcut: chatFloatShortcutLabel(), + onDock: widget.controller.dock, + onHide: () => widget.controller.setFloatShown(false), + child: content, + ), + ), + ], + ), + ), + ], + ); + } +} diff --git a/app/lib/features/chat/workspace/chat_float_shortcut.dart b/app/lib/features/chat/workspace/chat_float_shortcut.dart new file mode 100644 index 00000000..aec2738d --- /dev/null +++ b/app/lib/features/chat/workspace/chat_float_shortcut.dart @@ -0,0 +1,39 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +import '../../../ui/input/keyboard_owner.dart'; + +/// Whether [event] shows or hides the floating chat: Ctrl+Y, and Cmd+Y on +/// Apple platforms. It is a global key handler like the terminal's toggle, +/// so it works while a composer or the terminal has the keyboard; a plain Y +/// (or Shift+Y, Alt+Y) always types. On Apple platforms Ctrl+Y inside a +/// terminal is left to the shell (yank), since Cmd+Y is there; elsewhere +/// Ctrl+Y is the chord, so it takes priority over the shell's yank. +/// +/// A held chord's repeats match too (and are swallowed); only its first +/// press toggles. +bool chatFloatShortcut( + KeyEvent event, + HardwareKeyboard keyboard, { + TargetPlatform? platform, +}) { + if (event is KeyUpEvent || + event.logicalKey != LogicalKeyboardKey.keyY || + keyboard.isShiftPressed || + keyboard.isAltPressed) { + return false; + } + final control = keyboard.isControlPressed; + final meta = keyboard.isMetaPressed; + if (control == meta) return false; + if (!_apple(platform ?? defaultTargetPlatform)) return control; + return meta || !primaryFocusIsTypingSurface(); +} + +bool _apple(TargetPlatform platform) => + platform == TargetPlatform.macOS || platform == TargetPlatform.iOS; + +/// The floating chat's shortcut as it reads on this platform, for menus and +/// tooltips. +String chatFloatShortcutLabel([TargetPlatform? platform]) => + _apple(platform ?? defaultTargetPlatform) ? 'Cmd+Y' : 'Ctrl+Y'; diff --git a/app/lib/features/chat/workspace/chat_float_store.dart b/app/lib/features/chat/workspace/chat_float_store.dart new file mode 100644 index 00000000..69848d4d --- /dev/null +++ b/app/lib/features/chat/workspace/chat_float_store.dart @@ -0,0 +1,121 @@ +import 'dart:convert'; +import 'dart:ui'; + +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../../core/servers/server_scope.dart'; +import 'chat_workspace_nodes.dart'; + +const chatFloatPreferenceKey = 'pipelines.next.chatFloat.v1'; + +/// The floating window's default frame and smallest size; frames clamp to +/// what the window allows. +const Rect chatFloatDefaultRect = Rect.fromLTWH(120, 96, 480, 560); +const Size chatFloatMinSize = Size(320, 240); + +/// The floating chat as saved on this device: which pane floats (if any), +/// whether it is shown, and the window's frame. Identities and geometry only, +/// like the workspace snapshot. +class ChatFloatRecord { + const ChatFloatRecord({this.pane, this.shown = false, required this.rect}); + + final ChatWorkspacePane? pane; + final bool shown; + final Rect rect; + + String encode() => jsonEncode({ + 'version': 1, + 'pane': pane == null + ? null + : {'id': pane!.id, 'session_id': pane!.sessionId}, + 'shown': shown, + 'rect': [rect.left, rect.top, rect.width, rect.height], + }); + + static ChatFloatRecord? decode(String source) { + if (source.length > 4096) return null; + try { + final data = jsonDecode(source); + if (data is! Map || data['version'] != 1) return null; + final values = data['rect']; + if (values is! List || + values.length != 4 || + values.any((v) => v is! num || !v.isFinite)) { + return null; + } + final [left, top, width, height] = [ + for (final v in values) (v as num).toDouble(), + ]; + if (width <= 0 || height <= 0) return null; + final pane = data['pane']; + ChatWorkspacePane? floating; + if (pane is Map) { + final id = pane['id'], session = pane['session_id']; + if (!_identity(id, 256) || !_identity(session, 512)) return null; + floating = ChatWorkspacePane(id as String, session as String); + } else if (pane != null) { + return null; + } + return ChatFloatRecord( + pane: floating, + shown: data['shown'] == true, + rect: Rect.fromLTWH(left, top, width, height), + ); + } on Object { + return null; + } + } + + @override + bool operator ==(Object other) => + other is ChatFloatRecord && + other.pane?.id == pane?.id && + other.pane?.sessionId == pane?.sessionId && + other.shown == shown && + other.rect == rect; + + @override + int get hashCode => Object.hash(pane?.id, pane?.sessionId, shown, rect); +} + +bool _identity(Object? value, int limit) => + value is String && + value.isNotEmpty && + value.length <= limit && + value.trim() == value && + !value.contains(RegExp(r'[\x00-\x20\x7f]')); + +abstract interface class ChatFloatStore { + Future read(); + Future write(ChatFloatRecord record); +} + +/// Device-local, scoped like the workspace layout it belongs to. +class SharedPreferencesChatFloatStore implements ChatFloatStore { + const SharedPreferencesChatFloatStore({required this.serverScope}); + final String serverScope; + + String get key => scopedServerKey(chatFloatPreferenceKey, serverScope); + + @override + Future read() async { + try { + final source = (await SharedPreferences.getInstance()).getString(key); + return source == null ? null : ChatFloatRecord.decode(source); + } on Object { + return null; + } + } + + @override + Future write(ChatFloatRecord record) async { + try { + return await (await SharedPreferences.getInstance()).setString( + key, + record.encode(), + ); + } on Object { + return false; + } + } +} diff --git a/app/lib/features/chat/workspace/chat_float_window.dart b/app/lib/features/chat/workspace/chat_float_window.dart new file mode 100644 index 00000000..b3f8ab9d --- /dev/null +++ b/app/lib/features/chat/workspace/chat_float_window.dart @@ -0,0 +1,217 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; + +import '../../terminal/terminal_float_frame.dart' show terminalFloatChrome; +import 'chat_float_binding.dart'; +import 'chat_float_store.dart'; + +/// [rect] moved and shrunk to fit inside [bounds], at least the smallest +/// window where the bounds allow it. +Rect fitChatFloat(Rect rect, Size bounds) { + final width = rect.width + .clamp(chatFloatMinSize.width, double.infinity) + .clamp(0.0, bounds.width); + final height = rect.height + .clamp(chatFloatMinSize.height, double.infinity) + .clamp(0.0, bounds.height); + return Rect.fromLTWH( + rect.left.clamp(0.0, bounds.width - width), + rect.top.clamp(0.0, bounds.height - height), + width, + height, + ); +} + +/// The floating chat's window: moved by its title bar, resized from its +/// lower right corner, kept inside [bounds]. It grows and fades in from its +/// place as [reveal] runs forward and leaves the same way in reverse. +class ChatFloatWindow extends StatelessWidget { + const ChatFloatWindow({ + super.key, + required this.frame, + required this.bounds, + required this.title, + required this.cupertino, + required this.reveal, + required this.hiding, + this.offstage = false, + required this.shortcut, + required this.onDock, + required this.onHide, + required this.child, + }); + + final ChatFloatFrame frame; + final Size bounds; + final String title; + final bool cupertino; + final Animation reveal; + + /// While the window hides it takes no input. + final bool hiding; + + /// Hidden and settled: kept built (the chat keeps its state) but unpainted. + final bool offstage; + final String shortcut; + final VoidCallback onDock; + final VoidCallback onHide; + final Widget child; + + static const double revealScale = 0.92; + + void _resize(Offset delta) { + final rect = fitChatFloat(frame.rect, bounds); + frame.move( + fitChatFloat( + Rect.fromLTWH( + rect.left, + rect.top, + rect.width + delta.dx, + rect.height + delta.dy, + ), + bounds, + ), + ); + } + + @override + Widget build(BuildContext context) { + final rect = fitChatFloat(frame.rect, bounds); + final window = SizedBox.fromSize( + size: rect.size, + child: Stack( + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _titleBar(context, rect), + Expanded( + child: MediaQuery.removePadding( + context: context, + removeTop: true, + removeBottom: true, + removeLeft: true, + removeRight: true, + child: child, + ), + ), + ], + ), + PositionedDirectional(end: 0, bottom: 0, child: _corner()), + ], + ), + ); + return Positioned( + left: rect.left, + top: rect.top, + child: Offstage( + offstage: offstage, + child: IgnorePointer( + ignoring: hiding, + child: ExcludeFocus( + excluding: hiding, + child: FadeTransition( + opacity: reveal, + child: ScaleTransition( + scale: Tween( + begin: revealScale, + end: 1, + ).animate(reveal), + child: Semantics( + container: true, + label: 'Floating chat', + identifier: 'chat-float-window', + child: terminalFloatChrome(context, cupertino, window), + ), + ), + ), + ), + ), + ), + ); + } + + Widget _titleBar(BuildContext context, Rect rect) { + final label = Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: cupertino + ? CupertinoTheme.of(context).textTheme.navTitleTextStyle + : Theme.of(context).textTheme.titleSmall, + ); + final drag = MouseRegion( + cursor: SystemMouseCursors.move, + child: GestureDetector( + key: const ValueKey('chat-float-title'), + behavior: HitTestBehavior.opaque, + dragStartBehavior: DragStartBehavior.down, + onPanUpdate: (details) => frame.move( + fitChatFloat( + fitChatFloat(frame.rect, bounds).shift(details.delta), + bounds, + ), + ), + onPanEnd: (_) => frame.commit(), + child: Padding( + padding: const EdgeInsetsDirectional.only(start: 12), + child: Align( + alignment: AlignmentDirectional.centerStart, + child: label, + ), + ), + ), + ); + return Row( + children: [ + Expanded(child: drag), + _button( + 'Dock', + Icons.vertical_split_outlined, + CupertinoIcons.rectangle_split_3x1, + onDock, + ), + _button( + 'Hide floating chat ($shortcut)', + Icons.close, + CupertinoIcons.xmark, + onHide, + ), + ], + ); + } + + Widget _button( + String label, + IconData material, + IconData cupertinoIcon, + VoidCallback onPressed, + ) => cupertino + ? CupertinoButton( + padding: const EdgeInsets.symmetric(horizontal: 8), + onPressed: onPressed, + child: Icon(cupertinoIcon, semanticLabel: label), + ) + : IconButton(tooltip: label, onPressed: onPressed, icon: Icon(material)); + + Widget _corner() => Semantics( + label: 'Resize floating chat', + child: MouseRegion( + cursor: SystemMouseCursors.resizeDownRight, + child: GestureDetector( + key: const ValueKey('chat-float-resize'), + behavior: HitTestBehavior.opaque, + dragStartBehavior: DragStartBehavior.down, + onPanUpdate: (details) => _resize(details.delta), + onPanEnd: (_) => frame.commit(), + child: Padding( + padding: const EdgeInsets.all(4), + child: Icon( + cupertino ? CupertinoIcons.arrow_down_right : Icons.south_east, + ), + ), + ), + ), + ); +} diff --git a/app/lib/features/chat/workspace/chat_workspace.dart b/app/lib/features/chat/workspace/chat_workspace.dart index a30794af..55be5e8f 100644 --- a/app/lib/features/chat/workspace/chat_workspace.dart +++ b/app/lib/features/chat/workspace/chat_workspace.dart @@ -4,6 +4,8 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../../../ui/motion/quick_switch_animation.dart'; +import 'chat_float_binding.dart'; +import 'chat_float_host.dart'; import 'chat_workspace_controller.dart'; import 'chat_workspace_geometry.dart'; import 'chat_mobile_panes.dart'; @@ -59,6 +61,7 @@ class ChatWorkspace extends StatefulWidget { this.animationStyle, this.paneTitle, this.onVisibleSessionIdsChanged, + this.floatFrame, }); final ChatWorkspaceController controller; final ChatWorkspacePaneBuilder paneBuilder; @@ -71,6 +74,10 @@ class ChatWorkspace extends StatefulWidget { final String Function(ChatWorkspacePane)? paneTitle; final ValueChanged>? onVisibleSessionIdsChanged; + /// Offers the floating chat (see [ChatFloatHost]) in this frame; null for a + /// workspace without one. It shows only while the panes are not collapsed. + final ChatFloatFrame? floatFrame; + /// Keyboard navigation only: the owner can focus the target composer. /// Pointer activation leaves text-selection and pointer focus alone. final ValueChanged? onFocusPane; @@ -83,6 +90,10 @@ class _ChatWorkspaceState extends State with SingleTickerProviderStateMixin { final _focus = FocusNode(debugLabel: 'Chat workspace'); final Map _panes = {}; + + /// Each pane's view keeps its State when it moves into or out of the + /// floating window. + final Map _views = {}; late final ChatPaneSwitchMotion _motion; ChatWorkspaceGeometry? _geometry; String? _lastActiveId; @@ -246,7 +257,11 @@ class _ChatWorkspaceState extends State : !collapsed || pane.id == activeId) pane.sessionId, }); - final existing = panes.map((p) => p.id).toSet(); + final floating = widget.floatFrame == null + ? null + : widget.controller.floatingPane; + final existing = {...panes.map((p) => p.id), ?floating?.id}; + _views.removeWhere((id, _) => !existing.contains(id)); for (final id in _panes.keys.where((id) => !existing.contains(id)).toList()) { final node = _panes.remove(id)!; @@ -285,7 +300,7 @@ class _ChatWorkspaceState extends State edge, }, }; - return chatWorkspaceSurface( + final surface = chatWorkspaceSurface( context: context, backdrop: _backdrop, motion: _motion, @@ -298,6 +313,23 @@ class _ChatWorkspaceState extends State paneView: (pane) => _paneView(pane, mobile, collapsed, activeId, sharedEdges), ); + final frame = widget.floatFrame; + if (frame == null) return surface; + return ChatFloatHost( + controller: widget.controller, + frame: frame, + enabled: !widget.singlePane, + title: floating == null + ? '' + : widget.paneTitle?.call(floating) ?? floating.sessionId, + content: floating == null ? null : _floatView(floating), + scope: floating == null ? null : _panes[floating.id], + focusedPane: () => widget.controller.panes + .where((pane) => _panes[pane.id]?.hasFocus ?? false) + .firstOrNull, + onFocusPane: widget.onFocusPane, + child: surface, + ); }, ), ), @@ -330,44 +362,59 @@ class _ChatWorkspaceState extends State FocusManager.instance.primaryFocus?.unfocus(); widget.controller.activate(pane.id); }, - child: FocusScope( - node: _panes.putIfAbsent( - pane.id, - () => FocusScopeNode(debugLabel: pane.id), - ), - onFocusChange: (focused) { - if (focused && mobile == null) { - widget.controller.activate(pane.id); - } - }, - child: Listener( - behavior: HitTestBehavior.translucent, - // A press in the peek scrolls or taps; the tap alone activates. - onPointerDown: peek - ? null - : (_) => widget.controller.activate(pane.id), - child: Semantics( - identifier: 'chat-pane-${pane.id}', - container: true, - sortKey: mobile == null ? null : const OrdinalSortKey(0), - child: ChatWorkspacePaneScope( - topEdgeShared: sharedEdges[pane.id]?.contains('top') ?? false, - bottomEdgeShared: - sharedEdges[pane.id]?.contains('bottom') ?? false, - leftEdgeShared: - sharedEdges[pane.id]?.contains('left') ?? false, - rightEdgeShared: - sharedEdges[pane.id]?.contains('right') ?? false, - child: Builder( - builder: (paneContext) => - widget.paneBuilder(paneContext, pane, active), - ), - ), - ), - ), + child: _paneContent( + pane, + active: active, + peek: peek, + mobile: mobile != null, + edges: sharedEdges[pane.id] ?? const {}, ), ), ), ); } + + /// The floating chat's view: the same keyed content as in the tiling, so + /// floating and docking move it without rebuilding the chat. + Widget _floatView(ChatWorkspacePane pane) => + _paneContent(pane, active: true, peek: false, mobile: false, edges: {}); + + Widget _paneContent( + ChatWorkspacePane pane, { + required bool active, + required bool peek, + required bool mobile, + required Set edges, + }) => KeyedSubtree( + key: _views.putIfAbsent(pane.id, () => GlobalKey(debugLabel: pane.id)), + child: FocusScope( + node: _panes.putIfAbsent( + pane.id, + () => FocusScopeNode(debugLabel: pane.id), + ), + onFocusChange: (focused) { + if (focused && !mobile) widget.controller.activate(pane.id); + }, + child: Listener( + behavior: HitTestBehavior.translucent, + // A press in the peek scrolls or taps; the tap alone activates. + onPointerDown: peek ? null : (_) => widget.controller.activate(pane.id), + child: Semantics( + identifier: 'chat-pane-${pane.id}', + container: true, + sortKey: mobile ? const OrdinalSortKey(0) : null, + child: ChatWorkspacePaneScope( + topEdgeShared: edges.contains('top'), + bottomEdgeShared: edges.contains('bottom'), + leftEdgeShared: edges.contains('left'), + rightEdgeShared: edges.contains('right'), + child: Builder( + builder: (paneContext) => + widget.paneBuilder(paneContext, pane, active), + ), + ), + ), + ), + ), + ); } diff --git a/app/lib/features/chat/workspace/chat_workspace_controller.dart b/app/lib/features/chat/workspace/chat_workspace_controller.dart index f15c296a..37fc3d01 100644 --- a/app/lib/features/chat/workspace/chat_workspace_controller.dart +++ b/app/lib/features/chat/workspace/chat_workspace_controller.dart @@ -5,10 +5,16 @@ import 'chat_workspace_snapshot.dart'; export 'chat_workspace_nodes.dart'; +part 'chat_workspace_float.dart'; + /// Pane identities survive nested splits, resizing and validated restoration. class ChatWorkspaceController extends ChangeNotifier { ChatWorkspaceNode? _root; String? _active; + + /// The chat taken out of the tiling into the floating window, if any. + ChatWorkspacePane? _floating; + bool _floatShown = false; double _mobilePeekFraction = .2; double get mobilePeekFraction => _mobilePeekFraction; void resizeMobilePeek(double fraction) { @@ -49,6 +55,7 @@ class ChatWorkspaceController extends ChangeNotifier { } collect(_root); + collect(_floating); String id; do { id = 'chat-$kind-${++_serial}'; @@ -62,6 +69,7 @@ class ChatWorkspaceController extends ChangeNotifier { _root = snapshot.root; _active = snapshot.activePaneId; _mobilePeekFraction = snapshot.mobilePeekFraction; + _floating = null; _serial = 0; _changed(); return true; @@ -82,7 +90,7 @@ class ChatWorkspaceController extends ChangeNotifier { /// Ordinary opening replaces the active pane; an already-open chat is focused. void open(String sessionId) { - if (sessionId.isEmpty) return; + if (sessionId.isEmpty || _showFloating(sessionId)) return; final existing = panes.where((p) => p.sessionId == sessionId).firstOrNull; if (existing != null) { activate(existing.id); @@ -105,7 +113,7 @@ class ChatWorkspaceController extends ChangeNotifier { } void splitActive(String sessionId, ChatSplitAxis axis) { - if (sessionId.isEmpty) return; + if (sessionId.isEmpty || _showFloating(sessionId)) return; if (_root == null) { open(sessionId); return; @@ -161,10 +169,12 @@ class ChatWorkspaceController extends ChangeNotifier { } void close(String paneId) { + if (_closeFloating(paneId)) return; final before = panes; final index = before.indexWhere((p) => p.id == paneId); if (index < 0) return; _root = _remove(_root!, paneId); + _adoptFloatingIfEmpty(); final after = panes; if (_active == paneId) { _active = after.isEmpty @@ -175,7 +185,9 @@ class ChatWorkspaceController extends ChangeNotifier { } void replaceSession(String oldId, String newId) { - if (oldId == newId || newId.isEmpty) return; + if (oldId == newId || newId.isEmpty || _replaceFloating(oldId, newId)) { + return; + } final pane = panes.where((p) => p.sessionId == oldId).firstOrNull; if (pane == null) return; final existing = panes.where((p) => p.sessionId == newId).firstOrNull; diff --git a/app/lib/features/chat/workspace/chat_workspace_float.dart b/app/lib/features/chat/workspace/chat_workspace_float.dart new file mode 100644 index 00000000..eadff91f --- /dev/null +++ b/app/lib/features/chat/workspace/chat_workspace_float.dart @@ -0,0 +1,137 @@ +part of 'chat_workspace_controller.dart'; + +/// One chat at a time can leave the split tiling for a floating window over +/// the app. The floating pane keeps its id (and so its live view) while it +/// floats, hides, docks or swaps places with another pane. +extension ChatWorkspaceFloat on ChatWorkspaceController { + /// The floating chat, shown or hidden. + ChatWorkspacePane? get floatingPane => _floating; + + /// Whether the floating chat is shown (rather than hidden by Ctrl+Y). + bool get floatShown => _floating != null && _floatShown; + + /// Whether [sessionId] is open in the tiling or the floating window. + bool holdsSession(String sessionId) => + _floating?.sessionId == sessionId || + panes.any((pane) => pane.sessionId == sessionId); + + /// A tiled pane can float when another chat stays in the tiling: a second + /// tiled pane, or the chat floating now (which takes its place). + bool canFloat(String paneId) => + panes.any((pane) => pane.id == paneId) && + (paneCount > 1 || _floating != null); + + /// Floats the tiled pane [paneId]. A chat already floating returns to the + /// tiling in the place [paneId] leaves. + void float(String paneId) { + if (!canFloat(paneId)) return; + final pane = panes.firstWhere((pane) => pane.id == paneId); + final previous = _floating; + if (previous != null) { + _root = _replace(_root!, paneId, previous); + if (_active == paneId) _active = previous.id; + } else { + final index = panes.indexWhere((p) => p.id == paneId); + _root = _remove(_root!, paneId); + if (_active == paneId) { + final after = panes; + _active = after[index.clamp(0, after.length - 1)].id; + } + } + _floating = pane; + _floatShown = true; + _changed(); + } + + /// Puts the floating chat back into the tiling, to the right of the + /// active pane, and makes it the active pane. + void dock() { + final pane = _floating; + if (pane == null) return; + final split = _id('split'); + _floating = null; + if (_root == null) { + _root = pane; + } else { + final target = activePane ?? panes.first; + _root = _replace( + _root!, + target.id, + ChatWorkspaceSplit(split, ChatSplitAxis.horizontal, target, pane), + ); + } + _active = pane.id; + _changed(); + } + + void setFloatShown(bool shown) { + if (_floating == null || _floatShown == shown) return; + _floatShown = shown; + _changed(); + } + + void toggleFloatShown() => setFloatShown(!_floatShown); + + /// Restores a saved floating chat unless its session is already open or + /// its pane id is taken. With no tiled pane it becomes the tiling instead. + bool restoreFloat(ChatWorkspacePane pane, {required bool shown}) { + if (_floating != null || holdsSession(pane.sessionId)) return false; + bool taken(ChatWorkspaceNode? node) => + node != null && + (node.id == pane.id || + node is ChatWorkspaceSplit && + (taken(node.first) || taken(node.second))); + if (taken(_root)) return false; + if (_root == null) { + _root = pane; + _active = pane.id; + } else { + _floating = pane; + _floatShown = shown; + } + _changed(); + return true; + } + + /// Opening the floating chat (from the list, a link) shows it. + bool _showFloating(String sessionId) { + if (_floating?.sessionId != sessionId) return false; + setFloatShown(true); + return true; + } + + bool _closeFloating(String paneId) { + if (_floating?.id != paneId) return false; + _floating = null; + _changed(); + return true; + } + + /// The tiling never empties while a chat floats: the floating chat docks. + void _adoptFloatingIfEmpty() { + if (_root != null || _floating == null) return; + _root = _floating; + _floating = null; + } + + /// `/new` in the floating chat keeps it floating under the new session. + bool _replaceFloating(String oldId, String newId) { + final pane = _floating; + if (pane == null) return false; + if (pane.sessionId == oldId) { + if (panes.any((p) => p.sessionId == newId)) { + _closeFloating(pane.id); + } else { + _floating = ChatWorkspacePane(pane.id, newId); + _changed(); + } + return true; + } + if (pane.sessionId != newId) return false; + // A tiled chat moved to the session that floats: the float stays. + final tiled = panes.where((p) => p.sessionId == oldId).firstOrNull; + if (tiled != null) close(tiled.id); + setFloatShown(true); + return true; + } +} diff --git a/app/lib/features/terminal/terminal_stage.dart b/app/lib/features/terminal/terminal_stage.dart index a46b9be5..8e5240b1 100644 --- a/app/lib/features/terminal/terminal_stage.dart +++ b/app/lib/features/terminal/terminal_stage.dart @@ -1,5 +1,6 @@ import 'package:flutter/widgets.dart'; +import '../../ui/floating/floating_layer.dart'; import 'terminal_float.dart'; import 'terminal_hub.dart'; import 'terminal_layout.dart'; @@ -81,16 +82,25 @@ class TerminalStage extends StatelessWidget { ), ), ), + // The window shares the app's floating layer, so it and a + // floating chat stack by which was used last. if (float) - TerminalFloat( - key: const ValueKey('terminal-float'), - hub: hub, - layout: layout, - cupertino: cupertino, - bounds: constraints.biggest, - reveal: reveal, - focus: focus, - hiding: hiding, + Positioned.fill( + child: FloatingLayer( + open: layout.visible, + builder: (context, bounds) => [ + TerminalFloat( + key: const ValueKey('terminal-float'), + hub: hub, + layout: layout, + cupertino: cupertino, + bounds: bounds, + reveal: reveal, + focus: focus, + hiding: hiding, + ), + ], + ), ), ], ); diff --git a/app/lib/ui/floating/floating_layer.dart b/app/lib/ui/floating/floating_layer.dart new file mode 100644 index 00000000..66d68479 --- /dev/null +++ b/app/lib/ui/floating/floating_layer.dart @@ -0,0 +1,99 @@ +import 'package:flutter/widgets.dart'; + +/// A layer of floating windows painted in the app's root overlay, above the +/// page, while it keeps its place in the tree (its inherited widgets, focus +/// and state stay where it is built). Every [FloatingLayer] shares that one +/// overlay, so windows from different features (the terminal, a floating +/// chat) stack by use: the layer last pressed, focused or opened is on top. +/// +/// [builder] returns the windows as [Positioned] children of a [Stack] the +/// size of [bounds]: this widget's own box, or the whole overlay when +/// [coverOverlay] is set. Space between windows takes no input. Without an +/// overlay (a bare widget test) the layer paints in place. +class FloatingLayer extends StatefulWidget { + const FloatingLayer({ + super.key, + required this.builder, + this.open = true, + this.coverOverlay = false, + }); + + final List Function(BuildContext context, Size bounds) builder; + + /// Turning true brings the layer to the top, as its window opens. + final bool open; + + final bool coverOverlay; + + @override + State createState() => _FloatingLayerState(); +} + +class _FloatingLayerState extends State { + final OverlayPortalController _portal = OverlayPortalController( + debugLabel: 'floating layer', + ); + + @override + void initState() { + super.initState(); + _portal.show(); + } + + @override + void didUpdateWidget(covariant FloatingLayer oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.open && !oldWidget.open) { + WidgetsBinding.instance.addPostFrameCallback((_) => _raise()); + } + } + + void _raise() { + if (mounted) _portal.show(); + } + + Widget _layer(BuildContext context, Size bounds) => Listener( + behavior: HitTestBehavior.deferToChild, + onPointerDown: (_) => _raise(), + child: Focus( + canRequestFocus: false, + skipTraversal: true, + onFocusChange: (focused) { + if (focused) _raise(); + }, + child: SizedBox.fromSize( + size: bounds, + child: Stack( + clipBehavior: Clip.none, + children: widget.builder(context, bounds), + ), + ), + ), + ); + + @override + Widget build(BuildContext context) { + if (Overlay.maybeOf(context, rootOverlay: true) == null) { + return LayoutBuilder( + builder: (context, constraints) => _layer(context, constraints.biggest), + ); + } + return OverlayPortal.overlayChildLayoutBuilder( + controller: _portal, + overlayLocation: OverlayChildLocation.rootOverlay, + overlayChildBuilder: (context, info) => widget.coverOverlay + ? Positioned.fill(child: _layer(context, info.overlaySize)) + : Positioned( + left: 0, + top: 0, + width: info.childSize.width, + height: info.childSize.height, + child: Transform( + transform: info.childPaintTransform, + child: _layer(context, info.childSize), + ), + ), + child: const SizedBox.expand(), + ); + } +} diff --git a/app/notes/chat-floating-pane.md b/app/notes/chat-floating-pane.md new file mode 100644 index 00000000..eec33ac0 --- /dev/null +++ b/app/notes/chat-floating-pane.md @@ -0,0 +1,70 @@ +# Floating chat pane + +On a wide layout one chat at a time can leave the split tiling and float in a +window over the app, like the floating terminal. Ctrl+Y (Cmd+Y on macOS) +shows or hides it. + +## Behaviour + +- **Float**: a tiled pane's More menu offers `Float (Ctrl+Y)` (`Cmd+Y` on Apple + platforms) when another chat stays in the tiling. A single chat cannot float, + because the tiling would be empty. Floating a second chat swaps them: the chat + that was floating goes back into the tiling where the new one was. +- **Window**: you drag it by its title bar and resize it from the lower right + corner. The title bar has Dock and Hide buttons. The window keeps its frame + inside the app when the browser window resizes (`fitChatFloat`). Grow and fade + in, and shrink and fade out, use `Motion.standard` through `Motion.of`, so + reduced motion and the animation speed apply. +- **Floating chat's menu**: Dock (back into the tiling, right of the active pane, + which it becomes), `Hide floating chat (Ctrl+Y)`, and Close pane (removes it + from the workspace; no backend close). If the last tiled pane closes, the + floating chat docks in its place. +- **Shortcut**: Ctrl+Y on every platform, and Cmd+Y on macOS and iOS. It is an + early key handler, so it works from a composer or the terminal; Y, Shift+Y and + Alt+Y still type. When no chat floats, Ctrl+Y floats the tiled pane that has + the keyboard. When no pane has the keyboard, or that pane cannot float, the + chord is left alone. So in the terminal Ctrl+Y stays the shell's yank until a + chat floats. After that, on Windows, Linux and web, Ctrl+Y toggles even from + the terminal (yank is unavailable there, as with Ctrl+T). On macOS, Ctrl+Y in + a `TypingSurface` (terminal) always goes to the shell, and Cmd+Y toggles. +- **Focus**: showing the chat focuses its composer. Hiding it gives the keyboard + back to whatever had it before (as `TerminalFocus` does), otherwise the + keyboard is unfocused. +- **Where it shows**: only on a wide layout and while Chat is the current + destination. On narrow or phone layouts, and on other destinations, the menu + item is absent and the chord passes through. A chat that is already floating + stays floating there, unpainted, with its state, and reappears when the + window is wide again. +- **Persistence**: `pipelines.next.chatFloat.v1` is stored device-locally and + scoped like the workspace layout. It records the floating pane's id and + session, whether it is shown, and the frame. It is restored after the + workspace layout. A saved float whose session is already tiled is dropped. + +## Design + +- `ChatWorkspaceController` keeps the floating pane outside the tree + (`chat_workspace_float.dart`, a `part` with the `ChatWorkspaceFloat` + extension). `panes` and `paneCount` stay tiled-only. The pane keeps its id + through float, swap, hide and dock. +- `ChatWorkspace` gives each pane's content a `GlobalKey`. The floating chat is + that same keyed subtree, built by `ChatFloatHost` inside the workspace, so the + `ChatThreadView` State, draft, scroll and running turn move with it and are + not rebuilt. Its inherited context and focus tree stay in the workspace. +- `FloatingLayer` (`lib/ui/floating/`) paints a layer in the root overlay + through `OverlayPortal`. The chat window covers the whole app. The terminal's + floating window now uses the same layer, so the two share one z-order: the + last one pressed, focused or opened is on top. Without an overlay (bare + widget tests) the layer paints in place. +- New files: `chat_float_{host,window,binding,store,shortcut}.dart`, + `chat_workspace_float.dart`, `chat_screen_float.dart` and + `ui/floating/floating_layer.dart`. Existing files changed: workspace + controller hooks (open, split, close, replace, restore), the + `ChatWorkspace.floatFrame` parameter and keyed content, the pane controls and + `/close` and `/new` handling in `screen.dart`, the persistence wiring in + `chat_screen_workspace.dart`, and `terminal_stage.dart`. + +## Not done + +- The sidebar's "visible" highlight does not count the floating chat. +- Cmd+Y in a browser on macOS may be taken by the browser (History) before the + app sees it. Ctrl+Y works there. diff --git a/app/test/features/chat/chat_floating_pane_test.dart b/app/test/features/chat/chat_floating_pane_test.dart new file mode 100644 index 00000000..45ff1f1e --- /dev/null +++ b/app/test/features/chat/chat_floating_pane_test.dart @@ -0,0 +1,187 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/servers/server_scope.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/workspace/chat_float_store.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace_store.dart'; + +import 'conversation/chat_thread_fixtures.dart'; + +class _Gateway extends FakeChatGateway { + @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'}, + ], + }); + } + if (type == 'chat_shells') return Future.value({'chat_shells': []}); + return super.call(type, fields); + } +} + +Finder _thread(String id) => find.byWidgetPredicate( + (widget) => widget is ChatThreadView && widget.sessionId == id, + skipOffstage: false, +); +Finder _input(String id) => find.descendant( + of: find.byKey(ValueKey('chat-composer-$id'), skipOffstage: false), + matching: find.byType(EditableText, skipOffstage: false), + skipOffstage: false, +); +ChatWorkspaceController _workspace(WidgetTester tester) => + tester.widget(find.byType(ChatWorkspace)).controller; + +Future<_Gateway> _mount( + WidgetTester tester, { + Size size = const Size(1800, 1000), +}) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final gateway = _Gateway()..history = (_) async => chatPage([]); + bindServerIdentity(gateway, 'server-a'); + addTearDown(gateway.close); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ChatScreen(gateway: gateway, persistWorkspace: true), + ), + ), + ); + await tester.pumpAndSettle(); + return gateway; +} + +/// Opens [session]'s pane menu (wherever it is) and chooses [label]. +Future _menu(WidgetTester tester, String session, String label) async { + await tester.tap( + find + .descendant( + of: _thread(session), + matching: find.byTooltip('More actions'), + ) + .hitTestable(), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text(label).last); + await tester.pumpAndSettle(); +} + +Future _saved(String a, String b) async { + final layout = ChatWorkspaceController() + ..open(a) + ..splitActive(b, ChatSplitAxis.horizontal); + SharedPreferences.setMockInitialValues({ + scopedServerKey(chatWorkspacePreferenceKey, 'server-a'): layout + .snapshot()! + .encode(), + }); +} + +void main() { + testWidgets('Float and Dock move the live chat with its draft', ( + tester, + ) async { + await _saved('a', 'b'); + final gateway = await _mount(tester); + final b = tester.state(_thread('b')); + await tester.enterText(_input('b'), 'Draft B'); + await _menu(tester, 'b', 'Float (Ctrl+Y)'); + final controller = _workspace(tester); + expect(controller.floatingPane?.sessionId, 'b'); + expect(controller.panes.map((p) => p.sessionId), ['a']); + expect(find.byKey(const ValueKey('chat-float-title')), findsOneWidget); + expect(tester.state(_thread('b')), same(b)); + expect(tester.widget(_input('b')).controller.text, 'Draft B'); + // The window floats over the app, not inside a pane. + final window = tester.getRect( + find.byKey(const ValueKey('chat-float-title')), + ); + expect(window.width, lessThan(1800 / 2)); + + // The lone tiled pane can still float, swapping with the floating one. + await tester.tap( + find + .descendant( + of: _thread('a'), + matching: find.byTooltip('More actions'), + ) + .hitTestable(), + ); + await tester.pumpAndSettle(); + expect(find.text('Float (Ctrl+Y)'), findsOneWidget); + await tester.tapAt(const Offset(5, 995)); + await tester.pumpAndSettle(); + + await _menu(tester, 'b', 'Dock'); + expect(controller.floatingPane, isNull); + expect(controller.panes.map((p) => p.sessionId), ['a', 'b']); + expect(tester.state(_thread('b')), same(b)); + expect(tester.widget(_input('b')).controller.text, 'Draft B'); + expect( + gateway.calls.where( + (call) => ['chat_close', 'chat_interrupt'].contains(call.type), + ), + isEmpty, + ); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('the floating chat and its frame survive a reload', ( + tester, + ) async { + await _saved('a', 'b'); + await _mount(tester); + await _menu(tester, 'b', 'Float (Ctrl+Y)'); + await tester.drag( + find.byKey(const ValueKey('chat-float-title')), + const Offset(200, 40), + ); + await tester.pumpAndSettle(); + await _menu(tester, 'b', 'Hide floating chat (Ctrl+Y)'); + expect(find.byKey(const ValueKey('chat-float-title')), findsNothing); + await tester.pump(const Duration(seconds: 1)); + final preferences = await SharedPreferences.getInstance(); + final record = ChatFloatRecord.decode( + preferences.getString( + scopedServerKey(chatFloatPreferenceKey, 'server-a'), + )!, + )!; + expect(record.pane?.sessionId, 'b'); + expect(record.shown, isFalse); + expect(record.rect.left, chatFloatDefaultRect.left + 200); + + await tester.pumpWidget(const SizedBox.shrink()); + await _mount(tester); + final controller = _workspace(tester); + expect(controller.floatingPane?.sessionId, 'b'); + expect(controller.floatShown, isFalse); + expect(controller.panes.map((p) => p.sessionId), ['a']); + controller.setFloatShown(true); + await tester.pumpAndSettle(); + expect( + tester.getTopLeft(find.byKey(const ValueKey('chat-float-title'))).dx, + greaterThanOrEqualTo(chatFloatDefaultRect.left + 200), + ); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('narrow layouts offer no Float', (tester) async { + await _saved('a', 'b'); + await _mount(tester, size: const Size(430, 900)); + final finder = find.byTooltip('More actions').hitTestable(); + await tester.tap(finder.first); + await tester.pumpAndSettle(); + expect(find.textContaining('Float'), findsNothing); + expect(find.text('Open chats (2)'), findsOneWidget); + await tester.pumpWidget(const SizedBox.shrink()); + }); +} diff --git a/app/test/features/chat/workspace/chat_float_shortcut_test.dart b/app/test/features/chat/workspace/chat_float_shortcut_test.dart new file mode 100644 index 00000000..ed506c16 --- /dev/null +++ b/app/test/features/chat/workspace/chat_float_shortcut_test.dart @@ -0,0 +1,229 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_float_binding.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_float_shortcut.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; +import 'package:pipelines_app/ui/input/keyboard_owner.dart'; + +class _Pane extends StatefulWidget { + const _Pane(this.id); + final String id; + @override + State<_Pane> createState() => _PaneState(); +} + +class _PaneState extends State<_Pane> { + final text = TextEditingController(); + final focus = FocusNode(); + @override + void dispose() { + text.dispose(); + focus.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => Material( + child: TextField( + key: ValueKey('field-${widget.id}'), + controller: text, + focusNode: focus, + ), + ); +} + +Finder _pane(String id) => find.byWidgetPredicate( + (w) => w is _Pane && w.id == id, + skipOffstage: false, +); + +class _Harness { + final controller = ChatWorkspaceController() + ..open('a') + ..splitActive('b', ChatSplitAxis.horizontal); + final frame = ChatFloatFrame(); + final typing = FocusNode(debugLabel: 'terminal'); + final typed = []; + + Widget app({bool narrow = false}) => MaterialApp( + home: Scaffold( + body: Column( + children: [ + Expanded( + child: ChatWorkspace( + controller: controller, + floatFrame: frame, + singlePane: narrow, + onFocusPane: (pane) => _focus(pane.sessionId), + paneBuilder: (context, pane, active) => _Pane(pane.sessionId), + ), + ), + TypingSurface( + child: Focus( + focusNode: typing, + onKeyEvent: (node, event) { + if (event is KeyDownEvent && + event.logicalKey == LogicalKeyboardKey.keyY) { + typed.add(event.logicalKey); + } + return KeyEventResult.handled; + }, + child: const SizedBox(height: 40, child: Text('terminal')), + ), + ), + ], + ), + ), + ); + + WidgetTester? tester; + void _focus(String session) => + tester!.state<_PaneState>(_pane(session)).focus.requestFocus(); + + void dispose() { + controller.dispose(); + frame.dispose(); + typing.dispose(); + } +} + +Future _chord( + WidgetTester tester, + LogicalKeyboardKey modifier, { + LogicalKeyboardKey key = LogicalKeyboardKey.keyY, +}) async { + await tester.sendKeyDownEvent(modifier); + await tester.sendKeyEvent(key); + await tester.sendKeyUpEvent(modifier); + await tester.pumpAndSettle(); +} + +void main() { + test('the chord is Ctrl+Y, and Cmd+Y on Apple platforms', () { + expect(chatFloatShortcutLabel(TargetPlatform.linux), 'Ctrl+Y'); + expect(chatFloatShortcutLabel(TargetPlatform.windows), 'Ctrl+Y'); + expect(chatFloatShortcutLabel(TargetPlatform.macOS), 'Cmd+Y'); + }); + + Future<_Harness> pump(WidgetTester tester, {bool narrow = false}) async { + tester.view.physicalSize = const Size(1280, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final h = _Harness()..tester = tester; + addTearDown(h.dispose); + await tester.pumpWidget(h.app(narrow: narrow)); + await tester.pumpAndSettle(); + return h; + } + + testWidgets('Ctrl+Y floats the focused pane, then hides and shows it', ( + tester, + ) async { + final h = await pump(tester); + final b = tester.state<_PaneState>(_pane('b')); + await tester.enterText(find.byKey(const ValueKey('field-b')), 'draft'); + await tester.tap(find.byKey(const ValueKey('field-a'))); + await tester.pump(); + // Plain Y and Shift+Y type; only the chord acts. + await tester.sendKeyEvent(LogicalKeyboardKey.keyY); + await _chord(tester, LogicalKeyboardKey.shiftLeft); + expect(h.controller.floatingPane, isNull); + + tester.state<_PaneState>(_pane('b')).focus.requestFocus(); + await tester.pump(); + await _chord(tester, LogicalKeyboardKey.controlLeft); + expect(h.controller.floatingPane?.sessionId, 'b'); + expect(h.controller.paneCount, 1); + expect(find.byKey(const ValueKey('chat-float-title')), findsOneWidget); + // The chat moved: same State, same draft, its field has the keyboard. + expect(tester.state<_PaneState>(_pane('b')), same(b)); + expect(b.text.text, 'draft'); + expect(b.focus.hasFocus, isTrue); + + await _chord(tester, LogicalKeyboardKey.controlLeft); + expect(h.controller.floatShown, isFalse); + expect(find.byKey(const ValueKey('chat-float-title')), findsNothing); + expect(tester.state<_PaneState>(_pane('b')), same(b)); + + // Showing focuses the floating chat; hiding gives the keyboard back. + final a = tester.state<_PaneState>(_pane('a')); + a.focus.requestFocus(); + await tester.pump(); + await _chord(tester, LogicalKeyboardKey.controlLeft); + expect(h.controller.floatShown, isTrue); + expect(b.focus.hasFocus, isTrue); + await _chord(tester, LogicalKeyboardKey.controlLeft); + expect(a.focus.hasFocus, isTrue); + + // Docking returns the same chat to the tiling. + h.controller.dock(); + await tester.pumpAndSettle(); + expect(h.controller.paneCount, 2); + expect(tester.state<_PaneState>(_pane('b')), same(b)); + expect(b.text.text, 'draft'); + expect(tester.takeException(), isNull); + }); + + testWidgets('in a terminal, Ctrl+Y acts only when a chat floats', ( + tester, + ) async { + final h = await pump(tester); + h.typing.requestFocus(); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.keyY); + await _chord(tester, LogicalKeyboardKey.controlLeft); + // Nothing to float from the terminal: the shell gets Ctrl+Y (yank). + expect(h.controller.floatingPane, isNull); + expect(h.typed, contains(LogicalKeyboardKey.keyY)); + expect(h.typed.where((k) => k == LogicalKeyboardKey.keyY).length, 2); + + h.controller.float(h.controller.panes.last.id); + await tester.pumpAndSettle(); + h.typing.requestFocus(); + await tester.pump(); + h.typed.clear(); + await _chord(tester, LogicalKeyboardKey.controlLeft); + expect(h.controller.floatShown, isFalse); + expect(h.typed, isNot(contains(LogicalKeyboardKey.keyY))); + await tester.sendKeyEvent(LogicalKeyboardKey.keyY); + expect(h.typed, [LogicalKeyboardKey.keyY]); + }); + + testWidgets( + 'on macOS Cmd+Y toggles and Ctrl+Y in a terminal stays with it', + (tester) async { + final h = await pump(tester); + h.controller.float(h.controller.panes.last.id); + await tester.pumpAndSettle(); + h.typing.requestFocus(); + await tester.pump(); + await _chord(tester, LogicalKeyboardKey.controlLeft); + expect(h.controller.floatShown, isTrue); + expect(h.typed, [LogicalKeyboardKey.keyY]); + await _chord(tester, LogicalKeyboardKey.metaLeft); + expect(h.controller.floatShown, isFalse); + await _chord(tester, LogicalKeyboardKey.metaLeft); + expect(h.controller.floatShown, isTrue); + }, + variant: const TargetPlatformVariant({TargetPlatform.macOS}), + ); + + testWidgets('narrow layouts never show the window or take the chord', ( + tester, + ) async { + final h = await pump(tester, narrow: true); + tester.state<_PaneState>(_pane('b')).focus.requestFocus(); + await tester.pump(); + await _chord(tester, LogicalKeyboardKey.controlLeft); + expect(h.controller.floatingPane, isNull); + // A float saved on a wide window stays, unpainted, with its state. + h.controller.float(h.controller.panes.last.id); + await tester.pumpAndSettle(); + expect(find.byKey(const ValueKey('chat-float-title')), findsNothing); + expect(_pane('b'), findsOneWidget); + await _chord(tester, LogicalKeyboardKey.controlLeft); + expect(h.controller.floatShown, isTrue); + }); +} diff --git a/app/test/features/chat/workspace/chat_workspace_float_test.dart b/app/test/features/chat/workspace/chat_workspace_float_test.dart new file mode 100644 index 00000000..93045315 --- /dev/null +++ b/app/test/features/chat/workspace/chat_workspace_float_test.dart @@ -0,0 +1,191 @@ +import 'dart:ui'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_float_binding.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_float_store.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace_controller.dart'; + +ChatWorkspaceController _three() => ChatWorkspaceController() + ..open('a') + ..splitActive('b', ChatSplitAxis.horizontal) + ..splitActive('c', ChatSplitAxis.vertical); + +List _sessions(ChatWorkspaceController c) => + c.panes.map((p) => p.sessionId).toList(); + +class _Store implements ChatFloatStore { + _Store([this.record]); + ChatFloatRecord? record; + int writes = 0; + @override + Future read() async => record; + @override + Future write(ChatFloatRecord value) async { + writes++; + record = value; + return true; + } +} + +void main() { + test('float takes a pane out of the tiling and keeps its id', () { + final c = _three(); + final b = c.panes.firstWhere((p) => p.sessionId == 'b'); + c.activate(b.id); + c.float(b.id); + expect(c.floatingPane?.id, b.id); + expect(c.floatShown, isTrue); + expect(_sessions(c), ['a', 'c']); + expect(c.activePane?.sessionId, isNot('b')); + expect(c.holdsSession('b'), isTrue); + }); + + test('a lone pane cannot float; the tiling never empties', () { + final c = ChatWorkspaceController()..open('a'); + expect(c.canFloat(c.panes.single.id), isFalse); + c.float(c.panes.single.id); + expect(c.floatingPane, isNull); + c.splitActive('b', ChatSplitAxis.horizontal); + final b = c.activePane!; + c.float(b.id); + // Closing the last tiled pane docks the floating chat in its place. + c.close(c.panes.single.id); + expect(c.floatingPane, isNull); + expect(c.panes.single.id, b.id); + expect(c.activePaneId, b.id); + }); + + test('floating another chat swaps it with the floating one', () { + final c = _three(); + final a = c.panes.firstWhere((p) => p.sessionId == 'a'); + final c3 = c.panes.firstWhere((p) => p.sessionId == 'c'); + c.float(a.id); + c.setFloatShown(false); + c.float(c3.id); + expect(c.floatingPane?.id, c3.id); + expect(c.floatShown, isTrue); + expect(_sessions(c), ['b', 'a']); + expect(c.panes.last.id, a.id); + }); + + test('dock puts the chat right of the active pane and activates it', () { + final c = _three(); + final b = c.panes.firstWhere((p) => p.sessionId == 'b'); + c.float(b.id); + final active = c.activePane!; + c.dock(); + expect(c.floatingPane, isNull); + expect(c.activePaneId, b.id); + final panes = c.panes.map((p) => p.id).toList(); + expect(panes.indexOf(b.id), panes.indexOf(active.id) + 1); + expect(_sessions(c).toSet(), {'a', 'b', 'c'}); + }); + + test('hide, show, reopen, close and /new follow the floating chat', () { + final c = _three(); + final b = c.panes.firstWhere((p) => p.sessionId == 'b'); + c.float(b.id); + c.toggleFloatShown(); + expect(c.floatShown, isFalse); + c.open('b'); + expect(c.floatShown, isTrue); + expect(_sessions(c), ['a', 'c']); + c.splitActive('b', ChatSplitAxis.vertical); + expect(c.paneCount, 2); + c.replaceSession('b', 'b2'); + expect(c.floatingPane?.id, b.id); + expect(c.floatingPane?.sessionId, 'b2'); + c.close(b.id); + expect(c.floatingPane, isNull); + expect(c.paneCount, 2); + }); + + test('restoreFloat skips open sessions and taken ids', () { + final c = ChatWorkspaceController() + ..open('a') + ..splitActive('b', ChatSplitAxis.horizontal); + final taken = c.panes.first.id; + expect( + c.restoreFloat(const ChatWorkspacePane('x', 'a'), shown: true), + isFalse, + ); + expect(c.restoreFloat(ChatWorkspacePane(taken, 'z'), shown: true), isFalse); + expect( + c.restoreFloat(const ChatWorkspacePane('x', 'z'), shown: false), + isTrue, + ); + expect(c.floatingPane?.sessionId, 'z'); + expect(c.floatShown, isFalse); + // A new split id never collides with the floating pane's. + c.splitActive('d', ChatSplitAxis.vertical); + expect(c.panes.map((p) => p.id), isNot(contains('x'))); + }); + + test('a restored layout drops any floating chat', () { + final c = _three(); + c.float(c.panes.first.id); + final snapshot = c.snapshot()!; + c.restoreLayout(snapshot); + expect(c.floatingPane, isNull); + }); + + test('records round-trip and reject malformed input', () { + const record = ChatFloatRecord( + pane: ChatWorkspacePane('p1', 'server:abc'), + shown: true, + rect: Rect.fromLTWH(10, 20, 400, 300), + ); + expect(ChatFloatRecord.decode(record.encode()), record); + const none = ChatFloatRecord(rect: chatFloatDefaultRect); + expect(ChatFloatRecord.decode(none.encode()), none); + for (final bad in [ + '', + '[]', + '{"version":2,"rect":[0,0,1,1]}', + '{"version":1,"rect":[0,0,-1,1]}', + '{"version":1,"rect":[0,0,1]}', + '{"version":1,"rect":[0,0,1,1],"pane":{"id":" x","session_id":"a"}}', + '{"version":1,"rect":[0,0,1,1],"pane":7}', + ]) { + expect(ChatFloatRecord.decode(bad), isNull, reason: bad); + } + }); + + test('binding restores after the layout and saves changes', () async { + final c = ChatWorkspaceController() + ..open('a') + ..splitActive('b', ChatSplitAxis.horizontal); + final store = _Store( + const ChatFloatRecord( + pane: ChatWorkspacePane('f', 'c'), + shown: true, + rect: Rect.fromLTWH(5, 6, 400, 300), + ), + ); + final frame = ChatFloatFrame(); + final binding = ChatFloatBinding( + controller: c, + frame: frame, + store: store, + debounce: Duration.zero, + ); + await binding.start(); + expect(c.floatingPane?.sessionId, 'c'); + expect(c.floatShown, isTrue); + expect(frame.rect, const Rect.fromLTWH(5, 6, 400, 300)); + expect(store.writes, 0); + c.setFloatShown(false); + await Future.delayed(Duration.zero); + await binding.flush(); + expect(store.record?.shown, isFalse); + frame.move(const Rect.fromLTWH(50, 60, 400, 300)); + final writes = store.writes; + await binding.flush(); + expect(store.writes, writes + 1); + expect(store.record?.rect.left, 50); + c.dock(); + binding.dispose(); + await Future.delayed(Duration.zero); + expect(store.record?.pane, isNull); + }); +} diff --git a/app/test/ui/floating/floating_layer_test.dart b/app/test/ui/floating/floating_layer_test.dart new file mode 100644 index 00000000..69148e4a --- /dev/null +++ b/app/test/ui/floating/floating_layer_test.dart @@ -0,0 +1,80 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/ui/floating/floating_layer.dart'; + +void main() { + testWidgets('the layer last pressed or focused paints on top', ( + tester, + ) async { + tester.view.physicalSize = const Size(800, 600); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final hits = []; + final focus = FocusNode(); + addTearDown(focus.dispose); + Widget window(String name, double left, {FocusNode? node}) => Positioned( + left: left, + top: 100, + width: 200, + height: 200, + child: Focus( + focusNode: node, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => hits.add(name), + child: const SizedBox.expand(), + ), + ), + ); + var behind = 0; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Stack( + children: [ + Positioned.fill( + child: GestureDetector( + onTap: () => behind++, + child: const ColoredBox(color: Colors.white), + ), + ), + // Nested inside a page, like the chat workspace. + Positioned.fill( + child: FloatingLayer( + coverOverlay: true, + builder: (context, bounds) => [ + window('chat', 100, node: focus), + ], + ), + ), + Positioned.fill( + child: FloatingLayer( + builder: (context, bounds) => [window('terminal', 200)], + ), + ), + ], + ), + ), + ), + ); + const overlap = Offset(250, 200); + await tester.tapAt(overlap); + expect(hits.last, 'terminal'); + await tester.tapAt(const Offset(120, 200)); + await tester.pump(); + await tester.tapAt(overlap); + expect(hits.last, 'chat'); + await tester.tapAt(const Offset(380, 200)); + await tester.pump(); + await tester.tapAt(overlap); + expect(hits.last, 'terminal'); + focus.requestFocus(); + await tester.pump(); + await tester.pump(); + await tester.tapAt(overlap); + expect(hits.last, 'chat'); + // Space between windows passes through to the page. + await tester.tapAt(const Offset(700, 500)); + expect(behind, 1); + }); +}