Files
buzz/mobile/lib/features/channels/message_long_press_region.dart
Matt Toohey bea77282da fix(mobile): open message actions only from a long press on the message (#9753)
## Why
I find myself putting my finger down before scrolling and end up
triggering the long press. Each time I think "but i wasnt touching
anything?"

## Summary

On mobile, the long-press recognizer covered the whole message row, so
holding the empty space beside a bubble in a channel, DM or thread
opened that message's actions. A hold now opens the actions only when it
lands on a part of the message.

- **Bubble and media:** a hold on the painted bubble or media opens the
actions, as before.
- **Other message parts:** the avatar, author line, edited marker, photo
count label, reply footer and add-reaction button are marked as
long-press targets around their own extent, so they still open the
actions while the unused row width beside them stays inert.
- **Empty space beside a message:** a hold there opens nothing and gives
no haptic, and releasing it does not open the thread. A quick tap there
still opens the thread.
- **Unchanged:** swipe-to-reply still starts only on the bubble and
media, and the screen-reader long press, the reaction tray's long press
and the system rows' full-row hold behave as before.


https://github.com/user-attachments/assets/2ede96b0-b9dd-49f3-926f-5cad32f7242e


### Related issue

N/A. I searched issues and PRs for "long press" and found none for this;
the closest is #8500 (action sheet opening while scrolling), which is a
different problem.

### Testing

Widget tests in `swipe_reply_tests.dart` cover a hold beside the bubble
(no actions, no thread, no haptic, and a quick tap still opens the
thread), a hold on each message part in channels and threads for own and
other messages, attachment and gallery holds, the semantics long press,
and that a swipe from the non-bubble parts starts no reply.

Side-by-side recording on an iPhone 17 Pro simulator (iOS 27.2), `main`
on the left and this branch on the right, running the same four 1.0 s
holds at the same coordinates. The red ring marks the press point and
was overlaid afterwards. Holding the empty space beside a message opens
the action sheet on the left and nothing on the right; holding the
bubble opens it on both sides.

The recording was made at the first commit on this branch (`378dde654`),
before the two follow-up commits, and uses a local relay with seeded
throwaway data. It covers short messages from another author in a
channel and a thread; own messages, DMs and media are covered by the
tests only.

🤖 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: Jitter <2b2e6415e748c35180847a37aadae06a11e30dddc76b784e7fd9354c4eb42e7a@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-20 11:35:11 +11:00

252 lines
8.6 KiB
Dart

import 'dart:math' as math;
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'message_reply_drag_target.dart';
/// Shared hold deadline so nested reaction pills win before the message menu.
const iosMessageLongPressDuration = Duration(milliseconds: 500);
const _maxMessageSnapshotDimension = 2048.0;
double _messageSnapshotPixelRatio(Size size, double devicePixelRatio) {
final longestSide = size.longestSide;
if (!longestSide.isFinite || longestSide <= 0) return devicePixelRatio;
return math.min(devicePixelRatio, _maxMessageSnapshotDimension / longestSide);
}
/// Geometry and snapshot controls for a completed message long press.
///
/// Call [captureSnapshot] while the source is still mounted, then use
/// [setSourceHidden] to hide it behind the lifted preview. Restore the source
/// before the preview is disposed or dismissed.
class MessageLongPressDetails {
/// The long-pressed source bounds in global logical coordinates.
final Rect anchorRect;
/// Captures the current source as an image for the lifted preview.
///
/// The returned future can fail if the source is no longer mounted.
final Future<ui.Image> Function() captureSnapshot;
/// Hides or reveals the mounted source while its preview is displayed.
final ValueChanged<bool> setSourceHidden;
/// Creates the details passed to a completed long-press callback.
const MessageLongPressDetails({
required this.anchorRect,
required this.captureSnapshot,
required this.setSourceHidden,
});
}
/// An [InkWell] whose long press is observed above interactive descendants.
class MessageLongPressInkWell extends StatelessWidget {
final VoidCallback? onTap;
final ValueChanged<Rect>? onLongPress;
/// Handles a completed long press with snapshot and source-visibility access.
///
/// When provided, this callback takes precedence over [onLongPress].
final ValueChanged<MessageLongPressDetails>? onLongPressDetails;
final BorderRadius? borderRadius;
final Color? highlightColor;
/// Identifies the [RepaintBoundary] to capture for the lifted preview.
///
/// The key's current context must resolve to a boundary covering the message
/// content. When omitted, this widget inserts and owns that boundary.
final GlobalKey? snapshotKey;
/// Whether a pointer long press opens actions only on a
/// [MessageLongPressTarget] or [MessageReplyDragTarget] below this region.
/// A hold on the empty row space around them does nothing, and neither does
/// its release. Otherwise a hold anywhere in the region opens actions.
final bool targetsOnly;
final Widget child;
const MessageLongPressInkWell({
super.key,
this.onTap,
this.onLongPress,
this.onLongPressDetails,
this.borderRadius,
this.highlightColor,
this.snapshotKey,
this.targetsOnly = false,
required this.child,
}) : assert(onLongPress != null || onLongPressDetails != null);
@override
Widget build(BuildContext context) {
return _MessageLongPressRegion(
onTap: onTap,
onLongPress: onLongPress,
onLongPressDetails: onLongPressDetails,
borderRadius: borderRadius,
highlightColor: highlightColor,
externalSnapshotKey: snapshotKey,
targetsOnly: targetsOnly,
child: child,
);
}
}
/// Detects a message long press through Flutter's gesture arena.
///
/// Links, media, reactions, and other nested controls keep their normal tap
/// gestures, while a completed hold wins over descendant taps.
class _MessageLongPressRegion extends HookWidget {
final VoidCallback? onTap;
final ValueChanged<Rect>? onLongPress;
final ValueChanged<MessageLongPressDetails>? onLongPressDetails;
final BorderRadius? borderRadius;
final Color? highlightColor;
final GlobalKey? externalSnapshotKey;
final bool targetsOnly;
final Widget child;
const _MessageLongPressRegion({
required this.onTap,
required this.onLongPress,
required this.onLongPressDetails,
required this.borderRadius,
required this.highlightColor,
required this.externalSnapshotKey,
required this.targetsOnly,
required this.child,
});
@override
Widget build(BuildContext context) {
final fallbackSnapshotKey = useMemoized(GlobalKey.new, const []);
final snapshotKey = externalSnapshotKey ?? fallbackSnapshotKey;
final sourceHidden = useState(false);
final onTarget = useRef(false);
void recognize() {
final renderObject = snapshotKey.currentContext?.findRenderObject();
if (renderObject is! RenderRepaintBoundary || !renderObject.hasSize) {
return;
}
final anchorRect =
renderObject.localToGlobal(Offset.zero) & renderObject.size;
final detailsCallback = onLongPressDetails;
if (detailsCallback == null) {
onLongPress?.call(anchorRect);
return;
}
final maxSnapshotPixelRatio = math.min(
MediaQuery.devicePixelRatioOf(context),
2.0,
);
Future<ui.Image> captureSnapshot() async {
RenderRepaintBoundary? boundary;
final renderObject = snapshotKey.currentContext?.findRenderObject();
if (renderObject is RenderRepaintBoundary && renderObject.hasSize) {
boundary = renderObject;
}
if (boundary == null) {
throw StateError('Message snapshot is unavailable');
}
final snapshotPixelRatio = _messageSnapshotPixelRatio(
boundary.size,
maxSnapshotPixelRatio,
);
try {
return await boundary.toImage(pixelRatio: snapshotPixelRatio);
} catch (_) {
await WidgetsBinding.instance.endOfFrame;
final retryBoundary = snapshotKey.currentContext?.findRenderObject();
if (retryBoundary is! RenderRepaintBoundary ||
!retryBoundary.hasSize) {
rethrow;
}
try {
return await retryBoundary.toImage(
pixelRatio: _messageSnapshotPixelRatio(
retryBoundary.size,
maxSnapshotPixelRatio,
),
);
} catch (_) {
if (snapshotPixelRatio <= 1) rethrow;
return retryBoundary.toImage(
pixelRatio: _messageSnapshotPixelRatio(retryBoundary.size, 1),
);
}
}
}
void setSourceHidden(bool hidden) {
if (!context.mounted) return;
sourceHidden.value = hidden;
}
detailsCallback(
MessageLongPressDetails(
anchorRect: anchorRect,
captureSnapshot: captureSnapshot,
setSourceHidden: setSourceHidden,
),
);
}
return Semantics(
container: true,
onLongPress: recognize,
child: RawGestureDetector(
behavior: HitTestBehavior.translucent,
// The detector's own semantic long press reports its centre, which
// can miss every target on a wide row. The action above needs no
// position.
excludeFromSemantics: true,
gestures: {
LongPressGestureRecognizer:
GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>(
() => LongPressGestureRecognizer(
duration: defaultTargetPlatform == TargetPlatform.iOS
? iosMessageLongPressDuration
: null,
),
// A hold beside the targets still wins the arena, so its
// release cannot fall through to the row's tap; it just
// opens nothing. The target is decided at pointer down, so
// an edit or reaction that moves the bubble mid-hold doesn't
// change the outcome.
(recognizer) => recognizer
..onLongPressDown = (details) {
onTarget.value =
!targetsOnly ||
messageLongPressTargetAt(
context.findRenderObject(),
details.globalPosition,
);
}
..onLongPressStart = (_) {
if (onTarget.value) recognize();
},
),
},
child: InkWell(
onTap: onTap,
borderRadius: borderRadius,
highlightColor: highlightColor,
child: Opacity(
opacity: sourceHidden.value ? 0 : 1,
child: externalSnapshotKey == null
? RepaintBoundary(key: snapshotKey, child: child)
: child,
),
),
),
);
}
}