2022-05-01 18:30:30 +02:00
|
|
|
import SwiftUI
|
2023-12-12 17:33:42 +01:00
|
|
|
import SwiftData
|
2022-05-01 18:30:30 +02:00
|
|
|
|
|
|
|
struct HistoryView: View {
|
2024-04-22 12:58:49 +02:00
|
|
|
|
|
|
|
@Environment(\.modelContext)
|
|
|
|
private var context
|
2022-05-01 18:30:30 +02:00
|
|
|
|
2024-04-22 12:58:49 +02:00
|
|
|
@Query(sort: \HistoryItem.startDate, order: .reverse)
|
2023-08-14 10:39:29 +02:00
|
|
|
private var items: [HistoryItem] = []
|
|
|
|
|
2023-12-12 17:33:42 +01:00
|
|
|
private var unlockCount: Int {
|
|
|
|
items.count { $0.response == .unlocked }
|
|
|
|
}
|
2023-08-14 10:39:29 +02:00
|
|
|
|
|
|
|
private var percentage: Double {
|
|
|
|
guard items.count > 0 else {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
return Double(unlockCount * 100) / Double(items.count)
|
|
|
|
}
|
2023-12-12 17:33:42 +01:00
|
|
|
|
|
|
|
private var requestNumberText: String {
|
|
|
|
guard items.count != 1 else {
|
|
|
|
return "1 Request"
|
|
|
|
}
|
|
|
|
return "\(items.count) Requests"
|
|
|
|
}
|
2022-05-01 18:30:30 +02:00
|
|
|
|
|
|
|
var body: some View {
|
2023-04-11 18:18:31 +02:00
|
|
|
NavigationView {
|
2023-08-14 10:39:29 +02:00
|
|
|
List {
|
|
|
|
HStack {
|
2023-12-12 17:33:42 +01:00
|
|
|
Text(requestNumberText)
|
2023-08-14 10:39:29 +02:00
|
|
|
.foregroundColor(.primary)
|
|
|
|
.font(.body)
|
|
|
|
Spacer()
|
|
|
|
Text(String(format: "%d successful (%.1f %%)", unlockCount, percentage))
|
|
|
|
.foregroundColor(.secondary)
|
|
|
|
.font(.footnote)
|
|
|
|
}
|
|
|
|
ForEach(items) {entry in
|
|
|
|
HistoryListItem(entry: entry)
|
2024-04-22 12:58:49 +02:00
|
|
|
}.onDelete(perform: { indexSet in
|
|
|
|
let objects = indexSet.map { items[$0] }
|
|
|
|
for object in objects {
|
|
|
|
context.delete(object)
|
|
|
|
}
|
|
|
|
do {
|
|
|
|
try context.save()
|
|
|
|
} catch {
|
|
|
|
print("Failed to save after deleting \(objects.count) object(s): \(error)")
|
|
|
|
}
|
|
|
|
})
|
2023-04-11 18:18:31 +02:00
|
|
|
}
|
|
|
|
.navigationTitle("History")
|
2022-05-01 18:30:30 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-12 17:33:42 +01:00
|
|
|
#Preview {
|
|
|
|
do {
|
|
|
|
let config = ModelConfiguration(isStoredInMemoryOnly: true)
|
|
|
|
let container = try ModelContainer(for: HistoryItem.self, configurations: config)
|
|
|
|
|
|
|
|
let item = HistoryItem.mock
|
|
|
|
container.mainContext.insert(item)
|
|
|
|
try container.mainContext.save()
|
|
|
|
return HistoryView()
|
|
|
|
.modelContainer(container)
|
|
|
|
} catch {
|
|
|
|
fatalError("Failed to create model container.")
|
2022-05-01 18:30:30 +02:00
|
|
|
}
|
|
|
|
}
|