Skip to content

Commit

Permalink
Mac Page Up / Page Down in text fields (#105497)
Browse files Browse the repository at this point in the history
Adds support for Mac/iOS's behavior of scrolling (but not moving the cursor) when using page up/down in a text field.
  • Loading branch information
justinmc authored Nov 7, 2022
1 parent 497a528 commit 7e36cf1
Show file tree
Hide file tree
Showing 6 changed files with 300 additions and 18 deletions.
5 changes: 4 additions & 1 deletion packages/flutter/lib/src/widgets/app.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1767,7 +1767,10 @@ class _WidgetsAppState extends State<WidgetsApp> with WidgetsBindingObserver {
// fall through to the defaultShortcuts.
child: DefaultTextEditingShortcuts(
child: Actions(
actions: widget.actions ?? WidgetsApp.defaultActions,
actions: widget.actions ?? <Type, Action<Intent>>{
...WidgetsApp.defaultActions,
ScrollIntent: Action<ScrollIntent>.overridable(context: context, defaultAction: ScrollAction()),
},
child: FocusTraversalGroup(
policy: ReadingOrderTraversalPolicy(),
child: TapRegionSurface(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
// found in the LICENSE file.

import 'package:flutter/foundation.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/services.dart';

import 'actions.dart';
import 'focus_traversal.dart';
import 'framework.dart';
import 'scrollable.dart';
import 'shortcuts.dart';
import 'text_editing_intents.dart';

Expand Down Expand Up @@ -157,8 +159,8 @@ class DefaultTextEditingShortcuts extends StatelessWidget {
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;

// These are shortcuts are shared between most platforms except macOS for it
// uses different modifier keys as the line/word modifier.
// These shortcuts are shared between all platforms except Apple platforms,
// because they use different modifier keys as the line/word modifier.
static final Map<ShortcutActivator, Intent> _commonShortcuts = <ShortcutActivator, Intent>{
// Delete Shortcuts.
for (final bool pressShift in const <bool>[true, false])
Expand Down Expand Up @@ -315,6 +317,8 @@ class DefaultTextEditingShortcuts extends StatelessWidget {
const SingleActivator(LogicalKeyboardKey.home, shift: true): const ExpandSelectionToDocumentBoundaryIntent(forward: false),
const SingleActivator(LogicalKeyboardKey.end, shift: true): const ExpandSelectionToDocumentBoundaryIntent(forward: true),

const SingleActivator(LogicalKeyboardKey.pageUp): const ScrollIntent(direction: AxisDirection.up, type: ScrollIncrementType.page),
const SingleActivator(LogicalKeyboardKey.pageDown): const ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page),
const SingleActivator(LogicalKeyboardKey.pageUp, shift: true): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: false, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.pageDown, shift: true): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: false),

Expand Down Expand Up @@ -553,9 +557,8 @@ Intent? intentForMacOSSelector(String selectorName) {
'scrollToBeginningOfDocument:': ScrollToDocumentBoundaryIntent(forward: false),
'scrollToEndOfDocument:': ScrollToDocumentBoundaryIntent(forward: true),

// TODO(knopp): Page Up/Down intents are missing (https://github.com/flutter/flutter/pull/105497)
'scrollPageUp:': ScrollToDocumentBoundaryIntent(forward: false),
'scrollPageDown:': ScrollToDocumentBoundaryIntent(forward: true),
'scrollPageUp:': ScrollIntent(direction: AxisDirection.up, type: ScrollIncrementType.page),
'scrollPageDown:': ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page),
'pageUpAndModifySelection:': ExtendSelectionVerticallyToAdjacentPageIntent(forward: false, collapseSelection: false),
'pageDownAndModifySelection:': ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: false),

Expand Down
95 changes: 95 additions & 0 deletions packages/flutter/lib/src/widgets/editable_text.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import 'media_query.dart';
import 'scroll_configuration.dart';
import 'scroll_controller.dart';
import 'scroll_physics.dart';
import 'scroll_position.dart';
import 'scrollable.dart';
import 'shortcuts.dart';
import 'spell_check.dart';
Expand Down Expand Up @@ -1907,6 +1908,7 @@ class EditableTextState extends State<EditableText> with AutomaticKeepAliveClien

TextSelectionOverlay? _selectionOverlay;

final GlobalKey _scrollableKey = GlobalKey();
ScrollController? _internalScrollController;
ScrollController get _scrollController => widget.scrollController ?? (_internalScrollController ??= ScrollController());

Expand Down Expand Up @@ -3953,6 +3955,96 @@ class EditableTextState extends State<EditableText> with AutomaticKeepAliveClien
}
}

/// Handles [ScrollIntent] by scrolling the [Scrollable] inside of
/// [EditableText].
void _scroll(ScrollIntent intent) {
if (intent.type != ScrollIncrementType.page) {
return;
}

final ScrollPosition position = _scrollController.position;
if (widget.maxLines == 1) {
_scrollController.jumpTo(position.maxScrollExtent);
return;
}

// If the field isn't scrollable, do nothing. For example, when the lines of
// text is less than maxLines, the field has nothing to scroll.
if (position.maxScrollExtent == 0.0 && position.minScrollExtent == 0.0) {
return;
}

final ScrollableState? state = _scrollableKey.currentState as ScrollableState?;
final double increment = ScrollAction.getDirectionalIncrement(state!, intent);
final double destination = clampDouble(
position.pixels + increment,
position.minScrollExtent,
position.maxScrollExtent,
);
if (destination == position.pixels) {
return;
}
_scrollController.jumpTo(destination);
}

/// Extend the selection down by page if the `forward` parameter is true, or
/// up by page otherwise.
void _extendSelectionByPage(ExtendSelectionByPageIntent intent) {
if (widget.maxLines == 1) {
return;
}

final TextSelection nextSelection;
final Rect extentRect = renderEditable.getLocalRectForCaret(
_value.selection.extent,
);
final ScrollableState? state = _scrollableKey.currentState as ScrollableState?;
final double increment = ScrollAction.getDirectionalIncrement(
state!,
ScrollIntent(
direction: intent.forward ? AxisDirection.down : AxisDirection.up,
type: ScrollIncrementType.page,
),
);
final ScrollPosition position = _scrollController.position;
if (intent.forward) {
if (_value.selection.extentOffset >= _value.text.length) {
return;
}
final Offset nextExtentOffset =
Offset(extentRect.left, extentRect.top + increment);
final double height = position.maxScrollExtent + renderEditable.size.height;
final TextPosition nextExtent = nextExtentOffset.dy + position.pixels >= height
? TextPosition(offset: _value.text.length)
: renderEditable.getPositionForPoint(
renderEditable.localToGlobal(nextExtentOffset),
);
nextSelection = _value.selection.copyWith(
extentOffset: nextExtent.offset,
);
} else {
if (_value.selection.extentOffset <= 0) {
return;
}
final Offset nextExtentOffset =
Offset(extentRect.left, extentRect.top + increment);
final TextPosition nextExtent = nextExtentOffset.dy + position.pixels <= 0
? const TextPosition(offset: 0)
: renderEditable.getPositionForPoint(
renderEditable.localToGlobal(nextExtentOffset),
);
nextSelection = _value.selection.copyWith(
extentOffset: nextExtent.offset,
);
}

bringIntoView(nextSelection.extent);
userUpdateTextEditingValue(
_value.copyWith(selection: nextSelection),
SelectionChangedCause.keyboard,
);
}

void _updateSelection(UpdateSelectionIntent intent) {
bringIntoView(intent.newSelection.extent);
userUpdateTextEditingValue(
Expand Down Expand Up @@ -4058,6 +4150,7 @@ class EditableTextState extends State<EditableText> with AutomaticKeepAliveClien

// Extend/Move Selection
ExtendSelectionByCharacterIntent: _makeOverridable(_UpdateTextSelectionAction<ExtendSelectionByCharacterIntent>(this, false, _characterBoundary)),
ExtendSelectionByPageIntent: _makeOverridable(CallbackAction<ExtendSelectionByPageIntent>(onInvoke: _extendSelectionByPage)),
ExtendSelectionToNextWordBoundaryIntent: _makeOverridable(_UpdateTextSelectionAction<ExtendSelectionToNextWordBoundaryIntent>(this, true, _nextWordBoundary)),
ExtendSelectionToLineBreakIntent: _makeOverridable(_UpdateTextSelectionAction<ExtendSelectionToLineBreakIntent>(this, true, _linebreak)),
ExpandSelectionToLineBreakIntent: _makeOverridable(CallbackAction<ExpandSelectionToLineBreakIntent>(onInvoke: _expandSelectionToLinebreak)),
Expand All @@ -4067,6 +4160,7 @@ class EditableTextState extends State<EditableText> with AutomaticKeepAliveClien
ExtendSelectionToDocumentBoundaryIntent: _makeOverridable(_UpdateTextSelectionAction<ExtendSelectionToDocumentBoundaryIntent>(this, true, _documentBoundary)),
ExtendSelectionToNextWordBoundaryOrCaretLocationIntent: _makeOverridable(_ExtendSelectionOrCaretPositionAction(this, _nextWordBoundary)),
ScrollToDocumentBoundaryIntent: _makeOverridable(CallbackAction<ScrollToDocumentBoundaryIntent>(onInvoke: _scrollToDocumentBoundary)),
ScrollIntent: CallbackAction<ScrollIntent>(onInvoke: _scroll),

// Copy Paste
SelectAllTextIntent: _makeOverridable(_SelectAllAction(this)),
Expand Down Expand Up @@ -4099,6 +4193,7 @@ class EditableTextState extends State<EditableText> with AutomaticKeepAliveClien
includeSemantics: false,
debugLabel: kReleaseMode ? null : 'EditableText',
child: Scrollable(
key: _scrollableKey,
excludeFromSemantics: true,
axisDirection: _isMultiline ? AxisDirection.down : AxisDirection.right,
controller: _scrollController,
Expand Down
24 changes: 12 additions & 12 deletions packages/flutter/lib/src/widgets/scrollable.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1789,14 +1789,14 @@ class ScrollAction extends Action<ScrollIntent> {
return false;
}

// Returns the scroll increment for a single scroll request, for use when
// scrolling using a hardware keyboard.
//
// Must not be called when the position is null, or when any of the position
// metrics (pixels, viewportDimension, maxScrollExtent, minScrollExtent) are
// null. The type and state arguments must not be null, and the widget must
// have already been laid out so that the position fields are valid.
double _calculateScrollIncrement(ScrollableState state, { ScrollIncrementType type = ScrollIncrementType.line }) {
/// Returns the scroll increment for a single scroll request, for use when
/// scrolling using a hardware keyboard.
///
/// Must not be called when the position is null, or when any of the position
/// metrics (pixels, viewportDimension, maxScrollExtent, minScrollExtent) are
/// null. The type and state arguments must not be null, and the widget must
/// have already been laid out so that the position fields are valid.
static double _calculateScrollIncrement(ScrollableState state, { ScrollIncrementType type = ScrollIncrementType.line }) {
assert(type != null);
assert(state.position != null);
assert(state.position.hasPixels);
Expand All @@ -1820,9 +1820,9 @@ class ScrollAction extends Action<ScrollIntent> {
}
}

// Find out how much of an increment to move by, taking the different
// directions into account.
double _getIncrement(ScrollableState state, ScrollIntent intent) {
/// Find out how much of an increment to move by, taking the different
/// directions into account.
static double getDirectionalIncrement(ScrollableState state, ScrollIntent intent) {
final double increment = _calculateScrollIncrement(state, type: intent.type);
switch (intent.direction) {
case AxisDirection.down:
Expand Down Expand Up @@ -1912,7 +1912,7 @@ class ScrollAction extends Action<ScrollIntent> {
if (state!._physics != null && !state._physics!.shouldAcceptUserOffset(state.position)) {
return;
}
final double increment = _getIncrement(state, intent);
final double increment = getDirectionalIncrement(state, intent);
if (increment == 0.0) {
return;
}
Expand Down
9 changes: 9 additions & 0 deletions packages/flutter/lib/src/widgets/text_editing_intents.dart
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,15 @@ class ScrollToDocumentBoundaryIntent extends DirectionalTextEditingIntent {
}) : super(forward);
}

/// Scrolls up or down by page depending on the [forward] parameter.
/// Extends the selection up or down by page based on the [forward] parameter.
class ExtendSelectionByPageIntent extends DirectionalTextEditingIntent {
/// Creates a [ExtendSelectionByPageIntent].
const ExtendSelectionByPageIntent({
required bool forward,
}) : super(forward);
}

/// An [Intent] to select everything in the field.
class SelectAllTextIntent extends Intent {
/// Creates an instance of [SelectAllTextIntent].
Expand Down
Loading

0 comments on commit 7e36cf1

Please sign in to comment.