1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import SwiftUI
struct ScrollRefreshControl: UIViewRepresentable {
let isRefreshing: Bool
let isActive: Bool
var accessibilityIdentifier: String?
var accessibilityLabel: String?
var scrollToTopRequest = 0
var allowsScrollToTop = false
func makeUIView(context: Context) -> Probe {
let view = Probe()
view.scrollToTopRequest = scrollToTopRequest
return view
}
func updateUIView(_ view: Probe, context: Context) {
let scrollRequested = scrollToTopRequest != view.scrollToTopRequest
view.scrollToTopRequest = scrollToTopRequest
view.isRefreshing = isRefreshing
view.isActive = isActive
view.refreshAccessibilityIdentifier = accessibilityIdentifier
view.refreshAccessibilityLabel = accessibilityLabel
view.setNeedsLayout()
view.synchronize()
view.synchronizeAfterLayout()
if !allowsScrollToTop {
view.cancelScrollToTop()
} else if scrollRequested {
view.scrollToTop(animated: !context.environment.accessibilityReduceMotion)
}
}
static func dismantleUIView(_ view: Probe, coordinator: ()) {
view.cancelScrollToTop()
view.finish()
}
final class Probe: UIView {
var isRefreshing = false
var isActive = false
var refreshAccessibilityIdentifier: String?
var refreshAccessibilityLabel: String?
var scrollToTopRequest = 0
private let scrollToTopAnimation = ScrollToTopAnimation()
private weak var ownedControl: UIRefreshControl?
private weak var attachedControl: UIRefreshControl?
private weak var attachedScroll: UIScrollView?
private weak var attachmentContainer: UIView?
private var synchronizationScheduled = false
private var transitionSynchronizationScheduled = false
override func didMoveToSuperview() {
super.didMoveToSuperview()
clearAttachment()
}
override func didMoveToWindow() {
super.didMoveToWindow()
clearAttachment()
synchronize()
synchronizeAfterLayout()
}
override func layoutSubviews() {
super.layoutSubviews()
synchronize()
synchronizeAfterLayout()
}
func scrollToTop(animated: Bool) {
guard let scroll = attachedRefreshScroll() else { return }
scrollToTopAnimation.start(on: scroll, animated: animated)
}
func cancelScrollToTop() {
scrollToTopAnimation.cancel()
}
func synchronize(afterTransition: Bool = false) {
let scroll = attachedRefreshScroll()
if let control = scroll?.refreshControl { applyTint(to: control) }
guard isRefreshing else {
finish()
return
}
guard isActive, window != nil, bounds.width > 0, bounds.height > 0 else { return }
if !afterTransition, synchronizeAfterTransition() { return }
guard let scroll, let control = scroll.refreshControl else { return }
if let identifier = refreshAccessibilityIdentifier {
control.accessibilityIdentifier = identifier
control.isAccessibilityElement = true
control.accessibilityLabel = refreshAccessibilityLabel ?? "Refreshing"
}
if let ownedControl, ownedControl !== control { finish() }
guard ownedControl == nil, !control.isRefreshing else { return }
let restingTop = -scroll.adjustedContentInset.top
let canReveal =
!scroll.isDragging && !scroll.isDecelerating
&& scroll.contentOffset.y <= restingTop + 1
ownedControl = control
if canReveal {
let height = max(control.bounds.height, 60)
scroll.setContentOffset(
CGPoint(x: scroll.contentOffset.x, y: restingTop - height), animated: false)
scroll.layoutIfNeeded()
}
control.beginRefreshing()
}
private func applyTint(to control: UIRefreshControl) {
let tint = UIColor(AppPalette.accent)
let traits = control.traitCollection
if control.tintColor?.resolvedColor(with: traits) != tint.resolvedColor(with: traits) {
control.tintColor = tint
}
}
private func attachedRefreshScroll() -> UIScrollView? {
guard window != nil, bounds.width > 0, bounds.height > 0 else {
clearAttachment()
return nil
}
if let scroll = attachedScroll, let control = attachedControl, let container = attachmentContainer,
scroll.refreshControl === control,
isDescendant(of: container), scroll.isDescendant(of: container), matchesRegion(of: scroll) {
return scroll
}
clearAttachment()
var ancestor = superview
while let container = ancestor {
if let scroll = refreshScroll(in: container) {
attachedScroll = scroll
attachedControl = scroll.refreshControl
attachmentContainer = container
return scroll
}
ancestor = container.superview
}
return nil
}
private func clearAttachment() {
attachedControl = nil
attachedScroll = nil
attachmentContainer = nil
}
func synchronizeAfterLayout() {
guard !synchronizationScheduled, window != nil else { return }
synchronizationScheduled = true
DispatchQueue.main.async { [weak self] in
guard let self else { return }
self.synchronizationScheduled = false
self.synchronize()
}
}
private func synchronizeAfterTransition() -> Bool {
guard !transitionSynchronizationScheduled else { return true }
var responder: UIResponder? = self
while let current = responder {
if let controller = current as? UIViewController, let transition = controller.transitionCoordinator {
transitionSynchronizationScheduled = true
let scheduled = transition.animate(alongsideTransition: nil) { [weak self] _ in
self?.transitionSynchronizationScheduled = false
self?.synchronize(afterTransition: true)
}
if !scheduled { transitionSynchronizationScheduled = false }
return scheduled
}
responder = current.next
}
return false
}
private func refreshScroll(in view: UIView) -> UIScrollView? {
if let scroll = view as? UIScrollView, scroll.refreshControl != nil, matchesRegion(of: scroll) {
return scroll
}
for child in view.subviews where child !== self && !child.isHidden && child.alpha > 0.01 {
if let scroll = refreshScroll(in: child) { return scroll }
}
return nil
}
private func matchesRegion(of scroll: UIScrollView) -> Bool {
guard let window, scroll.window === window else { return false }
var ancestor: UIView? = scroll
while let view = ancestor {
guard !view.isHidden, view.alpha > 0.01 else { return false }
ancestor = view.superview
}
let probeFrame = convert(bounds, to: window)
let scrollFrame = scroll.convert(scroll.bounds, to: window)
let overlap = probeFrame.intersection(scrollFrame)
guard !overlap.isNull, scrollFrame.width > 0, scrollFrame.height > 0 else { return false }
return overlap.width >= probeFrame.width * 0.8
&& overlap.width >= scrollFrame.width * 0.8
&& overlap.height >= min(probeFrame.height, scrollFrame.height) * 0.8
}
func finish() {
let control = ownedControl
ownedControl = nil
if refreshAccessibilityIdentifier != nil {
control?.isAccessibilityElement = false
}
control?.endRefreshing()
}
}
}
@MainActor
private final class ScrollToTopAnimation {
private weak var scrollView: UIScrollView?
private var displayLink: CADisplayLink?
private var startedAt: CFTimeInterval = 0
private var duration: CFTimeInterval = 0
private var previousProgress: Double = 0
func start(on scroll: UIScrollView, animated: Bool) {
cancel()
guard scroll.contentOffset.y > -scroll.adjustedContentInset.top else { return }
scroll.stopScrollingAndZooming()
guard animated else {
settleAtTop(scroll)
return
}
scrollView = scroll
let distance = scroll.contentOffset.y + scroll.adjustedContentInset.top
let viewport = max(
1, scroll.bounds.height - scroll.adjustedContentInset.top - scroll.adjustedContentInset.bottom)
duration = min(0.65, 0.38 + 0.035 * Double(distance / viewport))
startedAt = CACurrentMediaTime()
previousProgress = 0
let target = FrameTarget()
target.animation = self
let link = CADisplayLink(target: target, selector: #selector(FrameTarget.advance(_:)))
displayLink = link
link.add(to: .main, forMode: .common)
}
func cancel() {
displayLink?.invalidate()
displayLink = nil
scrollView = nil
}
private func advance(_ link: CADisplayLink) {
guard let scroll = scrollView, scroll.window != nil, !scroll.isTracking, !scroll.isDragging else {
cancel()
return
}
let progress = min(1, max(0, (link.targetTimestamp - startedAt) / duration))
let eased = progress * progress * (3 - 2 * progress)
if eased >= 1 {
settleAtTop(scroll)
cancel()
return
}
let offset = scroll.contentOffset
let remaining = max(0, offset.y + scroll.adjustedContentInset.top)
let fraction = (eased - previousProgress) / (1 - previousProgress)
previousProgress = eased
// Use the current offset because row heights can change during the scroll.
UIView.performWithoutAnimation {
scroll.setContentOffset(CGPoint(x: offset.x, y: offset.y - remaining * fraction), animated: false)
scroll.layoutIfNeeded()
}
}
private func settleAtTop(_ scroll: UIScrollView) {
UIView.performWithoutAnimation {
scroll.setContentOffset(
CGPoint(x: scroll.contentOffset.x, y: -scroll.adjustedContentInset.top), animated: false)
scroll.layoutIfNeeded()
if scroll.contentOffset.y > -scroll.adjustedContentInset.top {
scroll.setContentOffset(
CGPoint(x: scroll.contentOffset.x, y: -scroll.adjustedContentInset.top), animated: false)
}
}
}
deinit { displayLink?.invalidate() }
@MainActor
private final class FrameTarget: NSObject {
weak var animation: ScrollToTopAnimation?
@objc func advance(_ link: CADisplayLink) {
animation?.advance(link)
}
}
}