SPB Git

Repository Public

PlumbScene.swift 18.9 KB 413 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/PlumbScene.swift10// Description      : la scène du geste « d'aplomb » en tête d'une fiche — la11//                    photo (ou un pignon filaire) prend place, le fil à plomb12//                    tombe du faîte, oscille lentement, s'immobilise net ; sa13//                    pointe désigne la valeur estimée sur la jauge ; puis le14//                    chiffre, le prix et la cote d'écart apparaissent. Fonction15//                    pure du temps (TimelineView), interruptible d'un toucher,16//                    figée par `-VPPlumbT <ms>`.17// Module           : VraiPrix18// Repository       : https://git.spboucher.ai/vrai-prix-ios-v319// Project Website  : https://www.vrai-prix.com20// Created          : 2026-11-2621// Last Modified    : 2026-11-2822//23// =============================================================================24// AUTHOR & PROFESSIONAL AFFILIATION25// =============================================================================26//27// Author           : Simon-Pierre Boucher28// Position         : Professor of Finance29// Institution      : Université du Québec en Outaouais (UQO)30// Department       : Département des sciences administratives31// Organization     : SP Boucher32//33// Website          : https://spboucher.ai34// Git              : https://git.spboucher.ai35//36// =============================================================================37// OFFICIAL CONTACT DIRECTORY38// =============================================================================39//40// General          : info@spboucher.ai41// Professional     : contact@spboucher.ai42// Direct           : simon@spboucher.ai43// Research         : research@spboucher.ai44// Development      : dev@spboucher.ai45// Support          : support@spboucher.ai46// Security/Admin   : admin@spboucher.ai47// Notifications    : notifications@spboucher.ai48//49// Preferred Contact: support@spboucher.ai50//51// =============================================================================52// COPYRIGHT & INTELLECTUAL PROPERTY53// =============================================================================54//55// Copyright (c) 202656// Simon-Pierre Boucher57//58// All rights reserved where applicable.59//60// This file is governed by the applicable project license,61// copyright notices, institutional agreements and relevant law.62//63// Unless expressly authorized by the applicable license or64// rights holder, copying, redistribution, sublicensing,65// publication and commercial exploitation are not permitted.66//67// Existing third-party rights and notices remain unaffected.68//69// =============================================================================70// CONFIDENTIALITY & SECURITY71// =============================================================================72//73// Classification   : Public74// Distribution     : Public repository; use is governed by the project license75// Security Contact : admin@spboucher.ai76//77// Access to this source does not independently grant permission78// to redistribute or disclose confidential materials.79//80// Do not embed credentials, private keys, access tokens,81// certificates or confidential personal information.82//83// =============================================================================84// LICENSE & MAINTENANCE85// =============================================================================86//87// License          : None specified (no license file in this repository)88// Maintainer       : Simon-Pierre Boucher89// Technical Contact: dev@spboucher.ai90//91// =============================================================================92// END OF SP BOUCHER SOURCE HEADER93// =============================================================================9495import SwiftUI96import UIKit9798/// Ce que la scène mesure.99struct PlumbData: Equatable, Sendable {100    var value: Double101    var low: Double102    var high: Double103    var price: Double?104    /// « Prix demandé », « Vendue en mars 2024 »105    var priceLabel: String?106    /// lecture du prix : celle du service, sinon la même règle appliquée ici107    var reading: Reading?108109    init(value: Double, low: Double, high: Double, price: Double? = nil, priceLabel: String? = nil, reading: Reading? = nil) {110        self.value = value; self.low = low; self.high = high; self.price = price; self.priceLabel = priceLabel111        self.reading = reading ?? Reading(price: price, value: value, low: low, high: high)112    }113114    // --- API v3 : la valeur porte son régime, la lecture du prix est une position face à l'intervalle ---115    /// dessin de la jauge (API 2 par défaut)116    var style: GaugeScale.Style = .classic117    /// surtitre du chiffre118    var title = "Valeur estimée"119    /// le chiffre tel qu'il s'écrit (arrondi selon son incertitude, « ≈ » pour un ordre de grandeur)120    var amountText: String?121    /// la ligne sous le chiffre (l'intervalle et ce qu'il veut dire)122    var caption: String?123    /// écart du prix comparé à la valeur, en % (celui du moteur)124    var gapOverride: Double?125    /// phrase de position pour un lecteur d'écran (« Dans l'intervalle »)126    var positionText: String?127    /// chorégraphie 3.0 : le chiffre s'écrit à l'instant où le plomb touche l'axe128    var answerFirst = false129130    /// Valeur de l'API v3. `gap` et `position` viennent du moteur quand il a situé le prix.131    init(v3 value: Double, low: Double, high: Double, approximate: Bool, price: Double? = nil, priceLabel: String? = nil,132         gap: Double? = nil, position: PricePosition? = nil) {133        self.value = value; self.low = low; self.high = high; self.price = price; self.priceLabel = priceLabel134        reading = nil135        style = approximate ? .approximate : .interval136        title = approximate ? "Ordre de grandeur" : "Valeur estimée"137        amountText = approximate ? ValueFmt.approx(value) : ValueFmt.firm(value, low: low, high: high)138        caption = approximate ? "Entre \(Fmt.money(low)) et \(Fmt.money(high)), sans plus de précision"139                              : "Intervalle : \(Fmt.money(low)) à \(Fmt.money(high))"140        gapOverride = price == nil ? nil : gap141        positionText = position?.label142        answerFirst = true143    }144145    var scale: GaugeScale { GaugeScale(value: value, low: low, high: high, price: price, style: style) }146    var gapPct: Double? { gapOverride ?? reading?.gapPct }147}148149struct PlumbScene: View {150    let data: PlumbData151    /// photo de tête ; nil : pignon filaire (estimation seule)152    var photo: UIImage?153    var level: PlumbLevel154    var background: Color = Theme.bg155    /// appelé quand les lignes sous le chiffre peuvent apparaître (fin du geste, ou d'emblée sans mouvement)156    var onReveal: () -> Void = {}157158    @Environment(MotionCenter.self) private var motion159    @Environment(\.horizontalSizeClass) private var sizeClass160    @State private var width: CGFloat = 0161    @State private var start: Date?162    @State private var finished = false163    @State private var settled = false164    @State private var revealed = false165    @State private var fade = 0.0166    @State private var tasks: [Task<Void, Never>] = []167168    /// hauteur du plomb : nettement visible (le prototype web, à 30, a été jugé trop discret)169    private var plumbH: CGFloat { sizeClass == .regular ? 46 : 40 }170    private var threadW: CGFloat { 2.5 }171    private var drop: CGFloat { plumbH + 12 + GaugeDraw.smallSize(11) * 2.9 + 8 }172173    private struct Geo: Sendable {174        var w: CGFloat175        var heroH: CGFloat176        var pivot: CGPoint177        var baseline: CGFloat178        var height: CGFloat179        var gable: Gable?180        var hasPhoto: Bool181        var plumbH: CGFloat182        var threadW: CGFloat183        var tickFont: CGFloat184        var labelFont: CGFloat185    }186    private struct Gable: Sendable { var apex: CGPoint; var half: CGFloat; var rise: CGFloat }187188    private func geo(_ w: CGFloat) -> Geo {189        let below = 14 + GaugeDraw.smallSize(10.5) * 1.5190        if photo != nil {191            let h = (w * (w > 560 ? 0.56 : 0.68)).rounded()192            return Geo(w: w, heroH: h, pivot: CGPoint(x: w / 2, y: 0), baseline: h + drop, height: h + drop + below, gable: nil,193                       hasPhoto: true, plumbH: plumbH, threadW: threadW, tickFont: GaugeDraw.smallSize(10.5), labelFont: GaugeDraw.smallSize(11))194        }195        let gw = min(w * 0.66, 340), rise = (gw * 0.36).rounded()196        let apex = CGPoint(x: w / 2, y: 12)197        let h = apex.y + rise + 22198        return Geo(w: w, heroH: h, pivot: apex, baseline: h + drop, height: h + drop + below, gable: Gable(apex: apex, half: gw / 2, rise: rise),199                   hasPhoto: false, plumbH: plumbH, threadW: threadW, tickFont: GaugeDraw.smallSize(10.5), labelFont: GaugeDraw.smallSize(11))200    }201202    var body: some View {203        VStack(spacing: 0) {204            Color.clear.frame(height: 0)205                // largeur arrondie au demi-point : la scène se dimensionne à cette largeur, et une largeur relue telle quelle peut206                // dériver d'un epsilon à chaque passe de mise en page (boucle sans fin constatée sur une fiche d'inscription)207                .onGeometryChange(for: CGFloat.self) { ($0.size.width * 2).rounded(.down) / 2 } action: { width = $0 }208            if width > 0 {209                let g = geo(width)210                if let frozen = motion.frozenT, level != .none {211                    frame(g, t: frozen, choreo: choreo(level) ?? choreo(.signature)!)212                } else if let choreo = choreo(level), !finished {213                    TimelineView(.animation) { ctx in214                        frame(g, t: start.map { ctx.date.timeIntervalSince($0) * 1000 } ?? 0, choreo: choreo)215                    }216                } else {217                    // état final : plomb immobile sur la valeur (sans mouvement : un fondu de 140 ms)218                    frame(g, t: 1e9, choreo: choreo(.signature)!).opacity(level == .none ? fade : 1)219                }220            }221        }222        .contentShape(Rectangle())223        .onTapGesture { finish() }   // toujours interruptible : un toucher amène l'état final224        .sensoryFeedback(.impact(weight: .light, intensity: 0.7), trigger: settled)225        .onAppear(perform: begin)226        .onDisappear { tasks.forEach { $0.cancel() }; tasks = [] }227        .accessibilityElement(children: .ignore)228        .accessibilityLabel(accessibilityText)229        .accessibilityIdentifier("plumb-scene")230    }231232    private var accessibilityText: String {233        var s = "\(data.title) : \(data.amountText ?? Fmt.money(data.value)). \(data.style == .classic ? "Fourchette" : "Intervalle") : \(Fmt.money(data.low)) à \(Fmt.money(data.high))."234        if let p = data.price, let l = data.priceLabel {235            s += " \(l) : \(Fmt.money(p))."236            if let r = data.reading { s += " Écart : \(Fmt.pct(r.gapPct)). \(r.verdict.label)." }237            else if let g = data.gapPct { s += " Écart : \(Fmt.pct(g))." + (data.positionText.map { " \($0)." } ?? "") }238        }239        return s240    }241242    private func begin() {243        guard start == nil, !finished else { return }244        guard motion.frozenT == nil else { revealed = true; onReveal(); return }245        guard let choreo = choreo(level) else {246            finished = true247            withAnimation(.easeOut(duration: 0.14)) { fade = 1 }248            reveal()249            return250        }251        start = .now252        tasks = [253            Task { @MainActor in254                try? await Task.sleep(for: .milliseconds(Int(choreo.settle)))255                if !Task.isCancelled { settled = true }256            },257            Task { @MainActor in258                try? await Task.sleep(for: .milliseconds(Int(choreo.rows.a)))259                if !Task.isCancelled { reveal() }260            },261            Task { @MainActor in262                try? await Task.sleep(for: .milliseconds(Int(choreo.total) + 60))263                if !Task.isCancelled { finished = true }264            },265        ]266    }267268    /// Table des temps du niveau : celle du geste 3.0 quand la valeur vient de l'API v3.269    private func choreo(_ l: PlumbLevel) -> PlumbChoreo? {270        guard data.answerFirst else { return l.choreo }271        switch l {272        case .signature: return .signature3273        case .short: return .short3274        case .none: return nil275        }276    }277278    private func finish() {279        guard !finished, motion.frozenT == nil else { return }280        tasks.forEach { $0.cancel() }; tasks = []281        finished = true282        reveal()283    }284285    private func reveal() {286        guard !revealed else { return }287        revealed = true288        onReveal()289    }290291    // MARK: Une image du geste292293    @ViewBuilder294    private func frame(_ g: Geo, t: Double, choreo c: PlumbChoreo) -> some View {295        let kHero = PlumbChoreo.easeOut(c.hero.at(t))296        let kValue = PlumbChoreo.easeOut(c.value.at(t))297        VStack(spacing: 0) {298            ZStack(alignment: .top) {299                if let photo {300                    Image(uiImage: photo).resizable().aspectRatio(contentMode: .fill)301                        .frame(width: g.w, height: g.heroH)302                        .clipShape(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous))303                        .scaleEffect(0.965 + 0.035 * kHero, anchor: .center)304                        .opacity(kHero)305                }306                let d = data, bgc = background307                Canvas { ctx, _ in PlumbScene.draw(ctx, g, t, c, d, bgc) }308                    .frame(width: g.w, height: g.height)309            }310            .frame(width: g.w, height: g.height, alignment: .top)311312            // le chiffre se pose : opacité et 6 pt de montée, jamais de compteur qui défile313            VStack(spacing: 4) {314                Text(data.title).eyebrowStyle()315                Text(data.amountText ?? Fmt.money(data.value))316                    .font(.display(sizeClass == .regular ? 42 : 36, weight: data.style == .approximate ? .regular : .semibold)).num()317                    .foregroundStyle(Theme.ink)318                    .minimumScaleFactor(0.6).lineLimit(1)319                    .accessibilityIdentifier("estimate-value")320                Text(data.caption ?? "Fourchette : \(Fmt.money(data.low)) à \(Fmt.money(data.high))")321                    .font(.footnote).num().foregroundStyle(Theme.ink3)322                    .multilineTextAlignment(.center)323            }324            .padding(.top, 10)325            .opacity(kValue)326            .offset(y: (1 - kValue) * 6)327        }328    }329330    nonisolated private static func draw(_ ctx: GraphicsContext, _ g: Geo, _ t: Double, _ c: PlumbChoreo, _ data: PlumbData, _ background: Color) {331        let cx = g.w / 2332        let plumbH = g.plumbH, threadW = g.threadW333        let progress = GaugeProgress(sol: PlumbChoreo.easeOut(c.sol.at(t)), ticks: c.ticks.at(t), range: PlumbChoreo.easeOut(c.range.at(t)),334                                     price: PlumbChoreo.easeOut(c.price.at(t)), cote: PlumbChoreo.easePlumb(c.cote.at(t)))335        GaugeDraw.draw(ctx, scale: data.scale, x0: 0, width: g.w, baseline: g.baseline, plumbHeight: plumbH, progress: progress,336                       priceLabel: data.priceLabel, gapLabel: data.gapPct.map { Fmt.pct($0) }, background: background,337                       tickFont: g.tickFont, labelFont: g.labelFont)338339        // pignon filaire : il se trace avec la mise en place340        if let gb = g.gable {341            let k = PlumbChoreo.easeOut(c.hero.at(t))342            var roof = Path()343            roof.move(to: CGPoint(x: gb.apex.x - gb.half * k, y: gb.apex.y + gb.rise * k))344            roof.addLine(to: gb.apex)345            roof.addLine(to: CGPoint(x: gb.apex.x + gb.half * k, y: gb.apex.y + gb.rise * k))346            var rc = ctx347            rc.opacity = min(1, k * 1.5)348            rc.stroke(roof, with: .color(Theme.ink), style: StrokeStyle(lineWidth: 3, lineCap: .butt, lineJoin: .miter, miterLimit: 8))349        }350351        // le pendule : le fil se déroule du pivot, le plomb au bout ; rotation autour du pivot352        guard t >= c.descent.a else { return }353        let kd = PlumbChoreo.easePlumb(c.descent.at(t))354        let full = g.baseline - g.pivot.y355        let len = max(plumbH * 0.6, full * kd)           // distance pivot → pointe356        let theta = -c.angle(t)                          // positif = vers la droite357        var pc = ctx358        pc.translateBy(x: g.pivot.x, y: g.pivot.y)359        pc.rotate(by: .degrees(theta))360        pc.translateBy(x: -g.pivot.x, y: -g.pivot.y)361        let tip = CGPoint(x: cx, y: g.pivot.y + len)362        var fil = Path()363        fil.move(to: g.pivot); fil.addLine(to: CGPoint(x: cx, y: tip.y - plumbH + 1.5))364        let plumb = BrandGeometry.plumb(tip: tip, height: plumbH)365366        if g.hasPhoto {367            // exemplaire sur la photo : fil ivoire à liseré sombre, plomb à liseré clair ; il s'efface à la fin368            let onPhoto = 1 - c.retract.at(t)369            var a = pc370            a.clip(to: Path(CGRect(x: -g.w, y: 0, width: g.w * 3, height: g.heroH)), options: [])371            // (le découpage suit la rotation du contexte : négligeable à ces angles, et la photo est large)372            var af = a373            af.opacity = onPhoto374            af.stroke(fil, with: .color(.black.opacity(0.34)), lineWidth: threadW + 1.6)375            af.stroke(fil, with: .color(Theme.ivory), lineWidth: threadW)376            a.stroke(plumb, with: .color(.black.opacity(0.25)), style: StrokeStyle(lineWidth: 4.6, lineJoin: .miter, miterLimit: 6))377            a.stroke(plumb, with: .color(Theme.ivory), style: StrokeStyle(lineWidth: 3.2, lineJoin: .miter, miterLimit: 6))378            a.fill(plumb, with: .color(Theme.plumb))379            // exemplaire sous la photo : fil charbon, plomb nu380            var b = pc381            b.clip(to: Path(CGRect(x: -g.w, y: g.heroH, width: g.w * 3, height: g.height)), options: [])382            b.stroke(fil, with: .color(Theme.ink), lineWidth: threadW)383            b.fill(plumb, with: .color(Theme.plumb))384        } else {385            pc.stroke(fil, with: .color(Theme.ink), lineWidth: threadW)386            pc.fill(plumb, with: .color(Theme.plumb))387        }388    }389390}391392/// Chargement (attente réelle seulement) : le plomb du symbole oscille sans amortissement, A = 6°, T = 1 400 ms.393struct PlumbLoader: View {394    var size: CGFloat = 44395    var label: String = "Chargement"396    @Environment(\.accessibilityReduceMotion) private var reduceMotion397398    var body: some View {399        Group {400            if reduceMotion {401                BrandSymbol()402            } else {403                TimelineView(.animation) { ctx in404                    BrandSymbol(angle: 6 * sin(2 * .pi * ctx.date.timeIntervalSinceReferenceDate / 1.4))405                }406            }407        }408        .frame(width: size, height: size)409        .accessibilityElement(children: .ignore)410        .accessibilityLabel(label)411    }412}413
Files main
Menu

Theme