react-native-nitro-input 0.1.0 → 0.3.0

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