Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Vrai-Prix iOS9// File : VraiPrix/Design/V3/ValueViews.swift10// Description : les pièces du système « Aplomb 3 » : la valeur à quatre11// régimes (jamais un montant sans intervalle, jamais un12// montant hors d'une valeur ferme ou d'un ordre de13// grandeur), la position d'un prix (plaque pleine et glyphe,14// jamais la couleur seule), la jauge d'intervalle des lignes15// et des cartes.16// Module : VraiPrix17// Repository : https://git.spboucher.ai/vrai-prix-ios-v318// Project Website : https://www.vrai-prix.com19// Created : 2026-11-2820// Last Modified : 2026-11-2821//22// =============================================================================23// AUTHOR & PROFESSIONAL AFFILIATION24// =============================================================================25//26// Author : Simon-Pierre Boucher27// Position : Professor of Finance28// Institution : Université du Québec en Outaouais (UQO)29// Department : Département des sciences administratives30// Organization : SP Boucher31//32// Website : https://spboucher.ai33// Git : https://git.spboucher.ai34//35// =============================================================================36// OFFICIAL CONTACT DIRECTORY37// =============================================================================38//39// General : info@spboucher.ai40// Professional : contact@spboucher.ai41// Direct : simon@spboucher.ai42// Research : research@spboucher.ai43// Development : dev@spboucher.ai44// Support : support@spboucher.ai45// Security/Admin : admin@spboucher.ai46// Notifications : notifications@spboucher.ai47//48// Preferred Contact: support@spboucher.ai49//50// =============================================================================51// COPYRIGHT & INTELLECTUAL PROPERTY52// =============================================================================53//54// Copyright (c) 202655// Simon-Pierre Boucher56//57// All rights reserved where applicable.58//59// This file is governed by the applicable project license,60// copyright notices, institutional agreements and relevant law.61//62// Unless expressly authorized by the applicable license or63// rights holder, copying, redistribution, sublicensing,64// publication and commercial exploitation are not permitted.65//66// Existing third-party rights and notices remain unaffected.67//68// =============================================================================69// CONFIDENTIALITY & SECURITY70// =============================================================================71//72// Classification : Public73// Distribution : Public repository; use is governed by the project license74// Security Contact : admin@spboucher.ai75//76// Access to this source does not independently grant permission77// to redistribute or disclose confidential materials.78//79// Do not embed credentials, private keys, access tokens,80// certificates or confidential personal information.81//82// =============================================================================83// LICENSE & MAINTENANCE84// =============================================================================85//86// License : None specified (no license file in this repository)87// Maintainer : Simon-Pierre Boucher88// Technical Contact: dev@spboucher.ai89//90// =============================================================================91// END OF SP BOUCHER SOURCE HEADER92// =============================================================================9394import SwiftUI9596// MARK: - Formats liés à l'incertitude9798enum ValueFmt {99 /// Pas d'arrondi : au plus le vingtième de la demi-largeur de l'intervalle, ramené à 100, 500, 1 000, 5 000…100 /// (même règle que le site : on n'écrit pas au dollar ce qu'on connaît à 10 % près).101 static func step(_ value: Double, low: Double?, high: Double?) -> Double {102 guard value > 0 else { return 1 }103 guard let low, let high, high > low else { return pow(10, max(0, floor(log10(value)) - 2)) }104 let target = (high - low) / 2 / 20105 var step = 100.0106 for p in [100.0, 500, 1000, 5000, 10000, 50000, 100_000, 500_000, 1_000_000] where p <= target { step = p }107 return step108 }109110 static func rounded(_ value: Double, low: Double?, high: Double?) -> Double {111 let s = step(value, low: low, high: high)112 return (value / s).rounded() * s113 }114115 /// Valeur ferme : « 460 000 $ » pour 460 130 $ à ± 50 000 $.116 static func firm(_ value: Double, low: Double?, high: Double?) -> String { Fmt.money(rounded(value, low: low, high: high)) }117118 /// Ordre de grandeur : deux chiffres significatifs, précédé de « ≈ ».119 static func approx(_ value: Double) -> String {120 guard value > 0 else { return "—" }121 let p = pow(10, floor(log10(value)) - 1)122 return "≈" + Fmt.nbsp + Fmt.money((value / p).rounded() * p)123 }124125 static func interval(_ low: Double, _ high: Double) -> String { "\(Fmt.money(low)) à \(Fmt.money(high))" }126127 /// Le montant d'un bloc de valeur tel qu'il s'écrit, ou nil s'il ne s'en écrit aucun.128 static func amount(_ v: ValueBlock?) -> String? {129 guard let v, let a = v.amounts else { return nil }130 return v.status == .ordre ? approx(a.value) : firm(a.value, low: a.low, high: a.high)131 }132133 /// Phrase complète (partage, lecteur d'écran).134 static func sentence(_ v: ValueBlock?) -> String {135 guard let v else { return "Aucune valeur." }136 if let a = v.amounts {137 return v.status == .ordre138 ? "Ordre de grandeur : \(approx(a.value)), entre \(interval(a.low, a.high))."139 : "Valeur estimée : \(firm(a.value, low: a.low, high: a.high)). Intervalle : \(interval(a.low, a.high))."140 }141 return ["Aucune valeur", v.motif?.familyTitle, v.motif?.libelle].compactMap { $0 }.joined(separator: " : ") + "."142 }143}144145// MARK: - Valeur146147/// La valeur et son intervalle, toujours ensemble. Trois tailles.148struct ValueView: View {149 enum Size { case sheet, card, line }150 let value: ValueBlock?151 var size: Size = .card152153 var body: some View {154 Group {155 if let v = value, let a = v.amounts {156 amounts(v, a)157 } else {158 absence159 }160 }161 .accessibilityElement(children: .ignore)162 .accessibilityLabel(ValueFmt.sentence(value))163 }164165 @ViewBuilder166 private func amounts(_ v: ValueBlock, _ a: (value: Double, low: Double, high: Double)) -> some View {167 let approx = v.status == .ordre168 VStack(alignment: size == .line ? .trailing : .leading, spacing: size == .sheet ? 4 : 1) {169 Text(approx ? ValueFmt.approx(a.value) : ValueFmt.firm(a.value, low: a.low, high: a.high))170 .font(size == .sheet ? .display(34, weight: approx ? .regular : .semibold)171 : .system(size == .card ? .title3 : .subheadline, design: .default, weight: approx ? .regular : .semibold))172 .num().foregroundStyle(Theme.ink).lineLimit(1).minimumScaleFactor(0.7)173 Text(approx && size == .line ? "ordre de grandeur" : (approx && size != .sheet ? "ordre de grandeur · " : "") + ValueFmt.interval(a.low, a.high))174 .font(size == .sheet ? .footnote : .caption).num().foregroundStyle(Theme.ink3).lineLimit(size == .line ? 1 : 2)175 .multilineTextAlignment(size == .line ? .trailing : .leading)176 }177 }178179 private var absence: some View {180 VStack(alignment: size == .line ? .trailing : .leading, spacing: 1) {181 Text("Aucune valeur")182 .font(size == .sheet ? .editorial(22) : (size == .card ? .subheadline.weight(.semibold) : .footnote.weight(.semibold)))183 .foregroundStyle(Theme.ink)184 if let m = value?.motif, size != .line {185 Text([m.familyTitle, m.libelle.isEmpty ? nil : m.libelle].compactMap { $0 }.joined(separator: " : "))186 .font(.caption).foregroundStyle(Theme.ink3).lineLimit(size == .sheet ? nil : 2)187 .fixedSize(horizontal: false, vertical: true)188 } else if let m = value?.motif, let t = m.familyTitle {189 Text(t).font(.caption2).foregroundStyle(Theme.ink3).lineLimit(1)190 }191 }192 }193}194195// MARK: - Position d'un prix196197/// Glyphe de position : l'intervalle est un trait coté, le prix un losange à sa place (trois silhouettes distinctes) ;198/// sans position, le trait seul, tireté.199struct PositionGlyph: View {200 let position: PricePosition?201 var body: some View {202 Canvas { ctx, size in203 let s = min(size.width, size.height) / 24204 func p(_ x: CGFloat, _ y: CGFloat) -> CGPoint { CGPoint(x: x * s, y: y * s) }205 let fg = GraphicsContext.Shading.foreground206 var bar = Path()207 bar.move(to: p(7, 15)); bar.addLine(to: p(17, 15))208 bar.move(to: p(7, 12)); bar.addLine(to: p(7, 18)); bar.move(to: p(17, 12)); bar.addLine(to: p(17, 18))209 ctx.stroke(bar, with: fg, style: StrokeStyle(lineWidth: 1.7 * s, lineCap: .butt, dash: position == nil ? [2.4 * s, 1.8 * s] : []))210 guard let position else { return }211 let cx: CGFloat = position.side < 0 ? 3.5 : (position.side > 0 ? 20.5 : 12)212 let cy: CGFloat = position.side == 0 ? 8 : 15213 var d = Path()214 d.move(to: p(cx, cy - 3.6)); d.addLine(to: p(cx + 3.3, cy)); d.addLine(to: p(cx, cy + 3.6)); d.addLine(to: p(cx - 3.3, cy)); d.closeSubpath()215 ctx.fill(d, with: fg)216 }217 .aspectRatio(1, contentMode: .fit)218 .accessibilityHidden(true)219 }220}221222extension Theme {223 static func color(for p: PricePosition?) -> Color {224 switch p {225 case .sous: good226 case .dans: fair227 case .auDessus: high228 case nil: ink3229 }230 }231}232233/// Position d'un prix face à l'intervalle : une plaque pleine à la couleur de la position porte le glyphe ; le libellé234/// et l'écart sont au charbon. Sans position : contour tireté, « Sans verdict », et le motif.235struct PositionPlate: View {236 enum Size { case block, line, compact }237 let position: PricePosition?238 var gapPct: Double?239 var size: Size = .line240 /// pourquoi aucune position n'est rendue (libellé du moteur)241 var reason: String?242243 private var side: CGFloat {244 switch size {245 case .block: 30246 case .line: 22247 case .compact: 18248 }249 }250251 var body: some View {252 HStack(alignment: .center, spacing: size == .block ? 10 : 6) {253 plate254 VStack(alignment: .leading, spacing: 1) {255 HStack(alignment: .firstTextBaseline, spacing: 5) {256 Text(position.map { size == .compact ? $0.shortLabel : $0.label } ?? "Sans verdict")257 .font(size == .block ? .headline : .caption.weight(.semibold)).foregroundStyle(Theme.ink)258 if let gapPct, position != nil {259 Text(Fmt.pct(gapPct)).font(size == .block ? .subheadline.weight(.semibold) : .caption.weight(.medium)).num()260 .foregroundStyle(Theme.ink2)261 }262 }263 .lineLimit(1).minimumScaleFactor(0.75)264 if size == .block, position == nil, let reason {265 Text(Fmt.capitalized(reason)).font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)266 }267 }268 }269 .accessibilityElement(children: .ignore)270 .accessibilityLabel((position?.label ?? "Sans verdict") + (position != nil ? (gapPct.map { ", écart de " + Fmt.pct($0) } ?? "") : (reason.map { " : " + $0 } ?? "")))271 }272273 @ViewBuilder274 private var plate: some View {275 let shape = RoundedRectangle(cornerRadius: size == .block ? 6 : 4, style: .continuous)276 if let position {277 PositionGlyph(position: position).foregroundStyle(Theme.onVerdict)278 .padding(size == .block ? 5 : 3)279 .frame(width: side, height: side)280 .background(Theme.color(for: position), in: shape)281 } else {282 PositionGlyph(position: nil).foregroundStyle(Theme.ink3)283 .padding(size == .block ? 5 : 3)284 .frame(width: side, height: side)285 .overlay(shape.strokeBorder(Theme.lineControl, style: StrokeStyle(lineWidth: 1, dash: [3, 2])))286 }287 }288}289290// MARK: - Jauge d'intervalle (lignes, cartes, comparateur)291292/// Jauge compacte : l'axe, la bande de l'intervalle (tiretée pour un ordre de grandeur), les bornes chiffrées, le plomb293/// à la valeur et le prix en losange. Avec `domain`, plusieurs jauges partagent un axe : le plomb est alors à sa valeur.294struct IntervalBar: View {295 let value: Double296 let low: Double297 let high: Double298 var approximate = false299 var price: Double?300 /// axe commun (minimum, maximum) ; nil : axe centré sur la valeur301 var domain: ClosedRange<Double>?302 var background: Color = Theme.bg303304 private var range: ClosedRange<Double> {305 if let domain, domain.upperBound > domain.lowerBound { return domain }306 let r = max(value - low, high - value, value * 0.02)307 var m = r308 if let p = price { m = max(m, min(abs(p - value), r * 2.4)) }309 return (value - 1.14 * m)...(value + 1.14 * m)310 }311312 static func commonDomain(_ entries: [(low: Double, high: Double, price: Double?)]) -> ClosedRange<Double>? {313 guard !entries.isEmpty else { return nil }314 var lo = entries.map(\.low).min()!, hi = entries.map(\.high).max()!315 let core = hi - lo316 for p in entries.compactMap(\.price) where p >= lo - core / 2 && p <= hi + core / 2 { lo = min(lo, p); hi = max(hi, p) }317 let pad = max((hi - lo) * 0.06, 1)318 return (lo - pad)...(hi + pad)319 }320321 var body: some View {322 Canvas { ctx, size in323 let r = range, w = size.width, b: CGFloat = 16324 func x(_ a: Double) -> CGFloat { CGFloat((a - r.lowerBound) / (r.upperBound - r.lowerBound)) * w }325 func clamp(_ v: CGFloat) -> CGFloat { min(max(v, 0), w) }326 var axis = Path(); axis.move(to: CGPoint(x: 0, y: b)); axis.addLine(to: CGPoint(x: w, y: b))327 ctx.stroke(axis, with: .color(Theme.lineControl), lineWidth: 1)328 let xl = clamp(x(low)), xh = clamp(x(high)), xv = clamp(x(value))329 var band = Path(); band.move(to: CGPoint(x: xl, y: b)); band.addLine(to: CGPoint(x: xh, y: b))330 ctx.stroke(band, with: .color(Theme.ink), style: StrokeStyle(lineWidth: 3, lineCap: .butt, dash: approximate ? [5, 3] : []))331 var ends = Path()332 ends.move(to: CGPoint(x: xl, y: b - 4)); ends.addLine(to: CGPoint(x: xl, y: b + 4))333 ends.move(to: CGPoint(x: xh, y: b - 4)); ends.addLine(to: CGPoint(x: xh, y: b + 4))334 ctx.stroke(ends, with: .color(Theme.ink), lineWidth: 1.4)335 // le plomb à la valeur : pointe sur l'axe336 ctx.fill(BrandGeometry.plumb(tip: CGPoint(x: xv, y: b), height: 12), with: .color(Theme.plumb))337 var fil = Path(); fil.move(to: CGPoint(x: xv, y: 0)); fil.addLine(to: CGPoint(x: xv, y: b - 11))338 ctx.stroke(fil, with: .color(Theme.ink), lineWidth: 1.2)339 // bornes chiffrées340 let font = Font.system(size: 10, weight: .medium).monospacedDigit()341 let lo = ctx.resolve(Text(GaugeScale.label(low)).font(font).foregroundStyle(Theme.ink3))342 let hi = ctx.resolve(Text(GaugeScale.label(high)).font(font).foregroundStyle(Theme.ink3))343 let big = CGSize(width: 160, height: 30)344 let lw = lo.measure(in: big).width, hw = hi.measure(in: big).width345 let lx = min(max(xl - lw / 2, 0), w - lw), hx = min(max(xh - hw / 2, 0), w - hw)346 if lx + lw + 6 > hx {347 let both = ctx.resolve(Text(GaugeScale.label(low) + " à " + GaugeScale.label(high)).font(font).foregroundStyle(Theme.ink3))348 let bw = both.measure(in: big).width349 ctx.draw(both, at: CGPoint(x: min(max((xl + xh) / 2 - bw / 2, 0), max(0, w - bw)), y: b + 6), anchor: .topLeading)350 } else {351 ctx.draw(lo, at: CGPoint(x: lx, y: b + 6), anchor: .topLeading)352 ctx.draw(hi, at: CGPoint(x: hx, y: b + 6), anchor: .topLeading)353 }354 // le prix : losange creux à sa place ; hors de l'axe, au bord, avec un chevron355 if let p = price {356 let raw = x(p), off = raw < 0 || raw > w357 let px = min(max(raw, 6), w - 6), d: CGFloat = 5358 var dia = Path()359 dia.move(to: CGPoint(x: px, y: b - d)); dia.addLine(to: CGPoint(x: px + d, y: b))360 dia.addLine(to: CGPoint(x: px, y: b + d)); dia.addLine(to: CGPoint(x: px - d, y: b)); dia.closeSubpath()361 ctx.fill(dia, with: .color(background))362 ctx.stroke(dia, with: .color(Theme.ink), style: StrokeStyle(lineWidth: 1.5, lineJoin: .miter))363 if off {364 let s: CGFloat = raw > w ? 1 : -1365 var ch = Path()366 ch.move(to: CGPoint(x: px + s * 1, y: b - 9)); ch.addLine(to: CGPoint(x: px + s * 5, y: b - 6)); ch.addLine(to: CGPoint(x: px + s * 1, y: b - 3))367 ctx.stroke(ch, with: .color(Theme.ink), lineWidth: 1.3)368 }369 }370 }371 .frame(height: 36)372 .accessibilityHidden(true)373 }374}375376// MARK: - Étiquettes377378/// Étiquette sobre : nature d'un chiffre, qualification d'une vente, état d'une inscription.379struct PlainTag: View {380 let text: String381 var tone: Color = Theme.ink2382 var dashed = false383 var body: some View {384 Text(text).font(.caption2.weight(.semibold)).foregroundStyle(tone).lineLimit(1)385 .padding(.horizontal, 6).padding(.vertical, 3)386 .overlay(RoundedRectangle(cornerRadius: 4, style: .continuous)387 .strokeBorder(dashed ? Theme.lineControl : Theme.line2, style: StrokeStyle(lineWidth: 1, dash: dashed ? [3, 2] : [])))388 }389}390391/// Bloc de note encadré d'un filet à gauche (mise en garde, précision de méthode).392struct NoteBlock: View {393 let text: String394 var dashed = false395 var body: some View {396 HStack(alignment: .top, spacing: 10) {397 Rectangle().fill(.clear).frame(width: 2)398 .overlay(Rectangle().stroke(Theme.lineControl, style: StrokeStyle(lineWidth: 2, dash: dashed ? [4, 3] : [])).frame(width: 2))399 Text(text).font(.footnote).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)400 .frame(maxWidth: .infinity, alignment: .leading)401 }402 .accessibilityElement(children: .combine)403 }404}405