SPB Git

Repository Public

GaugeDraw.swift 18.1 KB 351 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Vrai-Prix iOS9// File             : VraiPrix/Design/Plumb/GaugeDraw.swift10// Description      : dessin de la jauge de valeur (Canvas) — ligne de base11//                    ouverte sous la pointe du plomb, graduations, fourchette,12//                    losange du prix demandé ou vendu, cote d'écart. Fidèle à13//                    `ValueGauge` de la marque.14// Module           : VraiPrix15// Repository       : https://git.spboucher.ai/vrai-prix-ios-v316// Project Website  : https://www.vrai-prix.com17// Created          : 2026-11-2618// Last Modified    : 2026-11-2819//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author           : Simon-Pierre Boucher25// Position         : Professor of Finance26// Institution      : Université du Québec en Outaouais (UQO)27// Department       : Département des sciences administratives28// Organization     : SP Boucher29//30// Website          : https://spboucher.ai31// Git              : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General          : info@spboucher.ai38// Professional     : contact@spboucher.ai39// Direct           : simon@spboucher.ai40// Research         : research@spboucher.ai41// Development      : dev@spboucher.ai42// Support          : support@spboucher.ai43// Security/Admin   : admin@spboucher.ai44// Notifications    : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification   : Public71// Distribution     : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License          : None specified (no license file in this repository)85// Maintainer       : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import SwiftUI93import UIKit9495/// Avancement de chaque pièce de la jauge (1 = en place).96struct GaugeProgress: Equatable, Sendable {97    var sol = 1.098    var ticks = 1.099    var range = 1.0100    var price = 1.0101    var cote = 1.0102    static let done = GaugeProgress()103}104105enum GaugeDraw {106    /// Demi-ouverture du sol autour du centre (la pointe du plomb y vient).107    static let gap: CGFloat = 7108109    /// Taille des petits textes de la jauge : suit « Taille du texte », bornée pour rester dans la bande.110    @MainActor static func smallSize(_ base: CGFloat) -> CGFloat {111        min(UIFontMetrics(forTextStyle: .caption2).scaledValue(for: base), base * 1.45)112    }113114    /// Dessine la jauge. `x0`/`width` : étendue horizontale ; `baseline` : ordonnée de la ligne de base ;115    /// `plumbHeight` : hauteur du plomb (la cote passe au-dessus). Renvoie rien : tout est dans `ctx`.116    static func draw(_ ctx: GraphicsContext, scale: GaugeScale, x0: CGFloat, width: CGFloat, baseline b: CGFloat,117                     plumbHeight: CGFloat, progress p: GaugeProgress, priceLabel: String?, gapLabel: String?,118                     background: Color, tickFont: CGFloat, labelFont: CGFloat, compact: Bool = false) {119        let cx = x0 + width / 2120        let v3 = scale.style != .classic121        // API v3 : la bande est continue, la pointe du plomb touche l'axe sans le couper122        let gap: CGFloat = v3 ? 0 : GaugeDraw.gap123        let ink = Theme.ink, ink2 = Theme.ink2, ink3 = Theme.ink3, line2 = v3 ? Theme.lineControl : Theme.line2124125        // 1. le sol : du centre vers les bords, ouvert sous la pointe126        if p.sol > 0 {127            let half = (width / 2 - gap) * p.sol128            var base = Path()129            base.move(to: CGPoint(x: cx - gap, y: b)); base.addLine(to: CGPoint(x: cx - gap - half, y: b))130            base.move(to: CGPoint(x: cx + gap, y: b)); base.addLine(to: CGPoint(x: cx + gap + half, y: b))131            ctx.stroke(base, with: .color(line2), lineWidth: 1)132        }133134        // 2. graduations : une par pas, plus longue et étiquetée tous les cinq pas135        if p.ticks > 0, !compact {136            var tc = ctx137            tc.opacity = p.ticks138            var minor = Path(), major = Path()139            var lastLabelMaxX = -CGFloat.infinity140            for t in scale.ticks(maxMinor: width < 340 ? 20 : 26) {141                let x = x0 + scale.x(t.amount, width: width)142                if abs(x - cx) < gap + 1 { continue }143                if t.major {144                    major.move(to: CGPoint(x: x, y: b)); major.addLine(to: CGPoint(x: x, y: b + (v3 ? 7 : 9)))145                    if v3 { continue }   // les montants écrits sous l'axe sont les deux bornes de l'intervalle146                    let text = tc.resolve(Text(GaugeScale.label(t.amount)).font(.system(size: tickFont, weight: .medium).monospacedDigit()).foregroundStyle(ink3))147                    let w = text.measure(in: CGSize(width: 200, height: 40)).width148                    if x - w / 2 >= x0, x + w / 2 <= x0 + width, x - w / 2 > lastLabelMaxX + 6 {149                        tc.draw(text, at: CGPoint(x: x, y: b + 12), anchor: .top)150                        lastLabelMaxX = x + w / 2151                    }152                } else {153                    minor.move(to: CGPoint(x: x, y: b)); minor.addLine(to: CGPoint(x: x, y: b + 5))154                }155            }156            tc.stroke(minor, with: .color(ink3.opacity(0.6)), lineWidth: 1)157            tc.stroke(major, with: .color(ink3), lineWidth: 1)158        }159160        // 3. fourchette : trait épais du bas au haut, tiré depuis le centre161        if p.range > 0 {162            let xl = x0 + scale.x(scale.low, width: width), xh = x0 + scale.x(scale.high, width: width)163            var band = Path()164            let l = cx - gap - max(0, (cx - gap - xl)) * p.range, h = cx + gap + max(0, (xh - cx - gap)) * p.range165            if cx - gap > xl { band.move(to: CGPoint(x: cx - gap, y: b)); band.addLine(to: CGPoint(x: l, y: b)) }166            if xh > cx + gap { band.move(to: CGPoint(x: cx + gap, y: b)); band.addLine(to: CGPoint(x: h, y: b)) }167            let dash: [CGFloat] = scale.style == .approximate ? (compact ? [4, 3] : [7, 4]) : []168            ctx.stroke(band, with: .color(ink), style: StrokeStyle(lineWidth: compact ? 2 : (v3 ? 3 : 2.5), lineCap: .butt, dash: dash))169            if v3, p.range > 0.6 {170                // bornes chiffrées sous l'axe, à toutes les tailles ; trop proches, elles fusionnent171                var bc = ctx172                bc.opacity = min(1, (p.range - 0.6) / 0.4)173                let font = Font.system(size: compact ? max(tickFont, 9.5) : tickFont + 0.5, weight: .medium).monospacedDigit()174                let lo = bc.resolve(Text(GaugeScale.label(scale.low)).font(font).foregroundStyle(ink2))175                let hi = bc.resolve(Text(GaugeScale.label(scale.high)).font(font).foregroundStyle(ink2))176                let big = CGSize(width: 200, height: 40)177                let lw = lo.measure(in: big).width, hw = hi.measure(in: big).width178                let y = b + (compact ? 5 : 11)179                var lx = min(max(xl - lw / 2, x0), x0 + width - lw), hx = min(max(xh - hw / 2, x0), x0 + width - hw)180                if lx + lw + 8 > hx {181                    let both = bc.resolve(Text(GaugeScale.label(scale.low) + " à " + GaugeScale.label(scale.high)).font(font).foregroundStyle(ink2))182                    let w = both.measure(in: big).width183                    bc.draw(both, at: CGPoint(x: min(max((xl + xh) / 2 - w / 2, x0), x0 + width - w), y: y), anchor: .topLeading)184                } else {185                    if lx + lw > hx - 8 { lx = hx - 8 - lw }186                    hx = max(hx, lx + lw + 8)187                    bc.draw(lo, at: CGPoint(x: lx, y: y), anchor: .topLeading)188                    bc.draw(hi, at: CGPoint(x: hx, y: y), anchor: .topLeading)189                }190            }191            if p.range >= 1, !compact {192                // bornes de la fourchette : deux petits repères193                var ends = Path()194                ends.move(to: CGPoint(x: xl, y: b - 4)); ends.addLine(to: CGPoint(x: xl, y: b + 4))195                ends.move(to: CGPoint(x: xh, y: b - 4)); ends.addLine(to: CGPoint(x: xh, y: b + 4))196                ctx.stroke(ends, with: .color(ink), lineWidth: 1.5)197            }198        }199200        // 4. prix demandé ou vendu : losange creux sur la ligne, ligne d'attache, cote d'écart201        guard let px = scale.priceX(width: width).map({ x0 + $0 }) else { return }202        let d: CGFloat = compact ? 4.5 : 6.5203        let coteY = b - (plumbHeight + 12)204        // prix presque sur l'aplomb : l'attache et la cote traverseraient le plomb ; seul le libellé est posé à côté205        let near = abs(px - cx) < plumbHeight * 0.34 + 4206        if p.price > 0 {207            var pc = ctx208            pc.opacity = p.price209            if !compact, !near {210                var leader = Path()211                leader.move(to: CGPoint(x: px, y: b - d)); leader.addLine(to: CGPoint(x: px, y: coteY - 7))212                pc.stroke(leader, with: .color(ink2), lineWidth: 1)213            }214            var dia = Path()215            dia.move(to: CGPoint(x: px, y: b - d)); dia.addLine(to: CGPoint(x: px + d, y: b))216            dia.addLine(to: CGPoint(x: px, y: b + d)); dia.addLine(to: CGPoint(x: px - d, y: b)); dia.closeSubpath()217            pc.fill(dia, with: .color(background))218            pc.stroke(dia, with: .color(ink), style: StrokeStyle(lineWidth: compact ? 1.4 : 1.7, lineJoin: .miter))219            if scale.priceOffScale, !compact {220                // prix hors échelle : chevron vers l'extérieur221                let s: CGFloat = px > cx ? 1 : -1222                var ch = Path()223                ch.move(to: CGPoint(x: px + s * 10, y: b - 4)); ch.addLine(to: CGPoint(x: px + s * 14, y: b)); ch.addLine(to: CGPoint(x: px + s * 10, y: b + 4))224                pc.stroke(ch, with: .color(ink), lineWidth: 1.5)225            }226        }227        guard !compact else { return }228        let right = px >= cx229        if p.cote > 0, !near, gapLabel != nil {230            let end = cx + (px - cx) * p.cote231            var line = Path()232            line.move(to: CGPoint(x: cx, y: coteY)); line.addLine(to: CGPoint(x: end, y: coteY))233            ctx.stroke(line, with: .color(ink2), lineWidth: 1)234            if abs(px - cx) > 22 {235                // flèches pleines 8 × 6, pointes sur l'aplomb et sur l'attache236                let s: CGFloat = right ? 1 : -1237                var a1 = Path()238                a1.move(to: CGPoint(x: cx, y: coteY)); a1.addLine(to: CGPoint(x: cx + s * 8, y: coteY - 3)); a1.addLine(to: CGPoint(x: cx + s * 8, y: coteY + 3)); a1.closeSubpath()239                ctx.fill(a1, with: .color(ink2))240                if p.cote > 0.98 {241                    var a2 = Path()242                    a2.move(to: CGPoint(x: px, y: coteY)); a2.addLine(to: CGPoint(x: px - s * 8, y: coteY - 3)); a2.addLine(to: CGPoint(x: px - s * 8, y: coteY + 3)); a2.closeSubpath()243                    ctx.fill(a2, with: .color(ink2))244                }245            }246        }247        // libellés : l'écart (graisse 600) puis « Prix demandé », du côté extérieur de l'attache248        let labelOpacity = min(p.price, 1)249        if labelOpacity > 0 {250            var lc = ctx251            let gapText = gapLabel.map { lc.resolve(Text($0).font(.system(size: labelFont + 1.5, weight: .semibold).monospacedDigit()).foregroundStyle(ink)) }252            let nameText = priceLabel.map { lc.resolve(Text($0).font(.system(size: labelFont, weight: .regular)).foregroundStyle(ink2)) }253            let big = CGSize(width: 260, height: 60)254            let gw = gapText?.measure(in: big) ?? .zero, nw = nameText?.measure(in: big) ?? .zero255            let w = max(gw.width, nw.width)256            // côté du libellé : l'extérieur de l'attache ; s'il n'y tient pas et que l'autre côté est plus large, on bascule257            let clear = plumbHeight * 0.34 + 4258            var side: CGFloat = right ? 1 : -1259            let roomOut = side > 0 ? x0 + width - px - 10 : px - x0 - 10260            let roomIn = side > 0 ? (near ? cx - clear - x0 - 10 : 0) : (near ? x0 + width - cx - clear - 10 : 0)261            if w > roomOut, roomIn > roomOut { side = -side }262            let anchorX = near ? cx + side * clear : px263            var lx = side > 0 ? anchorX + 8 : anchorX - 8 - w264            lx = min(max(lx, x0 + 2), x0 + width - w - 2)265            let onRight = side > 0266            let top = coteY - gw.height + 2267            // fond : le texte reste lisible s'il recouvre la cote ou l'attache268            let backing = CGRect(x: lx - 3, y: top - 1, width: w + 6, height: gw.height + nw.height + 2)269            lc.opacity = labelOpacity270            lc.fill(Path(backing), with: .color(background))271            if let nameText { lc.draw(nameText, at: CGPoint(x: onRight ? lx : lx + w, y: top + gw.height), anchor: onRight ? .topLeading : .topTrailing) }272            if let gapText {273                var gc = lc274                gc.opacity = labelOpacity * (near ? 1 : min(1, max(0, (p.cote - 0.6) / 0.4)))275                gc.draw(gapText, at: CGPoint(x: onRight ? lx : lx + w, y: top), anchor: onRight ? .topLeading : .topTrailing)276            }277        }278    }279280    /// Le plomb au repos sur la jauge : pointe sur la ligne de base, bout de fil au-dessus.281    static func restingPlumb(_ ctx: GraphicsContext, cx: CGFloat, baseline b: CGFloat, height: CGFloat, thread: CGFloat, lineWidth: CGFloat) {282        var fil = Path()283        fil.move(to: CGPoint(x: cx, y: b - height - thread)); fil.addLine(to: CGPoint(x: cx, y: b - height + 1))284        ctx.stroke(fil, with: .color(Theme.ink), lineWidth: lineWidth)285        ctx.fill(BrandGeometry.plumb(tip: CGPoint(x: cx, y: b), height: height), with: .color(Theme.plumb))286    }287}288289/// Jauge de valeur statique (fiches, comparateur) : la valeur est la verticale, le prix un losange, l'écart coté.290struct ValueGauge: View {291    let scale: GaugeScale292    var priceLabel: String?293    var gapPct: Double?294    var background: Color = Theme.bg295    var plumbHeight: CGFloat = 30296297    var body: some View {298        let tick = GaugeDraw.smallSize(10.5), label = GaugeDraw.smallSize(11)299        let above = plumbHeight + 12 + label * 1.6 + 6300        Canvas { ctx, size in301            let b = above302            let gap = gapPct303            GaugeDraw.draw(ctx, scale: scale, x0: 0, width: size.width, baseline: b, plumbHeight: plumbHeight, progress: .done,304                           priceLabel: priceLabel, gapLabel: gap.map { Fmt.pct($0) }, background: background, tickFont: tick, labelFont: label)305            GaugeDraw.restingPlumb(ctx, cx: size.width / 2, baseline: b, height: plumbHeight, thread: 10, lineWidth: 2)306        }307        .frame(height: above + 14 + tick * 1.4)308        .accessibilityHidden(true)309    }310}311312/// Jauge miniature d'une ligne de liste : pas d'oscillation ; le losange du prix glisse à sa place en 240 ms.313struct MiniGauge: View {314    let scale: GaugeScale315    var background: Color = Theme.bg316    @State private var shown = false317    @Environment(\.accessibilityReduceMotion) private var reduceMotion318    @Environment(MotionCenter.self) private var motion319320    var body: some View {321        Canvas { ctx, size in322            let b = size.height - 6323            var s = scale324            s.price = nil325            GaugeDraw.draw(ctx, scale: s, x0: 0, width: size.width, baseline: b, plumbHeight: 13, progress: .done, priceLabel: nil,326                           gapLabel: nil, background: background, tickFont: 9, labelFont: 9, compact: true)327            GaugeDraw.restingPlumb(ctx, cx: size.width / 2, baseline: b, height: 13, thread: 4, lineWidth: 1.5)328        }329        .overlay {330            GeometryReader { g in331                if let px = scale.priceX(width: g.size.width) {332                    Rectangle().fill(background)333                        .overlay(Rectangle().strokeBorder(Theme.ink, lineWidth: 1.4))334                        .frame(width: 7, height: 7)335                        .rotationEffect(.degrees(45))336                        .position(x: shown ? px : g.size.width / 2, y: g.size.height - 6)337                        .opacity(shown ? 1 : 0)338                }339            }340        }341        .frame(height: 24)342        .onAppear {343            guard !shown else { return }344            if motion.allowed(reduceMotion: reduceMotion) {345                withAnimation(.timingCurve(0.2, 0.7, 0.2, 1, duration: 0.24).delay(0.08)) { shown = true }346            } else { shown = true }347        }348        .accessibilityHidden(true)349    }350}351
Files main
Menu

Theme