forked from siteline/swiftui-introspect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIntrospectionSelector.swift
75 lines (68 loc) · 2.6 KB
/
IntrospectionSelector.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
#if !os(watchOS)
@_spi(Advanced)
public struct IntrospectionSelector<Target: PlatformEntity>: Sendable {
@_spi(Advanced)
public static var `default`: Self { .from(Target.self, selector: { $0 }) }
@_spi(Advanced)
public static func from<Entry: PlatformEntity>(_ entryType: Entry.Type, selector: @MainActor @Sendable @escaping (Entry) -> Target?) -> Self {
.init(
receiverSelector: { controller in
controller.as(Entry.Base.self)?.receiver(ofType: Entry.self).flatMap(selector)
},
ancestorSelector: { controller in
controller.as(Entry.Base.self)?.ancestor(ofType: Entry.self).flatMap(selector)
}
)
}
private var receiverSelector: @MainActor @Sendable (IntrospectionPlatformViewController) -> Target?
private var ancestorSelector: @MainActor @Sendable (IntrospectionPlatformViewController) -> Target?
private init(
receiverSelector: @MainActor @Sendable @escaping (IntrospectionPlatformViewController) -> Target?,
ancestorSelector: @MainActor @Sendable @escaping (IntrospectionPlatformViewController) -> Target?
) {
self.receiverSelector = receiverSelector
self.ancestorSelector = ancestorSelector
}
@_spi(Advanced)
public func withReceiverSelector(_ selector: @MainActor @Sendable @escaping (PlatformViewController) -> Target?) -> Self {
var copy = self
copy.receiverSelector = selector
return copy
}
@_spi(Advanced)
public func withAncestorSelector(_ selector: @MainActor @Sendable @escaping (PlatformViewController) -> Target?) -> Self {
var copy = self
copy.ancestorSelector = selector
return copy
}
@MainActor func callAsFunction(_ controller: IntrospectionPlatformViewController, _ scope: IntrospectionScope) -> Target? {
if
scope.contains(.receiver),
let target = receiverSelector(controller)
{
return target
}
if
scope.contains(.ancestor),
let target = ancestorSelector(controller)
{
return target
}
return nil
}
}
extension PlatformViewController {
func `as`<Base: PlatformEntity>(_ baseType: Base.Type) -> (any PlatformEntity)? {
if Base.self == PlatformView.self {
#if canImport(UIKit)
return viewIfLoaded
#elseif canImport(AppKit)
return isViewLoaded ? view : nil
#endif
} else if Base.self == PlatformViewController.self {
return self
}
return nil
}
}
#endif