-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
text_editing.dart
2467 lines (2146 loc) · 87.1 KB
/
text_editing.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 2013 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.
import 'dart:async';
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:meta/meta.dart';
import 'package:ui/ui.dart' as ui;
import '../browser_detection.dart';
import '../dom.dart';
import '../embedder.dart';
import '../platform_dispatcher.dart';
import '../safe_browser_api.dart';
import '../semantics.dart';
import '../services.dart';
import '../text/paragraph.dart';
import '../util.dart';
import 'autofill_hint.dart';
import 'composition_aware_mixin.dart';
import 'input_action.dart';
import 'input_type.dart';
import 'text_capitalization.dart';
/// Make the content editable span visible to facilitate debugging.
bool _debugVisibleTextEditing = false;
/// Set this to `true` to print when text input commands are scheduled and run.
bool _debugPrintTextInputCommands = false;
/// The `keyCode` of the "Enter" key.
const int _kReturnKeyCode = 13;
/// Offset in pixels to place an element outside of the screen.
const int offScreenOffset = -9999;
/// Blink and Webkit engines, bring an overlay on top of the text field when it
/// is autofilled.
bool browserHasAutofillOverlay() =>
browserEngine == BrowserEngine.blink ||
browserEngine == BrowserEngine.webkit;
/// `transparentTextEditing` class is configured to make the autofill overlay
/// transparent.
const String transparentTextEditingClass = 'transparentTextEditing';
void _emptyCallback(dynamic _) {}
/// The default [HostNode] that hosts all DOM required for text editing when a11y is not enabled.
@visibleForTesting
DomElement get defaultTextEditingRoot =>
flutterViewEmbedder.textEditingHostNode;
/// These style attributes are constant throughout the life time of an input
/// element.
///
/// They are assigned once during the creation of the DOM element.
void _setStaticStyleAttributes(DomHTMLElement domElement) {
domElement.classList.add(HybridTextEditing.textEditingClass);
final DomCSSStyleDeclaration elementStyle = domElement.style;
elementStyle
// Prevent (forced-colors: active) from making our invisible text fields visible.
// For more details, see: https://developer.mozilla.org/en-US/docs/Web/CSS/forced-color-adjust
..setProperty('forced-color-adjust', 'none')
..whiteSpace = 'pre-wrap'
..alignContent = 'center'
..position = 'absolute'
..top = '0'
..left = '0'
..padding = '0'
..opacity = '1'
..color = 'transparent'
..backgroundColor = 'transparent'
..background = 'transparent'
// This property makes the input's blinking cursor transparent.
..caretColor = 'transparent'
..outline = 'none'
..border = 'none'
..resize = 'none'
..textShadow = 'none'
..overflow = 'hidden'
..transformOrigin = '0 0 0';
if (browserHasAutofillOverlay()) {
domElement.classList.add(transparentTextEditingClass);
}
if (_debugVisibleTextEditing) {
elementStyle
..color = 'purple'
..outline = '1px solid purple';
}
}
/// Sets attributes to hide autofill elements.
///
/// These style attributes are constant throughout the life time of an input
/// element.
///
/// They are assigned once during the creation of the DOM element.
void _styleAutofillElements(
DomHTMLElement domElement, {
bool isOffScreen = false,
bool shouldHideElement = true,
bool shouldDisablePointerEvents = false,
}) {
final DomCSSStyleDeclaration elementStyle = domElement.style;
elementStyle
..whiteSpace = 'pre-wrap'
..alignContent = 'center'
..padding = '0'
..opacity = '1'
..color = 'transparent'
..backgroundColor = 'transparent'
..background = 'transparent'
..outline = 'none'
..border = 'none'
..resize = 'none'
..textShadow = 'transparent'
..transformOrigin = '0 0 0';
if (isOffScreen) {
elementStyle
..top = '${offScreenOffset}px'
..left = '${offScreenOffset}px';
}
if (shouldHideElement) {
elementStyle
..width = '0'
..height = '0';
}
if (shouldDisablePointerEvents) {
elementStyle.pointerEvents = 'none';
}
if (browserHasAutofillOverlay()) {
domElement.classList.add(transparentTextEditingClass);
}
/// This property makes the input's blinking cursor transparent.
elementStyle.setProperty('caret-color', 'transparent');
}
/// Form that contains all the fields in the same AutofillGroup.
///
/// An [EngineAutofillForm] will only be constructed when autofill is enabled
/// (the default) on the current input field. See the [fromFrameworkMessage]
/// static method.
class EngineAutofillForm {
EngineAutofillForm({
required this.formElement,
this.elements,
this.items,
this.formIdentifier = '',
this.insertionReferenceNode,
});
final DomHTMLFormElement formElement;
final Map<String, DomHTMLElement>? elements;
final Map<String, AutofillInfo>? items;
final DomHTMLElement? insertionReferenceNode;
/// Identifier for the form.
///
/// It is constructed by concatenating unique ids of input elements on the
/// form.
///
/// It is used for storing the form until submission.
/// See [formsOnTheDom].
final String formIdentifier;
/// Creates an [EngineAutofillFrom] from the JSON representation of a Flutter
/// framework `TextInputConfiguration` object.
///
/// The `focusedElementAutofill` argument corresponds to the "autofill" field
/// in a `TextInputConfiguration`. Not having this field indicates autofill
/// is explicitly disabled on the text field by the developer.
///
/// The `fields` argument corresponds to the "fields" field in a
/// `TextInputConfiguration`.
///
/// Returns null if autofill is disabled for the input field.
static EngineAutofillForm? fromFrameworkMessage(
Map<String, dynamic>? focusedElementAutofill,
List<dynamic>? fields,
) {
// Autofill value will be null if the developer explicitly disables it on
// the input field.
if (focusedElementAutofill == null) {
return null;
}
// If there is only one text field in the autofill model, `fields` will be
// null. `focusedElementAutofill` contains the information about the one
// text field.
final Map<String, DomHTMLElement> elements = <String, DomHTMLElement>{};
final Map<String, AutofillInfo> items = <String, AutofillInfo>{};
final DomHTMLFormElement formElement = createDomHTMLFormElement();
final bool isSafariDesktopStrategy = textEditing.strategy is SafariDesktopTextEditingStrategy;
DomHTMLElement? insertionReferenceNode;
// Validation is in the framework side.
formElement.noValidate = true;
formElement.method = 'post';
formElement.action = '#';
formElement.addEventListener('submit', createDomEventListener((DomEvent e) {
e.preventDefault();
}));
// We need to explicitly disable pointer events on the form in Safari Desktop,
// so that we don't have pointer event collisions if users hover over or click
// into the invisible autofill elements within the form.
_styleAutofillElements(formElement, shouldDisablePointerEvents: isSafariDesktopStrategy);
// We keep the ids in a list then sort them later, in case the text fields'
// locations are re-ordered on the framework side.
final List<String> ids = List<String>.empty(growable: true);
// The focused text editing element will not be created here.
final AutofillInfo focusedElement =
AutofillInfo.fromFrameworkMessage(focusedElementAutofill);
if (fields != null) {
bool fieldIsFocusedElement = false;
for (final Map<String, dynamic> field in
fields.cast<Map<String, dynamic>>()) {
final Map<String, dynamic> autofillInfo = field.readJson('autofill');
final AutofillInfo autofill = AutofillInfo.fromFrameworkMessage(
autofillInfo,
textCapitalization: TextCapitalizationConfig.fromInputConfiguration(
field.readString('textCapitalization'),
),
);
ids.add(autofill.uniqueIdentifier);
if (autofill.uniqueIdentifier != focusedElement.uniqueIdentifier) {
final EngineInputType engineInputType = EngineInputType.fromName(
field.readJson('inputType').readString('name'),
);
final DomHTMLElement htmlElement = engineInputType.createDomElement();
autofill.editingState.applyToDomElement(htmlElement);
autofill.applyToDomElement(htmlElement);
// Safari Desktop does not respect elements that are invisible (or
// have no size) and that leads to issues with autofill only partially
// working (ref: https://github.com/flutter/flutter/issues/71275).
// Thus, we have to make sure that the elements remain invisible to users,
// but not to Safari for autofill to work. Since these elements are
// sized and placed on the DOM, we also have to disable pointer events.
_styleAutofillElements(htmlElement,
shouldHideElement: !isSafariDesktopStrategy,
shouldDisablePointerEvents: isSafariDesktopStrategy);
items[autofill.uniqueIdentifier] = autofill;
elements[autofill.uniqueIdentifier] = htmlElement;
formElement.append(htmlElement);
// We want to track the node in the position directly after our focused
// element, so we can later insert that element in the correct position
// right before this node.
if(fieldIsFocusedElement){
insertionReferenceNode = htmlElement;
fieldIsFocusedElement = false;
}
} else {
// current field is the focused element that we create elsewhere
fieldIsFocusedElement = true;
}
}
} else {
// There is one input element in the form.
ids.add(focusedElement.uniqueIdentifier);
}
ids.sort();
final StringBuffer idBuffer = StringBuffer();
// Add a separator between element identifiers.
for (final String id in ids) {
if (idBuffer.length > 0) {
idBuffer.write('*');
}
idBuffer.write(id);
}
final String formIdentifier = idBuffer.toString();
// If a form with the same Autofill elements is already on the dom, remove
// it from DOM.
final DomHTMLFormElement? form = formsOnTheDom[formIdentifier];
form?.remove();
// In order to submit the form when Framework sends a `TextInput.commit`
// message, we add a submit button to the form.
final DomHTMLInputElement submitButton = createDomHTMLInputElement();
_styleAutofillElements(submitButton, isOffScreen: true);
submitButton.className = 'submitBtn';
submitButton.type = 'submit';
formElement.append(submitButton);
// If the focused node is at the end of the form, we'll default to inserting
// it before the submit field.
insertionReferenceNode ??= submitButton;
return EngineAutofillForm(
formElement: formElement,
elements: elements,
items: items,
formIdentifier: formIdentifier,
insertionReferenceNode: insertionReferenceNode
);
}
void placeForm(DomHTMLElement mainTextEditingElement) {
formElement.insertBefore(mainTextEditingElement, insertionReferenceNode);
defaultTextEditingRoot.append(formElement);
}
void storeForm() {
formsOnTheDom[formIdentifier] = formElement;
_styleAutofillElements(formElement, isOffScreen: true);
}
/// Listens to `onInput` event on the form fields.
///
/// Registering to the listeners could have been done in the constructor.
/// On the other hand, overall for text editing there is already a lifecycle
/// for subscriptions: All the subscriptions of the DOM elements are to the
/// `subscriptions` property of [DefaultTextEditingStrategy].
/// [TextEditingStrategy] manages all subscription lifecyle. All
/// listeners with no exceptions are added during
/// [TextEditingStrategy.addEventHandlers] method call and all
/// listeners are removed during [TextEditingStrategy.disable] method call.
List<DomSubscription> addInputEventListeners() {
final Iterable<String> keys = elements!.keys;
final List<DomSubscription> subscriptions = <DomSubscription>[];
void addSubscriptionForKey(String key) {
final DomElement element = elements![key]!;
subscriptions.add(
DomSubscription(element, 'input',
(DomEvent e) {
if (items![key] == null) {
throw StateError(
'AutofillInfo must have a valid uniqueIdentifier.');
} else {
final AutofillInfo autofillInfo = items![key]!;
handleChange(element, autofillInfo);
}
}));
}
keys.forEach(addSubscriptionForKey);
return subscriptions;
}
void handleChange(DomElement domElement, AutofillInfo autofillInfo) {
final EditingState newEditingState = EditingState.fromDomElement(
domElement as DomHTMLElement);
_sendAutofillEditingState(autofillInfo.uniqueIdentifier, newEditingState);
}
/// Sends the 'TextInputClient.updateEditingStateWithTag' message to the framework.
void _sendAutofillEditingState(String? tag, EditingState editingState) {
EnginePlatformDispatcher.instance.invokeOnPlatformMessage(
'flutter/textinput',
const JSONMethodCodec().encodeMethodCall(
MethodCall(
'TextInputClient.updateEditingStateWithTag',
<dynamic>[
0,
<String?, dynamic>{tag: editingState.toFlutter()}
],
),
),
_emptyCallback,
);
}
}
/// Autofill related values.
///
/// These values are to be used when a text field have autofill enabled.
@visibleForTesting
class AutofillInfo {
AutofillInfo({
required this.editingState,
required this.uniqueIdentifier,
required this.autofillHint,
required this.textCapitalization,
this.placeholder,
});
factory AutofillInfo.fromFrameworkMessage(Map<String, dynamic> autofill,
{TextCapitalizationConfig textCapitalization =
const TextCapitalizationConfig.defaultCapitalization()}) {
final String uniqueIdentifier = autofill.readString('uniqueIdentifier');
final List<dynamic>? hintsList = autofill.tryList('hints');
final String? firstHint = (hintsList == null || hintsList.isEmpty) ? null : hintsList.first as String;
final EditingState editingState =
EditingState.fromFrameworkMessage(autofill.readJson('editingValue'));
return AutofillInfo(
uniqueIdentifier: uniqueIdentifier,
autofillHint: (firstHint != null) ? BrowserAutofillHints.instance.flutterToEngine(firstHint) : null,
editingState: editingState,
placeholder: autofill.tryString('hintText'),
textCapitalization: textCapitalization,
);
}
/// The current text and selection state of a text field.
final EditingState editingState;
/// Unique value set by the developer or generated by the framework.
///
/// Used as id of the text field.
///
/// An example an id generated by the framework: `EditableText-285283643`.
final String uniqueIdentifier;
/// Information on how should autofilled text capitalized.
///
/// For example for [TextCapitalization.characters] each letter is converted
/// to upper case.
///
/// This value is not necessary for autofilling the focused element since
/// [DefaultTextEditingStrategy.inputConfiguration] already has this
/// information.
///
/// On the other hand for the multi element forms, for the input elements
/// other the focused field, we need to use this information.
final TextCapitalizationConfig textCapitalization;
/// The type of information expected in the field, specified by the developer.
///
/// Used as a guidance to the browser as to the type of information expected
/// in the field.
/// See: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete
final String? autofillHint;
/// The optional hint text placed on the view that typically suggests what
/// sort of input the field accepts, for example "enter your password here".
///
/// If the developer does not specify any [autofillHints], the [placeholder]
/// can be a useful indication to the platform autofill service as to what
/// information is expected in this field.
final String? placeholder;
void applyToDomElement(DomHTMLElement domElement,
{bool focusedElement = false}) {
final String? autofillHint = this.autofillHint;
final String? placeholder = this.placeholder;
if (domInstanceOfString(domElement, 'HTMLInputElement')) {
final DomHTMLInputElement element = domElement as DomHTMLInputElement;
if (placeholder != null) {
element.placeholder = placeholder;
}
if (autofillHint != null) {
element.name = autofillHint;
element.id = autofillHint;
if (autofillHint.contains('password')) {
element.type = 'password';
} else {
element.type = 'text';
}
}
element.autocomplete = autofillHint ?? 'on';
} else if (domInstanceOfString(domElement, 'HTMLTextAreaElement')) {
final DomHTMLTextAreaElement element = domElement as DomHTMLTextAreaElement;
if (placeholder != null) {
element.placeholder = placeholder;
}
if (autofillHint != null) {
element.name = autofillHint;
element.id = autofillHint;
}
element.setAttribute('autocomplete', autofillHint ?? 'on');
}
}
}
/// Replaces a range of text in the original string with the text given in the
/// replacement string.
String _replace(String originalText, String replacementText, ui.TextRange replacedRange) {
assert(replacedRange.isValid);
assert(replacedRange.start <= originalText.length && replacedRange.end <= originalText.length);
final ui.TextRange normalizedRange = ui.TextRange(start: math.min(replacedRange.start, replacedRange.end), end: math.max(replacedRange.start, replacedRange.end));
return normalizedRange.textBefore(originalText) + replacementText + normalizedRange.textAfter(originalText);
}
/// The change between the last editing state and the current editing state
/// of a text field.
///
/// This is packaged into a JSON and sent to the framework
/// to be processed into a concrete [TextEditingDelta].
class TextEditingDeltaState {
TextEditingDeltaState({
this.oldText = '',
this.deltaText = '',
this.deltaStart = -1,
this.deltaEnd = -1,
this.baseOffset,
this.extentOffset,
this.composingOffset,
this.composingExtent,
});
/// Infers the correct delta values based on information from the new editing state
/// and the last editing state.
///
/// For a deletion, the length and the direction of the deletion (backward or forward)
/// are calculated by comparing the new and last editing states.
/// If the deletion is backward, the length is susbtracted from the [deltaEnd]
/// that we set when beforeinput was fired to determine the [deltaStart].
/// If the deletion is forward, [deltaStart] is set to the new editing state baseOffset
/// and [deltaEnd] is set to [deltaStart] incremented by the length of the deletion.
///
/// For a replacement at a selection we set the [deltaStart] to be the beginning of the selection
/// from the last editing state.
///
/// For the composing region we check if a composing range was captured by the compositionupdate event,
/// we have a non empty [deltaText], and that we did not have an active selection. An active selection
/// would mean we are not composing.
///
/// We then verify that the delta we collected results in the text contained within the new editing state
/// when applied to the last editing state. If it is not then we use our new editing state as the source of truth,
/// and use regex to find the correct [deltaStart] and [deltaEnd].
static TextEditingDeltaState inferDeltaState(EditingState newEditingState, EditingState? lastEditingState, TextEditingDeltaState lastTextEditingDeltaState) {
final TextEditingDeltaState newTextEditingDeltaState = lastTextEditingDeltaState.copyWith();
final bool previousSelectionWasCollapsed = lastEditingState?.baseOffset == lastEditingState?.extentOffset;
final bool isTextBeingRemoved = newTextEditingDeltaState.deltaText.isEmpty && newTextEditingDeltaState.deltaEnd != -1;
final bool isTextBeingChangedAtActiveSelection = newTextEditingDeltaState.deltaText.isNotEmpty && !previousSelectionWasCollapsed;
if (isTextBeingRemoved) {
// When text is deleted outside of the composing region or is cut using the native toolbar,
// we calculate the length of the deleted text by comparing the new and old editing state lengths.
// If the deletion is backward, the length is subtracted from the [deltaEnd]
// that we set when beforeinput was fired to determine the [deltaStart].
// If the deletion is forward, [deltaStart] is set to the new editing state baseOffset
// and [deltaEnd] is set to [deltaStart] incremented by the length of the deletion.
final int deletedLength = newTextEditingDeltaState.oldText.length - newEditingState.text!.length;
final bool backwardDeletion = newEditingState.baseOffset != lastEditingState?.baseOffset;
if (backwardDeletion) {
newTextEditingDeltaState.deltaStart = newTextEditingDeltaState.deltaEnd - deletedLength;
} else {
// Forward deletion
newTextEditingDeltaState.deltaStart = newEditingState.baseOffset!;
newTextEditingDeltaState.deltaEnd = newTextEditingDeltaState.deltaStart + deletedLength;
}
} else if (isTextBeingChangedAtActiveSelection) {
final bool isPreviousSelectionInverted = lastEditingState!.baseOffset! > lastEditingState.extentOffset!;
// When a selection of text is replaced by a copy/paste operation we set the starting range
// of the delta to be the beginning of the selection of the previous editing state.
newTextEditingDeltaState.deltaStart = isPreviousSelectionInverted ? lastEditingState.extentOffset! : lastEditingState.baseOffset!;
}
// If we are composing then set the delta range to the composing region we
// captured in compositionupdate.
final bool isCurrentlyComposing = newTextEditingDeltaState.composingOffset != null && newTextEditingDeltaState.composingOffset != newTextEditingDeltaState.composingExtent;
if (newTextEditingDeltaState.deltaText.isNotEmpty && previousSelectionWasCollapsed && isCurrentlyComposing) {
newTextEditingDeltaState.deltaStart = newTextEditingDeltaState.composingOffset!;
}
final bool isDeltaRangeEmpty = newTextEditingDeltaState.deltaStart == -1 && newTextEditingDeltaState.deltaStart == newTextEditingDeltaState.deltaEnd;
if (!isDeltaRangeEmpty) {
// To verify the range of our delta we should compare the newEditingState's
// text with the delta applied to the oldText. If they differ then capture
// the correct delta range from the newEditingState's text value.
//
// We can assume the deltaText for additions and replacements to the text value
// are accurate. What may not be accurate is the range of the delta.
//
// We can think of the newEditingState as our source of truth.
//
// This verification is needed for cases such as the insertion of a period
// after a double space, and the insertion of an accented character through
// a native composing menu.
final ui.TextRange replacementRange = ui.TextRange(start: newTextEditingDeltaState.deltaStart, end: newTextEditingDeltaState.deltaEnd);
final String textAfterDelta = _replace(
newTextEditingDeltaState.oldText, newTextEditingDeltaState.deltaText,
replacementRange);
final bool isDeltaVerified = textAfterDelta == newEditingState.text!;
if (!isDeltaVerified) {
// 1. Find all matches for deltaText.
// 2. Apply matches/replacement to oldText until oldText matches the
// new editing state's text value.
final bool isPeriodInsertion = newTextEditingDeltaState.deltaText.contains('.');
final RegExp deltaTextPattern = RegExp(RegExp.escape(newTextEditingDeltaState.deltaText));
for (final Match match in deltaTextPattern.allMatches(newEditingState.text!)) {
String textAfterMatch;
int actualEnd;
final bool isMatchWithinOldTextBounds = match.start >= 0 && match.end <= newTextEditingDeltaState.oldText.length;
if (!isMatchWithinOldTextBounds) {
actualEnd = match.start + newTextEditingDeltaState.deltaText.length - 1;
textAfterMatch = _replace(
newTextEditingDeltaState.oldText,
newTextEditingDeltaState.deltaText,
ui.TextRange(
start: match.start,
end: actualEnd,
),
);
} else {
actualEnd = actualEnd = isPeriodInsertion? match.end - 1 : match.end;
textAfterMatch = _replace(
newTextEditingDeltaState.oldText,
newTextEditingDeltaState.deltaText,
ui.TextRange(
start: match.start,
end: actualEnd,
),
);
}
if (textAfterMatch == newEditingState.text!) {
newTextEditingDeltaState.deltaStart = match.start;
newTextEditingDeltaState.deltaEnd = actualEnd;
break;
}
}
}
}
// Update selection of the delta using information from the new editing state.
newTextEditingDeltaState.baseOffset = newEditingState.baseOffset;
newTextEditingDeltaState.extentOffset = newEditingState.extentOffset;
return newTextEditingDeltaState;
}
/// The text before the text field was updated.
String oldText;
/// The text that is being inserted/replaced into the text field.
/// This will be an empty string for deletions and non text updates
/// such as selection updates.
String deltaText;
/// The position in the text field where the change begins.
///
/// Has a default value of -1 to signify an empty range.
int deltaStart;
/// The position in the text field where the change ends.
///
/// Has a default value of -1 to signify an empty range.
int deltaEnd;
/// The updated starting position of the selection in the text field.
int? baseOffset;
/// The updated terminating position of the selection in the text field.
int? extentOffset;
/// The starting position of the composing region.
int? composingOffset;
/// The terminating position of the composing region.
int? composingExtent;
Map<String, dynamic> toFlutter() => <String, dynamic>{
'deltas': <Map<String, dynamic>>[
<String, dynamic>{
'oldText': oldText,
'deltaText': deltaText,
'deltaStart': deltaStart,
'deltaEnd': deltaEnd,
'selectionBase': baseOffset,
'selectionExtent': extentOffset,
'composingBase': composingOffset,
'composingExtent': composingExtent
},
],
};
TextEditingDeltaState copyWith({
String? oldText,
String? deltaText,
int? deltaStart,
int? deltaEnd,
int? baseOffset,
int? extentOffset,
int? composingOffset,
int? composingExtent,
}) {
return TextEditingDeltaState(
oldText: oldText ?? this.oldText,
deltaText: deltaText ?? this.deltaText,
deltaStart: deltaStart ?? this.deltaStart,
deltaEnd: deltaEnd ?? this.deltaEnd,
baseOffset: baseOffset ?? this.baseOffset,
extentOffset: extentOffset ?? this.extentOffset,
composingOffset: composingOffset ?? this.composingOffset,
composingExtent: composingExtent ?? this.composingExtent,
);
}
}
/// The current text and selection state of a text field.
class EditingState {
EditingState({
this.text,
int? baseOffset,
int? extentOffset,
this.composingBaseOffset = -1,
this.composingExtentOffset = -1
}) :
// Don't allow negative numbers.
baseOffset = math.max(0, baseOffset ?? 0),
// Don't allow negative numbers.
extentOffset = math.max(0, extentOffset ?? 0);
/// Creates an [EditingState] instance using values from an editing state Map
/// coming from Flutter.
///
/// The `editingState` Map has the following structure:
/// ```json
/// {
/// "text": "The text here",
/// "selectionBase": 0,
/// "selectionExtent": 0,
/// "selectionAffinity": "TextAffinity.upstream",
/// "selectionIsDirectional": false,
/// "composingBase": -1,
/// "composingExtent": -1
/// }
/// ```
///
/// Flutter Framework can send the [selectionBase] and [selectionExtent] as
/// -1, if so 0 assigned to the [baseOffset] and [extentOffset]. -1 is not a
/// valid selection range for input DOM elements.
factory EditingState.fromFrameworkMessage(
Map<String, dynamic> flutterEditingState) {
final String? text = flutterEditingState.tryString('text');
final int selectionBase = flutterEditingState.readInt('selectionBase');
final int selectionExtent = flutterEditingState.readInt('selectionExtent');
final int? composingBase = flutterEditingState.tryInt('composingBase');
final int? composingExtent = flutterEditingState.tryInt('composingExtent');
return EditingState(
text: text,
baseOffset: selectionBase,
extentOffset: selectionExtent,
composingBaseOffset: composingBase ?? -1,
composingExtentOffset: composingExtent ?? -1
);
}
/// Creates an [EditingState] instance using values from the editing element
/// in the DOM.
///
/// [domElement] can be a [InputElement] or a [TextAreaElement] depending on
/// the [InputType] of the text field.
factory EditingState.fromDomElement(DomHTMLElement? domElement) {
if (domInstanceOfString(domElement, 'HTMLInputElement')) {
final DomHTMLInputElement element = domElement! as DomHTMLInputElement;
if (element.selectionDirection == 'backward') {
return EditingState(
text: element.value,
baseOffset: element.selectionEnd?.toInt(),
extentOffset: element.selectionStart?.toInt());
} else {
return EditingState(
text: element.value,
baseOffset: element.selectionStart?.toInt(),
extentOffset: element.selectionEnd?.toInt());
}
} else if (domInstanceOfString(domElement, 'HTMLTextAreaElement')) {
final DomHTMLTextAreaElement element = domElement! as
DomHTMLTextAreaElement;
if (element.selectionDirection == 'backward') {
return EditingState(
text: element.value,
baseOffset: element.selectionEnd?.toInt(),
extentOffset: element.selectionStart?.toInt());
} else {
return EditingState(
text: element.value,
baseOffset: element.selectionStart?.toInt(),
extentOffset: element.selectionEnd?.toInt());
}
} else {
throw UnsupportedError('Initialized with unsupported input type');
}
}
// Pick the smallest selection index for base.
int get minOffset => math.min(baseOffset ?? 0, extentOffset ?? 0);
// Pick the greatest selection index for extent.
int get maxOffset => math.max(baseOffset ?? 0, extentOffset ?? 0);
EditingState copyWith({
String? text,
int? baseOffset,
int? extentOffset,
int? composingBaseOffset,
int? composingExtentOffset,
}) {
return EditingState(
text: text ?? this.text,
baseOffset: baseOffset ?? this.baseOffset,
extentOffset: extentOffset ?? this.extentOffset,
composingBaseOffset: composingBaseOffset ?? this.composingBaseOffset,
composingExtentOffset: composingExtentOffset ?? this.composingExtentOffset,
);
}
/// The counterpart of [EditingState.fromFrameworkMessage]. It generates a Map that
/// can be sent to Flutter.
// TODO(mdebbar): Should we get `selectionAffinity` and other properties from flutter's editing state?
Map<String, dynamic> toFlutter() => <String, dynamic>{
'text': text,
'selectionBase': baseOffset,
'selectionExtent': extentOffset,
'composingBase': composingBaseOffset,
'composingExtent': composingExtentOffset,
};
/// The current text being edited.
final String? text;
/// The offset at which the text selection originates.
final int? baseOffset;
/// The offset at which the text selection terminates.
final int? extentOffset;
/// The offset at which [CompositionAwareMixin.composingText] begins, if any.
final int composingBaseOffset;
/// The offset at which [CompositionAwareMixin.composingText] terminates, if any.
final int composingExtentOffset;
/// Whether the current editing state is valid or not.
bool get isValid => baseOffset! >= 0 && extentOffset! >= 0;
@override
int get hashCode => Object.hash(
text, baseOffset, extentOffset, composingBaseOffset, composingExtentOffset
);
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (runtimeType != other.runtimeType) {
return false;
}
return other is EditingState &&
other.text == text &&
other.minOffset == minOffset &&
other.maxOffset == maxOffset &&
other.composingBaseOffset == composingBaseOffset &&
other.composingExtentOffset == composingExtentOffset;
}
@override
String toString() {
String result = super.toString();
assert(() {
result = 'EditingState("$text", base:$baseOffset, extent:$extentOffset, composingBase:$composingBaseOffset, composingExtent:$composingExtentOffset)';
return true;
}());
return result;
}
/// Sets the selection values of a DOM element using this [EditingState].
///
/// [domElement] can be a [InputElement] or a [TextAreaElement] depending on
/// the [InputType] of the text field.
///
/// This should only be used by focused elements only, because only focused
/// elements can have their text selection range set. Attempting to set
/// selection range on a non-focused element will cause it to request focus.
///
/// See also:
///
/// * [applyTextToDomElement], which is used for non-focused elements.
void applyToDomElement(DomHTMLElement? domElement) {
if (domInstanceOfString(domElement, 'HTMLInputElement')) {
final DomHTMLInputElement element = domElement! as DomHTMLInputElement;
element.value = text;
element.setSelectionRange(minOffset, maxOffset);
} else if (domInstanceOfString(domElement, 'HTMLTextAreaElement')) {
final DomHTMLTextAreaElement element = domElement! as
DomHTMLTextAreaElement;
element.value = text;
element.setSelectionRange(minOffset, maxOffset);
} else {
throw UnsupportedError('Unsupported DOM element type: <${domElement?.tagName}> (${domElement.runtimeType})');
}
}
/// Applies the [text] to the [domElement].
///
/// This is used by non-focused elements.
///
/// See also:
///
/// * [applyToDomElement], which is used for focused elements.
void applyTextToDomElement(DomHTMLElement? domElement) {
if (domInstanceOfString(domElement, 'HTMLInputElement')) {
final DomHTMLInputElement element = domElement! as DomHTMLInputElement;
element.value = text;
} else if (domInstanceOfString(domElement, 'HTMLTextAreaElement')) {
final DomHTMLTextAreaElement element = domElement! as
DomHTMLTextAreaElement;
element.value = text;
} else {
throw UnsupportedError('Unsupported DOM element type');
}
}
}
/// Controls the appearance of the input control being edited.
///
/// For example, [inputType] determines whether we should use `<input>` or
/// `<textarea>` as a backing DOM element.
///
/// This corresponds to Flutter's [TextInputConfiguration].
class InputConfiguration {
InputConfiguration({
this.inputType = EngineInputType.text,
this.inputAction = 'TextInputAction.done',
this.obscureText = false,
this.readOnly = false,
this.autocorrect = true,
this.textCapitalization =
const TextCapitalizationConfig.defaultCapitalization(),
this.autofill,
this.autofillGroup,
this.enableDeltaModel = false,
});
InputConfiguration.fromFrameworkMessage(
Map<String, dynamic> flutterInputConfiguration)
: inputType = EngineInputType.fromName(
flutterInputConfiguration.readJson('inputType').readString('name'),
isDecimal: flutterInputConfiguration.readJson('inputType').tryBool('decimal') ?? false,
),
inputAction =
flutterInputConfiguration.tryString('inputAction') ?? 'TextInputAction.done',
obscureText = flutterInputConfiguration.tryBool('obscureText') ?? false,
readOnly = flutterInputConfiguration.tryBool('readOnly') ?? false,
autocorrect = flutterInputConfiguration.tryBool('autocorrect') ?? true,
textCapitalization = TextCapitalizationConfig.fromInputConfiguration(
flutterInputConfiguration.readString('textCapitalization'),
),
autofill = flutterInputConfiguration.containsKey('autofill')
? AutofillInfo.fromFrameworkMessage(
flutterInputConfiguration.readJson('autofill'))
: null,
autofillGroup = EngineAutofillForm.fromFrameworkMessage(
flutterInputConfiguration.tryJson('autofill'),
flutterInputConfiguration.tryList('fields'),
),
enableDeltaModel = flutterInputConfiguration.tryBool('enableDeltaModel') ?? false;
/// The type of information being edited in the input control.
final EngineInputType inputType;
/// The default action for the input field.
final String inputAction;
/// Whether the text field can be edited or not.
///
/// Defaults to false.
final bool readOnly;
/// Whether to hide the text being edited.
final bool obscureText;
/// Whether to enable autocorrection.
///
/// Definition of autocorrect can be found in:
/// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
///
/// For future manual tests, note that autocorrect is an attribute only
/// supported by Safari.
final bool autocorrect;
final bool enableDeltaModel;