react-native-nitro-input 0.3.8 → 0.4.1

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 (108) hide show
  1. package/CHANGELOG.md +105 -0
  2. package/README.md +6 -1
  3. package/android/src/main/java/com/margelo/nitro/nitroinput/DigitSlots.kt +143 -0
  4. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroInputMeasure.kt +52 -0
  5. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroInputView.kt +80 -80
  6. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroNumberView.kt +18 -18
  7. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroTextView.kt +14 -14
  8. package/android/src/main/java/com/margelo/nitro/nitroinput/InputFonts.kt +244 -0
  9. package/android/src/main/java/com/margelo/nitro/nitroinput/InputSizing.kt +404 -0
  10. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputView.kt +168 -338
  11. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroNumberView.kt +178 -30
  12. package/ios/HybridNitroInputView.swift +73 -75
  13. package/ios/HybridNitroNumberView.swift +18 -18
  14. package/ios/HybridNitroTextView.swift +14 -14
  15. package/ios/InputSizing.swift +628 -0
  16. package/ios/NitroInputView.swift +180 -209
  17. package/ios/NitroNumberView.swift +98 -23
  18. package/lib/commonjs/nitrogen/generated/shared/json/NitroInputViewConfig.json +14 -8
  19. package/lib/commonjs/nitrogen/generated/shared/json/NitroNumberViewConfig.json +6 -6
  20. package/lib/commonjs/nitrogen/generated/shared/json/NitroTextViewConfig.json +6 -6
  21. package/lib/commonjs/src/NitroInput.js +166 -23
  22. package/lib/commonjs/src/NitroNumber.js +1 -1
  23. package/lib/commonjs/src/NitroText.js +6 -6
  24. package/lib/commonjs/src/specs/NitroInputMeasure.nitro.js +2 -0
  25. package/lib/module/nitrogen/generated/shared/json/NitroInputViewConfig.json +14 -8
  26. package/lib/module/nitrogen/generated/shared/json/NitroNumberViewConfig.json +6 -6
  27. package/lib/module/nitrogen/generated/shared/json/NitroTextViewConfig.json +6 -6
  28. package/lib/module/src/NitroInput.js +167 -24
  29. package/lib/module/src/NitroNumber.js +1 -1
  30. package/lib/module/src/NitroText.js +6 -6
  31. package/lib/module/src/specs/NitroInputMeasure.nitro.js +1 -0
  32. package/lib/typescript/src/NitroInput.d.ts +20 -16
  33. package/lib/typescript/src/specs/NitroInput.nitro.d.ts +21 -8
  34. package/lib/typescript/src/specs/NitroInputMeasure.nitro.d.ts +69 -0
  35. package/lib/typescript/src/specs/NitroNumber.nitro.d.ts +6 -6
  36. package/lib/typescript/src/specs/NitroText.nitro.d.ts +6 -6
  37. package/nitro.json +10 -0
  38. package/nitrogen/generated/android/NitroInput+autolinking.cmake +2 -0
  39. package/nitrogen/generated/android/NitroInputOnLoad.cpp +16 -0
  40. package/nitrogen/generated/android/c++/JHybridNitroInputMeasureSpec.cpp +93 -0
  41. package/nitrogen/generated/android/c++/JHybridNitroInputMeasureSpec.hpp +63 -0
  42. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.cpp +94 -40
  43. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.hpp +28 -16
  44. package/nitrogen/generated/android/c++/JHybridNitroNumberViewSpec.cpp +30 -30
  45. package/nitrogen/generated/android/c++/JHybridNitroNumberViewSpec.hpp +12 -12
  46. package/nitrogen/generated/android/c++/JHybridNitroTextViewSpec.cpp +30 -30
  47. package/nitrogen/generated/android/c++/JHybridNitroTextViewSpec.hpp +12 -12
  48. package/nitrogen/generated/android/c++/JNitroInputSize.hpp +61 -0
  49. package/nitrogen/generated/android/c++/JNitroInputSizing.hpp +292 -0
  50. package/nitrogen/generated/android/c++/views/JHybridNitroInputViewStateUpdater.cpp +54 -24
  51. package/nitrogen/generated/android/c++/views/JHybridNitroNumberViewStateUpdater.cpp +18 -18
  52. package/nitrogen/generated/android/c++/views/JHybridNitroTextViewStateUpdater.cpp +18 -18
  53. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroInputMeasureSpec.kt +56 -0
  54. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroInputViewSpec.kt +44 -8
  55. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroNumberViewSpec.kt +6 -6
  56. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroTextViewSpec.kt +6 -6
  57. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputSize.kt +56 -0
  58. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputSizing.kt +256 -0
  59. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.cpp +17 -0
  60. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.hpp +29 -0
  61. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Umbrella.hpp +11 -0
  62. package/nitrogen/generated/ios/NitroInputAutolinking.mm +8 -0
  63. package/nitrogen/generated/ios/NitroInputAutolinking.swift +12 -0
  64. package/nitrogen/generated/ios/c++/HybridNitroInputMeasureSpecSwift.cpp +11 -0
  65. package/nitrogen/generated/ios/c++/HybridNitroInputMeasureSpecSwift.hpp +112 -0
  66. package/nitrogen/generated/ios/c++/HybridNitroInputViewSpecSwift.hpp +68 -32
  67. package/nitrogen/generated/ios/c++/HybridNitroNumberViewSpecSwift.hpp +24 -24
  68. package/nitrogen/generated/ios/c++/HybridNitroTextViewSpecSwift.hpp +24 -24
  69. package/nitrogen/generated/ios/c++/views/HybridNitroInputViewComponent.mm +68 -32
  70. package/nitrogen/generated/ios/c++/views/HybridNitroNumberViewComponent.mm +24 -24
  71. package/nitrogen/generated/ios/c++/views/HybridNitroTextViewComponent.mm +24 -24
  72. package/nitrogen/generated/ios/swift/HybridNitroInputMeasureSpec.swift +55 -0
  73. package/nitrogen/generated/ios/swift/HybridNitroInputMeasureSpec_cxx.swift +138 -0
  74. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec.swift +14 -8
  75. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec_cxx.swift +90 -24
  76. package/nitrogen/generated/ios/swift/HybridNitroNumberViewSpec.swift +6 -6
  77. package/nitrogen/generated/ios/swift/HybridNitroNumberViewSpec_cxx.swift +18 -18
  78. package/nitrogen/generated/ios/swift/HybridNitroTextViewSpec.swift +6 -6
  79. package/nitrogen/generated/ios/swift/HybridNitroTextViewSpec_cxx.swift +18 -18
  80. package/nitrogen/generated/ios/swift/NitroInputSize.swift +34 -0
  81. package/nitrogen/generated/ios/swift/NitroInputSizing.swift +252 -0
  82. package/nitrogen/generated/shared/c++/HybridNitroInputMeasureSpec.cpp +21 -0
  83. package/nitrogen/generated/shared/c++/HybridNitroInputMeasureSpec.hpp +66 -0
  84. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.cpp +28 -16
  85. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.hpp +28 -16
  86. package/nitrogen/generated/shared/c++/HybridNitroNumberViewSpec.cpp +12 -12
  87. package/nitrogen/generated/shared/c++/HybridNitroNumberViewSpec.hpp +12 -12
  88. package/nitrogen/generated/shared/c++/HybridNitroTextViewSpec.cpp +12 -12
  89. package/nitrogen/generated/shared/c++/HybridNitroTextViewSpec.hpp +12 -12
  90. package/nitrogen/generated/shared/c++/NitroInputSize.hpp +87 -0
  91. package/nitrogen/generated/shared/c++/NitroInputSizing.hpp +271 -0
  92. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.cpp +28 -16
  93. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.hpp +42 -24
  94. package/nitrogen/generated/shared/c++/views/HybridNitroNumberViewComponent.cpp +12 -12
  95. package/nitrogen/generated/shared/c++/views/HybridNitroNumberViewComponent.hpp +18 -18
  96. package/nitrogen/generated/shared/c++/views/HybridNitroTextViewComponent.cpp +12 -12
  97. package/nitrogen/generated/shared/c++/views/HybridNitroTextViewComponent.hpp +18 -18
  98. package/nitrogen/generated/shared/json/NitroInputViewConfig.json +14 -8
  99. package/nitrogen/generated/shared/json/NitroNumberViewConfig.json +6 -6
  100. package/nitrogen/generated/shared/json/NitroTextViewConfig.json +6 -6
  101. package/package.json +4 -2
  102. package/src/NitroInput.tsx +215 -64
  103. package/src/NitroNumber.tsx +6 -6
  104. package/src/NitroText.tsx +6 -6
  105. package/src/specs/NitroInput.nitro.ts +21 -8
  106. package/src/specs/NitroInputMeasure.nitro.ts +78 -0
  107. package/src/specs/NitroNumber.nitro.ts +6 -6
  108. package/src/specs/NitroText.nitro.ts +6 -6
package/CHANGELOG.md CHANGED
@@ -1,5 +1,110 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.1
4
+
5
+ - **`NitroInput`'s `tabularNums` prop: tabular digits in any font.** Digits
6
+ were tabular only in fonts that ship tabular figures: in one without (Open
7
+ Runde) a typed "1" was far narrower than the placeholder's "0" it replaced,
8
+ so `keepPlaceholder`'s tail slid left on each keystroke (by 14 dp over a
9
+ card number), and an amount changed width as its digits did.
10
+ `tabularNums` lays every digit out as wide as the widest, centred, as
11
+ `NitroNumber`'s columns are: in the field's own text, the placeholder, the
12
+ tail and the measure, on both platforms. Unset, the field asks for the
13
+ font's tabular figures as before, at no cost; `false` asks for its
14
+ proportional ones (as does a style's `fontVariant: ['proportional-nums']`).
15
+ - **Android: a plain field's text and placeholder ask for tabular figures.**
16
+ The overlay's paints did, the edit text did not, so a font whose tabular
17
+ figures are off by default (ABC Diatype) shifted the tail the same way.
18
+
19
+ ## 0.4.0
20
+
21
+ - **Android: `NitroNumber`'s numeric transition no longer blocks the UI
22
+ thread (ANRs).** A glyph mask the warm thread had not made yet was blurred
23
+ in `onDraw`, and the shared mask cache made every mask inside its lock. Two
24
+ ANRs on low-end phones followed: the UI thread `Blocked` in the cache's
25
+ `get` behind the warm thread (which runs at `MIN_PRIORITY`), and the UI
26
+ thread waiting for a GC while the blur allocated two float copies of a large
27
+ glyph. Now masks are made outside the lock, the UI thread never blurs (a
28
+ mask not warmed yet is drawn sharp for a frame while the warm thread makes
29
+ it), and the blur reuses per-thread buffers instead of allocating per mask.
30
+ A mask the screen is waiting on is made ahead of the warm-up's queue (it
31
+ waited behind every digit at every blur level, ~50 ms), the warm thread runs
32
+ at background priority rather than the lowest, and a mask that cannot be
33
+ made is skipped rather than crashing the app.
34
+ - **iOS: the numeric transition no longer blurs on the main thread.** Its
35
+ digits were blurred and rasterized ahead of the first swap, but on the main
36
+ queue: opening a screen of numeric figures spent ~1 s of the main thread on
37
+ it (Release, simulator), in blocks of up to ~180 ms, and a prefix or suffix
38
+ that changed text was blurred on demand mid-frame. The warm-up now runs on
39
+ a background queue, a blur the screen is waiting on on a second one ahead
40
+ of it (drawn sharp until it lands), and the shared glyph caches are
41
+ thread-safe.
42
+ - **`NitroInput` lays out at its real size in the commit that mounts it.**
43
+ Its size came from the view, through `onSizeChange` and a React commit, so
44
+ the first layout had none: an `autoWidth` field took its parent's width (or
45
+ none) for a commit, and every field without a fixed height moved by a pixel
46
+ or two as its line box arrived. Now a single-line field is measured on the JS
47
+ thread before its view exists (a new `NitroInputMeasure`), with the code the
48
+ view sizes itself with - fonts, affixes and their seams, number and mask
49
+ formatting, the placeholder and `keepPlaceholder`'s tail - as React
50
+ Native's `TextInput` measures in its shadow node. About 0.1 ms per field;
51
+ the view's own report then matches and no longer costs a commit. A wrapping
52
+ field, a `transform` worklet and a style that sets both sides keep the old
53
+ path.
54
+ - **A framed field sizes itself.** With no width or height from its style,
55
+ an `outlined` or `filled` field took the size of its text line alone: the
56
+ frame's side insets and the label were left out, so a resting label was
57
+ drawn outside the field and a filled one cut its text off. Its size now
58
+ includes the frame: the side insets either side of the text or the resting
59
+ label, whichever is wider, and above and below it the same 16 of padding
60
+ (and a filled field's label line) a wrapping field already had. A field
61
+ given a height in its style is unchanged.
62
+ - **A secure field fits its bullets.** Android set the password input type
63
+ after the typeface, which switches the field to monospace, so its bullets
64
+ were wider than the field measured them; the typeface is now put back, as
65
+ React Native's `TextInput` does. On iOS the field measured its text as
66
+ bullets in its own font, but UIKit draws U+2219 in the system font; it now
67
+ measures those. An `autoWidth` secure field showed `●●●●…` for 8 characters
68
+ on iOS and 5 bullets on Android.
69
+ - **No size jump on mount, and no amount sliding in on a reused field.** A
70
+ size the view reported before its props were applied (the defaults', or a
71
+ recycled view's last element's) reached JS and made the field jump to it and
72
+ back. And on iOS a recycled view took the empty text its props reset fed the
73
+ engine for its first, so a reflowing amount on a reused view slid in instead
74
+ of showing as it is.
75
+ - **Android: `keepPlaceholder`'s greyed tail stays inside the field.** The
76
+ rest of the placeholder, drawn after what was typed, was not clipped to the
77
+ text area as the field's own text and hint are: in a padded field narrower
78
+ than its placeholder (or once the typed text filled it), the tail ran over
79
+ the padding to the field's edge. iOS already clipped it.
80
+ - **A `TextInput` style no longer crashes a field, and `NitroInput` reads
81
+ its typography from it.** Fabric hands a view its style's keys as props,
82
+ and six to eight of each view's native props shared a name with a text
83
+ style key: `style={{ fontWeight: '700' }}` threw ("Value is a string,
84
+ expected a number") on `NitroInput`, `NitroNumber` and `NitroText`, and a
85
+ numeric `fontSize` or `color` there was fought over by the style and the
86
+ prop. The native props are renamed (`textSize`, `textWeight`,
87
+ `textFamily`, `textColor`, `textLetterSpacing`, `textLineHeight`,
88
+ `textAlignment`, `textVerticalAlignment`); the components' own props keep
89
+ their names. A test now fails if any native prop shares a name with a React
90
+ Native style key or view prop. `NitroInput` also takes `fontSize`,
91
+ `fontWeight`, `fontFamily`, `color`, `letterSpacing`, `lineHeight`,
92
+ `textAlign` and `textAlignVertical` from `style`, as `TextInput` does (its
93
+ `style` is typed as `TextInput`'s); the props of the same name win.
94
+ - **`NitroInput` matches `TextInput` in three more places**, found by a
95
+ visual comparison of the two side by side:
96
+ - Android: `textAlign` `center` / `right` on a plain field did nothing; the
97
+ alignment set when the field became plain (before `textAlign` arrived in
98
+ the same commit) overrode it.
99
+ - A `style` padding or border insets the text and adds to the size the
100
+ field works out for itself, as `TextInput`'s does. An `autoWidth` field
101
+ with `paddingHorizontal: 8` squeezed its text to "…" on iOS; on Android
102
+ the padding did not inset the text at all (React Native never hands a
103
+ Nitro view its padding there, so the view now insets its text, overlay and
104
+ frame itself).
105
+ - iOS: `lineHeight` sets a single line's height, as on Android; it was the
106
+ font's own line box whatever the prop said.
107
+
3
108
  ## 0.3.8
4
109
 
5
110
  - **`NitroNumber` shows what its `format` prints, value by value.** It read the
package/README.md CHANGED
@@ -173,6 +173,10 @@ interpolate between them.
173
173
  `variant="filled"` gives a filled field instead: a `fillColor`
174
174
  background with a square bottom and an indicator rule along it.
175
175
 
176
+ Without a size in its style the field sizes itself to the frame: its text (or
177
+ its resting label, if wider) between the side insets, and 16 of padding above
178
+ and below the line, plus a line for a filled field's floated label.
179
+
176
180
  The label runs 200 ms on a decelerate curve, and the notch is staggered 50 ms behind it opening and closes in 50 ms,
177
181
  so the gap is never open under a label that has not arrived. All of it runs
178
182
  inside the view, off a native focus callback — there is no React state to
@@ -517,6 +521,7 @@ screen behaves like theirs with these settings:
517
521
  | `affixAlign` | `'baseline' \| 'center' \| 'top' \| 'bottom'` | `'baseline'` | How they line up with the text: `top` pins glyph tops, `bottom` the bottom of the ink (a currency code sits on the digits' baseline). |
518
522
  | `prefixAlign` / `suffixAlign` | same | `affixAlign` | Per-affix override. |
519
523
  | `letterSpacing` | number | `0` | Points added after every glyph, like `Text`'s; a smaller affix gets it in proportion to its size. |
524
+ | `tabularNums` | boolean | unset | Unset: the font's tabular figures where it has them (the system fonts do), at no cost. `true`: every digit as wide as the widest even in a font without them (Open Runde), laid out that wide and centred, so a `keepPlaceholder` tail never moves and an amount keeps its width as it changes; a little work on each change. `false`: the font's proportional figures, as is a style's `fontVariant: ['proportional-nums']`. |
520
525
  | `prefixSpacing` / `suffixSpacing` | number | the letter spacing | Points between the prefix and the text, and between the text and the suffix. |
521
526
  | `prefixOffset` / `suffixOffset` | number | `0` | Points an affix is moved down after its alignment (negative: up). |
522
527
  | `format` | `NumberFormat` | none | The amount follows it: prefix and suffix, separators, fraction digits, where the sign goes. Sets `mode="number"`; the individual props override it. |
@@ -583,7 +588,7 @@ screen behaves like theirs with these settings:
583
588
  | `onKeyPress` | `(event) => void` | – | Before the text changes: the character, `'Backspace'` or `'Enter'`. |
584
589
  | `onNativeRef` | `(ref) => void` | – | Receives the Nitro object on mount. |
585
590
  | `id` / `aria-label` | `string` | – | React Native's HTML-style aliases for `nativeID` / `accessibilityLabel`, resolved here because a Nitro view is handed the raw props; each wins over the older spelling. |
586
- | `style`, `testID`, … | `ViewProps` | – | Regular view props. `testID` and the accessibility label are forwarded to the system field, the element VoiceOver, TalkBack and e2e tools interact with. The field takes its width from its parent like a `TextInput`; see `autoWidth`. |
591
+ | `style`, `testID`, … | `ViewProps`; `style` as `TextInput`'s | – | Regular view props. `testID` and the accessibility label are forwarded to the system field, the element VoiceOver, TalkBack and e2e tools interact with. The field takes its width from its parent like a `TextInput`; see `autoWidth`. As on a `TextInput`, `style` can carry the typography (`fontSize`, `fontWeight`, `fontFamily`, `color`, `letterSpacing`, `lineHeight`, `textAlign`, `textAlignVertical`; the props of the same name win), and its padding and border inset the text and add to a size the field works out for itself. Two deliberate differences: digits are tabular by default where the font has tabular figures (Android's Roboto has them anyway, and a field keeps its width whether it reflows or not; see `tabularNums` for a font without them), and Android gets no default padding (iOS's `TextInput` has none; React Native's Android one keeps the platform field's). |
587
592
 
588
593
  `keyboardType`: `'default' | 'number-pad' | 'decimal-pad' | 'numeric' | 'email-address' | 'phone-pad' | 'url' | 'ascii-capable' | 'numbers-and-punctuation'`.
589
594
 
@@ -0,0 +1,143 @@
1
+ package com.margelo.nitro.nitroinput
2
+
3
+ import android.graphics.Canvas
4
+ import android.graphics.Paint
5
+ import android.graphics.Typeface
6
+ import android.text.NoCopySpan
7
+ import android.text.Spannable
8
+ import android.text.TextPaint
9
+ import android.text.style.ReplacementSpan
10
+ import kotlin.math.ceil
11
+
12
+ private const val DIGITS = "0123456789"
13
+
14
+ /**
15
+ * Tabular figures for a font that has none.
16
+ *
17
+ * The paints ask for `tnum`, but a font without the feature (Open Runde) keeps
18
+ * its proportional digits: every typed "1" was narrower than the placeholder's
19
+ * "0" it replaced, so `keepPlaceholder`'s tail slid left on each keystroke and
20
+ * an amount changed width as its digits did. With `tabularNums` every digit
21
+ * is given a slot as wide as the widest digit instead, centred in it, as
22
+ * NitroNumber's columns are. In a font with tabular figures the digits are
23
+ * all that wide already, and nothing changes.
24
+ *
25
+ * In the edit text a slot is a [ReplacementSpan], whose width is a whole
26
+ * pixel, so a slot is the widest digit and one letter spacing rounded up, and
27
+ * [InputFonts] measures and draws with that same width. (Letter spacing on the
28
+ * digit was the first try: from API 35 the platform trims it at either end of
29
+ * a line, so the first and last digit went without.)
30
+ */
31
+ internal object DigitSlots {
32
+ fun isDigit(codePoint: Int): Boolean = codePoint in '0'.code..'9'.code
33
+
34
+ /** Each digit's advance in a paint, letter spacing aside, and the widest of them. */
35
+ class Digits(val widths: FloatArray) {
36
+ val widest = widths.max()
37
+
38
+ /** A slot in px, for a letter spacing of [spacing] px. */
39
+ fun slot(spacing: Float): Int = ceil(widest + spacing - 0.001f).toInt()
40
+ }
41
+
42
+ /**
43
+ * The digits of [paint] (its letter spacing aside), or null when they are
44
+ * one width already (within a hundredth of the font size).
45
+ */
46
+ fun measure(paint: Paint): Digits? {
47
+ val bare = Paint(paint)
48
+ bare.letterSpacing = 0f
49
+ val widths = FloatArray(10) { bare.measureText(DIGITS, it, it + 1) }
50
+ if (widths.max() - widths.min() <= paint.textSize * 0.01f) return null
51
+ return Digits(widths)
52
+ }
53
+
54
+ private data class Key(val typeface: Typeface?, val size: Float, val features: String?)
55
+
56
+ // For the edit text's paint, which the spans are handed a copy of on every layout pass.
57
+ private val cache = HashMap<Key, Digits?>()
58
+
59
+ private fun digits(paint: Paint): Digits? = synchronized(cache) {
60
+ val key = Key(paint.typeface, paint.textSize, paint.fontFeatureSettings)
61
+ if (key in cache) cache[key] else measure(paint).also {
62
+ if (cache.size > 32) cache.clear()
63
+ cache[key] = it
64
+ }
65
+ }
66
+
67
+ private fun spacing(paint: Paint): Float = paint.letterSpacing * paint.textSize
68
+
69
+ /**
70
+ * Re-spans every digit of [text] for [paint] (the edit text's), or only
71
+ * clears the spans when its font has tabular figures, or when [off].
72
+ */
73
+ fun apply(text: Spannable, paint: Paint, off: Boolean) {
74
+ val on = !off && paint.textSize > 0f && digits(paint) != null
75
+ // Only what changed: every span set or removed lays the edit text out
76
+ // again, and a keystroke adds one digit (the spans of the others move
77
+ // with their characters). Re-spanning the lot cost ~1.5 ms a keystroke.
78
+ val spanned = BooleanArray(text.length)
79
+ for (span in text.getSpans(0, text.length, Slot::class.java)) {
80
+ val start = text.getSpanStart(span)
81
+ val keep = on && text.getSpanEnd(span) == start + 1 && isDigit(text[start].code) && !spanned[start]
82
+ if (keep) spanned[start] = true else text.removeSpan(span)
83
+ }
84
+ if (!on) return
85
+ for (i in text.indices) {
86
+ if (!spanned[i] && isDigit(text[i].code)) text.setSpan(Slot(), i, i + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Draws [text] at [x] in [paint] as the spans lay it out in the edit text:
92
+ * digits in their slots, the runs between them whole.
93
+ */
94
+ fun draw(canvas: Canvas, text: String, x: Float, y: Float, paint: Paint) {
95
+ val digits = digits(paint)
96
+ if (digits == null) {
97
+ canvas.drawText(text, x, y, paint)
98
+ return
99
+ }
100
+ val slot = digits.slot(spacing(paint))
101
+ val spacing = paint.letterSpacing
102
+ var left = x
103
+ var start = 0
104
+ while (start < text.length) {
105
+ if (isDigit(text[start].code)) {
106
+ paint.letterSpacing = 0f
107
+ canvas.drawText(text, start, start + 1, left + (slot - digits.widths[text[start] - '0']) / 2f, y, paint)
108
+ paint.letterSpacing = spacing
109
+ left += slot
110
+ start++
111
+ continue
112
+ }
113
+ var end = start + 1
114
+ while (end < text.length && !isDigit(text[end].code)) end++
115
+ canvas.drawText(text, start, end, left, y, paint)
116
+ left += paint.measureText(text, start, end)
117
+ start = end
118
+ }
119
+ }
120
+
121
+ /**
122
+ * One digit, drawn centred in its slot. Not copied with the text (the
123
+ * clipboard, a saved state): the watcher puts the spans back on whatever
124
+ * text the field ends up with.
125
+ */
126
+ private class Slot : ReplacementSpan(), NoCopySpan {
127
+ private val bare = TextPaint()
128
+
129
+ override fun getSize(paint: Paint, text: CharSequence, start: Int, end: Int, fm: Paint.FontMetricsInt?): Int {
130
+ if (fm != null) paint.getFontMetricsInt(fm)
131
+ val digits = digits(paint) ?: return ceil(paint.measureText(text, start, end)).toInt()
132
+ return digits.slot(spacing(paint))
133
+ }
134
+
135
+ override fun draw(canvas: Canvas, text: CharSequence, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) {
136
+ bare.set(paint)
137
+ bare.letterSpacing = 0f
138
+ val digits = digits(paint)
139
+ val inset = if (digits == null) 0f else (digits.slot(spacing(paint)) - digits.widths[text[start] - '0']) / 2f
140
+ canvas.drawText(text, start, end, x + inset, y.toFloat(), bare)
141
+ }
142
+ }
143
+ }
@@ -0,0 +1,52 @@
1
+ package com.margelo.nitro.nitroinput
2
+
3
+ import android.content.res.Resources
4
+ import android.graphics.Color
5
+ import androidx.annotation.Keep
6
+ import com.facebook.proguard.annotations.DoNotStrip
7
+ import com.margelo.nitro.NitroModules
8
+
9
+ /**
10
+ * Measures a single-line field on the JS thread, before its view exists, with
11
+ * [InputFonts], [InputText] and [InputGlyphs] - the code the view sizes itself
12
+ * with - so it lays out at its real size in the commit that mounts it.
13
+ * `Paint`, `ReactFontManager` and the C++ engines are safe off the main
14
+ * thread, as React Native's own text measurement relies on.
15
+ *
16
+ * Mirrors `HybridNitroInputMeasure` on iOS.
17
+ */
18
+ @Keep
19
+ @DoNotStrip
20
+ class HybridNitroInputMeasure : HybridNitroInputMeasureSpec() {
21
+ // Reused across calls and reconfigured by each: measures come one at a
22
+ // time from the JS thread, and the lock keeps a second runtime out.
23
+ private val formatter = AmountFormatter()
24
+ private val maskEngine = MaskEngine()
25
+
26
+ @Synchronized
27
+ override fun measure(sizing: NitroInputSizing): NitroInputSize {
28
+ val context = NitroModules.applicationContext
29
+ val resources = context?.resources ?: Resources.getSystem()
30
+ val density = resources.displayMetrics.density
31
+ val props = SizingProps(sizing)
32
+ val format = formatOf(props)
33
+ val fonts = InputFonts(sizingTypographyOf(props, density), density, resources.configuration.fontScale, context?.assets, Color.BLACK)
34
+ InputText.configure(formatter, maskEngine, null, format)
35
+ val text = InputText.conform(sizing.text, format, formatter, maskEngine, clampedInt(sizing.maxLength, 0, Int.MAX_VALUE, 0))
36
+ val frame = sizingFrameOf(props)
37
+ // Unfocused, as a field mounts: a label resting inside it hides the placeholder.
38
+ val labelFloats = frame.labelBehavior == NitroInputView.LabelBehavior.ALWAYS || text.isNotEmpty()
39
+ val hint = if (frame.hasLabel && !labelFloats) "" else InputText.basePlaceholder(format, maskEngine)
40
+ val tail = InputText.ghostTail(text, format, maskEngine, sizing.secureTextEntry)
41
+ val width = if (sizing.plain) {
42
+ InputSizing.plainWidthPx(fonts, format, InputSizing.plainBody(text, hint, tail, sizing.secureTextEntry))
43
+ } else {
44
+ InputSizing.reflowWidthPx(fonts, format, text, hint, tail, sizing.secureTextEntry)
45
+ }
46
+ return InputSizing.reported(
47
+ InputFrame.widthPx(width, frame, fonts, density),
48
+ InputFrame.singleLineHeightPx(fonts.lineHeight, frame, fonts, density),
49
+ density,
50
+ )
51
+ }
52
+ }
@@ -14,7 +14,7 @@ import com.margelo.nitro.views.RecyclableView
14
14
  */
15
15
  @Keep
16
16
  @DoNotStrip
17
- class HybridNitroInputView(private val context: ThemedReactContext) : HybridNitroInputViewSpec(), RecyclableView {
17
+ class HybridNitroInputView(private val context: ThemedReactContext) : HybridNitroInputViewSpec(), RecyclableView, InputSizingProps {
18
18
  private val mainHandler = Handler(Looper.getMainLooper())
19
19
 
20
20
  /**
@@ -73,7 +73,7 @@ class HybridNitroInputView(private val context: ThemedReactContext) : HybridNitr
73
73
  }
74
74
  inputView.onKeyPress = { key -> onKeyPress?.invoke(key) }
75
75
  inputView.onIntrinsicSizeChange = { width, height ->
76
- onSizeChange?.invoke(width.toDouble(), height.toDouble())
76
+ if (!configured || committing) sizeHeld = true else onSizeChange?.invoke(width.toDouble(), height.toDouble())
77
77
  }
78
78
  }
79
79
 
@@ -127,7 +127,11 @@ class HybridNitroInputView(private val context: ThemedReactContext) : HybridNitr
127
127
  set(v) { field = v; markConfigDirty() }
128
128
  override var suffixAlign: NitroInputAffixAlign = NitroInputAffixAlign.BASELINE
129
129
  set(v) { field = v; markConfigDirty() }
130
- override var letterSpacing: Double = 0.0
130
+ override var textLetterSpacing: Double = 0.0
131
+ set(v) { field = v; markConfigDirty() }
132
+ override var tabularNums: Boolean = true
133
+ set(v) { field = v; markConfigDirty() }
134
+ override var slotDigits: Boolean = false
131
135
  set(v) { field = v; markConfigDirty() }
132
136
  override var prefixSpacing: Double = Double.POSITIVE_INFINITY
133
137
  set(v) { field = v; markConfigDirty() }
@@ -171,17 +175,17 @@ class HybridNitroInputView(private val context: ThemedReactContext) : HybridNitr
171
175
  set(v) { field = v; markConfigDirty() }
172
176
  override var effect: NitroInputEffect = NitroInputEffect.AUTO
173
177
  set(v) { field = v; markConfigDirty() }
174
- override var fontSize: Double = 32.0
178
+ override var textSize: Double = 32.0
175
179
  set(v) { field = v; markConfigDirty() }
176
- override var lineHeight: Double = 0.0
180
+ override var textLineHeight: Double = 0.0
177
181
  set(v) { field = v; markConfigDirty() }
178
- override var fontWeight: Double = 400.0
182
+ override var textWeight: Double = 400.0
179
183
  set(v) { field = v; markConfigDirty() }
180
- override var fontFamily: String = ""
184
+ override var textFamily: String = ""
181
185
  set(v) { field = v; markConfigDirty() }
182
- override var color: Double = Double.NaN
186
+ override var textColor: Double = Double.NaN
183
187
  set(v) { field = v; markConfigDirty() }
184
- override var textAlign: NitroInputTextAlign = NitroInputTextAlign.AUTO
188
+ override var textAlignment: NitroInputTextAlign = NitroInputTextAlign.AUTO
185
189
  set(v) { field = v; markConfigDirty() }
186
190
  override var rightToLeft: Boolean = false
187
191
  set(v) { field = v; markConfigDirty() }
@@ -213,7 +217,15 @@ class HybridNitroInputView(private val context: ThemedReactContext) : HybridNitr
213
217
  set(v) { field = v; markConfigDirty() }
214
218
  override var numberOfLines: Double = 0.0
215
219
  set(v) { field = v; markConfigDirty() }
216
- override var textAlignVertical: NitroInputTextAlignVertical = NitroInputTextAlignVertical.AUTO
220
+ override var textVerticalAlignment: NitroInputTextAlignVertical = NitroInputTextAlignVertical.AUTO
221
+ set(v) { field = v; markConfigDirty() }
222
+ override var textInsetLeft: Double = 0.0
223
+ set(v) { field = v; markConfigDirty() }
224
+ override var textInsetTop: Double = 0.0
225
+ set(v) { field = v; markConfigDirty() }
226
+ override var textInsetRight: Double = 0.0
227
+ set(v) { field = v; markConfigDirty() }
228
+ override var textInsetBottom: Double = 0.0
217
229
  set(v) { field = v; markConfigDirty() }
218
230
  override var scrollEnabled: Boolean = true
219
231
  set(v) { field = v; markConfigDirty() }
@@ -285,7 +297,7 @@ class HybridNitroInputView(private val context: ThemedReactContext) : HybridNitr
285
297
  override var onSizeChange: ((width: Double, height: Double) -> Unit)? = null
286
298
  set(v) {
287
299
  field = v
288
- onMain { inputView.resendIntrinsicSize() }
300
+ onMain { if (configured) inputView.resendIntrinsicSize() }
289
301
  }
290
302
 
291
303
  // endregion
@@ -414,7 +426,9 @@ class HybridNitroInputView(private val context: ThemedReactContext) : HybridNitr
414
426
  prefixFontSize = Double.NaN
415
427
  suffixFontSize = Double.NaN
416
428
  signPlacement = NitroInputSignPlacement.BEFOREAFFIX
417
- letterSpacing = 0.0
429
+ textLetterSpacing = 0.0
430
+ tabularNums = true
431
+ slotDigits = false
418
432
  prefixSpacing = Double.POSITIVE_INFINITY
419
433
  suffixSpacing = Double.POSITIVE_INFINITY
420
434
  prefixOffset = 0.0
@@ -438,12 +452,12 @@ class HybridNitroInputView(private val context: ThemedReactContext) : HybridNitr
438
452
  easing = NitroInputEasing.EXPO
439
453
  bounce = 0.15
440
454
  effect = NitroInputEffect.AUTO
441
- fontSize = 32.0
442
- lineHeight = 0.0
443
- fontWeight = 400.0
444
- fontFamily = ""
445
- color = Double.NaN
446
- textAlign = NitroInputTextAlign.AUTO
455
+ textSize = 32.0
456
+ textLineHeight = 0.0
457
+ textWeight = 400.0
458
+ textFamily = ""
459
+ textColor = Double.NaN
460
+ textAlignment = NitroInputTextAlign.AUTO
447
461
  rightToLeft = false
448
462
  caretColor = Double.NaN
449
463
  selectionColor = Double.NaN
@@ -459,7 +473,11 @@ class HybridNitroInputView(private val context: ThemedReactContext) : HybridNitr
459
473
  editable = true
460
474
  multiline = false
461
475
  numberOfLines = 0.0
462
- textAlignVertical = NitroInputTextAlignVertical.AUTO
476
+ textVerticalAlignment = NitroInputTextAlignVertical.AUTO
477
+ textInsetLeft = 0.0
478
+ textInsetTop = 0.0
479
+ textInsetRight = 0.0
480
+ textInsetBottom = 0.0
463
481
  scrollEnabled = true
464
482
  autoFocus = false
465
483
  plain = false
@@ -505,7 +523,10 @@ class HybridNitroInputView(private val context: ThemedReactContext) : HybridNitr
505
523
  configDirty = true
506
524
  textDirty = true
507
525
  isBatching = false
508
- onMain { inputView.resetForRecycle() }
526
+ onMain {
527
+ configured = false
528
+ inputView.resetForRecycle()
529
+ }
509
530
  }
510
531
 
511
532
  // endregion
@@ -565,12 +586,35 @@ class HybridNitroInputView(private val context: ThemedReactContext) : HybridNitr
565
586
  else -> null
566
587
  }
567
588
 
589
+ /**
590
+ * Whether the props have been applied since the view was made or recycled.
591
+ * Until then its size is the defaults' (or the last element's), and JS, which
592
+ * lays the field out at its measured size from the first commit, must not
593
+ * see it: a stray report made the field jump to it and back.
594
+ */
595
+ private var configured = false
596
+ /** Inside [commit], where a size is of half-applied props. */
597
+ private var committing = false
598
+ /** A size was held back by the two above, so the settled one is sent after. */
599
+ private var sizeHeld = false
600
+
568
601
  private fun commit() {
569
602
  onMain {
570
- inputView.batch {
571
- flushConfigIfNeeded()
572
- flushTextIfNeeded()
573
- flushSelectionIfNeeded()
603
+ committing = true
604
+ try {
605
+ inputView.batch {
606
+ flushConfigIfNeeded()
607
+ flushTextIfNeeded()
608
+ flushSelectionIfNeeded()
609
+ }
610
+ } finally {
611
+ committing = false
612
+ }
613
+ // Once after the first commit, so JS always hears the view's size.
614
+ if (!configured || sizeHeld) {
615
+ configured = true
616
+ sizeHeld = false
617
+ inputView.resendIntrinsicSize()
574
618
  }
575
619
  }
576
620
  }
@@ -601,54 +645,18 @@ class HybridNitroInputView(private val context: ThemedReactContext) : HybridNitr
601
645
  if (!configDirty) return
602
646
  configDirty = false
603
647
 
604
- val size = finite(fontSize, 32.0).toFloat()
605
- inputView.format = NitroInputView.Format(
606
- mode = when (mode) {
607
- NitroInputMode.NUMBER -> NitroInputView.Mode.NUMBER
608
- NitroInputMode.MASK -> NitroInputView.Mode.MASK
609
- else -> NitroInputView.Mode.TEXT
610
- },
611
- mask = mask,
612
- maskNotations = maskNotations.map {
613
- NitroInputView.MaskNotation(it.character, it.characterSet, it.isOptional)
614
- },
615
- maskAutocomplete = maskAutocomplete,
616
- maskAutoSkip = maskAutoSkip,
617
- maskAffinityFormats = maskAffinityFormats.toList(),
618
- maskAffinityStrategy = maskAffinityStrategy.value,
619
- maskTextCase = maskTextCase.value,
620
- maskCharacterMap = maskCharacterMap.map { NitroInputView.MaskMapping(it.from, it.to) },
621
- maskSlotPlaceholder = maskSlotPlaceholder,
622
- keepPlaceholder = keepPlaceholder,
623
- fractionDigits = clampInt(fractionDigits, 0, 9, 2),
624
- maxIntegerDigits = clampInt(maxIntegerDigits, 1, 30, 15),
625
- groupingSeparator = groupingSeparator,
626
- decimalSeparator = decimalSeparator,
627
- prefix = prefix,
628
- suffix = suffix,
629
- signBeforeAffix = signPlacement != NitroInputSignPlacement.AFTERAFFIX,
630
- placeholder = placeholder,
631
- )
632
- inputView.typography = NitroInputView.Typography(
633
- fontSize = size,
634
- lineHeightPx = (Math.max(0.0, finite(lineHeight, 0.0)) * inputView.resources.displayMetrics.density).toFloat(),
635
- prefixFontSize = finite(prefixFontSize, size.toDouble()).toFloat(),
636
- suffixFontSize = finite(suffixFontSize, size.toDouble()).toFloat(),
637
- fontWeight = clampInt(fontWeight, 100, 900, 400),
638
- fontFamily = fontFamily.ifEmpty { null },
639
- color = colorFromARGB(color),
648
+ // The sizing half of the mapping is shared with HybridNitroInputMeasure,
649
+ // which sizes the field before this view exists.
650
+ inputView.format = formatOf(this)
651
+ inputView.typography = sizingTypographyOf(this, inputView.resources.displayMetrics.density).copy(
652
+ color = colorFromARGB(textColor),
640
653
  placeholderColor = colorFromARGB(placeholderColor),
641
654
  prefixAlign = mapAffixAlign(prefixAlign),
642
655
  suffixAlign = mapAffixAlign(suffixAlign),
643
- letterSpacing = if (letterSpacing.isFinite()) letterSpacing.toFloat() else 0f,
644
- prefixSpacing = prefixSpacing.takeIf { it.isFinite() }?.toFloat(),
645
- suffixSpacing = suffixSpacing.takeIf { it.isFinite() }?.toFloat(),
646
656
  prefixOffset = if (prefixOffset.isFinite()) prefixOffset.toFloat() else 0f,
647
657
  suffixOffset = if (suffixOffset.isFinite()) suffixOffset.toFloat() else 0f,
648
658
  adjustsFontSizeToFit = adjustsFontSizeToFit,
649
659
  minimumFontScale = finite(minimumFontScale, 0.5).coerceIn(0.05, 1.0).toFloat(),
650
- allowFontScaling = allowFontScaling,
651
- maxFontSizeMultiplier = Math.max(0.0, finite(maxFontSizeMultiplier, 0.0)).toFloat(),
652
660
  )
653
661
  inputView.worklets = NitroInputView.Worklets(
654
662
  transform = clampInt(transformWorklet, 0, Int.MAX_VALUE, 0),
@@ -709,7 +717,7 @@ class HybridNitroInputView(private val context: ThemedReactContext) : HybridNitr
709
717
  plain = plain,
710
718
  multiline = multiline,
711
719
  numberOfLines = clampInt(numberOfLines, 0, 1000, 0),
712
- textAlignVertical = when (textAlignVertical) {
720
+ textAlignVertical = when (textVerticalAlignment) {
713
721
  NitroInputTextAlignVertical.TOP -> NitroInputView.TextAlignVertical.TOP
714
722
  NitroInputTextAlignVertical.CENTER -> NitroInputView.TextAlignVertical.CENTER
715
723
  NitroInputTextAlignVertical.BOTTOM -> NitroInputView.TextAlignVertical.BOTTOM
@@ -737,27 +745,19 @@ class HybridNitroInputView(private val context: ThemedReactContext) : HybridNitr
737
745
  selectionColor = colorFromARGB(selectionColor),
738
746
  hidden = caretHidden,
739
747
  )
740
- inputView.inputFrame = NitroInputView.Frame(
741
- variant = when (variant) {
742
- NitroInputVariant.OUTLINED -> NitroInputView.Variant.OUTLINED
743
- NitroInputVariant.FILLED -> NitroInputView.Variant.FILLED
744
- NitroInputVariant.NONE -> NitroInputView.Variant.NONE
745
- },
746
- label = label,
747
- labelBehavior = when (labelBehavior) {
748
- NitroInputLabelBehavior.ALWAYS -> NitroInputView.LabelBehavior.ALWAYS
749
- NitroInputLabelBehavior.FLOAT -> NitroInputView.LabelBehavior.FLOAT
750
- },
748
+ inputView.inputFrame = sizingFrameOf(this).copy(
751
749
  labelColor = colorFromARGB(labelColor),
752
750
  labelFocusedColor = colorFromARGB(labelFocusedColor),
753
- labelFontSize = Math.max(0.0, finite(labelFontSize, 0.0)).toFloat(),
754
751
  strokeColor = colorFromARGB(strokeColor),
755
752
  focusedStrokeColor = colorFromARGB(focusedStrokeColor),
756
753
  strokeWidth = Math.max(0.0, finite(strokeWidth, 1.0)).toFloat(),
757
- cornerRadius = Math.max(0.0, finite(cornerRadius, 8.0)).toFloat(),
758
754
  fillColor = colorFromARGB(fillColor),
759
755
  )
760
- inputView.alignment = when (textAlign) {
756
+ inputView.contentInsets = android.graphics.RectF(
757
+ Math.max(0.0, finite(textInsetLeft, 0.0)).toFloat(), Math.max(0.0, finite(textInsetTop, 0.0)).toFloat(),
758
+ Math.max(0.0, finite(textInsetRight, 0.0)).toFloat(), Math.max(0.0, finite(textInsetBottom, 0.0)).toFloat(),
759
+ )
760
+ inputView.alignment = when (textAlignment) {
761
761
  NitroInputTextAlign.CENTER -> NitroInputView.Alignment.CENTER
762
762
  NitroInputTextAlign.RIGHT -> NitroInputView.Alignment.RIGHT
763
763
  NitroInputTextAlign.LEFT -> NitroInputView.Alignment.LEFT