Repository Public
1//2// Fabri-Ka iOS v23// File: FabriKa/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, search, stores, saved17}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 store(String)25 case regions26 case region(String)27 case city(String)28 case recents29 case settings30 case about31 case method32 case privacy33 case register34}3536enum Appearance: String, CaseIterable, Identifiable, Sendable {37 case system, light, dark38 var id: String { rawValue }39 var label: String {40 switch self {41 case .system: "Selon le système"42 case .light: "Clair"43 case .dark: "Sombre"44 }45 }46 var scheme: ColorScheme? {47 switch self {48 case .system: nil49 case .light: .light50 case .dark: .dark51 }52 }53}5455@MainActor56@Observable57final class AppModel {58 var tab: AppTab = .home59 var paths: [AppTab: NavigationPath] = [:]60 var toast: String?61 let motion: MotionCenter6263 var appearance: Appearance {64 didSet { UserDefaults.standard.set(appearance.rawValue, forKey: "appearance") }65 }6667 /// arguments de lancement utiles aux tests et aux captures68 let launchAnchor: String?69 let launchSheet: String?70 let launchQuery: String?71 let launchMap: Bool72 let launchSaved: String?7374 init(motion: MotionCenter) {75 self.motion = motion76 let d = UserDefaults.standard77 appearance = Appearance(rawValue: d.string(forKey: "appearance") ?? "") ?? .system78 launchAnchor = d.string(forKey: "FBAnchor")79 launchSheet = d.string(forKey: "FBSheet")80 launchQuery = d.string(forKey: "FBQuery")81 launchMap = d.bool(forKey: "FBMap")82 launchSaved = d.string(forKey: "FBSaved")83 if let t = d.string(forKey: "FBTab"), let tab = AppTab(rawValue: t) { self.tab = tab }84 // destination ouverte au lancement : « produit/<uid> », « boutique/<id> », « region/<slug> », « categorie/<slug> »…85 if let o = d.string(forKey: "FBOpen"), let u = URL(string: "fabrika://" + (o.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? o)) {86 handle(url: u, forcedGesture: motion.isForced)87 }88 if let r = d.string(forKey: "FBRoute") {89 var f = SearchFilters()90 f.q = d.string(forKey: "FBSearch") ?? ""91 if let s = d.string(forKey: "FBSort"), let so = SortOrder(rawValue: s) { f.sort = so }92 if d.bool(forKey: "FBNew") { f.new = true; f.daysMax = 7 }93 let map: [String: Route] = ["categories": .categories, "regions": .regions, "recents": .recents, "settings": .settings,94 "about": .about, "privacy": .privacy, "method": .method, "register": .register, "search": .search(f)]95 if let route = map[r] { open(route) }96 }97 }9899 func path(for tab: AppTab) -> Binding<NavigationPath> {100 Binding(get: { self.paths[tab] ?? NavigationPath() }, set: { self.paths[tab] = $0 })101 }102103 /// Ouvre une destination dans l'onglet courant.104 func open(_ route: Route, animated: Bool = true) {105 var p = paths[tab] ?? NavigationPath()106 p.append(route)107 if animated {108 paths[tab] = p109 } else {110 var t = Transaction()111 t.disablesAnimations = true112 withTransaction(t) { paths[tab] = p }113 }114 }115116 /// Ouvre la fiche d'un produit touché : la carte et le rectangle de sa vignette partent avec lui, pour que la117 /// photo voyage jusqu'à sa place et que l'enseigne se pose sans attendre le réseau.118 func openProduct(_ product: Product, from source: CGRect? = nil, trigger: SignTrigger = .card) {119 motion.arm(SignSeed(product: product, source: source, trigger: trigger))120 // quand le geste se joue, la fiche arrive d'un coup : c'est la photo qui voyage, pas la page121 let plays = trigger != .direct && source != nil && motion.allowed(reduceMotion: UIAccessibility.isReduceMotionEnabled)122 open(.product(product.uid), animated: !plays)123 }124125 func openStore(_ id: String) { open(.store(id)) }126 func openSearch(_ f: SearchFilters) { open(.search(f)) }127128 func openCategory(key: String, label: String, sub: (slug: String, label: String)? = nil) {129 var f = SearchFilters()130 f.category = key; f.categoryName = label131 if let sub { f.subcategory = sub.slug; f.subcategoryName = sub.label }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 /// Identifiant d'un produit dans un chemin canonique : `/produits/{slug}-{uid}` (uid = 20 caractères hexadécimaux).144 nonisolated static func productUID(fromPathComponent c: String) -> String? {145 let last = c.split(separator: "-").last.map(String.init) ?? c146 let hex = CharacterSet(charactersIn: "0123456789abcdef")147 guard last.count == 20, last.unicodeScalars.allSatisfy(hex.contains) else { return nil }148 return last149 }150151 /// Liens profonds : `fabrika://produit/<uid>` et les chemins du site (`/produits/<slug>-<uid>`, `/boutiques/<id>`,152 /// `/categorie/<slug>[/<sous-catégorie>]`, `/region/<slug>`, `/ville/<slug>`, `/regions`, `/carte`, `/favoris`…).153 func handle(url: URL, forcedGesture: Bool = false) {154 var parts = url.pathComponents.filter { $0 != "/" }155 if url.scheme == "fabrika", let host = url.host(percentEncoded: false), !host.isEmpty { parts.insert(host, at: 0) }156 guard let first = parts.first else { return }157 let rest = Array(parts.dropFirst())158 let arg = rest.first?.removingPercentEncoding ?? rest.first159 switch first {160 case "produit", "produits":161 guard let arg else { tab = .search; return }162 let uid = AppModel.productUID(fromPathComponent: arg) ?? arg163 if forcedGesture {164 // capture ou test du geste : la fiche le joue sans carte d'origine165 motion.arm(SignSeed(product: Product(uid: uid, title: ""), source: nil, trigger: .card))166 }167 open(.product(uid), animated: !forcedGesture)168 case "boutique", "boutiques":169 if let arg { open(.store(arg)) } else { tab = .stores }170 case "carte": tab = .stores171 case "categorie":172 guard let arg else { open(.categories); return }173 var f = SearchFilters()174 f.category = arg; f.categoryName = arg.replacingOccurrences(of: "-", with: " ").capitalized175 if rest.count > 2, rest[1] == "region" {176 f.region = rest[2]; f.regionName = rest[2].replacingOccurrences(of: "-", with: " ").capitalized177 } else if rest.count > 1 {178 f.subcategory = rest[1]; f.subcategoryName = rest[1].replacingOccurrences(of: "-", with: " ").capitalized179 }180 open(.search(f))181 case "categories": open(.categories)182 case "region": if let arg { open(.region(arg)) } else { open(.regions) }183 case "regions": open(.regions)184 case "ville": if let arg { open(.city(arg)) }185 case "recherche":186 var f = SearchFilters()187 f.q = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.first { $0.name == "q" }?.value ?? ""188 open(.search(f))189 case "favoris": tab = .saved190 case "inscrire": open(.register)191 case "a-propos": open(.about)192 case "methode": open(.method)193 case "confidentialite": open(.privacy)194 case "reglages": open(.settings)195 default: break196 }197 }198}199