Repository Public
1//2// Fabri-Ka iOS v23// File: FabriKa/Features/Stores/StoreView.swift4// Description: page d'une boutique — la grande enseigne (le bras se tire, la plaque s'accroche et bat), qui elle5// est et où, son site, ses produits, sa place sur la carte, ses voisines. Fiche « annuaire » sobre6// quand le catalogue n'est pas suivi. Ce que la règle « public » écarte chez elle est dit.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10//1112import SwiftUI1314struct StoreView: View {15 let id: String1617 @Environment(AppModel.self) private var model18 @Environment(Library.self) private var library19 @Environment(MotionCenter.self) private var motion20 @Environment(\.accessibilityReduceMotion) private var reduceMotion21 @Environment(\.horizontalSizeClass) private var sizeClass2223 @State private var state: Loadable<StoreDetail> = .loading24 @State private var choreo: SignChoreo?25 @State private var t: Double = 026 @State private var started = false27 @State private var safari: IdentifiedURL?2829 var body: some View {30 ScrollViewReader { proxy in31 ScrollView {32 VStack(alignment: .leading, spacing: 0) {33 switch state {34 case .loading: LoadingSign(label: "Chargement de la boutique").pageColumn()35 case .failed(let e): ErrorState(error: e) { Task { await load() } }.pageColumn()36 case .loaded(let d, let stale):37 if stale { StaleBanner().pageColumn().padding(.bottom, 12) }38 StoreHeader(t: choreo == nil ? 0 : t, choreo: choreo, detail: d, wide: sizeClass == .regular,39 onSite: { safari = IdentifiedURL(d.website) })40 if d.catalogue { content(d) } else { directoryOnly(d) }41 }42 }43 .padding(.top, 10).padding(.bottom, 44)44 }45 .onChange(of: state.value?.store.id) { _, v in46 guard v != nil, let a = model.launchAnchor else { return }47 Task { @MainActor in48 try? await Task.sleep(for: .milliseconds(500))49 proxy.scrollTo(a, anchor: .top)50 }51 }52 }53 .linen()54 .navigationTitle(state.value?.store.name ?? "")55 .navigationBarTitleDisplayMode(.inline)56 .toolbar {57 if let d = state.value, d.catalogue {58 ToolbarItemGroup(placement: .topBarTrailing) {59 if let url = URL(string: "/boutiques/" + APIClient.segment(d.store.id), relativeTo: APIClient.site)?.absoluteURL {60 ShareLink(item: url, subject: Text(d.store.name)) { Image(systemName: "square.and.arrow.up") }61 .accessibilityLabel("Partager la boutique")62 }63 }64 }65 }66 .simultaneousGesture(DragGesture(minimumDistance: 12).onChanged { _ in settle() })67 .sheet(item: $safari) { SafariView(url: $0.url).ignoresSafeArea() }68 .task { await load() }69 }7071 private func load() async {72 if state.value == nil, state.error != nil { state = .loading }73 guard let s = await Loadable.from({ try await APIClient.shared.store(id, pageSize: 12) }) else { return }74 state = s75 guard let d = s.value else { return }76 library.update(d.store)77 if !started {78 started = true79 // l'entrée dans une boutique : entière aux deux premières de la session, puis sans battement80 choreo = motion.storeChoreo(reduceMotion: reduceMotion)81 if let c = choreo {82 if let frozen = motion.frozenT { t = min(frozen, c.total) } else {83 t = 084 withAnimation(.linear(duration: c.total / 1000)) { t = c.total }85 }86 }87 }88 }8990 private func settle() {91 guard let c = choreo, t < c.total, motion.frozenT == nil else { return }92 var tx = Transaction()93 tx.disablesAnimations = true94 withTransaction(tx) { t = c.total }95 }9697 // --- Contenu --------------------------------------------------------------------------------------9899 @ViewBuilder100 private func content(_ d: StoreDetail) -> some View {101 let store = d.store102 VStack(alignment: .leading, spacing: 0) {103 // qui elle est104 VStack(alignment: .leading, spacing: 12) {105 if let s = store.summary {106 Text(s).font(.body).foregroundStyle(Theme.ink2).lineSpacing(3).fixedSize(horizontal: false, vertical: true)107 .textSelection(.enabled)108 Text("Présentation tirée du site de la boutique.").font(.footnote).foregroundStyle(Theme.ink3)109 }110 HonestNote(text: store.originSentence + " Fabri-Ka ne sait pas, produit par produit, où l'objet a été fabriqué.",111 icon: store.isReseller ? "ic-boutique" : "ic-atelier")112 if !store.certifications.isEmpty, store.originLabel?.contains("adhérer") != true {113 HonestNote(text: "La boutique déclare adhérer à : " + store.certifications.map(\.label).joined(separator: ", ") + ".")114 }115 if store.place == nil { HonestNote(text: "Lieu non précisé par la boutique.", icon: "ic-region") }116 }117 .padding(.top, 26)118119 // faits120 VStack(spacing: 0) {121 if let s = d.stats {122 FactRow("Produits au répertoire", Fmt.count(s.products ?? store.n))123 if let n = s.inStock { FactRow("En stock au dernier relevé", Fmt.count(n)) }124 if let n = s.new, n > 0 { FactRow("Vus depuis 14 jours", Fmt.count(n)) }125 if let span = Fmt.span(s.priceMin, s.priceMax) {126 FactRow("Prix", span + (s.priceMedian.map { " · médiane \(Fmt.shortPrice($0))" } ?? ""))127 }128 }129 if let f = d.freshness, let ago = Fmt.ago(f.lastOk) {130 FactRow("Dernier relevé réussi", ago + (f.cadenceHours.map { " · toutes les \(Int($0)) h" } ?? ""))131 }132 FactRow("Au répertoire depuis", Fmt.month(store.firstSeen), divider: !d.listedBy.isEmpty)133 if !d.listedBy.isEmpty { FactRow("Répertoriée par", d.listedBy.prefix(4).joined(separator: ", "), divider: false) }134 }135 .padding(.top, 22)136 .id("facts")137 }138 .pageColumn()139140 // ses produits141 if let p = d.products, !p.products.isEmpty {142 VStack(alignment: .leading, spacing: 14) {143 SectionHeader("Ses produits", note: Fmt.products(p.total) + " au répertoire, les plus récents d'abord.")144 let cats = (d.facets?.categories ?? d.categories).filter { $0.n > 0 }.prefix(8)145 if cats.count > 1 {146 ScrollView(.horizontal, showsIndicators: false) {147 HStack(spacing: 8) {148 ForEach(Array(cats)) { c in149 Chip(label: c.label, count: c.n) {150 var f = catalogue(store)151 f.category = c.key; f.categoryName = c.label152 model.openSearch(f)153 }154 }155 }156 .padding(.horizontal, Theme.margin)157 }158 .padding(.horizontal, -Theme.margin)159 }160 ProductGrid(products: p.products, trigger: .secondary, showStore: false)161 if p.total > p.products.count {162 Button("Voir ses \(Fmt.products(p.total))") { model.openSearch(catalogue(store)) }163 .buttonStyle(SecondaryButtonStyle()).num().frame(maxWidth: 380).padding(.top, 6)164 .accessibilityIdentifier("store-all-products")165 }166 }167 .pageColumn(920)168 .padding(.top, 36)169 .id("products")170 .opacity(choreo?.state(at: t).action ?? 1)171 } else {172 Text("Aucun produit de cette boutique n'est publié pour l'instant.")173 .font(.subheadline).foregroundStyle(Theme.ink3).pageColumn().padding(.top, 30)174 }175176 VStack(alignment: .leading, spacing: 0) {177 contact(d)178 if let coordinate = store.coordinate {179 VStack(alignment: .leading, spacing: 12) {180 SectionHeader("Où elle est", note: [store.city, store.region].compactMap { $0 }.joined(separator: ", "))181 if d.placeVerified { StatusPill(kind: .verified) }182 StoreMiniMap(coordinate: coordinate, name: store.name)183 HonestNote(text: "La position est le centre du secteur postal, à quelques kilomètres près."184 + (d.placeVerified ? " « Lieu vérifié » veut dire une seule chose : l'adresse de la boutique a été recoupée." : "")185 + (d.regionSource == "secteur_postal" ? " La région est déduite du code postal." : ""))186 }187 .padding(.top, 36)188 .id("map")189 }190 if !d.nearby.isEmpty {191 VStack(alignment: .leading, spacing: 0) {192 SectionHeader("Boutiques voisines").padding(.bottom, 4)193 ForEach(d.nearby.prefix(6)) { s in194 NavRow(icon: "ic-boutique", title: s.name,195 detail: [Fmt.distance(s.distanceKm), s.city, Fmt.products(s.n)].compactMap { $0 }.joined(separator: " · ")) {196 model.openStore(s.id)197 }198 }199 }200 .padding(.top, 36)201 }202 if !d.similar.isEmpty {203 VStack(alignment: .leading, spacing: 18) {204 SectionHeader("Boutiques semblables", note: "Même catégorie dominante" + (store.region != nil ? ", même région d'abord." : "."))205 SignGrid(items: Array(d.similar.prefix(4))) { StoreCard(store: $0, showImage: false) }206 }207 .padding(.top, 36)208 .id("similar")209 }210 if !d.excluded.isEmpty {211 VStack(alignment: .leading, spacing: 6) {212 Text("Ce que le répertoire ne montre pas de cette boutique").font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink)213 Text(d.excluded.map { "\(Fmt.group($0.n)) : \($0.label)" }.joined(separator: " ; ") + ".")214 .font(.footnote).num().foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)215 }216 .padding(.top, 36)217 .accessibilityElement(children: .combine)218 }219 }220 .pageColumn()221 }222223 private func catalogue(_ store: Store) -> SearchFilters {224 var f = SearchFilters()225 f.store = store.id; f.storeName = store.name226 return f227 }228229 @ViewBuilder230 private func contact(_ d: StoreDetail) -> some View {231 let c = d.contact232 if c.phone != nil || c.email != nil || !c.socials.isEmpty || d.shipping != nil {233 VStack(alignment: .leading, spacing: 0) {234 SectionHeader("La joindre").padding(.bottom, 4)235 if let p = c.phone, let url = URL(string: "tel:" + (p.tel ?? p.display).filter { $0.isNumber || $0 == "+" }) {236 FactRow(label: "Téléphone") { Link(p.display, destination: url).font(.subheadline.weight(.medium)).num() }237 }238 if let e = c.email, let url = URL(string: "mailto:" + e) {239 FactRow(label: "Courriel") { Link(e, destination: url).font(.subheadline.weight(.medium)) }240 }241 ForEach(c.socials.prefix(4), id: \.self) { s in242 if let url = URL(string: s.url) {243 FactRow(label: s.network.capitalized) { Link(Fmt.host(s.url) ?? s.url, destination: url).font(.subheadline.weight(.medium)) }244 }245 }246 if let ship = d.shipping {247 Text("Livraison, selon la boutique").eyebrowStyle().padding(.top, 16)248 Text(ship).font(.subheadline).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true).padding(.top, 4)249 }250 }251 .padding(.top, 36)252 }253 }254255 /// Fiche « annuaire » : répertoriée, sans catalogue suivi.256 private func directoryOnly(_ d: StoreDetail) -> some View {257 VStack(alignment: .leading, spacing: 12) {258 Text(d.note ?? "Cette boutique est répertoriée, mais son catalogue n'est pas suivi : Fabri-Ka ne connaît que son site.")259 .font(.body).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)260 if let c = d.store.coordinate { StoreMiniMap(coordinate: c, name: d.store.name) }261 }262 .pageColumn()263 .padding(.top, 24)264 .accessibilityIdentifier("store-directory-only")265 }266}267268/// L'en-tête d'une boutique : la grande enseigne et ses actions. Vue `Animatable` (t en ms), comme la fiche.269struct StoreHeader: View, @preconcurrency Animatable {270 var t: Double271 let choreo: SignChoreo?272 let detail: StoreDetail273 let wide: Bool274 let onSite: () -> Void275276 var animatableData: Double {277 get { t }278 set { t = newValue }279 }280281 var body: some View {282 let s = choreo?.state(at: t) ?? .settled283 let store = detail.store284 VStack(alignment: .leading, spacing: 0) {285 HangingSign(metrics: .page, platine: s.platine, arm: s.arm, leg: s.leg, shown: s.plaqueShown, theta: s.theta) {286 Plaque(full: s.full, theta: s.theta, radius: 8, padding: EdgeInsets(top: 16, leading: 20, bottom: 18, trailing: 18)) { tone in287 PlaqueText(tone: tone, eyebrow: store.eyebrow, name: store.name,288 line: detail.catalogue ? store.countLine : [store.city, store.region].compactMap { $0 }.joined(separator: ", "),289 nameSize: wide ? 40 : 30)290 }291 .scaleEffect(s.plaqueScale, anchor: .top)292 }293 .padding(.leading, wide ? 0 : -6)294 .accessibilityElement(children: .ignore)295 .accessibilityLabel("\(store.eyebrow), \(store.name), \(store.countLine)")296 .accessibilityAddTraits(.isHeader)297 .accessibilityIdentifier("store-sign")298299 VStack(alignment: .leading, spacing: 10) {300 HStack(spacing: 10) {301 Button(action: onSite) {302 HStack(spacing: 8) {303 Text("Voir son site").lineLimit(1)304 Image("ic-lien-boutique").resizable().scaledToFit().frame(width: 18, height: 18)305 }306 }307 .buttonStyle(PrimaryButtonStyle())308 .disabled(detail.website == nil)309 .accessibilityIdentifier("visit-site")310 if detail.catalogue { FollowButton(store: store) }311 }312 .frame(maxWidth: 480)313 if let host = Fmt.host(detail.website) {314 Text("On n'achète rien ici : le bouton mène à \(host).")315 .font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true)316 }317 }318 .padding(.top, 22)319 .opacity(s.name).offset(y: 8 * (1 - s.name))320 }321 .pageColumn()322 }323}324