react-native-nitro-input 0.4.0 → 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 (38) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +2 -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/HybridNitroInputView.kt +6 -0
  5. package/android/src/main/java/com/margelo/nitro/nitroinput/InputFonts.kt +50 -5
  6. package/android/src/main/java/com/margelo/nitro/nitroinput/InputSizing.kt +7 -1
  7. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputView.kt +57 -6
  8. package/ios/HybridNitroInputView.swift +4 -0
  9. package/ios/InputSizing.swift +98 -4
  10. package/ios/NitroInputView.swift +79 -12
  11. package/lib/commonjs/nitrogen/generated/shared/json/NitroInputViewConfig.json +2 -0
  12. package/lib/commonjs/src/NitroInput.js +3 -1
  13. package/lib/module/nitrogen/generated/shared/json/NitroInputViewConfig.json +2 -0
  14. package/lib/module/src/NitroInput.js +3 -1
  15. package/lib/typescript/src/NitroInput.d.ts +11 -0
  16. package/lib/typescript/src/specs/NitroInput.nitro.d.ts +4 -0
  17. package/lib/typescript/src/specs/NitroInputMeasure.nitro.d.ts +2 -0
  18. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.cpp +18 -0
  19. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.hpp +4 -0
  20. package/nitrogen/generated/android/c++/JNitroInputSizing.hpp +9 -1
  21. package/nitrogen/generated/android/c++/views/JHybridNitroInputViewStateUpdater.cpp +10 -0
  22. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroInputViewSpec.kt +12 -0
  23. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputSizing.kt +12 -2
  24. package/nitrogen/generated/ios/c++/HybridNitroInputViewSpecSwift.hpp +12 -0
  25. package/nitrogen/generated/ios/c++/views/HybridNitroInputViewComponent.mm +12 -0
  26. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec.swift +2 -0
  27. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec_cxx.swift +22 -0
  28. package/nitrogen/generated/ios/swift/NitroInputSizing.swift +12 -2
  29. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.cpp +4 -0
  30. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.hpp +4 -0
  31. package/nitrogen/generated/shared/c++/NitroInputSizing.hpp +9 -1
  32. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.cpp +4 -0
  33. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.hpp +6 -0
  34. package/nitrogen/generated/shared/json/NitroInputViewConfig.json +2 -0
  35. package/package.json +1 -1
  36. package/src/NitroInput.tsx +14 -0
  37. package/src/specs/NitroInput.nitro.ts +4 -0
  38. package/src/specs/NitroInputMeasure.nitro.ts +2 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
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
+
3
19
  ## 0.4.0
4
20
 
5
21
  - **Android: `NitroNumber`'s numeric transition no longer blocks the UI
package/README.md CHANGED
@@ -521,6 +521,7 @@ screen behaves like theirs with these settings:
521
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). |
522
522
  | `prefixAlign` / `suffixAlign` | same | `affixAlign` | Per-affix override. |
523
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']`. |
524
525
  | `prefixSpacing` / `suffixSpacing` | number | the letter spacing | Points between the prefix and the text, and between the text and the suffix. |
525
526
  | `prefixOffset` / `suffixOffset` | number | `0` | Points an affix is moved down after its alignment (negative: up). |
526
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. |
@@ -587,7 +588,7 @@ screen behaves like theirs with these settings:
587
588
  | `onKeyPress` | `(event) => void` | – | Before the text changes: the character, `'Backspace'` or `'Enter'`. |
588
589
  | `onNativeRef` | `(ref) => void` | – | Receives the Nitro object on mount. |
589
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. |
590
- | `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 always tabular (Android's Roboto has them anyway, and a field keeps its width whether it reflows or not), and Android gets no default padding (iOS's `TextInput` has none; React Native's Android one keeps the platform field's). |
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). |
591
592
 
592
593
  `keyboardType`: `'default' | 'number-pad' | 'decimal-pad' | 'numeric' | 'email-address' | 'phone-pad' | 'url' | 'ascii-capable' | 'numbers-and-punctuation'`.
593
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
+ }
@@ -129,6 +129,10 @@ class HybridNitroInputView(private val context: ThemedReactContext) : HybridNitr
129
129
  set(v) { field = v; markConfigDirty() }
130
130
  override var textLetterSpacing: Double = 0.0
131
131
  set(v) { field = v; markConfigDirty() }
132
+ override var tabularNums: Boolean = true
133
+ set(v) { field = v; markConfigDirty() }
134
+ override var slotDigits: Boolean = false
135
+ set(v) { field = v; markConfigDirty() }
132
136
  override var prefixSpacing: Double = Double.POSITIVE_INFINITY
133
137
  set(v) { field = v; markConfigDirty() }
134
138
  override var suffixSpacing: Double = Double.POSITIVE_INFINITY
@@ -423,6 +427,8 @@ class HybridNitroInputView(private val context: ThemedReactContext) : HybridNitr
423
427
  suffixFontSize = Double.NaN
424
428
  signPlacement = NitroInputSignPlacement.BEFOREAFFIX
425
429
  textLetterSpacing = 0.0
430
+ tabularNums = true
431
+ slotDigits = false
426
432
  prefixSpacing = Double.POSITIVE_INFINITY
427
433
  suffixSpacing = Double.POSITIVE_INFINITY
428
434
  prefixOffset = 0.0
@@ -86,9 +86,54 @@ internal class InputFonts(
86
86
  InputRole.SUFFIX -> suffix
87
87
  }
88
88
 
89
- /** Advance of one character, in px. */
89
+ /**
90
+ * The body's digits when they are slotted (`tabularNums` set) and the font
91
+ * has no tabular figures: each is then laid out in a slot as wide as the
92
+ * widest ([DigitSlots]); null otherwise. The affixes keep their own: they
93
+ * never change under the typing.
94
+ */
95
+ private val bodyDigits: DigitSlots.Digits? = if (t.slotDigits) DigitSlots.measure(body) else null
96
+
97
+ /** A slotted body digit's advance, its letter spacing aside: the edit text's slot less that spacing. */
98
+ private val bodySlot: Float = bodyDigits?.let { it.slot(bodySpacing) - bodySpacing } ?: 0f
99
+
100
+ private fun slotted(codePoint: Int, role: InputRole): Boolean =
101
+ role == InputRole.BODY && bodyDigits != null && DigitSlots.isDigit(codePoint)
102
+
103
+ /** Advance of one character, in px: a slotted digit's is the slot's. */
90
104
  fun width(codePoint: Int, role: InputRole): Float =
91
- widthCaches[role.ordinal].getOrPut(codePoint) { paint(role).measureText(charString(codePoint)) }
105
+ widthCaches[role.ordinal].getOrPut(codePoint) {
106
+ if (slotted(codePoint, role)) bodySlot else paint(role).measureText(charString(codePoint))
107
+ }
108
+
109
+ /** How far to draw a character in from the left of its advance: a slotted digit is centred in it. */
110
+ fun inset(codePoint: Int, role: InputRole): Float {
111
+ if (!slotted(codePoint, role)) return 0f
112
+ return (bodySlot - bodyDigits!!.widths[codePoint - '0'.code]) / 2f
113
+ }
114
+
115
+ /**
116
+ * [text] in the body paint as the edit text lays it out, without letter
117
+ * spacing: whole, or, when its digits are slotted, in runs split at each
118
+ * digit, which is where the slots' spans split it.
119
+ */
120
+ fun plainWidth(text: String): Float {
121
+ if (bodyDigits == null) return body.measureText(text)
122
+ var total = 0f
123
+ var start = 0
124
+ while (start < text.length) {
125
+ if (DigitSlots.isDigit(text[start].code)) {
126
+ total += width(text[start].code, InputRole.BODY)
127
+ start++
128
+ continue
129
+ }
130
+ var end = start + 1
131
+ while (end < text.length && !DigitSlots.isDigit(text[end].code)) end++
132
+ total += body.measureText(text, start, end)
133
+ start = end
134
+ }
135
+ return total
136
+ }
92
137
 
93
138
  /** Sum of the per-character advances of [text] (what the engine lays out). */
94
139
  fun width(text: String, role: InputRole): Float {
@@ -174,9 +219,9 @@ internal class InputFonts(
174
219
  paint.typeface = makeTypeface(t)
175
220
  paint.textSize = sizeDp * density
176
221
  paint.color = t.color ?: defaultColor
177
- // Tabular figures in every mode, as on iOS: the engine slides digit runs
178
- // in text mode too, and proportional digits would jitter as they change.
179
- paint.fontFeatureSettings = "tnum"
222
+ // Tabular figures unless asked not to, as on iOS: the engine slides digit
223
+ // runs in text mode too, and proportional digits would jitter as they change.
224
+ paint.fontFeatureSettings = if (t.tabularNums) "tnum" else "pnum"
180
225
  return paint
181
226
  }
182
227
 
@@ -41,6 +41,8 @@ internal interface InputSizingProps {
41
41
  val textWeight: Double
42
42
  val textFamily: String
43
43
  val textLetterSpacing: Double
44
+ val tabularNums: Boolean
45
+ val slotDigits: Boolean
44
46
  val prefixSpacing: Double
45
47
  val suffixSpacing: Double
46
48
  val allowFontScaling: Boolean
@@ -96,6 +98,8 @@ internal fun sizingTypographyOf(p: InputSizingProps, density: Float): Typography
96
98
  fontWeight = clampedInt(p.textWeight, 100, 900, 400),
97
99
  fontFamily = p.textFamily.ifEmpty { null },
98
100
  letterSpacing = if (p.textLetterSpacing.isFinite()) p.textLetterSpacing.toFloat() else 0f,
101
+ tabularNums = p.tabularNums,
102
+ slotDigits = p.slotDigits,
99
103
  prefixSpacing = p.prefixSpacing.takeIf { it.isFinite() }?.toFloat(),
100
104
  suffixSpacing = p.suffixSpacing.takeIf { it.isFinite() }?.toFloat(),
101
105
  allowFontScaling = p.allowFontScaling,
@@ -328,7 +332,7 @@ internal object InputSizing {
328
332
  */
329
333
  fun plainWidthPx(f: InputFonts, format: Format, body: String): Float =
330
334
  f.affixRoom(format.prefix, InputRole.PREFIX) +
331
- f.paint(InputRole.BODY).measureText(body) + f.bodySpacing * body.codePointCount(0, body.length) +
335
+ f.plainWidth(body) + f.bodySpacing * body.codePointCount(0, body.length) +
332
336
  f.affixRoom(format.suffix, InputRole.SUFFIX)
333
337
 
334
338
  /** What a plain field measures: the placeholder when empty, bullets when secure, else the text and its tail. */
@@ -386,6 +390,8 @@ internal class SizingProps(s: NitroInputSizing) : InputSizingProps {
386
390
  override val textWeight = s.textWeight
387
391
  override val textFamily = s.textFamily
388
392
  override val textLetterSpacing = s.textLetterSpacing
393
+ override val tabularNums = s.tabularNums
394
+ override val slotDigits = s.slotDigits
389
395
  override val prefixSpacing = s.prefixSpacing
390
396
  override val suffixSpacing = s.suffixSpacing
391
397
  override val allowFontScaling = s.allowFontScaling
@@ -142,6 +142,10 @@ class NitroInputView(context: Context) : FrameLayout(context) {
142
142
  val suffixAlign: AffixAlign = AffixAlign.BASELINE,
143
143
  /** Dp added after every glyph, as `Text`'s letterSpacing; an affix gets it in proportion to its size. */
144
144
  val letterSpacing: Float = 0f,
145
+ /** The font's tabular figures (`tnum`) rather than its proportional ones. */
146
+ val tabularNums: Boolean = true,
147
+ /** Every digit laid out as wide as the widest, centred ([DigitSlots]): tabular figures for a font without them. */
148
+ val slotDigits: Boolean = false,
145
149
  /** Dp between the prefix and the text, and between the text and the suffix, in place of the letter spacing there. */
146
150
  val prefixSpacing: Float? = null,
147
151
  val suffixSpacing: Float? = null,
@@ -445,7 +449,11 @@ class NitroInputView(context: Context) : FrameLayout(context) {
445
449
  (scrollX + width - compoundPaddingRight).toFloat(),
446
450
  (scrollY + height).toFloat(),
447
451
  )
448
- canvas.drawText(tail, x, baseline.toFloat(), ghostPaint)
452
+ if (typography.slotDigits) {
453
+ DigitSlots.draw(canvas, tail, x, baseline.toFloat(), ghostPaint)
454
+ } else {
455
+ canvas.drawText(tail, x, baseline.toFloat(), ghostPaint)
456
+ }
449
457
  canvas.restore()
450
458
  }
451
459
 
@@ -639,6 +647,16 @@ class NitroInputView(context: Context) : FrameLayout(context) {
639
647
  editText.setSingleLine()
640
648
  defaultHighlightColor = editText.highlightColor
641
649
  editText.addTextChangedListener(Watcher())
650
+ // After it, and on every change, the engine's own writes included.
651
+ editText.addTextChangedListener(object : TextWatcher {
652
+ override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
653
+
654
+ override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
655
+
656
+ override fun afterTextChanged(s: Editable) {
657
+ DigitSlots.apply(s, editText.paint, off = !slotsDigits)
658
+ }
659
+ })
642
660
  editText.setOnFocusChangeListener { _, focused ->
643
661
  if (resyncingFocus) return@setOnFocusChangeListener
644
662
  restartBlink()
@@ -770,6 +788,13 @@ class NitroInputView(context: Context) : FrameLayout(context) {
770
788
  private fun applyEditTextLayout() {
771
789
  val f = fonts
772
790
  editText.typeface = f.body.typeface
791
+ // The paints' tabular figures too, which the field's own text, its hint and
792
+ // keepPlaceholder's tail (drawn in a copy of its paint) did not get: with a
793
+ // font whose digits are proportional unless asked (ABC Diatype) every typed
794
+ // "1" was narrower than the "0" of the placeholder it replaced, and the
795
+ // rest of the placeholder slid left by the difference on each keystroke.
796
+ // A font with no tabular figures at all is slotted (applyDigitSlots).
797
+ editText.fontFeatureSettings = f.body.fontFeatureSettings
773
798
  // Spaced like the overlay, so the selection highlight lines up with the drawn glyphs.
774
799
  editText.letterSpacing = if (f.body.textSize > 0f) f.bodySpacing / f.body.textSize else 0f
775
800
  // Not `setTextSize` directly: the platform ignores it while auto-sizing is
@@ -829,6 +854,22 @@ class NitroInputView(context: Context) : FrameLayout(context) {
829
854
  Alignment.CENTER -> Gravity.CENTER_HORIZONTAL
830
855
  Alignment.RIGHT -> Gravity.RIGHT
831
856
  }
857
+ applyDigitSlots()
858
+ }
859
+
860
+ /**
861
+ * Gives the edit text's digits, and its hint's, the widest digit's advance
862
+ * when the font has no tabular figures ([DigitSlots]), as [InputFonts] does
863
+ * for the overlay and the measure. A secure field's bullets stand where the
864
+ * digits are, so it has none.
865
+ */
866
+ /** Whether the edit text's own digits are slotted: when asked, and not under a secure field's bullets. */
867
+ private val slotsDigits: Boolean
868
+ get() = typography.slotDigits && !keyboard.secureTextEntry
869
+
870
+ private fun applyDigitSlots() {
871
+ editText.text?.let { DigitSlots.apply(it, editText.paint, off = !slotsDigits) }
872
+ applyHint(force = true)
832
873
  }
833
874
 
834
875
  // endregion
@@ -883,7 +924,10 @@ class NitroInputView(context: Context) : FrameLayout(context) {
883
924
  // A password input type switches the field to monospace, so its bullets
884
925
  // were wider than the field measures them; React Native's TextInput puts
885
926
  // the typeface back the same way.
886
- if (k.secureTextEntry) editText.typeface = fonts.body.typeface
927
+ if (k.secureTextEntry) {
928
+ editText.typeface = fonts.body.typeface
929
+ editText.fontFeatureSettings = fonts.body.fontFeatureSettings
930
+ }
887
931
  if (rawType != null) editText.setRawInputType(rawType)
888
932
  if (k.multiline) {
889
933
  editText.setSingleLine(false)
@@ -902,6 +946,7 @@ class NitroInputView(context: Context) : FrameLayout(context) {
902
946
  if (k.secureTextEntry) {
903
947
  editText.transformationMethod = android.text.method.PasswordTransformationMethod.getInstance()
904
948
  }
949
+ applyDigitSlots()
905
950
  val length = editText.text?.length ?: 0
906
951
  if (selectionStart >= 0 && (editText.selectionStart != selectionStart || editText.selectionEnd != selectionEnd)) {
907
952
  editText.setSelection(minOf(selectionStart, length), minOf(maxOf(selectionStart, selectionEnd), length))
@@ -1006,6 +1051,7 @@ class NitroInputView(context: Context) : FrameLayout(context) {
1006
1051
  if (edge == Gravity.END) side else 0, 0)
1007
1052
  view.gravity = Gravity.CENTER_VERTICAL
1008
1053
  view.typeface = paint.typeface
1054
+ view.fontFeatureSettings = paint.fontFeatureSettings
1009
1055
  view.setTextSize(TypedValue.COMPLEX_UNIT_PX, paint.textSize)
1010
1056
  view.letterSpacing = if (paint.textSize > 0f) fonts.spacing(role) / paint.textSize else 0f
1011
1057
  // The seam against the text, and the affix's own offset.
@@ -1860,10 +1906,12 @@ class NitroInputView(context: Context) : FrameLayout(context) {
1860
1906
  }
1861
1907
  if (g.scale != 1f) canvas.scale(g.scale, g.scale, g.x + g.width / 2f, lineHeight / 2f)
1862
1908
  val baseline = f.baseline(role, str, 0f) + g.y * lineHeight
1909
+ // A digit in a font without tabular figures, centred in its slot.
1910
+ val inset = f.inset(g.character, role)
1863
1911
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
1864
- glyphPositions = f.shaped(g.character, role).draw(canvas, g.x, baseline, paint, glyphPositions)
1912
+ glyphPositions = f.shaped(g.character, role).draw(canvas, g.x + inset, baseline, paint, glyphPositions)
1865
1913
  } else {
1866
- canvas.drawText(str, g.x, baseline, paint)
1914
+ canvas.drawText(str, g.x + inset, baseline, paint)
1867
1915
  }
1868
1916
  canvas.restore()
1869
1917
  }
@@ -2053,9 +2101,12 @@ class NitroInputView(context: Context) : FrameLayout(context) {
2053
2101
  }
2054
2102
 
2055
2103
  /** The placeholder waits for a resting label to float clear of the line. */
2056
- private fun applyHint() {
2104
+ private fun applyHint(force: Boolean = false) {
2057
2105
  val hint = effectivePlaceholder
2058
- if (editText.hint?.toString() != hint) editText.hint = hint
2106
+ if (!force && editText.hint?.toString() == hint) return
2107
+ val spanned = android.text.SpannableString(hint)
2108
+ DigitSlots.apply(spanned, editText.paint, off = !typography.slotDigits)
2109
+ editText.hint = spanned
2059
2110
  }
2060
2111
 
2061
2112
  /** Re-feeds the engine so the placeholder follows the label. */
@@ -118,6 +118,8 @@ final class HybridNitroInputView: HybridNitroInputViewSpec, RecyclableView {
118
118
  var prefixAlign: NitroInputAffixAlign = .baseline { didSet { markConfigDirty() } }
119
119
  var suffixAlign: NitroInputAffixAlign = .baseline { didSet { markConfigDirty() } }
120
120
  var textLetterSpacing: Double = 0 { didSet { markConfigDirty() } }
121
+ var tabularNums: Bool = true { didSet { markConfigDirty() } }
122
+ var slotDigits: Bool = false { didSet { markConfigDirty() } }
121
123
  var prefixSpacing: Double = .infinity { didSet { markConfigDirty() } }
122
124
  var suffixSpacing: Double = .infinity { didSet { markConfigDirty() } }
123
125
  var prefixOffset: Double = 0 { didSet { markConfigDirty() } }
@@ -337,6 +339,8 @@ final class HybridNitroInputView: HybridNitroInputViewSpec, RecyclableView {
337
339
  prefixAlign = .baseline
338
340
  suffixAlign = .baseline
339
341
  textLetterSpacing = 0
342
+ tabularNums = true
343
+ slotDigits = false
340
344
  prefixSpacing = .infinity
341
345
  suffixSpacing = .infinity
342
346
  prefixOffset = 0
@@ -47,6 +47,8 @@ protocol InputSizingProps {
47
47
  var textWeight: Double { get }
48
48
  var textFamily: String { get }
49
49
  var textLetterSpacing: Double { get }
50
+ var tabularNums: Bool { get }
51
+ var slotDigits: Bool { get }
50
52
  var prefixSpacing: Double { get }
51
53
  var suffixSpacing: Double { get }
52
54
  var allowFontScaling: Bool { get }
@@ -108,6 +110,8 @@ enum InputMapping {
108
110
  typography.fontWeight = CGFloat(p.textWeight.isFinite ? p.textWeight : 400)
109
111
  typography.fontFamily = p.textFamily.isEmpty ? nil : p.textFamily
110
112
  typography.letterSpacing = CGFloat(p.textLetterSpacing.isFinite ? p.textLetterSpacing : 0)
113
+ typography.tabularNums = p.tabularNums
114
+ typography.slotDigits = p.slotDigits
111
115
  typography.prefixSpacing = p.prefixSpacing.isFinite ? CGFloat(p.prefixSpacing) : nil
112
116
  typography.suffixSpacing = p.suffixSpacing.isFinite ? CGFloat(p.suffixSpacing) : nil
113
117
  typography.allowFontScaling = p.allowFontScaling
@@ -215,6 +219,17 @@ final class InputMetrics {
215
219
  let lineBoxHeight: CGFloat
216
220
  /// The advance of one of the bullets a plain secure field draws (see `init`).
217
221
  let secureBulletWidth: CGFloat
222
+ /// The body's digit advances when they are slotted (`tabularNums` set) and
223
+ /// the font has no tabular figures; nil otherwise. The monospaced-numbers feature asks for them, but a font
224
+ /// without it (Open Runde) keeps proportional digits: every typed "1" was
225
+ /// narrower than the placeholder's "0" it replaced, so `keepPlaceholder`'s
226
+ /// tail slid left on each keystroke and an amount changed width as its
227
+ /// digits did. Such a font's digits each get a slot as wide as the widest,
228
+ /// centred in it, as NitroNumber's columns do (and as Android's DigitSlots
229
+ /// does). The affixes keep their own: they never change under the typing.
230
+ let bodyDigitWidths: [CGFloat]?
231
+ /// The slot a body digit is laid out in, when `bodyDigitWidths` is set.
232
+ let bodySlot: CGFloat
218
233
  private var widthCache: [WidthKey: CGFloat] = [:]
219
234
 
220
235
  private struct WidthKey: Hashable {
@@ -224,9 +239,11 @@ final class InputMetrics {
224
239
 
225
240
  init(_ t: NitroInputView.Typography) {
226
241
  let scale = NitroInputView.systemFontMultiplier(t)
227
- body = NitroInputView.makeFont(size: t.fontSize * scale, weight: t.fontWeight, family: t.fontFamily)
228
- prefix = NitroInputView.makeFont(size: (t.prefixFontSize ?? t.fontSize) * scale, weight: t.fontWeight, family: t.fontFamily)
229
- suffix = NitroInputView.makeFont(size: (t.suffixFontSize ?? t.fontSize) * scale, weight: t.fontWeight, family: t.fontFamily)
242
+ body = NitroInputView.makeFont(size: t.fontSize * scale, weight: t.fontWeight, family: t.fontFamily, tabular: t.tabularNums)
243
+ prefix = NitroInputView.makeFont(size: (t.prefixFontSize ?? t.fontSize) * scale, weight: t.fontWeight, family: t.fontFamily,
244
+ tabular: t.tabularNums)
245
+ suffix = NitroInputView.makeFont(size: (t.suffixFontSize ?? t.fontSize) * scale, weight: t.fontWeight, family: t.fontFamily,
246
+ tabular: t.tabularNums)
230
247
  bodySpacing = t.letterSpacing * scale
231
248
  prefixLetterSpacing = t.letterSpacing * scale * (prefix.pointSize / body.pointSize)
232
249
  suffixLetterSpacing = t.letterSpacing * scale * (suffix.pointSize / body.pointSize)
@@ -245,6 +262,10 @@ final class InputMetrics {
245
262
  ? UIFont.systemFont(ofSize: body.pointSize, weight: NitroInputView.uiWeight(t.fontWeight))
246
263
  : UIFont.systemFont(ofSize: body.pointSize)
247
264
  secureBulletWidth = ("\u{2219}" as NSString).size(withAttributes: [.font: bulletFont]).width
265
+ let bodyFont = body
266
+ let digits = (0..<10).map { NSAttributedString(string: String($0), attributes: [.font: bodyFont, .kern: 0]).size().width }
267
+ bodySlot = digits.max() ?? 0
268
+ bodyDigitWidths = t.slotDigits && bodySlot - (digits.min() ?? 0) > bodyFont.pointSize * 0.01 ? digits : nil
248
269
  }
249
270
 
250
271
  func font(for role: NitroInputView.GlyphRole) -> UIFont {
@@ -268,11 +289,84 @@ final class InputMetrics {
268
289
  func width(of text: String, role: NitroInputView.GlyphRole) -> CGFloat {
269
290
  let key = WidthKey(text: text, role: role)
270
291
  if let cached = widthCache[key] { return cached }
271
- let width = NSAttributedString(string: text, attributes: [.font: font(for: role), .kern: 0]).size().width
292
+ var width = NSAttributedString(string: text, attributes: [.font: font(for: role), .kern: 0]).size().width
293
+ if role == .body, bodyDigitWidths != nil {
294
+ for scalar in text.unicodeScalars { width += 2 * halfRoom(scalar) }
295
+ }
272
296
  widthCache[key] = width
273
297
  return width
274
298
  }
275
299
 
300
+ private static func digit(_ scalar: Unicode.Scalar) -> Int? {
301
+ scalar.value >= 0x30 && scalar.value <= 0x39 ? Int(scalar.value - 0x30) : nil
302
+ }
303
+
304
+ /// Half the room a body digit's slot leaves beside its glyph (0 for anything else).
305
+ private func halfRoom(_ scalar: Unicode.Scalar) -> CGFloat {
306
+ guard let widths = bodyDigitWidths, let digit = Self.digit(scalar) else { return 0 }
307
+ return (bodySlot - widths[digit]) / 2
308
+ }
309
+
310
+ private var pairKernCache: [UInt64: CGFloat] = [:]
311
+
312
+ /// The body font's own kerning between `a` and `b`, which non-zero `.kern`s on both leave in place.
313
+ private func pairKern(_ a: Unicode.Scalar, _ b: Unicode.Scalar) -> CGFloat {
314
+ let key = UInt64(a.value) << 32 | UInt64(b.value)
315
+ if let cached = pairKernCache[key] { return cached }
316
+ // The pair with a kern of 1 on both glyphs, against the same with kerning off.
317
+ func line(_ kern: CGFloat) -> CGFloat {
318
+ let pair = NSAttributedString(string: String(a) + String(b), attributes: [.font: body, .kern: kern])
319
+ return CGFloat(CTLineGetTypographicBounds(CTLineCreateWithAttributedString(pair), nil, nil, nil))
320
+ }
321
+ let kern = line(1) - 2 - line(0)
322
+ pairKernCache[key] = kern
323
+ return kern
324
+ }
325
+
326
+ /// How far in from the left of its advance to draw `text` (one glyph): a slotted digit is centred in it.
327
+ func inset(of text: String, role: NitroInputView.GlyphRole) -> CGFloat {
328
+ guard role == .body, let scalar = text.unicodeScalars.first else { return 0 }
329
+ return halfRoom(scalar)
330
+ }
331
+
332
+ /// `text` in `attributes`, kerned for UIKit to lay out as the overlay and the
333
+ /// measure do: the body spacing after every glyph and each digit in its slot.
334
+ /// Kerning only adds room after a glyph, so half a digit's room goes after
335
+ /// the glyph before it and half after its own. A first digit has none before
336
+ /// it: with `lead`, that half is returned for the caller to move the text by
337
+ /// (the tail's label); without, the first line is indented by it (the
338
+ /// field's text and placeholder, which UIKit places itself). Nil when the
339
+ /// digits are not slotted.
340
+ func slotted(_ text: String, attributes: [NSAttributedString.Key: Any], lead: Bool) -> (string: NSAttributedString, lead: CGFloat)? {
341
+ guard bodyDigitWidths != nil else { return nil }
342
+ let result = NSMutableAttributedString(string: text, attributes: attributes)
343
+ let scalars = Array(text.unicodeScalars)
344
+ let halves = scalars.map(halfRoom)
345
+ var leading: CGFloat = 0
346
+ var offset = 0
347
+ let kerns = halves.indices.map { bodySpacing + halves[$0] + ($0 + 1 < halves.count ? halves[$0 + 1] : 0) }
348
+ for (i, scalar) in scalars.enumerated() {
349
+ var kern = kerns[i]
350
+ // The font's kerning between two glyphs comes back once both carry a
351
+ // kern other than 0 (Open Runde kerns "74" by -0.058 em). The measure
352
+ // has it off, so it is taken back out of the first one's.
353
+ if i + 1 < scalars.count, kern != 0, kerns[i + 1] != 0 {
354
+ kern -= pairKern(scalar, scalars[i + 1])
355
+ if kern == 0 { kern = 0.0001 }
356
+ }
357
+ if i == 0 { leading = halves[0] }
358
+ let length = String(scalar).utf16.count
359
+ result.addAttribute(.kern, value: kern, range: NSRange(location: offset, length: length))
360
+ offset += length
361
+ }
362
+ if !lead, leading > 0 {
363
+ let style = ((attributes[.paragraphStyle] as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle) ?? NSMutableParagraphStyle()
364
+ style.firstLineHeadIndent = leading
365
+ result.addAttribute(.paragraphStyle, value: style, range: NSRange(location: 0, length: result.length))
366
+ }
367
+ return (result, leading)
368
+ }
369
+
276
370
  /// The room an affix takes beside the text: its glyphs, their spacing and the seam.
277
371
  func affixRoom(_ affix: String, role: NitroInputView.GlyphRole) -> CGFloat {
278
372
  guard !affix.isEmpty else { return 0 }