react-native-nitro-input 0.3.7 → 0.4.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 (129) hide show
  1. package/CHANGELOG.md +133 -0
  2. package/README.md +9 -4
  3. package/android/CMakeLists.txt +1 -0
  4. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroInputMeasure.kt +52 -0
  5. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroInputView.kt +74 -80
  6. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroNumberView.kt +18 -18
  7. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroTextView.kt +14 -14
  8. package/android/src/main/java/com/margelo/nitro/nitroinput/InputFonts.kt +199 -0
  9. package/android/src/main/java/com/margelo/nitro/nitroinput/InputSizing.kt +398 -0
  10. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputView.kt +112 -333
  11. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroNumberView.kt +178 -30
  12. package/cpp/RollingEngine.cpp +68 -5
  13. package/cpp/RollingEngine.hpp +13 -0
  14. package/cpp/numberformat/FormatFigure.cpp +134 -0
  15. package/cpp/numberformat/FormatFigure.hpp +65 -0
  16. package/cpp/numberformat/HybridNitroNumberFormat.cpp +32 -10
  17. package/cpp/numberformat/HybridNitroNumberFormat.hpp +9 -1
  18. package/ios/HybridNitroInputView.swift +69 -75
  19. package/ios/HybridNitroNumberView.swift +18 -18
  20. package/ios/HybridNitroTextView.swift +14 -14
  21. package/ios/InputSizing.swift +534 -0
  22. package/ios/NitroInputView.swift +102 -198
  23. package/ios/NitroNumberView.swift +98 -23
  24. package/lib/commonjs/nitrogen/generated/shared/json/NitroInputViewConfig.json +12 -8
  25. package/lib/commonjs/nitrogen/generated/shared/json/NitroNumberViewConfig.json +6 -6
  26. package/lib/commonjs/nitrogen/generated/shared/json/NitroTextViewConfig.json +6 -6
  27. package/lib/commonjs/src/NitroInput.js +164 -23
  28. package/lib/commonjs/src/NitroNumber.js +19 -11
  29. package/lib/commonjs/src/NitroText.js +6 -6
  30. package/lib/commonjs/src/NumberFormat.js +20 -0
  31. package/lib/commonjs/src/formatProps.js +57 -81
  32. package/lib/commonjs/src/specs/NitroInputMeasure.nitro.js +2 -0
  33. package/lib/module/nitrogen/generated/shared/json/NitroInputViewConfig.json +12 -8
  34. package/lib/module/nitrogen/generated/shared/json/NitroNumberViewConfig.json +6 -6
  35. package/lib/module/nitrogen/generated/shared/json/NitroTextViewConfig.json +6 -6
  36. package/lib/module/src/NitroInput.js +165 -24
  37. package/lib/module/src/NitroNumber.js +20 -12
  38. package/lib/module/src/NitroText.js +6 -6
  39. package/lib/module/src/NumberFormat.js +18 -0
  40. package/lib/module/src/formatProps.js +54 -81
  41. package/lib/module/src/specs/NitroInputMeasure.nitro.js +1 -0
  42. package/lib/typescript/src/NitroInput.d.ts +9 -16
  43. package/lib/typescript/src/NitroNumber.d.ts +25 -7
  44. package/lib/typescript/src/NumberFormat.d.ts +15 -1
  45. package/lib/typescript/src/formatProps.d.ts +23 -18
  46. package/lib/typescript/src/specs/NitroInput.nitro.d.ts +17 -8
  47. package/lib/typescript/src/specs/NitroInputMeasure.nitro.d.ts +67 -0
  48. package/lib/typescript/src/specs/NitroNumber.nitro.d.ts +6 -6
  49. package/lib/typescript/src/specs/NitroText.nitro.d.ts +6 -6
  50. package/lib/typescript/src/specs/NumberFormat.nitro.d.ts +33 -0
  51. package/nitro.json +10 -0
  52. package/nitrogen/generated/android/NitroInput+autolinking.cmake +2 -0
  53. package/nitrogen/generated/android/NitroInputOnLoad.cpp +16 -0
  54. package/nitrogen/generated/android/c++/JHybridNitroInputMeasureSpec.cpp +93 -0
  55. package/nitrogen/generated/android/c++/JHybridNitroInputMeasureSpec.hpp +63 -0
  56. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.cpp +76 -40
  57. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.hpp +24 -16
  58. package/nitrogen/generated/android/c++/JHybridNitroNumberViewSpec.cpp +30 -30
  59. package/nitrogen/generated/android/c++/JHybridNitroNumberViewSpec.hpp +12 -12
  60. package/nitrogen/generated/android/c++/JHybridNitroTextViewSpec.cpp +30 -30
  61. package/nitrogen/generated/android/c++/JHybridNitroTextViewSpec.hpp +12 -12
  62. package/nitrogen/generated/android/c++/JNitroInputSize.hpp +61 -0
  63. package/nitrogen/generated/android/c++/JNitroInputSizing.hpp +284 -0
  64. package/nitrogen/generated/android/c++/views/JHybridNitroInputViewStateUpdater.cpp +44 -24
  65. package/nitrogen/generated/android/c++/views/JHybridNitroNumberViewStateUpdater.cpp +18 -18
  66. package/nitrogen/generated/android/c++/views/JHybridNitroTextViewStateUpdater.cpp +18 -18
  67. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroInputMeasureSpec.kt +56 -0
  68. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroInputViewSpec.kt +32 -8
  69. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroNumberViewSpec.kt +6 -6
  70. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroTextViewSpec.kt +6 -6
  71. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputSize.kt +56 -0
  72. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputSizing.kt +246 -0
  73. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.cpp +17 -0
  74. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.hpp +29 -0
  75. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Umbrella.hpp +11 -0
  76. package/nitrogen/generated/ios/NitroInputAutolinking.mm +8 -0
  77. package/nitrogen/generated/ios/NitroInputAutolinking.swift +12 -0
  78. package/nitrogen/generated/ios/c++/HybridNitroInputMeasureSpecSwift.cpp +11 -0
  79. package/nitrogen/generated/ios/c++/HybridNitroInputMeasureSpecSwift.hpp +112 -0
  80. package/nitrogen/generated/ios/c++/HybridNitroInputViewSpecSwift.hpp +56 -32
  81. package/nitrogen/generated/ios/c++/HybridNitroNumberViewSpecSwift.hpp +24 -24
  82. package/nitrogen/generated/ios/c++/HybridNitroTextViewSpecSwift.hpp +24 -24
  83. package/nitrogen/generated/ios/c++/views/HybridNitroInputViewComponent.mm +56 -32
  84. package/nitrogen/generated/ios/c++/views/HybridNitroNumberViewComponent.mm +24 -24
  85. package/nitrogen/generated/ios/c++/views/HybridNitroTextViewComponent.mm +24 -24
  86. package/nitrogen/generated/ios/swift/HybridNitroInputMeasureSpec.swift +55 -0
  87. package/nitrogen/generated/ios/swift/HybridNitroInputMeasureSpec_cxx.swift +138 -0
  88. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec.swift +12 -8
  89. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec_cxx.swift +68 -24
  90. package/nitrogen/generated/ios/swift/HybridNitroNumberViewSpec.swift +6 -6
  91. package/nitrogen/generated/ios/swift/HybridNitroNumberViewSpec_cxx.swift +18 -18
  92. package/nitrogen/generated/ios/swift/HybridNitroTextViewSpec.swift +6 -6
  93. package/nitrogen/generated/ios/swift/HybridNitroTextViewSpec_cxx.swift +18 -18
  94. package/nitrogen/generated/ios/swift/NitroInputSize.swift +34 -0
  95. package/nitrogen/generated/ios/swift/NitroInputSizing.swift +242 -0
  96. package/nitrogen/generated/shared/c++/HybridNitroInputMeasureSpec.cpp +21 -0
  97. package/nitrogen/generated/shared/c++/HybridNitroInputMeasureSpec.hpp +66 -0
  98. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.cpp +24 -16
  99. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.hpp +24 -16
  100. package/nitrogen/generated/shared/c++/HybridNitroNumberFormatSpec.cpp +2 -0
  101. package/nitrogen/generated/shared/c++/HybridNitroNumberFormatSpec.hpp +8 -0
  102. package/nitrogen/generated/shared/c++/HybridNitroNumberViewSpec.cpp +12 -12
  103. package/nitrogen/generated/shared/c++/HybridNitroNumberViewSpec.hpp +12 -12
  104. package/nitrogen/generated/shared/c++/HybridNitroTextViewSpec.cpp +12 -12
  105. package/nitrogen/generated/shared/c++/HybridNitroTextViewSpec.hpp +12 -12
  106. package/nitrogen/generated/shared/c++/NitroInputSize.hpp +87 -0
  107. package/nitrogen/generated/shared/c++/NitroInputSizing.hpp +263 -0
  108. package/nitrogen/generated/shared/c++/NumberFigure.hpp +95 -0
  109. package/nitrogen/generated/shared/c++/NumberFormatLayout.hpp +112 -0
  110. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.cpp +24 -16
  111. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.hpp +36 -24
  112. package/nitrogen/generated/shared/c++/views/HybridNitroNumberViewComponent.cpp +12 -12
  113. package/nitrogen/generated/shared/c++/views/HybridNitroNumberViewComponent.hpp +18 -18
  114. package/nitrogen/generated/shared/c++/views/HybridNitroTextViewComponent.cpp +12 -12
  115. package/nitrogen/generated/shared/c++/views/HybridNitroTextViewComponent.hpp +18 -18
  116. package/nitrogen/generated/shared/json/NitroInputViewConfig.json +12 -8
  117. package/nitrogen/generated/shared/json/NitroNumberViewConfig.json +6 -6
  118. package/nitrogen/generated/shared/json/NitroTextViewConfig.json +6 -6
  119. package/package.json +5 -3
  120. package/src/NitroInput.tsx +201 -64
  121. package/src/NitroNumber.tsx +54 -25
  122. package/src/NitroText.tsx +6 -6
  123. package/src/NumberFormat.ts +22 -0
  124. package/src/formatProps.ts +59 -99
  125. package/src/specs/NitroInput.nitro.ts +17 -8
  126. package/src/specs/NitroInputMeasure.nitro.ts +76 -0
  127. package/src/specs/NitroNumber.nitro.ts +6 -6
  128. package/src/specs/NitroText.nitro.ts +6 -6
  129. package/src/specs/NumberFormat.nitro.ts +35 -0
@@ -0,0 +1,534 @@
1
+ ///
2
+ /// InputSizing.swift
3
+ /// What a single-line field's size follows, worked out the same way before its
4
+ /// view exists (`HybridNitroInputMeasure`, on the JS thread) and after
5
+ /// (`NitroInputView.reportIntrinsicSize`, on the main thread).
6
+ ///
7
+ /// Mirrors `InputSizing.kt` on Android.
8
+ ///
9
+
10
+ import Foundation
11
+ import NitroModules
12
+ import UIKit
13
+
14
+ private typealias AmountFormatter = margelo.nitro.nitroinput.AmountFormatter
15
+ private typealias MaskEngine = margelo.nitro.nitroinput.MaskEngine
16
+
17
+ // MARK: - Props
18
+
19
+ /// The props a field's size follows, under the names both
20
+ /// `HybridNitroInputView` and `NitroInputSizing` give them, so one mapping
21
+ /// serves the view and the measure that runs before it exists.
22
+ protocol InputSizingProps {
23
+ var mode: NitroInputMode { get }
24
+ var mask: String { get }
25
+ var maskNotations: [NitroInputNotation] { get }
26
+ var maskAutocomplete: Bool { get }
27
+ var maskAutoSkip: Bool { get }
28
+ var maskAffinityFormats: [String] { get }
29
+ var maskAffinityStrategy: NitroInputMaskAffinity { get }
30
+ var maskTextCase: NitroInputTextCase { get }
31
+ var maskCharacterMap: [NitroInputCharacterMapping] { get }
32
+ var maskSlotPlaceholder: String { get }
33
+ var keepPlaceholder: Bool { get }
34
+ var fractionDigits: Double { get }
35
+ var maxIntegerDigits: Double { get }
36
+ var groupingSeparator: String { get }
37
+ var decimalSeparator: String { get }
38
+ var prefix: String { get }
39
+ var suffix: String { get }
40
+ var signPlacement: NitroInputSignPlacement { get }
41
+ var placeholder: String { get }
42
+ var maxLength: Double { get }
43
+ var textSize: Double { get }
44
+ var textLineHeight: Double { get }
45
+ var prefixFontSize: Double { get }
46
+ var suffixFontSize: Double { get }
47
+ var textWeight: Double { get }
48
+ var textFamily: String { get }
49
+ var textLetterSpacing: Double { get }
50
+ var prefixSpacing: Double { get }
51
+ var suffixSpacing: Double { get }
52
+ var allowFontScaling: Bool { get }
53
+ var maxFontSizeMultiplier: Double { get }
54
+ var variant: NitroInputVariant { get }
55
+ var label: String { get }
56
+ var labelBehavior: NitroInputLabelBehavior { get }
57
+ var labelFontSize: Double { get }
58
+ var cornerRadius: Double { get }
59
+ }
60
+
61
+ extension HybridNitroInputView: InputSizingProps {}
62
+ extension NitroInputSizing: InputSizingProps {}
63
+
64
+ enum InputMapping {
65
+ static func clampInt(_ value: Double, _ lower: Int, _ upper: Int, fallback: Int) -> Int {
66
+ guard value.isFinite else { return fallback }
67
+ return min(upper, max(lower, Int(value.rounded())))
68
+ }
69
+
70
+ static func format(_ p: some InputSizingProps) -> NitroInputView.Format {
71
+ var format = NitroInputView.Format()
72
+ switch p.mode {
73
+ case .number: format.mode = .number
74
+ case .mask: format.mode = .mask
75
+ case .text: format.mode = .text
76
+ }
77
+ format.mask = p.mask
78
+ format.maskNotations = p.maskNotations.map {
79
+ NitroInputView.MaskNotation(character: $0.character, characterSet: $0.characterSet, isOptional: $0.isOptional)
80
+ }
81
+ format.maskAutocomplete = p.maskAutocomplete
82
+ format.maskAutoSkip = p.maskAutoSkip
83
+ format.maskAffinityFormats = p.maskAffinityFormats
84
+ format.maskAffinityStrategy = Int(p.maskAffinityStrategy.rawValue)
85
+ format.maskTextCase = Int(p.maskTextCase.rawValue)
86
+ format.maskCharacterMap = p.maskCharacterMap.map { NitroInputView.MaskMapping(from: $0.from, to: $0.to) }
87
+ format.maskSlotPlaceholder = p.maskSlotPlaceholder
88
+ format.keepPlaceholder = p.keepPlaceholder
89
+ format.fractionDigits = clampInt(p.fractionDigits, 0, 9, fallback: 2)
90
+ format.maxIntegerDigits = clampInt(p.maxIntegerDigits, 1, 30, fallback: 15)
91
+ format.groupingSeparator = p.groupingSeparator
92
+ format.decimalSeparator = p.decimalSeparator.isEmpty ? "." : p.decimalSeparator
93
+ format.prefix = p.prefix
94
+ format.suffix = p.suffix
95
+ format.signPlacement = p.signPlacement == .afteraffix ? .afterAffix : .beforeAffix
96
+ format.placeholder = p.placeholder
97
+ format.maxLength = clampInt(p.maxLength, 0, 1_000_000, fallback: 0)
98
+ return format
99
+ }
100
+
101
+ /// The typography's sizing half; the view adds the colours, alignment and offsets.
102
+ static func sizingTypography(_ p: some InputSizingProps) -> NitroInputView.Typography {
103
+ var typography = NitroInputView.Typography()
104
+ typography.fontSize = CGFloat(p.textSize.isFinite && p.textSize > 0 ? p.textSize : 32)
105
+ typography.lineHeight = CGFloat(p.textLineHeight.isFinite && p.textLineHeight > 0 ? p.textLineHeight : 0)
106
+ typography.prefixFontSize = p.prefixFontSize.isFinite && p.prefixFontSize > 0 ? CGFloat(p.prefixFontSize) : nil
107
+ typography.suffixFontSize = p.suffixFontSize.isFinite && p.suffixFontSize > 0 ? CGFloat(p.suffixFontSize) : nil
108
+ typography.fontWeight = CGFloat(p.textWeight.isFinite ? p.textWeight : 400)
109
+ typography.fontFamily = p.textFamily.isEmpty ? nil : p.textFamily
110
+ typography.letterSpacing = CGFloat(p.textLetterSpacing.isFinite ? p.textLetterSpacing : 0)
111
+ typography.prefixSpacing = p.prefixSpacing.isFinite ? CGFloat(p.prefixSpacing) : nil
112
+ typography.suffixSpacing = p.suffixSpacing.isFinite ? CGFloat(p.suffixSpacing) : nil
113
+ typography.allowFontScaling = p.allowFontScaling
114
+ typography.maxFontSizeMultiplier = CGFloat(max(0, p.maxFontSizeMultiplier.isFinite ? p.maxFontSizeMultiplier : 0))
115
+ return typography
116
+ }
117
+ }
118
+
119
+ extension InputMapping {
120
+ /// The frame's sizing half; the view adds the colours and the stroke width.
121
+ static func sizingFrame(_ p: some InputSizingProps) -> NitroInputView.Frame {
122
+ var frame = NitroInputView.Frame()
123
+ switch p.variant {
124
+ case .outlined: frame.variant = .outlined
125
+ case .filled: frame.variant = .filled
126
+ case .none: frame.variant = .none
127
+ }
128
+ frame.label = p.label
129
+ frame.labelBehavior = p.labelBehavior == .always ? .always : .float
130
+ frame.labelFontSize = p.labelFontSize.isFinite ? max(0, CGFloat(p.labelFontSize)) : 0
131
+ frame.cornerRadius = p.cornerRadius.isFinite ? max(0, CGFloat(p.cornerRadius)) : 8
132
+ return frame
133
+ }
134
+ }
135
+
136
+ // MARK: - Frame
137
+
138
+ /// The room an outlined or filled frame keeps around its text and for its
139
+ /// label. The view lays itself out with these; `InputSizing` adds them to the
140
+ /// size it reports. Mirrors `InputFrame` in InputSizing.kt.
141
+ enum InputFrameMetrics {
142
+ /// The room a framed field keeps above and below its text. Flat, because
143
+ /// nothing about the vertical middle of the box depends on its corners.
144
+ static let framePadding: CGFloat = 16
145
+ /// Material's ratio: the floated label is three quarters of the body size.
146
+ static let floatedLabelRatio: CGFloat = 0.75
147
+ /// A filled field's floated label line, as a multiple of its size. A fudge,
148
+ /// not a Material metric: enough of a gap under the floated label that the
149
+ /// two lines do not crowd at the default sizes.
150
+ static let filledLabelLine: CGFloat = 1.4
151
+
152
+ /// How far in the label - and so the text under it - starts: far enough past
153
+ /// the corner that the notch never opens onto the arc itself.
154
+ static func labelInset(_ frame: NitroInputView.Frame) -> CGFloat { max(16, frame.cornerRadius + 8) }
155
+
156
+ static func sideInset(_ frame: NitroInputView.Frame) -> CGFloat { frame.draws ? labelInset(frame) : 0 }
157
+
158
+ static func floatedLabelSize(_ frame: NitroInputView.Frame, restingSize: CGFloat) -> CGFloat {
159
+ frame.labelFontSize > 0 ? frame.labelFontSize : max(9, restingSize * floatedLabelRatio)
160
+ }
161
+
162
+ /// Room at the top for the floated label - which only the filled variant
163
+ /// needs. Its floated label lives inside the box, on its own line above the
164
+ /// text. An outlined field's sits *on* the stroke, outside the content box.
165
+ static func topInset(_ frame: NitroInputView.Frame, restingSize: CGFloat) -> CGFloat {
166
+ guard frame.hasLabel, frame.variant == .filled else { return 0 }
167
+ return floatedLabelSize(frame, restingSize: restingSize) * filledLabelLine
168
+ }
169
+
170
+ /// The label at rest, in the body font: the widest it gets.
171
+ static func restingLabelWidth(_ frame: NitroInputView.Frame, metrics: InputMetrics) -> CGFloat {
172
+ guard frame.hasLabel else { return 0 }
173
+ return (frame.label as NSString).size(withAttributes: [.font: metrics.body]).width
174
+ }
175
+
176
+ /// A framed field's width: its content, or its label if wider, between the side insets.
177
+ static func width(content: CGFloat, frame: NitroInputView.Frame, metrics: InputMetrics) -> CGFloat {
178
+ guard frame.draws else { return content }
179
+ return 2 * sideInset(frame) + max(content, restingLabelWidth(frame, metrics: metrics))
180
+ }
181
+
182
+ /// A framed single line's height: the line with the frame's padding above
183
+ /// and below it, and a filled field's label line. The line is centred in it,
184
+ /// as it is in any height the caller gives. (A wrapping field adds its own.)
185
+ static func singleLineHeight(_ line: CGFloat, frame: NitroInputView.Frame, metrics: InputMetrics) -> CGFloat {
186
+ guard frame.draws else { return line }
187
+ return line + topInset(frame, restingSize: metrics.body.pointSize) + 2 * framePadding
188
+ }
189
+ }
190
+
191
+ // MARK: - Metrics
192
+
193
+ /// A field's body / prefix / suffix fonts, the letter spacing and seams between
194
+ /// them, and the advance widths of what they draw. `NitroInputView.FontSet`
195
+ /// draws with one; `HybridNitroInputMeasure` measures with its own.
196
+ ///
197
+ /// Not thread-safe (its width cache): one instance per thread. Fonts and
198
+ /// attributed-string measuring are safe off the main thread.
199
+ final class InputMetrics {
200
+ let body: UIFont
201
+ let prefix: UIFont
202
+ let suffix: UIFont
203
+ /// Letter spacing after a body / prefix / suffix glyph, the spacing at the affix seams (nil: the letter spacing) and the affix offsets, scaled with the fonts.
204
+ let bodySpacing: CGFloat
205
+ let prefixLetterSpacing: CGFloat
206
+ let suffixLetterSpacing: CGFloat
207
+ let prefixSeam: CGFloat?
208
+ let suffixSeam: CGFloat?
209
+ let prefixOffset: CGFloat
210
+ let suffixOffset: CGFloat
211
+ /// Height of the line box (the body font's line height).
212
+ let lineHeight: CGFloat
213
+ /// The height a single line asks for: `lineHeight` when the typography sets
214
+ /// one, else the font's own, as on Android (and as `TextInput` sizes itself).
215
+ let lineBoxHeight: CGFloat
216
+ /// The advance of one of the bullets a plain secure field draws (see `init`).
217
+ let secureBulletWidth: CGFloat
218
+ private var widthCache: [WidthKey: CGFloat] = [:]
219
+
220
+ private struct WidthKey: Hashable {
221
+ let text: String
222
+ let role: NitroInputView.GlyphRole
223
+ }
224
+
225
+ init(_ t: NitroInputView.Typography) {
226
+ let scale = NitroInputView.systemFontMultiplier(t)
227
+ body = NitroInputView.makeFont(size: t.fontSize * scale, weight: t.fontWeight, family: t.fontFamily)
228
+ prefix = NitroInputView.makeFont(size: (t.prefixFontSize ?? t.fontSize) * scale, weight: t.fontWeight, family: t.fontFamily)
229
+ suffix = NitroInputView.makeFont(size: (t.suffixFontSize ?? t.fontSize) * scale, weight: t.fontWeight, family: t.fontFamily)
230
+ bodySpacing = t.letterSpacing * scale
231
+ prefixLetterSpacing = t.letterSpacing * scale * (prefix.pointSize / body.pointSize)
232
+ suffixLetterSpacing = t.letterSpacing * scale * (suffix.pointSize / body.pointSize)
233
+ prefixSeam = t.prefixSpacing.map { $0 * scale }
234
+ suffixSeam = t.suffixSpacing.map { $0 * scale }
235
+ prefixOffset = t.prefixOffset * scale
236
+ suffixOffset = t.suffixOffset * scale
237
+ lineHeight = ceil(body.lineHeight)
238
+ lineBoxHeight = t.lineHeight > 0 ? t.lineHeight : lineHeight
239
+ // A plain secure field is drawn by UITextField, which shows every
240
+ // character as U+2219 in the *system* font at the field's size - in the
241
+ // field's weight when that is the system font, regular otherwise - not as
242
+ // the field's own font would draw a bullet. Measured with the caret on the
243
+ // simulator: 8 bullets at 18 pt advance 87 pt whatever the field's font.
244
+ let bulletFont = t.fontFamily == nil
245
+ ? UIFont.systemFont(ofSize: body.pointSize, weight: NitroInputView.uiWeight(t.fontWeight))
246
+ : UIFont.systemFont(ofSize: body.pointSize)
247
+ secureBulletWidth = ("\u{2219}" as NSString).size(withAttributes: [.font: bulletFont]).width
248
+ }
249
+
250
+ func font(for role: NitroInputView.GlyphRole) -> UIFont {
251
+ switch role {
252
+ case .body: return body
253
+ case .prefix: return prefix
254
+ case .suffix: return suffix
255
+ }
256
+ }
257
+
258
+ /// Letter spacing after a glyph of `role`.
259
+ func spacing(for role: NitroInputView.GlyphRole) -> CGFloat {
260
+ switch role {
261
+ case .body: return bodySpacing
262
+ case .prefix: return prefixLetterSpacing
263
+ case .suffix: return suffixLetterSpacing
264
+ }
265
+ }
266
+
267
+ /// Advance width of `text` in the role's font, in points.
268
+ func width(of text: String, role: NitroInputView.GlyphRole) -> CGFloat {
269
+ let key = WidthKey(text: text, role: role)
270
+ if let cached = widthCache[key] { return cached }
271
+ let width = NSAttributedString(string: text, attributes: [.font: font(for: role), .kern: 0]).size().width
272
+ widthCache[key] = width
273
+ return width
274
+ }
275
+
276
+ /// The room an affix takes beside the text: its glyphs, their spacing and the seam.
277
+ func affixRoom(_ affix: String, role: NitroInputView.GlyphRole) -> CGFloat {
278
+ guard !affix.isEmpty else { return 0 }
279
+ let glyphs = affix.unicodeScalars.reduce(CGFloat(0)) { $0 + width(of: String($1), role: role) }
280
+ let count = CGFloat(affix.unicodeScalars.count)
281
+ if role == .prefix { return glyphs + prefixLetterSpacing * (count - 1) + (prefixSeam ?? prefixLetterSpacing) }
282
+ // The field's own kerning already spaces its last glyph by the body spacing.
283
+ return glyphs + suffixLetterSpacing * count + ((suffixSeam ?? bodySpacing) - bodySpacing)
284
+ }
285
+ }
286
+
287
+ // MARK: - Text
288
+
289
+ /// What a field shows for its format: the text conformed to it, the placeholder
290
+ /// and `keepPlaceholder`'s tail. Pure functions of the format and the shared C++
291
+ /// engines, which the view holds for its life and a measure configures afresh.
292
+ enum InputText {
293
+ /// Points the formatter and the mask engine at `format`. `previous` skips
294
+ /// what did not change; nil configures everything.
295
+ fileprivate static func configure(formatter: inout AmountFormatter, maskEngine: inout MaskEngine,
296
+ previous: NitroInputView.Format?, format: NitroInputView.Format) -> Bool {
297
+ if format.mode == .number {
298
+ formatter.setFormat(Int32(max(0, format.fractionDigits)), Int32(max(1, format.maxIntegerDigits)),
299
+ std.string(format.groupingSeparator), std.string(format.decimalSeparator))
300
+ }
301
+ let maskChanged = previous.map {
302
+ format.mask != $0.mask || format.maskNotations != $0.maskNotations
303
+ || format.maskAffinityFormats != $0.maskAffinityFormats
304
+ || format.maskAffinityStrategy != $0.maskAffinityStrategy
305
+ || format.maskTextCase != $0.maskTextCase || format.maskCharacterMap != $0.maskCharacterMap
306
+ || format.maskSlotPlaceholder != $0.maskSlotPlaceholder
307
+ } ?? true
308
+ if format.mode == .mask, maskChanged || previous?.mode != .mask {
309
+ maskEngine.clearNotations()
310
+ for notation in format.maskNotations {
311
+ maskEngine.addNotation(std.string(notation.character), std.string(notation.characterSet),
312
+ notation.isOptional)
313
+ }
314
+ maskEngine.clearAffinityFormats()
315
+ for alternative in format.maskAffinityFormats {
316
+ maskEngine.addAffinityFormat(std.string(alternative))
317
+ }
318
+ maskEngine.setAffinityStrategy(Int32(format.maskAffinityStrategy))
319
+ maskEngine.setTextCase(Int32(format.maskTextCase))
320
+ maskEngine.clearCharacterMap()
321
+ for mapping in format.maskCharacterMap {
322
+ maskEngine.addCharacterMapping(std.string(mapping.from), std.string(mapping.to))
323
+ }
324
+ maskEngine.setSlotPlaceholder(std.string(format.maskSlotPlaceholder))
325
+ // A bad pattern leaves the engine inactive; the field then behaves as
326
+ // plain text rather than refusing every keystroke.
327
+ _ = maskEngine.setFormat(std.string(format.mask))
328
+ }
329
+ return maskChanged
330
+ }
331
+
332
+ /// `raw` as the format holds it: formatted, masked, or cut to `maxLength` code points.
333
+ fileprivate static func normalized(_ raw: String, format: NitroInputView.Format,
334
+ formatter: inout AmountFormatter, maskEngine: inout MaskEngine) -> String {
335
+ switch format.mode {
336
+ case .number:
337
+ return String(formatter.normalize(std.string(raw)).text)
338
+ case .mask:
339
+ let count = Int32(raw.unicodeScalars.count)
340
+ let result = maskEngine.apply(std.string(raw), count, true, format.maskAutocomplete, false)
341
+ return String(result.formattedText)
342
+ case .text:
343
+ return truncated(raw, to: format.maxLength)
344
+ }
345
+ }
346
+
347
+ static func truncated(_ text: String, to maxLength: Int) -> String {
348
+ guard maxLength > 0, text.unicodeScalars.count > maxLength else { return text }
349
+ var view = String.UnicodeScalarView()
350
+ view.append(contentsOf: text.unicodeScalars.prefix(maxLength))
351
+ return String(view)
352
+ }
353
+
354
+ /// `keepPlaceholder` without a `placeholder` shows the mask itself, empty
355
+ /// slots as `maskSlotPlaceholder`: "+1 (___) ___-____".
356
+ fileprivate static func basePlaceholder(format: NitroInputView.Format, maskEngine: inout MaskEngine) -> String {
357
+ if format.placeholder.isEmpty, format.mode == .mask, format.keepPlaceholder, maskEngine.isActive() {
358
+ return String(maskEngine.apply(std.string(""), 0, true, false, false).tailPlaceholder)
359
+ }
360
+ return format.placeholder
361
+ }
362
+
363
+ /// `keepPlaceholder`: what is still to come after the typed text, drawn in
364
+ /// the placeholder colour. The caller's placeholder from where the text ends
365
+ /// - "1234 5" leaves "678 9012" of "1234 5678 9012" - or, without one, the
366
+ /// rest of the mask. The placeholder is written for `mask`, so when one of
367
+ /// `maskAffinityFormats` has taken over (a 4-6-5 Amex under a 4-4-4-4
368
+ /// placeholder) its characters no longer line up, and that format's own
369
+ /// tail is shown instead. A complete text has nothing to come.
370
+ fileprivate static func ghostTail(_ text: String, format: NitroInputView.Format, maskEngine: inout MaskEngine,
371
+ secure: Bool) -> String {
372
+ guard format.mode == .mask, format.keepPlaceholder, !text.isEmpty, !secure,
373
+ maskEngine.isActive() else { return "" }
374
+ let typed = text.unicodeScalars.count
375
+ let result = maskEngine.apply(std.string(text), Int32(typed), true, false, false)
376
+ if result.complete { return "" }
377
+ let placeholder = Array(format.placeholder.unicodeScalars)
378
+ if placeholder.isEmpty || result.formatIndex != 0 { return String(result.tailPlaceholder) }
379
+ guard typed < placeholder.count else { return "" }
380
+ var rest = String.UnicodeScalarView()
381
+ rest.append(contentsOf: placeholder[typed...])
382
+ return String(rest)
383
+ }
384
+
385
+ /// `secureTextEntry` draws a bullet for every code point.
386
+ static func bullets(_ text: String) -> String {
387
+ String(repeating: "\u{2022}", count: text.unicodeScalars.count)
388
+ }
389
+
390
+ /// A leading minus, in either the keyboard's spelling or the typographic one.
391
+ static func isSign(_ scalar: Unicode.Scalar) -> Bool {
392
+ scalar == "-" || scalar.value == 0x2212
393
+ }
394
+ }
395
+
396
+ extension NitroInputView {
397
+ /// The view's engines, configured through `InputText` as a measure's are.
398
+ func configureEngines(previous: Format?) -> Bool {
399
+ InputText.configure(formatter: &formatter, maskEngine: &maskEngine, previous: previous, format: format)
400
+ }
401
+
402
+ func normalizedText(_ raw: String) -> String {
403
+ InputText.normalized(raw, format: format, formatter: &formatter, maskEngine: &maskEngine)
404
+ }
405
+
406
+ var sharedBasePlaceholder: String {
407
+ InputText.basePlaceholder(format: format, maskEngine: &maskEngine)
408
+ }
409
+
410
+ func sharedGhostTail(secure: Bool) -> String {
411
+ InputText.ghostTail(text, format: format, maskEngine: &maskEngine, secure: secure)
412
+ }
413
+ }
414
+
415
+ // MARK: - Glyphs
416
+
417
+ /// The glyphs a reflowing field lays out, in order, with the advance each
418
+ /// takes: the prefix, the text (or the placeholder), `keepPlaceholder`'s tail
419
+ /// and the suffix. The view hands them to the engine; `InputSizing` adds them
420
+ /// up, which is the engine's width at rest.
421
+ enum InputGlyphs {
422
+ /// `shown` is the text or, when `showPlaceholder`, the placeholder; `tail` is
423
+ /// ignored then. Advances carry the letter spacing; the last prefix glyph and
424
+ /// the last body glyph before a suffix carry the seams instead.
425
+ static func walk(_ m: InputMetrics, format: NitroInputView.Format, shown: String, showPlaceholder: Bool, tail: String,
426
+ _ sink: (_ scalar: Unicode.Scalar, _ role: NitroInputView.GlyphRole, _ placeholder: Bool, _ advance: CGFloat) -> Void) {
427
+ // A negative amount reads "-$1,234.56", not "$-1,234.56": the sign belongs
428
+ // to the amount, not to the digits after the symbol. It stays a *body*
429
+ // glyph - it is part of the text, and the caret counts body glyphs in the
430
+ // order they are added - and is only laid out ahead of the prefix.
431
+ var rest = Array(shown.unicodeScalars)
432
+ let sign: Unicode.Scalar? =
433
+ format.signPlacement == .beforeAffix && !showPlaceholder && !format.prefix.isEmpty
434
+ && rest.first.map(InputText.isSign) == true
435
+ ? rest.removeFirst()
436
+ : nil
437
+ if let sign {
438
+ sink(sign, .body, false, m.width(of: String(sign), role: .body) + m.bodySpacing)
439
+ }
440
+ let prefixScalars = Array(format.prefix.unicodeScalars)
441
+ for (i, scalar) in prefixScalars.enumerated() {
442
+ let after = i == prefixScalars.count - 1 ? (m.prefixSeam ?? m.prefixLetterSpacing) : m.prefixLetterSpacing
443
+ sink(scalar, .prefix, false, m.width(of: String(scalar), role: .prefix) + after)
444
+ }
445
+ let hasSuffix = !format.suffix.isEmpty
446
+ for (i, scalar) in rest.enumerated() {
447
+ let after = hasSuffix && i == rest.count - 1 ? (m.suffixSeam ?? m.bodySpacing) : m.bodySpacing
448
+ sink(scalar, .body, showPlaceholder, m.width(of: String(scalar), role: .body) + after)
449
+ }
450
+ // `keepPlaceholder`: the rest of the mask trails the text as placeholder
451
+ // glyphs. They come after every typed glyph, so the caret - which counts
452
+ // body glyphs in order - never lands among them.
453
+ if !showPlaceholder {
454
+ for scalar in tail.unicodeScalars {
455
+ sink(scalar, .body, true, m.width(of: String(scalar), role: .body) + m.bodySpacing)
456
+ }
457
+ }
458
+ for scalar in format.suffix.unicodeScalars {
459
+ sink(scalar, .suffix, false, m.width(of: String(scalar), role: .suffix) + m.suffixLetterSpacing)
460
+ }
461
+ }
462
+ }
463
+
464
+ // MARK: - Size
465
+
466
+ /// The size a single-line field reports through `onSizeChange`.
467
+ enum InputSizing {
468
+ /// A plain field's content width: the text (the placeholder when empty, a
469
+ /// bullet per character when secure, with `keepPlaceholder`'s tail) and the
470
+ /// affixes. The field's own kerning follows every glyph; the affixes take
471
+ /// their room with their seams.
472
+ static func plainWidth(_ m: InputMetrics, format: NitroInputView.Format, text: String, hint: String, tail: String,
473
+ secure: Bool) -> CGFloat {
474
+ let affixes = m.affixRoom(format.prefix, role: .prefix) + m.affixRoom(format.suffix, role: .suffix)
475
+ if secure, !text.isEmpty {
476
+ let count = CGFloat(text.unicodeScalars.count)
477
+ return affixes + (m.secureBulletWidth + m.bodySpacing) * count
478
+ }
479
+ let body = text.isEmpty ? hint : text + tail
480
+ return affixes + m.width(of: body, role: .body) + m.bodySpacing * CGFloat(body.unicodeScalars.count)
481
+ }
482
+
483
+ /// A reflowing field's width at rest: the engine's target, the sum of its glyphs' advances.
484
+ static func reflowWidth(_ m: InputMetrics, format: NitroInputView.Format, text: String, hint: String, tail: String,
485
+ secure: Bool) -> CGFloat {
486
+ let body = secure ? InputText.bullets(text) : text
487
+ let showPlaceholder = body.isEmpty && !hint.isEmpty
488
+ var width: Double = 0
489
+ // The engine clamps every advance at 0 (a negative letter spacing).
490
+ InputGlyphs.walk(m, format: format, shown: showPlaceholder ? hint : body, showPlaceholder: showPlaceholder,
491
+ tail: tail) { _, _, _, advance in width += max(0, Double(advance)) }
492
+ return CGFloat(width)
493
+ }
494
+
495
+ /// Content width and line height to the reported size.
496
+ static func reported(width: CGFloat, height: CGFloat) -> CGSize {
497
+ CGSize(width: ceil(width + 2), height: height)
498
+ }
499
+ }
500
+
501
+ // MARK: - Measure
502
+
503
+ /// Measures a single-line field on the JS thread, before its view exists, with
504
+ /// `InputMetrics`, `InputText` and `InputGlyphs` - the code the view sizes
505
+ /// itself with - so it lays out at its real size in the commit that mounts it.
506
+ ///
507
+ /// Mirrors `HybridNitroInputMeasure` on Android.
508
+ final class HybridNitroInputMeasure: HybridNitroInputMeasureSpec {
509
+ // Reused across calls and reconfigured by each; the lock keeps a second
510
+ // runtime out while one measures.
511
+ private var formatter = AmountFormatter()
512
+ private var maskEngine = MaskEngine()
513
+ private let lock = NSLock()
514
+
515
+ func measure(sizing: NitroInputSizing) throws -> NitroInputSize {
516
+ lock.lock()
517
+ defer { lock.unlock() }
518
+ let format = InputMapping.format(sizing)
519
+ let metrics = InputMetrics(InputMapping.sizingTypography(sizing))
520
+ _ = InputText.configure(formatter: &formatter, maskEngine: &maskEngine, previous: nil, format: format)
521
+ let text = InputText.normalized(sizing.text, format: format, formatter: &formatter, maskEngine: &maskEngine)
522
+ let frame = InputMapping.sizingFrame(sizing)
523
+ // Unfocused, as a field mounts: a label resting inside it hides the placeholder.
524
+ let labelFloats = frame.labelBehavior == .always || !text.isEmpty
525
+ let hint = frame.hasLabel && !labelFloats ? "" : InputText.basePlaceholder(format: format, maskEngine: &maskEngine)
526
+ let tail = InputText.ghostTail(text, format: format, maskEngine: &maskEngine, secure: sizing.secureTextEntry)
527
+ let width = sizing.plain
528
+ ? InputSizing.plainWidth(metrics, format: format, text: text, hint: hint, tail: tail, secure: sizing.secureTextEntry)
529
+ : InputSizing.reflowWidth(metrics, format: format, text: text, hint: hint, tail: tail, secure: sizing.secureTextEntry)
530
+ let size = InputSizing.reported(width: InputFrameMetrics.width(content: width, frame: frame, metrics: metrics),
531
+ height: InputFrameMetrics.singleLineHeight(metrics.lineBoxHeight, frame: frame, metrics: metrics))
532
+ return NitroInputSize(width: Double(size.width), height: Double(size.height))
533
+ }
534
+ }