react-native-nitro-input 0.3.3 → 0.3.5

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,73 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.5
4
+
5
+ - **`focusedValue`**: pass a shared value (Reanimated's `useSharedValue(false)`)
6
+ and the field keeps it equal to its focus, set on the UI thread the moment
7
+ focus changes, while `onFocus` / `onBlur` still run on JS. For focus styling
8
+ that must not wait for JS and that wraps more than the field: a border
9
+ around a row holding an icon or a country picker in front and a clear
10
+ button behind. Needs `react-native-worklets`.
11
+ - **Worklet focus handlers see the first focus of an `autoFocus` field.** They
12
+ were registered in an effect, which can run after the view has attached and
13
+ taken focus, so a worklet `onFocus` (and `useNitroInputState`'s `focused`)
14
+ missed it. They are registered while rendering now.
15
+ - **iOS: no keyboard left over a screen popped back to.** Going back from a
16
+ screen whose field had the keyboard, with `keyboardHandoffMs`, to a screen
17
+ where no field takes it (a list whose search field was never focused), the
18
+ keyboard stayed up over that screen for the whole `keyboardHandoffMs` after
19
+ the pop. React unmounts the popped screen's field before the pop starts, so
20
+ the handoff could not tell a pop from a field swapped in place. The hold now
21
+ ends as the screen starts to leave when no field is waiting for the
22
+ keyboard; a field there that had it when it was covered, or one focused on
23
+ return, still takes it over.
24
+
25
+ ## 0.3.4
26
+
27
+ - **iOS: a focused field that took no typing** (with
28
+ react-native-keyboard-controller). keyboard-controller wraps the focused
29
+ field's delegate in one composite shared by every input and forwards to the
30
+ delegate it stored last; when focus moves faster than it re-wraps (a pushed
31
+ screen's `autoFocus` field, which the push's own `endEditing` then resigns),
32
+ a field's delegate calls reach another field
33
+ ([keyboard-controller#1588](https://github.com/kirillzyusko/react-native-keyboard-controller/issues/1588)).
34
+ The field looked focused, but every keystroke was checked against the
35
+ other field's rules and applied to it (a number field threw the letters
36
+ away). A NitroInput now hands a delegate call for another field to that
37
+ field, and puts its own delegate back before it starts editing.
38
+ - **`focus()` as a field mounts opens the keyboard even when it is down.**
39
+ A `focus()` that arrives before the view is on screen is held until it is,
40
+ and was then honoured only while the keyboard was still up: right for a
41
+ screen navigated back to (a keyboard dismissed on the way stays down), but
42
+ it also dropped `useEffect(() => ref.current?.focus(), [])` on a field
43
+ swapped in after one without a keyboard (a free-text question after a
44
+ multiple-choice one). A field that has never been on screen now takes the
45
+ focus it was asked for, as `autoFocus` does. Both platforms.
46
+ - **iOS: an `autoFocus` field on a screen pushed without a slide**
47
+ (`animation: 'none'`, `'fade'`, `'simple_push'`) no longer blurs and
48
+ refocuses, and the keyboard no longer starts to close and comes back
49
+ ([react-navigation#11643](https://github.com/react-navigation/react-navigation/issues/11643),
50
+ [#11626](https://github.com/react-navigation/react-navigation/issues/11626)).
51
+ UINavigationController ends editing in the incoming view mid-transition
52
+ and hands first responder back as it completes; the field now keeps it
53
+ through the transition.
54
+ - **iOS: a `selection` given while the field is not focused** is where the
55
+ caret goes when it is focused, instead of the end of the text
56
+ ([react-native#46943](https://github.com/facebook/react-native/issues/46943)).
57
+ - **iOS: Japanese, Chinese and Korean input** with `maxLength` or a
58
+ `transform`: the IME's composition is left alone until it is committed,
59
+ then cut to `maxLength` and transformed. The unconverted letters no longer
60
+ count against `maxLength`, and a controlled parent echoing the text back
61
+ mid-composition no longer ends it
62
+ ([react-native#56463](https://github.com/facebook/react-native/issues/56463),
63
+ [#52552](https://github.com/facebook/react-native/issues/52552)).
64
+ - **Android: `maxLength` counts characters when typing**, as it already did
65
+ for text set by the program and as iOS does: an emoji took two places when
66
+ typed.
67
+ - **Android: changing `secureTextEntry` (or another keyboard prop) on a
68
+ focused field keeps the caret where it was** instead of moving it to the
69
+ start ([react-native#38676](https://github.com/facebook/react-native/issues/38676)).
70
+
3
71
  ## 0.3.3
4
72
 
5
73
  - **`keyboardHandoffMs`**: when the focused field is popped or unmounted,
package/README.md CHANGED
@@ -357,6 +357,33 @@ function Field() {
357
357
  values; `field.handlers` are the worklets that keep them current. Typing in
358
358
  that field runs nothing on the JS thread and re-renders nothing.
359
359
 
360
+ #### Focus styling around a field and what sits beside it
361
+
362
+ `field.handlers` replace your JS `onFocus` / `onBlur`. When you only need the
363
+ focus state, and keep your handlers, pass a shared value as `focusedValue`: the
364
+ field sets it on the UI thread the moment focus changes, `autoFocus` included,
365
+ and `onFocus` / `onBlur` still run. The row that draws the border can then hold
366
+ anything, the way a form field often has an icon or a country picker in front
367
+ and a clear button behind:
368
+
369
+ ```tsx
370
+ function SearchField({ onFocus }: { onFocus: () => void }) {
371
+ const focused = useSharedValue(false)
372
+ const ring = useAnimatedStyle(() => ({
373
+ borderColor: focused.value ? '#2563eb' : 'transparent',
374
+ }))
375
+ return (
376
+ <Animated.View style={[styles.row, ring]}>
377
+ <SearchIcon />
378
+ <NitroInput style={{ flex: 1 }} focusedValue={focused} onFocus={onFocus} />
379
+ <ClearButton />
380
+ </Animated.View>
381
+ )
382
+ }
383
+ ```
384
+
385
+ The border changes in the frame the caret appears, with no JS round trip.
386
+
360
387
  A worklet can only reach what it closes over, unless worklets run in
361
388
  [Bundle Mode](https://docs.swmansion.com/react-native-worklets/docs/bundleMode/),
362
389
  which gives them the whole bundle. That is what lets a `transform` use a real
@@ -549,6 +576,7 @@ screen behaves like theirs with these settings:
549
576
  | `onChangeMask` | `(formatted, extracted, tail, complete) => void` | – | `mask` mode: the formatted text, the characters the user contributed, what is still missing, and whether every mandatory slot is filled. |
550
577
  | `signPlacement` | `'beforeAffix' \| 'afterAffix'` | `'beforeAffix'` | Where a negative amount's sign sits relative to `prefix`: `-$1,234.56` or `$-1,234.56`. Reflow only — a plain field's affixes are accessory views outside the text. |
551
578
  | `onFocus` / `onBlur` | `(event) => void` | – | Carries `text`, `eventCount` and `target`. |
579
+ | `focusedValue` | `SharedValue<boolean>` | – | Kept equal to the field's focus on the UI thread, while `onFocus` / `onBlur` still run. Needs `react-native-worklets`. |
552
580
  | `onSubmitEditing` | `(event) => void` | – | Return key pressed; what happens next is `submitBehavior`. |
553
581
  | `onEndEditing` | `(event) => void` | – | Editing finished. |
554
582
  | `onSelectionChange` | `(event) => void` | – | The caret or selection moved, in code points. |
@@ -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,34 @@ 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
+ /// Every live field, to ask whether one is about to take the keyboard.
637
+ private static let liveFields = NSHashTable<NitroInputView>.weakObjects()
638
+ private var everInWindow = false
611
639
  /// When the field last stopped editing while on screen (media time; 0 = never).
612
640
  private var endedEditingAt: CFTimeInterval = 0
613
641
  /// Had the keyboard when its screen was covered: take it back on return.
@@ -679,6 +707,7 @@ final class NitroInputView: UIView {
679
707
  super.init(frame: frame)
680
708
  // Starts it tracking the keyboard before any field needs to ask.
681
709
  _ = KeyboardHandoff.shared
710
+ Self.liveFields.add(self)
682
711
  isOpaque = false
683
712
  backgroundColor = .clear
684
713
  clipsToBounds = false
@@ -855,17 +884,23 @@ final class NitroInputView: UIView {
855
884
  }
856
885
  }
857
886
  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.
887
+ // A screen coming back takes it only while the keyboard is still up
888
+ // (held for this field, or another field has it): a keyboard dismissed
889
+ // during the transition stays down. A field focused as it mounts takes
890
+ // it anyway.
860
891
  let handoff = KeyboardHandoff.shared
861
- let wanted = CACurrentMediaTime() < pendingFocusUntil && (handoff.isHolding || handoff.keyboardVisible)
892
+ let wanted = CACurrentMediaTime() < pendingFocusUntil
893
+ && (pendingFocusOnMount || handoff.isHolding || handoff.keyboardVisible)
862
894
  pendingFocusUntil = 0
895
+ pendingFocusOnMount = false
863
896
  if wanted, traits.editable { claimFirstResponder() }
864
897
  }
898
+ if window != nil { everInWindow = true }
865
899
  maybeAutoFocus()
866
900
  }
867
901
 
868
902
  override func willMove(toWindow newWindow: UIWindow?) {
903
+ if newWindow == nil { holdsFocusThroughTransition = false }
869
904
  // Before UIKit resigns the field on its way out, so the keyboard never
870
905
  // starts to hide.
871
906
  if newWindow == nil {
@@ -882,7 +917,61 @@ final class NitroInputView: UIView {
882
917
  func handOffKeyboardIfFocused() {
883
918
  guard traits.keyboardHandoffMs > 0, traits.showSoftInputOnFocus,
884
919
  let window, editor.isFirstResponder else { return }
885
- KeyboardHandoff.shared.hold(like: editor, in: window, for: traits.keyboardHandoffMs)
920
+ let hold = KeyboardHandoff.shared.hold(like: editor, in: window, for: traits.keyboardHandoffMs)
921
+ if let hold, let host = hostViewController {
922
+ Self.letGo(hold, ifLeaving: host, until: CACurrentMediaTime() + traits.keyboardHandoffMs / 1000)
923
+ }
924
+ }
925
+
926
+ /// Ends a hold as soon as the leaving field's screen turns out to be going
927
+ /// itself (back, a sheet closing) with no field waiting to take the
928
+ /// keyboard: held on, it only stays up over a screen that has no use for it
929
+ /// until the time runs out. React unmounts a popped screen's fields before
930
+ /// react-native-screens starts the pop, so at the handoff a pop still looks
931
+ /// like a view swapped in place; the screen starts leaving a moment later.
932
+ /// A field on the screen underneath that takes the keyboard back ends the
933
+ /// hold itself.
934
+ private static func letGo(_ hold: Int, ifLeaving host: UIViewController, until deadline: CFTimeInterval) {
935
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) { [weak host] in
936
+ let handoff = KeyboardHandoff.shared
937
+ guard let host, handoff.isHolding, handoff.currentHold == hold else { return }
938
+ if isLeaving(host) {
939
+ // Once more a moment later: the screen underneath comes back into the
940
+ // window as the pop starts, and a field there that had the keyboard
941
+ // asks for it back only then.
942
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
943
+ guard handoff.isHolding, handoff.currentHold == hold, !fieldWaitsForKeyboard() else { return }
944
+ handoff.letGo()
945
+ }
946
+ return
947
+ }
948
+ if CACurrentMediaTime() < deadline { letGo(hold, ifLeaving: host, until: deadline) }
949
+ }
950
+ }
951
+
952
+ /// `controller`'s screen is being popped or dismissed. react-native-screens
953
+ /// takes a popped screen out of its navigation controller as the pop
954
+ /// starts, while its views are still on screen: a controller in no
955
+ /// container, presented by nothing and not the window's root is on its way
956
+ /// out.
957
+ private static func isLeaving(_ controller: UIViewController) -> Bool {
958
+ var current: UIViewController? = controller
959
+ while let each = current {
960
+ if each.isMovingFromParent || each.isBeingDismissed { return true }
961
+ if each.parent == nil, each.presentingViewController == nil,
962
+ each.viewIfLoaded?.window?.rootViewController !== each { return true }
963
+ current = each.parent
964
+ }
965
+ return false
966
+ }
967
+
968
+ /// A field is about to take first responder: a return waiting for the
969
+ /// transition to end, or a focus() held until its view is back in a window.
970
+ private static func fieldWaitsForKeyboard() -> Bool {
971
+ let now = CACurrentMediaTime()
972
+ return liveFields.allObjects.contains { field in
973
+ (field.focusAfterTransition && field.window != nil) || field.pendingFocusUntil > now
974
+ }
886
975
  }
887
976
 
888
977
  /// `becomeFirstResponder`, retried next turn if UIKit declines because the
@@ -898,10 +987,26 @@ final class NitroInputView: UIView {
898
987
  @discardableResult
899
988
  private func claimOnce() -> Bool {
900
989
  claimingFocus = true
901
- defer { claimingFocus = false }
990
+ Self.claimInProgress = true
991
+ defer {
992
+ claimingFocus = false
993
+ Self.claimInProgress = false
994
+ }
902
995
  return editor.becomeFirstResponder()
903
996
  }
904
997
 
998
+ /// Whether a resign now should be declined: the field took focus as its
999
+ /// screen came in, and the push has no slide (`animation: 'none'`, 'fade',
1000
+ /// 'simple_push'), so UINavigationController ends editing in the incoming
1001
+ /// view mid-transition and hands first responder back as it completes. The
1002
+ /// keyboard would start to close and come back (react-navigation#11626),
1003
+ /// and the field would blur and refocus (#11643). `blur()`, another field
1004
+ /// taking the focus and the view leaving the window still resign it.
1005
+ fileprivate func keepsFocusThroughTransition() -> Bool {
1006
+ holdsFocusThroughTransition && !blurring && !Self.claimInProgress && window != nil
1007
+ && hostViewController?.transitionCoordinator != nil
1008
+ }
1009
+
905
1010
  /// Sends the current selection to a delegate someone put in front of ours
906
1011
  /// (see `textFieldDidBeginEditing`). Ours reports selections itself.
907
1012
  private func announceSelectionToDelegate() {
@@ -1010,6 +1115,13 @@ final class NitroInputView: UIView {
1010
1115
  worklets = Worklets()
1011
1116
  if editor.isFirstResponder { editor.resignFirstResponder() }
1012
1117
  pendingFocusUntil = 0
1118
+ pendingFocusOnMount = false
1119
+ everInWindow = false
1120
+ selectionForFocus = nil
1121
+ beganInTransition = false
1122
+ withheldBlur = false
1123
+ holdsFocusThroughTransition = false
1124
+ composition = nil
1013
1125
  restoreOnReturn = false
1014
1126
  endedEditingAt = 0
1015
1127
  focusAfterTransition = false
@@ -1050,6 +1162,7 @@ final class NitroInputView: UIView {
1050
1162
  // what swaps the keyboard in place rather than hiding and showing it.
1051
1163
  guard window != nil else {
1052
1164
  pendingFocusUntil = CACurrentMediaTime() + 1
1165
+ pendingFocusOnMount = !everInWindow
1053
1166
  return
1054
1167
  }
1055
1168
  pendingFocusUntil = 0
@@ -1062,7 +1175,9 @@ final class NitroInputView: UIView {
1062
1175
  endedEditingAt = 0
1063
1176
  focusAfterTransition = false
1064
1177
  if editor.isFirstResponder {
1178
+ blurring = true
1065
1179
  editor.resignFirstResponder()
1180
+ blurring = false
1066
1181
  } else {
1067
1182
  // `Keyboard.dismiss()` while a field that just left the screen holds the
1068
1183
  // keyboard for the next one: nothing is focused, so let it go now.
@@ -1075,6 +1190,9 @@ final class NitroInputView: UIView {
1075
1190
  let count = text.unicodeScalars.count
1076
1191
  let lower = min(max(0, start), count)
1077
1192
  let upper = min(max(lower, end), count)
1193
+ // UIKit puts the caret at the end when a field starts editing, so a
1194
+ // selection given while it is not is kept for then (react-native#46943).
1195
+ selectionForFocus = editor.isFirstResponder ? nil : (lower, upper)
1078
1196
  guard let from = field.position(from: field.beginningOfDocument, offset: utf16Offset(ofCodePoint: lower)),
1079
1197
  let to = field.position(from: field.beginningOfDocument, offset: utf16Offset(ofCodePoint: upper)),
1080
1198
  let range = field.textRange(from: from, to: to) else { return }
@@ -1094,6 +1212,11 @@ final class NitroInputView: UIView {
1094
1212
  /// text mode), caret at the end. Returns false when nothing changed.
1095
1213
  @discardableResult
1096
1214
  func setText(_ newText: String, reason: ChangeReason) -> Bool {
1215
+ // A controlled parent echoing a composition back mid-way (a Japanese,
1216
+ // Chinese or Korean IME): it is what the field shows, but cut to
1217
+ // `maxLength` or run through the transform it would replace the marked
1218
+ // text and end the composition. It is conformed once committed.
1219
+ if reason == .prop, newText == text, (editor as? UITextInput)?.markedTextRange != nil { return false }
1097
1220
  var normalized = normalized(newText)
1098
1221
  if worklets.transform != 0 {
1099
1222
  let count = normalized.unicodeScalars.count
@@ -1704,11 +1827,47 @@ final class NitroInputView: UIView {
1704
1827
 
1705
1828
  @objc private func fieldEditingChanged() {
1706
1829
  guard !isSettingText else { return }
1830
+ if let composition, field.markedTextRange == nil {
1831
+ self.composition = nil
1832
+ conformCommittedComposition(base: composition.base, start: composition.start)
1833
+ }
1707
1834
  // Text mode: the field edited itself; number mode edits never reach here
1708
1835
  // (the delegate applies them and returns false).
1709
1836
  textDidChange(caret: caretCodePointIndex(), reason: .user)
1710
1837
  }
1711
1838
 
1839
+ /// A text-mode composition was committed: cut it to `maxLength` and run the
1840
+ /// transform over it now, as a typed edit would have been, keeping the caret
1841
+ /// after what was committed.
1842
+ private func conformCommittedComposition(base: String, start: Int) {
1843
+ guard format.mode == .text else { return }
1844
+ let committed = text
1845
+ var caret = caretCodePointIndex()
1846
+ var newText = Self.truncated(committed, to: format.maxLength)
1847
+ caret = min(caret, newText.unicodeScalars.count)
1848
+ var selectionEnd = caret
1849
+ if worklets.transform != 0 {
1850
+ let result = margelo.nitro.nitroinput.nitroinputworklets.runTransform(
1851
+ Int32(worklets.transform), std.string(newText), std.string(base), Int32(caret), Int32(caret), Int32(start), Int32(start))
1852
+ if result.applied {
1853
+ newText = String(result.text)
1854
+ let count = newText.unicodeScalars.count
1855
+ caret = Int(result.selectionStart) < 0 ? count : min(Int(result.selectionStart), count)
1856
+ selectionEnd = min(max(caret, Int(result.selectionEnd)), count)
1857
+ }
1858
+ }
1859
+ guard newText != committed else { return }
1860
+ isSettingText = true
1861
+ replaceMinimally(in: field, with: newText)
1862
+ let from = Self.utf16Offset(in: newText, codePoint: caret)
1863
+ let to = Self.utf16Offset(in: newText, codePoint: selectionEnd)
1864
+ if let fromPosition = field.position(from: field.beginningOfDocument, offset: from),
1865
+ let toPosition = field.position(from: field.beginningOfDocument, offset: to) {
1866
+ field.selectedTextRange = field.textRange(from: fromPosition, to: toPosition)
1867
+ }
1868
+ isSettingText = false
1869
+ }
1870
+
1712
1871
  /// The selection start in code points (the engine's caret index).
1713
1872
  private func caretCodePointIndex() -> Int {
1714
1873
  guard let range = field.selectedTextRange else { return text.unicodeScalars.count }
@@ -2212,8 +2371,14 @@ final class NitroInputView: UIView {
2212
2371
 
2213
2372
  override func becomeFirstResponder() -> Bool {
2214
2373
  if owner?.deferFocusWhileTransitioning() == true { return false }
2374
+ if let other = delegate as? NitroInputView, other !== owner { delegate = owner }
2215
2375
  return super.becomeFirstResponder()
2216
2376
  }
2377
+
2378
+ override func resignFirstResponder() -> Bool {
2379
+ if owner?.keepsFocusThroughTransition() == true { return false }
2380
+ return super.resignFirstResponder()
2381
+ }
2217
2382
  var placeholder: String = "" { didSet { setNeedsDisplay() } }
2218
2383
  var placeholderColor: UIColor = .placeholderText { didSet { setNeedsDisplay() } }
2219
2384
 
@@ -2278,10 +2443,24 @@ final class NitroInputView: UIView {
2278
2443
  fileprivate final class HiddenTextField: UITextField {
2279
2444
  weak var owner: NitroInputView?
2280
2445
 
2446
+ /// keyboard-controller swaps a proxy delegate into the focused field and
2447
+ /// writes the "original" back when focus moves on. When one field takes the
2448
+ /// keyboard from another and loses it again within the same transition (an
2449
+ /// `autoFocus` field on a pushed screen, which the push's own `endEditing`
2450
+ /// then resigns), it can write the other field's delegate back into this
2451
+ /// one. Every edit then goes to the other field - a number field rejects the
2452
+ /// letters - and this field, focused, takes no typing. A field is only ever
2453
+ /// its own owner's, so put that back before editing starts.
2281
2454
  override func becomeFirstResponder() -> Bool {
2282
2455
  if owner?.deferFocusWhileTransitioning() == true { return false }
2456
+ if let other = delegate as? NitroInputView, other !== owner { delegate = owner }
2283
2457
  return super.becomeFirstResponder()
2284
2458
  }
2459
+
2460
+ override func resignFirstResponder() -> Bool {
2461
+ if owner?.keepsFocusThroughTransition() == true { return false }
2462
+ return super.resignFirstResponder()
2463
+ }
2285
2464
  var leftInset: CGFloat = 0
2286
2465
  var rightInset: CGFloat = 0
2287
2466
  /// Room for a floated label sitting on the top edge.
@@ -2406,18 +2585,42 @@ final class NitroInputView: UIView {
2406
2585
  }
2407
2586
  }
2408
2587
 
2588
+ // MARK: - Misrouted delegate callbacks
2589
+
2590
+ extension NitroInputView {
2591
+ /// The view a delegate callback really belongs to, when it is not this one.
2592
+ ///
2593
+ /// react-native-keyboard-controller wraps the focused field's delegate in one
2594
+ /// composite it shares between every input, and that composite forwards to
2595
+ /// whichever delegate it stored last. When focus moves on faster than it
2596
+ /// re-wraps (an `autoFocus` field on a pushed screen), a field's callbacks
2597
+ /// can arrive here, at another field's view
2598
+ /// (kirillzyusko/react-native-keyboard-controller#1588). Answering them as
2599
+ /// ours would filter the typing through this field's rules and apply it to
2600
+ /// this field's text: the focused field would take no typing at all. So
2601
+ /// they go to the field's own view instead.
2602
+ fileprivate func rightfulOwner(of input: UIView) -> NitroInputView? {
2603
+ if input === field || input === editor { return nil }
2604
+ let owner = (input as? HiddenTextField)?.owner ?? (input as? HiddenTextView)?.owner
2605
+ return owner === self ? nil : owner
2606
+ }
2607
+ }
2608
+
2409
2609
  // MARK: - UITextViewDelegate
2410
2610
 
2411
2611
  extension NitroInputView: UITextViewDelegate {
2412
2612
  func textViewDidBeginEditing(_ textView: UITextView) {
2613
+ if let owner = rightfulOwner(of: textView) { return owner.textViewDidBeginEditing(textView) }
2413
2614
  textFieldDidBeginEditing(field)
2414
2615
  }
2415
2616
 
2416
2617
  func textViewDidEndEditing(_ textView: UITextView) {
2618
+ if let owner = rightfulOwner(of: textView) { return owner.textViewDidEndEditing(textView) }
2417
2619
  textFieldDidEndEditing(field)
2418
2620
  }
2419
2621
 
2420
2622
  func textViewDidChange(_ textView: UITextView) {
2623
+ if let owner = rightfulOwner(of: textView) { return owner.textViewDidChange(textView) }
2421
2624
  // Typing does not go through `text`'s setter, so the drawn placeholder
2422
2625
  // would stay under the first characters typed.
2423
2626
  textView.setNeedsDisplay()
@@ -2433,11 +2636,15 @@ extension NitroInputView: UITextViewDelegate {
2433
2636
  }
2434
2637
 
2435
2638
  func textViewDidChangeSelection(_ textView: UITextView) {
2639
+ if let owner = rightfulOwner(of: textView) { return owner.textViewDidChangeSelection(textView) }
2436
2640
  guard !isSettingText else { return }
2437
2641
  reportSelection()
2438
2642
  }
2439
2643
 
2440
2644
  func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
2645
+ if let owner = rightfulOwner(of: textView) {
2646
+ return owner.textView(textView, shouldChangeTextIn: range, replacementText: text)
2647
+ }
2441
2648
  // The return key arrives as a lone line break. Only that one is the key:
2442
2649
  // a pasted line break is text, and goes in whatever the submit behaviour.
2443
2650
  guard text == "\n", (textView as? HiddenTextView)?.isPasting != true else { return true }
@@ -2451,6 +2658,9 @@ extension NitroInputView: UITextViewDelegate {
2451
2658
  extension NitroInputView: UITextFieldDelegate {
2452
2659
 
2453
2660
  func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
2661
+ if let owner = rightfulOwner(of: textField) {
2662
+ return owner.textField(textField, shouldChangeCharactersIn: range, replacementString: string)
2663
+ }
2454
2664
  // Like React Native's `onKeyPress`: fires before the text changes, with
2455
2665
  // 'Backspace' for a deletion and the inserted string otherwise.
2456
2666
  if worklets.onKeyPress != 0 {
@@ -2482,6 +2692,19 @@ extension NitroInputView: UITextFieldDelegate {
2482
2692
  // Without a transform or a length limit the field edits itself (keeps
2483
2693
  // marked text / autocorrect intact); `fieldEditingChanged` reports it.
2484
2694
  guard worklets.transform != 0 || format.maxLength > 0, let swiftRange = Range(range, in: current) else { return true }
2695
+ // Mid-composition the marked text is the IME's: replacing it, or holding
2696
+ // its unconverted letters against `maxLength`, loses the composition
2697
+ // (react-native#56463, #52552). Both apply once it is committed.
2698
+ if let marked = textField.markedTextRange {
2699
+ if composition == nil {
2700
+ let from = textField.offset(from: textField.beginningOfDocument, to: marked.start)
2701
+ let to = textField.offset(from: textField.beginningOfDocument, to: marked.end)
2702
+ var base = current
2703
+ if let markedRange = Range(NSRange(location: from, length: to - from), in: base) { base.removeSubrange(markedRange) }
2704
+ composition = (base, Self.codePointOffset(in: current, utf16: from))
2705
+ }
2706
+ return true
2707
+ }
2485
2708
  var replacement = string
2486
2709
  if format.maxLength > 0 {
2487
2710
  // Keep as much of the replacement as fits (a paste), or nothing.
@@ -2554,6 +2777,23 @@ extension NitroInputView: UITextFieldDelegate {
2554
2777
  }
2555
2778
 
2556
2779
  func textFieldDidBeginEditing(_ textField: UITextField) {
2780
+ if let owner = rightfulOwner(of: textField) { return owner.textFieldDidBeginEditing(textField) }
2781
+ let resumed = withheldBlur
2782
+ withheldBlur = false
2783
+ beganInTransition = hostViewController?.transitionCoordinator != nil
2784
+ if !resumed, let coordinator = hostViewController?.transitionCoordinator {
2785
+ holdsFocusThroughTransition = true
2786
+ coordinator.animate(alongsideTransition: nil) { [weak self] _ in self?.holdsFocusThroughTransition = false }
2787
+ }
2788
+ if resumed {
2789
+ // UIKit giving the focus back that its own transition took away a moment
2790
+ // ago: to JS the field never lost it, so nothing is sent.
2791
+ DispatchQueue.main.async { [weak self] in self?.announceSelectionToDelegate() }
2792
+ if contentOverflows { render() }
2793
+ updateCaret(restartBlink: true)
2794
+ if wantsFrameDrawing { layoutFrame(animated: false) }
2795
+ return
2796
+ }
2557
2797
  // keyboard-controller puts its own delegate in front of ours a turn after
2558
2798
  // editing begins, and its KeyboardAwareScrollView waits for a selection
2559
2799
  // event from the newly focused field before it scrolls. A tap or Next
@@ -2564,7 +2804,15 @@ extension NitroInputView: UITextFieldDelegate {
2564
2804
  DispatchQueue.main.async { [weak self] in self?.announceSelectionToDelegate() }
2565
2805
  }
2566
2806
  if traits.clearTextOnFocus {
2807
+ selectionForFocus = nil
2567
2808
  setText("", reason: .user)
2809
+ } else if let (start, end) = selectionForFocus, !traits.selectTextOnFocus {
2810
+ // In the next runloop turn, after UIKit has put its own caret down.
2811
+ selectionForFocus = nil
2812
+ DispatchQueue.main.async { [weak self] in
2813
+ guard let self, self.editor.isFirstResponder else { return }
2814
+ self.setSelection(start: start, end: end)
2815
+ }
2568
2816
  } else if traits.selectTextOnFocus {
2569
2817
  // In the next runloop turn: UIKit sets its own selection as it begins.
2570
2818
  DispatchQueue.main.async { [weak self] in
@@ -2582,9 +2830,49 @@ extension NitroInputView: UITextFieldDelegate {
2582
2830
  }
2583
2831
 
2584
2832
  func textFieldDidEndEditing(_ textField: UITextField) {
2833
+ if let owner = rightfulOwner(of: textField) { return owner.textFieldDidEndEditing(textField) }
2585
2834
  if window != nil { endedEditingAt = CACurrentMediaTime() }
2586
2835
  if contentOverflows { render() }
2587
2836
  updateCaret()
2837
+ // A field that took focus as its screen came in (`autoFocus`) is resigned
2838
+ // by the push itself when it has no slide (`animation: 'none'`, 'fade',
2839
+ // 'simple_push': UINavigationController ends editing in the incoming view)
2840
+ // and handed first responder back as the push completes. Sent as it
2841
+ // happens, that is an onBlur and a second onFocus for a field the user
2842
+ // never left (react-navigation#11643). So the blur waits for the
2843
+ // transition: gone for good by then, it is sent; given back, it never was.
2844
+ if beganInTransition, let window, let coordinator = hostViewController?.transitionCoordinator {
2845
+ withheldBlur = true
2846
+ // Keep the keyboard up across the gap, or it starts to close and comes
2847
+ // back when the push hands the focus back (react-navigation#11626).
2848
+ if traits.showSoftInputOnFocus, KeyboardHandoff.shared.keyboardVisible {
2849
+ KeyboardHandoff.shared.hold(like: editor, in: window, for: 1000)
2850
+ }
2851
+ coordinator.animate(alongsideTransition: nil) { [weak self] _ in
2852
+ DispatchQueue.main.async { self?.releaseWithheldBlur() }
2853
+ }
2854
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in self?.releaseWithheldBlur() }
2855
+ if wantsFrameDrawing { layoutFrame(animated: true) }
2856
+ return
2857
+ }
2858
+ beganInTransition = false
2859
+ emitBlur()
2860
+ if wantsFrameDrawing { layoutFrame(animated: true) }
2861
+ }
2862
+
2863
+ /// Sends a blur held back during a transition, unless the field has the
2864
+ /// focus again.
2865
+ private func releaseWithheldBlur() {
2866
+ guard withheldBlur else { return }
2867
+ withheldBlur = false
2868
+ beganInTransition = false
2869
+ guard !editor.isFirstResponder else { return }
2870
+ // Nothing took the focus back: let a keyboard held for it go.
2871
+ if KeyboardHandoff.shared.isHolding { KeyboardHandoff.shared.letGo() }
2872
+ emitBlur()
2873
+ }
2874
+
2875
+ private func emitBlur() {
2588
2876
  if worklets.onFocusChange != 0 {
2589
2877
  margelo.nitro.nitroinput.nitroinputworklets.runFocusChange(Int32(worklets.onFocusChange), false, std.string(text))
2590
2878
  }
@@ -2593,10 +2881,10 @@ extension NitroInputView: UITextFieldDelegate {
2593
2881
  }
2594
2882
  onFocusChange?(false)
2595
2883
  onEndEditing?(text)
2596
- if wantsFrameDrawing { layoutFrame(animated: true) }
2597
2884
  }
2598
2885
 
2599
2886
  func textFieldDidChangeSelection(_ textField: UITextField) {
2887
+ if let owner = rightfulOwner(of: textField) { return owner.textFieldDidChangeSelection(textField) }
2600
2888
  guard !isSettingText else { return }
2601
2889
  // A caret move alone does not re-render; when the content is wider than
2602
2890
  // the view the scroll offset has to follow it.
@@ -2606,6 +2894,7 @@ extension NitroInputView: UITextFieldDelegate {
2606
2894
  }
2607
2895
 
2608
2896
  func textFieldShouldReturn(_ textField: UITextField) -> Bool {
2897
+ if let owner = rightfulOwner(of: textField) { return owner.textFieldShouldReturn(textField) }
2609
2898
  handleReturnKey()
2610
2899
  return false
2611
2900
  }
@@ -3055,6 +3344,8 @@ final class KeyboardHandoff {
3055
3344
  private var holder: UITextField?
3056
3345
  private var release: DispatchWorkItem?
3057
3346
  private var endObserver: NSObjectProtocol?
3347
+ /// Which hold is running, so a check on an older one leaves this one alone.
3348
+ private(set) var currentHold = 0
3058
3349
  /// Whether the system keyboard is up or on its way up.
3059
3350
  private(set) var keyboardVisible = false
3060
3351
 
@@ -3072,7 +3363,8 @@ final class KeyboardHandoff {
3072
3363
 
3073
3364
  /// Takes the keyboard from `editor` (the leaving field's system field) for up
3074
3365
  /// to `milliseconds`.
3075
- func hold(like editor: UIView, in window: UIWindow, for milliseconds: Double) {
3366
+ @discardableResult
3367
+ func hold(like editor: UIView, in window: UIWindow, for milliseconds: Double) -> Int? {
3076
3368
  letGo()
3077
3369
  let box = UIView(frame: CGRect(x: -1000, y: -1000, width: 1, height: 1))
3078
3370
  box.tag = -1
@@ -3102,10 +3394,14 @@ final class KeyboardHandoff {
3102
3394
  field.inputAccessoryView = editor.inputAccessoryView
3103
3395
  box.addSubview(field)
3104
3396
  window.addSubview(box)
3105
- guard field.becomeFirstResponder() else {
3397
+ NitroInputView.claimInProgress = true
3398
+ let held = field.becomeFirstResponder()
3399
+ NitroInputView.claimInProgress = false
3400
+ guard held else {
3106
3401
  box.removeFromSuperview()
3107
- return
3402
+ return nil
3108
3403
  }
3404
+ currentHold += 1
3109
3405
  container = box
3110
3406
  holder = field
3111
3407
  // Another field took the keyboard: the hold is over.
@@ -3118,6 +3414,7 @@ final class KeyboardHandoff {
3118
3414
  let item = DispatchWorkItem { [weak self] in self?.letGo() }
3119
3415
  release = item
3120
3416
  DispatchQueue.main.asyncAfter(deadline: .now() + milliseconds / 1000, execute: item)
3417
+ return currentHold
3121
3418
  }
3122
3419
 
3123
3420
  /// Nothing claimed the keyboard in time, or `Keyboard.dismiss()`: let it hide.
@@ -198,7 +198,7 @@ function warnIncompatible(what) {
198
198
  * Like a `TextInput`, it takes its width from its parent; `autoWidth` sizes
199
199
  * it to its content instead, and is on by default when the text reflows.
200
200
  */
201
- exports.NitroInput = (0, react_1.forwardRef)(function NitroInput({ value, defaultValue, mode, fractionDigits, maxIntegerDigits, groupingSeparator, decimalSeparator, prefix, suffix, prefixFontSize, suffixFontSize, affixAlign, signPlacement, prefixAlign, suffixAlign, letterSpacing, prefixSpacing, suffixSpacing, prefixOffset, suffixOffset, format, placeholder, placeholderTextColor, duration, easing, bounce, effect, fontSize, lineHeight, fontWeight, fontFamily, color, textAlign, cursorColor, selectionColor, caretHidden, adjustsFontSizeToFit, minimumFontScale, allowFontScaling, maxFontSizeMultiplier, variant, label, labelBehavior, labelColor, labelFocusedColor, labelFontSize, strokeColor, focusedStrokeColor, strokeWidth, cornerRadius, fillColor, keyboardType, inputMode, enterKeyHint, mask, maskNotations, maskAutocomplete, maskAutoSkip, maskAffinityFormats, maskAffinityStrategy, maskTextCase, maskCharacterMap, maskSlotPlaceholder, keepPlaceholder, returnKeyType, autoCapitalize, autoCorrect, editable, multiline, numberOfLines, rows, textAlignVertical, scrollEnabled, autoFocus, transition, autoWidth: autoWidthProp, submitBehavior, blurOnSubmit, secureTextEntry, keyboardAppearance, textContentType, autoComplete, enablesReturnKeyAutomatically, showSoftInputOnFocus, selectTextOnFocus, clearTextOnFocus, keyboardHandoffMs, returnKeyBar, contextMenuHidden, spellCheck, readOnly, selection, onEndEditing, onSelectionChange, onKeyPress, maxLength, transform, onChangeText, onChange, onChangeValue, onChangeMask, onFocus, onBlur, onSubmitEditing, onNativeRef, style, ...viewProps }, ref) {
201
+ exports.NitroInput = (0, react_1.forwardRef)(function NitroInput({ value, defaultValue, mode, fractionDigits, maxIntegerDigits, groupingSeparator, decimalSeparator, prefix, suffix, prefixFontSize, suffixFontSize, affixAlign, signPlacement, prefixAlign, suffixAlign, letterSpacing, prefixSpacing, suffixSpacing, prefixOffset, suffixOffset, format, placeholder, placeholderTextColor, duration, easing, bounce, effect, fontSize, lineHeight, fontWeight, fontFamily, color, textAlign, cursorColor, selectionColor, caretHidden, adjustsFontSizeToFit, minimumFontScale, allowFontScaling, maxFontSizeMultiplier, variant, label, labelBehavior, labelColor, labelFocusedColor, labelFontSize, strokeColor, focusedStrokeColor, strokeWidth, cornerRadius, fillColor, keyboardType, inputMode, enterKeyHint, mask, maskNotations, maskAutocomplete, maskAutoSkip, maskAffinityFormats, maskAffinityStrategy, maskTextCase, maskCharacterMap, maskSlotPlaceholder, keepPlaceholder, returnKeyType, autoCapitalize, autoCorrect, editable, multiline, numberOfLines, rows, textAlignVertical, scrollEnabled, autoFocus, transition, autoWidth: autoWidthProp, submitBehavior, blurOnSubmit, secureTextEntry, keyboardAppearance, textContentType, autoComplete, enablesReturnKeyAutomatically, showSoftInputOnFocus, selectTextOnFocus, clearTextOnFocus, keyboardHandoffMs, returnKeyBar, contextMenuHidden, spellCheck, readOnly, selection, onEndEditing, onSelectionChange, onKeyPress, maxLength, transform, onChangeText, onChange, onChangeValue, onChangeMask, onFocus, onBlur, focusedValue, onSubmitEditing, onNativeRef, style, ...viewProps }, ref) {
202
202
  const nativeRef = (0, react_1.useRef)(null);
203
203
  // `keyboardHandoffMs`: hand the keyboard off while this field still has it.
204
204
  // A layout-effect cleanup runs in React's commit, so the native call is
@@ -270,7 +270,7 @@ exports.NitroInput = (0, react_1.forwardRef)(function NitroInput({ value, defaul
270
270
  const onChangeValueId = useWorkletId(onChangeValueWorklet, worklets_1.registerCallback);
271
271
  // Marking any of these `'worklet'` moves it to the UI thread; the JS
272
272
  // handler is then skipped, exactly as `onChangeText` already worked.
273
- const onFocusId = useWorkletPairId((0, worklets_1.isWorklet)(onFocus) ? onFocus : undefined, (0, worklets_1.isWorklet)(onBlur) ? onBlur : undefined, worklets_1.registerFocusChange);
273
+ const onFocusId = useFocusWorkletId((0, worklets_1.isWorklet)(onFocus) ? onFocus : undefined, (0, worklets_1.isWorklet)(onBlur) ? onBlur : undefined, focusedValue);
274
274
  const onSelectionChangeId = useWorkletId((0, worklets_1.isWorklet)(onSelectionChange) ? onSelectionChange : undefined, worklets_1.registerSelectionChange);
275
275
  const onSubmitEditingId = useWorkletId((0, worklets_1.isWorklet)(onSubmitEditing) ? onSubmitEditing : undefined, worklets_1.registerTextEvent);
276
276
  const onEndEditingId = useWorkletId((0, worklets_1.isWorklet)(onEndEditing) ? onEndEditing : undefined, worklets_1.registerTextEvent);
@@ -680,16 +680,27 @@ function useWorkletId(fn, register) {
680
680
  return id;
681
681
  }
682
682
  /**
683
- * The same, for the focus pair: native reports one focus change, so the two
684
- * handlers share an id and the wrapper picks between them.
683
+ * The same, for focus: native reports one focus change, so the two handlers
684
+ * and `focusedValue` share an id and the wrapper picks between them.
685
+ *
686
+ * Registered while rendering, not in an effect: an `autoFocus` field takes
687
+ * focus as its view attaches, which can come before this component's effects
688
+ * run, and a focus change for an id that is not registered yet is dropped -
689
+ * `focusedValue` would miss the field's first focus. The registration is
690
+ * synchronous on the UI runtime, so it is there before the view is.
685
691
  */
686
- function useWorkletPairId(onFocus, onBlur, register) {
687
- const id = (0, react_1.useMemo)(() => (onFocus || onBlur ? (0, worklets_1.allocateWorkletId)() : 0), [onFocus, onBlur]);
692
+ function useFocusWorkletId(onFocus, onBlur, focusedValue) {
693
+ const id = (0, react_1.useMemo)(() => {
694
+ if (!onFocus && !onBlur && !focusedValue)
695
+ return 0;
696
+ const allocated = (0, worklets_1.allocateWorkletId)();
697
+ (0, worklets_1.registerFocusChange)(onFocus, onBlur, allocated, focusedValue);
698
+ return allocated;
699
+ }, [onFocus, onBlur, focusedValue]);
688
700
  (0, react_1.useEffect)(() => {
689
701
  if (id === 0)
690
702
  return;
691
- register(onFocus, onBlur, id);
692
703
  return () => (0, worklets_1.unregisterWorklet)(id);
693
- }, [id, onFocus, onBlur, register]);
704
+ }, [id]);
694
705
  return id;
695
706
  }
@@ -153,15 +153,19 @@ function registerCallback(callback, id) {
153
153
  * The event is the one the JS handlers get, minus `target`: a react tag is a
154
154
  * JS-thread notion and there is nothing on the UI runtime to ask for it.
155
155
  */
156
- function registerFocusChange(onFocus, onBlur, id) {
156
+ function registerFocusChange(onFocus, onBlur, id, focused) {
157
157
  if (id === 0 || !ensureWorkletsInstalled())
158
158
  return;
159
159
  const worklets = loadWorklets();
160
160
  worklets.executeOnUIRuntimeSync(() => {
161
161
  'worklet';
162
- const wrapper = (focused, text) => {
163
- const event = { text, target: 0, eventCount: 0, nativeEvent: { text, target: 0, eventCount: 0 } };
162
+ const wrapper = (isFocused, text) => {
164
163
  if (focused)
164
+ focused.value = isFocused;
165
+ if (!onFocus && !onBlur)
166
+ return;
167
+ const event = { text, target: 0, eventCount: 0, nativeEvent: { text, target: 0, eventCount: 0 } };
168
+ if (isFocused)
165
169
  onFocus?.(event);
166
170
  else
167
171
  onBlur?.(event);
@@ -159,7 +159,7 @@ function warnIncompatible(what) {
159
159
  * Like a `TextInput`, it takes its width from its parent; `autoWidth` sizes
160
160
  * it to its content instead, and is on by default when the text reflows.
161
161
  */
162
- export const NitroInput = forwardRef(function NitroInput({ value, defaultValue, mode, fractionDigits, maxIntegerDigits, groupingSeparator, decimalSeparator, prefix, suffix, prefixFontSize, suffixFontSize, affixAlign, signPlacement, prefixAlign, suffixAlign, letterSpacing, prefixSpacing, suffixSpacing, prefixOffset, suffixOffset, format, placeholder, placeholderTextColor, duration, easing, bounce, effect, fontSize, lineHeight, fontWeight, fontFamily, color, textAlign, cursorColor, selectionColor, caretHidden, adjustsFontSizeToFit, minimumFontScale, allowFontScaling, maxFontSizeMultiplier, variant, label, labelBehavior, labelColor, labelFocusedColor, labelFontSize, strokeColor, focusedStrokeColor, strokeWidth, cornerRadius, fillColor, keyboardType, inputMode, enterKeyHint, mask, maskNotations, maskAutocomplete, maskAutoSkip, maskAffinityFormats, maskAffinityStrategy, maskTextCase, maskCharacterMap, maskSlotPlaceholder, keepPlaceholder, returnKeyType, autoCapitalize, autoCorrect, editable, multiline, numberOfLines, rows, textAlignVertical, scrollEnabled, autoFocus, transition, autoWidth: autoWidthProp, submitBehavior, blurOnSubmit, secureTextEntry, keyboardAppearance, textContentType, autoComplete, enablesReturnKeyAutomatically, showSoftInputOnFocus, selectTextOnFocus, clearTextOnFocus, keyboardHandoffMs, returnKeyBar, contextMenuHidden, spellCheck, readOnly, selection, onEndEditing, onSelectionChange, onKeyPress, maxLength, transform, onChangeText, onChange, onChangeValue, onChangeMask, onFocus, onBlur, onSubmitEditing, onNativeRef, style, ...viewProps }, ref) {
162
+ export const NitroInput = forwardRef(function NitroInput({ value, defaultValue, mode, fractionDigits, maxIntegerDigits, groupingSeparator, decimalSeparator, prefix, suffix, prefixFontSize, suffixFontSize, affixAlign, signPlacement, prefixAlign, suffixAlign, letterSpacing, prefixSpacing, suffixSpacing, prefixOffset, suffixOffset, format, placeholder, placeholderTextColor, duration, easing, bounce, effect, fontSize, lineHeight, fontWeight, fontFamily, color, textAlign, cursorColor, selectionColor, caretHidden, adjustsFontSizeToFit, minimumFontScale, allowFontScaling, maxFontSizeMultiplier, variant, label, labelBehavior, labelColor, labelFocusedColor, labelFontSize, strokeColor, focusedStrokeColor, strokeWidth, cornerRadius, fillColor, keyboardType, inputMode, enterKeyHint, mask, maskNotations, maskAutocomplete, maskAutoSkip, maskAffinityFormats, maskAffinityStrategy, maskTextCase, maskCharacterMap, maskSlotPlaceholder, keepPlaceholder, returnKeyType, autoCapitalize, autoCorrect, editable, multiline, numberOfLines, rows, textAlignVertical, scrollEnabled, autoFocus, transition, autoWidth: autoWidthProp, submitBehavior, blurOnSubmit, secureTextEntry, keyboardAppearance, textContentType, autoComplete, enablesReturnKeyAutomatically, showSoftInputOnFocus, selectTextOnFocus, clearTextOnFocus, keyboardHandoffMs, returnKeyBar, contextMenuHidden, spellCheck, readOnly, selection, onEndEditing, onSelectionChange, onKeyPress, maxLength, transform, onChangeText, onChange, onChangeValue, onChangeMask, onFocus, onBlur, focusedValue, onSubmitEditing, onNativeRef, style, ...viewProps }, ref) {
163
163
  const nativeRef = useRef(null);
164
164
  // `keyboardHandoffMs`: hand the keyboard off while this field still has it.
165
165
  // A layout-effect cleanup runs in React's commit, so the native call is
@@ -231,7 +231,7 @@ export const NitroInput = forwardRef(function NitroInput({ value, defaultValue,
231
231
  const onChangeValueId = useWorkletId(onChangeValueWorklet, registerCallback);
232
232
  // Marking any of these `'worklet'` moves it to the UI thread; the JS
233
233
  // handler is then skipped, exactly as `onChangeText` already worked.
234
- const onFocusId = useWorkletPairId(isWorklet(onFocus) ? onFocus : undefined, isWorklet(onBlur) ? onBlur : undefined, registerFocusChange);
234
+ const onFocusId = useFocusWorkletId(isWorklet(onFocus) ? onFocus : undefined, isWorklet(onBlur) ? onBlur : undefined, focusedValue);
235
235
  const onSelectionChangeId = useWorkletId(isWorklet(onSelectionChange) ? onSelectionChange : undefined, registerSelectionChange);
236
236
  const onSubmitEditingId = useWorkletId(isWorklet(onSubmitEditing) ? onSubmitEditing : undefined, registerTextEvent);
237
237
  const onEndEditingId = useWorkletId(isWorklet(onEndEditing) ? onEndEditing : undefined, registerTextEvent);
@@ -641,16 +641,27 @@ function useWorkletId(fn, register) {
641
641
  return id;
642
642
  }
643
643
  /**
644
- * The same, for the focus pair: native reports one focus change, so the two
645
- * handlers share an id and the wrapper picks between them.
644
+ * The same, for focus: native reports one focus change, so the two handlers
645
+ * and `focusedValue` share an id and the wrapper picks between them.
646
+ *
647
+ * Registered while rendering, not in an effect: an `autoFocus` field takes
648
+ * focus as its view attaches, which can come before this component's effects
649
+ * run, and a focus change for an id that is not registered yet is dropped -
650
+ * `focusedValue` would miss the field's first focus. The registration is
651
+ * synchronous on the UI runtime, so it is there before the view is.
646
652
  */
647
- function useWorkletPairId(onFocus, onBlur, register) {
648
- const id = useMemo(() => (onFocus || onBlur ? allocateWorkletId() : 0), [onFocus, onBlur]);
653
+ function useFocusWorkletId(onFocus, onBlur, focusedValue) {
654
+ const id = useMemo(() => {
655
+ if (!onFocus && !onBlur && !focusedValue)
656
+ return 0;
657
+ const allocated = allocateWorkletId();
658
+ registerFocusChange(onFocus, onBlur, allocated, focusedValue);
659
+ return allocated;
660
+ }, [onFocus, onBlur, focusedValue]);
649
661
  useEffect(() => {
650
662
  if (id === 0)
651
663
  return;
652
- register(onFocus, onBlur, id);
653
664
  return () => unregisterWorklet(id);
654
- }, [id, onFocus, onBlur, register]);
665
+ }, [id]);
655
666
  return id;
656
667
  }
@@ -141,15 +141,19 @@ export function registerCallback(callback, id) {
141
141
  * The event is the one the JS handlers get, minus `target`: a react tag is a
142
142
  * JS-thread notion and there is nothing on the UI runtime to ask for it.
143
143
  */
144
- export function registerFocusChange(onFocus, onBlur, id) {
144
+ export function registerFocusChange(onFocus, onBlur, id, focused) {
145
145
  if (id === 0 || !ensureWorkletsInstalled())
146
146
  return;
147
147
  const worklets = loadWorklets();
148
148
  worklets.executeOnUIRuntimeSync(() => {
149
149
  'worklet';
150
- const wrapper = (focused, text) => {
151
- const event = { text, target: 0, eventCount: 0, nativeEvent: { text, target: 0, eventCount: 0 } };
150
+ const wrapper = (isFocused, text) => {
152
151
  if (focused)
152
+ focused.value = isFocused;
153
+ if (!onFocus && !onBlur)
154
+ return;
155
+ const event = { text, target: 0, eventCount: 0, nativeEvent: { text, target: 0, eventCount: 0 } };
156
+ if (isFocused)
153
157
  onFocus?.(event);
154
158
  else
155
159
  onBlur?.(event);
@@ -3,6 +3,7 @@ import { type ColorValue, type TextStyle, type ViewProps } from 'react-native';
3
3
  import { type HybridRef } from 'react-native-nitro-modules';
4
4
  import type { NitroInputAffixAlign, NitroInputAutoCapitalize, NitroInputEasing, NitroInputEffect, NitroInputKeyboardAppearance, NitroInputKeyboardType, NitroInputLabelBehavior, NitroInputMethods, NitroInputMode, NitroInputProps as NativeNitroInputProps, NitroInputReturnKeyType, NitroInputSubmitBehavior, NitroInputTextAlign, NitroInputTextAlignVertical, NitroInputSignPlacement, NitroInputVariant, NitroInputNotation, NitroInputMaskAffinity, NitroInputTextCase } from './specs/NitroInput.nitro';
5
5
  import { type NitroInputSelection, type NitroInputTransform } from './worklets';
6
+ import type { SharedValueLike } from './useNitroInputState';
6
7
  import type { NumberFormat } from './NumberFormat';
7
8
  /** React Native's `inputMode`, the HTML-aligned alias for `keyboardType`. */
8
9
  export type InputMode = 'none' | 'text' | 'decimal' | 'numeric' | 'tel' | 'search' | 'email' | 'url';
@@ -439,6 +440,22 @@ export interface NitroInputProps extends Omit<ViewProps, 'children' | 'onFocus'
439
440
  * `({ text }) => …` reads better than `(e) => e.nativeEvent.text`.
440
441
  */
441
442
  onFocus?: (event: NitroInputFocusEvent) => void;
443
+ /**
444
+ * A shared value (Reanimated's `useSharedValue(false)`) the field keeps equal
445
+ * to whether it has focus, set on the UI thread the moment focus changes.
446
+ * `onFocus` / `onBlur` still run as usual. For focus styling that must not
447
+ * wait for JS: a border around the field and whatever sits beside it, an
448
+ * icon's tint, a label's colour. Needs `react-native-worklets`.
449
+ *
450
+ * ```tsx
451
+ * const focused = useSharedValue(false)
452
+ * const ring = useAnimatedStyle(() => ({ borderColor: focused.value ? '#2563eb' : 'transparent' }))
453
+ * <Animated.View style={[styles.row, ring]}>
454
+ * <Icon /><NitroInput focusedValue={focused} onFocus={track} /><ClearButton />
455
+ * </Animated.View>
456
+ * ```
457
+ */
458
+ focusedValue?: SharedValueLike<boolean>;
442
459
  /** Blurred. Same event as {@link NitroInputProps.onFocus}. */
443
460
  onBlur?: (event: NitroInputFocusEvent) => void;
444
461
  /** The return key was pressed. */
@@ -103,7 +103,9 @@ export declare function registerCallback(callback: (arg: never) => void, id: num
103
103
  * The event is the one the JS handlers get, minus `target`: a react tag is a
104
104
  * JS-thread notion and there is nothing on the UI runtime to ask for it.
105
105
  */
106
- export declare function registerFocusChange(onFocus: ((event: WorkletFocusEvent) => void) | undefined, onBlur: ((event: WorkletFocusEvent) => void) | undefined, id: number): void;
106
+ export declare function registerFocusChange(onFocus: ((event: WorkletFocusEvent) => void) | undefined, onBlur: ((event: WorkletFocusEvent) => void) | undefined, id: number, focused?: {
107
+ value: boolean;
108
+ }): void;
107
109
  /** Registers an `onSelectionChange` worklet, given the two scalars native sends. */
108
110
  export declare function registerSelectionChange(handler: (event: WorkletSelectionEvent) => void, id: number): void;
109
111
  /** Registers an `onSubmitEditing` / `onEndEditing` worklet, given the text. */
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.5",
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",
@@ -54,7 +54,9 @@ import {
54
54
  unregisterWorklet,
55
55
  type NitroInputSelection,
56
56
  type NitroInputTransform,
57
+ type WorkletFocusEvent,
57
58
  } from './worklets'
59
+ import type { SharedValueLike } from './useNitroInputState'
58
60
  import { toNumericWeight, toProcessedColor } from './styleHelpers'
59
61
  import { formatProps } from './formatProps'
60
62
  import type { NumberFormat } from './NumberFormat'
@@ -644,6 +646,22 @@ export interface NitroInputProps extends Omit<ViewProps, 'children' | 'onFocus'
644
646
  * `({ text }) => …` reads better than `(e) => e.nativeEvent.text`.
645
647
  */
646
648
  onFocus?: (event: NitroInputFocusEvent) => void
649
+ /**
650
+ * A shared value (Reanimated's `useSharedValue(false)`) the field keeps equal
651
+ * to whether it has focus, set on the UI thread the moment focus changes.
652
+ * `onFocus` / `onBlur` still run as usual. For focus styling that must not
653
+ * wait for JS: a border around the field and whatever sits beside it, an
654
+ * icon's tint, a label's colour. Needs `react-native-worklets`.
655
+ *
656
+ * ```tsx
657
+ * const focused = useSharedValue(false)
658
+ * const ring = useAnimatedStyle(() => ({ borderColor: focused.value ? '#2563eb' : 'transparent' }))
659
+ * <Animated.View style={[styles.row, ring]}>
660
+ * <Icon /><NitroInput focusedValue={focused} onFocus={track} /><ClearButton />
661
+ * </Animated.View>
662
+ * ```
663
+ */
664
+ focusedValue?: SharedValueLike<boolean>
647
665
  /** Blurred. Same event as {@link NitroInputProps.onFocus}. */
648
666
  onBlur?: (event: NitroInputFocusEvent) => void
649
667
  /** The return key was pressed. */
@@ -822,6 +840,7 @@ export const NitroInput = forwardRef<NitroInputHandle, NitroInputProps>(
822
840
  onChangeMask,
823
841
  onFocus,
824
842
  onBlur,
843
+ focusedValue,
825
844
  onSubmitEditing,
826
845
  onNativeRef,
827
846
  style,
@@ -902,10 +921,10 @@ export const NitroInput = forwardRef<NitroInputHandle, NitroInputProps>(
902
921
  const onChangeValueId = useWorkletId(onChangeValueWorklet, registerCallback)
903
922
  // Marking any of these `'worklet'` moves it to the UI thread; the JS
904
923
  // handler is then skipped, exactly as `onChangeText` already worked.
905
- const onFocusId = useWorkletPairId(
924
+ const onFocusId = useFocusWorkletId(
906
925
  isWorklet(onFocus) ? (onFocus as never) : undefined,
907
926
  isWorklet(onBlur) ? (onBlur as never) : undefined,
908
- registerFocusChange
927
+ focusedValue
909
928
  )
910
929
  const onSelectionChangeId = useWorkletId(
911
930
  isWorklet(onSelectionChange) ? (onSelectionChange as never) : undefined,
@@ -1537,19 +1556,29 @@ function useWorkletId<T extends (...args: never[]) => unknown>(
1537
1556
  }
1538
1557
 
1539
1558
  /**
1540
- * The same, for the focus pair: native reports one focus change, so the two
1541
- * handlers share an id and the wrapper picks between them.
1559
+ * The same, for focus: native reports one focus change, so the two handlers
1560
+ * and `focusedValue` share an id and the wrapper picks between them.
1561
+ *
1562
+ * Registered while rendering, not in an effect: an `autoFocus` field takes
1563
+ * focus as its view attaches, which can come before this component's effects
1564
+ * run, and a focus change for an id that is not registered yet is dropped -
1565
+ * `focusedValue` would miss the field's first focus. The registration is
1566
+ * synchronous on the UI runtime, so it is there before the view is.
1542
1567
  */
1543
- function useWorkletPairId<T extends (...args: never[]) => unknown>(
1544
- onFocus: T | undefined,
1545
- onBlur: T | undefined,
1546
- register: (a: T | undefined, b: T | undefined, id: number) => void
1568
+ function useFocusWorkletId(
1569
+ onFocus: ((event: WorkletFocusEvent) => void) | undefined,
1570
+ onBlur: ((event: WorkletFocusEvent) => void) | undefined,
1571
+ focusedValue: SharedValueLike<boolean> | undefined
1547
1572
  ): number {
1548
- const id = useMemo(() => (onFocus || onBlur ? allocateWorkletId() : 0), [onFocus, onBlur])
1573
+ const id = useMemo(() => {
1574
+ if (!onFocus && !onBlur && !focusedValue) return 0
1575
+ const allocated = allocateWorkletId()
1576
+ registerFocusChange(onFocus, onBlur, allocated, focusedValue)
1577
+ return allocated
1578
+ }, [onFocus, onBlur, focusedValue])
1549
1579
  useEffect(() => {
1550
1580
  if (id === 0) return
1551
- register(onFocus, onBlur, id)
1552
1581
  return () => unregisterWorklet(id)
1553
- }, [id, onFocus, onBlur, register])
1582
+ }, [id])
1554
1583
  return id
1555
1584
  }
package/src/worklets.ts CHANGED
@@ -227,15 +227,18 @@ export function registerCallback(callback: (arg: never) => void, id: number): vo
227
227
  export function registerFocusChange(
228
228
  onFocus: ((event: WorkletFocusEvent) => void) | undefined,
229
229
  onBlur: ((event: WorkletFocusEvent) => void) | undefined,
230
- id: number
230
+ id: number,
231
+ focused?: { value: boolean }
231
232
  ): void {
232
233
  if (id === 0 || !ensureWorkletsInstalled()) return
233
234
  const worklets = loadWorklets()!
234
235
  worklets.executeOnUIRuntimeSync(() => {
235
236
  'worklet'
236
- const wrapper = (focused: boolean, text: string) => {
237
+ const wrapper = (isFocused: boolean, text: string) => {
238
+ if (focused) focused.value = isFocused
239
+ if (!onFocus && !onBlur) return
237
240
  const event = { text, target: 0, eventCount: 0, nativeEvent: { text, target: 0, eventCount: 0 } }
238
- if (focused) onFocus?.(event)
241
+ if (isFocused) onFocus?.(event)
239
242
  else onBlur?.(event)
240
243
  }
241
244
  globalThis.__nitroInputWorklets?.set(id, wrapper as (...args: never[]) => unknown)