Repository Public
1//2// Auto-Ka iOS v23// File: AutoKa/Design/Gauge/MarketGauge.swift4// Description: la fourchette de marché — où le prix demandé se situe parmi les véhicules comparables.5// Auto-Ka n'estime rien : il montre l'intervalle des prix comparables publié par le service6// (1er et 3e quartiles, médiane) et y pose l'étiquette du prix. Aucun seuil dans l'app.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10//1112import SwiftUI1314/// Échelle de la fourchette : logique pure.15struct GaugeScale: Equatable, Sendable {16 var lo: Double17 var hi: Double1819 /// Domaine : de min(10e centile, prix) − 13 % à max(90e centile, prix) + 13 % de l'étendue 10e–90e20 /// (système de marque, section 9). Sans centiles (ancienne réponse) : les quartiles, élargis de 22 %.21 init(price: Double, low: Double, median: Double, high: Double, p10: Double? = nil, p90: Double? = nil) {22 if let p10, let p90, p90 > p10 {23 let pad = (p90 - p10) * 0.1324 lo = min(p10, price, low) - pad25 hi = max(p90, price, high) + pad26 } else {27 let a = min(low, price, median), b = max(high, price, median)28 let span = max(b - a, median * 0.02, 1)29 lo = a - span * 0.2230 hi = b + span * 0.2231 }32 }3334 init(price: Double, verdict v: PriceVerdict) {35 self.init(price: price, low: v.marketLow, median: v.marketPrice, high: v.marketHigh, p10: v.marketP10, p90: v.marketP90)36 }3738 /// Position 0…1 d'un prix sur l'axe.39 func x(_ price: Double) -> Double { hi > lo ? max(0, min(1, (price - lo) / (hi - lo))) : 0.5 }4041 /// Pas des graduations chiffrées : le plus petit pas « rond » qui donne au plus `maxLabels` libellés.42 func step(maxLabels: Int) -> Double {43 let steps: [Double] = [250, 500, 1000, 2000, 2500, 5000, 10_000, 20_000, 25_000, 50_000, 100_000]44 return steps.first { (hi - lo) / $0 <= Double(max(2, maxLabels)) } ?? 100_00045 }4647 /// Graduations dans le domaine : `major` = chiffrée.48 func ticks(maxLabels: Int) -> [(value: Double, major: Bool)] {49 let s = step(maxLabels: maxLabels), minor = s / 250 var out: [(Double, Bool)] = []51 var v = (lo / minor).rounded(.up) * minor52 while v <= hi + 0.001 {53 out.append((v, abs(v.remainder(dividingBy: s)) < 0.001))54 v += minor55 }56 return out57 }58}5960/// Étiquette de prix au pan coupé : le coin haut gauche est coupé à la pente du montant de la portière.61struct PriceTagShape: InsettableShape {62 var radius: CGFloat = 663 /// largeur et hauteur du pan coupé (7,4 × 13 pour une étiquette de 26 de haut)64 var cut = CGSize(width: 7.4, height: 13)65 /// pointe en bas au centre (marqueur de carte) ; 0 = aucune66 var pointer: CGFloat = 067 var inset: CGFloat = 06869 func inset(by amount: CGFloat) -> PriceTagShape {70 var s = self; s.inset += amount; return s71 }7273 func path(in rect: CGRect) -> Path {74 let r = rect.insetBy(dx: inset, dy: inset)75 let body = CGRect(x: r.minX, y: r.minY, width: r.width, height: r.height - pointer)76 let c = CGSize(width: min(cut.width, body.width / 3), height: min(cut.height, body.height / 2))77 var v: [CGPoint] = [CGPoint(x: body.minX, y: body.maxY), CGPoint(x: body.minX, y: body.minY + c.height),78 CGPoint(x: body.minX + c.width, y: body.minY), CGPoint(x: body.maxX, y: body.minY),79 CGPoint(x: body.maxX, y: body.maxY)]80 var radii: [CGFloat] = [radius, radius * 0.5, radius * 0.5, radius, radius]81 if pointer > 0 {82 v.append(CGPoint(x: body.midX + pointer, y: body.maxY))83 v.append(CGPoint(x: body.midX, y: body.maxY + pointer))84 v.append(CGPoint(x: body.midX - pointer, y: body.maxY))85 radii += [0, 0.8, 0]86 }87 return PortiereGeometry.path(PortiereGeometry.rounded(v, radii, samples: 5))88 }89}9091/// Pastille du verdict : icône de position + libellé du service + « · » + écart signé, en couleur de verdict92/// sur son fond doux. Jamais la couleur seule. Sans verdict : pastille neutre, aucun jugement.93struct VerdictPill: View {94 let verdict: PriceVerdict?95 var compact = false96 /// avancement du roulement de l'écart ; 1 = posé97 var roll: Double = 198 /// atténuation du libellé pendant le tracé (35 % → 100 %)99 var emphasis: Double = 1100101 var body: some View {102 if let v = verdict {103 let c = Theme.color(for: v.position)104 HStack(spacing: 5) {105 Image(Theme.icon(for: v.position)).resizable().scaledToFit().frame(width: 15, height: 15)106 Text(v.displayLabel).opacity(0.35 + 0.65 * emphasis)107 Text("·").opacity(0.6)108 RollingDeviation(pct: v.deviationPct, progress: roll)109 }110 .font((compact ? Font.caption : Font.footnote).weight(.semibold))111 .foregroundStyle(c)112 .lineLimit(1)113 .minimumScaleFactor(0.8)114 .padding(.horizontal, compact ? 0 : 8)115 .padding(.vertical, compact ? 0 : 5)116 .background(compact ? Color.clear : Theme.softColor(for: v.position), in: RoundedRectangle(cornerRadius: Theme.radiusTag, style: .continuous))117 .accessibilityElement(children: .ignore)118 .accessibilityLabel("\(v.displayLabel), \(Fmt.signedPct(v.deviationPct)) par rapport au prix de marché")119 } else {120 Text("Pas assez de comparables")121 .font((compact ? Font.caption : Font.footnote).weight(.medium))122 .foregroundStyle(Theme.ink3)123 .lineLimit(1)124 .minimumScaleFactor(0.8)125 .padding(.horizontal, compact ? 0 : 8)126 .padding(.vertical, compact ? 0 : 5)127 .background(compact ? Color.clear : Theme.surface2, in: RoundedRectangle(cornerRadius: Theme.radiusTag, style: .continuous))128 .accessibilityLabel("Pas assez de véhicules comparables pour situer ce prix")129 }130 }131}132133/// Mini-fourchette d'une carte de résultat : trait, bande, médiane, point (14 pt de haut).134struct MiniGauge: View {135 let price: Double136 let verdict: PriceVerdict137138 var body: some View {139 Canvas { ctx, size in140 let s = GaugeScale(price: price, verdict: verdict)141 let y = size.height / 2142 func x(_ p: Double) -> CGFloat { 4 + (size.width - 8) * s.x(p) }143 var base = Path(); base.move(to: CGPoint(x: 0, y: y)); base.addLine(to: CGPoint(x: size.width, y: y))144 ctx.stroke(base, with: .color(Theme.line2), lineWidth: 1)145 if let a = verdict.marketP10, let b = verdict.marketP90 {146 var w = Path(); w.move(to: CGPoint(x: x(a), y: y)); w.addLine(to: CGPoint(x: x(b), y: y))147 ctx.stroke(w, with: .color(Theme.ink3), lineWidth: 2)148 }149 ctx.fill(Path(CGRect(x: x(verdict.marketLow), y: y - 3.5, width: max(2, x(verdict.marketHigh) - x(verdict.marketLow)), height: 7)), with: .color(Theme.band))150 ctx.fill(Path(CGRect(x: x(verdict.marketPrice) - 1, y: y - 6.5, width: 2, height: 13)), with: .color(Theme.ink))151 let dot = CGRect(x: x(price) - 4, y: y - 4, width: 8, height: 8)152 ctx.fill(Path(ellipseIn: dot.insetBy(dx: -1.5, dy: -1.5)), with: .color(Theme.bg))153 ctx.fill(Path(ellipseIn: dot), with: .color(Theme.color(for: verdict.position)))154 }155 .frame(width: 62, height: 14)156 .accessibilityHidden(true)157 }158}159160/// La fourchette de marché, en deux tailles.161struct MarketGauge: View {162 enum Size { case hero, medium }163164 let price: Double165 let verdict: PriceVerdict166 var size: Size = .hero167 /// état du tracé (geste d'ouverture ou « verdict seul ») ; `.final` = posé168 var choreo: GaugeChoreo = .final169170 @Environment(\.dynamicTypeSize) private var typeSize171172 private var height: CGFloat { size == .hero ? (typeSize.isAccessibilitySize ? 112 : 96) : 62 }173174 var body: some View {175 Canvas { ctx, sz in draw(&ctx, sz) }176 .frame(height: height)177 .accessibilityElement()178 .accessibilityLabel(accessibilityText)179 }180181 private var accessibilityText: String {182 "Prix demandé \(Fmt.money(price)). Prix de marché \(Fmt.money(verdict.marketPrice)). \(verdict.marketP10.flatMap { a in verdict.marketP90.map { "Du dixième au quatre-vingt-dixième centile des véhicules comparables : \(Fmt.money(a)) à \(Fmt.money($0)). " } } ?? "")La moitié se situent entre \(Fmt.money(verdict.marketLow)) et \(Fmt.money(verdict.marketHigh)). Écart : \(Fmt.signedMoney(verdict.gap(price: price)))."183 }184185 private func draw(_ ctx: inout GraphicsContext, _ sz: CGSize) {186 let hero = size == .hero187 let s = GaugeScale(price: price, verdict: verdict)188 let color = Theme.color(for: verdict.position)189 let tagH: CGFloat = 26190 let baseY: CGFloat = hero ? 60 : 44191 let padX: CGFloat = 2192 func x(_ p: Double) -> CGFloat { padX + (sz.width - 2 * padX) * s.x(p) }193 let xMed = x(verdict.marketPrice), xPrice = x(price)194 // l'étiquette part de la médiane et glisse jusqu'au prix demandé195 let xTag = xMed + (xPrice - xMed) * choreo.slide196197 // ligne de base, tracée depuis la médiane198 if choreo.base > 0 {199 var base = Path()200 base.move(to: CGPoint(x: xMed - (xMed - 0) * choreo.base, y: baseY))201 base.addLine(to: CGPoint(x: xMed + (sz.width - xMed) * choreo.base, y: baseY))202 ctx.stroke(base, with: .color(Theme.line2), lineWidth: 1)203 }204205 // graduations206 if hero, choreo.ticks > 0 {207 let maxLabels = max(2, Int(sz.width / (typeSize.isAccessibilitySize ? 110 : 76)))208 for tick in s.ticks(maxLabels: maxLabels) {209 let tx = x(tick.value)210 var p = Path()211 p.move(to: CGPoint(x: tx, y: baseY)); p.addLine(to: CGPoint(x: tx, y: baseY + (tick.major ? 7 : 4)))212 ctx.stroke(p, with: .color(Theme.line2.opacity(choreo.ticks)), lineWidth: 1)213 if tick.major {214 let label = ctx.resolve(Text(Fmt.kPrice(tick.value)).font(.caption2).monospacedDigit().foregroundStyle(Theme.ink3))215 let w = label.measure(in: sz).width216 let lx = min(max(tx, w / 2), sz.width - w / 2)217 var g = ctx; g.opacity = choreo.ticks218 g.draw(label, at: CGPoint(x: lx, y: baseY + 10), anchor: .top)219 }220 }221 }222223 // trait du 10e au 90e centile, depuis la médiane224 if choreo.whisker > 0, let p10 = verdict.marketP10, let p90 = verdict.marketP90 {225 var w = Path()226 w.move(to: CGPoint(x: xMed - (xMed - x(p10)) * choreo.whisker, y: baseY))227 w.addLine(to: CGPoint(x: xMed + (x(p90) - xMed) * choreo.whisker, y: baseY))228 ctx.stroke(w, with: .color(Theme.ink3), lineWidth: 3)229 }230231 // bande du 1er au 3e quartile, depuis la médiane232 if choreo.band > 0 {233 let x0 = xMed - (xMed - x(verdict.marketLow)) * choreo.band, x1 = xMed + (x(verdict.marketHigh) - xMed) * choreo.band234 ctx.fill(Path(CGRect(x: x0, y: baseY - 6.5, width: max(1, x1 - x0), height: 13)), with: .color(Theme.band))235 }236237 // médiane : trait et libellé du côté opposé au prix demandé238 if choreo.median > 0 {239 let half = 14.5 * choreo.median240 ctx.fill(Path(CGRect(x: xMed - 1, y: baseY - half, width: 2, height: half * 2)), with: .color(Theme.ink))241 if hero {242 let label = ctx.resolve(Text("Médiane \(Fmt.money(verdict.marketPrice))").font(.caption).monospacedDigit().foregroundStyle(Theme.ink2))243 let w = label.measure(in: sz).width244 let right = xPrice <= xMed245 var lx = right ? xMed + 7 : xMed - 7 - w246 lx = min(max(lx, 0), sz.width - w)247 var g = ctx; g.opacity = choreo.median248 g.draw(label, at: CGPoint(x: lx, y: baseY - 22), anchor: .topLeading)249 }250 }251252 // étiquette du prix demandé : tige, point, pan coupé253 if choreo.tagIn > 0 {254 var g = ctx; g.opacity = choreo.tagIn255 // cote : de la tige à la médiane256 if hero, abs(xTag - xMed) > 2 {257 var cote = Path()258 let cy = baseY - 19259 cote.move(to: CGPoint(x: xTag, y: cy)); cote.addLine(to: CGPoint(x: xMed, y: cy))260 g.stroke(cote, with: .color(Theme.ink2), lineWidth: 1)261 }262 let text = g.resolve(Text(Fmt.money(price)).font(.footnote.weight(.semibold)).monospacedDigit().foregroundStyle(Theme.tagInk))263 let tw = text.measure(in: sz).width + 18264 let tagY: CGFloat = hero ? 2 : 0265 let tx = min(max(xTag - tw * 0.32, 0), sz.width - tw)266 var stem = Path()267 stem.move(to: CGPoint(x: xTag, y: tagY + tagH - 1)); stem.addLine(to: CGPoint(x: xTag, y: baseY))268 g.stroke(stem, with: .color(color), lineWidth: 2)269 let tag = CGRect(x: tx, y: tagY, width: tw, height: tagH)270 g.fill(PriceTagShape().path(in: tag), with: .color(color))271 g.draw(text, at: CGPoint(x: tag.midX + 2, y: tag.midY), anchor: .center)272 let dot = CGRect(x: xTag - 4.5, y: baseY - 4.5, width: 9, height: 9)273 g.fill(Path(ellipseIn: dot.insetBy(dx: -2, dy: -2)), with: .color(Theme.bg))274 g.fill(Path(ellipseIn: dot), with: .color(color))275276 // cote chiffrée en dollars, si elle mesure au moins 64 pt277 if hero, choreo.legend > 0, abs(xPrice - xMed) >= 64 {278 let gap = g.resolve(Text(Fmt.signedMoney(verdict.gap(price: price))).font(.caption.weight(.semibold)).monospacedDigit().foregroundStyle(Theme.ink))279 let gw = gap.measure(in: sz)280 let mid = (xPrice + xMed) / 2281 var gg = ctx; gg.opacity = choreo.legend282 let r = CGRect(x: mid - gw.width / 2 - 3, y: baseY - 19 - gw.height / 2, width: gw.width + 6, height: gw.height)283 gg.fill(Path(r), with: .color(Theme.bg))284 gg.draw(gap, at: CGPoint(x: mid, y: baseY - 19), anchor: .center)285 }286 }287 }288}289290/// Fourchette sans verdict : ligne en pointillé et une phrase. Aucune couleur, aucun jugement.291struct NoVerdictGauge: View {292 var reason: String = "Moins de véhicules comparables qu'il n'en faut, kilométrage inconnu ou prix trop dispersés : aucun verdict n'est donné."293294 var body: some View {295 VStack(alignment: .leading, spacing: 10) {296 Rectangle().stroke(Theme.line2, style: StrokeStyle(lineWidth: 1, dash: [3, 3])).frame(height: 1)297 Text(reason).font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)298 }299 .accessibilityElement(children: .combine)300 }301}302