Add resizable split chat workspace primitives

This commit is contained in:
2026-11-06 18:01:14 +00:00
parent 51ee950a5b
commit dfcdf1c154
6 changed files with 937 additions and 0 deletions
@@ -0,0 +1,179 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'chat_workspace_controller.dart';
import 'chat_workspace_divider.dart';
import 'chat_workspace_geometry.dart';
export 'chat_workspace_controller.dart';
export 'chat_workspace_geometry.dart' show ChatPaneDirection;
typedef ChatWorkspacePaneBuilder =
Widget Function(BuildContext context, ChatWorkspacePane pane, bool active);
/// All chat views are stable siblings, independent of the split tree. Moving a
/// divider or adding/removing a neighbouring split never reparents a chat view.
class ChatWorkspace extends StatefulWidget {
const ChatWorkspace({
super.key,
required this.controller,
required this.paneBuilder,
this.onFocusPane,
this.shortcutsEnabled = true,
});
final ChatWorkspaceController controller;
final ChatWorkspacePaneBuilder paneBuilder;
final bool shortcutsEnabled;
/// Keyboard navigation only: the owner can focus the target composer.
/// Pointer activation leaves text-selection and pointer focus alone.
final ValueChanged<ChatWorkspacePane>? onFocusPane;
@override
State<ChatWorkspace> createState() => _ChatWorkspaceState();
}
class _ChatWorkspaceState extends State<ChatWorkspace> {
final _focus = FocusNode(debugLabel: 'Chat workspace');
final Map<String, FocusScopeNode> _panes = {};
ChatWorkspaceGeometry? _geometry;
@override
void initState() {
super.initState();
HardwareKeyboard.instance.addHandler(_key);
}
bool _key(KeyEvent event) {
if (!widget.shortcutsEnabled ||
!_focus.hasFocus ||
event is! KeyDownEvent) {
return false;
}
final keyboard = HardwareKeyboard.instance;
final modifier =
keyboard.isControlPressed && !keyboard.isMetaPressed ||
defaultTargetPlatform == TargetPlatform.macOS &&
keyboard.isMetaPressed &&
!keyboard.isControlPressed;
if (!modifier || !keyboard.isShiftPressed || keyboard.isAltPressed) {
return false;
}
final direction = switch (event.logicalKey) {
LogicalKeyboardKey.arrowLeft => ChatPaneDirection.left,
LogicalKeyboardKey.arrowRight => ChatPaneDirection.right,
LogicalKeyboardKey.arrowUp => ChatPaneDirection.up,
LogicalKeyboardKey.arrowDown => ChatPaneDirection.down,
_ => null,
};
if (direction == null) return false;
final id = widget.controller.activePaneId;
final target = id == null ? null : _geometry?.neighbor(id, direction);
if (target != null) {
widget.controller.activate(target);
final pane = widget.controller.activePane!;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || widget.controller.activePaneId != target) return;
if (widget.onFocusPane != null) {
widget.onFocusPane!(pane);
} else {
_panes[target]?.requestFocus();
}
});
}
// Consume a workspace navigation chord at an edge too: it must not select
// words in the current composer when there is no neighbouring pane.
return true;
}
@override
void dispose() {
HardwareKeyboard.instance.removeHandler(_key);
_focus.dispose();
for (final node in _panes.values) {
node.dispose();
}
super.dispose();
}
@override
Widget build(BuildContext context) => Focus(
focusNode: _focus,
child: ListenableBuilder(
listenable: widget.controller,
builder: (context, _) => LayoutBuilder(
builder: (context, constraints) {
final root = widget.controller.root;
if (root == null) return const SizedBox.shrink();
final geometry = ChatWorkspaceGeometry(root, constraints.biggest);
_geometry = geometry;
final panes = widget.controller.panes;
final existing = panes.map((p) => p.id).toSet();
for (final id
in _panes.keys.where((id) => !existing.contains(id)).toList()) {
final node = _panes.remove(id)!;
WidgetsBinding.instance.addPostFrameCallback((_) => node.dispose());
}
return Stack(
fit: StackFit.expand,
clipBehavior: Clip.hardEdge,
children: [
for (final pane in panes)
Positioned.fromRect(
key: ValueKey('chat-workspace-${pane.id}'),
rect: geometry.collapsed
? Offset.zero & constraints.biggest
: geometry.panes[pane.id]!,
child: Offstage(
offstage:
geometry.collapsed &&
pane.id != widget.controller.activePaneId,
child: ExcludeFocus(
excluding:
geometry.collapsed &&
pane.id != widget.controller.activePaneId,
child: FocusScope(
node: _panes.putIfAbsent(
pane.id,
() => FocusScopeNode(debugLabel: pane.id),
),
onFocusChange: (focused) {
if (focused) widget.controller.activate(pane.id);
},
child: Listener(
behavior: HitTestBehavior.translucent,
onPointerDown: (_) =>
widget.controller.activate(pane.id),
child: Semantics(
identifier: 'chat-pane-${pane.id}',
container: true,
child: widget.paneBuilder(
context,
pane,
pane.id == widget.controller.activePaneId,
),
),
),
),
),
),
),
if (!geometry.collapsed)
for (final divider in geometry.dividers)
Positioned.fromRect(
key: ValueKey('chat-workspace-${divider.split.id}'),
rect: divider.rect,
child: ChatWorkspaceDivider(
geometry: divider,
onChanged: (ratio) =>
widget.controller.resize(divider.split.id, ratio),
),
),
],
);
},
),
),
);
}
@@ -0,0 +1,177 @@
import 'package:flutter/foundation.dart';
enum ChatSplitAxis { horizontal, vertical }
sealed class ChatWorkspaceNode {
const ChatWorkspaceNode(this.id);
final String id;
}
class ChatWorkspacePane extends ChatWorkspaceNode {
const ChatWorkspacePane(super.id, this.sessionId);
final String sessionId;
}
class ChatWorkspaceSplit extends ChatWorkspaceNode {
const ChatWorkspaceSplit(
super.id,
this.axis,
this.first,
this.second, {
this.ratio = .5,
});
final ChatSplitAxis axis;
final ChatWorkspaceNode first, second;
final double ratio;
}
/// Visit-local layout. Pane identities survive nested splits and resizing.
class ChatWorkspaceController extends ChangeNotifier {
ChatWorkspaceNode? _root;
String? _active;
int _serial = 0;
ChatWorkspaceNode? get root => _root;
String? get activePaneId => _active;
int get paneCount => panes.length;
List<ChatWorkspacePane> get panes => _panes(_root).toList();
ChatWorkspacePane? get activePane =>
panes.where((p) => p.id == _active).firstOrNull;
Iterable<ChatWorkspacePane> _panes(ChatWorkspaceNode? node) sync* {
if (node is ChatWorkspacePane) yield node;
if (node is ChatWorkspaceSplit) {
yield* _panes(node.first);
yield* _panes(node.second);
}
}
String _id(String kind) => 'chat-$kind-${++_serial}';
/// Ordinary opening replaces the active pane; an already-open chat is focused.
void open(String sessionId) {
if (sessionId.isEmpty) return;
final existing = panes.where((p) => p.sessionId == sessionId).firstOrNull;
if (existing != null) {
activate(existing.id);
return;
}
if (_root == null) {
final pane = ChatWorkspacePane(_id('pane'), sessionId);
_root = pane;
_active = pane.id;
} else {
final target = activePane ?? panes.first;
_root = _replace(
_root!,
target.id,
ChatWorkspacePane(target.id, sessionId),
);
_active = target.id;
}
notifyListeners();
}
void splitActive(String sessionId, ChatSplitAxis axis) {
if (sessionId.isEmpty) return;
if (_root == null) {
open(sessionId);
return;
}
final existing = panes.where((p) => p.sessionId == sessionId).firstOrNull;
if (existing != null) {
activate(existing.id);
return;
}
final target = activePane ?? panes.first;
final added = ChatWorkspacePane(_id('pane'), sessionId);
_root = _replace(
_root!,
target.id,
ChatWorkspaceSplit(_id('split'), axis, target, added),
);
_active = added.id;
notifyListeners();
}
void activate(String paneId) {
if (_active == paneId || !panes.any((p) => p.id == paneId)) return;
_active = paneId;
notifyListeners();
}
void resize(String splitId, double ratio) {
if (_root == null || !ratio.isFinite) return;
_root = _resize(_root!, splitId, ratio.clamp(.01, .99));
notifyListeners();
}
void close(String paneId) {
final before = panes;
final index = before.indexWhere((p) => p.id == paneId);
if (index < 0) return;
_root = _remove(_root!, paneId);
final after = panes;
if (_active == paneId) {
_active = after.isEmpty
? null
: after[index.clamp(0, after.length - 1)].id;
}
notifyListeners();
}
void replaceSession(String oldId, String newId) {
if (oldId == newId || newId.isEmpty) return;
final pane = panes.where((p) => p.sessionId == oldId).firstOrNull;
if (pane == null) return;
final existing = panes.where((p) => p.sessionId == newId).firstOrNull;
if (existing != null) {
close(pane.id);
activate(existing.id);
return;
}
_root = _replace(_root!, pane.id, ChatWorkspacePane(pane.id, newId));
notifyListeners();
}
ChatWorkspaceNode _replace(
ChatWorkspaceNode node,
String id,
ChatWorkspaceNode replacement,
) {
if (node.id == id) return replacement;
if (node is! ChatWorkspaceSplit) return node;
return ChatWorkspaceSplit(
node.id,
node.axis,
_replace(node.first, id, replacement),
_replace(node.second, id, replacement),
ratio: node.ratio,
);
}
ChatWorkspaceNode _resize(ChatWorkspaceNode node, String id, double ratio) {
if (node is! ChatWorkspaceSplit) return node;
return ChatWorkspaceSplit(
node.id,
node.axis,
_resize(node.first, id, ratio),
_resize(node.second, id, ratio),
ratio: node.id == id ? ratio : node.ratio,
);
}
ChatWorkspaceNode? _remove(ChatWorkspaceNode node, String id) {
if (node.id == id) return null;
if (node is! ChatWorkspaceSplit) return node;
final first = _remove(node.first, id), second = _remove(node.second, id);
if (first == null) return second;
if (second == null) return first;
return ChatWorkspaceSplit(
node.id,
node.axis,
first,
second,
ratio: node.ratio,
);
}
}
@@ -0,0 +1,112 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../ui/adaptive/host.dart';
import 'chat_workspace_controller.dart';
import 'chat_workspace_geometry.dart';
/// A standard separator with a mouse/touch grab area and keyboard resizing.
class ChatWorkspaceDivider extends StatefulWidget {
const ChatWorkspaceDivider({
super.key,
required this.geometry,
required this.onChanged,
});
final ChatWorkspaceDividerGeometry geometry;
final ValueChanged<double> onChanged;
@override
State<ChatWorkspaceDivider> createState() => _ChatWorkspaceDividerState();
}
class _ChatWorkspaceDividerState extends State<ChatWorkspaceDivider> {
double? _drag;
bool _hovered = false, _focused = false;
bool get _horizontal =>
widget.geometry.split.axis == ChatSplitAxis.horizontal;
double get _available =>
(_horizontal
? widget.geometry.container.width
: widget.geometry.container.height) -
chatPaneDividerExtent;
double get _actual =>
(_horizontal
? widget.geometry.rect.left - widget.geometry.container.left
: widget.geometry.rect.top - widget.geometry.container.top) /
_available;
void _change(double value) => widget.onChanged(
value.clamp(widget.geometry.minimum, widget.geometry.maximum),
);
void _step(double value) => _change(_actual + value / _available);
@override
Widget build(BuildContext context) {
final verticalLine = _horizontal;
final color = usesCupertinoHost(context)
? CupertinoColors.separator.resolveFrom(context)
: Theme.of(context).dividerColor;
return Semantics(
identifier: 'chat-divider-${widget.geometry.split.id}',
label: 'Resize chat panes ${_horizontal ? 'horizontally' : 'vertically'}',
value: '${(_actual * 100).round()} percent',
increasedValue:
'${((_actual + 16 / _available).clamp(widget.geometry.minimum, widget.geometry.maximum) * 100).round()} percent',
decreasedValue:
'${((_actual - 16 / _available).clamp(widget.geometry.minimum, widget.geometry.maximum) * 100).round()} percent',
onIncrease: () => _step(16),
onDecrease: () => _step(-16),
child: Focus(
onFocusChange: (value) => setState(() => _focused = value),
onKeyEvent: (_, event) {
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return KeyEventResult.ignored;
}
final negative = _horizontal
? LogicalKeyboardKey.arrowLeft
: LogicalKeyboardKey.arrowUp;
final positive = _horizontal
? LogicalKeyboardKey.arrowRight
: LogicalKeyboardKey.arrowDown;
if (event.logicalKey != negative && event.logicalKey != positive) {
return KeyEventResult.ignored;
}
_step(event.logicalKey == negative ? -16 : 16);
return KeyEventResult.handled;
},
child: MouseRegion(
cursor: _horizontal
? SystemMouseCursors.resizeColumn
: SystemMouseCursors.resizeRow,
onEnter: (_) => setState(() => _hovered = true),
onExit: (_) => setState(() => _hovered = false),
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onDoubleTap: () => _change(.5),
onPanStart: (_) => setState(() => _drag = _actual),
onPanUpdate: (details) {
_drag =
(_drag ?? _actual) +
(_horizontal ? details.delta.dx : details.delta.dy) /
_available;
_change(_drag!);
},
onPanEnd: (_) => setState(() => _drag = null),
onPanCancel: () => setState(() => _drag = null),
child: Center(
child: Container(
width: verticalLine
? (_hovered || _focused || _drag != null ? 3 : 1)
: null,
height: verticalLine
? null
: (_hovered || _focused || _drag != null ? 3 : 1),
color: color,
),
),
),
),
),
);
}
}
@@ -0,0 +1,150 @@
import 'dart:math' as math;
import 'dart:ui';
import 'chat_workspace_controller.dart';
const chatPaneMinimumWidth = 240.0;
const chatPaneMinimumHeight = 200.0;
const chatPaneDividerExtent = 12.0;
enum ChatPaneDirection { left, right, up, down }
class ChatWorkspaceDividerGeometry {
const ChatWorkspaceDividerGeometry(
this.split,
this.rect,
this.container,
this.minimum,
this.maximum,
);
final ChatWorkspaceSplit split;
final Rect rect, container;
final double minimum, maximum;
}
/// Geometry is separate from widget ancestry: leaf widgets remain siblings.
class ChatWorkspaceGeometry {
ChatWorkspaceGeometry(ChatWorkspaceNode root, Size size) {
final minimum = minimumSize(root);
collapsed = size.width < minimum.width || size.height < minimum.height;
_layout(
root,
Offset.zero &
Size(
math.max(size.width, minimum.width),
math.max(size.height, minimum.height),
),
);
}
final Map<String, Rect> panes = {};
final List<ChatWorkspaceDividerGeometry> dividers = [];
late final bool collapsed;
static Size minimumSize(ChatWorkspaceNode node) {
if (node is ChatWorkspacePane) {
return const Size(chatPaneMinimumWidth, chatPaneMinimumHeight);
}
final split = node as ChatWorkspaceSplit;
final a = minimumSize(split.first), b = minimumSize(split.second);
return split.axis == ChatSplitAxis.horizontal
? Size(
a.width + b.width + chatPaneDividerExtent,
math.max(a.height, b.height),
)
: Size(
math.max(a.width, b.width),
a.height + b.height + chatPaneDividerExtent,
);
}
void _layout(ChatWorkspaceNode node, Rect bounds) {
if (node is ChatWorkspacePane) {
panes[node.id] = bounds;
return;
}
final split = node as ChatWorkspaceSplit;
final horizontal = split.axis == ChatSplitAxis.horizontal;
final a = minimumSize(split.first), b = minimumSize(split.second);
final available =
(horizontal ? bounds.width : bounds.height) - chatPaneDividerExtent;
final low = horizontal ? a.width : a.height;
final high = available - (horizontal ? b.width : b.height);
final extent = (available * split.ratio)
.clamp(low, math.max(low, high))
.toDouble();
final divider = horizontal
? Rect.fromLTWH(
bounds.left + extent,
bounds.top,
chatPaneDividerExtent,
bounds.height,
)
: Rect.fromLTWH(
bounds.left,
bounds.top + extent,
bounds.width,
chatPaneDividerExtent,
);
dividers.add(
ChatWorkspaceDividerGeometry(
split,
divider,
bounds,
low / available,
high / available,
),
);
_layout(
split.first,
horizontal
? Rect.fromLTWH(bounds.left, bounds.top, extent, bounds.height)
: Rect.fromLTWH(bounds.left, bounds.top, bounds.width, extent),
);
_layout(
split.second,
horizontal
? Rect.fromLTWH(
divider.right,
bounds.top,
available - extent,
bounds.height,
)
: Rect.fromLTWH(
bounds.left,
divider.bottom,
bounds.width,
available - extent,
),
);
}
String? neighbor(String active, ChatPaneDirection direction) {
final origin = panes[active];
if (origin == null) return null;
final horizontal =
direction == ChatPaneDirection.left ||
direction == ChatPaneDirection.right;
String? best;
var score = double.infinity;
for (final entry in panes.entries) {
if (entry.key == active) continue;
final candidate = entry.value;
final inDirection = switch (direction) {
ChatPaneDirection.left => candidate.right <= origin.left,
ChatPaneDirection.right => candidate.left >= origin.right,
ChatPaneDirection.up => candidate.bottom <= origin.top,
ChatPaneDirection.down => candidate.top >= origin.bottom,
};
if (!inDirection) continue;
final delta = candidate.center - origin.center;
final primary = horizontal ? delta.dx.abs() : delta.dy.abs();
final secondary = horizontal ? delta.dy.abs() : delta.dx.abs();
final next = primary + secondary * 2;
if (next < score) {
score = next;
best = entry.key;
}
}
return best;
}
}