Repository Public
1//2// Food-Ka iOS v23// File: FoodKa/Features/Product/HistoryChart.swift4// Description: historique du prix (Swift Charts) — courbe en paliers posée sur une tablette (un prix ne varie pas en5// pente), prix habituel en tirets, plus bas surligné sur toute sa durée, prix courant marqué d'un6// point et de son étiquette. Circulaires : des points non reliés.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10//1112import Charts13import SwiftUI1415/// Préparation des données de la courbe : pure, testée seule.16struct HistorySeries: Equatable, Sendable {17 struct Step: Equatable, Sendable, Identifiable {18 var id: Int19 var segment: Int20 var date: Date21 var price: Double22 }2324 struct Span: Equatable, Sendable, Identifiable {25 var id: Int26 var from: Date27 var to: Date28 var price: Double29 }3031 var steps: [Step] = []32 /// durées pendant lesquelles le prix était au plus bas de la période affichée33 var lows: [Span] = []34 var low: Double?35 var high: Double?36 var current: Double?37 var start: Date?38 var end: Date39 var isSteps: Bool4041 init(_ h: PriceHistory, now: Date = Date()) {42 isSteps = h.isSteps43 end = now44 let pts = h.points45 guard !pts.isEmpty else { return }46 start = Date(timeIntervalSince1970: pts[0].t)47 var segment = 048 var id = 049 var spans: [Span] = []50 for (i, p) in pts.enumerated() {51 guard let price = p.price else { segment += 1; continue } // produit retiré de l'affichage : trou dans la courbe52 let from = Date(timeIntervalSince1970: p.t)53 steps.append(Step(id: id, segment: segment, date: from, price: price)); id += 154 if isSteps {55 // un prix vaut jusqu'au point suivant ; le dernier jusqu'à maintenant56 let to = i + 1 < pts.count ? Date(timeIntervalSince1970: pts[i + 1].t) : now57 steps.append(Step(id: id, segment: segment, date: to, price: price)); id += 158 spans.append(Span(id: spans.count, from: from, to: to, price: price))59 }60 }61 let prices = steps.map(\.price)62 low = prices.min(); high = prices.max()63 current = pts.last?.price64 if let low, isSteps { lows = spans.filter { abs($0.price - low) < 0.005 } }65 }6667 /// Bornes de l'axe des prix, avec un peu d'air.68 var domain: ClosedRange<Double> {69 let lo = low ?? 0, hi = high ?? 170 let pad = max(0.25, (hi - lo) * 0.18)71 return max(0, lo - pad)...(hi + pad)72 }73}7475struct HistoryChart: View {76 let history: PriceHistory77 @Environment(\.dynamicTypeSize) private var typeSize7879 var body: some View {80 let s = HistorySeries(history)81 VStack(alignment: .leading, spacing: 0) {82 Chart {83 if let m = history.median90d, history.isSteps {84 RuleMark(y: .value("Prix habituel", m))85 .foregroundStyle(Theme.ink3)86 .lineStyle(StrokeStyle(lineWidth: 1, dash: [4, 4]))87 }88 ForEach(s.lows) { l in89 RuleMark(xStart: .value("Du", l.from), xEnd: .value("Au", l.to), y: .value("Plus bas", l.price))90 .foregroundStyle(Theme.good)91 .lineStyle(StrokeStyle(lineWidth: 5, lineCap: .butt))92 }93 if history.isSteps {94 ForEach(s.steps) { p in95 LineMark(x: .value("Date", p.date), y: .value("Prix", p.price), series: .value("Palier", p.segment))96 .foregroundStyle(Theme.ink)97 .lineStyle(StrokeStyle(lineWidth: 2.2, lineCap: .square, lineJoin: .miter))98 }99 } else {100 ForEach(s.steps) { p in101 PointMark(x: .value("Date", p.date), y: .value("Prix", p.price))102 .symbolSize(46)103 .foregroundStyle(Theme.ink)104 }105 }106 if let c = s.current {107 PointMark(x: .value("Date", history.isSteps ? s.end : (s.steps.last?.date ?? s.end)), y: .value("Prix", c))108 .symbolSize(70)109 .foregroundStyle(Theme.tag)110 }111 }112 .chartYScale(domain: s.domain)113 .chartXScale(domain: (s.start ?? s.end.addingTimeInterval(-86400))...s.end.addingTimeInterval(86400))114 .chartYAxis {115 AxisMarks(position: .leading, values: .automatic(desiredCount: 4)) { v in116 AxisGridLine().foregroundStyle(Theme.line)117 AxisValueLabel {118 if let d = v.as(Double.self) { Text(Fmt.price(d)).font(.chartAxis).monospacedDigit().foregroundStyle(Theme.ink3) }119 }120 }121 }122 .chartXAxis {123 AxisMarks(values: .automatic(desiredCount: typeSize.isAccessibilitySize ? 2 : 3)) { v in124 AxisValueLabel {125 if let d = v.as(Date.self) { Text(Fmt.shortDate(d)).font(.chartAxis).foregroundStyle(Theme.ink3) }126 }127 }128 }129 .frame(height: 190)130 .accessibilityElement(children: .ignore)131 .accessibilityLabel(summary(s))132 .accessibilityIdentifier("history-chart")133 // la tablette sous la courbe134 ShelfBar(thickness: 3).padding(.leading, 38).padding(.top, 2)135 }136 }137138 private func summary(_ s: HistorySeries) -> String {139 var parts = ["Historique du prix"]140 if let d = history.days { parts.append("\(Int(d.rounded())) jours de suivi") }141 if let c = s.current { parts.append("prix courant \(Fmt.price(c))") }142 if let l = history.low90d { parts.append("plus bas \(Fmt.price(l))") }143 if let m = history.median90d { parts.append("médiane \(Fmt.price(m))") }144 if let h = history.high90d { parts.append("plus haut \(Fmt.price(h))") }145 return parts.joined(separator: ", ")146 }147}148