diff --git a/app/lib/features/chat/chat_screen_float.dart b/app/lib/features/chat/chat_screen_float.dart index 6695fb00..9d3a540b 100644 --- a/app/lib/features/chat/chat_screen_float.dart +++ b/app/lib/features/chat/chat_screen_float.dart @@ -1,10 +1,10 @@ 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`). +/// The floating chats for one Chat destination visit: their menu choices, +/// window frames and persistence (see `notes/chat-floating-pane.md`). mixin _ChatScreenFloat on State, _ChatScreenWorkspace { @override - final ChatFloatFrame _floatFrame = ChatFloatFrame(); + final ChatFloatFrames _floatFrames = ChatFloatFrames(); ChatFloatBinding? _floatBinding; /// Restores and saves the floating chat in [store] once [restored] (the @@ -14,7 +14,7 @@ mixin _ChatScreenFloat on State, _ChatScreenWorkspace { _floatBinding?.dispose(); final binding = _floatBinding = ChatFloatBinding( controller: _workspace, - frame: _floatFrame, + frames: _floatFrames, store: store, ); unawaited( @@ -34,32 +34,31 @@ mixin _ChatScreenFloat on State, _ChatScreenWorkspace { void _disposeFloat() { _unbindFloat(); - _floatFrame.dispose(); + _floatFrames.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); + void _dockFloat(ChatWorkspacePane pane) { + _workspace.dock(pane.id); + _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. + /// Dock, Hide and Close on a floating chat. List _floatControls(ChatWorkspacePane pane) { final shortcut = chatFloatShortcutLabel(); - if (_workspace.floatingPane?.id == pane.id) { + if (_workspace.isFloating(pane.id)) { return [ ChatBarAction( label: 'Dock', - onPressed: _dockFloat, + onPressed: () => _dockFloat(pane), materialIcon: Icons.vertical_split_outlined, cupertinoIcon: CupertinoIcons.rectangle_split_3x1, ), ChatBarAction( - label: 'Hide floating chat ($shortcut)', + label: 'Hide floating chats ($shortcut)', onPressed: () => _workspace.setFloatShown(false), materialIcon: Icons.visibility_off_outlined, cupertinoIcon: CupertinoIcons.eye_slash, diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart index 20371241..8c352f74 100644 --- a/app/lib/features/chat/chat_screen_workspace.dart +++ b/app/lib/features/chat/chat_screen_workspace.dart @@ -11,7 +11,7 @@ mixin _ChatScreenWorkspace on State { JsonMap? _rowFor(String id); void _back(); bool get _pageOpen; - ChatFloatFrame get _floatFrame; + ChatFloatFrames get _floatFrames; void _bindFloat(ChatFloatStore store, Future restored); void _unbindFloat(); Widget _thread( @@ -328,7 +328,7 @@ mixin _ChatScreenWorkspace on State { controller: _workspace, onVisibleSessionIdsChanged: _workspaceVisibilityChanged, shortcutsEnabled: _workspaceVisible, - floatFrame: _floatFrame, + floatFrames: _floatFrames, singlePane: !showsListBesideDetail(context), mobilePeeks: true, paneTitle: (pane) => diff --git a/app/lib/features/chat/conversation/chat_background_tasks.dart b/app/lib/features/chat/conversation/chat_background_tasks.dart index 8097d308..8bc8f18f 100644 --- a/app/lib/features/chat/conversation/chat_background_tasks.dart +++ b/app/lib/features/chat/conversation/chat_background_tasks.dart @@ -202,7 +202,7 @@ class _ChatBackgroundTasksState extends State { // Level with the field's single line, beside Send. padding: const EdgeInsetsDirectional.only(end: 4, bottom: 4), child: Semantics( - identifier: 'chat-background-tasks-button', + identifier: 'chat-background-tasks-button', button: true, excludeSemantics: true, onTap: _open, diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index eef4bc39..a50204ec 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -319,8 +319,12 @@ class _ChatScreenState extends State .toList()) { _closePane(pane.id); } - final floating = _workspace.floatingPane; - if (floating?.sessionId == sessionId) _closePane(floating!.id); + for (final pane + in _workspace.floatingPanes + .where((pane) => pane.sessionId == sessionId) + .toList()) { + _closePane(pane.id); + } unawaited(_sessions.refresh()); } @@ -513,7 +517,7 @@ class _ChatScreenState extends State : _page.open || !showsListBesideDetail(context), paneControls: pane == null ? const [] - : _workspace.floatingPane?.id == pane.id + : _workspace.isFloating(pane.id) ? _floatControls(pane) : [ ChatBarAction( diff --git a/app/lib/features/chat/workspace/chat_float_binding.dart b/app/lib/features/chat/workspace/chat_float_binding.dart index 14c3cab8..12233a8b 100644 --- a/app/lib/features/chat/workspace/chat_float_binding.dart +++ b/app/lib/features/chat/workspace/chat_float_binding.dart @@ -6,20 +6,46 @@ 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; +/// The floating chat windows' frames, by pane id. A drag moves a window every +/// pointer event without saving; [commit] marks the end of the drag. A pane +/// keeps its frame while it is docked, so floating it again puts the window +/// back where it was. +class ChatFloatFrames extends ChangeNotifier { + ChatFloatFrames([Map frames = const {}]) + : _frames = {...frames}; + final Map _frames; int _commits = 0; + Map get frames => Map.unmodifiable(_frames); + /// 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; + /// [paneId]'s frame; a window without one opens at the default frame, + /// stepped down and right by [index] so stacked windows stay visible. + Rect rectFor(String paneId, {int index = 0}) => + _frames[paneId] ?? + chatFloatDefaultRect.shift(Offset(32, 32) * index.toDouble()); + + /// Gives [paneId] its opening frame ([rectFor] at [index]) unless it has + /// one, so the window stays put when other windows come and go. + void place(String paneId, {required int index}) { + if (_frames.containsKey(paneId)) return; + move(paneId, rectFor(paneId, index: index)); + } + + void move(String paneId, Rect rect) { + if (_frames[paneId] == rect) return; + _frames[paneId] = rect; + notifyListeners(); + } + + /// Replaces every frame (a restore). + void restore(Map frames) { + if (mapEquals(frames, _frames)) return; + _frames + ..clear() + ..addAll(frames); notifyListeners(); } @@ -29,21 +55,21 @@ class ChatFloatFrame extends ChangeNotifier { } } -/// Saves which chat floats, whether it shows and the window's frame, and +/// Saves which chats float, whether they show and their windows' frames, and /// restores them once the workspace layout itself has been restored. class ChatFloatBinding { ChatFloatBinding({ required this.controller, - required this.frame, + required this.frames, required this.store, this.debounce = const Duration(milliseconds: 250), }) { controller.addListener(_changed); - frame.addListener(_frameChanged); + frames.addListener(_framesChanged); } final ChatWorkspaceController controller; - final ChatFloatFrame frame; + final ChatFloatFrames frames; final ChatFloatStore store; final Duration debounce; ChatFloatRecord? _saved; @@ -53,11 +79,22 @@ class ChatFloatBinding { Timer? _timer; Future _writes = Future.value(); - ChatFloatRecord get _current => ChatFloatRecord( - pane: controller.floatingPane, - shown: controller.floatShown, - rect: frame.rect, - ); + /// Frames of panes still open somewhere (tiled or floating); a closed + /// pane's frame is dropped. + ChatFloatRecord get _current { + final open = { + for (final pane in controller.panes) pane.id, + for (final pane in controller.floatingPanes) pane.id, + }; + return ChatFloatRecord( + panes: controller.floatingPanes, + shown: controller.floatShown, + frames: { + for (final MapEntry(:key, :value) in frames.frames.entries) + if (open.contains(key)) key: value, + }, + ); + } /// Call after the workspace layout restored, so a saved float can tell /// whether its chat is already open in the tiling. @@ -66,25 +103,24 @@ class ChatFloatBinding { try { record = await store.read(); } on Object { - // Unavailable preferences leave the default frame and no float. + // Unavailable preferences leave the default frames 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); + _commits = frames.commits; + frames.restore(record.frames); + if (record.panes.isNotEmpty && controller.floatingPanes.isEmpty) { + controller.restoreFloats(record.panes, shown: record.shown); } } _loading = false; _changed(); } - void _frameChanged() { - if (frame.commits == _commits) return; - _commits = frame.commits; + void _framesChanged() { + if (frames.commits == _commits) return; + _commits = frames.commits; _changed(); } @@ -113,7 +149,7 @@ class ChatFloatBinding { void dispose() { if (_disposed) return; controller.removeListener(_changed); - frame.removeListener(_frameChanged); + frames.removeListener(_framesChanged); 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 index b550aebe..8d040bd5 100644 --- a/app/lib/features/chat/workspace/chat_float_host.dart +++ b/app/lib/features/chat/workspace/chat_float_host.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import '../../../ui/floating/floating_layer.dart'; @@ -11,18 +12,18 @@ 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 split workspace ([child]) with its floating chats over the app: their +/// windows, show and hide motion, focus and shortcut (see +/// [chatFloatShortcut]). [content] is a 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. +/// The windows show while [enabled] (a wide layout), over every destination, +/// like the floating terminal. They show and hide together. class ChatFloatHost extends StatefulWidget { const ChatFloatHost({ super.key, required this.controller, - required this.frame, + required this.frames, required this.enabled, required this.title, required this.content, @@ -33,13 +34,13 @@ class ChatFloatHost extends StatefulWidget { }); final ChatWorkspaceController controller; - final ChatFloatFrame frame; + final ChatFloatFrames frames; final bool enabled; - final String title; - final Widget? content; + final String Function(ChatWorkspacePane pane) title; + final Widget Function(ChatWorkspacePane pane) content; - /// The floating pane's focus scope. - final FocusScopeNode? scope; + /// A floating pane's focus scope. + final FocusScopeNode? Function(ChatWorkspacePane pane) scope; /// The tiled pane with the keyboard, which the shortcut floats when no /// chat floats yet. @@ -51,20 +52,9 @@ class ChatFloatHost extends StatefulWidget { 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; +class _ChatFloatHostState extends State { bool _visible = false; - String? _paneId; + Set _paneIds = const {}; FocusNode? _previous; @override @@ -72,13 +62,6 @@ class _ChatFloatHostState extends State 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()); } @@ -98,44 +81,41 @@ class _ChatFloatHostState extends State 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. + final panes = widget.controller.floatingPanes; + final ids = {for (final pane in panes) pane.id}; + final visible = widget.enabled && widget.controller.floatShown; + for (final (index, pane) in panes.indexed) { + widget.frames.place(pane.id, index: index); + } + if (panes.isEmpty) { + // Docked or closed: the views went back to the tiling. _previous = null; - _reveal.value = 0; } else if (visible != _visible) { if (visible) { _remember(); - unawaited(_reveal.forward()); - _focusSoon(pane); + _focusSoon(panes.last); } else { _release(); - unawaited(_reveal.reverse()); } - } else if (visible && pane.id != _paneId) { - // Another chat replaced the floating one. - _focusSoon(pane); + } else if (visible) { + // A newly floated chat takes the keyboard. + final added = panes.where((p) => !_paneIds.contains(p.id)).lastOrNull; + if (added != null) _focusSoon(added); } - _paneId = pane?.id; + _paneIds = ids; if (visible != _visible) setState(() => _visible = visible); } - bool _inside(FocusNode node) { - final scope = widget.scope; + bool _inside(FocusNode node) => widget.controller.floatingPanes.any((pane) { + final scope = widget.scope(pane); return scope != null && (identical(node, scope) || node.ancestors.contains(scope)); - } + }); void _remember() { final current = FocusManager.instance.primaryFocus; @@ -148,30 +128,30 @@ class _ChatFloatHostState extends State void _focusSoon(ChatWorkspacePane pane) { WidgetsBinding.instance ..addPostFrameCallback((_) { - if (!mounted || widget.controller.floatingPane?.id != pane.id) return; + if (!mounted || !widget.controller.isFloating(pane.id)) return; final focus = widget.onFocusPane; if (focus != null) { focus(pane); } else { - widget.scope?.requestFocus(); + widget.scope(pane)?.requestFocus(); } }) ..ensureVisualUpdate(); } - /// Gives the keyboard back to what had it before the chat showed, if the + /// Gives the keyboard back to what had it before the chats showed, if a /// floating chat has it now. void _release() { final previous = _previous; _previous = null; - final scope = widget.scope; - if (scope == null || !scope.hasFocus) return; + final current = FocusManager.instance.primaryFocus; + if (current == null || !_inside(current)) return; if (previous != null && previous.context != null && previous.canRequestFocus) { previous.requestFocus(); } else { - scope.unfocus(); + current.unfocus(); } } @@ -179,12 +159,12 @@ class _ChatFloatHostState extends State /// composer or the terminal; ignored (left to them) when it does nothing. KeyEventResult _key(KeyEvent event) { if (!mounted || - !_presentable || + !widget.enabled || !chatFloatShortcut(event, HardwareKeyboard.instance)) { return KeyEventResult.ignored; } final controller = widget.controller; - if (controller.floatingPane == null) { + if (controller.floatingPanes.isEmpty) { final pane = widget.focusedPane(); if (pane == null || !controller.canFloat(pane.id)) { return KeyEventResult.ignored; @@ -198,33 +178,37 @@ class _ChatFloatHostState extends State @override Widget build(BuildContext context) { - final content = widget.content; + final panes = widget.controller.floatingPanes; + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; return Stack( fit: StackFit.expand, children: [ widget.child, - if (content != null) + for (final (index, pane) in panes.indexed) Positioned.fill( + key: ValueKey(pane.id), + // Shown over every destination; the window's motion keeps + // running there (see [_ChatFloatSlot]). child: FloatingLayer( open: _visible, coverOverlay: true, builder: (context, bounds) => [ ListenableBuilder( - listenable: Listenable.merge([widget.frame, _reveal]), - builder: (context, _) => ChatFloatWindow( - frame: widget.frame, + listenable: widget.frames, + builder: (context, _) => _ChatFloatSlot( + visible: _visible, + rect: widget.frames.rectFor(pane.id, index: index), + currentRect: () => + widget.frames.rectFor(pane.id, index: index), + onMove: (rect) => widget.frames.move(pane.id, rect), + onCommit: widget.frames.commit, bounds: bounds, - title: widget.title, - cupertino: - chatControlsStyleOf(context) == - ChatControlsStyle.cupertino, - reveal: _curve, - hiding: !_visible, - offstage: !_visible && _reveal.isDismissed, - shortcut: chatFloatShortcutLabel(), - onDock: widget.controller.dock, + title: widget.title(pane), + cupertino: cupertino, + onDock: () => widget.controller.dock(pane.id), onHide: () => widget.controller.setFloatShown(false), - child: content, + child: widget.content(pane), ), ), ], @@ -234,3 +218,112 @@ class _ChatFloatHostState extends State ); } } + +/// One floating chat's window and its own grow-and-fade motion, so a chat +/// floated while the others show animates in alone. +class _ChatFloatSlot extends StatefulWidget { + const _ChatFloatSlot({ + required this.visible, + required this.rect, + required this.currentRect, + required this.onMove, + required this.onCommit, + required this.bounds, + required this.title, + required this.cupertino, + required this.onDock, + required this.onHide, + required this.child, + }); + + final bool visible; + final Rect rect; + final Rect Function() currentRect; + final ValueChanged onMove; + final VoidCallback onCommit; + final Size bounds; + final String title; + final bool cupertino; + final VoidCallback onDock; + final VoidCallback onHide; + final Widget child; + + @override + State<_ChatFloatSlot> createState() => _ChatFloatSlotState(); +} + +class _ChatFloatSlotState extends State<_ChatFloatSlot> + implements TickerProvider { + Ticker? _ticker; + + /// A ticker the hidden destination's [TickerMode] does not mute: the + /// window must still show and hide over another destination, and a + /// TickerMode cannot re-enable what an ancestor turned off. + @override + Ticker createTicker(TickerCallback onTick) { + assert(_ticker == null, 'one reveal ticker per window'); + return _ticker = Ticker(onTick, debugLabel: 'chat float reveal'); + } + + late final AnimationController _reveal = AnimationController( + vsync: this, + duration: Motion.standard, + ); + late final CurvedAnimation _curve = CurvedAnimation( + parent: _reveal, + curve: Motion.curve, + reverseCurve: Curves.easeInCubic, + ); + + @override + void initState() { + super.initState(); + if (widget.visible) { + WidgetsBinding.instance.addPostFrameCallback((_) => _run()); + } + } + + @override + void didUpdateWidget(covariant _ChatFloatSlot oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.visible != widget.visible) _run(); + } + + void _run() { + if (!mounted) return; + _reveal.duration = Motion.of(context, Motion.standard); + unawaited(widget.visible ? _reveal.forward() : _reveal.reverse()); + } + + @override + void dispose() { + _curve.dispose(); + _reveal.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => AnimatedBuilder( + animation: _reveal, + builder: (context, _) { + final offstage = !widget.visible && _reveal.isDismissed; + return ChatFloatWindow( + rect: widget.rect, + currentRect: widget.currentRect, + onMove: widget.onMove, + onCommit: widget.onCommit, + bounds: widget.bounds, + title: widget.title, + cupertino: widget.cupertino, + reveal: _curve, + hiding: !widget.visible, + offstage: offstage, + shortcut: chatFloatShortcutLabel(), + onDock: widget.onDock, + onHide: widget.onHide, + // A hidden window's chat pauses its tickers like a hidden tab. + child: TickerMode(enabled: !offstage, child: widget.child), + ); + }, + ); +} diff --git a/app/lib/features/chat/workspace/chat_float_store.dart b/app/lib/features/chat/workspace/chat_float_store.dart index 69848d4d..48878e4f 100644 --- a/app/lib/features/chat/workspace/chat_float_store.dart +++ b/app/lib/features/chat/workspace/chat_float_store.dart @@ -1,6 +1,7 @@ import 'dart:convert'; import 'dart:ui'; +import 'package:flutter/foundation.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../../../core/servers/server_scope.dart'; @@ -13,69 +14,128 @@ const chatFloatPreferenceKey = 'pipelines.next.chatFloat.v1'; 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}); +/// The most floating chats saved (and restored). +const int chatFloatMaxPanes = 12; - final ChatWorkspacePane? pane; +/// The floating chats as saved on this device: which panes float (oldest +/// first), whether they are shown, and each window's frame by pane id +/// (docked panes keep theirs, so floating again returns to the same place). +/// Identities and geometry only, like the workspace snapshot. +class ChatFloatRecord { + const ChatFloatRecord({ + this.panes = const [], + this.shown = false, + this.frames = const {}, + }); + + final List panes; final bool shown; - final Rect rect; + final Map frames; String encode() => jsonEncode({ - 'version': 1, - 'pane': pane == null - ? null - : {'id': pane!.id, 'session_id': pane!.sessionId}, + 'version': 2, + 'panes': [ + for (final pane in panes) {'id': pane.id, 'session_id': pane.sessionId}, + ], 'shown': shown, - 'rect': [rect.left, rect.top, rect.width, rect.height], + 'frames': { + for (final MapEntry(:key, value: r) in frames.entries) + key: [r.left, r.top, r.width, r.height], + }, }); static ChatFloatRecord? decode(String source) { - if (source.length > 4096) return null; + if (source.length > 65536) 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), - ); + if (data is! Map) return null; + return switch (data['version']) { + 1 => _decodeV1(data), + 2 => _decodeV2(data), + _ => null, + }; } on Object { return null; } } + /// One floating chat and one frame: the frame becomes that pane's. + static ChatFloatRecord? _decodeV1(Map data) { + final rect = _rect(data['rect']); + if (rect == null) return null; + final raw = data['pane']; + if (raw == null) return const ChatFloatRecord(); + final pane = _pane(raw); + if (pane == null) return null; + return ChatFloatRecord( + panes: [pane], + shown: data['shown'] == true, + frames: {pane.id: rect}, + ); + } + + static ChatFloatRecord? _decodeV2(Map data) { + final rawPanes = data['panes'], rawFrames = data['frames']; + if (rawPanes is! List || rawFrames is! Map) return null; + if (rawPanes.length > chatFloatMaxPanes) return null; + final panes = []; + for (final raw in rawPanes) { + final pane = _pane(raw); + if (pane == null || panes.any((p) => p.id == pane.id)) return null; + panes.add(pane); + } + if (rawFrames.length > 4 * chatFloatMaxPanes) return null; + final frames = {}; + for (final MapEntry(:key, :value) in rawFrames.entries) { + final rect = _rect(value); + if (!_identity(key, 256) || rect == null) return null; + frames[key as String] = rect; + } + return ChatFloatRecord( + panes: panes, + shown: data['shown'] == true, + frames: frames, + ); + } + + static ChatWorkspacePane? _pane(Object? raw) { + if (raw is! Map) return null; + final id = raw['id'], session = raw['session_id']; + if (!_identity(id, 256) || !_identity(session, 512)) return null; + return ChatWorkspacePane(id as String, session as String); + } + + static Rect? _rect(Object? values) { + 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; + return Rect.fromLTWH(left, top, width, height); + } + @override bool operator ==(Object other) => other is ChatFloatRecord && - other.pane?.id == pane?.id && - other.pane?.sessionId == pane?.sessionId && other.shown == shown && - other.rect == rect; + listEquals( + [for (final p in other.panes) (p.id, p.sessionId)], + [for (final p in panes) (p.id, p.sessionId)], + ) && + mapEquals(other.frames, frames); @override - int get hashCode => Object.hash(pane?.id, pane?.sessionId, shown, rect); + int get hashCode => Object.hash( + shown, + Object.hashAll([for (final p in panes) (p.id, p.sessionId)]), + Object.hashAllUnordered([ + for (final MapEntry(:key, :value) in frames.entries) (key, value), + ]), + ); } bool _identity(Object? value, int limit) => diff --git a/app/lib/features/chat/workspace/chat_float_window.dart b/app/lib/features/chat/workspace/chat_float_window.dart index 3e5c103d..bd367943 100644 --- a/app/lib/features/chat/workspace/chat_float_window.dart +++ b/app/lib/features/chat/workspace/chat_float_window.dart @@ -4,7 +4,6 @@ import 'package:flutter/material.dart'; import '../../../ui/adaptive/window_margins.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 @@ -24,13 +23,16 @@ Rect fitChatFloat(Rect rect, Size bounds) { ); } -/// The floating chat's window: moved by its title bar, resized from its +/// A 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.rect, + required this.currentRect, + required this.onMove, + required this.onCommit, required this.bounds, required this.title, required this.cupertino, @@ -43,7 +45,15 @@ class ChatFloatWindow extends StatelessWidget { required this.child, }); - final ChatFloatFrame frame; + /// The saved frame; it is drawn fitted inside [bounds]. + final Rect rect; + + /// The frame now: several drag events can arrive before a rebuild. + final Rect Function() currentRect; + final ValueChanged onMove; + + /// A move or resize ended. + final VoidCallback onCommit; final Size bounds; final String title; final bool cupertino; @@ -62,8 +72,8 @@ class ChatFloatWindow extends StatelessWidget { static const double revealScale = 0.92; void _resize(Offset delta) { - final rect = fitChatFloat(frame.rect, bounds); - frame.move( + final rect = fitChatFloat(currentRect(), bounds); + onMove( fitChatFloat( Rect.fromLTWH( rect.left, @@ -78,7 +88,7 @@ class ChatFloatWindow extends StatelessWidget { @override Widget build(BuildContext context) { - final rect = fitChatFloat(frame.rect, bounds); + final rect = fitChatFloat(this.rect, bounds); final window = SizedBox.fromSize( size: rect.size, child: Stack( @@ -122,7 +132,7 @@ class ChatFloatWindow extends StatelessWidget { ).animate(reveal), child: Semantics( container: true, - label: 'Floating chat', + label: 'Floating chat: $title', identifier: 'chat-float-window', child: terminalFloatChrome(context, cupertino, window), ), @@ -149,13 +159,13 @@ class ChatFloatWindow extends StatelessWidget { key: const ValueKey('chat-float-title'), behavior: HitTestBehavior.opaque, dragStartBehavior: DragStartBehavior.down, - onPanUpdate: (details) => frame.move( + onPanUpdate: (details) => onMove( fitChatFloat( - fitChatFloat(frame.rect, bounds).shift(details.delta), + fitChatFloat(currentRect(), bounds).shift(details.delta), bounds, ), ), - onPanEnd: (_) => frame.commit(), + onPanEnd: (_) => onCommit(), child: Padding( padding: const EdgeInsetsDirectional.only(start: 12), child: Align( @@ -175,7 +185,7 @@ class ChatFloatWindow extends StatelessWidget { onDock, ), _button( - 'Hide floating chat ($shortcut)', + 'Hide floating chats ($shortcut)', Icons.close, CupertinoIcons.xmark, onHide, @@ -206,7 +216,7 @@ class ChatFloatWindow extends StatelessWidget { behavior: HitTestBehavior.opaque, dragStartBehavior: DragStartBehavior.down, onPanUpdate: (details) => _resize(details.delta), - onPanEnd: (_) => frame.commit(), + onPanEnd: (_) => onCommit(), child: Padding( padding: const EdgeInsets.all(4), child: Icon( diff --git a/app/lib/features/chat/workspace/chat_workspace.dart b/app/lib/features/chat/workspace/chat_workspace.dart index bd7579d4..65dac2f0 100644 --- a/app/lib/features/chat/workspace/chat_workspace.dart +++ b/app/lib/features/chat/workspace/chat_workspace.dart @@ -3,6 +3,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import '../../../ui/floating/floating_layer.dart'; import '../../../ui/motion/motion.dart'; import '../../../ui/motion/quick_switch_animation.dart'; import 'chat_center_stage_layout.dart'; @@ -44,7 +45,7 @@ class ChatWorkspace extends StatefulWidget { this.onVisibleSessionIdsChanged, this.centerStage, this.paneColor, - this.floatFrame, + this.floatFrames, }); final ChatWorkspaceController controller; final ChatWorkspacePaneBuilder paneBuilder; @@ -64,9 +65,10 @@ class ChatWorkspace extends StatefulWidget { /// A pane's chat colour, for its strip beside the stage. final Color? Function(ChatWorkspacePane)? paneColor; - /// 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; + /// Offers floating chats (see [ChatFloatHost]) in these frames; null for a + /// workspace without them. They show only while the panes are not + /// collapsed. + final ChatFloatFrames? floatFrames; /// Keyboard navigation only: the owner can focus the target composer. /// Pointer activation leaves text-selection and pointer focus alone. @@ -293,10 +295,13 @@ class _ChatWorkspaceState extends State : !collapsed || pane.id == activeId) pane.sessionId, }); - final floating = widget.floatFrame == null - ? null - : widget.controller.floatingPane; - final existing = {...panes.map((p) => p.id), ?floating?.id}; + final floating = widget.floatFrames == null + ? const [] + : widget.controller.floatingPanes; + final existing = { + ...panes.map((p) => p.id), + ...floating.map((p) => p.id), + }; _views.removeWhere((id, _) => !existing.contains(id)); for (final id in _panes.keys.where((id) => !existing.contains(id)).toList()) { @@ -359,17 +364,15 @@ class _ChatWorkspaceState extends State moveTargets[pane.id], ), ); - final frame = widget.floatFrame; - if (frame == null) return surface; + final frames = widget.floatFrames; + if (frames == null) return surface; return ChatFloatHost( controller: widget.controller, - frame: frame, + frames: frames, 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], + title: (pane) => widget.paneTitle?.call(pane) ?? pane.sessionId, + content: _floatView, + scope: (pane) => _panes[pane.id], focusedPane: () => widget.controller.panes .where((pane) => _panes[pane.id]?.hasFocus ?? false) .firstOrNull, @@ -438,10 +441,18 @@ class _ChatWorkspaceState extends State ); } - /// 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: {}); + /// A floating chat's view: the same keyed content as in the tiling, so + /// floating and docking move it without rebuilding the chat. Its focus + /// hangs from the shell's [FloatingFocusRoot], so it keeps the keyboard + /// while another destination (which excludes this one) shows. + Widget _floatView(ChatWorkspacePane pane) => _paneContent( + pane, + active: true, + peek: false, + mobile: false, + edges: {}, + focusParent: FloatingFocusRoot.maybeOf(context), + ); Widget _paneContent( ChatWorkspacePane pane, { @@ -450,9 +461,11 @@ class _ChatWorkspaceState extends State required bool mobile, required Set edges, Map? moveTargets, + FocusNode? focusParent, }) => KeyedSubtree( key: _views.putIfAbsent(pane.id, () => GlobalKey(debugLabel: pane.id)), child: FocusScope( + parentNode: focusParent, node: _panes.putIfAbsent( pane.id, () => FocusScopeNode(debugLabel: pane.id), diff --git a/app/lib/features/chat/workspace/chat_workspace_controller.dart b/app/lib/features/chat/workspace/chat_workspace_controller.dart index 8f22bc72..540e605d 100644 --- a/app/lib/features/chat/workspace/chat_workspace_controller.dart +++ b/app/lib/features/chat/workspace/chat_workspace_controller.dart @@ -12,8 +12,9 @@ class ChatWorkspaceController extends ChangeNotifier { ChatWorkspaceNode? _root; String? _active; - /// The chat taken out of the tiling into the floating window, if any. - ChatWorkspacePane? _floating; + /// The chats taken out of the tiling into floating windows, oldest first. + /// They show and hide together. + final List _floating = []; bool _floatShown = false; double _mobilePeekFraction = .2; double get mobilePeekFraction => _mobilePeekFraction; @@ -55,7 +56,7 @@ class ChatWorkspaceController extends ChangeNotifier { } collect(_root); - collect(_floating); + _floating.forEach(collect); String id; do { id = 'chat-$kind-${++_serial}'; @@ -69,7 +70,7 @@ class ChatWorkspaceController extends ChangeNotifier { _root = snapshot.root; _active = snapshot.activePaneId; _mobilePeekFraction = snapshot.mobilePeekFraction; - _floating = null; + _floating.clear(); _serial = 0; _changed(); return true; diff --git a/app/lib/features/chat/workspace/chat_workspace_float.dart b/app/lib/features/chat/workspace/chat_workspace_float.dart index eadff91f..7503b5f4 100644 --- a/app/lib/features/chat/workspace/chat_workspace_float.dart +++ b/app/lib/features/chat/workspace/chat_workspace_float.dart @@ -1,55 +1,49 @@ 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. +/// Chats can leave the split tiling for floating windows over the app. They +/// show and hide together. A floating pane keeps its id (and so its live view) +/// while it floats, hides or docks. extension ChatWorkspaceFloat on ChatWorkspaceController { - /// The floating chat, shown or hidden. - ChatWorkspacePane? get floatingPane => _floating; + /// The floating chats, shown or hidden, oldest first. + List get floatingPanes => List.unmodifiable(_floating); - /// Whether the floating chat is shown (rather than hidden by Ctrl+Y). - bool get floatShown => _floating != null && _floatShown; + /// Whether [paneId] floats. + bool isFloating(String paneId) => _floating.any((pane) => pane.id == paneId); - /// Whether [sessionId] is open in the tiling or the floating window. + /// Whether the floating chats are shown (rather than hidden by Ctrl+Y). + bool get floatShown => _floating.isNotEmpty && _floatShown; + + /// Whether [sessionId] is open in the tiling or a floating window. bool holdsSession(String sessionId) => - _floating?.sessionId == sessionId || + _floating.any((pane) => pane.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). + /// A tiled pane can float while another chat stays in the tiling. bool canFloat(String paneId) => - panes.any((pane) => pane.id == paneId) && - (paneCount > 1 || _floating != null); + paneCount > 1 && panes.any((pane) => pane.id == paneId); - /// Floats the tiled pane [paneId]. A chat already floating returns to the - /// tiling in the place [paneId] leaves. + /// Floats the tiled pane [paneId] and shows every floating chat. 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; - } + 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; + _floating.add(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; + /// Puts the floating chat [paneId] back into the tiling, to the right of + /// the active pane, and makes it the active pane. + void dock(String paneId) { + final at = _floating.indexWhere((pane) => pane.id == paneId); + if (at < 0) return; + final pane = _floating.removeAt(at); final split = _id('split'); - _floating = null; if (_root == null) { _root = pane; } else { @@ -65,70 +59,82 @@ extension ChatWorkspaceFloat on ChatWorkspaceController { } void setFloatShown(bool shown) { - if (_floating == null || _floatShown == shown) return; + if (_floating.isEmpty || _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; + /// Restores saved floating chats, skipping any whose session is already + /// open or whose pane id is taken. With no tiled pane the first becomes + /// the tiling instead. Returns how many were restored. + int restoreFloats(List saved, {required bool shown}) { + var restored = 0; + for (final pane in saved) { + if (holdsSession(pane.sessionId) || _taken(pane.id)) continue; + if (_root == null) { + _root = pane; + _active = pane.id; + } else { + _floating.add(pane); + } + restored++; } + if (restored == 0) return 0; + _floatShown = shown; _changed(); - return true; + return restored; } - /// Opening the floating chat (from the list, a link) shows it. + bool _taken(String id) { + bool inTree(ChatWorkspaceNode? node) => + node != null && + (node.id == id || + node is ChatWorkspaceSplit && + (inTree(node.first) || inTree(node.second))); + return inTree(_root) || isFloating(id); + } + + /// Opening a floating chat (from the list, a link) shows the floats. bool _showFloating(String sessionId) { - if (_floating?.sessionId != sessionId) return false; + if (!_floating.any((pane) => pane.sessionId == sessionId)) return false; setFloatShown(true); return true; } bool _closeFloating(String paneId) { - if (_floating?.id != paneId) return false; - _floating = null; + final at = _floating.indexWhere((pane) => pane.id == paneId); + if (at < 0) return false; + _floating.removeAt(at); _changed(); return true; } - /// The tiling never empties while a chat floats: the floating chat docks. + /// The tiling never empties while a chat floats: the oldest one docks. void _adoptFloatingIfEmpty() { - if (_root != null || _floating == null) return; - _root = _floating; - _floating = null; + if (_root != null || _floating.isEmpty) return; + _root = _floating.removeAt(0); } - /// `/new` in the floating chat keeps it floating under the new session. + /// `/new` in a 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)) { + final at = _floating.indexWhere((pane) => pane.sessionId == oldId); + if (at >= 0) { + final pane = _floating[at]; + final elsewhere = + panes.any((p) => p.sessionId == newId) || + _floating.any((p) => p.sessionId == newId); + if (elsewhere) { _closeFloating(pane.id); } else { - _floating = ChatWorkspacePane(pane.id, newId); + _floating[at] = 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. + if (!_floating.any((pane) => pane.sessionId == newId)) return false; + // A tiled chat moved to a session that floats: the float stays. final tiled = panes.where((p) => p.sessionId == oldId).firstOrNull; if (tiled != null) close(tiled.id); setFloatShown(true); diff --git a/app/lib/features/chat/workspace/chat_workspace_geometry.dart b/app/lib/features/chat/workspace/chat_workspace_geometry.dart index 3900ff44..0724cad8 100644 --- a/app/lib/features/chat/workspace/chat_workspace_geometry.dart +++ b/app/lib/features/chat/workspace/chat_workspace_geometry.dart @@ -142,8 +142,10 @@ class ChatWorkspaceGeometry { }; if (gap < -slack || gap > chatPaneDividerExtent + slack) continue; final overlap = horizontal - ? math.min(origin.bottom, rect.bottom) - math.max(origin.top, rect.top) - : math.min(origin.right, rect.right) - math.max(origin.left, rect.left); + ? math.min(origin.bottom, rect.bottom) - + math.max(origin.top, rect.top) + : math.min(origin.right, rect.right) - + math.max(origin.left, rect.left); if (overlap <= slack) continue; final centred = horizontal ? rect.top <= centre && centre < rect.bottom diff --git a/app/lib/shell/adaptive_shell.dart b/app/lib/shell/adaptive_shell.dart index dd81fd6f..f88456fd 100644 --- a/app/lib/shell/adaptive_shell.dart +++ b/app/lib/shell/adaptive_shell.dart @@ -1,3 +1,4 @@ +import '../ui/floating/floating_layer.dart'; import '../ui/motion/fade_through_stack.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; @@ -422,12 +423,15 @@ class _AdaptiveShellState extends State { ); } + // Floating windows (chats) keep the keyboard over every destination. Widget _destinationStack(List contents) => ListPaneWidthsScope( widths: _paneWidths, - child: FadeThroughStack( - key: _destinationStackKey, - index: AppDestination.values.indexOf(_selected), - children: contents, + child: FloatingFocusRoot( + child: FadeThroughStack( + key: _destinationStackKey, + index: AppDestination.values.indexOf(_selected), + children: contents, + ), ), ); } diff --git a/app/lib/ui/floating/floating_layer.dart b/app/lib/ui/floating/floating_layer.dart index 66d68479..26b82973 100644 --- a/app/lib/ui/floating/floating_layer.dart +++ b/app/lib/ui/floating/floating_layer.dart @@ -97,3 +97,51 @@ class _FloatingLayerState extends State { ); } } + +/// A focus parent for floating windows placed above the app's destinations, +/// so a window built inside one destination keeps the keyboard while another +/// destination shows (a hidden destination excludes its own subtree from +/// focus). Windows attach their focus scope here with [maybeOf]. +class FloatingFocusRoot extends StatefulWidget { + const FloatingFocusRoot({super.key, required this.child}); + + final Widget child; + + /// The nearest root's focus node, or null outside one. + static FocusNode? maybeOf(BuildContext context) => + context.dependOnInheritedWidgetOfExactType<_FloatingFocusScope>()?.node; + + @override + State createState() => _FloatingFocusRootState(); +} + +class _FloatingFocusRootState extends State { + final FocusNode _node = FocusNode( + debugLabel: 'floating windows', + canRequestFocus: false, + skipTraversal: true, + ); + + @override + void dispose() { + _node.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => Focus( + focusNode: _node, + includeSemantics: false, + child: _FloatingFocusScope(node: _node, child: widget.child), + ); +} + +class _FloatingFocusScope extends InheritedWidget { + const _FloatingFocusScope({required this.node, required super.child}); + + final FocusNode node; + + @override + bool updateShouldNotify(_FloatingFocusScope oldWidget) => + oldWidget.node != node; +} diff --git a/app/notes/chat-floating-pane.md b/app/notes/chat-floating-pane.md index b4f1be4a..f74cb939 100644 --- a/app/notes/chat-floating-pane.md +++ b/app/notes/chat-floating-pane.md @@ -1,24 +1,29 @@ # 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. +On a wide layout chats can leave the split tiling and float in windows over +the app, like the floating terminal. Ctrl+Y (Cmd+Y on macOS) shows or hides +all of them together, on every destination. ## 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. + platforms) when another chat stays in the tiling. The last tiled chat cannot + float, because the tiling would be empty. Any number of chats can float; + floating one shows every floating chat. A new window opens at the default + frame stepped 32 px down and right per window already floating. +- **Show / hide**: the chord, a window's X and the menu's `Hide floating chats` + show or hide all floating windows at once. Each window keeps its own frame, + so they come back exactly where they were. - **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. + reduced motion and the animation speed apply. Each window animates on its + own, so a chat floated while others show grows in alone. - **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. + which it becomes; the others keep floating), `Hide floating chats (Ctrl+Y)`, + and Close pane (removes it from the workspace; no backend close). If the last + tiled pane closes, the oldest 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 @@ -30,23 +35,37 @@ shows or hides it. - **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. +- **Where it shows**: on a wide layout, over every destination (Runs, + Pipelines, Settings...), like the floating terminal. The windows move, + resize, type, hide and dock there as on Chat. On narrow or phone layouts the + menu item is absent and the chord passes through; floating chats stay + floating, unpainted, with their state, and reappear when the window is wide + again. +- **Other destinations (how)**: the shell hides a destination with + `FadeThroughStack` (muted tickers, no input, no focus). The windows already + paint and hit-test in the root overlay; the host also re-enables tickers + around each window (`TickerMode`) and parents each floating pane's + `FocusScope` on the shell's `FloatingFocusRoot` + (`ui/floating/floating_layer.dart`, above the destination stack), so a + hidden destination's `ExcludeFocus` does not take its keyboard. Before this, + leaving Chat started the hide animation on a muted ticker: the window stayed + painted but ignored input, so it could not be moved or closed. - **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. + scoped like the workspace layout. Record version 2 holds the floating panes + (id and session, oldest first, at most 12), whether they are shown, and a + frame per pane id. A docked pane keeps its frame, so floating it again + returns it to the same place; a closed pane's frame is dropped. Version 1 + records (one pane, one frame) still load. It is restored after the workspace + layout. A saved float whose session is already open is dropped. ## Design -- `ChatWorkspaceController` keeps the floating pane outside the tree +- `ChatWorkspaceController` keeps the floating panes 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 + extension: `floatingPanes`, `isFloating`, `dock(paneId)`, `restoreFloats`). + `panes` and `paneCount` stay tiled-only. A pane keeps its id through float, + hide and dock. Frames live in `ChatFloatFrames` (by pane id). +- `ChatWorkspace` gives each pane's content a `GlobalKey`. A 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. @@ -65,12 +84,31 @@ shows or hides it. ## Not done -- The sidebar's "visible" highlight does not count the floating chat. +- The sidebar's "visible" highlight does not count floating chats. +- Floating windows need the Chat destination to have been built; the shell + builds every destination up front, so this holds today. - Cmd+Y in a browser on macOS may be taken by the browser (History) before the app sees it. Ctrl+Y works there. ## Checks +### Multiple floats, every destination (2026-11-10) + +- `tool/memwatch/full.sh 'test/features/chat/chat_floating_pane_test.dart test/features/chat/workspace test/ui/floating'`: + 93 passed, 0 failed. `tool/analyze.sh lib test/features/chat`: clean. +- New tests: several floats toggled together by the chord and restored to + their frames, docking one keeps the other (`chat_floating_pane_test.dart`); + a float over another destination (a real `FadeThroughStack` page switch) + is hit-testable, drags, takes focus and typing, and hides by chord and its + X; controller, record v1/v2 and per-pane frame tests + (`chat_workspace_float_test.dart`). +- Fixed on the way: a drag read the frame from the last build, so several + pointer events in one frame lost movement; and a never-moved window's + cascaded frame shifted when another window docked (frames are now placed + when a chat floats). + +### Single float (earlier) + - `tool/analyze.sh lib test/features/chat test/ui test/features/terminal`: clean after the merge with main (pane moves, a410b9e5). In the merge, Float sits in the pane menu right after the Move items. diff --git a/app/test/features/chat/chat_floating_pane_test.dart b/app/test/features/chat/chat_floating_pane_test.dart index 45ff1f1e..dbd58993 100644 --- a/app/test/features/chat/chat_floating_pane_test.dart +++ b/app/test/features/chat/chat_floating_pane_test.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:pipelines_app/core/api_gateway.dart'; @@ -8,6 +9,8 @@ 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 'package:pipelines_app/ui/floating/floating_layer.dart'; +import 'package:pipelines_app/ui/motion/fade_through_stack.dart'; import 'conversation/chat_thread_fixtures.dart'; @@ -41,6 +44,7 @@ ChatWorkspaceController _workspace(WidgetTester tester) => Future<_Gateway> _mount( WidgetTester tester, { Size size = const Size(1800, 1000), + ValueNotifier? destination, }) async { tester.view.physicalSize = size; tester.view.devicePixelRatio = 1; @@ -48,10 +52,26 @@ Future<_Gateway> _mount( final gateway = _Gateway()..history = (_) async => chatPage([]); bindServerIdentity(gateway, 'server-a'); addTearDown(gateway.close); + final chat = ChatScreen(gateway: gateway, persistWorkspace: true); await tester.pumpWidget( MaterialApp( home: Scaffold( - body: ChatScreen(gateway: gateway, persistWorkspace: true), + body: destination == null + ? chat + // As the shell keeps destinations: the hidden one is muted, + // unfocusable and takes no input. + : FloatingFocusRoot( + child: ValueListenableBuilder( + valueListenable: destination, + builder: (context, index, _) => FadeThroughStack( + index: index, + children: [ + chat, + const Center(child: Text('Runs page')), + ], + ), + ), + ), ), ), ); @@ -74,10 +94,11 @@ Future _menu(WidgetTester tester, String session, String label) async { await tester.pumpAndSettle(); } -Future _saved(String a, String b) async { +Future _saved(String a, String b, [String? c]) async { final layout = ChatWorkspaceController() ..open(a) ..splitActive(b, ChatSplitAxis.horizontal); + if (c != null) layout.splitActive(c, ChatSplitAxis.horizontal); SharedPreferences.setMockInitialValues({ scopedServerKey(chatWorkspacePreferenceKey, 'server-a'): layout .snapshot()! @@ -95,7 +116,7 @@ void main() { 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.floatingPanes.single.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)); @@ -106,7 +127,7 @@ void main() { ); expect(window.width, lessThan(1800 / 2)); - // The lone tiled pane can still float, swapping with the floating one. + // The lone tiled pane cannot float: the tiling would be empty. await tester.tap( find .descendant( @@ -116,12 +137,12 @@ void main() { .hitTestable(), ); await tester.pumpAndSettle(); - expect(find.text('Float (Ctrl+Y)'), findsOneWidget); + expect(find.text('Float (Ctrl+Y)'), findsNothing); await tester.tapAt(const Offset(5, 995)); await tester.pumpAndSettle(); await _menu(tester, 'b', 'Dock'); - expect(controller.floatingPane, isNull); + expect(controller.floatingPanes, isEmpty); 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'); @@ -146,7 +167,7 @@ void main() { const Offset(200, 40), ); await tester.pumpAndSettle(); - await _menu(tester, 'b', 'Hide floating chat (Ctrl+Y)'); + await _menu(tester, 'b', 'Hide floating chats (Ctrl+Y)'); expect(find.byKey(const ValueKey('chat-float-title')), findsNothing); await tester.pump(const Duration(seconds: 1)); final preferences = await SharedPreferences.getInstance(); @@ -155,14 +176,15 @@ void main() { scopedServerKey(chatFloatPreferenceKey, 'server-a'), )!, )!; - expect(record.pane?.sessionId, 'b'); + final floated = record.panes.single; + expect(floated.sessionId, 'b'); expect(record.shown, isFalse); - expect(record.rect.left, chatFloatDefaultRect.left + 200); + expect(record.frames[floated.id]?.left, chatFloatDefaultRect.left + 200); await tester.pumpWidget(const SizedBox.shrink()); await _mount(tester); final controller = _workspace(tester); - expect(controller.floatingPane?.sessionId, 'b'); + expect(controller.floatingPanes.single.sessionId, 'b'); expect(controller.floatShown, isFalse); expect(controller.panes.map((p) => p.sessionId), ['a']); controller.setFloatShown(true); @@ -174,6 +196,127 @@ void main() { await tester.pumpWidget(const SizedBox.shrink()); }); + Future chord(WidgetTester tester) async { + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.keyY); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pumpAndSettle(); + } + + final titles = find.byKey(const ValueKey('chat-float-title')); + + testWidgets('several chats float; the chord hides and shows them all ' + 'where they were', (tester) async { + await _saved('a', 'b', 'c'); + await _mount(tester); + await _menu(tester, 'b', 'Float (Ctrl+Y)'); + await _menu(tester, 'c', 'Float (Ctrl+Y)'); + final controller = _workspace(tester); + expect(controller.floatingPanes.map((p) => p.sessionId), ['b', 'c']); + expect(controller.panes.map((p) => p.sessionId), ['a']); + expect(titles, findsNWidgets(2)); + // The second window opens stepped from the first, so both show. + final first = tester.getTopLeft(titles.first); + final second = tester.getTopLeft(titles.last); + expect(second.dx, greaterThan(first.dx)); + await tester.drag(titles.first, const Offset(300, 100)); + await tester.pumpAndSettle(); + final moved = tester.getTopLeft(titles.first); + expect(moved.dx, greaterThan(first.dx + 200)); + + await chord(tester); + expect(controller.floatShown, isFalse); + expect(titles, findsNothing); + await chord(tester); + expect(controller.floatShown, isTrue); + expect(titles, findsNWidgets(2)); + expect(tester.getTopLeft(titles.first), moved); + expect(tester.getTopLeft(titles.last), second); + + // Docking one leaves the other floating. + await _menu(tester, 'b', 'Dock'); + expect(controller.floatingPanes.map((p) => p.sessionId), ['c']); + expect(titles, findsOneWidget); + + await tester.pump(const Duration(seconds: 1)); + final preferences = await SharedPreferences.getInstance(); + final record = ChatFloatRecord.decode( + preferences.getString( + scopedServerKey(chatFloatPreferenceKey, 'server-a'), + )!, + )!; + expect(record.panes.map((p) => p.sessionId), ['c']); + // The docked chat keeps its frame for its next float. + expect(record.frames, hasLength(2)); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('a floating chat moves, types, hides and shows over another ' + 'destination', (tester) async { + await _saved('a', 'b'); + final destination = ValueNotifier(0); + addTearDown(destination.dispose); + await _mount(tester, destination: destination); + await _menu(tester, 'b', 'Float (Ctrl+Y)'); + final controller = _workspace(tester); + + destination.value = 1; + await tester.pumpAndSettle(); + expect(find.text('Runs page'), findsOneWidget); + // The chat page is offstage, so finders look past it; the window itself + // paints and takes input in the root overlay. + final title = find.byKey( + const ValueKey('chat-float-title'), + skipOffstage: false, + ); + bool hits(Finder finder) { + final box = tester.renderObject(finder); + return tester + .hitTestOnBinding(tester.getCenter(finder)) + .path + .any((entry) => identical(entry.target, box)); + } + + expect(hits(title), isTrue); + final before = tester.getTopLeft(title); + await tester.drag(title, const Offset(150, 60)); + await tester.pumpAndSettle(); + expect(tester.getTopLeft(title).dx, greaterThan(before.dx + 100)); + expect(tester.getTopLeft(title).dy, greaterThan(before.dy + 20)); + + // The composer takes the keyboard there. + final input = _input('b'); + expect(hits(input), isTrue); + await tester.tapAt(tester.getCenter(input)); + await tester.pump(); + final field = tester.widget(input); + expect(field.focusNode.hasFocus, isTrue); + tester.testTextInput.enterText('From runs'); + await tester.pump(); + expect(field.controller.text, 'From runs'); + + // The chord and the window's own hide button both work there. + // The window itself animates away and back, not only the state. + await chord(tester); + expect(controller.floatShown, isFalse); + expect(hits(title), isFalse); + await chord(tester); + expect(controller.floatShown, isTrue); + expect(hits(title), isTrue); + final hide = find.byTooltip( + 'Hide floating chats (Ctrl+Y)', + skipOffstage: false, + ); + expect(hits(hide), isTrue); + await tester.tapAt(tester.getCenter(hide)); + await tester.pumpAndSettle(); + expect(controller.floatShown, isFalse); + expect(hits(title), isFalse); + expect(tester.takeException(), isNull); + 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)); diff --git a/app/test/features/chat/chat_pane_move_test.dart b/app/test/features/chat/chat_pane_move_test.dart index c5ae8e8a..10a0fcee 100644 --- a/app/test/features/chat/chat_pane_move_test.dart +++ b/app/test/features/chat/chat_pane_move_test.dart @@ -82,7 +82,10 @@ Future _openMenu(WidgetTester tester, String session) async { MenuItemButton _item(WidgetTester tester, String label) => tester.widget( - find.ancestor(of: find.text(label), matching: find.byType(MenuItemButton)), + find.ancestor( + of: find.text(label), + matching: find.byType(MenuItemButton), + ), ); ChatWorkspaceController _controller(WidgetTester tester) => @@ -205,7 +208,9 @@ void main() { final gateway = _Gateway()..history = (_) async => chatPage([]); addTearDown(gateway.close); await tester.pumpWidget( - MaterialApp(home: Scaffold(body: ChatScreen(gateway: gateway))), + MaterialApp( + home: Scaffold(body: ChatScreen(gateway: gateway)), + ), ); await tester.pumpAndSettle(); await tester.tap(find.text('Chat a').first); diff --git a/app/test/features/chat/conversation/chat_bar_tint_test.dart b/app/test/features/chat/conversation/chat_bar_tint_test.dart index 8ac9ca46..d2c8a974 100644 --- a/app/test/features/chat/conversation/chat_bar_tint_test.dart +++ b/app/test/features/chat/conversation/chat_bar_tint_test.dart @@ -244,9 +244,6 @@ void main() { isSameColorAs(tint.foreground), ); // Outside the bar the theme's tint is untouched. - expect( - CupertinoTheme.of(context).primaryColor, - isNot(tint.foreground), - ); + expect(CupertinoTheme.of(context).primaryColor, isNot(tint.foreground)); }); } diff --git a/app/test/features/chat/files/files_panel_mutations_test.dart b/app/test/features/chat/files/files_panel_mutations_test.dart index df1bbe9a..4cc53905 100644 --- a/app/test/features/chat/files/files_panel_mutations_test.dart +++ b/app/test/features/chat/files/files_panel_mutations_test.dart @@ -271,19 +271,20 @@ void main() { expect(mounted.gateway.listings, 2); }); - testWidgets('A refused move is shown in the server\'s words until dismissed', ( - tester, - ) async { - final mounted = await pump(tester); - const refusal = '$shown/docs/notes.txt already exists'; - mounted.gateway.refusals['move_path'] = refusal; - await dragOnto(tester, 'notes.txt', 'docs'); - expect(find.text(refusal), findsOneWidget); - expect(mounted.gateway.listings, 2, reason: 'reloaded all the same'); - await tester.tap(find.text('Dismiss')); - await tester.pumpAndSettle(); - expect(find.text(refusal), findsNothing); - }); + testWidgets( + 'A refused move is shown in the server\'s words until dismissed', + (tester) async { + final mounted = await pump(tester); + const refusal = '$shown/docs/notes.txt already exists'; + mounted.gateway.refusals['move_path'] = refusal; + await dragOnto(tester, 'notes.txt', 'docs'); + expect(find.text(refusal), findsOneWidget); + expect(mounted.gateway.listings, 2, reason: 'reloaded all the same'); + await tester.tap(find.text('Dismiss')); + await tester.pumpAndSettle(); + expect(find.text(refusal), findsNothing); + }, + ); test('canDropEntryOn refuses files, itself and its own subtree', () { const docs = DirectoryEntry( diff --git a/app/test/features/chat/ui/sessions/session_attention_test.dart b/app/test/features/chat/ui/sessions/session_attention_test.dart index ce79e2fb..bedc1e14 100644 --- a/app/test/features/chat/ui/sessions/session_attention_test.dart +++ b/app/test/features/chat/ui/sessions/session_attention_test.dart @@ -39,11 +39,10 @@ void main() { }); test('only visible assistant reply text is unread', () { - bool attention(Map event) => - chatSessionFrameEffect({ - 'type': 'chat_event', - 'chat_event': {'session_id': 's', ...event}, - })!.attention; + bool attention(Map event) => chatSessionFrameEffect({ + 'type': 'chat_event', + 'chat_event': {'session_id': 's', ...event}, + })!.attention; for (final status in ['running', 'completed', 'error']) { expect( attention({ @@ -67,11 +66,7 @@ void main() { expect(attention({'kind': 'text', 'delta': ' \n'}), isFalse); for (final messageKind in ['notice', 'agent_report']) { expect( - attention({ - 'kind': 'text', - 'delta': 'x', - 'message_kind': messageKind, - }), + attention({'kind': 'text', 'delta': 'x', 'message_kind': messageKind}), isFalse, ); } diff --git a/app/test/features/chat/ui/transcript/chat_copy_gutter_test.dart b/app/test/features/chat/ui/transcript/chat_copy_gutter_test.dart index c66a4070..ab429dc4 100644 --- a/app/test/features/chat/ui/transcript/chat_copy_gutter_test.dart +++ b/app/test/features/chat/ui/transcript/chat_copy_gutter_test.dart @@ -76,34 +76,36 @@ void main() { expect(_opacity(tester), 1); }); - testWidgets('desktop shows it on hover and focus, and keeps semantics', ( - tester, - ) async { - final semantics = tester.ensureSemantics(); - await tester.pumpWidget(_host(48)); - expect(_opacity(tester), 0); - // Hidden, it is still reachable by a screen reader. - expect( - tester.getSemantics(_copy), - isSemantics(tooltip: 'Copy', isButton: true, isFocusable: true), - ); + testWidgets( + 'desktop shows it on hover and focus, and keeps semantics', + (tester) async { + final semantics = tester.ensureSemantics(); + await tester.pumpWidget(_host(48)); + expect(_opacity(tester), 0); + // Hidden, it is still reachable by a screen reader. + expect( + tester.getSemantics(_copy), + isSemantics(tooltip: 'Copy', isButton: true, isFocusable: true), + ); - final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); - addTearDown(mouse.removePointer); - await mouse.addPointer(location: Offset.zero); - await mouse.moveTo(tester.getCenter(find.text('The answer text'))); - await tester.pumpAndSettle(); - expect(_opacity(tester), 1); - await mouse.moveTo(const Offset(5, 590)); - await tester.pumpAndSettle(); - expect(_opacity(tester), 0); + final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); + addTearDown(mouse.removePointer); + await mouse.addPointer(location: Offset.zero); + await mouse.moveTo(tester.getCenter(find.text('The answer text'))); + await tester.pumpAndSettle(); + expect(_opacity(tester), 1); + await mouse.moveTo(const Offset(5, 590)); + await tester.pumpAndSettle(); + expect(_opacity(tester), 0); - // Keyboard focus reveals it too. - await tester.sendKeyEvent(LogicalKeyboardKey.tab); - await tester.pumpAndSettle(); - expect(_opacity(tester), 1); - semantics.dispose(); - }, variant: TargetPlatformVariant.only(TargetPlatform.macOS)); + // Keyboard focus reveals it too. + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.pumpAndSettle(); + expect(_opacity(tester), 1); + semantics.dispose(); + }, + variant: TargetPlatformVariant.only(TargetPlatform.macOS), + ); for (final (width, inGutter) in [(1400.0, true), (560.0, false)]) { testWidgets('a ${width.toInt()} px conversation puts Copy ' diff --git a/app/test/features/chat/workspace/chat_center_stage_test.dart b/app/test/features/chat/workspace/chat_center_stage_test.dart index 2948e6f9..4aedb91f 100644 --- a/app/test/features/chat/workspace/chat_center_stage_test.dart +++ b/app/test/features/chat/workspace/chat_center_stage_test.dart @@ -237,7 +237,7 @@ void main() { expect(widthOf(tester, 'two'), 1368 - 12 - 950); expect(find.byType(ChatCenterStageStrip), findsNothing); - workspace.dock(); + workspace.dock(workspace.floatingPanes.single.id); await tester.pumpAndSettle(); expect(workspace.activePane?.sessionId, 'one'); expect(widthOf(tester, 'one'), 950); diff --git a/app/test/features/chat/workspace/chat_float_shortcut_test.dart b/app/test/features/chat/workspace/chat_float_shortcut_test.dart index a4bdba59..cd48312d 100644 --- a/app/test/features/chat/workspace/chat_float_shortcut_test.dart +++ b/app/test/features/chat/workspace/chat_float_shortcut_test.dart @@ -42,7 +42,7 @@ class _Harness { final controller = ChatWorkspaceController() ..open('a') ..splitActive('b', ChatSplitAxis.horizontal); - final frame = ChatFloatFrame(); + final frames = ChatFloatFrames(); final typing = FocusNode(debugLabel: 'terminal'); final typed = []; @@ -53,7 +53,7 @@ class _Harness { Expanded( child: ChatWorkspace( controller: controller, - floatFrame: frame, + floatFrames: frames, singlePane: narrow, onFocusPane: (pane) => _focus(pane.sessionId), paneBuilder: (context, pane, active) => _Pane(pane.sessionId), @@ -83,7 +83,7 @@ class _Harness { void dispose() { controller.dispose(); - frame.dispose(); + frames.dispose(); typing.dispose(); } } @@ -128,12 +128,12 @@ void main() { // 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); + expect(h.controller.floatingPanes, isEmpty); tester.state<_PaneState>(_pane('b')).focus.requestFocus(); await tester.pump(); await _chord(tester, LogicalKeyboardKey.controlLeft); - expect(h.controller.floatingPane?.sessionId, 'b'); + expect(h.controller.floatingPanes.firstOrNull?.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. @@ -157,7 +157,7 @@ void main() { expect(a.focus.hasFocus, isTrue); // Docking returns the same chat to the tiling. - h.controller.dock(); + h.controller.dock(h.controller.floatingPanes.single.id); await tester.pumpAndSettle(); expect(h.controller.paneCount, 2); expect(tester.state<_PaneState>(_pane('b')), same(b)); @@ -174,7 +174,7 @@ void main() { 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.controller.floatingPanes, isEmpty); expect(h.typed, contains(LogicalKeyboardKey.keyY)); expect(h.typed.where((k) => k == LogicalKeyboardKey.keyY).length, 2); @@ -216,7 +216,7 @@ void main() { tester.state<_PaneState>(_pane('b')).focus.requestFocus(); await tester.pump(); await _chord(tester, LogicalKeyboardKey.controlLeft); - expect(h.controller.floatingPane, isNull); + expect(h.controller.floatingPanes, isEmpty); // A float saved on a wide window stays, unpainted, with its state. h.controller.float(h.controller.panes.last.id); await tester.pumpAndSettle(); diff --git a/app/test/features/chat/workspace/chat_pane_move_test.dart b/app/test/features/chat/workspace/chat_pane_move_test.dart index 4c727b48..4fdfdd8f 100644 --- a/app/test/features/chat/workspace/chat_pane_move_test.dart +++ b/app/test/features/chat/workspace/chat_pane_move_test.dart @@ -125,7 +125,9 @@ void main() { addTearDown(controller.dispose); final outer = controller.root as ChatWorkspaceSplit; controller.resize(outer.id, .3); - final ids = {for (final s in ['a', 'b', 'c', 'd']) s: _id(controller, s)}; + final ids = { + for (final s in ['a', 'b', 'c', 'd']) s: _id(controller, s), + }; final serial = controller.moveSerial; controller.swap(ids['a']!, ids['c']!); expect(controller.panes.map((p) => p.sessionId), ['c', 'b', 'a', 'd']); diff --git a/app/test/features/chat/workspace/chat_workspace_float_test.dart b/app/test/features/chat/workspace/chat_workspace_float_test.dart index 93045315..9a657953 100644 --- a/app/test/features/chat/workspace/chat_workspace_float_test.dart +++ b/app/test/features/chat/workspace/chat_workspace_float_test.dart @@ -13,6 +13,12 @@ ChatWorkspaceController _three() => ChatWorkspaceController() List _sessions(ChatWorkspaceController c) => c.panes.map((p) => p.sessionId).toList(); +List _floating(ChatWorkspaceController c) => + c.floatingPanes.map((p) => p.sessionId).toList(); + +ChatWorkspacePane _pane(ChatWorkspaceController c, String session) => + c.panes.firstWhere((p) => p.sessionId == session); + class _Store implements ChatFloatStore { _Store([this.record]); ChatFloatRecord? record; @@ -30,10 +36,11 @@ class _Store implements ChatFloatStore { 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'); + final b = _pane(c, 'b'); c.activate(b.id); c.float(b.id); - expect(c.floatingPane?.id, b.id); + expect(c.floatingPanes.single.id, b.id); + expect(c.isFloating(b.id), isTrue); expect(c.floatShown, isTrue); expect(_sessions(c), ['a', 'c']); expect(c.activePane?.sessionId, isNot('b')); @@ -44,37 +51,47 @@ void main() { final c = ChatWorkspaceController()..open('a'); expect(c.canFloat(c.panes.single.id), isFalse); c.float(c.panes.single.id); - expect(c.floatingPane, isNull); + expect(c.floatingPanes, isEmpty); 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. + // The last tiled chat stays: it cannot float too. + expect(c.canFloat(c.panes.single.id), isFalse); + // Closing the last tiled pane docks the oldest floating chat in its place. c.close(c.panes.single.id); - expect(c.floatingPane, isNull); + expect(c.floatingPanes, isEmpty); expect(c.panes.single.id, b.id); expect(c.activePaneId, b.id); }); - test('floating another chat swaps it with the floating one', () { + test('several chats float together and show or hide together', () { 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.float(_pane(c, 'a').id); c.setFloatShown(false); - c.float(c3.id); - expect(c.floatingPane?.id, c3.id); + c.float(_pane(c, 'c').id); + expect(_floating(c), ['a', 'c']); + // Floating another one shows them all. expect(c.floatShown, isTrue); + expect(_sessions(c), ['b']); + c.toggleFloatShown(); + expect(c.floatShown, isFalse); + c.toggleFloatShown(); + expect(c.floatShown, isTrue); + // Docking one leaves the other floating. + final a = c.floatingPanes.first; + c.dock(a.id); + expect(_floating(c), ['c']); + expect(c.activePaneId, a.id); 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'); + final b = _pane(c, 'b'); c.float(b.id); final active = c.activePane!; - c.dock(); - expect(c.floatingPane, isNull); + c.dock(b.id); + expect(c.floatingPanes, isEmpty); expect(c.activePaneId, b.id); final panes = c.panes.map((p) => p.id).toList(); expect(panes.indexOf(b.id), panes.indexOf(active.id) + 1); @@ -83,7 +100,7 @@ void main() { test('hide, show, reopen, close and /new follow the floating chat', () { final c = _three(); - final b = c.panes.firstWhere((p) => p.sessionId == 'b'); + final b = _pane(c, 'b'); c.float(b.id); c.toggleFloatShown(); expect(c.floatShown, isFalse); @@ -93,55 +110,101 @@ void main() { c.splitActive('b', ChatSplitAxis.vertical); expect(c.paneCount, 2); c.replaceSession('b', 'b2'); - expect(c.floatingPane?.id, b.id); - expect(c.floatingPane?.sessionId, 'b2'); + expect(c.floatingPanes.single.id, b.id); + expect(c.floatingPanes.single.sessionId, 'b2'); c.close(b.id); - expect(c.floatingPane, isNull); + expect(c.floatingPanes, isEmpty); expect(c.paneCount, 2); }); - test('restoreFloat skips open sessions and taken ids', () { + test('/new into a session another float holds closes the duplicate', () { + final c = _three(); + c.float(_pane(c, 'a').id); + c.float(_pane(c, 'b').id); + c.replaceSession('a', 'b'); + expect(_floating(c), ['b']); + }); + + test('restoreFloats 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, + c.restoreFloats([ + const ChatWorkspacePane('x', 'a'), + ChatWorkspacePane(taken, 'z'), + ], shown: true), + 0, ); - 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. + expect( + c.restoreFloats([ + const ChatWorkspacePane('x', 'z'), + const ChatWorkspacePane('y', 'w'), + const ChatWorkspacePane('x', 'v'), + ], shown: false), + 2, + ); + expect(_floating(c), ['z', 'w']); + expect(c.floatShown, isFalse); + // A new split id never collides with a floating pane's. c.splitActive('d', ChatSplitAxis.vertical); - expect(c.panes.map((p) => p.id), isNot(contains('x'))); + expect( + c.panes.map((p) => p.id), + isNot(anyOf(contains('x'), contains('y'))), + ); }); - test('a restored layout drops any floating chat', () { + test('a restored layout drops every floating chat', () { final c = _three(); c.float(c.panes.first.id); + c.float(c.panes.first.id); final snapshot = c.snapshot()!; c.restoreLayout(snapshot); - expect(c.floatingPane, isNull); + expect(c.floatingPanes, isEmpty); }); - test('records round-trip and reject malformed input', () { + test('records round-trip, read version 1 and reject malformed input', () { const record = ChatFloatRecord( - pane: ChatWorkspacePane('p1', 'server:abc'), + panes: [ + ChatWorkspacePane('p1', 'server:abc'), + ChatWorkspacePane('p2', 'server:def'), + ], shown: true, - rect: Rect.fromLTWH(10, 20, 400, 300), + frames: { + 'p1': Rect.fromLTWH(10, 20, 400, 300), + 'p3': Rect.fromLTWH(1, 2, 330, 250), + }, ); expect(ChatFloatRecord.decode(record.encode()), record); - const none = ChatFloatRecord(rect: chatFloatDefaultRect); + const none = ChatFloatRecord(); expect(ChatFloatRecord.decode(none.encode()), none); + expect( + ChatFloatRecord.decode( + '{"version":1,"rect":[1,2,400,300],"shown":true,' + '"pane":{"id":"p","session_id":"s"}}', + ), + const ChatFloatRecord( + panes: [ChatWorkspacePane('p', 's')], + shown: true, + frames: {'p': Rect.fromLTWH(1, 2, 400, 300)}, + ), + ); + expect( + ChatFloatRecord.decode('{"version":1,"rect":[0,0,1,1],"pane":null}'), + none, + ); for (final bad in [ '', '[]', - '{"version":2,"rect":[0,0,1,1]}', + '{"version":3,"panes":[],"frames":{}}', + '{"version":2,"panes":[]}', + '{"version":2,"panes":[7],"frames":{}}', + '{"version":2,"panes":[],"frames":{"p":[0,0,-1,1]}}', + '{"version":2,"panes":[],"frames":{" p":[0,0,1,1]}}', + '{"version":2,"panes":[{"id":"p","session_id":"a"},' + '{"id":"p","session_id":"b"}],"frames":{}}', '{"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"}}', @@ -151,41 +214,62 @@ void main() { } }); + test('frames are kept per pane, cascade by default and restore', () { + final frames = ChatFloatFrames(); + expect(frames.rectFor('a'), chatFloatDefaultRect); + expect( + frames.rectFor('b', index: 2), + chatFloatDefaultRect.shift(const Offset(64, 64)), + ); + frames.move('a', const Rect.fromLTWH(1, 2, 400, 300)); + expect(frames.rectFor('a', index: 3), const Rect.fromLTWH(1, 2, 400, 300)); + frames.restore({'b': const Rect.fromLTWH(9, 9, 400, 300)}); + expect(frames.rectFor('a'), chatFloatDefaultRect); + expect(frames.rectFor('b'), const Rect.fromLTWH(9, 9, 400, 300)); + }); + 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'), + panes: [ChatWorkspacePane('f', 'c'), ChatWorkspacePane('g', 'd')], shown: true, - rect: Rect.fromLTWH(5, 6, 400, 300), + frames: { + 'f': Rect.fromLTWH(5, 6, 400, 300), + 'g': Rect.fromLTWH(50, 60, 400, 300), + }, ), ); - final frame = ChatFloatFrame(); + final frames = ChatFloatFrames(); final binding = ChatFloatBinding( controller: c, - frame: frame, + frames: frames, store: store, debounce: Duration.zero, ); await binding.start(); - expect(c.floatingPane?.sessionId, 'c'); + expect(_floating(c), ['c', 'd']); expect(c.floatShown, isTrue); - expect(frame.rect, const Rect.fromLTWH(5, 6, 400, 300)); + expect(frames.rectFor('f'), const Rect.fromLTWH(5, 6, 400, 300)); + expect(frames.rectFor('g'), const Rect.fromLTWH(50, 60, 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)); + frames.move('f', const Rect.fromLTWH(70, 80, 400, 300)); final writes = store.writes; await binding.flush(); expect(store.writes, writes + 1); - expect(store.record?.rect.left, 50); - c.dock(); + expect(store.record?.frames['f']?.left, 70); + // A docked chat keeps its frame for the next float; a closed one drops it. + c.dock('f'); + c.close('g'); binding.dispose(); await Future.delayed(Duration.zero); - expect(store.record?.pane, isNull); + expect(store.record?.panes, isEmpty); + expect(store.record?.frames.keys, ['f']); }); }