-
-
Notifications
You must be signed in to change notification settings - Fork 156
Expand file tree
/
Copy pathSwiftUI.swift
More file actions
319 lines (268 loc) · 6.65 KB
/
SwiftUI.swift
File metadata and controls
319 lines (268 loc) · 6.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import SwiftUI
import Combine
extension Defaults {
@MainActor
final class Observable<Value: Serializable>: ObservableObject {
private var cancellable: AnyCancellable?
private var task: Task<Void, Never>?
var key: Defaults.Key<Value> {
didSet {
if key != oldValue {
observe()
}
}
}
var value: Value {
get { Defaults[key] }
set {
Defaults[key] = newValue
}
}
init(_ key: Key<Value>) {
self.key = key
observe()
}
deinit {
task?.cancel()
}
private func observe() {
// We only use this on the latest OSes (as of adding this) since the backdeploy library has a lot of bugs.
if #available(macOS 13, iOS 16, tvOS 16, watchOS 9, visionOS 1.0, *) {
task?.cancel()
// The `@MainActor` is important as the `.send()` method doesn't inherit the `@MainActor` from the class.
task = .detached(priority: .userInitiated) { @MainActor [weak self, key] in
for await _ in Defaults.updates(key, initial: false) {
guard let self else {
return
}
objectWillChange.send()
}
}
} else {
cancellable = Defaults.publisher(key, options: [.prior])
.sink { [weak self] change in
guard change.isPrior else {
return
}
Task { @MainActor in
self?.objectWillChange.send()
}
}
}
}
/**
Reset the key back to its default value.
*/
func reset() {
key.reset()
}
}
}
/**
Access stored values from SwiftUI.
This is similar to `@AppStorage` but it accepts a ``Defaults/Key`` and many more types.
*/
@MainActor
@propertyWrapper
public struct Default<Value: Defaults.Serializable>: @preconcurrency DynamicProperty {
@_documentation(visibility: private)
public typealias Publisher = AnyPublisher<Defaults.KeyChange<Value>, Never>
private let key: Defaults.Key<Value>
@StateObject private var observable: Defaults.Observable<Value>
/**
Get/set a `Defaults` item and also have the view be updated when the value changes. This is similar to `@State`.
- Important: You cannot use this in an `ObservableObject`. It's meant to be used in a `View`.
```swift
extension Defaults.Keys {
static let hasUnicorn = Key<Bool>("hasUnicorn", default: false)
}
struct ContentView: View {
@Default(.hasUnicorn) var hasUnicorn
var body: some View {
Text("Has Unicorn: \(hasUnicorn)")
Toggle("Toggle", isOn: $hasUnicorn)
Button("Reset") {
_hasUnicorn.reset()
}
}
}
```
*/
public init(_ key: Defaults.Key<Value>) {
self.key = key
self._observable = .init(wrappedValue: .init(key))
}
public var wrappedValue: Value {
get {
syncObservableKeyIfNeeded()
return observable.value
}
nonmutating set {
syncObservableKeyIfNeeded()
observable.value = newValue
}
}
public var projectedValue: Binding<Value> {
syncObservableKeyIfNeeded()
return $observable.value
}
/**
The default value of the key.
*/
public var defaultValue: Value { key.defaultValue }
/**
Combine publisher that publishes values when the `Defaults` item changes.
*/
public var publisher: Publisher { Defaults.publisher(key) }
@_documentation(visibility: private)
public mutating func update() {
_observable.update()
}
private func syncObservableKeyIfNeeded() {
guard observable.key != key else {
return
}
// Avoid touching `@StateObject` in `update()`, which triggers Xcode 16 warnings.
observable.key = key
}
/**
Reset the key back to its default value.
```swift
extension Defaults.Keys {
static let opacity = Key<Double>("opacity", default: 1)
}
struct ContentView: View {
@Default(.opacity) var opacity
var body: some View {
Button("Reset") {
_opacity.reset()
}
}
}
```
*/
public func reset() {
key.reset()
}
}
extension Default where Value: Equatable {
/**
Indicates whether the value is the same as the default value.
*/
public var isDefaultValue: Bool { wrappedValue == defaultValue }
}
extension Defaults {
/**
A SwiftUI `Toggle` view that is connected to a ``Defaults/Key`` with a `Bool` value.
The toggle works exactly like the SwiftUI `Toggle`.
```swift
extension Defaults.Keys {
static let showAllDayEvents = Key<Bool>("showAllDayEvents", default: false)
}
struct ShowAllDayEventsSetting: View {
var body: some View {
Defaults.Toggle("Show All-Day Events", key: .showAllDayEvents)
}
}
```
You can also listen to changes:
```swift
struct ShowAllDayEventsSetting: View {
var body: some View {
Defaults.Toggle("Show All-Day Events", key: .showAllDayEvents)
// Note that this has to be directly attached to `Defaults.Toggle`. It's not `View#onChange()`.
.onChange {
print("Value", $0)
}
}
}
```
*/
public struct Toggle<Label: View>: View {
@ViewStorage private var onChange: ((Bool) -> Void)?
private let label: () -> Label
private let inverted: Bool
// Intentionally using `@ObservedObject` over `@StateObject` so that the key can be dynamically changed.
@ObservedObject private var observable: Defaults.Observable<Bool>
public init(
key: Defaults.Key<Bool>,
inverted: Bool = false,
@ViewBuilder label: @escaping () -> Label
) {
self.inverted = inverted
self.label = label
self.observable = .init(key)
}
@_documentation(visibility: private)
public var body: some View {
SwiftUI.Toggle(
isOn: inverted ? $observable.value.toggled() : $observable.value,
label: label
)
.onChange(of: observable.value) {
onChange?(inverted ? !$0 : $0)
}
}
}
}
extension Defaults.Toggle<Text> {
public init(
_ title: some StringProtocol,
key: Defaults.Key<Bool>,
inverted: Bool = false
) {
self.init(key: key, inverted: inverted) {
Text(title)
}
}
}
extension Defaults.Toggle<Label<Text, Image>> {
public init(
_ title: some StringProtocol,
systemImage: String,
key: Defaults.Key<Bool>,
inverted: Bool = false
) {
self.init(key: key, inverted: inverted) {
Label(title, systemImage: systemImage)
}
}
}
extension Defaults.Toggle {
/**
Do something when the value changes to a different value.
*/
public func onChange(_ action: @escaping (Bool) -> Void) -> Self {
onChange = action
return self
}
}
@MainActor
@propertyWrapper
private struct ViewStorage<Value>: DynamicProperty {
@MainActor
private final class ValueBox {
var value: Value
init(_ value: Value) {
self.value = value
}
}
@State private var valueBox: ValueBox
var wrappedValue: Value {
get { valueBox.value }
nonmutating set {
valueBox.value = newValue
}
}
init(wrappedValue value: @autoclosure @escaping () -> Value) {
self._valueBox = .init(wrappedValue: ValueBox(value()))
}
}
extension Binding<Bool> {
func toggled() -> Self {
.init(
get: { !wrappedValue },
set: { wrappedValue = !$0 }
)
}
}