Make TextSpan hit testing precise. (#139717)

Fixes https://github.com/flutter/flutter/issues/131435, #104594, #43400
Needs https://github.com/flutter/engine/pull/48774 (to fix the web test failure).

Currently the method we use for text span hit testing `TextPainter.getPositionForOffset` always returns the closest `TextPosition`, even when the given offset is far away from the text. 

The new TextPaintes method tells you the layout bounds (`width =  letterspacing / 2 + x_advance + letterspacing / 2`, `height = font ascent + font descent`) of a character, the PR changes the hit testing implementation such that a TextSpan is only considered hit if the point-down event landed in one of it's character's layout bounds.

Potential issues:

1. In theory since the text is baseline aligned, we should use the max ascent and max descent of each character to calculate the height of the text span's hit-test region, in case some characters in the span have to fall back to a different font, but that will be slower and it typically doesn't make a huge difference. 

This is a breaking change. It also introduces a new finder and a new method `WidgetTester.tapOnText`: `await tester.tapOnText('string to match')` for ease of migration.
This commit is contained in:
LongCatIsLooong
2023-12-19 19:23:29 -08:00
committed by GitHub
parent e86b825819
commit ea5b97286e
13 changed files with 747 additions and 40 deletions

View File

@@ -24,6 +24,23 @@ const double kDragSlopDefault = 20.0;
const String _defaultPlatform = kIsWeb ? 'web' : 'android';
// Finds the end index (exclusive) of the span at `startIndex`, or `endIndex` if
// there are no other spans between `startIndex` and `endIndex`.
// The InlineSpan protocol doesn't expose the length of the span so we'll
// have to iterate through the whole range.
(InlineSpan, int)? _findEndOfSpan(InlineSpan rootSpan, int startIndex, int endIndex) {
assert(endIndex > startIndex);
final InlineSpan? subspan = rootSpan.getSpanForPosition(TextPosition(offset: startIndex));
if (subspan == null) {
return null;
}
int i = startIndex + 1;
while (i < endIndex && rootSpan.getSpanForPosition(TextPosition(offset: i)) == subspan) {
i += 1;
}
return (subspan, i);
}
// Examples can assume:
// typedef MyWidget = Placeholder;
@@ -997,6 +1014,47 @@ abstract class WidgetController {
return tapAt(getCenter(finder, warnIfMissed: warnIfMissed, callee: 'tap'), pointer: pointer, buttons: buttons, kind: kind);
}
/// Dispatch a pointer down / pointer up sequence at a hit-testable
/// [InlineSpan] (typically a [TextSpan]) within the given text range.
///
/// This method performs a more spatially precise tap action on a piece of
/// static text, than the widget-based [tap] method.
///
/// The given [Finder] must find one and only one matching substring, and the
/// substring must be hit-testable (meaning, it must not be off-screen, or be
/// obscured by other widgets, or in a disabled widget). Otherwise this method
/// throws a [FlutterError].
///
/// If the target substring contains more than one hit-testable [InlineSpan]s,
/// [tapOnText] taps on one of them, but does not guarantee which.
///
/// The `pointer` and `button` arguments specify [PointerEvent.pointer] and
/// [PointerEvent.buttons] of the tap event.
Future<void> tapOnText(finders.FinderBase<finders.TextRangeContext> textRangeFinder, {int? pointer, int buttons = kPrimaryButton }) {
final Iterable<finders.TextRangeContext> ranges = textRangeFinder.evaluate();
if (ranges.isEmpty) {
throw FlutterError(textRangeFinder.toString());
}
if (ranges.length > 1) {
throw FlutterError(
'$textRangeFinder. The "tapOnText" method needs a single non-empty TextRange.',
);
}
final Offset? tapLocation = _findHitTestableOffsetIn(ranges.single);
if (tapLocation == null) {
final finders.TextRangeContext found = textRangeFinder.evaluate().single;
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Finder specifies a TextRange that can not receive pointer events.'),
ErrorDescription('The finder used was: ${textRangeFinder.toString(describeSelf: true)}'),
ErrorDescription('Found a matching substring in a static text widget, within ${found.textRange}.'),
ErrorDescription('But the "tapOnText" method could not find a hit-testable Offset with in that text range.'),
found.renderObject.toDiagnosticsNode(name: 'The RenderBox of that static text widget was', style: DiagnosticsTreeStyle.shallow),
]
);
}
return tapAt(tapLocation, pointer: pointer, buttons: buttons);
}
/// Dispatch a pointer down / pointer up sequence at the given location.
Future<void> tapAt(
Offset location, {
@@ -1762,6 +1820,45 @@ abstract class WidgetController {
/// in the documentation for the [flutter_test] library.
static bool hitTestWarningShouldBeFatal = false;
/// Finds one hit-testable Offset in the given `textRangeContext`'s render
/// object.
Offset? _findHitTestableOffsetIn(finders.TextRangeContext textRangeContext) {
TestAsyncUtils.guardSync();
final TextRange range = textRangeContext.textRange;
assert(range.isNormalized);
assert(range.isValid);
final Offset renderParagraphPaintOffset = textRangeContext.renderObject.localToGlobal(Offset.zero);
assert(renderParagraphPaintOffset.isFinite);
int spanStart = range.start;
while (spanStart < range.end) {
switch (_findEndOfSpan(textRangeContext.renderObject.text, spanStart, range.end)) {
case (final HitTestTarget target, final int endIndex):
// Uses BoxHeightStyle.tight in getBoxesForSelection to make sure the
// returned boxes don't extend outside of the hit-testable region.
final Iterable<Offset> testOffsets = textRangeContext.renderObject
.getBoxesForSelection(TextSelection(baseOffset: spanStart, extentOffset: endIndex))
// Try hit-testing the center of each TextBox.
.map((TextBox textBox) => textBox.toRect().center);
for (final Offset localOffset in testOffsets) {
final HitTestResult result = HitTestResult();
final Offset globalOffset = localOffset + renderParagraphPaintOffset;
binding.hitTestInView(result, globalOffset, textRangeContext.view.view.viewId);
if (result.path.any((HitTestEntry entry) => entry.target == target)) {
return globalOffset;
}
}
spanStart = endIndex;
case (_, final int endIndex):
spanStart = endIndex;
case null:
break;
}
}
return null;
}
Offset _getElementPoint(finders.FinderBase<Element> finder, Offset Function(Size size) sizeToPoint, { required bool warnIfMissed, required String callee }) {
TestAsyncUtils.guardSync();
final Iterable<Element> elements = finder.evaluate();
@@ -1791,17 +1888,10 @@ abstract class WidgetController {
final FlutterView view = _viewOf(finder);
final HitTestResult result = HitTestResult();
binding.hitTestInView(result, location, view.viewId);
bool found = false;
for (final HitTestEntry entry in result.path) {
if (entry.target == box) {
found = true;
break;
}
}
final bool found = result.path.any((HitTestEntry entry) => entry.target == box);
if (!found) {
final RenderView renderView = binding.renderViews.firstWhere((RenderView r) => r.flutterView == view);
bool outOfBounds = false;
outOfBounds = !(Offset.zero & renderView.size).contains(location);
final bool outOfBounds = !(Offset.zero & renderView.size).contains(location);
if (hitTestWarningShouldBeFatal) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Finder specifies a widget that would not receive pointer events.'),