Last active
March 3, 2023 05:21
-
-
Save rcarver/917a311476d7cb91b591817c2f672891 to your computer and use it in GitHub Desktop.
Define animations statically but resolve them at runtime
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Dependencies | |
import Foundation | |
import SwiftUI | |
/// The things you could vary the animation on. | |
struct AnimationResolutionInput { | |
// This makes no sense, it's an example! | |
var colorScheme: ColorScheme | |
} | |
/// A way to create an animation based on some inputs. | |
protocol AnimationResolvable { | |
func resolve(input: AnimationResolutionInput) -> Animation? | |
} | |
/// The client | |
struct AnimationClient: Sendable { | |
/// self.animationClient.resolve(.sample) | |
var resolve: @Sendable (any AnimationResolvable) -> Animation? | |
} | |
extension AnimationClient: DependencyKey { | |
static let testValue = Self( | |
resolve: unimplemented("\(Self.self).resolve", placeholder: nil) | |
) | |
static let liveValue = Self( | |
// Gather the data to perform resolution using other @Dependency or whatever. | |
resolve: { $0.resolve(input: .init(colorScheme: .dark)) } | |
) | |
} | |
extension DependencyValues { | |
var animationClient: AnimationClient { | |
get { self[AnimationClient.self] } | |
set { self[AnimationClient.self] = newValue } | |
} | |
} | |
/// A sample animation. | |
struct SampleAnimation: AnimationResolvable { | |
func resolve(input: AnimationResolutionInput) -> Animation? { | |
.default | |
} | |
} | |
extension AnimationResolvable where Self == SampleAnimation { | |
// Note you can choose to make this public or not, letting you | |
// decie whether other modules can use this animation. | |
static var sample: Self { SampleAnimation() } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment