-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbutton.dart
694 lines (610 loc) · 19.3 KB
/
button.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
import 'dart:async';
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'control.dart';
import 'focusable_control_mixin.dart';
import 'hover_region.dart';
class ButtonState {
ButtonState({
this.selected = SelectionState.off,
this.enabled = false,
this.focused = false,
this.hovered = false,
this.pressed = false,
this.tracked = false,
});
/// Determines selection state of the control.
final SelectionState selected;
/// Control is enabled and can be interacted with.
final bool enabled;
/// Control has keyboard focus.
final bool focused;
/// Control is being hovered over by a pointer.
final bool hovered;
/// Control is being pressed. When pointer is released without leaving the
/// control, the control will receive a tap event.
final bool pressed;
/// Control is receiving pointer events but the pointer may or may not be
/// hovering over the control.
final bool tracked;
/// Returns the state of the nearest control above this context, or null if
/// there is no control in the tree above this context.
static ButtonState? maybeOf(BuildContext context) {
return context
.dependOnInheritedWidgetOfExactType<_ButtonStateProvider>()
?.state;
}
/// Returns the state of the nearest control above this context.
static ButtonState of(BuildContext context) {
final state = ButtonState.maybeOf(context);
assert(state != null,
'ButtonState.of() called with a context that does not contain a Button.');
return state!;
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
(other is ButtonState &&
other.selected == selected &&
other.enabled == enabled &&
other.focused == focused &&
other.hovered == hovered &&
other.pressed == pressed &&
other.tracked == tracked);
@override
int get hashCode => Object.hash(
selected,
enabled,
focused,
hovered,
pressed,
tracked,
);
@override
String toString() {
final res = StringBuffer();
void append(String text) {
if (res.isNotEmpty) {
res.write(', ');
}
res.write(text);
}
if (selected != SelectionState.off) {
append(selected.name);
}
if (enabled) {
append('enabled');
}
if (focused) {
append('focused');
}
if (hovered) {
append('hovered');
}
if (pressed) {
append('pressed');
}
if (tracked) {
append('tracked');
}
return 'ControlState($res)';
}
}
typedef ButtonBuilder = Widget Function(
BuildContext context,
ButtonState state,
Widget? child,
);
class Button extends StatefulWidget {
const Button({
super.key,
this.onPressed,
this.child,
required this.builder,
this.onPressedDown,
this.pressDownDelay = Duration.zero,
this.onKeyEvent,
this.focusNode,
this.tapToFocus = false,
this.keyUpTimeout,
this.triggerKeys = const [LogicalKeyboardKey.space],
this.selected = SelectionState.off,
this.cursor = SystemMouseCursors.basic,
this.hitTestBehavior = HitTestBehavior.deferToChild,
this.isSemanticButton = true,
this.touchExtraTolerance = EdgeInsets.zero,
this.mouseExtraTolerance = EdgeInsets.zero,
});
/// Callback fired when button is pressed and released.
///
/// If [onPressed] returns a [Future], the button will be considered
/// pressed until the future completes.
final FutureOr<void> Function()? onPressed;
/// Callback fired when button is pressed down, but not released yet.
/// The amount of time button has to be pressed down for the callback to
/// fire is determined by [pressDownDelay].
///
/// In case when [onPressedDown] is fired, [onPressed] will not be fired.
///
/// If [onPressedDown] returns a [Future], the button will be considered
/// pressed until the future completes.
final FutureOr<void> Function()? onPressedDown;
/// Controls the amount of time button has to be pressed down for
/// [onPressedDown] to fire. Defaults to [Duration.zero].
/// With non-zero [pressDownDelay] it is possible for long press to
/// trigger [onPressedDown], while short click will trigger [onPressed].
final Duration pressDownDelay;
/// Optional child to be passed to [builder].
final Widget? child;
/// Builder responsible for rendering the button.
final ButtonBuilder builder;
final MouseCursor cursor;
final SelectionState selected;
/// Set of keyboard keys that should trigger [onPressed] callback.
/// on MacOS it is customary for button to be only submitted when pressing
/// space. On Windows and Linux, pressing enter key on focused button should
/// trigger [onPressed] callback as well.
// (List instead Set because LogicalKeyboardKey overrides equals/hashCode)
final List<LogicalKeyboardKey> triggerKeys;
/// Optional callback to be called when key event is received.
final KeyEventResult? Function(KeyEvent)? onKeyEvent;
/// Optional focus node to be used for this button. If not specified
/// button will manage the focus node internally.
final FocusNode? focusNode;
/// If set to true, button will request focus when tapped. This is common
/// behavior on Windows.
final bool tapToFocus;
/// If set to true, button will be considered a button in accessibility
/// tree. Defaults to true.
final bool isSemanticButton;
/// Extra inset to be added to button bounds on touch devices when determining
/// whether button is considered pressed while being in [ControlState.tracked] state.
final EdgeInsets touchExtraTolerance;
/// Extra inset to be added to button bounds for mouse devices when determining
/// whether button is considered pressed while being in [ControlState.tracked] state.
final EdgeInsets mouseExtraTolerance;
/// If set the button will be considered pressed when `keyUpTimeout`
/// elapsed after the key down event. This is common behavior on macOS
/// and Linux.
final Duration? keyUpTimeout;
/// Controls how the button behaves during hit testing.
final HitTestBehavior hitTestBehavior;
@override
State<StatefulWidget> createState() => _ButtonState();
}
class ButtonGroup extends StatefulWidget {
const ButtonGroup({
super.key,
required this.child,
this.onActiveButtonChanged,
this.allowedDeviceKind = const {PointerDeviceKind.touch},
});
final Widget child;
final VoidCallback? onActiveButtonChanged;
final Set<PointerDeviceKind> allowedDeviceKind;
@override
State<StatefulWidget> createState() => _ButtonGroupState();
}
//
//
//
class _ButtonState extends State<Button> with FocusableControlMixin<Button> {
void _focusDidChange() {
_keyUpTimer?.cancel();
_keyUpTimer = null;
setState(() {});
if (focusNode.hasFocus) {
final ro = context.findRenderObject();
if (ro != null) {
ro.showOnScreen();
}
} else if (_keyPressed) {
_keyPressed = false;
_keyUpTimer?.cancel();
_keyUpTimer = null;
}
}
final _detector = GlobalKey();
bool _hovered = false;
bool _inside = false;
bool _tracked = false;
bool _keyPressed = false;
bool _waitingOnFuture = false;
bool get _pressed => (_tracked && _inside) || _keyPressed;
bool get _enabled => widget.onPressed != null || widget.onPressedDown != null;
void _update({
bool? hovered,
bool? inside,
bool? pointerPressed,
bool? keyPressed,
bool? futurePressed,
bool cancelled = false,
}) {
final pressedBefore = _pressed;
setState(() {
if (hovered != null) {
_hovered = hovered;
}
if (inside != null) {
_inside = inside;
}
if (pointerPressed != null) {
_tracked = pointerPressed;
}
if (keyPressed != null) {
_keyPressed = keyPressed;
}
if (futurePressed != null) {
_waitingOnFuture = futurePressed;
}
});
if (!pressedBefore && _pressed) {
if (widget.onPressedDown != null) {
assert(_pressedDownTimer == null);
void handlePressDown() {
_didFireLongPress = true;
final res = widget.onPressedDown?.call();
if (res is Future) {
_update(futurePressed: true);
res.then((value) {
_update(futurePressed: false);
}, onError: (error) {
_update(futurePressed: false);
});
}
}
if (widget.pressDownDelay == Duration.zero) {
handlePressDown();
} else {
_pressedDownTimer = Timer(widget.pressDownDelay, () {
_pressedDownTimer = null;
handlePressDown();
});
}
}
}
if (pressedBefore &&
!_keyPressed &&
!_tracked &&
!_waitingOnFuture &&
!cancelled) {
if (!_didFireLongPress) {
_onPressed();
}
}
if (!_pressed) {
_pressedDownTimer?.cancel();
_pressedDownTimer = null;
_didFireLongPress = false;
}
if (!pressedBefore &&
keyPressed == true &&
widget.keyUpTimeout != null &&
widget.onPressedDown == null) {
_keyUpTimer = Timer(widget.keyUpTimeout!, () {
_keyUpTimer = null;
// Timer should be invalidated when unsetting _keyPressed;
assert(_keyPressed);
_update(keyPressed: false);
});
}
}
void _onPressed() {
if (widget.onPressed != null) {
final res = widget.onPressed?.call();
if (res is Future) {
_update(futurePressed: true);
res.then((value) {
_update(futurePressed: false);
}, onError: (error) {
_update(futurePressed: false);
});
}
}
_keyUpTimer?.cancel();
_keyUpTimer = null;
}
Timer? _keyUpTimer;
Timer? _pressedDownTimer;
bool _didFireLongPress = false;
@override
KeyEventResult onKeyEvent(FocusNode node, KeyEvent event) {
assert(node == focusNode);
if (!_enabled) {
return KeyEventResult.ignored;
}
final widgetResult = widget.onKeyEvent?.call(event);
if (widgetResult != null) {
return widgetResult;
}
final isTriggerKey = widget.triggerKeys.contains(event.logicalKey);
if (isTriggerKey) {
if (event is KeyDownEvent) {
_update(keyPressed: true);
return KeyEventResult.handled;
} else if (event is KeyUpEvent) {
_update(keyPressed: false);
return KeyEventResult.handled;
} else if (event is KeyRepeatEvent) {
return KeyEventResult.handled;
}
}
return KeyEventResult.ignored;
}
@override
void dispose() {
super.dispose();
_keyUpTimer?.cancel();
_keyUpTimer = null;
_pressedDownTimer?.cancel();
_pressedDownTimer = null;
_buttonGroup?._buttons.remove(this);
}
void _onTapUp(TapUpDetails details) {
if (!_tracked && !_inside) {
// These have been cleared by pan gesture recognizer cancel. Revert
// so that _update fires onPressed callback.
_tracked = true;
_inside = true;
}
_update(inside: false, pointerPressed: false);
}
void _onPanDown(DragDownDetails details, PointerDeviceKind kind) {
_update(inside: true, pointerPressed: true);
if (widget.tapToFocus) {
// This is an oversight in how traversal is implemented in Flutter
// currently. Manually changing focus doesn't reset traversal history,
// which can result in unexpected directional movement after.
FocusTraversalGroup.of(context)
// ignore: invalid_use_of_protected_member
.invalidateScopeData(focusNode.nearestScope!);
FocusScope.of(context).requestFocus(focusNode);
}
}
void _onPanUpdate(DragUpdateDetails details, PointerDeviceKind kind) {
Rect bounds = Offset.zero & context.size!;
if (kind == PointerDeviceKind.touch) {
bounds = widget.touchExtraTolerance.inflateRect(bounds);
} else if (kind == PointerDeviceKind.mouse) {
bounds = widget.mouseExtraTolerance.inflateRect(bounds);
}
final isInside = bounds.contains(details.localPosition);
_update(inside: isInside);
}
void _onPanEnd(DragEndDetails _) {
_update(pointerPressed: false, inside: false);
}
void _onPanCancel() {
_update(pointerPressed: false, inside: false, cancelled: true);
}
late _PanGestureRecognizer _panGestureRecognizer;
_ButtonGroupState? _buttonGroup;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_buttonGroup?._buttons.remove(this);
_buttonGroup = context.findAncestorStateOfType<_ButtonGroupState>();
_buttonGroup?._buttons.add(this);
}
Map<Type, GestureRecognizerFactory> _buildGestures() {
int currentPointer() =>
_panGestureRecognizer._lastPointerDownEvent!.pointer;
PointerDeviceKind currentDeviceKind() =>
_panGestureRecognizer._lastPointerDownEvent!.kind;
return {
TapGestureRecognizer:
GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>(
() => TapGestureRecognizer(),
(instance) {
instance.onTapUp = _onTapUp;
},
),
_PanGestureRecognizer:
GestureRecognizerFactoryWithHandlers<_PanGestureRecognizer>(
() => _PanGestureRecognizer(), (instance) {
_panGestureRecognizer = instance;
instance.onDown = (details) {
if (_buttonGroup != null) {
_buttonGroup!
._onPanDown(currentPointer(), currentDeviceKind(), details);
} else {
_onPanDown(details, currentDeviceKind());
}
};
instance.onUpdate = (details) {
if (_buttonGroup != null) {
_buttonGroup!
._onPanUpdate(currentPointer(), currentDeviceKind(), details);
} else {
_onPanUpdate(details, currentDeviceKind());
}
};
instance.onEnd = (details) {
if (_buttonGroup != null) {
_buttonGroup!._onPanEnd(currentPointer(), details);
} else {
_onPanEnd(details);
}
};
instance.onCancel = () {
if (_buttonGroup != null) {
_buttonGroup!._onPanCancel(
_panGestureRecognizer._lastPointerDownEvent?.pointer ?? 0,
);
} else {
_onPanCancel();
}
};
}),
};
}
@override
Widget build(BuildContext context) {
bool noButtonInGroupTracked() {
if (_buttonGroup == null) {
return true;
}
return _buttonGroup!._buttons.every(
(element) => !element._tracked,
);
}
final state = ButtonState(
selected: widget.selected,
enabled: _enabled,
focused: _enabled && focusNode.hasFocus,
hovered: _enabled && _hovered && !_tracked && noButtonInGroupTracked(),
pressed: _enabled && (_pressed || _waitingOnFuture),
tracked: _enabled && _tracked,
);
return Semantics(
button: widget.isSemanticButton,
container: true,
enabled: _enabled,
onTap: _onPressed,
child: Focus.withExternalFocusNode(
focusNode: focusNode,
onFocusChange: (_) {
_focusDidChange();
},
child: HoverRegion(
cursor: _enabled ? widget.cursor : MouseCursor.defer,
onEnter: (event) {
_update(hovered: true);
},
onExit: (event) {
_update(hovered: false);
},
child: RawGestureDetector(
behavior: widget.hitTestBehavior,
key: _detector,
gestures: _buildGestures(),
child: _ButtonStateProvider(
state: state,
child: widget.builder(context, state, widget.child),
),
),
),
),
);
}
@override
FocusNode? getWidgetFocusNode(Button widget) => widget.focusNode;
@override
bool get widgetIsEnabled => _enabled;
}
class _PanGestureRecognizer extends PanGestureRecognizer {
@override
bool isPointerPanZoomAllowed(PointerPanZoomStartEvent event) {
return false;
}
PointerDownEvent? _lastPointerDownEvent;
@override
void addAllowedPointer(PointerDownEvent event) {
_lastPointerDownEvent = event;
super.addAllowedPointer(event);
}
@override
bool isPointerAllowed(PointerEvent event) {
if (event.kind == PointerDeviceKind.mouse) {
return event.buttons == 1;
}
return super.isPointerAllowed(event);
}
}
class _ButtonGroupState extends State<ButtonGroup> {
@override
Widget build(BuildContext context) {
return widget.child;
}
_ButtonState? buttonForOffset(Offset globalPosition) {
for (final button in _buttons) {
if (!button._enabled) {
continue;
}
final local = getLocalPosition(globalPosition, button);
final rect = Offset.zero & button.context.size!;
if (rect.contains(local)) {
return button;
}
}
return null;
}
Offset getLocalPosition(Offset globalPosition, _ButtonState state) {
final ro = state.context.findRenderObject()!;
final transform = ro.getTransformTo(null)..invert();
return MatrixUtils.transformPoint(transform, globalPosition);
}
void _onPanDown(
int pointer,
PointerDeviceKind deviceKind,
DragDownDetails details,
) {
assert(!_pointerToButton.containsKey(pointer));
final button = buttonForOffset(details.globalPosition);
if (button != null) {
_pointerToButton[pointer] = button;
final detailsTranslated = DragDownDetails(
globalPosition: details.globalPosition,
localPosition: getLocalPosition(details.globalPosition, button),
);
button._onPanDown(detailsTranslated, deviceKind);
}
}
void _onPanUpdate(
int pointer,
PointerDeviceKind deviceKind,
DragUpdateDetails details,
) {
final button = widget.allowedDeviceKind.contains(deviceKind)
? buttonForOffset(details.globalPosition) ?? _pointerToButton[pointer]
: _pointerToButton[pointer];
if (button == null) {
return; // can happen when starting with disabled button.
}
final localPosition = getLocalPosition(details.globalPosition, button);
if (button != _pointerToButton[pointer]) {
_pointerToButton[pointer]?._onPanCancel();
_pointerToButton[pointer]?._onPanEnd(DragEndDetails());
_pointerToButton[pointer] = button;
widget.onActiveButtonChanged?.call();
button._onPanDown(
DragDownDetails(
globalPosition: details.globalPosition,
localPosition: localPosition,
),
deviceKind,
);
}
final detailsTranslated = DragUpdateDetails(
globalPosition: details.globalPosition,
localPosition: localPosition,
);
button._onPanUpdate(detailsTranslated, deviceKind);
}
void _onPanEnd(int pointer, DragEndDetails details) {
final button = _pointerToButton.remove(pointer);
if (button != null) {
button._onPanEnd(details);
}
}
void _onPanCancel(int pointer) {
final button = _pointerToButton.remove(pointer);
if (button != null) {
button._onPanCancel();
}
}
final _pointerToButton = <int, _ButtonState>{};
final _buttons = <_ButtonState>{};
}
class _ButtonStateProvider extends InheritedWidget {
const _ButtonStateProvider({
required super.child,
required this.state,
});
final ButtonState state;
@override
bool updateShouldNotify(covariant _ButtonStateProvider oldWidget) {
return oldWidget.state != state;
}
}