generated from StanfordBDHG/SwiftPackageTemplate
-
-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
New Task model using SwiftData and Schedule creation using Calendar R…
…ecurrence Rule (#44) # New Task model using SwiftData and Schedule creation using Calendar Recurrence Rule ## ♻️ Current situation & Problem This PR completely rethinks the Scheduler package. We introduce an updated Task model that is completely backed by SwiftData. Further, we provide a new `Schedule` model that provides greater flexibility for formulating recurring events. Instead of formulating events based on intervals using [`DateComponents`](https://developer.apple.com/documentation/foundation/datecomponents), we use the new [`RecurrenceRule`](https://developer.apple.com/documentation/foundation/calendar/recurrencerule) infrastructure introduced with iOS 18. Using a `Schedule`, you can generate a potentially infinite list of `Occurrence`s. A `Task` uses the occurrences of its Schedule to generate `Events`. When events are marked as completed, they are associated with an `Outcome`. Both a `Task` and an `Outcome` can be extended with arbitrary data. This is enabled using the `@Property` macro, that allows to define custom properties on tasks and outcomes using a [`SharedRepository`](https://swiftpackageindex.com/stanfordspezi/spezifoundation/2.0.0-beta.2/documentation/spezifoundation/shared-repository)-backed storage implementation. `Task` are stored in an versioned, append-only store. Modifying the contents of a Task (e.g., instructions, schedules, ...), appends a new Task version and marks it as effective for the specified date. This allows to modify tasks without changing previous events or occurrences. Something that was impossible with the previous implementation. Lastly, the updated Scheduler provides additional support for UI components out of the box. We provide the new `@EventQuery` property wrapper that you can use in your SwiftUI views. It allows to easily and efficiently query Events directly in SwiftUI. Additionally, we provide several, reusable UI components out of the box to visualize events in your application. **Notifications are currently no longer supported with this version of SpeziScheduler: #45 (This is now tackled in #49 which will most likely be merged alongside this PR). An example of how to configure tasks with this new model is depicted below: ```swift import Spezi import SpeziScheduler class MySchedulerModule: Module { @dependency(Scheduler.self) private var scheduler init() {} func configure() { do { try scheduler.createOrUpdateTask( id: "my-daily-task", title: "Daily Questionnaire", instructions: "Please fill out the Questionnaire every day.", category: Task.Category("Questionnaire", systemName: "list.clipboard.fill"), schedule: .daily(hour: 9, minute: 0, startingAt: .today) ) } catch { // handle error (e.g., visualize in your UI) } } } ``` ## ⚙️ Release Notes * New version Scheduler Store using SwiftData. * New Task module using Events and Outcomes. * New Schedule model based on RecurrenceRule allowing for greater flexibility when specifying schedules. * Introduces new UI components to easily visualize events. * New `@EventQuery` property wrapper to easily query events in your SwiftUI view. ### Breaking Changes * This version of SpeziScheduler is not compatible with the previous version. All previously persisted data will be permanently deleted when using this new version. Already scheduled Notifications may currently not be removed and may be continue to be delivered. ## 📚 Documentation The documentation catalog was completely restructured, highlighting all the new API and functionality. ## ✅ Testing New unit and UI tests have been written to verify functionality. We aimed to set a focus on unit tests for fastest possible test execution. ## 📝 Code of Conduct & Contributing Guidelines By submitting creating this pull request, you agree to follow our [Code of Conduct](https://github.com/StanfordSpezi/.github/blob/main/CODE_OF_CONDUCT.md) and [Contributing Guidelines](https://github.com/StanfordSpezi/.github/blob/main/CONTRIBUTING.md): - [x] I agree to follow the [Code of Conduct](https://github.com/StanfordSpezi/.github/blob/main/CODE_OF_CONDUCT.md) and [Contributing Guidelines](https://github.com/StanfordSpezi/.github/blob/main/CONTRIBUTING.md).
- Loading branch information
Showing
93 changed files
with
5,185 additions
and
1,857 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ | ||
|
||
Files: Tests/SpeziSchedulerUITests/__Snapshots__/* | ||
Copyright: 2024 Stanford University and the project authors (see CONTRIBUTORS.md) | ||
License: MIT |
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,204 @@ | ||
// | ||
// This source file is part of the Stanford Spezi open-source project | ||
// | ||
// SPDX-FileCopyrightText: 2024 Stanford University and the project authors (see CONTRIBUTORS.md) | ||
// | ||
// SPDX-License-Identifier: MIT | ||
// | ||
|
||
import Combine | ||
import OSLog | ||
import SwiftData | ||
import SwiftUI | ||
|
||
|
||
/// Query events in your SwiftUI view. | ||
/// | ||
/// Use this property wrapper in your SwiftUI view to query a list of ``Event``s for a given date range. | ||
/// | ||
/// ```swift | ||
/// struct EventList: View { | ||
/// @EventQuery(in: .today..<Date.tomorrow) | ||
/// private var events | ||
/// | ||
/// var body: some View { | ||
/// List(events) { event in | ||
/// InstructionsTile(event) | ||
/// } | ||
/// } | ||
/// } | ||
/// ``` | ||
/// | ||
/// - Tip: If the query returns an error for whatever reason, the error will be stored in the ``Binding/fetchError`` property (access via the binding like `$events.fetchError`). | ||
/// | ||
/// ## Topics | ||
/// | ||
/// ### Retrieve Events | ||
/// - ``wrappedValue`` | ||
/// | ||
/// ### Fetch Error | ||
/// - ``Binding/fetchError`` | ||
/// - ``Binding`` | ||
/// - ``projectedValue`` | ||
@propertyWrapper | ||
@MainActor | ||
public struct EventQuery { | ||
private struct Configuration { | ||
let range: Range<Date> | ||
let taskPredicate: Predicate<Task> | ||
} | ||
|
||
@Observable | ||
@MainActor | ||
fileprivate final class Storage { | ||
var viewUpdate: UInt64 = 0 | ||
@ObservationIgnored var cancelable: AnyCancellable? | ||
|
||
@ObservationIgnored var fetchedEvents: [Event] = [] | ||
@ObservationIgnored var fetchedIdentifiers: Set<PersistentIdentifier> = [] | ||
} | ||
|
||
|
||
/// Binding to the `EventQuery`. | ||
public struct Binding { | ||
/// An error encountered during the most recent attempt to fetch events. | ||
/// | ||
/// This property contains the error from the most recent fetch. It is `nil` if the most recent fetch succeeded. | ||
/// Access this property via the binding of the `EventQuery`. | ||
/// | ||
/// ```swift | ||
/// struct EventList: View { | ||
/// @EventQuery(in: .today..<Date.tomorrow) | ||
/// private var events | ||
/// | ||
/// var body: some View { | ||
/// if let error = $events.fetchError { | ||
/// // ... display the error | ||
/// } | ||
/// } | ||
/// } | ||
/// ``` | ||
public fileprivate(set) var fetchError: (any Error)? | ||
} | ||
|
||
|
||
@Environment(Scheduler.self) | ||
private var scheduler | ||
|
||
private let configuration: Configuration | ||
private let storage = Storage() | ||
private var binding = Binding() | ||
|
||
/// The fetched events. | ||
/// | ||
/// If the most recent fetch failed due to a ``Binding/fetchError``, this property hold the results from the last successful fetch. If the first fetch attempt fails, | ||
/// an empty array is returned. | ||
public var wrappedValue: [Event] { | ||
_ = storage.viewUpdate // access the viewUpdate to make sure the view is tied to this observable | ||
return storage.fetchedEvents | ||
} | ||
|
||
/// Retrieves the binding of the event query. | ||
public var projectedValue: Binding { | ||
_ = storage.viewUpdate | ||
return binding | ||
} | ||
|
||
|
||
/// Create a new event query. | ||
/// - Parameters: | ||
/// - range: The date range to query events for. | ||
/// - predicate: An additional ``Task`` predicate. | ||
public init( | ||
in range: Range<Date>, | ||
predicate: Predicate<Task> = #Predicate { _ in true } | ||
) { | ||
self.configuration = Configuration(range: range, taskPredicate: predicate) | ||
} | ||
} | ||
|
||
|
||
extension EventQuery: DynamicProperty { | ||
public mutating nonisolated func update() { | ||
// This is not really ideal, however we require MainActor isolation and `DynamicProperty` doesn't annotate this guarantee | ||
// even though it will always be called from the main thread. | ||
// `EventQuery` is a non-Sendable type that must be initialized on the MainActor. This doesn't guarantee that | ||
// update will always be called on the Main thread (you can still `send` non-sendable values), however, it makes it harder to do. | ||
// If one ends up calling this on a different actor, they made it on purpose. This is fine for us. | ||
MainActor.assumeIsolated { | ||
doUpdate() | ||
} | ||
} | ||
|
||
private mutating func doUpdate() { | ||
// we cannot set @State in the update method (or anything that calls nested update() method!) | ||
|
||
if storage.cancelable == nil { | ||
do { | ||
storage.cancelable = try scheduler.sinkDidSavePublisher { [storage] _ in | ||
storage.viewUpdate &+= 1 | ||
} | ||
} catch { | ||
binding.fetchError = error | ||
return | ||
} | ||
} | ||
|
||
|
||
// The update model for the Event Query: | ||
// - All Models are Observable. Therefore, views will automatically update if they use anything that changes over the lifetime of the model. | ||
// Most importantly, we access the `nextVersion` of each Task in the `queryEvents` method. Inserting a new task is therefore covered by | ||
// observation. | ||
// - Should there be any completely new task, it triggers our `didSave` publisher above (new tasks are always saved immediately). | ||
// - Adding outcomes results in a call to the `save()` method. These updates are, therefore, also covered. | ||
|
||
do { | ||
// We always keep track of the set of models we are interested in. Only if that changes we query the "real thing". | ||
// Creating `Event` instances also incurs some overhead and sorting. | ||
// Querying just the identifiers can be up to 10x faster. | ||
let anchor = try measure(name: "Event Anchor Query") { | ||
try scheduler.queryEventsAnchor(for: configuration.range, predicate: configuration.taskPredicate) | ||
} | ||
|
||
guard anchor != storage.fetchedIdentifiers else { | ||
binding.fetchError = nil | ||
return | ||
} | ||
|
||
let events = try measure(name: "Event Query") { | ||
// Fetch also has a `batchSize` property we could explore in the future. It returns the results as a `FetchResultsCollection`. | ||
// It isn't documented how it works exactly, however, one could assume that it lazily loads (or just initializes) model objects | ||
// when iterating through the sequence. However, it probably doesn't really provide any real benefit. Users are expected to be interested | ||
// in all the results they query for (after all the provide a predicate). Further, we would need to adjust the underlying | ||
// type of the property wrapper to return a collection of type `FetchResultsCollection`. | ||
try scheduler.queryEvents(for: configuration.range, predicate: configuration.taskPredicate) | ||
} | ||
|
||
storage.fetchedEvents = events | ||
storage.fetchedIdentifiers = anchor | ||
binding.fetchError = nil | ||
} catch { | ||
binding.fetchError = error | ||
} | ||
} | ||
} | ||
|
||
|
||
private let logger = Logger(subsystem: "edu.stanford.spezi.scheduler", category: "EventQuery") | ||
|
||
|
||
private func measure<T, C: Clock>( | ||
clock: C = ContinuousClock(), | ||
name: @autoclosure @escaping () -> StaticString, | ||
_ action: () throws -> T | ||
) rethrows -> T where C.Instant.Duration == Duration { | ||
#if DEBUG || TEST | ||
let start = clock.now | ||
let result = try action() | ||
let end = clock.now | ||
logger.debug("Performing \(name()) took \(start.duration(to: end))") | ||
return result | ||
#else | ||
try action() | ||
#endif | ||
} |
Oops, something went wrong.