import SwiftUI import SwiftData struct HistoryView: View { @Environment(\.modelContext) private var context @Query(sort: \HistoryItem.startDate, order: .reverse) private var items: [HistoryItem] = [] private var unlockCount: Int { items.count { $0.response == .unlocked } } private var percentage: Double { guard items.count > 0 else { return 0 } return Double(unlockCount * 100) / Double(items.count) } private var requestNumberText: String { guard items.count != 1 else { return "1 Request" } return "\(items.count) Requests" } var body: some View { NavigationView { List { HStack { Text(requestNumberText) .foregroundColor(.primary) .font(.body) Spacer() Text(String(format: "%d successful (%.1f %%)", unlockCount, percentage)) .foregroundColor(.secondary) .font(.footnote) } ForEach(items) {entry in HistoryListItem(entry: entry) }.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") } } } #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.") } }