SPB Git

Repository Public

CarteVue.swift 20.2 KB 454 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Valo-Plex iOS9// File             : ValoPlex/Features/CarteVue.swift10// Description      : carte de tous les plex du Québec, en plan ou en 3D. Même11//                    rendu que la carte du site (src/components/CarteParc.tsx)12//                    : vue d'ensemble en pastilles ; de près, ce sont les vrais13//                    bâtiments du fond de carte qui prennent la couleur de la14//                    valeur par porte (Design/CarteGL.swift).15// Module           : ValoPlex16// Repository       : https://git.spboucher.ai/valo-plex-ios17// Project Website  : https://www.valo-plex.com18// Created          : 2026-12-0119// Last Modified    : 2026-12-0120//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 SwiftUI9495struct CibleCarte: Equatable {96    var lat: Double97    var lng: Double98    var zoom: Double99    /// Change à chaque demande, pour qu'une même adresse puisse être rejointe deux fois.100    var jeton = UUID()101}102103// MARK: écran104105struct CarteVue: View {106    @Environment(Navigation.self) private var navigation107108    @State private var relief = true109    @State private var classe = ""110    @State private var vendre = false111    @State private var donnees: ReponseCarte?112    @State private var vue: API.VueCarte?113    @State private var etat = ""114    @State private var prete = false115    @State private var enCours = false116    @State private var choix: PointCarte?117    @State private var voisins: [PointCarte] = []118    @State private var cible: CibleCarte?119    @State private var requete = ""120    @State private var resultats: [Resultat] = []121    @State private var legende = true122    @State private var depart: CibleCarte?123124    /// Montréal, comme la carte du site.125    static let departDefaut = CibleCarte(lat: 45.53, lng: -73.6, zoom: 12.2)126127    private struct Demande: Hashable {128        let vue: API.VueCarte?129        let classe: String130        let vendre: Bool131    }132133    var body: some View {134        VStack(spacing: 0) {135            HStack(spacing: 12) {136                Marque(taille: 26)137                Text("Valo-Plex").font(.serif(20, .demiGras, style: .headline)).foregroundStyle(VX.encre)138                Spacer()139                mode140            }141            .padding(.horizontal, VX.marge)142            .frame(height: 52)143            Filet(couleur: VX.encre)144            barre145            Filet(couleur: VX.encre)146            ZStack(alignment: .topLeading) {147                if let depart {148                    CarteGL(contenu: .parc(donnees), relief: relief, depart: depart, cible: cible,149                            surVue: { vue = $0 },150                            surGroupe: { cles in151                                // le plus proche du doigt d'abord ; les autres plex du même bâtiment sont listés152                                let index = Dictionary((donnees?.points ?? []).map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })153                                let l = cles.compactMap { index[$0] }154                                choix = l.first155                                voisins = Array(l.dropFirst().prefix(11))156                            },157                            surPrete: { prete = true })158                        .ignoresSafeArea(.keyboard)159                        .accessibilityLabel("Carte de tous les plex du Québec")160                        .accessibilityIdentifier("carte-gl")161                }162                if !prete {163                    VStack(spacing: 10) {164                        Marque(taille: 44, boucle: true)165                        Etiquette("La carte se dessine")166                    }167                    .frame(maxWidth: .infinity, maxHeight: .infinity)168                    .background(VX.papier2)169                }170                if prete { legendeVue.padding(10) }171                if !resultats.isEmpty { suggestions }172            }173            .overlay(alignment: .bottom) { if let choix { fiche(choix).padding(10) } }174            Filet(couleur: VX.encre)175            HStack(spacing: 10) {176                if enCours { Marque(taille: 18, boucle: true) }177                Text(etat.isEmpty ? "Tous les plex du Québec : de près, chaque bâtiment prend la couleur de sa valeur." : etat)178                    .font(.sans(12.5, style: .caption)).foregroundStyle(VX.encre2).lineLimit(2).fixedSize(horizontal: false, vertical: true)179                Spacer(minLength: 0)180            }181            .padding(.horizontal, VX.marge)182            .padding(.vertical, 8)183            .frame(minHeight: 44)184            .accessibilityIdentifier("carte-etat")185        }186        .background(VX.papier.ignoresSafeArea())187        .onAppear {188            guard depart == nil else { return }189            if let d = navigation.carteDepart { depart = CibleCarte(lat: d.lat, lng: d.lng, zoom: d.zoom) } else { depart = Self.departDefaut }190            if navigation.cartePlan { relief = false }191            if !navigation.filtre.classe.isEmpty, navigation.carteDepart != nil { classe = navigation.filtre.classe }192        }193        .task(id: Demande(vue: vue, classe: classe, vendre: vendre)) { await charger() }194        .task(id: requete) { await chercher() }195    }196197    // MARK: commandes198199    private var mode: some View {200        HStack(spacing: 0) {201            ForEach([false, true], id: \.self) { m in202                Button {203                    relief = m204                } label: {205                    Text(m ? "3D" : "PLAN")206                        .font(.custom("IBMPlexMono-Medium", fixedSize: 11))207                        .tracking(0.6)208                        .foregroundStyle(relief == m ? VX.papier : VX.encre)209                        .frame(width: 52, height: 32)210                        .background(relief == m ? VX.encre : Color.clear)211                        .contentShape(Rectangle())212                }213                .buttonStyle(.plain)214                .accessibilityLabel(m ? "Vue en trois dimensions" : "Vue en plan")215                .accessibilityAddTraits(relief == m ? .isSelected : [])216                .accessibilityIdentifier(m ? "carte-3d" : "carte-plan")217            }218        }219        .overlay(Rectangle().strokeBorder(VX.encre, lineWidth: 1))220    }221222    private var barre: some View {223        HStack(spacing: 8) {224            HStack(spacing: 6) {225                TextField("", text: $requete, prompt: Text("Aller à une adresse").foregroundStyle(VX.encre3))226                    .font(.sans(15, style: .subheadline))227                    .foregroundStyle(VX.encre)228                    .textInputAutocapitalization(.never)229                    .autocorrectionDisabled()230                    .submitLabel(.search)231                    .accessibilityIdentifier("carte-recherche")232                if !requete.isEmpty {233                    Button {234                        requete = ""235                        resultats = []236                    } label: {237                        Text("×").font(.sans(20)).foregroundStyle(VX.encre2).frame(width: 24, height: 24)238                    }239                    .buttonStyle(.plain)240                    .accessibilityLabel("Effacer la recherche")241                }242            }243            .padding(.horizontal, 10)244            .frame(height: 38)245            .background(VX.carton)246            .overlay(Rectangle().strokeBorder(VX.encre, lineWidth: 1))247248            Menu {249                Button("Tous les types") { classe = "" }250                ForEach(Fmt.classes, id: \.cle) { c in Button(c.nom) { classe = c.cle } }251            } label: {252                HStack(spacing: 5) {253                    Text(classe.isEmpty ? "Type" : Fmt.libelleClasse(classe)).font(.sans(14, style: .subheadline)).foregroundStyle(VX.encre).lineLimit(1)254                    Fleche().rotation(.degrees(-90)).stroke(VX.encre, lineWidth: 1.2).frame(width: 6, height: 10)255                }256                .padding(.horizontal, 10)257                .frame(height: 38)258                .background(classe.isEmpty ? VX.carton : VX.papier3)259                .overlay(Rectangle().strokeBorder(VX.encre, lineWidth: 1))260            }261            .accessibilityLabel("Type d'immeuble : \(classe.isEmpty ? "tous" : Fmt.libelleClasse(classe))")262263            Button {264                vendre.toggle()265            } label: {266                Text("À vendre")267                    .font(.sans(14, vendre ? .moyen : .normal, style: .subheadline))268                    .foregroundStyle(vendre ? VX.papier : VX.encre)269                    .lineLimit(1)270                    .padding(.horizontal, 10)271                    .frame(height: 38)272                    .background(vendre ? VX.cuivre : VX.carton)273                    .overlay(Rectangle().strokeBorder(vendre ? VX.cuivre : VX.encre, lineWidth: 1))274            }275            .buttonStyle(.plain)276            .accessibilityLabel("À vendre seulement")277            .accessibilityAddTraits(vendre ? .isSelected : [])278            .accessibilityIdentifier("carte-vendre")279        }280        .padding(.horizontal, VX.marge)281        .padding(.vertical, 8)282    }283284    private var suggestions: some View {285        VStack(spacing: 0) {286            ForEach(Array(resultats.enumerated()), id: \.element.id) { i, r in287                if i > 0 { Filet(couleur: VX.papier2) }288                Button {289                    if let c = r.coordonnee { cible = CibleCarte(lat: c.latitude, lng: c.longitude, zoom: 17.5) }290                    resultats = []291                    requete = ""292                    UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)293                } label: {294                    HStack(spacing: 6) {295                        Text(Fmt.adresse(r.adresse)).font(.sans(15, style: .subheadline)).foregroundStyle(VX.encre)296                        Text("· \(r.municipalite ?? "")").font(.sans(13, style: .footnote)).foregroundStyle(VX.encre2)297                        Spacer(minLength: 0)298                    }299                    .lineLimit(1)300                    .padding(.horizontal, 12)301                    .padding(.vertical, 11)302                    .contentShape(Rectangle())303                }304                .buttonStyle(.plain)305            }306        }307        .background(VX.carton)308        .overlay(Rectangle().strokeBorder(VX.encre, lineWidth: 1))309        .padding(.horizontal, VX.marge)310        .padding(.top, -1)311    }312313    private var legendeVue: some View {314        VStack(alignment: .leading, spacing: 5) {315            Button {316                legende.toggle()317            } label: {318                HStack(spacing: 6) {319                    Etiquette("Valeur par porte", couleur: VX.encre)320                    Text(legende ? "−" : "+").font(.custom("IBMPlexMono-Medium", fixedSize: 12)).foregroundStyle(VX.encre)321                }322                .contentShape(Rectangle())323            }324            .buttonStyle(.plain)325            .accessibilityLabel(legende ? "Replier la légende" : "Déplier la légende")326            if legende {327                ForEach(Array(VX.teintesPorte.enumerated()), id: \.offset) { i, c in328                    HStack(spacing: 7) {329                        Rectangle().fill(Color(hex: c)).frame(width: 12, height: 12).overlay(Rectangle().strokeBorder(VX.encre, lineWidth: 0.5))330                        Text(VX.libellesPorte[i]).font(.custom("IBMPlexMono-Regular", fixedSize: 10.5)).foregroundStyle(VX.encre)331                    }332                }333                HStack(spacing: 7) {334                    Rectangle().fill(VX.cuivre).frame(width: 12, height: 12)335                    Text("à vendre").font(.custom("IBMPlexMono-Regular", fixedSize: 10.5)).foregroundStyle(VX.encre)336                }337            }338        }339        .padding(9)340        .background(VX.carton)341        .overlay(Rectangle().strokeBorder(VX.encre, lineWidth: 1))342        .accessibilityElement(children: .contain)343    }344345    /// Feuille de l'immeuble touché : adresse, valeur, par porte, prix demandé et écart, accès à la fiche.346    private func fiche(_ p: PointCarte) -> some View {347        VStack(alignment: .leading, spacing: 0) {348            HStack(alignment: .top) {349                Etiquette((p.n.map { Fmt.logements($0) } ?? "Immeuble") + (p.an.map { " · \($0)" } ?? ""))350                Spacer()351                Button {352                    choix = nil353                    voisins = []354                } label: {355                    Text("×").font(.sans(22)).foregroundStyle(VX.encre).frame(width: 36, height: 30, alignment: .topTrailing).contentShape(Rectangle())356                }357                .buttonStyle(.plain)358                .accessibilityLabel("Fermer")359            }360            Text(Fmt.adresse(p.a)).font(.serif(21, style: .title3)).foregroundStyle(VX.encre).fixedSize(horizontal: false, vertical: true)361            Text(p.v.map { p.s == "ordre" ? "≈ " + Fmt.grand($0) : Fmt.dollars($0) } ?? "Aucune valeur")362                .font(.serif(30, style: .title)).foregroundStyle(p.s == "ordre" ? VX.encre2 : VX.encre).padding(.top, 8)363            HStack(spacing: 8) {364                Rectangle().fill(p.aVendre ? VX.cuivre : VX.teintePorte(p.pp)).frame(width: 11, height: 11).overlay(Rectangle().strokeBorder(VX.encre, lineWidth: 0.5))365                Text((p.pp.map { "\(Fmt.dollars($0)) par porte" } ?? "") + (p.s == "ordre" ? " · ordre de grandeur" : ""))366                    .font(.sans(13.5, style: .footnote)).foregroundStyle(VX.encre2)367            }368            .padding(.top, 2)369            if let av = p.av, av > 0 {370                Ligne("Demandé \(Fmt.dollars(av))", Fmt.pct(p.ecart, 0, signe: true), couleur: (p.ecart ?? 0) < 0 ? VX.cuivre : VX.brique, premiere: true)371                    .padding(.top, 8)372            }373            NavigationLink(value: Route.immeuble(p.id)) { Text("Ouvrir la fiche") }374                .buttonStyle(BoutonEncre())375                .padding(.top, 12)376                .accessibilityIdentifier("carte-ouvrir")377            if !voisins.isEmpty {378                Etiquette("Dans le même bâtiment").padding(.top, 14).padding(.bottom, 4)379                ScrollView {380                    VStack(spacing: 0) {381                        ForEach(voisins) { x in382                            Button {383                                voisins = [p] + voisins.filter { $0.id != x.id }384                                choix = x385                            } label: {386                                HStack {387                                    Text(Fmt.adresse(x.a)).font(.sans(14.5, style: .subheadline)).foregroundStyle(VX.encre).lineLimit(1)388                                    Spacer(minLength: 8)389                                    Text(x.v.map { Fmt.grand($0) } ?? Fmt.vide).font(.mono(13, style: .footnote)).foregroundStyle(VX.encre)390                                }391                                .padding(.vertical, 8)392                                .overlay(alignment: .top) { Filet(couleur: VX.papier2) }393                                .contentShape(Rectangle())394                            }395                            .buttonStyle(.plain)396                        }397                    }398                }399                .frame(maxHeight: 120)400            }401        }402        .padding(16)403        .frame(maxWidth: 460, alignment: .leading)404        .background(VX.carton)405        .overlay(Rectangle().strokeBorder(VX.encre, lineWidth: 1))406        .frame(maxWidth: .infinity, alignment: .leading)407    }408409    // MARK: données410411    private func charger() async {412        guard let vue else { return }413        // courte pause à la fin d'un déplacement : le service accepte 240 appels par minute414        try? await Task.sleep(for: .milliseconds(180))415        guard !Task.isCancelled else { return }416        enCours = true417        defer { enCours = false }418        do {419            let d = try await API.carte(vue, classe: classe, vendre: vendre)420            guard !Task.isCancelled else { return }421            donnees = d422            if !d.parPoints || !d.points.contains(where: { $0.id == choix?.id }) {423                choix = nil424                voisins = []425            }426            etat = Self.phrase(d, relief: relief, vendre: vendre)427        } catch is CancellationError {428        } catch {429            guard !Task.isCancelled else { return }430            etat = "La carte n'a pas pu charger cette zone. Déplacez-la pour réessayer."431        }432    }433434    nonisolated static func phrase(_ d: ReponseCarte, relief: Bool, vendre: Bool) -> String {435        if d.parPoints {436            if d.points.isEmpty { return vendre ? "Aucun plex à vendre dans la vue." : "Aucun immeuble de 2 logements et plus dans la vue." }437            return "\(Fmt.nombre(d.points.count)) \(vendre ? "plex à vendre" : "immeubles") dans la vue. Touchez un bâtiment pour sa valeur."438        }439        let n = d.cases.reduce(0) { $0 + $1.n }440        return "\(Fmt.nombre(n)) immeubles dans la vue, regroupés. Rapprochez la carte : chaque bâtiment prend la couleur de sa valeur."441    }442443    private func chercher() async {444        let q = requete.trimmingCharacters(in: .whitespaces)445        guard q.count >= 3 else {446            resultats = []447            return448        }449        try? await Task.sleep(for: .milliseconds(220))450        guard !Task.isCancelled else { return }451        if let r = try? await API.recherche(q, n: 6), !Task.isCancelled { resultats = r.filter { $0.coordonnee != nil } }452    }453}454
Files main
Menu

Theme