nitro-ui-macos 0.0.0 → 0.0.2

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 (128) hide show
  1. package/CONTRIBUTING.md +49 -0
  2. package/LICENSE +4 -3
  3. package/PARITY.md +373 -0
  4. package/README.md +144 -5
  5. package/native/nitro-core/Package.swift +78 -0
  6. package/native/nitro-ui-core/Package.swift +112 -0
  7. package/native/nitro-ui-core/Sources/NitroUICoreMac/AnimationFrameDisplayLink.swift +127 -0
  8. package/native/nitro-ui-core/Sources/NitroUICoreMac/HybridAnimationFrameScheduler.swift +91 -0
  9. package/native/nitro-ui-core/Sources/NitroUICoreMac/HybridLinking.swift +18 -0
  10. package/native/nitro-ui-dev/Package.swift +102 -0
  11. package/native/nitro-ui-dev/Sources/NitroUIDevMac/DevBundleLoad.swift +14 -0
  12. package/native/nitro-ui-dev/Sources/NitroUIDevMac/DevBundleLoader.swift +85 -0
  13. package/native/nitro-ui-dev/Sources/NitroUIDevMac/DevLauncher.swift +192 -0
  14. package/native/nitro-ui-dev/Sources/NitroUIDevMac/DevMenu.swift +172 -0
  15. package/native/nitro-ui-dev/Sources/NitroUIDevMac/DevServerBrowser.swift +86 -0
  16. package/native/nitro-ui-dev/Sources/NitroUIDevMac/DevSession.swift +151 -0
  17. package/native/nitro-ui-dev/Sources/NitroUIDevMac/DevShortcuts.swift +85 -0
  18. package/native/nitro-ui-dev/Sources/NitroUIDevMac/DevToast.swift +85 -0
  19. package/native/nitro-ui-dev/Sources/NitroUIDevMac/DevTools.swift +141 -0
  20. package/native/nitro-ui-dev/Sources/NitroUIDevMac/ErrorModels.swift +97 -0
  21. package/native/nitro-ui-dev/Sources/NitroUIDevMac/ErrorOverlay.swift +698 -0
  22. package/native/nitro-ui-dev/Sources/NitroUIDevMac/HybridDevBundles.swift +64 -0
  23. package/native/nitro-ui-dev/Sources/NitroUIDevMac/HybridDevErrors.swift +56 -0
  24. package/native/nitro-ui-dev/Sources/NitroUIDevMac/HybridDevLoadingView.swift +27 -0
  25. package/native/nitro-ui-dev/Sources/NitroUIDevMac/HybridDevMenu.swift +40 -0
  26. package/native/nitro-ui-dev/Sources/NitroUIDevMac/HybridDevToast.swift +19 -0
  27. package/native/nitro-ui-dev/Sources/NitroUIDevMac/LauncherWindowController.swift +217 -0
  28. package/native/nitro-ui-dev/Sources/NitroUIDevMac/LoadingOverlay.swift +104 -0
  29. package/native/nitro-ui-dev/Sources/NitroUIDevMac/RegisterDevLoader.swift +22 -0
  30. package/native/nitro-ui-dev/Sources/NitroUIDevMac/SavedBundles.swift +70 -0
  31. package/native/nitro-ui-glass/Package.swift +103 -0
  32. package/native/nitro-ui-glass/macos/HybridLiquidGlass.swift +5 -0
  33. package/native/nitro-ui-glass/macos/HybridNativeLiquidGlassContainerView.swift +40 -0
  34. package/native/nitro-ui-glass/macos/HybridNativeLiquidGlassView.swift +80 -0
  35. package/native/nitro-ui-glass/macos/LiquidGlassEffectView.swift +181 -0
  36. package/native/nitro-ui-glass/macos/LiquidGlassSupport.swift +17 -0
  37. package/native/nitro-ui-navigation/Package.swift +105 -0
  38. package/native/nitro-ui-navigation/Sources/NitroUINavigationMac/HybridNavigationScreen.swift +199 -0
  39. package/native/nitro-ui-navigation/Sources/NitroUINavigationMac/HybridNavigationSharedElement.swift +17 -0
  40. package/native/nitro-ui-navigation/Sources/NitroUINavigationMac/HybridNavigationSplit.swift +889 -0
  41. package/native/nitro-ui-navigation/Sources/NitroUINavigationMac/HybridNavigationStack.swift +404 -0
  42. package/native/nitro-ui-navigation/Sources/NitroUINavigationMac/HybridNavigationTabs.swift +186 -0
  43. package/native/nitro-ui-navigation/Sources/NitroUINavigationMac/MacStackContainerController.swift +260 -0
  44. package/native/nitro-ui-navigation/Sources/NitroUINavigationMac/NavigationSharedElementView.swift +28 -0
  45. package/native/nitro-ui-renderer/Package.swift +105 -0
  46. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Animations/HybridAnimator.swift +502 -0
  47. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Animations/NitroAnimationContext.swift +54 -0
  48. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Animations/View+Animations.swift +35 -0
  49. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/AssetFonts.swift +36 -0
  50. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/FlippedView.swift +360 -0
  51. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/HybridContainerView.swift +28 -0
  52. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/HybridFonts.swift +7 -0
  53. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/HybridLabel.swift +127 -0
  54. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/HybridMaskedView.swift +185 -0
  55. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/HybridScrollView.swift +255 -0
  56. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/HybridScrollViewContent.swift +22 -0
  57. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/HybridView.swift +18 -0
  58. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/Image/HybridImage.swift +281 -0
  59. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/Image/HybridImageFactory.swift +132 -0
  60. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/Image/HybridImageLoader.swift +149 -0
  61. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/Image/HybridImageView.swift +601 -0
  62. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/Image/ImagePixelSupport.swift +418 -0
  63. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/LabelView.swift +198 -0
  64. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/List/HybridListView.swift +177 -0
  65. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/List/NativeListCell.swift +98 -0
  66. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/List/NativeListContentView.swift +12 -0
  67. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/List/NativeListFenwickTree.swift +94 -0
  68. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/List/NativeListScrollView.swift +1100 -0
  69. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/List/NativeListSnapshot.swift +24 -0
  70. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/List/NativeListUpdate.swift +11 -0
  71. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/List/NativeListView.swift +260 -0
  72. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/NativeContainerView.swift +443 -0
  73. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/NitroViewProtocols.swift +275 -0
  74. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/ShadowLayers.swift +338 -0
  75. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/TextInput/HybridTextInput.swift +252 -0
  76. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/TextInput/NitroTextInputView.swift +447 -0
  77. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/View.swift +660 -0
  78. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/CustomViewController.swift +254 -0
  79. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/DesktopHostDelegate.swift +14 -0
  80. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Extensions.swift +102 -0
  81. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Gestures/GestureRecognizerDelegate.swift +24 -0
  82. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Gestures/HybridGestureRecognizer.swift +41 -0
  83. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Gestures/HybridLongPressGestureRecognizer.swift +172 -0
  84. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Gestures/HybridPanGestureRecognizer.swift +193 -0
  85. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Gestures/HybridTapGestureRecognizer.swift +165 -0
  86. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/HybridAppearance.swift +75 -0
  87. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/HybridApplication.swift +29 -0
  88. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/HybridKeyboard.swift +26 -0
  89. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/HybridScreen.swift +29 -0
  90. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/HybridViewController.swift +232 -0
  91. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/HybridWindow.swift +61 -0
  92. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/HybridWindowScene.swift +17 -0
  93. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/LayoutNode.swift +73 -0
  94. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/NSColor+rgba.swift +29 -0
  95. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/RegisterRootCallback.swift +27 -0
  96. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/RuntimeReloadableAppDelegate.swift +7 -0
  97. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/SafeAreaInsetsListeners.swift +26 -0
  98. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/SizeListeners.swift +27 -0
  99. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/UIErrorHandler.swift +15 -0
  100. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/ViewController.swift +6 -0
  101. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Window.swift +156 -0
  102. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/WindowScene.swift +23 -0
  103. package/native/nitro-ui-runtime/Package.swift +67 -0
  104. package/native/nitro-ui-runtime/Sources/NitroUIRuntimeMac/DevLoader.swift +16 -0
  105. package/native/nitro-ui-runtime/Sources/NitroUIRuntimeMac/NitroUIAppDelegate.swift +253 -0
  106. package/package.json +59 -8
  107. package/src/Platform.ts +43 -0
  108. package/src/bin.js +18 -0
  109. package/src/build.ts +453 -0
  110. package/src/bundleWorker.ts +80 -0
  111. package/src/cli.ts +157 -0
  112. package/src/config.ts +233 -0
  113. package/src/create.ts +67 -0
  114. package/src/files.ts +70 -0
  115. package/src/index.ts +1 -0
  116. package/src/init.ts +301 -0
  117. package/src/inlinePlatform.ts +140 -0
  118. package/src/modules.ts +385 -0
  119. package/src/packageApp.ts +103 -0
  120. package/src/packageDirectory.ts +61 -0
  121. package/src/preload.ts +40 -0
  122. package/src/prepare.ts +433 -0
  123. package/src/run.ts +41 -0
  124. package/src/runApp.ts +81 -0
  125. package/src/start.ts +152 -0
  126. package/src/toolchain.ts +83 -0
  127. package/src/versions.ts +103 -0
  128. package/templates/AppIcon.icns +0 -0
@@ -0,0 +1,1100 @@
1
+ internal import AppKit
2
+ internal import Foundation
3
+ internal import NitroModules
4
+ internal import QuartzCore
5
+
6
+ final class NativeListDocumentView: FlippedView {
7
+ override var isFlipped: Bool { true }
8
+ }
9
+
10
+ final class NativeListScrollView: NSScrollView, InteractionControllableView, TransformableView {
11
+ private struct MeasuredExtent {
12
+ let extent: Double
13
+ let version: Double
14
+ let crossAxisSize: CGFloat
15
+ }
16
+
17
+ var isUserInteractionEnabled: Bool = true
18
+ var nitroTransform = NitroTransformState()
19
+
20
+ private let docView = NativeListDocumentView(frame: .zero)
21
+ private(set) var isHorizontal = false
22
+ private(set) var crossAxisSize: CGFloat = 0
23
+ private var estimatedItemSize: Double = 44.0
24
+ private var contentPadding = NSEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
25
+ private var anchorId: String?
26
+ private var anchorAlignment: CGFloat = 0
27
+
28
+ private var snapshot: NativeListSnapshot?
29
+ private var fenwick = NativeListFenwickTree()
30
+ private var measuredExtents: [String: MeasuredExtent] = [:]
31
+
32
+ private var activeCells: [Int: NativeListCell] = [:]
33
+ private var reusePools: [String: [NativeListCell]] = [:]
34
+ private var outgoingCells: [NativeListCell] = []
35
+ private var nextCellId = 0.0
36
+
37
+ private var cellRenderer: (any Callback<(Double, any HybridViewSpec, String, Double), Void>)?
38
+ private var onApplied: (any Callback<(), Void>)?
39
+ private var applyGeneration = 0
40
+ private var animationGeneration = 0
41
+
42
+ private weak var bindingCell: NativeListCell?
43
+ private var isSyncingVisibleCells = false
44
+ private var isProgrammaticScroll = false
45
+ private var hasScheduledSizeReposition = false
46
+ private var lastSyncMainOffset: Double = 0
47
+
48
+ private var boundsObserver: NSObjectProtocol?
49
+ private var liveScrollStartObserver: NSObjectProtocol?
50
+ private var liveScrollEndObserver: NSObjectProtocol?
51
+
52
+ var isRefreshControlEnabled = false {
53
+ didSet {
54
+ updateRefreshElasticity()
55
+ if isRefreshControlEnabled == false {
56
+ pullOverscrollDistance = 0
57
+ hasTriggeredRefreshInCurrentGesture = false
58
+ onPullToRefreshProgress?(0)
59
+ }
60
+ }
61
+ }
62
+ var isRefreshing = false {
63
+ didSet {
64
+ if isRefreshing == false {
65
+ hasTriggeredRefreshInCurrentGesture = false
66
+ }
67
+ }
68
+ }
69
+ var onPullToRefreshProgress: ((CGFloat) -> Void)?
70
+ var onPullToRefreshTriggered: (() -> Void)?
71
+
72
+ private var pullOverscrollDistance: CGFloat = 0
73
+ private var hasTriggeredRefreshInCurrentGesture = false
74
+ private static let pullToRefreshThreshold: CGFloat = 120
75
+
76
+ override init(frame frameRect: NSRect) {
77
+ super.init(frame: frameRect)
78
+ let clipView = FlippedClipView(frame: NSRect(origin: .zero, size: frameRect.size))
79
+ clipView.drawsBackground = false
80
+ clipView.postsBoundsChangedNotifications = true
81
+ contentView = clipView
82
+ documentView = docView
83
+
84
+ drawsBackground = false
85
+ borderType = .noBorder
86
+ wantsLayer = true
87
+ scrollerStyle = .overlay
88
+ autohidesScrollers = true
89
+ hasVerticalScroller = true
90
+ hasHorizontalScroller = true
91
+ automaticallyAdjustsContentInsets = false
92
+ usesPredominantAxisScrolling = true
93
+
94
+ boundsObserver = NotificationCenter.default.addObserver(
95
+ forName: NSView.boundsDidChangeNotification,
96
+ object: clipView,
97
+ queue: nil
98
+ ) { [weak self] _ in
99
+ self?.handleClipViewBoundsChanged()
100
+ }
101
+ liveScrollStartObserver = NotificationCenter.default.addObserver(
102
+ forName: NSScrollView.willStartLiveScrollNotification,
103
+ object: self,
104
+ queue: nil
105
+ ) { [weak self] _ in
106
+ guard let self, !self.isProgrammaticScroll else { return }
107
+ self.anchorId = nil
108
+ self.pullOverscrollDistance = 0
109
+ self.hasTriggeredRefreshInCurrentGesture = false
110
+ }
111
+ liveScrollEndObserver = NotificationCenter.default.addObserver(
112
+ forName: NSScrollView.didEndLiveScrollNotification,
113
+ object: self,
114
+ queue: nil
115
+ ) { [weak self] _ in
116
+ guard let self else { return }
117
+ self.pullOverscrollDistance = 0
118
+ self.hasTriggeredRefreshInCurrentGesture = false
119
+ if !self.isRefreshing {
120
+ self.onPullToRefreshProgress?(0)
121
+ }
122
+ }
123
+ }
124
+
125
+ deinit {
126
+ if let boundsObserver {
127
+ NotificationCenter.default.removeObserver(boundsObserver)
128
+ }
129
+ if let liveScrollStartObserver {
130
+ NotificationCenter.default.removeObserver(liveScrollStartObserver)
131
+ }
132
+ if let liveScrollEndObserver {
133
+ NotificationCenter.default.removeObserver(liveScrollEndObserver)
134
+ }
135
+ disposeAllCells()
136
+ }
137
+
138
+ @available(*, unavailable)
139
+ required init?(coder: NSCoder) {
140
+ fatalError("init(coder:) has not been implemented")
141
+ }
142
+
143
+ override var isFlipped: Bool { true }
144
+
145
+ override func setFrameOrigin(_ newOrigin: NSPoint) {
146
+ super.setFrameOrigin(newOrigin)
147
+ applyNitroTransform()
148
+ }
149
+
150
+ override func setFrameSize(_ newSize: NSSize) {
151
+ super.setFrameSize(newSize)
152
+ applyNitroTransform()
153
+ }
154
+
155
+ override func layout() {
156
+ super.layout()
157
+ applyNitroTransform()
158
+ }
159
+
160
+ override func viewDidMoveToSuperview() {
161
+ super.viewDidMoveToSuperview()
162
+ applyNitroTransform()
163
+ }
164
+
165
+ override func viewDidMoveToWindow() {
166
+ super.viewDidMoveToWindow()
167
+ applyNitroTransform()
168
+ }
169
+
170
+ override func viewWillDraw() {
171
+ super.viewWillDraw()
172
+ applyNitroTransform()
173
+ }
174
+
175
+ func applyNitroTransform() {
176
+ if !wantsLayer { wantsLayer = true }
177
+ guard let layer = self.layer else { return }
178
+ let target = nitroTransform.makeCATransform3D(for: bounds.size)
179
+ if !NitroAnimationRegistry.hasActiveAnimation(on: layer, keyPath: "transform"),
180
+ CATransform3DEqualToTransform(layer.transform, target) {
181
+ return
182
+ }
183
+ NitroAnimationContext.performWithoutImplicitAnimations {
184
+ layer.transform = target
185
+ }
186
+ }
187
+
188
+ override func hitTest(_ point: NSPoint) -> NSView? {
189
+ guard isUserInteractionEnabled, !isHidden, alphaValue > 0.01 else {
190
+ return nil
191
+ }
192
+ guard let localPoint = NitroViewGeometry.convertFromSuperview(point, in: self) else {
193
+ return nil
194
+ }
195
+ guard bounds.contains(localPoint) else {
196
+ return nil
197
+ }
198
+ for subview in subviews.reversed() {
199
+ if let hit = subview.hitTest(localPoint) {
200
+ return hit
201
+ }
202
+ }
203
+ return self
204
+ }
205
+
206
+ override func scrollWheel(with event: NSEvent) {
207
+ guard isUserInteractionEnabled else {
208
+ nextResponder?.scrollWheel(with: event)
209
+ return
210
+ }
211
+ let docSize = docView.frame.size
212
+ let visibleSize = contentView.bounds.size
213
+ let canScrollVertically = !isHorizontal && (docSize.height > visibleSize.height + 0.5 || isRefreshControlEnabled)
214
+ let canScrollHorizontally = isHorizontal && docSize.width > visibleSize.width + 0.5
215
+
216
+ let deltaX = event.scrollingDeltaX
217
+ let deltaY = event.scrollingDeltaY
218
+ let verticalDominant = abs(deltaY) >= abs(deltaX)
219
+
220
+ // Forward scroll events along the non-scrollable axis to enclosing scroll views.
221
+ if verticalDominant && !canScrollVertically {
222
+ nextResponder?.scrollWheel(with: event)
223
+ return
224
+ }
225
+ if !verticalDominant && !canScrollHorizontally {
226
+ nextResponder?.scrollWheel(with: event)
227
+ return
228
+ }
229
+
230
+ // Trackpad pull-to-refresh overscroll at top of vertical lists.
231
+ if isRefreshControlEnabled && !isHorizontal && verticalDominant {
232
+ handlePullToRefreshScrollEvent(event, deltaY: deltaY)
233
+ }
234
+
235
+ // For non-trackpad discrete wheel events at a scroll boundary, chain to an outer scroll view.
236
+ if event.phase.isEmpty && event.momentumPhase.isEmpty {
237
+ let origin = contentView.bounds.origin
238
+ if verticalDominant {
239
+ let maxY = max(0, docSize.height - visibleSize.height)
240
+ let allowTopOverscroll = isRefreshControlEnabled && deltaY > 0
241
+ if (!allowTopOverscroll && deltaY > 0 && origin.y <= 0.5) || (deltaY < 0 && origin.y >= maxY - 0.5) {
242
+ nextResponder?.scrollWheel(with: event)
243
+ return
244
+ }
245
+ } else {
246
+ let maxX = max(0, docSize.width - visibleSize.width)
247
+ if (deltaX > 0 && origin.x <= 0.5) || (deltaX < 0 && origin.x >= maxX - 0.5) {
248
+ nextResponder?.scrollWheel(with: event)
249
+ return
250
+ }
251
+ }
252
+ }
253
+
254
+ anchorId = nil
255
+ super.scrollWheel(with: event)
256
+ }
257
+
258
+ private func updateRefreshElasticity() {
259
+ verticalScrollElasticity = (isRefreshControlEnabled && !isHorizontal) ? .allowed : .automatic
260
+ }
261
+
262
+ private func handlePullToRefreshScrollEvent(_ event: NSEvent, deltaY: CGFloat) {
263
+ // Momentum and phaseless wheel events never pull, so a flick to the top doesn't refresh.
264
+ guard !event.phase.isEmpty else { return }
265
+
266
+ if event.phase == .began {
267
+ pullOverscrollDistance = 0
268
+ hasTriggeredRefreshInCurrentGesture = false
269
+ }
270
+
271
+ if event.phase == .ended || event.phase == .cancelled {
272
+ pullOverscrollDistance = 0
273
+ hasTriggeredRefreshInCurrentGesture = false
274
+ if !isRefreshing {
275
+ onPullToRefreshProgress?(0)
276
+ }
277
+ return
278
+ }
279
+
280
+ let atTop = contentView.bounds.origin.y <= 0.5
281
+ if atTop && deltaY > 0 {
282
+ pullOverscrollDistance += deltaY
283
+ evaluatePullOverscroll(pullOverscrollDistance)
284
+ } else if pullOverscrollDistance > 0 {
285
+ pullOverscrollDistance = max(0, pullOverscrollDistance + deltaY)
286
+ if !isRefreshing {
287
+ onPullToRefreshProgress?(min(1, pullOverscrollDistance / Self.pullToRefreshThreshold))
288
+ }
289
+ }
290
+ }
291
+
292
+ private func evaluatePullOverscroll(_ overscroll: CGFloat) {
293
+ let progress = min(1, max(0, overscroll / Self.pullToRefreshThreshold))
294
+ onPullToRefreshProgress?(progress)
295
+ if overscroll >= Self.pullToRefreshThreshold && !isRefreshing && !hasTriggeredRefreshInCurrentGesture {
296
+ hasTriggeredRefreshInCurrentGesture = true
297
+ onPullToRefreshTriggered?()
298
+ }
299
+ }
300
+
301
+ func setHorizontal(_ horizontal: Bool) {
302
+ isHorizontal = horizontal
303
+ updateRefreshElasticity()
304
+ }
305
+
306
+ func setAnchorItemId(_ id: String?, alignment: CGFloat) {
307
+ anchorAlignment = alignment
308
+ anchorId = id
309
+ }
310
+
311
+ func disconnectRenderer() {
312
+ anchorId = nil
313
+ applyGeneration += 1
314
+ animationGeneration += 1
315
+ cellRenderer = nil
316
+ onApplied = nil
317
+ snapshot = nil
318
+ }
319
+
320
+ func updateFrame(_ frame: CGRect, estimatedItemSize: Double, contentPadding: NSEdgeInsets) -> Bool {
321
+ let previousEstimate = self.estimatedItemSize
322
+ self.estimatedItemSize = estimatedItemSize
323
+ let paddingChanged =
324
+ self.contentPadding.top != contentPadding.top
325
+ || self.contentPadding.left != contentPadding.left
326
+ || self.contentPadding.bottom != contentPadding.bottom
327
+ || self.contentPadding.right != contentPadding.right
328
+ self.contentPadding = contentPadding
329
+
330
+ let availableSize = isHorizontal
331
+ ? frame.height - contentPadding.top - contentPadding.bottom
332
+ : frame.width - contentPadding.left - contentPadding.right
333
+ let nextCrossAxisSize = max(0, availableSize)
334
+ let crossAxisChanged = abs(crossAxisSize - nextCrossAxisSize) > 0.001
335
+ crossAxisSize = nextCrossAxisSize
336
+
337
+ if self.frame != frame {
338
+ NitroAnimationContext.performWithoutImplicitAnimations {
339
+ self.frame = frame
340
+ }
341
+ }
342
+
343
+ if previousEstimate != estimatedItemSize, let snapshot {
344
+ rebuildFenwickForUnmeasured(snapshot: snapshot)
345
+ }
346
+
347
+ return crossAxisChanged || paddingChanged
348
+ }
349
+
350
+ func apply(_ update: NativeListUpdate, crossAxisChanged: Bool) {
351
+ applyGeneration += 1
352
+ let generation = applyGeneration
353
+ cancelOutgoingAnimations()
354
+
355
+ switch update {
356
+ case .clear:
357
+ snapshot = nil
358
+ cellRenderer = nil
359
+ onApplied = nil
360
+ anchorId = nil
361
+ measuredExtents.removeAll()
362
+ fenwick = NativeListFenwickTree()
363
+ disposeAllCells()
364
+ updateDocumentSize()
365
+ scrollProgrammatically(to: .zero)
366
+ return
367
+
368
+ case .snapshot(let target, let shouldAnimate, let renderer, let completion):
369
+ let previousSnapshot = snapshot
370
+ snapshot = target
371
+ cellRenderer = renderer
372
+ onApplied = completion
373
+
374
+ let reduceMotion = NSWorkspace.shared.accessibilityDisplayShouldReduceMotion
375
+ let animate = shouldAnimate && !reduceMotion && previousSnapshot != nil
376
+
377
+ // Save frames and references of currently active cells before rebuilding.
378
+ var oldCellsById: [String: NativeListCell] = [:]
379
+ var oldFramesById: [String: NSRect] = [:]
380
+ oldCellsById.reserveCapacity(activeCells.count)
381
+ oldFramesById.reserveCapacity(activeCells.count)
382
+ for cell in activeCells.values {
383
+ if let id = cell.itemId {
384
+ oldCellsById[id] = cell
385
+ oldFramesById[id] = cell.cellView.frame
386
+ } else {
387
+ recycleCell(cell)
388
+ }
389
+ }
390
+ activeCells.removeAll(keepingCapacity: true)
391
+
392
+ // Rebuild Fenwick tree for the new snapshot in O(N).
393
+ let itemCount = target.items.count
394
+ var extents = [Double](repeating: estimatedItemSize, count: itemCount)
395
+ let hasMeasured = !measuredExtents.isEmpty
396
+ for i in 0 ..< itemCount {
397
+ let item = target.items[i]
398
+ if let explicit = explicitMainExtent(for: item) {
399
+ extents[i] = explicit
400
+ } else if hasMeasured, let cached = measuredExtents[item.id] {
401
+ // Reuse cached measurement as initial extent (re-measured on bind if version/crossAxis changed).
402
+ extents[i] = cached.extent
403
+ }
404
+ }
405
+ fenwick = NativeListFenwickTree(values: extents)
406
+ updateDocumentSize()
407
+
408
+ if anchorId != nil {
409
+ scrollToAnchorOffsetOnly()
410
+ } else {
411
+ clampScrollOriginIfNeeded()
412
+ }
413
+
414
+ let range = desiredCellRange()
415
+
416
+ // Partition previously active cells into kept, outgoing (deleted), or recycled.
417
+ var animatingOutgoing: [NativeListCell] = []
418
+ var keptCellByNewIndex: [Int: NativeListCell] = [:]
419
+ for (id, cell) in oldCellsById {
420
+ if let newIndex = target.indices[id] {
421
+ let newItem = target.items[newIndex]
422
+ if let range, range.contains(newIndex), cell.itemType == newItem.type {
423
+ keptCellByNewIndex[newIndex] = cell
424
+ } else {
425
+ recycleCell(cell)
426
+ }
427
+ } else {
428
+ if animate {
429
+ animatingOutgoing.append(cell)
430
+ } else {
431
+ recycleCell(cell)
432
+ }
433
+ }
434
+ }
435
+
436
+ var insertedCells: [NativeListCell] = []
437
+ var movedCells: [(cell: NativeListCell, from: NSRect, to: NSRect)] = []
438
+
439
+ CATransaction.begin()
440
+ CATransaction.setDisableActions(true)
441
+
442
+ if let range {
443
+ isSyncingVisibleCells = true
444
+ for index in range {
445
+ let item = target.items[index]
446
+ let cell: NativeListCell
447
+ let isNewInSnapshot = previousSnapshot?.indices[item.id] == nil
448
+ if let kept = keptCellByNewIndex[index] {
449
+ cell = kept
450
+ activeCells[index] = cell
451
+ let needsRebind =
452
+ crossAxisChanged
453
+ || cell.boundVersion != item.version
454
+ || cell.boundIndex != index
455
+ || cell.boundCrossAxisSize != crossAxisSize
456
+ || cell.boundExplicitWidth != item.width
457
+ || cell.boundExplicitHeight != item.height
458
+ if needsRebind {
459
+ bind(cell, item: item, index: index)
460
+ }
461
+ } else {
462
+ cell = dequeueCell(for: item.type)
463
+ if cell.cellView.superview !== docView {
464
+ docView.addSubview(cell.cellView)
465
+ }
466
+ activeCells[index] = cell
467
+ bind(cell, item: item, index: index)
468
+ if animate && isNewInSnapshot {
469
+ insertedCells.append(cell)
470
+ }
471
+ }
472
+ }
473
+ isSyncingVisibleCells = false
474
+ }
475
+
476
+ updateDocumentSize()
477
+
478
+ // Re-align anchor once if binding updated any cell's measured height/width.
479
+ if anchorId != nil {
480
+ scrollToAnchorOffsetOnly()
481
+ ensureVisibleCellsBoundWithoutAnimation()
482
+ } else {
483
+ clampScrollOriginIfNeeded()
484
+ }
485
+
486
+ // Compute final frames and check whether any visible cell moved.
487
+ for (index, cell) in activeCells {
488
+ let item = target.items[index]
489
+ let targetFrame = frameForItem(at: index, item: item)
490
+ if animate, let oldFrame = oldFramesById[item.id], oldFrame != targetFrame {
491
+ cell.cellView.frame = oldFrame
492
+ movedCells.append((cell: cell, from: oldFrame, to: targetFrame))
493
+ } else {
494
+ cell.cellView.frame = targetFrame
495
+ }
496
+ }
497
+ for cell in insertedCells {
498
+ cell.cellView.alphaValue = 0
499
+ }
500
+
501
+ CATransaction.commit()
502
+
503
+ // Prune measured extents for deleted items when the map grows noticeably.
504
+ if measuredExtents.count > max(256, target.items.count) {
505
+ measuredExtents = measuredExtents.filter { target.indices[$0.key] != nil }
506
+ }
507
+
508
+ let hasAnimations = animate && (!animatingOutgoing.isEmpty || !insertedCells.isEmpty || !movedCells.isEmpty)
509
+ if hasAnimations {
510
+ outgoingCells = animatingOutgoing
511
+ animationGeneration += 1
512
+ let expectedAnimGen = animationGeneration
513
+ NSAnimationContext.runAnimationGroup({ context in
514
+ context.duration = 0.20
515
+ context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
516
+ context.allowsImplicitAnimation = true
517
+ for cell in animatingOutgoing {
518
+ cell.cellView.animator().alphaValue = 0
519
+ }
520
+ for cell in insertedCells {
521
+ cell.cellView.animator().alphaValue = 1
522
+ }
523
+ for move in movedCells {
524
+ move.cell.cellView.animator().frame = move.to
525
+ }
526
+ }, completionHandler: { [weak self] in
527
+ DispatchQueue.main.async {
528
+ guard let self, self.animationGeneration == expectedAnimGen else { return }
529
+ let toRecycle = self.outgoingCells
530
+ self.outgoingCells.removeAll()
531
+ for cell in toRecycle {
532
+ self.recycleCell(cell)
533
+ }
534
+ self.snapshotApplied(generation: generation)
535
+ }
536
+ })
537
+ } else {
538
+ snapshotApplied(generation: generation)
539
+ }
540
+ }
541
+ }
542
+
543
+ func updateContentLayout(crossAxisChanged: Bool) {
544
+ guard let snapshot else {
545
+ updateDocumentSize()
546
+ return
547
+ }
548
+ if crossAxisChanged {
549
+ CATransaction.begin()
550
+ CATransaction.setDisableActions(true)
551
+ isSyncingVisibleCells = true
552
+ for (index, cell) in activeCells {
553
+ guard index < snapshot.items.count else { continue }
554
+ let item = snapshot.items[index]
555
+ bind(cell, item: item, index: index)
556
+ }
557
+ isSyncingVisibleCells = false
558
+ updateDocumentSize()
559
+ CATransaction.commit()
560
+ }
561
+ if anchorId != nil {
562
+ alignToAnchorIfNeeded(allowFollowUp: true)
563
+ } else {
564
+ clampScrollOriginIfNeeded()
565
+ syncVisibleCells()
566
+ }
567
+ }
568
+
569
+ func contentSizeChanged(in cell: NativeListCell, from previousSize: CGSize, to size: CGSize) {
570
+ guard bindingCell !== cell else { return }
571
+ let mainAxisChanged = isHorizontal ? abs(size.width - previousSize.width) > 0.25 : abs(size.height - previousSize.height) > 0.25
572
+ guard mainAxisChanged else { return }
573
+ guard let index = cell.boundIndex,
574
+ activeCells[index] === cell,
575
+ let snapshot,
576
+ index < snapshot.items.count else { return }
577
+ let item = snapshot.items[index]
578
+ guard explicitMainExtent(for: item) == nil else { return }
579
+ let newExtent = max(0.0, Double(isHorizontal ? size.width : size.height))
580
+ let oldExtent = fenwick.values[index]
581
+ guard abs(newExtent - oldExtent) > 0.25 else { return }
582
+
583
+ measuredExtents[item.id] = MeasuredExtent(
584
+ extent: newExtent,
585
+ version: item.version,
586
+ crossAxisSize: crossAxisSize
587
+ )
588
+ fenwick.set(at: index, to: newExtent)
589
+
590
+ guard !hasScheduledSizeReposition else { return }
591
+ hasScheduledSizeReposition = true
592
+ DispatchQueue.main.async { [weak self] in
593
+ guard let self else { return }
594
+ self.hasScheduledSizeReposition = false
595
+ self.updateDocumentSize()
596
+ if self.anchorId != nil {
597
+ self.alignToAnchorIfNeeded(allowFollowUp: false)
598
+ } else {
599
+ self.syncVisibleCells()
600
+ }
601
+ }
602
+ }
603
+
604
+ // MARK: - Scrolling & Visible Cell Sync
605
+
606
+ private func handleClipViewBoundsChanged() {
607
+ if !isProgrammaticScroll {
608
+ if let vScroller = verticalScroller, vScroller.hitPart != .noPart {
609
+ anchorId = nil
610
+ }
611
+ if let hScroller = horizontalScroller, hScroller.hitPart != .noPart {
612
+ anchorId = nil
613
+ }
614
+ }
615
+ guard !isSyncingVisibleCells else { return }
616
+ syncVisibleCells()
617
+ }
618
+
619
+ func scrollToOffsetProgrammatically(_ point: CGPoint) {
620
+ anchorId = nil
621
+ scrollProgrammatically(to: point)
622
+ syncVisibleCells()
623
+ }
624
+
625
+ private func scrollProgrammatically(to point: CGPoint) {
626
+ let clamped = clampedScrollOrigin(for: point)
627
+ guard contentView.bounds.origin != clamped else { return }
628
+ isProgrammaticScroll = true
629
+ contentView.scroll(to: clamped)
630
+ reflectScrolledClipView(contentView)
631
+ isProgrammaticScroll = false
632
+ }
633
+
634
+ private func clampScrollOriginIfNeeded() {
635
+ let current = contentView.bounds.origin
636
+ let clamped = clampedScrollOrigin(for: current)
637
+ if abs(current.x - clamped.x) > 0.5 || abs(current.y - clamped.y) > 0.5 {
638
+ scrollProgrammatically(to: clamped)
639
+ }
640
+ }
641
+
642
+ private func clampedScrollOrigin(for point: CGPoint) -> CGPoint {
643
+ let maxOffset = maxScrollOffset
644
+ return CGPoint(
645
+ x: min(max(0, point.x), maxOffset.x),
646
+ y: min(max(0, point.y), maxOffset.y)
647
+ )
648
+ }
649
+
650
+ var maxScrollOffset: CGPoint {
651
+ let docSize = docView.frame.size
652
+ let visSize = contentView.bounds.size
653
+ return CGPoint(
654
+ x: max(0, docSize.width - visSize.width),
655
+ y: max(0, docSize.height - visSize.height)
656
+ )
657
+ }
658
+
659
+ private func syncVisibleCells() {
660
+ guard let snapshot, !snapshot.items.isEmpty else { return }
661
+ guard bounds.width > 0 && bounds.height > 0 else { return }
662
+ guard !isSyncingVisibleCells else { return }
663
+
664
+ isSyncingVisibleCells = true
665
+ CATransaction.begin()
666
+ CATransaction.setDisableActions(true)
667
+
668
+ let range = desiredCellRange()
669
+ let visibleStartOrigin = mainAxisOffset(of: contentView.bounds.origin)
670
+ var aboveViewportDelta: Double = 0
671
+
672
+ // 1. Recycle cells outside desired range.
673
+ if let range {
674
+ var indicesToRemove: [Int] = []
675
+ for index in activeCells.keys where !range.contains(index) {
676
+ indicesToRemove.append(index)
677
+ }
678
+ for index in indicesToRemove {
679
+ if let cell = activeCells.removeValue(forKey: index) {
680
+ recycleCell(cell)
681
+ }
682
+ }
683
+ } else {
684
+ for cell in activeCells.values {
685
+ recycleCell(cell)
686
+ }
687
+ activeCells.removeAll(keepingCapacity: true)
688
+ }
689
+
690
+ // 2. Bind newly entering cells and measure their actual extent.
691
+ var extentChanged = false
692
+ if let range {
693
+ for index in range {
694
+ let item = snapshot.items[index]
695
+ if activeCells[index] != nil {
696
+ continue
697
+ }
698
+ let oldExtent = fenwick.values[index]
699
+ let itemOriginBefore = leadingPadding + fenwick.prefixSum(before: index)
700
+ let cell = dequeueCell(for: item.type)
701
+ if cell.cellView.superview !== docView {
702
+ docView.addSubview(cell.cellView)
703
+ }
704
+ activeCells[index] = cell
705
+ let measuredDelta = bind(cell, item: item, index: index)
706
+ if abs(measuredDelta) > 0.25 {
707
+ extentChanged = true
708
+ // Preserve visual scroll position when a row strictly above the visible viewport changes size.
709
+ if anchorId == nil && visibleStartOrigin > 1.0 && (itemOriginBefore + oldExtent) <= visibleStartOrigin {
710
+ aboveViewportDelta += measuredDelta
711
+ }
712
+ }
713
+ }
714
+ }
715
+
716
+ if extentChanged {
717
+ updateDocumentSize()
718
+ if abs(aboveViewportDelta) > 0.25 {
719
+ var nextOrigin = contentView.bounds.origin
720
+ if isHorizontal {
721
+ nextOrigin.x += CGFloat(aboveViewportDelta)
722
+ } else {
723
+ nextOrigin.y += CGFloat(aboveViewportDelta)
724
+ }
725
+ scrollProgrammatically(to: nextOrigin)
726
+ }
727
+ }
728
+
729
+ // 3. Position all active cells accurately in O(visible).
730
+ if let range {
731
+ var cursor = leadingPadding + fenwick.prefixSum(before: range.lowerBound)
732
+ for index in range {
733
+ let extent = fenwick.values[index]
734
+ if let cell = activeCells[index] {
735
+ let item = snapshot.items[index]
736
+ let frame = makeCellFrame(mainOrigin: cursor, mainExtent: extent, item: item)
737
+ if cell.cellView.frame != frame {
738
+ cell.cellView.frame = frame
739
+ }
740
+ }
741
+ cursor += extent
742
+ }
743
+ }
744
+
745
+ CATransaction.commit()
746
+ lastSyncMainOffset = visibleStartOrigin - leadingPadding
747
+ isSyncingVisibleCells = false
748
+ }
749
+
750
+ private func ensureVisibleCellsBoundWithoutAnimation() {
751
+ guard let snapshot, !snapshot.items.isEmpty else { return }
752
+ guard let range = desiredCellRange() else { return }
753
+ isSyncingVisibleCells = true
754
+ var extentChanged = false
755
+ for index in range where activeCells[index] == nil {
756
+ let item = snapshot.items[index]
757
+ let cell = dequeueCell(for: item.type)
758
+ if cell.cellView.superview !== docView {
759
+ docView.addSubview(cell.cellView)
760
+ }
761
+ activeCells[index] = cell
762
+ let delta = bind(cell, item: item, index: index)
763
+ if abs(delta) > 0.25 {
764
+ extentChanged = true
765
+ }
766
+ }
767
+ if extentChanged {
768
+ updateDocumentSize()
769
+ }
770
+ isSyncingVisibleCells = false
771
+ }
772
+
773
+ private func alignToAnchorIfNeeded(allowFollowUp: Bool) {
774
+ guard anchorId != nil else { return }
775
+ guard scrollToAnchorOffsetOnly() else { return }
776
+ syncVisibleCells()
777
+ if allowFollowUp && anchorId != nil {
778
+ // One follow-up pass after self-sizing newly visible cells at the anchor target.
779
+ if scrollToAnchorOffsetOnly() {
780
+ syncVisibleCells()
781
+ }
782
+ }
783
+ }
784
+
785
+ @discardableResult
786
+ private func scrollToAnchorOffsetOnly() -> Bool {
787
+ guard let anchorId,
788
+ let snapshot,
789
+ bounds.width > 0,
790
+ bounds.height > 0,
791
+ let index = snapshot.indices[anchorId] else {
792
+ return false
793
+ }
794
+ let itemOrigin = leadingPadding + fenwick.prefixSum(before: index)
795
+ let itemExtent = fenwick.values[index]
796
+ let desired: CGFloat
797
+ let maxExtent: CGFloat
798
+ if isHorizontal {
799
+ let viewport = bounds.width - contentPadding.left - contentPadding.right
800
+ let shift = (viewport - CGFloat(itemExtent)) * anchorAlignment
801
+ if userInterfaceLayoutDirection == .rightToLeft {
802
+ desired = CGFloat(itemOrigin + itemExtent) + contentPadding.right - bounds.width + shift
803
+ } else {
804
+ desired = CGFloat(itemOrigin) - contentPadding.left - shift
805
+ }
806
+ maxExtent = max(0, docView.frame.width - bounds.width)
807
+ } else {
808
+ let viewport = bounds.height - contentPadding.top - contentPadding.bottom
809
+ let shift = (viewport - CGFloat(itemExtent)) * anchorAlignment
810
+ desired = CGFloat(itemOrigin) - contentPadding.top - shift
811
+ maxExtent = max(0, docView.frame.height - bounds.height)
812
+ }
813
+ let clamped = min(maxExtent, max(0, desired))
814
+ let current = isHorizontal ? contentView.bounds.origin.x : contentView.bounds.origin.y
815
+ let scale = window?.backingScaleFactor ?? NSScreen.main?.backingScaleFactor ?? 2.0
816
+ if abs(clamped - current) < (1.0 / scale) {
817
+ return false
818
+ }
819
+ let nextOrigin = isHorizontal
820
+ ? CGPoint(x: clamped, y: contentView.bounds.origin.y)
821
+ : CGPoint(x: contentView.bounds.origin.x, y: clamped)
822
+ scrollProgrammatically(to: nextOrigin)
823
+ return true
824
+ }
825
+
826
+ // MARK: - Cell Binding & Recycling
827
+
828
+ @discardableResult
829
+ private func bind(_ cell: NativeListCell, item: ListItemDescriptor, index: Int) -> Double {
830
+ bindingCell = cell
831
+ defer { bindingCell = nil }
832
+
833
+ var width = item.width
834
+ var height = item.height
835
+ if isHorizontal {
836
+ height = height ?? Double(crossAxisSize)
837
+ } else {
838
+ width = width ?? Double(crossAxisSize)
839
+ }
840
+
841
+ cell.itemId = item.id
842
+ cell.boundIndex = index
843
+ cell.boundVersion = item.version
844
+ cell.boundCrossAxisSize = crossAxisSize
845
+ cell.boundExplicitWidth = item.width
846
+ cell.boundExplicitHeight = item.height
847
+ cell.scrollView = self
848
+ cell.setLayoutConstraints(width: width, height: height)
849
+
850
+ if let cellRenderer {
851
+ let arguments: (Double, any HybridViewSpec, String, Double) = (
852
+ cell.cellId,
853
+ cell.container,
854
+ item.id,
855
+ Double(index)
856
+ )
857
+ do {
858
+ try cellRenderer.callSync(arguments)
859
+ } catch {
860
+ UIErrorHandler.report(error)
861
+ }
862
+ }
863
+
864
+ let previousExtent = fenwick.values[index]
865
+ let nextExtent: Double
866
+ if let explicit = explicitMainExtent(for: item) {
867
+ nextExtent = explicit
868
+ } else {
869
+ let measuredSize = cell.contentHost.frame.size
870
+ let measured = Double(isHorizontal ? measuredSize.width : measuredSize.height)
871
+ if measured > 0 {
872
+ nextExtent = measured
873
+ measuredExtents[item.id] = MeasuredExtent(
874
+ extent: measured,
875
+ version: item.version,
876
+ crossAxisSize: crossAxisSize
877
+ )
878
+ } else {
879
+ nextExtent = previousExtent
880
+ }
881
+ }
882
+
883
+ let delta = nextExtent - previousExtent
884
+ if abs(delta) > 0.25 {
885
+ fenwick.set(at: index, to: nextExtent)
886
+ }
887
+ return delta
888
+ }
889
+
890
+ private func dequeueCell(for itemType: String) -> NativeListCell {
891
+ if var pool = reusePools[itemType], let reused = pool.popLast() {
892
+ reusePools[itemType] = pool
893
+ reused.cellView.alphaValue = 1
894
+ reused.cellView.isHidden = false
895
+ return reused
896
+ }
897
+ let cell = NativeListCell(cellId: nextCellId, itemType: itemType)
898
+ nextCellId += 1
899
+ return cell
900
+ }
901
+
902
+ private func recycleCell(_ cell: NativeListCell) {
903
+ cell.resetForReuse()
904
+ reusePools[cell.itemType, default: []].append(cell)
905
+ }
906
+
907
+ private func cancelOutgoingAnimations() {
908
+ guard !outgoingCells.isEmpty else { return }
909
+ animationGeneration += 1
910
+ let toRecycle = outgoingCells
911
+ outgoingCells.removeAll()
912
+ for cell in toRecycle {
913
+ recycleCell(cell)
914
+ }
915
+ }
916
+
917
+ private func disposeAllCells() {
918
+ for cell in activeCells.values {
919
+ cell.dispose()
920
+ }
921
+ activeCells.removeAll()
922
+ for cell in outgoingCells {
923
+ cell.dispose()
924
+ }
925
+ outgoingCells.removeAll()
926
+ for pool in reusePools.values {
927
+ for cell in pool {
928
+ cell.dispose()
929
+ }
930
+ }
931
+ reusePools.removeAll()
932
+ }
933
+
934
+ private func snapshotApplied(generation: Int) {
935
+ guard applyGeneration == generation else { return }
936
+ let completion = onApplied
937
+ onApplied = nil
938
+ do {
939
+ try completion?.callSync(())
940
+ } catch {
941
+ UIErrorHandler.report(error)
942
+ }
943
+ }
944
+
945
+ // MARK: - Geometry Helpers
946
+
947
+ private var leadingPadding: Double {
948
+ Double(isHorizontal ? contentPadding.left : contentPadding.top)
949
+ }
950
+
951
+ private var trailingPadding: Double {
952
+ Double(isHorizontal ? contentPadding.right : contentPadding.bottom)
953
+ }
954
+
955
+ private func explicitMainExtent(for item: ListItemDescriptor) -> Double? {
956
+ isHorizontal ? item.width : item.height
957
+ }
958
+
959
+ private func mainAxisOffset(of origin: CGPoint) -> Double {
960
+ Double(isHorizontal ? origin.x : origin.y)
961
+ }
962
+
963
+ private func updateDocumentSize() {
964
+ let totalMain = CGFloat(leadingPadding + fenwick.total + trailingPadding)
965
+ let docSize: NSSize
966
+ if isHorizontal {
967
+ let height = max(bounds.height, crossAxisSize + contentPadding.top + contentPadding.bottom)
968
+ docSize = NSSize(width: max(bounds.width, totalMain), height: height)
969
+ } else {
970
+ let width = max(bounds.width, crossAxisSize + contentPadding.left + contentPadding.right)
971
+ docSize = NSSize(width: width, height: max(bounds.height, totalMain))
972
+ }
973
+ if docView.frame.size != docSize {
974
+ NitroAnimationContext.performWithoutImplicitAnimations {
975
+ self.docView.frame = NSRect(origin: .zero, size: docSize)
976
+ }
977
+ }
978
+ }
979
+
980
+ private func rebuildFenwickForUnmeasured(snapshot: NativeListSnapshot) {
981
+ let count = snapshot.items.count
982
+ var extents = [Double](repeating: estimatedItemSize, count: count)
983
+ for i in 0 ..< count {
984
+ let item = snapshot.items[i]
985
+ if let explicit = explicitMainExtent(for: item) {
986
+ extents[i] = explicit
987
+ } else if let cached = measuredExtents[item.id] {
988
+ extents[i] = cached.extent
989
+ }
990
+ }
991
+ fenwick = NativeListFenwickTree(values: extents)
992
+ updateDocumentSize()
993
+ }
994
+
995
+ private func desiredCellRange() -> ClosedRange<Int>? {
996
+ guard fenwick.count > 0 else { return nil }
997
+ let visBounds = contentView.bounds
998
+ let viewportMain = Double(isHorizontal ? visBounds.width : visBounds.height)
999
+ guard viewportMain > 0 else { return nil }
1000
+ let visStart = Double(isHorizontal ? visBounds.minX : visBounds.minY) - leadingPadding
1001
+ let visEnd = visStart + viewportMain
1002
+ // During large single-frame jumps (e.g. fast programmatic scrub or scrollbar drag),
1003
+ // bind only the visible viewport so we don't pay extra React portal flushes for offscreen rows.
1004
+ let jumpDelta = abs(visStart - lastSyncMainOffset)
1005
+ let overscan: Double = jumpDelta > viewportMain * 0.6
1006
+ ? 0.0
1007
+ : min(120.0, max(64.0, viewportMain * 0.18))
1008
+ guard let first = fenwick.index(atOffset: max(0.0, visStart - overscan)),
1009
+ let last = fenwick.index(atOffset: max(0.0, visEnd + overscan)) else {
1010
+ return nil
1011
+ }
1012
+ let clampedFirst = max(0, first)
1013
+ let clampedLast = min(fenwick.count - 1, max(clampedFirst, last))
1014
+ return clampedFirst ... clampedLast
1015
+ }
1016
+
1017
+ private func visibleViewportRange() -> ClosedRange<Int>? {
1018
+ guard fenwick.count > 0 else { return nil }
1019
+ let visBounds = contentView.bounds
1020
+ let viewportMain = Double(isHorizontal ? visBounds.width : visBounds.height)
1021
+ guard viewportMain > 0 else { return nil }
1022
+ let visStart = Double(isHorizontal ? visBounds.minX : visBounds.minY) - leadingPadding
1023
+ let visEnd = visStart + viewportMain
1024
+ if visEnd <= 0 || visStart >= fenwick.total {
1025
+ return nil
1026
+ }
1027
+ guard let first = fenwick.index(atOffset: max(0.0, visStart)),
1028
+ let last = fenwick.index(atOffset: max(0.0, min(fenwick.total - 0.001, visEnd))) else {
1029
+ return nil
1030
+ }
1031
+ return first ... max(first, last)
1032
+ }
1033
+
1034
+ private func frameForItem(at index: Int, item: ListItemDescriptor) -> NSRect {
1035
+ let origin = leadingPadding + fenwick.prefixSum(before: index)
1036
+ let extent = fenwick.values[index]
1037
+ return makeCellFrame(mainOrigin: origin, mainExtent: extent, item: item)
1038
+ }
1039
+
1040
+ private func makeCellFrame(mainOrigin: Double, mainExtent: Double, item: ListItemDescriptor) -> NSRect {
1041
+ if isHorizontal {
1042
+ let height = CGFloat(item.height ?? Double(crossAxisSize))
1043
+ return NSRect(
1044
+ x: CGFloat(mainOrigin),
1045
+ y: contentPadding.top,
1046
+ width: CGFloat(mainExtent),
1047
+ height: height
1048
+ )
1049
+ } else {
1050
+ let width = CGFloat(item.width ?? Double(crossAxisSize))
1051
+ return NSRect(
1052
+ x: contentPadding.left,
1053
+ y: CGFloat(mainOrigin),
1054
+ width: width,
1055
+ height: CGFloat(mainExtent)
1056
+ )
1057
+ }
1058
+ }
1059
+
1060
+ // MARK: - Diagnostics
1061
+
1062
+ func visibleAccessibilityRowViews() -> [NSView] {
1063
+ activeCells
1064
+ .sorted { $0.key < $1.key }
1065
+ .map(\.value.cellView)
1066
+ .filter { !$0.isHidden }
1067
+ }
1068
+
1069
+ func inspectMetrics(hasRefreshControl: Bool, isRefreshing: Bool) -> NitroListMetrics {
1070
+ let pooled = reusePools.values.reduce(0) { $0 + $1.count }
1071
+ let visible = visibleViewportRange()
1072
+ var blankCount = 0
1073
+ if let visible {
1074
+ for index in visible {
1075
+ guard let cell = activeCells[index],
1076
+ cell.cellView.superview === docView,
1077
+ !cell.cellView.isHidden,
1078
+ cell.cellView.frame.width > 0,
1079
+ cell.cellView.frame.height > 0 else {
1080
+ blankCount += 1
1081
+ continue
1082
+ }
1083
+ }
1084
+ }
1085
+ return NitroListMetrics(
1086
+ totalItemCount: snapshot?.items.count ?? 0,
1087
+ activeCellCount: activeCells.count,
1088
+ pooledCellCount: pooled,
1089
+ isHorizontal: isHorizontal,
1090
+ scrollOffset: contentView.bounds.origin,
1091
+ maxScrollOffset: maxScrollOffset,
1092
+ contentSize: docView.frame.size,
1093
+ viewportSize: contentView.bounds.size,
1094
+ visibleRange: visible,
1095
+ isRefreshing: isRefreshing,
1096
+ hasRefreshControl: hasRefreshControl,
1097
+ blankVisibleRowCount: blankCount
1098
+ )
1099
+ }
1100
+ }