react-native-nitro-input 0.2.0 → 0.3.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 (164) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +43 -1
  3. package/android/CMakeLists.txt +4 -0
  4. package/android/gradle.properties +1 -1
  5. package/android/src/main/cpp/JRollingEngine.cpp +3 -2
  6. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroInputView.kt +20 -0
  7. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroNumberFormatPlatform.kt +209 -0
  8. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroNumberView.kt +25 -0
  9. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputView.kt +69 -10
  10. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroNumberView.kt +164 -24
  11. package/android/src/main/java/com/margelo/nitro/nitroinput/RollingEngine.kt +2 -1
  12. package/cpp/RollingEngine.cpp +12 -2
  13. package/cpp/RollingEngine.hpp +8 -1
  14. package/cpp/numberformat/HybridNitroNumberFormat.cpp +498 -0
  15. package/cpp/numberformat/HybridNitroNumberFormat.hpp +74 -0
  16. package/cpp/numberformat/HybridNitroNumberFormatFactory.hpp +11 -0
  17. package/cpp/numberformat/NumberFormatCore.cpp +629 -0
  18. package/cpp/numberformat/NumberFormatCore.hpp +154 -0
  19. package/cpp/numberformat/NumberFormatProbe.cpp +354 -0
  20. package/cpp/numberformat/NumberFormatProbe.hpp +63 -0
  21. package/ios/HybridNitroInputView.swift +15 -0
  22. package/ios/HybridNitroNumberFormatPlatform.swift +348 -0
  23. package/ios/HybridNitroNumberView.swift +19 -0
  24. package/ios/NitroInputView.swift +79 -19
  25. package/ios/NitroNumberView.swift +171 -31
  26. package/lib/commonjs/nitrogen/generated/shared/json/NitroInputViewConfig.json +5 -0
  27. package/lib/commonjs/nitrogen/generated/shared/json/NitroNumberViewConfig.json +6 -0
  28. package/lib/commonjs/src/NitroInput.js +8 -6
  29. package/lib/commonjs/src/NitroNumber.js +4 -2
  30. package/lib/commonjs/src/NumberFormat.js +525 -0
  31. package/lib/commonjs/src/formatProps.js +48 -0
  32. package/lib/commonjs/src/index.js +3 -1
  33. package/lib/commonjs/src/specs/NumberFormat.nitro.js +2 -0
  34. package/lib/module/nitrogen/generated/shared/json/NitroInputViewConfig.json +5 -0
  35. package/lib/module/nitrogen/generated/shared/json/NitroNumberViewConfig.json +6 -0
  36. package/lib/module/src/NitroInput.js +8 -6
  37. package/lib/module/src/NitroNumber.js +4 -2
  38. package/lib/module/src/NumberFormat.js +521 -0
  39. package/lib/module/src/formatProps.js +45 -0
  40. package/lib/module/src/index.js +1 -0
  41. package/lib/module/src/specs/NumberFormat.nitro.js +1 -0
  42. package/lib/typescript/src/NitroInput.d.ts +22 -0
  43. package/lib/typescript/src/NitroNumber.d.ts +36 -1
  44. package/lib/typescript/src/NumberFormat.d.ts +47 -0
  45. package/lib/typescript/src/formatProps.d.ts +21 -0
  46. package/lib/typescript/src/index.d.ts +2 -0
  47. package/lib/typescript/src/specs/NitroInput.nitro.d.ts +10 -0
  48. package/lib/typescript/src/specs/NitroNumber.nitro.d.ts +13 -1
  49. package/lib/typescript/src/specs/NumberFormat.nitro.d.ts +139 -0
  50. package/nitro.json +16 -0
  51. package/nitrogen/generated/android/NitroInput+autolinking.cmake +6 -0
  52. package/nitrogen/generated/android/NitroInputOnLoad.cpp +28 -0
  53. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.cpp +45 -0
  54. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.hpp +10 -0
  55. package/nitrogen/generated/android/c++/JHybridNitroNumberFormatPlatformSpec.cpp +118 -0
  56. package/nitrogen/generated/android/c++/JHybridNitroNumberFormatPlatformSpec.hpp +64 -0
  57. package/nitrogen/generated/android/c++/JHybridNitroNumberViewSpec.cpp +54 -0
  58. package/nitrogen/generated/android/c++/JHybridNitroNumberViewSpec.hpp +12 -0
  59. package/nitrogen/generated/android/c++/JHybridNitroPlatformNumberFormatterSpec.cpp +65 -0
  60. package/nitrogen/generated/android/c++/JHybridNitroPlatformNumberFormatterSpec.hpp +64 -0
  61. package/nitrogen/generated/android/c++/JNitroNumberDirection.hpp +3 -0
  62. package/nitrogen/generated/android/c++/JNumberFormatCompactDisplay.hpp +58 -0
  63. package/nitrogen/generated/android/c++/JNumberFormatCurrencyDisplay.hpp +64 -0
  64. package/nitrogen/generated/android/c++/JNumberFormatCurrencySign.hpp +58 -0
  65. package/nitrogen/generated/android/c++/JNumberFormatNotation.hpp +64 -0
  66. package/nitrogen/generated/android/c++/JNumberFormatPlatformOptions.hpp +161 -0
  67. package/nitrogen/generated/android/c++/JNumberFormatPlatformSymbols.hpp +89 -0
  68. package/nitrogen/generated/android/c++/JNumberFormatRoundingMode.hpp +79 -0
  69. package/nitrogen/generated/android/c++/JNumberFormatSignDisplay.hpp +67 -0
  70. package/nitrogen/generated/android/c++/JNumberFormatStyle.hpp +64 -0
  71. package/nitrogen/generated/android/c++/JNumberFormatUnitDisplay.hpp +61 -0
  72. package/nitrogen/generated/android/c++/views/JHybridNitroInputViewStateUpdater.cpp +25 -0
  73. package/nitrogen/generated/android/c++/views/JHybridNitroNumberViewStateUpdater.cpp +30 -0
  74. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroInputViewSpec.kt +30 -0
  75. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroNumberFormatPlatformSpec.kt +60 -0
  76. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroNumberViewSpec.kt +36 -0
  77. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroPlatformNumberFormatterSpec.kt +62 -0
  78. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroNumberDirection.kt +2 -1
  79. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NumberFormatCompactDisplay.kt +23 -0
  80. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NumberFormatCurrencyDisplay.kt +25 -0
  81. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NumberFormatCurrencySign.kt +23 -0
  82. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NumberFormatNotation.kt +25 -0
  83. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NumberFormatPlatformOptions.kt +136 -0
  84. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NumberFormatPlatformSymbols.kt +91 -0
  85. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NumberFormatRoundingMode.kt +30 -0
  86. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NumberFormatSignDisplay.kt +26 -0
  87. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NumberFormatStyle.kt +25 -0
  88. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NumberFormatUnitDisplay.kt +24 -0
  89. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.cpp +34 -0
  90. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.hpp +63 -0
  91. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Umbrella.hpp +40 -0
  92. package/nitrogen/generated/ios/NitroInputAutolinking.mm +18 -0
  93. package/nitrogen/generated/ios/NitroInputAutolinking.swift +12 -0
  94. package/nitrogen/generated/ios/c++/HybridNitroInputViewSpecSwift.hpp +30 -0
  95. package/nitrogen/generated/ios/c++/HybridNitroNumberFormatPlatformSpecSwift.cpp +11 -0
  96. package/nitrogen/generated/ios/c++/HybridNitroNumberFormatPlatformSpecSwift.hpp +122 -0
  97. package/nitrogen/generated/ios/c++/HybridNitroNumberViewSpecSwift.hpp +42 -0
  98. package/nitrogen/generated/ios/c++/HybridNitroPlatformNumberFormatterSpecSwift.cpp +11 -0
  99. package/nitrogen/generated/ios/c++/HybridNitroPlatformNumberFormatterSpecSwift.hpp +94 -0
  100. package/nitrogen/generated/ios/c++/views/HybridNitroInputViewComponent.mm +30 -0
  101. package/nitrogen/generated/ios/c++/views/HybridNitroNumberViewComponent.mm +36 -0
  102. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec.swift +5 -0
  103. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec_cxx.swift +55 -0
  104. package/nitrogen/generated/ios/swift/HybridNitroNumberFormatPlatformSpec.swift +56 -0
  105. package/nitrogen/generated/ios/swift/HybridNitroNumberFormatPlatformSpec_cxx.swift +159 -0
  106. package/nitrogen/generated/ios/swift/HybridNitroNumberViewSpec.swift +6 -0
  107. package/nitrogen/generated/ios/swift/HybridNitroNumberViewSpec_cxx.swift +144 -0
  108. package/nitrogen/generated/ios/swift/HybridNitroPlatformNumberFormatterSpec.swift +56 -0
  109. package/nitrogen/generated/ios/swift/HybridNitroPlatformNumberFormatterSpec_cxx.swift +155 -0
  110. package/nitrogen/generated/ios/swift/NitroNumberDirection.swift +4 -0
  111. package/nitrogen/generated/ios/swift/NumberFormatCompactDisplay.swift +40 -0
  112. package/nitrogen/generated/ios/swift/NumberFormatCurrencyDisplay.swift +48 -0
  113. package/nitrogen/generated/ios/swift/NumberFormatCurrencySign.swift +40 -0
  114. package/nitrogen/generated/ios/swift/NumberFormatNotation.swift +48 -0
  115. package/nitrogen/generated/ios/swift/NumberFormatPlatformOptions.swift +159 -0
  116. package/nitrogen/generated/ios/swift/NumberFormatPlatformSymbols.swift +69 -0
  117. package/nitrogen/generated/ios/swift/NumberFormatRoundingMode.swift +68 -0
  118. package/nitrogen/generated/ios/swift/NumberFormatSignDisplay.swift +52 -0
  119. package/nitrogen/generated/ios/swift/NumberFormatStyle.swift +48 -0
  120. package/nitrogen/generated/ios/swift/NumberFormatUnitDisplay.swift +44 -0
  121. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.cpp +10 -0
  122. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.hpp +10 -0
  123. package/nitrogen/generated/shared/c++/HybridNitroNumberFormatFactorySpec.cpp +22 -0
  124. package/nitrogen/generated/shared/c++/HybridNitroNumberFormatFactorySpec.hpp +70 -0
  125. package/nitrogen/generated/shared/c++/HybridNitroNumberFormatPlatformSpec.cpp +22 -0
  126. package/nitrogen/generated/shared/c++/HybridNitroNumberFormatPlatformSpec.hpp +70 -0
  127. package/nitrogen/generated/shared/c++/HybridNitroNumberFormatSpec.cpp +23 -0
  128. package/nitrogen/generated/shared/c++/HybridNitroNumberFormatSpec.hpp +71 -0
  129. package/nitrogen/generated/shared/c++/HybridNitroNumberViewSpec.cpp +12 -0
  130. package/nitrogen/generated/shared/c++/HybridNitroNumberViewSpec.hpp +12 -0
  131. package/nitrogen/generated/shared/c++/HybridNitroPlatformNumberFormatterSpec.cpp +23 -0
  132. package/nitrogen/generated/shared/c++/HybridNitroPlatformNumberFormatterSpec.hpp +65 -0
  133. package/nitrogen/generated/shared/c++/NitroNumberDirection.hpp +4 -0
  134. package/nitrogen/generated/shared/c++/NumberFormatCompactDisplay.hpp +76 -0
  135. package/nitrogen/generated/shared/c++/NumberFormatCurrencyDisplay.hpp +84 -0
  136. package/nitrogen/generated/shared/c++/NumberFormatCurrencySign.hpp +76 -0
  137. package/nitrogen/generated/shared/c++/NumberFormatGrouping.hpp +80 -0
  138. package/nitrogen/generated/shared/c++/NumberFormatNotation.hpp +84 -0
  139. package/nitrogen/generated/shared/c++/NumberFormatOptions.hpp +193 -0
  140. package/nitrogen/generated/shared/c++/NumberFormatPart.hpp +87 -0
  141. package/nitrogen/generated/shared/c++/NumberFormatPlatformOptions.hpp +176 -0
  142. package/nitrogen/generated/shared/c++/NumberFormatPlatformSymbols.hpp +115 -0
  143. package/nitrogen/generated/shared/c++/NumberFormatRoundingMode.hpp +104 -0
  144. package/nitrogen/generated/shared/c++/NumberFormatRoundingPriority.hpp +80 -0
  145. package/nitrogen/generated/shared/c++/NumberFormatSignDisplay.hpp +88 -0
  146. package/nitrogen/generated/shared/c++/NumberFormatStyle.hpp +84 -0
  147. package/nitrogen/generated/shared/c++/NumberFormatTrailingZeroDisplay.hpp +76 -0
  148. package/nitrogen/generated/shared/c++/NumberFormatUnitDisplay.hpp +80 -0
  149. package/nitrogen/generated/shared/c++/ResolvedNumberFormatOptions.hpp +197 -0
  150. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.cpp +10 -0
  151. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.hpp +15 -0
  152. package/nitrogen/generated/shared/c++/views/HybridNitroNumberViewComponent.cpp +12 -0
  153. package/nitrogen/generated/shared/c++/views/HybridNitroNumberViewComponent.hpp +18 -0
  154. package/nitrogen/generated/shared/json/NitroInputViewConfig.json +5 -0
  155. package/nitrogen/generated/shared/json/NitroNumberViewConfig.json +6 -0
  156. package/package.json +2 -2
  157. package/src/NitroInput.tsx +42 -7
  158. package/src/NitroNumber.tsx +57 -7
  159. package/src/NumberFormat.ts +563 -0
  160. package/src/formatProps.ts +59 -0
  161. package/src/index.ts +18 -0
  162. package/src/specs/NitroInput.nitro.ts +10 -0
  163. package/src/specs/NitroNumber.nitro.ts +13 -1
  164. package/src/specs/NumberFormat.nitro.ts +145 -0
@@ -0,0 +1,348 @@
1
+ //
2
+ // HybridNitroNumberFormatPlatform.swift
3
+ // NitroInput
4
+ //
5
+ // Foundation's `NumberFormatter`, for the C++ `NumberFormat`: C++ learns a
6
+ // locale's format from it once (see NumberFormatProbe) and formats with it
7
+ // only for what C++ does not draw itself (compact and scientific notation,
8
+ // currency names). Hermes' `Intl.NumberFormat` uses the same formatter on
9
+ // iOS, so the two agree.
10
+ //
11
+
12
+ import Foundation
13
+ import NitroModules
14
+
15
+ final class HybridNitroNumberFormatPlatform: HybridNitroNumberFormatPlatformSpec {
16
+ func create(options: NumberFormatPlatformOptions) throws -> any HybridNitroPlatformNumberFormatterSpec {
17
+ return try HybridNitroPlatformNumberFormatter(options: options)
18
+ }
19
+
20
+ func supportedLocalesOf(locales: [String]) throws -> [String] {
21
+ return locales.compactMap { NumberFormatLocales.match($0)?.tag }
22
+ }
23
+ }
24
+
25
+ /// ECMA-402's lookup matcher over the locales Foundation has data for.
26
+ enum NumberFormatLocales {
27
+ private static let available = Set(Locale.availableIdentifiers)
28
+
29
+ struct Match {
30
+ /// The matched locale as a BCP 47 tag, without extensions ("de-DE").
31
+ let tag: String
32
+ /// Foundation's identifier for it ("de_DE").
33
+ let identifier: String
34
+ /// The numbering system asked for with `-u-nu-`, if any.
35
+ let numberingSystem: String?
36
+ }
37
+
38
+ static func match(_ requested: String) -> Match? {
39
+ let lowered = requested.replacingOccurrences(of: "_", with: "-").lowercased()
40
+ // "de-DE-u-nu-latn": the base tag and the numbering system of its Unicode extension.
41
+ var base = lowered
42
+ var numberingSystem: String?
43
+ if let range = lowered.range(of: "-u-") {
44
+ base = String(lowered[..<range.lowerBound])
45
+ let keys = lowered[range.upperBound...].split(separator: "-")
46
+ if let nu = keys.firstIndex(of: "nu"), nu + 1 < keys.endIndex { numberingSystem = String(keys[nu + 1]) }
47
+ }
48
+ // Canonical case: language lower, script title, region upper ("zh-hant-tw" → zh_Hant_TW).
49
+ var subtags = base.split(separator: "-").enumerated().map { index, tag -> String in
50
+ let tag = String(tag)
51
+ if index == 0 { return tag }
52
+ if tag.count == 4 { return tag.prefix(1).uppercased() + tag.dropFirst() }
53
+ if tag.count == 2 || (tag.count == 3 && tag.allSatisfy(\.isNumber)) { return tag.uppercased() }
54
+ return tag
55
+ }
56
+ // Foundation lists some locales with their script only ("zh_Hant_TW" for zh-TW): try the full form too.
57
+ if #available(iOS 16.0, *), subtags.count > 1 {
58
+ let maximal = Locale.Language(identifier: subtags.joined(separator: "-")).maximalIdentifier.replacingOccurrences(of: "-", with: "_")
59
+ if !available.contains(subtags.joined(separator: "_")), available.contains(maximal) {
60
+ return Match(tag: subtags.joined(separator: "-"), identifier: maximal, numberingSystem: numberingSystem)
61
+ }
62
+ }
63
+ while !subtags.isEmpty {
64
+ let identifier = subtags.joined(separator: "_")
65
+ if available.contains(identifier) {
66
+ return Match(tag: subtags.joined(separator: "-"), identifier: identifier, numberingSystem: numberingSystem)
67
+ }
68
+ subtags.removeLast()
69
+ }
70
+ return nil
71
+ }
72
+
73
+ /// The first requested locale Foundation knows, or the device's.
74
+ static func resolve(_ requested: [String]) -> Match {
75
+ for tag in requested {
76
+ if let match = match(tag) { return match }
77
+ }
78
+ let current = Locale.current.identifier
79
+ let base = current.split(separator: "@").first.map(String.init) ?? current
80
+ return Match(tag: base.replacingOccurrences(of: "_", with: "-"), identifier: base, numberingSystem: nil)
81
+ }
82
+ }
83
+
84
+ final class HybridNitroPlatformNumberFormatter: HybridNitroPlatformNumberFormatterSpec {
85
+ private let formatter = NumberFormatter()
86
+ /// Compact notation, which `NumberFormatter` does not have (iOS 16+).
87
+ private var compact: ((Double) -> String)?
88
+ /// Units, through `MeasurementFormatter` with this formatter for the number.
89
+ private var measure: ((Double) -> String)?
90
+ let symbols: NumberFormatPlatformSymbols
91
+
92
+ init(options o: NumberFormatPlatformOptions) throws {
93
+ let match = NumberFormatLocales.resolve(o.locales)
94
+ // Foundation knows numbering systems only in lower case, and one it does not
95
+ // know leaves the formatter without symbols; Intl ignores those, so drop it.
96
+ var numberingSystem = (o.numberingSystem ?? match.numberingSystem)?.lowercased()
97
+ // The currency goes into the locale too: Foundation otherwise takes some
98
+ // patterns (accounting in tr_TR) from the locale's own currency.
99
+ func makeLocale() -> Locale {
100
+ var keywords: [String] = []
101
+ if o.style == .currency, let code = o.currency { keywords.append("currency=\(code)") }
102
+ if let numberingSystem { keywords.append("numbers=\(numberingSystem)") }
103
+ return Locale(identifier: keywords.isEmpty ? match.identifier : "\(match.identifier)@\(keywords.joined(separator: ";"))")
104
+ }
105
+ var locale = makeLocale()
106
+ formatter.locale = locale
107
+ if numberingSystem != nil, (formatter.minusSign as String?) == nil {
108
+ numberingSystem = nil
109
+ locale = makeLocale()
110
+ formatter.locale = locale
111
+ }
112
+
113
+ var currencyShown = ""
114
+ switch o.style {
115
+ case .decimal:
116
+ formatter.numberStyle = .decimal
117
+ case .percent:
118
+ formatter.numberStyle = .percent
119
+ case .currency:
120
+ switch o.currencyDisplay {
121
+ case .code:
122
+ formatter.numberStyle = .currencyISOCode
123
+ case .name:
124
+ formatter.numberStyle = .currencyPlural
125
+ default:
126
+ formatter.numberStyle = o.currencySign == .accounting ? .currencyAccounting : .currency
127
+ }
128
+ formatter.currencyCode = o.currency ?? "USD"
129
+ if o.currencyDisplay == .narrowsymbol, let narrow = Self.narrowSymbol(o.currency ?? "USD", locale: locale) {
130
+ formatter.currencySymbol = narrow
131
+ }
132
+ currencyShown = (o.currencyDisplay == .code ? formatter.internationalCurrencySymbol as String? : formatter.currencySymbol as String?) ?? (o.currency ?? "")
133
+ case .unit:
134
+ formatter.numberStyle = .decimal
135
+ }
136
+
137
+ switch o.notation {
138
+ case .scientific, .engineering:
139
+ formatter.numberStyle = .scientific
140
+ case .compact, .standard:
141
+ break
142
+ }
143
+ formatter.usesGroupingSeparator = o.useGrouping
144
+ formatter.minimumIntegerDigits = Int(o.minimumIntegerDigits)
145
+ if o.minimumSignificantDigits > 0 {
146
+ formatter.usesSignificantDigits = true
147
+ formatter.minimumSignificantDigits = Int(o.minimumSignificantDigits)
148
+ formatter.maximumSignificantDigits = Int(o.maximumSignificantDigits)
149
+ } else {
150
+ formatter.minimumFractionDigits = Int(o.minimumFractionDigits)
151
+ formatter.maximumFractionDigits = Int(o.maximumFractionDigits)
152
+ }
153
+ formatter.roundingMode = Self.roundingMode(o.roundingMode)
154
+ switch o.signDisplay {
155
+ case .always, .exceptzero:
156
+ formatter.positivePrefix = ((formatter.plusSign as String?) ?? "+") + ((formatter.positivePrefix as String?) ?? "")
157
+ case .never:
158
+ formatter.negativePrefix = formatter.positivePrefix
159
+ formatter.negativeSuffix = formatter.positiveSuffix
160
+ case .auto, .negative:
161
+ break
162
+ }
163
+
164
+ if o.notation == .compact, #available(iOS 16.0, *) {
165
+ var style = FloatingPointFormatStyle<Double>(locale: locale)
166
+ .notation(.compactName)
167
+ .grouping(o.useGrouping ? .automatic : .never)
168
+ if o.minimumSignificantDigits > 0 {
169
+ style = style.precision(.significantDigits(Int(o.minimumSignificantDigits)...Int(o.maximumSignificantDigits)))
170
+ } else {
171
+ style = style.precision(.fractionLength(Int(o.minimumFractionDigits)...Int(o.maximumFractionDigits)))
172
+ }
173
+ compact = { style.format($0) }
174
+ }
175
+
176
+ if o.style == .unit, let unit = o.unit {
177
+ measure = try Self.unitFormatter(unit, display: o.unitDisplay, locale: locale, number: formatter)
178
+ }
179
+
180
+ symbols = NumberFormatPlatformSymbols(
181
+ locale: match.tag,
182
+ numberingSystem: Self.numberingSystem(of: locale),
183
+ minusSign: (formatter.minusSign as String?) ?? "-",
184
+ plusSign: (formatter.plusSign as String?) ?? "+",
185
+ percentSign: (formatter.percentSymbol as String?) ?? "%",
186
+ currency: currencyShown,
187
+ nan: (formatter.notANumberSymbol as String?) ?? "NaN",
188
+ infinity: (formatter.positiveInfinitySymbol as String?) ?? "∞",
189
+ exponentSeparator: (formatter.exponentSymbol as String?) ?? "E"
190
+ )
191
+ }
192
+
193
+ func format(value: Double) throws -> String {
194
+ if let measure { return measure(value) }
195
+ if let compact { return compact(value) }
196
+ return formatter.string(from: NSNumber(value: value)) ?? ""
197
+ }
198
+
199
+ func formatDecimal(value: String) throws -> String {
200
+ if value.hasSuffix("Infinity") || value == "NaN" {
201
+ return try format(value: value == "NaN" ? .nan : value.hasPrefix("-") ? -.infinity : .infinity)
202
+ }
203
+ if compact != nil || measure != nil { return try format(value: Double(value) ?? .nan) }
204
+ let number = NSDecimalNumber(string: value, locale: Locale(identifier: "en_US_POSIX"))
205
+ return formatter.string(from: number) ?? ""
206
+ }
207
+
208
+ /// ECMA-402's sanctioned units as Foundation units.
209
+ private static func dimension(_ unit: String) -> Dimension? {
210
+ switch unit {
211
+ case "acre": return UnitArea.acres
212
+ case "hectare": return UnitArea.hectares
213
+ case "bit": return UnitInformationStorage.bits
214
+ case "byte": return UnitInformationStorage.bytes
215
+ case "kilobit": return UnitInformationStorage.kilobits
216
+ case "kilobyte": return UnitInformationStorage.kilobytes
217
+ case "megabit": return UnitInformationStorage.megabits
218
+ case "megabyte": return UnitInformationStorage.megabytes
219
+ case "gigabit": return UnitInformationStorage.gigabits
220
+ case "gigabyte": return UnitInformationStorage.gigabytes
221
+ case "terabit": return UnitInformationStorage.terabits
222
+ case "terabyte": return UnitInformationStorage.terabytes
223
+ case "petabyte": return UnitInformationStorage.petabytes
224
+ case "celsius": return UnitTemperature.celsius
225
+ case "fahrenheit": return UnitTemperature.fahrenheit
226
+ case "centimeter": return UnitLength.centimeters
227
+ case "foot": return UnitLength.feet
228
+ case "inch": return UnitLength.inches
229
+ case "kilometer": return UnitLength.kilometers
230
+ case "meter": return UnitLength.meters
231
+ case "mile": return UnitLength.miles
232
+ case "mile-scandinavian": return UnitLength.scandinavianMiles
233
+ case "millimeter": return UnitLength.millimeters
234
+ case "yard": return UnitLength.yards
235
+ case "degree": return UnitAngle.degrees
236
+ case "fluid-ounce": return UnitVolume.fluidOunces
237
+ case "gallon": return UnitVolume.gallons
238
+ case "liter": return UnitVolume.liters
239
+ case "milliliter": return UnitVolume.milliliters
240
+ case "gram": return UnitMass.grams
241
+ case "kilogram": return UnitMass.kilograms
242
+ case "ounce": return UnitMass.ounces
243
+ case "pound": return UnitMass.pounds
244
+ case "stone": return UnitMass.stones
245
+ case "hour": return UnitDuration.hours
246
+ case "minute": return UnitDuration.minutes
247
+ case "second": return UnitDuration.seconds
248
+ case "millisecond": return UnitDuration.milliseconds
249
+ case "microsecond": return UnitDuration.microseconds
250
+ case "nanosecond": return UnitDuration.nanoseconds
251
+ case "kilometer-per-hour": return UnitSpeed.kilometersPerHour
252
+ case "meter-per-second": return UnitSpeed.metersPerSecond
253
+ case "mile-per-hour": return UnitSpeed.milesPerHour
254
+ case "mile-per-gallon": return UnitFuelEfficiency.milesPerGallon
255
+ case "liter-per-kilometer": return nil
256
+ default: return nil
257
+ }
258
+ }
259
+
260
+ /// A unit formatter: Foundation's for the units it has; days to years and
261
+ /// other compound units through DateComponentsFormatter or "x/y".
262
+ private static func unitFormatter(_ unit: String, display: NumberFormatUnitDisplay, locale: Locale, number: NumberFormatter) throws -> (Double) -> String {
263
+ if unit == "percent" {
264
+ let percent = number.copy() as! NumberFormatter
265
+ percent.numberStyle = .percent
266
+ percent.multiplier = 1
267
+ percent.minimumFractionDigits = number.minimumFractionDigits
268
+ percent.maximumFractionDigits = number.maximumFractionDigits
269
+ return { percent.string(from: NSNumber(value: $0)) ?? "" }
270
+ }
271
+ let formatter = MeasurementFormatter()
272
+ formatter.locale = locale
273
+ formatter.unitOptions = .providedUnit
274
+ formatter.numberFormatter = number
275
+ formatter.unitStyle = display == .long ? .long : display == .narrow ? .short : .medium
276
+ if let dimension = dimension(unit) {
277
+ return { (value: Double) -> String in
278
+ let measurement: Measurement<Dimension> = Measurement(value: value, unit: dimension)
279
+ return formatter.string(from: measurement)
280
+ }
281
+ }
282
+ let durations: [String: NSCalendar.Unit] = ["day": .day, "week": .weekOfMonth, "month": .month, "year": .year]
283
+ if let calendarUnit = durations[unit] {
284
+ let components = DateComponentsFormatter()
285
+ components.allowedUnits = [calendarUnit]
286
+ components.unitsStyle = display == .long ? .full : display == .narrow ? .abbreviated : .short
287
+ var calendar = Calendar(identifier: .gregorian)
288
+ calendar.locale = locale
289
+ components.calendar = calendar
290
+ return { value in
291
+ var parts = DateComponents()
292
+ let whole = Int(value.rounded(.towardZero))
293
+ switch calendarUnit {
294
+ case .day: parts.day = whole
295
+ case .weekOfMonth: parts.weekOfMonth = whole
296
+ case .month: parts.month = whole
297
+ default: parts.year = whole
298
+ }
299
+ return value == value.rounded(.towardZero) ? (components.string(from: parts) ?? "") : "\(number.string(from: NSNumber(value: value)) ?? "") \(unit)"
300
+ }
301
+ }
302
+ if let per = unit.range(of: "-per-") {
303
+ let first = String(unit[..<per.lowerBound])
304
+ let second = String(unit[per.upperBound...])
305
+ // "x-per-y" as "x/y", with Foundation's symbol for y where it has one.
306
+ let head = try unitFormatter(first, display: display, locale: locale, number: number)
307
+ var suffix = second
308
+ if let b = dimension(second) {
309
+ let symbols = MeasurementFormatter()
310
+ symbols.locale = locale
311
+ symbols.unitStyle = .short
312
+ let unitB: Unit = b
313
+ suffix = symbols.string(from: unitB)
314
+ }
315
+ return { (value: Double) -> String in head(value) + "/" + suffix }
316
+ }
317
+ throw RuntimeError.error(withMessage: "NumberFormat: the unit '\(unit)' is not available on iOS.")
318
+ }
319
+
320
+ private static func roundingMode(_ mode: NumberFormatRoundingMode) -> NumberFormatter.RoundingMode {
321
+ switch mode {
322
+ case .ceil: return .ceiling
323
+ case .floor: return .floor
324
+ case .expand: return .up
325
+ case .trunc: return .down
326
+ case .halftrunc: return .halfDown
327
+ case .halfeven: return .halfEven
328
+ case .halfexpand, .halfceil, .halffloor: return .halfUp
329
+ }
330
+ }
331
+
332
+ private static func numberingSystem(of locale: Locale) -> String {
333
+ if #available(iOS 16.0, *) { return locale.numberingSystem.identifier }
334
+ return "latn"
335
+ }
336
+
337
+ /// The currency's narrow symbol ("$" for CA$), read off a formatted zero.
338
+ private static func narrowSymbol(_ code: String, locale: Locale) -> String? {
339
+ guard #available(iOS 16.0, *) else { return nil }
340
+ let text = Decimal(0).formatted(.currency(code: code).locale(locale).presentation(.narrow))
341
+ let symbol = text.unicodeScalars.filter { scalar in
342
+ !CharacterSet.decimalDigits.contains(scalar) && !CharacterSet.whitespaces.contains(scalar) && !CharacterSet.punctuationCharacters.contains(scalar)
343
+ && !(0x200E...0x200F).contains(scalar.value) && scalar.value != 0x061C
344
+ }
345
+ let result = String(String.UnicodeScalarView(symbol))
346
+ return result.isEmpty ? nil : result
347
+ }
348
+ }
@@ -85,6 +85,12 @@ final class HybridNitroNumberView: HybridNitroNumberViewSpec, RecyclableView {
85
85
  var affixAlign: NitroNumberAffixAlign? { didSet { markConfigDirty() } }
86
86
  var prefixAlign: NitroNumberAffixAlign? { didSet { markConfigDirty() } }
87
87
  var suffixAlign: NitroNumberAffixAlign? { didSet { markConfigDirty() } }
88
+ var letterSpacing: Double? { didSet { markConfigDirty() } }
89
+ var prefixSpacing: Double? { didSet { markConfigDirty() } }
90
+ var suffixSpacing: Double? { didSet { markConfigDirty() } }
91
+ var prefixOffset: Double? { didSet { markConfigDirty() } }
92
+ var suffixOffset: Double? { didSet { markConfigDirty() } }
93
+ var tabularNums: Bool? { didSet { markConfigDirty() } }
88
94
  var adjustsFontSizeToFit: Bool? { didSet { markConfigDirty() } }
89
95
  var minimumFontScale: Double? { didSet { markConfigDirty() } }
90
96
  var allowFontScaling: Bool? { didSet { markConfigDirty() } }
@@ -225,6 +231,12 @@ final class HybridNitroNumberView: HybridNitroNumberViewSpec, RecyclableView {
225
231
  affixAlign = nil
226
232
  prefixAlign = nil
227
233
  suffixAlign = nil
234
+ letterSpacing = nil
235
+ prefixSpacing = nil
236
+ suffixSpacing = nil
237
+ prefixOffset = nil
238
+ suffixOffset = nil
239
+ tabularNums = nil
228
240
  adjustsFontSizeToFit = nil
229
241
  minimumFontScale = nil
230
242
  allowFontScaling = nil
@@ -305,6 +317,12 @@ final class HybridNitroNumberView: HybridNitroNumberViewSpec, RecyclableView {
305
317
  let sharedAlign = Self.mapAffixAlign(affixAlign)
306
318
  typography.prefixAlign = prefixAlign.map { Self.mapAffixAlign($0) } ?? sharedAlign
307
319
  typography.suffixAlign = suffixAlign.map { Self.mapAffixAlign($0) } ?? sharedAlign
320
+ typography.letterSpacing = CGFloat((letterSpacing ?? 0).isFinite ? letterSpacing ?? 0 : 0)
321
+ typography.prefixSpacing = prefixSpacing.flatMap { $0.isFinite ? CGFloat($0) : nil }
322
+ typography.suffixSpacing = suffixSpacing.flatMap { $0.isFinite ? CGFloat($0) : nil }
323
+ typography.prefixOffset = CGFloat((prefixOffset ?? 0).isFinite ? prefixOffset ?? 0 : 0)
324
+ typography.suffixOffset = CGFloat((suffixOffset ?? 0).isFinite ? suffixOffset ?? 0 : 0)
325
+ typography.tabularNums = tabularNums ?? true
308
326
  typography.adjustsFontSizeToFit = adjustsFontSizeToFit ?? false
309
327
  typography.minimumFontScale = CGFloat(min(1, max(0.05, minimumFontScale ?? 0.5)))
310
328
  typography.allowFontScaling = allowFontScaling ?? false
@@ -411,6 +429,7 @@ final class HybridNitroNumberView: HybridNitroNumberViewSpec, RecyclableView {
411
429
  case .auto: return .auto
412
430
  case .up: return .up
413
431
  case .down: return .down
432
+ case .shortest: return .shortest
414
433
  default: return .auto
415
434
  }
416
435
  }
@@ -118,6 +118,14 @@ final class NitroInputView: UIView {
118
118
  var placeholderColor: UIColor = .placeholderText
119
119
  var prefixAlign: AffixAlign = .baseline
120
120
  var suffixAlign: AffixAlign = .baseline
121
+ /// Points added after every glyph, as `Text`'s letterSpacing; an affix gets it in proportion to its size.
122
+ var letterSpacing: CGFloat = 0
123
+ /// Points between the prefix and the text, and between the text and the suffix, in place of the letter spacing there.
124
+ var prefixSpacing: CGFloat? = nil
125
+ var suffixSpacing: CGFloat? = nil
126
+ /// Points an affix is moved down (negative: up) after its alignment.
127
+ var prefixOffset: CGFloat = 0
128
+ var suffixOffset: CGFloat = 0
121
129
  var adjustsFontSizeToFit: Bool = false
122
130
  var minimumFontScale: CGFloat = 0.5
123
131
  var allowFontScaling: Bool = false
@@ -337,6 +345,14 @@ final class NitroInputView: UIView {
337
345
  let placeholderColor: UIColor
338
346
  let prefixAlign: AffixAlign
339
347
  let suffixAlign: AffixAlign
348
+ /// 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.
349
+ let bodySpacing: CGFloat
350
+ let prefixLetterSpacing: CGFloat
351
+ let suffixLetterSpacing: CGFloat
352
+ let prefixSeam: CGFloat?
353
+ let suffixSeam: CGFloat?
354
+ let prefixOffset: CGFloat
355
+ let suffixOffset: CGFloat
340
356
  /// Height of the line box (the body font's line height).
341
357
  let lineHeight: CGFloat
342
358
  /// Pixel density the glyph images are rendered at.
@@ -396,9 +412,35 @@ final class NitroInputView: UIView {
396
412
  placeholderColor = t.placeholderColor.resolvedColor(with: traits)
397
413
  prefixAlign = t.prefixAlign
398
414
  suffixAlign = t.suffixAlign
415
+ bodySpacing = t.letterSpacing * scale
416
+ prefixLetterSpacing = t.letterSpacing * scale * (prefix.pointSize / body.pointSize)
417
+ suffixLetterSpacing = t.letterSpacing * scale * (suffix.pointSize / body.pointSize)
418
+ prefixSeam = t.prefixSpacing.map { $0 * scale }
419
+ suffixSeam = t.suffixSpacing.map { $0 * scale }
420
+ prefixOffset = t.prefixOffset * scale
421
+ suffixOffset = t.suffixOffset * scale
399
422
  lineHeight = ceil(body.lineHeight)
400
423
  }
401
424
 
425
+ /// Letter spacing after a glyph of `role`.
426
+ func spacing(for role: GlyphRole) -> CGFloat {
427
+ switch role {
428
+ case .body: return bodySpacing
429
+ case .prefix: return prefixLetterSpacing
430
+ case .suffix: return suffixLetterSpacing
431
+ }
432
+ }
433
+
434
+ /// The room an affix takes beside the text: its glyphs, their spacing and the seam.
435
+ func affixRoom(_ affix: String, role: GlyphRole) -> CGFloat {
436
+ guard !affix.isEmpty else { return 0 }
437
+ let glyphs = affix.unicodeScalars.reduce(CGFloat(0)) { $0 + width(of: String($1), role: role) }
438
+ let count = CGFloat(affix.unicodeScalars.count)
439
+ if role == .prefix { return glyphs + prefixLetterSpacing * (count - 1) + (prefixSeam ?? prefixLetterSpacing) }
440
+ // The field's own kerning already spaces its last glyph by the body spacing.
441
+ return glyphs + suffixLetterSpacing * count + ((suffixSeam ?? bodySpacing) - bodySpacing)
442
+ }
443
+
402
444
  func font(for role: GlyphRole) -> UIFont {
403
445
  switch role {
404
446
  case .body: return body
@@ -461,6 +503,10 @@ final class NitroInputView: UIView {
461
503
  /// Top of the glyph's line box for `role` drawing `text`, given the top of the body line box.
462
504
  func top(for role: GlyphRole, text: String, lineTop: CGFloat) -> CGFloat {
463
505
  guard role != .body else { return lineTop }
506
+ return alignedTop(for: role, text: text, lineTop: lineTop) + (role == .prefix ? prefixOffset : suffixOffset)
507
+ }
508
+
509
+ private func alignedTop(for role: GlyphRole, text: String, lineTop: CGFloat) -> CGFloat {
464
510
  let f = font(for: role)
465
511
  switch role == .prefix ? prefixAlign : suffixAlign {
466
512
  case .baseline:
@@ -1000,7 +1046,8 @@ final class NitroInputView: UIView {
1000
1046
  private func applyFonts() {
1001
1047
  field.font = fonts.body
1002
1048
  var attributes = field.defaultTextAttributes
1003
- attributes[.kern] = 0
1049
+ // The hidden field spaces its glyphs like the overlay, so the caret and the selection line up with them.
1050
+ attributes[.kern] = fonts.bodySpacing
1004
1051
  attributes[.font] = fonts.body
1005
1052
  attributes[.foregroundColor] = traits.plain ? typography.color : UIColor.clear
1006
1053
  field.defaultTextAttributes = attributes
@@ -1036,8 +1083,8 @@ final class NitroInputView: UIView {
1036
1083
  field.rightView = nil
1037
1084
  field.leftViewMode = .never
1038
1085
  field.rightViewMode = .never
1039
- let prefixRoom = affixWidth(format.prefix, role: .prefix)
1040
- let suffixRoom = affixWidth(format.suffix, role: .suffix)
1086
+ let prefixRoom = fonts.affixRoom(format.prefix, role: .prefix)
1087
+ let suffixRoom = fonts.affixRoom(format.suffix, role: .suffix)
1041
1088
  field.leftInset = side + (rtl ? suffixRoom : prefixRoom)
1042
1089
  field.rightInset = side + (rtl ? prefixRoom : suffixRoom)
1043
1090
  }
@@ -1047,17 +1094,22 @@ final class NitroInputView: UIView {
1047
1094
  private func affixLabel(_ affix: String, role: GlyphRole, reusing existing: UILabel?) -> UILabel? {
1048
1095
  guard !affix.isEmpty else { return nil }
1049
1096
  let label = existing ?? UILabel()
1050
- label.font = fonts.font(for: role)
1051
- label.textColor = typography.color
1052
- if label.text != affix { label.text = affix }
1097
+ let text = NSAttributedString(string: affix, attributes: [
1098
+ .font: fonts.font(for: role),
1099
+ .foregroundColor: typography.color,
1100
+ .kern: fonts.spacing(for: role),
1101
+ ])
1102
+ if label.attributedText != text { label.attributedText = text }
1053
1103
  label.sizeToFit()
1104
+ // The seam against the text: after a prefix, before a suffix (the label hugs the text's side).
1105
+ let room = fonts.affixRoom(affix, role: role)
1106
+ label.frame.size.width = room
1107
+ label.textAlignment = role == .prefix ? .left : .right
1108
+ let offset = role == .prefix ? fonts.prefixOffset : fonts.suffixOffset
1109
+ label.transform = offset == 0 ? .identity : CGAffineTransform(translationX: 0, y: offset)
1054
1110
  return label
1055
1111
  }
1056
1112
 
1057
- private func affixWidth(_ affix: String, role: GlyphRole) -> CGFloat {
1058
- affix.unicodeScalars.reduce(CGFloat(0)) { $0 + fonts.width(of: String($1), role: role) }
1059
- }
1060
-
1061
1113
  /// Swaps which backing view is showing, and mirrors onto the text view the
1062
1114
  /// settings that matter to it. Everything the single-line path does is left
1063
1115
  /// alone: a field that never sets `multiline` never builds the text view and
@@ -1371,19 +1423,26 @@ final class NitroInputView: UIView {
1371
1423
  && rest.first.map(Self.isSign) == true
1372
1424
  ? rest.removeFirst()
1373
1425
  : nil
1426
+ // Advances carry the letter spacing; the last prefix glyph and the last
1427
+ // body glyph before a suffix carry the seams instead.
1428
+ let fonts = self.fonts
1374
1429
  if let sign {
1375
1430
  let kind = numberKinds ? formatter.kindOf(sign.value) : Kind.text
1376
- engine.addGlyph(sign.value, Role.body, kind, Double(fonts.width(of: String(sign), role: .body)), false)
1431
+ engine.addGlyph(sign.value, Role.body, kind, Double(fonts.width(of: String(sign), role: .body) + fonts.bodySpacing), false)
1377
1432
  }
1378
- for scalar in format.prefix.unicodeScalars {
1379
- engine.addGlyph(scalar.value, Role.prefix, Kind.text, Double(fonts.width(of: String(scalar), role: .prefix)), false)
1433
+ let prefixScalars = Array(format.prefix.unicodeScalars)
1434
+ for (i, scalar) in prefixScalars.enumerated() {
1435
+ let after = i == prefixScalars.count - 1 ? (fonts.prefixSeam ?? fonts.prefixLetterSpacing) : fonts.prefixLetterSpacing
1436
+ engine.addGlyph(scalar.value, Role.prefix, Kind.text, Double(fonts.width(of: String(scalar), role: .prefix) + after), false)
1380
1437
  }
1381
- for scalar in rest {
1438
+ let hasSuffix = !format.suffix.isEmpty
1439
+ for (i, scalar) in rest.enumerated() {
1382
1440
  let kind = numberKinds ? formatter.kindOf(scalar.value) : Kind.text
1383
- engine.addGlyph(scalar.value, Role.body, kind, Double(fonts.width(of: String(scalar), role: .body)), showPlaceholder)
1441
+ let after = hasSuffix && i == rest.count - 1 ? (fonts.suffixSeam ?? fonts.bodySpacing) : fonts.bodySpacing
1442
+ engine.addGlyph(scalar.value, Role.body, kind, Double(fonts.width(of: String(scalar), role: .body) + after), showPlaceholder)
1384
1443
  }
1385
1444
  for scalar in format.suffix.unicodeScalars {
1386
- engine.addGlyph(scalar.value, Role.suffix, Kind.text, Double(fonts.width(of: String(scalar), role: .suffix)), false)
1445
+ engine.addGlyph(scalar.value, Role.suffix, Kind.text, Double(fonts.width(of: String(scalar), role: .suffix) + fonts.suffixLetterSpacing), false)
1387
1446
  }
1388
1447
  engine.commitText(Int32(caret), CACurrentMediaTime())
1389
1448
  reportIntrinsicSize()
@@ -1571,9 +1630,10 @@ final class NitroInputView: UIView {
1571
1630
  let body = text.isEmpty
1572
1631
  ? effectivePlaceholder
1573
1632
  : traits.secureTextEntry ? String(repeating: "\u{2022}", count: text.unicodeScalars.count) : text
1574
- return fonts.width(of: format.prefix, role: .prefix)
1575
- + fonts.width(of: body, role: .body)
1576
- + fonts.width(of: format.suffix, role: .suffix)
1633
+ // The field's own kerning follows every glyph; the affixes take their room with their seams.
1634
+ return fonts.affixRoom(format.prefix, role: .prefix)
1635
+ + fonts.width(of: body, role: .body) + fonts.bodySpacing * CGFloat(body.unicodeScalars.count)
1636
+ + fonts.affixRoom(format.suffix, role: .suffix)
1577
1637
  }
1578
1638
 
1579
1639
  private func reportIntrinsicSize() {