diff --git a/app/lib/features/chat/conversation/chat_thread_header.dart b/app/lib/features/chat/conversation/chat_thread_header.dart index a8c756f8..a568b076 100644 --- a/app/lib/features/chat/conversation/chat_thread_header.dart +++ b/app/lib/features/chat/conversation/chat_thread_header.dart @@ -34,7 +34,6 @@ class ChatThreadHeader extends StatelessWidget { this.moreActions = const [], this.chatColor, this.identity, - this.identityHeroTag, }); final String title; @@ -55,9 +54,8 @@ class ChatThreadHeader extends StatelessWidget { /// The chat's colour name, or null for none. final String? chatColor; - /// The chat identity carried from the mobile session row into this header. + /// The chat's identity avatar, shown in the title on a phone. final Widget? identity; - final String? identityHeroTag; @override Widget build(BuildContext context) { @@ -68,12 +66,6 @@ class ChatThreadHeader extends StatelessWidget { builder: (context, constraints) { final textScale = MediaQuery.textScalerOf(context).scale(14) / 14; final compact = constraints.maxWidth / textScale < 800; - final heroIdentity = - identity == null || - identityHeroTag == null || - (MediaQuery.maybeDisableAnimationsOf(context) ?? false) - ? identity - : Hero(tag: identityHeroTag!, child: identity!); final Widget bar = SegmentedBar( cupertino: cupertino, pillColor: tint?.fill, @@ -89,7 +81,7 @@ class ChatThreadHeader extends StatelessWidget { ) : null, title: title.isEmpty ? 'Chat' : title, - titleLeading: heroIdentity, + titleLeading: identity, subtitle: ServerContext.metadata(context, folder), subtitleIcon: cupertino ? CupertinoIcons.folder diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index d4527e33..b8b00508 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -1393,13 +1393,6 @@ class _ChatThreadViewState extends State { MediaQuery.sizeOf(context).width >= kListDetailMinWidth ? null : ChatSessionAvatar(session: session, selected: true), - identityHeroTag: - widget.useNativeBack && - session != null && - MediaQuery.sizeOf(context).width < kListDetailMinWidth && - !(MediaQuery.maybeDisableAnimationsOf(context) ?? false) - ? 'chat-identity-${widget.sessionId}' - : null, onInfo: _openInfo, showBack: canGoBack, // A pushed page keeps the platform's stock Back (pop this route); a diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index e82099c2..6d8dcbbb 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -10,6 +10,7 @@ import '../../shell/empty_detail_pane.dart'; import '../../shell/list_detail.dart'; import 'dart:async'; import '../../ui/motion/motion.dart'; +import '../../ui/motion/container_transform_source.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart' show setEquals; @@ -415,6 +416,13 @@ class _ChatScreenState extends State /// On a phone the open chat is a real page above the main screen. final DetailPageHost _page = DetailPageHost(); + + /// The list rows the phone's chat page grows from and shrinks back into: + /// the open chat's row, also after the page switched to another chat. + final ContainerTransformSources _rowSources = ContainerTransformSources(); + late final ContainerTransformLink _growFromRow = _rowSources.link( + () => _selected, + ); @override bool get _pageOpen => _page.open; @@ -550,13 +558,14 @@ class _ChatScreenState extends State selected: selected != null && !beside && !_usedWorkspace, destination: AppDestination.chat, onClosed: _back, + growFrom: _growFromRow, builder: (context) => selected == null ? const SizedBox.shrink() : ShellBar(barless: true, child: _workspaceView()), ); // The session list pads its first row by the bar's height itself, so it // scrolls behind the shell's floating bar like the other lists. - final fullList = ChatSessionsScreen( + final sessions = ChatSessionsScreen( gateway: widget.gateway, embedded: true, syncToken: widget.syncToken, @@ -575,6 +584,10 @@ class _ChatScreenState extends State _sidebarMode == ChatSidebarMode.expanded) && (beside || !_usedWorkspace || selected == null), ); + final fullList = ContainerTransformScope( + sources: _rowSources, + child: sessions, + ); final list = _sidebarList(fullList, selected, beside); if (!beside) { if (!_usedWorkspace) return list; diff --git a/app/lib/features/chat/ui/sessions/session_row_content.dart b/app/lib/features/chat/ui/sessions/session_row_content.dart index 555038bc..d275a6f9 100644 --- a/app/lib/features/chat/ui/sessions/session_row_content.dart +++ b/app/lib/features/chat/ui/sessions/session_row_content.dart @@ -6,7 +6,7 @@ import '../../../../core/api_gateway.dart'; import '../../../../ui/layout/app_list_avatar.dart'; import '../../../../ui/layout/app_list_row.dart'; import '../../../../ui/text/relative_time_label.dart'; -import '../../../../shell/list_detail_policy.dart'; +import '../../../../ui/motion/container_transform_source.dart'; import '../../domain/chat_colors.dart'; import '../../domain/chat_list_activity.dart'; import '../../domain/chat_sessions.dart'; @@ -65,11 +65,34 @@ class ChatSessionRow extends StatelessWidget { final id = '${session['id'] ?? ''}'; final cupertino = chatControlsStyleOf(context) == ChatControlsStyle.cupertino; - final closed = chatSessionRowStatus(session, unseen: false) == 'Closed'; - final unread = unseen && !closed; final accent = cupertino ? CupertinoTheme.of(context).primaryColor : Theme.of(context).colorScheme.primary; + final shade = chatColorShade(context, chatSessionColor(session)); + final marker = shade ?? accent; + final tint = AppListRow.tintFor(context, shade, cupertino: cupertino); + final background = cupertino + ? CupertinoDynamicColor.resolve( + CupertinoTheme.of(context).scaffoldBackgroundColor, + context, + ) + : Theme.of(context).scaffoldBackgroundColor; + // On a phone the chat's page grows out of this row and shrinks back + // into it; the surface it starts from is the row's tint over the list. + return ContainerTransformSource( + id: id, + color: tint == null ? background : Color.alphaBlend(tint, background), + marker: marker, + markerWidth: visible ? (selected ? 10 : 3) : 0, + child: _marked(context, id, marker, accent), + ); + } + + Widget _marked(BuildContext context, String id, Color marker, Color accent) { + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final closed = chatSessionRowStatus(session, unseen: false) == 'Closed'; + final unread = unseen && !closed; final text = chatSessionSubtitle(session); final updatedAt = _chatSessionInstant(session['updated_at']); final avatar = ChatSessionAvatar( @@ -80,15 +103,9 @@ class ChatSessionRow extends StatelessWidget { : chatSessionBackgroundTasks(session), selected: selected, ); - final mobileHero = - !showsListBesideDetail(context) && - !(MediaQuery.maybeDisableAnimationsOf(context) ?? false); - final identity = mobileHero - ? Hero(tag: 'chat-identity-$id', child: avatar) - : avatar; return ChatVisibilityMarker( sessionId: id, - color: chatColorShade(context, chatSessionColor(session)) ?? accent, + color: marker, visible: visible, active: selected, child: AppListRow( @@ -102,7 +119,7 @@ class ChatSessionRow extends StatelessWidget { onLongPress: selectionOnly ? null : onLongPress, accent: chatColorShade(context, chatSessionColor(session)), showAccentBorder: false, - leading: identity, + leading: avatar, // The star rides in the title's own text, so a narrow row ellipsises // them together. title: Text.rich( diff --git a/app/lib/features/chat/workspace/chat_workspace_entrance.dart b/app/lib/features/chat/workspace/chat_workspace_entrance.dart index 3bec11a9..a6ae83e0 100644 --- a/app/lib/features/chat/workspace/chat_workspace_entrance.dart +++ b/app/lib/features/chat/workspace/chat_workspace_entrance.dart @@ -65,8 +65,8 @@ class _ChatWorkspaceEntranceState extends State @override Widget build(BuildContext context) { final content = HeroMode( - // The initial pushed page has a native Hero. Here both surfaces share - // one route; only the workspace entrance animates, never duplicate tags. + // Both surfaces share one route here; only the workspace entrance + // animates, so no Hero inside the chat flies or duplicates a tag. enabled: false, child: TickerMode(enabled: widget.visible, child: widget.child), ); diff --git a/app/lib/shell/detail_page.dart b/app/lib/shell/detail_page.dart index 0de9f47e..11941427 100644 --- a/app/lib/shell/detail_page.dart +++ b/app/lib/shell/detail_page.dart @@ -3,6 +3,8 @@ import 'package:flutter/material.dart'; import '../ui/adaptive/host.dart'; import '../ui/adaptive/segmented_bar.dart'; +import '../ui/motion/container_transform_route.dart'; +import '../ui/motion/container_transform_source.dart'; import 'destination.dart'; import 'shell_bar.dart'; @@ -26,6 +28,7 @@ class DetailPageHost { required AppDestination destination, required WidgetBuilder builder, required VoidCallback onClosed, + ContainerTransformLink? growFrom, }) { if (selected && _route != null) { // Another route cannot be rebuilt mid-build; the page follows next frame. @@ -38,6 +41,7 @@ class DetailPageHost { final route = detailPageRoute( context, destination: destination, + growFrom: growFrom, builder: (context) => ValueListenableBuilder( valueListenable: _content, builder: (context, build, _) => @@ -78,13 +82,26 @@ class DetailPageHost { /// A full-screen page whose bar shows what the page's content publishes /// through [ShellBar] (title and actions), with the platform's Back. +/// +/// With [growFrom] the page grows out of the list item that opened it and +/// shrinks back into it ([ContainerTransformPageRoute]); otherwise it enters +/// with the platform's page transition. PageRoute detailPageRoute( BuildContext context, { required AppDestination destination, required WidgetBuilder builder, + ContainerTransformLink? growFrom, }) { final page = DetailPane(destination: destination, builder: builder); - return usesCupertinoHost(context) + final cupertino = usesCupertinoHost(context); + if (growFrom != null) { + return ContainerTransformPageRoute( + link: growFrom, + cupertino: cupertino, + builder: (_) => page, + ); + } + return cupertino ? CupertinoPageRoute(builder: (_) => page) : MaterialPageRoute(builder: (_) => page); } diff --git a/app/lib/ui/layout/app_list_row.dart b/app/lib/ui/layout/app_list_row.dart index 45d6a118..19dce618 100644 --- a/app/lib/ui/layout/app_list_row.dart +++ b/app/lib/ui/layout/app_list_row.dart @@ -118,6 +118,14 @@ class AppListRow extends StatelessWidget { /// Overrides the host detection (some features pick a style per platform). final bool? cupertino; + /// The faint tint an unselected row with [accent] wears over the list. + static Color? tintFor( + BuildContext context, + Color? accent, { + required bool cupertino, + }) => + accent?.withValues(alpha: _darkSurface(context, cupertino) ? 0.12 : 0.07); + /// The open row's fill on each host. static Color selectedColor(BuildContext context, {required bool cupertino}) => cupertino @@ -173,9 +181,7 @@ class AppListRow extends StatelessWidget { ], ), ); - final tint = accent?.withValues( - alpha: _darkSurface(context, cupertino) ? 0.12 : 0.07, - ); + final tint = tintFor(context, accent, cupertino: cupertino); final surface = cupertino ? _CupertinoRowSurface( tapKey: tapKey, diff --git a/app/lib/ui/motion/container_transform_flight.dart b/app/lib/ui/motion/container_transform_flight.dart new file mode 100644 index 00000000..f8a1b377 --- /dev/null +++ b/app/lib/ui/motion/container_transform_flight.dart @@ -0,0 +1,264 @@ +import 'package:flutter/widgets.dart'; + +import 'container_transform_source.dart'; +import 'motion.dart'; + +/// Key of the growing surface, for finders. +const containerTransformSurfaceKey = ValueKey( + 'container-transform-surface', +); + +/// A page growing out of its item's rectangle and shrinking back into it. +/// +/// The surface morphs from the item's (its bounds, shape, tint and edge +/// marker) to the page's while the content cross-fades: on opening the item +/// is covered early and the page appears late; on closing the page goes +/// early and the item shows through late. The list behind never moves. +/// +/// Without an [origin] (reduced motion, or the item is not on screen) the +/// page simply fades. The widget tree is the same in every state, so the +/// page keeps its state at rest and through any transition. +class ContainerTransformFlight extends StatefulWidget { + const ContainerTransformFlight({ + super.key, + required this.animation, + required this.origin, + required this.closing, + required this.tracking, + required this.pageColor, + required this.scrimColor, + required this.child, + }); + + /// The route's animation: 0 at the item, 1 as the full page. + final Animation animation; + + /// Resolves where to grow from or shrink into; null fades instead. + final ContainerTransformOrigin? Function()? origin; + + /// Whether the page is on its way back into the item. + final bool Function() closing; + + /// Whether a finger drives the animation (it then follows linearly). + final bool Function() tracking; + final Color pageColor; + final Color scrimColor; + final Widget child; + + @override + State createState() => + _ContainerTransformFlightState(); +} + +class _ContainerTransformFlightState extends State { + ContainerTransformOrigin? _origin; + bool _resolved = false; + + @override + void initState() { + super.initState(); + widget.animation.addStatusListener(_statusChanged); + } + + @override + void didUpdateWidget(ContainerTransformFlight oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.animation != widget.animation) { + oldWidget.animation.removeStatusListener(_statusChanged); + widget.animation.addStatusListener(_statusChanged); + } + } + + @override + void dispose() { + widget.animation.removeStatusListener(_statusChanged); + super.dispose(); + } + + // Each flight measures its item afresh: the open item may have changed, + // or the window may have resized, while the page was up. + void _statusChanged(AnimationStatus status) { + if (status.isCompleted || status.isDismissed) _resolved = false; + } + + ContainerTransformOrigin? _resolve() { + if (!_resolved) { + _resolved = true; + _origin = widget.origin?.call(); + } + return _origin; + } + + @override + Widget build(BuildContext context) => LayoutBuilder( + builder: (context, constraints) { + final size = constraints.biggest; + return AnimatedBuilder( + animation: widget.animation, + child: widget.child, + builder: (context, child) { + final t = widget.animation.value; + final atRest = widget.animation.isCompleted; + final origin = atRest ? null : _resolve(); + final frame = origin == null + ? _Frame.fade(t, size, widget.pageColor) + : _Frame.transform( + t, + _local(origin.rect), + size, + origin, + widget.pageColor, + closing: widget.closing(), + tracking: widget.tracking(), + ); + // The list dims as the page grows and brightens as it shrinks. + final scrim = atRest ? 0.0 : Motion.containerTransformScrim * t; + return Stack( + fit: StackFit.expand, + children: [ + IgnorePointer( + child: ColoredBox( + color: widget.scrimColor.withValues( + alpha: widget.scrimColor.a * scrim, + ), + ), + ), + Positioned.fromRect( + rect: frame.rect, + child: Opacity( + opacity: frame.surfaceOpacity, + child: ClipRRect( + key: containerTransformSurfaceKey, + borderRadius: frame.radius, + clipBehavior: atRest ? Clip.none : Clip.hardEdge, + child: DecoratedBox( + decoration: BoxDecoration(color: frame.color), + position: DecorationPosition.background, + child: _Content( + size: size, + opacity: frame.contentOpacity, + marker: frame.marker, + markerWidth: frame.markerWidth, + child: child!, + ), + ), + ), + ), + ), + ], + ); + }, + ); + }, + ); + + /// [global] in this page's coordinates; the page fills its navigator. + Rect _local(Rect global) { + final box = context.findRenderObject(); + if (box is! RenderBox || !box.hasSize) return global; + return global.shift(-box.localToGlobal(Offset.zero)); + } +} + +/// The page laid out at its full size, aligned to the top of the surface +/// and scaled to its width, so nothing inside relayouts as it grows. +class _Content extends StatelessWidget { + const _Content({ + required this.size, + required this.opacity, + required this.marker, + required this.markerWidth, + required this.child, + }); + + final Size size; + final double opacity; + final Color? marker; + final double markerWidth; + final Widget child; + + @override + Widget build(BuildContext context) => DecoratedBox( + position: DecorationPosition.foreground, + decoration: BoxDecoration( + border: marker == null || markerWidth <= 0 + ? null + : BorderDirectional( + start: BorderSide(color: marker!, width: markerWidth), + ), + ), + child: FittedBox( + fit: BoxFit.fitWidth, + alignment: Alignment.topCenter, + clipBehavior: Clip.none, + child: SizedBox.fromSize( + size: size, + child: Opacity(opacity: opacity, child: child), + ), + ), + ); +} + +class _Frame { + const _Frame({ + required this.rect, + required this.radius, + required this.color, + required this.surfaceOpacity, + required this.contentOpacity, + this.marker, + this.markerWidth = 0, + }); + + /// The whole page fading in place. + factory _Frame.fade(double t, Size size, Color pageColor) => _Frame( + rect: Offset.zero & size, + radius: BorderRadius.zero, + color: pageColor, + surfaceOpacity: Curves.easeInOut.transform(t), + contentOpacity: 1, + ); + + factory _Frame.transform( + double t, + Rect start, + Size size, + ContainerTransformOrigin origin, + Color pageColor, { + required bool closing, + required bool tracking, + }) { + const curve = Curves.fastOutSlowIn; + // Played backwards in time, the same easing reads as the item settling. + final grown = tracking + ? t + : closing + ? curve.flipped.transform(t) + : curve.transform(t); + // Opening covers the item first and shows the page late; closing hides + // the page first and uncovers the item late. + final surface = closing + ? const Interval(0, 0.3).transform(t) + : const Interval(0, 0.2).transform(t); + final content = closing + ? const Interval(0.7, 1).transform(t) + : const Interval(0.25, 0.7, curve: Curves.easeIn).transform(t); + return _Frame( + rect: Rect.lerp(start, Offset.zero & size, grown)!, + radius: BorderRadius.lerp(origin.borderRadius, BorderRadius.zero, grown)!, + color: Color.lerp(origin.color, pageColor, grown)!, + surfaceOpacity: surface, + contentOpacity: content, + marker: origin.marker, + markerWidth: origin.markerWidth * (1 - grown), + ); + } + + final Rect rect; + final BorderRadius radius; + final Color color; + final double surfaceOpacity; + final double contentOpacity; + final Color? marker; + final double markerWidth; +} diff --git a/app/lib/ui/motion/container_transform_gestures.dart b/app/lib/ui/motion/container_transform_gestures.dart new file mode 100644 index 00000000..5a4ff7a2 --- /dev/null +++ b/app/lib/ui/motion/container_transform_gestures.dart @@ -0,0 +1,181 @@ +import 'dart:math' as math; + +import 'package:flutter/gestures.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +/// What a back gesture needs from the page it closes. +abstract interface class ContainerTransformGestureRoute + implements PredictiveBackRoute { + /// Whether a back gesture may start now: the page is current, at rest and + /// would really pop. + bool get backGestureEnabled; + + /// A finger took the page from the start edge. + void startSwipeBack(); + + /// The finger moved by [fraction] of the page's width toward the end edge. + void updateSwipeBack(double fraction); + + /// The finger let go at [velocity] page widths per second. + void endSwipeBack(double velocity); +} + +/// The back gestures of a page that shrinks into its item: on a Cupertino +/// host the native swipe from the start edge; on Android the system's +/// predictive back. Either one drives the page's own animation, so the +/// shrink follows the finger, and releasing commits or cancels it. +class ContainerTransformBackGestures extends StatelessWidget { + const ContainerTransformBackGestures({ + super.key, + required this.route, + required this.cupertino, + required this.child, + }); + + final ContainerTransformGestureRoute route; + final bool cupertino; + final Widget child; + + @override + Widget build(BuildContext context) => cupertino + ? _EdgeSwipeBack(route: route, child: child) + : _PredictiveBack(route: route, child: child); +} + +/// The width of the start edge that takes a swipe back, as in iOS. +const double _edgeWidth = 20; + +class _EdgeSwipeBack extends StatefulWidget { + const _EdgeSwipeBack({required this.route, required this.child}); + + final ContainerTransformGestureRoute route; + final Widget child; + + @override + State<_EdgeSwipeBack> createState() => _EdgeSwipeBackState(); +} + +class _EdgeSwipeBackState extends State<_EdgeSwipeBack> { + late final HorizontalDragGestureRecognizer _recognizer = + HorizontalDragGestureRecognizer(debugOwner: this) + ..onStart = _start + ..onUpdate = _update + ..onEnd = _end + ..onCancel = _cancel; + bool _dragging = false; + + @override + void dispose() { + _recognizer.dispose(); + if (_dragging) widget.route.endSwipeBack(0); + super.dispose(); + } + + double _logical(double value) => + Directionality.of(context) == TextDirection.rtl ? -value : value; + + void _start(DragStartDetails details) { + _dragging = true; + widget.route.startSwipeBack(); + } + + void _update(DragUpdateDetails details) { + if (!_dragging) return; + widget.route.updateSwipeBack( + _logical(details.primaryDelta! / context.size!.width), + ); + } + + void _end(DragEndDetails details) { + if (!_dragging) return; + _dragging = false; + widget.route.endSwipeBack( + _logical(details.velocity.pixelsPerSecond.dx / context.size!.width), + ); + } + + void _cancel() { + if (!_dragging) return; + _dragging = false; + widget.route.endSwipeBack(0); + } + + @override + Widget build(BuildContext context) { + final padding = MediaQuery.paddingOf(context); + final notch = Directionality.of(context) == TextDirection.rtl + ? padding.right + : padding.left; + return Stack( + fit: StackFit.passthrough, + children: [ + widget.child, + PositionedDirectional( + start: 0, + top: 0, + bottom: 0, + width: math.max(notch, _edgeWidth), + child: Listener( + behavior: HitTestBehavior.translucent, + onPointerDown: (event) { + if (widget.route.backGestureEnabled) { + _recognizer.addPointer(event); + } + }, + ), + ), + ], + ); + } +} + +/// Forwards Android's predictive back to the page, as the stock Material +/// page transition does, without that transition's own shrink. +class _PredictiveBack extends StatefulWidget { + const _PredictiveBack({required this.route, required this.child}); + + final ContainerTransformGestureRoute route; + final Widget child; + + @override + State<_PredictiveBack> createState() => _PredictiveBackState(); +} + +class _PredictiveBackState extends State<_PredictiveBack> + with WidgetsBindingObserver { + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } + + @override + bool handleStartBackGesture(PredictiveBackEvent backEvent) { + if (backEvent.isButtonEvent || !widget.route.backGestureEnabled) { + return false; + } + widget.route.handleStartBackGesture(progress: 1 - backEvent.progress); + return true; + } + + @override + void handleUpdateBackGestureProgress(PredictiveBackEvent backEvent) => widget + .route + .handleUpdateBackGestureProgress(progress: 1 - backEvent.progress); + + @override + void handleCancelBackGesture() => widget.route.handleCancelBackGesture(); + + @override + void handleCommitBackGesture() => widget.route.handleCommitBackGesture(); + + @override + Widget build(BuildContext context) => widget.child; +} diff --git a/app/lib/ui/motion/container_transform_route.dart b/app/lib/ui/motion/container_transform_route.dart new file mode 100644 index 00000000..92e83fc4 --- /dev/null +++ b/app/lib/ui/motion/container_transform_route.dart @@ -0,0 +1,173 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'container_transform_flight.dart'; +import 'container_transform_gestures.dart'; +import 'container_transform_source.dart'; +import 'motion.dart'; + +/// How long a page released mid-swipe takes to settle, as in iOS. +const Duration _droppedSwipeDuration = Duration(milliseconds: 350); + +/// A full-screen page that grows out of the item that opened it and shrinks +/// back into it on Back (Material's container transform). +/// +/// [link] resolves the item each time the page animates, so closing after +/// another item took the page shrinks into that one. When the item is not on +/// screen, or the system asks for reduced motion, the page fades instead. +/// The list behind stays put. A Cupertino host keeps the native swipe back +/// from the start edge and Android its predictive back; both drive the +/// shrink with the finger. The animation-speed setting scales every +/// duration through the scheduler clock. +class ContainerTransformPageRoute extends PageRoute + implements ContainerTransformGestureRoute { + ContainerTransformPageRoute({ + required this.builder, + required this.link, + required this.cupertino, + super.settings, + }); + + final WidgetBuilder builder; + final ContainerTransformLink link; + final bool cupertino; + + bool get _reducedMotion { + final context = navigator?.context; + return context != null && + (MediaQuery.maybeDisableAnimationsOf(context) ?? false); + } + + @override + Duration get transitionDuration => + _reducedMotion ? Motion.quick : Motion.containerTransform; + + @override + Duration get reverseTransitionDuration => + _reducedMotion ? Motion.quick : Motion.containerTransformReverse; + + @override + bool get opaque => true; + + @override + bool get maintainState => true; + + @override + Color? get barrierColor => null; + + @override + String? get barrierLabel => null; + + /// The list this page grew from never moves under it. + @override + bool canTransitionFrom(TransitionRoute previousRoute) => false; + + @override + Widget buildPage( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + ) => Semantics( + scopesRoute: true, + explicitChildNodes: true, + child: builder(context), + ); + + @override + Widget buildTransitions( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) { + final reduced = MediaQuery.maybeDisableAnimationsOf(context) ?? false; + final pageColor = cupertino + ? CupertinoDynamicColor.resolve( + CupertinoTheme.of(context).scaffoldBackgroundColor, + context, + ) + : Theme.of(context).scaffoldBackgroundColor; + Widget page = ContainerTransformFlight( + animation: animation, + origin: reduced ? null : link.resolve, + closing: () => + animation.status == AnimationStatus.reverse || popGestureInProgress, + tracking: () => popGestureInProgress, + pageColor: pageColor, + scrimColor: cupertino + ? CupertinoColors.black + : Theme.of(context).colorScheme.scrim, + child: child, + ); + if (cupertino) { + // A page pushed over this one keeps the native parallax. + page = CupertinoPageTransition( + primaryRouteAnimation: kAlwaysCompleteAnimation, + secondaryRouteAnimation: secondaryAnimation, + linearTransition: popGestureInProgress, + child: page, + ); + } + return ContainerTransformBackGestures( + route: this, + cupertino: cupertino, + child: page, + ); + } + + @override + bool get backGestureEnabled => + isCurrent && + popGestureEnabled && + !(navigator?.userGestureInProgress ?? true); + + @override + void startSwipeBack() => navigator?.didStartUserGesture(); + + @override + void updateSwipeBack(double fraction) { + if (!isCurrent) return; + controller?.value -= fraction; + } + + @override + void endSwipeBack(double velocity) { + final controller = this.controller; + final navigator = this.navigator; + if (controller == null || navigator == null) return; + // As in iOS: a fling decides; otherwise the page goes back past halfway. + final bool stay; + if (!isCurrent) { + stay = isActive; + } else if (velocity.abs() >= 1) { + stay = velocity <= 0; + } else { + stay = controller.value > 0.5; + } + const curve = Curves.fastEaseInToSlowEaseOut; + if (stay) { + controller.animateTo(1, duration: _droppedSwipeDuration, curve: curve); + } else { + if (isCurrent) navigator.pop(); + if (controller.isAnimating) { + controller.animateBack( + 0, + duration: _droppedSwipeDuration, + curve: curve, + ); + } + } + if (!controller.isAnimating) { + navigator.didStopUserGesture(); + return; + } + // The gesture lasts until the page settles, so the shrink keeps + // following linearly instead of jumping onto the eased curve. + late final AnimationStatusListener settle; + settle = (_) { + navigator.didStopUserGesture(); + controller.removeStatusListener(settle); + }; + controller.addStatusListener(settle); + } +} diff --git a/app/lib/ui/motion/container_transform_source.dart b/app/lib/ui/motion/container_transform_source.dart new file mode 100644 index 00000000..01f30b07 --- /dev/null +++ b/app/lib/ui/motion/container_transform_source.dart @@ -0,0 +1,145 @@ +import 'package:flutter/widgets.dart'; + +/// Where a container transform starts and ends: an item's rectangle on the +/// screen and the surface it wears there. +@immutable +class ContainerTransformOrigin { + const ContainerTransformOrigin({ + required this.rect, + required this.color, + this.borderRadius = BorderRadius.zero, + this.marker, + this.markerWidth = 0, + }); + + /// The item's bounds in global coordinates. + final Rect rect; + + /// The item's opaque surface (its tint over the list's background). + final Color color; + final BorderRadius borderRadius; + + /// The colour of the item's leading-edge marker, if it shows one. + final Color? marker; + final double markerWidth; +} + +/// The items of one list that pages can grow from, by key. +class ContainerTransformSources { + final Map _sources = {}; + + /// [key]'s current place and surface, or null when it is not laid out + /// (scrolled away, not built yet, or its list is gone). + ContainerTransformOrigin? originOf(Object? key) { + if (key == null) return null; + return _sources[key]?._origin(); + } + + /// A link a route can resolve [key] through each time it animates. + ContainerTransformLink link(Object? Function() key) => + ContainerTransformLink(() => originOf(key())); +} + +/// Resolves a route's origin lazily: the open item can change while the page +/// is up (another chat switched in), and closing shrinks into that one. +class ContainerTransformLink { + const ContainerTransformLink(this.resolve); + + final ContainerTransformOrigin? Function() resolve; +} + +/// Offers [ContainerTransformSources] to the items below it. +class ContainerTransformScope extends InheritedWidget { + const ContainerTransformScope({ + super.key, + required this.sources, + required super.child, + }); + + final ContainerTransformSources sources; + + static ContainerTransformSources? maybeOf(BuildContext context) => + context.getInheritedWidgetOfExactType()?.sources; + + @override + bool updateShouldNotify(ContainerTransformScope oldWidget) => + sources != oldWidget.sources; +} + +/// Registers [child] as the item [id] a page can grow from and shrink into. +/// Without a [ContainerTransformScope] above it, it only builds [child]. +class ContainerTransformSource extends StatefulWidget { + const ContainerTransformSource({ + super.key, + required this.id, + required this.color, + this.borderRadius = BorderRadius.zero, + this.marker, + this.markerWidth = 0, + required this.child, + }); + + final Object id; + final Color color; + final BorderRadius borderRadius; + final Color? marker; + final double markerWidth; + final Widget child; + + @override + State createState() => + _ContainerTransformSourceState(); +} + +class _ContainerTransformSourceState extends State { + ContainerTransformSources? _sources; + Object? _id; + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _register(); + } + + @override + void didUpdateWidget(ContainerTransformSource oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.id != widget.id) _register(); + } + + void _register() { + _unregister(); + final sources = ContainerTransformScope.maybeOf(context); + _sources = sources; + _id = widget.id; + sources?._sources[widget.id] = this; + } + + void _unregister() { + final sources = _sources; + if (sources != null && sources._sources[_id] == this) { + sources._sources.remove(_id); + } + } + + ContainerTransformOrigin? _origin() { + final box = context.findRenderObject(); + if (box is! RenderBox || !box.attached || !box.hasSize) return null; + return ContainerTransformOrigin( + rect: box.localToGlobal(Offset.zero) & box.size, + color: widget.color, + borderRadius: widget.borderRadius, + marker: widget.marker, + markerWidth: widget.markerWidth, + ); + } + + @override + void dispose() { + _unregister(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => widget.child; +} diff --git a/app/lib/ui/motion/motion.dart b/app/lib/ui/motion/motion.dart index 3982b836..f523fbc4 100644 --- a/app/lib/ui/motion/motion.dart +++ b/app/lib/ui/motion/motion.dart @@ -95,6 +95,15 @@ abstract final class Motion { /// softly with no overshoot. static const Curve sentMessageCurve = Cubic(0.05, 0.7, 0.1, 1); + /// A tapped item growing into its page (Material's container transform). + static const Duration containerTransform = Duration(milliseconds: 300); + + /// The page shrinking back into its item. + static const Duration containerTransformReverse = Duration(milliseconds: 250); + + /// How far the list behind a growing page dims, at most. + static const double containerTransformScrim = 0.2; + static const Curve curve = Curves.easeOutCubic; /// [duration], or zero under the system's reduce-motion setting. diff --git a/app/notes/chat-open-container-transform.md b/app/notes/chat-open-container-transform.md new file mode 100644 index 00000000..2b5fa59a --- /dev/null +++ b/app/notes/chat-open-container-transform.md @@ -0,0 +1,79 @@ +# Chat opens as a container transform from its row + +User request: "for the hero animation in the chat list, I meant like the chat +expanding from the list, not just the icon". + +## Behaviour + +On a phone (list and chat not side by side) tapping a chat row grows the row +itself into the full chat page; Back shrinks the page back into the row. + +- The surface morphs: bounds go from the row's rectangle to the full page + (`Curves.fastOutSlowIn`, played backwards for the close), colour goes from + the row's tint over the list background to the page background, and the + row's leading-edge marker (chat colour, 3 or 10 px) narrows to nothing. +- Content cross-fades: opening covers the row content in the first 20 % and + fades the page in over 25-70 %; closing fades the page out in the first + 30 % and uncovers the real row underneath in the last 30 %. +- The list behind does not move (the route refuses a secondary transition); + it dims by at most 20 % (`Motion.containerTransformScrim`) with the + page's size. +- Timing: `Motion.containerTransform` (300 ms) and + `Motion.containerTransformReverse` (250 ms). The animation-speed setting + scales them through `timeDilation`, as for every route. +- Reduced motion: no movement; the page fades in place (Flutter's + `AnimationBehavior.normal` additionally shortens the route under the + system setting). +- No row on screen (deep link at start-up, the row scrolled away, or the page + switched to a chat whose row is not laid out): the page fades instead. +- Closing resolves the row again, so after Next chat or the quick-switch tape + the page shrinks into the row of the chat now open. +- Cupertino host: the native swipe from the start edge (20 px, or the notch + inset) drives the shrink with the finger, linearly; release commits by + fling or past halfway, otherwise it settles back, as iOS does. A page pushed + over the chat keeps the Cupertino parallax. +- Android: system predictive back drives the same shrink; cancel restores + the page, commit pops it. +- Wide layouts (list beside the pane) and the workspace-after-wide path are + unchanged: neither pushes this route. +- The old identity-avatar `Hero` (row avatar to header) is removed: a + separate flying avatar over a fading container does not compose, and + Material's container transform is itself the shared element. + +## Code + +- `lib/ui/motion/container_transform_route.dart`: `ContainerTransformPageRoute` + (durations, opacity, swipe settle logic). +- `lib/ui/motion/container_transform_flight.dart`: the morph itself; one fixed + widget tree in every state, so the chat page keeps its state and scroll. +- `lib/ui/motion/container_transform_gestures.dart`: Cupertino edge swipe and + Android predictive back forwarding. +- `lib/ui/motion/container_transform_source.dart`: rows register their + rectangle, surface and marker by id under a `ContainerTransformScope`. +- `lib/shell/detail_page.dart`: `DetailPageHost.sync(growFrom:)` and + `detailPageRoute(growFrom:)`; runs and pipelines keep the platform route. +- `lib/features/chat/screen.dart`: scope around the list; link resolves the + currently selected chat. +- `lib/features/chat/ui/sessions/session_row_content.dart`: row registers as a + source (tint via the new `AppListRow.tintFor`). + +## Verification + +- `tool/memwatch/full.sh 'test/features/chat test/shell test/ui'`: PASS, + 1604 passed, 0 failed. +- `tool/analyze.sh`: clean. +- Tests: `test/ui/motion/container_transform_route_test.dart` (row rect to + full page and back, list stays put, reduced-motion fade, missing row fade, + Cupertino swipe follows the finger and commits, short swipe settles back, + Android predictive back cancel and commit) and + `test/features/chat/chat_open_transition_test.dart` (real `ChatScreen` at + 390x844 grows and shrinks with no Hero, reduced-motion fade, 1280x800 + opens beside the list with no transform, row surface/marker, Motion timing). +- Real Chrome, fixture `?chats=3&rich=1&colors=1`, 390x844, filmed with + `film=` (half animation speed so the headless screencast catches frames, + plus one at 1x): Material dark, Material light and Cupertino light open and + close contact sheets, and a held mid-swipe on Cupertino showing the page + shrunk toward the row. The kit warns about widths under 500 px; these + captures rendered correctly. +- Not verified on a device (iOS swipe and Android predictive back were only + exercised in widget tests and, for the swipe, with a mouse drag in Chrome). diff --git a/app/notes/chat-open-transition.md b/app/notes/chat-open-transition.md index 9c7b8411..fcf08d9e 100644 --- a/app/notes/chat-open-transition.md +++ b/app/notes/chat-open-transition.md @@ -1,5 +1,5 @@ # Mobile chat opening transition -The mobile chat row and conversation header share the chat identity avatar through a native Flutter `Hero`. The identity is added inside the existing title pill, preserving the colored header wash and desktop title geometry. Wide list/detail panes and reduced-motion contexts do not create a flight. - -Focused behavioral coverage is in `test/features/chat/chat_open_transition_test.dart`; it uses a fake chat, checks the mobile route opens/returns with the identity in the header, verifies an intermediate Hero geometry during the route animation, and checks reduced motion omits `Hero`. +Superseded by `chat-open-container-transform.md`: the tapped row itself grows +into the chat page and shrinks back on Back. The earlier identity-avatar +`Hero` between the row and the header was removed. diff --git a/app/test/features/chat/chat_open_transition_test.dart b/app/test/features/chat/chat_open_transition_test.dart index 6faa9879..da19c01e 100644 --- a/app/test/features/chat/chat_open_transition_test.dart +++ b/app/test/features/chat/chat_open_transition_test.dart @@ -1,106 +1,192 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:pipelines_app/features/chat/conversation/chat_thread_header.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/screen.dart'; import 'package:pipelines_app/features/chat/ui/sessions/session_row_content.dart'; +import 'package:pipelines_app/shell/adaptive_shell.dart'; +import 'package:pipelines_app/shell/destination.dart'; +import 'package:pipelines_app/ui/motion/container_transform_flight.dart'; +import 'package:pipelines_app/ui/motion/container_transform_route.dart'; +import 'package:pipelines_app/ui/motion/container_transform_source.dart'; +import 'package:pipelines_app/ui/motion/motion.dart'; import 'package:pipelines_app/ui/theme/app_theme.dart'; -const _session = { - 'id': 'fake-chat', - 'title': 'Fake chat', - 'directory': '/tmp/fake-chat', - 'color': 'blue', -}; +import '../../native_back.dart'; +import 'conversation/chat_thread_fixtures.dart'; + +class _Gateway extends FakeChatGateway { + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type == 'chat_sessions') { + return Future.value({ + 'chat_sessions': [ + {'id': 'a', 'title': 'First chat', 'color': 'blue'}, + {'id': 'b', 'title': 'Second chat'}, + ], + }); + } + if (type == 'chat_shells') return Future.value({'chat_shells': []}); + return super.call(type, fields); + } +} + +Future _pumpShell(WidgetTester tester, Size size) async { + SharedPreferences.setMockInitialValues({}); + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final gateway = _Gateway()..history = (_) async => chatPage(const []); + addTearDown(gateway.close); + await tester.pumpWidget( + MaterialApp( + theme: appLightTheme(), + home: AdaptiveShell( + destination: AppDestination.chat, + destinationBodies: { + AppDestination.chat: (_) => ChatScreen(gateway: gateway), + }, + ), + ), + ); + await tester.pumpAndSettle(); +} + +Finder get _surface => find.byKey(containerTransformSurfaceKey); void main() { - testWidgets('mobile identity flies into the header and returns to the row', ( + testWidgets('a phone grows the tapped row into the chat and back', ( tester, ) async { - tester.view.physicalSize = const Size(390, 844); - tester.view.devicePixelRatio = 1; - addTearDown(tester.view.reset); + // Chat tests run with reduced motion (flutter_test_config); this one + // covers the motion itself. + final reduced = tester.platformDispatcher.accessibilityFeatures; + tester.platformDispatcher.accessibilityFeaturesTestValue = + const FakeAccessibilityFeatures(); + addTearDown( + () => tester.platformDispatcher.accessibilityFeaturesTestValue = reduced, + ); + await _pumpShell(tester, const Size(390, 844)); + final row = tester.getRect(find.byKey(const Key('chat-row-a'))); + expect( + find.byType(Hero), + findsNothing, + reason: 'the row is the shared element', + ); + + await tester.tap(find.text('First chat')); + await tester.pump(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 120)); + final navigator = tester.state( + find.byType(Navigator).first, + ); + expect(navigator.canPop(), isTrue); + final mid = tester.getRect(_surface); + expect(mid.top, lessThan(row.top)); + expect(mid.height, greaterThan(row.height)); + expect(mid.height, lessThan(844)); + + await tester.pumpAndSettle(); + expect(tester.getRect(_surface), const Rect.fromLTWH(0, 0, 390, 844)); + expect(find.byKey(const ValueKey('chat-thread-a')), findsOneWidget); + expect(find.byType(Hero), findsNothing); + + await tester.tap(findNativeBack()); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + final closing = tester.getRect(_surface); + expect(closing.height, lessThan(844)); + expect(closing.height, greaterThan(row.height)); + + await tester.pumpAndSettle(); + expect(navigator.canPop(), isFalse); + expect(_surface, findsNothing); + expect(tester.getRect(find.byKey(const Key('chat-row-a'))), row); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('a phone under reduced motion fades the chat in place', ( + tester, + ) async { + await _pumpShell(tester, const Size(390, 844)); + await tester.tap(find.text('First chat')); + await tester.pump(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 1)); + expect(tester.getRect(_surface), const Rect.fromLTWH(0, 0, 390, 844)); + await tester.pumpAndSettle(); + expect(find.byKey(const ValueKey('chat-thread-a')), findsOneWidget); + await tester.tap(findNativeBack()); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 1)); + expect(tester.getRect(_surface), const Rect.fromLTWH(0, 0, 390, 844)); + await tester.pumpAndSettle(); + expect(_surface, findsNothing); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('a wide window opens the chat beside the list, untransformed', ( + tester, + ) async { + await _pumpShell(tester, const Size(1280, 800)); + await tester.tap(find.text('First chat')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 120)); + expect(_surface, findsNothing); + await tester.pumpAndSettle(); + expect(find.byKey(const ValueKey('chat-thread-a')), findsOneWidget); + expect(_surface, findsNothing); + final navigator = tester.state( + find.byType(Navigator).first, + ); + expect(navigator.canPop(), isFalse); + expect( + find.byWidgetPredicate((w) => w is ContainerTransformSource), + findsWidgets, + reason: 'rows still register, but nothing grows from them', + ); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('a row offers its tinted surface and edge marker', ( + tester, + ) async { + final sources = ContainerTransformSources(); await tester.pumpWidget( MaterialApp( theme: appLightTheme(), - builder: (context, child) => MediaQuery( - data: MediaQuery.of( - context, - ).copyWith(size: const Size(390, 844), disableAnimations: false), - child: child!, - ), home: Scaffold( - body: ChatSessionRow( - session: _session, - onOpen: (session) => - Navigator.of( - tester.element(find.byType(ChatSessionRow)), - ).push( - MaterialPageRoute( - builder: (_) => Scaffold( - body: ChatThreadHeader( - title: 'Fake chat', - folder: 'fake-chat', - onInfo: () {}, - showBack: true, - identity: ChatSessionAvatar( - session: session, - selected: true, - ), - identityHeroTag: 'chat-identity-fake-chat', - ), - ), - ), - ), - onAction: (_) {}, - ), - ), - ), - ); - await tester.pump(); - expect(find.byType(Hero), findsOneWidget); - final rowAvatar = find.byType(ChatSessionAvatar); - final rowRect = tester.getRect(rowAvatar); - await tester.tap(find.byKey(const Key('chat-row-fake-chat'))); - await tester.pump(const Duration(milliseconds: 100)); - expect(find.text('Fake chat'), findsOneWidget); - final heroFinder = find.byType(Hero, skipOffstage: false); - final heroRects = [ - for (var index = 0; index < tester.widgetList(heroFinder).length; index++) - tester.getRect(heroFinder.at(index)), - ]; - expect(heroRects, hasLength(2)); - expect( - heroRects.any((rect) => rect.size != rowRect.size && rect != rowRect), - isTrue, - ); - await tester.pumpAndSettle(); - final headerAvatar = tester.getRect(find.byType(ChatSessionAvatar)); - expect(headerAvatar.top, isNot(rowRect.top)); - await tester.pageBack(); - await tester.pumpAndSettle(); - expect(find.byKey(const Key('chat-row-fake-chat')), findsOneWidget); - }); - - testWidgets('reduced motion keeps the identity in place without a Hero', ( - tester, - ) async { - await tester.pumpWidget( - MediaQuery( - data: const MediaQueryData(disableAnimations: true), - child: MaterialApp( - theme: appLightTheme(), - home: Scaffold( - body: ChatThreadHeader( - title: 'Fake chat', - folder: 'fake-chat', - onInfo: () {}, - identity: ChatSessionAvatar(session: _session, selected: true), - identityHeroTag: 'chat-identity-fake-chat', + body: ContainerTransformScope( + sources: sources, + child: ChatSessionRow( + session: const {'id': 'x', 'title': 'Tinted', 'color': 'blue'}, + visible: true, + selected: true, + onOpen: (_) {}, + onAction: (_) {}, ), ), ), ), ); - await tester.pump(); - expect(find.byType(Hero), findsNothing); + final origin = sources.originOf('x')!; + expect(origin.rect, tester.getRect(find.byKey(const Key('chat-row-x')))); + final background = appLightTheme().scaffoldBackgroundColor; + expect(origin.color, isNot(background), reason: 'the chat colour tints it'); + expect(origin.color.a, 1); + expect(origin.markerWidth, 10); + expect(origin.marker, isNotNull); + }); + + test('the route reads its timing from Motion', () { + final route = ContainerTransformPageRoute( + link: ContainerTransformLink(() => null), + cupertino: false, + builder: (_) => const SizedBox(), + ); + expect(route.transitionDuration, Motion.containerTransform); + expect(route.reverseTransitionDuration, Motion.containerTransformReverse); + expect(route.opaque, isTrue); }); } diff --git a/app/test/ui/motion/container_transform_route_test.dart b/app/test/ui/motion/container_transform_route_test.dart new file mode 100644 index 00000000..fd733023 --- /dev/null +++ b/app/test/ui/motion/container_transform_route_test.dart @@ -0,0 +1,293 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/ui/motion/container_transform_flight.dart'; +import 'package:pipelines_app/ui/motion/container_transform_route.dart'; +import 'package:pipelines_app/ui/motion/container_transform_source.dart'; + +const _screen = Size(390, 844); +const _rowColor = Color(0xFFE3F2FD); + +/// A list of three rows; tapping one pushes its page, grown from that row. +class _List extends StatelessWidget { + const _List({required this.sources, required this.cupertino}); + + final ContainerTransformSources sources; + final bool cupertino; + + @override + Widget build(BuildContext context) => ContainerTransformScope( + sources: sources, + child: ListView( + padding: const EdgeInsets.only(top: 200), + children: [ + for (final id in ['a', 'b', 'c']) + ContainerTransformSource( + id: id, + color: _rowColor, + marker: const Color(0xFF1565C0), + markerWidth: 3, + child: GestureDetector( + key: Key('row-$id'), + onTap: () => Navigator.of(context).push( + ContainerTransformPageRoute( + link: sources.link(() => id), + cupertino: cupertino, + builder: (_) => _Page(id: id, cupertino: cupertino), + ), + ), + child: SizedBox(height: 72, child: Text('row $id')), + ), + ), + ], + ), + ); +} + +class _Page extends StatelessWidget { + const _Page({required this.id, required this.cupertino}); + + final String id; + final bool cupertino; + + @override + Widget build(BuildContext context) => cupertino + ? CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar(), + child: Center(child: Text('page $id')), + ) + : Scaffold( + appBar: AppBar(), + body: Center(child: Text('page $id')), + ); +} + +Future _pump( + WidgetTester tester, { + bool cupertino = false, + bool reduced = false, +}) async { + tester.view.physicalSize = _screen; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final sources = ContainerTransformSources(); + final home = _List(sources: sources, cupertino: cupertino); + Widget media(BuildContext context, Widget? child) => MediaQuery( + data: MediaQuery.of(context).copyWith(disableAnimations: reduced), + child: child!, + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp(builder: media, home: home) + : MaterialApp(builder: media, home: home), + ); + return sources; +} + +Rect _surface(WidgetTester tester) => + tester.getRect(find.byKey(containerTransformSurfaceKey)); + +double _opacityAbove(WidgetTester tester, Finder finder) => tester + .widget( + find.ancestor(of: finder, matching: find.byType(Opacity)).first, + ) + .opacity; + +/// Strictly between the row and the full screen on every edge it moves. +void _expectBetween(Rect rect, Rect row) { + expect(rect.top, lessThan(row.top)); + expect(rect.top, greaterThan(0)); + expect(rect.height, greaterThan(row.height)); + expect(rect.height, lessThan(_screen.height)); +} + +Future _backGesture(String method, [Map? args]) => + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage( + 'flutter/backgesture', + const StandardMethodCodec().encodeMethodCall( + MethodCall(method, args), + ), + (_) {}, + ); + +void main() { + testWidgets('the row grows into the page and Back shrinks it back', ( + tester, + ) async { + final sources = await _pump(tester); + final row = tester.getRect(find.byKey(const Key('row-b'))); + expect(sources.originOf('b')!.rect, row); + + await tester.tap(find.byKey(const Key('row-b'))); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 16)); + // The first frame starts on the row, in the row's colour, with the page + // content still hidden. + expect(_surface(tester).top, closeTo(row.top, 16)); + expect(_opacityAbove(tester, find.text('page b')), 0); + + await tester.pump(const Duration(milliseconds: 120)); + _expectBetween(_surface(tester), row); + // The list behind stays where it was. + expect(tester.getRect(find.byKey(const Key('row-b'))), row); + + await tester.pumpAndSettle(); + expect(_surface(tester), Offset.zero & _screen); + expect(_opacityAbove(tester, find.text('page b')), 1); + + await tester.pageBack(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 110)); + _expectBetween(_surface(tester), row); + // The page content goes early in the close. + expect(_opacityAbove(tester, find.text('page b')), lessThan(1)); + + await tester.pumpAndSettle(); + expect(find.text('page b'), findsNothing); + expect(find.byKey(containerTransformSurfaceKey), findsNothing); + expect(tester.getRect(find.byKey(const Key('row-b'))), row); + }); + + testWidgets('reduced motion fades the page in place', (tester) async { + await _pump(tester, reduced: true); + await tester.tap(find.byKey(const Key('row-b'))); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 60)); + expect(_surface(tester), Offset.zero & _screen); + final fading = tester + .widget( + find + .ancestor( + of: find.byKey(containerTransformSurfaceKey), + matching: find.byType(Opacity), + ) + .first, + ) + .opacity; + expect(fading, inExclusiveRange(0, 1)); + await tester.pumpAndSettle(); + expect(find.text('page b'), findsOneWidget); + + await tester.pageBack(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 60)); + expect(_surface(tester), Offset.zero & _screen); + await tester.pumpAndSettle(); + expect(find.text('page b'), findsNothing); + }); + + testWidgets('a row that is gone fades the page instead', (tester) async { + final sources = await _pump(tester); + expect(sources.originOf('missing'), isNull); + final navigator = tester.state(find.byType(Navigator)); + navigator.push( + ContainerTransformPageRoute( + link: sources.link(() => 'missing'), + cupertino: false, + builder: (_) => const _Page(id: 'x', cupertino: false), + ), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + expect(_surface(tester), Offset.zero & _screen); + await tester.pumpAndSettle(); + expect(find.text('page x'), findsOneWidget); + }); + + testWidgets('a Cupertino swipe back shrinks the page with the finger', ( + tester, + ) async { + await _pump(tester, cupertino: true); + final row = tester.getRect(find.byKey(const Key('row-b'))); + await tester.tap(find.byKey(const Key('row-b'))); + await tester.pumpAndSettle(); + expect(_surface(tester), Offset.zero & _screen); + + final gesture = await tester.startGesture(const Offset(5, 400)); + await gesture.moveBy(const Offset(20, 0)); + await gesture.moveBy(const Offset(100, 0)); + await tester.pump(); + final early = _surface(tester); + _expectBetween(early, row); + await gesture.moveBy(const Offset(100, 0)); + await tester.pump(); + final later = _surface(tester); + expect(later.height, lessThan(early.height), reason: 'follows the finger'); + + // Back toward the start edge, the page grows again. + await gesture.moveBy(const Offset(-150, 0)); + await tester.pump(); + expect(_surface(tester).height, greaterThan(later.height)); + + await gesture.moveBy(const Offset(200, 0)); + await gesture.up(); + await tester.pumpAndSettle(); + expect(find.text('page b'), findsNothing); + expect(find.byKey(const Key('row-b')), findsOneWidget); + }); + + testWidgets('a short Cupertino swipe released early stays on the page', ( + tester, + ) async { + await _pump(tester, cupertino: true); + await tester.tap(find.byKey(const Key('row-b'))); + await tester.pumpAndSettle(); + final gesture = await tester.startGesture(const Offset(5, 400)); + await gesture.moveBy(const Offset(20, 0)); + await gesture.moveBy(const Offset(40, 0)); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(find.text('page b'), findsOneWidget); + expect(_surface(tester), Offset.zero & _screen); + }); + + testWidgets('Android predictive back drives the shrink, then commits', ( + tester, + ) async { + await _pump(tester); + final row = tester.getRect(find.byKey(const Key('row-b'))); + await tester.tap(find.byKey(const Key('row-b'))); + await tester.pumpAndSettle(); + + await _backGesture('startBackGesture', { + 'touchOffset': [5.0, 400.0], + 'progress': 0.0, + 'swipeEdge': 0, + }); + await tester.pump(); + await _backGesture('updateBackGestureProgress', { + 'x': 120.0, + 'y': 400.0, + 'progress': 0.5, + 'swipeEdge': 0, + }); + await tester.pump(); + _expectBetween(_surface(tester), row); + + await _backGesture('cancelBackGesture'); + await tester.pumpAndSettle(); + expect(find.text('page b'), findsOneWidget); + expect(_surface(tester), Offset.zero & _screen); + + await _backGesture('startBackGesture', { + 'touchOffset': [5.0, 400.0], + 'progress': 0.0, + 'swipeEdge': 0, + }); + await tester.pump(); + await _backGesture('updateBackGestureProgress', { + 'x': 200.0, + 'y': 400.0, + 'progress': 0.7, + 'swipeEdge': 0, + }); + await tester.pump(); + await _backGesture('commitBackGesture'); + await tester.pumpAndSettle(); + expect(find.text('page b'), findsNothing); + expect(tester.getRect(find.byKey(const Key('row-b'))), row); + }); +}