FuelMan/Gas Man/Stats/PricePerGallonTrendChartVie...

65 lines
2.0 KiB
Swift

//
// PriceTrendChartView.swift
// Gas Man
//
// Created by Kameron Kenny on 3/19/25.
//
import SwiftUI
import Charts
import CoreData
struct PricePerGallonTrendChartView: View {
let fuelLogs: [FuelLog]
// Compute trend data by sorting logs by date ascending,
// then mapping each log's date and pricePerGalon.
var trendData: [(date: Date, price: Double)] {
let sortedLogs = fuelLogs.sorted { ($0.date ?? Date()) < ($1.date ?? Date()) }
return sortedLogs.compactMap { log in
if let date = log.date {
return (date, log.pricePerGalon)
} else {
return nil
}
}
}
var body: some View {
VStack {
if trendData.isEmpty {
Text("No price trend data available.")
.foregroundColor(.secondary)
} else {
Chart {
ForEach(trendData, id: \.date) { point in
LineMark(
x: .value("Date", point.date),
y: .value("Price", point.price)
)
PointMark(
x: .value("Date", point.date),
y: .value("Price", point.price)
)
.annotation(position: .top) {
// This annotation displays the data point number and the MPG value.
Text("\(point.price, specifier: "%.3f")")
.font(.caption2)
.foregroundColor(.blue)
}
}
}
.chartXAxis {
AxisMarks(values: .automatic(desiredCount: 4))
}
.chartYAxis {
AxisMarks(values: .automatic(desiredCount: 5))
}
}
}
.padding()
.navigationTitle("Price/Gallon Trend")
}
}