Skip to content

Instantly share code, notes, and snippets.

@rcarver
Last active March 3, 2023 05:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rcarver/917a311476d7cb91b591817c2f672891 to your computer and use it in GitHub Desktop.
Save rcarver/917a311476d7cb91b591817c2f672891 to your computer and use it in GitHub Desktop.
Define animations statically but resolve them at runtime
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