react-native-nitro-input 0.1.0 → 0.2.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 (116) hide show
  1. package/CHANGELOG.md +305 -3
  2. package/NitroInput.podspec +4 -4
  3. package/README.md +378 -53
  4. package/android/CMakeLists.txt +5 -3
  5. package/android/src/main/cpp/JOutlineGeometry.hpp +1 -1
  6. package/android/src/main/cpp/JReflowEngine.cpp +132 -0
  7. package/android/src/main/cpp/{JMorphEngine.hpp → JReflowEngine.hpp} +7 -7
  8. package/android/src/main/cpp/JRollingEngine.cpp +222 -0
  9. package/android/src/main/cpp/JRollingEngine.hpp +68 -0
  10. package/android/src/main/cpp/cpp-adapter.cpp +4 -2
  11. package/android/src/main/java/com/margelo/nitro/nitroinput/AmountFormatter.kt +1 -1
  12. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroInputView.kt +1 -1
  13. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroNumberView.kt +471 -0
  14. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputPackage.kt +2 -1
  15. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputView.kt +38 -16
  16. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroNumberView.kt +1741 -0
  17. package/android/src/main/java/com/margelo/nitro/nitroinput/{MorphEngine.kt → ReflowEngine.kt} +2 -2
  18. package/android/src/main/java/com/margelo/nitro/nitroinput/RollingEngine.kt +59 -0
  19. package/cpp/AmountFormatter.cpp +5 -0
  20. package/cpp/AmountFormatter.hpp +10 -2
  21. package/cpp/{MorphEngine.cpp → ReflowEngine.cpp} +52 -47
  22. package/cpp/{MorphEngine.hpp → ReflowEngine.hpp} +12 -4
  23. package/cpp/RollingEngine.cpp +1224 -0
  24. package/cpp/RollingEngine.hpp +468 -0
  25. package/cpp/SwiftNonCopyable.hpp +22 -0
  26. package/cpp/worklets/NitroInputWorkletsBridge.cpp +3 -3
  27. package/cpp/worklets/NitroInputWorkletsBridge.hpp +1 -1
  28. package/ios/{HybridMorphInputView.swift → HybridNitroInputView.swift} +1 -1
  29. package/ios/HybridNitroNumberView.swift +439 -0
  30. package/ios/NitroInputView.swift +69 -45
  31. package/ios/NitroNumberView.swift +1934 -0
  32. package/lib/commonjs/nitrogen/generated/shared/json/NitroNumberViewConfig.json +55 -0
  33. package/lib/commonjs/src/NitroInput.js +21 -52
  34. package/lib/commonjs/src/NitroNumber.js +139 -0
  35. package/lib/commonjs/src/index.js +4 -3
  36. package/lib/commonjs/src/specs/NitroNumber.nitro.js +2 -0
  37. package/lib/commonjs/src/styleHelpers.js +36 -0
  38. package/lib/module/nitrogen/generated/shared/json/NitroNumberViewConfig.json +55 -0
  39. package/lib/module/src/NitroInput.js +12 -43
  40. package/lib/module/src/NitroNumber.js +100 -0
  41. package/lib/module/src/index.js +1 -1
  42. package/lib/module/src/specs/NitroNumber.nitro.js +1 -0
  43. package/lib/module/src/styleHelpers.js +32 -0
  44. package/lib/typescript/src/NitroInput.d.ts +28 -21
  45. package/lib/typescript/src/NitroNumber.d.ts +211 -0
  46. package/lib/typescript/src/index.d.ts +3 -2
  47. package/lib/typescript/src/specs/NitroInput.nitro.d.ts +9 -9
  48. package/lib/typescript/src/specs/NitroNumber.nitro.d.ts +238 -0
  49. package/lib/typescript/src/styleHelpers.d.ts +3 -0
  50. package/nitro.json +10 -0
  51. package/nitrogen/generated/android/NitroInput+autolinking.cmake +4 -0
  52. package/nitrogen/generated/android/NitroInputOnLoad.cpp +20 -0
  53. package/nitrogen/generated/android/c++/JFunc_void.hpp +75 -0
  54. package/nitrogen/generated/android/c++/JFunc_void_double_double.hpp +10 -10
  55. package/nitrogen/generated/android/c++/JHybridNitroNumberViewSpec.cpp +536 -0
  56. package/nitrogen/generated/android/c++/JHybridNitroNumberViewSpec.hpp +156 -0
  57. package/nitrogen/generated/android/c++/JNitroNumberAffixAlign.hpp +64 -0
  58. package/nitrogen/generated/android/c++/JNitroNumberDirection.hpp +61 -0
  59. package/nitrogen/generated/android/c++/JNitroNumberEasing.hpp +67 -0
  60. package/nitrogen/generated/android/c++/JNitroNumberRevealStyle.hpp +58 -0
  61. package/nitrogen/generated/android/c++/JNitroNumberTextAlign.hpp +64 -0
  62. package/nitrogen/generated/android/c++/JNitroNumberTransition.hpp +61 -0
  63. package/nitrogen/generated/android/c++/views/JHybridNitroNumberViewStateUpdater.cpp +299 -0
  64. package/nitrogen/generated/android/c++/views/JHybridNitroNumberViewStateUpdater.hpp +54 -0
  65. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/Func_void.kt +78 -0
  66. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/Func_void_double_double.kt +9 -9
  67. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroNumberViewSpec.kt +363 -0
  68. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroNumberAffixAlign.kt +25 -0
  69. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroNumberDirection.kt +24 -0
  70. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroNumberEasing.kt +26 -0
  71. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroNumberRevealStyle.kt +23 -0
  72. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroNumberTextAlign.kt +25 -0
  73. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroNumberTransition.kt +24 -0
  74. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/views/HybridNitroNumberViewManager.kt +96 -0
  75. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/views/HybridNitroNumberViewStateUpdater.kt +23 -0
  76. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.cpp +25 -0
  77. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.hpp +248 -0
  78. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Umbrella.hpp +23 -0
  79. package/nitrogen/generated/ios/NitroInputAutolinking.mm +8 -0
  80. package/nitrogen/generated/ios/NitroInputAutolinking.swift +12 -0
  81. package/nitrogen/generated/ios/c++/HybridNitroNumberViewSpecSwift.cpp +11 -0
  82. package/nitrogen/generated/ios/c++/HybridNitroNumberViewSpecSwift.hpp +432 -0
  83. package/nitrogen/generated/ios/c++/views/HybridNitroNumberViewComponent.mm +414 -0
  84. package/nitrogen/generated/ios/swift/Func_void.swift +46 -0
  85. package/nitrogen/generated/ios/swift/Func_void_double_double.swift +5 -5
  86. package/nitrogen/generated/ios/swift/HybridNitroNumberViewSpec.swift +102 -0
  87. package/nitrogen/generated/ios/swift/HybridNitroNumberViewSpec_cxx.swift +1243 -0
  88. package/nitrogen/generated/ios/swift/NitroNumberAffixAlign.swift +48 -0
  89. package/nitrogen/generated/ios/swift/NitroNumberDirection.swift +44 -0
  90. package/nitrogen/generated/ios/swift/NitroNumberEasing.swift +52 -0
  91. package/nitrogen/generated/ios/swift/NitroNumberRevealStyle.swift +40 -0
  92. package/nitrogen/generated/ios/swift/NitroNumberTextAlign.swift +48 -0
  93. package/nitrogen/generated/ios/swift/NitroNumberTransition.swift +44 -0
  94. package/nitrogen/generated/shared/c++/HybridNitroNumberViewSpec.cpp +115 -0
  95. package/nitrogen/generated/shared/c++/HybridNitroNumberViewSpec.hpp +175 -0
  96. package/nitrogen/generated/shared/c++/NitroNumberAffixAlign.hpp +84 -0
  97. package/nitrogen/generated/shared/c++/NitroNumberDirection.hpp +80 -0
  98. package/nitrogen/generated/shared/c++/NitroNumberEasing.hpp +88 -0
  99. package/nitrogen/generated/shared/c++/NitroNumberRevealStyle.hpp +76 -0
  100. package/nitrogen/generated/shared/c++/NitroNumberTextAlign.hpp +84 -0
  101. package/nitrogen/generated/shared/c++/NitroNumberTransition.hpp +80 -0
  102. package/nitrogen/generated/shared/c++/views/HybridNitroNumberViewComponent.cpp +124 -0
  103. package/nitrogen/generated/shared/c++/views/HybridNitroNumberViewComponent.hpp +227 -0
  104. package/nitrogen/generated/shared/json/NitroNumberViewConfig.json +55 -0
  105. package/package.json +15 -7
  106. package/src/NitroInput.tsx +37 -60
  107. package/src/NitroNumber.tsx +481 -0
  108. package/src/index.ts +20 -6
  109. package/src/specs/NitroInput.nitro.ts +9 -9
  110. package/src/specs/NitroNumber.nitro.ts +259 -0
  111. package/src/styleHelpers.ts +32 -0
  112. package/android/src/main/cpp/JMorphEngine.cpp +0 -132
  113. package/lib/commonjs/src/MorphInput.js +0 -42
  114. package/lib/module/src/MorphInput.js +0 -6
  115. package/lib/typescript/src/MorphInput.d.ts +0 -18
  116. package/src/MorphInput.tsx +0 -30
@@ -0,0 +1,1934 @@
1
+ //
2
+ // NitroNumberView.swift
3
+ // NitroInput
4
+ //
5
+ // Draws a NitroNumber. All behaviour (wheel positions, rolls, stagger,
6
+ // easing, loading fade, shimmer phase) lives in the shared C++ `RollingEngine`
7
+ // (cpp/RollingEngine.hpp); this view owns fonts, layout, fit-to-width and
8
+ // rendering, and drives the engine from a display link.
9
+ //
10
+ // Rendering has two modes:
11
+ // - Layers (default): every glyph and wheel is a CALayer whose contents is a
12
+ // pre-rasterized image (a wheel is a clipped strip of the digits 0–9); a
13
+ // frame only moves layers, so the render server composites the roll and
14
+ // the main thread never redraws a bitmap. Profiling 24 rolling views showed
15
+ // two thirds of the main thread inside Core Animation's backing-store work
16
+ // for `draw(_:)` views, which this avoids entirely.
17
+ // - Bitmap (`draw(_:)`): used only while the loading glint is visible, because
18
+ // the source-atop sweep needs a Core Graphics transparency layer.
19
+ //
20
+
21
+ import Accelerate
22
+ import CoreText
23
+ import UIKit
24
+
25
+ final class NitroNumberView: UIView {
26
+
27
+ private typealias Engine = margelo.nitro.nitroinput.RollingEngine
28
+
29
+ // MARK: - Configuration
30
+
31
+ struct Format: Equatable {
32
+ var fractionDigits: Int = 0
33
+ var minimumIntegerDigits: Int = 1
34
+ var groupingSeparator: String = ""
35
+ var decimalSeparator: String = "."
36
+ var prefix: String = ""
37
+ var suffix: String = ""
38
+ }
39
+
40
+ enum AffixAlign {
41
+ case baseline, center, top, bottom
42
+ }
43
+
44
+ struct Typography: Equatable {
45
+ var fontSize: CGFloat = 32
46
+ var prefixFontSize: CGFloat? = nil
47
+ var suffixFontSize: CGFloat? = nil
48
+ var fontWeight: CGFloat = 400
49
+ var fontFamily: String? = nil
50
+ var color: UIColor = .label
51
+ var prefixAlign: AffixAlign = .baseline
52
+ var suffixAlign: AffixAlign = .baseline
53
+ var adjustsFontSizeToFit: Bool = false
54
+ var minimumFontScale: CGFloat = 0.5
55
+ var allowFontScaling: Bool = false
56
+ var maxFontSizeMultiplier: CGFloat = 0
57
+ }
58
+
59
+ enum Easing: Int32 {
60
+ case linear = 0, easeIn = 1, easeOut = 2, easeInOut = 3, spring = 4
61
+ }
62
+
63
+ enum Direction: Int32 {
64
+ case auto = 0, up = 1, down = 2
65
+ }
66
+
67
+ struct Timing: Equatable {
68
+ /// The odometer roll, or one of the glyph-swap transitions.
69
+ var transition: Transition = .roll
70
+ /// A punch of the whole figure on every change, peak overshoot 0 (none) to 1.
71
+ var popOnChange: Double = 0
72
+ var duration: TimeInterval = 0.5
73
+ var easing: Easing = .easeInOut
74
+ var bounce: Double = 0.15
75
+ /// Delay between the start of each wheel's roll, least significant first.
76
+ var stagger: TimeInterval = 0
77
+ var direction: Direction = .auto
78
+ /// Length of a jackpot reveal (the count, or until the last reel locks).
79
+ var revealDuration: TimeInterval = 2.2
80
+ /// Peak overshoot of the reveal's landing pop (0 = none).
81
+ var revealBounce: Double = 0.12
82
+ /// Count style: how much smaller the figure opens, growing to full size over the count.
83
+ var revealGrow: Double = 0.2
84
+ /// The reveal's presentation.
85
+ var revealStyle: RevealStyle = .count
86
+ /// Spin style: delay between reel stops, from the left.
87
+ var revealStagger: TimeInterval = 0.2
88
+ /// Count style: how long the count pauses on each milestone.
89
+ var revealMilestoneHold: TimeInterval = 0
90
+ }
91
+
92
+ enum RevealStyle: Int32 {
93
+ case count = 0, spin = 1
94
+ }
95
+
96
+ enum Transition: Int32 {
97
+ case roll = 0, numeric = 1, scramble = 2
98
+ }
99
+
100
+ /// The change flash: the colours a changed digit lights up in (nil = off) and how long the light lasts.
101
+ struct Flash: Equatable {
102
+ var upColor: UIColor?
103
+ var downColor: UIColor?
104
+ var duration: TimeInterval = 0.6
105
+ }
106
+
107
+ struct Shimmer: Equatable {
108
+ /// Color of the glint's core; `nil` uses a light neutral (dark neutral in dark mode).
109
+ var color: UIColor? = nil
110
+ /// Duration of one sweep across the number.
111
+ var duration: TimeInterval = 0.95
112
+ }
113
+
114
+ enum Alignment {
115
+ /// The start edge of the layout direction: left in a left-to-right app,
116
+ /// right in a right-to-left one. What `Text` does with no `textAlign`.
117
+ case auto
118
+ /// Absolute, whatever the layout direction.
119
+ case left, center, right
120
+ }
121
+
122
+ var format = Format() {
123
+ didSet {
124
+ guard format != oldValue else { return }
125
+ // A prefix, suffix or separator that changes while a value is shown
126
+ // swaps like a digit (`Engine.changeText`): keep the text that leaves.
127
+ if engine.hasShownValue() {
128
+ let rtl = isRTL
129
+ func prefixInk(_ text: String) -> String { rtl ? Self.splitAffix(text, spaceAtEnd: true).ink : text }
130
+ func suffixInk(_ text: String) -> String { rtl ? Self.splitAffix(text, spaceAtEnd: false).ink : text }
131
+ let now = CACurrentMediaTime()
132
+ func change(_ slot: Int, _ from: String, _ to: String) {
133
+ guard from != to else { return }
134
+ leavingText[slot] = from
135
+ engine.changeText(Int32(slot), now)
136
+ }
137
+ change(Self.prefixText, prefixInk(oldValue.prefix), prefixInk(format.prefix))
138
+ change(Self.suffixText, suffixInk(oldValue.suffix), suffixInk(format.suffix))
139
+ change(Self.groupingText, oldValue.groupingSeparator, format.groupingSeparator)
140
+ change(Self.decimalText, oldValue.decimalSeparator, format.decimalSeparator)
141
+ }
142
+ // Played in a glyph-swap transition; snaps otherwise (see the engine).
143
+ engine.changeFormat(Int32(format.fractionDigits), Int32(format.minimumIntegerDigits), CACurrentMediaTime())
144
+ if engine.hasShownValue() {
145
+ reportIntrinsicSize()
146
+ }
147
+ updateDisplayLinkNeed()
148
+ render()
149
+ }
150
+ }
151
+
152
+ // `Engine.TextSlot`, and the text each slot is swapping away from.
153
+ static let prefixText = 0
154
+ static let suffixText = 1
155
+ static let groupingText = 2
156
+ static let decimalText = 3
157
+ private var leavingText: [String?] = [nil, nil, nil, nil]
158
+
159
+ var typography = Typography() {
160
+ didSet {
161
+ guard typography != oldValue else { return }
162
+ rebuildFonts()
163
+ }
164
+ }
165
+
166
+ var timing = Timing() {
167
+ didSet {
168
+ engine.setTiming(timing.duration, timing.easing.rawValue, timing.bounce, timing.stagger, timing.direction.rawValue)
169
+ engine.setTransition(timing.transition.rawValue)
170
+ if timing.transition != oldValue.transition { warmSwapImages() }
171
+ engine.setPopOnChange(timing.popOnChange)
172
+ engine.setRevealTiming(timing.revealDuration, timing.revealBounce, timing.revealStyle.rawValue, timing.revealStagger)
173
+ engine.setRevealGrow(timing.revealGrow)
174
+ engine.setRevealMilestoneHold(timing.revealMilestoneHold)
175
+ }
176
+ }
177
+
178
+ /// Win tiers of a count-style reveal, in the figure's units.
179
+ var revealMilestones: [Double] = [] {
180
+ didSet {
181
+ guard revealMilestones != oldValue else { return }
182
+ engine.clearRevealMilestones()
183
+ for milestone in revealMilestones {
184
+ engine.addRevealMilestone(milestone)
185
+ }
186
+ }
187
+ }
188
+
189
+ var shimmer = Shimmer() {
190
+ didSet { render() }
191
+ }
192
+
193
+ var flash = Flash() {
194
+ didSet {
195
+ guard flash != oldValue else { return }
196
+ engine.setFlash(flash.upColor != nil || flash.downColor != nil ? flash.duration : 0)
197
+ // The tinted glyph images are per colour; a new flash colour means new ones.
198
+ if flash.upColor != oldValue.upColor || flash.downColor != oldValue.downColor {
199
+ render()
200
+ warmSwapImages()
201
+ }
202
+ }
203
+ }
204
+
205
+ /// Loading glint: full-color ink with a light band sweeping through it.
206
+ var loading = false {
207
+ didSet {
208
+ guard loading != oldValue else { return }
209
+ engine.setReduceMotion(UIAccessibility.isReduceMotionEnabled)
210
+ engine.setLoading(loading, CACurrentMediaTime())
211
+ updateDisplayLinkNeed()
212
+ render()
213
+ }
214
+ }
215
+
216
+ var alignment: Alignment = .auto {
217
+ didSet { render() }
218
+ }
219
+
220
+ /// Called with the settled (target) intrinsic size whenever it changes.
221
+ var onIntrinsicSizeChange: ((CGSize) -> Void)?
222
+ /// Called once a jackpot reveal has landed (count finished, pop rung out).
223
+ var onRevealEnd: (() -> Void)?
224
+ /// Called when a count-style reveal reaches a milestone (its index and value).
225
+ var onRevealMilestone: ((Int, Double) -> Void)?
226
+
227
+ /// The value currently shown or being rolled towards.
228
+ var targetValue: Double { engine.targetValue() }
229
+ /// True while a jackpot reveal counts or its landing pop rings out.
230
+ var isRevealing: Bool { engine.isRevealing() }
231
+
232
+ // MARK: - Shimmer geometry (matches the Uno "shine" variant)
233
+
234
+ private static let defaultShimmerColor = UIColor { traits in
235
+ traits.userInterfaceStyle == .dark
236
+ ? UIColor(red: 0x2B / 255, green: 0x2E / 255, blue: 0x37 / 255, alpha: 1)
237
+ : UIColor(red: 0xD6 / 255, green: 0xD9 / 255, blue: 0xE1 / 255, alpha: 1)
238
+ }
239
+ /// The core starts at the glyphs' left edge instead of parked off-screen.
240
+ private static let shimmerSeed: CGFloat = 0.25
241
+ /// How far the top of the band leads the bottom, as a fraction of the height ("/" slant).
242
+ private static let shimmerSlant: CGFloat = 0.6
243
+
244
+ // MARK: - Fonts
245
+
246
+ private enum GlyphRole {
247
+ case digit, prefix, suffix
248
+ }
249
+
250
+ private struct GlyphKey: Hashable {
251
+ let text: String
252
+ let role: GlyphRole
253
+ }
254
+
255
+ /// Images every NitroNumber shares, kept while they are in use. A numeric
256
+ /// transition cycles each digit through every blur level, so a screen of
257
+ /// figures in a few fonts and colours uses hundreds of blurred glyphs a
258
+ /// second; a cache that started over when it reached a fixed count dropped
259
+ /// ones about to be drawn again and re-blurred them (thousands of vImage
260
+ /// passes a second on a trading screen). Past `budget` bytes, what has gone
261
+ /// unused for `idle` seconds is dropped, oldest first; what is still in use
262
+ /// stays unless the cache passes `limit`. A memory warning empties it.
263
+ private final class RecentImageCache<Key: Hashable> {
264
+ private struct Entry {
265
+ let image: UIImage
266
+ let bytes: Int
267
+ var used: CFTimeInterval
268
+ }
269
+ private var entries: [Key: Entry] = [:]
270
+ private(set) var bytes = 0
271
+ private let budget: Int
272
+ private let limit: Int
273
+ private let idle: CFTimeInterval
274
+ private var observer: NSObjectProtocol?
275
+
276
+ init(budget: Int = 8 << 20, limit: Int = 64 << 20, idle: CFTimeInterval = 2) {
277
+ self.budget = budget
278
+ self.limit = limit
279
+ self.idle = idle
280
+ observer = NotificationCenter.default.addObserver(
281
+ forName: UIApplication.didReceiveMemoryWarningNotification, object: nil, queue: .main
282
+ ) { [weak self] _ in
283
+ self?.entries.removeAll()
284
+ self?.bytes = 0
285
+ }
286
+ }
287
+
288
+ var count: Int { entries.count }
289
+
290
+ subscript(key: Key) -> UIImage? {
291
+ guard var entry = entries[key] else { return nil }
292
+ entry.used = CACurrentMediaTime()
293
+ entries[key] = entry
294
+ return entry.image
295
+ }
296
+
297
+ func insert(_ image: UIImage, for key: Key) {
298
+ let cost = image.cgImage.map { $0.bytesPerRow * $0.height } ?? 0
299
+ let now = CACurrentMediaTime()
300
+ if let old = entries.updateValue(Entry(image: image, bytes: cost, used: now), forKey: key) { bytes -= old.bytes }
301
+ bytes += cost
302
+ guard bytes > budget else { return }
303
+ for (key, entry) in entries.sorted(by: { $0.value.used < $1.value.used }) {
304
+ guard bytes > budget, now - entry.used > idle || bytes > limit else { break }
305
+ entries.removeValue(forKey: key)
306
+ bytes -= entry.bytes
307
+ }
308
+ }
309
+ }
310
+
311
+ /// Digit / prefix / suffix fonts with per-glyph caches.
312
+ private final class FontSet {
313
+ let digit: UIFont
314
+ let prefix: UIFont
315
+ let suffix: UIFont
316
+ /// The text color resolved for the view's traits: the glyph images bake it
317
+ /// in, and `.label` is dynamic (see `traitCollectionDidChange`).
318
+ let color: UIColor
319
+ let prefixAlign: AffixAlign
320
+ let suffixAlign: AffixAlign
321
+ /// Height of the line box (the digit font's line height).
322
+ let lineHeight: CGFloat
323
+ /// The numeric transition's blur radius at full blur, in line heights.
324
+ let numericBlur: CGFloat = NitroNumberView.numericBlur
325
+ /// Width of the widest digit glyph.
326
+ private(set) var digitWidth: CGFloat = 0
327
+ // Keyed by a value type rather than a concatenated string: a lookup on the
328
+ // frame path must not allocate.
329
+ private var glyphCache: [GlyphKey: NSAttributedString] = [:]
330
+ private var widthCache: [GlyphKey: CGFloat] = [:]
331
+ private var inkDescentCache: [GlyphKey: CGFloat] = [:]
332
+
333
+ /// The rasterized glyphs and strips are shared by every rolling number
334
+ /// drawn with the same font, colour and density. A view lives on after
335
+ /// Fabric drops it until the JS side's handle to it is collected, which is
336
+ /// Hermes's decision; twenty-four dropped views must not each hold a strip
337
+ /// (a 3× strip is most of a megabyte) meanwhile. Bounded: when the cache
338
+ /// grows past its capacity it starts over, which costs one re-rasterization.
339
+ private struct ImageKey: Hashable {
340
+ let font: String
341
+ let color: UInt32
342
+ let scale: CGFloat
343
+ let text: String
344
+ let role: GlyphRole
345
+ }
346
+ private struct StripKey: Hashable {
347
+ let font: String
348
+ let color: UInt32
349
+ let scale: CGFloat
350
+ let blankZero: Bool
351
+ }
352
+ private static var sharedImages: [ImageKey: UIImage] = [:]
353
+ /// Blurred glyphs, the digit's own colour (tint 0) and the flash's alike.
354
+ private static let sharedBlurred = RecentImageCache<TintKey>()
355
+ /// Glyphs in the change flash's colours, keyed like the sharp ones plus
356
+ /// the tint (0: the digit colour), and blurred ones plus their level.
357
+ private struct TintKey: Hashable {
358
+ let image: ImageKey
359
+ let tint: UInt32
360
+ var level = 0
361
+ /// The blur radius the level is a fraction of, in thousandths of a line height.
362
+ var blur = 0
363
+ }
364
+ private static var sharedTinted: [TintKey: UIImage] = [:]
365
+ private static var sharedStrips: [StripKey: UIImage] = [:]
366
+ private static let sharedCapacity = 512
367
+ private let colorKey: UInt32
368
+ private func fontTag(_ role: GlyphRole) -> String {
369
+ let font = self.font(for: role)
370
+ return "\(font.fontName)|\(font.pointSize)"
371
+ }
372
+ /// Pixel density the glyph images are rendered at.
373
+ let renderScale: CGFloat
374
+ /// Slots in a wheel strip: index -1 (blank) through 10 (the 0 after 9).
375
+ static let stripSlots = 12
376
+
377
+ init(_ t: Typography, traits: UITraitCollection) {
378
+ // The view's own display, not the main screen's (deprecated, and absent on visionOS).
379
+ renderScale = max(1, traits.displayScale)
380
+ let scale = NitroNumberView.systemFontMultiplier(t)
381
+ digit = NitroNumberView.makeFont(size: t.fontSize * scale, weight: t.fontWeight, family: t.fontFamily)
382
+ prefix = NitroNumberView.makeFont(size: (t.prefixFontSize ?? t.fontSize) * scale, weight: t.fontWeight, family: t.fontFamily)
383
+ suffix = NitroNumberView.makeFont(size: (t.suffixFontSize ?? t.fontSize) * scale, weight: t.fontWeight, family: t.fontFamily)
384
+ color = t.color.resolvedColor(with: traits)
385
+ var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
386
+ color.getRed(&r, green: &g, blue: &b, alpha: &a)
387
+ colorKey = (UInt32(max(0, min(1, a)) * 255) << 24) | (UInt32(max(0, min(1, r)) * 255) << 16) | (UInt32(max(0, min(1, g)) * 255) << 8) | UInt32(max(0, min(1, b)) * 255)
388
+ prefixAlign = t.prefixAlign
389
+ suffixAlign = t.suffixAlign
390
+ lineHeight = ceil(digit.lineHeight)
391
+ digitWidth = (0...9).map { width(of: String($0), role: .digit) }.max() ?? 0
392
+ }
393
+
394
+ func font(for role: GlyphRole) -> UIFont {
395
+ switch role {
396
+ case .digit: return digit
397
+ case .prefix: return prefix
398
+ case .suffix: return suffix
399
+ }
400
+ }
401
+
402
+ func attributed(_ text: String, role: GlyphRole) -> NSAttributedString {
403
+ let key = GlyphKey(text: text, role: role)
404
+ if let cached = glyphCache[key] { return cached }
405
+ let string = NSAttributedString(string: text, attributes: [
406
+ .font: font(for: role),
407
+ .foregroundColor: color,
408
+ ])
409
+ glyphCache[key] = string
410
+ return string
411
+ }
412
+
413
+ func width(of text: String, role: GlyphRole) -> CGFloat {
414
+ let key = GlyphKey(text: text, role: role)
415
+ if let cached = widthCache[key] { return cached }
416
+ let width = attributed(text, role: role).size().width
417
+ widthCache[key] = width
418
+ return width
419
+ }
420
+
421
+ /// The glyph rasterized once (text color baked in, at screen density) so a
422
+ /// frame is a handful of image blits instead of a Core Text layout and
423
+ /// rasterization pass per glyph. Profiling 24 rolling views showed the
424
+ /// per-glyph `NSAttributedString.draw` dominating the main thread.
425
+ func image(_ text: String, role: GlyphRole) -> UIImage? {
426
+ let key = ImageKey(font: fontTag(role), color: colorKey, scale: renderScale, text: text, role: role)
427
+ if let cached = Self.sharedImages[key] { return cached }
428
+ let string = attributed(text, role: role)
429
+ let size = string.size()
430
+ guard size.width > 0, size.height > 0 else { return nil }
431
+ let format = UIGraphicsImageRendererFormat()
432
+ format.scale = renderScale
433
+ format.opaque = false
434
+ let bounds = CGSize(width: ceil(size.width), height: ceil(size.height))
435
+ let image = UIGraphicsImageRenderer(size: bounds, format: format).image { _ in
436
+ string.draw(at: .zero)
437
+ }
438
+ if Self.sharedImages.count >= Self.sharedCapacity { Self.sharedImages.removeAll(keepingCapacity: true) }
439
+ Self.sharedImages[key] = image
440
+ return image
441
+ }
442
+
443
+ /// The digit out of focus, for the numeric transition: the sharp glyph
444
+ /// blurred by `numericBlur` line heights, padded so nothing is cut off,
445
+ /// rendered once per font, colour and density and shared like the sharp
446
+ /// one. A transitioning glyph is its sharp and its blurred image
447
+ /// cross-faded, which is a fixed cost per frame instead of a blur pass.
448
+ /// The digit at blur `level` of `numericBlurLevels` (level 0 is `image`):
449
+ /// a blurred glyph is not a sharp one cross-faded with a blurred one, which
450
+ /// reads as a sharp digit inside a glow, but the two levels nearest its
451
+ /// blur cross-faded, so it never shows a sharp core.
452
+ func blurredImage(_ text: String, role: GlyphRole = .digit, level: Int) -> UIImage? {
453
+ if level <= 0 || numericBlur <= 0 { return image(text, role: role) }
454
+ let key = TintKey(image: ImageKey(font: fontTag(role), color: colorKey, scale: renderScale, text: text, role: role), tint: 0, level: level, blur: blurKey)
455
+ if let cached = Self.sharedBlurred[key] { return cached }
456
+ guard let sharp = image(text, role: role), let image = blurred(sharp, level: level) else { return nil }
457
+ Self.sharedBlurred.insert(image, for: key)
458
+ return image
459
+ }
460
+
461
+ /// `blurredImage`'s twin for `tintedImage`, so a swapping glyph's change
462
+ /// flash blurs as the glyph does.
463
+ func tintedBlurredImage(_ text: String, tint: UIColor, level: Int) -> UIImage? {
464
+ if level <= 0 || numericBlur <= 0 { return tintedImage(text, tint: tint) }
465
+ let key = TintKey(image: ImageKey(font: fontTag(.digit), color: colorKey, scale: renderScale, text: text, role: .digit), tint: Self.key(of: tint), level: level, blur: blurKey)
466
+ if let cached = Self.sharedBlurred[key] { return cached }
467
+ guard let sharp = tintedImage(text, tint: tint), let image = blurred(sharp, level: level) else { return nil }
468
+ Self.sharedBlurred.insert(image, for: key)
469
+ return image
470
+ }
471
+
472
+ /// A swapping glyph's image at a blur level, in its own colour or the flash's.
473
+ func swapImage(_ text: String, level: Int, tint: UIColor?) -> UIImage? {
474
+ if let tint { return tintedBlurredImage(text, tint: tint, level: level) }
475
+ return blurredImage(text, level: level)
476
+ }
477
+
478
+ private var blurKey: Int { Int((numericBlur * 1000).rounded()) }
479
+
480
+ /// `sharp` blurred by `level / numericBlurLevels` of `numericBlur` line
481
+ /// heights, padded (for the full blur, so every level is the same size) so
482
+ /// nothing is cut off.
483
+ private func blurred(_ sharp: UIImage, level: Int) -> UIImage? {
484
+ guard let cg = sharp.cgImage else { return nil }
485
+ let full = lineHeight * numericBlur * renderScale
486
+ let sigma = full * CGFloat(level) / CGFloat(NitroNumberView.numericBlurLevels)
487
+ guard let blurred = Self.blur(cg, sigma: sigma, pad: Int(ceil(full * 3))) else { return nil }
488
+ return UIImage(cgImage: blurred, scale: renderScale, orientation: .up)
489
+ }
490
+
491
+ /// A colour as a cache key: eight bits a channel, alpha first.
492
+ static func key(of color: UIColor) -> UInt32 {
493
+ var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
494
+ color.getRed(&r, green: &g, blue: &b, alpha: &a)
495
+ return (UInt32(max(0, min(1, a)) * 255) << 24) | (UInt32(max(0, min(1, r)) * 255) << 16) | (UInt32(max(0, min(1, g)) * 255) << 8) | UInt32(max(0, min(1, b)) * 255)
496
+ }
497
+
498
+ /// `cg` blurred by about `sigma` pixels, with `pad` transparent pixels added
499
+ /// on every side for the blur to spread into: a tent convolution on the CPU
500
+ /// with vImage, which is a box blur run twice and reads as a gaussian at this
501
+ /// size, in well under a millisecond for a glyph. Core Image did this before,
502
+ /// and its first render of a session stalled the main thread for longer than
503
+ /// the swap itself, so the spring had finished behind it.
504
+ private static func blur(_ cg: CGImage, sigma: CGFloat, pad: Int) -> CGImage? {
505
+ var format = vImage_CGImageFormat(
506
+ bitsPerComponent: 8, bitsPerPixel: 32, colorSpace: nil,
507
+ bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue),
508
+ version: 0, decode: nil, renderingIntent: .defaultIntent)
509
+ var source = vImage_Buffer()
510
+ guard vImageBuffer_InitWithCGImage(&source, &format, nil, cg, vImage_Flags(kvImageNoFlags)) == kvImageNoError else { return nil }
511
+ defer { free(source.data) }
512
+ let width = Int(source.width) + 2 * pad
513
+ let height = Int(source.height) + 2 * pad
514
+ var padded = vImage_Buffer()
515
+ guard vImageBuffer_Init(&padded, vImagePixelCount(height), vImagePixelCount(width), 32, vImage_Flags(kvImageNoFlags)) == kvImageNoError else { return nil }
516
+ defer { free(padded.data) }
517
+ memset(padded.data, 0, padded.rowBytes * height)
518
+ for row in 0..<Int(source.height) {
519
+ memcpy(padded.data.advanced(by: (row + pad) * padded.rowBytes + pad * 4),
520
+ source.data.advanced(by: row * source.rowBytes),
521
+ Int(source.width) * 4)
522
+ }
523
+ var out = vImage_Buffer()
524
+ guard vImageBuffer_Init(&out, vImagePixelCount(height), vImagePixelCount(width), 32, vImage_Flags(kvImageNoFlags)) == kvImageNoError else { return nil }
525
+ defer { free(out.data) }
526
+ // A tent kernel of half-width h has a standard deviation of h / √6; run
527
+ // twice it is four box passes, a gaussian to the eye, of h / √3.
528
+ let half = max(1, Int((sigma * 1.732).rounded()))
529
+ let kernel = UInt32(half * 2 + 1)
530
+ guard vImageTentConvolve_ARGB8888(&padded, &out, nil, 0, 0, kernel, kernel, nil, vImage_Flags(kvImageEdgeExtend)) == kvImageNoError else { return nil }
531
+ guard vImageTentConvolve_ARGB8888(&out, &padded, nil, 0, 0, kernel, kernel, nil, vImage_Flags(kvImageEdgeExtend)) == kvImageNoError else { return nil }
532
+ return vImageCreateCGImageFromBuffer(&padded, &format, nil, nil, vImage_Flags(kvImageNoFlags), nil)?.takeRetainedValue()
533
+ }
534
+
535
+ /// The glyph in another colour, for the change flash: the same raster as
536
+ /// `image` with the tint baked in, composited over the glyph at the flash's
537
+ /// opacity. Made once per font, density and tint.
538
+ func tintedImage(_ text: String, tint: UIColor) -> UIImage? {
539
+ let key = TintKey(image: ImageKey(font: fontTag(.digit), color: colorKey, scale: renderScale, text: text, role: .digit), tint: Self.key(of: tint))
540
+ if let cached = Self.sharedTinted[key] { return cached }
541
+ let string = NSAttributedString(string: text, attributes: [.font: digit, .foregroundColor: tint])
542
+ let size = string.size()
543
+ guard size.width > 0, size.height > 0 else { return nil }
544
+ let format = UIGraphicsImageRendererFormat()
545
+ format.scale = renderScale
546
+ format.opaque = false
547
+ let image = UIGraphicsImageRenderer(size: CGSize(width: ceil(size.width), height: ceil(size.height)), format: format).image { _ in
548
+ string.draw(at: .zero)
549
+ }
550
+ if Self.sharedTinted.count >= 128 { Self.sharedTinted.removeAll(keepingCapacity: true) }
551
+ Self.sharedTinted[key] = image
552
+ return image
553
+ }
554
+
555
+ /// The strip in the change flash's colour, for a wheel that flashes while it
556
+ /// rolls: laid over the strip at the same offset, it rides the roll. One per
557
+ /// colour and variant, so two for a trading screen.
558
+ private struct TintedStripKey: Hashable {
559
+ let strip: StripKey
560
+ let tint: UInt32
561
+ }
562
+ private static var sharedTintedStrips: [TintedStripKey: UIImage] = [:]
563
+ func tintedStrip(blankZero: Bool, tint: UIColor) -> UIImage? {
564
+ let key = TintedStripKey(strip: StripKey(font: fontTag(.digit), color: colorKey, scale: renderScale, blankZero: blankZero), tint: Self.key(of: tint))
565
+ if let cached = Self.sharedTintedStrips[key] { return cached }
566
+ guard digitWidth > 0, lineHeight > 0 else { return nil }
567
+ let format = UIGraphicsImageRendererFormat()
568
+ format.scale = renderScale
569
+ format.opaque = false
570
+ let size = CGSize(width: ceil(digitWidth), height: lineHeight * CGFloat(Self.stripSlots))
571
+ let image = UIGraphicsImageRenderer(size: size, format: format).image { _ in
572
+ for slot in 0..<Self.stripSlots {
573
+ let index = slot - 1
574
+ if index < 0 || (blankZero && index == 0) { continue }
575
+ let text = String(index % 10)
576
+ let w = width(of: text, role: .digit)
577
+ NSAttributedString(string: text, attributes: [.font: digit, .foregroundColor: tint])
578
+ .draw(at: CGPoint(x: (digitWidth - w) / 2, y: CGFloat(slot) * lineHeight))
579
+ }
580
+ }
581
+ if Self.sharedTintedStrips.count >= 8 { Self.sharedTintedStrips.removeAll(keepingCapacity: true) }
582
+ Self.sharedTintedStrips[key] = image
583
+ return image
584
+ }
585
+
586
+ /// A wheel's whole digit strip as one image: slots for index -1 (blank) to
587
+ /// 10 (the 0 that follows 9 on a wrap), each `lineHeight` tall with the
588
+ /// digit centred in `digitWidth`. A wheel layer shows one slot-high window
589
+ /// of it and just moves the strip, so a roll is a position change.
590
+ func strip(blankZero: Bool) -> UIImage? {
591
+ let key = StripKey(font: fontTag(.digit), color: colorKey, scale: renderScale, blankZero: blankZero)
592
+ if let cached = Self.sharedStrips[key] { return cached }
593
+ guard digitWidth > 0, lineHeight > 0 else { return nil }
594
+ let format = UIGraphicsImageRendererFormat()
595
+ format.scale = renderScale
596
+ format.opaque = false
597
+ let size = CGSize(width: ceil(digitWidth), height: lineHeight * CGFloat(Self.stripSlots))
598
+ let image = UIGraphicsImageRenderer(size: size, format: format).image { _ in
599
+ for slot in 0..<Self.stripSlots {
600
+ let index = slot - 1
601
+ if index < 0 || (blankZero && index == 0) { continue }
602
+ let text = String(index % 10)
603
+ let w = width(of: text, role: .digit)
604
+ attributed(text, role: .digit).draw(at: CGPoint(x: (digitWidth - w) / 2, y: CGFloat(slot) * lineHeight))
605
+ }
606
+ }
607
+ if Self.sharedStrips.count >= 64 { Self.sharedStrips.removeAll(keepingCapacity: true) }
608
+ Self.sharedStrips[key] = image
609
+ return image
610
+ }
611
+
612
+ /// How far `text`'s ink hangs below the baseline (0 for digits and capitals).
613
+ func inkDescent(_ text: String, role: GlyphRole) -> CGFloat {
614
+ let key = GlyphKey(text: text, role: role)
615
+ if let cached = inkDescentCache[key] { return cached }
616
+ let line = CTLineCreateWithAttributedString(attributed(text, role: role))
617
+ let bounds = CTLineGetImageBounds(line, nil)
618
+ let descent = bounds.isNull ? 0 : max(0, -bounds.minY)
619
+ inkDescentCache[key] = descent
620
+ return descent
621
+ }
622
+
623
+ /// Top of the glyph's line box for `role` drawing `text`, given the top of the digit line box.
624
+ func top(for role: GlyphRole, text: String, lineTop: CGFloat) -> CGFloat {
625
+ guard role != .digit else { return lineTop }
626
+ let f = font(for: role)
627
+ switch role == .prefix ? prefixAlign : suffixAlign {
628
+ case .baseline:
629
+ return lineTop + (digit.ascender - f.ascender)
630
+ case .center:
631
+ return lineTop + (digit.lineHeight - f.lineHeight) / 2
632
+ case .top:
633
+ return lineTop + (digit.ascender - digit.capHeight) - (f.ascender - f.capHeight)
634
+ case .bottom:
635
+ // Pin the bottom of the ink, not of the line boxes: the digits' ink ends
636
+ // on the baseline, so "USD" sits on it too instead of hanging down to
637
+ // where a comma's tail reaches.
638
+ let affixBaseline = lineTop + digit.ascender + inkDescent("0123456789", role: .digit) - inkDescent(text, role: role)
639
+ return affixBaseline - f.ascender
640
+ }
641
+ }
642
+ }
643
+
644
+ // MARK: - State
645
+
646
+ private var engine = Engine()
647
+ private lazy var fonts = FontSet(Typography(), traits: traitCollection)
648
+ private var fontScale: CGFloat = 1
649
+ /// Reused every frame so the render path stops allocating once warm.
650
+ private var wheelBuffer: [Engine.Wheel] = []
651
+ private var elementBuffer: [Element] = []
652
+ private var settledWheels: [Engine.Wheel] = []
653
+ private var settledBuffer: [Element] = []
654
+ /// The affixes split from the space they keep against the digits (RTL only),
655
+ /// recomputed when the format or the direction changes.
656
+ private var affixBlocks = AffixBlocks(prefix: "", suffix: "", rtl: false)
657
+ private var displayLink: CADisplayLink?
658
+ private var lastReportedSize: CGSize = .zero
659
+
660
+ /// Scaled and aligned container for the element layers.
661
+ private let contentLayer = QuietLayer()
662
+ /// One entry per laid-out element, in drawing order.
663
+ private var slots: [ElementLayer] = []
664
+ /// True while the loading glint is visible and frames go through `draw(_:)`.
665
+ private var usesBitmap = false
666
+
667
+ private enum LayerKind: Equatable {
668
+ case wheel
669
+ case glyph(String, GlyphRole)
670
+ }
671
+
672
+ /// One layer of a swapping glyph and what it holds: a digit at a blur level, in a tint.
673
+ private final class GlyphLayer {
674
+ let layer = QuietLayer()
675
+ var glyph = -2
676
+ var level = -1
677
+ var tint: UInt32 = 0
678
+ /// Text swaps only: the text the layer shows.
679
+ var text: String?
680
+ }
681
+
682
+ /// A prefix, suffix or separator changing its text (`Engine.changeText`):
683
+ /// the leaving and the arriving text, each a pair of layers holding the two
684
+ /// blur levels nearest its blur, cross-faded as a swapping digit's are. On
685
+ /// the slot's overlay, unclipped, so the haze stays whole.
686
+ private final class TextSwapLayers {
687
+ let leaving = (GlyphLayer(), GlyphLayer())
688
+ let arriving = (GlyphLayer(), GlyphLayer())
689
+ var hidden = true
690
+ var all: [CALayer] { [leaving.0, leaving.1, arriving.0, arriving.1].map { $0.layer } }
691
+
692
+ init(scale: CGFloat) {
693
+ for layer in all {
694
+ layer.contentsScale = scale
695
+ layer.isHidden = true
696
+ }
697
+ }
698
+ }
699
+
700
+ /// The numeric transition's layers of one wheel: the leaving glyph and the
701
+ /// arriving one, each a pair of layers holding the two blur levels nearest
702
+ /// the glyph's blur, cross-faded (`placeSwapGlyph`), and the same two pairs
703
+ /// again in the change flash's colour, laid over their twins at the flash's
704
+ /// opacity, which is the ink mixed towards the tint. Made the first time the
705
+ /// wheel swaps, hidden whenever it is settled. They live on the slot's
706
+ /// overlay, not in its clipped container: a blurred glyph's haze reaches
707
+ /// past the digit cell, and cut at the cell it read as a pale box around
708
+ /// the digit.
709
+ private final class SwapLayers {
710
+ let leaving = (GlyphLayer(), GlyphLayer())
711
+ let arriving = (GlyphLayer(), GlyphLayer())
712
+ let leavingTint = (GlyphLayer(), GlyphLayer())
713
+ let arrivingTint = (GlyphLayer(), GlyphLayer())
714
+ var hidden = true
715
+ var all: [CALayer] {
716
+ [leaving.0, leaving.1, arriving.0, arriving.1, leavingTint.0, leavingTint.1, arrivingTint.0, arrivingTint.1].map { $0.layer }
717
+ }
718
+
719
+ init(scale: CGFloat) {
720
+ for layer in all {
721
+ layer.contentsScale = scale
722
+ layer.isHidden = true
723
+ }
724
+ }
725
+ }
726
+
727
+ /// A class, not a struct: the frame loop reads every slot, and a struct
728
+ /// copy retained and released each of its layers every frame.
729
+ private final class ElementLayer {
730
+ let kind: LayerKind
731
+ var layer: CALayer
732
+ /// The strip (wheels) or the glyph's image (glyphs), inside `layer`.
733
+ var inner: CALayer
734
+ /// Wheels only: which strip variant the layer currently shows.
735
+ var blankZero: Bool
736
+ /// Wheels only: the numeric transition's layers, once the wheel has swapped,
737
+ /// on an unclipped layer of their own over the containers.
738
+ var swap: SwapLayers?
739
+ var overlay: CALayer?
740
+ /// Glyphs only: a text swap's layers, on `overlay`, once the text has changed.
741
+ var textSwap: TextSwapLayers?
742
+ /// Wheels only: the change flash of a wheel that is not swapping, a
743
+ /// tinted copy of the strip over the strip.
744
+ var flashLayer: CALayer?
745
+ var flashGlyph = -2
746
+ var flashTint: UInt32 = 0
747
+ /// Glyphs only: the image's top within the line box, fixed for the font set.
748
+ var glyphTop: CGFloat
749
+ /// What the layers were last given, so a frame only touches what moved:
750
+ /// every Core Animation setter costs a transaction entry and a KVO round
751
+ /// trip even when the value is the same, and most of a number's layers
752
+ /// (affixes, separators, wheels that are not rolling) do not move.
753
+ var frame = CGRect.null
754
+ var innerFrame = CGRect.null
755
+ var opacity: Float = -1
756
+
757
+ init(kind: LayerKind, layer: CALayer, inner: CALayer, blankZero: Bool, glyphTop: CGFloat) {
758
+ self.kind = kind
759
+ self.layer = layer
760
+ self.inner = inner
761
+ self.blankZero = blankZero
762
+ self.glyphTop = glyphTop
763
+ }
764
+ }
765
+
766
+ private struct AffixBlocks {
767
+ let prefix: String
768
+ let suffix: String
769
+ let rtl: Bool
770
+ let prefixInk: String
771
+ let prefixGap: String
772
+ let suffixInk: String
773
+ let suffixGap: String
774
+
775
+ init(prefix: String, suffix: String, rtl: Bool) {
776
+ self.prefix = prefix
777
+ self.suffix = suffix
778
+ self.rtl = rtl
779
+ let p = rtl ? NitroNumberView.splitAffix(prefix, spaceAtEnd: true) : (ink: prefix, gap: "")
780
+ let s = rtl ? NitroNumberView.splitAffix(suffix, spaceAtEnd: false) : (ink: suffix, gap: "")
781
+ prefixInk = p.ink
782
+ prefixGap = p.gap
783
+ suffixInk = s.ink
784
+ suffixGap = s.gap
785
+ }
786
+ }
787
+
788
+ // MARK: - Lifecycle
789
+
790
+ override init(frame: CGRect) {
791
+ super.init(frame: frame)
792
+ isOpaque = false
793
+ backgroundColor = .clear
794
+ contentMode = .redraw
795
+ contentLayer.anchorPoint = .zero
796
+ contentLayer.contentsScale = fonts.renderScale
797
+ layer.addSublayer(contentLayer)
798
+ // Not clipped: in auto-size mode a new leading digit can draw past the old
799
+ // frame for the one render it takes JS to apply the reported size, instead
800
+ // of being cut off. Nothing else about the roll touches the JS thread.
801
+ clipsToBounds = false
802
+ isAccessibilityElement = true
803
+ accessibilityTraits = .staticText
804
+ NotificationCenter.default.addObserver(
805
+ self, selector: #selector(contentSizeCategoryDidChange),
806
+ name: UIContentSizeCategory.didChangeNotification, object: nil
807
+ )
808
+ }
809
+
810
+ @available(*, unavailable)
811
+ required init?(coder: NSCoder) {
812
+ fatalError("init(coder:) is not supported")
813
+ }
814
+
815
+ deinit {
816
+ displayLink?.invalidate()
817
+ NotificationCenter.default.removeObserver(self)
818
+ }
819
+
820
+ override func layoutSubviews() {
821
+ super.layoutSubviews()
822
+ if awaitingLayout, abs(bounds.width - lastReportedSize.width) <= 1 { awaitingLayout = false }
823
+ learnAnchor()
824
+ // The shrink-to-fit scale and alignment depend on the bounds.
825
+ render()
826
+ }
827
+
828
+ override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
829
+ super.traitCollectionDidChange(previousTraitCollection)
830
+ // The glyph images bake the resolved text color and the pixel density in:
831
+ // a light/dark switch (`.label` is dynamic) or a move to another display
832
+ // re-rasterizes them.
833
+ let resolved = typography.color.resolvedColor(with: traitCollection)
834
+ if resolved != fonts.color || max(1, traitCollection.displayScale) != fonts.renderScale {
835
+ rebuildFonts()
836
+ }
837
+ }
838
+
839
+ @objc private func contentSizeCategoryDidChange() {
840
+ guard typography.allowFontScaling else { return }
841
+ rebuildFonts()
842
+ }
843
+
844
+ func stopAnimation() {
845
+ stopDisplayLink()
846
+ }
847
+
848
+ /// Fabric dropped the view. Its component view goes to Fabric's recycle
849
+ /// pool and the hybrid lives on until the JS handle to it is collected, so
850
+ /// everything that could outlive the drop stops here and everything
851
+ /// sizeable is let go of: the display link, the element layers, the engine's
852
+ /// wheels and the buffers. The glyph images are shared and stay cached. The
853
+ /// view stays usable: `resetForRecycle` and a new element's props may follow.
854
+ func release() {
855
+ stopDisplayLink()
856
+ engine.reset()
857
+ clearSlots()
858
+ wheelBuffer = []
859
+ elementBuffer = []
860
+ settledWheels = []
861
+ settledBuffer = []
862
+ usesBitmap = false
863
+ layer.contents = nil
864
+ }
865
+
866
+ /// What one mounted rolling number costs, for the JS garbage collector
867
+ /// (Nitro's `memorySize`). Measured, not estimated: the example's
868
+ /// `footprint` benchmark mounts 100 copies, asks malloc to return freed
869
+ /// pages before and with them, and divides the difference, on the first
870
+ /// mount (Fabric hands later mounts the pooled views of earlier ones).
871
+ /// iPhone 11 Pro and 13 Pro Max, 2026-09-22: 60–80 KB of malloc (layers,
872
+ /// engine, buffers) and a 70–90 KB physical footprint per copy; a plain
873
+ /// `Text` is 28 KB of malloc and 120–130 KB of footprint, its backing
874
+ /// store. The layers' render-server side is not in this process and not
875
+ /// counted. A constant, because Nitro reads it from the JS thread.
876
+ static let memoryEstimateBytes = 64 * 1024
877
+
878
+ /// Returns the view to its pristine state so Fabric can reuse it for a new
879
+ /// element (`RecyclableView`). Props are re-applied by Nitro afterwards.
880
+ func resetForRecycle() {
881
+ stopDisplayLink()
882
+ engine.reset()
883
+ fontScale = 1
884
+ lastReportedSize = .zero
885
+ leavingText = [nil, nil, nil, nil]
886
+ autoAnchor = nil
887
+ awaitingLayout = false
888
+ laidFrame = nil
889
+ pendingSizeReport = false
890
+ format = Format()
891
+ typography = Typography()
892
+ timing = Timing()
893
+ shimmer = Shimmer()
894
+ alignment = .auto
895
+ revealMilestones = []
896
+ // `onIntrinsicSizeChange`, `onRevealEnd` and `onRevealMilestone` are the
897
+ // hybrid's wiring, not the element's props: they stay across recycling
898
+ // (the hybrid clears its own callback props).
899
+ clearSlots()
900
+ layer.contents = nil
901
+ usesBitmap = false
902
+ contentLayer.isHidden = false
903
+ }
904
+
905
+ // MARK: - Public API
906
+
907
+ /// Shows `value` immediately with continuously positioned wheels (odometer
908
+ /// style). Cancels any running roll. Intended to be called every frame.
909
+ func setValue(_ value: Double) {
910
+ engine.setValue(value)
911
+ reportIntrinsicSize()
912
+ updateDisplayLinkNeed()
913
+ render()
914
+ }
915
+
916
+ /// Rolls every wheel to `value` (snaps on first show, duration 0 or Reduce Motion).
917
+ func animate(to value: Double) {
918
+ engine.setReduceMotion(UIAccessibility.isReduceMotionEnabled)
919
+ engine.animateTo(value, CACurrentMediaTime())
920
+ reportIntrinsicSize()
921
+ updateDisplayLinkNeed()
922
+ // A roll is rendered by the display link's next tick, within a frame; a
923
+ // value that snapped (duration 0, Reduce Motion, nothing shown yet) has
924
+ // no tick coming and is rendered now. Rendering here as well doubled the
925
+ // main-thread work of a value stream (24 views fed every frame: two layer
926
+ // passes per view per frame).
927
+ if displayLink == nil { render() }
928
+ }
929
+
930
+ /// Shows the opening frame of a jackpot reveal for `value` ("$0.00" in the
931
+ /// target's layout), waiting for `reveal(to:)`.
932
+ func holdReveal(_ value: Double) {
933
+ engine.holdReveal(value)
934
+ reportIntrinsicSize()
935
+ updateDisplayLinkNeed()
936
+ render()
937
+ }
938
+
939
+ /// Counts up from 0 to `value` and lands with a pop (snaps under Reduce Motion).
940
+ func reveal(to value: Double) {
941
+ engine.setReduceMotion(UIAccessibility.isReduceMotionEnabled)
942
+ engine.reveal(value, CACurrentMediaTime())
943
+ reportIntrinsicSize()
944
+ updateDisplayLinkNeed()
945
+ render()
946
+ reportMilestones(reachedBefore: 0)
947
+ if !engine.isRevealing() {
948
+ // Snapped (Reduce Motion / duration 0): the reveal is over before it began.
949
+ onRevealEnd?()
950
+ }
951
+ }
952
+
953
+ /// Fires `onRevealMilestone` for every milestone reached since `reachedBefore`.
954
+ private func reportMilestones(reachedBefore: Int) {
955
+ let reached = Int(engine.revealMilestonesReached())
956
+ guard reached > reachedBefore, let onRevealMilestone else { return }
957
+ for index in reachedBefore..<reached {
958
+ onRevealMilestone(index, engine.revealMilestoneValue(Int32(index)))
959
+ }
960
+ }
961
+
962
+ /// Re-sends the last reported intrinsic size (e.g. after a listener was attached).
963
+ func resendIntrinsicSize() {
964
+ guard lastReportedSize != .zero else { return }
965
+ onIntrinsicSizeChange?(lastReportedSize)
966
+ }
967
+
968
+ // MARK: - Display link
969
+
970
+ fileprivate func step(_ link: CADisplayLink) {
971
+ let wasRevealing = engine.isRevealing()
972
+ let reachedBefore = Int(engine.revealMilestonesReached())
973
+ _ = engine.tick(CACurrentMediaTime())
974
+ if pendingSizeReport, !engine.isRolling() {
975
+ reportIntrinsicSize()
976
+ }
977
+ updateDisplayLinkNeed()
978
+ render()
979
+ if wasRevealing {
980
+ reportMilestones(reachedBefore: reachedBefore)
981
+ if !engine.isRevealing() {
982
+ onRevealEnd?()
983
+ }
984
+ }
985
+ }
986
+
987
+ /// Keeps the display link alive only while the engine says something moves.
988
+ private func updateDisplayLinkNeed() {
989
+ if engine.needsFrames() {
990
+ startDisplayLink()
991
+ } else {
992
+ stopDisplayLink()
993
+ }
994
+ }
995
+
996
+ private func startDisplayLink() {
997
+ guard displayLink == nil else { return }
998
+ let proxy = DisplayLinkProxy(target: self)
999
+ let link = CADisplayLink(target: proxy, selector: #selector(DisplayLinkProxy.tick(_:)))
1000
+ // A ProMotion panel runs at 120 Hz only while something asks for it; a
1001
+ // display link left at its default gets 60 there, and so did the roll.
1002
+ // Ask for the panel's maximum (like a Reanimated animation does) so a roll
1003
+ // is as smooth as the screen allows; the link only lives while wheels move.
1004
+ if #available(iOS 15.0, *) {
1005
+ let maxFps = (window?.screen ?? UIScreen.main).maximumFramesPerSecond
1006
+ if maxFps > 60 {
1007
+ link.preferredFrameRateRange = CAFrameRateRange(minimum: 60, maximum: Float(maxFps), preferred: Float(maxFps))
1008
+ }
1009
+ }
1010
+ link.add(to: .main, forMode: .common)
1011
+ displayLink = link
1012
+ }
1013
+
1014
+ private func stopDisplayLink() {
1015
+ displayLink?.invalidate()
1016
+ displayLink = nil
1017
+ }
1018
+
1019
+ private final class DisplayLinkProxy: NSObject {
1020
+ weak var target: NitroNumberView?
1021
+ init(target: NitroNumberView) { self.target = target }
1022
+ @objc func tick(_ link: CADisplayLink) { target?.step(link) }
1023
+ }
1024
+
1025
+ // MARK: - Typography
1026
+
1027
+ private func rebuildFonts() {
1028
+ fonts = FontSet(typography, traits: traitCollection)
1029
+ contentLayer.contentsScale = fonts.renderScale
1030
+ fontScale = 1
1031
+ // Every cached glyph image belongs to the old font set.
1032
+ clearSlots()
1033
+ if engine.hasShownValue() {
1034
+ reportIntrinsicSize()
1035
+ }
1036
+ render()
1037
+ warmSwapImages()
1038
+ }
1039
+
1040
+ /// Renders the ten digits' sharp and blurred images ahead of the first
1041
+ /// numeric swap, on the next turn of the main queue so the mount itself
1042
+ /// pays nothing. Rendered on demand instead, the first change of a session
1043
+ /// spent its opening frames drawing glyphs, and the spring had landed by
1044
+ /// the time the second frame was on screen.
1045
+ private func warmSwapImages() {
1046
+ guard timing.transition == .numeric else { return }
1047
+ DispatchQueue.main.async { [weak self] in
1048
+ guard let self, self.timing.transition == .numeric else { return }
1049
+ let tints = [self.flash.upColor, self.flash.downColor].compactMap { $0 }
1050
+ for digit in Self.digitStrings {
1051
+ for level in 0...Self.numericBlurLevels {
1052
+ _ = self.fonts.blurredImage(digit, level: level)
1053
+ for tint in tints {
1054
+ _ = self.fonts.tintedBlurredImage(digit, tint: tint, level: level)
1055
+ }
1056
+ }
1057
+ }
1058
+ }
1059
+ }
1060
+
1061
+ /// Shrink-to-fit scale for the current bounds and the content as it is drawn
1062
+ /// *right now* (including half-appeared wheels): the amount shrinks and grows
1063
+ /// continuously in step with the roll and never overflows.
1064
+ private func updateFontScale(contentWidth: CGFloat) {
1065
+ var scale: CGFloat = 1
1066
+ if typography.adjustsFontSizeToFit, bounds.width > 0, contentWidth > bounds.width {
1067
+ scale = max(min(1, typography.minimumFontScale), bounds.width / contentWidth)
1068
+ }
1069
+ fontScale = scale
1070
+ }
1071
+
1072
+ /// Dynamic Type multiplier for `allowFontScaling`, capped by `maxFontSizeMultiplier`.
1073
+ private static func systemFontMultiplier(_ t: Typography) -> CGFloat {
1074
+ guard t.allowFontScaling else { return 1 }
1075
+ let multiplier = UIFontMetrics(forTextStyle: .body).scaledValue(for: 100) / 100
1076
+ if t.maxFontSizeMultiplier > 0 {
1077
+ return min(multiplier, t.maxFontSizeMultiplier)
1078
+ }
1079
+ return multiplier
1080
+ }
1081
+
1082
+ private static func makeFont(size: CGFloat, weight: CGFloat, family: String?) -> UIFont {
1083
+ let uiWeight = uiWeight(weight)
1084
+ let traits: [UIFontDescriptor.TraitKey: Any] = [.weight: uiWeight]
1085
+ var base: UIFont
1086
+ if let family, !family.isEmpty, let named = UIFont(name: family, size: size) {
1087
+ // A face name ("Inter-Bold") or a family UIKit resolves directly; pick the face for `weight`.
1088
+ let descriptor = named.fontDescriptor.addingAttributes([.traits: traits])
1089
+ base = UIFont(descriptor: descriptor, size: size)
1090
+ } else if let family, !family.isEmpty, !UIFont.fontNames(forFamilyName: family).isEmpty {
1091
+ // A family name registered through UIAppFonts (e.g. via expo-font): match by weight like <Text>.
1092
+ let descriptor = UIFontDescriptor(fontAttributes: [.family: family, .traits: traits])
1093
+ base = UIFont(descriptor: descriptor, size: size)
1094
+ } else {
1095
+ base = UIFont.systemFont(ofSize: size, weight: uiWeight)
1096
+ }
1097
+ // Tabular (monospaced) digits so every column has the same width.
1098
+ let feature: [UIFontDescriptor.FeatureKey: Int]
1099
+ if #available(iOS 15.0, *) {
1100
+ feature = [.type: kNumberSpacingType, .selector: kMonospacedNumbersSelector]
1101
+ } else {
1102
+ feature = [.featureIdentifier: kNumberSpacingType, .typeIdentifier: kMonospacedNumbersSelector]
1103
+ }
1104
+ let descriptor = base.fontDescriptor.addingAttributes([.featureSettings: [feature]])
1105
+ return UIFont(descriptor: descriptor, size: size)
1106
+ }
1107
+
1108
+ private static func uiWeight(_ w: CGFloat) -> UIFont.Weight {
1109
+ switch w {
1110
+ case ..<150: return .ultraLight
1111
+ case ..<250: return .thin
1112
+ case ..<350: return .light
1113
+ case ..<450: return .regular
1114
+ case ..<550: return .medium
1115
+ case ..<650: return .semibold
1116
+ case ..<750: return .bold
1117
+ case ..<850: return .heavy
1118
+ default: return .black
1119
+ }
1120
+ }
1121
+
1122
+ // MARK: - Layout
1123
+
1124
+ private enum ElementKind {
1125
+ case wheel(Int)
1126
+ case glyph(String, GlyphRole)
1127
+ }
1128
+
1129
+ private struct Element {
1130
+ var kind: ElementKind
1131
+ var width: CGFloat
1132
+ var fullWidth: CGFloat
1133
+ var factor: Double
1134
+ /// A text slot swapping: its slot, the text leaving, and the side it keeps to (-1 left, 0 centre, 1 right).
1135
+ var slot = -1
1136
+ var fromText: String?
1137
+ var anchor = 1
1138
+ }
1139
+
1140
+ /// Pulls the engine's wheels into `wheelBuffer`.
1141
+ private func syncWheels() {
1142
+ wheelBuffer.removeAll(keepingCapacity: true)
1143
+ let count = Int(engine.wheelCount())
1144
+ for index in 0..<count {
1145
+ wheelBuffer.append(engine.wheelAt(Int32(index)))
1146
+ }
1147
+ }
1148
+
1149
+ /// Lays the run out into `elements` (emptied first, capacity kept).
1150
+ private func buildElements(into elements: inout [Element], wheels: [Engine.Wheel], signFactor: Double, animated: Bool = true) {
1151
+ elements.removeAll(keepingCapacity: true)
1152
+ let fonts = self.fonts
1153
+ // The decimal columns laid out now: more than the format's while dropped ones close.
1154
+ let fd = animated ? Int(engine.displayFractionDigits()) : format.fractionDigits
1155
+ let decimal = animated ? engine.decimalFactor() : 1
1156
+
1157
+ func addGlyph(_ text: String, role: GlyphRole, factor: Double, slot: Int = -1, anchor: Int = 1) {
1158
+ guard factor > 0 else { return }
1159
+ // A slot swapping its text: the width eases from the old text's to the new one's.
1160
+ if animated, slot >= 0, let from = leavingText[slot], from != text {
1161
+ let change = engine.textChange(Int32(slot))
1162
+ if change.active {
1163
+ let g = CGFloat(max(0, min(1, change.grow)))
1164
+ let fromWidth = fonts.width(of: from, role: role)
1165
+ let toWidth = text.isEmpty ? 0 : fonts.width(of: text, role: role)
1166
+ elements.append(Element(
1167
+ kind: .glyph(text, role),
1168
+ width: (fromWidth + (toWidth - fromWidth) * g) * CGFloat(factor),
1169
+ fullWidth: max(fromWidth, toWidth),
1170
+ factor: factor,
1171
+ slot: slot,
1172
+ fromText: from,
1173
+ anchor: anchor
1174
+ ))
1175
+ return
1176
+ }
1177
+ }
1178
+ guard !text.isEmpty else { return }
1179
+ let width = fonts.width(of: text, role: role)
1180
+ elements.append(Element(kind: .glyph(text, role), width: width * CGFloat(factor), fullWidth: width, factor: factor))
1181
+ }
1182
+
1183
+ // Under a right-to-left layout the prefix belongs at the start edge - the
1184
+ // right - and the suffix at the end, while the digits stay a left-to-right
1185
+ // run: a number reads the same way in every script. So the run is laid out
1186
+ // block by block in mirror order, each block keeping its own order, and the
1187
+ // space an affix keeps against the digits stays against them: " USD" after
1188
+ // the number is "USD " before it.
1189
+ let rtl = isRTL
1190
+ if affixBlocks.rtl != rtl || affixBlocks.prefix != format.prefix || affixBlocks.suffix != format.suffix {
1191
+ affixBlocks = AffixBlocks(prefix: format.prefix, suffix: format.suffix, rtl: rtl)
1192
+ }
1193
+ let affixes = affixBlocks
1194
+ // A swapping affix keeps to the digits' side; a separator is centred.
1195
+ if rtl {
1196
+ addGlyph(affixes.suffixInk, role: .suffix, factor: 1, slot: Self.suffixText, anchor: 1)
1197
+ addGlyph(affixes.suffixGap, role: .suffix, factor: 1)
1198
+ } else {
1199
+ // Sign first, then the currency prefix: "-$1,234.50".
1200
+ addGlyph("-", role: .digit, factor: signFactor)
1201
+ addGlyph(affixes.prefixInk, role: .prefix, factor: 1, slot: Self.prefixText, anchor: 1)
1202
+ }
1203
+ var power = wheels.count - 1
1204
+ while power >= 0 {
1205
+ let wheel = wheels[power]
1206
+ if wheel.width > 0 {
1207
+ elements.append(Element(kind: .wheel(power), width: fonts.digitWidth * CGFloat(wheel.width), fullWidth: fonts.digitWidth, factor: wheel.width))
1208
+ }
1209
+ if power > fd, (power - fd) % 3 == 0 {
1210
+ addGlyph(format.groupingSeparator, role: .digit, factor: wheel.width, slot: Self.groupingText, anchor: 0)
1211
+ }
1212
+ if fd > 0, power == fd {
1213
+ addGlyph(format.decimalSeparator, role: .digit, factor: decimal, slot: Self.decimalText, anchor: 0)
1214
+ }
1215
+ power -= 1
1216
+ }
1217
+ if rtl {
1218
+ addGlyph(affixes.prefixGap, role: .prefix, factor: 1)
1219
+ addGlyph(affixes.prefixInk, role: .prefix, factor: 1, slot: Self.prefixText, anchor: -1)
1220
+ addGlyph("-", role: .digit, factor: signFactor)
1221
+ } else {
1222
+ addGlyph(affixes.suffixInk, role: .suffix, factor: 1, slot: Self.suffixText, anchor: -1)
1223
+ }
1224
+ }
1225
+
1226
+ /// The layout direction this view is in. The hybrid sets
1227
+ /// `semanticContentAttribute` from the `rightToLeft` prop, since Fabric
1228
+ /// never hands a Hybrid View its resolved direction.
1229
+ var isRTL: Bool { effectiveUserInterfaceLayoutDirection == .rightToLeft }
1230
+
1231
+ /// `.auto` resolved: in a box that hugs the figure, the edge the box kept
1232
+ /// the last time it changed width (`learnAnchor`), else the start edge of
1233
+ /// the layout direction. The rest are already absolute.
1234
+ private var resolvedAlignment: Alignment {
1235
+ guard alignment == .auto else { return alignment }
1236
+ if let autoAnchor, hugsFigure { return autoAnchor }
1237
+ return isRTL ? .right : .left
1238
+ }
1239
+
1240
+ // A box that hugs the figure is as wide as the figure at rest, so its
1241
+ // alignment only shows while the figure grows or shrinks: the box takes the
1242
+ // new width at once and the digits open or close inside it. Which edge they
1243
+ // keep to is the edge the parent keeps the box to: a figure at the end of a
1244
+ // row (`justifyContent: 'space-between'`) keeps its right edge, and
1245
+ // start-aligned it jumped a digit to the left and then opened a gap after
1246
+ // its prefix. So `.auto` follows the box: the edge that stayed put when its
1247
+ // width last changed, both for a centred box.
1248
+ private var autoAnchor: Alignment?
1249
+ private var laidFrame: CGRect?
1250
+
1251
+ /// A size reported and not yet laid out by React: for a frame or two the box
1252
+ /// still has the old width. Counted as hugging, or a shrinking figure fell
1253
+ /// back to the start edge for those frames and flashed across the box.
1254
+ private var awaitingLayout = false
1255
+
1256
+ private var hugsFigure: Bool {
1257
+ lastReportedSize.width > 0 && (awaitingLayout || abs(bounds.width - lastReportedSize.width) <= 1)
1258
+ }
1259
+
1260
+ /// Where the box sits in the view that lays it out (Fabric wraps a Hybrid
1261
+ /// View in its component view, whose parent that is).
1262
+ private func learnAnchor() {
1263
+ guard let container = superview, let parent = container.superview else { return }
1264
+ let frame = convert(bounds, to: parent)
1265
+ defer { laidFrame = frame }
1266
+ guard let previous = laidFrame, abs(frame.width - previous.width) > 0.5 else { return }
1267
+ let dl = frame.minX - previous.minX
1268
+ let dr = frame.maxX - previous.maxX
1269
+ if abs(dl) <= 0.5 {
1270
+ autoAnchor = .left
1271
+ } else if abs(dr) <= 0.5 {
1272
+ autoAnchor = .right
1273
+ } else if abs(dl + dr) <= 1 {
1274
+ autoAnchor = .center
1275
+ }
1276
+ }
1277
+
1278
+ private static let affixSpaces: Set<Unicode.Scalar> = [" ", "\u{A0}", "\u{2009}", "\u{202F}"]
1279
+
1280
+ /// Splits an affix from the space it keeps against the digits: a prefix's
1281
+ /// trailing run, a suffix's leading one. An affix that is all space is one
1282
+ /// block.
1283
+ private static func splitAffix(_ text: String, spaceAtEnd: Bool) -> (ink: String, gap: String) {
1284
+ let scalars = Array(text.unicodeScalars)
1285
+ var n = 0
1286
+ while n < scalars.count, affixSpaces.contains(spaceAtEnd ? scalars[scalars.count - 1 - n] : scalars[n]) {
1287
+ n += 1
1288
+ }
1289
+ guard n > 0, n < scalars.count else { return (text, "") }
1290
+ let cut = spaceAtEnd ? scalars.count - n : n
1291
+ let head = String(String.UnicodeScalarView(scalars[0..<cut]))
1292
+ let tail = String(String.UnicodeScalarView(scalars[cut...]))
1293
+ return spaceAtEnd ? (ink: head, gap: tail) : (ink: tail, gap: head)
1294
+ }
1295
+
1296
+ private func settledWidth() -> CGFloat {
1297
+ let count = Int(engine.settledPowerCount())
1298
+ settledWheels.removeAll(keepingCapacity: true)
1299
+ for _ in 0..<count {
1300
+ settledWheels.append(Engine.Wheel(position: 0, width: 1, linear: false, blankZero: false, fromGlyph: -1, toGlyph: -1, blend: 1, fromAbove: true, focus: 1, grow: 1, blurOut: 1, flash: 0, flashUp: true))
1301
+ }
1302
+ buildElements(into: &settledBuffer, wheels: settledWheels, signFactor: engine.settledNegative() ? 1 : 0, animated: false)
1303
+ return settledBuffer.reduce(CGFloat(0)) { $0 + $1.width }
1304
+ }
1305
+
1306
+ /// Formats the target the way it is displayed, for VoiceOver.
1307
+ private func accessibleText() -> String {
1308
+ let fd = format.fractionDigits
1309
+ var digits = ""
1310
+ var power = Int(engine.settledPowerCount()) - 1
1311
+ while power >= 0 {
1312
+ digits += String(engine.targetDigit(Int32(power)))
1313
+ if power > fd, (power - fd) % 3 == 0 {
1314
+ digits += format.groupingSeparator
1315
+ }
1316
+ if fd > 0, power == fd {
1317
+ digits += format.decimalSeparator
1318
+ }
1319
+ power -= 1
1320
+ }
1321
+ return (engine.settledNegative() ? "-" : "") + format.prefix + digits + format.suffix
1322
+ }
1323
+
1324
+ // VoiceOver reads the settled figure when it asks for it, so a value update
1325
+ // (which can come every frame) formats nothing.
1326
+ override var accessibilityLabel: String? {
1327
+ get { engine.hasShownValue() ? accessibleText() : nil }
1328
+ set {}
1329
+ }
1330
+
1331
+ override var accessibilityValue: String? {
1332
+ get { loading ? "Loading" : nil }
1333
+ set {}
1334
+ }
1335
+
1336
+ /// A narrower settled size waiting for the current roll to finish before it is reported.
1337
+ private var pendingSizeReport = false
1338
+
1339
+ private func reportIntrinsicSize() {
1340
+ // The reported size is always the full-size one: with shrink-to-fit the view
1341
+ // keeps its height and the scaled number is centred inside it when drawing.
1342
+ let size = CGSize(width: ceil(settledWidth()), height: fonts.lineHeight)
1343
+ guard abs(size.width - lastReportedSize.width) > 0.01 || abs(size.height - lastReportedSize.height) > 0.01 else {
1344
+ pendingSizeReport = false
1345
+ return
1346
+ }
1347
+ // Growing: report right away so React widens the box before the new digit has
1348
+ // fully appeared (the view is not clipped meanwhile). Shrinking mid-roll: keep
1349
+ // the wider box until the roll has finished, otherwise adjustsFontSizeToFit
1350
+ // would squeeze the still-rolling digits into the smaller box and the whole
1351
+ // amount would visibly shrink and grow back.
1352
+ if lastReportedSize != .zero, size.width < lastReportedSize.width, engine.isRolling() {
1353
+ pendingSizeReport = true
1354
+ return
1355
+ }
1356
+ pendingSizeReport = false
1357
+ // Only a box that hugged the old size will follow the new one.
1358
+ awaitingLayout = lastReportedSize.width > 0 && abs(bounds.width - lastReportedSize.width) <= 1
1359
+ lastReportedSize = size
1360
+ onIntrinsicSizeChange?(size)
1361
+ }
1362
+
1363
+ // MARK: - Rendering (layers)
1364
+
1365
+ /// Renders the current engine state: layers normally, `draw(_:)` while the
1366
+ /// loading glint is showing.
1367
+ private func render() {
1368
+ guard engine.hasShownValue() else {
1369
+ clearSlots()
1370
+ return
1371
+ }
1372
+ let wantBitmap = engine.loadingProgress() > 0
1373
+ if wantBitmap != usesBitmap {
1374
+ usesBitmap = wantBitmap
1375
+ contentLayer.isHidden = wantBitmap
1376
+ if !wantBitmap {
1377
+ layer.contents = nil
1378
+ }
1379
+ }
1380
+ if usesBitmap {
1381
+ setNeedsDisplay()
1382
+ } else {
1383
+ renderLayers()
1384
+ }
1385
+ }
1386
+
1387
+ private func clearSlots() {
1388
+ for slot in slots {
1389
+ slot.layer.removeFromSuperlayer()
1390
+ slot.overlay?.removeFromSuperlayer()
1391
+ }
1392
+ slots = []
1393
+ }
1394
+
1395
+ private func renderLayers() {
1396
+ let fonts = self.fonts
1397
+ for slot in 0..<leavingText.count where leavingText[slot] != nil && !engine.textChange(Int32(slot)).active {
1398
+ leavingText[slot] = nil
1399
+ }
1400
+ syncWheels()
1401
+ buildElements(into: &elementBuffer, wheels: wheelBuffer, signFactor: engine.signFactor())
1402
+ let wheels = wheelBuffer
1403
+ let elements = elementBuffer
1404
+ let total = elements.reduce(CGFloat(0)) { $0 + $1.width }
1405
+ updateFontScale(contentWidth: total)
1406
+ let placement = contentPlacement(total: total, lineHeight: fonts.lineHeight)
1407
+
1408
+ let contentBounds = CGRect(x: 0, y: 0, width: max(total, 1), height: fonts.lineHeight)
1409
+ if contentLayer.bounds != contentBounds { contentLayer.bounds = contentBounds }
1410
+ if contentLayer.position != placement.origin { contentLayer.position = placement.origin }
1411
+ let contentTransform = placement.scale == 1 ? CATransform3DIdentity : CATransform3DMakeScale(placement.scale, placement.scale, 1)
1412
+ if !CATransform3DEqualToTransform(contentLayer.transform, contentTransform) { contentLayer.transform = contentTransform }
1413
+
1414
+ syncSlots(with: elements, wheels: wheels, fonts: fonts)
1415
+
1416
+ var x: CGFloat = 0
1417
+ for (i, element) in elements.enumerated() {
1418
+ let slot = slots[i]
1419
+ let frame = CGRect(x: x, y: 0, width: element.width, height: fonts.lineHeight)
1420
+ // The mask: the cell, widened on its far side to the whole glyph. A cell
1421
+ // still opening or closing is not cut to its width (the glyph read as a
1422
+ // sliver of its right edge, a ")" of a 0 rolling past); the glyph
1423
+ // overhangs, faded (`openingOpacity`). Vertically it is the roll's window.
1424
+ let mask = CGRect(x: x + element.width - element.fullWidth, y: 0, width: element.fullWidth, height: fonts.lineHeight)
1425
+ if slot.frame != mask {
1426
+ slot.layer.frame = mask
1427
+ slot.overlay?.frame = frame
1428
+ slots[i].frame = mask
1429
+ }
1430
+ switch element.kind {
1431
+ case .wheel(let index):
1432
+ let wheel = wheels[index]
1433
+ let opacity = Self.openingOpacity(wheel.width)
1434
+ if slot.opacity != opacity {
1435
+ slot.layer.opacity = opacity
1436
+ slot.overlay?.opacity = Float(wheel.width)
1437
+ slots[i].opacity = opacity
1438
+ }
1439
+ let strip = slot.inner
1440
+ let swapping = wheel.blend < 1 || wheel.focus < 1 || wheel.grow < 1
1441
+ let tint = wheel.flash > 0.002 ? (wheel.flashUp ? flash.upColor : flash.downColor) : nil
1442
+ // While the glyphs swap, the strip stays put underneath, hidden.
1443
+ if swapping {
1444
+ let swap: SwapLayers
1445
+ if let existing = slot.swap {
1446
+ swap = existing
1447
+ } else {
1448
+ swap = SwapLayers(scale: fonts.renderScale)
1449
+ // Above every container, unclipped, so the blur's haze stays whole.
1450
+ let overlay = QuietLayer()
1451
+ overlay.frame = frame
1452
+ overlay.opacity = Float(wheel.width)
1453
+ for layer in swap.all { overlay.addSublayer(layer) }
1454
+ contentLayer.addSublayer(overlay)
1455
+ slots[i].overlay = overlay
1456
+ slots[i].swap = swap
1457
+ }
1458
+ layoutSwap(swap, wheel: wheel, fonts: fonts, cellWidth: element.width, tint: tint, flash: CGFloat(wheel.flash))
1459
+ } else if let swap = slot.swap, !swap.hidden {
1460
+ for layer in swap.all { layer.isHidden = true }
1461
+ swap.hidden = true
1462
+ }
1463
+ if strip.isHidden != swapping { strip.isHidden = swapping }
1464
+ if slot.blankZero != wheel.blankZero {
1465
+ strip.contents = fonts.strip(blankZero: wheel.blankZero)?.cgImage
1466
+ slots[i].blankZero = wheel.blankZero
1467
+ }
1468
+ // Linear strips run from -1 (blank) to 9; a roll can be any real, so wrap it onto 0..<10.
1469
+ let position = wheel.linear ? wheel.position : Self.wrap10(wheel.position)
1470
+ let stripFrame = CGRect(
1471
+ x: element.fullWidth - fonts.digitWidth,
1472
+ y: -(position + 1) * fonts.lineHeight,
1473
+ width: strip.bounds.width,
1474
+ height: strip.bounds.height
1475
+ )
1476
+ if slot.innerFrame != stripFrame {
1477
+ strip.frame = stripFrame
1478
+ slots[i].innerFrame = stripFrame
1479
+ }
1480
+ layoutFlash(slotIndex: i, wheel: wheel, tint: swapping ? nil : tint, fonts: fonts, stripFrame: stripFrame)
1481
+ case .glyph(let text, let role):
1482
+ if let from = element.fromText {
1483
+ // Swapping its text: the overlay's pair of pairs instead of the image.
1484
+ if !slot.layer.isHidden { slot.layer.isHidden = true }
1485
+ let swap: TextSwapLayers
1486
+ if let existing = slot.textSwap {
1487
+ swap = existing
1488
+ } else {
1489
+ swap = TextSwapLayers(scale: fonts.renderScale)
1490
+ let overlay = QuietLayer()
1491
+ overlay.frame = frame
1492
+ for layer in swap.all { overlay.addSublayer(layer) }
1493
+ contentLayer.addSublayer(overlay)
1494
+ slots[i].overlay = overlay
1495
+ slots[i].textSwap = swap
1496
+ }
1497
+ layoutTextSwap(swap, element: element, from: from, to: text, role: role, fonts: fonts)
1498
+ x += element.width
1499
+ continue
1500
+ }
1501
+ if slot.layer.isHidden { slot.layer.isHidden = false }
1502
+ if let swap = slot.textSwap, !swap.hidden {
1503
+ for layer in swap.all { layer.isHidden = true }
1504
+ swap.hidden = true
1505
+ }
1506
+ let opacity = Self.openingOpacity(element.factor)
1507
+ if slot.opacity != opacity {
1508
+ slot.layer.opacity = opacity
1509
+ slots[i].opacity = opacity
1510
+ }
1511
+ let image = slot.inner
1512
+ let imageFrame = CGRect(
1513
+ x: 0,
1514
+ y: slot.glyphTop,
1515
+ width: image.bounds.width,
1516
+ height: image.bounds.height
1517
+ )
1518
+ if slot.innerFrame != imageFrame {
1519
+ image.frame = imageFrame
1520
+ slots[i].innerFrame = imageFrame
1521
+ }
1522
+ }
1523
+ x += element.width
1524
+ }
1525
+ }
1526
+
1527
+ /// Opacity of a cell `width` open (0…1). Squared, so while a glyph
1528
+ /// overhangs a narrow cell the overlap stays faint.
1529
+ static func openingOpacity(_ width: Double) -> Float {
1530
+ let w = max(0, min(1, width))
1531
+ return Float(w * w)
1532
+ }
1533
+
1534
+ // The numeric transition's geometry, in line heights; mirrors
1535
+ // `RollingEngine::kNumeric*`, where the effect is described.
1536
+ static let numericOffset: CGFloat = 0.34
1537
+ static let numericScale: CGFloat = 0.4
1538
+ /// The blur radius at full blur, in line heights: SwiftUI's own.
1539
+ static let numericBlur: CGFloat = 0.08
1540
+ /// Blurred copies per digit, from a touch of blur to the full one.
1541
+ static let numericBlurLevels = 6
1542
+
1543
+ /// Places the leaving and the arriving glyph of a swapping wheel for this
1544
+ /// frame: each scaled about its centre, offset along the axis, faded, and
1545
+ /// cross-faded with its blurred image as it goes out of, or comes into,
1546
+ /// focus. With a change flash on (`tint`), the same two again in the tint
1547
+ /// at `flash` of their opacity, over them: the ink mixed towards the tint.
1548
+ private func layoutSwap(_ swap: SwapLayers, wheel: Engine.Wheel, fonts: FontSet, cellWidth: CGFloat, tint: UIColor?, flash: CGFloat) {
1549
+ // The position clock overshoots 1 (a spring); only the offsets follow it there.
1550
+ let b = CGFloat(wheel.blend)
1551
+ let g = max(0, min(1, CGFloat(wheel.grow)))
1552
+ let f = max(0, min(1, CGFloat(wheel.focus)))
1553
+ let d: CGFloat = wheel.fromAbove ? 1 : -1
1554
+ let offset = fonts.lineHeight * Self.numericOffset
1555
+ // The digit column is right-aligned in its cell (the cell shrinks and grows from the left).
1556
+ let center = CGPoint(x: cellWidth - fonts.digitWidth / 2, y: fonts.lineHeight / 2)
1557
+ let outGlyph = Int(wheel.fromGlyph)
1558
+ let outCenter = CGPoint(x: center.x, y: center.y + d * offset * b)
1559
+ let outScale = 1 - (1 - Self.numericScale) * g
1560
+ let outAlpha = 1 - g
1561
+ let outBlur = max(0, min(1, CGFloat(wheel.blurOut)))
1562
+ let inGlyph = Int(wheel.toGlyph)
1563
+ let inCenter = CGPoint(x: center.x, y: center.y - d * offset * (1 - b))
1564
+ let inScale = Self.numericScale + (1 - Self.numericScale) * g
1565
+ let inAlpha = g
1566
+ let inBlur = 1 - f
1567
+ placeSwapGlyph(swap.leaving, glyph: outGlyph, fonts: fonts, tint: nil, center: outCenter, scale: outScale, alpha: outAlpha, blur: outBlur)
1568
+ placeSwapGlyph(swap.arriving, glyph: inGlyph, fonts: fonts, tint: nil, center: inCenter, scale: inScale, alpha: inAlpha, blur: inBlur)
1569
+ let tintAlpha = tint == nil ? 0 : flash
1570
+ placeSwapGlyph(swap.leavingTint, glyph: outGlyph, fonts: fonts, tint: tint, center: outCenter, scale: outScale, alpha: outAlpha * tintAlpha, blur: outBlur)
1571
+ placeSwapGlyph(swap.arrivingTint, glyph: inGlyph, fonts: fonts, tint: tint, center: inCenter, scale: inScale, alpha: inAlpha * tintAlpha, blur: inBlur)
1572
+ swap.hidden = false
1573
+ }
1574
+
1575
+ /// A prefix, suffix or separator changing its text, drawn like a swapping
1576
+ /// digit without the travel: the old text blurs and fades out as the new
1577
+ /// one comes into focus, each kept to the side of the cell that faces the
1578
+ /// digits (a separator centred).
1579
+ private func layoutTextSwap(_ swap: TextSwapLayers, element: Element, from: String, to: String, role: GlyphRole, fonts: FontSet) {
1580
+ let change = engine.textChange(Int32(element.slot))
1581
+ let g = CGFloat(max(0, min(1, change.grow)))
1582
+ let opening = CGFloat(Self.openingOpacity(element.factor))
1583
+ func left(_ text: String) -> CGFloat {
1584
+ let width = fonts.width(of: text, role: role)
1585
+ switch element.anchor {
1586
+ case -1: return 0
1587
+ case 0: return (element.width - width) / 2
1588
+ default: return element.width - width
1589
+ }
1590
+ }
1591
+ placeTextGlyph(swap.leaving, text: from, role: role, fonts: fonts, left: left(from), alpha: (1 - g) * opening, blur: CGFloat(change.blurOut))
1592
+ placeTextGlyph(swap.arriving, text: to, role: role, fonts: fonts, left: left(to), alpha: g * opening, blur: 1 - CGFloat(change.focus))
1593
+ swap.hidden = false
1594
+ }
1595
+
1596
+ /// One text of a text swap, its left edge at `left` in the cell: the two
1597
+ /// blur levels nearest `amount`, cross-faded as `placeSwapGlyph` does.
1598
+ private func placeTextGlyph(_ pair: (GlyphLayer, GlyphLayer), text: String, role: GlyphRole, fonts: FontSet, left: CGFloat, alpha: CGFloat, blur amount: CGFloat) {
1599
+ guard !text.isEmpty, alpha > 0.002, let sharp = fonts.image(text, role: role) else {
1600
+ if !pair.0.layer.isHidden { pair.0.layer.isHidden = true }
1601
+ if !pair.1.layer.isHidden { pair.1.layer.isHidden = true }
1602
+ return
1603
+ }
1604
+ let levels = Self.numericBlurLevels
1605
+ let x = max(0, min(1, amount)) * CGFloat(levels)
1606
+ let lo = min(levels, Int(floor(x)))
1607
+ let hi = min(levels, lo + 1)
1608
+ let w = lo == levels ? 0 : x - CGFloat(lo)
1609
+ let hiAlpha = alpha * w
1610
+ let loAlpha = hiAlpha >= 0.999 ? 0 : alpha * (1 - w) / (1 - hiAlpha)
1611
+ // Blurred images are padded evenly, so each shares the sharp one's centre.
1612
+ let center = CGPoint(x: left + sharp.size.width / 2, y: fonts.top(for: role, text: text, lineTop: 0) + sharp.size.height / 2)
1613
+ // A local function, not a loop over an array literal: that allocated an array per call.
1614
+ func place(_ slot: GlyphLayer, _ level: Int, _ layerAlpha: CGFloat) {
1615
+ let layer = slot.layer
1616
+ let hidden = layerAlpha <= 0.002
1617
+ if layer.isHidden != hidden { layer.isHidden = hidden }
1618
+ if hidden { return }
1619
+ if slot.text != text || slot.level != level {
1620
+ if let image = fonts.blurredImage(text, role: role, level: level) {
1621
+ layer.contents = image.cgImage
1622
+ layer.bounds = CGRect(origin: .zero, size: image.size)
1623
+ }
1624
+ slot.text = text
1625
+ slot.level = level
1626
+ }
1627
+ layer.position = center
1628
+ layer.opacity = Float(layerAlpha)
1629
+ }
1630
+ place(pair.0, lo, loAlpha)
1631
+ place(pair.1, hi, hiAlpha)
1632
+ }
1633
+
1634
+ /// Places one glyph of a swap: the two blur levels nearest `amount` (of
1635
+ /// `numericBlurLevels`, level 0 sharp), cross-faded by where between them
1636
+ /// it falls, so a glyph half out of focus is half-blurred rather than a
1637
+ /// sharp glyph half-hidden in a fully blurred one.
1638
+ private func placeSwapGlyph(_ pair: (GlyphLayer, GlyphLayer), glyph: Int, fonts: FontSet, tint: UIColor?, center: CGPoint, scale: CGFloat, alpha: CGFloat, blur amount: CGFloat) {
1639
+ guard glyph >= 0, alpha > 0.002 else {
1640
+ if !pair.0.layer.isHidden { pair.0.layer.isHidden = true }
1641
+ if !pair.1.layer.isHidden { pair.1.layer.isHidden = true }
1642
+ return
1643
+ }
1644
+ let levels = Self.numericBlurLevels
1645
+ let x = max(0, min(1, amount)) * CGFloat(levels)
1646
+ let lo = min(levels, Int(floor(x)))
1647
+ let hi = min(levels, lo + 1)
1648
+ let w = lo == levels ? 0 : x - CGFloat(lo)
1649
+ // The two levels composite "over", which is not additive: at (1 - w) and
1650
+ // w they came out only 75 % opaque half way between levels, and the
1651
+ // digit pulsed paler and darker at every level crossing. The upper one
1652
+ // gets its share, w, of the opacity and the lower one whatever makes the
1653
+ // pair composite to the whole of it.
1654
+ let hiAlpha = alpha * w
1655
+ let loAlpha = hiAlpha >= 0.999 ? 0 : alpha * (1 - w) / (1 - hiAlpha)
1656
+ let tintKey = tint.map { FontSet.key(of: $0) } ?? 0
1657
+ let text = Self.digitStrings[glyph % 10]
1658
+ let transform = CATransform3DMakeScale(scale, scale, 1)
1659
+ // A local function, not a loop over an array literal: that allocated an array per call.
1660
+ func place(_ slot: GlyphLayer, _ level: Int, _ layerAlpha: CGFloat) {
1661
+ let layer = slot.layer
1662
+ let hidden = layerAlpha <= 0.002
1663
+ if layer.isHidden != hidden { layer.isHidden = hidden }
1664
+ if hidden { return }
1665
+ if slot.glyph != glyph || slot.level != level || slot.tint != tintKey {
1666
+ if let image = fonts.swapImage(text, level: level, tint: tint) {
1667
+ layer.contents = image.cgImage
1668
+ layer.bounds = CGRect(origin: .zero, size: image.size)
1669
+ }
1670
+ slot.glyph = glyph
1671
+ slot.level = level
1672
+ slot.tint = tintKey
1673
+ }
1674
+ layer.position = center
1675
+ layer.transform = transform
1676
+ layer.opacity = Float(layerAlpha)
1677
+ }
1678
+ place(pair.0, lo, loAlpha)
1679
+ place(pair.1, hi, hiAlpha)
1680
+ }
1681
+
1682
+ /// The change flash of a wheel that is not swapping (at rest, or rolling):
1683
+ /// a tinted copy of its strip at the strip's own offset, in the up or the
1684
+ /// down colour at the flash's opacity, so the tint rides the roll instead
1685
+ /// of hovering over it. A swapping wheel's flash is its swap layers' tinted
1686
+ /// twins (`layoutSwap`), so `tint` is nil for it.
1687
+ private func layoutFlash(slotIndex i: Int, wheel: Engine.Wheel, tint: UIColor?, fonts: FontSet, stripFrame: CGRect) {
1688
+ guard let tint, !stripFrame.isNull else {
1689
+ if let layer = slots[i].flashLayer, !layer.isHidden { layer.isHidden = true }
1690
+ return
1691
+ }
1692
+ let layer: CALayer
1693
+ if let existing = slots[i].flashLayer {
1694
+ layer = existing
1695
+ } else {
1696
+ layer = QuietLayer()
1697
+ layer.contentsScale = fonts.renderScale
1698
+ slots[i].layer.addSublayer(layer)
1699
+ slots[i].flashLayer = layer
1700
+ }
1701
+ let tintKey = FontSet.key(of: tint)
1702
+ // The strip's own tinted twin, keyed as a glyph the digits can never be.
1703
+ let stripGlyph = 100 + (wheel.blankZero ? 1 : 0)
1704
+ if slots[i].flashGlyph != stripGlyph || slots[i].flashTint != tintKey {
1705
+ guard let image = fonts.tintedStrip(blankZero: wheel.blankZero, tint: tint) else { return }
1706
+ layer.contents = image.cgImage
1707
+ slots[i].flashGlyph = stripGlyph
1708
+ slots[i].flashTint = tintKey
1709
+ }
1710
+ layer.frame = stripFrame
1711
+ layer.opacity = Float(CGFloat(wheel.flash) * CGFloat(wheel.width))
1712
+ if layer.isHidden { layer.isHidden = false }
1713
+ }
1714
+
1715
+ /// Makes `slots` match `elements` one to one; layers are only rebuilt when
1716
+ /// the element kinds change (a wheel appearing or disappearing).
1717
+ private func syncSlots(with elements: [Element], wheels: [Engine.Wheel], fonts: FontSet) {
1718
+ if slotsMatch(elements) { return }
1719
+ clearSlots()
1720
+ slots.reserveCapacity(elements.count)
1721
+ for element in elements {
1722
+ let container = QuietLayer()
1723
+ container.masksToBounds = true
1724
+ let inner = QuietLayer()
1725
+ inner.contentsScale = fonts.renderScale
1726
+ switch element.kind {
1727
+ case .wheel(let index):
1728
+ let blankZero = wheels[index].blankZero
1729
+ if let strip = fonts.strip(blankZero: blankZero) {
1730
+ inner.contents = strip.cgImage
1731
+ inner.bounds = CGRect(origin: .zero, size: strip.size)
1732
+ }
1733
+ container.addSublayer(inner)
1734
+ contentLayer.addSublayer(container)
1735
+ slots.append(ElementLayer(kind: .wheel, layer: container, inner: inner, blankZero: blankZero, glyphTop: 0))
1736
+ case .glyph(let text, let role):
1737
+ if let image = fonts.image(text, role: role) {
1738
+ inner.contents = image.cgImage
1739
+ inner.bounds = CGRect(origin: .zero, size: image.size)
1740
+ }
1741
+ container.addSublayer(inner)
1742
+ contentLayer.addSublayer(container)
1743
+ slots.append(ElementLayer(kind: .glyph(text, role), layer: container, inner: inner, blankZero: false, glyphTop: fonts.top(for: role, text: text, lineTop: 0)))
1744
+ }
1745
+ }
1746
+ }
1747
+
1748
+ /// Whether the layers already match `elements` one to one. Compared in
1749
+ /// place: this runs every frame, so it builds nothing to compare.
1750
+ private func slotsMatch(_ elements: [Element]) -> Bool {
1751
+ guard elements.count == slots.count else { return false }
1752
+ for index in elements.indices {
1753
+ switch (elements[index].kind, slots[index].kind) {
1754
+ case (.wheel, .wheel):
1755
+ continue
1756
+ case (.glyph(let text, let role), .glyph(let slotText, let slotRole)) where text == slotText && role == slotRole:
1757
+ continue
1758
+ default:
1759
+ return false
1760
+ }
1761
+ }
1762
+ return true
1763
+ }
1764
+
1765
+ private static func wrap10(_ position: Double) -> Double {
1766
+ let r = fmod(position, 10)
1767
+ return r < 0 ? r + 10 : r
1768
+ }
1769
+
1770
+ /// Where the content box (`total` × `lineHeight`, in font space) goes and how
1771
+ /// it is scaled: the shrink-to-fit scale, aligned in the bounds, times the
1772
+ /// reveal's landing pop about the content's centre.
1773
+ private func contentPlacement(total: CGFloat, lineHeight: CGFloat) -> (origin: CGPoint, scale: CGFloat) {
1774
+ let fit = fontScale
1775
+ let originX: CGFloat
1776
+ switch resolvedAlignment {
1777
+ case .auto, .left: originX = 0
1778
+ case .center: originX = (bounds.width - total * fit) / 2
1779
+ case .right: originX = bounds.width - total * fit
1780
+ }
1781
+ let originY = (bounds.height - lineHeight * fit) / 2
1782
+ let pop = CGFloat(engine.revealScale())
1783
+ guard pop != 1 else { return (CGPoint(x: originX, y: originY), fit) }
1784
+ return (
1785
+ CGPoint(x: originX + total * fit * (1 - pop) / 2, y: originY + lineHeight * fit * (1 - pop) / 2),
1786
+ fit * pop
1787
+ )
1788
+ }
1789
+
1790
+ // MARK: - Drawing (bitmap, loading glint only)
1791
+
1792
+ override func draw(_ rect: CGRect) {
1793
+ guard usesBitmap, engine.hasShownValue(), let ctx = UIGraphicsGetCurrentContext() else { return }
1794
+ let fonts = self.fonts
1795
+ syncWheels()
1796
+ buildElements(into: &elementBuffer, wheels: wheelBuffer, signFactor: engine.signFactor())
1797
+ let wheels = wheelBuffer
1798
+ let elements = elementBuffer
1799
+ let total = elements.reduce(CGFloat(0)) { $0 + $1.width }
1800
+ updateFontScale(contentWidth: total)
1801
+ let placement = contentPlacement(total: total, lineHeight: fonts.lineHeight)
1802
+
1803
+ // Position the (scaled) content, then draw everything in unscaled font space.
1804
+ ctx.saveGState()
1805
+ ctx.translateBy(x: placement.origin.x, y: placement.origin.y)
1806
+ ctx.scaleBy(x: placement.scale, y: placement.scale)
1807
+
1808
+ let dim = CGFloat(min(1, max(0, engine.loadingProgress())))
1809
+ if dim > 0 {
1810
+ // Everything drawn in this layer is what the sweep gets composited onto.
1811
+ ctx.beginTransparencyLayer(auxiliaryInfo: nil)
1812
+ }
1813
+ var x: CGFloat = 0
1814
+ for element in elements {
1815
+ switch element.kind {
1816
+ case .wheel(let index):
1817
+ drawWheel(wheels[index], fonts: fonts, x: x, width: element.width, ctx: ctx)
1818
+ case .glyph(let text, let role):
1819
+ drawGlyph(text, role: role, fonts: fonts, x: x, width: element.width, fullWidth: element.fullWidth, alpha: element.factor, ctx: ctx)
1820
+ }
1821
+ x += element.width
1822
+ }
1823
+ if dim > 0 {
1824
+ drawShimmer(contentWidth: total, dim: dim, ctx: ctx)
1825
+ ctx.endTransparencyLayer()
1826
+ }
1827
+ ctx.restoreGState()
1828
+ }
1829
+
1830
+ /// A "shine" glint: a text-wide, slanted band that recolors the ink from the
1831
+ /// text color to the highlight and back (`[base, highlight, base]` at
1832
+ /// 10/50/90 %), composited source-atop so only the glyphs light up.
1833
+ private func drawShimmer(contentWidth: CGFloat, dim: CGFloat, ctx: CGContext) {
1834
+ guard contentWidth > 0 else { return }
1835
+ var br: CGFloat = 0, bg: CGFloat = 0, bb: CGFloat = 0, ba: CGFloat = 1
1836
+ typography.color.getRed(&br, green: &bg, blue: &bb, alpha: &ba)
1837
+ var hr: CGFloat = 0, hg: CGFloat = 0, hb: CGFloat = 0, ha: CGFloat = 1
1838
+ (shimmer.color ?? Self.defaultShimmerColor).getRed(&hr, green: &hg, blue: &hb, alpha: &ha)
1839
+ let base = CGColor(red: br, green: bg, blue: bb, alpha: ba)
1840
+ let colors = [base, CGColor(red: hr, green: hg, blue: hb, alpha: ha), base] as CFArray
1841
+ guard let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: colors, locations: [0.1, 0.5, 0.9]) else { return }
1842
+ let phase = CGFloat(engine.shimmerPhase(CACurrentMediaTime(), shimmer.duration))
1843
+ let progress = Self.shimmerSeed + (1 - Self.shimmerSeed) * phase
1844
+ // Core at width * (2p - 0.5): enters at the left edge, exits past the right.
1845
+ let startX = contentWidth * (2 * progress - 1)
1846
+ ctx.saveGState()
1847
+ ctx.setBlendMode(.sourceAtop)
1848
+ ctx.setAlpha(dim)
1849
+ ctx.drawLinearGradient(
1850
+ gradient,
1851
+ start: CGPoint(x: startX, y: 0),
1852
+ end: CGPoint(x: startX + contentWidth, y: Self.shimmerSlant * contentWidth),
1853
+ options: [.drawsBeforeStartLocation, .drawsAfterEndLocation]
1854
+ )
1855
+ ctx.restoreGState()
1856
+ }
1857
+
1858
+ private func drawGlyph(_ text: String, role: GlyphRole, fonts: FontSet, x: CGFloat, width: CGFloat, fullWidth: CGFloat, alpha: Double, ctx: CGContext) {
1859
+ guard width > 0 else { return }
1860
+ ctx.saveGState()
1861
+ // Whole against the text it joins while its cell opens, faded; see `renderLayers`.
1862
+ ctx.clip(to: CGRect(x: x + width - fullWidth, y: 0, width: fullWidth, height: fonts.lineHeight))
1863
+ ctx.setAlpha(CGFloat(Self.openingOpacity(alpha)))
1864
+ fonts.image(text, role: role)?.draw(at: CGPoint(x: x + width - fullWidth, y: fonts.top(for: role, text: text, lineTop: 0)))
1865
+ ctx.restoreGState()
1866
+ }
1867
+
1868
+ private func drawWheel(_ wheel: Engine.Wheel, fonts: FontSet, x: CGFloat, width: CGFloat, ctx: CGContext) {
1869
+ guard width > 0 else { return }
1870
+ let lineHeight = fonts.lineHeight
1871
+ ctx.saveGState()
1872
+ // The roll's window, the whole digit wide (see `renderLayers`).
1873
+ ctx.clip(to: CGRect(x: x + width - fonts.digitWidth, y: 0, width: fonts.digitWidth, height: lineHeight))
1874
+ ctx.setAlpha(CGFloat(Self.openingOpacity(wheel.width)))
1875
+ if wheel.blend < 1 || wheel.focus < 1 || wheel.grow < 1 {
1876
+ // The numeric transition under the glint: the pair, without the blur.
1877
+ let b = CGFloat(wheel.blend)
1878
+ let g = max(0, min(1, CGFloat(wheel.grow)))
1879
+ let d: CGFloat = wheel.fromAbove ? 1 : -1
1880
+ let offset = lineHeight * Self.numericOffset
1881
+ let cx = x + width - fonts.digitWidth / 2
1882
+ let pair: [(glyph: Int, dy: CGFloat, scale: CGFloat, alpha: CGFloat)] = [
1883
+ (Int(wheel.fromGlyph), d * offset * b, 1 - (1 - Self.numericScale) * g, 1 - g),
1884
+ (Int(wheel.toGlyph), -d * offset * (1 - b), Self.numericScale + (1 - Self.numericScale) * g, g),
1885
+ ]
1886
+ for item in pair where item.glyph >= 0 && item.alpha > 0.002 {
1887
+ guard let image = fonts.image(Self.digitStrings[item.glyph % 10], role: .digit) else { continue }
1888
+ ctx.saveGState()
1889
+ ctx.setAlpha(CGFloat(wheel.width) * item.alpha)
1890
+ ctx.translateBy(x: cx, y: lineHeight / 2 + item.dy)
1891
+ ctx.scaleBy(x: item.scale, y: item.scale)
1892
+ image.draw(at: CGPoint(x: -image.size.width / 2, y: -image.size.height / 2))
1893
+ ctx.restoreGState()
1894
+ }
1895
+ ctx.restoreGState()
1896
+ return
1897
+ }
1898
+ let base = wheel.position.rounded(.down)
1899
+ let fraction = CGFloat(wheel.position - base)
1900
+ let index = Int(base)
1901
+ let columnLeft = x + width - fonts.digitWidth
1902
+ if let text = digitText(at: index, in: wheel), let image = fonts.image(text, role: .digit) {
1903
+ image.draw(at: CGPoint(x: columnLeft + (fonts.digitWidth - fonts.width(of: text, role: .digit)) / 2, y: -fraction * lineHeight))
1904
+ }
1905
+ if fraction > 0.0001, let text = digitText(at: index + 1, in: wheel), let image = fonts.image(text, role: .digit) {
1906
+ image.draw(at: CGPoint(x: columnLeft + (fonts.digitWidth - fonts.width(of: text, role: .digit)) / 2, y: (1 - fraction) * lineHeight))
1907
+ }
1908
+ ctx.restoreGState()
1909
+ }
1910
+
1911
+ private static let digitStrings = (0...9).map { String($0) }
1912
+
1913
+ private func digitText(at index: Int, in wheel: Engine.Wheel) -> String? {
1914
+ if wheel.linear && index < 0 { return nil }
1915
+ if wheel.blankZero && index == 0 { return nil }
1916
+ return Self.digitStrings[((index % 10) + 10) % 10]
1917
+ }
1918
+ }
1919
+
1920
+ /// A layer that never animates a change implicitly: every layer of a
1921
+ /// NitroNumber, and of a reflowing NitroInput, is placed frame by frame, by
1922
+ /// the engine. Switching the actions off with an explicit `CATransaction` did
1923
+ /// the same, but a display link's callback runs outside any transaction, so
1924
+ /// each view's frame was a commit of its own to the render server, dozens per
1925
+ /// frame on a busy screen; these changes join the run loop's one implicit
1926
+ /// transaction instead.
1927
+ final class QuietLayer: CALayer {
1928
+ override func action(forKey event: String) -> CAAction? { nil }
1929
+ }
1930
+
1931
+ /// `QuietLayer`'s gradient: NitroInput's edge fade is re-laid out with the text.
1932
+ final class QuietGradientLayer: CAGradientLayer {
1933
+ override func action(forKey event: String) -> CAAction? { nil }
1934
+ }