SPB Git

Repository Public

AppModel.swift 8.5 KB 222 lines swift

1//2//  Auto-Ka iOS v23//  File: AutoKa/App/AppModel.swift4//  Description: état global — onglets, navigation, liens profonds, recherche en attente, réglages, messages.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//910import Observation11import SwiftUI12import UIKit1314enum AppTab: String, Hashable, CaseIterable, Sendable {15    case home, search, favorites, market, more16}1718/// Destinations de navigation partagées par tous les onglets.19enum Route: Hashable, Sendable {20    case vehicle(String)21    case brands22    /// slug de la marque23    case brand(String)24    /// slugs de la marque et du modèle25    case model(make: String, model: String)26    case cities27    /// slug de la ville28    case city(String)29    case dealers30    /// identifiant du concessionnaire31    case dealer(String)32    case electrics33    case priceDrops34    /// décodeur de NIV, avec un NIV à décoder d'emblée s'il y a lieu35    case vin(String?)36    case recalls37    case compare38    case recent39    case method40    case about41    case privacy42    case terms43    case settings44}4546enum Appearance: String, CaseIterable, Identifiable, Sendable {47    case system, light, dark48    var id: String { rawValue }49    var label: String {50        switch self {51        case .system: "Selon le système"52        case .light: "Clair"53        case .dark: "Sombre"54        }55    }56    var scheme: ColorScheme? {57        switch self {58        case .system: nil59        case .light: .light60        case .dark: .dark61        }62    }63}6465@MainActor66@Observable67final class AppModel {68    var tab: AppTab = .home69    var paths: [AppTab: NavigationPath] = [:]70    /// Recherche à appliquer à l'onglet Recherche (depuis l'accueil, une marque, une ville, une recherche gardée).71    var pendingSearch: PendingSearch?72    var toast: String?7374    var appearance: Appearance {75        didSet { UserDefaults.standard.set(appearance.rawValue, forKey: "appearance") }76    }77    var units: DistanceUnit {78        didSet { UserDefaults.standard.set(units.rawValue, forKey: "units") }79    }8081    /// Cartes déjà chargées, par identifiant : la fiche s'affiche tout de suite avec ce que la carte savait.82    @ObservationIgnored private var seeds: [String: Vehicle] = [:]8384    struct PendingSearch: Equatable {85        var filters: SearchFilters86        var sort: SearchSort = .recent87        /// ouvrir la carte géographique plutôt que la liste88        var map = false89        var id = UUID()90    }9192    init() {93        let d = UserDefaults.standard94        appearance = Appearance(rawValue: d.string(forKey: "appearance") ?? "") ?? .system95        if let u = d.string(forKey: "AKUnits"), let unit = DistanceUnit(rawValue: u) { d.set(unit.rawValue, forKey: "units") }96        units = DistanceUnit(rawValue: d.string(forKey: "units") ?? "") ?? .km97        // arguments de lancement (tests, captures) : onglet, destination, recherche98        if let t = d.string(forKey: "AKTab"), let tab = AppTab(rawValue: t) { self.tab = tab }99        if let s = d.string(forKey: "AKSearch") {100            pendingSearch = PendingSearch(filters: AppModel.filters(fromArgument: s), map: d.string(forKey: "AKMode") == "map")101            tab = .search102        } else if d.string(forKey: "AKMode") == "map" {103            pendingSearch = PendingSearch(filters: SearchFilters(), map: true)104            tab = .search105        }106        if let o = d.string(forKey: "AKOpen"), let u = URL(string: "autoka://" + (o.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? o)) {107            handle(url: u)108        }109        if let r = d.string(forKey: "AKRoute") {110            let map: [String: Route] = ["brands": .brands, "cities": .cities, "dealers": .dealers, "electrics": .electrics, "drops": .priceDrops,111                                        "vin": .vin(d.string(forKey: "AKVIN")), "recalls": .recalls, "compare": .compare, "recent": .recent,112                                        "method": .method, "about": .about, "privacy": .privacy, "terms": .terms, "settings": .settings]113            if let route = map[r] { open(route) }114        }115    }116117    /// `-AKSearch "make:Toyota,model:RAV4,city:Sherbrooke,fuel:electrifie,body:VUS,drop:1"`118    static func filters(fromArgument s: String) -> SearchFilters {119        var f = SearchFilters()120        for pair in s.split(separator: ",") {121            let kv = pair.split(separator: ":", maxSplits: 1).map(String.init)122            guard kv.count == 2 else { continue }123            switch kv[0] {124            case "make": f.makes.append(kv[1])125            case "model": f.models.append(kv[1])126            case "city": f.cities.append(kv[1])127            case "region": f.regions.append(kv[1])128            case "fuel": f.fuels.append(kv[1])129            case "body": f.bodyTypes.append(kv[1])130            case "verdict": f.verdicts.append(kv[1])131            case "kind": f.kind = kv[1]132            case "pricemax": f.priceMax = Int(kv[1])133            case "kmmax": f.kmMax = Int(kv[1])134            case "yearmin": f.yearMin = Int(kv[1])135            case "drop": f.priceDrop = kv[1] == "1"136            case "q": f.q = kv[1]137            default: break138            }139        }140        return f141    }142143    func path(for tab: AppTab) -> Binding<NavigationPath> {144        Binding(get: { self.paths[tab] ?? NavigationPath() }, set: { self.paths[tab] = $0 })145    }146147    /// Ouvre une destination dans l'onglet courant.148    func open(_ route: Route) {149        var p = paths[tab] ?? NavigationPath()150        p.append(route)151        paths[tab] = p152    }153154    /// Lance une recherche dans l'onglet Recherche.155    func search(_ filters: SearchFilters, sort: SearchSort = .recent, map: Bool = false) {156        pendingSearch = PendingSearch(filters: filters, sort: sort, map: map)157        paths[.search] = NavigationPath()158        tab = .search159    }160161    // MARK: Véhicules162163    func seed(_ v: Vehicle) { if seeds[v.uid] == nil || v.isDetail { seeds[v.uid] = v } }164    func seed(for uid: String) -> Vehicle? { seeds[uid] }165166    /// Ouvre la fiche d'un véhicule par le geste « monter à bord » (niveau choisi selon l'origine et les réglages).167    func openVehicle(_ v: Vehicle, origin: BoardingOrigin, boarding: BoardingCenter) {168        seed(v)169        boarding.open(v, origin: origin, reduceMotion: UIAccessibility.isReduceMotionEnabled) { [weak self] in170            self?.open(.vehicle(v.uid))171        }172    }173174    func toggleCompare(_ v: Vehicle, library: Library) {175        switch library.toggleCompare(v.uid) {176        case .added: Haptics.tap(); showToast("Ajouté à la comparaison (\(library.compareIDs.count) sur \(Library.compareMax))")177        case .removed: showToast("Retiré de la comparaison")178        case .full: Haptics.warning(); showToast("La comparaison est limitée à \(Library.compareMax) véhicules")179        }180    }181182    func showToast(_ text: String) {183        toast = text184        Task { @MainActor in185            try? await Task.sleep(for: .seconds(2.4))186            if toast == text { toast = nil }187        }188    }189190    // MARK: Liens191192    /// Liens profonds `autoka://vehicule/<uid>`, `marque/<slug>[/<modèle>]`, `ville/<slug>`, `concessionnaire/<id>`,193    /// `niv/<niv>`, et les adresses équivalentes de www.auto-ka.com (`/vehicule/…`, `/usagees/…`, `/ville/…`).194    func handle(url: URL) {195        var parts = url.pathComponents.filter { $0 != "/" }196        if url.scheme == "autoka", let host = url.host(percentEncoded: false), !host.isEmpty { parts.insert(host, at: 0) }197        guard let first = parts.first else { return }198        let rest = Array(parts.dropFirst()).map { $0.removingPercentEncoding ?? $0 }199        switch first {200        case "vehicule" where !rest.isEmpty: open(.vehicle(rest[0]))201        case "marque" where !rest.isEmpty, "usagees" where !rest.isEmpty:202            open(rest.count > 1 ? .model(make: rest[0], model: rest[1]) : .brand(rest[0]))203        case "marques": open(.brands)204        case "ville" where !rest.isEmpty: open(.city(rest[0]))205        case "villes": open(.cities)206        case "region" where !rest.isEmpty:207            search(.region(rest[0]))208        case "carrosserie" where !rest.isEmpty:209            if let b = BodyType.all.first(where: { Fmt.slug($0.value) == rest[0] }) { search(.body(b.value)) }210        case "concessionnaire" where !rest.isEmpty: open(.dealer(rest[0]))211        case "concessionnaires": open(.dealers)212        case "niv": open(.vin(rest.first))213        case "recherche": tab = .search214        case "carte": search(SearchFilters(), map: true)215        case "stats", "marche": tab = .market216        case "favoris": tab = .favorites217        case "comparer": tab = .favorites; open(.compare)218        default: break219        }220    }221}222
Files main
Menu

Theme