Skip to content

Commit d7b1d71

Browse files
authored
Refactor .introspect to use ViewModifier (#253)
1 parent 80356a6 commit d7b1d71

File tree

1 file changed

+34
-17
lines changed

1 file changed

+34
-17
lines changed

Sources/Introspect.swift

Lines changed: 34 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -12,33 +12,50 @@ public struct IntrospectionScope: OptionSet {
1212
}
1313

1414
extension View {
15-
@ViewBuilder
1615
public func introspect<SwiftUIViewType: IntrospectableViewType, PlatformSpecificEntity: PlatformEntity>(
1716
_ viewType: SwiftUIViewType,
1817
on platforms: (PlatformViewVersions<SwiftUIViewType, PlatformSpecificEntity>)...,
1918
scope: IntrospectionScope? = nil,
2019
customize: @escaping (PlatformSpecificEntity) -> Void
2120
) -> some View {
21+
self.modifier(IntrospectModifier(viewType, platforms: platforms, scope: scope, customize: customize))
22+
}
23+
}
24+
25+
struct IntrospectModifier<SwiftUIViewType: IntrospectableViewType, PlatformSpecificEntity: PlatformEntity>: ViewModifier {
26+
let id = IntrospectionViewID()
27+
let scope: IntrospectionScope
28+
let selector: IntrospectionSelector<PlatformSpecificEntity>?
29+
let customize: (PlatformSpecificEntity) -> Void
30+
31+
init(
32+
_ viewType: SwiftUIViewType,
33+
platforms: [PlatformViewVersions<SwiftUIViewType, PlatformSpecificEntity>],
34+
scope: IntrospectionScope?,
35+
customize: @escaping (PlatformSpecificEntity) -> Void
36+
) {
37+
self.scope = scope ?? viewType.scope
2238
if let platform = platforms.first(where: \.isCurrent) {
23-
let introspectionViewID = IntrospectionViewID()
24-
self.background(
25-
IntrospectionAnchorView(
26-
id: introspectionViewID
39+
self.selector = platform.selector ?? .default
40+
} else {
41+
self.selector = nil
42+
}
43+
self.customize = customize
44+
}
45+
46+
func body(content: Content) -> some View {
47+
if let selector {
48+
content
49+
.background(
50+
IntrospectionAnchorView(id: id)
51+
.frame(width: 0, height: 0)
2752
)
28-
.frame(width: 0, height: 0)
29-
)
30-
.overlay(
31-
IntrospectionView(
32-
id: introspectionViewID,
33-
selector: { controller in
34-
(platform.selector ?? .default)(controller, scope ?? viewType.scope)
35-
},
36-
customize: customize
53+
.overlay(
54+
IntrospectionView(id: id, selector: { selector($0, scope) }, customize: customize)
55+
.frame(width: 0, height: 0)
3756
)
38-
.frame(width: 0, height: 0)
39-
)
4057
} else {
41-
self
58+
content
4259
}
4360
}
4461
}

0 commit comments

Comments
 (0)