forked from superlistapp/super_editor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
document_interaction_mobile.dart
1692 lines (1493 loc) · 62.8 KB
/
document_interaction_mobile.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
import 'dart:math';
import 'dart:ui';
import 'package:diff_match_patch/diff_match_patch.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart' hide SelectableText;
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:super_editor/src/core/document.dart';
import 'package:super_editor/src/core/document_layout.dart';
import 'package:super_editor/src/core/document_selection.dart';
import 'package:super_editor/src/core/edit_context.dart';
import 'package:super_editor/src/infrastructure/_logging.dart';
import 'package:super_editor/src/infrastructure/multi_tap_gesture.dart';
import 'package:super_editor/super_editor.dart';
import 'document_interaction.dart' show DocumentInteractor, DocumentKeyboardAction, ExecutionInstruction;
import 'text_tools.dart';
final _log = Logger(scope: 'softkeyboard_document_interaction.dart');
final isSoftKeyboard = (defaultTargetPlatform == TargetPlatform.iOS || defaultTargetPlatform == TargetPlatform.android);
/// An Interactor Selector based on the platform.
class DefaultDocumentInteractor extends StatelessWidget {
const DefaultDocumentInteractor({
Key? key,
required this.editContext,
required this.keyboardActions,
this.scrollController,
this.focusNode,
required this.document,
this.showDebugPaint = false,
this.readOnly = false,
}) : super(key: key);
final EditContext editContext;
final List<DocumentKeyboardAction> keyboardActions;
final ScrollController? scrollController;
final FocusNode? focusNode;
final Widget document;
final showDebugPaint;
final bool readOnly;
@override
Widget build(BuildContext context) {
if (isSoftKeyboard) {
return SoftKeyboardDocumentInteractor(
editContext: editContext,
keyboardActions: keyboardActions,
scrollController: scrollController,
focusNode: focusNode,
document: document,
readOnly: readOnly,
);
} else {
return DocumentInteractor(
editContext: editContext,
keyboardActions: keyboardActions,
scrollController: scrollController,
focusNode: focusNode,
document: document,
showDebugPaint: showDebugPaint,
);
}
}
}
/// a document interactor for touch devices with softkeyboard
class SoftKeyboardDocumentInteractor extends StatefulWidget {
const SoftKeyboardDocumentInteractor({
Key? key,
required this.editContext,
required this.keyboardActions,
this.scrollController,
this.focusNode,
required this.document,
this.readOnly = false,
}) : super(key: key);
final EditContext editContext;
final List<DocumentKeyboardAction> keyboardActions;
final ScrollController? scrollController;
final FocusNode? focusNode;
final Widget document;
final bool readOnly;
@override
_SoftKeyboardDocumentInteractorState createState() => _SoftKeyboardDocumentInteractorState();
}
class _SoftKeyboardDocumentInteractorState extends State<SoftKeyboardDocumentInteractor> implements TextInputClient {
final _documentWrapperKey = GlobalKey();
late FocusNode _focusNode;
late ScrollController _scrollController;
// TODO: should this be nullable? mainly because it's not initialized in read-only mode.
late TextInputConnection _textInputConnection;
// the top left position of the interactor in the global coordinate space
late final Offset _interactorTopLeft;
// the top left position of the wrapper in the global coordinate space
late final Offset _wrapperTopLeft;
// the top left position of the document in the global coordinate space
late final Offset _documentTopLeft;
// TODO: minimize the dance between the three coordinate spaces as much as possible
// and try to solely rely on the document coordinates.
// helper functions
Offset get _documentPadding => (_documentTopLeft - _wrapperTopLeft);
Offset _convertFromGlobalToDocument(Offset offset) => offset - _documentTopLeft + Offset(0, _scrollController.offset);
Offset _convertFromWrapperToDocument(Offset offset) => offset - _documentPadding;
Offset _convertFromWrapperToGlobal(Offset offset) => offset + _wrapperTopLeft;
Offset _convertFromDocumentToWrapper(Offset offset) => offset + _documentPadding;
// the height and width of the document layout.
//
// this value is primarly used to determine the bottom boundry for scrolling
// and to prevent autoscrolling when the bottom is already visible.
// This value should be updated at the start of any activity that needs it
// such as scrolling or floating cursor since computing the value for every
// selection change is unncessary.
//
// the value is updated by calling `_computeDocumentSize`.
late Size _documentSize;
/// the visible portion of the document in the document's coordinate space.
///
/// this value is computed by _computeDocumentViewPort and it's influenced by
/// both the scrollOffset and whether the virtual keyboard is visible or not.
late Rect _documentViewportRect;
Offset? _currentCursorPosition;
// the position and dimension of the base drag handles in the wrapper coordinates
Rect? _baseDragHandleRect;
// the position and dimension of the extent drag handles in the wrapper coordinates
Rect? _extentDragHandleRect;
final dragHandleSize = 20.0;
// indicates if any of drag handles is being dragged.
bool _isDragging = false;
// the initial position is used to update the floating cursor position
// since all the floating cursor updates are relative to the initial
// position from where the folating cursor started.
// i.e. _currentCursorPosition = _floatingCursorInitialPosition only at
// at the start of floatingCursor activity.
Offset? _floatingCursorInitialPosition;
Offset? _floatingCursorPosition;
DocumentLayout get _layout => widget.editContext.documentLayout;
final selectionControls = SelectionControlsOverlay();
bool get _isSelectionCollapsed => widget.editContext.composer.selection?.isCollapsed ?? true;
@override
void initState() {
super.initState();
_focusNode = widget.focusNode ?? FocusNode();
_scrollController =
_scrollController = (widget.scrollController ?? ScrollController())..addListener(_computeDocumentViewPort);
widget.editContext.composer.addListener(_onSelectionChange);
if (!widget.readOnly) {
// the keyboard needs to access the Theme.of(context).brightness
// to set the keyboard brightness according to the current Theme
// which is not accessible before the first frame.
WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
_attachTextInputClientForSoftKeyboard();
});
_focusNode.addListener(_onFocusChange);
// needed when selection == null to hide the soft keyboard
widget.editContext.composer.addListener(_onFocusChange);
}
_setDocumentOffset();
}
@override
void didUpdateWidget(SoftKeyboardDocumentInteractor oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.editContext.composer != oldWidget.editContext.composer) {
oldWidget.editContext.composer.removeListener(_onSelectionChange);
widget.editContext.composer.addListener(_onSelectionChange);
}
if (widget.scrollController != oldWidget.scrollController) {
_scrollController.removeListener(_computeDocumentViewPort);
if (oldWidget.scrollController == null) {
_scrollController.dispose();
}
_scrollController = (widget.scrollController ?? ScrollController())..addListener(_computeDocumentViewPort);
}
if (widget.focusNode != oldWidget.focusNode) {
_focusNode = widget.focusNode ?? FocusNode();
if (!widget.readOnly) {
_focusNode.addListener(_onFocusChange);
}
}
}
@override
void dispose() {
widget.editContext.composer.removeListener(_onSelectionChange);
_scrollController.removeListener(_computeDocumentViewPort);
if (widget.scrollController == null) {
_scrollController.dispose();
}
if (widget.focusNode == null) {
_focusNode.dispose();
}
if (!widget.readOnly) {
_textInputConnection.close();
}
selectionControls.hide();
super.dispose();
}
void _setDocumentOffset() {
WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
// get the top left position of the layout
// dx is usually zero, and dy will account for anything above the layout such as a toolbar.
final interactorBox = context.findRenderObject() as RenderBox;
_interactorTopLeft = interactorBox.localToGlobal(Offset.zero);
final documentTopLeftInInteractor = _layout.getDocumentOffsetFromAncestorOffset(Offset.zero, interactorBox) * -1;
_documentTopLeft = documentTopLeftInInteractor + _interactorTopLeft;
final wrapperBox = _documentWrapperKey.currentContext!.findRenderObject() as RenderBox;
_wrapperTopLeft = wrapperBox.localToGlobal(Offset.zero);
_computeDocumentSize();
});
}
// This function should be call upon the start of an activity that requires auto scrolling
// such as floating cursor or drag handles. This will ensure we've the latest documentSize
// and documentViewportRect.
void _computeDocumentSize() {
final wrapperBox = _documentWrapperKey.currentContext!.findRenderObject() as RenderBox;
_documentSize = (wrapperBox.size - _documentPadding * 2) as Size;
_computeDocumentViewPort();
}
// This function should update the viewport upon scrolling and when a documentSize changes.
void _computeDocumentViewPort() {
// note: everything is initially computed in wrapper's coordinate space then
// it's converted to document coordinate space for easier logic.
// the scroll controller already computes the viewport dimension and it accounts for any
// inset/padding such as the virtual keyboard height.
final portHeight = _scrollController.position.viewportDimension;
final scrollOffset = _scrollController.offset;
// the top padding is only visible when scroll offset == 0, so the top padding will vary
// in height and it will reach zero when the scrollOffset >= the top documentPadding
final topPadding = max(0.0, _documentPadding.dy - scrollOffset);
final top = topPadding + scrollOffset;
final bottom = min(top + portHeight - topPadding, _documentSize.height + _documentPadding.dy);
_documentViewportRect = Rect.fromLTRB(
_documentPadding.dx,
top,
_documentSize.width,
bottom,
).shift(_convertFromWrapperToDocument(Offset.zero));
}
void _onFocusChange() {
if (_focusNode.hasFocus && widget.editContext.composer.selection != null) {
if (!_textInputConnection.attached) {
_attachTextInputClientForSoftKeyboard();
_showSoftKeyboard();
}
} else {
selectionControls.hide();
_hideSoftKeyboard();
}
}
void _showSoftKeyboard() async {
try {
_textInputConnection.show();
} catch (e) {
_log.log('showSoftKeyboard', 'failed to show soft keyboard $e');
}
}
void _hideSoftKeyboard() async {
try {
_textInputConnection.close();
} catch (e) {
_log.log('hideSoftKeyboard', 'failed to hide soft keyboard $e');
}
}
void _onSelectionChange() {
_log.log('_onSelectionChange', 'EditableDocument: _onSelectionChange()');
// while most cases do not require a post frame call back, there are two cases that's requires
// calling `_updateDragHandles` in a post frame to place drag handles appropriately:
// 1- when a text node changes alignment while there's a selection.
// 2- when a node is transformed (e.g. paragraph => blockquote) where the node id will also change,
// hence a post frame call back will prevent calling the old node.
WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
setState(() {
_updateDragHandles();
});
});
_updateCurrentSelection();
}
// This should be null when the node is not TextNode
// or the selection has multiple nodes even if all of them are TextNodes
// This value is primarly used for supporting autocorrect and
// suggetions which are handled at `_applyRemoteChanges`.
TextNode? _currentSelectedTextNode;
// At least in iOS, when more than one word is selected (excluding spaces),
// both autocorrect/suggetion are not presented. For this reason, when the selection
// contains a single text node only, the text is delegated to _localTextEditingValue
// to be handled remotely and which allow it to be handled in batches (e.g. autocorrect).
// In all other cases, _localTextEditingValue will be set as an empty value
// (i.e. _zwspEditingValue to detect backspace events) without any text
// since autocorrect/suggetion won't be presented anyway. In these cases,
// characters are inserted one by one
// e.g. - inserting a character when the selection spans across two paragraphs
// or a non-text node is being selected.
TextEditingValue _localTextEditingValue = _zwspEditingValue;
TextEditingValue? _lastKnownRemoteTextEditingValue;
// this is used during a batch edit or when the user inserts
// multiple characters at once. when the value is true,
// _setEditingState should not be invoked.
// TODO: this may not be necessary anymore if batches are
// inserted directly through a single command
bool _isUpdatingEditingValue = false;
void _updateCurrentSelection() {
if (widget.readOnly || _isFloatingCursorActive || _isDragging) {
// it's unncessary and computationally expensive to update during these activity.
// Consequently, both activities should trigger this method once they're done.
return;
}
final selection = widget.editContext.composer.selection;
if (selection == null) {
_localTextEditingValue = _zwspEditingValue;
_currentSelectedTextNode = null;
_setEditingState();
return;
}
final selectedNodes = widget.editContext.editor.document.getNodesInside(selection.base, selection.extent);
if (selectedNodes.length > 1 || selectedNodes.first is! TextNode) {
_localTextEditingValue = _zwspEditingValue;
_currentSelectedTextNode = null;
_lastKnownRemoteTextEditingValue = null;
} else {
_currentSelectedTextNode = selectedNodes.first as TextNode;
_localTextEditingValue = TextEditingValue(
text: _zwsp + _currentSelectedTextNode!.text.text,
selection: TextSelection(
baseOffset: (selection.base.nodePosition as TextPosition).offset + _zwsp.length,
extentOffset: (selection.extent.nodePosition as TextPosition).offset + _zwsp.length,
),
);
}
if (!_isUpdatingEditingValue) {
_setEditingState();
} else {}
}
void _setEditingState() {
if (!_textInputConnection.attached) {
// TODO: should we connect and reinvoke _setEditingState?
return;
}
// calling _textInputConnection.setEditingState should be avoided when the remote value equals the
// local value. Doing otherwise, can interrupt user activity such as voice dictation and also it can
// emit unncessary updates.
if (_didRemoteTextEditingValueChange) {
_textInputConnection.setEditingState(_localTextEditingValue);
_lastKnownRemoteTextEditingValue = _localTextEditingValue;
}
}
// using _currentTextEditingValue == _lastKnownRemoteTextEditingValue directly
// is avoided since it compares affinity which can be different but are not important.
// Only the differences in text and selection are important in this use case.
bool get _didRemoteTextEditingValueChange =>
_lastKnownRemoteTextEditingValue == null ||
_lastKnownRemoteTextEditingValue!.text != _localTextEditingValue.text ||
_lastKnownRemoteTextEditingValue!.selection.base.offset != _localTextEditingValue.selection.base.offset ||
_lastKnownRemoteTextEditingValue!.selection.extent.offset != _localTextEditingValue.selection.extent.offset;
KeyEventResult _onKeyPressed(RawKeyEvent keyEvent) {
_log.log('_onKeyPressed', 'keyEvent: ${keyEvent.character}');
if (keyEvent is! RawKeyDownEvent) {
_log.log('_onKeyPressed', ' - not a "down" event. Ignoring.');
return KeyEventResult.handled;
}
ExecutionInstruction instruction = ExecutionInstruction.continueExecution;
int index = 0;
while (instruction == ExecutionInstruction.continueExecution && index < widget.keyboardActions.length) {
instruction = widget.keyboardActions[index](
editContext: widget.editContext,
keyEvent: keyEvent,
);
index += 1;
}
return instruction == ExecutionInstruction.haltExecution ? KeyEventResult.handled : KeyEventResult.ignored;
}
void _onTapDown(TapDownDetails details) {
if (_isInsideDragHandle(details.globalPosition)) {
return;
}
_log.log('_onTapDown', 'EditableDocument: onTapDown()');
final docOffset = _getDocOffset(details.localPosition);
_log.log('_onTapDown', ' - document offset: $docOffset');
final docPosition = _layout.getDocumentPositionAtOffset(docOffset);
_log.log('_onTapDown', ' - tapped document position: $docPosition');
if (docPosition != null) {
// Place the document selection at the location where the
// user tapped.
_selectPosition(docPosition);
} else {
// handle the user tapDown outside any of the nodes (e.g. empty space between nodes).
// This is especially useful when a document contains one paragraph node that's empty
// it's tough for the user to find where to tap to get the cursor to show up.
//
// Currently, it'll place the selection at the end of the first node, if any.
//
// TODO: place the selection at the nearest node from where the user tapped
final nodes = widget.editContext.editor.document.nodes;
if (nodes.isNotEmpty) {
final firstNode = widget.editContext.editor.document.nodes.last;
final newSelection = DocumentSelection.collapsed(
position: DocumentPosition(
nodeId: firstNode.id,
nodePosition: firstNode.endPosition,
),
);
widget.editContext.composer.selection = newSelection;
_ensureCaretIsVisibleInViewport();
}
}
_focusNode.requestFocus();
}
void _onDoubleTapDown(TapDownDetails details) {
if (_isInsideDragHandle(details.globalPosition)) return;
_log.log('_onDoubleTapDown', 'EditableDocument: onDoubleTap()');
_clearSelection();
final docOffset = _getDocOffset(details.localPosition);
final docPosition = _layout.getDocumentPositionAtOffset(docOffset);
_log.log('_onDoubleTapDown', ' - tapped document position: $docPosition');
if (docPosition != null) {
final didSelectWord = _selectWordAt(
docPosition: docPosition,
docLayout: _layout,
);
if (!didSelectWord) {
// Place the document selection at the location where the
// user tapped.
_selectPosition(docPosition);
}
}
_focusNode.requestFocus();
}
void _onTripleTapDown(TapDownDetails details) {
if (_isInsideDragHandle(details.globalPosition)) return;
_log.log('_onTripleTapDown', 'EditableDocument: onTripleTapDown()');
_clearSelection();
final docOffset = _getDocOffset(details.localPosition);
final docPosition = _layout.getDocumentPositionAtOffset(docOffset);
_log.log('_onTripleTapDown', ' - tapped document position: $docPosition');
if (docPosition != null) {
final didSelectParagraph = _selectParagraphAt(
docPosition: docPosition,
docLayout: _layout,
);
if (!didSelectParagraph) {
// Place the document selection at the location where the
// user tapped.
_selectPosition(docPosition);
}
}
_focusNode.requestFocus();
}
void _onLongPress() {
showSelectionControls();
}
bool _selectWordAt({
required DocumentPosition docPosition,
required DocumentLayout docLayout,
}) {
final newSelection = getWordSelection(docPosition: docPosition, docLayout: docLayout);
if (newSelection != null) {
widget.editContext.composer.selection = newSelection;
return true;
} else {
return false;
}
}
bool _selectParagraphAt({
required DocumentPosition docPosition,
required DocumentLayout docLayout,
}) {
final newSelection = getParagraphSelection(docPosition: docPosition, docLayout: docLayout);
if (newSelection != null) {
widget.editContext.composer.selection = newSelection;
return true;
} else {
return false;
}
}
void _selectPosition(DocumentPosition position) {
_log.log('_selectPosition', 'Setting document selection to $position');
widget.editContext.composer.selection = DocumentSelection.collapsed(
position: position,
);
}
void _selectRegion({
required DocumentLayout documentLayout,
required Offset baseOffset,
required Offset extentOffset,
}) {
_log.log('_selectionRegion', 'Composer: selectionRegion(). Mode: Position');
var selection = documentLayout.getDocumentSelectionInRegion(baseOffset, extentOffset);
var basePosition = selection?.base;
var extentPosition = selection?.extent;
_log.log('_selectionRegion', ' - base: $basePosition, extent: $extentPosition');
if (basePosition == null || extentPosition == null) {
widget.editContext.composer.selection = null;
return;
}
// prevent hiding the drag handles when base == extent
// when the handles are being dragged.
if (_isDragging && selection!.isCollapsed) {
return;
}
widget.editContext.composer.selection = (DocumentSelection(
base: basePosition,
extent: extentPosition,
));
_log.log('_selectionRegion', 'Region selection: ${widget.editContext.composer.selection}');
}
void _clearSelection() {
widget.editContext.composer.clearSelection();
}
// Converts the given [offset] from the [DocumentInteractor]'s coordinate
// space to the [DocumentLayout]'s coordinate space.
Offset _getDocOffset(Offset offset) {
return _layout.getDocumentOffsetFromAncestorOffset(offset, context.findRenderObject()!);
}
bool _isInsideDragHandle(Offset offset) {
// when selection is collapsed, drag handles are not shown.
if (_isSelectionCollapsed) return false;
if (_baseDragHandleRect != null) {
if (_baseDragHandleRect!
.shift(_documentTopLeft - _documentPadding)
.translate(0, -_scrollController.offset)
.contains(offset)) {
return true;
}
}
if (_extentDragHandleRect != null) {
if (_extentDragHandleRect!
.shift(_documentTopLeft - _documentPadding)
.translate(0, -_scrollController.offset)
.contains(offset)) {
return true;
}
}
return false;
}
void _updateDragHandles() {
final selection = widget.editContext.composer.selection;
if (selection == null) {
_baseDragHandleRect = null;
_extentDragHandleRect = null;
if (selectionControls.isVisible) {
selectionControls.hide();
}
return;
}
// this in document coordinates..
_currentCursorPosition = _layout.getRectForPosition(selection.extent)?.center;
late final Offset? selectionTopLeft;
late final Offset? selectionBottomRight;
if (selection.isCollapsed) {
selectionTopLeft = _currentCursorPosition;
selectionBottomRight = _currentCursorPosition;
} else {
// text is still not factoring line height
// see: default_deitor/text.dart#_TextComponentState#getRectForPosition
selectionTopLeft = _layout.getRectForPosition(selection.base)?.topLeft;
selectionBottomRight = _layout.getRectForPosition(selection.extent)?.bottomRight;
}
_baseDragHandleRect = Rect.fromCenter(
center: _convertFromDocumentToWrapper(selectionTopLeft!),
width: dragHandleSize,
height: dragHandleSize,
);
_extentDragHandleRect = Rect.fromCenter(
center: _convertFromDocumentToWrapper(selectionBottomRight!),
width: dragHandleSize,
height: dragHandleSize,
);
if (!_isDragging && !selection.isCollapsed) {
showSelectionControls();
} else {
if (selectionControls.isVisible) {
selectionControls.hide();
}
}
}
/* -------------------------------------------------------------------------- */
/* SELECTION CONTROLS */
/* -------------------------------------------------------------------------- */
void showSelectionControls() {
if (_baseDragHandleRect == null || _extentDragHandleRect == null) return;
final baseOffset = _convertFromWrapperToGlobal(_baseDragHandleRect!.center);
final extentOffset = _convertFromWrapperToGlobal(_extentDragHandleRect!.center);
// find the center point where the selection controls pointer will point at..
// there are three cases:
// - base and extent on the same line
// - base before extent in multiline
// - base after extent in multiline
double dx;
double dy;
final screenWidth = MediaQuery.of(context).size.width;
if (baseOffset.dy == extentOffset.dy) {
dy = baseOffset.dy - _scrollController.offset;
dx = baseOffset.dx + ((extentOffset.dx - baseOffset.dx) / 2) + _interactorTopLeft.dx;
} else if (baseOffset.dy < extentOffset.dy) {
dy = baseOffset.dy - _scrollController.offset;
// in a multi line selection, place selection controls in the center unless
// the base handle > the center, then place it above the selected portion.
dx = max(screenWidth / 2, baseOffset.dx + _interactorTopLeft.dx + 20);
} else {
dy = extentOffset.dy - _scrollController.offset;
// in a multi line selection, place selection controls in the center unless
// the extent handle > the center, then place it above the selected portion.
dx = max(screenWidth / 2, extentOffset.dx + _interactorTopLeft.dx + 20);
}
dy = max(dy, max(_interactorTopLeft.dy, MediaQuery.of(context).padding.top));
selectionControls.show(
context: context,
topCenter: Offset(dx, max(dy, _interactorTopLeft.dy)),
onCopy: _isSelectionCollapsed ? null : _onCopy,
onSelectAll: _onSelectAll,
onCut: widget.readOnly || _isSelectionCollapsed ? null : _onCut,
onPaste: widget.readOnly ? null : _onPaste,
);
}
void _onCopy() {
copyWhenCmdVIsPressed(editContext: widget.editContext, keyEvent: copyKeyEvent);
selectionControls.hide();
}
void _onCut() {
// copy the text
copyWhenCmdVIsPressed(editContext: widget.editContext, keyEvent: copyKeyEvent);
// delete the text
anyCharacterOrDestructiveKeyToDeleteSelection(
editContext: widget.editContext, keyEvent: backspaceKeyEvent);
selectionControls.hide();
}
void _onSelectAll() {
print('select all called');
widget.editContext.commonOps.selectAll();
// to move the selection controls in the new proper position.
selectionControls.hide();
showSelectionControls();
}
// TODO: fix the isuee when pasting a multiline content. Since in mobile we aren't supporting multiline
// within a TextNode, we should split the pasted text based on '\n' and add each node
// individually. This could also be useful for parsing URLs and horziontal lines or quotes when pasted.
// for instance, if the text is surronded by quotation mark, it's a blockquote or if the text is "---" then
// it's a horizontal divider, and if it's an image url, then it's an image and so on.
void _onPaste() {
pasteWhenCmdVIsPressed(editContext: widget.editContext, keyEvent: pasteKeyEvent);
}
// TODO: find good numbers (also choose clearer names)
final _autoScrollArea = 50;
final _scrollAmount = 10;
// pass the document offset to scroll if necessary.
//
// This is mainly used by the drag handles and floating cursor when either one
// is near the upper or lower boundries.
void _scrollIfNearBoundries(Offset documentOffset) {
final scrollOffset = _scrollController.offset;
if (documentOffset.dy - _autoScrollArea < _documentViewportRect.top) {
// prevent scrolling beyond the beginning
if (scrollOffset <= 0) return;
_scrollController.jumpTo(scrollOffset - _scrollAmount);
return;
}
if (documentOffset.dy > _documentViewportRect.bottom - _autoScrollArea) {
// prevent scrolling beyond the end
if (scrollOffset >= _scrollController.position.maxScrollExtent) return;
_scrollController.jumpTo(scrollOffset + _scrollAmount);
return;
}
}
@override
Widget build(BuildContext context) {
return _buildFocusAndGesture(
child: SizedBox.expand(
child: Stack(
children: [
_buildDocumentContainer(
document: widget.document,
),
],
),
),
);
}
Widget _buildFocusAndGesture({
required Widget child,
}) {
return Focus(
focusNode: _focusNode,
autofocus: true,
child: _buildRawGestureDetector(child: child),
);
}
Widget _buildRawGestureDetector({
required Widget child,
}) {
return RawGestureDetector(
behavior: HitTestBehavior.translucent,
gestures: <Type, GestureRecognizerFactory>{
TapSequenceGestureRecognizer: GestureRecognizerFactoryWithHandlers<TapSequenceGestureRecognizer>(
() => TapSequenceGestureRecognizer(),
(TapSequenceGestureRecognizer recognizer) {
recognizer
..onTapDown = _onTapDown
..onDoubleTapDown = _onDoubleTapDown
..onTripleTapDown = _onTripleTapDown;
},
),
LongPressGestureRecognizer: GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>(
() => LongPressGestureRecognizer(), (LongPressGestureRecognizer recognizer) {
recognizer.onLongPress = _onLongPress;
}),
},
child: child,
);
}
// TODO: improve how drag handles are implemented. The handle itself should not know
// whether it's base or extent since what matter is whether it's right or left
// In LTR text, the left handle is placed at the top of the selection whereas
// the right handle is placed at the bottom, and vice versa for RTL text.
Widget buildDragHandle(Rect rect, bool isBase, [Color color = Colors.blue]) {
return Positioned.fromRect(
rect: rect,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onPanStart: (details) {
_isDragging = true;
_computeDocumentSize();
},
onPanUpdate: (details) {
// just in case
if (_extentDragHandleRect == null || _baseDragHandleRect == null) {
print('extentDragHandleRect! = $_extentDragHandleRect! && baseDragHandleRect! $_baseDragHandleRect!');
return;
}
// when the drag handles are near the document borders, their position can
// be outside the document boundries which will cause `_selectRegion` to return
// a null selection. To avoid such case, we clamp the drag handles positions to
// be slightly larger than lower boundries and slightly lower than the upper boundries.
// Shrinking the boundries by 1px seems to work fine.
final dx = details.globalPosition.dx.clamp(
_documentTopLeft.dx + 1,
_documentTopLeft.dx + _documentSize.width - 1,
);
final dy = details.globalPosition.dy.clamp(
_documentTopLeft.dy - _scrollController.offset + 1,
_documentTopLeft.dy - _scrollController.offset + _documentSize.height - 1,
);
final documentOffset = _convertFromGlobalToDocument(Offset(dx, dy));
if (isBase) {
_selectRegion(
documentLayout: _layout,
baseOffset: documentOffset.translate(0, 5),
// since the selection height is unknown, the top position can overlap
// with the line that is above the current the selection. This will cause
// the selection to move up on every drag update even though it didn't
// actually move. This is mainly an issue with larger font sizes (H1 and H2).
// We need to translate the position to be just below the top boundry of the selection.
// While 5 is an arbitary number, it was tested on H1, H2, and H3 and seems to
// do the job for now until the selection height becomes known to us.
extentOffset: _convertFromWrapperToDocument(_extentDragHandleRect!.center).translate(0, 5),
);
} else {
_selectRegion(
documentLayout: _layout,
// see note above
baseOffset: _convertFromWrapperToDocument(_baseDragHandleRect!.center).translate(0, 5),
extentOffset: documentOffset.translate(0, 5),
);
}
_scrollIfNearBoundries(documentOffset);
},
onPanCancel: () {
// this is a temp work around until the conflict with scrolling is solved.
// due to the conflict, onPanCancel is invoked when the draghandle is dragged
// vertically where the scrolling takes over the gesture activity. so we avoid
// setting state in that case when _isDragging is already false.
if (_isDragging) {
setState(() {
_isDragging = false;
_updateDragHandles();
});
}
},
onPanEnd: (details) {
setState(() {
_isDragging = false;
// temp: when the selection is TextSelection where base.nodePosition.offset == extent.nodePosition.offset,
// it's possible that base.nodePosition.affinity != extent.nodePosition.affinity which leads to
// selection.isCollapsed == false. Hence, we check if the drag handles coincide, and if so, we
// collapse the selection to hide the drag handles.
// note: once we've access to the selection heigt for textNode, the approach needs to change.
if (_baseDragHandleRect?.center == _extentDragHandleRect?.center) {
// collapse the selection
_selectPosition(widget.editContext.composer.selection!.base);
} else {
// to show selection controls if necessary.
_updateDragHandles();
}
_updateCurrentSelection();
});
},
child: Container(
height: dragHandleSize,
width: dragHandleSize,
child: Icon(
Icons.circle,
color: color,
size: 15,
),
),
),
);
}
// TODO: match the height of the carret which once selection height is available
final floatingCursorHeight = 15.0;
Widget _buildFloatingCursor() {
// boundry to limit vertical movement inside the document
final topBound = _documentPadding.dy;
final bottomBound = topBound + _documentSize.height - floatingCursorHeight;
final top = max(topBound, min(bottomBound, _floatingCursorPosition!.dy));
// boundry to limit horizontal movement inside the document
final leftBound = _documentPadding.dx;
final rightBound = leftBound + _documentSize.width;
final left = max(leftBound, min(rightBound, _floatingCursorPosition!.dx));
return Positioned(
top: top,
left: left,
child: Container(
height: floatingCursorHeight,
width: 3,
color: Colors.blue,
),
);
}
Widget _buildDocumentContainer({
required Widget document,
}) {
return SingleChildScrollView(
controller: _scrollController,
physics: const AlwaysScrollableScrollPhysics(),
primary: false, // it conflicts with panning the draghandles
child: Center(
child: Stack(
children: [
SizedBox(
key: _documentWrapperKey,
child: document,
),
if (_baseDragHandleRect != null && !_isSelectionCollapsed) buildDragHandle(_baseDragHandleRect!, true),
if (_extentDragHandleRect != null && !_isSelectionCollapsed) buildDragHandle(_extentDragHandleRect!, false),
if (_floatingCursorPosition != null) _buildFloatingCursor(),
],
),
),
);
}
/* -------------------------------------------------------------------------- */
/* TEXT INPUT CLIENT IMPLEMENTATION */
/* -------------------------------------------------------------------------- */
void _attachTextInputClientForSoftKeyboard() {
_textInputConnection = TextInput.attach(this, _createTextInputConfiguration());
_textInputConnection.setEditingState(_localTextEditingValue);
}
TextInputConfiguration _createTextInputConfiguration() {
return TextInputConfiguration(
// Using `TextInputAction.newline` will show the return symbol on the soft keyboard,
// but it'll allow inserting new lines in the remote textEditingValue. For this reason,
// newlines should be handled at `updateTextEditingValue` and not at `performAction`.
inputAction: TextInputAction.newline,
inputType: TextInputType.text,
keyboardAppearance: Theme.of(context).brightness,
enableSuggestions: true,
autocorrect: true,
);
}
@override
// TODO: implement connectionClosed
void connectionClosed() {}
@override
// TODO: implement currentAutofillScope
AutofillScope? get currentAutofillScope {
return null;
}
@override
// TODO: implement currentTextEditingValue
TextEditingValue? get currentTextEditingValue {
print('get currentTextEditingValue');
return TextEditingValue.empty;
}