SPB Git

Repository Public

AppModel.swift 7.0 KB 179 lines swift

1//2//  Food-Ka iOS v23//  File: FoodKa/App/AppModel.swift4//  Description: état global — onglets, navigation, liens profonds, apparence, arguments de lancement (captures et5//               tests sans piloter l'interface).6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import Observation12import SwiftUI13import UIKit1415enum AppTab: String, Hashable, CaseIterable, Sendable {16    case home, deals, basket, market, followed17}1819/// Destinations de navigation partagées par tous les onglets.20enum Route: Hashable, Sendable {21    case product(String)22    case search(SearchFilters)23    case categories24    case deals25    case flyers26    case flyer(String)27    case stores28    case store(String)29    case index30    case movements31    case recents32    case settings33    case about34    case privacy35    case method36}3738enum Appearance: String, CaseIterable, Identifiable, Sendable {39    case system, light, dark40    var id: String { rawValue }41    var label: String {42        switch self {43        case .system: "Selon le système"44        case .light: "Clair"45        case .dark: "Sombre"46        }47    }48    var scheme: ColorScheme? {49        switch self {50        case .system: nil51        case .light: .light52        case .dark: .dark53        }54    }55}5657@MainActor58@Observable59final class AppModel {60    var tab: AppTab = .home61    var paths: [AppTab: NavigationPath] = [:]62    var toast: String?63    /// le mode « à l'épicerie » est ouvert (plein écran)64    var storeMode = false65    let motion: MotionCenter6667    var appearance: Appearance {68        didSet { UserDefaults.standard.set(appearance.rawValue, forKey: "appearance") }69    }7071    /// arguments de lancement utiles aux tests et aux captures72    let launchAnchor: String?73    let launchSheet: String?74    let launchQuery: String?7576    init(motion: MotionCenter) {77        self.motion = motion78        let d = UserDefaults.standard79        appearance = Appearance(rawValue: d.string(forKey: "appearance") ?? "") ?? .system80        launchAnchor = d.string(forKey: "FKAnchor")81        launchSheet = d.string(forKey: "FKSheet")82        launchQuery = d.string(forKey: "FKQuery")83        if let t = d.string(forKey: "FKTab"), let tab = AppTab(rawValue: t) { self.tab = tab }84        // destination ouverte au lancement : « produit/<id> », « enseigne/<id> », « circulaires/<id> », « categorie/<slug> »85        if let o = d.string(forKey: "FKOpen"), let u = URL(string: "foodka://" + (o.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? o)) {86            handle(url: u, forcedGesture: motion.isForced)87        }88        if let r = d.string(forKey: "FKRoute") {89            var f = SearchFilters()90            f.q = d.string(forKey: "FKSearch") ?? ""91            if let s = d.string(forKey: "FKSort"), let so = SortOrder(rawValue: s) { f.sort = so }92            let map: [String: Route] = ["categories": .categories, "deals": .deals, "flyers": .flyers, "stores": .stores, "index": .index,93                                        "movements": .movements, "recents": .recents, "settings": .settings, "about": .about,94                                        "privacy": .privacy, "method": .method, "search": .search(f)]95            if let route = map[r] { open(route) }96        }97        storeMode = d.bool(forKey: "FKStoreMode")98    }99100    func path(for tab: AppTab) -> Binding<NavigationPath> {101        Binding(get: { self.paths[tab] ?? NavigationPath() }, set: { self.paths[tab] = $0 })102    }103104    /// Ouvre une destination dans l'onglet courant.105    func open(_ route: Route, animated: Bool = true) {106        var p = paths[tab] ?? NavigationPath()107        p.append(route)108        if animated {109            paths[tab] = p110        } else {111            var t = Transaction()112            t.disablesAnimations = true113            withTransaction(t) { paths[tab] = p }114        }115    }116117    /// Ouvre la fiche d'un produit touché : la carte et le rectangle de sa vignette partent avec lui, pour que le118    /// produit voyage jusqu'à sa tablette sans attendre le réseau.119    func openProduct(_ product: Product, from source: CGRect? = nil, trigger: ShelfTrigger = .card) {120        motion.arm(ShelfSeed(product: product, source: source, trigger: trigger))121        // quand le geste se joue, la fiche arrive d'un coup : c'est le produit qui voyage, pas la page122        let plays = trigger != .direct && motion.allowed(reduceMotion: UIAccessibility.isReduceMotionEnabled)123        open(.product(product.id), animated: !plays)124    }125126    func openSearch(_ f: SearchFilters) { open(.search(f)) }127128    func openCategory(name: String, slug: String, sub: (name: String, slug: String)? = nil) {129        var f = SearchFilters()130        f.category = slug; f.categoryName = name131        if let sub { f.subcategory = sub.slug; f.subcategoryName = sub.name }132        open(.search(f))133    }134135    func showToast(_ text: String) {136        toast = text137        Task { @MainActor in138            try? await Task.sleep(for: .seconds(2.2))139            if toast == text { toast = nil }140        }141    }142143    /// Liens profonds : `foodka://produit/<id>` et les chemins de www.food-ka.com (`/produit/<id>`, `/enseigne/<id>`,144    /// `/circulaires/<id>`, `/categorie/<rayon>[/<sous-rayon>]`, `/aubaines`, `/panier`, `/marche`).145    func handle(url: URL, forcedGesture: Bool = false) {146        var parts = url.pathComponents.filter { $0 != "/" }147        if url.scheme == "foodka", let host = url.host(percentEncoded: false), !host.isEmpty { parts.insert(host, at: 0) }148        guard let first = parts.first else { return }149        let rest = parts.dropFirst().joined(separator: "/").removingPercentEncoding ?? parts.dropFirst().joined(separator: "/")150        switch first {151        case "produit" where !rest.isEmpty:152            if forcedGesture {153                // capture ou test du geste : la fiche le joue sans carte d'origine154                motion.arm(ShelfSeed(product: Product(id: rest, name: "", store: "", storeName: "", price: nil), source: nil, trigger: .card))155            }156            open(.product(rest), animated: !forcedGesture)157        case "enseigne" where !rest.isEmpty: open(.store(rest))158        case "enseignes": open(.stores)159        case "circulaires" where !rest.isEmpty: tab = .deals; open(.flyer(rest))160        case "circulaires": tab = .deals; open(.flyers)161        case "categorie" where !rest.isEmpty:162            let p = rest.split(separator: "/").map(String.init)163            var f = SearchFilters()164            f.category = p[0]; f.categoryName = p[0].replacingOccurrences(of: "-", with: " ").capitalized165            if p.count > 1 { f.subcategory = p[1]; f.subcategoryName = p[1].replacingOccurrences(of: "-", with: " ").capitalized }166            open(.search(f))167        case "recherche":168            var f = SearchFilters()169            f.q = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.first { $0.name == "q" }?.value ?? ""170            open(.search(f))171        case "aubaines", "soldes": tab = .deals172        case "panier", "liste": tab = .basket173        case "marche", "stats": tab = .market174        case "suivis": tab = .followed175        default: break176        }177    }178}179
Files main
Menu

Theme