-
Notifications
You must be signed in to change notification settings - Fork 10
/
custom_cupertino_text_selection_controls.dart
1270 lines (1121 loc) · 42.1 KB
/
custom_cupertino_text_selection_controls.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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// @dart = 2.8
import 'dart:collection';
import 'dart:math' as math;
import 'dart:ui' as ui;
import 'package:flutter/cupertino.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
// Read off from the output on iOS 12. This color does not vary with the
// application's theme color.
const double _kSelectionHandleOverlap = 1.5;
// Extracted from https://developer.apple.com/design/resources/.
const double _kSelectionHandleRadius = 6;
// Minimal padding from all edges of the selection toolbar to all edges of the
// screen.
const double _kToolbarScreenPadding = 8.0;
// Minimal padding from tip of the selection toolbar arrow to horizontal edges of the
// screen. Eyeballed value.
const double _kArrowScreenPadding = 26.0;
// Vertical distance between the tip of the arrow and the line of text the arrow
// is pointing to. The value used here is eyeballed.
const double _kToolbarContentDistance = 8.0;
// Values derived from https://developer.apple.com/design/resources/.
// 92% Opacity ~= 0xEB
// Values extracted from https://developer.apple.com/design/resources/.
// The height of the toolbar, including the arrow.
const double _kToolbarHeight = 43.0;
const Size _kToolbarArrowSize = Size(14.0, 7.0);
const Radius _kToolbarBorderRadius = Radius.circular(8);
// Colors extracted from https://developer.apple.com/design/resources/.
// TODO(LongCatIsLooong): https://github.com/flutter/flutter/issues/41507.
const Color _kToolbarBackgroundColor = Color(0xEB202020);
const Color _kToolbarDividerColor = Color(0xFF808080);
const TextStyle _kToolbarButtonFontStyle = TextStyle(
inherit: false,
fontSize: 14.0,
letterSpacing: -0.15,
fontWeight: FontWeight.w400,
color: CupertinoColors.white,
);
const TextStyle _kToolbarButtonDisabledFontStyle = TextStyle(
inherit: false,
fontSize: 14.0,
letterSpacing: -0.15,
fontWeight: FontWeight.w400,
color: CupertinoColors.inactiveGray,
);
// Eyeballed value.
const EdgeInsets _kToolbarButtonPadding = EdgeInsets.symmetric(vertical: 10.0, horizontal: 18.0);
// Generates the child that's passed into CupertinoTextSelectionToolbar.
class _CupertinoTextSelectionToolbarWrapper extends StatefulWidget {
const _CupertinoTextSelectionToolbarWrapper({
Key key,
this.arrowTipX,
this.barTopY,
this.clipboardStatus,
this.handleCut,
this.handleCopy,
this.handlePaste,
this.handleSelectAll,
this.handleCancelTarget,
this.isArrowPointingDown,
}) : super(key: key);
final double arrowTipX;
final double barTopY;
final ClipboardStatusNotifier clipboardStatus;
final VoidCallback handleCut;
final VoidCallback handleCopy;
final VoidCallback handlePaste;
final VoidCallback handleSelectAll;
final VoidCallback handleCancelTarget;
final bool isArrowPointingDown;
@override
_CupertinoTextSelectionToolbarWrapperState createState() => _CupertinoTextSelectionToolbarWrapperState();
}
class _CupertinoTextSelectionToolbarWrapperState extends State<_CupertinoTextSelectionToolbarWrapper> {
ClipboardStatusNotifier _clipboardStatus;
void _onChangedClipboardStatus() {
setState(() {
// Inform the widget that the value of clipboardStatus has changed.
});
}
@override
void initState() {
super.initState();
_clipboardStatus = widget.clipboardStatus ?? ClipboardStatusNotifier();
_clipboardStatus.addListener(_onChangedClipboardStatus);
_clipboardStatus.update();
}
@override
void didUpdateWidget(_CupertinoTextSelectionToolbarWrapper oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.clipboardStatus == null && widget.clipboardStatus != null) {
_clipboardStatus.removeListener(_onChangedClipboardStatus);
_clipboardStatus.dispose();
_clipboardStatus = widget.clipboardStatus;
} else if (oldWidget.clipboardStatus != null) {
if (widget.clipboardStatus == null) {
_clipboardStatus = ClipboardStatusNotifier();
_clipboardStatus.addListener(_onChangedClipboardStatus);
oldWidget.clipboardStatus.removeListener(_onChangedClipboardStatus);
} else if (widget.clipboardStatus != oldWidget.clipboardStatus) {
_clipboardStatus = widget.clipboardStatus;
_clipboardStatus.addListener(_onChangedClipboardStatus);
oldWidget.clipboardStatus.removeListener(_onChangedClipboardStatus);
}
}
if (widget.handlePaste != null) {
_clipboardStatus.update();
}
}
@override
void dispose() {
super.dispose();
// When used in an Overlay, this can be disposed after its creator has
// already disposed _clipboardStatus.
if (!_clipboardStatus.disposed) {
_clipboardStatus.removeListener(_onChangedClipboardStatus);
if (widget.clipboardStatus == null) {
_clipboardStatus.dispose();
}
}
}
@override
Widget build(BuildContext context) {
// Don't render the menu until the state of the clipboard is known.
if (widget.handlePaste != null && _clipboardStatus.value == ClipboardStatus.unknown) {
return const SizedBox(width: 0.0, height: 0.0);
}
final List<Widget> items = <Widget>[];
final CupertinoLocalizations localizations = CupertinoLocalizations.of(context);
final EdgeInsets arrowPadding = widget.isArrowPointingDown
? EdgeInsets.only(bottom: _kToolbarArrowSize.height)
: EdgeInsets.only(top: _kToolbarArrowSize.height);
final Widget onePhysicalPixelVerticalDivider = SizedBox(width: 1.0 / MediaQuery.of(context).devicePixelRatio);
void addToolbarButton(
String text,
VoidCallback onPressed,
) {
if (items.isNotEmpty) {
items.add(onePhysicalPixelVerticalDivider);
}
items.add(CupertinoButton(
child: Text(
text,
overflow: TextOverflow.ellipsis,
style: _kToolbarButtonFontStyle,
),
borderRadius: null,
color: _kToolbarBackgroundColor,
minSize: _kToolbarHeight,
onPressed: onPressed,
padding: _kToolbarButtonPadding.add(arrowPadding),
pressedOpacity: 0.7,
));
}
if (widget.handleCut != null) {
addToolbarButton(localizations.cutButtonLabel, widget.handleCut);
}
if (widget.handleCopy != null) {
addToolbarButton(localizations.copyButtonLabel, widget.handleCopy);
}
if (widget.handlePaste != null && _clipboardStatus.value == ClipboardStatus.pasteable) {
addToolbarButton(localizations.pasteButtonLabel, widget.handlePaste);
}
if (widget.handleSelectAll != null) {
addToolbarButton(localizations.selectAllButtonLabel, widget.handleSelectAll);
}
if (widget.handleCancelTarget != null) {
addToolbarButton("dismissReplyPointerTrans".tr, widget.handleCancelTarget);
}
return CupertinoTextSelectionToolbar._(
barTopY: widget.barTopY,
arrowTipX: widget.arrowTipX,
isArrowPointingDown: widget.isArrowPointingDown,
child: items.isEmpty
? null
: _CupertinoTextSelectionToolbarContent(
isArrowPointingDown: widget.isArrowPointingDown,
children: items,
),
);
}
}
/// An iOS-style toolbar that appears in response to text selection.
///
/// Typically displays buttons for text manipulation, e.g. copying and pasting text.
///
/// See also:
///
/// * [TextSelectionControls.buildToolbar], where [CupertinoTextSelectionToolbar]
/// will be used to build an iOS-style toolbar.
@visibleForTesting
class CupertinoTextSelectionToolbar extends SingleChildRenderObjectWidget {
const CupertinoTextSelectionToolbar._({
Key key,
double barTopY,
double arrowTipX,
bool isArrowPointingDown,
Widget child,
}) : _barTopY = barTopY,
_arrowTipX = arrowTipX,
_isArrowPointingDown = isArrowPointingDown,
super(key: key, child: child);
// The y-coordinate of toolbar's top edge, in global coordinate system.
final double _barTopY;
// The y-coordinate of the tip of the arrow, in global coordinate system.
final double _arrowTipX;
// Whether the arrow should point down and be attached to the bottom
// of the toolbar, or point up and be attached to the top of the toolbar.
final bool _isArrowPointingDown;
@override
_ToolbarRenderBox createRenderObject(BuildContext context) =>
_ToolbarRenderBox(_barTopY, _arrowTipX, _isArrowPointingDown, null);
@override
void updateRenderObject(BuildContext context, _ToolbarRenderBox renderObject) {
renderObject
..barTopY = _barTopY
..arrowTipX = _arrowTipX
..isArrowPointingDown = _isArrowPointingDown;
}
}
class _ToolbarParentData extends BoxParentData {
// The x offset from the tip of the arrow to the center of the toolbar.
// Positive if the tip of the arrow has a larger x-coordinate than the
// center of the toolbar.
double arrowXOffsetFromCenter;
@override
String toString() => 'offset=$offset, arrowXOffsetFromCenter=$arrowXOffsetFromCenter';
}
class _ToolbarRenderBox extends RenderShiftedBox {
_ToolbarRenderBox(
this._barTopY,
this._arrowTipX,
this._isArrowPointingDown,
RenderBox child,
) : super(child);
@override
bool get isRepaintBoundary => true;
double _barTopY;
set barTopY(double value) {
if (_barTopY == value) {
return;
}
_barTopY = value;
markNeedsLayout();
markNeedsSemanticsUpdate();
}
double _arrowTipX;
set arrowTipX(double value) {
if (_arrowTipX == value) {
return;
}
_arrowTipX = value;
markNeedsLayout();
markNeedsSemanticsUpdate();
}
bool _isArrowPointingDown;
set isArrowPointingDown(bool value) {
if (_isArrowPointingDown == value) {
return;
}
_isArrowPointingDown = value;
markNeedsLayout();
markNeedsSemanticsUpdate();
}
final BoxConstraints heightConstraint = const BoxConstraints.tightFor(height: _kToolbarHeight);
@override
void setupParentData(RenderObject child) {
if (child.parentData is! _ToolbarParentData) {
child.parentData = _ToolbarParentData();
}
}
@override
void performLayout() {
final BoxConstraints constraints = this.constraints;
size = constraints.biggest;
if (child == null) {
return;
}
final BoxConstraints enforcedConstraint =
constraints.deflate(const EdgeInsets.symmetric(horizontal: _kToolbarScreenPadding)).loosen();
child.layout(
heightConstraint.enforce(enforcedConstraint),
parentUsesSize: true,
);
final _ToolbarParentData childParentData = child.parentData as _ToolbarParentData;
// The local x-coordinate of the center of the toolbar.
final double lowerBound = child.size.width / 2 + _kToolbarScreenPadding;
final double upperBound = size.width - child.size.width / 2 - _kToolbarScreenPadding;
final double adjustedCenterX = _arrowTipX.clamp(lowerBound, upperBound) as double;
childParentData.offset = Offset(adjustedCenterX - child.size.width / 2, _barTopY);
childParentData.arrowXOffsetFromCenter = _arrowTipX - adjustedCenterX;
}
// The path is described in the toolbar's coordinate system.
Path _clipPath() {
final _ToolbarParentData childParentData = child.parentData as _ToolbarParentData;
final Path rrect = Path()
..addRRect(
RRect.fromRectAndRadius(
Offset(
0,
_isArrowPointingDown ? 0 : _kToolbarArrowSize.height,
) &
Size(child.size.width, child.size.height - _kToolbarArrowSize.height),
_kToolbarBorderRadius,
),
);
final double arrowTipX = child.size.width / 2 + childParentData.arrowXOffsetFromCenter;
final double arrowBottomY =
_isArrowPointingDown ? child.size.height - _kToolbarArrowSize.height : _kToolbarArrowSize.height;
final double arrowTipY = _isArrowPointingDown ? child.size.height : 0;
final Path arrow = Path()
..moveTo(arrowTipX, arrowTipY)
..lineTo(arrowTipX - _kToolbarArrowSize.width / 2, arrowBottomY)
..lineTo(arrowTipX + _kToolbarArrowSize.width / 2, arrowBottomY)
..close();
return Path.combine(PathOperation.union, rrect, arrow);
}
@override
void paint(PaintingContext context, Offset offset) {
if (child == null) {
return;
}
final _ToolbarParentData childParentData = child.parentData as _ToolbarParentData;
context.pushClipPath(
needsCompositing,
offset + childParentData.offset,
Offset.zero & child.size,
_clipPath(),
(PaintingContext innerContext, Offset innerOffset) => innerContext.paintChild(child, innerOffset),
);
}
Paint _debugPaint;
@override
void debugPaintSize(PaintingContext context, Offset offset) {
assert(() {
if (child == null) {
return true;
}
_debugPaint ??= Paint()
..shader = ui.Gradient.linear(
const Offset(0.0, 0.0),
const Offset(10.0, 10.0),
<Color>[const Color(0x00000000), const Color(0xFFFF00FF), const Color(0xFFFF00FF), const Color(0x00000000)],
<double>[0.25, 0.25, 0.75, 0.75],
TileMode.repeated,
)
..strokeWidth = 2.0
..style = PaintingStyle.stroke;
final _ToolbarParentData childParentData = child.parentData as _ToolbarParentData;
context.canvas.drawPath(_clipPath().shift(offset + childParentData.offset), _debugPaint);
return true;
}());
}
}
/// Draws a single text selection handle with a bar and a ball.
class _TextSelectionHandlePainter extends CustomPainter {
const _TextSelectionHandlePainter(this.color);
final Color color;
@override
void paint(Canvas canvas, Size size) {
const double halfStrokeWidth = 1.0;
final Paint paint = Paint()..color = color;
final Rect circle = Rect.fromCircle(
center: const Offset(_kSelectionHandleRadius, _kSelectionHandleRadius),
radius: _kSelectionHandleRadius,
);
final Rect line = Rect.fromPoints(
const Offset(
_kSelectionHandleRadius - halfStrokeWidth,
2 * _kSelectionHandleRadius - _kSelectionHandleOverlap,
),
Offset(_kSelectionHandleRadius + halfStrokeWidth, size.height),
);
final Path path = Path()
..addOval(circle)
// Draw line so it slightly overlaps the circle.
..addRect(line);
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(_TextSelectionHandlePainter oldPainter) => color != oldPainter.color;
}
typedef BoolCallback = bool Function();
class CustomCupertinoTextSelectionControls extends TextSelectionControls {
CustomCupertinoTextSelectionControls({
@required this.canCancelTarget,
@required this.cancelTarget,
});
final BoolCallback canCancelTarget;
final VoidCallback cancelTarget;
/// Returns the size of the Cupertino handle.
@override
Size getHandleSize(double textLineHeight) {
return Size(
_kSelectionHandleRadius * 2,
textLineHeight + _kSelectionHandleRadius * 2 - _kSelectionHandleOverlap,
);
}
/// Builder for iOS-style copy/paste text selection toolbar.
@override
Widget buildToolbar(
BuildContext context,
Rect globalEditableRegion,
double textLineHeight,
Offset position,
List<TextSelectionPoint> endpoints,
TextSelectionDelegate delegate,
ClipboardStatusNotifier clipboardStatus,
Offset lastSecondaryTapDownPosition,
) {
assert(debugCheckHasMediaQuery(context));
final MediaQueryData mediaQuery = MediaQuery.of(context);
// The toolbar should appear below the TextField when there is not enough
// space above the TextField to show it, assuming there's always enough space
// at the bottom in this case.
final double toolbarHeightNeeded =
mediaQuery.padding.top + _kToolbarScreenPadding + _kToolbarHeight + _kToolbarContentDistance;
final double availableHeight = globalEditableRegion.top + endpoints.first.point.dy - textLineHeight;
final bool isArrowPointingDown = toolbarHeightNeeded <= availableHeight;
final double arrowTipX = (position.dx + globalEditableRegion.left).clamp(
_kArrowScreenPadding + mediaQuery.padding.left,
mediaQuery.size.width - mediaQuery.padding.right - _kArrowScreenPadding,
) as double;
// The y-coordinate has to be calculated instead of directly quoting position.dy,
// since the caller (TextSelectionOverlay._buildToolbar) does not know whether
// the toolbar is going to be facing up or down.
final double localBarTopY = isArrowPointingDown
? endpoints.first.point.dy - textLineHeight - _kToolbarContentDistance - _kToolbarHeight
: endpoints.last.point.dy + _kToolbarContentDistance;
return _CupertinoTextSelectionToolbarWrapper(
arrowTipX: arrowTipX,
barTopY: localBarTopY + globalEditableRegion.top,
clipboardStatus: clipboardStatus,
handleCut: canCut(delegate) ? () => handleCut(delegate) : null,
handleCopy: canCopy(delegate) ? () => handleCopy(delegate, clipboardStatus) : null,
handlePaste: canPaste(delegate) ? () => handlePaste(delegate) : null,
handleSelectAll: canSelectAll(delegate) ? () => handleSelectAll(delegate) : null,
handleCancelTarget: canCancelTarget()
? () {
if (cancelTarget != null) cancelTarget();
delegate.hideToolbar();
}
: null,
isArrowPointingDown: isArrowPointingDown,
);
}
/// Builder for iOS text selection edges.
@override
Widget buildHandle(BuildContext context, TextSelectionHandleType type, double textLineHeight) {
// We want a size that's a vertical line the height of the text plus a 18.0
// padding in every direction that will constitute the selection drag area.
final Size desiredSize = getHandleSize(textLineHeight);
final Widget handle = SizedBox.fromSize(
size: desiredSize,
child: CustomPaint(
painter: _TextSelectionHandlePainter(CupertinoTheme.of(context).primaryColor),
),
);
// [buildHandle]'s widget is positioned at the selection cursor's bottom
// baseline. We transform the handle such that the SizedBox is superimposed
// on top of the text selection endpoints.
switch (type) {
case TextSelectionHandleType.left:
return handle;
case TextSelectionHandleType.right:
// Right handle is a vertical mirror of the left.
return Transform(
transform: Matrix4.identity()
..translate(desiredSize.width / 2, desiredSize.height / 2)
..rotateZ(math.pi)
..translate(-desiredSize.width / 2, -desiredSize.height / 2),
child: handle,
);
// iOS doesn't draw anything for collapsed selections.
case TextSelectionHandleType.collapsed:
return const SizedBox();
}
assert(type != null);
return null;
}
/// Gets anchor for cupertino-style text selection handles.
///
/// See [TextSelectionControls.getHandleAnchor].
@override
Offset getHandleAnchor(TextSelectionHandleType type, double textLineHeight) {
final Size handleSize = getHandleSize(textLineHeight);
switch (type) {
// The circle is at the top for the left handle, and the anchor point is
// all the way at the bottom of the line.
case TextSelectionHandleType.left:
return Offset(
handleSize.width / 2,
handleSize.height,
);
// The right handle is vertically flipped, and the anchor point is near
// the top of the circle to give slight overlap.
case TextSelectionHandleType.right:
return Offset(
handleSize.width / 2,
handleSize.height - 2 * _kSelectionHandleRadius + _kSelectionHandleOverlap,
);
// A collapsed handle anchors itself so that it's centered.
default:
return Offset(
handleSize.width / 2,
textLineHeight + (handleSize.height - textLineHeight) / 2,
);
}
}
}
// Renders the content of the selection menu and maintains the page state.
class _CupertinoTextSelectionToolbarContent extends StatefulWidget {
const _CupertinoTextSelectionToolbarContent({
Key key,
@required this.children,
@required this.isArrowPointingDown,
}) : assert(children != null),
// This ignore is used because .isNotEmpty isn't compatible with const.
assert(children.length > 0), // ignore: prefer_is_empty
super(key: key);
final List<Widget> children;
final bool isArrowPointingDown;
@override
_CupertinoTextSelectionToolbarContentState createState() => _CupertinoTextSelectionToolbarContentState();
}
class _CupertinoTextSelectionToolbarContentState extends State<_CupertinoTextSelectionToolbarContent>
with TickerProviderStateMixin {
// Controls the fading of the buttons within the menu during page transitions.
AnimationController _controller;
int _page = 0;
int _nextPage;
void _handleNextPage() {
_controller.reverse();
_controller.addStatusListener(_statusListener);
_nextPage = _page + 1;
}
void _handlePreviousPage() {
_controller.reverse();
_controller.addStatusListener(_statusListener);
_nextPage = _page - 1;
}
void _statusListener(AnimationStatus status) {
if (status != AnimationStatus.dismissed) {
return;
}
setState(() {
_page = _nextPage;
_nextPage = null;
});
_controller.forward();
_controller.removeStatusListener(_statusListener);
}
@override
void initState() {
super.initState();
_controller = AnimationController(
value: 1.0,
vsync: this,
// This was eyeballed on a physical iOS device running iOS 13.
duration: const Duration(milliseconds: 150),
);
}
@override
void didUpdateWidget(_CupertinoTextSelectionToolbarContent oldWidget) {
// If the children are changing, the current page should be reset.
if (widget.children != oldWidget.children) {
_page = 0;
_nextPage = null;
_controller.forward();
_controller.removeStatusListener(_statusListener);
}
super.didUpdateWidget(oldWidget);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final EdgeInsets arrowPadding = widget.isArrowPointingDown
? EdgeInsets.only(bottom: _kToolbarArrowSize.height)
: EdgeInsets.only(top: _kToolbarArrowSize.height);
return DecoratedBox(
decoration: const BoxDecoration(color: _kToolbarDividerColor),
child: FadeTransition(
opacity: _controller,
child: _CupertinoTextSelectionToolbarItems(
page: _page,
backButton: CupertinoButton(
borderRadius: null,
color: _kToolbarBackgroundColor,
minSize: _kToolbarHeight,
onPressed: _handlePreviousPage,
padding: arrowPadding,
pressedOpacity: 0.7,
child: const Text('◀', style: _kToolbarButtonFontStyle),
),
dividerWidth: 1.0 / MediaQuery.of(context).devicePixelRatio,
nextButton: CupertinoButton(
borderRadius: null,
color: _kToolbarBackgroundColor,
minSize: _kToolbarHeight,
onPressed: _handleNextPage,
padding: arrowPadding,
pressedOpacity: 0.7,
child: const Text('▶', style: _kToolbarButtonFontStyle),
),
nextButtonDisabled: CupertinoButton(
borderRadius: null,
color: _kToolbarBackgroundColor,
disabledColor: _kToolbarBackgroundColor,
minSize: _kToolbarHeight,
onPressed: null,
padding: arrowPadding,
pressedOpacity: 1.0,
child: const Text('▶', style: _kToolbarButtonDisabledFontStyle),
),
children: widget.children,
),
),
);
}
}
// The custom RenderObjectWidget that, together with
// _CupertinoTextSelectionToolbarItemsRenderBox and
// _CupertinoTextSelectionToolbarItemsElement, paginates the menu items.
class _CupertinoTextSelectionToolbarItems extends RenderObjectWidget {
_CupertinoTextSelectionToolbarItems({
Key key,
@required this.page,
@required this.children,
@required this.backButton,
@required this.dividerWidth,
@required this.nextButton,
@required this.nextButtonDisabled,
}) : assert(children != null),
assert(children.isNotEmpty),
assert(backButton != null),
assert(dividerWidth != null),
assert(nextButton != null),
assert(nextButtonDisabled != null),
assert(page != null),
super(key: key);
final Widget backButton;
final List<Widget> children;
final double dividerWidth;
final Widget nextButton;
final Widget nextButtonDisabled;
final int page;
@override
_CupertinoTextSelectionToolbarItemsRenderBox createRenderObject(BuildContext context) {
return _CupertinoTextSelectionToolbarItemsRenderBox(
dividerWidth: dividerWidth,
page: page,
);
}
@override
void updateRenderObject(BuildContext context, _CupertinoTextSelectionToolbarItemsRenderBox renderObject) {
renderObject
..page = page
..dividerWidth = dividerWidth;
}
@override
_CupertinoTextSelectionToolbarItemsElement createElement() => _CupertinoTextSelectionToolbarItemsElement(this);
}
// The custom RenderObjectElement that helps paginate the menu items.
class _CupertinoTextSelectionToolbarItemsElement extends RenderObjectElement {
_CupertinoTextSelectionToolbarItemsElement(
_CupertinoTextSelectionToolbarItems widget,
) : super(widget);
List<Element> _children;
final Map<_CupertinoTextSelectionToolbarItemsSlot, Element> slotToChild =
<_CupertinoTextSelectionToolbarItemsSlot, Element>{};
final Map<Element, _CupertinoTextSelectionToolbarItemsSlot> childToSlot =
<Element, _CupertinoTextSelectionToolbarItemsSlot>{};
// We keep a set of forgotten children to avoid O(n^2) work walking _children
// repeatedly to remove children.
final Set<Element> _forgottenChildren = HashSet<Element>();
@override
_CupertinoTextSelectionToolbarItems get widget => super.widget as _CupertinoTextSelectionToolbarItems;
@override
_CupertinoTextSelectionToolbarItemsRenderBox get renderObject =>
super.renderObject as _CupertinoTextSelectionToolbarItemsRenderBox;
void _updateRenderObject(RenderBox child, _CupertinoTextSelectionToolbarItemsSlot slot) {
switch (slot) {
case _CupertinoTextSelectionToolbarItemsSlot.backButton:
renderObject.backButton = child;
break;
case _CupertinoTextSelectionToolbarItemsSlot.nextButton:
renderObject.nextButton = child;
break;
case _CupertinoTextSelectionToolbarItemsSlot.nextButtonDisabled:
renderObject.nextButtonDisabled = child;
break;
}
}
@override
void insertChildRenderObject(RenderObject child, dynamic slot) {
if (slot is _CupertinoTextSelectionToolbarItemsSlot) {
assert(child is RenderBox);
assert(slot is _CupertinoTextSelectionToolbarItemsSlot);
_updateRenderObject(child as RenderBox, slot);
assert(renderObject.childToSlot.containsKey(child));
assert(renderObject.slotToChild.containsKey(slot));
return;
}
if (slot is IndexedSlot) {
assert(renderObject.debugValidateChild(child));
renderObject.insert(child as RenderBox, after: slot?.value?.renderObject as RenderBox);
return;
}
assert(false, 'slot must be _CupertinoTextSelectionToolbarItemsSlot or IndexedSlot');
}
// This is not reachable for children that don't have an IndexedSlot.
@override
void moveChildRenderObject(RenderObject child, IndexedSlot<Element> slot) {
assert(child.parent == renderObject);
renderObject.move(child as RenderBox, after: slot?.value?.renderObject as RenderBox);
}
static bool _shouldPaint(Element child) {
return (child.renderObject.parentData as ToolbarItemsParentData).shouldPaint;
}
@override
void removeChildRenderObject(RenderObject child) {
// Check if the child is in a slot.
if (renderObject.childToSlot.containsKey(child)) {
assert(child is RenderBox);
assert(renderObject.childToSlot.containsKey(child));
_updateRenderObject(null, renderObject.childToSlot[child]);
assert(!renderObject.childToSlot.containsKey(child));
assert(!renderObject.slotToChild.containsKey(slot));
return;
}
// Otherwise look for it in the list of children.
assert(child.parent == renderObject);
renderObject.remove(child as RenderBox);
}
@override
void visitChildren(ElementVisitor visitor) {
slotToChild.values.forEach(visitor);
for (final Element child in _children) {
if (!_forgottenChildren.contains(child)) visitor(child);
}
}
@override
void forgetChild(Element child) {
assert(slotToChild.values.contains(child) || _children.contains(child));
assert(!_forgottenChildren.contains(child));
// Handle forgetting a child in children or in a slot.
if (childToSlot.containsKey(child)) {
final _CupertinoTextSelectionToolbarItemsSlot slot = childToSlot[child];
childToSlot.remove(child);
slotToChild.remove(slot);
} else {
_forgottenChildren.add(child);
}
super.forgetChild(child);
}
// Mount or update slotted child.
void _mountChild(Widget widget, _CupertinoTextSelectionToolbarItemsSlot slot) {
final Element oldChild = slotToChild[slot];
final Element newChild = updateChild(oldChild, widget, slot);
if (oldChild != null) {
slotToChild.remove(slot);
childToSlot.remove(oldChild);
}
if (newChild != null) {
slotToChild[slot] = newChild;
childToSlot[newChild] = slot;
}
}
@override
void mount(Element parent, dynamic newSlot) {
super.mount(parent, newSlot);
// Mount slotted children.
_mountChild(widget.backButton, _CupertinoTextSelectionToolbarItemsSlot.backButton);
_mountChild(widget.nextButton, _CupertinoTextSelectionToolbarItemsSlot.nextButton);
_mountChild(widget.nextButtonDisabled, _CupertinoTextSelectionToolbarItemsSlot.nextButtonDisabled);
// Mount list children.
_children = List<Element>(widget.children.length);
Element previousChild;
for (int i = 0; i < _children.length; i += 1) {
final Element newChild = inflateWidget(widget.children[i], IndexedSlot<Element>(i, previousChild));
_children[i] = newChild;
previousChild = newChild;
}
}
@override
void debugVisitOnstageChildren(ElementVisitor visitor) {
// Visit slot children.
childToSlot.forEach((Element child, _) {
if (!_shouldPaint(child) || _forgottenChildren.contains(child)) {
return;
}
visitor(child);
});
// Visit list children.
_children.where((Element child) => !_forgottenChildren.contains(child) && _shouldPaint(child)).forEach(visitor);
}
@override
void update(_CupertinoTextSelectionToolbarItems newWidget) {
super.update(newWidget);
assert(widget == newWidget);
// Update slotted children.
_mountChild(widget.backButton, _CupertinoTextSelectionToolbarItemsSlot.backButton);
_mountChild(widget.nextButton, _CupertinoTextSelectionToolbarItemsSlot.nextButton);
_mountChild(widget.nextButtonDisabled, _CupertinoTextSelectionToolbarItemsSlot.nextButtonDisabled);
// Update list children.
_children = updateChildren(_children, widget.children, forgottenChildren: _forgottenChildren);
_forgottenChildren.clear();
}
}
// The custom RenderBox that helps paginate the menu items.
class _CupertinoTextSelectionToolbarItemsRenderBox extends RenderBox
with
ContainerRenderObjectMixin<RenderBox, ToolbarItemsParentData>,
RenderBoxContainerDefaultsMixin<RenderBox, ToolbarItemsParentData> {
_CupertinoTextSelectionToolbarItemsRenderBox({
@required double dividerWidth,
@required int page,
}) : assert(dividerWidth != null),
assert(page != null),
_dividerWidth = dividerWidth,
_page = page,
super();
final Map<_CupertinoTextSelectionToolbarItemsSlot, RenderBox> slotToChild =
<_CupertinoTextSelectionToolbarItemsSlot, RenderBox>{};
final Map<RenderBox, _CupertinoTextSelectionToolbarItemsSlot> childToSlot =
<RenderBox, _CupertinoTextSelectionToolbarItemsSlot>{};
RenderBox _updateChild(RenderBox oldChild, RenderBox newChild, _CupertinoTextSelectionToolbarItemsSlot slot) {
if (oldChild != null) {
dropChild(oldChild);
childToSlot.remove(oldChild);
slotToChild.remove(slot);
}
if (newChild != null) {
childToSlot[newChild] = slot;
slotToChild[slot] = newChild;
adoptChild(newChild);
}
return newChild;
}
int _page;
int get page => _page;
set page(int value) {
if (value == _page) {
return;
}
_page = value;
markNeedsLayout();
}
double _dividerWidth;
double get dividerWidth => _dividerWidth;
set dividerWidth(double value) {
if (value == _dividerWidth) {
return;
}
_dividerWidth = value;
markNeedsLayout();
}
RenderBox _backButton;
RenderBox get backButton => _backButton;
set backButton(RenderBox value) {
_backButton = _updateChild(_backButton, value, _CupertinoTextSelectionToolbarItemsSlot.backButton);
}
RenderBox _nextButton;
RenderBox get nextButton => _nextButton;
set nextButton(RenderBox value) {
_nextButton = _updateChild(_nextButton, value, _CupertinoTextSelectionToolbarItemsSlot.nextButton);
}
RenderBox _nextButtonDisabled;
RenderBox get nextButtonDisabled => _nextButtonDisabled;
set nextButtonDisabled(RenderBox value) {
_nextButtonDisabled =