Skip to content

Commit 16c4a96

Browse files
committed
Show runtime warning when using layoutStep() without inspectLayout()
Closes #9
1 parent 1b02118 commit 16c4a96

File tree

1 file changed

+28
-5
lines changed

1 file changed

+28
-5
lines changed

Sources/LayoutInspector/DebugLayoutImpl.swift

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ struct InspectLayout: ViewModifier {
3131
.offset(x: inspectorFrame.minX, y: inspectorFrame.minY)
3232
.coordinateSpace(name: Self.coordSpaceName)
3333
}
34+
.environment(\.didCallInspectLayout, true)
3435
.environmentObject(logStore)
3536
}
3637

@@ -90,21 +91,43 @@ struct InspectLayout: ViewModifier {
9091
}
9192
}
9293

94+
enum DidCallInspectLayout: EnvironmentKey {
95+
static var defaultValue: Bool = false
96+
}
97+
98+
extension EnvironmentValues {
99+
var didCallInspectLayout: Bool {
100+
get { self[DidCallInspectLayout.self] }
101+
set { self[DidCallInspectLayout.self] = newValue }
102+
}
103+
}
104+
93105
@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
94106
struct DebugLayoutModifier: ViewModifier {
95107
var label: String
96108
var file: StaticString
97109
var line: UInt
110+
@Environment(\.didCallInspectLayout) private var didCallInspectLayout
111+
/// The log store for the current inspectLayout() subtree.
112+
///
113+
/// - Important: You must verify that `didCallInspectLayout == true` before accessing
114+
/// this property. Failure to do so will result in a crash as the object won't be
115+
/// in the environment.
98116
@EnvironmentObject private var logStore: LogStore
99117

100118
func body(content: Content) -> some View {
101-
DebugLayout(label: label, logStore: logStore) {
119+
if didCallInspectLayout {
120+
DebugLayout(label: label, logStore: logStore) {
121+
content
122+
}
123+
.onAppear {
124+
logStore.registerViewLabelAndWarnIfNotUnique(label, file: file, line: line)
125+
}
126+
.modifier(DebugLayoutSelectionHighlight(viewID: label))
127+
} else {
128+
let _ = runtimeWarning("%@:%llu: Calling .layoutStep() without a matching .inspectLayout() is illegal. Add .inspectLayout() as an ancestor of the view tree you want to inspect.", [String(describing: file), UInt64(line)], file: file, line: line)
102129
content
103130
}
104-
.onAppear {
105-
logStore.registerViewLabelAndWarnIfNotUnique(label, file: file, line: line)
106-
}
107-
.modifier(DebugLayoutSelectionHighlight(viewID: label))
108131
}
109132
}
110133

0 commit comments

Comments
 (0)