Float one chat pane over the app and toggle it with Ctrl+Y / Cmd+Y

This commit is contained in:
2026-11-10 12:56:39 +00:00
parent 19aa726e7f
commit bb669aface
18 changed files with 1957 additions and 56 deletions
@@ -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<ChatScreen>, _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<void> 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<Widget> _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,
),
];
}
}
@@ -11,6 +11,9 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
JsonMap? _rowFor(String id);
void _back();
bool get _pageOpen;
ChatFloatFrame get _floatFrame;
void _bindFloat(ChatFloatStore store, Future<void> restored);
void _unbindFloat();
Widget _thread(
String selected,
VoidCallback onBack, {
@@ -114,8 +117,17 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
_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<ChatScreen> {
}
_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<ChatScreen> {
controller: _workspace,
onVisibleSessionIdsChanged: _workspaceVisibilityChanged,
shortcutsEnabled: _workspaceVisible,
floatFrame: _floatFrame,
singlePane: !showsListBesideDetail(context),
mobilePeeks: true,
paneTitle: (pane) =>
+12 -5
View File
@@ -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<ChatScreen>
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<ChatScreen>
/// 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<ChatScreen>
.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<ChatScreen>
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<ChatScreen>
: _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<ChatScreen>
materialIcon: Icons.close,
cupertinoIcon: CupertinoIcons.xmark,
),
..._floatControls(pane),
],
);
return ChatComposerFocusScope(
@@ -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<void> _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<void> 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<void> 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;
}
}
@@ -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<ChatWorkspacePane>? onFocusPane;
final Widget child;
@override
State<ChatFloatHost> createState() => _ChatFloatHostState();
}
class _ChatFloatHostState extends State<ChatFloatHost>
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,
),
),
],
),
),
],
);
}
}
@@ -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';
@@ -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<ChatFloatRecord?> read();
Future<bool> 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<ChatFloatRecord?> read() async {
try {
final source = (await SharedPreferences.getInstance()).getString(key);
return source == null ? null : ChatFloatRecord.decode(source);
} on Object {
return null;
}
}
@override
Future<bool> write(ChatFloatRecord record) async {
try {
return await (await SharedPreferences.getInstance()).setString(
key,
record.encode(),
);
} on Object {
return false;
}
}
}
@@ -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<double> 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<double>(
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,
),
),
),
),
);
}
@@ -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<Set<String>>? 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<ChatWorkspacePane>? onFocusPane;
@@ -83,6 +90,10 @@ class _ChatWorkspaceState extends State<ChatWorkspace>
with SingleTickerProviderStateMixin {
final _focus = FocusNode(debugLabel: 'Chat workspace');
final Map<String, FocusScopeNode> _panes = {};
/// Each pane's view keeps its State when it moves into or out of the
/// floating window.
final Map<String, GlobalKey> _views = {};
late final ChatPaneSwitchMotion _motion;
ChatWorkspaceGeometry? _geometry;
String? _lastActiveId;
@@ -246,7 +257,11 @@ class _ChatWorkspaceState extends State<ChatWorkspace>
: !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<ChatWorkspace>
edge,
},
};
return chatWorkspaceSurface(
final surface = chatWorkspaceSurface(
context: context,
backdrop: _backdrop,
motion: _motion,
@@ -298,6 +313,23 @@ class _ChatWorkspaceState extends State<ChatWorkspace>
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<ChatWorkspace>
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<String> 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),
),
),
),
),
),
);
}
@@ -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;
@@ -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;
}
}
+19 -9
View File
@@ -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,
),
],
),
),
],
);
+99
View File
@@ -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<Widget> 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<FloatingLayer> createState() => _FloatingLayerState();
}
class _FloatingLayerState extends State<FloatingLayer> {
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(),
);
}
}