Sesame-iOS/Sesame/History/HistoryView.swift

75 lines
2.2 KiB
Swift
Raw Permalink Normal View History

import SwiftUI
2023-12-12 17:33:42 +01:00
import SwiftData
struct HistoryView: View {
2024-04-22 12:58:49 +02:00
@Environment(\.modelContext)
private var context
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"
}
var body: some View {
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)")
}
})
}
.navigationTitle("History")
}
}
}
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.")
}
}