-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPropertyInspector.swift
2202 lines (1858 loc) · 74.1 KB
/
PropertyInspector.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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// MIT License
//
// Copyright (c) 2024 Pedro Almeida
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// auto-generated file, do not edit directly
import Combine
import Foundation
import SwiftUI
struct ViewInspectabilityKey: EnvironmentKey {
static let defaultValue: Bool = true
}
struct RowDetailFontKey: EnvironmentKey {
static let defaultValue: Font = .caption
}
struct RowLabelFontKey: EnvironmentKey {
static let defaultValue: Font = .callout
}
extension EnvironmentValues {
var rowDetailFont: Font {
get { self[RowDetailFontKey.self] }
set { self[RowDetailFontKey.self] = newValue }
}
var rowLabelFont: Font {
get { self[RowLabelFontKey.self] }
set { self[RowLabelFontKey.self] = newValue }
}
var isInspectable: Bool {
get { self[ViewInspectabilityKey.self] }
set { self[ViewInspectabilityKey.self] = newValue }
}
}
struct PropertyPreferenceKey: PreferenceKey {
static var defaultValue = [PropertyType: Set<Property>]()
static func reduce(value: inout [PropertyType: Set<Property>], nextValue: () -> [PropertyType: Set<Property>]) {
value.merge(nextValue()) { lhs, rhs in
lhs.union(rhs)
}
}
}
struct TitlePreferenceKey: PreferenceKey {
static let defaultValue = LocalizedStringKey("Properties")
static func reduce(value _: inout LocalizedStringKey, nextValue _: () -> LocalizedStringKey) {}
}
struct RowDetailPreferenceKey: PreferenceKey {
static let defaultValue = RowViewBuilderRegistry()
static func reduce(value: inout RowViewBuilderRegistry, nextValue: () -> RowViewBuilderRegistry) {
value.merge(nextValue())
}
}
struct RowIconPreferenceKey: PreferenceKey {
static let defaultValue = RowViewBuilderRegistry()
static func reduce(value: inout RowViewBuilderRegistry, nextValue: () -> RowViewBuilderRegistry) {
value.merge(nextValue())
}
}
struct RowLabelPreferenceKey: PreferenceKey {
static let defaultValue = RowViewBuilderRegistry()
static func reduce(value: inout RowViewBuilderRegistry, nextValue: () -> RowViewBuilderRegistry) {
value.merge(nextValue())
}
}
extension Animation {
static let inspectorDefault: Animation = .snappy(duration: 0.25)
}
extension View {
@ViewBuilder
func ios16_scrollBounceBehaviorBasedOnSize() -> some View {
if #available(iOS 16.4, *) {
scrollBounceBehavior(.basedOnSize)
} else {
self
}
}
@ViewBuilder
func ios16_hideScrollIndicators(_ hide: Bool = true) -> some View {
if #available(iOS 16.0, *) {
scrollIndicators(hide ? .hidden : .automatic)
} else {
self
}
}
@ViewBuilder
func ios17_interpolateSymbolEffect() -> some View {
if #available(iOS 17.0, *) {
contentTransition(.symbolEffect(.automatic, options: .speed(2)))
} else if #available(iOS 16.0, *) {
contentTransition(.interpolate)
} else {
self
}
}
}
extension Context {
final class Data: ObservableObject {
private var cancellables = Set<AnyCancellable>()
private var _allObjects = [PropertyType: Set<Property>]()
private var _searchQuery = ""
var allProperties = [Property]()
var filters = Set<Filter<PropertyType>>()
@Published
var properties = [Property]() {
didSet {
#if VERBOSE
print("\(Self.self): Updated Properties")
for property in properties {
print("\t- \(property)")
}
#endif
}
}
@Published
var iconRegistry = RowViewBuilderRegistry() {
didSet {
#if VERBOSE
print("\(Self.self): Updated Icons \(iconRegistry)")
#endif
}
}
@Published
var labelRegistry = RowViewBuilderRegistry() {
didSet {
#if VERBOSE
print("\(Self.self): Updated Labels \(labelRegistry)")
#endif
}
}
@Published
var detailRegistry = RowViewBuilderRegistry() {
didSet {
#if VERBOSE
print("\(Self.self): Updated Details \(iconRegistry)")
#endif
}
}
var allObjects: [PropertyType: Set<Property>] {
get { _allObjects }
set {
guard _allObjects != newValue else { return }
_allObjects = newValue
makeProperties()
}
}
var searchQuery: String {
get { _searchQuery }
set {
guard _searchQuery != newValue else { return }
_searchQuery = newValue
makeProperties()
}
}
init() {
setupDebouncing()
}
private func isOn(filter: Filter<PropertyType>) -> Bool {
if let index = filters.firstIndex(of: filter) {
filters[index].isOn
} else {
false
}
}
func toggleFilter(_ filter: Filter<PropertyType>) -> Binding<Bool> {
Binding { [unowned self] in
if let index = filters.firstIndex(of: filter) {
filters[index].isOn
} else {
false
}
} set: { [unowned self] newValue in
if let index = self.filters.firstIndex(of: filter) {
filters[index].isOn = newValue
_allObjects[filter.wrappedValue]?.forEach { prop in
if prop.isHighlighted {
prop.isHighlighted = false
}
}
makeProperties()
}
}
}
var toggleAllFilters: Binding<Bool> {
let allSelected = !filters.map(\.isOn).contains(false)
return Binding {
allSelected
} set: { [unowned self] newValue in
for filter in filters {
filter.isOn = newValue
}
for set in _allObjects.values {
for prop in set where prop.isHighlighted {
prop.isHighlighted = false
}
}
makeProperties()
}
}
private func setupDebouncing() {
Just(_searchQuery)
.removeDuplicates()
.debounce(for: .milliseconds(150), scheduler: RunLoop.main)
.sink(receiveValue: { [unowned self] _ in
makeProperties()
})
.store(in: &cancellables)
}
private func isFilterEnabled(_ type: PropertyType) -> Bool? {
for filter in filters where filter.wrappedValue == type {
return filter.isOn
}
return nil
}
private func makeProperties() {
var all = Set<Property>()
var properties = Set<Property>()
var filters = Set<Filter<PropertyType>>()
for (type, set) in _allObjects {
let searchResult = search(in: set)
if !searchResult.isEmpty {
filters.insert(
Filter(
type,
isOn: isFilterEnabled(type) ?? true
)
)
}
all.formUnion(set)
properties.formUnion(searchResult)
}
withAnimation(.inspectorDefault) {
self.filters = filters
self.allProperties = Array(all)
self.properties = filter(in: Array(properties)).sorted()
}
}
private func search(in properties: Set<Property>) -> Set<Property> {
guard !_searchQuery.isEmpty else {
return properties
}
let query = _searchQuery.trimmingCharacters(in: .whitespacesAndNewlines)
guard query.count > 1 else {
return properties
}
return properties.filter {
if $0.stringValue.localizedCaseInsensitiveContains(query) { return true }
if $0.stringValueType.localizedStandardContains(query) { return true }
return $0.id.location.description.localizedStandardContains(query)
}
}
private func filter(in properties: [Property]) -> [Property] {
let activeTypes = Set(filters.filter { $0.isOn }.map(\.wrappedValue))
guard activeTypes.count != filters.count else {
return properties
}
let result = properties.filter {
activeTypes.contains($0.value.type)
}
return result
}
}
}
extension Context {
final class Filter<F> {
var wrappedValue: F
var isOn: Bool
init(_ wrappedValue: F, isOn: Bool) {
self.wrappedValue = wrappedValue
self.isOn = isOn
}
}
}
extension Context.Filter: Hashable where F: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(wrappedValue)
}
}
extension Context.Filter: Equatable where F: Equatable {
static func == (lhs: Context.Filter<F>, rhs: Context.Filter<F>) -> Bool {
lhs.wrappedValue == rhs.wrappedValue
}
}
extension Context.Filter: Comparable where F: Comparable {
static func < (rhs: Context.Filter<F>, lhs: Context.Filter<F>) -> Bool {
if rhs.isOn == lhs.isOn {
rhs.wrappedValue < lhs.wrappedValue
} else {
rhs.isOn && !lhs.isOn
}
}
}
struct HashableBox<Value>: Hashable {
let id = UUID()
let value: Value
init(_ value: Value) {
self.value = value
}
static func == (lhs: HashableBox<Value>, rhs: HashableBox<Value>) -> Bool {
lhs.id == rhs.id
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
final class HashableDictionary<Key, Value>: Hashable where Key: Hashable, Value: Hashable {
static func == (lhs: HashableDictionary<Key, Value>, rhs: HashableDictionary<Key, Value>) -> Bool {
lhs.data == rhs.data
}
private var data = [Key: Value]()
subscript(id: Key) -> Value? {
get { data[id] }
set { data[id] = newValue }
}
func hash(into hasher: inout Hasher) {
data.hash(into: &hasher)
}
func removeAll() {
data.removeAll(keepingCapacity: true)
}
}
/// `Property` encapsulates details about a specific property within a view or model, including its value, display metadata, and location.
/// This struct is intended for internal use within the ``PropertyInspector`` framework to track and manage property information dynamically.
final class Property: Identifiable, Comparable, Hashable, CustomStringConvertible {
/// A unique identifier for the property, ensuring that each instance is uniquely identifiable.
let id: PropertyID
/// The value of the property stored as `Any`, allowing it to accept any property type.
let value: PropertyValue
/// A binding to a Boolean that indicates whether the property is currently highlighted in the UI.
@Binding
var isHighlighted: Bool
/// Signal view updates
let token: AnyHashable
/// Returns the type of the value as a string, useful for dynamic type checks or displays.
var stringValueType: String {
String(describing: type(of: value.rawValue))
}
/// Returns the string representation of the property's value.
var stringValue: String {
String(describing: value.rawValue)
}
var description: String { stringValue }
/// Initializes a new `Property` with detailed information about its value and location.
/// - Parameters:
/// - value: The value of the property.
/// - isHighlighted: A binding to the Boolean indicating if the property is highlighted.
/// - location: The location of the property in the source code.
/// - offset: An offset used to uniquely sort the property when multiple properties share the same location.
init(
id: ID,
token: AnyHashable,
value: PropertyValue,
isHighlighted: Binding<Bool>
) {
self.token = token
self.id = id
self.value = value
_isHighlighted = isHighlighted
}
/// Compares two `Property` instances for equality, considering both their unique identifiers and highlight states.
static func == (lhs: Property, rhs: Property) -> Bool {
lhs.id == rhs.id &&
lhs.stringValue == rhs.stringValue &&
lhs.token == rhs.token
}
/// Determines if one `Property` should precede another in a sorted list, based on a composite string that includes their location and value.
static func < (lhs: Property, rhs: Property) -> Bool {
lhs.id < rhs.id
}
/// Contributes to the hashability of the property, incorporating its unique identifier into the hash.
func hash(into hasher: inout Hasher) {
hasher.combine(id)
hasher.combine(stringValue)
hasher.combine(token)
}
}
final class PropertyID {
private let _uuid = UUID()
/// The location of the property within the source code, provided for better traceability and debugging.
let location: PropertyLocation
let createdAt: Date
/// A computed string that provides a sortable representation of the property based on its location and offset.
private let sortString: String
init(
offset: Int,
createdAt: Date,
location: PropertyLocation
) {
self.location = location
self.createdAt = createdAt
sortString = [
location.id,
String(createdAt.timeIntervalSince1970),
String(offset)
].joined(separator: "_")
}
}
extension PropertyID: Hashable {
/// Compares two `Property` instances for equality, considering both their unique identifiers and highlight states.
static func == (lhs: PropertyID, rhs: PropertyID) -> Bool {
lhs._uuid == rhs._uuid
}
/// Contributes to the hashability of the property, incorporating its unique identifier into the hash.
func hash(into hasher: inout Hasher) {
hasher.combine(_uuid)
}
}
extension PropertyID: Comparable {
/// Determines if one `ID` should precede another in a sorted list, based on a composite string that includes their location and value.
static func < (lhs: PropertyID, rhs: PropertyID) -> Bool {
lhs.sortString.localizedStandardCompare(rhs.sortString) == .orderedAscending
}
}
/// An enumeration that defines the behavior of property highlights in the PropertyInspector.
///
/// `PropertyInspectorHighlightBehavior` controls how properties are highlighted when the
/// PropertyInspector is presented and dismissed.
public enum PropertyInspectorHighlightBehavior: String, CaseIterable {
/// Highlights must be manually managed by the user.
///
/// When using `manual`, any active highlights will remain active even after the inspector is dismissed.
/// This option gives you full control over the highlighting behavior.
case manual
/// Highlights are shown automatically when the inspector is presented and hidden when it is dismissed.
///
/// When using `automatic`, all visible views that contain inspectable properties are highlighted
/// automatically when the inspector is presented. Any active highlights are hidden automatically
/// upon dismissal of the inspector.
case automatic
/// Highlights are hidden automatically upon dismissal of the inspector.
///
/// When using `hideOnDismiss`, any active highlights are hidden when the inspector is dismissed.
/// This option ensures that highlights are automatically cleaned up when the inspector is no longer in view.
case hideOnDismiss
var label: LocalizedStringKey {
switch self {
case .manual:
"Manual"
case .automatic:
"Show / Hide Automatically"
case .hideOnDismiss:
"Hide Automatically"
}
}
}
/// `PropertyLocation` provides detailed information about the source location of a property within the code.
/// This includes the function, file, and line number where the property is used or modified, which is particularly useful for debugging and logging purposes.
final class PropertyLocation: Identifiable, Comparable, CustomStringConvertible {
/// A unique identifier for the location, composed of the file path, line number, and function name.
let id: String
/// The name of the function where the location is recorded.
let function: String
/// The full path of the file where the location is recorded.
let file: String
/// The line number in the file where the location is recorded.
let line: Int
/// A human-readable description of the location, typically formatted as "filename:line".
let description: String
/// Initializes a new `PropertyLocation` with the specified source code location details.
/// - Parameters:
/// - function: The name of the function encapsulating the location.
/// - file: The full path of the source file.
/// - line: The line number in the source file.
init(function: String, file: String, line: Int) {
let fileName = URL(string: file)?.lastPathComponent ?? file
id = "\(file):\(line):\(function)"
description = "\(fileName):\(line)"
self.function = function
self.file = file
self.line = line
}
/// Compares two `PropertyLocation` instances for ascending order based on their `id`.
/// - Returns: `true` if the identifier of the first location is less than the second, otherwise `false`.
static func < (lhs: PropertyLocation, rhs: PropertyLocation) -> Bool {
lhs.id.localizedStandardCompare(rhs.id) == .orderedAscending
}
/// Determines if two `PropertyLocation` instances are equal based on their identifiers.
/// - Returns: `true` if both locations have the same identifier, otherwise `false`.
static func == (lhs: PropertyLocation, rhs: PropertyLocation) -> Bool {
lhs.id == rhs.id
}
}
struct PropertyType: Identifiable {
let id: ObjectIdentifier
let rawValue: Any.Type
init<T>(_ subject: T) {
let start = Date()
let type: Any.Type
if T.self == Any.self {
// only use mirror as last resort
type = Mirror(reflecting: subject).subjectType
#if VERBOSE
let elapsedTime = (Date().timeIntervalSince(start) * 1000).formatted()
print(#function, "🐢", "Determined type \(type) in \(elapsedTime) ms")
#endif
} else {
type = T.self
#if VERBOSE
let elapsedTime = (Date().timeIntervalSince(start) * 1000).formatted()
print(#function, "🐰", "Determined type \(type) in \(elapsedTime) ms")
#endif
}
id = ObjectIdentifier(type)
rawValue = type
}
}
extension PropertyType: Comparable {
static func < (lhs: PropertyType, rhs: PropertyType) -> Bool {
lhs.description.localizedStandardCompare(rhs.description) == .orderedAscending
}
}
extension PropertyType: CustomDebugStringConvertible {
var debugDescription: String {
"<PropertyType: \(description)>"
}
}
extension PropertyType: CustomStringConvertible {
var description: String {
String(describing: rawValue)
}
}
extension PropertyType: Equatable {
static func == (lhs: RowViewBuilder.ID, rhs: RowViewBuilder.ID) -> Bool {
lhs.id == rhs.id
}
}
extension PropertyType: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
struct PropertyValue: Identifiable {
let id: PropertyValueID
let rawValue: Any
var type: PropertyType { id.type }
init<T>(_ value: T) {
id = ID(value)
rawValue = value
}
init(_ other: PropertyValue) {
self = other
}
}
struct PropertyValueID: Hashable {
let hashValue: Int
let type: PropertyType
init<T>(_ value: T) {
hashValue = String(describing: value).hashValue
type = PropertyType(value)
}
func hash(into hasher: inout Hasher) {
hasher.combine(hashValue)
hasher.combine(type)
}
}
struct RowViewBuilder: Hashable, Identifiable {
let id: PropertyType
let body: (Property) -> AnyView?
init<D, C: View>(@ViewBuilder body: @escaping (_ data: D) -> C) {
id = ID(D.self)
self.body = { property in
guard let castedValue = property.value.rawValue as? D else {
return nil
}
return AnyView(body(castedValue))
}
}
static func == (lhs: RowViewBuilder, rhs: RowViewBuilder) -> Bool {
lhs.id == rhs.id
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
struct RowViewBuilderRegistry: Hashable, CustomStringConvertible {
private var data: [PropertyType: RowViewBuilder]
private let cache = HashableDictionary<PropertyValueID, HashableBox<AnyView>>()
init(_ values: RowViewBuilder...) {
data = values.reduce(into: [:]) { partialResult, builder in
partialResult[builder.id] = builder
}
}
var description: String {
"\(Self.self)\(data.keys.map { "\n\t-\($0.rawValue)" }.joined())"
}
var isEmpty: Bool { data.isEmpty }
var identifiers: [PropertyType] {
Array(data.keys)
}
subscript(id: PropertyType) -> RowViewBuilder? {
get {
data[id]
}
set {
if data[id] != newValue {
data[id] = newValue
}
}
}
mutating func merge(_ other: RowViewBuilderRegistry) {
data.merge(other.data) { content, _ in
content
}
}
func merged(_ other: RowViewBuilderRegistry) -> Self {
var copy = self
copy.merge(other)
return copy
}
func makeBody(property: Property) -> AnyView? {
if let cached = resolveFromCache(property: property) {
#if VERBOSE
print("[PropertyInspector]", "♻️", property.stringValue, "resolved from cache")
#endif
return cached
} else if let body = createBody(property: property) {
#if VERBOSE
print("[PropertyInspector]", "🆕", property.stringValue, "created new view")
#endif
return body
}
return nil
}
private func resolveFromCache(property: Property) -> AnyView? {
if let cached = cache[property.value.id] {
return cached.value
}
return nil
}
#if DEBUG
private func createBody(property: Property) -> AnyView? {
var matches = [PropertyType: AnyView]()
for id in identifiers {
if let view = data[id]?.body(property) {
matches[id] = view
}
}
if matches.keys.count > 1 {
let matchingTypes = matches.keys.map { String(describing: $0.rawValue) }
print(
"[PropertyInspector]",
"⚠️ Warning:",
"Undefined behavior.",
"Multiple row builders",
"match '\(property.stringValueType)' declared in '\(property.id.location)':",
matchingTypes.sorted().joined(separator: ", ")
)
}
if let match = matches.first {
cache[property.value.id] = HashableBox(match.value)
return match.value
}
return nil
}
#else
private func createBody(property: Property) -> AnyView? {
for id in identifiers {
if let view = data[id]?.body(property) {
cache[property.value.id] = HashableBox(view)
return view
}
}
return nil
}
#endif
}
// swiftformat:disable stripunusedargs
public extension View {
/// Inspects the view itself.
func inspectSelf<S: Shape>(
shape: S = Rectangle(),
function: String = #function,
line: Int = #line,
file: String = #file
) -> some View {
inspectProperty(
self,
shape: shape,
function: function,
line: line,
file: file
)
}
/**
Adds a modifier for inspecting properties with dynamic debugging capabilities.
This method allows developers to dynamically inspect values of properties within a SwiftUI view, useful for debugging and during development to ensure that view states are correctly managed.
- Parameters:
- values: A variadic list of properties whose values you want to inspect.
- shape: The shape of the highlight.
- function: The function from which the inspector is called, generally used for debugging purposes. Defaults to the name of the calling function.
- line: The line number in the source file from which the inspector is called, aiding in pinpointing where inspections are set. Defaults to the line number in the source file.
- file: The name of the source file from which the inspector is called, useful for tracing the call in larger projects. Defaults to the filename.
- Returns: A view modified to include property inspection capabilities, reflecting the current state of the provided properties.
## Usage Example
```swift
Text("Current Count: \(count)").inspectProperty(count)
```
This can be particularly useful when paired with logging or during step-by-step debugging to monitor how and when your view's state changes.
- seeAlso: ``propertyInspectorHidden()`` and ``inspectSelf(shape:function:line:file:)``
*/
@_disfavoredOverload
func inspectProperty<S: Shape>(
_ values: Any...,
shape: S = Rectangle(),
function: String = #function,
line: Int = #line,
file: String = #file
) -> some View {
modifier(
PropertyWriter(
data: values.map(PropertyValue.init),
shape: shape,
location: .init(
function: function,
file: file,
line: line
)
)
)
}
/**
Adds a modifier for inspecting properties with dynamic debugging capabilities.
This method allows developers to dynamically inspect values of properties within a SwiftUI view, useful for debugging and during development to ensure that view states are correctly managed.
- Parameters:
- values: A variadic list of properties whose values you want to inspect.
- shape: The shape of the highlight.
- function: The function from which the inspector is called, generally used for debugging purposes. Defaults to the name of the calling function.
- line: The line number in the source file from which the inspector is called, aiding in pinpointing where inspections are set. Defaults to the line number in the source file.
- file: The name of the source file from which the inspector is called, useful for tracing the call in larger projects. Defaults to the filename.
- Returns: A view modified to include property inspection capabilities, reflecting the current state of the provided properties.
## Usage Example
```swift
Text("Current Count: \(count)").inspectProperty(count)
```
This can be particularly useful when paired with logging or during step-by-step debugging to monitor how and when your view's state changes.
- seeAlso: ``propertyInspectorHidden()`` and ``inspectSelf(shape:function:line:file:)``
*/
func inspectProperty<T, S: Shape>(
_ values: T...,
shape: S = Rectangle(),
function: String = #function,
line: Int = #line,
file: String = #file
) -> some View {
modifier(
PropertyWriter(
data: values.map {
PropertyValue($0)
},
shape: shape,
location: .init(
function: function,
file: file,
line: line
)
)
)
}
/**
Hides the view from property inspection.
Use this method to unconditionally hide nodes from the property inspector, which can be useful in many ways.
- Returns: A view that no longer shows its properties in the property inspector, effectively hiding them from debugging tools.
## Usage Example
```swift
Text("Hello, World!").propertyInspectorHidden()
```
This method can be used to safeguard sensitive information or simply to clean up the debugging output for views that no longer need inspection.
- seeAlso: <doc:/documentation/PropertyInspector/SwiftUICore/View/inspectProperty(_:shape:function:line:file:)-7u3kz> and <doc:/documentation/PropertyInspector/SwiftUICore/View/inspectProperty(_:shape:function:line:file:)-4bprj>.
*/
func propertyInspectorHidden() -> some View {
environment(\.isInspectable, false)
}
/**
Applies a modifier to inspect properties with custom icons based on their data type.
This method allows you to define custom icons for different data types displayed in the property inspector, enhancing the visual differentiation and user experience.
- Parameter data: The type of data for which the icon is defined.
- Parameter icon: A closure that returns the icon to use for the given data type.
- Returns: A modified view with the custom icon configuration applied to relevant properties.
## Usage Example
```swift
Text("Example Property")
.propertyInspectorRowIcon(for: String.self) { _ in
Image(systemName: "text.quote")
}
```
- seeAlso: ``propertyInspectorRowLabel(for:label:)``, ``propertyInspectorRowDetail(for:detail:)``, ``propertyInspectorRowIcon(for:systemName:)``
*/
func propertyInspectorRowIcon<D, Icon: View>(
for data: D.Type = Any.self,
@ViewBuilder icon: @escaping (_ data: D) -> Icon
) -> some View {
setPreference(RowIconPreferenceKey.self, body: icon)
}
/**
Applies a modifier to inspect properties with custom icons based on their data type.
This method allows you to define custom icons for different data types displayed in the property inspector, enhancing the visual differentiation and user experience.
- Parameter data: The type of data for which the icon is defined.
- Parameter systemName: A closure that returns the icon to use for the given data type.
- Returns: A modified view with the custom icon configuration applied to relevant properties.
## Usage Example
```swift
Text("Example Property").propertyInspectorRowIcon(systemName: "text.quote")
```
- seeAlso: ``propertyInspectorRowLabel(for:label:)``, ``propertyInspectorRowDetail(for:detail:)``, ``propertyInspectorRowIcon(for:icon:)``.
*/
func propertyInspectorRowIcon<D>(
for data: D.Type = Any.self,
systemName: String
) -> some View { // swiftformat:disable:this stripunusedargs
setPreference(RowIconPreferenceKey.self) { (_: D) in
Image(systemName: systemName)
}
}
/**
Defines a label for properties based on their data type within the property inspector.
Use this method to provide custom labels for different data types, which can help in categorizing and identifying properties more clearly in the UI.
- Parameter data: The type of data for which the label is defined.
- Parameter label: A closure that returns the label to use for the given data type.
- Returns: A modified view with the custom label configuration applied to relevant properties.
## Usage Example