forked from pointfreeco/sqlite-data
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountersListFeature.swift
More file actions
109 lines (101 loc) · 2.33 KB
/
CountersListFeature.swift
File metadata and controls
109 lines (101 loc) · 2.33 KB
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
import CloudKit
import SQLiteData
import SwiftUI
import SwiftUINavigation
struct CountersListView: View {
@FetchAll var counters: [Counter]
@Dependency(\.defaultDatabase) var database
var body: some View {
List {
if !counters.isEmpty {
Section {
ForEach(counters) { counter in
CounterRow(counter: counter)
.buttonStyle(.borderless)
}
.onDelete { indexSet in
deleteRows(at: indexSet)
}
}
}
}
.navigationTitle("Counters")
.toolbar {
ToolbarItem(placement: .primaryAction) {
Button("Add") {
withErrorReporting {
try database.write { db in
try Counter.insert { Counter.Draft() }
.execute(db)
}
}
}
}
}
}
func deleteRows(at indexSet: IndexSet) {
withErrorReporting {
try database.write { db in
for index in indexSet {
try Counter.find(counters[index].id).delete()
.execute(db)
}
}
}
}
}
struct CounterRow: View {
let counter: Counter
@State var sharedRecord: SharedRecord?
@Dependency(\.defaultDatabase) var database
@Dependency(\.defaultSyncEngine) var syncEngine
var body: some View {
VStack {
HStack {
Text("\(counter.count)")
Button("-") {
decrementButtonTapped()
}
Button("+") {
incrementButtonTapped()
}
Spacer()
Button {
shareButtonTapped()
} label: {
Image(systemName: "square.and.arrow.up")
}
}
}
.sheet(item: $sharedRecord) { sharedRecord in
CloudSharingView(sharedRecord: sharedRecord)
}
}
func shareButtonTapped() {
Task {
sharedRecord = try await syncEngine.share(record: counter) { share in
share[CKShare.SystemFieldKey.title] = "Join my counter!"
}
}
}
func decrementButtonTapped() {
withErrorReporting {
try database.write { db in
try Counter.find(counter.id).update {
$0.count -= 1
}
.execute(db)
}
}
}
func incrementButtonTapped() {
withErrorReporting {
try database.write { db in
try Counter.find(counter.id).update {
$0.count += 1
}
.execute(db)
}
}
}
}