react-native-nitro-input 0.1.0

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 (187) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/LICENSE +21 -0
  3. package/NitroInput.podspec +54 -0
  4. package/README.md +524 -0
  5. package/android/CMakeLists.txt +52 -0
  6. package/android/build.gradle +158 -0
  7. package/android/fix-prefab.gradle +51 -0
  8. package/android/gradle.properties +4 -0
  9. package/android/src/main/AndroidManifest.xml +2 -0
  10. package/android/src/main/cpp/JAmountFormatter.cpp +70 -0
  11. package/android/src/main/cpp/JAmountFormatter.hpp +45 -0
  12. package/android/src/main/cpp/JMaskEngine.cpp +81 -0
  13. package/android/src/main/cpp/JMaskEngine.hpp +52 -0
  14. package/android/src/main/cpp/JMorphEngine.cpp +132 -0
  15. package/android/src/main/cpp/JMorphEngine.hpp +54 -0
  16. package/android/src/main/cpp/JNitroInputWorklets.cpp +83 -0
  17. package/android/src/main/cpp/JNitroInputWorklets.hpp +40 -0
  18. package/android/src/main/cpp/JOutlineGeometry.cpp +58 -0
  19. package/android/src/main/cpp/JOutlineGeometry.hpp +55 -0
  20. package/android/src/main/cpp/cpp-adapter.cpp +19 -0
  21. package/android/src/main/java/com/margelo/nitro/nitroinput/AmountFormatter.kt +35 -0
  22. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroInputView.kt +730 -0
  23. package/android/src/main/java/com/margelo/nitro/nitroinput/MaskEngine.kt +50 -0
  24. package/android/src/main/java/com/margelo/nitro/nitroinput/MorphEngine.kt +47 -0
  25. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputPackage.kt +24 -0
  26. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputView.kt +2176 -0
  27. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputWorklets.kt +34 -0
  28. package/android/src/main/java/com/margelo/nitro/nitroinput/OutlineGeometry.kt +71 -0
  29. package/cpp/AmountFormatter.cpp +346 -0
  30. package/cpp/AmountFormatter.hpp +88 -0
  31. package/cpp/MaskEngine.cpp +596 -0
  32. package/cpp/MaskEngine.hpp +136 -0
  33. package/cpp/MorphEngine.cpp +904 -0
  34. package/cpp/MorphEngine.hpp +213 -0
  35. package/cpp/OutlineGeometry.cpp +159 -0
  36. package/cpp/OutlineGeometry.hpp +107 -0
  37. package/cpp/worklets/HybridNitroInputWorklets.cpp +30 -0
  38. package/cpp/worklets/HybridNitroInputWorklets.hpp +30 -0
  39. package/cpp/worklets/NitroInputWorkletsBridge.cpp +203 -0
  40. package/cpp/worklets/NitroInputWorkletsBridge.hpp +52 -0
  41. package/cpp/worklets/NitroInputWorkletsBridgeJSI.hpp +23 -0
  42. package/ios/HybridMorphInputView.swift +710 -0
  43. package/ios/NitroInputCommands.mm +66 -0
  44. package/ios/NitroInputView.swift +2600 -0
  45. package/lib/commonjs/nitrogen/generated/shared/json/NitroInputViewConfig.json +101 -0
  46. package/lib/commonjs/src/MorphInput.js +42 -0
  47. package/lib/commonjs/src/NitroInput.js +623 -0
  48. package/lib/commonjs/src/index.js +12 -0
  49. package/lib/commonjs/src/specs/NitroInput.nitro.js +2 -0
  50. package/lib/commonjs/src/specs/NitroInputWorklets.nitro.js +2 -0
  51. package/lib/commonjs/src/useNitroInputState.js +58 -0
  52. package/lib/commonjs/src/worklets.js +226 -0
  53. package/lib/module/nitrogen/generated/shared/json/NitroInputViewConfig.json +101 -0
  54. package/lib/module/package.json +1 -0
  55. package/lib/module/src/MorphInput.js +6 -0
  56. package/lib/module/src/NitroInput.js +584 -0
  57. package/lib/module/src/index.js +4 -0
  58. package/lib/module/src/specs/NitroInput.nitro.js +1 -0
  59. package/lib/module/src/specs/NitroInputWorklets.nitro.js +1 -0
  60. package/lib/module/src/useNitroInputState.js +55 -0
  61. package/lib/module/src/worklets.js +214 -0
  62. package/lib/typescript/src/MorphInput.d.ts +18 -0
  63. package/lib/typescript/src/NitroInput.d.ts +411 -0
  64. package/lib/typescript/src/index.d.ts +6 -0
  65. package/lib/typescript/src/specs/NitroInput.nitro.d.ts +390 -0
  66. package/lib/typescript/src/specs/NitroInputWorklets.nitro.d.ts +15 -0
  67. package/lib/typescript/src/useNitroInputState.d.ts +55 -0
  68. package/lib/typescript/src/worklets.d.ts +117 -0
  69. package/nitro.json +37 -0
  70. package/nitrogen/generated/.gitattributes +1 -0
  71. package/nitrogen/generated/android/NitroInput+autolinking.cmake +84 -0
  72. package/nitrogen/generated/android/NitroInput+autolinking.gradle +27 -0
  73. package/nitrogen/generated/android/NitroInputOnLoad.cpp +78 -0
  74. package/nitrogen/generated/android/NitroInputOnLoad.hpp +34 -0
  75. package/nitrogen/generated/android/c++/JFunc_void_bool.hpp +75 -0
  76. package/nitrogen/generated/android/c++/JFunc_void_double.hpp +75 -0
  77. package/nitrogen/generated/android/c++/JFunc_void_double_double.hpp +75 -0
  78. package/nitrogen/generated/android/c++/JFunc_void_std__string.hpp +76 -0
  79. package/nitrogen/generated/android/c++/JFunc_void_std__string_double.hpp +76 -0
  80. package/nitrogen/generated/android/c++/JFunc_void_std__string_std__string_std__string_bool.hpp +76 -0
  81. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.cpp +1073 -0
  82. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.hpp +254 -0
  83. package/nitrogen/generated/android/c++/JNitroInputAffixAlign.hpp +64 -0
  84. package/nitrogen/generated/android/c++/JNitroInputAutoCapitalize.hpp +64 -0
  85. package/nitrogen/generated/android/c++/JNitroInputEasing.hpp +67 -0
  86. package/nitrogen/generated/android/c++/JNitroInputEffect.hpp +61 -0
  87. package/nitrogen/generated/android/c++/JNitroInputKeyboardAppearance.hpp +61 -0
  88. package/nitrogen/generated/android/c++/JNitroInputKeyboardType.hpp +79 -0
  89. package/nitrogen/generated/android/c++/JNitroInputLabelBehavior.hpp +58 -0
  90. package/nitrogen/generated/android/c++/JNitroInputMode.hpp +61 -0
  91. package/nitrogen/generated/android/c++/JNitroInputNotation.hpp +65 -0
  92. package/nitrogen/generated/android/c++/JNitroInputReturnKeyType.hpp +70 -0
  93. package/nitrogen/generated/android/c++/JNitroInputSignPlacement.hpp +58 -0
  94. package/nitrogen/generated/android/c++/JNitroInputSubmitBehavior.hpp +61 -0
  95. package/nitrogen/generated/android/c++/JNitroInputTextAlign.hpp +64 -0
  96. package/nitrogen/generated/android/c++/JNitroInputTextAlignVertical.hpp +64 -0
  97. package/nitrogen/generated/android/c++/JNitroInputVariant.hpp +61 -0
  98. package/nitrogen/generated/android/c++/views/JHybridNitroInputViewStateUpdater.cpp +529 -0
  99. package/nitrogen/generated/android/c++/views/JHybridNitroInputViewStateUpdater.hpp +54 -0
  100. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/Func_void_bool.kt +78 -0
  101. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/Func_void_double.kt +78 -0
  102. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/Func_void_double_double.kt +78 -0
  103. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/Func_void_std__string.kt +78 -0
  104. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/Func_void_std__string_double.kt +78 -0
  105. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/Func_void_std__string_std__string_std__string_bool.kt +78 -0
  106. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroInputViewSpec.kt +711 -0
  107. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputAffixAlign.kt +25 -0
  108. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputAutoCapitalize.kt +25 -0
  109. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputEasing.kt +26 -0
  110. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputEffect.kt +24 -0
  111. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputKeyboardAppearance.kt +24 -0
  112. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputKeyboardType.kt +30 -0
  113. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputLabelBehavior.kt +23 -0
  114. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputMode.kt +24 -0
  115. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputNotation.kt +61 -0
  116. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputOnLoad.kt +35 -0
  117. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputReturnKeyType.kt +27 -0
  118. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputSignPlacement.kt +23 -0
  119. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputSubmitBehavior.kt +24 -0
  120. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputTextAlign.kt +25 -0
  121. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputTextAlignVertical.kt +25 -0
  122. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputVariant.kt +24 -0
  123. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/views/HybridNitroInputViewManager.kt +96 -0
  124. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/views/HybridNitroInputViewStateUpdater.kt +23 -0
  125. package/nitrogen/generated/ios/NitroInput+autolinking.rb +62 -0
  126. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.cpp +81 -0
  127. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.hpp +348 -0
  128. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Umbrella.hpp +92 -0
  129. package/nitrogen/generated/ios/NitroInputAutolinking.mm +43 -0
  130. package/nitrogen/generated/ios/NitroInputAutolinking.swift +26 -0
  131. package/nitrogen/generated/ios/c++/HybridNitroInputViewSpecSwift.cpp +11 -0
  132. package/nitrogen/generated/ios/c++/HybridNitroInputViewSpecSwift.hpp +769 -0
  133. package/nitrogen/generated/ios/c++/views/HybridNitroInputViewComponent.mm +690 -0
  134. package/nitrogen/generated/ios/swift/Func_void_bool.swift +46 -0
  135. package/nitrogen/generated/ios/swift/Func_void_double.swift +46 -0
  136. package/nitrogen/generated/ios/swift/Func_void_double_double.swift +46 -0
  137. package/nitrogen/generated/ios/swift/Func_void_std__string.swift +46 -0
  138. package/nitrogen/generated/ios/swift/Func_void_std__string_double.swift +46 -0
  139. package/nitrogen/generated/ios/swift/Func_void_std__string_std__string_std__string_bool.swift +46 -0
  140. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec.swift +154 -0
  141. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec_cxx.swift +1454 -0
  142. package/nitrogen/generated/ios/swift/NitroInputAffixAlign.swift +48 -0
  143. package/nitrogen/generated/ios/swift/NitroInputAutoCapitalize.swift +48 -0
  144. package/nitrogen/generated/ios/swift/NitroInputEasing.swift +52 -0
  145. package/nitrogen/generated/ios/swift/NitroInputEffect.swift +44 -0
  146. package/nitrogen/generated/ios/swift/NitroInputKeyboardAppearance.swift +44 -0
  147. package/nitrogen/generated/ios/swift/NitroInputKeyboardType.swift +68 -0
  148. package/nitrogen/generated/ios/swift/NitroInputLabelBehavior.swift +40 -0
  149. package/nitrogen/generated/ios/swift/NitroInputMode.swift +44 -0
  150. package/nitrogen/generated/ios/swift/NitroInputNotation.swift +39 -0
  151. package/nitrogen/generated/ios/swift/NitroInputReturnKeyType.swift +56 -0
  152. package/nitrogen/generated/ios/swift/NitroInputSignPlacement.swift +40 -0
  153. package/nitrogen/generated/ios/swift/NitroInputSubmitBehavior.swift +44 -0
  154. package/nitrogen/generated/ios/swift/NitroInputTextAlign.swift +48 -0
  155. package/nitrogen/generated/ios/swift/NitroInputTextAlignVertical.swift +48 -0
  156. package/nitrogen/generated/ios/swift/NitroInputVariant.swift +44 -0
  157. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.cpp +213 -0
  158. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.hpp +300 -0
  159. package/nitrogen/generated/shared/c++/HybridNitroInputWorkletsSpec.cpp +21 -0
  160. package/nitrogen/generated/shared/c++/HybridNitroInputWorkletsSpec.hpp +62 -0
  161. package/nitrogen/generated/shared/c++/NitroInputAffixAlign.hpp +84 -0
  162. package/nitrogen/generated/shared/c++/NitroInputAutoCapitalize.hpp +84 -0
  163. package/nitrogen/generated/shared/c++/NitroInputEasing.hpp +88 -0
  164. package/nitrogen/generated/shared/c++/NitroInputEffect.hpp +80 -0
  165. package/nitrogen/generated/shared/c++/NitroInputKeyboardAppearance.hpp +80 -0
  166. package/nitrogen/generated/shared/c++/NitroInputKeyboardType.hpp +104 -0
  167. package/nitrogen/generated/shared/c++/NitroInputLabelBehavior.hpp +76 -0
  168. package/nitrogen/generated/shared/c++/NitroInputMode.hpp +80 -0
  169. package/nitrogen/generated/shared/c++/NitroInputNotation.hpp +91 -0
  170. package/nitrogen/generated/shared/c++/NitroInputReturnKeyType.hpp +92 -0
  171. package/nitrogen/generated/shared/c++/NitroInputSignPlacement.hpp +76 -0
  172. package/nitrogen/generated/shared/c++/NitroInputSubmitBehavior.hpp +80 -0
  173. package/nitrogen/generated/shared/c++/NitroInputTextAlign.hpp +84 -0
  174. package/nitrogen/generated/shared/c++/NitroInputTextAlignVertical.hpp +84 -0
  175. package/nitrogen/generated/shared/c++/NitroInputVariant.hpp +80 -0
  176. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.cpp +216 -0
  177. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.hpp +374 -0
  178. package/nitrogen/generated/shared/json/NitroInputViewConfig.json +101 -0
  179. package/package.json +141 -0
  180. package/react-native.config.js +16 -0
  181. package/src/MorphInput.tsx +30 -0
  182. package/src/NitroInput.tsx +1364 -0
  183. package/src/index.ts +55 -0
  184. package/src/specs/NitroInput.nitro.ts +436 -0
  185. package/src/specs/NitroInputWorklets.nitro.ts +13 -0
  186. package/src/useNitroInputState.ts +101 -0
  187. package/src/worklets.ts +300 -0
@@ -0,0 +1,2176 @@
1
+ package com.margelo.nitro.nitroinput
2
+
3
+ import android.animation.ValueAnimator
4
+ import android.content.Context
5
+ import android.content.res.Configuration
6
+ import android.database.ContentObserver
7
+ import android.graphics.Canvas
8
+ import android.graphics.Color
9
+ import android.graphics.Paint
10
+ import android.graphics.Path
11
+ import android.graphics.Rect
12
+ import android.graphics.RectF
13
+ import android.graphics.Typeface
14
+ import android.os.Build
15
+ import android.os.Handler
16
+ import android.os.Looper
17
+ import android.os.SystemClock
18
+ import android.provider.Settings
19
+ import android.text.Editable
20
+ import android.text.InputFilter
21
+ import android.text.InputType
22
+ import android.text.Selection
23
+ import android.text.TextPaint
24
+ import android.text.TextWatcher
25
+ import android.util.TypedValue
26
+ import android.view.Choreographer
27
+ import android.view.Gravity
28
+ import android.view.KeyEvent
29
+ import android.view.View
30
+ import android.view.animation.PathInterpolator
31
+ import android.view.inputmethod.EditorInfo
32
+ import android.view.inputmethod.InputConnection
33
+ import android.view.inputmethod.InputMethodManager
34
+ import android.widget.FrameLayout
35
+ import android.widget.TextView
36
+ import androidx.appcompat.widget.AppCompatEditText
37
+ import androidx.core.widget.TextViewCompat
38
+ import com.facebook.react.common.assets.ReactFontManager
39
+ import kotlin.math.abs
40
+ import kotlin.math.ceil
41
+ import kotlin.math.max
42
+ import kotlin.math.min
43
+ import kotlin.math.roundToInt
44
+
45
+ /**
46
+ * The morphing input. A hidden [AppCompatEditText] filling the bounds owns the
47
+ * keyboard, editing, selection, paste and accessibility; an overlay on top
48
+ * draws the glyphs the shared C++ `MorphEngine` reports (through the
49
+ * [MorphEngine] JNI handle) plus our own caret. In number mode every edit is
50
+ * run through the shared `AmountFormatter` before it is committed, so the
51
+ * field never shows an unformatted frame.
52
+ *
53
+ * Mirrors `NitroInputView.swift` on iOS.
54
+ */
55
+ class NitroInputView(context: Context) : FrameLayout(context) {
56
+
57
+ // region Configuration
58
+
59
+ enum class Mode { TEXT, NUMBER, MASK }
60
+ enum class AffixAlign { BASELINE, CENTER, TOP, BOTTOM }
61
+ /** `AUTO` is the start edge of the layout direction, as `TextInput` with no `textAlign`; the rest are absolute. */
62
+ enum class Alignment { AUTO, LEFT, CENTER, RIGHT }
63
+ enum class TextAlignVertical { AUTO, TOP, CENTER, BOTTOM }
64
+ enum class Easing(val raw: Int) { EXPO(0), EASE_OUT(1), EASE_IN_OUT(2), LINEAR(3), SPRING(4) }
65
+ enum class Effect(val raw: Int) { AUTO(0), SLIDE(1), FADE(2) }
66
+ enum class KeyboardType { DEFAULT, NUMBER_PAD, DECIMAL_PAD, NUMERIC, EMAIL_ADDRESS, PHONE_PAD, URL, ASCII_CAPABLE, NUMBERS_AND_PUNCTUATION }
67
+ enum class ReturnKeyType { DEFAULT, DONE, GO, NEXT, SEARCH, SEND }
68
+ enum class AutoCapitalize { NONE, SENTENCES, WORDS, CHARACTERS }
69
+ enum class Variant { NONE, OUTLINED, FILLED }
70
+ enum class LabelBehavior { FLOAT, ALWAYS }
71
+ /**
72
+ * What the return key does, as React Native's `submitBehavior`. On a single
73
+ * line `SUBMIT` and `BLUR_AND_SUBMIT` both fire `onSubmitEditing` (the latter
74
+ * also dismisses the keyboard) and `NEWLINE` does nothing at all; on a
75
+ * wrapping field `NEWLINE` inserts the line break instead.
76
+ */
77
+ enum class SubmitBehavior { SUBMIT, BLUR_AND_SUBMIT, NEWLINE }
78
+
79
+ /** A caller-defined slot character for [Format.mask]. */
80
+ data class MaskNotation(val character: String, val characterSet: String, val isOptional: Boolean)
81
+
82
+ /**
83
+ * The frame the view draws for itself: the outline (or fill) and the floating
84
+ * label. Separate from [Format] because it changes independently. Lengths are
85
+ * dp, like the rest of the props; the view scales them by density.
86
+ *
87
+ * Mirrors `Frame` in `NitroInputView.swift`.
88
+ */
89
+ data class Frame(
90
+ val variant: Variant = Variant.NONE,
91
+ val label: String = "",
92
+ val labelBehavior: LabelBehavior = LabelBehavior.FLOAT,
93
+ val labelColor: Int? = null,
94
+ val labelFocusedColor: Int? = null,
95
+ val labelFontSize: Float = 0f,
96
+ val strokeColor: Int? = null,
97
+ val focusedStrokeColor: Int? = null,
98
+ val strokeWidth: Float = 1f,
99
+ val cornerRadius: Float = 8f,
100
+ val fillColor: Int? = null,
101
+ ) {
102
+ val draws: Boolean get() = variant != Variant.NONE
103
+ val hasLabel: Boolean get() = draws && label.isNotEmpty()
104
+ }
105
+
106
+ data class Format(
107
+ val mode: Mode = Mode.TEXT,
108
+ /** Mask mode: the pattern, e.g. "+1 ([000]) [000]-[0000]". */
109
+ val mask: String = "",
110
+ val maskNotations: List<MaskNotation> = emptyList(),
111
+ val maskAutocomplete: Boolean = true,
112
+ val maskAutoSkip: Boolean = false,
113
+ val fractionDigits: Int = 2,
114
+ val maxIntegerDigits: Int = 15,
115
+ val groupingSeparator: String = ",",
116
+ val decimalSeparator: String = ".",
117
+ val prefix: String = "",
118
+ val suffix: String = "",
119
+ /** Where a negative amount's sign sits relative to `prefix`. */
120
+ val signBeforeAffix: Boolean = true,
121
+ val placeholder: String = "",
122
+ )
123
+
124
+ data class Typography(
125
+ val fontSize: Float = 32f,
126
+ val prefixFontSize: Float = 32f,
127
+ val suffixFontSize: Float = 32f,
128
+ val fontWeight: Int = 400,
129
+ val fontFamily: String? = null,
130
+ val color: Int? = null,
131
+ val placeholderColor: Int? = null,
132
+ val prefixAlign: AffixAlign = AffixAlign.BASELINE,
133
+ val suffixAlign: AffixAlign = AffixAlign.BASELINE,
134
+ val adjustsFontSizeToFit: Boolean = false,
135
+ val minimumFontScale: Float = 0.5f,
136
+ val allowFontScaling: Boolean = false,
137
+ val maxFontSizeMultiplier: Float = 0f,
138
+ /** Line box height in px; `0` uses the font's own. */
139
+ val lineHeightPx: Float = 0f
140
+ )
141
+
142
+ data class Timing(
143
+ val durationMs: Long = 400,
144
+ val easing: Easing = Easing.EXPO,
145
+ val bounce: Double = 0.15,
146
+ val effect: Effect = Effect.AUTO,
147
+ )
148
+
149
+ data class Keyboard(
150
+ val keyboardType: KeyboardType = KeyboardType.DEFAULT,
151
+ val returnKeyType: ReturnKeyType = ReturnKeyType.DEFAULT,
152
+ val autoCapitalize: AutoCapitalize = AutoCapitalize.SENTENCES,
153
+ val autoCorrect: Boolean = true,
154
+ val editable: Boolean = true,
155
+ val autoFocus: Boolean = false,
156
+ /** Text mode only, as on iOS - a mask or a number format sets its own length; 0 = unlimited. */
157
+ val maxLength: Int = 0,
158
+ val submitBehavior: SubmitBehavior = SubmitBehavior.BLUR_AND_SUBMIT,
159
+ val secureTextEntry: Boolean = false,
160
+ /** Android autofill hint, or null for no autofill. */
161
+ val autofillHint: String? = null,
162
+ val showSoftInputOnFocus: Boolean = true,
163
+ val selectTextOnFocus: Boolean = false,
164
+ val clearTextOnFocus: Boolean = false,
165
+ val contextMenuHidden: Boolean = false,
166
+ val spellCheck: Boolean = true,
167
+ /**
168
+ * `testID` and `accessibilityLabel`, forwarded from JS so the hidden
169
+ * EditText — the element TalkBack and e2e tools see — carries them.
170
+ */
171
+ val testID: String? = null,
172
+ val accessibilityLabel: String? = null,
173
+ /** `NitroInput`: the EditText draws its own text and the overlay is off. */
174
+ val plain: Boolean = false,
175
+ /**
176
+ * Wrapping field. Always plain and always text - the JS side drops `morph`
177
+ * and any non-text mode before it gets here - so nothing below has to
178
+ * reconcile a wrapped run with the glyph engine.
179
+ */
180
+ val multiline: Boolean = false,
181
+ /** `multiline`: lines before it scrolls; `0` grows with the content. */
182
+ val numberOfLines: Int = 0,
183
+ val textAlignVertical: TextAlignVertical = TextAlignVertical.AUTO,
184
+ val scrollEnabled: Boolean = true,
185
+ )
186
+
187
+ data class Caret(
188
+ val color: Int? = null,
189
+ val selectionColor: Int? = null,
190
+ val hidden: Boolean = false,
191
+ )
192
+
193
+ /** Ids of worklets registered from JS (0 = none), run synchronously on the UI thread while an edit is handled. */
194
+ data class Worklets(
195
+ val transform: Int = 0,
196
+ val onChangeText: Int = 0,
197
+ val onChangeValue: Int = 0,
198
+ val onFocusChange: Int = 0,
199
+ val onSelectionChange: Int = 0,
200
+ val onSubmitEditing: Int = 0,
201
+ val onEndEditing: Int = 0,
202
+ val onKeyPress: Int = 0,
203
+ )
204
+
205
+ var worklets: Worklets = Worklets()
206
+
207
+ var format: Format = Format()
208
+ set(value) {
209
+ if (field == value) return
210
+ val old = field
211
+ field = value
212
+ formatter.setFormat(value.fractionDigits, value.maxIntegerDigits, value.groupingSeparator, value.decimalSeparator)
213
+ if (value.mode == Mode.MASK &&
214
+ (old.mode != Mode.MASK || old.mask != value.mask || old.maskNotations != value.maskNotations)
215
+ ) {
216
+ maskEngine.clearNotations()
217
+ value.maskNotations.forEach { maskEngine.addNotation(it.character, it.characterSet, it.isOptional) }
218
+ // A bad pattern leaves the engine inactive; the field then behaves as
219
+ // plain text rather than refusing every keystroke.
220
+ maskEngine.setFormat(value.mask)
221
+ }
222
+ if (old.mode != value.mode) {
223
+ rebuildFonts()
224
+ applyKeyboard()
225
+ }
226
+ applyEditTextLayout()
227
+ applyHint()
228
+ if (value.mode == Mode.NUMBER || value.mode == Mode.MASK) {
229
+ // The field's own format changed: what it holds must follow it.
230
+ val next = conform(text)
231
+ if (next != text) {
232
+ setProgrammatic(next, notify = true)
233
+ return
234
+ }
235
+ }
236
+ requestFeed(-1)
237
+ }
238
+
239
+ var typography: Typography = Typography()
240
+ set(value) {
241
+ if (field == value) return
242
+ field = value
243
+ rebuildFonts()
244
+ requestFeed(-1)
245
+ }
246
+
247
+ var timing: Timing = Timing()
248
+ set(value) {
249
+ field = value
250
+ engine.setTiming(value.durationMs / 1000.0, value.easing.raw, value.bounce)
251
+ engine.setEffect(value.effect.raw)
252
+ }
253
+
254
+ var keyboard: Keyboard = Keyboard()
255
+ set(value) {
256
+ if (field == value) return
257
+ val wasMultiline = field.multiline
258
+ val wasLines = field.numberOfLines
259
+ val wasPlain = field.plain
260
+ val wasSecure = field.secureTextEntry
261
+ field = value
262
+ applyKeyboard()
263
+ // `applyPlain` emptied the engine on the way *into* plain mode, so coming
264
+ // back the overlay has nothing to draw until it is fed again. Masking
265
+ // changes what is drawn, not what is stored, so it re-feeds too - as iOS
266
+ // does; without this the real glyphs stayed up until the next edit.
267
+ if ((wasPlain && !value.plain) || wasSecure != value.secureTextEntry) requestFeed(-1)
268
+ // How tall the field wants to be depends on `multiline` and
269
+ // `numberOfLines`, and this prop lands *after* `typography` — whose
270
+ // `rebuildFonts` is the usual reporter. Without this a wrapping field
271
+ // reported a single line and stayed one line tall.
272
+ if (value.multiline != wasMultiline || value.numberOfLines != wasLines) {
273
+ // The padding is `multiline`'s too — a wrapping field pays for both
274
+ // edges — and it is read back below, so it has to be applied first.
275
+ if (value.multiline != wasMultiline) applyEditTextLayout()
276
+ reportIntrinsicSize()
277
+ }
278
+ maybeAutoFocus()
279
+ }
280
+
281
+ var caret: Caret = Caret()
282
+ set(value) {
283
+ if (field == value) return
284
+ field = value
285
+ deriveColors()
286
+ editText.highlightColor = value.selectionColor ?: defaultHighlightColor
287
+ applyNativeCursor()
288
+ restartBlink()
289
+ }
290
+
291
+ var alignment: Alignment = Alignment.AUTO
292
+ set(value) {
293
+ if (field == value) return
294
+ field = value
295
+ applyEditTextLayout()
296
+ overlay.invalidate()
297
+ }
298
+
299
+ /** The outline / fill and floating label this view draws for itself. */
300
+ var inputFrame: Frame = Frame()
301
+ set(value) {
302
+ if (field == value) return
303
+ val wasDrawing = field.draws
304
+ field = value
305
+ // A FrameLayout draws nothing by default; the frame goes in our own
306
+ // onDraw, which runs before the children, so the text stays on top.
307
+ setWillNotDraw(!value.draws)
308
+ rebuildLabelPaint()
309
+ applyEditTextLayout()
310
+ // The label is also the field's accessible name when nothing else gives
311
+ // it one, so a change to it has to reach TalkBack.
312
+ syncAccessibilityFromHost()
313
+ // A label resting inside the field hides the placeholder, and gaining or
314
+ // losing one changes that. `syncLabelProgress` only reports a *change*,
315
+ // and on mount there is none - the label starts resting - so the hint has
316
+ // to be refreshed here or the two draw on top of each other.
317
+ applyHint()
318
+ if (!wasDrawing || !value.draws) {
319
+ labelAnimator?.cancel()
320
+ notchAnimator?.cancel()
321
+ focusAnimator?.cancel()
322
+ }
323
+ syncLabelProgress(animated = false)
324
+ syncFocusProgress(animated = false)
325
+ // A frame changes the padding (`applyEditTextLayout` above), and a
326
+ // wrapping field's height is that padding plus its lines. This prop lands
327
+ // after `keyboard`, so without this the box keeps the height it reported
328
+ // before it had a frame to make room for. `reportIntrinsicSize` compares
329
+ // against the last report, so calling it when nothing moved costs nothing.
330
+ reportIntrinsicSize()
331
+ invalidate()
332
+ overlay.invalidate()
333
+ }
334
+
335
+ /** Called after every native-originated change (user edit, clear, setText, setValue) with the text and its value (NaN in text mode / empty). */
336
+ var onTextChange: ((text: String, value: Double) -> Unit)? = null
337
+ /** Mask mode: formatted, extracted, tail placeholder, complete. */
338
+ var onMaskChange: ((formatted: String, extracted: String, tailPlaceholder: String, complete: Boolean) -> Unit)? = null
339
+ var onFocusChange: ((focused: Boolean) -> Unit)? = null
340
+ var onSubmit: ((text: String) -> Unit)? = null
341
+ var onEndEditing: ((text: String) -> Unit)? = null
342
+ var onSelectionChange: ((start: Int, end: Int) -> Unit)? = null
343
+ var onKeyPress: ((key: String) -> Unit)? = null
344
+ /** Last selection handed to `onSelectionChange`, so it only fires on a move. */
345
+ private var lastReportedSelection: Pair<Int, Int>? = 0 to 0
346
+ /** Called with the settled intrinsic size, in dp, whenever it changes. */
347
+ var onIntrinsicSizeChange: ((widthDp: Float, heightDp: Float) -> Unit)? = null
348
+
349
+ /** The field's current (formatted) text. */
350
+ var text: String = ""
351
+ private set(value) {
352
+ val wasEmpty = field.isEmpty()
353
+ field = value
354
+ // A label that floats on content follows the field going empty or not.
355
+ if (wasEmpty != value.isEmpty()) syncLabelProgress(animated = true)
356
+ }
357
+
358
+ /** The numeric value of [text] in number mode; NaN otherwise or when empty. */
359
+ fun currentValue(): Double = if (format.mode == Mode.NUMBER) formatter.value(text) else Double.NaN
360
+
361
+ // endregion
362
+
363
+ // region Views
364
+
365
+ /** Owns keyboard, editing, selection and accessibility; draws nothing but the selection highlight. */
366
+ private inner class HiddenEditText(context: Context) : AppCompatEditText(context) {
367
+ var ready = false
368
+
369
+ override fun getOffsetForPosition(x: Float, y: Float): Int {
370
+ // A plain field draws its own text and the engine holds no glyphs for
371
+ // it, so the EditText's own mapping is the right one. (Going through the
372
+ // engine there found a single boundary and put every tap at index 0.)
373
+ if (!ready || keyboard.plain) return super.getOffsetForPosition(x, y)
374
+ return offsetForTap(x)
375
+ }
376
+
377
+ override fun onSelectionChanged(selStart: Int, selEnd: Int) {
378
+ super.onSelectionChanged(selStart, selEnd)
379
+ if (!ready) return
380
+ restartBlink()
381
+ reportSelection(selStart, selEnd)
382
+ }
383
+
384
+ override fun clearFocus() {
385
+ // Like React Native's ReactEditText: keep the system from handing focus straight back.
386
+ val wasFocusable = isFocusableInTouchMode
387
+ isFocusableInTouchMode = false
388
+ super.clearFocus()
389
+ isFocusableInTouchMode = wasFocusable
390
+ }
391
+
392
+ override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? {
393
+ val connection = super.onCreateInputConnection(outAttrs)
394
+ // The platform gives every wrapping field IME_FLAG_NO_ENTER_ACTION, so
395
+ // the IME's return key inserts a line break. One that submits instead
396
+ // has to lose the flag, or the IME never shows the action key nor sends
397
+ // the action - the same fix-up ReactEditText applies.
398
+ if (keyboard.multiline && keyboard.submitBehavior != SubmitBehavior.NEWLINE) {
399
+ outAttrs.imeOptions = outAttrs.imeOptions and EditorInfo.IME_FLAG_NO_ENTER_ACTION.inv()
400
+ }
401
+ return connection
402
+ }
403
+ }
404
+
405
+ /// `contextMenuHidden`: an action-mode callback that never creates a menu.
406
+ private object NoSelectionActionMode : android.view.ActionMode.Callback {
407
+ override fun onCreateActionMode(mode: android.view.ActionMode?, menu: android.view.Menu?) = false
408
+ override fun onPrepareActionMode(mode: android.view.ActionMode?, menu: android.view.Menu?) = false
409
+ override fun onActionItemClicked(mode: android.view.ActionMode?, item: android.view.MenuItem?) = false
410
+ override fun onDestroyActionMode(mode: android.view.ActionMode?) {}
411
+ }
412
+
413
+ private val editText = HiddenEditText(context)
414
+ private val overlay = object : View(context) {
415
+ override fun onDraw(canvas: Canvas) {
416
+ super.onDraw(canvas)
417
+ drawContent(canvas, this)
418
+ }
419
+ }
420
+
421
+ // endregion
422
+
423
+ // region State
424
+
425
+ /** One drawn glyph. The engine also reports an id and an exiting flag per slot; nothing here draws by them, so they are skipped. */
426
+ private class Glyph {
427
+ var character = 0
428
+ var role = 1
429
+ var kind = 0
430
+ var width = 0f
431
+ var placeholder = false
432
+ var x = 0f
433
+ var y = 0f
434
+ var opacity = 1f
435
+ var scale = 1f
436
+ }
437
+
438
+ private val engine = MorphEngine()
439
+ private val formatter = AmountFormatter()
440
+ private val maskEngine = MaskEngine()
441
+ private val density = context.resources.displayMetrics.density
442
+ /**
443
+ * The theme's primary text and accent colours. Resolved here, on a
444
+ * configuration change and never per frame: each lookup allocates a
445
+ * `TypedValue`, walks the theme and fetches a `ColorStateList`.
446
+ */
447
+ private var themeTextColor = resolveThemeColor(android.R.attr.textColorPrimary, Color.BLACK)
448
+ private var themeCaretColor = resolveThemeColor(android.R.attr.colorAccent, 0xFF2196F3.toInt())
449
+ /** `typography.color`, or the theme's. Derived whenever the fonts are rebuilt. */
450
+ private var resolvedTextColor = themeTextColor
451
+ /**
452
+ * [resolvedTextColor] at hint strength: what the placeholder, the stroke and
453
+ * the label fall back to. A React Native activity usually runs a bare
454
+ * `AppCompat` theme with no text appearance, so `android.R.attr.textColorHint`
455
+ * comes back as the *primary* text colour — which would draw the placeholder
456
+ * solid black instead of the muted grey every other input on the platform
457
+ * shows. Deriving it from the text colour, the way iOS's `.placeholderText`
458
+ * is derived from `.label`, is theme-independent and still reads correctly
459
+ * on a dark background.
460
+ */
461
+ private var mutedTextColor = muted(themeTextColor)
462
+ /** `typography.placeholderColor`, or [mutedTextColor]. */
463
+ private var resolvedPlaceholderColor = mutedTextColor
464
+ /** `caret.color`, or the theme's accent. */
465
+ private var resolvedCaretColor = themeCaretColor
466
+ private var fonts: FontSet = FontSet(Typography())
467
+ private val glyphs = ArrayList<Glyph>()
468
+ /** Reused per frame so the JNI hop never allocates; grown on demand. */
469
+ private var frameBuffer = DoubleArray(3 + 11 * 64)
470
+ private var contentWidth = 0f
471
+ private var lastReportedWidth = -1f
472
+ private var lastReportedHeight = -1f
473
+ /** A narrower settled size waiting for the running morph to finish before it is reported. */
474
+ private var pendingSizeReport = false
475
+ private var frameScheduled = false
476
+ private var applying = false
477
+ private var batchDepth = 0
478
+ private var feedPending = false
479
+ private var feedCaret = -1
480
+ /** False until the engine was fed after construction / recycling: the first batch always feeds. */
481
+ private var fed = false
482
+ private var autoFocused = false
483
+ private var blinkOn = true
484
+ private val defaultHighlightColor: Int
485
+ private val caretPaint = Paint(Paint.ANTI_ALIAS_FLAG)
486
+ private val framePaint = Paint(Paint.ANTI_ALIAS_FLAG)
487
+ private val labelPaint = TextPaint(Paint.ANTI_ALIAS_FLAG)
488
+ private val framePath = Path()
489
+ private val arcOval = RectF()
490
+ private val outlineGeometry = OutlineGeometry()
491
+ /** Reused per draw so tracing the frame never allocates; grown on demand. */
492
+ private var outlineBuffer = DoubleArray(OutlineGeometry.STRIDE * 16)
493
+ private val labelRect = DoubleArray(4)
494
+ /** 0 = label resting inside the field, 1 = floated onto the outline. */
495
+ private var labelProgress = 0f
496
+ private var labelAnimator: ValueAnimator? = null
497
+ /**
498
+ * The notch, on its own clock: it lags the label opening and leads it
499
+ * closing, so the hole is never open under a label that is not there yet.
500
+ */
501
+ private var notchProgress = 0f
502
+ private var notchAnimator: ValueAnimator? = null
503
+ /** 0 = blurred, 1 = focused. Blends the stroke rather than snapping it. */
504
+ private var focusProgress = 0f
505
+ private var focusAnimator: ValueAnimator? = null
506
+ private val charCache = HashMap<Int, String>()
507
+
508
+ private val frameCallback = Choreographer.FrameCallback { frameTimeNanos ->
509
+ frameScheduled = false
510
+ engine.tick(frameTimeNanos / 1e9)
511
+ if (pendingSizeReport && !engine.isAnimating()) reportIntrinsicSize()
512
+ overlay.invalidate()
513
+ scheduleFrameIfNeeded()
514
+ }
515
+
516
+ private val blink = object : Runnable {
517
+ override fun run() {
518
+ blinkOn = !blinkOn
519
+ overlay.invalidate()
520
+ if (shouldShowCaret()) postDelayed(this, BLINK_MS)
521
+ }
522
+ }
523
+
524
+ init {
525
+ val matchParent = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
526
+ editText.setTextColor(Color.TRANSPARENT)
527
+ editText.setHintTextColor(Color.TRANSPARENT)
528
+ // `applyPlain()` makes these real again when the overlay is off.
529
+ editText.background = null
530
+ editText.isCursorVisible = false
531
+ editText.includeFontPadding = false
532
+ editText.setSingleLine()
533
+ defaultHighlightColor = editText.highlightColor
534
+ editText.addTextChangedListener(Watcher())
535
+ editText.setOnFocusChangeListener { _, focused ->
536
+ restartBlink()
537
+ syncLabelProgress(animated = true)
538
+ syncFocusProgress(animated = true)
539
+ if (focused) {
540
+ if (keyboard.clearTextOnFocus) {
541
+ clear()
542
+ } else if (keyboard.selectTextOnFocus) {
543
+ editText.post { if (editText.hasFocus()) editText.selectAll() }
544
+ }
545
+ }
546
+ // A worklet handler runs on the UI thread, before the JS one hears anything.
547
+ if (worklets.onFocusChange != 0) {
548
+ NitroInputWorklets.runFocusChange(worklets.onFocusChange, focused, text)
549
+ }
550
+ if (!focused && worklets.onEndEditing != 0) {
551
+ NitroInputWorklets.runEndEditing(worklets.onEndEditing, text)
552
+ }
553
+ onFocusChange?.invoke(focused)
554
+ if (!focused) onEndEditing?.invoke(text)
555
+ }
556
+ editText.setOnEditorActionListener { _, actionId, event ->
557
+ val isEnter = event != null && event.keyCode == KeyEvent.KEYCODE_ENTER
558
+ if (isEnter && event.action != KeyEvent.ACTION_DOWN) return@setOnEditorActionListener true
559
+ if (actionId == EditorInfo.IME_ACTION_NONE && !isEnter) return@setOnEditorActionListener false
560
+ // The three-way `submitBehavior`, decided the way ReactEditText decides
561
+ // it: `submit` fires and keeps focus so a form can move on itself,
562
+ // `blurAndSubmit` fires and dismisses the keyboard, `newline` does
563
+ // neither - on a wrapping field it is the line break.
564
+ val behavior = keyboard.submitBehavior
565
+ val submits = behavior != SubmitBehavior.NEWLINE
566
+ val blurs = behavior == SubmitBehavior.BLUR_AND_SUBMIT
567
+ if (submits) {
568
+ if (worklets.onKeyPress != 0) NitroInputWorklets.runKeyPress(worklets.onKeyPress, "Enter")
569
+ if (worklets.onSubmitEditing != 0) {
570
+ NitroInputWorklets.runSubmitEditing(worklets.onSubmitEditing, text)
571
+ }
572
+ onKeyPress?.invoke("Enter")
573
+ onSubmit?.invoke(text)
574
+ }
575
+ if (blurs) blur()
576
+ // Consumed unless a wrapping field is to get its line break. A single
577
+ // line never inserts one, so there `newline` swallows the key, which is
578
+ // what React Native does too.
579
+ if (submits || blurs || !keyboard.multiline) return@setOnEditorActionListener true
580
+ // A full-screen IME (landscape) renders the `returnKeyType` action even
581
+ // on a wrapping field; next / previous must not move focus on their own.
582
+ actionId == EditorInfo.IME_ACTION_NEXT || actionId == EditorInfo.IME_ACTION_PREVIOUS
583
+ }
584
+ addView(editText, matchParent)
585
+
586
+ overlay.isClickable = false
587
+ overlay.isFocusable = false
588
+ overlay.importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO
589
+ overlay.setWillNotDraw(false)
590
+ addView(overlay, matchParent)
591
+ // The overlay draws a hair outside its bounds while glyphs slide through the line box.
592
+ clipChildren = false
593
+ clipToPadding = false
594
+
595
+ applyKeyboard()
596
+ applyEditTextLayout()
597
+ editText.ready = true
598
+ engine.setTiming(timing.durationMs / 1000.0, timing.easing.raw, timing.bounce)
599
+ engine.setEffect(timing.effect.raw)
600
+ }
601
+
602
+ // endregion
603
+
604
+ // region Fonts
605
+
606
+ private enum class Role { PREFIX, BODY, SUFFIX }
607
+
608
+ /** Body / prefix / suffix paints with per-character advance caches. */
609
+ private inner class FontSet(t: Typography) {
610
+ private val scale = systemFontMultiplier(t)
611
+ val body = makePaint(t, t.fontSize * scale)
612
+ val prefix = makePaint(t, t.prefixFontSize * scale)
613
+ val suffix = makePaint(t, t.suffixFontSize * scale)
614
+ private val prefixAlign = t.prefixAlign
615
+ private val suffixAlign = t.suffixAlign
616
+ private val bodyMetrics: Paint.FontMetrics = body.fontMetrics
617
+ /** The font's own line box, before any `lineHeight` override. */
618
+ val fontLineHeight: Float = ceil(bodyMetrics.descent - bodyMetrics.ascent)
619
+ /** Height of the line box in px: `lineHeight` when given, else the font's. */
620
+ val lineHeight: Float = if (t.lineHeightPx > 0f) t.lineHeightPx else fontLineHeight
621
+ /**
622
+ * How far to push the glyphs down inside the line box. The platform stacks
623
+ * the extra leading above the line, so without this the run rides high;
624
+ * with a line height *tighter* than the font it rides low, and the same
625
+ * halving corrects both. React Native skips the tighter case.
626
+ */
627
+ val baselineNudge: Float = (lineHeight - fontLineHeight) / 2f
628
+ private val widthCaches = Array(3) { HashMap<Int, Float>() }
629
+ private val capHeightCache = HashMap<Role, Float>()
630
+ private val inkDescentCache = HashMap<String, Float>()
631
+
632
+ fun paint(role: Role): TextPaint = when (role) {
633
+ Role.BODY -> body
634
+ Role.PREFIX -> prefix
635
+ Role.SUFFIX -> suffix
636
+ }
637
+
638
+ /** Advance of one character, in px. */
639
+ fun width(codePoint: Int, role: Role): Float =
640
+ widthCaches[role.ordinal].getOrPut(codePoint) { paint(role).measureText(charString(codePoint)) }
641
+
642
+ /** Sum of the per-character advances of [text] (what the engine lays out). */
643
+ fun width(text: String, role: Role): Float {
644
+ var total = 0f
645
+ var i = 0
646
+ while (i < text.length) {
647
+ val cp = text.codePointAt(i)
648
+ total += width(cp, role)
649
+ i += Character.charCount(cp)
650
+ }
651
+ return total
652
+ }
653
+
654
+ /** Baseline y for `role` drawing `text`, given the top of the body line box. */
655
+ fun baseline(role: Role, text: String, lineTop: Float): Float {
656
+ // `baselineNudge` re-centres the run when `lineHeight` differs from the
657
+ // font's: the extra goes above the line, so the body sits that far lower.
658
+ // Everything pinned to the body follows it; `CENTER` does not, because it
659
+ // centres in the line box itself, which is already the new height.
660
+ val bodyBaseline = lineTop + baselineNudge - bodyMetrics.ascent
661
+ if (role == Role.BODY) return bodyBaseline
662
+ val p = paint(role)
663
+ val m = p.fontMetrics
664
+ return when (if (role == Role.PREFIX) prefixAlign else suffixAlign) {
665
+ AffixAlign.BASELINE -> bodyBaseline
666
+ AffixAlign.CENTER -> lineTop + (lineHeight - (m.descent - m.ascent)) / 2f - m.ascent
667
+ AffixAlign.TOP -> bodyBaseline - capHeight(Role.BODY) + capHeight(role)
668
+ // Pin the bottom of the ink, not of the line boxes: the digits' ink ends
669
+ // on the baseline, so "USD" sits on it too instead of hanging down to
670
+ // where a comma's tail reaches.
671
+ AffixAlign.BOTTOM -> bodyBaseline + inkDescent(ALL_DIGITS, Role.BODY) - inkDescent(text, role)
672
+ }
673
+ }
674
+
675
+ /** How far `text`'s ink hangs below the baseline (0 for digits and capitals). */
676
+ private fun inkDescent(text: String, role: Role): Float = inkDescentCache.getOrPut(role.name + "|" + text) {
677
+ val bounds = Rect()
678
+ paint(role).getTextBounds(text, 0, text.length, bounds)
679
+ max(0, bounds.bottom).toFloat()
680
+ }
681
+
682
+ private fun capHeight(role: Role): Float = capHeightCache.getOrPut(role) {
683
+ val bounds = Rect()
684
+ paint(role).getTextBounds("0", 0, 1, bounds)
685
+ -bounds.top.toFloat()
686
+ }
687
+ }
688
+
689
+ /** System font scale for `allowFontScaling`, capped by `maxFontSizeMultiplier`. */
690
+ private fun systemFontMultiplier(t: Typography): Float {
691
+ if (!t.allowFontScaling) return 1f
692
+ val multiplier = context.resources.configuration.fontScale
693
+ return if (t.maxFontSizeMultiplier > 0f) min(multiplier, t.maxFontSizeMultiplier) else multiplier
694
+ }
695
+
696
+ private fun makePaint(t: Typography, sizeDp: Float): TextPaint {
697
+ val paint = TextPaint(Paint.ANTI_ALIAS_FLAG or Paint.SUBPIXEL_TEXT_FLAG)
698
+ paint.typeface = makeTypeface(t)
699
+ paint.textSize = sizeDp * density
700
+ paint.color = t.color ?: themeTextColor
701
+ // Tabular figures in every mode, as on iOS: the engine slides digit runs
702
+ // in text mode too, and proportional digits would jitter as they change.
703
+ paint.fontFeatureSettings = "tnum"
704
+ return paint
705
+ }
706
+
707
+ private fun makeTypeface(t: Typography): Typeface {
708
+ val family = t.fontFamily
709
+ return try {
710
+ if (!family.isNullOrEmpty()) {
711
+ ReactFontManager.getInstance().getTypeface(family, Typeface.NORMAL, t.fontWeight, context.assets)
712
+ } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
713
+ Typeface.create(Typeface.DEFAULT, t.fontWeight, false)
714
+ } else if (t.fontWeight >= 600) {
715
+ Typeface.DEFAULT_BOLD
716
+ } else {
717
+ Typeface.DEFAULT
718
+ }
719
+ } catch (e: Throwable) {
720
+ if (t.fontWeight >= 600) Typeface.DEFAULT_BOLD else Typeface.DEFAULT
721
+ }
722
+ }
723
+
724
+ private fun resolveThemeColor(attr: Int, fallback: Int): Int {
725
+ val value = TypedValue()
726
+ return if (context.theme.resolveAttribute(attr, value, true)) {
727
+ if (value.resourceId != 0) {
728
+ try {
729
+ context.resources.getColorStateList(value.resourceId, context.theme).defaultColor
730
+ } catch (e: Throwable) {
731
+ fallback
732
+ }
733
+ } else {
734
+ value.data
735
+ }
736
+ } else {
737
+ fallback
738
+ }
739
+ }
740
+
741
+ /** [color] at placeholder strength: the same hue, its alpha multiplied down. */
742
+ private fun muted(color: Int): Int = Color.argb(
743
+ (Color.alpha(color) * PLACEHOLDER_ALPHA).toInt(),
744
+ Color.red(color),
745
+ Color.green(color),
746
+ Color.blue(color),
747
+ )
748
+
749
+ /** Re-reads the theme (a light / dark switch) and everything derived from it. */
750
+ private fun refreshThemeColors() {
751
+ themeTextColor = resolveThemeColor(android.R.attr.textColorPrimary, Color.BLACK)
752
+ themeCaretColor = resolveThemeColor(android.R.attr.colorAccent, 0xFF2196F3.toInt())
753
+ deriveColors()
754
+ }
755
+
756
+ /** The colours the frames draw with, settled once here rather than per frame. */
757
+ private fun deriveColors() {
758
+ resolvedTextColor = typography.color ?: themeTextColor
759
+ mutedTextColor = muted(resolvedTextColor)
760
+ resolvedPlaceholderColor = typography.placeholderColor ?: mutedTextColor
761
+ resolvedCaretColor = caret.color ?: themeCaretColor
762
+ }
763
+
764
+ private fun charString(codePoint: Int): String = charCache.getOrPut(codePoint) { String(Character.toChars(codePoint)) }
765
+
766
+ private fun rebuildFonts() {
767
+ deriveColors()
768
+ fonts = FontSet(typography)
769
+ applyEditTextLayout()
770
+ reportIntrinsicSize()
771
+ overlay.invalidate()
772
+ }
773
+
774
+ /** Mirrors our typeface, size, alignment and affix room on the hidden edit text so its selection highlight lines up. */
775
+ private fun applyEditTextLayout() {
776
+ val f = fonts
777
+ editText.typeface = f.body.typeface
778
+ // Not `setTextSize` directly: the platform ignores it while auto-sizing is
779
+ // on, which would leave the auto-size bounds stale after a font change.
780
+ applyAutoSize()
781
+ // TextViewCompat distributes the leading properly (and back-ports
782
+ // `setLineHeight` below API 28), so the plain path needs no nudge of its
783
+ // own - unlike the overlay, which positions its own glyphs.
784
+ if (typography.lineHeightPx > 0f) {
785
+ TextViewCompat.setLineHeight(editText, typography.lineHeightPx.roundToInt())
786
+ } else {
787
+ // `setLineHeight` is line spacing underneath; back to the font's own
788
+ // once the override is gone, or the last value would stick.
789
+ editText.setLineSpacing(0f, 1f)
790
+ }
791
+ // An outlined or filled frame reserves room at the sides for its stroke and
792
+ // at the top for the floated label. A single line is centred in whatever
793
+ // height the caller gives it, so only the top is padded there - that moves
794
+ // the centred text down rather than leaving it put. A wrapping field
795
+ // reports its own height and starts at the top, so nothing else is going to
796
+ // put space between its first line and the stroke: it pays for both edges.
797
+ val side = frameSideInsetPx.roundToInt()
798
+ val framePadding = if (inputFrame.draws && keyboard.multiline) {
799
+ (FRAME_PADDING_DP * density).roundToInt()
800
+ } else {
801
+ 0
802
+ }
803
+ // An outlined field's floated label straddles the top stroke, so half of it
804
+ // hangs back into the box. A single line is centred well below it; a
805
+ // wrapping field's first line starts at the top, right where the label is,
806
+ // so it has to be paid for - as it is on iOS, or the same props would give
807
+ // the two platforms different heights.
808
+ val labelOverhang = if (inputFrame.draws && keyboard.multiline &&
809
+ inputFrame.hasLabel && inputFrame.variant != Variant.FILLED
810
+ ) {
811
+ (floatedLabelSizePx / 2f).roundToInt()
812
+ } else {
813
+ 0
814
+ }
815
+ // Relative: the prefix sits at the start edge and the suffix at the end,
816
+ // so under a right-to-left layout the room for them swaps sides too.
817
+ editText.setPaddingRelative(
818
+ side + f.width(format.prefix, Role.PREFIX).roundToInt(),
819
+ frameTopInsetPx.roundToInt() + framePadding + labelOverhang,
820
+ side + f.width(format.suffix, Role.SUFFIX).roundToInt(),
821
+ framePadding,
822
+ )
823
+ applyAffixes()
824
+ val vertical = if (!keyboard.multiline) Gravity.CENTER_VERTICAL else when (keyboard.textAlignVertical) {
825
+ TextAlignVertical.CENTER -> Gravity.CENTER_VERTICAL
826
+ TextAlignVertical.BOTTOM -> Gravity.BOTTOM
827
+ else -> Gravity.TOP
828
+ }
829
+ editText.gravity = vertical or when (alignment) {
830
+ Alignment.AUTO -> Gravity.START
831
+ Alignment.LEFT -> Gravity.LEFT
832
+ Alignment.CENTER -> Gravity.CENTER_HORIZONTAL
833
+ Alignment.RIGHT -> Gravity.RIGHT
834
+ }
835
+ }
836
+
837
+ // endregion
838
+
839
+ // region Keyboard
840
+
841
+ private fun applyKeyboard() {
842
+ val k = keyboard
843
+ val numberMode = format.mode == Mode.NUMBER
844
+ var textType = InputType.TYPE_CLASS_TEXT
845
+ // Number / phone classes are applied as the *raw* input type: `setInputType`
846
+ // would install a DigitsKeyListener that filters every programmatic set too,
847
+ // and "1,234" has to survive it.
848
+ var rawType: Int? = null
849
+ when (k.keyboardType) {
850
+ KeyboardType.DEFAULT, KeyboardType.ASCII_CAPABLE -> {}
851
+ KeyboardType.NUMBER_PAD -> rawType = InputType.TYPE_CLASS_NUMBER
852
+ KeyboardType.DECIMAL_PAD, KeyboardType.NUMERIC -> rawType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL
853
+ KeyboardType.NUMBERS_AND_PUNCTUATION ->
854
+ rawType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL or InputType.TYPE_NUMBER_FLAG_SIGNED
855
+ KeyboardType.EMAIL_ADDRESS -> textType = textType or InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
856
+ KeyboardType.PHONE_PAD -> rawType = InputType.TYPE_CLASS_PHONE
857
+ KeyboardType.URL -> textType = textType or InputType.TYPE_TEXT_VARIATION_URI
858
+ }
859
+ if (!numberMode && rawType == null) {
860
+ textType = textType or when (k.autoCapitalize) {
861
+ AutoCapitalize.NONE -> 0
862
+ AutoCapitalize.SENTENCES -> InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
863
+ AutoCapitalize.WORDS -> InputType.TYPE_TEXT_FLAG_CAP_WORDS
864
+ AutoCapitalize.CHARACTERS -> InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS
865
+ }
866
+ textType = textType or if (k.autoCorrect) InputType.TYPE_TEXT_FLAG_AUTO_CORRECT else InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
867
+ if (!k.spellCheck) textType = textType or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
868
+ }
869
+ // A password variation is what keeps the IME from suggesting, learning or
870
+ // showing the text; the overlay does the masking itself (see `feedEngine`).
871
+ if (k.secureTextEntry) {
872
+ textType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
873
+ rawType = null
874
+ }
875
+ if (k.multiline) {
876
+ // TYPE_TEXT_FLAG_MULTI_LINE is what makes the IME offer a return key that
877
+ // inserts a newline rather than submitting.
878
+ textType = textType or InputType.TYPE_TEXT_FLAG_MULTI_LINE
879
+ }
880
+ editText.inputType = textType
881
+ if (rawType != null) editText.setRawInputType(rawType)
882
+ if (k.multiline) {
883
+ editText.setSingleLine(false)
884
+ editText.setHorizontallyScrolling(false)
885
+ editText.maxLines = if (k.numberOfLines > 0) k.numberOfLines else Int.MAX_VALUE
886
+ if (k.numberOfLines > 0) editText.minLines = k.numberOfLines
887
+ editText.isVerticalScrollBarEnabled = k.scrollEnabled
888
+ editText.movementMethod = android.text.method.ArrowKeyMovementMethod.getInstance()
889
+ } else {
890
+ editText.setSingleLine()
891
+ editText.maxLines = 1
892
+ editText.minLines = 1
893
+ }
894
+ editText.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI or when (k.returnKeyType) {
895
+ ReturnKeyType.DEFAULT -> EditorInfo.IME_ACTION_UNSPECIFIED
896
+ ReturnKeyType.DONE -> EditorInfo.IME_ACTION_DONE
897
+ ReturnKeyType.GO -> EditorInfo.IME_ACTION_GO
898
+ ReturnKeyType.NEXT -> EditorInfo.IME_ACTION_NEXT
899
+ ReturnKeyType.SEARCH -> EditorInfo.IME_ACTION_SEARCH
900
+ ReturnKeyType.SEND -> EditorInfo.IME_ACTION_SEND
901
+ }
902
+ // Text mode only, as on iOS. A mask's pattern is its own length, and
903
+ // `setEditable` replaces through the `Editable`, which re-runs the filters:
904
+ // a length filter there clipped the mask's punctuation off the end.
905
+ editText.filters = if (format.mode == Mode.TEXT && k.maxLength > 0) {
906
+ arrayOf<InputFilter>(InputFilter.LengthFilter(k.maxLength))
907
+ } else {
908
+ emptyArray<InputFilter>()
909
+ }
910
+ editText.isEnabled = k.editable
911
+ editText.isFocusable = k.editable
912
+ editText.isFocusableInTouchMode = k.editable
913
+ applyPlain()
914
+ syncAccessibilityFromHost()
915
+ editText.showSoftInputOnFocus = k.showSoftInputOnFocus
916
+ editText.setTextIsSelectable(false)
917
+ editText.isLongClickable = !k.contextMenuHidden
918
+ editText.customSelectionActionModeCallback = if (k.contextMenuHidden) NoSelectionActionMode else null
919
+ if (k.autofillHint != null) {
920
+ editText.setAutofillHints(k.autofillHint)
921
+ editText.importantForAutofill = IMPORTANT_FOR_AUTOFILL_YES
922
+ } else {
923
+ editText.setAutofillHints(null)
924
+ editText.importantForAutofill = IMPORTANT_FOR_AUTOFILL_NO
925
+ }
926
+ if (!k.editable && editText.hasFocus()) blur()
927
+ if (editText.hasFocus()) inputMethodManager()?.restartInput(editText)
928
+ }
929
+
930
+ /**
931
+ * React Native applies `testID` and `accessibilityLabel` to the *host* view
932
+ * that contains this one, but the EditText is the element e2e tools and
933
+ * TalkBack interact with, so they are copied down.
934
+ */
935
+ private fun syncAccessibilityFromHost() {
936
+ // The props carry the identity explicitly; the host view's own tag is the
937
+ // fallback for a caller that set it natively.
938
+ val testId = keyboard.testID ?: (parent as? android.view.View)?.tag as? String
939
+ if (editText.tag != testId) editText.tag = testId
940
+ // React Native also keys the testID under its own id, which is what e2e
941
+ // tooling reads; mirror both.
942
+ runCatching { editText.setTag(com.facebook.react.R.id.react_test_id, testId) }
943
+ // A floating label is the field's visible name, but it is drawn on the
944
+ // canvas - TalkBack cannot see it. Without this a field whose only name is
945
+ // its `label` is announced as an unnamed edit box. An explicit
946
+ // `accessibilityLabel` still wins.
947
+ val label: CharSequence? = keyboard.accessibilityLabel
948
+ ?: (parent as? android.view.View)?.contentDescription
949
+ ?: inputFrame.label.ifEmpty { null }
950
+ if (editText.contentDescription != label) editText.contentDescription = label
951
+ }
952
+
953
+ /**
954
+ * `adjustsFontSizeToFit` in plain mode. The overlay implements it by scaling
955
+ * the glyphs it draws, which is no help once the EditText is drawing itself,
956
+ * so the platform's own auto-sizing has to take over - iOS uses
957
+ * `adjustsFontSizeToFitWidth` for the same reason. Without this the prop was
958
+ * a silent no-op on Android for every `NitroInput`.
959
+ */
960
+ private var prefixView: TextView? = null
961
+ private var suffixView: TextView? = null
962
+
963
+ /**
964
+ * Prefix and suffix in plain mode. The overlay draws them as glyphs while it
965
+ * is up, which is no help once the EditText draws itself - iOS uses real
966
+ * `leftView` / `rightView` accessories for the same reason. Without these the
967
+ * EditText's padding reserved the space (see `applyEditTextLayout`) and
968
+ * nothing filled it, so a currency symbol was simply a gap.
969
+ */
970
+ private fun applyAffixes() {
971
+ prefixView = affixView(prefixView, format.prefix, Role.PREFIX, Gravity.START)
972
+ suffixView = affixView(suffixView, format.suffix, Role.SUFFIX, Gravity.END)
973
+ }
974
+
975
+ private fun affixView(existing: TextView?, affix: String, role: Role, edge: Int): TextView? {
976
+ if (!keyboard.plain || affix.isEmpty()) {
977
+ existing?.let { removeView(it) }
978
+ return null
979
+ }
980
+ val paint = fonts.paint(role)
981
+ val view = existing ?: TextView(context).also {
982
+ it.isClickable = false
983
+ it.isFocusable = false
984
+ it.includeFontPadding = false
985
+ it.importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO
986
+ addView(it, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT))
987
+ }
988
+ val side = frameSideInsetPx.roundToInt()
989
+ (view.layoutParams as LayoutParams).gravity = edge or Gravity.CENTER_VERTICAL
990
+ view.setPaddingRelative(if (edge == Gravity.START) side else 0, frameTopInsetPx.roundToInt(),
991
+ if (edge == Gravity.END) side else 0, 0)
992
+ view.gravity = Gravity.CENTER_VERTICAL
993
+ view.typeface = paint.typeface
994
+ view.setTextSize(TypedValue.COMPLEX_UNIT_PX, paint.textSize)
995
+ view.setTextColor(resolvedTextColor)
996
+ if (view.text?.toString() != affix) view.text = affix
997
+ return view
998
+ }
999
+
1000
+ private fun applyAutoSize() {
1001
+ val t = typography
1002
+ // Only in plain mode: with the overlay up it scales the glyphs itself (see
1003
+ // `contentLayout`), and the two would fight.
1004
+ if (!keyboard.plain || !t.adjustsFontSizeToFit) {
1005
+ TextViewCompat.setAutoSizeTextTypeWithDefaults(editText, TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE)
1006
+ editText.setTextSize(TypedValue.COMPLEX_UNIT_PX, fonts.body.textSize)
1007
+ return
1008
+ }
1009
+ val max = fonts.body.textSize.roundToInt().coerceAtLeast(2)
1010
+ val min = (fonts.body.textSize * t.minimumFontScale).roundToInt().coerceIn(1, max - 1)
1011
+ TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(
1012
+ editText, min, max, 1, TypedValue.COMPLEX_UNIT_PX,
1013
+ )
1014
+ }
1015
+
1016
+ /** Switches between "hidden EditText + overlay" and "the EditText draws itself". */
1017
+ private fun applyPlain() {
1018
+ if (keyboard.plain) {
1019
+ overlay.visibility = GONE
1020
+ stopAnimation()
1021
+ engine.reset()
1022
+ editText.setTextColor(resolvedTextColor)
1023
+ editText.setHintTextColor(resolvedPlaceholderColor)
1024
+ applyNativeCursor()
1025
+ applyAutoSize()
1026
+ applyAffixes()
1027
+ // `AUTO` is the start edge of the layout direction; `LEFT` and `RIGHT`
1028
+ // are absolute, which only `TEXT_ALIGNMENT_GRAVITY` over an absolute
1029
+ // gravity gives - `VIEW_START` / `VIEW_END` would flip with the direction.
1030
+ editText.textAlignment = when (alignment) {
1031
+ Alignment.AUTO -> TEXT_ALIGNMENT_VIEW_START
1032
+ Alignment.CENTER -> TEXT_ALIGNMENT_CENTER
1033
+ Alignment.LEFT, Alignment.RIGHT -> TEXT_ALIGNMENT_GRAVITY
1034
+ }
1035
+ // The width now comes from the field, not the engine.
1036
+ reportIntrinsicSize()
1037
+ } else {
1038
+ overlay.visibility = VISIBLE
1039
+ editText.setTextColor(Color.TRANSPARENT)
1040
+ editText.setHintTextColor(Color.TRANSPARENT)
1041
+ applyNativeCursor()
1042
+ applyAutoSize()
1043
+ applyAffixes()
1044
+ editText.textAlignment = TEXT_ALIGNMENT_VIEW_START
1045
+ }
1046
+ }
1047
+
1048
+ /**
1049
+ * The overlay draws its own caret, so the `EditText`'s is switched off for it.
1050
+ * In `plain` mode there is no overlay and the system caret is the caret —
1051
+ * tinted with `cursorColor` where the platform allows it.
1052
+ */
1053
+ private fun applyNativeCursor() {
1054
+ val visible = keyboard.plain && !caret.hidden
1055
+ if (editText.isCursorVisible != visible) editText.isCursorVisible = visible
1056
+ if (!visible) return
1057
+ val color = caret.color ?: return
1058
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
1059
+ editText.textCursorDrawable?.let {
1060
+ it.setTint(color)
1061
+ editText.textCursorDrawable = it
1062
+ }
1063
+ }
1064
+ }
1065
+
1066
+ private fun inputMethodManager(): InputMethodManager? =
1067
+ context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
1068
+
1069
+ private fun maybeAutoFocus() {
1070
+ if (!keyboard.autoFocus || autoFocused || !isAttachedToWindow) return
1071
+ autoFocused = true
1072
+ post { focus() }
1073
+ }
1074
+
1075
+ // endregion
1076
+
1077
+ // region Public API
1078
+
1079
+ fun focus() {
1080
+ if (!keyboard.editable) return
1081
+ editText.isFocusableInTouchMode = true
1082
+ if (!editText.hasFocus()) editText.requestFocus()
1083
+ // `showSoftInputOnFocus: false` keeps focus and the caret but no keyboard;
1084
+ // the EditText honours it on its own, so only the explicit ask is guarded.
1085
+ // No flags, as ReactEditText asks: `SHOW_IMPLICIT` is deprecated and only
1086
+ // ever let the platform decline to show the keyboard.
1087
+ if (keyboard.showSoftInputOnFocus) {
1088
+ inputMethodManager()?.showSoftInput(editText, 0)
1089
+ }
1090
+ }
1091
+
1092
+ /// Moves the caret/selection to `start`..`end`, in code points.
1093
+ fun setSelection(start: Int, end: Int) {
1094
+ val count = text.codePointCount(0, text.length)
1095
+ val lower = start.coerceIn(0, count)
1096
+ val upper = end.coerceIn(lower, count)
1097
+ val from = text.offsetByCodePoints(0, lower)
1098
+ val to = text.offsetByCodePoints(0, upper)
1099
+ if (editText.selectionStart == from && editText.selectionEnd == to) return
1100
+ editText.setSelection(from, to)
1101
+ }
1102
+
1103
+ /// Reports the caret/selection in code points, and only when it moved.
1104
+ private fun reportSelection(selStart: Int, selEnd: Int) {
1105
+ // A worklet handler counts as a listener too - returning on the JS one
1106
+ // alone would make a field with only a worklet report nothing.
1107
+ val handler = onSelectionChange
1108
+ if (handler == null && worklets.onSelectionChange == 0) return
1109
+ if (selStart < 0 || selEnd < 0) return
1110
+ val current = text
1111
+ val start = current.codePointCount(0, selStart.coerceIn(0, current.length))
1112
+ val end = current.codePointCount(0, selEnd.coerceIn(0, current.length))
1113
+ if (lastReportedSelection?.first == start && lastReportedSelection?.second == end) return
1114
+ lastReportedSelection = start to end
1115
+ if (worklets.onSelectionChange != 0) {
1116
+ NitroInputWorklets.runSelectionChange(worklets.onSelectionChange, start, end)
1117
+ }
1118
+ handler?.invoke(start, end)
1119
+ }
1120
+
1121
+ fun blur() {
1122
+ if (editText.hasFocus()) editText.clearFocus()
1123
+ inputMethodManager()?.hideSoftInputFromWindow(editText.windowToken, 0)
1124
+ }
1125
+
1126
+ /** Empties the field, morphing the characters away. */
1127
+ fun clear() = setProgrammatic("", notify = true)
1128
+
1129
+ /** Replaces the text (formatted in number mode), caret at the end. */
1130
+ fun replaceText(value: String) = setProgrammatic(conform(value), notify = true)
1131
+
1132
+ /** Number mode: shows [value] formatted; NaN empties the field. */
1133
+ fun setValue(value: Double) = setProgrammatic(formatter.format(value), notify = true)
1134
+
1135
+ /** Applies the `text` prop: like [replaceText], but silently (JS already knows). */
1136
+ fun applyText(value: String) = setProgrammatic(conform(value), notify = false)
1137
+
1138
+ /** Runs [block] with engine feeds coalesced into one commit at the end. */
1139
+ fun batch(block: () -> Unit) {
1140
+ batchDepth++
1141
+ try {
1142
+ block()
1143
+ } finally {
1144
+ batchDepth--
1145
+ if (batchDepth == 0 && (feedPending || !fed)) {
1146
+ feedPending = false
1147
+ val caret = feedCaret
1148
+ feedCaret = -1
1149
+ feedEngine(caret)
1150
+ }
1151
+ }
1152
+ }
1153
+
1154
+ /** Re-sends the last reported intrinsic size (e.g. after a listener was attached). */
1155
+ fun resendIntrinsicSize() {
1156
+ if (lastReportedWidth < 0f) return
1157
+ onIntrinsicSizeChange?.invoke(lastReportedWidth, lastReportedHeight)
1158
+ }
1159
+
1160
+ fun stopAnimation() {
1161
+ if (frameScheduled) {
1162
+ Choreographer.getInstance().removeFrameCallback(frameCallback)
1163
+ frameScheduled = false
1164
+ }
1165
+ labelAnimator?.cancel()
1166
+ labelAnimator = null
1167
+ notchAnimator?.cancel()
1168
+ notchAnimator = null
1169
+ focusAnimator?.cancel()
1170
+ focusAnimator = null
1171
+ }
1172
+
1173
+ /**
1174
+ * Returns the view to its pristine state so Fabric can reuse it for a new
1175
+ * element (RecyclableView). Props are re-applied by Nitro afterwards.
1176
+ */
1177
+ fun resetForRecycle() {
1178
+ worklets = Worklets()
1179
+ inputFrame = Frame()
1180
+ labelProgress = 0f
1181
+ notchProgress = 0f
1182
+ focusProgress = 0f
1183
+ stopAnimation()
1184
+ removeCallbacks(blink)
1185
+ blur()
1186
+ applying = true
1187
+ editText.setText("")
1188
+ applying = false
1189
+ text = ""
1190
+ engine.reset()
1191
+ glyphs.clear()
1192
+ contentWidth = 0f
1193
+ lastReportedWidth = -1f
1194
+ lastReportedHeight = -1f
1195
+ pendingSizeReport = false
1196
+ feedPending = false
1197
+ feedCaret = -1
1198
+ fed = false
1199
+ autoFocused = false
1200
+ batch {
1201
+ format = Format()
1202
+ typography = Typography()
1203
+ timing = Timing()
1204
+ keyboard = Keyboard()
1205
+ caret = Caret()
1206
+ alignment = Alignment.AUTO
1207
+ }
1208
+ // onTextChange, onFocusChange, onSubmit and onIntrinsicSizeChange are the
1209
+ // hybrid's wiring, not the element's props: they stay across recycling
1210
+ // (the hybrid clears its own callback props).
1211
+ overlay.invalidate()
1212
+ }
1213
+
1214
+ override fun onAttachedToWindow() {
1215
+ super.onAttachedToWindow()
1216
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
1217
+ animatorScale = -1f
1218
+ context.contentResolver.registerContentObserver(
1219
+ Settings.Global.getUriFor(Settings.Global.ANIMATOR_DURATION_SCALE), false, animatorScaleObserver,
1220
+ )
1221
+ }
1222
+ scheduleFrameIfNeeded()
1223
+ restartBlink()
1224
+ syncAccessibilityFromHost()
1225
+ maybeAutoFocus()
1226
+ }
1227
+
1228
+ override fun onDetachedFromWindow() {
1229
+ stopAnimation()
1230
+ removeCallbacks(blink)
1231
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
1232
+ context.contentResolver.unregisterContentObserver(animatorScaleObserver)
1233
+ }
1234
+ super.onDetachedFromWindow()
1235
+ }
1236
+
1237
+ override fun onConfigurationChanged(newConfig: Configuration?) {
1238
+ super.onConfigurationChanged(newConfig)
1239
+ // The paints resolve the theme's colours and the system font scale when
1240
+ // they are built; a light / dark switch or a text-size change rebuilds
1241
+ // them, and a plain field's own text colour follows.
1242
+ refreshThemeColors()
1243
+ rebuildFonts()
1244
+ applyPlain()
1245
+ invalidate()
1246
+ }
1247
+
1248
+ override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
1249
+ super.onSizeChanged(w, h, oldw, oldh)
1250
+ overlay.invalidate()
1251
+ // Props land after the view is attached, so the host's testID is only
1252
+ // reliable once it has been measured.
1253
+ syncAccessibilityFromHost()
1254
+ }
1255
+
1256
+ // endregion
1257
+
1258
+ // region Text flow
1259
+
1260
+ /** Text mode truncates to `maxLength`; number mode formats. */
1261
+ private fun conform(value: String): String {
1262
+ if (format.mode == Mode.NUMBER) return formatter.normalize(value)
1263
+ if (format.mode == Mode.MASK) {
1264
+ return maskEngine.applyAll(value, value.codePointCount(0, value.length), true, format.maskAutocomplete, false)
1265
+ }
1266
+ val limit = keyboard.maxLength
1267
+ if (limit <= 0) return value
1268
+ val end = utf16Index(value, limit)
1269
+ return value.substring(0, end)
1270
+ }
1271
+
1272
+ private fun setProgrammatic(value: String, notify: Boolean) {
1273
+ var next = value
1274
+ if (worklets.transform != 0) {
1275
+ val count = next.codePointCount(0, next.length)
1276
+ val transformed = NitroInputWorklets.runTransform(
1277
+ worklets.transform, next, text, count, count,
1278
+ codePointIndex(text, editText.selectionStart), codePointIndex(text, editText.selectionEnd),
1279
+ )
1280
+ if (transformed != null) next = transformed
1281
+ }
1282
+ if (next == text && next == editText.text.toString()) return
1283
+ applying = true
1284
+ editText.setText(next)
1285
+ editText.text?.let { Selection.setSelection(it, it.length) }
1286
+ applying = false
1287
+ val changed = next != text
1288
+ text = next
1289
+ requestFeed(-1)
1290
+ if (!changed) return
1291
+ // A wrapping field's height follows its text, whichever way it arrived.
1292
+ if (keyboard.multiline) post { reportIntrinsicSize() }
1293
+ if (notify) {
1294
+ notifyChange()
1295
+ } else {
1296
+ // The `text` prop is silent for `onChangeText`, as it is for a
1297
+ // TextInput, but a mask reports what the new text fills in on every
1298
+ // route (iOS does the same), so the app learns `complete` for a value it set.
1299
+ reportMaskChange()
1300
+ }
1301
+ }
1302
+
1303
+ /** Worklet callbacks first (synchronously, on this thread), then the JS ones. */
1304
+ private fun notifyChange() {
1305
+ if (worklets.onChangeText != 0) NitroInputWorklets.runChangeText(worklets.onChangeText, text)
1306
+ if (worklets.onChangeValue != 0 && format.mode == Mode.NUMBER) NitroInputWorklets.runChangeValue(worklets.onChangeValue, currentValue())
1307
+ reportMaskChange()
1308
+ onTextChange?.invoke(text, currentValue())
1309
+ }
1310
+
1311
+ /** `onChangeMask`, derived from the settled text so every route reports the same thing. */
1312
+ private fun reportMaskChange() {
1313
+ if (format.mode != Mode.MASK) return
1314
+ maskEngine.applyAll(text, text.codePointCount(0, text.length), true, format.maskAutocomplete, false)
1315
+ onMaskChange?.invoke(text, maskEngine.lastExtracted(), maskEngine.lastTailPlaceholder(), maskEngine.lastComplete())
1316
+ }
1317
+
1318
+ /** Every change to the edit text (typing, backspace, paste, IME) lands here and goes through the engine. */
1319
+ private inner class Watcher : TextWatcher {
1320
+ private var previous = ""
1321
+ private var start = 0
1322
+ private var count = 0
1323
+ private var replacement = ""
1324
+ private var previousSelectionStart = 0
1325
+ private var previousSelectionEnd = 0
1326
+
1327
+ override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
1328
+ if (applying) return
1329
+ previous = s.toString()
1330
+ this.start = start
1331
+ this.count = count
1332
+ previousSelectionStart = codePointIndex(previous, editText.selectionStart)
1333
+ previousSelectionEnd = codePointIndex(previous, editText.selectionEnd)
1334
+ }
1335
+
1336
+ override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
1337
+ if (applying) return
1338
+ replacement = s.subSequence(start, min(s.length, start + count)).toString()
1339
+ // Like React Native's `onKeyPress`: the inserted text, or 'Backspace'.
1340
+ // Only for real key events — the watcher also runs for the initial set.
1341
+ if (editText.hasFocus()) {
1342
+ // A wrapping field's IME commits the line break as text; React Native
1343
+ // reports that as the Enter key, and so does the single-line path.
1344
+ val key = when (replacement) {
1345
+ "" -> "Backspace"
1346
+ "\n" -> "Enter"
1347
+ else -> replacement
1348
+ }
1349
+ if (worklets.onKeyPress != 0) NitroInputWorklets.runKeyPress(worklets.onKeyPress, key)
1350
+ onKeyPress?.invoke(key)
1351
+ }
1352
+ }
1353
+
1354
+ override fun afterTextChanged(s: Editable) {
1355
+ if (applying) return
1356
+ handleUserEdit(s, previous, start, count, replacement, previousSelectionStart, previousSelectionEnd)
1357
+ }
1358
+ }
1359
+
1360
+ private fun handleUserEdit(
1361
+ editable: Editable,
1362
+ previous: String,
1363
+ start: Int,
1364
+ count: Int,
1365
+ replacement: String,
1366
+ previousSelectionStart: Int,
1367
+ previousSelectionEnd: Int,
1368
+ ) {
1369
+ var caretCodePoints: Int
1370
+ if (format.mode == Mode.MASK) {
1371
+ val cpStart = codePointIndex(previous, start)
1372
+ val cpEnd = codePointIndex(previous, start + count)
1373
+ val next = maskEngine.applyEdit(
1374
+ previous, cpStart, cpEnd, replacement, format.maskAutocomplete, format.maskAutoSkip,
1375
+ )
1376
+ val caret = maskEngine.lastCaret()
1377
+ if (next != editable.toString()) {
1378
+ setEditable(editable, next, caret)
1379
+ } else {
1380
+ val sel = utf16Index(next, caret)
1381
+ if (editText.selectionStart != sel || editText.selectionEnd != sel) {
1382
+ applying = true
1383
+ Selection.setSelection(editable, sel)
1384
+ applying = false
1385
+ }
1386
+ }
1387
+ caretCodePoints = caret
1388
+ } else if (format.mode == Mode.NUMBER) {
1389
+ val cpStart = codePointIndex(previous, start)
1390
+ val cpEnd = codePointIndex(previous, start + count)
1391
+ val next = formatter.applyEdit(previous, cpStart, cpEnd, replacement)
1392
+ val caret = formatter.lastCaret()
1393
+ if (!formatter.lastAccepted()) {
1394
+ // Too many digits: the keystroke never shows.
1395
+ setEditable(editable, previous, caret)
1396
+ return
1397
+ }
1398
+ if (next != editable.toString()) {
1399
+ setEditable(editable, next, caret)
1400
+ } else {
1401
+ val sel = utf16Index(next, caret)
1402
+ if (editText.selectionStart != sel || editText.selectionEnd != sel) {
1403
+ applying = true
1404
+ Selection.setSelection(editable, sel)
1405
+ applying = false
1406
+ }
1407
+ }
1408
+ caretCodePoints = caret
1409
+ } else {
1410
+ caretCodePoints = codePointIndex(editable.toString(), start + replacement.length)
1411
+ }
1412
+ if (worklets.transform != 0) {
1413
+ val current = editable.toString()
1414
+ val transformed = NitroInputWorklets.runTransform(
1415
+ worklets.transform, current, previous, caretCodePoints, caretCodePoints, previousSelectionStart, previousSelectionEnd,
1416
+ )
1417
+ if (transformed != null) {
1418
+ val length = transformed.codePointCount(0, transformed.length)
1419
+ val selStart = NitroInputWorklets.lastSelectionStart().let { if (it < 0) length else min(it, length) }
1420
+ val selEnd = NitroInputWorklets.lastSelectionEnd().coerceIn(selStart, length)
1421
+ setEditable(editable, transformed, selStart, selEnd)
1422
+ caretCodePoints = selStart
1423
+ }
1424
+ }
1425
+ val updated = editable.toString()
1426
+ if (updated == text) return
1427
+ text = updated
1428
+ requestFeed(caretCodePoints)
1429
+ // A wrapping field's height follows its text; the glyph engine is off, so
1430
+ // nothing else would ask.
1431
+ if (keyboard.multiline) post { reportIntrinsicSize() }
1432
+ notifyChange()
1433
+ }
1434
+
1435
+ /** Replaces only the span that differs (a comma that appeared, a mask's punctuation), not the whole editable. */
1436
+ private fun setEditable(editable: Editable, value: String, caretCodePoints: Int, selectionEndCodePoints: Int = caretCodePoints) {
1437
+ applying = true
1438
+ val current = editable.toString()
1439
+ var prefix = 0
1440
+ while (prefix < current.length && prefix < value.length && current[prefix] == value[prefix]) prefix++
1441
+ var suffix = 0
1442
+ while (suffix < current.length - prefix && suffix < value.length - prefix &&
1443
+ current[current.length - 1 - suffix] == value[value.length - 1 - suffix]) suffix++
1444
+ if (prefix + suffix < current.length || prefix + suffix < value.length) {
1445
+ editable.replace(prefix, current.length - suffix, value, prefix, value.length - suffix)
1446
+ }
1447
+ Selection.setSelection(editable, utf16Index(value, caretCodePoints), utf16Index(value, selectionEndCodePoints))
1448
+ applying = false
1449
+ }
1450
+
1451
+ /** Feeds now, or once at the end of the enclosing [batch] (-1 wins over a caret). */
1452
+ private fun requestFeed(caret: Int) {
1453
+ if (batchDepth > 0) {
1454
+ feedCaret = if (feedPending && feedCaret == -1) -1 else caret
1455
+ feedPending = true
1456
+ } else {
1457
+ feedEngine(caret)
1458
+ }
1459
+ }
1460
+
1461
+ /** Hands the engine the prefix, body (or placeholder) and suffix as glyphs and commits. */
1462
+ private fun feedEngine(caret: Int) {
1463
+ // A plain field draws its own text and never feeds the engine, but its
1464
+ // width still has to reach React for `autoWidth`; every text, font, affix
1465
+ // and hint change comes through here.
1466
+ if (keyboard.plain) { reportIntrinsicSize(); return }
1467
+ val f = fonts
1468
+ engine.setReduceMotion(animationsDisabled())
1469
+ engine.beginText()
1470
+ val hint = effectivePlaceholder
1471
+ val showPlaceholder = text.isEmpty() && hint.isNotEmpty()
1472
+ // `secureTextEntry` masks what the overlay draws: the EditText keeps the
1473
+ // real text (the IME and autofill need it), every drawn glyph is a bullet.
1474
+ val body = if (keyboard.secureTextEntry) "\u2022".repeat(text.codePointCount(0, text.length)) else text
1475
+ val shown = if (showPlaceholder) hint else body
1476
+
1477
+ // A negative amount reads "-$1,234.56", not "$-1,234.56": the sign belongs
1478
+ // to the amount, not to the digits after the symbol. It stays a *body*
1479
+ // glyph - it is part of the text, and the caret counts body glyphs in the
1480
+ // order they are added - and is only laid out ahead of the prefix.
1481
+ val signed = format.signBeforeAffix && !showPlaceholder && format.prefix.isNotEmpty() &&
1482
+ shown.isNotEmpty() && isSign(shown[0])
1483
+ if (signed) addRun(shown.substring(0, 1), Role.BODY, f, placeholder = false)
1484
+ addRun(format.prefix, Role.PREFIX, f, placeholder = false)
1485
+ addRun(if (signed) shown.substring(1) else shown, Role.BODY, f, placeholder = showPlaceholder)
1486
+ addRun(format.suffix, Role.SUFFIX, f, placeholder = false)
1487
+ engine.commitText(caret, now())
1488
+ fed = true
1489
+ reportIntrinsicSize()
1490
+ scheduleFrameIfNeeded()
1491
+ overlay.invalidate()
1492
+ }
1493
+
1494
+ /** A leading minus, in either the keyboard's spelling or the typographic one. */
1495
+ private fun isSign(c: Char): Boolean = c == '-' || c == '\u2212'
1496
+
1497
+ private fun addRun(s: String, role: Role, f: FontSet, placeholder: Boolean) {
1498
+ val numberKinds = role == Role.BODY && format.mode == Mode.NUMBER
1499
+ var i = 0
1500
+ while (i < s.length) {
1501
+ val cp = s.codePointAt(i)
1502
+ val kind = if (numberKinds) formatter.kindOf(cp) else 0
1503
+ engine.addGlyph(cp, role.ordinal, kind, f.width(cp, role).toDouble(), placeholder)
1504
+ i += Character.charCount(cp)
1505
+ }
1506
+ }
1507
+
1508
+ /** Nearest glyph boundary to a tap, as a UTF-16 offset into the edit text. */
1509
+ private fun offsetForTap(x: Float): Int {
1510
+ val layout = contentLayout(overlay.width, overlay.height, contentWidth)
1511
+ val contentX = (x - layout.originX) / layout.fit
1512
+ val bodyCount = engine.bodyCount()
1513
+ val current = editText.text?.toString() ?: ""
1514
+ val limit = min(bodyCount, current.codePointCount(0, current.length))
1515
+ var best = 0
1516
+ var bestDistance = Float.MAX_VALUE
1517
+ for (index in 0..limit) {
1518
+ val distance = abs(engine.caretX(index).toFloat() - contentX)
1519
+ if (distance < bestDistance) {
1520
+ bestDistance = distance
1521
+ best = index
1522
+ }
1523
+ }
1524
+ return utf16Index(current, best)
1525
+ }
1526
+
1527
+ private fun codePointIndex(s: String, utf16: Int): Int = s.codePointCount(0, utf16.coerceIn(0, s.length))
1528
+
1529
+ private fun utf16Index(s: String, codePoints: Int): Int {
1530
+ val total = s.codePointCount(0, s.length)
1531
+ return s.offsetByCodePoints(0, codePoints.coerceIn(0, total))
1532
+ }
1533
+
1534
+ // endregion
1535
+
1536
+ // region Frame loop
1537
+
1538
+ private fun now(): Double = SystemClock.uptimeMillis() / 1000.0
1539
+
1540
+ private fun scheduleFrameIfNeeded() {
1541
+ if (!frameScheduled && engine.needsFrames()) {
1542
+ frameScheduled = true
1543
+ Choreographer.getInstance().postFrameCallback(frameCallback)
1544
+ }
1545
+ }
1546
+
1547
+ /**
1548
+ * The animator duration scale on API < 33, read once and refreshed by
1549
+ * [animatorScaleObserver] (a settings query per keystroke was a binder call
1550
+ * on every edit). -1 = not read yet.
1551
+ */
1552
+ private var animatorScale = -1f
1553
+ private val animatorScaleObserver = object : ContentObserver(Handler(Looper.getMainLooper())) {
1554
+ override fun onChange(selfChange: Boolean) {
1555
+ animatorScale = -1f
1556
+ }
1557
+ }
1558
+
1559
+ /** True when the user removed animations (Android's animator scale is 0), the equivalent of Reduce Motion. */
1560
+ private fun animationsDisabled(): Boolean {
1561
+ val scale = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
1562
+ ValueAnimator.getDurationScale()
1563
+ } else {
1564
+ if (animatorScale < 0f) {
1565
+ animatorScale = Settings.Global.getFloat(context.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f)
1566
+ }
1567
+ animatorScale
1568
+ }
1569
+ return scale <= 0f
1570
+ }
1571
+
1572
+ /** Pulls the engine's render state into reusable [Glyph] objects (no per-frame allocation once warm). */
1573
+ private fun syncFromEngine() {
1574
+ var written = engine.frameInto(frameBuffer)
1575
+ if (written < 0) {
1576
+ frameBuffer = DoubleArray(3 + 11 * (engine.glyphCount() + 32))
1577
+ written = engine.frameInto(frameBuffer)
1578
+ if (written < 0) return
1579
+ }
1580
+ val f = frameBuffer
1581
+ val count = f[0].toInt()
1582
+ contentWidth = f[1].toFloat()
1583
+ while (glyphs.size < count) glyphs.add(Glyph())
1584
+ while (glyphs.size > count) glyphs.removeAt(glyphs.size - 1)
1585
+ for (i in 0 until count) {
1586
+ // Slot 0 is the engine's glyph id and slot 10 its exiting flag; neither
1587
+ // is needed to draw, so they are left in the buffer.
1588
+ val base = 3 + i * 11
1589
+ val g = glyphs[i]
1590
+ g.character = f[base + 1].toInt()
1591
+ g.role = f[base + 2].toInt()
1592
+ g.kind = f[base + 3].toInt()
1593
+ g.width = f[base + 4].toFloat()
1594
+ g.placeholder = f[base + 5] != 0.0
1595
+ g.x = f[base + 6].toFloat()
1596
+ g.y = f[base + 7].toFloat()
1597
+ g.opacity = f[base + 8].toFloat()
1598
+ g.scale = f[base + 9].toFloat()
1599
+ }
1600
+ }
1601
+
1602
+ // endregion
1603
+
1604
+ // region Intrinsic size
1605
+
1606
+ /**
1607
+ * One line, or - wrapping - as tall as the text actually is. `maxLines` caps
1608
+ * it, so a field with `numberOfLines` stops growing and scrolls instead;
1609
+ * without one it keeps growing and React follows through `onSizeChange`.
1610
+ */
1611
+ /** The height one line occupies: an explicit `lineHeight`, or the font's own. */
1612
+ private val lineBoxPx: Float
1613
+ get() = if (typography.lineHeightPx > 0f) typography.lineHeightPx else fonts.lineHeight
1614
+
1615
+ private fun intrinsicHeightPx(): Float {
1616
+ if (!keyboard.multiline) return fonts.lineHeight
1617
+ // The frame's padding counts on both paths. Leaving it off this one was
1618
+ // enough to lose it entirely: at mount there is no layout yet, so this
1619
+ // branch answered, and by the time the frame arrived and set the padding
1620
+ // the answer had not changed - so the report deduplicated itself away and
1621
+ // the box kept a height with no room for its own stroke.
1622
+ val padding = (editText.paddingTop + editText.paddingBottom).toFloat()
1623
+ val layout = editText.layout ?: return fonts.lineHeight * maxOf(1, keyboard.numberOfLines) + padding
1624
+ val lines = if (keyboard.numberOfLines > 0) {
1625
+ layout.lineCount.coerceAtMost(keyboard.numberOfLines).coerceAtLeast(keyboard.numberOfLines)
1626
+ } else {
1627
+ layout.lineCount.coerceAtLeast(1)
1628
+ }
1629
+ // With an explicit line height, compute the box rather than trusting
1630
+ // `layout.height`: StaticLayout does not add the extra leading after the
1631
+ // final line, so three lines at 34 measured 97.7dp instead of 102. Asking
1632
+ // for `numberOfLines` x `lineHeight` and getting it is the contract worth
1633
+ // having, and it keeps the two platforms agreeing.
1634
+ val text = when {
1635
+ typography.lineHeightPx > 0f -> fonts.lineHeight * lines
1636
+ lines == layout.lineCount -> layout.height.toFloat()
1637
+ else -> fonts.lineHeight * lines
1638
+ }
1639
+ return text + padding
1640
+ }
1641
+
1642
+ /**
1643
+ * The width the content asks for: the engine's layout in morph mode; in plain
1644
+ * mode, which never feeds the engine, the text (or the hint) and the affixes
1645
+ * measured with the paints the field draws them in.
1646
+ */
1647
+ private fun contentWidthPx(): Float {
1648
+ if (!keyboard.plain) return engine.targetWidth().toFloat()
1649
+ val body = when {
1650
+ text.isEmpty() -> effectivePlaceholder
1651
+ keyboard.secureTextEntry -> "\u2022".repeat(text.codePointCount(0, text.length))
1652
+ else -> text
1653
+ }
1654
+ return fonts.paint(Role.PREFIX).measureText(format.prefix) +
1655
+ fonts.paint(Role.BODY).measureText(body) +
1656
+ fonts.paint(Role.SUFFIX).measureText(format.suffix)
1657
+ }
1658
+
1659
+ private fun reportIntrinsicSize() {
1660
+ // The reported size is always the full-size one: with shrink-to-fit the view
1661
+ // keeps its height and the scaled text is centred inside it when drawing.
1662
+ val widthDp = ceil(contentWidthPx() / density + 2f)
1663
+ val heightDp = ceil(intrinsicHeightPx() / density)
1664
+ if (abs(widthDp - lastReportedWidth) <= 0.01f && abs(heightDp - lastReportedHeight) <= 0.01f) {
1665
+ pendingSizeReport = false
1666
+ return
1667
+ }
1668
+ // Growing: report right away so React widens the box before the new glyph
1669
+ // has arrived. Shrinking mid-morph: keep the wider box until the morph has
1670
+ // finished, otherwise adjustsFontSizeToFit would squeeze the leaving glyphs.
1671
+ if (lastReportedWidth > 0f && widthDp < lastReportedWidth && engine.isAnimating()) {
1672
+ pendingSizeReport = true
1673
+ return
1674
+ }
1675
+ pendingSizeReport = false
1676
+ lastReportedWidth = widthDp
1677
+ lastReportedHeight = heightDp
1678
+ onIntrinsicSizeChange?.invoke(widthDp, heightDp)
1679
+ }
1680
+
1681
+ // endregion
1682
+
1683
+ // region Drawing
1684
+
1685
+ private class ContentLayout(var originX: Float = 0f, var originY: Float = 0f, var fit: Float = 1f)
1686
+
1687
+ private val layoutScratch = ContentLayout()
1688
+
1689
+ /** Horizontal offset (px) when the content is wider than the view; follows the caret like an EditText scrolls. */
1690
+ private var scrollX = 0f
1691
+
1692
+ /**
1693
+ * Where the (possibly shrunk) content box sits inside a `width` x `height` view.
1694
+ * With [trackCaret] the scroll offset is updated to keep the caret in view
1695
+ * (drawing); without it the current offset is only read (hit testing).
1696
+ */
1697
+ /** Whether this view is laid out right-to-left. Fabric sets it from Yoga's resolved direction. */
1698
+ val isRtl: Boolean get() = layoutDirection == LAYOUT_DIRECTION_RTL
1699
+
1700
+ /** `AUTO` resolved against the layout direction; the rest are already absolute. */
1701
+ private val resolvedAlignment: Alignment
1702
+ get() = if (alignment == Alignment.AUTO) (if (isRtl) Alignment.RIGHT else Alignment.LEFT) else alignment
1703
+
1704
+ override fun onRtlPropertiesChanged(layoutDirection: Int) {
1705
+ super.onRtlPropertiesChanged(layoutDirection)
1706
+ // The overlay resolves `AUTO` at draw time, and the engine mirrors the
1707
+ // affixes; the frame's label and the plain affixes resolve themselves.
1708
+ engine.setRightToLeft(layoutDirection == LAYOUT_DIRECTION_RTL)
1709
+ overlay.invalidate()
1710
+ invalidate()
1711
+ }
1712
+
1713
+ private fun contentLayout(width: Int, height: Int, contentWidth: Float, trackCaret: Boolean = false): ContentLayout {
1714
+ val t = typography
1715
+ var fit = 1f
1716
+ if (t.adjustsFontSizeToFit && width > 0 && contentWidth > width) {
1717
+ fit = max(min(1f, t.minimumFontScale), width / contentWidth)
1718
+ }
1719
+ val out = layoutScratch
1720
+ out.fit = fit
1721
+ val shown = contentWidth * fit
1722
+ if (width > 0 && shown > width + 0.5f) {
1723
+ // Wider than the view (no shrink-to-fit, or its floor reached): scroll so
1724
+ // the caret stays visible while editing; at rest show the start (the end
1725
+ // for right-aligned content).
1726
+ val maxScroll = shown - width
1727
+ if (trackCaret) {
1728
+ if (editText.hasFocus()) {
1729
+ val margin = 2f * density
1730
+ val index = codePointIndex(text, editText.selectionStart).coerceIn(0, engine.bodyCount())
1731
+ val caretOnScreen = engine.caretX(index).toFloat() * fit - scrollX
1732
+ if (caretOnScreen > width - margin) scrollX += caretOnScreen - (width - margin)
1733
+ else if (caretOnScreen < margin) scrollX -= margin - caretOnScreen
1734
+ } else {
1735
+ scrollX = if (resolvedAlignment == Alignment.RIGHT) maxScroll else 0f
1736
+ }
1737
+ }
1738
+ scrollX = scrollX.coerceIn(0f, maxScroll)
1739
+ out.originX = -scrollX
1740
+ } else {
1741
+ scrollX = 0f
1742
+ out.originX = when (resolvedAlignment) {
1743
+ Alignment.AUTO, Alignment.LEFT -> 0f
1744
+ Alignment.CENTER -> (width - shown) / 2f
1745
+ Alignment.RIGHT -> width - shown
1746
+ }
1747
+ }
1748
+ out.originY = (height - fonts.lineHeight * fit) / 2f
1749
+ return out
1750
+ }
1751
+
1752
+ private fun drawContent(canvas: Canvas, view: View) {
1753
+ syncFromEngine()
1754
+ val f = fonts
1755
+ val side = frameSideInsetPx
1756
+ val top = frameTopInsetPx
1757
+ val boxWidth = max(0, (view.width - side * 2f).roundToInt())
1758
+ val boxHeight = max(0, (view.height - top).roundToInt())
1759
+ val layout = contentLayout(boxWidth, boxHeight, contentWidth, trackCaret = true)
1760
+ val lineHeight = f.lineHeight
1761
+ val textColor = resolvedTextColor
1762
+ val placeholderColor = resolvedPlaceholderColor
1763
+ val effect = timing.effect
1764
+
1765
+ val outer = canvas.save()
1766
+ // Content wider than the view is scrolled and clipped to the view's edges
1767
+ // (like an EditText); otherwise glyphs may overhang while they move.
1768
+ if (layout.originX < 0f || contentWidth * layout.fit > boxWidth + 0.5f) {
1769
+ canvas.clipRect(side, -1e5f, side + boxWidth, 1e5f)
1770
+ }
1771
+ canvas.translate(side + layout.originX, top + layout.originY)
1772
+ canvas.scale(layout.fit, layout.fit)
1773
+
1774
+ for (g in glyphs) {
1775
+ if (g.opacity <= 0f) continue
1776
+ val role = ROLES[g.role.coerceIn(0, 2)]
1777
+ val paint = f.paint(role)
1778
+ val base = if (g.placeholder) placeholderColor else textColor
1779
+ paint.color = base
1780
+ // The hint colour carries its own alpha — the platform's is translucent
1781
+ // black, not grey. Multiply the morph's opacity into it rather than
1782
+ // replacing it, or the placeholder is drawn solid.
1783
+ val alpha = (Color.alpha(base) * g.opacity).roundToInt().coerceIn(0, 255)
1784
+ if (alpha == 0) continue
1785
+ paint.alpha = alpha
1786
+ val str = charString(g.character)
1787
+ val slides = effect == Effect.SLIDE || (effect == Effect.AUTO && g.kind != 0)
1788
+ canvas.save()
1789
+ // Sliding glyphs pass through the line box: clip so they appear from its
1790
+ // edges, with a 0.15 em margin so a comma's tail is never cut at rest.
1791
+ if (slides) {
1792
+ val band = min(lineHeight / 3f, 0.15f * f.paint(Role.BODY).textSize)
1793
+ canvas.clipRect(-1e5f, -band, 1e5f, lineHeight + band)
1794
+ }
1795
+ if (g.scale != 1f) canvas.scale(g.scale, g.scale, g.x + g.width / 2f, lineHeight / 2f)
1796
+ canvas.drawText(str, g.x, f.baseline(role, str, 0f) + g.y * lineHeight, paint)
1797
+ canvas.restore()
1798
+ }
1799
+
1800
+ if (shouldShowCaret() && blinkOn) {
1801
+ val index = codePointIndex(text, editText.selectionStart).coerceIn(0, engine.bodyCount())
1802
+ val x = engine.caretX(index).toFloat()
1803
+ val w = CARET_WIDTH_DP * density
1804
+ val h = lineHeight * (1f - CARET_INSET)
1805
+ val top = (lineHeight - h) / 2f
1806
+ caretPaint.color = resolvedCaretColor
1807
+ canvas.drawRoundRect(x, top, x + w, top + h, w / 2f, w / 2f, caretPaint)
1808
+ }
1809
+ canvas.restoreToCount(outer)
1810
+ }
1811
+
1812
+ // endregion
1813
+
1814
+ // region Outlined / filled frame
1815
+
1816
+ /**
1817
+ * How far in the label - and so the text under it - starts. Far enough past
1818
+ * the corner that the notch never opens onto the arc itself.
1819
+ */
1820
+ private val labelInsetPx: Float
1821
+ get() = max(LABEL_INSET_DP * density, inputFrame.cornerRadius * density + LABEL_CORNER_GAP_DP * density)
1822
+
1823
+ private val frameSideInsetPx: Float
1824
+ get() = if (inputFrame.draws) labelInsetPx else 0f
1825
+
1826
+ /**
1827
+ * Room at the top for the floated label - which only the filled variant
1828
+ * needs. Its label floats inside the box, on its own line above the text. An
1829
+ * outlined field's label sits *on* the stroke, outside the content box: it
1830
+ * intrudes into the top of the frame but never onto the text's line, so the
1831
+ * text stays centred the way it would with no label at all.
1832
+ */
1833
+ private val frameTopInsetPx: Float
1834
+ get() {
1835
+ if (!inputFrame.hasLabel || inputFrame.variant != Variant.FILLED) return 0f
1836
+ // 1.4 is a fudge, not a Material metric - see the note on iOS.
1837
+ return floatedLabelSizePx * 1.4f
1838
+ }
1839
+
1840
+ private val restingLabelSizePx: Float get() = fonts.paint(Role.BODY).textSize
1841
+
1842
+ private val floatedLabelSizePx: Float
1843
+ get() {
1844
+ val explicit = inputFrame.labelFontSize
1845
+ if (explicit > 0f) return explicit * density
1846
+ return max(MIN_FLOATED_LABEL_DP * density, restingLabelSizePx * FLOATED_LABEL_RATIO)
1847
+ }
1848
+
1849
+ /** The label floats once focused or holding text - or always, if asked. */
1850
+ private val labelShouldFloat: Boolean
1851
+ get() {
1852
+ if (!inputFrame.hasLabel) return false
1853
+ if (inputFrame.labelBehavior == LabelBehavior.ALWAYS) return true
1854
+ return editText.hasFocus() || text.isNotEmpty()
1855
+ }
1856
+
1857
+ /**
1858
+ * A label resting inside the field already labels it, so the placeholder
1859
+ * waits until the label has floated clear rather than printing over it.
1860
+ */
1861
+ private val effectivePlaceholder: String
1862
+ get() = if (inputFrame.hasLabel && !labelShouldFloat) "" else format.placeholder
1863
+
1864
+ private fun resolvedStrokeColor(): Int {
1865
+ val base = inputFrame.strokeColor ?: mutedTextColor
1866
+ return blend(base, inputFrame.focusedStrokeColor ?: base, focusProgress)
1867
+ }
1868
+
1869
+ private fun resolvedLabelColor(): Int {
1870
+ val resting = inputFrame.labelColor ?: mutedTextColor
1871
+ val focused = inputFrame.labelFocusedColor ?: inputFrame.focusedStrokeColor ?: resting
1872
+ return blend(resting, focused, focusProgress)
1873
+ }
1874
+
1875
+ /** Doubles while focused, the way the iOS frame thickens its stroke. */
1876
+ private val strokeWidthPx: Float
1877
+ get() = inputFrame.strokeWidth * density * (1f + focusProgress)
1878
+
1879
+ private fun blend(from: Int, to: Int, t: Float): Int {
1880
+ if (t <= 0f || from == to) return from
1881
+ if (t >= 1f) return to
1882
+ fun mix(shift: Int): Int {
1883
+ val a = (from shr shift) and 0xff
1884
+ val b = (to shr shift) and 0xff
1885
+ return (a + (b - a) * t).roundToInt().coerceIn(0, 255)
1886
+ }
1887
+ return Color.argb(mix(24), mix(16), mix(8), mix(0))
1888
+ }
1889
+
1890
+ /**
1891
+ * Runs the stroke to its focused colour and weight. Separate from the label:
1892
+ * a field that already holds text does not move its label on focus, but the
1893
+ * stroke still travels.
1894
+ */
1895
+ private fun syncFocusProgress(animated: Boolean) {
1896
+ if (!inputFrame.draws) {
1897
+ focusAnimator?.cancel()
1898
+ focusAnimator = null
1899
+ focusProgress = if (editText.hasFocus()) 1f else 0f
1900
+ return
1901
+ }
1902
+ val target = if (editText.hasFocus()) 1f else 0f
1903
+ if (focusAnimator == null && focusProgress == target) return
1904
+ focusAnimator?.cancel()
1905
+ focusAnimator = null
1906
+ if (!animated || !isAttachedToWindow) {
1907
+ focusProgress = target
1908
+ invalidate()
1909
+ return
1910
+ }
1911
+ focusAnimator = run(focusProgress, target, FRAME_ANIM_MS, 0L) { focusProgress = it }
1912
+ }
1913
+
1914
+ private fun rebuildLabelPaint() {
1915
+ val body = fonts.paint(Role.BODY)
1916
+ labelPaint.typeface = body.typeface
1917
+ labelPaint.textSize = restingLabelSizePx
1918
+ }
1919
+
1920
+ /**
1921
+ * Runs the label to where it belongs. The morph glyphs are laid out against
1922
+ * the insets, and the placeholder appears only once the label is clear of it,
1923
+ * so a change re-feeds the engine as well as redrawing.
1924
+ */
1925
+ private fun syncLabelProgress(animated: Boolean) {
1926
+ if (!inputFrame.hasLabel) {
1927
+ labelAnimator?.cancel()
1928
+ labelAnimator = null
1929
+ notchAnimator?.cancel()
1930
+ notchAnimator = null
1931
+ labelProgress = 0f
1932
+ notchProgress = 0f
1933
+ return
1934
+ }
1935
+ val target = if (labelShouldFloat) 1f else 0f
1936
+ if (labelAnimator == null && labelProgress == target && notchProgress == target) return
1937
+ labelAnimator?.cancel()
1938
+ labelAnimator = null
1939
+ notchAnimator?.cancel()
1940
+ notchAnimator = null
1941
+ if (!animated || !isAttachedToWindow) {
1942
+ labelProgress = target
1943
+ notchProgress = target
1944
+ onLabelFloatChanged()
1945
+ invalidate()
1946
+ return
1947
+ }
1948
+ // The placeholder swaps at the start of the run, not the end: it is the
1949
+ // floated label that frees the line for it.
1950
+ onLabelFloatChanged()
1951
+ labelAnimator = run(labelProgress, target, FRAME_ANIM_MS, 0L) { labelProgress = it }
1952
+ // Staggered behind the label opening, ahead of it closing - the same shape
1953
+ // MUI gives its notched outline. See the timing note in the companion.
1954
+ val opening = target == 1f
1955
+ notchAnimator = run(
1956
+ notchProgress,
1957
+ target,
1958
+ if (opening) NOTCH_OPEN_MS else NOTCH_CLOSE_MS,
1959
+ if (opening) NOTCH_OPEN_DELAY_MS else 0L,
1960
+ ) { notchProgress = it }
1961
+ }
1962
+
1963
+ /** One eased float animator, invalidating as it goes. */
1964
+ private inline fun run(
1965
+ from: Float,
1966
+ to: Float,
1967
+ durationMs: Long,
1968
+ delayMs: Long,
1969
+ crossinline apply: (Float) -> Unit,
1970
+ ): ValueAnimator = ValueAnimator.ofFloat(from, to).apply {
1971
+ duration = durationMs
1972
+ startDelay = delayMs
1973
+ interpolator = DECELERATE
1974
+ addUpdateListener {
1975
+ apply(it.animatedValue as Float)
1976
+ invalidate()
1977
+ }
1978
+ start()
1979
+ }
1980
+
1981
+ /** The placeholder waits for a resting label to float clear of the line. */
1982
+ private fun applyHint() {
1983
+ val hint = effectivePlaceholder
1984
+ if (editText.hint?.toString() != hint) editText.hint = hint
1985
+ }
1986
+
1987
+ /** Re-feeds the engine so the placeholder follows the label. */
1988
+ private fun onLabelFloatChanged() {
1989
+ applyHint()
1990
+ requestFeed(-1)
1991
+ overlay.invalidate()
1992
+ }
1993
+
1994
+ override fun onDraw(canvas: Canvas) {
1995
+ super.onDraw(canvas)
1996
+ if (!inputFrame.draws || width <= 0 || height <= 0) return
1997
+
1998
+ val filled = inputFrame.variant == Variant.FILLED
1999
+ val stroke = strokeWidthPx
2000
+ val label = inputFrame.label
2001
+ val floatedSize = floatedLabelSizePx
2002
+ val restingSize = restingLabelSizePx
2003
+
2004
+ // The notch has to match the label at its floated size whatever the
2005
+ // progress, so the two paths we tween between describe the same shape.
2006
+ labelPaint.textSize = floatedSize
2007
+ val floatedWidth = if (inputFrame.hasLabel) labelPaint.measureText(label) else 0f
2008
+ labelPaint.textSize = restingSize
2009
+ val restingWidth = if (inputFrame.hasLabel) labelPaint.measureText(label) else 0f
2010
+
2011
+ val inset = labelInsetPx
2012
+ // The label sits at the start edge: `inset` from the left, or the same
2013
+ // distance from the right under a right-to-left layout. The notch is cut
2014
+ // where the floated label is, so it follows.
2015
+ val restingX = if (isRtl) width - inset - restingWidth else inset
2016
+ val floatedX = if (isRtl) width - inset - floatedWidth else inset
2017
+ val floatedCentreY = if (filled) floatedSize * 0.9f else 0f
2018
+ // Resting: on the text's own line. A single line is centred in the box, so
2019
+ // that is the middle; a wrapping one starts at the top, and the label
2020
+ // belongs where the first character will appear rather than halfway down
2021
+ // an empty field.
2022
+ val restingCentreY = if (keyboard.multiline) {
2023
+ editText.paddingTop + lineBoxPx / 2f
2024
+ } else {
2025
+ height / 2f
2026
+ }
2027
+
2028
+ outlineGeometry.lerp(
2029
+ restingX.toDouble(), restingCentreY.toDouble(), restingWidth.toDouble(), restingSize.toDouble(),
2030
+ floatedX.toDouble(), floatedCentreY.toDouble(), floatedWidth.toDouble(), floatedSize.toDouble(),
2031
+ labelProgress.toDouble(), labelRect,
2032
+ )
2033
+
2034
+ // Filled is not stroked, so its path is the fill's own edge rather than the
2035
+ // centre line of a stroke, and its bottom is square: that is the edge the
2036
+ // indicator rule sits flush against. Only the outlined variant is notched.
2037
+ val gapWidth = if (inputFrame.hasLabel && !filled) floatedWidth.toDouble() else 0.0
2038
+ if (!buildOutlinePath(
2039
+ width.toDouble(), height.toDouble(), inputFrame.cornerRadius * density.toDouble(),
2040
+ if (filled) 0.0 else stroke.toDouble(), if (filled) 0.0 else -1.0,
2041
+ floatedX.toDouble(), gapWidth, (LABEL_GAP_PADDING_DP * density).toDouble(), notchProgress.toDouble(),
2042
+ )
2043
+ ) {
2044
+ return
2045
+ }
2046
+
2047
+ if (filled) {
2048
+ framePaint.style = Paint.Style.FILL
2049
+ framePaint.color = inputFrame.fillColor ?: defaultFillColor()
2050
+ canvas.drawPath(framePath, framePaint)
2051
+ // The active indicator, along the square bottom edge.
2052
+ framePaint.style = Paint.Style.FILL
2053
+ framePaint.color = resolvedStrokeColor()
2054
+ canvas.drawRect(0f, height - stroke, width.toFloat(), height.toFloat(), framePaint)
2055
+ } else {
2056
+ framePaint.style = Paint.Style.STROKE
2057
+ framePaint.strokeWidth = stroke
2058
+ framePaint.color = resolvedStrokeColor()
2059
+ canvas.drawPath(framePath, framePaint)
2060
+ }
2061
+
2062
+ if (!inputFrame.hasLabel) return
2063
+ labelPaint.textSize = restingSize + (floatedSize - restingSize) * labelProgress
2064
+ labelPaint.color = resolvedLabelColor()
2065
+ val metrics = labelPaint.fontMetrics
2066
+ // The rect's y is the label's vertical centre, as it is on iOS.
2067
+ val baseline = labelRect[1].toFloat() - (metrics.ascent + metrics.descent) / 2f
2068
+ canvas.drawText(label, labelRect[0].toFloat(), baseline, labelPaint)
2069
+ }
2070
+
2071
+ /**
2072
+ * Traces the shared geometry into [framePath]. False when the box is too
2073
+ * small to have an outline at all.
2074
+ */
2075
+ private fun buildOutlinePath(
2076
+ boxWidth: Double,
2077
+ boxHeight: Double,
2078
+ radius: Double,
2079
+ stroke: Double,
2080
+ bottomRadius: Double,
2081
+ gapLeft: Double,
2082
+ gapWidth: Double,
2083
+ gapPadding: Double,
2084
+ progress: Double,
2085
+ ): Boolean {
2086
+ var count = outlineGeometry.outline(
2087
+ boxWidth, boxHeight, radius, stroke, bottomRadius, gapLeft, gapWidth, gapPadding, progress, outlineBuffer,
2088
+ )
2089
+ if (count < 0) {
2090
+ // Only ever a handful of segments, but grow rather than guess.
2091
+ outlineBuffer = DoubleArray(outlineBuffer.size * 2)
2092
+ count = outlineGeometry.outline(
2093
+ boxWidth, boxHeight, radius, stroke, bottomRadius, gapLeft, gapWidth, gapPadding, progress, outlineBuffer,
2094
+ )
2095
+ }
2096
+ if (count <= 0) return false
2097
+
2098
+ framePath.rewind()
2099
+ for (i in 0 until count) {
2100
+ val base = i * OutlineGeometry.STRIDE
2101
+ val x = outlineBuffer[base + 1].toFloat()
2102
+ val y = outlineBuffer[base + 2].toFloat()
2103
+ when (outlineBuffer[base].toInt()) {
2104
+ OutlineGeometry.MOVE -> framePath.moveTo(x, y)
2105
+ OutlineGeometry.LINE -> framePath.lineTo(x, y)
2106
+ else -> {
2107
+ // x/y is the arc's centre; the angles are the degrees `arcTo` takes.
2108
+ val r = outlineBuffer[base + 3].toFloat()
2109
+ arcOval.set(x - r, y - r, x + r, y + r)
2110
+ framePath.arcTo(arcOval, outlineBuffer[base + 4].toFloat(), outlineBuffer[base + 5].toFloat())
2111
+ }
2112
+ }
2113
+ }
2114
+ return true
2115
+ }
2116
+
2117
+ /** Matches iOS's `.secondarySystemFill`, which the filled variant defaults to. */
2118
+ private fun defaultFillColor(): Int = Color.argb(0x1f, 0x78, 0x78, 0x80)
2119
+
2120
+ // endregion
2121
+
2122
+ // region Drawing
2123
+
2124
+ private fun shouldShowCaret(): Boolean =
2125
+ isAttachedToWindow && editText.hasFocus() && !caret.hidden && editText.selectionStart == editText.selectionEnd
2126
+
2127
+ private fun restartBlink() {
2128
+ removeCallbacks(blink)
2129
+ blinkOn = true
2130
+ overlay.invalidate()
2131
+ if (shouldShowCaret()) postDelayed(blink, BLINK_MS)
2132
+ }
2133
+
2134
+ // endregion
2135
+
2136
+ companion object {
2137
+ /** Matches iOS's `.placeholderText`, which is the label colour at 30-40%. */
2138
+ private const val PLACEHOLDER_ALPHA = 0.38f
2139
+ private const val ALL_DIGITS = "0123456789"
2140
+ private const val BLINK_MS = 500L
2141
+ private const val CARET_WIDTH_DP = 2f
2142
+ /** Fraction of the line height the caret leaves free (split between top and bottom). */
2143
+ private const val CARET_INSET = 0.1f
2144
+ /** How far the label starts from the frame's left edge, at a minimum. */
2145
+ private const val LABEL_INSET_DP = 16f
2146
+ /**
2147
+ * The room a framed field keeps above and below its text. Flat, unlike the
2148
+ * side inset: that one grows with `cornerRadius` because the *label* has to
2149
+ * clear the corner curve, which is a horizontal problem. The text sits in
2150
+ * the middle of the box, so a rounder frame must not make the field taller.
2151
+ */
2152
+ private const val FRAME_PADDING_DP = 16f
2153
+ /** Clearance the label keeps past the corner arc, so the notch opens onto the straight run. */
2154
+ private const val LABEL_CORNER_GAP_DP = 8f
2155
+ /** Breathing room the notch leaves on each side of the label. */
2156
+ private const val LABEL_GAP_PADDING_DP = 4f
2157
+ /** The floated label's size, as a fraction of the resting one. */
2158
+ private const val FLOATED_LABEL_RATIO = 0.75f
2159
+ private const val MIN_FLOATED_LABEL_DP = 9f
2160
+ /**
2161
+ * Taken from Material's own text fields. MUI's OutlinedInput runs the label
2162
+ * 200ms on the standard decelerate curve and the legend's width 100ms after
2163
+ * a 50ms delay when notching, 50ms flat when un-notching. Material
2164
+ * Components Android runs label and cutout off one animator instead (167ms,
2165
+ * or 400ms `motionDurationMedium4` under an M3 theme) and snaps the stroke;
2166
+ * we animate the stroke with the label.
2167
+ */
2168
+ private const val FRAME_ANIM_MS = 200L
2169
+ private const val NOTCH_OPEN_DELAY_MS = 50L
2170
+ private const val NOTCH_OPEN_MS = 100L
2171
+ private const val NOTCH_CLOSE_MS = 50L
2172
+ /** Material's standard decelerate, the same curve the iOS side uses. */
2173
+ private val DECELERATE = PathInterpolator(0f, 0f, 0.2f, 1f)
2174
+ private val ROLES = Role.values()
2175
+ }
2176
+ }