-
Notifications
You must be signed in to change notification settings - Fork 11
/
RootView.swift
398 lines (356 loc) · 15.9 KB
/
RootView.swift
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
import SwiftUI
import SherlockDebugForms
/// NOTE: Each view that owns `SherlockForm` needs to conform to `SherlockView` protocol.
@MainActor
struct RootView: View, SherlockView
{
/// NOTE:
/// `searchText` is required for `SherlockView` protocol.
/// This is the only requirement to define as `@State`, and pass it to `SherlockForm`.
@State public private(set) var searchText: String = ""
@AppStorage(UserDefaultsStringKey.username.rawValue)
private var username: String = "John Appleseed"
@AppStorage(UserDefaultsStringKey.email.rawValue)
private var email: String = "[email protected]"
@AppStorage(UserDefaultsStringKey.password.rawValue)
private var password: String = "admin"
@AppStorage(UserDefaultsStringKey.languageSelection.rawValue)
private var languageSelection: String = Constant.languages[0]
/// Index of `Constant.languages`.
@AppStorage(UserDefaultsIntKey.languageIntSelection.rawValue)
private var languageIntSelection: Int = 0
@AppStorage(UserDefaultsStringKey.status.rawValue)
private var status = Constant.Status.online
@AppStorage(UserDefaultsBoolKey.lowPowerMode.rawValue)
private var isLowPowerOn: Bool = false
@AppStorage(UserDefaultsBoolKey.slowAnimation.rawValue)
private var isSlowAnimation: Bool = false
@AppStorage(UserDefaultsDoubleKey.speed.rawValue)
private var speed: Double = 1.0
@AppStorage(UserDefaultsDoubleKey.fontSize.rawValue)
private var fontSize: Double = 10
@AppStorage(UserDefaultsDateKey.birthday.rawValue)
private var birthday: SherlockDate = .init()
@AppStorage(UserDefaultsDateKey.alarm.rawValue)
private var alarmDate: SherlockDate = .init()
@AppStorage(UserDefaultsStringKey.testLongUserDefaults.rawValue)
private var stringForTestingLongUserDefault: String = ""
/// - Note:
/// Attaching `.enableSherlockHUD(true)` to topmost view will allow using `showHUD`.
/// See `SherlockHUD` module for more information.
@Environment(\.showHUD)
private var showHUD: @MainActor (HUDMessage) -> Void
var body: some View
{
// NOTE:
// `SherlockForm` and `xxxCell` is where all the search magic is happening!
// Just treat `SherlockForm` as a normal `Form`, and use `Section` and plain SwiftUI views accordingly.
SherlockForm(searchText: $searchText) {
// Simple form cells.
Section {
// Customized form cell using `vstackCell`.
// NOTE: Combination of `SherlockForm` and `ContainerCell` is the secret of `keyword`-based searching.
customVStackCell
// Built-in form cells (using `hstackCell` internally).
// See `FormCells` source directory for more info.
textCell(icon: Image(systemName: "person.fill"), title: "User", value: username)
arrayPickerCell(icon: Image(systemName: "character.bubble"), title: "Language", selection: $languageSelection, values: Constant.languages)
casePickerCell(icon: Image(systemName: "person.badge.clock"), title: "Status", selection: $status)
toggleCell(icon: Image(systemName: "battery.25"), title: "Low Power Mode", isOn: $isLowPowerOn)
} header: {
Text("Simple form cells")
} footer: {
if searchText.isEmpty {
Text("Tip: Long-press cells to copy!")
}
}
// More form cells
Section {
textFieldCell(icon: Image(systemName: "character.cursor.ibeam"), title: "Editable", value: $username) {
$0
.multilineTextAlignment(.trailing)
.textFieldStyle(RoundedBorderTextFieldStyle())
}
textEditorCell(icon: Image(systemName: "character.cursor.ibeam"), title: "Multiline Editable", value: $username) {
$0
.multilineTextAlignment(.trailing)
.frame(maxHeight: 100)
}
// Array picker cell that uses `languageIntSelection` (index) as state.
arrayPickerCell(
icon: Image(systemName: "filemenu.and.cursorarrow"),
title: "Int Picker",
selection: Binding(
get: { Constant.languages[languageIntSelection] },
set: { newValue in
guard let index = Constant.languages.firstIndex(of: newValue) else { return }
languageIntSelection = index
}
),
values: Constant.languages
)
arrayPickerCell(
icon: Image(systemName: "filemenu.and.cursorarrow"),
title: "Async Picker",
selection: $languageSelection,
accessory: {
Text("Default")
.foregroundColor(.gray)
Spacer().frame(width: 8)
ProgressView()
},
action: {
// Simulating async work...
try await Task.sleep(nanoseconds: 3_000_000_000)
return Constant.languages
},
valueType: String.self
)
sliderCell(
icon: Image(systemName: "speedometer"),
title: "Speed",
value: $speed,
in: 0.5 ... 2.0,
step: 0.1,
maxFractionDigits: 1,
valueString: { "x\($0)" },
sliderLabel: { EmptyView() },
minimumValueLabel: { Image(systemName: "tortoise") },
maximumValueLabel: { Image(systemName: "hare") },
onEditingChanged: { print("onEditingChanged", $0) }
)
stepperCell(
icon: Image(systemName: "textformat.size"),
title: "Font Size",
value: $fontSize,
in: 8 ... 24,
step: 1,
maxFractionDigits: 0,
valueString: { "\($0) pt" }
)
datePickerCell(
icon: Image(systemName: "birthday.cake"),
title: "Birthday",
selection: $birthday.date,
in: .distantPast ... Date(),
displayedComponents: .date
)
datePickerCell(
icon: Image(systemName: "alarm"),
title: "Alarm",
selection: $alarmDate.date,
displayedComponents: [.hourAndMinute, .date]
)
} header: {
Text("More form cells")
}
// NOTE:
// `hstackCell` is useful for more customizable HStack
// such as manually registering search keywords and configuring context-menu.
//
// Here, `hstackCell` is used with default configuration, which automatically hides
// whenever search happens, and no context-menu is set.
Section {
hstackCell {
Text("Email").frame(width: 80, alignment: .leading)
Spacer(minLength: 16)
TextField("Input Email", text: $email)
}
hstackCell {
Text("Password").frame(width: 80, alignment: .leading)
Spacer(minLength: 16)
SecureField("Input Password", text: $password)
}
} header: {
Text("HStack Cell (More customizable)")
}
// Navigation Link Cell (`navigationLinkCell`)
Section {
navigationLinkCell(
icon: Image(systemName: "person.fill"),
title: "UserDefaults",
destination: {
UserDefaultsListView(
editConfiguration: .init(
boolKeys: Array(UserDefaultsBoolKey.allCases.map(\.rawValue)),
stringKeys: Array(UserDefaultsStringKey.allCases.map(\.rawValue)),
dateKeys: Array(UserDefaultsDateKey.allCases.map(\.rawValue)),
intKeys: Array(UserDefaultsIntKey.allCases.map(\.rawValue)),
doubleKeys: Array(UserDefaultsDoubleKey.allCases.map(\.rawValue))
)
)
}
)
navigationLinkCell(
icon: Image(systemName: "app.badge"),
title: "App Info",
destination: { AppInfoView() }
)
navigationLinkCell(
icon: Image(systemName: "iphone"),
title: "Device Info",
destination: { DeviceInfoView() }
)
navigationLinkCell(icon: Image(systemName: "doc.richtext"), title: "Custom Page", destination: {
CustomView()
})
navigationLinkCell(icon: Image(systemName: "doc.richtext"), title: "Custom Page (Recursive)", destination: RootView.init)
navigationLinkCell(icon: Image(systemName: "list.bullet"), title: "Simple List", destination: {
ListView()
})
navigationLinkCell(icon: Image(systemName: "list.bullet.indent"), title: "Nested List", destination: {
NestedListView()
})
} header: {
Text("Navigation Link Cell")
} footer: {
if searchText.isEmpty {
Text("Tip: Custom page (even this page) is just a plain SwiftUI View.")
}
}
// Buttons (`buttonCell`)
Section {
buttonCell(
icon: Image(systemName: "trash"),
title: "Reset UserDefaults",
action: {
Helper.deleteUserDefaults()
showHUD(.init(message: "Finished resetting UserDefaults"))
}
)
buttonCell(
icon: Image(systemName: "trash"),
title: "Delete Caches",
action: {
// Fake long task...
try await Task.sleep(nanoseconds: 1_000_000_000)
try? Helper.deleteAllCaches()
showHUD(.init(message: "Finished deleting caches"))
}
)
if #available(iOS 15.0, *) {
// `buttonCell` with `confirmationDialog`.
buttonDialogCell(
icon: Image(systemName: "trash"),
title: "Delete All Contents",
dialogTitle: nil,
dialogButtons: [
.init(title: "Delete All Contents", role: .destructive) {
// Fake long task...
try await Task.sleep(nanoseconds: 2_000_000_000)
try? Helper.deleteAllFilesAndCaches()
showHUD(.init(message: "Finished deleting all contents"))
},
.init(title: "Cancel", role: .cancel) {
print("Cancelled")
}
]
)
}
else {
buttonCell(icon: Image(systemName: "person.fill"), title: "Delete All Contents", action: {
try? Helper.deleteAllFilesAndCaches()
})
}
} header: {
Text("Buttons")
} footer: {
if searchText.isEmpty {
Text("Tip: Last button is ButtonDialog.")
}
}
// Slow motion (`toggleCell`)
Section {
toggleCell(icon: Image(systemName: "figure.roll"), title: "Slow Animation", isOn: $isSlowAnimation)
.onChange(of: isSlowAnimation) { isSlowAnimation in
// Workaround:
// Immediately setting animation speed after `Toggle` change will cause
// its malformed UI, so add `sleep` to workaround (NOTE: 500 ms is not enough).
Task { @MainActor in
try await Task.sleep(nanoseconds: 1_000_000_000)
setAnimationSpeed(isSlowAnimation: isSlowAnimation)
}
}
.onAppear {
setAnimationSpeed(isSlowAnimation: isSlowAnimation)
}
} header: {
Text("Slow motion")
}
// Full-Text Search Result:
// Show navigationLink's search results as well.
if !searchText.isEmpty {
UserDefaultsListSectionsView(
searchText: searchText,
maxRecentlyUsedCount: 0,
sectionHeader: { sectionHeader(prefixes: "UserDefaults", title: $0) }
)
AppInfoSectionsView(
searchText: searchText,
sectionHeader: { sectionHeader(prefixes: "App Info", title: $0) }
)
DeviceInfoSectionsView(
searchText: searchText,
sectionHeader: { sectionHeader(prefixes: "Device Info", title: $0) }
)
}
}
.navigationTitle("Settings")
// NOTE:
// Use `formCellCopyable` here (as a wrapper of entire `SherlockForm`) to allow ALL `xxxCell`s to be copyable.
// To Make each cell copyable one by one instead, call it as a wrapper of each form cell.
.formCellCopyable(true)
// For aligning icons and texts horizontally.
.formCellIconWidth(30)
}
/// Customized form cell using `vstackCell`.
@ViewBuilder
private var customVStackCell: some View
{
vstackCell(
keywords: "Add", "your", "favorite", "keywords", "as much as possible", "Hello", "SherlockForms",
copyableKeyValue: .init(key: "Hello SherlockForms!"),
alignment: .center,
content: {
Text("🕵️♂️").font(.system(size: 48))
Text("Hello SherlockForms!").font(.title)
}
)
// NOTE:
// `formCellContentModifier` allows to modify `cellContent` that wraps `vstackCell`'s `content`).
//
// This method may sometimes be needed for SwiftUI View method-chaining
// to NOT start from "receiver" but from its `cellContent`.
.formCellContentModifier { cellContent in
cellContent
.frame(maxWidth: .greatestFiniteMagnitude, maxHeight: 150)
.padding()
.onTapGesture {
print("Hello SherlockForms!")
}
}
}
}
// MARK: - Private
private func sectionHeader(prefixes: String..., title: String) -> String
{
(prefixes + [title]).filter { !$0.isEmpty }.joined(separator: " > ")
}
@MainActor
private func setAnimationSpeed(isSlowAnimation: Bool)
{
if isSlowAnimation {
Helper.setAnimationSpeed(0.1)
}
else {
Helper.setAnimationSpeed(1)
}
}
// MARK: - Previews
struct RootView_Previews: PreviewProvider
{
static var previews: some View
{
RootView()
}
}