forked from facebook/react-native
-
Notifications
You must be signed in to change notification settings - Fork 166
Expand file tree
/
Copy pathRCTTextInputComponentView.mm
More file actions
1197 lines (1019 loc) · 45.3 KB
/
RCTTextInputComponentView.mm
File metadata and controls
1197 lines (1019 loc) · 45.3 KB
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 (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import "RCTTextInputComponentView.h"
#import <react/renderer/components/iostextinput/TextInputComponentDescriptor.h>
#import <react/renderer/textlayoutmanager/RCTAttributedTextUtils.h>
#import <react/renderer/textlayoutmanager/TextLayoutManager.h>
#import <React/RCTBackedTextInputViewProtocol.h>
#import <React/RCTScrollViewComponentView.h>
#if !TARGET_OS_OSX // [macOS]
#import <React/RCTUITextField.h>
#else // [macOS
#include <React/RCTUITextField.h>
#include <React/RCTUISecureTextField.h>
#endif // macOS]
#import <React/RCTUITextView.h>
#import <React/RCTUtils.h>
#if TARGET_OS_OSX // [macOS
#import <React/RCTWrappedTextView.h>
#import <React/RCTViewKeyboardEvent.h>
#endif // macOS]
#import "RCTConversions.h"
#import "RCTTextInputNativeCommands.h"
#import "RCTTextInputUtils.h"
#import "RCTFabricComponentsPlugins.h"
#if !TARGET_OS_OSX // [macOS]
/** Native iOS text field bottom keyboard offset amount */
static const CGFloat kSingleLineKeyboardBottomOffset = 15.0;
#endif // [macOS]
#if TARGET_OS_OSX // [macOS
static NSString *kEscapeKeyCode = @"\x1B";
#endif // macOS]
using namespace facebook::react;
@interface RCTTextInputComponentView () <RCTBackedTextInputDelegate, RCTTextInputViewProtocol>
@end
static NSSet<NSNumber *> *returnKeyTypesSet;
@implementation RCTTextInputComponentView {
TextInputShadowNode::ConcreteState::Shared _state;
#if !TARGET_OS_OSX // [macOS]
RCTUIView<RCTBackedTextInputViewProtocol> *_backedTextInputView;
#else // [macOS
RCTPlatformView<RCTBackedTextInputViewProtocol> *_backedTextInputView;
#endif // macOS]
NSUInteger _mostRecentEventCount;
NSAttributedString *_lastStringStateWasUpdatedWith;
/*
* UIKit uses either UITextField or UITextView as its UIKit element for <TextInput>. UITextField is for single line
* entry, UITextView is for multiline entry. There is a problem with order of events when user types a character. In
* UITextField (single line text entry), typing a character first triggers `onChange` event and then
* onSelectionChange. In UITextView (multi line text entry), typing a character first triggers `onSelectionChange` and
* then onChange. JavaScript depends on `onChange` to be called before `onSelectionChange`. This flag keeps state so
* if UITextView is backing text input view, inside `-[RCTTextInputComponentView textInputDidChangeSelection]` we make
* sure to call `onChange` before `onSelectionChange` and ignore next `-[RCTTextInputComponentView
* textInputDidChange]` call.
*/
BOOL _ignoreNextTextInputCall;
/*
* A flag that when set to true, `_mostRecentEventCount` won't be incremented when `[self _updateState]`
* and delegate methods `textInputDidChange` and `textInputDidChangeSelection` will exit early.
*
* Setting `_backedTextInputView.attributedText` triggers delegate methods `textInputDidChange` and
* `textInputDidChangeSelection` for multiline text input only.
* In multiline text input this is undesirable as we don't want to be sending events for changes that JS triggered.
*/
BOOL _comingFromJS;
BOOL _didMoveToWindow;
/*
* Newly initialized default typing attributes contain a no-op NSParagraphStyle and NSShadow. These cause inequality
* between the AttributedString backing the input and those generated from state. We store these attributes to make
* later comparison insensitive to them.
*/
NSDictionary<NSAttributedStringKey, id> *_originalTypingAttributes;
BOOL _hasInputAccessoryView;
}
#pragma mark - UIView overrides
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
const auto &defaultProps = TextInputShadowNode::defaultSharedProps();
_props = defaultProps;
#if !TARGET_OS_OSX // [macOS]
_backedTextInputView = defaultProps->multiline ? [RCTUITextView new] : [RCTUITextField new];
#else // [macOS
_backedTextInputView = defaultProps->multiline ? [[RCTWrappedTextView alloc] initWithFrame:self.bounds] : [RCTUITextField new];
#endif // macOS]
_backedTextInputView.textInputDelegate = self;
_ignoreNextTextInputCall = NO;
_comingFromJS = NO;
_didMoveToWindow = NO;
_originalTypingAttributes = [_backedTextInputView.typingAttributes copy];
#if TARGET_OS_OSX // [macOS
[self setClipsToBounds:YES];
#endif // macOS]
[self addSubview:_backedTextInputView];
#if TARGET_OS_IOS // [macOS] [visionOS]
[self initializeReturnKeyType];
#endif // [macOS] [visionOS]
}
return self;
}
- (void)updateEventEmitter:(const EventEmitter::Shared &)eventEmitter
{
[super updateEventEmitter:eventEmitter];
NSMutableDictionary<NSAttributedStringKey, id> *defaultAttributes =
[_backedTextInputView.defaultTextAttributes mutableCopy];
#if !TARGET_OS_MACCATALYST
RCTWeakEventEmitterWrapper *eventEmitterWrapper = [RCTWeakEventEmitterWrapper new];
eventEmitterWrapper.eventEmitter = _eventEmitter;
defaultAttributes[RCTAttributedStringEventEmitterKey] = eventEmitterWrapper;
#endif
_backedTextInputView.defaultTextAttributes = defaultAttributes;
}
- (void)didMoveToWindow
{
[super didMoveToWindow];
if (self.window && !_didMoveToWindow) {
const auto &props = static_cast<const TextInputProps &>(*_props);
if (props.autoFocus) {
#if !TARGET_OS_OSX // [macOS]
[_backedTextInputView becomeFirstResponder];
#else // [macOS
NSWindow *window = [_backedTextInputView window];
[window makeFirstResponder:_backedTextInputView.responder];
#endif // macOS]
[self scrollCursorIntoView];
}
_didMoveToWindow = YES;
#if TARGET_OS_IOS // [macOS] [visionOS]
[self initializeReturnKeyType];
#endif // [macOS] [visionOS]
}
[self _restoreTextSelection];
}
- (void)reactUpdateResponderOffsetForScrollView:(RCTScrollViewComponentView *)scrollView
{
#if !TARGET_OS_OSX // [macOS]
if (![self isDescendantOfView:scrollView.scrollView] || !_backedTextInputView.isFirstResponder) {
// View is outside scroll view or it's not a first responder.
scrollView.firstResponderViewOutsideScrollView = _backedTextInputView;
return;
}
UITextRange *selectedTextRange = _backedTextInputView.selectedTextRange;
UITextSelectionRect *selection = [_backedTextInputView selectionRectsForRange:selectedTextRange].firstObject;
CGRect focusRect;
if (selection == nil) {
// No active selection or caret - fallback to entire input frame
focusRect = self.bounds;
} else {
// Focus on text selection frame
focusRect = selection.rect;
BOOL isMultiline = [_backedTextInputView isKindOfClass:[UITextView class]];
if (!isMultiline) {
focusRect.size.height += kSingleLineKeyboardBottomOffset;
}
}
scrollView.firstResponderFocus = [self convertRect:focusRect toView:nil];
#endif // [macOS]
}
#pragma mark - RCTViewComponentView overrides
- (NSObject *)accessibilityElement
{
return _backedTextInputView;
}
#pragma mark - RCTComponentViewProtocol
+ (ComponentDescriptorProvider)componentDescriptorProvider
{
return concreteComponentDescriptorProvider<TextInputComponentDescriptor>();
}
- (void)updateProps:(const Props::Shared &)props oldProps:(const Props::Shared &)oldProps
{
const auto &oldTextInputProps = static_cast<const TextInputProps &>(*_props);
const auto &newTextInputProps = static_cast<const TextInputProps &>(*props);
// Traits:
if (newTextInputProps.multiline != oldTextInputProps.multiline) {
[self _setMultiline:newTextInputProps.multiline];
}
#if !TARGET_OS_OSX // [macOS]
if (newTextInputProps.traits.autocapitalizationType != oldTextInputProps.traits.autocapitalizationType) {
_backedTextInputView.autocapitalizationType =
RCTUITextAutocapitalizationTypeFromAutocapitalizationType(newTextInputProps.traits.autocapitalizationType);
}
#endif // [macOS]
#if !TARGET_OS_OSX // [macOS]
if (newTextInputProps.traits.autoCorrect != oldTextInputProps.traits.autoCorrect) {
_backedTextInputView.autocorrectionType =
RCTUITextAutocorrectionTypeFromOptionalBool(newTextInputProps.traits.autoCorrect);
}
#else // [macOS
if (newTextInputProps.traits.autoCorrect != oldTextInputProps.traits.autoCorrect && newTextInputProps.traits.autoCorrect.has_value()) {
_backedTextInputView.automaticSpellingCorrectionEnabled =
newTextInputProps.traits.autoCorrect.value();
}
#endif // macOS]
if (newTextInputProps.traits.contextMenuHidden != oldTextInputProps.traits.contextMenuHidden) {
_backedTextInputView.contextMenuHidden = newTextInputProps.traits.contextMenuHidden;
}
if (newTextInputProps.traits.editable != oldTextInputProps.traits.editable) {
_backedTextInputView.editable = newTextInputProps.traits.editable;
}
#if !TARGET_OS_OSX // [macOS]
if (newTextInputProps.multiline &&
newTextInputProps.traits.dataDetectorTypes != oldTextInputProps.traits.dataDetectorTypes) {
_backedTextInputView.dataDetectorTypes =
RCTUITextViewDataDetectorTypesFromStringVector(newTextInputProps.traits.dataDetectorTypes);
}
#endif // [macOS]
#if !TARGET_OS_OSX // [macOS]
if (newTextInputProps.traits.enablesReturnKeyAutomatically !=
oldTextInputProps.traits.enablesReturnKeyAutomatically) {
_backedTextInputView.enablesReturnKeyAutomatically = newTextInputProps.traits.enablesReturnKeyAutomatically;
}
if (newTextInputProps.traits.keyboardAppearance != oldTextInputProps.traits.keyboardAppearance) {
_backedTextInputView.keyboardAppearance =
RCTUIKeyboardAppearanceFromKeyboardAppearance(newTextInputProps.traits.keyboardAppearance);
}
#endif // [macOS]
#if !TARGET_OS_OSX // [macOS]
if (newTextInputProps.traits.spellCheck != oldTextInputProps.traits.spellCheck) {
_backedTextInputView.spellCheckingType =
RCTUITextSpellCheckingTypeFromOptionalBool(newTextInputProps.traits.spellCheck);
}
#else // [macOS
if (newTextInputProps.traits.spellCheck != oldTextInputProps.traits.spellCheck && newTextInputProps.traits.spellCheck.has_value()) {
_backedTextInputView.continuousSpellCheckingEnabled =
newTextInputProps.traits.spellCheck.value();
}
#endif // macOS]
#if TARGET_OS_OSX // [macOS
if (newTextInputProps.traits.grammarCheck != oldTextInputProps.traits.grammarCheck && newTextInputProps.traits.grammarCheck.has_value()) {
_backedTextInputView.grammarCheckingEnabled =
newTextInputProps.traits.grammarCheck.value();
}
#endif // macOS]
if (newTextInputProps.traits.caretHidden != oldTextInputProps.traits.caretHidden) {
_backedTextInputView.caretHidden = newTextInputProps.traits.caretHidden;
}
#if !TARGET_OS_OSX // [macOS]
if (newTextInputProps.traits.clearButtonMode != oldTextInputProps.traits.clearButtonMode) {
_backedTextInputView.clearButtonMode =
RCTUITextFieldViewModeFromTextInputAccessoryVisibilityMode(newTextInputProps.traits.clearButtonMode);
}
#endif // [macOS]
if (newTextInputProps.traits.scrollEnabled != oldTextInputProps.traits.scrollEnabled) {
_backedTextInputView.scrollEnabled = newTextInputProps.traits.scrollEnabled;
}
if (newTextInputProps.traits.secureTextEntry != oldTextInputProps.traits.secureTextEntry) {
#if !TARGET_OS_OSX // [macOS]
_backedTextInputView.secureTextEntry = newTextInputProps.traits.secureTextEntry;
#else // [macOS
[self _setSecureTextEntry:newTextInputProps.traits.secureTextEntry];
#endif // macOS]
}
#if !TARGET_OS_OSX // [macOS]
if (newTextInputProps.traits.keyboardType != oldTextInputProps.traits.keyboardType) {
_backedTextInputView.keyboardType = RCTUIKeyboardTypeFromKeyboardType(newTextInputProps.traits.keyboardType);
}
if (newTextInputProps.traits.returnKeyType != oldTextInputProps.traits.returnKeyType) {
_backedTextInputView.returnKeyType = RCTUIReturnKeyTypeFromReturnKeyType(newTextInputProps.traits.returnKeyType);
}
if (newTextInputProps.traits.textContentType != oldTextInputProps.traits.textContentType) {
_backedTextInputView.textContentType = RCTUITextContentTypeFromString(newTextInputProps.traits.textContentType);
}
if (newTextInputProps.traits.passwordRules != oldTextInputProps.traits.passwordRules) {
_backedTextInputView.passwordRules = RCTUITextInputPasswordRulesFromString(newTextInputProps.traits.passwordRules);
}
if (newTextInputProps.traits.smartInsertDelete != oldTextInputProps.traits.smartInsertDelete) {
_backedTextInputView.smartInsertDeleteType =
RCTUITextSmartInsertDeleteTypeFromOptionalBool(newTextInputProps.traits.smartInsertDelete);
}
if (newTextInputProps.traits.showSoftInputOnFocus != oldTextInputProps.traits.showSoftInputOnFocus) {
[self _setShowSoftInputOnFocus:newTextInputProps.traits.showSoftInputOnFocus];
}
#endif // [macOS]
// Traits `blurOnSubmit`, `clearTextOnFocus`, and `selectTextOnFocus` were omitted intentionally here
// because they are being checked on-demand.
// Other props:
if (newTextInputProps.placeholder != oldTextInputProps.placeholder) {
_backedTextInputView.placeholder = RCTNSStringFromString(newTextInputProps.placeholder);
}
if (newTextInputProps.placeholderTextColor != oldTextInputProps.placeholderTextColor) {
_backedTextInputView.placeholderColor = RCTUIColorFromSharedColor(newTextInputProps.placeholderTextColor);
}
if (newTextInputProps.textAttributes != oldTextInputProps.textAttributes) {
NSMutableDictionary<NSAttributedStringKey, id> *defaultAttributes =
RCTNSTextAttributesFromTextAttributes(newTextInputProps.getEffectiveTextAttributes(RCTFontSizeMultiplier()));
#if !TARGET_OS_MACCATALYST
defaultAttributes[RCTAttributedStringEventEmitterKey] =
_backedTextInputView.defaultTextAttributes[RCTAttributedStringEventEmitterKey];
#endif
_backedTextInputView.defaultTextAttributes = defaultAttributes;
}
#if !TARGET_OS_OSX // [macOS]
if (newTextInputProps.selectionColor != oldTextInputProps.selectionColor) {
_backedTextInputView.tintColor = RCTUIColorFromSharedColor(newTextInputProps.selectionColor);
}
#endif // [macOS]
if (newTextInputProps.inputAccessoryViewID != oldTextInputProps.inputAccessoryViewID) {
_backedTextInputView.inputAccessoryViewID = RCTNSStringFromString(newTextInputProps.inputAccessoryViewID);
}
if (newTextInputProps.inputAccessoryViewButtonLabel != oldTextInputProps.inputAccessoryViewButtonLabel) {
_backedTextInputView.inputAccessoryViewButtonLabel =
RCTNSStringFromString(newTextInputProps.inputAccessoryViewButtonLabel);
}
if (newTextInputProps.disableKeyboardShortcuts != oldTextInputProps.disableKeyboardShortcuts) {
_backedTextInputView.disableKeyboardShortcuts = newTextInputProps.disableKeyboardShortcuts;
}
#if TARGET_OS_OSX // [macOS
if (newTextInputProps.traits.pastedTypes!= oldTextInputProps.traits.pastedTypes) {
NSArray<NSPasteboardType> *types = RCTPasteboardTypeArrayFromProps(newTextInputProps.traits.pastedTypes);
[_backedTextInputView setReadablePasteBoardTypes:types];
}
#endif // macOS]
[super updateProps:props oldProps:oldProps];
#if TARGET_OS_IOS // [macOS] [visionOS]
[self setDefaultInputAccessoryView];
#endif // [macOS] [visionOS]
}
- (void)updateState:(const State::Shared &)state oldState:(const State::Shared &)oldState
{
_state = std::static_pointer_cast<const TextInputShadowNode::ConcreteState>(state);
if (!_state) {
assert(false && "State is `null` for <TextInput> component.");
_backedTextInputView.attributedText = nil;
return;
}
auto data = _state->getData();
if (!oldState) {
_mostRecentEventCount = _state->getData().mostRecentEventCount;
}
if (_mostRecentEventCount == _state->getData().mostRecentEventCount) {
_comingFromJS = YES;
[self _setAttributedString:RCTNSAttributedStringFromAttributedStringBox(data.attributedStringBox)];
_comingFromJS = NO;
}
}
- (void)updateLayoutMetrics:(const LayoutMetrics &)layoutMetrics
oldLayoutMetrics:(const LayoutMetrics &)oldLayoutMetrics
{
CGSize previousContentSize = _backedTextInputView.contentSize;
[super updateLayoutMetrics:layoutMetrics oldLayoutMetrics:oldLayoutMetrics];
#if TARGET_OS_OSX // [macOS
_backedTextInputView.pointScaleFactor = layoutMetrics.pointScaleFactor;
#endif // macOS]
_backedTextInputView.frame =
UIEdgeInsetsInsetRect(self.bounds, RCTUIEdgeInsetsFromEdgeInsets(layoutMetrics.borderWidth));
_backedTextInputView.textContainerInset =
RCTUIEdgeInsetsFromEdgeInsets(layoutMetrics.contentInsets - layoutMetrics.borderWidth);
if (!CGSizeEqualToSize(previousContentSize, _backedTextInputView.contentSize) && _eventEmitter) {
static_cast<const TextInputEventEmitter &>(*_eventEmitter).onContentSizeChange([self _textInputMetrics]);
}
}
- (void)prepareForRecycle
{
[super prepareForRecycle];
_state.reset();
_backedTextInputView.attributedText = nil;
_mostRecentEventCount = 0;
_comingFromJS = NO;
_lastStringStateWasUpdatedWith = nil;
_ignoreNextTextInputCall = NO;
_didMoveToWindow = NO;
[_backedTextInputView resignFirstResponder];
}
#pragma mark - RCTBackedTextInputDelegate
- (BOOL)textInputShouldBeginEditing
{
return YES;
}
- (void)textInputDidBeginEditing
{
if (_eventEmitter) {
static_cast<const TextInputEventEmitter &>(*_eventEmitter).onFocus([self _textInputMetrics]);
}
}
- (BOOL)textInputShouldEndEditing
{
return YES;
}
- (void)textInputDidEndEditing
{
if (_eventEmitter) {
static_cast<const TextInputEventEmitter &>(*_eventEmitter).onEndEditing([self _textInputMetrics]);
static_cast<const TextInputEventEmitter &>(*_eventEmitter).onBlur([self _textInputMetrics]);
}
}
- (BOOL)textInputShouldSubmitOnReturn
{
const SubmitBehavior submitBehavior = [self getSubmitBehavior];
const BOOL shouldSubmit = submitBehavior == SubmitBehavior::Submit || submitBehavior == SubmitBehavior::BlurAndSubmit;
// We send `submit` event here, in `textInputShouldSubmitOnReturn`
// (not in `textInputDidReturn)`, because of semantic of the event:
// `onSubmitEditing` is called when "Submit" button
// (the blue key on onscreen keyboard) did pressed
// (no connection to any specific "submitting" process).
if (_eventEmitter && shouldSubmit) {
static_cast<const TextInputEventEmitter &>(*_eventEmitter).onSubmitEditing([self _textInputMetrics]);
}
return shouldSubmit;
}
- (BOOL)textInputShouldReturn
{
return [self getSubmitBehavior] == SubmitBehavior::BlurAndSubmit;
}
- (void)textInputDidReturn
{
// Does nothing.
}
- (NSString *)textInputShouldChangeText:(NSString *)text inRange:(NSRange)range
{
const auto &props = static_cast<const TextInputProps &>(*_props);
if (!_backedTextInputView.textWasPasted) {
if (_eventEmitter) {
const auto &textInputEventEmitter = static_cast<const TextInputEventEmitter &>(*_eventEmitter);
textInputEventEmitter.onKeyPress({
.text = RCTStringFromNSString(text),
.eventCount = static_cast<int>(_mostRecentEventCount),
});
}
}
if (props.maxLength) {
NSInteger allowedLength = props.maxLength - _backedTextInputView.attributedText.string.length + range.length;
if (allowedLength > 0 && text.length > allowedLength) {
// make sure unicode characters that are longer than 16 bits (such as emojis) are not cut off
NSRange cutOffCharacterRange = [text rangeOfComposedCharacterSequenceAtIndex:allowedLength - 1];
if (cutOffCharacterRange.location + cutOffCharacterRange.length > allowedLength) {
// the character at the length limit takes more than 16bits, truncation should end at the character before
allowedLength = cutOffCharacterRange.location;
}
}
if (allowedLength <= 0) {
return nil;
}
return allowedLength > text.length ? text : [text substringToIndex:allowedLength];
}
return text;
}
- (BOOL)textInputShouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
return YES;
}
- (void)textInputDidChange
{
if (_comingFromJS) {
return;
}
if (_ignoreNextTextInputCall && [_lastStringStateWasUpdatedWith isEqual:_backedTextInputView.attributedText]) {
_ignoreNextTextInputCall = NO;
return;
}
[self _updateState];
if (_eventEmitter) {
const auto &textInputEventEmitter = static_cast<const TextInputEventEmitter &>(*_eventEmitter);
textInputEventEmitter.onChange([self _textInputMetrics]);
}
}
- (void)textInputDidChangeSelection
{
if (_comingFromJS) {
return;
}
// T207198334: Setting a new AttributedString (_comingFromJS) will trigger a selection change before the backing
// string is updated, so indicies won't point to what we want yet. Only respond to user selection change, and let
// `_setAttributedString` handle updating typing attributes if content changes.
[self _updateTypingAttributes];
const auto &props = static_cast<const TextInputProps &>(*_props);
if (props.multiline && ![_lastStringStateWasUpdatedWith isEqual:_backedTextInputView.attributedText]) {
[self textInputDidChange];
_ignoreNextTextInputCall = YES;
}
if (_eventEmitter) {
static_cast<const TextInputEventEmitter &>(*_eventEmitter).onSelectionChange([self _textInputMetrics]);
}
}
#if TARGET_OS_OSX // [macOS
- (void)setEnableFocusRing:(BOOL)enableFocusRing {
[super setEnableFocusRing:enableFocusRing];
if ([_backedTextInputView respondsToSelector:@selector(setEnableFocusRing:)]) {
[_backedTextInputView setEnableFocusRing:enableFocusRing];
}
}
- (void)automaticSpellingCorrectionDidChange:(BOOL)enabled {
if (_eventEmitter) {
std::static_pointer_cast<TextInputEventEmitter const>(_eventEmitter)->onAutoCorrectChange({.autoCorrectEnabled = static_cast<bool>(enabled)});
}
}
- (void)continuousSpellCheckingDidChange:(BOOL)enabled
{
if (_eventEmitter) {
std::static_pointer_cast<TextInputEventEmitter const>(_eventEmitter)->onSpellCheckChange({.spellCheckEnabled = static_cast<bool>(enabled)});
}
}
- (void)grammarCheckingDidChange:(BOOL)enabled
{
if (_eventEmitter) {
std::static_pointer_cast<TextInputEventEmitter const>(_eventEmitter)->onGrammarCheckChange({.grammarCheckEnabled = static_cast<bool>(enabled)});
}
}
- (void)submitOnKeyDownIfNeeded:(nonnull NSEvent *)event
{
BOOL shouldSubmit = NO;
NSDictionary *keyEvent = [RCTViewKeyboardEvent bodyFromEvent:event];
auto const &props = *std::static_pointer_cast<TextInputProps const>(_props);
if (props.traits.submitKeyEvents.empty()) {
shouldSubmit = [keyEvent[@"key"] isEqualToString:@"Enter"]
&& ![keyEvent[@"altKey"] boolValue]
&& ![keyEvent[@"shiftKey"] boolValue]
&& ![keyEvent[@"ctrlKey"] boolValue]
&& ![keyEvent[@"metaKey"] boolValue]
&& ![keyEvent[@"functionKey"] boolValue]; // Default clearTextOnSubmit key
} else {
NSString *keyValue = keyEvent[@"key"];
const char *keyCString = [keyValue UTF8String];
if (keyCString != nullptr) {
std::string_view key(keyCString);
const bool altKey = [keyEvent[@"altKey"] boolValue];
const bool shiftKey = [keyEvent[@"shiftKey"] boolValue];
const bool ctrlKey = [keyEvent[@"ctrlKey"] boolValue];
const bool metaKey = [keyEvent[@"metaKey"] boolValue];
const bool functionKey = [keyEvent[@"functionKey"] boolValue];
shouldSubmit = std::any_of(
props.traits.submitKeyEvents.begin(),
props.traits.submitKeyEvents.end(),
[&](auto const &submitKeyEvent) {
return submitKeyEvent.key == key && submitKeyEvent.altKey == altKey &&
submitKeyEvent.shiftKey == shiftKey && submitKeyEvent.ctrlKey == ctrlKey &&
submitKeyEvent.metaKey == metaKey && submitKeyEvent.functionKey == functionKey;
});
}
}
if (shouldSubmit) {
if (_eventEmitter) {
auto const &textInputEventEmitter = *std::static_pointer_cast<TextInputEventEmitter const>(_eventEmitter);
textInputEventEmitter.onSubmitEditing([self _textInputMetrics]);
}
if (props.traits.clearTextOnSubmit) {
_backedTextInputView.attributedText = nil;
[self textInputDidChange];
}
}
}
- (void)textInputDidCancel
{
if (_eventEmitter) {
auto const &textInputEventEmitter = *std::static_pointer_cast<TextInputEventEmitter const>(_eventEmitter);
textInputEventEmitter.onKeyPress({
.text = RCTStringFromNSString(kEscapeKeyCode),
.eventCount = static_cast<int>(_mostRecentEventCount),
});
}
[self textInputDidEndEditing];
}
- (NSDragOperation)textInputDraggingEntered:(nonnull id<NSDraggingInfo>)draggingInfo {
if ([draggingInfo.draggingPasteboard availableTypeFromArray:self.registeredDraggedTypes]) {
return [self draggingEntered:draggingInfo];
}
return NSDragOperationNone;
}
- (void)textInputDraggingExited:(nonnull id<NSDraggingInfo>)draggingInfo {
if ([draggingInfo.draggingPasteboard availableTypeFromArray:self.registeredDraggedTypes]) {
[self draggingExited:draggingInfo];
}
}
- (BOOL)textInputShouldHandleDragOperation:(nonnull id<NSDraggingInfo>)draggingInfo {
if ([draggingInfo.draggingPasteboard availableTypeFromArray:self.registeredDraggedTypes]) {
[self performDragOperation:draggingInfo];
return NO;
}
return YES;
}
- (BOOL)textInputShouldHandleDeleteBackward:(nonnull id<RCTBackedTextInputViewProtocol>)sender {
return YES;
}
- (BOOL)textInputShouldHandleDeleteForward:(nonnull id<RCTBackedTextInputViewProtocol>)sender {
return YES;
}
- (BOOL)textInputShouldHandleKeyEvent:(nonnull NSEvent *)event {
return ![self handleKeyboardEvent:event];
}
- (BOOL)textInputShouldHandlePaste:(nonnull id<RCTBackedTextInputViewProtocol>)sender {
NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
NSPasteboardType fileType = [pasteboard availableTypeFromArray:@[NSFilenamesPboardType, NSPasteboardTypePNG, NSPasteboardTypeTIFF]];
NSArray<NSPasteboardType>* pastedTypes = ((RCTUITextView*) _backedTextInputView).readablePasteboardTypes;
// If there's a fileType that is of interest, notify JS. Also blocks notifying JS if it's a text paste
if (_eventEmitter && fileType != nil && [pastedTypes containsObject:fileType]) {
auto const &textInputEventEmitter = *std::static_pointer_cast<TextInputEventEmitter const>(_eventEmitter);
DataTransfer dataTransfer = [self dataTransferForPasteboard:pasteboard];
textInputEventEmitter.onPaste({.dataTransfer = std::move(dataTransfer)});
}
// Only allow pasting text.
return fileType == nil;
}
#endif // macOS]
#pragma mark - RCTBackedTextInputDelegate (UIScrollViewDelegate)
- (void)scrollViewDidScroll:(RCTUIScrollView *)scrollView // [macOS]
{
if (_eventEmitter) {
#if !TARGET_OS_OSX // [macOS]
static_cast<const TextInputEventEmitter &>(*_eventEmitter).onScroll([self _textInputMetrics]);
#else // [macOS
static_cast<const TextInputEventEmitter &>(*_eventEmitter).onScroll([self _textInputMetricsWithScrollView:scrollView]);
#endif // macOS]
}
}
#pragma mark - Native Commands
- (void)handleCommand:(const NSString *)commandName args:(const NSArray *)args
{
RCTTextInputHandleCommand(self, commandName, args);
}
- (void)focus
{
#if !TARGET_OS_OSX // [macOS]
[_backedTextInputView becomeFirstResponder];
#else // [macOS
NSWindow *window = [_backedTextInputView window];
[window makeFirstResponder:_backedTextInputView];
#endif // macOS]
const auto &props = static_cast<const TextInputProps &>(*_props);
if (props.traits.clearTextOnFocus) {
_backedTextInputView.attributedText = nil;
[self textInputDidChange];
}
if (props.traits.selectTextOnFocus) {
[_backedTextInputView selectAll:nil];
[self textInputDidChangeSelection];
}
[self scrollCursorIntoView];
}
- (void)blur
{
#if !TARGET_OS_OSX // [macOS]
[_backedTextInputView resignFirstResponder];
#else // [macOS
NSWindow *window = [_backedTextInputView window];
if ([window firstResponder] == _backedTextInputView.responder) {
[window makeFirstResponder:nil];
}
#endif // macOS]
}
- (void)setTextAndSelection:(NSInteger)eventCount
value:(NSString *__nullable)value
start:(NSInteger)start
end:(NSInteger)end
{
if (_mostRecentEventCount != eventCount) {
return;
}
_comingFromJS = YES;
if (value && ![value isEqualToString:_backedTextInputView.attributedText.string]) {
NSAttributedString *attributedString =
[[NSAttributedString alloc] initWithString:value attributes:_backedTextInputView.defaultTextAttributes];
[self _setAttributedString:attributedString];
[self _updateState];
}
#if !TARGET_OS_OSX // [macOS]
UITextPosition *startPosition = [_backedTextInputView positionFromPosition:_backedTextInputView.beginningOfDocument
offset:start];
UITextPosition *endPosition = [_backedTextInputView positionFromPosition:_backedTextInputView.beginningOfDocument
offset:end];
if (startPosition && endPosition) {
UITextRange *range = [_backedTextInputView textRangeFromPosition:startPosition toPosition:endPosition];
[_backedTextInputView setSelectedTextRange:range notifyDelegate:NO];
}
#else // [macOS
NSInteger startPosition = MIN(start, end);
NSInteger endPosition = MAX(start, end);
[_backedTextInputView setSelectedTextRange:NSMakeRange(startPosition, endPosition - startPosition) notifyDelegate:YES];
#endif // macOS]
_comingFromJS = NO;
}
#pragma mark - Default input accessory view
#if TARGET_OS_IOS // [macOS] [visionOS] Input Accessory Views are only a concept on iOS
- (NSString *)returnKeyTypeToString:(UIReturnKeyType)returnKeyType
{
switch (returnKeyType) {
case UIReturnKeyGo:
return @"Go";
case UIReturnKeyNext:
return @"Next";
case UIReturnKeySearch:
return @"Search";
case UIReturnKeySend:
return @"Send";
case UIReturnKeyYahoo:
return @"Yahoo";
case UIReturnKeyGoogle:
return @"Google";
case UIReturnKeyRoute:
return @"Route";
case UIReturnKeyJoin:
return @"Join";
case UIReturnKeyEmergencyCall:
return @"Emergency Call";
default:
return @"Done";
}
}
- (void)initializeReturnKeyType
{
returnKeyTypesSet = [NSSet setWithObjects:@(UIReturnKeyDone),
@(UIReturnKeyGo),
@(UIReturnKeyNext),
@(UIReturnKeySearch),
@(UIReturnKeySend),
@(UIReturnKeyYahoo),
@(UIReturnKeyGoogle),
@(UIReturnKeyRoute),
@(UIReturnKeyJoin),
@(UIReturnKeyRoute),
@(UIReturnKeyEmergencyCall),
nil];
}
- (void)setDefaultInputAccessoryView
{
// InputAccessoryView component sets the inputAccessoryView when inputAccessoryViewID exists
if (_backedTextInputView.inputAccessoryViewID) {
if (_backedTextInputView.isFirstResponder) {
[_backedTextInputView reloadInputViews];
}
return;
}
UIKeyboardType keyboardType = _backedTextInputView.keyboardType;
UIReturnKeyType returnKeyType = _backedTextInputView.returnKeyType;
NSString *inputAccessoryViewButtonLabel = _backedTextInputView.inputAccessoryViewButtonLabel;
BOOL containsKeyType = [returnKeyTypesSet containsObject:@(returnKeyType)];
BOOL containsInputAccessoryViewButtonLabel = inputAccessoryViewButtonLabel != nil;
// These keyboard types (all are number pads) don't have a "returnKey" button by default,
// so we create an `inputAccessoryView` with this button for them.
BOOL shouldHaveInputAccessoryView =
(keyboardType == UIKeyboardTypeNumberPad || keyboardType == UIKeyboardTypePhonePad ||
keyboardType == UIKeyboardTypeDecimalPad || keyboardType == UIKeyboardTypeASCIICapableNumberPad) &&
(containsKeyType || containsInputAccessoryViewButtonLabel);
if (_hasInputAccessoryView == shouldHaveInputAccessoryView) {
return;
}
_hasInputAccessoryView = shouldHaveInputAccessoryView;
if (shouldHaveInputAccessoryView) {
NSString *buttonLabel = inputAccessoryViewButtonLabel != nil ? inputAccessoryViewButtonLabel
: [self returnKeyTypeToString:returnKeyType];
UIToolbar *toolbarView = [UIToolbar new];
[toolbarView sizeToFit];
UIBarButtonItem *flexibleSpace =
[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:buttonLabel
style:UIBarButtonItemStylePlain
target:self
action:@selector(handleInputAccessoryDoneButton)];
toolbarView.items = @[ flexibleSpace, doneButton ];
_backedTextInputView.inputAccessoryView = toolbarView;
} else {
_backedTextInputView.inputAccessoryView = nil;
}
if (_backedTextInputView.isFirstResponder) {
[_backedTextInputView reloadInputViews];
}
}
- (void)handleInputAccessoryDoneButton
{
// Ignore the value of whether we submitted; just make sure the submit event is called if necessary.
[self textInputShouldSubmitOnReturn];
if ([self textInputShouldReturn]) {
[_backedTextInputView endEditing:YES];
}
}
#endif // [macOS] [visionOS]
#pragma mark - Other
- (TextInputEventEmitter::Metrics)_textInputMetrics
{
return {
.text = RCTStringFromNSString(_backedTextInputView.attributedText.string),
.selectionRange = [self _selectionRange],
.eventCount = static_cast<int>(_mostRecentEventCount),
#if !TARGET_OS_OSX // [macOS]
.contentOffset = RCTPointFromCGPoint(_backedTextInputView.contentOffset),
.contentInset = RCTEdgeInsetsFromUIEdgeInsets(_backedTextInputView.contentInset),
#else // [macOS
.contentOffset = {.x = 0, .y = 0},
.contentInset = EdgeInsets{},
#endif // macOS]
.contentSize = RCTSizeFromCGSize(_backedTextInputView.contentSize),
.layoutMeasurement = RCTSizeFromCGSize(_backedTextInputView.bounds.size),
.zoomScale = 1,
};
}
#if TARGET_OS_OSX // [macOS
- (TextInputEventEmitter::Metrics)_textInputMetricsWithScrollView:(RCTUIScrollView *)scrollView
{
TextInputEventEmitter::Metrics metrics = [self _textInputMetrics];
if (scrollView) {
metrics.contentOffset = RCTPointFromCGPoint(scrollView.contentOffset);
metrics.contentInset = RCTEdgeInsetsFromUIEdgeInsets(scrollView.contentInset);
metrics.contentSize = RCTSizeFromCGSize(scrollView.contentSize);
metrics.layoutMeasurement = RCTSizeFromCGSize(scrollView.bounds.size);
metrics.zoomScale = scrollView.zoomScale ?: 1;
}
return metrics;
}
#endif // macOS]
- (void)_updateState
{
if (!_state) {
return;
}
NSAttributedString *attributedString = _backedTextInputView.attributedText;
auto data = _state->getData();
_lastStringStateWasUpdatedWith = attributedString;
data.attributedStringBox = RCTAttributedStringBoxFromNSAttributedString(attributedString);
_mostRecentEventCount += _comingFromJS ? 0 : 1;
data.mostRecentEventCount = _mostRecentEventCount;
_state->updateState(std::move(data));
}
- (AttributedString::Range)_selectionRange
{
#if !TARGET_OS_OSX // [macOS]
UITextRange *selectedTextRange = _backedTextInputView.selectedTextRange;
NSInteger start = [_backedTextInputView offsetFromPosition:_backedTextInputView.beginningOfDocument
toPosition:selectedTextRange.start];
NSInteger end = [_backedTextInputView offsetFromPosition:_backedTextInputView.beginningOfDocument
toPosition:selectedTextRange.end];
return AttributedString::Range{(int)start, (int)(end - start)};
#else // [macOS
NSRange selectedTextRange = [_backedTextInputView selectedTextRange];
return AttributedString::Range{(int)selectedTextRange.location, (int)selectedTextRange.length};
#endif // macOS]
}
- (void)_restoreTextSelection
{
const auto &selection = static_cast<const TextInputProps &>(*_props).selection;
if (!selection.has_value()) {
return;
}
#if !TARGET_OS_OSX // [macOS]
auto start = [_backedTextInputView positionFromPosition:_backedTextInputView.beginningOfDocument
offset:selection->start];
auto end = [_backedTextInputView positionFromPosition:_backedTextInputView.beginningOfDocument offset:selection->end];
auto range = [_backedTextInputView textRangeFromPosition:start toPosition:end];
[_backedTextInputView setSelectedTextRange:range notifyDelegate:YES];