-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRoutineRunList.swift
More file actions
205 lines (168 loc) · 6.98 KB
/
RoutineRunList.swift
File metadata and controls
205 lines (168 loc) · 6.98 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
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
//
// RoutineRunList.swift
//
// Copyright 2023 OpenAlloc LLC
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
import CoreData
import os
import StoreKit
import SwiftUI
import Compactor
import Tabler
import TrackerLib
import TrackerUI
import TroutLib
import TroutUI
struct MRoutineRunList: View {
@Environment(\.requestReview) private var requestReview
@Environment(\.verticalSizeClass) private var verticalSizeClass
@Environment(\.colorScheme) private var colorScheme
@Environment(\.managedObjectContext) private var viewContext
@EnvironmentObject private var router: TroutRouter
typealias Sort = TablerSort<ZRoutineRun>
typealias Context = TablerContext<ZRoutineRun>
typealias ProjectedValue = ObservedObject<ZRoutineRun>.Wrapper
// MARK: - Parameters
private var archiveStore: NSPersistentStore
init(archiveStore: NSPersistentStore) {
self.archiveStore = archiveStore
let predicate = ZRoutineRun.getPredicate(userRemoved: false)
let sortDescriptors = ZRoutineRun.byStartedAt(ascending: false)
let request = makeRequest(ZRoutineRun.self,
predicate: predicate,
sortDescriptors: sortDescriptors,
inStore: archiveStore)
_routineRuns = FetchRequest<ZRoutineRun>(fetchRequest: request)
}
// MARK: - Locals
private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!,
category: String(describing: MRoutineRunList.self))
private let columnSpacing: CGFloat = 10
private var columnPadding: EdgeInsets {
EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)
// EdgeInsets(top: 0, leading: 5, bottom: 0, trailing: 5)
}
private static let df: DateFormatter = {
let df = DateFormatter()
df.dateStyle = .short
df.timeStyle = .none
return df
}()
@FetchRequest private var routineRuns: FetchedResults<ZRoutineRun>
private var listConfig: TablerListConfig<ZRoutineRun> {
TablerListConfig<ZRoutineRun>(
onDelete: userRemoveAction
)
}
private var gridItems: [GridItem] { [
GridItem(.flexible(minimum: 180), spacing: columnSpacing, alignment: .leading),
GridItem(.flexible(minimum: 70), spacing: columnSpacing, alignment: .leading),
GridItem(.flexible(minimum: 70), spacing: columnSpacing, alignment: .leading),
] }
private static let tc = TimeCompactor(ifZero: "", style: .medium, roundSmallToWhole: false)
// support for app review prompt
@SceneStorage("has-been-prompted-for-app-review") private var hasBeenPromptedForAppReview = false
private let minimumRunsForAppReviewAlert = 30
// MARK: - Views
var body: some View {
TablerList(listConfig,
header: header,
row: listRow,
rowBackground: rowBackground,
results: routineRuns)
.listStyle(.plain)
.onAppear(perform: appearAction)
}
private func header(ctx _: Binding<Context>) -> some View {
LazyVGrid(columns: gridItems, alignment: .leading) {
Text("Routine")
.padding(columnPadding)
Text("Date")
.padding(columnPadding)
Text("Duration")
.padding(columnPadding)
}
}
@ViewBuilder
private func listRow(element: ZRoutineRun) -> some View {
Button(action: { detailAction(zRoutineRun: element) }) {
LazyVGrid(columns: gridItems, alignment: .leading) {
Text(element.zRoutine?.name ?? "")
.lineLimit(1)
.padding(columnPadding)
startedAtText(element.startedAt)
.lineLimit(1)
.padding(columnPadding)
durationText(element.elapsedSecs)
.lineLimit(1)
.padding(columnPadding)
}
.frame(maxWidth: .infinity)
}
}
private func rowBackground(_: ZRoutineRun) -> some View {
EntityBackground(routineColor)
}
private func startedAtText(_ date: Date?) -> some View {
guard let date else { return Text("") }
return Text(Self.df.string(from: date))
}
private func durationText(_ duration: TimeInterval) -> some View {
Text(Self.tc.string(from: duration as NSNumber) ?? "")
}
// MARK: - Properties
// MARK: - Actions
private func appearAction() {
guard !hasBeenPromptedForAppReview,
routineRuns.count >= minimumRunsForAppReviewAlert else { return }
hasBeenPromptedForAppReview = true
logger.notice("\(#function): attempting to request review, which may not work")
requestReview()
}
private func detailAction(zRoutineRun: ZRoutineRun) {
router.path.append(TroutRoute.taskRunList(zRoutineRun.uriRepresentation))
}
// NOTE: 'removes' matching records, where present, from both mainStore and archiveStore.
private func userRemoveAction(at offsets: IndexSet) {
do {
for index in offsets {
let zRoutineRun = routineRuns[index]
guard let routineArchiveID = zRoutineRun.zRoutine?.routineArchiveID,
let startedAt = zRoutineRun.startedAt
else { continue }
try ZRoutineRun.userRemove(viewContext, routineArchiveID: routineArchiveID, startedAt: startedAt)
}
try viewContext.save()
// update the widget(s), if any
try WidgetEntry.refresh(viewContext,
reload: true,
defaultColor: .accentColor)
} catch {
logger.error("\(#function): \(error.localizedDescription)")
}
}
}
struct MRoutineRunList_Previews: PreviewProvider {
static var previews: some View {
let manager = CoreDataStack.getPreviewStack()
let ctx = manager.container.viewContext
let archiveStore = manager.getArchiveStore(ctx)!
let routineArchiveID = UUID()
let startedAt1 = Date.now.addingTimeInterval(-20000)
let duration1 = 500.0
let startedAt2 = Date.now.addingTimeInterval(-10000)
let duration2 = 400.0
let zR = ZRoutine.create(ctx, routineArchiveID: routineArchiveID, routineName: "Chest & Shoulder", toStore: archiveStore)
_ = ZRoutineRun.create(ctx, zRoutine: zR, startedAt: startedAt1, elapsedSecs: duration1, toStore: archiveStore)
_ = ZRoutineRun.create(ctx, zRoutine: zR, startedAt: startedAt2, elapsedSecs: duration2, toStore: archiveStore)
try! ctx.save()
return NavigationStack {
MRoutineRunList(archiveStore: archiveStore)
.environment(\.managedObjectContext, ctx)
}
}
}