Files
Kymo/kymo/UI/Components/MetricMotion.swift
T

56 lines
2.1 KiB
Swift

import SwiftUI
import QuartzCore
private struct MetricAnimationsKey: EnvironmentKey {
static let defaultValue = false
}
extension EnvironmentValues {
var metricAnimationsEnabled: Bool {
get { self[MetricAnimationsKey.self] }
set { self[MetricAnimationsKey.self] = newValue }
}
}
/// Finite property animations; no opacity substitution or per-frame CPU timer.
@MainActor final class MetricMotion {
static let duration: TimeInterval = 0.35
static let key = "kymo.metric.movement"
private weak var layer: CALayer?
private var deadline: DispatchSourceTimer?
var isRunning: Bool { layer?.animation(forKey: Self.key) != nil }
func start(on layer: CALayer?, animation: CAAnimation) {
stop()
guard let layer else { return }
self.layer = layer
animation.duration = Self.duration
animation.beginTime = layer.convertTime(CACurrentMediaTime(), from: nil)
animation.isRemovedOnCompletion = true
layer.add(animation, forKey: Self.key)
// Backing layers may retain completed animations. Bound their lifetime explicitly.
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()
}
/// Cubic timing curve used by the original SwiftUI easeInOut animation.
static func easeInOut(_ time: Double) -> Double {
let time = min(1, max(0, time))
var low = 0.0, high = 1.0
for _ in 0..<24 {
let u = (low + high) / 2, v = 1 - u
let x = 3 * v * v * u * 0.42 + 3 * v * u * u * 0.58 + u * u * u
if x < time { low = u } else { high = u }
}
let u = (low + high) / 2
return 3 * (1 - u) * u * u + u * u * u
}
func stop() {
deadline?.cancel(); deadline = nil
layer?.removeAnimation(forKey: Self.key); layer = nil
}
deinit { deadline?.cancel() }
}