react-native-nitro-input 0.3.3 → 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,51 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.4
4
+
5
+ - **iOS: a focused field that took no typing** (with
6
+ react-native-keyboard-controller). keyboard-controller wraps the focused
7
+ field's delegate in one composite shared by every input and forwards to the
8
+ delegate it stored last; when focus moves faster than it re-wraps (a pushed
9
+ screen's `autoFocus` field, which the push's own `endEditing` then resigns),
10
+ a field's delegate calls reach another field
11
+ ([keyboard-controller#1588](https://github.com/kirillzyusko/react-native-keyboard-controller/issues/1588)).
12
+ The field looked focused, but every keystroke was checked against the
13
+ other field's rules and applied to it (a number field threw the letters
14
+ away). A NitroInput now hands a delegate call for another field to that
15
+ field, and puts its own delegate back before it starts editing.
16
+ - **`focus()` as a field mounts opens the keyboard even when it is down.**
17
+ A `focus()` that arrives before the view is on screen is held until it is,
18
+ and was then honoured only while the keyboard was still up: right for a
19
+ screen navigated back to (a keyboard dismissed on the way stays down), but
20
+ it also dropped `useEffect(() => ref.current?.focus(), [])` on a field
21
+ swapped in after one without a keyboard (a free-text question after a
22
+ multiple-choice one). A field that has never been on screen now takes the
23
+ focus it was asked for, as `autoFocus` does. Both platforms.
24
+ - **iOS: an `autoFocus` field on a screen pushed without a slide**
25
+ (`animation: 'none'`, `'fade'`, `'simple_push'`) no longer blurs and
26
+ refocuses, and the keyboard no longer starts to close and comes back
27
+ ([react-navigation#11643](https://github.com/react-navigation/react-navigation/issues/11643),
28
+ [#11626](https://github.com/react-navigation/react-navigation/issues/11626)).
29
+ UINavigationController ends editing in the incoming view mid-transition
30
+ and hands first responder back as it completes; the field now keeps it
31
+ through the transition.
32
+ - **iOS: a `selection` given while the field is not focused** is where the
33
+ caret goes when it is focused, instead of the end of the text
34
+ ([react-native#46943](https://github.com/facebook/react-native/issues/46943)).
35
+ - **iOS: Japanese, Chinese and Korean input** with `maxLength` or a
36
+ `transform`: the IME's composition is left alone until it is committed,
37
+ then cut to `maxLength` and transformed. The unconverted letters no longer
38
+ count against `maxLength`, and a controlled parent echoing the text back
39
+ mid-composition no longer ends it
40
+ ([react-native#56463](https://github.com/facebook/react-native/issues/56463),
41
+ [#52552](https://github.com/facebook/react-native/issues/52552)).
42
+ - **Android: `maxLength` counts characters when typing**, as it already did
43
+ for text set by the program and as iOS does: an emoji took two places when
44
+ typed.
45
+ - **Android: changing `secureTextEntry` (or another keyboard prop) on a
46
+ focused field keeps the caret where it was** instead of moving it to the
47
+ start ([react-native#38676](https://github.com/facebook/react-native/issues/38676)).
48
+
3
49
  ## 0.3.3
4
50
 
5
51
  - **`keyboardHandoffMs`**: when the focused field is popped or unmounted,
@@ -547,6 +547,14 @@ class NitroInputView(context: Context) : FrameLayout(context) {
547
547
  * refocuses its field before react-native-screens puts it back.
548
548
  */
549
549
  private var pendingFocusUntil = 0L
550
+ /**
551
+ * The pending `focus()` came before the view was ever on a window: a field
552
+ * focused as it mounts (a step swapped in place, keyed by its question), not
553
+ * a screen coming back. It is taken whatever the keyboard is doing, as
554
+ * `autoFocus` is.
555
+ */
556
+ private var pendingFocusOnMount = false
557
+ private var everAttached = false
550
558
  private var batchDepth = 0
551
559
  private var feedPending = false
552
560
  private var feedCaret = -1
@@ -1003,6 +1011,11 @@ class NitroInputView(context: Context) : FrameLayout(context) {
1003
1011
  // inserts a newline rather than submitting.
1004
1012
  textType = textType or InputType.TYPE_TEXT_FLAG_MULTI_LINE
1005
1013
  }
1014
+ // setInputType, setSingleLine and a new transformation each put the caret
1015
+ // back at 0: a secureTextEntry toggle on a focused field moved it
1016
+ // (react-native#38676). Put it back where it was.
1017
+ val selectionStart = editText.selectionStart
1018
+ val selectionEnd = editText.selectionEnd
1006
1019
  editText.inputType = textType
1007
1020
  if (rawType != null) editText.setRawInputType(rawType)
1008
1021
  if (k.multiline) {
@@ -1022,6 +1035,10 @@ class NitroInputView(context: Context) : FrameLayout(context) {
1022
1035
  if (k.secureTextEntry) {
1023
1036
  editText.transformationMethod = android.text.method.PasswordTransformationMethod.getInstance()
1024
1037
  }
1038
+ val length = editText.text?.length ?: 0
1039
+ if (selectionStart >= 0 && (editText.selectionStart != selectionStart || editText.selectionEnd != selectionEnd)) {
1040
+ editText.setSelection(minOf(selectionStart, length), minOf(maxOf(selectionStart, selectionEnd), length))
1041
+ }
1025
1042
  editText.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI or when (k.returnKeyType) {
1026
1043
  ReturnKeyType.DEFAULT -> EditorInfo.IME_ACTION_UNSPECIFIED
1027
1044
  ReturnKeyType.DONE -> EditorInfo.IME_ACTION_DONE
@@ -1034,7 +1051,7 @@ class NitroInputView(context: Context) : FrameLayout(context) {
1034
1051
  // `setEditable` replaces through the `Editable`, which re-runs the filters:
1035
1052
  // a length filter there clipped the mask's punctuation off the end.
1036
1053
  editText.filters = if (format.mode == Mode.TEXT && k.maxLength > 0) {
1037
- arrayOf<InputFilter>(InputFilter.LengthFilter(k.maxLength))
1054
+ arrayOf<InputFilter>(CodePointLengthFilter(k.maxLength))
1038
1055
  } else {
1039
1056
  emptyArray<InputFilter>()
1040
1057
  }
@@ -1221,6 +1238,7 @@ class NitroInputView(context: Context) : FrameLayout(context) {
1221
1238
  // subtree shown in the same commit that asks for focus): an invisible
1222
1239
  // view cannot take focus. Honour it once the view is attached and shown.
1223
1240
  pendingFocusUntil = SystemClock.uptimeMillis() + 1000
1241
+ pendingFocusOnMount = !everAttached
1224
1242
  return
1225
1243
  }
1226
1244
  pendingFocusUntil = 0
@@ -1356,6 +1374,8 @@ class NitroInputView(context: Context) : FrameLayout(context) {
1356
1374
  fun resetForRecycle() {
1357
1375
  worklets = Worklets()
1358
1376
  pendingFocusUntil = 0
1377
+ pendingFocusOnMount = false
1378
+ everAttached = false
1359
1379
  inputFrame = Frame()
1360
1380
  labelProgress = 0f
1361
1381
  notchProgress = 0f
@@ -1393,6 +1413,7 @@ class NitroInputView(context: Context) : FrameLayout(context) {
1393
1413
 
1394
1414
  override fun onAttachedToWindow() {
1395
1415
  super.onAttachedToWindow()
1416
+ everAttached = true
1396
1417
  if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
1397
1418
  animatorScale = -1f
1398
1419
  context.contentResolver.registerContentObserver(
@@ -1414,10 +1435,13 @@ class NitroInputView(context: Context) : FrameLayout(context) {
1414
1435
  /** A `focus()` asked for while the view was off the window or hidden. */
1415
1436
  private fun focusIfPending() {
1416
1437
  if (pendingFocusUntil <= 0 || !isAttachedToWindow || !isShown) return
1417
- // Only while the keyboard is still up (held for this field, or another
1418
- // field has it): a keyboard dismissed during the transition stays down.
1419
- val wanted = SystemClock.uptimeMillis() < pendingFocusUntil && (KeyboardHandoff.isHolding || imeVisible())
1438
+ // A screen coming back takes it only while the keyboard is still up (held
1439
+ // for this field, or another field has it): a keyboard dismissed during
1440
+ // the transition stays down. A field focused as it mounts takes it anyway.
1441
+ val wanted = SystemClock.uptimeMillis() < pendingFocusUntil &&
1442
+ (pendingFocusOnMount || KeyboardHandoff.isHolding || imeVisible())
1420
1443
  pendingFocusUntil = 0
1444
+ pendingFocusOnMount = false
1421
1445
  if (wanted) post { focus() }
1422
1446
  }
1423
1447
 
@@ -2513,3 +2537,19 @@ internal object KeyboardHandoff {
2513
2537
  (field.parent as? android.view.ViewGroup)?.removeView(field)
2514
2538
  }
2515
2539
  }
2540
+
2541
+ /**
2542
+ * `maxLength` in characters (code points), as everywhere else in the field and
2543
+ * as iOS counts it: `InputFilter.LengthFilter` counts UTF-16 units, so an emoji
2544
+ * took two of the places when typed and one when set by the program. Never
2545
+ * splits a surrogate pair.
2546
+ */
2547
+ internal class CodePointLengthFilter(private val max: Int) : InputFilter {
2548
+ override fun filter(source: CharSequence, start: Int, end: Int, dest: android.text.Spanned, dstart: Int, dend: Int): CharSequence? {
2549
+ val kept = Character.codePointCount(dest, 0, dstart) + Character.codePointCount(dest, dend, dest.length)
2550
+ val room = max - kept
2551
+ if (room <= 0) return if (start == end) null else ""
2552
+ if (Character.codePointCount(source, start, end) <= room) return null
2553
+ return source.subSequence(start, Character.offsetByCodePoints(source, start, room))
2554
+ }
2555
+ }
@@ -608,6 +608,32 @@ final class NitroInputView: UIView {
608
608
  /// pop is re-added only as the transition starts): taken the moment the view
609
609
  /// is back, unless it has gone stale.
610
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
611
637
  /// When the field last stopped editing while on screen (media time; 0 = never).
612
638
  private var endedEditingAt: CFTimeInterval = 0
613
639
  /// Had the keyboard when its screen was covered: take it back on return.
@@ -855,17 +881,23 @@ final class NitroInputView: UIView {
855
881
  }
856
882
  }
857
883
  if window != nil, pendingFocusUntil > 0 {
858
- // Only while the keyboard is still up (held for this field, or another
859
- // field has it): a keyboard dismissed during the transition stays down.
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.
860
888
  let handoff = KeyboardHandoff.shared
861
- let wanted = CACurrentMediaTime() < pendingFocusUntil && (handoff.isHolding || handoff.keyboardVisible)
889
+ let wanted = CACurrentMediaTime() < pendingFocusUntil
890
+ && (pendingFocusOnMount || handoff.isHolding || handoff.keyboardVisible)
862
891
  pendingFocusUntil = 0
892
+ pendingFocusOnMount = false
863
893
  if wanted, traits.editable { claimFirstResponder() }
864
894
  }
895
+ if window != nil { everInWindow = true }
865
896
  maybeAutoFocus()
866
897
  }
867
898
 
868
899
  override func willMove(toWindow newWindow: UIWindow?) {
900
+ if newWindow == nil { holdsFocusThroughTransition = false }
869
901
  // Before UIKit resigns the field on its way out, so the keyboard never
870
902
  // starts to hide.
871
903
  if newWindow == nil {
@@ -898,10 +930,26 @@ final class NitroInputView: UIView {
898
930
  @discardableResult
899
931
  private func claimOnce() -> Bool {
900
932
  claimingFocus = true
901
- defer { claimingFocus = false }
933
+ Self.claimInProgress = true
934
+ defer {
935
+ claimingFocus = false
936
+ Self.claimInProgress = false
937
+ }
902
938
  return editor.becomeFirstResponder()
903
939
  }
904
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
+
905
953
  /// Sends the current selection to a delegate someone put in front of ours
906
954
  /// (see `textFieldDidBeginEditing`). Ours reports selections itself.
907
955
  private func announceSelectionToDelegate() {
@@ -1010,6 +1058,13 @@ final class NitroInputView: UIView {
1010
1058
  worklets = Worklets()
1011
1059
  if editor.isFirstResponder { editor.resignFirstResponder() }
1012
1060
  pendingFocusUntil = 0
1061
+ pendingFocusOnMount = false
1062
+ everInWindow = false
1063
+ selectionForFocus = nil
1064
+ beganInTransition = false
1065
+ withheldBlur = false
1066
+ holdsFocusThroughTransition = false
1067
+ composition = nil
1013
1068
  restoreOnReturn = false
1014
1069
  endedEditingAt = 0
1015
1070
  focusAfterTransition = false
@@ -1050,6 +1105,7 @@ final class NitroInputView: UIView {
1050
1105
  // what swaps the keyboard in place rather than hiding and showing it.
1051
1106
  guard window != nil else {
1052
1107
  pendingFocusUntil = CACurrentMediaTime() + 1
1108
+ pendingFocusOnMount = !everInWindow
1053
1109
  return
1054
1110
  }
1055
1111
  pendingFocusUntil = 0
@@ -1062,7 +1118,9 @@ final class NitroInputView: UIView {
1062
1118
  endedEditingAt = 0
1063
1119
  focusAfterTransition = false
1064
1120
  if editor.isFirstResponder {
1121
+ blurring = true
1065
1122
  editor.resignFirstResponder()
1123
+ blurring = false
1066
1124
  } else {
1067
1125
  // `Keyboard.dismiss()` while a field that just left the screen holds the
1068
1126
  // keyboard for the next one: nothing is focused, so let it go now.
@@ -1075,6 +1133,9 @@ final class NitroInputView: UIView {
1075
1133
  let count = text.unicodeScalars.count
1076
1134
  let lower = min(max(0, start), count)
1077
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)
1078
1139
  guard let from = field.position(from: field.beginningOfDocument, offset: utf16Offset(ofCodePoint: lower)),
1079
1140
  let to = field.position(from: field.beginningOfDocument, offset: utf16Offset(ofCodePoint: upper)),
1080
1141
  let range = field.textRange(from: from, to: to) else { return }
@@ -1094,6 +1155,11 @@ final class NitroInputView: UIView {
1094
1155
  /// text mode), caret at the end. Returns false when nothing changed.
1095
1156
  @discardableResult
1096
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 }
1097
1163
  var normalized = normalized(newText)
1098
1164
  if worklets.transform != 0 {
1099
1165
  let count = normalized.unicodeScalars.count
@@ -1704,11 +1770,47 @@ final class NitroInputView: UIView {
1704
1770
 
1705
1771
  @objc private func fieldEditingChanged() {
1706
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
+ }
1707
1777
  // Text mode: the field edited itself; number mode edits never reach here
1708
1778
  // (the delegate applies them and returns false).
1709
1779
  textDidChange(caret: caretCodePointIndex(), reason: .user)
1710
1780
  }
1711
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
+
1712
1814
  /// The selection start in code points (the engine's caret index).
1713
1815
  private func caretCodePointIndex() -> Int {
1714
1816
  guard let range = field.selectedTextRange else { return text.unicodeScalars.count }
@@ -2212,8 +2314,14 @@ final class NitroInputView: UIView {
2212
2314
 
2213
2315
  override func becomeFirstResponder() -> Bool {
2214
2316
  if owner?.deferFocusWhileTransitioning() == true { return false }
2317
+ if let other = delegate as? NitroInputView, other !== owner { delegate = owner }
2215
2318
  return super.becomeFirstResponder()
2216
2319
  }
2320
+
2321
+ override func resignFirstResponder() -> Bool {
2322
+ if owner?.keepsFocusThroughTransition() == true { return false }
2323
+ return super.resignFirstResponder()
2324
+ }
2217
2325
  var placeholder: String = "" { didSet { setNeedsDisplay() } }
2218
2326
  var placeholderColor: UIColor = .placeholderText { didSet { setNeedsDisplay() } }
2219
2327
 
@@ -2278,10 +2386,24 @@ final class NitroInputView: UIView {
2278
2386
  fileprivate final class HiddenTextField: UITextField {
2279
2387
  weak var owner: NitroInputView?
2280
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.
2281
2397
  override func becomeFirstResponder() -> Bool {
2282
2398
  if owner?.deferFocusWhileTransitioning() == true { return false }
2399
+ if let other = delegate as? NitroInputView, other !== owner { delegate = owner }
2283
2400
  return super.becomeFirstResponder()
2284
2401
  }
2402
+
2403
+ override func resignFirstResponder() -> Bool {
2404
+ if owner?.keepsFocusThroughTransition() == true { return false }
2405
+ return super.resignFirstResponder()
2406
+ }
2285
2407
  var leftInset: CGFloat = 0
2286
2408
  var rightInset: CGFloat = 0
2287
2409
  /// Room for a floated label sitting on the top edge.
@@ -2406,18 +2528,42 @@ final class NitroInputView: UIView {
2406
2528
  }
2407
2529
  }
2408
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
+
2409
2552
  // MARK: - UITextViewDelegate
2410
2553
 
2411
2554
  extension NitroInputView: UITextViewDelegate {
2412
2555
  func textViewDidBeginEditing(_ textView: UITextView) {
2556
+ if let owner = rightfulOwner(of: textView) { return owner.textViewDidBeginEditing(textView) }
2413
2557
  textFieldDidBeginEditing(field)
2414
2558
  }
2415
2559
 
2416
2560
  func textViewDidEndEditing(_ textView: UITextView) {
2561
+ if let owner = rightfulOwner(of: textView) { return owner.textViewDidEndEditing(textView) }
2417
2562
  textFieldDidEndEditing(field)
2418
2563
  }
2419
2564
 
2420
2565
  func textViewDidChange(_ textView: UITextView) {
2566
+ if let owner = rightfulOwner(of: textView) { return owner.textViewDidChange(textView) }
2421
2567
  // Typing does not go through `text`'s setter, so the drawn placeholder
2422
2568
  // would stay under the first characters typed.
2423
2569
  textView.setNeedsDisplay()
@@ -2433,11 +2579,15 @@ extension NitroInputView: UITextViewDelegate {
2433
2579
  }
2434
2580
 
2435
2581
  func textViewDidChangeSelection(_ textView: UITextView) {
2582
+ if let owner = rightfulOwner(of: textView) { return owner.textViewDidChangeSelection(textView) }
2436
2583
  guard !isSettingText else { return }
2437
2584
  reportSelection()
2438
2585
  }
2439
2586
 
2440
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
+ }
2441
2591
  // The return key arrives as a lone line break. Only that one is the key:
2442
2592
  // a pasted line break is text, and goes in whatever the submit behaviour.
2443
2593
  guard text == "\n", (textView as? HiddenTextView)?.isPasting != true else { return true }
@@ -2451,6 +2601,9 @@ extension NitroInputView: UITextViewDelegate {
2451
2601
  extension NitroInputView: UITextFieldDelegate {
2452
2602
 
2453
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
+ }
2454
2607
  // Like React Native's `onKeyPress`: fires before the text changes, with
2455
2608
  // 'Backspace' for a deletion and the inserted string otherwise.
2456
2609
  if worklets.onKeyPress != 0 {
@@ -2482,6 +2635,19 @@ extension NitroInputView: UITextFieldDelegate {
2482
2635
  // Without a transform or a length limit the field edits itself (keeps
2483
2636
  // marked text / autocorrect intact); `fieldEditingChanged` reports it.
2484
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
+ }
2485
2651
  var replacement = string
2486
2652
  if format.maxLength > 0 {
2487
2653
  // Keep as much of the replacement as fits (a paste), or nothing.
@@ -2554,6 +2720,23 @@ extension NitroInputView: UITextFieldDelegate {
2554
2720
  }
2555
2721
 
2556
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
+ }
2557
2740
  // keyboard-controller puts its own delegate in front of ours a turn after
2558
2741
  // editing begins, and its KeyboardAwareScrollView waits for a selection
2559
2742
  // event from the newly focused field before it scrolls. A tap or Next
@@ -2564,7 +2747,15 @@ extension NitroInputView: UITextFieldDelegate {
2564
2747
  DispatchQueue.main.async { [weak self] in self?.announceSelectionToDelegate() }
2565
2748
  }
2566
2749
  if traits.clearTextOnFocus {
2750
+ selectionForFocus = nil
2567
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
+ }
2568
2759
  } else if traits.selectTextOnFocus {
2569
2760
  // In the next runloop turn: UIKit sets its own selection as it begins.
2570
2761
  DispatchQueue.main.async { [weak self] in
@@ -2582,9 +2773,49 @@ extension NitroInputView: UITextFieldDelegate {
2582
2773
  }
2583
2774
 
2584
2775
  func textFieldDidEndEditing(_ textField: UITextField) {
2776
+ if let owner = rightfulOwner(of: textField) { return owner.textFieldDidEndEditing(textField) }
2585
2777
  if window != nil { endedEditingAt = CACurrentMediaTime() }
2586
2778
  if contentOverflows { render() }
2587
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() {
2588
2819
  if worklets.onFocusChange != 0 {
2589
2820
  margelo.nitro.nitroinput.nitroinputworklets.runFocusChange(Int32(worklets.onFocusChange), false, std.string(text))
2590
2821
  }
@@ -2593,10 +2824,10 @@ extension NitroInputView: UITextFieldDelegate {
2593
2824
  }
2594
2825
  onFocusChange?(false)
2595
2826
  onEndEditing?(text)
2596
- if wantsFrameDrawing { layoutFrame(animated: true) }
2597
2827
  }
2598
2828
 
2599
2829
  func textFieldDidChangeSelection(_ textField: UITextField) {
2830
+ if let owner = rightfulOwner(of: textField) { return owner.textFieldDidChangeSelection(textField) }
2600
2831
  guard !isSettingText else { return }
2601
2832
  // A caret move alone does not re-render; when the content is wider than
2602
2833
  // the view the scroll offset has to follow it.
@@ -2606,6 +2837,7 @@ extension NitroInputView: UITextFieldDelegate {
2606
2837
  }
2607
2838
 
2608
2839
  func textFieldShouldReturn(_ textField: UITextField) -> Bool {
2840
+ if let owner = rightfulOwner(of: textField) { return owner.textFieldShouldReturn(textField) }
2609
2841
  handleReturnKey()
2610
2842
  return false
2611
2843
  }
@@ -3102,7 +3334,10 @@ final class KeyboardHandoff {
3102
3334
  field.inputAccessoryView = editor.inputAccessoryView
3103
3335
  box.addSubview(field)
3104
3336
  window.addSubview(box)
3105
- guard field.becomeFirstResponder() else {
3337
+ NitroInputView.claimInProgress = true
3338
+ let held = field.becomeFirstResponder()
3339
+ NitroInputView.claimInProgress = false
3340
+ guard held else {
3106
3341
  box.removeFromSuperview()
3107
3342
  return
3108
3343
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-nitro-input",
3
- "version": "0.3.3",
3
+ "version": "0.3.4",
4
4
  "description": "Native text for React Native, built with Nitro: a text and amount input with native formatting, masks and a Torph-style reflow, and an animated number (odometer, SwiftUI-style numeric text, ticker) whose digits roll or swap natively, with currency layouts and animated currency switches, shrink-to-fit, a loading shimmer and a jackpot reveal.",
5
5
  "main": "lib/commonjs/src/index.js",
6
6
  "module": "lib/module/src/index.js",