From c489972aa21fbabd27df01851fabfa36c0a7e907 Mon Sep 17 00:00:00 2001 From: Lukas Pistrol Date: Tue, 26 Nov 2024 12:44:49 +0100 Subject: [PATCH] Feature/task trigger button (#8) * add TaskTriggerUI Package * implement TaskTriggerButton * fix file headers * fix available annotation for all platforms --- Package.swift | 4 +- README.md | 11 ++ .../Documentation.docc/Documentation.md | 27 +++- Sources/TaskTrigger/TaskTrigger.swift | 11 +- .../TaskTriggerButton+Behavior.swift | 43 ++++++ .../TaskTriggerButton+Init.swift | 81 ++++++++++ .../TaskTriggerButton/TaskTriggerButton.swift | 107 +++++++++++++ Sources/TaskTrigger/View+Task.swift | 4 +- .../TaskTriggerDemo.xcodeproj/project.pbxproj | 16 +- .../TaskTriggerDemo/ContentView.swift | 104 ++----------- .../TaskTriggerButtonExampleView.swift | 140 ++++++++++++++++++ .../TaskTriggerExampleView.swift | 113 ++++++++++++++ 12 files changed, 550 insertions(+), 111 deletions(-) create mode 100644 Sources/TaskTrigger/TaskTriggerButton/TaskTriggerButton+Behavior.swift create mode 100644 Sources/TaskTrigger/TaskTriggerButton/TaskTriggerButton+Init.swift create mode 100644 Sources/TaskTrigger/TaskTriggerButton/TaskTriggerButton.swift create mode 100644 TaskTriggerDemo/TaskTriggerDemo/TaskTriggerButtonExampleView.swift create mode 100644 TaskTriggerDemo/TaskTriggerDemo/TaskTriggerExampleView.swift diff --git a/Package.swift b/Package.swift index f1cfb7a..7f90204 100644 --- a/Package.swift +++ b/Package.swift @@ -17,7 +17,9 @@ let package = Package( products: [ .library( name: taskTrigger, - targets: [taskTrigger] + targets: [ + taskTrigger, + ] ), ], targets: [ diff --git a/README.md b/README.md index e132746..fc6fe65 100644 --- a/README.md +++ b/README.md @@ -159,6 +159,17 @@ var body: some View { } ``` +### TaskTriggerButton + +To make it even simpler to use when using a `TaskTrigger` with a button, we can also use +`TaskTriggerButton`. The following example is equivalent to the previous example: + +```swift +TaskTriggerButton("Do Something") { + await someAsyncOperation() +} +``` + ## Contribution If you have any ideas on how to take this further I'm happy to discuss things in an issue. diff --git a/Sources/TaskTrigger/Documentation.docc/Documentation.md b/Sources/TaskTrigger/Documentation.docc/Documentation.md index 85815de..028ce20 100644 --- a/Sources/TaskTrigger/Documentation.docc/Documentation.md +++ b/Sources/TaskTrigger/Documentation.docc/Documentation.md @@ -78,7 +78,7 @@ hold the state in a view model. ## The Solution To make things simpler on the caller's side let's wrap all of this functionality inside -a simple type ``TaskTrigger/TaskTrigger``. +a simple type ``TaskTrigger``. ```swift @State var trigger = TaskTrigger() @@ -96,10 +96,10 @@ var body: some View { ``` 1. We declare a new state variable `trigger` and initialize the `TaskTrigger` of type `Int`. -2. In our button we call the ``TaskTrigger/TaskTrigger/trigger(value:id:)`` method on our `trigger` and pass in our value. +2. In our button we call the ``TaskTrigger/trigger(value:id:)`` method on our `trigger` and pass in our value. 3. We attach a new variant of the `task` view modifier to our view and bind it to our `trigger`. 4. The body will only execute when the `trigger` was triggered. The value we passed into the -``TaskTrigger/TaskTrigger/trigger(value:id:)`` method earlier gets passed into the closure as an argument. +``TaskTrigger/trigger(value:id:)`` method earlier gets passed into the closure as an argument. 5. All cancellation related handling, sanity checking, as well as resetting the state is handled automatically behind the scenes. @@ -110,7 +110,7 @@ automatically behind the scenes. > In case you don't want that to happen explicitly set the `id` parameter and it won't cancel > prior operations since both the `value` and `id` are still the same. -For triggers that don't need to attach a value, we can simply use ``TaskTrigger/PlainTaskTrigger`` (which is a +For triggers that don't need to attach a value, we can simply use ``PlainTaskTrigger`` (which is a typealias for `TaskTrigger`): ```swift @@ -126,9 +126,24 @@ var body: some View { } ``` +### TaskTriggerButton + +To make it even simpler to use when using a ``TaskTrigger`` with a button, we can also use +``TaskTriggerButton``. The following example is equivalent to the previous example: + +```swift +TaskTriggerButton("Do Something") { + await someAsyncOperation() +} +``` + ## Topics ### Triggers -- ``TaskTrigger/TaskTrigger`` -- ``TaskTrigger/PlainTaskTrigger`` +- ``TaskTrigger`` +- ``PlainTaskTrigger`` + +### Views + +- ``TaskTriggerButton`` diff --git a/Sources/TaskTrigger/TaskTrigger.swift b/Sources/TaskTrigger/TaskTrigger.swift index 7853f98..9c66207 100644 --- a/Sources/TaskTrigger/TaskTrigger.swift +++ b/Sources/TaskTrigger/TaskTrigger.swift @@ -9,17 +9,18 @@ import SwiftUI public struct TaskTrigger: Equatable where Value: Sendable { - internal enum TaskState: Equatable { + public enum TaskState: Equatable { case none case active(value: T, uuid: UUID? = nil) } - /// Creates a new ``TaskTrigger/TaskTrigger``. + /// Creates a new ``TaskTrigger``. public init() {} - internal var state: TaskState = .none + /// The current state of the task. + public private(set) var state: TaskState = .none - /// Triggers the tasks associated with this ``TaskTrigger/TaskTrigger`` and passes along a value of type `Value`. + /// Triggers the tasks associated with this ``TaskTrigger`` and passes along a value of type `Value`. /// - Parameters: /// - value: The value to pass along. /// - id: (Optional) An UUID which by default is initialized each time this method gets called. @@ -37,7 +38,7 @@ public struct TaskTrigger: Equatable where Value: Sendable { public typealias PlainTaskTrigger = TaskTrigger public extension PlainTaskTrigger { - /// Triggers the tasks associated with this ``TaskTrigger/PlainTaskTrigger``. + /// Triggers the tasks associated with this ``PlainTaskTrigger``. mutating func trigger() { self.state = .active(value: true, uuid: .init()) } diff --git a/Sources/TaskTrigger/TaskTriggerButton/TaskTriggerButton+Behavior.swift b/Sources/TaskTrigger/TaskTriggerButton/TaskTriggerButton+Behavior.swift new file mode 100644 index 0000000..3596932 --- /dev/null +++ b/Sources/TaskTrigger/TaskTriggerButton/TaskTriggerButton+Behavior.swift @@ -0,0 +1,43 @@ +// +// TaskTriggerButton+Behavior.swift +// TaskTrigger +// +// Created by Lukas Pistrol on 26.11.24. +// + +import Foundation + +extension TaskTriggerButton { + /// Describes how the button behaves when tapped and a task is running. + /// + /// All can show a separate placeholder while the task is running. + public enum Behavior { + /// The button is disabled while the task is running. A placeholder can be shown while the task is running. + case blocking(showPlaceholder: Bool) + + /// The button can be tapped again to cancel the task. A placeholder can be shown while the task is running. + case cancellable(showPlaceholder: Bool) + + /// The button can be tapped again to cancel and restart the task. A placeholder can be shown while the task + /// is running. + case restart(showPlaceholder: Bool) + + var showPlaceholder: Bool { + switch self { + case .blocking(let showPlaceholder): + return showPlaceholder + case .cancellable(let showPlaceholder): + return showPlaceholder + case .restart(let showPlaceholder): + return showPlaceholder + } + } + + var isBlocking: Bool { + if case .blocking = self { + return true + } + return false + } + } +} diff --git a/Sources/TaskTrigger/TaskTriggerButton/TaskTriggerButton+Init.swift b/Sources/TaskTrigger/TaskTriggerButton/TaskTriggerButton+Init.swift new file mode 100644 index 0000000..fcef3d3 --- /dev/null +++ b/Sources/TaskTrigger/TaskTriggerButton/TaskTriggerButton+Init.swift @@ -0,0 +1,81 @@ +// +// TaskTriggerButton+Init.swift +// TaskTrigger +// +// Created by Lukas Pistrol on 26.11.24. +// + +import SwiftUI + +extension TaskTriggerButton { + /// Creates a new ``TaskTriggerButton`` with a title. + /// - Parameters: + /// - text: The button's title. + /// - role: The button's role. Defaults to `nil`. + /// - behavior: The button's behavior. Defaults to `.blocking(showPlaceholder: true)`. + /// - action: The async action to perform when the button is tapped. + /// - placeholder: The placeholder to show while the task is running. Defaults to a `ProgressView`. + /// If `showPlaceholder` on the `role` is set to `false`, this is ignored. + public init( + _ text: LocalizedStringKey, + role: ButtonRole? = nil, + behavior: Behavior = .blocking(showPlaceholder: true), + action: @escaping @Sendable @MainActor () async -> Void, + @ViewBuilder placeholder: @escaping () -> P = { ProgressView() } + ) where L == Text { + self.action = action + self.label = { Text(text) } + self.placeholder = placeholder + self.role = role + self.behavior = behavior + } + + /// Creates a new ``TaskTriggerButton`` with a title and an image. + /// - Parameters: + /// - text: The button's title. + /// - image: The button's image. + /// - role: The button's role. Defaults to `nil`. + /// - behavior: The button's behavior. Defaults to `.blocking(showPlaceholder: true)`. + /// - action: The async action to perform when the button is tapped. + /// - placeholder: The placeholder to show while the task is running. Defaults to a `ProgressView`. + /// If `showPlaceholder` on the `role` is set to `false`, this is ignored. + @available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *) + public init( + _ text: LocalizedStringKey, + image: ImageResource, + role: ButtonRole? = nil, + behavior: Behavior = .blocking(showPlaceholder: true), + action: @escaping @Sendable @MainActor () async -> Void, + @ViewBuilder placeholder: @escaping () -> P = { ProgressView() } + ) where L == Label { + self.action = action + self.label = { Label(text, image: image) } + self.placeholder = placeholder + self.role = role + self.behavior = behavior + } + + /// Creates a new ``TaskTriggerButton`` with a title and a system image. + /// - Parameters: + /// - text: The button's title. + /// - systemImage: The button's system image. + /// - role: The button's role. Defaults to `nil`. + /// - behavior: The button's behavior. Defaults to `.blocking(showPlaceholder: true)`. + /// - action: The async action to perform when the button is tapped. + /// - placeholder: The placeholder to show while the task is running. Defaults to a `ProgressView`. + /// If `showPlaceholder` on the `role` is set to `false`, this is ignored. + public init( + _ text: LocalizedStringKey, + systemImage: String, + role: ButtonRole? = nil, + behavior: Behavior = .blocking(showPlaceholder: true), + action: @escaping @Sendable @MainActor () async -> Void, + @ViewBuilder placeholder: @escaping () -> P = { ProgressView() } + ) where L == Label { + self.action = action + self.label = { Label(text, systemImage: systemImage) } + self.placeholder = placeholder + self.role = role + self.behavior = behavior + } +} diff --git a/Sources/TaskTrigger/TaskTriggerButton/TaskTriggerButton.swift b/Sources/TaskTrigger/TaskTriggerButton/TaskTriggerButton.swift new file mode 100644 index 0000000..780dd63 --- /dev/null +++ b/Sources/TaskTrigger/TaskTriggerButton/TaskTriggerButton.swift @@ -0,0 +1,107 @@ +// +// TaskTriggerButton.swift +// TaskTrigger +// +// Created by Lukas Pistrol on 26.11.24. +// + +import SwiftUI + +/// A `Button` that triggers an async task that is bound to the button using a ``TaskTrigger``. +/// +/// > To get a better understanding of how a ``TaskTrigger`` works and its use cases, please refer to the +/// > documentation of the ``TaskTrigger`` package. +/// +/// When the button is tapped the action is performed. Depending on the ``TaskTriggerButton/Behavior`` the button +/// behaves differently: +/// +/// - `.blocking`: +/// The button is disabled while the task is running. +/// A placeholder can be shown while the task is running. +/// - `.cancellable`: +/// The button can be tapped again to cancel the task. +/// A placeholder can be shown while the task is running. +/// - `.restart`: +/// The button can be tapped again to cancel and restart +/// the task. A placeholder can be shown while the task is running. +/// +/// ```swift +/// // ⛔ Bad: +/// // Task will not be cancelled when the button is +/// // removed from the view hierarchy or is tapped +/// // multiple times. +/// Button("Start Task") { +/// Task { +/// await someAsyncTask() +/// } +/// } +/// +/// // ✅ Good: +/// TaskTriggerButton("Start Task") { +/// await someAsyncTask() +/// } +/// ``` +/// +/// The default behavior is `.blocking` with a `ProgressView` as a placeholder. In all cases the task is bound to +/// the ``TaskTriggerButton`` and will be cancelled as soon as the ``TaskTriggerButton`` is removed from the view +/// hierarchy. +public struct TaskTriggerButton: View { + + let action: @Sendable @MainActor () async -> Void + let label: () -> L + let placeholder: () -> P + let role: ButtonRole? + let behavior: Behavior + + /// Creates a new ``TaskTriggerButton`` with a label. + /// - Parameters: + /// - role: The button's role. Defaults to `nil`. + /// - behavior: The button's behavior. Defaults to `.blocking(showPlaceholder: true)`. + /// - action: The async action to perform when the button is tapped. + /// - label: The button's label. This can be any `View`. + /// - placeholder: The placeholder to show while the task is running. Defaults to a `ProgressView`. + /// If `showPlaceholder` on the `role` is set to `false`, this is ignored. + public init( + role: ButtonRole? = nil, + behavior: Behavior = .blocking(showPlaceholder: true), + action: @escaping @Sendable @MainActor () async -> Void, + @ViewBuilder label: @escaping () -> L, + @ViewBuilder placeholder: @escaping () -> P = { ProgressView() } + ) { + self.action = action + self.label = label + self.placeholder = placeholder + self.role = role + self.behavior = behavior + } + + @State private var trigger = PlainTaskTrigger() + + public var body: some View { + Button(role: role) { + switch trigger.state { + case .none: + trigger.trigger() + case .active: + if case .cancellable = behavior { + trigger.cancel() + } else if case .restart = behavior { + trigger.trigger() + } + } + } label: { + switch trigger.state { + case .none: + label() + case .active: + if behavior.showPlaceholder { + placeholder() + } else { + label() + } + } + } + .disabled(behavior.isBlocking && trigger.state != .none) + .task($trigger, action) + } +} diff --git a/Sources/TaskTrigger/View+Task.swift b/Sources/TaskTrigger/View+Task.swift index fc83922..e1b77ac 100644 --- a/Sources/TaskTrigger/View+Task.swift +++ b/Sources/TaskTrigger/View+Task.swift @@ -10,7 +10,7 @@ import SwiftUI public extension View { /// Adds a task to perform whenever the specified trigger with an attached value fires. /// - Parameters: - /// - trigger: A binding to a ``TaskTrigger/TaskTrigger``. + /// - trigger: A binding to a ``TaskTrigger``. /// - action: An async action to perform whenever the trigger fires. The attached value /// is passed into the closure as an argument. func task( @@ -22,7 +22,7 @@ public extension View { /// Adds a task to perform whenever the specified trigger fires. /// - Parameters: - /// - trigger: A binding to a ``TaskTrigger/PlainTaskTrigger``. + /// - trigger: A binding to a ``PlainTaskTrigger``. /// - action: An async action to perform whenever the trigger fires. func task( _ trigger: Binding, diff --git a/TaskTriggerDemo/TaskTriggerDemo.xcodeproj/project.pbxproj b/TaskTriggerDemo/TaskTriggerDemo.xcodeproj/project.pbxproj index 7496046..2bf5469 100644 --- a/TaskTriggerDemo/TaskTriggerDemo.xcodeproj/project.pbxproj +++ b/TaskTriggerDemo/TaskTriggerDemo.xcodeproj/project.pbxproj @@ -7,8 +7,10 @@ objects = { /* Begin PBXBuildFile section */ + 2898E8422CF5D1A200314324 /* TaskTriggerButtonExampleView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2898E8412CF5D1A200314324 /* TaskTriggerButtonExampleView.swift */; }; + 2898E8442CF5D1E900314324 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2898E8432CF5D1E900314324 /* ContentView.swift */; }; 28C862282ABB4EEE002EA26C /* TaskTriggerDemoApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28C862272ABB4EEE002EA26C /* TaskTriggerDemoApp.swift */; }; - 28C8622A2ABB4EEE002EA26C /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28C862292ABB4EEE002EA26C /* ContentView.swift */; }; + 28C8622A2ABB4EEE002EA26C /* TaskTriggerExampleView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28C862292ABB4EEE002EA26C /* TaskTriggerExampleView.swift */; }; 28C8622C2ABB4EF0002EA26C /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 28C8622B2ABB4EF0002EA26C /* Assets.xcassets */; }; 28C8622F2ABB4EF0002EA26C /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 28C8622E2ABB4EF0002EA26C /* Preview Assets.xcassets */; }; 28C862362ABB4F1A002EA26C /* TaskTrigger in Resources */ = {isa = PBXBuildFile; fileRef = 28C862352ABB4F1A002EA26C /* TaskTrigger */; }; @@ -16,9 +18,11 @@ /* End PBXBuildFile section */ /* Begin PBXFileReference section */ + 2898E8412CF5D1A200314324 /* TaskTriggerButtonExampleView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TaskTriggerButtonExampleView.swift; sourceTree = ""; }; + 2898E8432CF5D1E900314324 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = ""; }; 28C862242ABB4EEE002EA26C /* TaskTriggerDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = TaskTriggerDemo.app; sourceTree = BUILT_PRODUCTS_DIR; }; 28C862272ABB4EEE002EA26C /* TaskTriggerDemoApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TaskTriggerDemoApp.swift; sourceTree = ""; }; - 28C862292ABB4EEE002EA26C /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = ""; }; + 28C862292ABB4EEE002EA26C /* TaskTriggerExampleView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TaskTriggerExampleView.swift; sourceTree = ""; }; 28C8622B2ABB4EF0002EA26C /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 28C8622E2ABB4EF0002EA26C /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = ""; }; 28C862352ABB4F1A002EA26C /* TaskTrigger */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = TaskTrigger; path = ..; sourceTree = ""; }; @@ -58,7 +62,9 @@ isa = PBXGroup; children = ( 28C862272ABB4EEE002EA26C /* TaskTriggerDemoApp.swift */, - 28C862292ABB4EEE002EA26C /* ContentView.swift */, + 2898E8432CF5D1E900314324 /* ContentView.swift */, + 28C862292ABB4EEE002EA26C /* TaskTriggerExampleView.swift */, + 2898E8412CF5D1A200314324 /* TaskTriggerButtonExampleView.swift */, 28C8622B2ABB4EF0002EA26C /* Assets.xcassets */, 28C8622D2ABB4EF0002EA26C /* Preview Content */, ); @@ -154,7 +160,9 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 28C8622A2ABB4EEE002EA26C /* ContentView.swift in Sources */, + 2898E8422CF5D1A200314324 /* TaskTriggerButtonExampleView.swift in Sources */, + 28C8622A2ABB4EEE002EA26C /* TaskTriggerExampleView.swift in Sources */, + 2898E8442CF5D1E900314324 /* ContentView.swift in Sources */, 28C862282ABB4EEE002EA26C /* TaskTriggerDemoApp.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/TaskTriggerDemo/TaskTriggerDemo/ContentView.swift b/TaskTriggerDemo/TaskTriggerDemo/ContentView.swift index 01fa359..7a335ef 100644 --- a/TaskTriggerDemo/TaskTriggerDemo/ContentView.swift +++ b/TaskTriggerDemo/TaskTriggerDemo/ContentView.swift @@ -2,109 +2,27 @@ // ContentView.swift // TaskTriggerDemo // -// Created by Lukas Pistrol on 2023-09-20. +// Created by Lukas Pistrol on 26.11.24. // import SwiftUI -import TaskTrigger - -/* - This is a very simple example showing how to use TaskTrigger in a SwiftUI View. - - The view contains a Text showing a random number and two buttons. The first button - triggers a task that sets the random number to a new value. The second button - triggers a task that resets the random number to zero. - - Both tasks simulate an async operation by using Task.sleep. - */ struct ContentView: View { - - @State private var randomNumber: Int = 0 - - /* - TaskTrigger is generic and accepts any value that conforms to Equatable and Sendable. - - For convenience there is also PlainTaskTrigger which is basically `TaskTrigger`. - PlainTaskTrigger is useful if you don't need to pass a value to the task and therefore - can be triggered with the trigger() method instead of trigger(value:). - */ - - @State private var randomTrigger = TaskTrigger() - @State private var resetTrigger = PlainTaskTrigger() - var body: some View { - VStack { - Text(randomNumber, format: .number) - .font(.system(size: 60, weight: .semibold, design: .rounded)) - .monospacedDigit() - .contentTransition(.numericText()) - - VStack { - HStack { - Button("Random Number") { - randomTrigger.trigger(value: Int.random(in: 0...100)) - } - Button("Reset", role: .destructive) { - resetTrigger.trigger() - } + NavigationStack { + List { + NavigationLink { + TaskTriggerExampleView() + } label: { + Label("TaskTrigger", systemImage: "play") } - Button("Cancel All") { - randomTrigger.cancel() - resetTrigger.cancel() + NavigationLink { + TaskTriggerButtonExampleView() + } label: { + Label("TaskTriggerButton", systemImage: "play.rectangle.fill") } } - .buttonStyle(.borderedProminent) - } - .animation(.snappy, value: randomNumber) - - /* - The task modifiers below look pretty similar to the ones provided by SwiftUI. - - It takes a binding to a TaskTrigger and the closure gets executed whenever the - trigger fires. The closure also gets passed the value that was attached to the - trigger. The PlainTaskTrigger variant doesn't need a value since its boolean - value is always true in the triggered state. - - The task only lives as long as the view is alive. If the view gets destroyed - the task is cancelled automatically. You can also cancel the task manually - by calling the cancel() method on the trigger. - - Firing a trigger multiple times in a row will cancel the previous task and - start a new one. - */ - - .task($randomTrigger) { value in - await setRandomNumber(value) } - .task($resetTrigger) { - await resetToZero() - } - } - - /* - The two functions below simulate an asynchroneous task wich also checks for cancellation. - - You can test this easily by pressing a button twice in a row. The first task will be - cancelled and the second one will be executed. - - This also happens if the "random number" should be the same each time since TaskTrigger - also creates a new UUID each time the trigger method gets called. - - Typically those functions would live in a ViewModel or similar and perform a real async - operation like a network call or some other (possibly) expensive operation. - */ - - private func setRandomNumber(_ value: Int) async { - try? await Task.sleep(for: .seconds(1)) - if Task.isCancelled { return } - self.randomNumber = value - } - - private func resetToZero() async { - try? await Task.sleep(for: .seconds(1)) - if Task.isCancelled { return } - self.randomNumber = 0 } } diff --git a/TaskTriggerDemo/TaskTriggerDemo/TaskTriggerButtonExampleView.swift b/TaskTriggerDemo/TaskTriggerDemo/TaskTriggerButtonExampleView.swift new file mode 100644 index 0000000..93bbacd --- /dev/null +++ b/TaskTriggerDemo/TaskTriggerDemo/TaskTriggerButtonExampleView.swift @@ -0,0 +1,140 @@ +// +// TaskTriggerButtonExampleView.swift +// TaskTriggerDemo +// +// Created by Lukas Pistrol on 26.11.24. +// + +import SwiftUI +import TaskTriggerUI + +struct TaskTriggerButtonExampleView: View { + + enum ButtonState { + case idle + case loading + case success + case cancelled + } + + @State private var state: ButtonState = .idle + + var body: some View { + List { + Section { + statusImage + } + Section { + TaskTriggerButton(behavior: .blocking(showPlaceholder: false)) { + await test() + } label: { + Label("Trigger", systemImage: "play") + } + } footer: { + Text("Blocking behavior, no placeholder") + } + Section { + TaskTriggerButton( + "Test", + role: .destructive, + behavior: .cancellable(showPlaceholder: true) + ) { + await test() + } placeholder: { + Text("Cancel") + } + } footer: { + Text("Cancellable behavior, show \"Cancel\" as placeholder") + } + Section { + TaskTriggerButton("Test", systemImage: "globe") { + await test() + } placeholder: { + Label { + Text("Waiting...") + } icon: { + ProgressView() + } + } + } footer: { + Text("Default (blocking) behavior, show \"Waiting...\" as placeholder") + } + Section { + TaskTriggerButton( + "Test", + behavior: .restart(showPlaceholder: true) + ) { + await test() + } placeholder: { + Text("Restart") + } + } footer: { + Text("Restarting behavior, show \"Restart\" as placeholder") + } + } + } + + private var statusImage: some View { + VStack { + Group { + switch state { + case .idle: + Image(systemName: "circle.dotted") + .resizable() + .aspectRatio(contentMode: .fit) + .foregroundStyle(.secondary) + case .loading: + Image(systemName: "arrow.trianglehead.2.clockwise") + .resizable() + .aspectRatio(contentMode: .fit) + .foregroundStyle(Color.accentColor) + case .success: + Image(systemName: "checkmark.circle.fill") + .resizable() + .aspectRatio(contentMode: .fit) + .foregroundStyle(.green) + case .cancelled: + Image(systemName: "xmark.circle.fill") + .resizable() + .aspectRatio(contentMode: .fit) + .foregroundStyle(.red) + } + } + .imageScale(.large) + .frame(height: 120) + Text(String(describing: state)) + } + .frame(maxWidth: .infinity) + } + + private func test() async { + defer { + print("") + Task { + await reset() + } + } + state = .loading + print("Triggered") + try? await Task.sleep(nanoseconds: 2_000_000_000) + if Task.isCancelled { + state = .cancelled + print("Cancelled") + return + } + state = .success + print("Waited 2s") + } + + private func reset() async { + try? await Task.sleep(nanoseconds: 1_000_000_000) + if Task.isCancelled || state == .loading { + return + } + state = .idle + } +} + +#Preview { + TaskTriggerButtonExampleView() +} diff --git a/TaskTriggerDemo/TaskTriggerDemo/TaskTriggerExampleView.swift b/TaskTriggerDemo/TaskTriggerDemo/TaskTriggerExampleView.swift new file mode 100644 index 0000000..4ad3564 --- /dev/null +++ b/TaskTriggerDemo/TaskTriggerDemo/TaskTriggerExampleView.swift @@ -0,0 +1,113 @@ +// +// TaskTriggerExampleView.swift +// TaskTriggerDemo +// +// Created by Lukas Pistrol on 2023-09-20. +// + +import SwiftUI +import TaskTrigger + +/* + This is a very simple example showing how to use TaskTrigger in a SwiftUI View. + + The view contains a Text showing a random number and two buttons. The first button + triggers a task that sets the random number to a new value. The second button + triggers a task that resets the random number to zero. + + Both tasks simulate an async operation by using Task.sleep. + */ + +struct TaskTriggerExampleView: View { + + @State private var randomNumber: Int = 0 + + /* + TaskTrigger is generic and accepts any value that conforms to Equatable and Sendable. + + For convenience there is also PlainTaskTrigger which is basically `TaskTrigger`. + PlainTaskTrigger is useful if you don't need to pass a value to the task and therefore + can be triggered with the trigger() method instead of trigger(value:). + */ + + @State private var randomTrigger = TaskTrigger() + @State private var resetTrigger = PlainTaskTrigger() + + var body: some View { + VStack { + Text(randomNumber, format: .number) + .font(.system(size: 60, weight: .semibold, design: .rounded)) + .monospacedDigit() + .contentTransition(.numericText()) + + VStack { + HStack { + Button("Random Number") { + randomTrigger.trigger(value: Int.random(in: 0...100)) + } + Button("Reset", role: .destructive) { + resetTrigger.trigger() + } + } + Button("Cancel All") { + randomTrigger.cancel() + resetTrigger.cancel() + } + } + .buttonStyle(.borderedProminent) + } + .animation(.snappy, value: randomNumber) + + /* + The task modifiers below look pretty similar to the ones provided by SwiftUI. + + It takes a binding to a TaskTrigger and the closure gets executed whenever the + trigger fires. The closure also gets passed the value that was attached to the + trigger. The PlainTaskTrigger variant doesn't need a value since its boolean + value is always true in the triggered state. + + The task only lives as long as the view is alive. If the view gets destroyed + the task is cancelled automatically. You can also cancel the task manually + by calling the cancel() method on the trigger. + + Firing a trigger multiple times in a row will cancel the previous task and + start a new one. + */ + + .task($randomTrigger) { value in + await setRandomNumber(value) + } + .task($resetTrigger) { + await resetToZero() + } + } + + /* + The two functions below simulate an asynchroneous task wich also checks for cancellation. + + You can test this easily by pressing a button twice in a row. The first task will be + cancelled and the second one will be executed. + + This also happens if the "random number" should be the same each time since TaskTrigger + also creates a new UUID each time the trigger method gets called. + + Typically those functions would live in a ViewModel or similar and perform a real async + operation like a network call or some other (possibly) expensive operation. + */ + + private func setRandomNumber(_ value: Int) async { + try? await Task.sleep(for: .seconds(1)) + if Task.isCancelled { return } + self.randomNumber = value + } + + private func resetToZero() async { + try? await Task.sleep(for: .seconds(1)) + if Task.isCancelled { return } + self.randomNumber = 0 + } +} + +#Preview { + TaskTriggerExampleView() +}