react-native-nitro-input 0.3.2 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/CHANGELOG.md +129 -0
  2. package/README.md +45 -0
  3. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroInputView.kt +25 -4
  4. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputView.kt +211 -3
  5. package/android/src/main/java/com/margelo/nitro/nitroinput/UnmountHandoffs.kt +57 -0
  6. package/ios/HybridNitroInputView.swift +19 -4
  7. package/ios/NitroInputCommands.mm +10 -0
  8. package/ios/NitroInputView.swift +585 -14
  9. package/lib/commonjs/nitrogen/generated/shared/json/NitroInputViewConfig.json +2 -0
  10. package/lib/commonjs/src/NitroInput.js +103 -15
  11. package/lib/module/nitrogen/generated/shared/json/NitroInputViewConfig.json +2 -0
  12. package/lib/module/src/NitroInput.js +104 -16
  13. package/lib/typescript/src/NitroInput.d.ts +16 -0
  14. package/lib/typescript/src/specs/NitroInput.nitro.d.ts +22 -0
  15. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.cpp +22 -0
  16. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.hpp +5 -0
  17. package/nitrogen/generated/android/c++/views/JHybridNitroInputViewStateUpdater.cpp +10 -0
  18. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroInputViewSpec.kt +16 -0
  19. package/nitrogen/generated/ios/c++/HybridNitroInputViewSpecSwift.hpp +18 -0
  20. package/nitrogen/generated/ios/c++/views/HybridNitroInputViewComponent.mm +12 -0
  21. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec.swift +3 -0
  22. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec_cxx.swift +33 -0
  23. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.cpp +5 -0
  24. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.hpp +5 -0
  25. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.cpp +4 -0
  26. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.hpp +6 -0
  27. package/nitrogen/generated/shared/json/NitroInputViewConfig.json +2 -0
  28. package/package.json +1 -1
  29. package/src/NitroInput.tsx +117 -11
  30. package/src/specs/NitroInput.nitro.ts +22 -0
@@ -185,6 +185,11 @@ final class NitroInputView: UIView {
185
185
  var showSoftInputOnFocus: Bool = true
186
186
  var selectTextOnFocus: Bool = false
187
187
  var clearTextOnFocus: Bool = false
188
+ /// How long a focused field that is leaving its window keeps the keyboard
189
+ /// up for the next field (see `KeyboardHandoff`); 0 is off.
190
+ var keyboardHandoffMs: Double = 0
191
+ /// The return key bar over the number pads (see `applyReturnAccessory`).
192
+ var returnKeyBar: Bool = true
188
193
  var contextMenuHidden: Bool = false
189
194
  var spellCheck: Bool = true
190
195
  /// `testID` and `accessibilityLabel`, forwarded from JS so the hidden
@@ -599,6 +604,45 @@ final class NitroInputView: UIView {
599
604
  /// A narrower settled size waiting for the current reflow to finish before it is reported.
600
605
  private var pendingSizeReport = false
601
606
  private var didAutoFocus = false
607
+ /// `focus()` arrived while the view had no window (a screen coming back on a
608
+ /// pop is re-added only as the transition starts): taken the moment the view
609
+ /// is back, unless it has gone stale.
610
+ private var pendingFocusUntil: CFTimeInterval = 0
611
+ /// The pending `focus()` came before the view was ever in a window: a field
612
+ /// focused as it mounts (a step swapped in place, keyed by its question), not
613
+ /// a screen coming back. It is taken whatever the keyboard is doing, as
614
+ /// `autoFocus` is.
615
+ private var pendingFocusOnMount = false
616
+ /// A selection set while the field was not editing, applied once it is.
617
+ private var selectionForFocus: (Int, Int)?
618
+ /// Editing began while the screen was still in a transition.
619
+ private var beganInTransition = false
620
+ /// A blur held back until the transition that caused it has finished (see
621
+ /// `textFieldDidEndEditing`).
622
+ private var withheldBlur = false
623
+ /// Focused as its screen comes in, until that transition has finished: the
624
+ /// push's own `endEditing` does not take the focus away (see
625
+ /// `keepsFocusThroughTransition`).
626
+ private var holdsFocusThroughTransition = false
627
+ /// Set while `blur()` resigns the field.
628
+ private var blurring = false
629
+ /// An IME composition (Japanese, Chinese, Korean...) is under way in text
630
+ /// mode: the text and caret before it, and where it started, for applying
631
+ /// `maxLength` and the transform once it is committed.
632
+ private var composition: (base: String, start: Int)?
633
+ /// Set while a NitroInput (or the keyboard handoff's stand-in) takes first
634
+ /// responder, which must never be refused.
635
+ fileprivate static var claimInProgress = false
636
+ private var everInWindow = false
637
+ /// When the field last stopped editing while on screen (media time; 0 = never).
638
+ private var endedEditingAt: CFTimeInterval = 0
639
+ /// Had the keyboard when its screen was covered: take it back on return.
640
+ private var restoreOnReturn = false
641
+ /// Set while this view asks for focus itself (focus(), autoFocus, a return
642
+ /// after a handoff): those go through at once, even mid-transition.
643
+ private var claimingFocus = false
644
+ /// A restore deferred to the end of the running transition is waiting.
645
+ private var focusAfterTransition = false
602
646
  /// Set while this view writes the field's text itself, so the change handler
603
647
  /// can tell a programmatic set from a user edit.
604
648
  private var isSettingText = false
@@ -620,6 +664,8 @@ final class NitroInputView: UIView {
620
664
  }()
621
665
  /// True once `textView` has been built; reading the lazy var would build it.
622
666
  private var didBuildTextView = false
667
+ /// The return key the number-pad bar shows, or nil when there is no bar.
668
+ private var returnAccessoryKey: UIReturnKeyType?
623
669
  /// The width the multiline height was last measured against.
624
670
  private var lastMeasuredWidth: CGFloat = 0
625
671
  /// Scaled and aligned container for the content (font space).
@@ -657,6 +703,8 @@ final class NitroInputView: UIView {
657
703
 
658
704
  override init(frame: CGRect) {
659
705
  super.init(frame: frame)
706
+ // Starts it tracking the keyboard before any field needs to ask.
707
+ _ = KeyboardHandoff.shared
660
708
  isOpaque = false
661
709
  backgroundColor = .clear
662
710
  clipsToBounds = false
@@ -816,9 +864,137 @@ final class NitroInputView: UIView {
816
864
  // The fonts were built against whatever traits the view had when it was
817
865
  // made; the window's are the ones that count.
818
866
  if window != nil { syncWithTraits(appearanceChanged: false) }
867
+ if window != nil, restoreOnReturn {
868
+ // Back on screen after its screen was covered while it had the keyboard.
869
+ // UIKit gives the keyboard back itself when nothing else has it - but a
870
+ // field on the covering screen with `keyboardHandoffMs` hands it to its
871
+ // stand-in as it leaves, and UIKit then sees a first responder and gives
872
+ // nothing back. So while the keyboard is still up (a field on the
873
+ // leaving screen, or its stand-in, has it), this field takes it, at the
874
+ // start of the way back as UIKit would. Down, UIKit's own restore runs.
875
+ restoreOnReturn = false
876
+ let handoff = KeyboardHandoff.shared
877
+ if traits.editable, !editor.isFirstResponder, handoff.isHolding || handoff.keyboardVisible {
878
+ // As UIKit's own restore: once the screen has settled (see
879
+ // `deferFocusWhileTransitioning`), or now when nothing is moving.
880
+ if !deferFocusWhileTransitioning() { claimFirstResponder() }
881
+ }
882
+ }
883
+ if window != nil, pendingFocusUntil > 0 {
884
+ // A screen coming back takes it only while the keyboard is still up
885
+ // (held for this field, or another field has it): a keyboard dismissed
886
+ // during the transition stays down. A field focused as it mounts takes
887
+ // it anyway.
888
+ let handoff = KeyboardHandoff.shared
889
+ let wanted = CACurrentMediaTime() < pendingFocusUntil
890
+ && (pendingFocusOnMount || handoff.isHolding || handoff.keyboardVisible)
891
+ pendingFocusUntil = 0
892
+ pendingFocusOnMount = false
893
+ if wanted, traits.editable { claimFirstResponder() }
894
+ }
895
+ if window != nil { everInWindow = true }
819
896
  maybeAutoFocus()
820
897
  }
821
898
 
899
+ override func willMove(toWindow newWindow: UIWindow?) {
900
+ if newWindow == nil { holdsFocusThroughTransition = false }
901
+ // Before UIKit resigns the field on its way out, so the keyboard never
902
+ // starts to hide.
903
+ if newWindow == nil {
904
+ // Covered while it had the keyboard: UIKit resigns a field as the
905
+ // transition starts, a moment before its view leaves the window.
906
+ restoreOnReturn = editor.isFirstResponder || CACurrentMediaTime() - endedEditingAt < 1
907
+ handOffKeyboardIfFocused()
908
+ }
909
+ super.willMove(toWindow: newWindow)
910
+ }
911
+
912
+ /// A focused field leaving the screen hands the keyboard to a stand-in field
913
+ /// instead of dropping it, so the next field to focus takes it over in place.
914
+ func handOffKeyboardIfFocused() {
915
+ guard traits.keyboardHandoffMs > 0, traits.showSoftInputOnFocus,
916
+ let window, editor.isFirstResponder else { return }
917
+ KeyboardHandoff.shared.hold(like: editor, in: window, for: traits.keyboardHandoffMs)
918
+ }
919
+
920
+ /// `becomeFirstResponder`, retried next turn if UIKit declines because the
921
+ /// view is in a window but not ready to accept it yet.
922
+ private func claimFirstResponder() {
923
+ if claimOnce() { return }
924
+ DispatchQueue.main.async { [weak self] in
925
+ guard let self, self.window != nil else { return }
926
+ self.claimOnce()
927
+ }
928
+ }
929
+
930
+ @discardableResult
931
+ private func claimOnce() -> Bool {
932
+ claimingFocus = true
933
+ Self.claimInProgress = true
934
+ defer {
935
+ claimingFocus = false
936
+ Self.claimInProgress = false
937
+ }
938
+ return editor.becomeFirstResponder()
939
+ }
940
+
941
+ /// Whether a resign now should be declined: the field took focus as its
942
+ /// screen came in, and the push has no slide (`animation: 'none'`, 'fade',
943
+ /// 'simple_push'), so UINavigationController ends editing in the incoming
944
+ /// view mid-transition and hands first responder back as it completes. The
945
+ /// keyboard would start to close and come back (react-navigation#11626),
946
+ /// and the field would blur and refocus (#11643). `blur()`, another field
947
+ /// taking the focus and the view leaving the window still resign it.
948
+ fileprivate func keepsFocusThroughTransition() -> Bool {
949
+ holdsFocusThroughTransition && !blurring && !Self.claimInProgress && window != nil
950
+ && hostViewController?.transitionCoordinator != nil
951
+ }
952
+
953
+ /// Sends the current selection to a delegate someone put in front of ours
954
+ /// (see `textFieldDidBeginEditing`). Ours reports selections itself.
955
+ private func announceSelectionToDelegate() {
956
+ guard editor.isFirstResponder else { return }
957
+ if let field = editor as? UITextField, let delegate = field.delegate, delegate !== self {
958
+ delegate.textFieldDidChangeSelection?(field)
959
+ } else if let view = editor as? UITextView, let delegate = view.delegate, delegate !== self {
960
+ delegate.textViewDidChangeSelection?(view)
961
+ }
962
+ }
963
+
964
+ /// The view controller this field's screen belongs to.
965
+ private var hostViewController: UIViewController? {
966
+ var responder: UIResponder? = self
967
+ while let next = responder?.next {
968
+ if let controller = next as? UIViewController { return controller }
969
+ responder = next
970
+ }
971
+ return nil
972
+ }
973
+
974
+ /// UIKit gives a field its focus back when you return to its screen (back,
975
+ /// swipe-back, a sheet closing), and does it as the transition starts. On
976
+ /// iOS 26 the keyboard then travels in with the sliding screen as a flat
977
+ /// dark snapshot of itself, and only turns into the real keyboard once the
978
+ /// screen has settled. The platform apps give focus back after the
979
+ /// transition, so the real keyboard rises from the bottom (Contacts'
980
+ /// search): this does the same. Returns true when the focus was deferred.
981
+ /// Focus this view asks for itself (`claimingFocus`) is never deferred:
982
+ /// that is `focus()` and `autoFocus`, which keep the keyboard up across a
983
+ /// push to a screen that focuses its own field.
984
+ fileprivate func deferFocusWhileTransitioning() -> Bool {
985
+ guard !claimingFocus, let coordinator = hostViewController?.transitionCoordinator else { return false }
986
+ if focusAfterTransition { return true }
987
+ focusAfterTransition = true
988
+ coordinator.animate(alongsideTransition: nil) { [weak self] context in
989
+ // Cancelled meanwhile by blur() / Keyboard.dismiss() or a recycle.
990
+ guard let self, self.focusAfterTransition else { return }
991
+ self.focusAfterTransition = false
992
+ guard !context.isCancelled, self.window != nil, self.traits.editable else { return }
993
+ self.claimFirstResponder()
994
+ }
995
+ return true
996
+ }
997
+
822
998
  override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
823
999
  super.traitCollectionDidChange(previousTraitCollection)
824
1000
  let appearanceChanged = previousTraitCollection.map { traitCollection.hasDifferentColorAppearance(comparedTo: $0) } ?? true
@@ -863,11 +1039,7 @@ final class NitroInputView: UIView {
863
1039
  private func maybeAutoFocus() {
864
1040
  guard window != nil, traits.autoFocus, traits.editable, !didAutoFocus else { return }
865
1041
  didAutoFocus = true
866
- if editor.becomeFirstResponder() { return }
867
- DispatchQueue.main.async { [weak self] in
868
- guard let self, self.window != nil else { return }
869
- self.editor.becomeFirstResponder()
870
- }
1042
+ claimFirstResponder()
871
1043
  }
872
1044
 
873
1045
  @objc private func contentSizeCategoryDidChange() {
@@ -885,6 +1057,17 @@ final class NitroInputView: UIView {
885
1057
  func resetForRecycle() {
886
1058
  worklets = Worklets()
887
1059
  if editor.isFirstResponder { editor.resignFirstResponder() }
1060
+ pendingFocusUntil = 0
1061
+ pendingFocusOnMount = false
1062
+ everInWindow = false
1063
+ selectionForFocus = nil
1064
+ beganInTransition = false
1065
+ withheldBlur = false
1066
+ holdsFocusThroughTransition = false
1067
+ composition = nil
1068
+ restoreOnReturn = false
1069
+ endedEditingAt = 0
1070
+ focusAfterTransition = false
888
1071
  stopDisplayLink()
889
1072
  stopBlink()
890
1073
  engine.reset()
@@ -914,13 +1097,35 @@ final class NitroInputView: UIView {
914
1097
 
915
1098
  // MARK: - Public API
916
1099
 
917
- func focus() {
1100
+ @objc(nitroFocus) func focus() {
918
1101
  guard traits.editable else { return }
919
- editor.becomeFirstResponder()
1102
+ // Not in a window: nothing can take first responder there. A screen being
1103
+ // popped back to is re-added only as its transition starts, so hold the
1104
+ // request for that moment - claiming it the same turn the view arrives is
1105
+ // what swaps the keyboard in place rather than hiding and showing it.
1106
+ guard window != nil else {
1107
+ pendingFocusUntil = CACurrentMediaTime() + 1
1108
+ pendingFocusOnMount = !everInWindow
1109
+ return
1110
+ }
1111
+ pendingFocusUntil = 0
1112
+ claimFirstResponder()
920
1113
  }
921
1114
 
922
- func blur() {
923
- editor.resignFirstResponder()
1115
+ @objc(nitroBlur) func blur() {
1116
+ pendingFocusUntil = 0
1117
+ restoreOnReturn = false
1118
+ endedEditingAt = 0
1119
+ focusAfterTransition = false
1120
+ if editor.isFirstResponder {
1121
+ blurring = true
1122
+ editor.resignFirstResponder()
1123
+ blurring = false
1124
+ } else {
1125
+ // `Keyboard.dismiss()` while a field that just left the screen holds the
1126
+ // keyboard for the next one: nothing is focused, so let it go now.
1127
+ KeyboardHandoff.shared.letGo()
1128
+ }
924
1129
  }
925
1130
 
926
1131
  /// Moves the caret/selection to `start`..`end`, in code points.
@@ -928,6 +1133,9 @@ final class NitroInputView: UIView {
928
1133
  let count = text.unicodeScalars.count
929
1134
  let lower = min(max(0, start), count)
930
1135
  let upper = min(max(lower, end), count)
1136
+ // UIKit puts the caret at the end when a field starts editing, so a
1137
+ // selection given while it is not is kept for then (react-native#46943).
1138
+ selectionForFocus = editor.isFirstResponder ? nil : (lower, upper)
931
1139
  guard let from = field.position(from: field.beginningOfDocument, offset: utf16Offset(ofCodePoint: lower)),
932
1140
  let to = field.position(from: field.beginningOfDocument, offset: utf16Offset(ofCodePoint: upper)),
933
1141
  let range = field.textRange(from: from, to: to) else { return }
@@ -947,6 +1155,11 @@ final class NitroInputView: UIView {
947
1155
  /// text mode), caret at the end. Returns false when nothing changed.
948
1156
  @discardableResult
949
1157
  func setText(_ newText: String, reason: ChangeReason) -> Bool {
1158
+ // A controlled parent echoing a composition back mid-way (a Japanese,
1159
+ // Chinese or Korean IME): it is what the field shows, but cut to
1160
+ // `maxLength` or run through the transform it would replace the marked
1161
+ // text and end the composition. It is conformed once committed.
1162
+ if reason == .prop, newText == text, (editor as? UITextInput)?.markedTextRange != nil { return false }
950
1163
  var normalized = normalized(newText)
951
1164
  if worklets.transform != 0 {
952
1165
  let count = normalized.unicodeScalars.count
@@ -1163,7 +1376,13 @@ final class NitroInputView: UIView {
1163
1376
  textView.isUserInteractionEnabled = on && traits.editable
1164
1377
  field.isHidden = on
1165
1378
  field.isUserInteractionEnabled = !on && traits.editable
1166
- guard on else { return }
1379
+ // The hidden twin must not count as an input: keyboard-controller's
1380
+ // next/previous and its toolbar walk every enabled field and editable view.
1381
+ field.isEnabled = !on && traits.editable
1382
+ guard on else {
1383
+ textView.isEditable = false
1384
+ return
1385
+ }
1167
1386
 
1168
1387
  textView.frame = bounds
1169
1388
  textView.keyboardType = traits.keyboardType
@@ -1296,7 +1515,8 @@ final class NitroInputView: UIView {
1296
1515
  applyMultiline()
1297
1516
  field.keyboardType = traits.keyboardType
1298
1517
  field.returnKeyType = traits.returnKeyType
1299
- field.isEnabled = traits.editable
1518
+ applyReturnAccessory()
1519
+ field.isEnabled = traits.editable && !traits.multiline
1300
1520
  field.isUserInteractionEnabled = traits.editable
1301
1521
  // `tintColor` is both the caret and the selection on a UITextField. The
1302
1522
  // overlay draws its own caret, so only `plain` has a caret colour to honour
@@ -1373,6 +1593,53 @@ final class NitroInputView: UIView {
1373
1593
  }
1374
1594
  }
1375
1595
 
1596
+ /// The number pads (number, phone, decimal) have no return key, so a form
1597
+ /// chained with `returnKeyType="next"` would stop at its first numeric field.
1598
+ /// As React Native's `TextInput` does, a field on one of them with a return
1599
+ /// key type set gets a bar above the keyboard with that key: "Next", "Go",
1600
+ /// "Done"... It is the return key, submit behaviour and all.
1601
+ private func applyReturnAccessory() {
1602
+ let pads: [UIKeyboardType] = [.numberPad, .phonePad, .decimalPad, .asciiCapableNumberPad]
1603
+ let returnKey = traits.returnKeyType
1604
+ let wanted = traits.returnKeyBar && pads.contains(traits.keyboardType) && returnKey != .default
1605
+ if !wanted {
1606
+ guard returnAccessoryKey != nil else { return }
1607
+ returnAccessoryKey = nil
1608
+ field.inputAccessoryView = nil
1609
+ } else {
1610
+ guard returnAccessoryKey != returnKey else { return }
1611
+ returnAccessoryKey = returnKey
1612
+ let bar = UIToolbar()
1613
+ bar.sizeToFit()
1614
+ let button = returnKey == .done
1615
+ ? UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(returnAccessoryTapped))
1616
+ : UIBarButtonItem(title: Self.returnKeyTitle(returnKey), style: .plain, target: self, action: #selector(returnAccessoryTapped))
1617
+ bar.items = [UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), button]
1618
+ field.inputAccessoryView = bar
1619
+ }
1620
+ if didBuildTextView { textView.inputAccessoryView = field.inputAccessoryView }
1621
+ if editor.isFirstResponder { editor.reloadInputViews() }
1622
+ }
1623
+
1624
+ @objc private func returnAccessoryTapped() {
1625
+ handleReturnKey()
1626
+ }
1627
+
1628
+ /// The return key's own label, as React Native names it for the same bar.
1629
+ private static func returnKeyTitle(_ key: UIReturnKeyType) -> String {
1630
+ switch key {
1631
+ case .go: return "Go"
1632
+ case .next: return "Next"
1633
+ case .search: return "Search"
1634
+ case .send: return "Send"
1635
+ case .route: return "Route"
1636
+ case .join: return "Join"
1637
+ case .emergencyCall: return "Emergency Call"
1638
+ case .continue: return "Continue"
1639
+ default: return "Done"
1640
+ }
1641
+ }
1642
+
1376
1643
  private func applyKeyboardTraitsForMode() {
1377
1644
  // A mask decides every character, so the keyboard must not second-guess it:
1378
1645
  // autocorrect would fight `shouldChangeCharactersIn` over the replacement.
@@ -1503,11 +1770,47 @@ final class NitroInputView: UIView {
1503
1770
 
1504
1771
  @objc private func fieldEditingChanged() {
1505
1772
  guard !isSettingText else { return }
1773
+ if let composition, field.markedTextRange == nil {
1774
+ self.composition = nil
1775
+ conformCommittedComposition(base: composition.base, start: composition.start)
1776
+ }
1506
1777
  // Text mode: the field edited itself; number mode edits never reach here
1507
1778
  // (the delegate applies them and returns false).
1508
1779
  textDidChange(caret: caretCodePointIndex(), reason: .user)
1509
1780
  }
1510
1781
 
1782
+ /// A text-mode composition was committed: cut it to `maxLength` and run the
1783
+ /// transform over it now, as a typed edit would have been, keeping the caret
1784
+ /// after what was committed.
1785
+ private func conformCommittedComposition(base: String, start: Int) {
1786
+ guard format.mode == .text else { return }
1787
+ let committed = text
1788
+ var caret = caretCodePointIndex()
1789
+ var newText = Self.truncated(committed, to: format.maxLength)
1790
+ caret = min(caret, newText.unicodeScalars.count)
1791
+ var selectionEnd = caret
1792
+ if worklets.transform != 0 {
1793
+ let result = margelo.nitro.nitroinput.nitroinputworklets.runTransform(
1794
+ Int32(worklets.transform), std.string(newText), std.string(base), Int32(caret), Int32(caret), Int32(start), Int32(start))
1795
+ if result.applied {
1796
+ newText = String(result.text)
1797
+ let count = newText.unicodeScalars.count
1798
+ caret = Int(result.selectionStart) < 0 ? count : min(Int(result.selectionStart), count)
1799
+ selectionEnd = min(max(caret, Int(result.selectionEnd)), count)
1800
+ }
1801
+ }
1802
+ guard newText != committed else { return }
1803
+ isSettingText = true
1804
+ replaceMinimally(in: field, with: newText)
1805
+ let from = Self.utf16Offset(in: newText, codePoint: caret)
1806
+ let to = Self.utf16Offset(in: newText, codePoint: selectionEnd)
1807
+ if let fromPosition = field.position(from: field.beginningOfDocument, offset: from),
1808
+ let toPosition = field.position(from: field.beginningOfDocument, offset: to) {
1809
+ field.selectedTextRange = field.textRange(from: fromPosition, to: toPosition)
1810
+ }
1811
+ isSettingText = false
1812
+ }
1813
+
1511
1814
  /// The selection start in code points (the engine's caret index).
1512
1815
  private func caretCodePointIndex() -> Int {
1513
1816
  guard let range = field.selectedTextRange else { return text.unicodeScalars.count }
@@ -2008,6 +2311,17 @@ final class NitroInputView: UIView {
2008
2311
  */
2009
2312
  fileprivate final class HiddenTextView: UITextView {
2010
2313
  weak var owner: NitroInputView?
2314
+
2315
+ override func becomeFirstResponder() -> Bool {
2316
+ if owner?.deferFocusWhileTransitioning() == true { return false }
2317
+ if let other = delegate as? NitroInputView, other !== owner { delegate = owner }
2318
+ return super.becomeFirstResponder()
2319
+ }
2320
+
2321
+ override func resignFirstResponder() -> Bool {
2322
+ if owner?.keepsFocusThroughTransition() == true { return false }
2323
+ return super.resignFirstResponder()
2324
+ }
2011
2325
  var placeholder: String = "" { didSet { setNeedsDisplay() } }
2012
2326
  var placeholderColor: UIColor = .placeholderText { didSet { setNeedsDisplay() } }
2013
2327
 
@@ -2026,7 +2340,10 @@ final class NitroInputView: UIView {
2026
2340
  override func caretRect(for position: UITextPosition) -> CGRect {
2027
2341
  let rect = super.caretRect(for: position)
2028
2342
  guard hidesNativeCaret else { return rect }
2029
- return CGRect(origin: rect.origin, size: .zero)
2343
+ // Zero width hides it; the full height is what keyboard-controller
2344
+ // scrolls to (the caret's bottom edge), so the whole line clears the
2345
+ // keyboard rather than only its top.
2346
+ return CGRect(x: rect.minX, y: rect.minY, width: 0, height: rect.height)
2030
2347
  }
2031
2348
 
2032
2349
  var hidesNativeCaret = false {
@@ -2068,6 +2385,25 @@ final class NitroInputView: UIView {
2068
2385
 
2069
2386
  fileprivate final class HiddenTextField: UITextField {
2070
2387
  weak var owner: NitroInputView?
2388
+
2389
+ /// keyboard-controller swaps a proxy delegate into the focused field and
2390
+ /// writes the "original" back when focus moves on. When one field takes the
2391
+ /// keyboard from another and loses it again within the same transition (an
2392
+ /// `autoFocus` field on a pushed screen, which the push's own `endEditing`
2393
+ /// then resigns), it can write the other field's delegate back into this
2394
+ /// one. Every edit then goes to the other field - a number field rejects the
2395
+ /// letters - and this field, focused, takes no typing. A field is only ever
2396
+ /// its own owner's, so put that back before editing starts.
2397
+ override func becomeFirstResponder() -> Bool {
2398
+ if owner?.deferFocusWhileTransitioning() == true { return false }
2399
+ if let other = delegate as? NitroInputView, other !== owner { delegate = owner }
2400
+ return super.becomeFirstResponder()
2401
+ }
2402
+
2403
+ override func resignFirstResponder() -> Bool {
2404
+ if owner?.keepsFocusThroughTransition() == true { return false }
2405
+ return super.resignFirstResponder()
2406
+ }
2071
2407
  var leftInset: CGFloat = 0
2072
2408
  var rightInset: CGFloat = 0
2073
2409
  /// Room for a floated label sitting on the top edge.
@@ -2112,7 +2448,10 @@ final class NitroInputView: UIView {
2112
2448
  override func caretRect(for position: UITextPosition) -> CGRect {
2113
2449
  let rect = super.caretRect(for: position)
2114
2450
  guard hidesNativeCaret else { return rect }
2115
- return CGRect(origin: rect.origin, size: .zero)
2451
+ // Zero width hides it; the full height is what keyboard-controller
2452
+ // scrolls to (the caret's bottom edge), so the whole line clears the
2453
+ // keyboard rather than only its top.
2454
+ return CGRect(x: rect.minX, y: rect.minY, width: 0, height: rect.height)
2116
2455
  }
2117
2456
 
2118
2457
  override func textRect(forBounds bounds: CGRect) -> CGRect {
@@ -2189,18 +2528,45 @@ final class NitroInputView: UIView {
2189
2528
  }
2190
2529
  }
2191
2530
 
2531
+ // MARK: - Misrouted delegate callbacks
2532
+
2533
+ extension NitroInputView {
2534
+ /// The view a delegate callback really belongs to, when it is not this one.
2535
+ ///
2536
+ /// react-native-keyboard-controller wraps the focused field's delegate in one
2537
+ /// composite it shares between every input, and that composite forwards to
2538
+ /// whichever delegate it stored last. When focus moves on faster than it
2539
+ /// re-wraps (an `autoFocus` field on a pushed screen), a field's callbacks
2540
+ /// can arrive here, at another field's view
2541
+ /// (kirillzyusko/react-native-keyboard-controller#1588). Answering them as
2542
+ /// ours would filter the typing through this field's rules and apply it to
2543
+ /// this field's text: the focused field would take no typing at all. So
2544
+ /// they go to the field's own view instead.
2545
+ fileprivate func rightfulOwner(of input: UIView) -> NitroInputView? {
2546
+ if input === field || input === editor { return nil }
2547
+ let owner = (input as? HiddenTextField)?.owner ?? (input as? HiddenTextView)?.owner
2548
+ return owner === self ? nil : owner
2549
+ }
2550
+ }
2551
+
2192
2552
  // MARK: - UITextViewDelegate
2193
2553
 
2194
2554
  extension NitroInputView: UITextViewDelegate {
2195
2555
  func textViewDidBeginEditing(_ textView: UITextView) {
2556
+ if let owner = rightfulOwner(of: textView) { return owner.textViewDidBeginEditing(textView) }
2196
2557
  textFieldDidBeginEditing(field)
2197
2558
  }
2198
2559
 
2199
2560
  func textViewDidEndEditing(_ textView: UITextView) {
2561
+ if let owner = rightfulOwner(of: textView) { return owner.textViewDidEndEditing(textView) }
2200
2562
  textFieldDidEndEditing(field)
2201
2563
  }
2202
2564
 
2203
2565
  func textViewDidChange(_ textView: UITextView) {
2566
+ if let owner = rightfulOwner(of: textView) { return owner.textViewDidChange(textView) }
2567
+ // Typing does not go through `text`'s setter, so the drawn placeholder
2568
+ // would stay under the first characters typed.
2569
+ textView.setNeedsDisplay()
2204
2570
  // The text view owns the text here. `setText` runs it through the
2205
2571
  // formatter, which is single-line by definition, so the multiline path
2206
2572
  // reports what the view already holds instead.
@@ -2213,11 +2579,15 @@ extension NitroInputView: UITextViewDelegate {
2213
2579
  }
2214
2580
 
2215
2581
  func textViewDidChangeSelection(_ textView: UITextView) {
2582
+ if let owner = rightfulOwner(of: textView) { return owner.textViewDidChangeSelection(textView) }
2216
2583
  guard !isSettingText else { return }
2217
2584
  reportSelection()
2218
2585
  }
2219
2586
 
2220
2587
  func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
2588
+ if let owner = rightfulOwner(of: textView) {
2589
+ return owner.textView(textView, shouldChangeTextIn: range, replacementText: text)
2590
+ }
2221
2591
  // The return key arrives as a lone line break. Only that one is the key:
2222
2592
  // a pasted line break is text, and goes in whatever the submit behaviour.
2223
2593
  guard text == "\n", (textView as? HiddenTextView)?.isPasting != true else { return true }
@@ -2231,6 +2601,9 @@ extension NitroInputView: UITextViewDelegate {
2231
2601
  extension NitroInputView: UITextFieldDelegate {
2232
2602
 
2233
2603
  func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
2604
+ if let owner = rightfulOwner(of: textField) {
2605
+ return owner.textField(textField, shouldChangeCharactersIn: range, replacementString: string)
2606
+ }
2234
2607
  // Like React Native's `onKeyPress`: fires before the text changes, with
2235
2608
  // 'Backspace' for a deletion and the inserted string otherwise.
2236
2609
  if worklets.onKeyPress != 0 {
@@ -2262,6 +2635,19 @@ extension NitroInputView: UITextFieldDelegate {
2262
2635
  // Without a transform or a length limit the field edits itself (keeps
2263
2636
  // marked text / autocorrect intact); `fieldEditingChanged` reports it.
2264
2637
  guard worklets.transform != 0 || format.maxLength > 0, let swiftRange = Range(range, in: current) else { return true }
2638
+ // Mid-composition the marked text is the IME's: replacing it, or holding
2639
+ // its unconverted letters against `maxLength`, loses the composition
2640
+ // (react-native#56463, #52552). Both apply once it is committed.
2641
+ if let marked = textField.markedTextRange {
2642
+ if composition == nil {
2643
+ let from = textField.offset(from: textField.beginningOfDocument, to: marked.start)
2644
+ let to = textField.offset(from: textField.beginningOfDocument, to: marked.end)
2645
+ var base = current
2646
+ if let markedRange = Range(NSRange(location: from, length: to - from), in: base) { base.removeSubrange(markedRange) }
2647
+ composition = (base, Self.codePointOffset(in: current, utf16: from))
2648
+ }
2649
+ return true
2650
+ }
2265
2651
  var replacement = string
2266
2652
  if format.maxLength > 0 {
2267
2653
  // Keep as much of the replacement as fits (a paste), or nothing.
@@ -2334,8 +2720,42 @@ extension NitroInputView: UITextFieldDelegate {
2334
2720
  }
2335
2721
 
2336
2722
  func textFieldDidBeginEditing(_ textField: UITextField) {
2723
+ if let owner = rightfulOwner(of: textField) { return owner.textFieldDidBeginEditing(textField) }
2724
+ let resumed = withheldBlur
2725
+ withheldBlur = false
2726
+ beganInTransition = hostViewController?.transitionCoordinator != nil
2727
+ if !resumed, let coordinator = hostViewController?.transitionCoordinator {
2728
+ holdsFocusThroughTransition = true
2729
+ coordinator.animate(alongsideTransition: nil) { [weak self] _ in self?.holdsFocusThroughTransition = false }
2730
+ }
2731
+ if resumed {
2732
+ // UIKit giving the focus back that its own transition took away a moment
2733
+ // ago: to JS the field never lost it, so nothing is sent.
2734
+ DispatchQueue.main.async { [weak self] in self?.announceSelectionToDelegate() }
2735
+ if contentOverflows { render() }
2736
+ updateCaret(restartBlink: true)
2737
+ if wantsFrameDrawing { layoutFrame(animated: false) }
2738
+ return
2739
+ }
2740
+ // keyboard-controller puts its own delegate in front of ours a turn after
2741
+ // editing begins, and its KeyboardAwareScrollView waits for a selection
2742
+ // event from the newly focused field before it scrolls. A tap or Next
2743
+ // moves the caret and sends one; a field given its focus back with the
2744
+ // caret where it was sends none, and the form never scrolls it into view.
2745
+ // So once that delegate is in place, tell it where the selection is.
2746
+ DispatchQueue.main.async {
2747
+ DispatchQueue.main.async { [weak self] in self?.announceSelectionToDelegate() }
2748
+ }
2337
2749
  if traits.clearTextOnFocus {
2750
+ selectionForFocus = nil
2338
2751
  setText("", reason: .user)
2752
+ } else if let (start, end) = selectionForFocus, !traits.selectTextOnFocus {
2753
+ // In the next runloop turn, after UIKit has put its own caret down.
2754
+ selectionForFocus = nil
2755
+ DispatchQueue.main.async { [weak self] in
2756
+ guard let self, self.editor.isFirstResponder else { return }
2757
+ self.setSelection(start: start, end: end)
2758
+ }
2339
2759
  } else if traits.selectTextOnFocus {
2340
2760
  // In the next runloop turn: UIKit sets its own selection as it begins.
2341
2761
  DispatchQueue.main.async { [weak self] in
@@ -2353,8 +2773,49 @@ extension NitroInputView: UITextFieldDelegate {
2353
2773
  }
2354
2774
 
2355
2775
  func textFieldDidEndEditing(_ textField: UITextField) {
2776
+ if let owner = rightfulOwner(of: textField) { return owner.textFieldDidEndEditing(textField) }
2777
+ if window != nil { endedEditingAt = CACurrentMediaTime() }
2356
2778
  if contentOverflows { render() }
2357
2779
  updateCaret()
2780
+ // A field that took focus as its screen came in (`autoFocus`) is resigned
2781
+ // by the push itself when it has no slide (`animation: 'none'`, 'fade',
2782
+ // 'simple_push': UINavigationController ends editing in the incoming view)
2783
+ // and handed first responder back as the push completes. Sent as it
2784
+ // happens, that is an onBlur and a second onFocus for a field the user
2785
+ // never left (react-navigation#11643). So the blur waits for the
2786
+ // transition: gone for good by then, it is sent; given back, it never was.
2787
+ if beganInTransition, let window, let coordinator = hostViewController?.transitionCoordinator {
2788
+ withheldBlur = true
2789
+ // Keep the keyboard up across the gap, or it starts to close and comes
2790
+ // back when the push hands the focus back (react-navigation#11626).
2791
+ if traits.showSoftInputOnFocus, KeyboardHandoff.shared.keyboardVisible {
2792
+ KeyboardHandoff.shared.hold(like: editor, in: window, for: 1000)
2793
+ }
2794
+ coordinator.animate(alongsideTransition: nil) { [weak self] _ in
2795
+ DispatchQueue.main.async { self?.releaseWithheldBlur() }
2796
+ }
2797
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in self?.releaseWithheldBlur() }
2798
+ if wantsFrameDrawing { layoutFrame(animated: true) }
2799
+ return
2800
+ }
2801
+ beganInTransition = false
2802
+ emitBlur()
2803
+ if wantsFrameDrawing { layoutFrame(animated: true) }
2804
+ }
2805
+
2806
+ /// Sends a blur held back during a transition, unless the field has the
2807
+ /// focus again.
2808
+ private func releaseWithheldBlur() {
2809
+ guard withheldBlur else { return }
2810
+ withheldBlur = false
2811
+ beganInTransition = false
2812
+ guard !editor.isFirstResponder else { return }
2813
+ // Nothing took the focus back: let a keyboard held for it go.
2814
+ if KeyboardHandoff.shared.isHolding { KeyboardHandoff.shared.letGo() }
2815
+ emitBlur()
2816
+ }
2817
+
2818
+ private func emitBlur() {
2358
2819
  if worklets.onFocusChange != 0 {
2359
2820
  margelo.nitro.nitroinput.nitroinputworklets.runFocusChange(Int32(worklets.onFocusChange), false, std.string(text))
2360
2821
  }
@@ -2363,10 +2824,10 @@ extension NitroInputView: UITextFieldDelegate {
2363
2824
  }
2364
2825
  onFocusChange?(false)
2365
2826
  onEndEditing?(text)
2366
- if wantsFrameDrawing { layoutFrame(animated: true) }
2367
2827
  }
2368
2828
 
2369
2829
  func textFieldDidChangeSelection(_ textField: UITextField) {
2830
+ if let owner = rightfulOwner(of: textField) { return owner.textFieldDidChangeSelection(textField) }
2370
2831
  guard !isSettingText else { return }
2371
2832
  // A caret move alone does not re-render; when the content is wider than
2372
2833
  // the view the scroll offset has to follow it.
@@ -2376,6 +2837,7 @@ extension NitroInputView: UITextFieldDelegate {
2376
2837
  }
2377
2838
 
2378
2839
  func textFieldShouldReturn(_ textField: UITextField) -> Bool {
2840
+ if let owner = rightfulOwner(of: textField) { return owner.textFieldShouldReturn(textField) }
2379
2841
  handleReturnKey()
2380
2842
  return false
2381
2843
  }
@@ -2800,3 +3262,112 @@ extension NitroInputView {
2800
3262
  }
2801
3263
  }
2802
3264
 
3265
+
3266
+
3267
+ /// Keeps the keyboard up while a focused field is taken off screen (its screen
3268
+ /// popped or unmounted), for the next field to take over.
3269
+ ///
3270
+ /// UIKit hides the keyboard as soon as nothing is first responder and shows it
3271
+ /// again when a field claims it, even a moment later: a pop from one field's
3272
+ /// screen back to another's drops the keyboard and raises it again. A hidden
3273
+ /// stand-in field configured like the leaving one takes first responder in the
3274
+ /// same turn, so the keyboard stays; the next field to focus takes it from the
3275
+ /// stand-in in place. If none does within the hold, the stand-in lets it go.
3276
+ ///
3277
+ /// The stand-in must stay invisible to anything tracking the focused input:
3278
+ /// keyboard-controller reads the first responder's superview `tag` as the
3279
+ /// focused input and swaps its own delegate into that field. So each hold
3280
+ /// builds a fresh field with no delegate inside a 1x1 container tagged `-1`,
3281
+ /// which keyboard-controller reads as "no focused input", and throws both away
3282
+ /// as soon as the stand-in stops being first responder.
3283
+ final class KeyboardHandoff {
3284
+ static let shared = KeyboardHandoff()
3285
+
3286
+ private var container: UIView?
3287
+ private var holder: UITextField?
3288
+ private var release: DispatchWorkItem?
3289
+ private var endObserver: NSObjectProtocol?
3290
+ /// Whether the system keyboard is up or on its way up.
3291
+ private(set) var keyboardVisible = false
3292
+
3293
+ var isHolding: Bool { holder?.isFirstResponder == true }
3294
+
3295
+ private init() {
3296
+ let center = NotificationCenter.default
3297
+ center.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main) { [weak self] _ in
3298
+ self?.keyboardVisible = true
3299
+ }
3300
+ center.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: .main) { [weak self] _ in
3301
+ self?.keyboardVisible = false
3302
+ }
3303
+ }
3304
+
3305
+ /// Takes the keyboard from `editor` (the leaving field's system field) for up
3306
+ /// to `milliseconds`.
3307
+ func hold(like editor: UIView, in window: UIWindow, for milliseconds: Double) {
3308
+ letGo()
3309
+ let box = UIView(frame: CGRect(x: -1000, y: -1000, width: 1, height: 1))
3310
+ box.tag = -1
3311
+ box.isUserInteractionEnabled = false
3312
+ box.accessibilityElementsHidden = true
3313
+ let field = UITextField(frame: box.bounds)
3314
+ field.alpha = 0.01
3315
+ field.isAccessibilityElement = false
3316
+ // The leaving field's own keyboard, as configured for its mode (a number
3317
+ // or mask field turns autocorrect and suggestions off): any difference
3318
+ // would re-lay the keyboard, and a suggestion bar that comes or goes
3319
+ // changes its height mid-hold.
3320
+ if let source = editor as? UITextInputTraits {
3321
+ field.keyboardType = source.keyboardType ?? .default
3322
+ field.keyboardAppearance = source.keyboardAppearance ?? .default
3323
+ field.returnKeyType = source.returnKeyType ?? .default
3324
+ field.autocapitalizationType = source.autocapitalizationType ?? .sentences
3325
+ field.autocorrectionType = source.autocorrectionType ?? .default
3326
+ field.spellCheckingType = source.spellCheckingType ?? .default
3327
+ field.smartQuotesType = source.smartQuotesType ?? .default
3328
+ field.smartDashesType = source.smartDashesType ?? .default
3329
+ field.smartInsertDeleteType = source.smartInsertDeleteType ?? .default
3330
+ field.textContentType = source.textContentType ?? nil
3331
+ field.isSecureTextEntry = source.isSecureTextEntry ?? false
3332
+ if #available(iOS 17.0, *) { field.inlinePredictionType = source.inlinePredictionType ?? .default }
3333
+ }
3334
+ field.inputAccessoryView = editor.inputAccessoryView
3335
+ box.addSubview(field)
3336
+ window.addSubview(box)
3337
+ NitroInputView.claimInProgress = true
3338
+ let held = field.becomeFirstResponder()
3339
+ NitroInputView.claimInProgress = false
3340
+ guard held else {
3341
+ box.removeFromSuperview()
3342
+ return
3343
+ }
3344
+ container = box
3345
+ holder = field
3346
+ // Another field took the keyboard: the hold is over.
3347
+ endObserver = NotificationCenter.default.addObserver(
3348
+ forName: UITextField.textDidEndEditingNotification, object: field, queue: .main
3349
+ ) { [weak self, weak field] _ in
3350
+ guard let self, let field, self.holder === field else { return }
3351
+ self.drop()
3352
+ }
3353
+ let item = DispatchWorkItem { [weak self] in self?.letGo() }
3354
+ release = item
3355
+ DispatchQueue.main.asyncAfter(deadline: .now() + milliseconds / 1000, execute: item)
3356
+ }
3357
+
3358
+ /// Nothing claimed the keyboard in time, or `Keyboard.dismiss()`: let it hide.
3359
+ func letGo() {
3360
+ if let holder, holder.isFirstResponder { holder.resignFirstResponder() }
3361
+ drop()
3362
+ }
3363
+
3364
+ private func drop() {
3365
+ release?.cancel()
3366
+ release = nil
3367
+ if let endObserver { NotificationCenter.default.removeObserver(endObserver) }
3368
+ endObserver = nil
3369
+ holder = nil
3370
+ container?.removeFromSuperview()
3371
+ container = nil
3372
+ }
3373
+ }