SPB Git

Repository Public

AuraMotion.swift 9.7 KB 223 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Browser9// File             : SPBrowser/Shared/Aura/AuraMotion.swift10// Module           : SPBrowser11// Repository       : https://git.spboucher.ai/sp-browser12// Created          : 2026-11-1913// Last Modified    : 2026-11-1914//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : None specified (no license file in this repository)80// Maintainer       : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import Combine88import SwiftUI89#if canImport(UIKit)90import UIKit91#endif9293/// AURA Motion Engine: turns the motion tokens of `Core/Aura/MotionTokens.swift` into SwiftUI animations and transitions,94/// under one policy for Reduce Motion, Low Power Mode and background windows.95@MainActor96enum AuraMotion {97    /// The policy currently in force. Kept up to date by `auraRoot()`; read by code that animates outside a view body.98    static var policy = MotionPolicy.standard99100    static func animation(_ token: MotionToken, policy: MotionPolicy? = nil) -> Animation? {101        guard let spec = (policy ?? Self.policy).spec(for: token) else { return nil }102        switch spec.curve {103        case .easeOut: return .easeOut(duration: spec.duration)104        case .easeInOut: return .easeInOut(duration: spec.duration)105        case .spring(let response, let damping): return .spring(response: response, dampingFraction: damping)106        }107    }108109    /// `withAnimation` with a token.110    static func perform(_ token: MotionToken, _ body: () -> Void) {111        withAnimation(animation(token), body)112    }113}114115private struct AuraPolicyKey: EnvironmentKey { static let defaultValue = MotionPolicy.standard }116private struct AuraDensityKey: EnvironmentKey { static let defaultValue = Aura.Density.regular }117extension EnvironmentValues {118    var auraPolicy: MotionPolicy {119        get { self[AuraPolicyKey.self] }120        set { self[AuraPolicyKey.self] = newValue }121    }122    var auraDensity: Aura.Density {123        get { self[AuraDensityKey.self] }124        set { self[AuraDensityKey.self] = newValue }125    }126}127128/// Installed once at the root of every window or scene: it watches accessibility, power and activity, and publishes the motion policy.129private struct AuraRoot: ViewModifier {130    let decorativeAllowed: Bool131    @Environment(\.accessibilityReduceMotion) private var reduceMotion132    @Environment(\.scenePhase) private var scenePhase133    #if os(macOS)134    @Environment(\.controlActiveState) private var activeState135    #endif136    @State private var lowPower = ProcessInfo.processInfo.isLowPowerModeEnabled137138    private var isBackground: Bool {139        #if os(macOS)140        // An AppKit-hosted view has no scene: `scenePhase` is not meaningful there, the window's activity is.141        return activeState == .inactive142        #else143        return scenePhase != .active144        #endif145    }146147    private var policy: MotionPolicy {148        MotionPolicy(reduceMotion: reduceMotion, lowPower: lowPower || !decorativeAllowed, isBackground: isBackground)149    }150151    func body(content: Content) -> some View {152        let current = policy153        content154            .environment(\.auraPolicy, current)155            .onAppear { AuraMotion.policy = MotionPolicy(reduceMotion: current.reduceMotion, lowPower: current.lowPower) }156            .onChange(of: current) { _, value in AuraMotion.policy = MotionPolicy(reduceMotion: value.reduceMotion, lowPower: value.lowPower) }157            .onReceive(NotificationCenter.default.publisher(for: .NSProcessInfoPowerStateDidChange).receive(on: RunLoop.main)) { _ in158                lowPower = ProcessInfo.processInfo.isLowPowerModeEnabled159            }160    }161}162163private struct AuraAnimationModifier<V: Equatable>: ViewModifier {164    let token: MotionToken165    let value: V166    @Environment(\.auraPolicy) private var policy167    func body(content: Content) -> some View { content.animation(AuraMotion.animation(token, policy: policy), value: value) }168}169170extension View {171    /// Publishes the AURA motion policy to this view tree. `decorative: false` (a user setting) stops ambient motion.172    func auraRoot(decorative: Bool = true) -> some View { modifier(AuraRoot(decorativeAllowed: decorative)) }173    /// Animates changes of `value` with a motion token, honouring Reduce Motion and Low Power.174    func auraAnimation<V: Equatable>(_ token: MotionToken, value: V) -> some View { modifier(AuraAnimationModifier(token: token, value: value)) }175}176177/// AURA transitions. Each has a spatial form and a Reduce Motion form (a plain fade).178@MainActor179enum AuraTransition {180    /// Comes forward from slightly behind: suggestion lists, palettes, peeks.181    static func depth(_ policy: MotionPolicy = AuraMotion.policy, anchor: UnitPoint = .top) -> AnyTransition {182        policy.allowsSpatial ? .opacity.combined(with: .scale(scale: 0.96, anchor: anchor)).combined(with: .offset(y: anchor == .bottom ? 8 : -6)) : .opacity183    }184185    /// Slides in from an edge: sidebars, panels, floating bars.186    static func rise(_ edge: Edge, _ policy: MotionPolicy = AuraMotion.policy) -> AnyTransition {187        policy.allowsSpatial ? .move(edge: edge).combined(with: .opacity) : .opacity188    }189190    /// Grows out of a point (the link that was clicked, the tab that was tapped) and shrinks back into it.191    static func morph(from anchor: UnitPoint, _ policy: MotionPolicy = AuraMotion.policy) -> AnyTransition {192        policy.allowsSpatial ? .scale(scale: 0.08, anchor: anchor).combined(with: .opacity) : .opacity193    }194195    /// A tab chip appearing in or leaving the strip.196    static func tabChip(_ policy: MotionPolicy = AuraMotion.policy) -> AnyTransition {197        policy.allowsSpatial ? .asymmetric(insertion: .scale(scale: 0.6, anchor: .leading).combined(with: .opacity),198                                           removal: .scale(scale: 0.4, anchor: .center).combined(with: .opacity)) : .opacity199    }200201    static let fade = AnyTransition.opacity202}203204/// Haptic and tactile feedback. iPhone: Taptic Engine; Mac: trackpad alignment tick (for snaps only); iPad: no-op without hardware.205@MainActor206enum AuraHaptics {207    enum Kind { case tap, selection, success, warning, snap }208209    static func play(_ kind: Kind) {210        #if canImport(UIKit)211        switch kind {212        case .tap: UIImpactFeedbackGenerator(style: .light).impactOccurred()213        case .snap: UIImpactFeedbackGenerator(style: .rigid).impactOccurred(intensity: 0.6)214        case .selection: UISelectionFeedbackGenerator().selectionChanged()215        case .success: UINotificationFeedbackGenerator().notificationOccurred(.success)216        case .warning: UINotificationFeedbackGenerator().notificationOccurred(.warning)217        }218        #else219        if kind == .snap { NSHapticFeedbackManager.defaultPerformer.perform(.alignment, performanceTime: .now) }220        #endif221    }222}223
Files main
Menu

Theme