react-native-nitro-input 0.3.2 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/CHANGELOG.md +129 -0
  2. package/README.md +45 -0
  3. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroInputView.kt +25 -4
  4. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputView.kt +211 -3
  5. package/android/src/main/java/com/margelo/nitro/nitroinput/UnmountHandoffs.kt +57 -0
  6. package/ios/HybridNitroInputView.swift +19 -4
  7. package/ios/NitroInputCommands.mm +10 -0
  8. package/ios/NitroInputView.swift +585 -14
  9. package/lib/commonjs/nitrogen/generated/shared/json/NitroInputViewConfig.json +2 -0
  10. package/lib/commonjs/src/NitroInput.js +103 -15
  11. package/lib/module/nitrogen/generated/shared/json/NitroInputViewConfig.json +2 -0
  12. package/lib/module/src/NitroInput.js +104 -16
  13. package/lib/typescript/src/NitroInput.d.ts +16 -0
  14. package/lib/typescript/src/specs/NitroInput.nitro.d.ts +22 -0
  15. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.cpp +22 -0
  16. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.hpp +5 -0
  17. package/nitrogen/generated/android/c++/views/JHybridNitroInputViewStateUpdater.cpp +10 -0
  18. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroInputViewSpec.kt +16 -0
  19. package/nitrogen/generated/ios/c++/HybridNitroInputViewSpecSwift.hpp +18 -0
  20. package/nitrogen/generated/ios/c++/views/HybridNitroInputViewComponent.mm +12 -0
  21. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec.swift +3 -0
  22. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec_cxx.swift +33 -0
  23. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.cpp +5 -0
  24. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.hpp +5 -0
  25. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.cpp +4 -0
  26. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.hpp +6 -0
  27. package/nitrogen/generated/shared/json/NitroInputViewConfig.json +2 -0
  28. package/package.json +1 -1
  29. package/src/NitroInput.tsx +117 -11
  30. package/src/specs/NitroInput.nitro.ts +22 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,134 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.4
4
+
5
+ - **iOS: a focused field that took no typing** (with
6
+ react-native-keyboard-controller). keyboard-controller wraps the focused
7
+ field's delegate in one composite shared by every input and forwards to the
8
+ delegate it stored last; when focus moves faster than it re-wraps (a pushed
9
+ screen's `autoFocus` field, which the push's own `endEditing` then resigns),
10
+ a field's delegate calls reach another field
11
+ ([keyboard-controller#1588](https://github.com/kirillzyusko/react-native-keyboard-controller/issues/1588)).
12
+ The field looked focused, but every keystroke was checked against the
13
+ other field's rules and applied to it (a number field threw the letters
14
+ away). A NitroInput now hands a delegate call for another field to that
15
+ field, and puts its own delegate back before it starts editing.
16
+ - **`focus()` as a field mounts opens the keyboard even when it is down.**
17
+ A `focus()` that arrives before the view is on screen is held until it is,
18
+ and was then honoured only while the keyboard was still up: right for a
19
+ screen navigated back to (a keyboard dismissed on the way stays down), but
20
+ it also dropped `useEffect(() => ref.current?.focus(), [])` on a field
21
+ swapped in after one without a keyboard (a free-text question after a
22
+ multiple-choice one). A field that has never been on screen now takes the
23
+ focus it was asked for, as `autoFocus` does. Both platforms.
24
+ - **iOS: an `autoFocus` field on a screen pushed without a slide**
25
+ (`animation: 'none'`, `'fade'`, `'simple_push'`) no longer blurs and
26
+ refocuses, and the keyboard no longer starts to close and comes back
27
+ ([react-navigation#11643](https://github.com/react-navigation/react-navigation/issues/11643),
28
+ [#11626](https://github.com/react-navigation/react-navigation/issues/11626)).
29
+ UINavigationController ends editing in the incoming view mid-transition
30
+ and hands first responder back as it completes; the field now keeps it
31
+ through the transition.
32
+ - **iOS: a `selection` given while the field is not focused** is where the
33
+ caret goes when it is focused, instead of the end of the text
34
+ ([react-native#46943](https://github.com/facebook/react-native/issues/46943)).
35
+ - **iOS: Japanese, Chinese and Korean input** with `maxLength` or a
36
+ `transform`: the IME's composition is left alone until it is committed,
37
+ then cut to `maxLength` and transformed. The unconverted letters no longer
38
+ count against `maxLength`, and a controlled parent echoing the text back
39
+ mid-composition no longer ends it
40
+ ([react-native#56463](https://github.com/facebook/react-native/issues/56463),
41
+ [#52552](https://github.com/facebook/react-native/issues/52552)).
42
+ - **Android: `maxLength` counts characters when typing**, as it already did
43
+ for text set by the program and as iOS does: an emoji took two places when
44
+ typed.
45
+ - **Android: changing `secureTextEntry` (or another keyboard prop) on a
46
+ focused field keeps the caret where it was** instead of moving it to the
47
+ start ([react-native#38676](https://github.com/facebook/react-native/issues/38676)).
48
+
49
+ ## 0.3.3
50
+
51
+ - **`keyboardHandoffMs`**: when the focused field is popped or unmounted,
52
+ the keyboard stays up this long for the next field to take over (the
53
+ screen you return to, the next step's field), instead of dropping and
54
+ rising again. Both platforms; `Keyboard.dismiss()` ends the hold at once.
55
+ - **`focus()` on a field that is not on screen yet** (a screen navigated back
56
+ to, refocusing its field before it is shown again) now focuses it as soon
57
+ as it is, while the keyboard is still up. On Android this alone keeps the
58
+ keyboard up across a stack pop.
59
+ - **iOS number pads get a return key**: a field on the number, phone or
60
+ decimal pad with a `returnKeyType` set shows a bar above the keyboard with
61
+ that key ("Next", "Go", "Done"...), as `TextInput` does. The pads have no
62
+ return key of their own, so a form chained with Next stopped at its first
63
+ numeric field. The bar is the return key: `submitBehavior`,
64
+ `onSubmitEditing` and worklets run as for the real one.
65
+ - **`returnKeyBar`** (iOS, default `true`): `false` leaves a number pad
66
+ without the return key bar, for a screen whose own button rides the
67
+ keyboard (a sticky or morphing CTA) and would otherwise be doubled.
68
+ - **Fixed (iOS)**: coming back to a screen whose field had the keyboard, when
69
+ the field on the leaving screen used `keyboardHandoffMs`, left the keyboard
70
+ down: the stand-in held it, so UIKit had nothing to give back. The field
71
+ now takes the keyboard back itself, with the back animation.
72
+ - **Fixed (iOS)**: a multiline field kept drawing its placeholder under the
73
+ first characters typed.
74
+ - **iOS 26: no dark keyboard on the way back.** When you return to a screen
75
+ whose field had the keyboard, UIKit gives the field its focus back as the
76
+ transition starts, and iOS 26 then slides the keyboard in with the screen as
77
+ a flat dark snapshot. The field now takes its focus back once the screen has
78
+ settled, so the real keyboard rises from the bottom, as in the system apps
79
+ (Contacts). Focus the app asks for (`focus()`, `autoFocus`) is unchanged.
80
+ - **Fixed: `<Activity>`** (React 19.2). A hidden `<Activity>` deletes its
81
+ native views and creates new ones when shown again, so a NitroInput came
82
+ back with its first text (an uncontrolled field's text lived only
83
+ natively), and a handle kept from before hiding reached the pooled view,
84
+ which another field may have been given: `focus()` on a hidden field's
85
+ handle focused that other field. The text is now kept across hide and show,
86
+ and while hidden a field's handle does nothing (`focus()` / `blur()`) or
87
+ waits (`setText`); `getText()` returns the kept text. On Android, where
88
+ a hidden field keeps its view, the field takes it back when shown, and a
89
+ `focus()` asked for while the field is still hidden waits until it is
90
+ shown.
91
+ - **Fixed**: `Keyboard.dismiss()` right after a field with `keyboardHandoffMs`
92
+ unmounted, on a screen with no other field (a questionnaire's tap-only
93
+ question), waited for the hold to run out (about 0.4 s) before the keyboard
94
+ closed. It closes at once now.
95
+ - **Fixed (iOS)**: keyboard-controller's `KeyboardAwareScrollView` did not
96
+ scroll a field that got its focus back (the caret had not moved, so it got no
97
+ selection event and waited for one). The field now reports its selection
98
+ once editing begins.
99
+ - **Changed**: a controlled field whose parent keeps its `value` while the
100
+ user types (a rejected edit, a digits-only filter) puts the value back, as
101
+ `TextInput` does. It used to keep showing what was typed.
102
+ - **Fixed (Android)**: `keyboardHandoffMs` on a field that unmounts could lose
103
+ the race with the frame that removes it (about two runs in three on a
104
+ Galaxy A22), and the keyboard dropped anyway. The handoff now runs on the
105
+ UI thread just before Fabric applies that frame's view changes.
106
+ - **Docs**: "The keyboard across screens and lists" in the README: the
107
+ settings that make a NitroInput screen behave like the platform apps, back
108
+ navigation included (iOS gives the field its keyboard back as long as
109
+ native-stack's `keyboardHandlingEnabled` stays off).
110
+ - **Fixed (Android)**: a field on a screen react-native-screens covered and
111
+ uncovered came back still flagged as focused, and `focus()` did nothing.
112
+ - **Fixed (Android)**: keyboard-controller saw no focused input for a
113
+ NitroInput, so `KeyboardAwareScrollView` never scrolled to it.
114
+ - **Fixed (Android)**: changing `clearTextOnFocus` after mount had no effect.
115
+ - **Fixed (iOS)**: `KeyboardAwareScrollView` scrolled a reflowing field only
116
+ far enough to show the top of its line.
117
+ - **Fixed (iOS)**: a multiline field counted twice for keyboard-controller's
118
+ next / previous and its toolbar.
119
+ - **Fixed (iOS)**: React Native's `focus` / `blur` view commands now go
120
+ through the field's own `focus()` / `blur()` (retrying a declined focus).
121
+ - An on-device keyboard suite measures each of these: no keyboard hide when
122
+ focus moves, a field unmounts as the next autofocuses, a stack pops, a
123
+ search list filters under the field, or a scroll moves it out of sight.
124
+ The example app has an input lab (a search list and a form chained with
125
+ Next, each with NitroInput or TextInput), and
126
+ `example/e2e/keyboard-lab-android.sh` drives it with real touches over adb.
127
+ The lab also has a form with a sticky and a morphing CTA (keyboard-
128
+ controller), a push, a form sheet and a list of fields, and a scripted run
129
+ (`globalThis.__lab.run()`) that records keyboard-controller's events on a
130
+ device nothing can tap on.
131
+
3
132
  ## 0.3.2
4
133
 
5
134
  - **`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,22 @@ 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
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
524
558
  private var batchDepth = 0
525
559
  private var feedPending = false
526
560
  private var feedCaret = -1
@@ -580,10 +614,13 @@ class NitroInputView(context: Context) : FrameLayout(context) {
580
614
  defaultHighlightColor = editText.highlightColor
581
615
  editText.addTextChangedListener(Watcher())
582
616
  editText.setOnFocusChangeListener { _, focused ->
617
+ if (resyncingFocus) return@setOnFocusChangeListener
583
618
  restartBlink()
584
619
  syncLabelProgress(animated = true)
585
620
  syncFocusProgress(animated = true)
586
621
  if (focused) {
622
+ // This field took the keyboard over from a stand-in, if one held it.
623
+ KeyboardHandoff.claimed()
587
624
  if (keyboard.clearTextOnFocus) {
588
625
  clear()
589
626
  } else if (keyboard.selectTextOnFocus) {
@@ -974,6 +1011,11 @@ class NitroInputView(context: Context) : FrameLayout(context) {
974
1011
  // inserts a newline rather than submitting.
975
1012
  textType = textType or InputType.TYPE_TEXT_FLAG_MULTI_LINE
976
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
977
1019
  editText.inputType = textType
978
1020
  if (rawType != null) editText.setRawInputType(rawType)
979
1021
  if (k.multiline) {
@@ -988,6 +1030,15 @@ class NitroInputView(context: Context) : FrameLayout(context) {
988
1030
  editText.maxLines = 1
989
1031
  editText.minLines = 1
990
1032
  }
1033
+ // setSingleLine swaps the transformation the password input type installed
1034
+ // for a single-line one, and a plain field draws the EditText's own text.
1035
+ if (k.secureTextEntry) {
1036
+ editText.transformationMethod = android.text.method.PasswordTransformationMethod.getInstance()
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
+ }
991
1042
  editText.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI or when (k.returnKeyType) {
992
1043
  ReturnKeyType.DEFAULT -> EditorInfo.IME_ACTION_UNSPECIFIED
993
1044
  ReturnKeyType.DONE -> EditorInfo.IME_ACTION_DONE
@@ -1000,7 +1051,7 @@ class NitroInputView(context: Context) : FrameLayout(context) {
1000
1051
  // `setEditable` replaces through the `Editable`, which re-runs the filters:
1001
1052
  // a length filter there clipped the mask's punctuation off the end.
1002
1053
  editText.filters = if (format.mode == Mode.TEXT && k.maxLength > 0) {
1003
- arrayOf<InputFilter>(InputFilter.LengthFilter(k.maxLength))
1054
+ arrayOf<InputFilter>(CodePointLengthFilter(k.maxLength))
1004
1055
  } else {
1005
1056
  emptyArray<InputFilter>()
1006
1057
  }
@@ -1182,7 +1233,33 @@ class NitroInputView(context: Context) : FrameLayout(context) {
1182
1233
 
1183
1234
  fun focus() {
1184
1235
  if (!keyboard.editable) return
1236
+ if (!isAttachedToWindow || !isShown) {
1237
+ // Off the window, or on it but hidden (a hidden <Activity>, or a
1238
+ // subtree shown in the same commit that asks for focus): an invisible
1239
+ // view cannot take focus. Honour it once the view is attached and shown.
1240
+ pendingFocusUntil = SystemClock.uptimeMillis() + 1000
1241
+ pendingFocusOnMount = !everAttached
1242
+ return
1243
+ }
1244
+ pendingFocusUntil = 0
1185
1245
  editText.isFocusableInTouchMode = true
1246
+ val focusedInWindow = editText.rootView?.findFocus()
1247
+ if (editText.isFocused && focusedInWindow !== editText) {
1248
+ // Flagged focused while another view has the window's focus: a screen
1249
+ // container (react-native-screens' ScreensFrameLayout) skips
1250
+ // `clearFocus()` while a screen is invisible mid-transition, so a field
1251
+ // on a screen that was covered comes back still flagged. `requestFocus()`
1252
+ // is a no-op on it then, and the IME ignores it. The view that really
1253
+ // has focus lets go first (clearing ours alone would cut its focus chain
1254
+ // and leave it flagged in turn), then the stale flag is dropped quietly.
1255
+ focusedInWindow?.clearFocus()
1256
+ resyncingFocus = true
1257
+ try {
1258
+ editText.clearFocus()
1259
+ } finally {
1260
+ resyncingFocus = false
1261
+ }
1262
+ }
1186
1263
  if (!editText.hasFocus()) editText.requestFocus()
1187
1264
  // `showSoftInputOnFocus: false` keeps focus and the caret but no keyboard;
1188
1265
  // the EditText honours it on its own, so only the explicit ask is guarded.
@@ -1223,10 +1300,26 @@ class NitroInputView(context: Context) : FrameLayout(context) {
1223
1300
  }
1224
1301
 
1225
1302
  fun blur() {
1226
- if (editText.hasFocus()) editText.clearFocus()
1303
+ pendingFocusUntil = 0
1304
+ if (!editText.hasFocus()) {
1305
+ // `Keyboard.dismiss()` while a field that just left the screen holds the
1306
+ // keyboard for the next one: nothing is focused, so let it go now.
1307
+ KeyboardHandoff.letGo()
1308
+ return
1309
+ }
1310
+ editText.clearFocus()
1227
1311
  inputMethodManager()?.hideSoftInputFromWindow(editText.windowToken, 0)
1228
1312
  }
1229
1313
 
1314
+ /**
1315
+ * About to be unmounted (`NitroInput` calls this before the view is removed):
1316
+ * hand the IME to a stand-in so it stays up for the next field to focus.
1317
+ */
1318
+ fun handOffKeyboardIfFocused() {
1319
+ if (keyboard.keyboardHandoffMs <= 0 || !keyboard.showSoftInputOnFocus || !editText.hasFocus()) return
1320
+ KeyboardHandoff.hold(editText, keyboard.keyboardHandoffMs)
1321
+ }
1322
+
1230
1323
  /** Empties the field, reflowing the characters away. */
1231
1324
  fun clear() = setProgrammatic("", notify = true)
1232
1325
 
@@ -1280,6 +1373,9 @@ class NitroInputView(context: Context) : FrameLayout(context) {
1280
1373
  */
1281
1374
  fun resetForRecycle() {
1282
1375
  worklets = Worklets()
1376
+ pendingFocusUntil = 0
1377
+ pendingFocusOnMount = false
1378
+ everAttached = false
1283
1379
  inputFrame = Frame()
1284
1380
  labelProgress = 0f
1285
1381
  notchProgress = 0f
@@ -1317,6 +1413,7 @@ class NitroInputView(context: Context) : FrameLayout(context) {
1317
1413
 
1318
1414
  override fun onAttachedToWindow() {
1319
1415
  super.onAttachedToWindow()
1416
+ everAttached = true
1320
1417
  if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
1321
1418
  animatorScale = -1f
1322
1419
  context.contentResolver.registerContentObserver(
@@ -1327,8 +1424,31 @@ class NitroInputView(context: Context) : FrameLayout(context) {
1327
1424
  restartBlink()
1328
1425
  syncAccessibilityFromHost()
1329
1426
  maybeAutoFocus()
1427
+ focusIfPending()
1428
+ }
1429
+
1430
+ override fun onVisibilityChanged(changedView: View, visibility: Int) {
1431
+ super.onVisibilityChanged(changedView, visibility)
1432
+ if (isShown) focusIfPending()
1330
1433
  }
1331
1434
 
1435
+ /** A `focus()` asked for while the view was off the window or hidden. */
1436
+ private fun focusIfPending() {
1437
+ if (pendingFocusUntil <= 0 || !isAttachedToWindow || !isShown) return
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())
1443
+ pendingFocusUntil = 0
1444
+ pendingFocusOnMount = false
1445
+ if (wanted) post { focus() }
1446
+ }
1447
+
1448
+ private fun imeVisible(): Boolean =
1449
+ androidx.core.view.ViewCompat.getRootWindowInsets(this)
1450
+ ?.isVisible(androidx.core.view.WindowInsetsCompat.Type.ime()) == true
1451
+
1332
1452
  override fun onDetachedFromWindow() {
1333
1453
  stopAnimation()
1334
1454
  removeCallbacks(blink)
@@ -2345,3 +2465,91 @@ class NitroInputView(context: Context) : FrameLayout(context) {
2345
2465
  private val ROLES = Role.values()
2346
2466
  }
2347
2467
  }
2468
+
2469
+ /**
2470
+ * Keeps the IME up while a focused field is removed (its screen popped or its
2471
+ * element unmounted), for the next field to take over.
2472
+ *
2473
+ * Android hides the IME when the focused editor is removed from the window,
2474
+ * and shows it again when the next field asks: a pop from one field's screen
2475
+ * back to another's drops the keyboard and raises it. Moving focus to another
2476
+ * editor keeps it up instead, so a 1x1 stand-in `EditText` configured like the
2477
+ * leaving field takes focus first; the next field to focus takes the IME from
2478
+ * it in place. If none does within the hold, the stand-in hides the IME.
2479
+ * It has no id, which keyboard-controller reads as "no focused input".
2480
+ */
2481
+ internal object KeyboardHandoff {
2482
+ private val handler = Handler(Looper.getMainLooper())
2483
+ private var holder: android.widget.EditText? = null
2484
+ private val timeout = Runnable { letGo() }
2485
+
2486
+ val isHolding: Boolean get() = holder != null
2487
+
2488
+ fun hold(from: android.widget.EditText, milliseconds: Double) {
2489
+ val content = from.rootView?.findViewById<android.view.ViewGroup>(android.R.id.content) ?: return
2490
+ drop()
2491
+ val field = android.widget.EditText(from.context).apply {
2492
+ inputType = from.inputType
2493
+ imeOptions = from.imeOptions
2494
+ alpha = 0f
2495
+ translationX = -10000f
2496
+ background = null
2497
+ isSaveEnabled = false
2498
+ isFocusableInTouchMode = true
2499
+ importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
2500
+ }
2501
+ content.addView(field, FrameLayout.LayoutParams(1, 1))
2502
+ if (!field.requestFocus()) {
2503
+ content.removeView(field)
2504
+ return
2505
+ }
2506
+ holder = field
2507
+ handler.postDelayed(timeout, milliseconds.toLong())
2508
+ }
2509
+
2510
+ /** A field took the IME over: the stand-in can go, without hiding it. */
2511
+ fun claimed() {
2512
+ val field = holder ?: return
2513
+ if (field.hasFocus()) return
2514
+ handler.removeCallbacks(timeout)
2515
+ holder = null
2516
+ // Not in the middle of the focus change that got us here.
2517
+ handler.post { (field.parent as? android.view.ViewGroup)?.removeView(field) }
2518
+ }
2519
+
2520
+ /** Nothing claimed the IME in time, or `Keyboard.dismiss()`: hide it. */
2521
+ fun letGo() {
2522
+ handler.removeCallbacks(timeout)
2523
+ val field = holder ?: return
2524
+ holder = null
2525
+ if (field.hasFocus()) {
2526
+ val imm = field.context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
2527
+ imm?.hideSoftInputFromWindow(field.windowToken, 0)
2528
+ field.clearFocus()
2529
+ }
2530
+ (field.parent as? android.view.ViewGroup)?.removeView(field)
2531
+ }
2532
+
2533
+ private fun drop() {
2534
+ handler.removeCallbacks(timeout)
2535
+ val field = holder ?: return
2536
+ holder = null
2537
+ (field.parent as? android.view.ViewGroup)?.removeView(field)
2538
+ }
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
+ }
@@ -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
+ }