-
Notifications
You must be signed in to change notification settings - Fork 147
/
ViewSearch.swift
519 lines (465 loc) · 21.7 KB
/
ViewSearch.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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
import SwiftUI
// MARK: - Search namespace and types
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public struct ViewSearch {
public enum Relation {
case child
case parent
}
public enum Traversal {
case depthFirst
case breadthFirst
}
public typealias Condition = (InspectableView<ViewType.ClassifiedView>) throws -> Bool
}
// MARK: - Public search API
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView {
/**
Searches for a `Text` view containing the specified string
- Parameter text: The string to look up for
- Parameter locale: The locale for the string extraction.
Defaults to `testsDefault` (i.e. `Locale(identifier: "en")`)
- Throws: An error if the view cannot be found
- Returns: A found `Text` view
*/
func find(text: String,
locale: Locale = .testsDefault
) throws -> InspectableView<ViewType.Text> {
return try find(textWhere: { value, _ in value == text }, locale: locale)
}
/**
Searches for a `Text` view matching a given condition, based on its string and attributes
- Parameter textWhere: The condition closure for detecting a matching `Text`.
Thrown errors are interpreted as "this view does not match"
- Parameter locale: The locale for the string extraction.
Defaults to `testsDefault` (i.e. `Locale(identifier: "en")`)
- Throws: An error if the view cannot be found
- Returns: A found `Text` view
*/
func find(textWhere condition: (String, ViewType.Text.Attributes) throws -> Bool,
locale: Locale = .testsDefault
) throws -> InspectableView<ViewType.Text> {
return try find(ViewType.Text.self, where: {
try condition(try $0.string(locale: locale), try $0.attributes())
})
}
/**
Searches for a `Button` view with matching title
- Parameter button: The title to look up for
- Parameter locale: The locale for the title extraction.
Defaults to `testsDefault` (i.e. `Locale(identifier: "en")`)
- Throws: An error if the view cannot be found
- Returns: A found `Button` view
*/
func find(button title: String,
locale: Locale = .testsDefault
) throws -> InspectableView<ViewType.Button> {
return try find(ViewType.Button.self, containing: title, locale: locale)
}
/**
Searches for a `Link` view with matching `URL` parameter
- Parameter link: The `URL` to look up for
- Throws: An error if the view cannot be found
- Returns: A found `Link` view
*/
@available(iOS 14.0, macOS 11.0, tvOS 14.0, *)
func find(link url: URL) throws -> InspectableView<ViewType.Link> {
return try find(ViewType.Link.self, where: { view in
try view.url() == url
})
}
/**
Searches for a `Link` view with matching label parameter
- Parameter link: The string to look up for as Link's label
- Parameter locale: The locale for the label extraction.
Defaults to `testsDefault` (i.e. `Locale(identifier: "en")`)
- Throws: An error if the view cannot be found
- Returns: A found `Link` view
*/
@available(iOS 14.0, macOS 11.0, tvOS 14.0, *)
func find(link label: String,
locale: Locale = .testsDefault
) throws -> InspectableView<ViewType.Link> {
return try find(ViewType.Link.self, containing: label, locale: locale)
}
/**
Searches for a `NavigationLink` view with matching label parameter
- Parameter navigationLink: The string to look up for
- Parameter locale: The locale for the label extraction.
Defaults to `testsDefault` (i.e. `Locale(identifier: "en")`)
- Throws: An error if the view cannot be found
- Returns: A found `NavigationLink` view
*/
func find(navigationLink string: String,
locale: Locale = .testsDefault
) throws -> InspectableView<ViewType.NavigationLink> {
return try find(ViewType.NavigationLink.self, containing: string, locale: locale)
}
/**
Searches for a view with given `id`
- Parameter viewWithId: The `id` to look up for
- Throws: An error if the view cannot be found
- Returns: A found view
*/
func find(viewWithId id: AnyHashable) throws -> InspectableView<ViewType.ClassifiedView> {
return try find { try $0.id() == id }
}
/**
Searches for a view with given `tag`
- Parameter viewWithTag: The `tag` to look up for
- Throws: An error if the view cannot be found
- Returns: A found view
*/
func find(viewWithTag tag: AnyHashable) throws -> InspectableView<ViewType.ClassifiedView> {
return try find { try $0.tag() == tag }
}
/**
Searches for a view with given `accessibilityLabel`
- Parameter viewWithAccessibilityLabel: The `accessibilityLabel` to look up for
- Throws: An error if the view cannot be found
- Returns: A found view
*/
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
func find(
viewWithAccessibilityLabel accessibilityLabel: String
) throws -> InspectableView<ViewType.ClassifiedView> {
return try find { try $0.accessibilityLabel().string() == accessibilityLabel }
}
/**
Searches for a view with given `accessibilityIdentifier`
- Parameter viewWithAccessibilityIdentifier: The `accessibilityIdentifier` to look up for
- Throws: An error if the view cannot be found
- Returns: A found view
*/
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
func find(
viewWithAccessibilityIdentifier accessibilityIdentifier: String
) throws -> InspectableView<ViewType.ClassifiedView> {
return try find { try $0.accessibilityIdentifier() == accessibilityIdentifier }
}
/**
Searches for a view of a specific type that matches a given condition
- Parameter customViewType: Your custom view type. For example: `ContentView.self`
- Parameter relation: The direction of the search. Defaults to `.child`
- Parameter where: The condition closure for detecting a matching view.
Thrown errors are interpreted as "this view does not match"
- Throws: An error if the view cannot be found
- Returns: A found view
*/
func find<V>(_ customViewType: V.Type,
relation: ViewSearch.Relation = .child,
where condition: (InspectableView<ViewType.View<V>>) throws -> Bool = { _ in true }
) throws -> InspectableView<ViewType.View<V>> where V: SwiftUI.View {
guard !Inspector.isSystemType(type: customViewType) else {
let name = Inspector.typeName(type: customViewType)
throw InspectionError.notSupported(
"Please use .find(ViewType.\(name).self) instead of .find(\(name).self) inspection call.")
}
return try find(ViewType.View<V>.self, relation: relation, where: condition)
}
/**
Searches for a view of a specific type, which enclosed hierarchy contains a `Text` with the provided string
- Parameter customViewType: Your custom view type. For example: `ContentView.self`
- Parameter containing: The string to look up for
- Parameter locale: The locale for the text extraction.
Defaults to `testsDefault` (i.e. `Locale(identifier: "en")`)
- Throws: An error if the view cannot be found
- Returns: A found view
*/
func find<V>(_ customViewType: V.Type,
containing string: String,
locale: Locale = .testsDefault
) throws -> InspectableView<ViewType.View<V>> where V: SwiftUI.View {
guard !Inspector.isSystemType(type: customViewType) else {
let name = Inspector.typeName(type: customViewType)
throw InspectionError.notSupported(
"Please use .find(ViewType.\(name).self) instead of .find(\(name).self) inspection call.")
}
return try find(ViewType.View<V>.self, containing: string, locale: locale)
}
/**
Searches for a view of a specific type, which enclosed hierarchy contains a `Text` with the provided string
- Parameter viewType: The type of the view. For example: `ViewType.HStack.self`
- Parameter containing: The string to look up for
- Parameter locale: The locale for the text extraction.
Defaults to `testsDefault` (i.e. `Locale(identifier: "en")`)
- Throws: An error if the view cannot be found
- Returns: A found view
*/
func find<T>(_ viewType: T.Type,
containing string: String,
locale: Locale = .testsDefault
) throws -> InspectableView<T> where T: BaseViewType {
return try find(ViewType.Text.self, where: { text in
try text.string(locale: locale) == string
&& (try? text.find(T.self, relation: .parent)) != nil
}).find(T.self, relation: .parent)
}
/**
Searches for a view of a specific type that matches a given condition
- Parameter viewType: The type of the view. For example: `ViewType.HStack.self`
- Parameter relation: The direction of the search. Defaults to `.child`
- Parameter traversal: The algorithm for view hierarchy traversal. Defaults to `.breadthFirst`
- Parameter skipFound: How many matching views to skip. Defaults to `0`
- Parameter where: The condition closure for detecting a matching view.
Thrown errors are interpreted as "this view does not match"
- Throws: An error if the view cannot be found
- Returns: A found view of the given type.
*/
func find<T>(_ viewType: T.Type,
relation: ViewSearch.Relation = .child,
traversal: ViewSearch.Traversal = .breadthFirst,
skipFound: Int = 0,
where condition: (InspectableView<T>) throws -> Bool = { _ in true }
) throws -> InspectableView<T> where T: BaseViewType {
let view = try find(relation: relation, traversal: traversal, skipFound: skipFound, where: { view -> Bool in
let typedView = try view.asInspectableView(ofType: T.self)
return try condition(typedView)
})
return try view.asInspectableView(ofType: T.self)
}
/**
Searches for a view that matches a given condition
- Parameter relation: The direction of the search. Defaults to `.child`
- Parameter traversal: The algorithm for view hierarchy traversal. Defaults to `.breadthFirst`
- Parameter skipFound: How many matching views to skip. Defaults to `0`
- Parameter where: The condition closure for detecting a matching view.
Thrown errors are interpreted as "this view does not match"
- Throws: An error if the view cannot be found
- Returns: A found view of the given type.
*/
func find(relation: ViewSearch.Relation = .child,
traversal: ViewSearch.Traversal = .breadthFirst,
skipFound: Int = 0,
where condition: ViewSearch.Condition
) throws -> InspectableView<ViewType.ClassifiedView> {
precondition(skipFound >= 0)
switch relation {
case .child:
return try findChild(condition: condition, traversal: traversal, skipFound: skipFound)
case .parent:
return try findParent(condition: condition, skipFound: skipFound)
}
}
/**
Searches for all the views of a specific type that match a given condition.
The hierarchy is traversed in depth-first order, meaning that you'll get views
ordered top-to-bottom as they appear in the code, regardless of their nesting depth.
- Parameter customViewType: Your custom view type. For example: `ContentView.self`
- Parameter where: The condition closure for detecting a matching view.
Thrown errors are interpreted as "this view does not match"
- Returns: An array of all matching views or an empty array if none are found.
*/
func findAll<V>(_ customViewType: V.Type,
where condition: (InspectableView<ViewType.View<V>>) throws -> Bool = { _ in true }
) -> [InspectableView<ViewType.View<V>>] where V: SwiftUI.View {
return findAll(ViewType.View<V>.self, where: condition)
}
/**
Searches for all the views of a specific type that match a given condition.
The hierarchy is traversed in depth-first order, meaning that you'll get views
ordered top-to-bottom as they appear in the code, regardless of their nesting depth.
- Parameter viewType: The type of the view. For example: `ViewType.HStack.self`
- Parameter where: The condition closure for detecting a matching view.
Thrown errors are interpreted as "this view does not match"
- Returns: An array of all matching views or an empty array if none are found.
*/
func findAll<T>(_ viewType: T.Type,
where condition: (InspectableView<T>) throws -> Bool = { _ in true }
) -> [InspectableView<T>] where T: BaseViewType {
return findAll(where: { view in
guard let typedView = try? view.asInspectableView(ofType: T.self)
else { return false }
return try condition(typedView)
}).compactMap({ try? $0.asInspectableView(ofType: T.self) })
}
/**
Searches for all the views that match a given condition.
The hierarchy is traversed in depth-first order, meaning that you'll get views
ordered top-to-bottom as they appear in the code, regardless of their nesting depth.
- Parameter where: The condition closure for detecting a matching view.
Thrown errors are interpreted as "this view does not match"
- Returns: An array of all matching views or an empty array if none are found.
*/
func findAll(where condition: ViewSearch.Condition) -> [InspectableView<ViewType.ClassifiedView>] {
var results: [InspectableView<ViewType.ClassifiedView>] = []
depthFirstTraversal(condition, stopOnFoundMatch: { view in
if let view = try? view.asInspectableView() {
results.append(view)
}
return false
}, identificationFailure: { _ in })
return results
}
}
// MARK: - Search
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
private extension UnwrappedView {
func findParent(condition: ViewSearch.Condition, skipFound: Int
) throws -> InspectableView<ViewType.ClassifiedView> {
var current = parentView
var counter = skipFound + 1
while let parent = try? current?.asInspectableView() {
if (try? condition(parent)) == true {
counter -= 1
}
if counter == 0 {
return parent
}
current = parent.parentView
}
throw InspectionError.searchFailure(skipped: skipFound + 1 - counter, blockers: [])
}
func findChild(condition: ViewSearch.Condition,
traversal: ViewSearch.Traversal,
skipFound: Int
) throws -> InspectableView<ViewType.ClassifiedView> {
var unknownViews: [Any] = []
var result: UnwrappedView?
var counter = skipFound + 1
traversal.search(in: self, condition: condition, stopOnFoundMatch: { view -> Bool in
counter -= 1
if counter == 0 {
result = view
return true
}
return false
}, identificationFailure: { content in
unknownViews.append(content.view)
})
if let result = result {
return try result.asInspectableView()
}
let blockers = blockersDescription(unknownViews)
throw InspectionError.searchFailure(skipped: skipFound + 1 - counter, blockers: blockers)
}
func blockersDescription(_ views: [Any]) -> [String] {
return views.map { view -> String in
let name = Inspector.typeName(value: view)
if name.hasPrefix("EnvironmentReaderView") {
return "navigationBarItems"
}
if name.hasPrefix(ViewType.Popover.standardModifierName) {
return "popover"
}
if !Inspector.isSystemType(value: view) {
let missingObjects = EnvironmentInjection.missingEnvironmentObjects(for: view)
if missingObjects.count > 0 {
return InspectionError
.missingEnvironmentObjects(view: name, objects: missingObjects)
.localizedDescription
}
}
return name
}
}
func breadthFirstTraversal(_ condition: ViewSearch.Condition,
stopOnFoundMatch: (UnwrappedView) -> Bool,
identificationFailure: (Content) -> Void) {
var queue: [(isSingle: Bool, children: LazyGroup<UnwrappedView>)] = []
queue.append((true, .init(count: 1, { _ in self })))
while !queue.isEmpty {
let (isSingle, children) = queue.remove(at: 0)
for offset in 0..<children.count {
guard let view = try? children.element(at: offset),
view.recursionAbsenceCheck()
else { continue }
let viewIndex = view.inspectionIndex ?? 0
let index = isSingle && viewIndex == 0 ? nil : viewIndex
guard let (identity, instance) = ViewSearch
.identifyAndInstantiate(view, index: index)
else {
if (try? condition(try view.asInspectableView())) == true,
stopOnFoundMatch(view) {
return
}
identificationFailure(view.content)
continue
}
if (try? condition(try instance.asInspectableView())) == true,
stopOnFoundMatch(instance) {
return
}
if let descendants = try? identity.children(instance),
descendants.count > 0 {
let isSingle = (identity.viewType is SingleViewContent.Type) && descendants.count == 1
queue.append((isSingle, descendants))
}
if let descendants = try? identity.modifiers(instance),
descendants.count > 0 {
queue.append((true, descendants))
}
if let descendants = try? identity.supplementary(instance),
descendants.count > 0 {
queue.append((true, descendants))
}
}
}
}
func depthFirstTraversal(_ condition: ViewSearch.Condition,
stopOnFoundMatch: (UnwrappedView) -> Bool,
identificationFailure: (Content) -> Void) {
var shouldContinue: Bool = true
depthFirstRecursion(shouldContinue: &shouldContinue, isSingle: true, offset: 0,
condition: condition, stopOnFoundMatch: stopOnFoundMatch,
identificationFailure: identificationFailure)
}
func depthFirstRecursion(shouldContinue: inout Bool,
isSingle: Bool, offset: Int,
condition: ViewSearch.Condition,
stopOnFoundMatch: (UnwrappedView) -> Bool,
identificationFailure: (Content) -> Void) {
if (try? condition(try self.asInspectableView())) == true,
stopOnFoundMatch(self) {
shouldContinue = false
}
guard shouldContinue, recursionAbsenceCheck() else { return }
let index = isSingle ? nil : offset
guard let (identity, instance) = ViewSearch
.identifyAndInstantiate(self, index: index) else {
identificationFailure(self.content)
return
}
guard let descendants = try? identity.allDescendants(instance)
else { return }
let isSingle = (identity.viewType is SingleViewContent.Type)
&& descendants.count == 1
for offset in 0..<descendants.count {
guard let descendant = try? descendants.element(at: offset) else { continue }
descendant.depthFirstRecursion(
shouldContinue: &shouldContinue, isSingle: isSingle, offset: offset,
condition: condition, stopOnFoundMatch: stopOnFoundMatch,
identificationFailure: identificationFailure)
guard shouldContinue else { return }
}
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
private extension UnwrappedView {
func recursionAbsenceCheck() -> Bool {
guard content.isCustomView else { return true }
let typeRef = type(of: content.view)
var isDirectParent = true
return (try? findParent(condition: { parent in
defer { isDirectParent = false }
return typeRef == type(of: parent.content.view) && !isDirectParent
}, skipFound: 0)) == nil
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
private extension ViewSearch.Traversal {
func search(in view: UnwrappedView,
condition: ViewSearch.Condition,
stopOnFoundMatch: (UnwrappedView) -> Bool,
identificationFailure: (Content) -> Void) {
switch self {
case .breadthFirst:
view.breadthFirstTraversal(condition, stopOnFoundMatch: stopOnFoundMatch,
identificationFailure: identificationFailure)
case .depthFirst:
view.depthFirstTraversal(condition, stopOnFoundMatch: stopOnFoundMatch,
identificationFailure: identificationFailure)
}
}
}