fix(mobile): hand message action menu scrolling off to sheet dismissal (#9760)

## Summary

On mobile, the message action menu is a modal bottom sheet whose body
scrolls when the actions overflow (long menus, large text sizes). Before
this change, dragging down inside the body only scrolled or bounced the
content: the sheet itself could be pulled down only by its handle. Now a
downward drag in the body carries on into pulling the sheet down once
the content reaches its top, in the same touch, and the sheet can be
dismissed that way.

- **Handoff in both directions.** Drag updates are split between the
content and the existing modal route. Dragging down past the top of the
content moves the sheet; reversing without lifting restores the sheet
first and then scrolls the content again.
- **Release policy is the stock sheet's.** If the finger has displaced
the sheet at release, downward velocity strictly above 700 px/s closes
it; otherwise it closes when it has been pulled more than half its
height, and settles open if not. Where the gesture began, and whether it
scrolled content on the way to the top, does not matter.
- **Guards against accidental dismissal:**
  - a release with the sheet not displaced by the finger never closes;
- ballistic and programmatic scrolling cannot start a sheet drag, so a
content fling that reaches the top after the finger lifted stops there;
  - carried scroll momentum is not added to the release velocity;
- a slow return across the top that pulls the sheet less than half way
settles open;
  - an upward release velocity keeps the sheet open.
- **Unchanged:** handle and barrier behaviour, reactions, cancellation
recovery, reduced motion, and the action/focus contracts.

The handoff lives in a shared widget,
`mobile/lib/shared/widgets/modal_scroll_handoff.dart`;
`message_actions.dart` changes by three lines to use it.
`docs/mobile-message-action-scroll.md` records the design contract and a
manual native checklist.

### Related issue

N/A. None found (searched issues and PRs for the message action menu
dismissal and scroll).

### Testing

Run at `558a79710`:

- `just mobile-check`: passed (format; analyze: no issues).
- `just mobile-test`: passed (5462 Flutter tests, 71 skipped; 27 crypto
tests).
- `just file-size-check`: passed.
- Restoring the previous release rule fails 12 of the updated tests,
including all four message action journey variants.

Coverage: the message action journey (2x text scale, iOS and Android
platform settings) drives the production sheet with timed pointer
events; the shared widget tests cover the release table at several
scroll offsets, pointer flicks on both platforms, parity with the stock
sheet drag around both thresholds, trailing bounce on short menus,
cancellation and interruption.

**Simulator recordings.** Both videos are side-by-side captures from the
iPhone 17 simulator (iOS 27.2, text size `accessibility-large` so the
menu overflows). Each side replays the same touch script.

Scroll-to-dismiss handoff. Left: base (`9bcb3e45a`), the body only
bounces and the sheet never moves. Right: branch at `23c31e2e1`, the
same touches pull the sheet down, restore it on reversal, and dismiss it
on a slow drag past half and on a flick.


https://github.com/user-attachments/assets/09b0cfc2-ed61-4822-8b35-b80d0f47e830

Scroll up slightly, then swipe down hard. Left: `23c31e2e1`, the menu
settles back open after both swipes. Right: `558a79710` (branch head),
the same touches close it, as a new touch and without lifting; the final
slow return across the top stays open on both sides.


https://github.com/user-attachments/assets/068faff4-a4d4-478f-aaf4-fc65c644632f

**Limits of this validation:**

- The touches were scripted synthetic touch events (linear motion, exact
timing), not a human finger.
- Both sides ran a dummy-data harness that calls the production
`showMessageActions` for a placeholder message, not the real channel
page. The harness is not part of this PR.
- Android, a physical device, VoiceOver and reduced motion were not
exercised natively; they are covered by widget tests only.
- The right side of the first video was built from `23c31e2e1`, one
commit before the branch head. `558a79710` changes only releases with a
fast downward velocity after content was scrolled. The gestures in that
video are slow or held releases and gestures that start at the top,
which resolve the same way under both rules; this follows from the
release rule and was not re-recorded.
- A human has not yet confirmed the behaviour by hand.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Matt Toohey <contact@matttoohey.com>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
This commit is contained in:
Matt Toohey
2026-11-20 14:41:01 +11:00
committed by GitHub
parent 8d4b30176b
commit 5e8fa368a4
7 changed files with 2197 additions and 412 deletions

View File

@@ -0,0 +1,118 @@
# Message-action body scroll handoff
Only `showMessageActions` opts into `ModalScrollHandoff`. Image actions and other
sheets keep their existing scrolling. The helper retains the modal route,
shared chrome, stock handle drag, barrier dismissal, and accessibility action.
The explicit, non-primary, downward vertical scroll position allocates a user
update between content and the existing route animation. Crossing the content's
leading edge spends that update's remainder on sheet translation; reversing
spends the remainder on content after fully reopening. Nested scroll positions
never feed this allocator. Programmatic and ballistic scrolling cannot start a
sheet drag. There is no extra gesture recognizer or replacement route.
The enclosing `BottomSheet` supplies its animation, full rendered height, drag
start/end callbacks, and cancellation close callback. Entrance must finish
before handoff can begin. Geometry is read again for every update. The route
owns animation disposal; the helper owns only its controller and gesture token.
Release policy follows Flutter 3.47.9's `material/bottom_sheet.dart`, with one
deliberate difference. As in the stock sheet, a release with the sheet displaced
closes when downward velocity is strictly above 700 logical px/s, and otherwise
when progress is strictly below 0.5 of the sheet height. The difference: a raw
upward velocity strictly below -700 vetoes the progress rule.
Where the gesture began does not matter. A swipe that starts with content
scrolled away from the top, by a little or a lot, or that scrolls content down
and back in the same touch, closes on velocity like one that began at the top,
provided the finger has carried content to the top and displaced the sheet by
the time it lifts. The guards against accidental dismissal are these:
- A release with the sheet not displaced by the finger never closes, however
fast. A flick that leaves content short of the top only scrolls.
- Ballistic and programmatic scrolling cannot start a sheet drag, so a content
fling that reaches the top after the finger lifted stops there.
- Scroll momentum carried into a new touch is not added to the release
velocity.
- A slow return across the top that displaces the sheet less than half way
settles open.
A parity test releases the same pointer gestures through the stock sheet drag
and through the body, so a Flutter upgrade that moves either stock threshold
fails it. The wrapper captures the raw terminal event before Flutter negates it or
adds carried scroll momentum. Cancellations and activity interruptions reopen,
including when another active route covers the sheet. Flutter delivers a
system-cancelled pointer to an accepted drag as an ordinary end, so the body
listens for the pointer cancellation itself and treats that end as an
interruption: a deep pull that the system cancels reopens. Departing routes are not
reopened. Reduced motion preserves direct manipulation but settles immediately.
The route close callback returns null, leaving message selection and composer
focus restoration with their existing owners.
The sheet has one drag owner at a time. A body gesture owns the sheet from its
first sheet movement until it settles it. If anything else moves the route
animation meanwhile, such as a second finger dragging the handle, the body
gesture gives the sheet up for the rest of that touch: it neither moves nor
settles the sheet, and only scrolls content. The handle's own release then
settles the sheet. A body gesture cannot begin a sheet drag while the sheet is
already displaced, and a body touch that lands during a handle drag joins the
stock sheet recognizer rather than the scroll position.
Content shorter than its viewport still uses always-scrollable physics on
purpose: a downward body drag on a short menu, such as the system-message
reaction menu, moves the sheet exactly as a drag on the handle does.
## Automated validation
From the repository root:
```sh
. ./bin/activate-hermit
just mobile-install mobile-check mobile-test
```
Focused journeys run with:
```sh
. ./bin/activate-hermit
cd mobile
flutter test test/features/channels/message_actions_test.dart \
test/shared/widgets/modal_scroll_handoff_test.dart
```
The message-action journey uses a 375×667 viewport, 2× text, management
permissions, and reminder/thread actions on iOS and Android settings. The
shared tests cover the release boundaries, releases after scrolled content
(new touch and same touch), stock parity, interruptions, bouncing offsets,
carried momentum, a real pointer cancellation, a second finger on the handle,
layout changes, short bodies, reduced motion, and nested
scrolling.
## Manual native checklist
Widget tests are not native confirmation. Run `just mobile-dev` against an
accessible community, with a nonempty focused draft, and long-press an owned
message. Increase text size until the lower actions start offscreen.
1. Scroll to the last action and back; every action is reachable.
2. From the top, drag the body down slowly past half the sheet and release: the
menu closes. Release before half: it settles open.
3. From the top, flick the body down: the menu closes.
4. Scroll the list up slightly and lift, then swipe the body down hard so the
sheet moves: the menu closes. Repeat after scrolling to the last action.
5. From the top, in one touch, drag up to scroll the list slightly, then swipe
down hard without lifting so the sheet moves: the menu closes.
6. Scroll down and lift, then flick so the list flings to the top after the
finger has lifted: the sheet does not move and the menu stays open. Drag
slowly back across the top so the sheet moves less than half way and
release: it settles open.
7. Cross the top without lifting, then reverse: the sheet reopens fully before
content scrolls, and it follows the finger throughout.
8. Pull the sheet down, then release with a strong upward flick: it stays open.
9. Compare the same drags on the handle; check barrier tap and system back.
10. Settling open leaves composer focus alone; dismissing restores it. The
draft survives both.
11. Pull the body down slightly and hold. With a second finger drag the handle
past half way, then lift the body finger: the menu stays under the handle
finger. Lift that finger above half way: the menu settles open.
12. Repeat on a thread message and on the short system-message reaction menu.

View File

@@ -23,6 +23,7 @@ import '../../shared/emoji/native_emoji_glyph.dart';
import '../../shared/emoji/emoji_data_provider.dart';
import '../../shared/widgets/sheet_action_section.dart';
import '../../shared/widgets/modal_presentation.dart';
import '../../shared/widgets/modal_scroll_handoff.dart';
import '../../shared/reminders/remind_me_later_sheet.dart';
import '../../shared/reminders/reminder_service.dart';
import 'channel_management_provider.dart';
@@ -107,7 +108,7 @@ Future<void> showMessageActions({
constraints: BoxConstraints(
maxHeight: MediaQuery.sizeOf(sheetContext).height * 0.7,
),
child: SingleChildScrollView(
child: ModalScrollHandoff(
child: Padding(
padding: const EdgeInsets.fromLTRB(
Grid.gutter,

View File

@@ -0,0 +1,346 @@
import 'dart:math' as math;
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
/// A single vertical modal body whose leading-edge drags move its existing
/// bottom-sheet route. Only this explicit scroll position participates; nested
/// scrollables and horizontal gestures retain their ordinary behavior.
///
/// The route owns its animation and chrome. Outside an enabled, fully entered
/// modal bottom sheet this is an ordinary, always-scrollable body.
class ModalScrollHandoff extends HookConsumerWidget {
/// Creates an opt-in body for a modal bottom sheet.
const ModalScrollHandoff({super.key, required this.child});
/// The scrollable body, excluding the sheet's handle and header.
final Widget child;
@override
Widget build(BuildContext context, WidgetRef ref) {
final controller = useMemoized(() => _HandoffController(() => context));
useEffect(() => controller.dispose, [controller]);
// A system-cancelled pointer reaches the scroll drag as an ordinary end.
// This listener sees each pointer event before the drag recognizer does,
// so the release can tell a cancellation from a lift.
return Listener(
onPointerDown: (_) => controller.pointerCancelled = false,
onPointerMove: (_) => controller.pointerCancelled = false,
onPointerUp: (_) => controller.pointerCancelled = false,
onPointerCancel: (_) => controller.pointerCancelled = true,
child: SingleChildScrollView(
controller: controller,
primary: false,
physics: const AlwaysScrollableScrollPhysics(),
// Like a primary scroll view, keep nested scrollables off the route's
// controller, which this body's position joins below.
child: PrimaryScrollController.none(child: child),
),
);
}
}
// Flutter 3.47.9, material/bottom_sheet.dart: _kMinFlingVelocity and
// _kCloseProgressThreshold. Keep the body policy aligned with the stock handle,
// except that a deliberate upward release vetoes the distance-based close.
const _minFlingVelocity = 700.0;
const _closeProgressThreshold = 0.5;
class _SheetBinding {
_SheetBinding(this.element, this.route, this.sheet, this.reduceMotion);
final Element element;
final ModalBottomSheetRoute<dynamic> route;
final BottomSheet sheet;
final bool reduceMotion;
AnimationController get animation => sheet.animationController!;
bool get recoverable =>
element.mounted &&
route.isActive &&
animation.status != AnimationStatus.reverse;
bool get current => recoverable && route.isCurrent;
double? get height {
if (!element.mounted) return null;
final box = element.findRenderObject();
if (box is! RenderBox || !box.hasSize) return null;
final height = box.size.height;
return height.isFinite && height > 0 ? height : null;
}
static _SheetBinding? read(BuildContext context) {
if (!context.mounted) return null;
final route = ModalRoute.of(context);
if (route is! ModalBottomSheetRoute || !route.isCurrent) return null;
_SheetBinding? binding;
context.visitAncestorElements((element) {
final widget = element.widget;
if (widget is! BottomSheet) return true;
if (widget.enableDrag && widget.animationController != null) {
binding = _SheetBinding(
element,
route,
widget,
MediaQuery.disableAnimationsOf(context),
);
}
return false;
});
return binding;
}
}
class _HandoffController extends ScrollController {
_HandoffController(this.bodyContext);
final BuildContext Function() bodyContext;
/// Whether the body's most recent pointer event was a cancellation.
bool pointerCancelled = false;
@override
ScrollPosition createScrollPosition(
ScrollPhysics physics,
ScrollContext context,
ScrollPosition? oldPosition,
) => _HandoffPosition(
owner: this,
physics: physics,
context: context,
oldPosition: oldPosition,
);
ScrollController? _route;
// Keyboard ScrollAction targets the route's primary controller while focus
// rests on the modal scope, so the body also joins it, as a primary scroll
// view would.
@override
void attach(ScrollPosition position) {
super.attach(position);
final route = bodyContext()
.findAncestorWidgetOfExactType<PrimaryScrollController>()
?.controller;
if (route == null || route == this) return;
_route = route;
route.attach(position);
}
@override
void detach(ScrollPosition position) {
if (position is _HandoffPosition) position.interrupt();
final route = _route;
if (route != null && route.positions.contains(position)) {
route.detach(position);
}
super.detach(position);
}
}
class _HandoffPosition extends ScrollPositionWithSingleContext {
_HandoffPosition({
required this.owner,
required super.physics,
required super.context,
super.oldPosition,
});
final _HandoffController owner;
Object? _gesture;
_SheetBinding? _sheet;
DragStartDetails? _start;
bool _suppressBallistic = false;
bool _movingSheet = false;
// A terminal token is cleared before delegating end/cancel: Flutter disposes
// its ScrollDragController during normal activity replacement as well.
void interrupt() => _finish(null);
@override
void absorb(ScrollPosition other) {
if (other is _HandoffPosition) other.interrupt();
super.absorb(other);
}
@override
void beginActivity(ScrollActivity? newActivity) {
if (newActivity != null) interrupt();
super.beginActivity(newActivity);
}
@override
Drag drag(DragStartDetails details, VoidCallback dragCancelCallback) {
interrupt();
final drag = super.drag(details, dragCancelCallback);
// A displaced release that never went ballistic belongs to the old gesture.
_suppressBallistic = false;
// Semantics scroll actions synthesize a drag without a pointer kind; they
// only scroll content, never the sheet.
if (details.kind == null) return drag;
final token = Object();
_gesture = token;
_start = details;
return _HandoffDrag(drag, (end) {
if (_gesture != token) return;
// A cancelled pointer restores the sheet like any other interruption.
_finish(owner.pointerCancelled ? null : end);
});
}
// The sheet has one drag owner. This gesture owns it from its first sheet
// movement until it settles the sheet, or until anything else moves the
// route animation: a second finger on the handle, or the route closing. It
// then gives the sheet up for good, neither moving nor settling it, and
// only scrolls content. It cannot begin while the sheet is displaced.
void _yieldSheet() {
if (_movingSheet) return;
_sheet?.animation.removeListener(_yieldSheet);
_sheet = null;
_gesture = null;
_start = null;
}
@override
void applyUserOffset(double delta) {
if (_gesture == null ||
axisDirection != AxisDirection.down ||
owner.positions.length != 1) {
super.applyUserOffset(delta);
return;
}
final binding = _sheet ?? _SheetBinding.read(owner.bodyContext());
final height = binding?.height;
if (binding == null ||
!binding.current ||
height == null ||
(_sheet == null && !binding.animation.isCompleted)) {
interrupt();
super.applyUserOffset(delta);
return;
}
updateUserScrollDirection(
delta > 0 ? ScrollDirection.forward : ScrollDirection.reverse,
);
// Repay inherited top bounce before handing any remainder to the route.
// Downward motion while already overscrolled stays with platform physics.
if (pixels < minScrollExtent) {
if (delta >= 0) {
super.applyUserOffset(delta);
return;
}
final repay = math.min(-delta, minScrollExtent - pixels);
setPixels(pixels + repay);
delta += repay;
}
if (delta > 0) {
final content = math.min(delta, math.max(0.0, pixels - minScrollExtent));
setPixels(pixels - content);
delta -= content;
} else if (delta < 0 && _sheet != null) {
final reopen = math.min(-delta, (1 - binding.animation.value) * height);
_moveSheet(binding, reopen / height);
delta += reopen;
}
if (delta > 0) {
_moveSheet(binding, -delta / height);
} else if (delta < 0) {
super.applyUserOffset(delta);
}
}
void _moveSheet(_SheetBinding binding, double progress) {
if (progress == 0) return;
final animation = binding.animation;
if (_sheet == null) {
_sheet = binding;
binding.sheet.onDragStart?.call(_start!);
animation.addListener(_yieldSheet);
}
_movingSheet = true;
try {
animation.value = (animation.value + progress).clamp(0, 1);
} finally {
_movingSheet = false;
}
}
void _finish(DragEndDetails? end) {
_gesture = null;
_start = null;
final binding = _sheet;
_sheet = null;
binding?.animation.removeListener(_yieldSheet);
if (binding == null || !binding.recoverable) return;
final animation = binding.animation;
final displaced = animation.value < 1;
final velocity = end?.velocity.pixelsPerSecond.dy ?? 0.0;
// Only a release with the sheet still displaced by the finger can close.
// Where the gesture began, and whether it scrolled content on the way to
// the top, does not matter.
final closing =
end != null &&
binding.route.isCurrent &&
displaced &&
(velocity > _minFlingVelocity ||
(velocity >= -_minFlingVelocity &&
animation.value < _closeProgressThreshold));
binding.sheet.onDragEnd?.call(end ?? DragEndDetails(), isClosing: closing);
_suppressBallistic = displaced;
if (binding.reduceMotion || animation.duration == Duration.zero) {
animation.value = closing ? 0 : 1;
} else if (closing) {
final height = binding.height;
animation.fling(
velocity: velocity > _minFlingVelocity && height != null
? -velocity / height
: -1,
);
} else {
animation.forward();
}
if (closing) binding.sheet.onClosing();
}
@override
void goBallistic(double velocity) {
// Synthetic ballistic transitions are interruptions, never releases.
interrupt();
final suppress = _suppressBallistic;
_suppressBallistic = false;
super.goBallistic(suppress ? 0 : velocity);
}
@override
void dispose() {
// Never animate a departing route from final disposal.
_gesture = null;
_sheet?.animation.removeListener(_yieldSheet);
_sheet = null;
super.dispose();
}
}
class _HandoffDrag implements Drag {
_HandoffDrag(this.delegate, this.finish);
final Drag delegate;
final void Function(DragEndDetails?) finish;
@override
void update(DragUpdateDetails details) => delegate.update(details);
@override
void end(DragEndDetails details) {
finish(details);
delegate.end(details);
}
@override
void cancel() {
finish(null);
delegate.cancel();
}
}

View File

@@ -0,0 +1,337 @@
part of 'message_actions_test.dart';
void _messageActionsScrollTests() {
for (final (platform, sameTouch) in [
(TargetPlatform.iOS, false),
(TargetPlatform.iOS, true),
(TargetPlatform.android, false),
(TargetPlatform.android, true),
]) {
testWidgets(
'overflowing message actions hand off in both directions: $platform, '
'${sameTouch ? 'same-touch' : 'new-touch'} swipe dismissal',
(tester) async {
debugDefaultTargetPlatformOverride = platform;
tester.view.physicalSize = const Size(375, 667);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
addTearDown(() => debugDefaultTargetPlatformOverride = null);
try {
await _pumpMessageActionsPopover(
tester,
message: _message(rootId: threadIdRootDash1),
prefs: await _mockPrefs(),
canManageMessage: true,
allMessages: [_message()],
reminderService: _stubReminderService(),
textScaler: TextScaler.linear(2),
);
final body = find
.descendant(
of: find.byType(BottomSheet),
matching: find.byType(Scrollable),
)
.first;
final position = tester.state<ScrollableState>(body).position;
expect(position.maxScrollExtent, greaterThan(0));
final sheet = find.byType(BottomSheet);
final animation = tester
.widget<BottomSheet>(sheet)
.animationController!;
final top = tester.getTopLeft(sheet).dy;
final viewport = tester.getRect(body);
final start = Offset(viewport.center.dx, viewport.top + 85);
final gesture = await tester.startGesture(start);
await gesture.moveBy(const Offset(0, -24));
await gesture.moveBy(const Offset(0, -70));
await tester.pump();
expect(position.pixels, greaterThan(0));
expect(animation.value, 1);
// One update repays content and spends its remainder on the whole route.
final offset = position.pixels;
await gesture.moveBy(Offset(0, offset + 40));
await tester.pump();
expect(position.pixels, 0);
expect(tester.getTopLeft(sheet).dy, closeTo(top + 40, 0.1));
// Reverse without lifting: the same update restores route and scrolls.
await gesture.moveBy(const Offset(0, -65));
await tester.pump();
expect(animation.value, 1);
expect(position.pixels, closeTo(25, 0.1));
await gesture.cancel();
await tester.pumpAndSettle();
// Lower management actions really are reachable by touch.
await tester.drag(body, const Offset(0, -900));
await tester.pumpAndSettle();
expect(find.text('Delete message').hitTestable(), findsOneWidget);
position.jumpTo(0);
await tester.pumpAndSettle();
await tester.drag(
find.byKey(const ValueKey('quick-reaction-👍')),
const Offset(-120, 0),
);
await tester.pumpAndSettle();
expect(animation.value, 1);
expect(position.pixels, 0);
// A short slow pull settles open rather than completing the modal future.
final pull = await tester.startGesture(start);
await pull.moveBy(const Offset(0, 24));
await pull.moveBy(const Offset(0, 60));
await tester.pump();
expect(animation.value, lessThan(1));
await tester.pump(const Duration(milliseconds: 200));
await pull.up();
await tester.pumpAndSettle();
expect(animation.value, 1);
// A system-cancelled touch after a deep pull restores the menu.
final cancelled = await tester.startGesture(start);
await cancelled.moveBy(const Offset(0, 24));
await cancelled.moveBy(Offset(0, tester.getSize(sheet).height * 0.7));
await tester.pump();
expect(animation.value, lessThan(0.5));
await cancelled.cancel();
await tester.pumpAndSettle();
expect(animation.value, 1);
// A second finger on the handle takes the sheet over: lifting the
// body finger leaves it with the handle, which then settles it open.
final held = await tester.startGesture(start);
await held.moveBy(const Offset(0, 24));
await held.moveBy(const Offset(0, 40));
final handle = await tester.startGesture(
tester.getCenter(
find.byKey(const ValueKey('buzz-sheet-drag-handle')),
),
);
await handle.moveBy(const Offset(0, 24));
await handle.moveBy(Offset(0, tester.getSize(sheet).height * 0.6));
await tester.pump();
final displaced = animation.value;
expect(displaced, lessThan(0.5));
await held.up();
await tester.pumpAndSettle();
expect(animation.value, displaced);
await handle.moveBy(Offset(0, -tester.getSize(sheet).height * 0.5));
await handle.up();
await tester.pumpAndSettle();
expect(animation.value, 1);
expect(position.pixels, 0);
// Scroll the list up slightly, then swipe down hard: the finger
// carries content to the top, pulls the sheet a little and the
// release velocity dismisses the menu. Either as a new touch after
// lifting or without lifting at all.
final touch = await tester.startGesture(
Offset(start.dx, viewport.bottom - 40),
);
for (var i = 1; i <= 6; i++) {
await touch.moveBy(
const Offset(0, -8),
timeStamp: Duration(milliseconds: 40 * i),
);
}
await tester.pump(const Duration(milliseconds: 200));
var swipe = touch;
var elapsed = 440;
if (!sameTouch) {
await touch.up(timeStamp: const Duration(milliseconds: 440));
await tester.pumpAndSettle();
swipe = await tester.startGesture(start);
elapsed = 0;
}
final scrolled = position.pixels;
expect(scrolled, inExclusiveRange(5, 50));
for (var i = 1; i <= 8; i++) {
await swipe.moveBy(
Offset(0, (scrolled + 80) / 8),
timeStamp: Duration(milliseconds: elapsed + 8 * i),
);
}
await tester.pump();
expect(position.pixels, 0);
expect(animation.value, inExclusiveRange(0.5, 1));
await swipe.up(timeStamp: Duration(milliseconds: elapsed + 64));
await tester.pumpAndSettle();
expect(sheet, findsNothing);
} finally {
debugDefaultTargetPlatformOverride = null;
}
},
);
}
for (final platform in [TargetPlatform.iOS, TargetPlatform.android]) {
testWidgets('overflowing message actions keep keyboard and screen-reader '
'scrolling: $platform', (tester) async {
final semantics = tester.ensureSemantics();
debugDefaultTargetPlatformOverride = platform;
tester.view.physicalSize = const Size(375, 667);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
try {
await _pumpMessageActionsPopover(
tester,
message: _message(rootId: threadIdRootDash1),
prefs: await _mockPrefs(),
canManageMessage: true,
allMessages: [_message()],
reminderService: _stubReminderService(),
textScaler: TextScaler.linear(2),
);
final sheet = find.byType(BottomSheet);
final body = find
.descendant(of: sheet, matching: find.byType(Scrollable))
.first;
final position = tester.state<ScrollableState>(body).position;
expect(position.maxScrollExtent, greaterThan(0));
// Page Down from the initial focus on the modal scope scrolls the body.
await tester.sendKeyEvent(LogicalKeyboardKey.pageDown);
await tester.pumpAndSettle();
expect(position.pixels, greaterThan(0));
// A screen-reader scroll toward the top only scrolls content, even
// when its fixed step overshoots the top by more than half the sheet.
position.jumpTo(16);
await tester.pumpAndSettle();
final scrollNode = find.semantics
.byAction(ui.SemanticsAction.scrollDown)
.evaluate()
.single;
tester.binding.performSemanticsAction(
ui.SemanticsActionEvent(
type: ui.SemanticsAction.scrollDown,
viewId: tester.view.viewId,
nodeId: scrollNode.id,
),
);
await tester.pumpAndSettle();
expect(sheet, findsOneWidget);
expect(position.pixels, 0);
} finally {
debugDefaultTargetPlatformOverride = null;
semantics.dispose();
}
});
}
for (final outcome in [
'cancel',
'unfocused',
'slow',
'fast',
'upward',
'barrier',
'back',
'action',
'reaction',
'picker',
]) {
testWidgets('message drag result, draft, focus and popover: $outcome', (
tester,
) async {
final focus = FocusNode();
addTearDown(focus.dispose);
final actions = _RecordingReactionActions();
final harness = await _pumpMessageActionsPopover(
tester,
message: _message(),
prefs: await _mockPrefs(),
composerFocusNode: focus,
composerInitiallyFocused: outcome != 'unfocused',
composerDraft: 'Keep this draft',
launcherOnNestedRoute: true,
createChannelActions: (_) => actions,
emojiDataset: outcome == 'picker'
? EmojiDataset.fromJson(
jsonDecode(File(emojiDataAssetPath).readAsStringSync())
as Map<String, dynamic>,
)
: null,
);
final sheet = find.byType(BottomSheet);
final animation = tester.widget<BottomSheet>(sheet).animationController!;
final body = find
.descendant(of: sheet, matching: find.byType(Scrollable))
.first;
final position = tester.state<ScrollableState>(body).position;
// Exact raw release policy uses the production position and Drag wrapper,
// independent of platform velocity-estimator heuristics.
final drag = position.drag(
DragStartDetails(kind: PointerDeviceKind.touch),
() {},
);
final height = tester.getSize(sheet).height;
final distance = ['slow', 'upward', 'cancel'].contains(outcome)
? height * 0.65
: 50.0;
drag.update(
DragUpdateDetails(
globalPosition: Offset.zero,
delta: Offset(0, distance),
primaryDelta: distance,
),
);
await tester.pump();
expect(animation.value, lessThan(1));
expect(focus.hasFocus, isFalse);
if (outcome == 'cancel') {
drag.cancel();
} else {
final velocity = outcome == 'fast'
? 701.0
: outcome == 'upward'
? -701.0
: 0.0;
drag.end(
DragEndDetails(
velocity: Velocity(pixelsPerSecond: Offset(0, velocity)),
primaryVelocity: velocity,
),
);
}
await tester.pumpAndSettle();
if (outcome == 'slow' || outcome == 'fast') {
expect(sheet, findsNothing);
expect(focus.hasFocus, isTrue);
} else {
expect(animation.value, 1);
expect(focus.hasFocus, isFalse);
switch (outcome) {
case 'barrier':
await tester.tapAt(const Offset(5, 5));
case 'back':
await tester.binding.handlePopRoute();
case 'action':
await tester.tap(find.text('Copy text'));
case 'reaction':
await tester.tap(find.byKey(const ValueKey('quick-reaction-👍')));
case 'picker':
await tester.tap(find.byKey(const ValueKey('quick-reaction-more')));
default:
await tester.tapAt(const Offset(5, 5));
}
await tester.pumpAndSettle();
expect(
focus.hasFocus,
!['action', 'reaction', 'picker', 'unfocused'].contains(outcome),
);
if (outcome == 'reaction') expect(actions.added, ['👍']);
if (outcome == 'picker') {
expect(find.text('Copy text'), findsNothing);
expect(find.byType(BottomSheet), findsOneWidget);
await tester.tapAt(const Offset(5, 5));
await tester.pumpAndSettle();
} else {
expect(sheet, findsNothing);
}
}
expect(find.text('Keep this draft'), findsOneWidget);
expect(harness.sourceHidden.value, isFalse);
expect(
find.byKey(const ValueKey('message-actions-underlying-page')),
findsOneWidget,
);
expect(
find.byKey(const ValueKey('message-actions-root-page')),
findsNothing,
);
});
}
}

View File

@@ -3,7 +3,11 @@ import 'package:buzz/features/channels/thread_follows/thread_follows_storage.dar
import 'package:buzz/shared/widgets/sheet_action_section.dart';
import 'package:buzz/shared/widgets/app_list_card.dart';
import 'dart:ui' as ui;
import 'dart:convert';
import 'dart:io';
import 'package:buzz/shared/emoji/emoji_data.dart';
import 'package:flutter/services.dart';
import 'package:buzz/shared/emoji/emoji_data_provider.dart';
import 'package:buzz/features/channels/channel.dart';
import 'package:buzz/features/channels/channel_management_provider.dart';
@@ -18,6 +22,7 @@ import 'package:buzz/shared/reminders/reminder_service.dart';
import 'package:buzz/shared/relay/relay.dart';
import 'package:buzz/shared/theme/theme.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -30,420 +35,13 @@ import 'package:shared_preferences/shared_preferences.dart';
import '../../helpers/thread_ids.dart';
part 'message_actions_scroll_journeys.dart';
part 'message_actions_test_helpers.dart';
const _channelId = 'chan-1';
TimelineMessage _message({
String id = 'msg-1',
String pubkey = 'alice',
int createdAt = 1000,
bool isSystem = false,
String? rootId,
List<List<String>> tags = const [],
List<TimelineReaction> reactions = const [],
}) => TimelineMessage(
id: id,
pubkey: pubkey,
createdAt: createdAt,
content: 'hello world',
isSystem: isSystem,
rootId: rootId,
tags: tags,
reactions: reactions,
);
class _RecordingReactionActions implements ChannelActions {
final added = <String>[];
final targetAuthors = <String>[];
final removed = <String>[];
@override
Future<void> addReaction(
String eventId,
String emoji, {
required String targetAuthor,
}) async {
added.add(emoji);
targetAuthors.add(targetAuthor);
}
@override
Future<void> removeReaction(String eventId, String emoji) async =>
removed.add(eventId);
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
final _listedChannel = Channel(
id: _channelId,
name: 'general',
channelType: 'stream',
visibility: 'open',
description: '',
createdBy: 'creator',
createdAt: DateTime(2026),
memberCount: 2,
isMember: true,
);
class _ListedChannelsNotifier extends ChannelsNotifier {
@override
Future<List<Channel>> build() async => [_listedChannel];
}
class _FakeReadStateNotifier extends ReadStateNotifier {
final ReadStateState _initialState;
final Map<String, int> markedRead = {};
final List<String> markedUnread = [];
_FakeReadStateNotifier(this._initialState);
@override
ReadStateState build() => _initialState;
@override
void markContextRead(
String contextId,
int unixTimestamp, {
bool clearForcedMessages = false,
bool explicit = false,
}) {
markedRead[contextId] = unixTimestamp;
var forced = {
for (final entry in state.forcedUnreadContexts.entries)
if (entry.key != contextId) entry.key: entry.value,
};
if (clearForcedMessages) {
forced = {
for (final entry in forced.entries)
if (entry.value != contextId) entry.key: entry.value,
};
}
state = _withForced(forced).copyWithContext(contextId, unixTimestamp);
}
@override
bool markContextUnread(
String contextId, {
required String channelId,
String? threadRootId,
bool channelCatchUp = false,
}) {
markedUnread.add(contextId);
state = _withForced({...state.forcedUnreadContexts, contextId: channelId});
return true;
}
@override
Future<bool> setThreadFollow(
String channelId,
String rootId,
bool follow,
) async {
state = ReadStateState(
isReady: state.isReady,
pubkey: state.pubkey,
contexts: state.contexts,
version: state.version + 1,
forcedUnreadContexts: state.forcedUnreadContexts,
threadFollows: {
...state.threadFollows,
threadFollowKey(channelId, rootId): (follow: follow, at: 1),
},
threadFollowsIncomplete: false,
);
return true;
}
ReadStateState _withForced(Map<String, String> forced) => ReadStateState(
isReady: state.isReady,
pubkey: state.pubkey,
contexts: state.contexts,
version: state.version + 1,
forcedUnreadContexts: Map.unmodifiable(forced),
);
}
ReadStateState _readState(Map<String, int> contexts, {bool isReady = true}) =>
ReadStateState(
isReady: isReady,
pubkey: 'self',
contexts: contexts,
version: 1,
);
Future<SharedPreferences> _mockPrefs() async {
SharedPreferences.setMockInitialValues({});
return SharedPreferences.getInstance();
}
/// A [ReminderService] whose constructor dependencies are inert until used —
/// enough for visibility checks on the "Remind me" fast action.
ReminderService _stubReminderService() {
final keys = nostr.Keys.generate();
return ReminderService(
signedEventRelay: SignedEventRelay(
session: RelaySessionNotifier(),
nsec: keys.nsec,
),
crypto: ReminderCrypto(keys.nsec, keys.public),
);
}
Future<void> _pumpSheet(
WidgetTester tester, {
required TimelineMessage message,
required SharedPreferences prefs,
ReadStateNotifier Function()? readStateOverride,
bool canManageMessage = false,
List<TimelineMessage>? allMessages,
ReminderService? reminderService,
Rect? anchorRect,
bool nativePresentation = false,
String? currentPubkey = 'self',
bool listChannel = false,
}) async {
Future<void>? presentation;
await tester.pumpWidget(
ProviderScope(
overrides: [
savedPrefsProvider.overrideWithValue(prefs),
myPubkeyProvider.overrideWithValue('self'),
readStateProvider.overrideWith(
readStateOverride ??
() => _FakeReadStateNotifier(
_readState(const {_channelId: 100000}),
),
),
// No signing identity → "Remind me" hidden by default; individual
// tests opt in by passing a stub service.
reminderServiceProvider.overrideWithValue(reminderService),
if (listChannel)
channelsProvider.overrideWith(_ListedChannelsNotifier.new),
],
child: MaterialApp(
theme: AppTheme.light(),
home: Scaffold(
body: Consumer(
builder: (context, ref, _) {
// The channel page keeps the channel list alive.
if (listChannel) ref.watch(channelsProvider);
return TextButton(
onPressed: () => presentation = showMessageActions(
context: context,
ref: ref,
message: message,
channelId: _channelId,
canManageMessage: canManageMessage,
anchorRect: anchorRect,
captureAnchorSnapshot: nativePresentation
? _testMessageSnapshot
: null,
allMessages: allMessages,
currentPubkey: currentPubkey,
isMember: true,
),
child: const Text('open'),
);
},
),
),
),
),
);
if (listChannel) await tester.pump();
if (nativePresentation) {
await tester.runAsync(() async {
await tester.tap(find.text('open'));
await presentation;
});
} else {
await tester.tap(find.text('open'));
}
await tester.pumpAndSettle();
}
Future<void> _pumpImageSheet(
WidgetTester tester, {
required TimelineMessage message,
bool canManageMessage = false,
http.Client? mediaClient,
}) async {
await tester.pumpWidget(
ProviderScope(
overrides: [
if (mediaClient != null)
mediaHttpClientProvider.overrideWithValue(mediaClient),
],
child: MaterialApp(
theme: AppTheme.light(),
home: Scaffold(
body: Consumer(
builder: (context, ref, _) => TextButton(
onPressed: () => showImageActions(
context: context,
ref: ref,
message: message,
channelId: _channelId,
imageUrl: 'https://example.com/photo.png',
canManageMessage: canManageMessage,
),
child: const Text('open image actions'),
),
),
),
),
),
);
await tester.tap(find.text('open image actions'));
await tester.pumpAndSettle();
}
Future<ui.Image> _testMessageSnapshot() async {
final recorder = ui.PictureRecorder();
final canvas = ui.Canvas(recorder);
canvas.drawRect(
const Rect.fromLTWH(0, 0, 300, 72),
ui.Paint()..color = const Color(0xffeeeeee),
);
return recorder.endRecording().toImage(300, 72);
}
class _MessageActionsPopoverHarness {
final ProviderContainer container;
final ValueNotifier<bool> sourceHidden;
const _MessageActionsPopoverHarness({
required this.container,
required this.sourceHidden,
});
}
Future<_MessageActionsPopoverHarness> _pumpMessageActionsPopover(
WidgetTester tester, {
required TimelineMessage message,
required SharedPreferences prefs,
ReadStateNotifier Function()? readStateOverride,
bool canManageMessage = false,
List<TimelineMessage>? allMessages,
ReminderService? reminderService,
bool disableAnimations = false,
EdgeInsets viewInsets = EdgeInsets.zero,
TextScaler textScaler = TextScaler.noScaling,
Future<ui.Image> Function()? captureAnchorSnapshot,
FocusNode? composerFocusNode,
bool composerInitiallyFocused = false,
bool launcherOnNestedRoute = false,
ChannelActions Function(Ref ref)? createChannelActions,
Rect anchorRect = const Rect.fromLTWH(32, 260, 300, 72),
String? currentPubkey = 'self',
bool listChannel = false,
}) async {
final sourceHidden = ValueNotifier(false);
Widget launcherPage() => Scaffold(
key: const ValueKey('message-actions-underlying-page'),
body: Consumer(
builder: (context, ref, _) {
// The channel page keeps the channel list alive.
if (listChannel) ref.watch(channelsProvider);
return Column(
children: [
if (composerFocusNode != null)
TextField(focusNode: composerFocusNode),
TextButton(
key: const ValueKey('open-message-actions-popover'),
onPressed: () => showMessageActions(
context: context,
ref: ref,
message: message,
channelId: _channelId,
canManageMessage: canManageMessage,
allMessages: allMessages,
currentPubkey: currentPubkey,
isMember: true,
anchorRect: anchorRect,
captureAnchorSnapshot:
captureAnchorSnapshot ?? _testMessageSnapshot,
onPopoverPreviewVisibilityChanged: (visible) =>
sourceHidden.value = visible,
onPopoverDismissed: () => sourceHidden.value = false,
composerFocusNode: composerFocusNode,
restoreComposerFocus: composerFocusNode?.requestFocus,
),
child: const Text('open message actions'),
),
],
);
},
),
);
await tester.pumpWidget(
ProviderScope(
overrides: [
savedPrefsProvider.overrideWithValue(prefs),
myPubkeyProvider.overrideWithValue('self'),
readStateProvider.overrideWith(
readStateOverride ??
() => _FakeReadStateNotifier(
_readState(const {_channelId: 100000}),
),
),
reminderServiceProvider.overrideWithValue(reminderService),
if (createChannelActions != null)
channelActionsProvider.overrideWith(createChannelActions),
if (listChannel)
channelsProvider.overrideWith(_ListedChannelsNotifier.new),
],
child: MaterialApp(
theme: AppTheme.light(),
builder: (context, child) => MediaQuery(
data: MediaQuery.of(context).copyWith(
disableAnimations: disableAnimations,
viewInsets: viewInsets,
textScaler: textScaler,
),
child: child!,
),
home: launcherOnNestedRoute
? Builder(
builder: (context) => Scaffold(
key: const ValueKey('message-actions-root-page'),
body: TextButton(
key: const ValueKey('push-message-actions-launcher'),
onPressed: () => Navigator.of(context).push(
MaterialPageRoute<void>(builder: (_) => launcherPage()),
),
child: const Text('push launcher'),
),
),
)
: launcherPage(),
),
),
);
if (launcherOnNestedRoute) {
await tester.tap(
find.byKey(const ValueKey('push-message-actions-launcher')),
);
await tester.pumpAndSettle();
}
if (composerInitiallyFocused) {
composerFocusNode!.requestFocus();
await tester.pump();
}
if (listChannel) await tester.pump();
await tester.tap(find.byKey(const ValueKey('open-message-actions-popover')));
await tester.pumpAndSettle();
final container = ProviderScope.containerOf(
tester.element(find.byKey(const ValueKey('open-message-actions-popover'))),
);
return _MessageActionsPopoverHarness(
container: container,
sourceHidden: sourceHidden,
);
}
void main() {
_messageActionsScrollTests();
testWidgets(
'quick reactions show selection, label controls, and remove our reaction',
(tester) async {

View File

@@ -0,0 +1,423 @@
part of 'message_actions_test.dart';
TimelineMessage _message({
String id = 'msg-1',
String pubkey = 'alice',
int createdAt = 1000,
bool isSystem = false,
String? rootId,
List<List<String>> tags = const [],
List<TimelineReaction> reactions = const [],
}) => TimelineMessage(
id: id,
pubkey: pubkey,
createdAt: createdAt,
content: 'hello world',
isSystem: isSystem,
rootId: rootId,
tags: tags,
reactions: reactions,
);
class _RecordingReactionActions implements ChannelActions {
final added = <String>[];
final targetAuthors = <String>[];
final removed = <String>[];
@override
Future<void> addReaction(
String eventId,
String emoji, {
required String targetAuthor,
}) async {
added.add(emoji);
targetAuthors.add(targetAuthor);
}
@override
Future<void> removeReaction(String eventId, String emoji) async =>
removed.add(eventId);
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
final _listedChannel = Channel(
id: _channelId,
name: 'general',
channelType: 'stream',
visibility: 'open',
description: '',
createdBy: 'creator',
createdAt: DateTime(2026),
memberCount: 2,
isMember: true,
);
class _ListedChannelsNotifier extends ChannelsNotifier {
@override
Future<List<Channel>> build() async => [_listedChannel];
}
class _FakeReadStateNotifier extends ReadStateNotifier {
final ReadStateState _initialState;
final Map<String, int> markedRead = {};
final List<String> markedUnread = [];
_FakeReadStateNotifier(this._initialState);
@override
ReadStateState build() => _initialState;
@override
void markContextRead(
String contextId,
int unixTimestamp, {
bool clearForcedMessages = false,
bool explicit = false,
}) {
markedRead[contextId] = unixTimestamp;
var forced = {
for (final entry in state.forcedUnreadContexts.entries)
if (entry.key != contextId) entry.key: entry.value,
};
if (clearForcedMessages) {
forced = {
for (final entry in forced.entries)
if (entry.value != contextId) entry.key: entry.value,
};
}
state = _withForced(forced).copyWithContext(contextId, unixTimestamp);
}
@override
bool markContextUnread(
String contextId, {
required String channelId,
String? threadRootId,
bool channelCatchUp = false,
}) {
markedUnread.add(contextId);
state = _withForced({...state.forcedUnreadContexts, contextId: channelId});
return true;
}
@override
Future<bool> setThreadFollow(
String channelId,
String rootId,
bool follow,
) async {
state = ReadStateState(
isReady: state.isReady,
pubkey: state.pubkey,
contexts: state.contexts,
version: state.version + 1,
forcedUnreadContexts: state.forcedUnreadContexts,
threadFollows: {
...state.threadFollows,
threadFollowKey(channelId, rootId): (follow: follow, at: 1),
},
threadFollowsIncomplete: false,
);
return true;
}
ReadStateState _withForced(Map<String, String> forced) => ReadStateState(
isReady: state.isReady,
pubkey: state.pubkey,
contexts: state.contexts,
version: state.version + 1,
forcedUnreadContexts: Map.unmodifiable(forced),
);
}
ReadStateState _readState(Map<String, int> contexts, {bool isReady = true}) =>
ReadStateState(
isReady: isReady,
pubkey: 'self',
contexts: contexts,
version: 1,
);
Future<SharedPreferences> _mockPrefs() async {
SharedPreferences.setMockInitialValues({});
return SharedPreferences.getInstance();
}
/// A [ReminderService] whose constructor dependencies are inert until used —
/// enough for visibility checks on the "Remind me" fast action.
ReminderService _stubReminderService() {
final keys = nostr.Keys.generate();
return ReminderService(
signedEventRelay: SignedEventRelay(
session: RelaySessionNotifier(),
nsec: keys.nsec,
),
crypto: ReminderCrypto(keys.nsec, keys.public),
);
}
Future<void> _pumpSheet(
WidgetTester tester, {
required TimelineMessage message,
required SharedPreferences prefs,
ReadStateNotifier Function()? readStateOverride,
bool canManageMessage = false,
List<TimelineMessage>? allMessages,
ReminderService? reminderService,
Rect? anchorRect,
bool nativePresentation = false,
String? currentPubkey = 'self',
bool listChannel = false,
}) async {
Future<void>? presentation;
await tester.pumpWidget(
ProviderScope(
overrides: [
savedPrefsProvider.overrideWithValue(prefs),
myPubkeyProvider.overrideWithValue('self'),
readStateProvider.overrideWith(
readStateOverride ??
() => _FakeReadStateNotifier(
_readState(const {_channelId: 100000}),
),
),
// No signing identity → "Remind me" hidden by default; individual
// tests opt in by passing a stub service.
reminderServiceProvider.overrideWithValue(reminderService),
if (listChannel)
channelsProvider.overrideWith(_ListedChannelsNotifier.new),
],
child: MaterialApp(
theme: AppTheme.light(),
home: Scaffold(
body: Consumer(
builder: (context, ref, _) {
// The channel page keeps the channel list alive.
if (listChannel) ref.watch(channelsProvider);
return TextButton(
onPressed: () => presentation = showMessageActions(
context: context,
ref: ref,
message: message,
channelId: _channelId,
canManageMessage: canManageMessage,
anchorRect: anchorRect,
captureAnchorSnapshot: nativePresentation
? _testMessageSnapshot
: null,
allMessages: allMessages,
currentPubkey: currentPubkey,
isMember: true,
),
child: const Text('open'),
);
},
),
),
),
),
);
if (listChannel) await tester.pump();
if (nativePresentation) {
await tester.runAsync(() async {
await tester.tap(find.text('open'));
await presentation;
});
} else {
await tester.tap(find.text('open'));
}
await tester.pumpAndSettle();
}
Future<void> _pumpImageSheet(
WidgetTester tester, {
required TimelineMessage message,
bool canManageMessage = false,
http.Client? mediaClient,
}) async {
await tester.pumpWidget(
ProviderScope(
overrides: [
if (mediaClient != null)
mediaHttpClientProvider.overrideWithValue(mediaClient),
],
child: MaterialApp(
theme: AppTheme.light(),
home: Scaffold(
body: Consumer(
builder: (context, ref, _) => TextButton(
onPressed: () => showImageActions(
context: context,
ref: ref,
message: message,
channelId: _channelId,
imageUrl: 'https://example.com/photo.png',
canManageMessage: canManageMessage,
),
child: const Text('open image actions'),
),
),
),
),
),
);
await tester.tap(find.text('open image actions'));
await tester.pumpAndSettle();
}
Future<ui.Image> _testMessageSnapshot() async {
final recorder = ui.PictureRecorder();
final canvas = ui.Canvas(recorder);
canvas.drawRect(
const Rect.fromLTWH(0, 0, 300, 72),
ui.Paint()..color = const Color(0xffeeeeee),
);
return recorder.endRecording().toImage(300, 72);
}
class _MessageActionsPopoverHarness {
final ProviderContainer container;
final ValueNotifier<bool> sourceHidden;
const _MessageActionsPopoverHarness({
required this.container,
required this.sourceHidden,
});
}
Future<_MessageActionsPopoverHarness> _pumpMessageActionsPopover(
WidgetTester tester, {
required TimelineMessage message,
required SharedPreferences prefs,
ReadStateNotifier Function()? readStateOverride,
bool canManageMessage = false,
List<TimelineMessage>? allMessages,
ReminderService? reminderService,
bool disableAnimations = false,
EmojiDataset? emojiDataset,
EdgeInsets viewInsets = EdgeInsets.zero,
TextScaler textScaler = TextScaler.noScaling,
Future<ui.Image> Function()? captureAnchorSnapshot,
FocusNode? composerFocusNode,
bool composerInitiallyFocused = false,
String? composerDraft,
bool launcherOnNestedRoute = false,
ChannelActions Function(Ref ref)? createChannelActions,
Rect anchorRect = const Rect.fromLTWH(32, 260, 300, 72),
String? currentPubkey = 'self',
bool listChannel = false,
}) async {
final sourceHidden = ValueNotifier(false);
final draftController = composerDraft == null
? null
: TextEditingController(text: composerDraft);
if (draftController != null) addTearDown(draftController.dispose);
Widget launcherPage() => Scaffold(
key: const ValueKey('message-actions-underlying-page'),
body: Consumer(
builder: (context, ref, _) {
// The channel page keeps the channel list alive.
if (listChannel) ref.watch(channelsProvider);
return Column(
children: [
if (composerFocusNode != null)
TextField(
focusNode: composerFocusNode,
controller: draftController,
),
TextButton(
key: const ValueKey('open-message-actions-popover'),
onPressed: () => showMessageActions(
context: context,
ref: ref,
message: message,
channelId: _channelId,
canManageMessage: canManageMessage,
allMessages: allMessages,
currentPubkey: currentPubkey,
isMember: true,
anchorRect: anchorRect,
captureAnchorSnapshot:
captureAnchorSnapshot ?? _testMessageSnapshot,
onPopoverPreviewVisibilityChanged: (visible) =>
sourceHidden.value = visible,
onPopoverDismissed: () => sourceHidden.value = false,
composerFocusNode: composerFocusNode,
restoreComposerFocus: composerFocusNode?.requestFocus,
),
child: const Text('open message actions'),
),
],
);
},
),
);
await tester.pumpWidget(
ProviderScope(
overrides: [
if (emojiDataset != null)
emojiDatasetProvider.overrideWith((_) async => emojiDataset),
savedPrefsProvider.overrideWithValue(prefs),
myPubkeyProvider.overrideWithValue('self'),
readStateProvider.overrideWith(
readStateOverride ??
() => _FakeReadStateNotifier(
_readState(const {_channelId: 100000}),
),
),
reminderServiceProvider.overrideWithValue(reminderService),
if (createChannelActions != null)
channelActionsProvider.overrideWith(createChannelActions),
if (listChannel)
channelsProvider.overrideWith(_ListedChannelsNotifier.new),
],
child: MaterialApp(
theme: AppTheme.light(),
builder: (context, child) => MediaQuery(
data: MediaQuery.of(context).copyWith(
disableAnimations: disableAnimations,
viewInsets: viewInsets,
textScaler: textScaler,
),
child: child!,
),
home: launcherOnNestedRoute
? Builder(
builder: (context) => Scaffold(
key: const ValueKey('message-actions-root-page'),
body: TextButton(
key: const ValueKey('push-message-actions-launcher'),
onPressed: () => Navigator.of(context).push(
MaterialPageRoute<void>(builder: (_) => launcherPage()),
),
child: const Text('push launcher'),
),
),
)
: launcherPage(),
),
),
);
if (launcherOnNestedRoute) {
await tester.tap(
find.byKey(const ValueKey('push-message-actions-launcher')),
);
await tester.pumpAndSettle();
}
if (composerInitiallyFocused) {
composerFocusNode!.requestFocus();
await tester.pump();
}
if (listChannel) await tester.pump();
await tester.tap(find.byKey(const ValueKey('open-message-actions-popover')));
await tester.pumpAndSettle();
final container = ProviderScope.containerOf(
tester.element(find.byKey(const ValueKey('open-message-actions-popover'))),
);
return _MessageActionsPopoverHarness(
container: container,
sourceHidden: sourceHidden,
);
}

View File

@@ -0,0 +1,962 @@
import 'package:buzz/shared/theme/theme.dart';
import 'package:buzz/shared/widgets/modal_presentation.dart';
import 'package:buzz/shared/widgets/modal_scroll_handoff.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
const _bodyKey = ValueKey('handoff-body');
const _horizontalKey = ValueKey('horizontal');
const _nestedKey = ValueKey('nested');
// Only the surrounding layout and platform scroll policy vary. The controller,
// position, drag, modal animation, chrome and navigator are all production code.
class _Harness {
final navigator = GlobalKey<NavigatorState>();
final height = ValueNotifier(360.0);
final visible = ValueNotifier(true);
final bouncing = ValueNotifier(false);
AnimationController animation(WidgetTester tester) =>
tester.widget<BottomSheet>(find.byType(BottomSheet)).animationController!;
ScrollPosition position(WidgetTester tester) => tester
.state<ScrollableState>(
find
.descendant(
of: find.byType(ModalScrollHandoff),
matching: find.byType(Scrollable),
)
.first,
)
.position;
double sheetHeight(WidgetTester tester) =>
tester.getSize(find.byType(BottomSheet)).height;
Future<void> open(
WidgetTester tester, {
bool short = false,
bool reducedMotion = false,
bool enableDrag = true,
bool settle = true,
Widget? child,
}) async {
addTearDown(height.dispose);
addTearDown(visible.dispose);
addTearDown(bouncing.dispose);
await tester.pumpWidget(
ProviderScope(
child: MaterialApp(
navigatorKey: navigator,
theme: AppTheme.light(),
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(disableAnimations: reducedMotion),
child: child!,
),
home: Scaffold(
body: Builder(
builder: (context) => TextButton(
onPressed: () => showBuzzModalBottomSheet<void>(
context: context,
title: 'Handoff',
showDragHandle: true,
enableDrag: enableDrag,
isScrollControlled: true,
builder: (_) => ValueListenableBuilder(
valueListenable: height,
builder: (context, height, _) => SizedBox(
height: height,
child: ValueListenableBuilder(
valueListenable: visible,
builder: (context, visible, _) => visible
? ValueListenableBuilder(
valueListenable: bouncing,
builder: (context, bouncing, _) =>
ScrollConfiguration(
behavior: _ScrollPolicy(bouncing),
child: ModalScrollHandoff(
child:
child ??
SizedBox(
key: _bodyKey,
height: short ? 40 : 1400,
width: double.infinity,
child: const Text('Body content'),
),
),
),
)
: const Text('Body removed'),
),
),
),
),
child: const Text('Open'),
),
),
),
),
),
);
await tester.tap(find.text('Open'));
await tester.pump();
if (settle) await tester.pumpAndSettle();
}
Future<void> close(WidgetTester tester) async {
if (navigator.currentState!.canPop()) navigator.currentState!.pop();
await tester.pumpAndSettle();
}
}
class _ScrollPolicy extends MaterialScrollBehavior {
const _ScrollPolicy(this.bouncing);
final bool bouncing;
@override
bool shouldNotify(covariant _ScrollPolicy oldDelegate) =>
bouncing != oldDelegate.bouncing;
@override
ScrollPhysics getScrollPhysics(BuildContext context) =>
bouncing ? const BouncingScrollPhysics() : const ClampingScrollPhysics();
}
Drag _start(ScrollPosition position) =>
position.drag(DragStartDetails(kind: PointerDeviceKind.touch), () {});
void _move(Drag drag, double dy) => drag.update(
DragUpdateDetails(
globalPosition: Offset.zero,
delta: Offset(0, dy),
primaryDelta: dy,
),
);
void _end(Drag drag, double velocity) => drag.end(
DragEndDetails(
velocity: Velocity(pixelsPerSecond: Offset(0, velocity)),
primaryVelocity: velocity,
),
);
void main() {
testWidgets('one drag consumes content, moves route, reopens, then scrolls', (
tester,
) async {
final h = _Harness();
await h.open(tester);
final position = h.position(tester);
final animation = h.animation(tester);
final sheetHeight = h.sheetHeight(tester);
final top = tester.getTopLeft(find.byType(BottomSheet)).dy;
position.jumpTo(80);
final drag = _start(position);
_move(drag, 50);
expect(position.pixels, 30);
expect(animation.value, 1);
_move(drag, 70);
expect(position.pixels, 0);
expect(animation.value, closeTo(1 - 40 / sheetHeight, 1e-9));
await tester.pump();
expect(
tester.getTopLeft(find.byType(BottomSheet)).dy,
closeTo(top + 40, 0.01),
);
_move(drag, -65);
expect(animation.value, 1);
expect(position.pixels, closeTo(25, 1e-9));
_end(drag, 0);
await tester.pumpAndSettle();
expect(find.text('Handoff'), findsOneWidget);
expect(position.pixels, closeTo(25, 1e-9));
await h.close(tester);
});
testWidgets('raw release velocity and progress use strict stock boundaries', (
tester,
) async {
// Cross both sides of each threshold. At exactly -700, distance still
// closes; only a strictly faster upward release vetoes that close.
for (final progress in [0.499, 0.5, 0.501, 1.0]) {
for (final velocity in [
-700.01,
-700.0,
-699.99,
0.0,
699.99,
700.0,
700.01,
]) {
final h = _Harness();
await h.open(tester);
final position = h.position(tester);
final drag = _start(position);
_move(drag, (1 - progress) * h.sheetHeight(tester));
expect(h.animation(tester).value, closeTo(progress, 1e-9));
_end(drag, velocity);
await tester.pumpAndSettle();
final closes =
progress < 1 &&
(velocity > 700 || (velocity >= -700 && progress < 0.5));
expect(
find.text('Handoff'),
closes ? findsNothing : findsOneWidget,
reason: 'progress=$progress, raw dy velocity=$velocity',
);
if (!closes) {
expect(h.animation(tester).value, 1);
// No residual content fling from a sheet-owned release.
if (progress < 1) expect(position.pixels, 0);
}
await h.close(tester);
}
}
// Scrolled content does not change the policy. A gesture that began
// mid-content, or scrolled away from the top and back in the same touch,
// releases exactly as one that began at the top: by a little or a lot.
for (final sameTouch in [false, true]) {
for (final offset in [6.0, 30.0, 300.0]) {
for (final (progress, velocity, closes) in [
(0.9, 2000.0, true),
(0.501, 700.01, true),
(0.501, 700.0, false),
(0.499, 0.0, true),
(0.499, -700.01, false),
(1.0, 2000.0, false),
]) {
final h = _Harness();
await h.open(tester);
final position = h.position(tester);
if (!sameTouch) position.jumpTo(offset);
final drag = _start(position);
if (sameTouch) _move(drag, -offset);
expect(position.pixels, offset);
_move(drag, offset + (1 - progress) * h.sheetHeight(tester));
expect(position.pixels, 0);
expect(h.animation(tester).value, closeTo(progress, 1e-9));
_end(drag, velocity);
await tester.pumpAndSettle();
expect(
find.text('Handoff'),
closes ? findsNothing : findsOneWidget,
reason:
'${sameTouch ? 'same-touch scroll' : 'mid-content start'}, '
'offset=$offset, progress=$progress, velocity=$velocity',
);
if (!closes) {
expect(h.animation(tester).value, 1);
if (progress < 1) expect(position.pixels, 0);
}
await h.close(tester);
}
}
}
});
testWidgets('a downward flick closes through trailing bounce', (
tester,
) async {
// A short menu under bouncing physics overscrolls on an upward drag
// although nothing scrolled: in the same touch, and in a new touch during
// the spring-back. A long menu can be overscrolled past its last action.
// One update repays the bounce and any content, then moves the sheet, and
// the flick closes in every case.
for (final scenario in [
'short, same-touch nudge',
'short, spring-back',
'long, trailing overscroll',
]) {
final h = _Harness();
await h.open(tester, short: scenario.startsWith('short'));
h.bouncing.value = true;
await tester.pumpAndSettle();
final position = h.position(tester);
var drag = _start(position);
switch (scenario) {
case 'short, same-touch nudge':
_move(drag, -80);
case 'short, spring-back':
_move(drag, -80);
_end(drag, 0);
await tester.pump();
await tester.pump(const Duration(milliseconds: 16));
drag = _start(position);
case 'long, trailing overscroll':
drag.cancel();
position.jumpTo(position.maxScrollExtent + 40);
drag = _start(position);
}
expect(
position.pixels - position.maxScrollExtent,
greaterThan(1),
reason: scenario,
);
_move(drag, position.pixels + 60);
expect(position.pixels, 0, reason: scenario);
expect(
h.animation(tester).value,
inExclusiveRange(0.5, 1),
reason: scenario,
);
_end(drag, 700.01);
await tester.pumpAndSettle();
expect(find.text('Handoff'), findsNothing, reason: scenario);
await h.close(tester);
}
});
testWidgets('a displaced release cannot zero a later gesture ballistic', (
tester,
) async {
final h = _Harness();
await h.open(tester);
final position = h.position(tester) as ScrollPositionWithSingleContext;
final displaced = _start(position);
_move(displaced, 60);
// Interrupted by an activity that never goes ballistic for this gesture.
position.beginActivity(IdleScrollActivity(position));
await tester.pumpAndSettle();
expect(h.animation(tester).value, 1);
final scroll = _start(position);
_move(scroll, -100);
expect(position.pixels, 100);
position.goBallistic(1500);
await tester.pumpAndSettle();
expect(position.pixels, greaterThan(100));
await h.close(tester);
});
// Pointer events with explicit timestamps, through the real recognizers. A
// zero velocity rests before lifting, so no fling is reported.
Future<void> release(
WidgetTester tester,
Offset from,
double dy,
double velocity,
) async {
const steps = 10;
final micros = velocity == 0 ? 80000 : (dy / velocity * 1e6).round();
final gesture = await tester.startGesture(from);
for (var i = 1; i <= steps; i++) {
await gesture.moveBy(
Offset(0, dy / steps),
timeStamp: Duration(microseconds: micros * i ~/ steps),
);
}
if (velocity == 0) await tester.pump(const Duration(milliseconds: 200));
await gesture.up(timeStamp: Duration(microseconds: micros));
await tester.pumpAndSettle();
}
for (final platform in [TargetPlatform.iOS, TargetPlatform.android]) {
testWidgets(
'body releases from the top match the stock sheet drag: $platform',
(tester) async {
debugDefaultTargetPlatformOverride = platform;
try {
// Both sides of the stock 700 px/s and 0.5 progress thresholds, with
// room for touch slop. A Flutter upgrade that moves either threshold
// changes the stock outcome and fails here.
for (final (fraction, velocity, closes) in [
(0.2, 0.0, false),
(0.4, 0.0, false),
(0.6, 0.0, true),
(0.25, 400.0, false),
(0.25, 1000.0, true),
]) {
for (final stock in [true, false]) {
final h = _Harness();
await h.open(tester);
final target = stock
? tester.getCenter(
find.byKey(const ValueKey('buzz-sheet-drag-handle')),
)
: tester.getRect(find.byType(ModalScrollHandoff)).topCenter +
const Offset(0, 20);
await release(
tester,
target,
fraction * h.sheetHeight(tester),
velocity,
);
expect(
find.text('Handoff'),
closes ? findsNothing : findsOneWidget,
reason:
'${stock ? 'stock handle' : 'body'}, '
'fraction=$fraction, velocity=$velocity',
);
await h.close(tester);
}
}
} finally {
debugDefaultTargetPlatformOverride = null;
}
},
);
// The hand-tested gesture: scroll the list up, slightly or a long way,
// then swipe down hard so the finger carries content to the top and pulls
// the sheet. A new touch after lifting, or the same touch that scrolled.
for (final scenario in [
'from the top',
'new touch after a slight scroll',
'same touch after a slight scroll',
'same touch after a long scroll',
'slow return across the top',
]) {
testWidgets('pointer swipe down, $scenario: $platform', (tester) async {
debugDefaultTargetPlatformOverride = platform;
try {
final h = _Harness();
await h.open(tester);
h.bouncing.value = platform == TargetPlatform.iOS;
await tester.pumpAndSettle();
final from =
tester.getRect(find.byType(ModalScrollHandoff)).topCenter +
const Offset(0, 20);
final long = scenario.contains('long');
final sameTouch = scenario.startsWith('same touch');
TestGesture? touch;
var elapsed = 0;
if (scenario != 'from the top') {
// Scroll up slowly and rest, so the scroll itself carries no fling.
touch = await tester.startGesture(from + const Offset(0, 200));
for (var i = 1; i <= 6; i++) {
elapsed = 40000 * i;
await touch.moveBy(
Offset(0, long ? -40 : -8),
timeStamp: Duration(microseconds: elapsed),
);
}
await tester.pump(const Duration(milliseconds: 200));
elapsed += 200000;
if (!sameTouch) {
await touch.up(timeStamp: Duration(microseconds: elapsed));
await tester.pumpAndSettle();
touch = null;
}
final scrolled = h.position(tester).pixels;
expect(scrolled, long ? greaterThan(150) : inExclusiveRange(5, 50));
}
final scrolled = h.position(tester).pixels;
if (touch == null) {
await release(
tester,
from,
scrolled + 80,
scenario.startsWith('slow') ? 0 : 2000,
);
} else {
const steps = 10;
final back = scrolled + 80;
final micros = (back / 2000 * 1e6).round();
for (var i = 1; i <= steps; i++) {
await touch.moveBy(
Offset(0, back / steps),
timeStamp: Duration(
microseconds: elapsed + micros * i ~/ steps,
),
);
}
await tester.pump();
expect(h.position(tester).pixels, 0);
expect(h.animation(tester).value, inExclusiveRange(0.5, 1));
await touch.up(timeStamp: Duration(microseconds: elapsed + micros));
await tester.pumpAndSettle();
}
if (scenario.startsWith('slow')) {
// The finger displaced the sheet less than half way and rested:
// neither rule closes, and the menu settles open at the top.
expect(find.text('Handoff'), findsOneWidget);
expect(h.animation(tester).value, 1);
expect(h.position(tester).pixels, 0);
await h.close(tester);
} else {
expect(find.text('Handoff'), findsNothing);
}
} finally {
debugDefaultTargetPlatformOverride = null;
}
});
}
}
testWidgets('interruptions restore deeply displaced sheets without closing', (
tester,
) async {
for (final interruption in [
'cancel',
'ballistic',
'activity',
'jump',
'physics',
'detach',
]) {
final h = _Harness();
await h.open(tester);
final position = h.position(tester);
final drag = _start(position);
_move(drag, h.sheetHeight(tester) * 0.7);
expect(h.animation(tester).value, closeTo(0.3, 1e-9));
switch (interruption) {
case 'cancel':
drag.cancel();
case 'ballistic':
(position as ScrollPositionWithSingleContext).goBallistic(0);
case 'activity':
(position as ScrollPositionWithSingleContext).beginActivity(
IdleScrollActivity(position),
);
case 'jump':
position.jumpTo(0);
case 'physics':
h.bouncing.value = true;
await tester.pump();
expect(h.position(tester), isNot(same(position)));
expect(
h.position(tester).physics.parent,
isA<BouncingScrollPhysics>(),
);
case 'detach':
h.visible.value = false;
await tester.pump();
}
await tester.pumpAndSettle();
expect(find.text('Handoff'), findsOneWidget, reason: interruption);
expect(h.animation(tester).value, 1, reason: interruption);
if (interruption == 'detach') {
h.visible.value = true;
await tester.pumpAndSettle();
}
// A fresh gesture must still own its own terminal event after interruption.
final next = _start(h.position(tester));
_move(next, h.sheetHeight(tester) * 0.2);
_end(next, 701);
await tester.pumpAndSettle();
expect(find.text('Handoff'), findsNothing, reason: interruption);
}
});
testWidgets('a live pointer cannot release a detached body', (tester) async {
final h = _Harness();
await h.open(tester);
final gesture = await tester.startGesture(
tester.getBottomLeft(find.byType(BottomSheet)) + const Offset(200, -40),
);
await gesture.moveBy(const Offset(0, 24));
await gesture.moveBy(Offset(0, h.sheetHeight(tester) * 0.7));
await tester.pump();
expect(h.animation(tester).value, lessThan(0.5));
h.visible.value = false;
await tester.pumpAndSettle();
expect(h.animation(tester).value, 1);
h.visible.value = true;
await tester.pumpAndSettle();
await gesture.moveBy(const Offset(0, 100));
await gesture.up();
await tester.pumpAndSettle();
expect(find.text('Handoff'), findsOneWidget);
expect(h.animation(tester).value, 1);
final next = _start(h.position(tester));
_move(next, 60);
_end(next, 701);
await tester.pumpAndSettle();
expect(find.text('Handoff'), findsNothing);
});
testWidgets('a system-cancelled pointer restores a deeply displaced sheet', (
tester,
) async {
final h = _Harness();
await h.open(tester);
final from =
tester.getRect(find.byType(ModalScrollHandoff)).topCenter +
const Offset(0, 20);
// Flutter ends an accepted drag on PointerCancelEvent, it does not cancel.
final cancelled = await tester.startGesture(from);
await cancelled.moveBy(const Offset(0, 24));
await cancelled.moveBy(Offset(0, h.sheetHeight(tester) * 0.7));
await tester.pump();
expect(h.animation(tester).value, lessThan(0.5));
await cancelled.cancel();
await tester.pumpAndSettle();
expect(find.text('Handoff'), findsOneWidget);
expect(h.animation(tester).value, 1);
// The cancellation does not outlive its pointer: the same pull, lifted,
// closes on progress.
final lifted = await tester.startGesture(from);
await lifted.moveBy(const Offset(0, 24));
await lifted.moveBy(Offset(0, h.sheetHeight(tester) * 0.7));
await tester.pump();
await lifted.up();
await tester.pumpAndSettle();
expect(find.text('Handoff'), findsNothing);
});
testWidgets('the sheet has one drag owner across body and handle', (
tester,
) async {
final h = _Harness();
await h.open(tester);
final height = h.sheetHeight(tester);
// A shallow body pull, then a second finger pulls the handle past half.
final body = await tester.startGesture(
tester.getRect(find.byType(ModalScrollHandoff)).topCenter +
const Offset(0, 20),
);
await body.moveBy(const Offset(0, 24));
await body.moveBy(const Offset(0, 40));
final handle = await tester.startGesture(
tester.getCenter(find.byKey(const ValueKey('buzz-sheet-drag-handle'))),
);
await handle.moveBy(const Offset(0, 24));
await handle.moveBy(Offset(0, height * 0.6));
await tester.pump();
final displaced = h.animation(tester).value;
expect(displaced, lessThan(0.5));
// The handle owns the sheet: the body can no longer move or settle it.
await body.moveBy(const Offset(0, 30));
await body.up();
await tester.pumpAndSettle();
expect(find.text('Handoff'), findsOneWidget);
expect(h.animation(tester).value, displaced);
await handle.moveBy(Offset(0, -height * 0.5));
await handle.up();
await tester.pumpAndSettle();
expect(h.animation(tester).value, 1);
// Ownership ends with the gesture: the body's next pull closes.
final next = _start(h.position(tester));
_move(next, 60);
_end(next, 701);
await tester.pumpAndSettle();
expect(find.text('Handoff'), findsNothing);
});
testWidgets('carried scroll momentum cannot promote a raw sheet release', (
tester,
) async {
final h = _Harness();
await h.open(tester);
h.bouncing.value = true;
await tester.pumpAndSettle();
final position = h.position(tester) as ScrollPositionWithSingleContext;
position.jumpTo(200);
position.goBallistic(-1000);
// Capture an actual bouncing ballistic's velocity just as a pointer down
// does, retaining enough momentum to take a raw 699 release above 700.
position.hold(() {});
final carried = position.physics.carriedMomentum(-1000);
expect(carried.abs(), greaterThan(700 - 699));
expect(699, greaterThan(carried.abs() * 0.5));
final drag = _start(position);
_move(drag, 260);
expect(position.pixels, 0);
expect(h.animation(tester).value, greaterThan(0.5));
expect(h.animation(tester).value, lessThan(1));
_end(drag, 699);
await tester.pumpAndSettle();
expect(find.text('Handoff'), findsOneWidget);
expect(h.animation(tester).value, 1);
expect(position.pixels, 0);
await h.close(tester);
});
testWidgets(
'short content remains draggable; reduced motion settles immediately',
(tester) async {
for (final reduced in [false, true]) {
final h = _Harness();
await h.open(tester, short: true, reducedMotion: reduced);
expect(h.position(tester).maxScrollExtent, 0);
final animation = h.animation(tester);
final cancel = _start(h.position(tester));
_move(cancel, h.sheetHeight(tester) * 0.7);
expect(animation.value, closeTo(0.3, 1e-9));
cancel.cancel();
if (reduced) {
expect(animation.value, 1);
expect(animation.isAnimating, isFalse);
}
await tester.pumpAndSettle();
final dismiss = _start(h.position(tester));
_move(dismiss, h.sheetHeight(tester) * 0.7);
_end(dismiss, 0);
if (reduced) {
expect(animation.value, 0);
expect(animation.isAnimating, isFalse);
}
await tester.pumpAndSettle();
expect(find.text('Handoff'), findsNothing);
}
},
);
testWidgets(
'inherited top and bottom bounce are repaid before route movement',
(tester) async {
final h = _Harness();
await h.open(tester);
h.bouncing.value = true;
await tester.pumpAndSettle();
final position = h.position(tester);
final animation = h.animation(tester);
position.jumpTo(-40);
final drag = _start(position);
_move(drag, 20);
expect(position.pixels, lessThan(-40));
expect(animation.value, 1);
final debt = -position.pixels;
_move(drag, -debt / 2);
expect(position.pixels, closeTo(-debt / 2, 1e-9));
expect(animation.value, 1);
_move(drag, -debt / 2 - 30);
expect(position.pixels, closeTo(30, 1e-9));
expect(animation.value, 1);
_move(drag, 50);
expect(position.pixels, 0);
expect(animation.value, closeTo(1 - 20 / h.sheetHeight(tester), 1e-9));
drag.cancel();
await tester.pumpAndSettle();
position.jumpTo(position.maxScrollExtent + 40);
final bottom = _start(position);
_move(bottom, 20);
expect(position.pixels, greaterThan(position.maxScrollExtent));
expect(animation.value, 1);
bottom.cancel();
await tester.pumpAndSettle();
expect(position.pixels, closeTo(position.maxScrollExtent, 0.01));
await h.close(tester);
},
);
testWidgets(
'entrance interruption and invalid binding stay ordinary scrolling',
(tester) async {
final h = _Harness();
await h.open(tester, settle: false);
final animation = h.animation(tester);
expect(animation.isCompleted, isFalse);
final entrance = _start(h.position(tester));
final before = animation.value;
_move(entrance, 100);
expect(animation.value, before);
_end(entrance, 1500);
await tester.pumpAndSettle();
expect(animation.value, 1);
await h.close(tester);
final disabled = _Harness();
await disabled.open(tester, enableDrag: false);
final drag = _start(disabled.position(tester));
_move(drag, 300);
_end(drag, 2000);
await tester.pumpAndSettle();
expect(disabled.animation(tester).value, 1);
expect(find.text('Handoff'), findsOneWidget);
await disabled.close(tester);
final covered = _Harness();
await covered.open(tester);
final coveredPosition = covered.position(tester);
final coveredAnimation = covered.animation(tester);
final displaced = _start(coveredPosition);
_move(displaced, covered.sheetHeight(tester) * 0.7);
expect(coveredAnimation.value, closeTo(0.3, 1e-9));
covered.navigator.currentState!.push<void>(
DialogRoute<void>(
context: covered.navigator.currentContext!,
builder: (_) => const AlertDialog(content: Text('Covering route')),
),
);
await tester.pumpAndSettle();
displaced.cancel();
await tester.pumpAndSettle();
expect(coveredAnimation.value, 1);
final obscured = _start(coveredPosition);
_move(obscured, 300);
_end(obscured, 2000);
await tester.pumpAndSettle();
expect(coveredAnimation.value, 1);
expect(find.text('Covering route'), findsOneWidget);
covered.navigator.currentState!.pop();
await tester.pumpAndSettle();
expect(find.text('Handoff'), findsOneWidget);
final fresh = _start(coveredPosition);
_move(fresh, 80);
expect(coveredAnimation.value, lessThan(1));
fresh.cancel();
await tester.pumpAndSettle();
expect(coveredAnimation.value, 1);
await covered.close(tester);
await tester.pumpWidget(
const ProviderScope(
child: MaterialApp(
home: Scaffold(
body: SizedBox(
height: 300,
child: ModalScrollHandoff(child: SizedBox(height: 1400)),
),
),
),
),
);
final ordinary = disabled.position(tester);
final outside = _start(ordinary);
_move(outside, -100);
expect(ordinary.pixels, greaterThan(0));
_move(outside, 200);
outside.cancel();
await tester.pumpAndSettle();
expect(find.byType(ModalScrollHandoff), findsOneWidget);
expect(tester.takeException(), isNull);
},
);
testWidgets(
'layout changes and external pop never turn into a drag release',
(tester) async {
final h = _Harness();
await h.open(tester);
var drag = _start(h.position(tester));
_move(drag, h.sheetHeight(tester) * 0.2);
h.height.value = 240;
await tester.pumpAndSettle();
expect(find.text('Handoff'), findsOneWidget);
drag.cancel();
await tester.pumpAndSettle();
expect(h.animation(tester).value, 1);
// The next drag must use current sheet geometry, not its original height.
drag = _start(h.position(tester));
_move(drag, h.sheetHeight(tester) * 0.25);
expect(h.animation(tester).value, closeTo(0.75, 1e-9));
final animation = h.animation(tester);
h.navigator.currentState!.pop();
expect(animation.status, AnimationStatus.reverse);
drag.cancel();
expect(animation.status, AnimationStatus.reverse);
await tester.pumpAndSettle();
expect(find.text('Handoff'), findsNothing);
expect(tester.takeException(), isNull);
},
);
testWidgets(
'touch gestures isolate horizontal and deeper vertical scrollables',
(tester) async {
final h = _Harness();
await h.open(
tester,
child: Column(
children: [
SizedBox(
height: 90,
child: ListView(
key: _horizontalKey,
scrollDirection: Axis.horizontal,
children: List.generate(
12,
(i) => SizedBox(width: 120, child: Text('Card $i')),
),
),
),
SizedBox(
height: 130,
child: ListView(
key: _nestedKey,
children: List.generate(
20,
(i) => SizedBox(height: 40, child: Text('Nested $i')),
),
),
),
const SizedBox(height: 1200, child: Text('Outer drag area')),
],
),
);
ScrollPosition inner(Key key) => tester
.state<ScrollableState>(
find.descendant(
of: find.byKey(key),
matching: find.byType(Scrollable),
),
)
.position;
await tester.drag(find.byKey(_horizontalKey), const Offset(-180, 0));
await tester.pumpAndSettle();
expect(inner(_horizontalKey).pixels, greaterThan(0));
expect(h.position(tester).pixels, 0);
expect(h.animation(tester).value, 1);
await tester.drag(find.byKey(_nestedKey), const Offset(0, -80));
await tester.pumpAndSettle();
expect(inner(_nestedKey).pixels, greaterThan(0));
await tester.drag(find.byKey(_nestedKey), const Offset(0, 250));
await tester.pumpAndSettle();
expect(inner(_nestedKey).pixels, 0);
expect(h.position(tester).pixels, 0);
expect(h.animation(tester).value, 1);
// Unlike its descendants, the opted-in body really moves the route by touch.
final gesture = await tester.startGesture(
tester.getBottomLeft(find.byType(BottomSheet)) + const Offset(200, -40),
);
await gesture.moveBy(const Offset(0, 24)); // Establish the drag arena.
await gesture.moveBy(const Offset(0, 76));
await tester.pump();
expect(h.animation(tester).value, lessThan(1));
await gesture.cancel();
await tester.pumpAndSettle();
expect(h.animation(tester).value, 1);
await h.close(tester);
},
);
testWidgets(
'stock handle drag and accessible dismiss survive body cancellation',
(tester) async {
final semantics = tester.ensureSemantics();
// Release before widget-test invariants, including on assertion failure.
try {
for (final accessible in [false, true]) {
final h = _Harness();
await h.open(tester);
final drag = _start(h.position(tester));
_move(drag, 70);
drag.cancel();
await tester.pumpAndSettle();
final handle = find.byKey(const ValueKey('buzz-sheet-drag-handle'));
expect(handle, findsOneWidget);
if (accessible) {
final dismiss = find.bySemanticsLabel('Dismiss').first;
final node = tester.getSemantics(dismiss);
expect(node.flagsCollection.isButton, isTrue);
expect(
node.getSemanticsData().hasAction(SemanticsAction.tap),
isTrue,
);
tester.binding.performSemanticsAction(
SemanticsActionEvent(
type: SemanticsAction.tap,
viewId: tester.view.viewId,
nodeId: node.id,
),
);
} else {
await tester.drag(handle, Offset(0, h.sheetHeight(tester) * 0.7));
}
await tester.pumpAndSettle();
expect(find.text('Handoff'), findsNothing);
}
} finally {
semantics.dispose();
}
},
);
}