~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/old-fella

Old people's social media app

0
1
main
295 lines · 11.3 KB Raw History
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)
        }
    }
}