48 lines
1.8 KiB
Swift
48 lines
1.8 KiB
Swift
import SwiftUI
|
|
import QuartzCore
|
|
|
|
private struct MetricAnimationsKey: EnvironmentKey {
|
|
static let defaultValue = false
|
|
}
|
|
extension EnvironmentValues {
|
|
/// The owner supplies actual visibility and user/system motion policy.
|
|
var metricAnimationsEnabled: Bool {
|
|
get { self[MetricAnimationsKey.self] }
|
|
set { self[MetricAnimationsKey.self] = newValue }
|
|
}
|
|
}
|
|
|
|
/// A finite compositor transition; native controls never create per-frame CPU timers.
|
|
@MainActor final class MetricMotion {
|
|
static let duration: TimeInterval = 0.25
|
|
private weak var layer: CALayer?
|
|
private var deadline: DispatchSourceTimer?
|
|
// Core Animation stores every CATransition under this reserved key.
|
|
private static let key = kCATransition
|
|
var isRunning: Bool { layer?.animation(forKey: Self.key) != nil }
|
|
|
|
func start(on layer: CALayer?) {
|
|
stop()
|
|
guard let layer else { return }
|
|
self.layer = layer
|
|
let transition = CATransition()
|
|
transition.type = .fade
|
|
transition.duration = Self.duration
|
|
transition.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
|
|
transition.isRemovedOnCompletion = true
|
|
layer.add(transition, forKey: Self.key)
|
|
// AppKit backing layers can retain a finished transition; enforce a finite lifetime.
|
|
// One coalescible cleanup deadline, never a per-frame CPU callback.
|
|
let deadline = DispatchSource.makeTimerSource(queue: .main)
|
|
deadline.schedule(deadline: .now() + Self.duration, leeway: .milliseconds(10))
|
|
deadline.setEventHandler { [weak self] in MainActor.assumeIsolated { self?.stop() } }
|
|
self.deadline = deadline
|
|
deadline.resume()
|
|
}
|
|
func stop() {
|
|
deadline?.cancel(); deadline = nil
|
|
layer?.removeAnimation(forKey: Self.key); layer = nil
|
|
}
|
|
deinit { deadline?.cancel() }
|
|
}
|