forked from ole/swiftui-layout-inspector
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDebugLayoutLog.swift
209 lines (184 loc) · 7.53 KB
/
DebugLayoutLog.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
import SwiftUI
func logLayoutStep(_ label: String, step: LogEntry.Step) {
DispatchQueue.main.async {
guard let prevEntry = LogStore.shared.log.last else {
// First log entry → start at indent 0.
LogStore.shared.log.append(LogEntry(label: label, step: step, indent: 0))
return
}
var newEntry = LogEntry(label: label, step: step, indent: prevEntry.indent)
let isSameView = prevEntry.label == label
switch (isSameView, prevEntry.step, step) {
case (true, .proposal(let prop), .response(let resp)):
// Response follows immediately after proposal for the same view.
// → We want to display them in a single row.
// → Coalesce both layout steps.
LogStore.shared.log.removeLast()
newEntry = prevEntry
newEntry.step = .proposalAndResponse(proposal: prop, response: resp)
LogStore.shared.log.append(newEntry)
case (_, .proposal, .proposal):
// A proposal follows a proposal → nested view → increment indent.
newEntry.indent += 1
LogStore.shared.log.append(newEntry)
case (_, .response, .response),
(_, .proposalAndResponse, .response):
// A response follows a response → last child returns to parent → decrement indent.
newEntry.indent -= 1
LogStore.shared.log.append(newEntry)
default:
// Keep current indentation.
LogStore.shared.log.append(newEntry)
}
}
}
/// A custom layout that clears the DebugLayout log
/// at the point where it's placed in the view tree.
struct ClearDebugLayoutLog: Layout {
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
assert(subviews.count == 1)
DispatchQueue.main.async {
LogStore.shared.log.removeAll()
LogStore.shared.viewLabels.removeAll()
}
return subviews[0].sizeThatFits(proposal)
}
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
assert(subviews.count == 1)
subviews[0].place(at: bounds.origin, proposal: proposal)
}
}
public final class LogStore: ObservableObject {
public static let shared: LogStore = .init()
@Published var log: [LogEntry] = []
var viewLabels: Set<String> = []
func registerViewLabelAndWarnIfNotUnique(_ label: String, file: StaticString, line: UInt) {
DispatchQueue.main.async {
if self.viewLabels.contains(label) {
let message: StaticString = "Duplicate view label '%s' detected. Use unique labels in debugLayout() calls"
runtimeWarning(message, [label], file: file, line: line)
}
self.viewLabels.insert(label)
}
}
}
struct LogEntry: Identifiable {
enum Step {
case proposal(ProposedViewSize)
case response(CGSize)
case proposalAndResponse(proposal: ProposedViewSize, response: CGSize)
}
var id: UUID = .init()
var label: String
var step: Step
var indent: Int
var proposal: ProposedViewSize? {
switch step {
case .proposal(let p): return p
case .response(_): return nil
case .proposalAndResponse(proposal: let p, response: _): return p
}
}
var response: CGSize? {
switch step {
case .proposal(_): return nil
case .response(let r): return r
case .proposalAndResponse(proposal: _, response: let r): return r
}
}
}
struct DebugLayoutSelectedViewID: EnvironmentKey {
static var defaultValue: String? { nil }
}
extension EnvironmentValues {
var debugLayoutSelectedViewID: String? {
get { self[DebugLayoutSelectedViewID.self] }
set { self[DebugLayoutSelectedViewID.self] = newValue }
}
}
public struct DebugLayoutLogView: View {
@Binding var selection: String?
@ObservedObject var logStore: LogStore
private static let tableRowHorizontalPadding: CGFloat = 8
private static let tableRowVerticalPadding: CGFloat = 4
public init(selection: Binding<String?>? = nil, logStore: LogStore = LogStore.shared) {
if let binding = selection {
self._selection = binding
} else {
var nirvana: String? = nil
self._selection = Binding(get: { nirvana }, set: { nirvana = $0 })
}
self._logStore = ObservedObject(wrappedValue: logStore)
}
public var body: some View {
ScrollView(.vertical) {
Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 0, verticalSpacing: 0) {
// Table header row
GridRow {
Text("View")
Text("Proposal")
Text("Response")
}
.font(.headline)
.padding(.vertical, Self.tableRowVerticalPadding)
.padding(.horizontal, Self.tableRowHorizontalPadding)
// Table header separator line
Rectangle().fill(.secondary)
.frame(height: 1)
.gridCellUnsizedAxes(.horizontal)
.padding(.vertical, Self.tableRowVerticalPadding)
.padding(.horizontal, Self.tableRowHorizontalPadding)
// Table rows
ForEach(logStore.log) { item in
let isSelected = selection == item.label
GridRow {
HStack(spacing: 0) {
indentation(level: item.indent)
Text(item.label)
.font(.body)
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
Text(item.proposal?.pretty ?? "…")
.monospacedDigit()
.fixedSize()
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
Text(item.response?.pretty ?? "…")
.monospacedDigit()
.fixedSize()
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
}
.font(.callout)
.padding(.vertical, Self.tableRowVerticalPadding)
.padding(.horizontal, Self.tableRowHorizontalPadding)
.foregroundColor(isSelected ? .white : nil)
.background(isSelected ? Color.accentColor : .clear)
.contentShape(Rectangle())
.onTapGesture {
selection = isSelected ? nil : item.label
}
}
}
.padding(.vertical, 8)
}
.background {
#if os(macOS)
Color(white: 0.8)
#else
Color(uiColor: .secondarySystemBackground)
#endif
}
}
private func indentation(level: Int) -> some View {
ForEach(0 ..< level, id: \.self) { _ in
Color.clear
.frame(width: 16)
.overlay(alignment: .leading) {
Rectangle()
.frame(width: 1)
.padding(.leading, 4)
// Compensate for cell padding, we want continuous vertical lines.
.padding(.vertical, -Self.tableRowVerticalPadding)
}
}
}
}