import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import '../../../ui/floating/floating_layer.dart'; import '../../../ui/motion/motion.dart'; import '../../../ui/motion/surface_visibility.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 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 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.frames, 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 ChatFloatFrames frames; final bool enabled; final String Function(ChatWorkspacePane pane) title; final Widget Function(ChatWorkspacePane pane) content; /// 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. final ChatWorkspacePane? Function() focusedPane; final ValueChanged? onFocusPane; final Widget child; @override State createState() => _ChatFloatHostState(); } class _ChatFloatHostState extends State { bool _visible = false; Set _paneIds = const {}; FocusNode? _previous; @override void initState() { super.initState(); FocusManager.instance.addEarlyKeyEventHandler(_key); widget.controller.addListener(_sync); 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); super.dispose(); } void _sync() { if (!mounted) return; 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; } else if (visible != _visible) { if (visible) { _remember(); _focusSoon(panes.last); } else { _release(); } } 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); } _paneIds = ids; if (visible != _visible) setState(() => _visible = visible); } 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; 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.isFloating(pane.id)) return; final focus = widget.onFocusPane; if (focus != null) { focus(pane); } else { widget.scope(pane)?.requestFocus(); } }) ..ensureVisualUpdate(); } /// 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 current = FocusManager.instance.primaryFocus; if (current == null || !_inside(current)) return; if (previous != null && previous.context != null && previous.canRequestFocus) { previous.requestFocus(); } else { current.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 || !widget.enabled || !chatFloatShortcut(event, HardwareKeyboard.instance)) { return KeyEventResult.ignored; } final controller = widget.controller; if (controller.floatingPanes.isEmpty) { 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 panes = widget.controller.floatingPanes; final cupertino = chatControlsStyleOf(context) == ChatControlsStyle.cupertino; return Stack( fit: StackFit.expand, children: [ widget.child, 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: 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(pane), cupertino: cupertino, onDock: () => widget.controller.dock(pane.id), onHide: () => widget.controller.setFloatShown(false), child: widget.content(pane), ), ), ], ), ), ], ); } } /// 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: SurfaceVisibility( shown: !offstage, current: !offstage, child: widget.child, ), ), ); }, ); }