react-native-nitro-input 0.3.8 → 0.4.1

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