Move platform specific text selection behavior out of styled TextField classes (#155774)

Fixes #129726
This commit is contained in:
Renzo Olivares
2024-09-30 15:44:20 -07:00
committed by GitHub
parent 91fd01bf65
commit 72edaa3d66
4 changed files with 237 additions and 284 deletions

View File

@@ -65,91 +65,12 @@ class _SelectableTextSelectionGestureDetectorBuilder extends TextSelectionGestur
final _SelectableTextState _state;
/// The viewport offset pixels of any [Scrollable] containing the
/// [RenderEditable] at the last drag start.
double _dragStartScrollOffset = 0.0;
/// The viewport offset pixels of the [RenderEditable] at the last drag start.
double _dragStartViewportOffset = 0.0;
double get _scrollPosition {
final ScrollableState? scrollableState =
delegate.editableTextKey.currentContext == null
? null
: Scrollable.maybeOf(delegate.editableTextKey.currentContext!);
return scrollableState == null
? 0.0
: scrollableState.position.pixels;
}
AxisDirection? get _scrollDirection {
final ScrollableState? scrollableState =
delegate.editableTextKey.currentContext == null
? null
: Scrollable.maybeOf(delegate.editableTextKey.currentContext!);
return scrollableState?.axisDirection;
}
@override
void onForcePressStart(ForcePressDetails details) {
super.onForcePressStart(details);
if (delegate.selectionEnabled && shouldShowSelectionToolbar) {
editableText.showToolbar();
}
}
@override
void onForcePressEnd(ForcePressDetails details) {
// Not required.
}
@override
void onSingleLongTapStart(LongPressStartDetails details) {
if (!delegate.selectionEnabled) {
return;
}
renderEditable.selectWord(cause: SelectionChangedCause.longPress);
Feedback.forLongPress(_state.context);
_dragStartViewportOffset = renderEditable.offset.pixels;
_dragStartScrollOffset = _scrollPosition;
}
@override
void onSingleLongTapMoveUpdate(LongPressMoveUpdateDetails details) {
if (!delegate.selectionEnabled) {
return;
}
// Adjust the drag start offset for possible viewport offset changes.
final Offset editableOffset = renderEditable.maxLines == 1
? Offset(renderEditable.offset.pixels - _dragStartViewportOffset, 0.0)
: Offset(0.0, renderEditable.offset.pixels - _dragStartViewportOffset);
final Offset scrollableOffset = switch (axisDirectionToAxis(_scrollDirection ?? AxisDirection.left)) {
Axis.horizontal => Offset(_scrollPosition - _dragStartScrollOffset, 0),
Axis.vertical => Offset(0, _scrollPosition - _dragStartScrollOffset),
};
renderEditable.selectWordsInRange(
from: details.globalPosition - details.offsetFromOrigin - editableOffset - scrollableOffset,
to: details.globalPosition,
cause: SelectionChangedCause.longPress,
);
}
@override
void onSingleTapUp(TapDragUpDetails details) {
if (!delegate.selectionEnabled) {
return;
}
editableText.hideToolbar();
switch (Theme.of(_state.context).platform) {
case TargetPlatform.iOS:
renderEditable.selectWordEdge(cause: SelectionChangedCause.tap);
case TargetPlatform.macOS:
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
renderEditable.selectPosition(cause: SelectionChangedCause.tap);
}
super.onSingleTapUp(details);
_state.widget.onTap?.call();
}
}

View File

@@ -58,19 +58,6 @@ class _TextFieldSelectionGestureDetectorBuilder extends TextSelectionGestureDete
final _TextFieldState _state;
@override
void onForcePressStart(ForcePressDetails details) {
super.onForcePressStart(details);
if (delegate.selectionEnabled && shouldShowSelectionToolbar) {
editableText.showToolbar();
}
}
@override
void onForcePressEnd(ForcePressDetails details) {
// Not required.
}
@override
bool get onUserTapAlwaysCalled => _state.widget.onTapAlwaysCalled;
@@ -78,23 +65,6 @@ class _TextFieldSelectionGestureDetectorBuilder extends TextSelectionGestureDete
void onUserTap() {
_state.widget.onTap?.call();
}
@override
void onSingleLongTapStart(LongPressStartDetails details) {
super.onSingleLongTapStart(details);
if (delegate.selectionEnabled) {
switch (Theme.of(_state.context).platform) {
case TargetPlatform.iOS:
case TargetPlatform.macOS:
break;
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
Feedback.forLongPress(_state.context);
}
}
}
}
/// A Material Design text field.

View File

@@ -22,6 +22,7 @@ import 'constants.dart';
import 'context_menu_controller.dart';
import 'debug.dart';
import 'editable_text.dart';
import 'feedback.dart';
import 'framework.dart';
import 'gesture_detector.dart';
import 'inherited_theme.dart';
@@ -2319,12 +2320,14 @@ class TextSelectionGestureDetectorBuilder {
void onForcePressStart(ForcePressDetails details) {
assert(delegate.forcePressEnabled);
_shouldShowSelectionToolbar = true;
if (delegate.selectionEnabled) {
renderEditable.selectWordsInRange(
from: details.globalPosition,
cause: SelectionChangedCause.forcePress,
);
if (!delegate.selectionEnabled) {
return;
}
renderEditable.selectWordsInRange(
from: details.globalPosition,
cause: SelectionChangedCause.forcePress,
);
editableText.showToolbar();
}
/// Handler for [TextSelectionGestureDetector.onForcePressEnd].
@@ -2381,96 +2384,103 @@ class TextSelectionGestureDetectorBuilder {
/// this callback.
@protected
void onSingleTapUp(TapDragUpDetails details) {
if (delegate.selectionEnabled) {
// It is impossible to extend the selection when the shift key is pressed, if the
// renderEditable.selection is invalid.
final bool isShiftPressedValid = _isShiftPressed && renderEditable.selection?.baseOffset != null;
switch (defaultTargetPlatform) {
case TargetPlatform.linux:
case TargetPlatform.macOS:
case TargetPlatform.windows:
break;
// On desktop platforms the selection is set on tap down.
case TargetPlatform.android:
editableText.hideToolbar(false);
if (isShiftPressedValid) {
_extendSelection(details.globalPosition, SelectionChangedCause.tap);
return;
}
renderEditable.selectPosition(cause: SelectionChangedCause.tap);
editableText.showSpellCheckSuggestionsToolbar();
case TargetPlatform.fuchsia:
editableText.hideToolbar(false);
if (isShiftPressedValid) {
_extendSelection(details.globalPosition, SelectionChangedCause.tap);
return;
}
renderEditable.selectPosition(cause: SelectionChangedCause.tap);
case TargetPlatform.iOS:
if (isShiftPressedValid) {
// On iOS, a shift-tapped unfocused field expands from 0, not from
// the previous selection.
final TextSelection? fromSelection = renderEditable.hasFocus
? null
: const TextSelection.collapsed(offset: 0);
_expandSelection(
details.globalPosition,
SelectionChangedCause.tap,
fromSelection,
);
return;
}
switch (details.kind) {
case PointerDeviceKind.mouse:
case PointerDeviceKind.trackpad:
case PointerDeviceKind.stylus:
case PointerDeviceKind.invertedStylus:
// TODO(camsim99): Determine spell check toolbar behavior in these cases:
// https://github.com/flutter/flutter/issues/119573.
// Precise devices should place the cursor at a precise position if the
// word at the text position is not misspelled.
renderEditable.selectPosition(cause: SelectionChangedCause.tap);
case PointerDeviceKind.touch:
case PointerDeviceKind.unknown:
// If the word that was tapped is misspelled, select the word and show the spell check suggestions
// toolbar once. If additional taps are made on a misspelled word, toggle the toolbar. If the word
// is not misspelled, default to the following behavior:
//
// Toggle the toolbar if the `previousSelection` is collapsed, the tap is on the selection, the
// TextAffinity remains the same, and the editable is focused. The TextAffinity is important when the
// cursor is on the boundary of a line wrap, if the affinity is different (i.e. it is downstream), the
// selection should move to the following line and not toggle the toolbar.
//
// Toggle the toolbar when the tap is exclusively within the bounds of a non-collapsed `previousSelection`,
// and the editable is focused.
//
// Selects the word edge closest to the tap when the editable is not focused, or if the tap was neither exclusively
// or inclusively on `previousSelection`. If the selection remains the same after selecting the word edge, then we
// toggle the toolbar. If the selection changes then we hide the toolbar.
final TextSelection previousSelection = renderEditable.selection ?? editableText.textEditingValue.selection;
final TextPosition textPosition = renderEditable.getPositionForPoint(details.globalPosition);
final bool isAffinityTheSame = textPosition.affinity == previousSelection.affinity;
final bool wordAtCursorIndexIsMisspelled = editableText.findSuggestionSpanAtCursorIndex(textPosition.offset) != null;
if (!delegate.selectionEnabled) {
editableText.requestKeyboard();
return;
}
// It is impossible to extend the selection when the shift key is pressed, if the
// renderEditable.selection is invalid.
final bool isShiftPressedValid = _isShiftPressed && renderEditable.selection?.baseOffset != null;
switch (defaultTargetPlatform) {
case TargetPlatform.linux:
case TargetPlatform.macOS:
case TargetPlatform.windows:
break;
// On desktop platforms the selection is set on tap down.
case TargetPlatform.android:
editableText.hideToolbar(false);
if (isShiftPressedValid) {
_extendSelection(details.globalPosition, SelectionChangedCause.tap);
return;
}
renderEditable.selectPosition(cause: SelectionChangedCause.tap);
editableText.showSpellCheckSuggestionsToolbar();
case TargetPlatform.fuchsia:
editableText.hideToolbar(false);
if (isShiftPressedValid) {
_extendSelection(details.globalPosition, SelectionChangedCause.tap);
return;
}
renderEditable.selectPosition(cause: SelectionChangedCause.tap);
case TargetPlatform.iOS:
if (isShiftPressedValid) {
// On iOS, a shift-tapped unfocused field expands from 0, not from
// the previous selection.
final TextSelection? fromSelection = renderEditable.hasFocus
? null
: const TextSelection.collapsed(offset: 0);
_expandSelection(
details.globalPosition,
SelectionChangedCause.tap,
fromSelection,
);
return;
}
switch (details.kind) {
case PointerDeviceKind.mouse:
case PointerDeviceKind.trackpad:
case PointerDeviceKind.stylus:
case PointerDeviceKind.invertedStylus:
// TODO(camsim99): Determine spell check toolbar behavior in these cases:
// https://github.com/flutter/flutter/issues/119573.
// Precise devices should place the cursor at a precise position if the
// word at the text position is not misspelled.
renderEditable.selectPosition(cause: SelectionChangedCause.tap);
case PointerDeviceKind.touch:
case PointerDeviceKind.unknown:
// If the word that was tapped is misspelled, select the word and show the spell check suggestions
// toolbar once. If additional taps are made on a misspelled word, toggle the toolbar. If the word
// is not misspelled, default to the following behavior:
//
// Toggle the toolbar when the tap is exclusively within the bounds of a non-collapsed `previousSelection`,
// and the editable is focused.
//
// Toggle the toolbar if the `previousSelection` is collapsed, the tap is on the selection, the
// TextAffinity remains the same, the editable field is not read only, and the editable is focused.
// The TextAffinity is important when the cursor is on the boundary of a line wrap, if the affinity
// is different (i.e. it is downstream), the selection should move to the following line and not toggle
// the toolbar.
//
// Selects the word edge closest to the tap when the editable is not focused, or if the tap was neither exclusively
// or inclusively on `previousSelection`. If the selection remains the same after selecting the word edge, then we
// toggle the toolbar, if the editable field is not read only. If the selection changes then we hide the toolbar.
final TextSelection previousSelection = renderEditable.selection ?? editableText.textEditingValue.selection;
final TextPosition textPosition = renderEditable.getPositionForPoint(details.globalPosition);
final bool isAffinityTheSame = textPosition.affinity == previousSelection.affinity;
final bool wordAtCursorIndexIsMisspelled = editableText.findSuggestionSpanAtCursorIndex(textPosition.offset) != null;
if (wordAtCursorIndexIsMisspelled) {
renderEditable.selectWord(cause: SelectionChangedCause.tap);
if (previousSelection != editableText.textEditingValue.selection) {
editableText.showSpellCheckSuggestionsToolbar();
} else {
editableText.toggleToolbar(false);
}
} else if (((_positionWasOnSelectionExclusive(textPosition) && !previousSelection.isCollapsed) || (_positionWasOnSelectionInclusive(textPosition) && previousSelection.isCollapsed && isAffinityTheSame)) && renderEditable.hasFocus) {
if (wordAtCursorIndexIsMisspelled) {
renderEditable.selectWord(cause: SelectionChangedCause.tap);
if (previousSelection != editableText.textEditingValue.selection) {
editableText.showSpellCheckSuggestionsToolbar();
} else {
editableText.toggleToolbar(false);
}
} else if (((_positionWasOnSelectionExclusive(textPosition) && !previousSelection.isCollapsed)
|| (_positionWasOnSelectionInclusive(textPosition) && previousSelection.isCollapsed && isAffinityTheSame && !renderEditable.readOnly))
&& renderEditable.hasFocus) {
editableText.toggleToolbar(false);
} else {
renderEditable.selectWordEdge(cause: SelectionChangedCause.tap);
if (previousSelection == editableText.textEditingValue.selection
&& renderEditable.hasFocus
&& !renderEditable.readOnly) {
editableText.toggleToolbar(false);
} else {
renderEditable.selectWordEdge(cause: SelectionChangedCause.tap);
if (previousSelection == editableText.textEditingValue.selection && renderEditable.hasFocus) {
editableText.toggleToolbar(false);
} else {
editableText.hideToolbar(false);
}
editableText.hideToolbar(false);
}
}
}
}
}
}
editableText.requestKeyboard();
}
@@ -2497,44 +2507,53 @@ class TextSelectionGestureDetectorBuilder {
/// this callback.
@protected
void onSingleLongTapStart(LongPressStartDetails details) {
if (delegate.selectionEnabled) {
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
case TargetPlatform.macOS:
if (!renderEditable.hasFocus) {
_longPressStartedWithoutFocus = true;
renderEditable.selectWord(cause: SelectionChangedCause.longPress);
} else {
renderEditable.selectPositionAt(
from: details.globalPosition,
cause: SelectionChangedCause.longPress,
);
// Show the floating cursor.
final RawFloatingCursorPoint cursorPoint = RawFloatingCursorPoint(
state: FloatingCursorDragState.Start,
startLocation: (
renderEditable.globalToLocal(details.globalPosition),
TextPosition(
offset: editableText.textEditingValue.selection.baseOffset,
affinity: editableText.textEditingValue.selection.affinity,
),
),
offset: Offset.zero,
);
editableText.updateFloatingCursor(cursorPoint);
}
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
renderEditable.selectWord(cause: SelectionChangedCause.longPress);
}
_showMagnifierIfSupportedByPlatform(details.globalPosition);
_dragStartViewportOffset = renderEditable.offset.pixels;
_dragStartScrollOffset = _scrollPosition;
if (!delegate.selectionEnabled) {
return;
}
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
case TargetPlatform.macOS:
if (!renderEditable.hasFocus) {
_longPressStartedWithoutFocus = true;
renderEditable.selectWord(cause: SelectionChangedCause.longPress);
} else if (renderEditable.readOnly) {
renderEditable.selectWord(cause: SelectionChangedCause.longPress);
if (editableText.context.mounted) {
Feedback.forLongPress(editableText.context);
}
} else {
renderEditable.selectPositionAt(
from: details.globalPosition,
cause: SelectionChangedCause.longPress,
);
// Show the floating cursor.
final RawFloatingCursorPoint cursorPoint = RawFloatingCursorPoint(
state: FloatingCursorDragState.Start,
startLocation: (
renderEditable.globalToLocal(details.globalPosition),
TextPosition(
offset: editableText.textEditingValue.selection.baseOffset,
affinity: editableText.textEditingValue.selection.affinity,
),
),
offset: Offset.zero,
);
editableText.updateFloatingCursor(cursorPoint);
}
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
renderEditable.selectWord(cause: SelectionChangedCause.longPress);
if (editableText.context.mounted) {
Feedback.forLongPress(editableText.context);
}
}
_showMagnifierIfSupportedByPlatform(details.globalPosition);
_dragStartViewportOffset = renderEditable.offset.pixels;
_dragStartScrollOffset = _scrollPosition;
}
/// Handler for [TextSelectionGestureDetector.onSingleLongTapMoveUpdate].
@@ -2548,49 +2567,50 @@ class TextSelectionGestureDetectorBuilder {
/// triggers this callback.
@protected
void onSingleLongTapMoveUpdate(LongPressMoveUpdateDetails details) {
if (delegate.selectionEnabled) {
// Adjust the drag start offset for possible viewport offset changes.
final Offset editableOffset = renderEditable.maxLines == 1
? Offset(renderEditable.offset.pixels - _dragStartViewportOffset, 0.0)
: Offset(0.0, renderEditable.offset.pixels - _dragStartViewportOffset);
final Offset scrollableOffset = switch (axisDirectionToAxis(_scrollDirection ?? AxisDirection.left)) {
Axis.horizontal => Offset(_scrollPosition - _dragStartScrollOffset, 0.0),
Axis.vertical => Offset(0.0, _scrollPosition - _dragStartScrollOffset),
};
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
case TargetPlatform.macOS:
if (_longPressStartedWithoutFocus) {
renderEditable.selectWordsInRange(
from: details.globalPosition - details.offsetFromOrigin - editableOffset - scrollableOffset,
to: details.globalPosition,
cause: SelectionChangedCause.longPress,
);
} else {
renderEditable.selectPositionAt(
from: details.globalPosition,
cause: SelectionChangedCause.longPress,
);
// Update the floating cursor.
final RawFloatingCursorPoint cursorPoint = RawFloatingCursorPoint(
state: FloatingCursorDragState.Update,
offset: details.offsetFromOrigin,
);
editableText.updateFloatingCursor(cursorPoint);
}
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
if (!delegate.selectionEnabled) {
return;
}
// Adjust the drag start offset for possible viewport offset changes.
final Offset editableOffset = renderEditable.maxLines == 1
? Offset(renderEditable.offset.pixels - _dragStartViewportOffset, 0.0)
: Offset(0.0, renderEditable.offset.pixels - _dragStartViewportOffset);
final Offset scrollableOffset = switch (axisDirectionToAxis(_scrollDirection ?? AxisDirection.left)) {
Axis.horizontal => Offset(_scrollPosition - _dragStartScrollOffset, 0.0),
Axis.vertical => Offset(0.0, _scrollPosition - _dragStartScrollOffset),
};
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
case TargetPlatform.macOS:
if (_longPressStartedWithoutFocus || renderEditable.readOnly) {
renderEditable.selectWordsInRange(
from: details.globalPosition - details.offsetFromOrigin - editableOffset - scrollableOffset,
to: details.globalPosition,
cause: SelectionChangedCause.longPress,
);
}
_showMagnifierIfSupportedByPlatform(details.globalPosition);
} else {
renderEditable.selectPositionAt(
from: details.globalPosition,
cause: SelectionChangedCause.longPress,
);
// Update the floating cursor.
final RawFloatingCursorPoint cursorPoint = RawFloatingCursorPoint(
state: FloatingCursorDragState.Update,
offset: details.offsetFromOrigin,
);
editableText.updateFloatingCursor(cursorPoint);
}
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
renderEditable.selectWordsInRange(
from: details.globalPosition - details.offsetFromOrigin - editableOffset - scrollableOffset,
to: details.globalPosition,
cause: SelectionChangedCause.longPress,
);
}
_showMagnifierIfSupportedByPlatform(details.globalPosition);
}
/// Handler for [TextSelectionGestureDetector.onSingleLongTapEnd].

View File

@@ -3593,7 +3593,7 @@ void main() {
);
testWidgets(
'long press tap cannot initiate a double tap',
'long press tap cannot initiate a double tap on macOS',
(WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
@@ -3622,18 +3622,56 @@ void main() {
final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first);
final TextEditingController controller = editableTextWidget.controller;
// On iOS, we ended up moving the cursor to the edge of the same word and dismissed
// the toolbar.
//
// On macOS, we move the cursor to the tapped position.
// Move the cursor to the tapped position.
expect(
controller.selection,
TextSelection.collapsed(offset: defaultTargetPlatform == TargetPlatform.iOS ? 7 : 4, affinity: TextAffinity.upstream),
const TextSelection.collapsed(offset: 4, affinity: TextAffinity.upstream),
);
expect(find.byType(CupertinoButton), findsNothing);
},
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }),
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
);
testWidgets(
'long press tap cannot initiate a double tap on iOS',
(WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
home: Material(
child: Center(
child: SelectableText('Atwater Peel Sherbrooke Bonaventure'),
),
),
),
);
final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText));
await tester.longPressAt(selectableTextStart + const Offset(50.0, 5.0));
await tester.pump(const Duration(milliseconds: 50));
// Hide the toolbar so it doesn't interfere with taps on the text.
final EditableTextState editableTextState =
tester.state<EditableTextState>(find.byType(EditableText));
editableTextState.hideToolbar();
await tester.pumpAndSettle();
await tester.tapAt(selectableTextStart + const Offset(50.0, 5.0));
await tester.pump();
final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first);
final TextEditingController controller = editableTextWidget.controller;
// Move the cursor to the edge of the same word and toggle the toolbar.
expect(
controller.selection,
const TextSelection(baseOffset: 0, extentOffset: 7),
);
expect(find.byType(CupertinoButton), findsNWidgets(4));
},
variant: TargetPlatformVariant.only(TargetPlatform.iOS),
);
testWidgets(
@@ -4342,13 +4380,17 @@ void main() {
await tester.pumpAndSettle(kDoubleTapTimeout);
await tester.tapAt(selectableTextStart + const Offset(10.0, 5.0));
await tester.pump(const Duration(milliseconds: 50));
// First tap moved the cursor.
// First tap moved the cursor and toggled the toolbar.
expect(find.byType(CupertinoButton), findsNothing);
expect(
controller.selection,
TextSelection.collapsed(offset: defaultTargetPlatform == TargetPlatform.iOS ? 7 : 1, affinity: TextAffinity.upstream),
defaultTargetPlatform == TargetPlatform.iOS ? const TextSelection(baseOffset: 0, extentOffset: 7) : const TextSelection.collapsed(offset: 1, affinity: TextAffinity.upstream),
);
await tester.tapAt(selectableTextStart + const Offset(10.0, 5.0));
await tester.pump(const Duration(milliseconds: 50));
// Second tap toggled the toolbar, and on macOS also selects the word at the tapped position.
// On iOS the selection remains the same.
expect(
controller.selection,
const TextSelection(baseOffset: 0, extentOffset: 7),