diff --git a/app/lib/features/chat/workspace/chat_pane_switch_motion.dart b/app/lib/features/chat/workspace/chat_pane_switch_motion.dart index 96efe020..1b73033e 100644 --- a/app/lib/features/chat/workspace/chat_pane_switch_motion.dart +++ b/app/lib/features/chat/workspace/chat_pane_switch_motion.dart @@ -3,52 +3,92 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import '../../../ui/motion/quick_switch_animation.dart'; import '../../../ui/motion/quick_switch_effect.dart'; +import 'chat_switch_ease.dart'; + +part 'chat_pane_switch_start.dart'; /// A vertical tape or a live card exchange, selected once for each transition. /// Tape uses an outgoing picture; swaps move the retained chats themselves. /// Every live transcript exists once and keeps its real visible viewport. +/// +/// A switch requested while another is moving starts at once from what is on +/// screen: swaps take each card's current rectangle, pose, opacity and bar as +/// their start; the tape takes a fresh picture of the current frame above the +/// incoming chat. The incoming chat keeps its speed, then brakes once. class ChatPaneSwitchMotion { ChatPaneSwitchMotion({required TickerProvider vsync}) : _controller = AnimationController( vsync: vsync, duration: duration, value: 1, - ); + ) { + _controller.addStatusListener(_settled); + } static const Duration duration = Duration(milliseconds: 440); - static const Curve curve = _TapeEase(); + static const Curve curve = ChatSwitchEase(); final AnimationController _controller; Animation get animation => _controller.view; final Map> _reveals = {}; + Curve _curve = curve; Map _from = const {}; Map _to = const {}; Map _barFrom = const {}; Map _barTo = const {}; + Map _opacityFrom = const {}; + Map _opacityTo = const {}; + + /// Interrupted cards' departure from the new path, decaying to nothing. + Map _residual = const {}; + Map _carried = const {}; + Map _viewports = const {}; + + /// Retained cards leaving the screen besides the previous active chat. + Set _leaving = const {}; Size? _size; String? _activeId; String? _outgoingId; String? _enteringPeekId; + + /// The tape's picture region: everything above the incoming chat. Rect? outgoingSourceRect; QuickSwitchAnimation _style = QuickSwitchAnimation.tape; QuickSwitchAnimation get style => _style; bool get isTape => _style == QuickSwitchAnimation.tape; double get progress => _progress; bool get outgoingOnTop => quickSwitchOutgoingOnTop(_style, _progress); - bool isRetainedOutgoing(String id) => - isAnimating && !isTape && id == _outgoingId; + bool _retained(String id) => + !isTape && (id == _outgoingId || _leaving.contains(id)); + bool isRetainedOutgoing(String id) => isAnimating && _retained(id); String? get topPaneId => outgoingOnTop ? _outgoingId : _activeId; - double opacityFor(String id) => - isAnimating && !isTape && id == _enteringPeekId && id != _outgoingId - ? _progress - : 1; + double opacityFor(String id) { + if (!isAnimating || isTape) return 1; + final to = _opacityTo[id] ?? 1; + // The chosen chat turns opaque, and cards leaving fade, within the first + // third: interrupted exchanges never stack several translucent cards. + // The arriving peek fades in under the moving cards across the whole run. + final early = id == _activeId || to == 0; + final t = early ? (_progress * 3).clamp(0.0, 1.0) : _progress; + return lerpDouble(_opacityFrom[id] ?? 1, to, t)!; + } + bool get isAnimating => _controller.isAnimating; - double get _progress => curve.transform(_controller.value); + double get _progress => _curve.transform(_controller.value); Animation revealFor(String id) => _reveals.putIfAbsent(id, () => _PaneReveal(this, id)); double _reveal(String id) => lerpDouble(_barFrom[id] ?? 1, _barTo[id] ?? 1, _progress)!; + /// The card's paint-only pose, including any pose it carried into this + /// transition from an interrupted one. + QuickSwitchPose poseFor(String id, {required bool outgoing}) { + if (!isAnimating) return const QuickSwitchPose(); + final pose = quickSwitchPose(_style, _progress, outgoing: outgoing); + final carried = _carried[id]; + return carried == null ? pose : pose.carry(carried, 1 - _progress); + } + void layout({ required Map rects, required Size size, @@ -66,25 +106,13 @@ class ChatPaneSwitchMotion { _activeId != activeId; _size = size; if (travel) { - _style = style; - _outgoingId = _activeId; - outgoingSourceRect = _to[_outgoingId]; - _enteringPeekId = rects.keys.firstWhere((id) => id != activeId); - final peek = rects[_enteringPeekId]!; - _from = {..._to, activeId: _to[activeId] ?? peek}; - _to = rects; - _barFrom = { - for (final id in {...rects.keys, _outgoingId!}) - id: !isTape && id == _outgoingId ? 1 : 0, - }; - _barTo = {for (final id in rects.keys) id: id == activeId ? 1 : 0}; - _activeId = activeId; - _controller.forward(from: 0); + _start(rects, size, activeId, style); } else if (!mapEquals(rects, _to) || !animate) { _from = _to = rects; _activeId = activeId; - _outgoingId = _enteringPeekId = null; + _enteringPeekId = _outgoingId = null; outgoingSourceRect = null; + _clearTransition(); _barFrom = _barTo = { for (final id in rects.keys) id: id == activeId ? 1 : 0, }; @@ -92,60 +120,89 @@ class ChatPaneSwitchMotion { } } + void _clearTransition() { + _curve = curve; + _leaving = const {}; + _residual = const {}; + _carried = const {}; + _viewports = const {}; + _opacityFrom = _opacityTo = const {}; + } + + void _settled(AnimationStatus status) { + if (status != AnimationStatus.completed) return; + _outgoingId = null; + _leaving = const {}; + _residual = const {}; + _carried = const {}; + } + void rest() { if (_to.isEmpty && _size == null) return; _from = _to = const {}; _barFrom = _barTo = const {}; _size = null; _activeId = _outgoingId = _enteringPeekId = null; + _clearTransition(); outgoingSourceRect = null; _controller.value = 1; } - /// Stable content constraints for paint-only movement during a switch. - /// The outgoing card keeps its source viewport; incoming/preview cards use - /// their destination viewport. At rest this is the actual visible rectangle. - Rect? viewportRectFor(String id) => - isRetainedOutgoing(id) ? outgoingSourceRect : _to[id] ?? rectFor(id); + /// Stable content size for paint-only movement during a swap. At rest this + /// is the actual visible rectangle. + Size? viewportFor(String id) => + (isAnimating ? _viewports[id] : null) ?? + _to[id]?.size ?? + rectFor(id)?.size; - Rect? rectFor(String id) { + Rect? rectFor(String id) => _rectAt(id, _progress); + + Rect? _rectAt(String id, double p) { final to = _to[id]; - if (isRetainedOutgoing(id)) return exitingRect; - if (to == null) return null; - if (isTape && _enteringPeekId == id && outgoingSourceRect != null) { - // The next pane in the ring enters from below with a true small - // viewport. With two panes this is the outgoing chat; with more it is - // the next added pane. The old active owns only the snapshot top exit. + Rect rect; + if (_retained(id)) { + final from = _from[id]; + if (from == null) return null; + final target = to ?? _to[_enteringPeekId] ?? from; + rect = quickSwitchRect(_style, p, from, target, outgoing: true); + } else if (to == null) { + return null; + } else if (isTape && _enteringPeekId == id && outgoingSourceRect != null) { + // The next pane in the ring follows the incoming chat up from below + // with a true small viewport. With two panes this is the outgoing chat; + // with more it is the next added pane. The old active owns only the + // picture's top exit. + final lead = _rectAt(_activeId!, p)!; final gap = to.top - _to[_activeId]!.bottom; - return to.translate(0, (_size!.height + gap - to.top) * (1 - _progress)); + rect = to.translate(0, lead.bottom + gap - to.top); + } else { + rect = quickSwitchRect(_style, p, _from[id] ?? to, to, outgoing: false); } - return quickSwitchRect( - _style, - _progress, - _from[id] ?? to, - to, - outgoing: false, + final residual = _residual[id]; + if (residual == null) return rect; + final w = 1 - p; + return Rect.fromLTRB( + rect.left + residual.left * w, + rect.top + residual.top * w, + rect.right + residual.right * w, + rect.bottom + residual.bottom * w, ); } + /// The tape's picture, moving up ahead of the incoming chat. Rect? get exitingRect { final source = outgoingSourceRect; final incoming = _from[_activeId]; - if (!isAnimating || source == null || incoming == null) return null; - if (isTape) return source.translate(0, -incoming.top * _progress); - final target = _to[_enteringPeekId] ?? source; - return quickSwitchRect(_style, _progress, source, target, outgoing: true); + if (!isAnimating || !isTape || source == null || incoming == null) { + return null; + } + return source.translate(0, -incoming.top * _progress); } - void dispose() => _controller.dispose(); -} - -/// Quintic easing has zero velocity and acceleration at both ends: the tape -/// picks up speed gradually and brakes without a sudden snap near the finish. -class _TapeEase extends Curve { - const _TapeEase(); - @override - double transformInternal(double t) => t * t * t * (t * (6 * t - 15) + 10); + void dispose() { + _controller.removeStatusListener(_settled); + _controller.dispose(); + } } class _PaneReveal extends Animation { diff --git a/app/lib/features/chat/workspace/chat_pane_switch_start.dart b/app/lib/features/chat/workspace/chat_pane_switch_start.dart new file mode 100644 index 00000000..3ce17e6c --- /dev/null +++ b/app/lib/features/chat/workspace/chat_pane_switch_start.dart @@ -0,0 +1,140 @@ +part of 'chat_pane_switch_motion.dart'; + +/// Starting a switch, from rest or from wherever an interrupted one has +/// brought the cards. +extension _SwitchStart on ChatPaneSwitchMotion { + void _start( + Map rects, + Size size, + String activeId, + QuickSwitchAnimation style, + ) { + // What is on screen now: the resting layout, or an interrupted switch. + final p = _progress; + final interrupted = isAnimating; + final presented = { + ..._to.keys, + if (interrupted) ...{..._leaving, ?_outgoingId}.where(_retained), + }; + final rectNow = {for (final id in presented) id: ?_rectAt(id, p)}; + final opacityNow = {for (final id in presented) id: opacityFor(id)}; + final revealNow = {for (final id in presented) id: _reveal(id)}; + final poseNow = { + for (final id in presented) + id: poseFor(id, outgoing: isRetainedOutgoing(id)), + }; + final viewportNow = { + for (final id in presented) + id: ?(interrupted ? _viewports[id] : null) ?? _to[id]?.size, + }; + final speed = interrupted ? _speed(activeId) : null; + + final previous = _activeId!; + _style = style; + _outgoingId = previous; + _activeId = activeId; + _enteringPeekId = rects.keys.firstWhere((id) => id != activeId); + final peek = rects[_enteringPeekId]!; + _to = rects; + _clearTransition(); + if (isTape) { + // The picture shows the current frame above the incoming chat; its live + // tree continues from where it is (or the peek's place if unseen). + final lead = rectNow[activeId] ?? peek; + final gap = peek.top - rects[activeId]!.bottom; + _from = {activeId: lead}; + outgoingSourceRect = Rect.fromLTRB( + 0, + 0, + size.width, + (lead.top - gap).clamp(0.0, size.height), + ); + _barFrom = { + for (final id in {...rects.keys, previous}) id: 0, + }; + _barTo = {for (final id in rects.keys) id: id == activeId ? 1 : 0}; + } else { + _leaving = { + for (final id in presented) + if (!rects.containsKey(id) && id != previous) id, + }; + final moving = {...rects.keys, previous, ..._leaving}; + _from = { + for (final id in moving) + id: rectNow[id] ?? (id == activeId ? peek : rects[id]!), + }; + outgoingSourceRect = _from[previous]; + _opacityFrom = { + for (final id in moving) + id: presented.contains(id) ? opacityNow[id]! : 0, + }; + _opacityTo = { + for (final id in moving) + id: rects.containsKey(id) || id == previous ? 1 : 0, + }; + _barFrom = {for (final id in moving) id: revealNow[id] ?? 0}; + _barTo = { + for (final id in moving) + id: rects.containsKey(id) + ? (id == activeId ? 1 : 0) + : revealNow[id] ?? 0, + }; + // Growing cards lay out at their destination; shrinking ones keep the + // viewport they have until they settle into the small preview. + _viewports = { + for (final id in moving) + id: + _SwitchStart._tallerOf(viewportNow[id], rects[id]?.size) ?? + _from[id]!.size, + }; + _carried = { + for (final MapEntry(key: id, value: pose) in poseNow.entries) + if (!pose.isRest) id: pose, + }; + // A fresh switch starts on its style's own path (a deck's next card + // already waits full-size behind the front one); an interrupted one + // eases each card from where it is onto the new path. + _residual = { + if (interrupted) + for (final id in moving) + if ((rectNow[id], _rectAt(id, 0)) case ( + final now?, + final start?, + ) when now != start) + id: Rect.fromLTRB( + now.left - start.left, + now.top - start.top, + now.right - start.right, + now.bottom - start.bottom, + ), + }; + } + if (speed != null) _curve = _launch(activeId, speed); + _controller.forward(from: 0); + } + + /// The incoming chat's current edge velocities, per unit of the clock. + (double, double)? _speed(String id) { + const dt = 1 / 120; + final t = _controller.value.clamp(0.0, 1 - dt); + final a = _rectAt(id, _curve.transform(t)); + final b = _rectAt(id, _curve.transform(t + dt)); + if (a == null || b == null) return null; + return ((b.top - a.top) / dt, (b.bottom - a.bottom) / dt); + } + + /// An ease whose starting slope keeps [speed] along the new path; zero when + /// the chat reverses, so a reversal starts from rest. + Curve _launch(String id, (double, double) speed) { + final start = _rectAt(id, 0), end = _rectAt(id, 1); + if (start == null || end == null) return ChatPaneSwitchMotion.curve; + final dTop = end.top - start.top, dBottom = end.bottom - start.bottom; + final length = dTop * dTop + dBottom * dBottom; + if (length < 1) return ChatPaneSwitchMotion.curve; + final slope = (speed.$1 * dTop + speed.$2 * dBottom) / length; + return slope > .01 ? ChatSwitchEase(slope) : ChatPaneSwitchMotion.curve; + } + + static Size? _tallerOf(Size? a, Size? b) => + a == null || (b != null && b.height > a.height) ? b : a; +} diff --git a/app/lib/features/chat/workspace/chat_switch_card.dart b/app/lib/features/chat/workspace/chat_switch_card.dart index 7d78c5bb..1edfeaf3 100644 --- a/app/lib/features/chat/workspace/chat_switch_card.dart +++ b/app/lib/features/chat/workspace/chat_switch_card.dart @@ -9,19 +9,26 @@ class ChatSwitchCard extends StatelessWidget { super.key, required this.motion, required this.outgoing, + this.paneId, required this.child, }); final ChatPaneSwitchMotion motion; final bool outgoing; + + /// A live pane's id: its pose includes one carried from an interrupted + /// switch. The tape's picture has none. + final String? paneId; final Widget child; @override Widget build(BuildContext context) { - final pose = quickSwitchPose( - motion.style, - motion.isAnimating ? motion.progress : 1, - outgoing: outgoing, - ); + final pose = paneId != null + ? motion.poseFor(paneId!, outgoing: outgoing) + : quickSwitchPose( + motion.style, + motion.isAnimating ? motion.progress : 1, + outgoing: outgoing, + ); final shadow = Theme.of(context).shadowColor; final surface = Theme.of(context).colorScheme.surface; return LayoutBuilder( diff --git a/app/lib/features/chat/workspace/chat_switch_ease.dart b/app/lib/features/chat/workspace/chat_switch_ease.dart new file mode 100644 index 00000000..370ef400 --- /dev/null +++ b/app/lib/features/chat/workspace/chat_switch_ease.dart @@ -0,0 +1,20 @@ +import 'package:flutter/animation.dart'; + +/// The quick switch's quintic ease. It always brakes to a stop with zero +/// velocity and acceleration. A fresh switch also starts from rest; a switch +/// that retargets one already in flight starts at [launch], the slope that +/// keeps the incoming chat moving at its current speed instead of stalling. +/// +/// f(t) = s·t + a·t³ + b·t⁴ + c·t⁵ with f(1) = 1 and f'(1) = f''(1) = 0. +/// Slopes above two would overshoot, so [launch] is clamped to [0, 2]. +class ChatSwitchEase extends Curve { + const ChatSwitchEase([this.launch = 0]); + final double launch; + + @override + double transformInternal(double t) { + final s = launch.clamp(0.0, 2.0); + final a = 10 - 6 * s, b = 8 * s - 15, c = 6 - 3 * s; + return t * (s + t * t * (a + t * (b + c * t))); + } +} diff --git a/app/lib/features/chat/workspace/chat_workspace.dart b/app/lib/features/chat/workspace/chat_workspace.dart index 11e345a4..194754a2 100644 --- a/app/lib/features/chat/workspace/chat_workspace.dart +++ b/app/lib/features/chat/workspace/chat_workspace.dart @@ -270,13 +270,9 @@ class _ChatWorkspaceState extends State }, }; _reportMoveTargets(moveTargets); - // Finish one joined loop before taking the latest requested role. - // Repeated taps/chords never tear the tape or duplicate a live chat. - final activeId = - _motion.isAnimating && - panes.any((pane) => pane.id == _lastActiveId) - ? _lastActiveId - : widget.controller.activePaneId; + // A new request retargets a switch in flight from what is on + // screen (see ChatPaneSwitchMotion); it never waits for the loop. + final activeId = widget.controller.activePaneId; final switching = _lastActiveId != activeId; if (switching) { _lastActiveId = activeId; diff --git a/app/lib/features/chat/workspace/chat_workspace_surface.dart b/app/lib/features/chat/workspace/chat_workspace_surface.dart index 5f63654a..0ae9f06b 100644 --- a/app/lib/features/chat/workspace/chat_workspace_surface.dart +++ b/app/lib/features/chat/workspace/chat_workspace_surface.dart @@ -87,12 +87,11 @@ Widget chatWorkspaceSurface({ ? Offset.zero & size : move.rectFor(pane.id, geometry.panes[pane.id]!)), child: IgnorePointer( - ignoring: - motion.isRetainedOutgoing(pane.id) || - (mobile != null - ? !mobile.rects.containsKey(pane.id) && - !motion.isRetainedOutgoing(pane.id) - : collapsed && pane.id != controller.activePaneId), + // Pointers follow the requested layout, even mid-switch: the + // arriving peek takes the next tap; a card on its way off does not. + ignoring: mobile != null + ? !mobile.rects.containsKey(pane.id) + : collapsed && pane.id != controller.activePaneId, child: Opacity( opacity: mobile != null && @@ -103,6 +102,7 @@ Widget chatWorkspaceSurface({ child: ChatSwitchCard( motion: motion, outgoing: motion.isRetainedOutgoing(pane.id), + paneId: pane.id, child: chatCenterStageLayer( strip: stage.stripFor(pane.id), covered: stage.stage?.strips.contains(pane.id) ?? false, @@ -111,7 +111,7 @@ Widget chatWorkspaceSurface({ : () => stageStrip(pane), view: ChatMotionViewport( size: mobile != null && motion.isAnimating && !motion.isTape - ? motion.viewportRectFor(pane.id)?.size + ? motion.viewportFor(pane.id) : stage.viewportFor(pane.id), child: child!, ), diff --git a/app/lib/ui/motion/quick_switch_effect.dart b/app/lib/ui/motion/quick_switch_effect.dart index be2d338c..46eae2a4 100644 --- a/app/lib/ui/motion/quick_switch_effect.dart +++ b/app/lib/ui/motion/quick_switch_effect.dart @@ -18,6 +18,31 @@ class QuickSwitchPose { final Offset translation; final double scale, rotationX, rotationY, rotationZ, depth, opacity, shadow; + /// This pose plus [weight] of [residual]'s departure from rest. A switch + /// that interrupts another carries the card's current pose and lets it + /// decay, so the card neither snaps flat nor jumps to the new path. + QuickSwitchPose carry(QuickSwitchPose residual, double weight) => + QuickSwitchPose( + translation: translation + residual.translation * weight, + scale: scale * (1 + (residual.scale - 1) * weight), + rotationX: rotationX + residual.rotationX * weight, + rotationY: rotationY + residual.rotationY * weight, + rotationZ: rotationZ + residual.rotationZ * weight, + depth: depth + residual.depth * weight, + opacity: opacity * (1 - (1 - residual.opacity) * weight), + shadow: (shadow + residual.shadow * weight).clamp(0.0, 1.0), + ); + + bool get isRest => + translation == Offset.zero && + scale == 1 && + rotationX == 0 && + rotationY == 0 && + rotationZ == 0 && + depth == 0 && + opacity == 1 && + shadow == 0; + Matrix4 transform(Size size) { // A flat card at constant depth projects to a uniform 2D scale. Keep it // affine so backdrop filters do not enter the renderer's 3D path. diff --git a/app/notes/mobile-tape.md b/app/notes/mobile-tape.md index b87eb18a..15ae085c 100644 --- a/app/notes/mobile-tape.md +++ b/app/notes/mobile-tape.md @@ -4,7 +4,7 @@ Both chats move upward as one joined tape. The old active exits above the incoming live pane as a bounded snapshot; its single retained live tree loops in from below with a real small scroll viewport. This avoids duplicating live chat state. The default is 560 ms, globally scaled by the animation setting. -Repeated activations queue the latest role until the current loop finishes. +Repeated activations retarget the switch in flight (see quick-switch-retarget.md). Reduced motion, first layout, or an unavailable fresh picture settle directly. The crossing-card rounded/shadow effect and its source file are removed. diff --git a/app/notes/quick-switch-retarget.md b/app/notes/quick-switch-retarget.md new file mode 100644 index 00000000..8b608bfe --- /dev/null +++ b/app/notes/quick-switch-retarget.md @@ -0,0 +1,40 @@ +# Quick switch retargets mid-animation + +Operator report: on mobile, a second peek tap did nothing until the first +switch finished. The workspace used to hold the old active pane while the +motion ran and take the latest request afterwards. Now every request (peek +tap, keyboard chord, programmatic `activate`) starts its switch at once, +from what is on screen. + +- Swap family (`chat_pane_switch_start.dart`): each card's `from` is its + current rect; its current opacity, bar reveal and paint pose carry into the + new run and decay (`QuickSwitchPose.carry`, rect residual for paths such as + a deck's that do not start where the card is). Retained cards that are + neither requested nor the previous active fade out within the first third + and never take pointers; the newly active chat turns opaque in that third. + Shrinking cards keep their viewport until they settle; growing ones lay + out at their destination. A fresh switch is unchanged. +- Tape: a fresh picture of the current frame (everything above the incoming + chat) replaces the old one and keeps moving up; the incoming live chat + continues from where it is, the next peek follows joined below it. An + unseen target starts at the peek's place. A failed capture settles at once. +- The incoming chat keeps its current speed (`ChatSwitchEase` launch slope, + clamped to avoid overshoot) and brakes once; a reversal starts from rest. +- Pointers follow the requested layout: the arriving peek is tappable while + it moves; cards on their way off ignore pointers. Reduced motion settles + each request directly, as before. + +Checks: `chat_switch_retarget_test.dart` (five rapid peek taps for tape, swap, +arc swap, card deck, crossfade over four chats; programmatic reversal for +tape, swap, deck slide; reduced motion; ease); tape test in +`chat_mobile_panes_test.dart` now asserts the reversal retarget. Suites +`test/features/chat/` 1448, `test/application/` 193, `test/ui/motion` 30 pass; +analyze clean. + +Browser films (capture kit `taps` option, 560x1000, four fixture chats, +five taps ~180 ms apart at the peek): `/tmp/review/retarget/v2-tape`, +`v2-swap`, `v3-cardStack`, `v3-arcSwap` (sheets `02-rapid-*-sheet.png`). +Headless input is delivered late and unevenly, so not every tap lands on the +arriving peek; each landed tap visibly started a new switch mid-motion and +the runs settled to one active chat and one peek. Browser evidence only; no +device run. diff --git a/app/test/features/chat/workspace/chat_mobile_panes_test.dart b/app/test/features/chat/workspace/chat_mobile_panes_test.dart index fc713160..57d0b6c0 100644 --- a/app/test/features/chat/workspace/chat_mobile_panes_test.dart +++ b/app/test/features/chat/workspace/chat_mobile_panes_test.dart @@ -138,7 +138,7 @@ void main() { } testWidgets( - 'tape exits above incoming, wraps below, queues reversal and retains drafts', + 'tape exits above incoming, wraps below, retargets reversal and retains drafts', (tester) async { phone(tester); final controller = ChatWorkspaceController()..open('a'); @@ -176,10 +176,19 @@ void main() { tester.getSize(find.byKey(const ValueKey('a'))).height, closeTo(incoming.height, .5), ); + // Reversing mid-loop starts at once: the arriving chat keeps its place + // and a fresh picture of the frame above it continues the exit. controller.activate(b); await tester.pump(); - expect(tester.getRect(rect(a)), incoming); - expect(tester.getRect(rect(b)), wrapped); + expect(tester.getRect(rect(b)).top, closeTo(wrapped.top, .5)); + final picture = tester.getRect( + find.byKey(const ValueKey('chat-tape-exit')), + ); + expect(picture.top, closeTo(0, .5)); + expect(picture.bottom + 6, closeTo(wrapped.top, .5)); + expect(tester.getRect(rect(a)).top, greaterThanOrEqualTo(800)); + await tester.pump(ChatPaneSwitchMotion.duration ~/ 8); + expect(tester.getRect(rect(b)).top, lessThan(wrapped.top - 1)); await tester.pumpAndSettle(); expect(tester.getRect(rect(a)).top, _peekTop); expect(tester.getRect(rect(b)).top, 0); diff --git a/app/test/features/chat/workspace/chat_switch_retarget_test.dart b/app/test/features/chat/workspace/chat_switch_retarget_test.dart new file mode 100644 index 00000000..40dbc5cf --- /dev/null +++ b/app/test/features/chat/workspace/chat_switch_retarget_test.dart @@ -0,0 +1,330 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_pane_switch_motion.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_switch_card.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_switch_ease.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; +import 'package:pipelines_app/ui/motion/quick_switch_animation.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +Widget _host(ChatWorkspaceController controller, {bool reduced = false}) => + MaterialApp( + home: MediaQuery( + data: MediaQueryData(disableAnimations: reduced), + child: ChatWorkspace( + controller: controller, + singlePane: true, + mobilePeeks: true, + paneBuilder: (_, pane, active) => + _Draft(key: ValueKey(pane.sessionId)), + ), + ), + ); + +class _Draft extends StatefulWidget { + const _Draft({super.key}); + @override + State<_Draft> createState() => _DraftState(); +} + +class _DraftState extends State<_Draft> { + final controller = TextEditingController(); + @override + void dispose() { + controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => + Material(child: TextField(controller: controller)); +} + +const _peekTop = (800 - 6) * .8 + 6; +const _step = Duration(milliseconds: 16); +Finder _rect(String pane) => find.byKey(ValueKey('chat-workspace-$pane')); + +void main() { + void phone(WidgetTester tester) { + tester.view.physicalSize = const Size(560, 800); + tester.view.devicePixelRatio = 1; + tester.platformDispatcher.accessibilityFeaturesTestValue = + const FakeAccessibilityFeatures(disableAnimations: false); + addTearDown(tester.platformDispatcher.clearAccessibilityFeaturesTestValue); + addTearDown(tester.view.reset); + } + + Future open( + WidgetTester tester, + QuickSwitchAnimation style, + List ids, + ) async { + phone(tester); + SharedPreferences.setMockInitialValues({}); + await QuickSwitchAnimationController.instance.setAnimation(style); + addTearDown( + () => QuickSwitchAnimationController.instance.setAnimation( + QuickSwitchAnimation.tape, + ), + ); + final controller = ChatWorkspaceController()..open(ids.first); + for (final id in ids.skip(1)) { + controller.splitActive(id, ChatSplitAxis.horizontal); + } + controller.activate(controller.panes.first.id); + await tester.pumpWidget(_host(controller)); + await tester.pumpAndSettle(); + return controller; + } + + String paneOf(ChatWorkspaceController controller, String session) => + controller.panes.firstWhere((p) => p.sessionId == session).id; + + bool ignoring(WidgetTester tester, String pane) => tester + .widget( + find + .descendant(of: _rect(pane), matching: find.byType(IgnorePointer)) + .first, + ) + .ignoring; + + /// A point where the card is uncovered on screen now, through its + /// paint-only pose: where a person would tap the arriving peek. + Offset? uncovered(WidgetTester tester, String pane) { + final card = find.byWidgetPredicate( + (w) => w is ChatSwitchCard && w.paneId == pane, + ); + final box = tester.renderObject( + find.descendant(of: card, matching: find.byType(DecoratedBox)).first, + ); + for (var y = box.size.height - 4; y > 0; y -= 4) { + for (final x in [.5, .25, .75]) { + final point = box.localToGlobal(Offset(box.size.width * x, y)); + if (point.dy < 0 || point.dy >= 800 || point.dx < 0) continue; + if (point.dx >= 560) continue; + final hits = tester.hitTestOnBinding(point).path; + if (hits.any((entry) => entry.target == box)) return point; + } + } + return null; + } + + Map presented(WidgetTester tester, Iterable panes) => { + for (final pane in panes) + if (tester + .widget( + find + .descendant(of: _rect(pane), matching: find.byType(Offstage)) + .first, + ) + .offstage + .isFalse) + pane: tester.getRect(_rect(pane)), + }; + + Future expectSettled( + WidgetTester tester, + ChatWorkspaceController controller, + Map drafts, + ) async { + await tester.pumpAndSettle(); + final active = controller.activePaneId!; + expect(tester.getRect(_rect(active)).top, 0); + final visible = presented(tester, controller.panes.map((p) => p.id)); + expect(visible.length, 2, reason: 'one active chat and one peek'); + final peek = visible.keys.firstWhere((id) => id != active); + expect(visible[peek]!.top, closeTo(_peekTop, .01)); + expect(ignoring(tester, active), isFalse); + expect(ignoring(tester, peek), isFalse); + for (final pane in controller.panes) { + // Every chat is one retained live tree, never a second copy. + expect( + find.byKey(ValueKey(pane.sessionId), skipOffstage: false), + findsOneWidget, + ); + final state = drafts[pane.sessionId]!; + expect( + tester.state(find.byKey(ValueKey(pane.sessionId), skipOffstage: false)), + same(state), + ); + expect(state.controller.text, 'Draft ${pane.sessionId}'); + } + expect(find.byKey(const ValueKey('chat-tape-exit')), findsNothing); + } + + for (final style in [ + QuickSwitchAnimation.tape, + QuickSwitchAnimation.swap, + QuickSwitchAnimation.arcSwap, + QuickSwitchAnimation.cardStack, + QuickSwitchAnimation.fade, + ]) { + testWidgets('${style.name}: rapid peek taps retarget without waiting', ( + tester, + ) async { + final controller = await open(tester, style, ['a', 'b', 'c', 'd']); + final drafts = { + for (final id in ['a', 'b', 'c', 'd']) + id: tester.state<_DraftState>( + find.byKey(ValueKey(id), skipOffstage: false), + )..controller.text = 'Draft $id', + }; + final ids = [for (final pane in controller.panes) pane.id]; + // Five taps, each on the peek arriving from the previous one. + for (var tap = 0; tap < 5; tap++) { + final target = ids[(ids.indexOf(controller.activePaneId!) + 1) % 4]; + final animating = tap > 0; + if (animating) { + // The arriving peek takes pointers while it is still moving. + expect(ignoring(tester, target), isFalse); + } + // A deck card may still be sliding back from aside: tap as soon as + // any of it shows. + var point = uncovered(tester, target); + for (var wait = 0; point == null && wait < 30; wait++) { + await tester.pump(_step); + point = uncovered(tester, target); + } + if (point == null) fail('$target never showed'); + final before = presented(tester, ids); + await tester.tapAt(point); + expect(controller.activePaneId, target, reason: 'tap ${tap + 1}'); + await tester.pump(); + final now = presented(tester, ids); + if (animating) { + // Motion continues from where the cards are: no jump. + final continuing = style == QuickSwitchAnimation.tape + ? [target] + : before.keys.where(now.containsKey); + for (final pane in continuing) { + expect(now[pane]!.top, closeTo(before[pane]!.top, 1), reason: pane); + expect( + now[pane]!.height, + closeTo(before[pane]!.height, 1), + reason: pane, + ); + } + if (style == QuickSwitchAnimation.tape) { + final picture = tester.getRect( + find.byKey(const ValueKey('chat-tape-exit')), + ); + expect(picture.top, closeTo(0, .5)); + expect(picture.bottom + 6, closeTo(now[target]!.top, 1)); + } + } + // The new switch starts at once: the chosen chat already rises (or, + // on a fresh deck, already waits full-size behind the front card). + await tester.pump(_step * 2); + if (now[target]!.top > 0) { + expect( + tester.getRect(_rect(target)).top, + lessThan(now[target]!.top - .5), + ); + } + // Every pane on screen is the requested pair or a card on its way + // off, which never takes a pointer. + for (final pane in presented(tester, ids).keys) { + final requested = + pane == target || + pane == ids[(ids.indexOf(target) + 1) % ids.length]; + expect(ignoring(tester, pane), !requested, reason: pane); + } + await tester.pump(ChatPaneSwitchMotion.duration * .4); + } + expect(controller.activePaneId, ids[(0 + 5) % 4]); + await expectSettled(tester, controller, drafts); + // Settled pointers are valid: the peek opens with one more tap. + final peek = ids[(ids.indexOf(controller.activePaneId!) + 1) % 4]; + await tester.tap(find.byKey(ValueKey('chat-peek-$peek'))); + await tester.pumpAndSettle(); + expect(controller.activePaneId, peek); + await tester.pumpWidget(const SizedBox()); + controller.dispose(); + }); + } + + for (final style in [ + QuickSwitchAnimation.tape, + QuickSwitchAnimation.swap, + QuickSwitchAnimation.deckSlide, + ]) { + testWidgets('${style.name}: a programmatic reversal starts immediately', ( + tester, + ) async { + final controller = await open(tester, style, ['a', 'b']); + final drafts = { + for (final id in ['a', 'b']) + id: tester.state<_DraftState>(find.byKey(ValueKey(id))) + ..controller.text = 'Draft $id', + }; + final a = paneOf(controller, 'a'), b = paneOf(controller, 'b'); + controller.activate(b); + await tester.pump(); + await tester.pump(ChatPaneSwitchMotion.duration * .3); + final before = presented(tester, [a, b]); + controller.activate(a); + await tester.pump(); + final now = presented(tester, [a, b]); + if (style == QuickSwitchAnimation.tape) { + // a's live tree was arriving from below as the next peek. + expect(now[a]!.top, closeTo(before[a]!.top, 1)); + } else { + for (final pane in [a, b]) { + expect(now[pane]!.top, closeTo(before[pane]!.top, 1)); + } + } + await tester.pump(ChatPaneSwitchMotion.duration * .1); + // A deck's incoming card already waits full-size behind the front one. + if (now[a]!.top > 0) { + expect(tester.getRect(_rect(a)).top, lessThan(now[a]!.top)); + } + await expectSettled(tester, controller, drafts); + expect(controller.activePaneId, a); + await tester.pumpWidget(const SizedBox()); + controller.dispose(); + }); + } + + testWidgets('reduced motion still settles each request at once', ( + tester, + ) async { + final controller = await open(tester, QuickSwitchAnimation.tape, [ + 'a', + 'b', + 'c', + ]); + await tester.pumpWidget(_host(controller, reduced: true)); + for (final session in ['b', 'c', 'a']) { + controller.activate(paneOf(controller, session)); + await tester.pump(); + expect(tester.getRect(_rect(controller.activePaneId!)).top, 0); + expect(find.byKey(const ValueKey('chat-tape-exit')), findsNothing); + } + await tester.pumpWidget(const SizedBox()); + controller.dispose(); + }); + + test('the retarget ease launches at its slope and brakes to rest', () { + for (final slope in [0.0, .8, 2.0]) { + final ease = ChatSwitchEase(slope); + expect(ease.transform(0), 0); + expect(ease.transform(1), 1); + expect(ease.transform(1e-4) / 1e-4, closeTo(slope, 1e-2)); + var last = 0.0; + for (var i = 1; i <= 100; i++) { + final value = ease.transform(i / 100); + expect(value, greaterThanOrEqualTo(last)); + expect(value, lessThanOrEqualTo(1)); + last = value; + } + } + expect( + const ChatSwitchEase().transform(.3), + ChatPaneSwitchMotion.curve.transform(.3), + ); + }); +} + +extension on bool { + bool get isFalse => !this; +} diff --git a/app/tool/capture/README.md b/app/tool/capture/README.md index d547866b..aa44c898 100644 --- a/app/tool/capture/README.md +++ b/app/tool/capture/README.md @@ -133,6 +133,8 @@ node tool/capture/capture.mjs --build build/probe-app --out /tmp/review/film \ In a JSON script, `{ "film": "Pipelines", "name": "tab-switch", "ms": 900, "frames": 6 }` sets the name, the duration and how many frames go on the sheet. +`"taps": [{ "after": 180, "target": "280,960" }]` adds taps while the film runs, +each `after` ms from the first and located when due (rapid-switch reviews). Find targets: run `labels=now` after any step and read `NN-now.json`. diff --git a/app/tool/capture/capture.mjs b/app/tool/capture/capture.mjs index 37a615bd..4f2451df 100644 --- a/app/tool/capture/capture.mjs +++ b/app/tool/capture/capture.mjs @@ -187,7 +187,7 @@ try { case 'film': { const what = String(value).startsWith('press:') ? String(value) : describe(parseTarget(value)); const name = step.name ?? `film-${what.replace(/\W+/g, '-').replace(/^-|-$/g, '')}`; - const frames = await page.film(value, Number(step.ms ?? opts['film-ms'])); + const frames = await page.film(value, Number(step.ms ?? opts['film-ms']), step.taps ?? []); const dir = join(out, name.replace(/[^\w.-]+/g, '_')); await mkdir(dir, { recursive: true }); for (const [i, f] of frames.entries()) { diff --git a/app/tool/capture/page.mjs b/app/tool/capture/page.mjs index beed4d6d..54f65873 100644 --- a/app/tool/capture/page.mjs +++ b/app/tool/capture/page.mjs @@ -224,7 +224,7 @@ export function flutterPage(browser, log, { touch = false, semantics = true, use pinch: async (target, scale) => pinch(send, await locate(target), scale), evaluate, /** Screencasts [ms] after clicking [target]; frames are `{ data, ms }` relative to the click. */ - async film(target, ms) { + async film(target, ms, taps = []) { // Contact sheets use a scratch tab. Restore this target's compositor // viewport before another screencast, otherwise Chrome can crop frames. await send('Page.bringToFront'); @@ -243,7 +243,13 @@ export function flutterPage(browser, log, { touch = false, semantics = true, use const clickAt = Date.now() / 1000; if (chord) await this.press(chord); else await tap(point); - await delay(ms); + // Further taps while the first transition runs, each `after` ms from + // the first and located when due (rapid-switch reviews). + for (const next of taps) { + await delay(Math.max(0, clickAt * 1000 + Number(next.after) - Date.now())); + await tap(await locate(next.target)); + } + await delay(Math.max(0, clickAt * 1000 + ms - Date.now())); await send('Page.stopScreencast'); await delay(100); off();