-
Notifications
You must be signed in to change notification settings - Fork 135
/
Item.swift
99 lines (87 loc) · 2.39 KB
/
Item.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
import SwiftUI
import SwiftUINavigation
struct Item: Equatable, Identifiable {
let id = UUID()
var color: Color?
var name: String
var status: Status
@CasePathable
enum Status: Equatable {
case inStock(quantity: Int)
case outOfStock(isOnBackOrder: Bool)
}
struct Color: Equatable, Hashable {
var name: String
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
static let defaults: [Self] = [
.red,
.green,
.blue,
.black,
.yellow,
.white,
]
static let red = Self(name: "Red", red: 1)
static let green = Self(name: "Green", green: 1)
static let blue = Self(name: "Blue", blue: 1)
static let black = Self(name: "Black")
static let yellow = Self(name: "Yellow", red: 1, green: 1)
static let white = Self(name: "White", red: 1, green: 1, blue: 1)
var swiftUIColor: SwiftUI.Color {
SwiftUI.Color(red: self.red, green: self.green, blue: self.blue)
}
}
}
struct ItemView: View {
@Binding var item: Item
var body: some View {
Form {
TextField("Name", text: self.$item.name)
Picker(selection: self.$item.color, label: Text("Color")) {
Text("None")
.tag(Item.Color?.none)
ForEach(Item.Color.defaults, id: \.name) { color in
Text(color.name)
.tag(Optional(color))
}
}
switch self.item.status {
case .inStock:
self.$item.status.inStock.map { $quantity in
Section {
Stepper("Quantity: \(quantity)", value: $quantity)
Button("Mark as sold out") {
withAnimation {
self.item.status = .outOfStock(isOnBackOrder: false)
}
}
} header: {
Text("In stock")
}
.transition(.opacity)
}
case .outOfStock:
self.$item.status.outOfStock.map { $isOnBackOrder in
Section {
Toggle("Is on back order?", isOn: $isOnBackOrder)
Button("Back in stock!") {
withAnimation {
self.item.status = .inStock(quantity: 1)
}
}
} header: {
Text("Out of stock")
}
.transition(.opacity)
}
}
}
}
}
#Preview {
WithState(initialValue: Item(color: nil, name: "", status: .inStock(quantity: 1))) { $item in
ItemView(item: $item)
}
}