generated from StanfordBDHG/SwiftPackageTemplate
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add @LocalStorageEntry property wrapper
- Loading branch information
1 parent
6e8e6dd
commit 6ca9e97
Showing
3 changed files
with
54 additions
and
2 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,49 @@ | ||
// | ||
// This source file is part of the Stanford Spezi open-source project | ||
// | ||
// SPDX-FileCopyrightText: 2025 Stanford University and the project authors (see CONTRIBUTORS.md) | ||
// | ||
// SPDX-License-Identifier: MIT | ||
// | ||
|
||
import Combine | ||
import SwiftUI | ||
|
||
|
||
/// Access ``LocalStorage`` entries within a SwiftUI View. | ||
@propertyWrapper | ||
public struct LocalStorageEntry<Value>: DynamicProperty { | ||
private let key: LocalStorageKey<Value> | ||
|
||
@Environment(LocalStorage.self) private var localStorage | ||
@State private var internals = LocalStorageEntryInternals<Value>() | ||
|
||
public init(_ key: LocalStorageKey<Value>) { | ||
self.key = key | ||
} | ||
|
||
public func update() { | ||
internals.subscribe(to: key, in: localStorage) | ||
} | ||
|
||
public var wrappedValue: Value? { | ||
get { internals.value } | ||
set { try? localStorage.store(newValue, for: key) } | ||
} | ||
} | ||
|
||
|
||
@Observable private final class LocalStorageEntryInternals<Value> { | ||
fileprivate var value: Value? | ||
|
||
@ObservationIgnored | ||
private var cancellable: AnyCancellable? | ||
|
||
func subscribe(to key: LocalStorageKey<Value>, in localStorage: LocalStorage) { | ||
cancellable?.cancel() | ||
cancellable = key.publisher.sink { [weak self] newValue in | ||
self?.value = newValue | ||
} | ||
value = try? localStorage.load(key) | ||
} | ||
} |
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