Skip to content

Commit cdf69de

Browse files
committed
Add ViewTraitCollection implementation
1 parent 3725a67 commit cdf69de

File tree

3 files changed

+93
-0
lines changed

3 files changed

+93
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
//
2+
// ViewTraitCollection.swift
3+
// OpenSwiftUI
4+
//
5+
// Audited for RELEASE_2021
6+
// Status: WIP
7+
// ID: 9929B476764059557433A108298EE66F
8+
9+
struct ViewTraitCollection {
10+
private var storage: [any AnyViewTrait]
11+
12+
private struct AnyTrait<Key: _ViewTraitKey>: AnyViewTrait {
13+
var value: Key.Value
14+
15+
init(value: Key.Value) {
16+
self.value = value
17+
}
18+
19+
var id: ObjectIdentifier { ObjectIdentifier(Key.self) }
20+
21+
subscript<V>() -> V {
22+
get { value as! V }
23+
set { value = newValue as! Key.Value }
24+
}
25+
}
26+
27+
subscript<Key: _ViewTraitKey>(_: Key.Type) -> Key.Value {
28+
get {
29+
value(for: Key.self)
30+
}
31+
set {
32+
if let index = storage.firstIndex(where: { $0.id == ObjectIdentifier(Key.self) }) {
33+
storage[index][] = newValue
34+
} else {
35+
storage.append(AnyTrait<Key>(value: newValue))
36+
}
37+
}
38+
}
39+
40+
func value<Key: _ViewTraitKey>(for _: Key.Type, defaultValue: Key.Value = Key.defaultValue) -> Key.Value {
41+
storage.first { $0.id == ObjectIdentifier(Key.self) }?[] ?? defaultValue
42+
}
43+
44+
mutating func setValueIfUnset<Key: _ViewTraitKey>(_ value: Key.Value, for _: Key.Type) {
45+
guard !storage.contains(where: { $0.id == ObjectIdentifier(Key.self) }) else {
46+
return
47+
}
48+
storage.append(AnyTrait<Key>(value: value))
49+
}
50+
51+
// func insertInteraction(for: OnInsertInteraction.Strategy) -> OnInsertInteraction? {
52+
// fatalError("TODO")
53+
// }
54+
//
55+
// var optionalTransition: AnyTransition? {
56+
// fatalError("TODO")
57+
// }
58+
}
59+
60+
private protocol AnyViewTrait {
61+
var id: ObjectIdentifier { get }
62+
subscript<V>() -> V { get set }
63+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
//
2+
// ViewTraitKey.swift
3+
// OpenSwiftUI
4+
//
5+
// Audited for RELEASE_2021
6+
// Status: Complete
7+
8+
protocol _ViewTraitKey {
9+
associatedtype Value
10+
static var defaultValue: Value { get }
11+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
//
2+
// ViewTraitKeys.swift
3+
// OpenSwiftUI
4+
//
5+
// Audited for RELEASE_2021
6+
// Status: Complete
7+
8+
struct ViewTraitKeys {
9+
var types: Set<ObjectIdentifier>
10+
var isDataDependent: Bool
11+
12+
mutating func insert<Key: _ViewTraitKey>(_ type: Key.Type) {
13+
types.insert(ObjectIdentifier(type))
14+
}
15+
16+
func contains<Key: _ViewTraitKey>(_ type: Key.Type) -> Bool {
17+
types.contains(ObjectIdentifier(type))
18+
}
19+
}

0 commit comments

Comments
 (0)