react-native-nitro-input 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/README.md +45 -0
  3. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroInputView.kt +25 -4
  4. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputView.kt +170 -2
  5. package/android/src/main/java/com/margelo/nitro/nitroinput/UnmountHandoffs.kt +57 -0
  6. package/ios/HybridNitroInputView.swift +19 -4
  7. package/ios/NitroInputCommands.mm +10 -0
  8. package/ios/NitroInputView.swift +349 -13
  9. package/lib/commonjs/nitrogen/generated/shared/json/NitroInputViewConfig.json +2 -0
  10. package/lib/commonjs/src/NitroInput.js +103 -15
  11. package/lib/module/nitrogen/generated/shared/json/NitroInputViewConfig.json +2 -0
  12. package/lib/module/src/NitroInput.js +104 -16
  13. package/lib/typescript/src/NitroInput.d.ts +16 -0
  14. package/lib/typescript/src/specs/NitroInput.nitro.d.ts +22 -0
  15. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.cpp +22 -0
  16. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.hpp +5 -0
  17. package/nitrogen/generated/android/c++/views/JHybridNitroInputViewStateUpdater.cpp +10 -0
  18. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroInputViewSpec.kt +16 -0
  19. package/nitrogen/generated/ios/c++/HybridNitroInputViewSpecSwift.hpp +18 -0
  20. package/nitrogen/generated/ios/c++/views/HybridNitroInputViewComponent.mm +12 -0
  21. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec.swift +3 -0
  22. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec_cxx.swift +33 -0
  23. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.cpp +5 -0
  24. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.hpp +5 -0
  25. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.cpp +4 -0
  26. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.hpp +6 -0
  27. package/nitrogen/generated/shared/json/NitroInputViewConfig.json +2 -0
  28. package/package.json +1 -1
  29. package/src/NitroInput.tsx +117 -11
  30. package/src/specs/NitroInput.nitro.ts +22 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,88 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.3
4
+
5
+ - **`keyboardHandoffMs`**: when the focused field is popped or unmounted,
6
+ the keyboard stays up this long for the next field to take over (the
7
+ screen you return to, the next step's field), instead of dropping and
8
+ rising again. Both platforms; `Keyboard.dismiss()` ends the hold at once.
9
+ - **`focus()` on a field that is not on screen yet** (a screen navigated back
10
+ to, refocusing its field before it is shown again) now focuses it as soon
11
+ as it is, while the keyboard is still up. On Android this alone keeps the
12
+ keyboard up across a stack pop.
13
+ - **iOS number pads get a return key**: a field on the number, phone or
14
+ decimal pad with a `returnKeyType` set shows a bar above the keyboard with
15
+ that key ("Next", "Go", "Done"...), as `TextInput` does. The pads have no
16
+ return key of their own, so a form chained with Next stopped at its first
17
+ numeric field. The bar is the return key: `submitBehavior`,
18
+ `onSubmitEditing` and worklets run as for the real one.
19
+ - **`returnKeyBar`** (iOS, default `true`): `false` leaves a number pad
20
+ without the return key bar, for a screen whose own button rides the
21
+ keyboard (a sticky or morphing CTA) and would otherwise be doubled.
22
+ - **Fixed (iOS)**: coming back to a screen whose field had the keyboard, when
23
+ the field on the leaving screen used `keyboardHandoffMs`, left the keyboard
24
+ down: the stand-in held it, so UIKit had nothing to give back. The field
25
+ now takes the keyboard back itself, with the back animation.
26
+ - **Fixed (iOS)**: a multiline field kept drawing its placeholder under the
27
+ first characters typed.
28
+ - **iOS 26: no dark keyboard on the way back.** When you return to a screen
29
+ whose field had the keyboard, UIKit gives the field its focus back as the
30
+ transition starts, and iOS 26 then slides the keyboard in with the screen as
31
+ a flat dark snapshot. The field now takes its focus back once the screen has
32
+ settled, so the real keyboard rises from the bottom, as in the system apps
33
+ (Contacts). Focus the app asks for (`focus()`, `autoFocus`) is unchanged.
34
+ - **Fixed: `<Activity>`** (React 19.2). A hidden `<Activity>` deletes its
35
+ native views and creates new ones when shown again, so a NitroInput came
36
+ back with its first text (an uncontrolled field's text lived only
37
+ natively), and a handle kept from before hiding reached the pooled view,
38
+ which another field may have been given: `focus()` on a hidden field's
39
+ handle focused that other field. The text is now kept across hide and show,
40
+ and while hidden a field's handle does nothing (`focus()` / `blur()`) or
41
+ waits (`setText`); `getText()` returns the kept text. On Android, where
42
+ a hidden field keeps its view, the field takes it back when shown, and a
43
+ `focus()` asked for while the field is still hidden waits until it is
44
+ shown.
45
+ - **Fixed**: `Keyboard.dismiss()` right after a field with `keyboardHandoffMs`
46
+ unmounted, on a screen with no other field (a questionnaire's tap-only
47
+ question), waited for the hold to run out (about 0.4 s) before the keyboard
48
+ closed. It closes at once now.
49
+ - **Fixed (iOS)**: keyboard-controller's `KeyboardAwareScrollView` did not
50
+ scroll a field that got its focus back (the caret had not moved, so it got no
51
+ selection event and waited for one). The field now reports its selection
52
+ once editing begins.
53
+ - **Changed**: a controlled field whose parent keeps its `value` while the
54
+ user types (a rejected edit, a digits-only filter) puts the value back, as
55
+ `TextInput` does. It used to keep showing what was typed.
56
+ - **Fixed (Android)**: `keyboardHandoffMs` on a field that unmounts could lose
57
+ the race with the frame that removes it (about two runs in three on a
58
+ Galaxy A22), and the keyboard dropped anyway. The handoff now runs on the
59
+ UI thread just before Fabric applies that frame's view changes.
60
+ - **Docs**: "The keyboard across screens and lists" in the README: the
61
+ settings that make a NitroInput screen behave like the platform apps, back
62
+ navigation included (iOS gives the field its keyboard back as long as
63
+ native-stack's `keyboardHandlingEnabled` stays off).
64
+ - **Fixed (Android)**: a field on a screen react-native-screens covered and
65
+ uncovered came back still flagged as focused, and `focus()` did nothing.
66
+ - **Fixed (Android)**: keyboard-controller saw no focused input for a
67
+ NitroInput, so `KeyboardAwareScrollView` never scrolled to it.
68
+ - **Fixed (Android)**: changing `clearTextOnFocus` after mount had no effect.
69
+ - **Fixed (iOS)**: `KeyboardAwareScrollView` scrolled a reflowing field only
70
+ far enough to show the top of its line.
71
+ - **Fixed (iOS)**: a multiline field counted twice for keyboard-controller's
72
+ next / previous and its toolbar.
73
+ - **Fixed (iOS)**: React Native's `focus` / `blur` view commands now go
74
+ through the field's own `focus()` / `blur()` (retrying a declined focus).
75
+ - An on-device keyboard suite measures each of these: no keyboard hide when
76
+ focus moves, a field unmounts as the next autofocuses, a stack pops, a
77
+ search list filters under the field, or a scroll moves it out of sight.
78
+ The example app has an input lab (a search list and a form chained with
79
+ Next, each with NitroInput or TextInput), and
80
+ `example/e2e/keyboard-lab-android.sh` drives it with real touches over adb.
81
+ The lab also has a form with a sticky and a morphing CTA (keyboard-
82
+ controller), a push, a form sheet and a list of fields, and a scripted run
83
+ (`globalThis.__lab.run()`) that records keyboard-controller's events on a
84
+ device nothing can tap on.
85
+
3
86
  ## 0.3.2
4
87
 
5
88
  - **`keepPlaceholder`**: the rest of a mask's placeholder stays visible,
package/README.md CHANGED
@@ -412,6 +412,49 @@ place. Typing uses **caret matching**: the characters on either side of the
412
412
  caret keep their identity, so inserting a `9` into `12|34` slides `34` over
413
413
  rather than renumbering the columns.
414
414
 
415
+ ### The keyboard across screens and lists
416
+
417
+ Held against iOS Contacts and Samsung's Settings and Contacts, a NitroInput
418
+ screen behaves like theirs with these settings:
419
+
420
+ - **Coming back to a screen whose field had the keyboard**: on iOS the field
421
+ gets its focus and the keyboard back once the screen has settled (swipe-back
422
+ too), so the real keyboard rises from the bottom as in Contacts rather than
423
+ sliding in with the screen as iOS 26's dark snapshot; on Android the
424
+ keyboard stays down. Native-stack does both by itself
425
+ as long as `keyboardHandlingEnabled` stays off, its default. Turned on
426
+ (react-native-screens' `hideKeyboardOnSwipe`), it takes the focus away as
427
+ the screen starts to leave, and there is nothing to give back.
428
+ - **The keyboard's Next key**: `returnKeyType="next"` with
429
+ `submitBehavior="submit"`, and `onSubmitEditing` focusing the next field.
430
+ The keyboard stays up between fields. On iOS's number, phone and decimal
431
+ pads, which have no return key, the field shows a bar with that key.
432
+ - **Lists and forms**: `keyboardShouldPersistTaps="handled"`, so a tap on a
433
+ row works while the keyboard is up (React Native's default spends the first
434
+ tap on closing it), and `keyboardDismissMode="on-drag"` to close the
435
+ keyboard when the list is dragged.
436
+ - **A field that leaves while it has the keyboard** (its step replaced, a
437
+ screen popped back to one that focuses its own field): `keyboardHandoffMs`
438
+ keeps the keyboard up for the next field instead of dropping and raising it.
439
+ Coming back to a screen whose field had the keyboard still gives it back:
440
+ that field takes it over from the stand-in.
441
+ - **A button riding the keyboard** (keyboard-controller's
442
+ `KeyboardStickyView`): measured frame by frame on an iPhone 11 Pro and a
443
+ Galaxy A22, it follows the keyboard through opening, closing, a keyboard
444
+ that changes height between fields (text, email, number and phone pads, a
445
+ TextInput in between) and a push to a screen that focuses its own field,
446
+ the same with NitroInput as with TextInput. On a number pad, pass
447
+ `returnKeyBar={false}` when the screen's own button is the keyboard's
448
+ action, or iOS shows two.
449
+
450
+ ```tsx
451
+ <Stack.Navigator>{/* keyboardHandlingEnabled left off */}</Stack.Navigator>
452
+
453
+ <FlatList keyboardShouldPersistTaps="handled" keyboardDismissMode="on-drag" … />
454
+
455
+ <NitroInput returnKeyType="next" submitBehavior="submit" onSubmitEditing={() => next.current?.focus()} />
456
+ ```
457
+
415
458
  ## NitroInput props
416
459
 
417
460
  | Prop | Type | Default | Description |
@@ -491,6 +534,8 @@ rather than renumbering the columns.
491
534
  | `showSoftInputOnFocus` | `boolean` | `true` | `false` focuses, with the caret, but shows no keyboard. |
492
535
  | `selectTextOnFocus` | `boolean` | `false` | Select everything when the field gains focus. |
493
536
  | `clearTextOnFocus` | `boolean` | `false` | Empty the field when it gains focus. |
537
+ | `returnKeyBar` | `boolean` | `true` | iOS: on the number, phone and decimal pads, which have no return key, a bar over the keyboard with the `returnKeyType` key ("Next", "Done"…), as `TextInput` shows. `false` for a screen with its own button riding the keyboard. |
538
+ | `keyboardHandoffMs` | `number` | `0` | When the focused field is popped or unmounted, keep the keyboard up this long for the next field to take over, instead of it dropping and rising again. 300-500 covers a stack pop. |
494
539
  | `contextMenuHidden` | `boolean` | `false` | Hides the Cut / Copy / Paste menu. |
495
540
  | `editable` | `boolean` | `true` | |
496
541
  | `readOnly` | `boolean` | `false` | Alias of `editable={false}`, as on `TextInput`. |
@@ -241,6 +241,10 @@ class HybridNitroInputView(private val context: ThemedReactContext) : HybridNitr
241
241
  set(v) { field = v; markConfigDirty() }
242
242
  override var clearTextOnFocus: Boolean = false
243
243
  set(v) { field = v; markConfigDirty() }
244
+ // iOS only: Android's number pads have an action key of their own.
245
+ override var returnKeyBar: Boolean = true
246
+ override var keyboardHandoffMs: Double = 0.0
247
+ set(v) { field = v; markConfigDirty() }
244
248
  override var contextMenuHidden: Boolean = false
245
249
  set(v) { field = v; markConfigDirty() }
246
250
  override var spellCheck: Boolean = true
@@ -292,6 +296,15 @@ class HybridNitroInputView(private val context: ThemedReactContext) : HybridNitr
292
296
 
293
297
  override fun blur() = onMain { inputView.blur() }
294
298
 
299
+ override fun prepareForUnmount() {
300
+ if (Looper.myLooper() == Looper.getMainLooper()) {
301
+ inputView.handOffKeyboardIfFocused()
302
+ return
303
+ }
304
+ // Before the frame that removes the view (see UnmountHandoffs).
305
+ if (!UnmountHandoffs.request(context, inputView)) onMain { inputView.handOffKeyboardIfFocused() }
306
+ }
307
+
295
308
  override fun clear() = onMain {
296
309
  flushConfigIfNeeded()
297
310
  inputView.clear()
@@ -460,6 +473,8 @@ class HybridNitroInputView(private val context: ThemedReactContext) : HybridNitr
460
473
  showSoftInputOnFocus = true
461
474
  selectTextOnFocus = false
462
475
  clearTextOnFocus = false
476
+ keyboardHandoffMs = 0.0
477
+ returnKeyBar = true
463
478
  contextMenuHidden = false
464
479
  spellCheck = true
465
480
  selectionStart = -1.0
@@ -555,16 +570,21 @@ class HybridNitroInputView(private val context: ThemedReactContext) : HybridNitr
555
570
  }
556
571
 
557
572
  /**
558
- * The `text` / `mostRecentEventCount` handshake: a new `text` is applied only
559
- * once JS has seen every native edit (a stale count means the user typed
560
- * since, and the field already shows what they typed).
573
+ * The `text` / `mostRecentEventCount` handshake: `text` is applied only once
574
+ * JS has seen every native edit (a stale count means the user typed since,
575
+ * and the field already shows what they typed). Compared with what the field
576
+ * shows, not just the last value applied: a controlled parent that keeps its
577
+ * value while the user types (a rejected edit) puts its text back, as
578
+ * `TextInput` does; `applyText` leaves the field alone when the conformed
579
+ * value is already there. An uncontrolled field sends a count of 0, so its
580
+ * initial text is never re-applied over what the user typed.
561
581
  */
562
582
  private fun flushTextIfNeeded() {
563
583
  if (!textDirty) return
564
584
  textDirty = false
565
585
  val value = text
566
- if (lastAppliedText == value) return
567
586
  if (mostRecentEventCount < eventCount) return
587
+ if (lastAppliedText == value && inputView.text == value) return
568
588
  lastAppliedText = value
569
589
  inputView.applyText(value)
570
590
  cachedText = inputView.text
@@ -698,6 +718,7 @@ class HybridNitroInputView(private val context: ThemedReactContext) : HybridNitr
698
718
  NitroInputSubmitBehavior.NEWLINE -> NitroInputView.SubmitBehavior.NEWLINE
699
719
  },
700
720
  secureTextEntry = secureTextEntry,
721
+ keyboardHandoffMs = if (keyboardHandoffMs.isFinite()) keyboardHandoffMs.coerceAtLeast(0.0) else 0.0,
701
722
  autofillHint = autofillHintFor(textContentType),
702
723
  showSoftInputOnFocus = showSoftInputOnFocus,
703
724
  selectTextOnFocus = selectTextOnFocus,
@@ -183,6 +183,8 @@ class NitroInputView(context: Context) : FrameLayout(context) {
183
183
  val showSoftInputOnFocus: Boolean = true,
184
184
  val selectTextOnFocus: Boolean = false,
185
185
  val clearTextOnFocus: Boolean = false,
186
+ /** How long a focused field leaving the screen keeps the IME up for the next one; 0 is off. */
187
+ val keyboardHandoffMs: Double = 0.0,
186
188
  val contextMenuHidden: Boolean = false,
187
189
  val spellCheck: Boolean = true,
188
190
  /**
@@ -457,7 +459,23 @@ class NitroInputView(context: Context) : FrameLayout(context) {
457
459
  override fun onDestroyActionMode(mode: android.view.ActionMode?) {}
458
460
  }
459
461
 
460
- private val editText = HiddenEditText(context)
462
+ private val editText = HiddenEditText(context).apply {
463
+ // Its id mirrors the host's React tag (see `setId`); saved state would
464
+ // then restore the text by id, which the props own instead.
465
+ isSaveEnabled = false
466
+ }
467
+
468
+ /**
469
+ * The React tag, mirrored onto the focusable `EditText`: keyboard-controller
470
+ * identifies the focused input by that view's id, and without it sees none,
471
+ * so its KeyboardAwareScrollView never scrolls to this field.
472
+ */
473
+ override fun setId(id: Int) {
474
+ super.setId(id)
475
+ // `setId` can run from the superclass constructor, before `editText` exists.
476
+ @Suppress("SENSELESS_COMPARISON")
477
+ if (editText != null) editText.id = id
478
+ }
461
479
  private val overlay = object : View(context) {
462
480
  override fun onDraw(canvas: Canvas) {
463
481
  super.onDraw(canvas)
@@ -521,6 +539,14 @@ class NitroInputView(context: Context) : FrameLayout(context) {
521
539
  private var pendingSizeReport = false
522
540
  private var frameScheduled = false
523
541
  private var applying = false
542
+ /** Clearing a stale focus flag in `focus()`: not a blur anyone should hear of. */
543
+ private var resyncingFocus = false
544
+ /**
545
+ * A `focus()` asked for while the view was off the window (uptime ms it
546
+ * stays good until; 0 = none), as a screen that is navigated back to
547
+ * refocuses its field before react-native-screens puts it back.
548
+ */
549
+ private var pendingFocusUntil = 0L
524
550
  private var batchDepth = 0
525
551
  private var feedPending = false
526
552
  private var feedCaret = -1
@@ -580,10 +606,13 @@ class NitroInputView(context: Context) : FrameLayout(context) {
580
606
  defaultHighlightColor = editText.highlightColor
581
607
  editText.addTextChangedListener(Watcher())
582
608
  editText.setOnFocusChangeListener { _, focused ->
609
+ if (resyncingFocus) return@setOnFocusChangeListener
583
610
  restartBlink()
584
611
  syncLabelProgress(animated = true)
585
612
  syncFocusProgress(animated = true)
586
613
  if (focused) {
614
+ // This field took the keyboard over from a stand-in, if one held it.
615
+ KeyboardHandoff.claimed()
587
616
  if (keyboard.clearTextOnFocus) {
588
617
  clear()
589
618
  } else if (keyboard.selectTextOnFocus) {
@@ -988,6 +1017,11 @@ class NitroInputView(context: Context) : FrameLayout(context) {
988
1017
  editText.maxLines = 1
989
1018
  editText.minLines = 1
990
1019
  }
1020
+ // setSingleLine swaps the transformation the password input type installed
1021
+ // for a single-line one, and a plain field draws the EditText's own text.
1022
+ if (k.secureTextEntry) {
1023
+ editText.transformationMethod = android.text.method.PasswordTransformationMethod.getInstance()
1024
+ }
991
1025
  editText.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI or when (k.returnKeyType) {
992
1026
  ReturnKeyType.DEFAULT -> EditorInfo.IME_ACTION_UNSPECIFIED
993
1027
  ReturnKeyType.DONE -> EditorInfo.IME_ACTION_DONE
@@ -1182,7 +1216,32 @@ class NitroInputView(context: Context) : FrameLayout(context) {
1182
1216
 
1183
1217
  fun focus() {
1184
1218
  if (!keyboard.editable) return
1219
+ if (!isAttachedToWindow || !isShown) {
1220
+ // Off the window, or on it but hidden (a hidden <Activity>, or a
1221
+ // subtree shown in the same commit that asks for focus): an invisible
1222
+ // view cannot take focus. Honour it once the view is attached and shown.
1223
+ pendingFocusUntil = SystemClock.uptimeMillis() + 1000
1224
+ return
1225
+ }
1226
+ pendingFocusUntil = 0
1185
1227
  editText.isFocusableInTouchMode = true
1228
+ val focusedInWindow = editText.rootView?.findFocus()
1229
+ if (editText.isFocused && focusedInWindow !== editText) {
1230
+ // Flagged focused while another view has the window's focus: a screen
1231
+ // container (react-native-screens' ScreensFrameLayout) skips
1232
+ // `clearFocus()` while a screen is invisible mid-transition, so a field
1233
+ // on a screen that was covered comes back still flagged. `requestFocus()`
1234
+ // is a no-op on it then, and the IME ignores it. The view that really
1235
+ // has focus lets go first (clearing ours alone would cut its focus chain
1236
+ // and leave it flagged in turn), then the stale flag is dropped quietly.
1237
+ focusedInWindow?.clearFocus()
1238
+ resyncingFocus = true
1239
+ try {
1240
+ editText.clearFocus()
1241
+ } finally {
1242
+ resyncingFocus = false
1243
+ }
1244
+ }
1186
1245
  if (!editText.hasFocus()) editText.requestFocus()
1187
1246
  // `showSoftInputOnFocus: false` keeps focus and the caret but no keyboard;
1188
1247
  // the EditText honours it on its own, so only the explicit ask is guarded.
@@ -1223,10 +1282,26 @@ class NitroInputView(context: Context) : FrameLayout(context) {
1223
1282
  }
1224
1283
 
1225
1284
  fun blur() {
1226
- if (editText.hasFocus()) editText.clearFocus()
1285
+ pendingFocusUntil = 0
1286
+ if (!editText.hasFocus()) {
1287
+ // `Keyboard.dismiss()` while a field that just left the screen holds the
1288
+ // keyboard for the next one: nothing is focused, so let it go now.
1289
+ KeyboardHandoff.letGo()
1290
+ return
1291
+ }
1292
+ editText.clearFocus()
1227
1293
  inputMethodManager()?.hideSoftInputFromWindow(editText.windowToken, 0)
1228
1294
  }
1229
1295
 
1296
+ /**
1297
+ * About to be unmounted (`NitroInput` calls this before the view is removed):
1298
+ * hand the IME to a stand-in so it stays up for the next field to focus.
1299
+ */
1300
+ fun handOffKeyboardIfFocused() {
1301
+ if (keyboard.keyboardHandoffMs <= 0 || !keyboard.showSoftInputOnFocus || !editText.hasFocus()) return
1302
+ KeyboardHandoff.hold(editText, keyboard.keyboardHandoffMs)
1303
+ }
1304
+
1230
1305
  /** Empties the field, reflowing the characters away. */
1231
1306
  fun clear() = setProgrammatic("", notify = true)
1232
1307
 
@@ -1280,6 +1355,7 @@ class NitroInputView(context: Context) : FrameLayout(context) {
1280
1355
  */
1281
1356
  fun resetForRecycle() {
1282
1357
  worklets = Worklets()
1358
+ pendingFocusUntil = 0
1283
1359
  inputFrame = Frame()
1284
1360
  labelProgress = 0f
1285
1361
  notchProgress = 0f
@@ -1327,8 +1403,28 @@ class NitroInputView(context: Context) : FrameLayout(context) {
1327
1403
  restartBlink()
1328
1404
  syncAccessibilityFromHost()
1329
1405
  maybeAutoFocus()
1406
+ focusIfPending()
1330
1407
  }
1331
1408
 
1409
+ override fun onVisibilityChanged(changedView: View, visibility: Int) {
1410
+ super.onVisibilityChanged(changedView, visibility)
1411
+ if (isShown) focusIfPending()
1412
+ }
1413
+
1414
+ /** A `focus()` asked for while the view was off the window or hidden. */
1415
+ private fun focusIfPending() {
1416
+ 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())
1420
+ pendingFocusUntil = 0
1421
+ if (wanted) post { focus() }
1422
+ }
1423
+
1424
+ private fun imeVisible(): Boolean =
1425
+ androidx.core.view.ViewCompat.getRootWindowInsets(this)
1426
+ ?.isVisible(androidx.core.view.WindowInsetsCompat.Type.ime()) == true
1427
+
1332
1428
  override fun onDetachedFromWindow() {
1333
1429
  stopAnimation()
1334
1430
  removeCallbacks(blink)
@@ -2345,3 +2441,75 @@ class NitroInputView(context: Context) : FrameLayout(context) {
2345
2441
  private val ROLES = Role.values()
2346
2442
  }
2347
2443
  }
2444
+
2445
+ /**
2446
+ * Keeps the IME up while a focused field is removed (its screen popped or its
2447
+ * element unmounted), for the next field to take over.
2448
+ *
2449
+ * Android hides the IME when the focused editor is removed from the window,
2450
+ * and shows it again when the next field asks: a pop from one field's screen
2451
+ * back to another's drops the keyboard and raises it. Moving focus to another
2452
+ * editor keeps it up instead, so a 1x1 stand-in `EditText` configured like the
2453
+ * leaving field takes focus first; the next field to focus takes the IME from
2454
+ * it in place. If none does within the hold, the stand-in hides the IME.
2455
+ * It has no id, which keyboard-controller reads as "no focused input".
2456
+ */
2457
+ internal object KeyboardHandoff {
2458
+ private val handler = Handler(Looper.getMainLooper())
2459
+ private var holder: android.widget.EditText? = null
2460
+ private val timeout = Runnable { letGo() }
2461
+
2462
+ val isHolding: Boolean get() = holder != null
2463
+
2464
+ fun hold(from: android.widget.EditText, milliseconds: Double) {
2465
+ val content = from.rootView?.findViewById<android.view.ViewGroup>(android.R.id.content) ?: return
2466
+ drop()
2467
+ val field = android.widget.EditText(from.context).apply {
2468
+ inputType = from.inputType
2469
+ imeOptions = from.imeOptions
2470
+ alpha = 0f
2471
+ translationX = -10000f
2472
+ background = null
2473
+ isSaveEnabled = false
2474
+ isFocusableInTouchMode = true
2475
+ importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
2476
+ }
2477
+ content.addView(field, FrameLayout.LayoutParams(1, 1))
2478
+ if (!field.requestFocus()) {
2479
+ content.removeView(field)
2480
+ return
2481
+ }
2482
+ holder = field
2483
+ handler.postDelayed(timeout, milliseconds.toLong())
2484
+ }
2485
+
2486
+ /** A field took the IME over: the stand-in can go, without hiding it. */
2487
+ fun claimed() {
2488
+ val field = holder ?: return
2489
+ if (field.hasFocus()) return
2490
+ handler.removeCallbacks(timeout)
2491
+ holder = null
2492
+ // Not in the middle of the focus change that got us here.
2493
+ handler.post { (field.parent as? android.view.ViewGroup)?.removeView(field) }
2494
+ }
2495
+
2496
+ /** Nothing claimed the IME in time, or `Keyboard.dismiss()`: hide it. */
2497
+ fun letGo() {
2498
+ handler.removeCallbacks(timeout)
2499
+ val field = holder ?: return
2500
+ holder = null
2501
+ if (field.hasFocus()) {
2502
+ val imm = field.context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
2503
+ imm?.hideSoftInputFromWindow(field.windowToken, 0)
2504
+ field.clearFocus()
2505
+ }
2506
+ (field.parent as? android.view.ViewGroup)?.removeView(field)
2507
+ }
2508
+
2509
+ private fun drop() {
2510
+ handler.removeCallbacks(timeout)
2511
+ val field = holder ?: return
2512
+ holder = null
2513
+ (field.parent as? android.view.ViewGroup)?.removeView(field)
2514
+ }
2515
+ }
@@ -0,0 +1,57 @@
1
+ package com.margelo.nitro.nitroinput
2
+
3
+ import com.facebook.react.bridge.ReactContext
4
+ import com.facebook.react.bridge.UIManager
5
+ import com.facebook.react.bridge.UIManagerListener
6
+ import com.facebook.react.common.annotations.UnstableReactNativeAPI
7
+ import com.facebook.react.uimanager.UIManagerHelper
8
+ import com.facebook.react.uimanager.common.UIManagerType
9
+ import java.util.Collections
10
+ import java.util.IdentityHashMap
11
+ import java.util.concurrent.ConcurrentLinkedQueue
12
+
13
+ /**
14
+ * Runs `keyboardHandoffMs` handoffs on the UI thread right before Fabric
15
+ * applies the next batch of view changes.
16
+ *
17
+ * `NitroInput` asks for the handoff from React's commit, on the JS thread,
18
+ * ahead of the commit that removes the field. A message posted from there to
19
+ * the UI thread does not reliably get there first: the UI thread can already be
20
+ * in the frame that applies the removal (seen 42 ms late on a Galaxy A22), and
21
+ * a removed editor takes the IME with it. Fabric's `willMountItems` runs on the
22
+ * UI thread before any view in the batch is touched, so the field still has
23
+ * focus when the stand-in takes it over.
24
+ */
25
+ @OptIn(UnstableReactNativeAPI::class)
26
+ internal object UnmountHandoffs : UIManagerListener {
27
+ private val pending = ConcurrentLinkedQueue<NitroInputView>()
28
+ private val listeningTo = Collections.newSetFromMap(IdentityHashMap<UIManager, Boolean>())
29
+
30
+ /** Queues `view`'s handoff for the next batch; false when there is no Fabric UIManager to wait for. */
31
+ fun request(context: ReactContext, view: NitroInputView): Boolean {
32
+ val uiManager = UIManagerHelper.getUIManager(context, UIManagerType.FABRIC) ?: return false
33
+ synchronized(listeningTo) {
34
+ if (listeningTo.add(uiManager)) uiManager.addUIManagerEventListener(this)
35
+ }
36
+ pending.add(view)
37
+ return true
38
+ }
39
+
40
+ private fun drain() {
41
+ while (true) {
42
+ val view = pending.poll() ?: return
43
+ view.handOffKeyboardIfFocused()
44
+ }
45
+ }
46
+
47
+ override fun willMountItems(uiManager: UIManager) = drain()
48
+
49
+ // Every frame, mount items or not: a request whose batch never came still runs.
50
+ override fun didDispatchMountItems(uiManager: UIManager) = drain()
51
+
52
+ override fun willDispatchViewUpdates(uiManager: UIManager) {}
53
+
54
+ override fun didMountItems(uiManager: UIManager) {}
55
+
56
+ override fun didScheduleMountItems(uiManager: UIManager) {}
57
+ }
@@ -157,6 +157,8 @@ final class HybridNitroInputView: HybridNitroInputViewSpec, RecyclableView {
157
157
  var showSoftInputOnFocus: Bool = true { didSet { markConfigDirty() } }
158
158
  var selectTextOnFocus: Bool = false { didSet { markConfigDirty() } }
159
159
  var clearTextOnFocus: Bool = false { didSet { markConfigDirty() } }
160
+ var keyboardHandoffMs: Double = 0 { didSet { markConfigDirty() } }
161
+ var returnKeyBar: Bool = true { didSet { markConfigDirty() } }
160
162
  var contextMenuHidden: Bool = false { didSet { markConfigDirty() } }
161
163
  var spellCheck: Bool = true { didSet { markConfigDirty() } }
162
164
  var selectionStart: Double = -1 { didSet { markSelectionDirty() } }
@@ -195,6 +197,10 @@ final class HybridNitroInputView: HybridNitroInputViewSpec, RecyclableView {
195
197
  onMain { self.inputView.blur() }
196
198
  }
197
199
 
200
+ func prepareForUnmount() throws {
201
+ onMain { self.inputView.handOffKeyboardIfFocused() }
202
+ }
203
+
198
204
  func clear() throws {
199
205
  onMain {
200
206
  self.flushConfigIfNeeded()
@@ -364,6 +370,8 @@ final class HybridNitroInputView: HybridNitroInputViewSpec, RecyclableView {
364
370
  showSoftInputOnFocus = true
365
371
  selectTextOnFocus = false
366
372
  clearTextOnFocus = false
373
+ keyboardHandoffMs = 0
374
+ returnKeyBar = true
367
375
  contextMenuHidden = false
368
376
  spellCheck = true
369
377
  selectionStart = -1
@@ -436,17 +444,22 @@ final class HybridNitroInputView: HybridNitroInputViewSpec, RecyclableView {
436
444
  inputView.setSelection(start: start, end: end)
437
445
  }
438
446
 
439
- /// The `text` prop handshake: apply it when it differs from the last applied
440
- /// value and JS has seen every native edit (`mostRecentEventCount` caught up
441
- /// with the native count), like React Native's own `TextInput`.
447
+ /// The `text` prop handshake: once JS has seen every native edit
448
+ /// (`mostRecentEventCount` caught up with the native count), the field shows
449
+ /// `text`, like React Native's own `TextInput`. Compared with what the field
450
+ /// shows, not just the last value applied: a controlled parent that keeps
451
+ /// its value while the user types (a rejected edit) puts its text back.
452
+ /// `setText` leaves the field (and the caret) alone when the formatted
453
+ /// value is already what it shows. An uncontrolled field sends a count of 0,
454
+ /// so its initial text is never re-applied over what the user typed.
442
455
  private func applyTextIfNeeded() {
443
456
  guard textDirty else { return }
444
457
  textDirty = false
445
- guard text != lastAppliedText else { return }
446
458
  snapshotLock.lock()
447
459
  let nativeCount = snapshot.eventCount
448
460
  snapshotLock.unlock()
449
461
  guard mostRecentEventCount.isFinite, Int(mostRecentEventCount) >= nativeCount else { return }
462
+ guard text != lastAppliedText || text != inputView.text else { return }
450
463
  lastAppliedText = text
451
464
  inputView.setText(text, reason: .prop)
452
465
  }
@@ -583,6 +596,8 @@ final class HybridNitroInputView: HybridNitroInputViewSpec, RecyclableView {
583
596
  traits.showSoftInputOnFocus = showSoftInputOnFocus
584
597
  traits.selectTextOnFocus = selectTextOnFocus
585
598
  traits.clearTextOnFocus = clearTextOnFocus
599
+ traits.keyboardHandoffMs = keyboardHandoffMs.isFinite ? max(0, keyboardHandoffMs) : 0
600
+ traits.returnKeyBar = returnKeyBar
586
601
  traits.contextMenuHidden = contextMenuHidden
587
602
  traits.spellCheck = spellCheck && autoCorrect
588
603
 
@@ -50,6 +50,16 @@ static BOOL NitroInputEditorIsEditable(UIView *editor)
50
50
 
51
51
  - (void)handleCommand:(const NSString *)commandName args:(const NSArray *)args
52
52
  {
53
+ // The field's own focus()/blur(): they retry a declined focus, hold a focus
54
+ // asked for while the view has no window, and let a held keyboard go.
55
+ UIView *host = self.contentView;
56
+ SEL own = [(NSString *)commandName isEqualToString:@"focus"] ? NSSelectorFromString(@"nitroFocus")
57
+ : [(NSString *)commandName isEqualToString:@"blur"] ? NSSelectorFromString(@"nitroBlur")
58
+ : nil;
59
+ if (own != nil && [host respondsToSelector:own]) {
60
+ ((void (*)(id, SEL))[host methodForSelector:own])(host, own);
61
+ return;
62
+ }
53
63
  UIView *editor = NitroInputFindEditor(self.contentView);
54
64
  if (editor == nil) {
55
65
  return;