Sesame-iOS/Sesame-Watch Watch App/HistoryView.swift

77 lines
2.2 KiB
Swift
Raw Permalink Normal View History

2023-08-07 15:57:09 +02:00
import SwiftUI
2023-12-12 17:33:42 +01:00
import SwiftData
2023-08-07 15:57:09 +02:00
struct HistoryView: View {
2023-12-12 17:33:42 +01:00
@Environment(\.modelContext)
private var modelContext
2023-08-09 16:29:18 +02:00
2023-12-12 17:33:42 +01:00
@Query(sort: \HistoryItem.startDate, order: .reverse)
var history: [HistoryItem] = []
2023-08-09 16:29:18 +02:00
2023-08-14 10:39:29 +02:00
private var unlockCount: Int {
2023-12-12 17:33:42 +01:00
history.count { $0.response == .unlocked }
2023-08-14 10:39:29 +02:00
}
private var percentage: Double {
2023-12-12 17:33:42 +01:00
guard history.count > 0 else {
2023-08-14 10:39:29 +02:00
return 0
}
2023-12-12 17:33:42 +01:00
return Double(unlockCount * 100) / Double(history.count)
2023-08-14 10:39:29 +02:00
}
2023-08-09 16:29:18 +02:00
2023-08-07 15:57:09 +02:00
var body: some View {
2023-08-14 10:39:29 +02:00
NavigationView {
List {
HStack {
VStack(alignment: .leading) {
2023-12-12 17:33:42 +01:00
Text("\(history.count) requests")
2023-08-14 10:39:29 +02:00
.foregroundColor(.primary)
.font(.body)
Text(String(format: "%.1f %% success", percentage))
.foregroundColor(.secondary)
.font(.footnote)
}
Spacer()
}
.listRowBackground(Color.clear)
2023-12-12 17:33:42 +01:00
ForEach(history) { item in
2023-08-14 10:39:29 +02:00
NavigationLink {
2023-12-12 17:33:42 +01:00
HistoryItemDetail(item: item)
2023-08-14 10:39:29 +02:00
} label: {
HistoryListRow(item: item)
}
.swipeActions(edge: .trailing) {
Button {
delete(item: item)
} label: {
Label("Delete", systemSymbol: .trash)
}.tint(.red)
}
2023-08-09 16:29:18 +02:00
}
}
.navigationTitle("History")
2023-08-14 10:39:29 +02:00
}
2023-08-09 16:29:18 +02:00
}
2023-08-14 10:39:29 +02:00
private func delete(item: HistoryItem) {
2023-12-12 17:33:42 +01:00
modelContext.delete(item)
2023-08-07 15:57:09 +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.")
2023-08-07 15:57:09 +02:00
}
}