import Foundation public struct MotionRequest: Sendable, Equatable { public var windowID: MotionWindowID public var appID: MotionAppID public var generation: UInt64 public var start: MotionRect public var target: MotionRect public var screen: MotionRect public var minimumSize: MotionSize public var surface: MotionSurface public var token: MotionToken public var staggerIndex: Int public var velocity: MotionVelocity public var startOpacity: Double public var targetOpacity: Double public var metrics: AppWriteMetrics public var animationAllowed: Bool public init( windowID: MotionWindowID, appID: MotionAppID, start: MotionRect, target: MotionRect, screen: MotionRect, minimumSize: MotionSize = .zero, surface: MotionSurface = .window, token: MotionToken = .settle, staggerIndex: Int = 0, velocity: MotionVelocity = .zero, startOpacity: Double = 1, targetOpacity: Double = 1, metrics: AppWriteMetrics = AppWriteMetrics(), generation: UInt64 = 0, animationAllowed: Bool = true ) { self.windowID = windowID self.appID = appID self.generation = generation self.start = start self.target = target self.screen = screen self.minimumSize = minimumSize self.surface = surface self.token = token self.staggerIndex = staggerIndex self.velocity = velocity self.startOpacity = startOpacity self.targetOpacity = targetOpacity self.metrics = metrics self.animationAllowed = animationAllowed } } public struct MotionFrame: Sendable, Equatable { public let windowID: MotionWindowID public let appID: MotionAppID public let generation: UInt64 public let rect: MotionRect public let opacity: Double public let scale: Double public let offsetHorizontal: Double public let offsetVertical: Double public let timestamp: Double public let revision: UInt64 public let isFinal: Bool } public struct MotionSample: Sendable, Equatable { public let frame: MotionFrame public let velocity: MotionVelocity } struct PresentationState: Sendable { var rect: MotionRect var velocity: MotionVelocity var opacity: SpringState var scale: SpringState var offsetHorizontal: SpringState var offsetVertical: SpringState mutating func removeAccents() { scale = SpringState(value: 1) offsetHorizontal = SpringState(value: 0) offsetVertical = SpringState(value: 0) } mutating func apply(_ accent: MotionAccent, layers: Int) { switch accent { case .none: break case .scale(let from): scale = SpringState(value: from) case .offset(let horizontal, let vertical): offsetHorizontal = SpringState(value: horizontal * Double(layers)) offsetVertical = SpringState(value: vertical * Double(layers)) } } mutating func settleUnchangedAxes(target: MotionRect) { if rect.originX == target.originX { velocity.horizontal = 0 } if rect.originY == target.originY { velocity.vertical = 0 } } } private struct MotionTiming { let duration: Double let delay: Double let curve: MotionCurve } public enum FramePlanner { public static func plan( _ request: MotionRequest, at timestamp: Double, policy: MotionPolicy = MotionPolicy(), settings: MotionSettings = MotionSettings() ) throws -> FramePlan { try makePlan(request, at: timestamp, policy: policy, settings: settings, inherited: nil, revision: 0) } static func makePlan( _ request: MotionRequest, at timestamp: Double, policy: MotionPolicy, settings: MotionSettings, inherited: PresentationState?, revision: UInt64 ) throws -> FramePlan { let bounds = try validate(request, at: timestamp) let isWindow = request.surface == .window let spec: MotionSpec if isWindow && request.token == .drop { spec = MotionSpec( duration: request.token.spec(settings: settings).duration, bounce: 0.2, stagger: 0, maximumStagger: 0, overshootLimit: 0.02, accent: .none, curve: .spring, maximumRedraws: nil) } else { spec = (isWindow ? MotionToken.settle : request.token).spec(settings: settings) } var behavior = policy.behavior(for: request.surface, level: settings.level) if isWindow && (!request.animationAllowed || request.metrics.shouldSnap(at: timestamp)) { behavior = .instant } let timing = timing(for: request, spec: spec, behavior: behavior, retargeting: inherited != nil) let target = bounds.constrained(request.target, rounded: true) var initial = initialState(request, target: target, spec: spec, inherited: inherited, level: settings.level) initial.rect = bounds.constrained(initial.rect, rounded: false) if timing.curve == .fade { initial.rect = target initial.velocity = .zero initial.removeAccents() } if timing.curve == .glide && inherited == nil && timing.duration > 0 { initial.velocity.horizontal = request.velocity.horizontal == 0 ? 4 * (target.originX - initial.rect.originX) / timing.duration : request.velocity.horizontal initial.velocity.vertical = request.velocity.vertical == 0 ? 4 * (target.originY - initial.rect.originY) / timing.duration : request.velocity.vertical } if isWindow { initial.settleUnchangedAxes(target: target) } if timing.duration == 0 { initial.velocity = .zero } let startTime = timestamp + timing.delay let endTime = startTime + timing.duration guard startTime.isFinite && endTime.isFinite && (timing.duration == 0 || endTime > startTime) else { throw MotionError.invalidTimestamp } return FramePlan( request: request, spec: spec, startTime: startTime, duration: timing.duration, curve: timing.curve, initial: initial, target: target, bounds: bounds, revision: revision ) } private static func validate(_ request: MotionRequest, at timestamp: Double) throws -> FrameBounds { guard timestamp.isFinite else { throw MotionError.invalidTimestamp } guard request.start.isValid && request.target.isValid && request.staggerIndex >= 0 else { throw MotionError.invalidGeometry } guard request.velocity.isValid else { throw MotionError.invalidVelocity } guard request.startOpacity.isFinite && request.targetOpacity.isFinite, (0...1).contains(request.startOpacity) && (0...1).contains(request.targetOpacity) else { throw MotionError.invalidOpacity } return try FrameBounds(screen: request.screen, minimumSize: request.minimumSize) } private static func timing( for request: MotionRequest, spec: MotionSpec, behavior: MotionBehavior, retargeting: Bool ) -> MotionTiming { switch behavior { case .instant: return MotionTiming(duration: 0, delay: 0, curve: spec.curve) case .fade(let duration): return MotionTiming(duration: duration, delay: 0, curve: .fade) case .animate: let isWindow = request.surface == .window return MotionTiming( duration: spec.duration, delay: isWindow || retargeting ? 0 : spec.delay(for: request.staggerIndex), curve: isWindow && request.token != .drop ? .glide : spec.curve) } } private static func initialState( _ request: MotionRequest, target: MotionRect, spec: MotionSpec, inherited: PresentationState?, level: WhimsyLevel ) -> PresentationState { var initial = inherited ?? PresentationState( rect: request.start, velocity: request.velocity, opacity: SpringState(value: request.startOpacity), scale: SpringState(value: 1), offsetHorizontal: SpringState(value: 0), offsetVertical: SpringState(value: 0) ) if inherited == nil { initial.apply(spec.accent, layers: request.token == .stack ? request.staggerIndex : 1) } if level == .calm { initial.removeAccents() } if request.surface == .window { initial.rect.width = min(initial.rect.width, target.width) initial.rect.height = min(initial.rect.height, target.height) initial.velocity.width = 0 initial.velocity.height = 0 initial.opacity = SpringState(value: 1) initial.removeAccents() } return initial } } public struct FramePlan: Sendable { public let request: MotionRequest public let spec: MotionSpec public let startTime: Double public let duration: Double public var endTime: Double { startTime + duration } let curve: MotionCurve let initial: PresentationState let target: MotionRect let bounds: FrameBounds public let revision: UInt64 public func sample(at timestamp: Double) throws -> MotionSample { guard timestamp.isFinite else { throw MotionError.invalidTimestamp } let state = state(at: timestamp) let frame = MotionFrame( windowID: request.windowID, appID: request.appID, generation: request.generation, rect: bounds.constrained(state.rect, rounded: true), opacity: state.opacity.value, scale: state.scale.value, offsetHorizontal: state.offsetHorizontal.value, offsetVertical: state.offsetVertical.value, timestamp: timestamp, revision: revision, isFinal: timestamp >= endTime ) return MotionSample(frame: frame, velocity: state.velocity) } func state(at timestamp: Double) -> PresentationState { if duration == 0 || timestamp >= endTime { return PresentationState( rect: target, velocity: .zero, opacity: SpringState(value: request.surface == .window ? 1 : request.targetOpacity), scale: SpringState(value: 1), offsetHorizontal: SpringState(value: 0), offsetVertical: SpringState(value: 0) ) } let elapsed = max(0, timestamp - startTime) let horizontal = component( initial.rect.originX, velocity: initial.velocity.horizontal, target: target.originX, elapsed: elapsed) let vertical = component( initial.rect.originY, velocity: initial.velocity.vertical, target: target.originY, elapsed: elapsed) let width = request.surface == .window ? SpringState(value: initial.rect.width) : component( initial.rect.width, velocity: initial.velocity.width, target: target.width, elapsed: elapsed) let height = request.surface == .window ? SpringState(value: initial.rect.height) : component( initial.rect.height, velocity: initial.velocity.height, target: target.height, elapsed: elapsed) let raw = MotionRect( originX: horizontal.value, originY: vertical.value, width: width.value, height: height.value) let rect = bounds.constrained(raw, rounded: false) let velocity = MotionVelocity( horizontal: rect.originX == raw.originX ? horizontal.velocity : 0, vertical: rect.originY == raw.originY ? vertical.velocity : 0, width: rect.width == raw.width ? width.velocity : 0, height: rect.height == raw.height ? height.velocity : 0 ) return PresentationState( rect: rect, velocity: velocity, opacity: component( initial.opacity.value, velocity: initial.opacity.velocity, target: request.surface == .window ? 1 : request.targetOpacity, elapsed: elapsed, limit: 0), scale: component(initial.scale.value, velocity: initial.scale.velocity, target: 1, elapsed: elapsed), offsetHorizontal: accent(initial.offsetHorizontal, elapsed: elapsed), offsetVertical: accent(initial.offsetVertical, elapsed: elapsed) ) } private func accent(_ initial: SpringState, elapsed: Double) -> SpringState { let result = component(initial.value, velocity: initial.velocity, target: 0, elapsed: elapsed) let value = min(abs(initial.value), max(-abs(initial.value), result.value)) return SpringState(value: value, velocity: value == result.value ? result.velocity : 0) } private func component( _ start: Double, velocity: Double, target: Double, elapsed: Double, limit: Double? = nil ) -> SpringState { if start == target && velocity == 0 { return SpringState(value: target) } let result: SpringState switch curve { case .spring: let spring = SpringState(value: start, velocity: velocity).advanced( to: target, by: elapsed, using: spec.spring) // A terminal envelope keeps the token deadline without cutting off spring momentum. let tail = duration * 0.3 let progress = max(0, (elapsed - duration * 0.7) / tail) let envelope = 1 - 10 * pow(progress, 3) + 15 * pow(progress, 4) - 6 * pow(progress, 5) let derivative = (-30 * pow(progress, 2) + 60 * pow(progress, 3) - 30 * pow(progress, 4)) / tail result = SpringState( value: target + (spring.value - target) * envelope, velocity: spring.velocity * envelope + (spring.value - target) * derivative ) case .glide: let progress = min(1, elapsed / duration) let remaining = 1 - progress let envelope = pow(remaining, 4) let correction = velocity - 4 * (target - start) / duration result = SpringState( value: target + (start - target + correction * elapsed) * envelope, velocity: correction * envelope - 4 * (start - target + correction * elapsed) * pow(remaining, 3) / duration ) case .fade: let progress = min(1, elapsed / duration) let remaining = 1 - progress result = SpringState( value: target + (start - target) * remaining * remaining, velocity: 2 * (target - start) * remaining / duration ) } if curve == .glide && limit == nil { // Reversals brake with the existing momentum, but never cross the new target. let value = target > start ? min(target, result.value) : target < start ? max(target, result.value) : result.value return SpringState(value: value, velocity: value == result.value ? result.velocity : 0) } let overshoot = abs(target - start) * (limit ?? spec.overshootLimit) if request.surface == .window && curve == .spring && limit == nil && overshoot > 0 { // Window settlement may breathe by at most two points, independently of travel distance. let bound = min(2, overshoot) let edge = result.value > max(start, target) ? max(start, target) : min(start, target) let excess = result.value - edge if result.value > max(start, target) || result.value < min(start, target) { let attenuation = 1 + abs(excess) / bound return SpringState( value: edge + excess / attenuation, velocity: result.velocity / (attenuation * attenuation)) } } let value = min(max(start, target) + overshoot, max(min(start, target) - overshoot, result.value)) return SpringState(value: value, velocity: value == result.value ? result.velocity : 0) } }