SPB Git

Repository Public

MarketView.swift 31.2 KB 609 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Lou-Ka iOS9// File             : LouKa/Features/Market/MarketView.swift10// Description      : Marché — portrait du marché locatif affiché d'un lieu (API11//                    v3) : indicateurs courants, comparaison à sources12//                    constantes, série hebdomadaire, indice Lou-Ka avec son13//                    intervalle, distribution, loyers par grandeur, lieux qui14//                    bougent. Les périodes provisoires sont dites.15// Module           : LouKa16// Repository       : https://git.spboucher.ai/lou-ka-ios-v317// Project Website  : https://www.lou-ka.com18// Created          : 2026-11-2519// Last Modified    : 2026-11-2820//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author           : Simon-Pierre Boucher26// Position         : Professor of Finance27// Institution      : Université du Québec en Outaouais (UQO)28// Department       : Département des sciences administratives29// Organization     : SP Boucher30//31// Website          : https://spboucher.ai32// Git              : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General          : info@spboucher.ai39// Professional     : contact@spboucher.ai40// Direct           : simon@spboucher.ai41// Research         : research@spboucher.ai42// Development      : dev@spboucher.ai43// Support          : support@spboucher.ai44// Security/Admin   : admin@spboucher.ai45// Notifications    : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification   : Public72// Distribution     : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License          : None specified (no license file in this repository)86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import Charts94import SwiftUI9596@MainActor97@Observable98final class MarketModel {99    var place: Place?100    var rooms: Int?101    var portrait: MarketPortrait?102    var series: MarketSeries?103    var index: IndexSeries?104    var distribution: MarketDistribution?105    var movers: MarketMovers?106    var error: Error?107    var loading = false108109    init(place: Place? = nil) { self.place = place }110111    func load() async {112        loading = true113        error = nil114        let api = APIClient.shared, p = place, r = rooms115        async let po = api.market(place: p, rooms: r)116        async let se = try? api.marketSeries(place: p, rooms: r)117        async let ix = try? api.marketIndex(place: p, rooms: r)118        async let di = try? api.marketDistribution(place: p, rooms: r)119        async let mo = try? api.marketMovers()120        do {121            let v = try await po122            guard p == place, r == rooms else { return }123            portrait = v124            if let pl = v.place, place != nil, place?.placeID == 0 { place = pl }   // lieu venu d'un lien : nom canonique125        } catch is CancellationError {126            return127        } catch {128            if portrait == nil { self.error = error }129        }130        let (sv, iv, dv, mv) = await (se, ix, di, mo)131        guard p?.slug == place?.slug, r == rooms else { return }132        series = sv; index = iv; distribution = dv; movers = mv ?? movers133        loading = false134    }135}136137struct MarketView: View {138    @Environment(AppModel.self) private var app139    @State private var model: MarketModel140    @State private var picking = false141    @State private var draw: Double = 0142    @State private var report: ExternalLink?143    private let isRoot: Bool144145    init(place: Place? = nil) {146        _model = State(initialValue: MarketModel(place: place))147        isRoot = place == nil148    }149150    var body: some View {151        ScrollView {152            LazyVStack(alignment: .leading, spacing: 30) {153                selectors154                if let p = model.portrait {155                    indicators(p)156                    comparison(p)157                    seriesChart158                    indexBlock159                    distributionBlock160                    byRooms(p)161                    if model.place == nil { moversBlock }162                    notes(p)163                } else if let error = model.error {164                    ErrorStateView(error: error) { Task { await model.load() } }165                } else {166                    Skeleton(height: 150, radius: Theme.radius)167                    Skeleton(height: 220, radius: Theme.radius)168                }169                if isRoot { guides }170            }171            .padding(.horizontal, 20).padding(.bottom, 30)172            .frame(maxWidth: 760)173            .frame(maxWidth: .infinity)174        }175        .background(Theme.bg)176        .navigationTitle(isRoot ? "Marché locatif" : (model.place?.name ?? "Marché"))177        .navigationBarTitleDisplayMode(isRoot ? .automatic : .inline)178        .toolbar {179            ToolbarItemGroup(placement: .topBarTrailing) {180                Button {181                    let p = model.place182                    Task { if let u = await APIClient.shared.reportURL(market: p) { report = ExternalLink(url: u) } }183                } label: { Image(systemName: "doc.richtext") }184                    .accessibilityLabel("Rapport PDF du marché")185                if isRoot {186                    NavigationLink(value: Route.settings) { Image(systemName: "gearshape") }.accessibilityLabel("Réglages")187                }188            }189        }190        .refreshable { await model.load() }191        .task(id: "\(model.place?.id ?? "qc")-\(model.rooms ?? -1)") { await model.load() }192        .sheet(isPresented: $picking) { PlacePicker(selected: model.place) { model.place = $0 } }193        .safariSheet($report)194    }195196    // MARK: Lieu et grandeur197198    private var selectors: some View {199        VStack(alignment: .leading, spacing: 12) {200            Text("Loyers affichés dans les annonces (loyers demandés). Ce ne sont ni des loyers signés ni les loyers payés par les locataires en place.")201                .font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)202            Button { picking = true } label: {203                HStack(spacing: 10) {204                    Image(systemName: "mappin.and.ellipse").foregroundStyle(Theme.brand)205                    VStack(alignment: .leading, spacing: 1) {206                        Text(model.place?.name ?? "Tout le Québec").font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink)207                        Text(model.place.map { $0.kindLabel } ?? "Province").font(.caption).foregroundStyle(Theme.ink3)208                    }209                    Spacer()210                    Text("Changer").font(.subheadline.weight(.semibold)).foregroundStyle(Theme.brand)211                }212                .padding(.horizontal, 14).frame(minHeight: 52)213                .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))214                .overlay(RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous).strokeBorder(Theme.lineControl, lineWidth: 1))215            }216            .buttonStyle(.plain)217            .accessibilityLabel("Lieu : \(model.place?.name ?? "tout le Québec"). Changer")218            .accessibilityIdentifier("market.place")219            ScrollView(.horizontal, showsIndicators: false) {220                HStack(spacing: 8) {221                    Chip(label: "Toutes", active: model.rooms == nil) { model.rooms = nil }222                    ForEach([1, 3, 4, 5, 6], id: \.self) { r in223                        Chip(label: Rooms.label(r), active: model.rooms == r) { model.rooms = model.rooms == r ? nil : r }224                    }225                }226            }227            .scrollClipDisabled()228        }229    }230231    // MARK: Indicateurs232233    private func indicators(_ p: MarketPortrait) -> some View {234        VStack(alignment: .leading, spacing: 12) {235            LazyVGrid(columns: [GridItem(.flexible(), spacing: 14), GridItem(.flexible(), spacing: 14)], spacing: 20) {236                metric(p.current["rent_median"], Fmt.money, "loyer médian")237                tile(interquartile(p), "la moitié des loyers", nil)238                metric(p.current["n_active"], { Fmt.int($0) }, "annonces présentes")239                metric(p.current["psf_median"], Fmt.perSqft, "loyer médian au pi²")240                metric(p.lastWeek["n_new"], { Fmt.int($0) }, "annonces nouvelles", hint: p.lastWeekPeriod.map { "semaine du \(Fmt.isoDay($0.start))" })241                metric(p.current["n_sources"], { Fmt.int($0) }, "sources actives")242            }243            .cardStyle()244            if let d = p.asOf {245                Text("Données du \(Fmt.isoDay(d, year: true)). Le stock des 14 derniers jours est provisoire : une partie des annonces disparues récemment réapparaîtra.")246                    .font(.caption).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)247            }248        }249    }250251    private func interquartile(_ p: MarketPortrait) -> String {252        guard let a = p.current["rent_p25"]?.value, let b = p.current["rent_p75"]?.value else { return "—" }253        return "\(Fmt.int(a)) à \(Fmt.money(b))"254    }255256    private func metric(_ i: Indicator?, _ format: (Double?) -> String, _ label: String, hint: String? = nil) -> some View {257        // valeur absente : effectif insuffisant, dit comme tel258        tile(i?.value == nil ? "—" : format(i?.value), label, i?.value == nil ? "effectif insuffisant" : hint)259    }260261    private func tile(_ value: String, _ label: String, _ hint: String?) -> some View {262        StatTile(value: value, label: label, hint: hint)263    }264265    // MARK: Comparaison à sources constantes266267    @ViewBuilder268    private func comparison(_ p: MarketPortrait) -> some View {269        if let m = p.month, let c = m.const["rent_median"], c.changePct != nil {270            VStack(alignment: .leading, spacing: 12) {271                SectionHeader(title: "D'un mois à l'autre",272                              subtitle: "\(Fmt.isoMonth(m.previous?.start).capitalized) comparé à \(Fmt.isoMonth(m.current?.start)), à sources constantes : les mêmes sources aux deux dates, pour ne pas confondre un nouveau site avec un mouvement des loyers.")273                VStack(spacing: 0) {274                    changeRow("Loyer médian", m.const["rent_median"], money: true)275                    changeRow("Loyer médian des annonces nouvelles", m.const["new_rent_median"], money: true)276                    changeRow("Annonces présentes", m.const["n_active"], money: false)277                    changeRow("Annonces nouvelles", m.const["n_new"], money: false)278                }279                if let all = m.all["rent_median"]?.changePct {280                    Text("Toutes sources confondues, sans contrôle : \(Fmt.points(all)).").font(.caption).num().foregroundStyle(Theme.ink3)281                }282            }283        }284    }285286    @ViewBuilder287    private func changeRow(_ label: String, _ c: Change?, money: Bool) -> some View {288        if let c, c.current != nil {289            HStack(alignment: .firstTextBaseline) {290                Text(label).font(.subheadline).foregroundStyle(Theme.ink)291                Spacer(minLength: 8)292                Text(money ? Fmt.money(c.current) : Fmt.int(c.current)).font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink)293                ChangeText(pct: c.changePct).frame(minWidth: 74, alignment: .trailing)294            }295            .padding(.vertical, 11)296            .accessibilityElement(children: .combine)297            Divider().overlay(Theme.line)298        }299    }300301    // MARK: Série302303    @ViewBuilder304    private var seriesChart: some View {305        if let s = model.series {306            let pts = s.points.filter { $0.value != nil }307            VStack(alignment: .leading, spacing: 12) {308                SectionHeader(title: "Loyer médian, semaine par semaine", subtitle: "Annonces présentes en fin de semaine.")309                if pts.count >= 3 {310                    let values = pts.compactMap(\.value)311                    let lo = (values.min() ?? 0) * 0.97, hi = (values.max() ?? 1) * 1.03312                    Chart {313                        ForEach(pts) { p in314                            LineMark(x: .value("Semaine", p.date), y: .value("Loyer", p.value ?? 0))315                                .foregroundStyle(Theme.data1).lineStyle(StrokeStyle(lineWidth: 2))316                            // rond plein : période ferme ; rond vide : période provisoire ou partielle317                            PointMark(x: .value("Semaine", p.date), y: .value("Loyer", p.value ?? 0))318                                .symbol(p.provisional || p.partial ? AnyChartSymbolShape(BasicChartSymbolShape.circle.strokeBorder(lineWidth: 1.6)) : AnyChartSymbolShape(BasicChartSymbolShape.circle))319                                .symbolSize(38).foregroundStyle(Theme.data1)320                        }321                    }322                    .chartYScale(domain: lo...hi)323                    .chartYAxis { AxisMarks(position: .leading, values: .automatic(desiredCount: 4)) { v in324                        AxisGridLine().foregroundStyle(Theme.dataGrid)325                        AxisValueLabel { if let d = v.as(Double.self) { Text(Fmt.money(d)).font(.caption2).monospacedDigit() } }326                    } }327                    .chartXAxis { AxisMarks(values: .automatic(desiredCount: 4)) { v in328                        AxisValueLabel { if let d = v.as(Date.self) { Text(d.formatted(.dateTime.day().month(.abbreviated).locale(Fmt.locale))).font(.caption2) } }329                    } }330                    .frame(height: 200)331                    .mask(alignment: .leading) { GeometryReader { g in Rectangle().frame(width: g.size.width * draw) } }332                    .drawOnAppear($draw, duration: Theme.durDraw)333                    .cardStyle()334                    .accessibilityLabel("Loyer médian par semaine, de \(Fmt.money(values.first)) à \(Fmt.money(values.last))")335                    Text("Ronds vides : semaines encore provisoires ou incomplètes. Moins de quatre mois de données : aucune variation annuelle ni saisonnalité n'est calculable.")336                        .font(.caption).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)337                } else {338                    insufficient("Pas assez de semaines publiables pour tracer une série.")339                }340            }341        }342    }343344    // MARK: Indice345346    @ViewBuilder347    private var indexBlock: some View {348        if let ix = model.index {349            VStack(alignment: .leading, spacing: 12) {350                SectionHeader(title: "Indice Lou-Ka",351                              subtitle: "Premier loyer affiché des annonces nouvelles, à caractéristiques, lieu et source constants. Base 100 en septembre 2026.")352                if ix.published, ix.series.count >= 2 {353                    let lows = ix.series.compactMap(\.low), highs = ix.series.compactMap(\.high)354                    let lo = min(lows.min() ?? 99, 99.5) - 0.3, hi = max(highs.max() ?? 101, 100.5) + 0.3355                    Chart {356                        ForEach(ix.series) { p in357                            if let l = p.low, let h = p.high {358                                // intervalle à 95 % : un trait vertical avec ses bornes, pas un aplat flou359                                RuleMark(x: .value("Mois", p.date), yStart: .value("Bas", l), yEnd: .value("Haut", h))360                                    .foregroundStyle(Theme.data1.opacity(0.45)).lineStyle(StrokeStyle(lineWidth: 6, lineCap: .butt))361                            }362                            LineMark(x: .value("Mois", p.date), y: .value("Indice", p.value)).foregroundStyle(Theme.data1)363                            PointMark(x: .value("Mois", p.date), y: .value("Indice", p.value))364                                .symbol(p.flag == "partial" ? AnyChartSymbolShape(BasicChartSymbolShape.circle.strokeBorder(lineWidth: 1.6)) : AnyChartSymbolShape(BasicChartSymbolShape.circle))365                                .symbolSize(44).foregroundStyle(Theme.data1)366                                .annotation(position: .top) { Text(Fmt.dec(p.value, 1)).font(.caption2.weight(.semibold)).monospacedDigit().foregroundStyle(Theme.ink) }367                        }368                        RuleMark(y: .value("Base", 100)).foregroundStyle(Theme.ink3).lineStyle(StrokeStyle(lineWidth: 1, dash: [3, 3]))369                    }370                    .chartYScale(domain: lo...hi)371                    .chartXScale(range: .plotDimension(padding: 28))372                    .chartYAxis { AxisMarks(position: .leading, values: .automatic(desiredCount: 4)) { _ in AxisGridLine().foregroundStyle(Theme.dataGrid); AxisValueLabel().font(.caption2) } }373                    .chartXAxis { AxisMarks(values: ix.series.map(\.date)) { v in374                        AxisValueLabel { if let d = v.as(Date.self) { Text(d.formatted(.dateTime.month(.abbreviated).locale(Fmt.locale))).font(.caption2) } }375                    } }376                    .frame(height: 190)377                    .cardStyle()378                    .accessibilityLabel("Indice Lou-Ka : " + ix.series.map { "\(Fmt.isoMonth($0.start)) \(Fmt.dec($0.value, 1))" }.joined(separator: ", "))379                    Text("Barres : intervalle à 95 %. Rond vide : mois incomplet. L'indice est expérimental : \(ix.series.count) points mensuels.")380                        .font(.caption).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)381                } else {382                    insufficient("Indice non publié pour ce lieu" + (ix.reason.map { " : \($0)." } ?? "."))383                }384            }385        }386    }387388    // MARK: Distribution389390    @ViewBuilder391    private var distributionBlock: some View {392        if let d = model.distribution, d.bins.count > 4 {393            let p95 = d.quantiles["p95"] ?? .infinity394            let bins = d.bins.filter { $0.from < p95 }395            VStack(alignment: .leading, spacing: 12) {396                SectionHeader(title: "Combien coûtent les loyers", subtitle: "Nombre d'annonces par tranche de loyer mensuel.")397                Chart(bins) { b in398                    RectangleMark(xStart: .value("De", b.from + (b.to - b.from) * 0.08), xEnd: .value("À", b.to - (b.to - b.from) * 0.08),399                                  yStart: .value("Base", 0), yEnd: .value("Annonces", b.n))400                        .foregroundStyle(Theme.data1)401                    if let m = d.quantiles["p50"] {402                        RuleMark(x: .value("Médiane", m)).foregroundStyle(Theme.accentUI).lineStyle(StrokeStyle(lineWidth: 1.5, dash: [4, 3]))403                    }404                }405                .chartXAxis { AxisMarks(values: .automatic(desiredCount: 5)) { v in406                    AxisValueLabel { if let x = v.as(Double.self) { Text(Fmt.money(x)).font(.caption2).monospacedDigit() } }407                } }408                .chartYAxis { AxisMarks(position: .leading, values: .automatic(desiredCount: 4)) { _ in AxisGridLine().foregroundStyle(Theme.dataGrid); AxisValueLabel().font(.caption2) } }409                .frame(height: 200)410                .cardStyle()411                .accessibilityLabel("Histogramme des loyers. Médiane \(Fmt.money(d.quantiles["p50"]))")412                Text("\(Fmt.plural(d.n, "annonce", "annonces")). Trait pointillé : médiane (\(Fmt.money(d.quantiles["p50"]))). Les 5 % de loyers les plus élevés, au-delà de \(Fmt.money(d.quantiles["p95"])), ne sont pas tracés.")413                    .font(.caption).num().foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)414            }415        }416    }417418    // MARK: Par grandeur419420    @ViewBuilder421    private func byRooms(_ p: MarketPortrait) -> some View {422        let rows = p.byRooms.filter { $0.median?.value != nil && ($0.rooms ?? 9) < 9 }423        if model.rooms == nil, !rows.isEmpty {424            VStack(alignment: .leading, spacing: 12) {425                SectionHeader(title: "Selon la grandeur", subtitle: "Loyer médian, et entre quelles bornes se trouve la moitié des annonces.")426                VStack(spacing: 0) {427                    ForEach(rows) { s in428                        HStack(alignment: .firstTextBaseline) {429                            Text(s.label).font(.subheadline.weight(.medium)).foregroundStyle(Theme.ink).frame(width: 96, alignment: .leading)430                            Text(s.active.map { Fmt.int($0) } ?? "").font(.caption).num().foregroundStyle(Theme.ink3)431                            Spacer()432                            if let a = s.p25?.value, let b = s.p75?.value {433                                Text("\(Fmt.int(a)) à \(Fmt.int(b))").font(.caption).num().foregroundStyle(Theme.ink3)434                            }435                            Text(Fmt.money(s.median?.value)).font(.subheadline.weight(.semibold)).num().foregroundStyle(Theme.ink)436                                .frame(minWidth: 76, alignment: .trailing)437                        }438                        .padding(.vertical, 11)439                        .accessibilityElement(children: .combine)440                        Divider().overlay(Theme.line)441                    }442                }443            }444        }445    }446447    // MARK: Lieux qui bougent448449    @ViewBuilder450    private var moversBlock: some View {451        if let mv = model.movers {452            let all = (mv.up + mv.down).sorted { abs($0.changePct ?? 0) > abs($1.changePct ?? 0) }453            let real = all.filter { !$0.withinNoise }454            VStack(alignment: .leading, spacing: 12) {455                SectionHeader(title: "Où le loyer médian bouge",456                              subtitle: "\(Fmt.isoMonth(mv.previousPeriod?.start).capitalized) à \(Fmt.isoMonth(mv.currentPeriod?.start)), à sources constantes, villes d'au moins 50 annonces.")457                if real.isEmpty {458                    insufficient("Aucune variation ne sort du bruit de mesure ce mois-ci.")459                } else {460                    VStack(spacing: 0) {461                        ForEach(real.prefix(8)) { m in462                            NavigationLink(value: Route.marketPlace(slug: m.place.slug, kind: m.place.kind, name: m.place.name)) {463                                HStack(alignment: .firstTextBaseline) {464                                    Text(m.place.name).font(.subheadline).foregroundStyle(Theme.ink)465                                    Spacer()466                                    Text("\(Fmt.int(m.previous)) → \(Fmt.money(m.current))").font(.caption).num().foregroundStyle(Theme.ink3)467                                    ChangeText(pct: m.changePct).frame(minWidth: 74, alignment: .trailing)468                                }469                                .padding(.vertical, 11)470                            }471                            .buttonStyle(.plain)472                            Divider().overlay(Theme.line)473                        }474                    }475                }476                let noise = all.count - real.count477                if noise > 0 {478                    Text("\(Fmt.plural(noise, "autre écart est", "autres écarts sont")) dans le bruit de mesure : à lire comme une absence de mouvement.")479                        .font(.caption).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)480                }481            }482        }483    }484485    private func notes(_ p: MarketPortrait) -> some View {486        VStack(alignment: .leading, spacing: 8) {487            if let c = p.constantSources, let t = p.sourcesTotal {488                Text("Panel à sources constantes : \(Fmt.int(c)) sources sur \(Fmt.int(t)).").font(.caption).num().foregroundStyle(Theme.ink3)489            }490            ForEach(p.warnings.dropFirst().prefix(2), id: \.self) { w in491                Text(w).font(.caption).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)492            }493        }494    }495496    private func insufficient(_ text: String) -> some View {497        Label(text, systemImage: "chart.bar.xaxis").font(.footnote).foregroundStyle(Theme.ink2)498            .padding(14).frame(maxWidth: .infinity, alignment: .leading)499            .overlay(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous).strokeBorder(Theme.line2, style: StrokeStyle(lineWidth: 1, dash: [4, 3])))500    }501502    private var guides: some View {503        VStack(alignment: .leading, spacing: 10) {504            SectionHeader(title: "Aller plus loin")505            guide(.neighborhoods(city: nil), "map", "Villes et quartiers", "Loyers, scores et services, classés selon vos priorités")506            guide(.fairValueGuide, "gauge.with.dots.needle.50percent", "L'estimation du loyer", "Valeur centrale, fourchette calibrée, limites")507            guide(.scoresGuide, "star", "Scores de quartier", "Les cinq scores et vos pondérations personnelles")508            guide(.about, "info.circle", "À propos de Lou-Ka", "Agrégateur indépendant, sans compte")509        }510    }511512    private func guide(_ route: Route, _ icon: String, _ title: String, _ subtitle: String) -> some View {513        NavigationLink(value: route) {514            HStack(spacing: 14) {515                Image(systemName: icon).foregroundStyle(Theme.brand).frame(width: 28)516                VStack(alignment: .leading, spacing: 2) {517                    Text(title).font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink)518                    Text(subtitle).font(.caption).foregroundStyle(Theme.ink3)519                }520                Spacer()521                Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(Theme.ink3)522            }523            .padding(.vertical, 10)524            .contentShape(Rectangle())525        }526        .buttonStyle(.plain)527    }528}529530/// Variation en pour cent : flèche, signe et valeur ; jamais la couleur seule.531struct ChangeText: View {532    let pct: Double?533    var body: some View {534        if let pct {535            HStack(spacing: 3) {536                Image(systemName: abs(pct) < 0.05 ? "equal" : pct > 0 ? "arrow.up.right" : "arrow.down.right").font(.system(size: 10, weight: .bold))537                Text(Fmt.points(pct)).font(.footnote.weight(.semibold)).monospacedDigit()538            }539            .foregroundStyle(abs(pct) < 0.05 ? Theme.ink3 : pct > 0 ? Theme.high : Theme.good)540            .accessibilityLabel(abs(pct) < 0.05 ? "stable" : "\(pct > 0 ? "hausse" : "baisse") de \(Fmt.points(pct, signed: false))")541        } else {542            Text("—").font(.footnote).foregroundStyle(Theme.ink3).accessibilityLabel("variation inconnue")543        }544    }545}546547/// Choix d'un lieu pour le marché : la province, une région, une ville, ou une recherche.548struct PlacePicker: View {549    let selected: Place?550    let onPick: (Place?) -> Void551    @Environment(\.dismiss) private var dismiss552    @State private var query = ""553    @State private var regions: [Place] = []554    @State private var cities: [Place] = []555    @State private var hits: [Place] = []556557    var body: some View {558        NavigationStack {559            List {560                if query.trimmingCharacters(in: .whitespaces).count >= 2 {561                    Section("Résultats") { ForEach(hits) { row($0) } }562                } else {563                    Section {564                        Button { onPick(nil); dismiss() } label: {565                            HStack { Text("Tout le Québec").foregroundStyle(Theme.ink); Spacer(); if selected == nil { Image(systemName: "checkmark").foregroundStyle(Theme.brand) } }566                        }567                    }568                    if !regions.isEmpty { Section("Régions") { ForEach(regions) { row($0) } } }569                    if !cities.isEmpty { Section("Villes") { ForEach(cities) { row($0) } } }570                }571            }572            .scrollContentBackground(.hidden)573            .background(Theme.bg)574            .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always), prompt: "Ville, arrondissement, quartier")575            .navigationTitle("Choisir un lieu")576            .navigationBarTitleDisplayMode(.inline)577            .toolbar { ToolbarItem(placement: .topBarTrailing) { Button("Fermer") { dismiss() } } }578            .task {579                async let r = try? APIClient.shared.places(kind: "region")580                async let c = try? APIClient.shared.places(kind: "municipalite", minListings: 150)581                regions = ((await r) ?? []).sorted { ($0.listings ?? 0) > ($1.listings ?? 0) }582                cities = ((await c) ?? []).sorted { ($0.listings ?? 0) > ($1.listings ?? 0) }583            }584            .task(id: query) {585                let q = query.trimmingCharacters(in: .whitespaces)586                guard q.count >= 2 else { hits = []; return }587                try? await Task.sleep(for: .milliseconds(200))588                if Task.isCancelled { return }589                hits = (try? await APIClient.shared.suggestPlaces(q, limit: 12)) ?? []590            }591        }592        .presentationDetents([.large])593    }594595    private func row(_ p: Place) -> some View {596        Button { onPick(p); dismiss() } label: {597            HStack {598                VStack(alignment: .leading, spacing: 2) {599                    Text(p.name).foregroundStyle(Theme.ink)600                    Text([p.kindLabel, p.kind == "region" || p.kind == "municipalite" ? nil : p.parent, p.listings.map { Fmt.plural($0, "annonce", "annonces") }]601                        .compactMap { $0 }.joined(separator: " · ")).font(.caption).monospacedDigit().foregroundStyle(Theme.ink3)602                }603                Spacer()604                if selected?.slug == p.slug, selected?.kind == p.kind { Image(systemName: "checkmark").foregroundStyle(Theme.brand) }605            }606        }607    }608}609
Files main
Menu

Theme