Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow external ownership for Modules #106

Merged
merged 8 commits into from
Jun 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 44 additions & 6 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,15 @@
// SPDX-License-Identifier: MIT
//

import class Foundation.ProcessInfo
import PackageDescription

#if swift(<6)
let swiftConcurrency: SwiftSetting = .enableExperimentalFeature("SwiftConcurrency")
#else
let swiftConcurrency: SwiftSetting = .enableUpcomingFeature("SwiftConcurrency")
#endif


let package = Package(
name: "Spezi",
Expand All @@ -27,29 +34,60 @@ let package = Package(
],
dependencies: [
.package(url: "https://github.com/StanfordSpezi/SpeziFoundation", from: "1.0.2"),
.package(url: "https://github.com/StanfordBDHG/XCTRuntimeAssertions", from: "1.0.1")
],
.package(url: "https://github.com/StanfordBDHG/XCTRuntimeAssertions", from: "1.0.1"),
.package(url: "https://github.com/apple/swift-collections.git", from: "1.1.1")
] + swiftLintPackage(),
targets: [
.target(
name: "Spezi",
dependencies: [
.product(name: "SpeziFoundation", package: "SpeziFoundation"),
.product(name: "XCTRuntimeAssertions", package: "XCTRuntimeAssertions")
]
.product(name: "XCTRuntimeAssertions", package: "XCTRuntimeAssertions"),
.product(name: "OrderedCollections", package: "swift-collections")
],
swiftSettings: [
swiftConcurrency
],
plugins: [] + swiftLintPlugin()
),
.target(
name: "XCTSpezi",
dependencies: [
.target(name: "Spezi")
]
],
swiftSettings: [
swiftConcurrency
],
plugins: [] + swiftLintPlugin()
),
.testTarget(
name: "SpeziTests",
dependencies: [
.target(name: "Spezi"),
.target(name: "XCTSpezi"),
.product(name: "XCTRuntimeAssertions", package: "XCTRuntimeAssertions")
]
],
swiftSettings: [
swiftConcurrency
],
plugins: [] + swiftLintPlugin()
)
]
)

func swiftLintPlugin() -> [Target.PluginUsage] {
// Fully quit Xcode and open again with `open --env SPEZI_DEVELOPMENT_SWIFTLINT /Applications/Xcode.app`
if ProcessInfo.processInfo.environment["SPEZI_DEVELOPMENT_SWIFTLINT"] != nil {
[.plugin(name: "SwiftLintBuildToolPlugin", package: "SwiftLint")]
} else {
[]
}
}

func swiftLintPackage() -> [PackageDescription.Package.Dependency] {
if ProcessInfo.processInfo.environment["SPEZI_DEVELOPMENT_SWIFTLINT"] != nil {
[.package(url: "https://github.com/realm/SwiftLint.git", .upToNextMinor(from: "0.55.1"))]
} else {
[]
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ public class _CollectPropertyWrapper<Value> {

extension _CollectPropertyWrapper: StorageValueCollector {
public func retrieve<Repository: SharedRepository<SpeziAnchor>>(from repository: Repository) {
injectedValues = repository[CollectedModuleValues<Value>.self]?.map { $0.value } ?? []
injectedValues = repository[CollectedModuleValues<Value>.self].reduce(into: []) { partialResult, entry in
partialResult.append(contentsOf: entry.value)
}
}

func clear() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,74 +6,16 @@
// SPDX-License-Identifier: MIT
//

import Foundation
import OrderedCollections
import SpeziFoundation

protocol AnyCollectModuleValue {
associatedtype Value

var moduleReference: ModuleReference { get }
}

protocol AnyCollectModuleValues {
associatedtype Value

var values: [any AnyCollectModuleValue] { get }

mutating func removeValues(from module: any Module) -> Bool

func store(into storage: inout SpeziStorage)
}


struct CollectModuleValue<Value>: AnyCollectModuleValue {
let value: Value
let moduleReference: ModuleReference

init(_ value: Value) {
self.value = value

guard let module = Spezi.moduleInitContext else {
preconditionFailure("Tried to initialize CollectModuleValue with unknown module init context.")
}
self.moduleReference = ModuleReference(module)
}
}

/// Provides the ``KnowledgeSource`` for any value we store in the ``SpeziStorage`` that is
/// provided or request from am ``Module``.
///
/// For more information, look at the ``Module/Provide`` or ``Module/Collect`` property wrappers.
struct CollectedModuleValues<ModuleValue>: DefaultProvidingKnowledgeSource {
typealias Anchor = SpeziAnchor

typealias Value = [CollectModuleValue<ModuleValue>]

typealias Value = OrderedDictionary<UUID, [ModuleValue]>

static var defaultValue: Value {
[]
}
}


extension Array: AnyCollectModuleValues where Element: AnyCollectModuleValue {
typealias Value = Element.Value

var values: [any AnyCollectModuleValue] {
self
}

mutating func removeValues(from module: any Module) -> Bool {
let previousCount = count
removeAll { entry in
entry.moduleReference == ModuleReference(module)
}
return previousCount != count
}

func store(into storage: inout SpeziStorage) {
guard let values = self as? [CollectModuleValue<Value>] else {
preconditionFailure("Unexpected array type: \(type(of: self))")
}
storage[CollectedModuleValues<Value>.self] = values
[:]
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,25 @@
// SPDX-License-Identifier: MIT
//


import Foundation
import SpeziFoundation
import XCTRuntimeAssertions


/// A protocol that identifies a ``_ProvidePropertyWrapper`` which `Value` type is a `Collection`.
protocol CollectionBasedProvideProperty {
func collectArrayElements<Repository: SharedRepository<SpeziAnchor>>(into repository: inout Repository)

func clearValues()
}


/// A protocol that identifies a ``_ProvidePropertyWrapper`` which `Value` type is a `Optional`.
protocol OptionalBasedProvideProperty {
func collectOptional<Repository: SharedRepository<SpeziAnchor>>(into repository: inout Repository)

func clearValues()
}


Expand All @@ -28,10 +34,16 @@ public class _ProvidePropertyWrapper<Value> {
// swiftlint:disable:previous type_name
// We want the type to be hidden from autocompletion and documentation generation

/// Persistent identifier to store and remove @Provide values.
fileprivate let id = UUID()

private var storedValue: Value
private var collected = false


private weak var spezi: Spezi?


/// Access the store value.
/// - Note: You cannot access the value once it was collected.
public var wrappedValue: Value {
Expand All @@ -50,6 +62,15 @@ public class _ProvidePropertyWrapper<Value> {
public init(wrappedValue value: Value) {
self.storedValue = value
}

func inject(spezi: Spezi) {
self.spezi = spezi
}


deinit {
clear()
}
}


Expand Down Expand Up @@ -116,38 +137,54 @@ extension _ProvidePropertyWrapper: StorageValueProvider {
} else if let wrapperWithArray = self as? CollectionBasedProvideProperty {
wrapperWithArray.collectArrayElements(into: &repository)
} else {
repository.appendValues([CollectModuleValue(storedValue)])
repository.setValues(for: id, [storedValue])
}

collected = true
}

func clear() {
collected = false

if let wrapperWithOptional = self as? OptionalBasedProvideProperty {
wrapperWithOptional.clearValues()
} else if let wrapperWithArray = self as? CollectionBasedProvideProperty {
wrapperWithArray.clearValues()
} else {
spezi?.handleCollectedValueRemoval(for: id, of: Value.self)
}
}
}


extension _ProvidePropertyWrapper: CollectionBasedProvideProperty where Value: AnyArray {
func collectArrayElements<Repository: SharedRepository<SpeziAnchor>>(into repository: inout Repository) {
repository.appendValues(storedValue.unwrappedArray.map { CollectModuleValue($0) })
repository.setValues(for: id, storedValue.unwrappedArray)
}

func clearValues() {
spezi?.handleCollectedValueRemoval(for: id, of: Value.Element.self)
}
}


extension _ProvidePropertyWrapper: OptionalBasedProvideProperty where Value: AnyOptional {
func collectOptional<Repository: SharedRepository<SpeziAnchor>>(into repository: inout Repository) {
if let storedValue = storedValue.unwrappedOptional {
repository.appendValues([CollectModuleValue(storedValue)])
repository.setValues(for: id, [storedValue])
}
}

func clearValues() {
spezi?.handleCollectedValueRemoval(for: id, of: Value.Wrapped.self)
}
}


extension SharedRepository where Anchor == SpeziAnchor {
fileprivate mutating func appendValues<Value>(_ values: [CollectModuleValue<Value>]) {
fileprivate mutating func setValues<Value>(for id: UUID, _ values: [Value]) {
var current = self[CollectedModuleValues<Value>.self]
current.append(contentsOf: values)
current[id] = values
self[CollectedModuleValues<Value>.self] = current
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import SpeziFoundation
import SwiftUI


private class RemoteNotificationContinuation: DefaultProvidingKnowledgeSource {
private final class RemoteNotificationContinuation: DefaultProvidingKnowledgeSource {
typealias Anchor = SpeziAnchor

static let defaultValue = RemoteNotificationContinuation()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public struct UnregisterRemoteNotificationsAction {


/// Unregisters for all remote notifications received through Apple Push Notification service.
@MainActor
public func callAsFunction() {
#if os(watchOS)
let application = _Application.shared()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public protocol EnvironmentAccessible: AnyObject, Observable {}


extension EnvironmentAccessible {
var viewModifier: any ViewModifier {
ModelModifier(model: self)
var viewModifierInitialization: any ViewModifierInitialization {
ModelModifierInitialization(model: self)
}
}
17 changes: 15 additions & 2 deletions Sources/Spezi/Capabilities/Observable/ModelPropertyWrapper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,12 @@ public class _ModelPropertyWrapper<Model: Observable & AnyObject> {
// swiftlint:disable:previous type_name
// We want the type to be hidden from autocompletion and documentation generation

let id = UUID()
private var storedValue: Model?
private var collected = false

private weak var spezi: Spezi?


/// Access the store model.
///
Expand All @@ -44,12 +47,22 @@ public class _ModelPropertyWrapper<Model: Observable & AnyObject> {
public init(wrappedValue: Model) {
self.storedValue = wrappedValue
}


deinit {
clear()
}
}


extension _ModelPropertyWrapper: SpeziPropertyWrapper {
func clear() {
collected = false
spezi?.handleViewModifierRemoval(for: id)
}

func inject(spezi: Spezi) {
self.spezi = spezi
}
}

Expand Down Expand Up @@ -84,15 +97,15 @@ extension Module {


extension _ModelPropertyWrapper: ViewModifierProvider {
var viewModifier: (any ViewModifier)? {
var viewModifierInitialization: (any ViewModifierInitialization)? {
collected = true

guard let storedValue else {
assertionFailure("@Model with type \(Model.self) was collected but no value was provided!")
return nil
}

return ModelModifier(model: storedValue)
return ModelModifierInitialization(model: storedValue)
}

var placement: ModifierPlacement {
Expand Down
Loading
Loading