SPB Git

Repository Public

PlacesViews.swift 11.2 KB 245 lines swift

1//2//  Fabri-Ka iOS v23//  File: FabriKa/Features/Places/PlacesViews.swift4//  Description: catégories (enseignes parlantes et sous-catégories), les dix-sept régions en plaques, et la page5//               d'une région ou d'une ville : comptes, catégories fortes (toujours avec le nombre de boutiques sur6//               lequel repose le chiffre), derniers produits, boutiques, carte.7//8//  Author: Simon-Pierre Boucher9//  Contact: contact@spboucher.ai10//1112import SwiftUI1314/// Toutes les catégories ; une catégorie se déplie sur ses sous-catégories (les types déclarés par les boutiques).15struct CategoriesView: View {16    @Environment(AppModel.self) private var model17    @State private var state: Loadable<Categories> = .loading18    @State private var open: String?1920    var body: some View {21        ScrollView {22            VStack(alignment: .leading, spacing: 0) {23                switch state {24                case .loading: LoadingSign(label: "Chargement des catégories")25                case .failed(let e): ErrorState(error: e) { Task { await load() } }26                case .loaded(let c, let stale):27                    if stale { StaleBanner().padding(.bottom, 12) }28                    Text("La catégorie d'un produit est déduite de son nom et du type que déclare la boutique : c'est une heuristique, des erreurs subsistent.")29                        .font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true).padding(.bottom, 8)30                    ForEach(c.categories) { cat in row(cat) }31                }32            }33            .pageColumn()34            .padding(.bottom, 40)35        }36        .linen()37        .navigationTitle("Catégories")38        .task { if state.value == nil { await load() } }39    }4041    private func load() async {42        if let s = await Loadable.from({ try await APIClient.shared.categories() }) { state = s }43    }4445    @ViewBuilder46    private func row(_ cat: CategoryNode) -> some View {47        let isOpen = open == cat.key48        VStack(alignment: .leading, spacing: 0) {49            HStack(spacing: 0) {50                Button { model.openCategory(key: cat.key, label: cat.label) } label: {51                    HStack(spacing: 12) {52                        Image(cat.icon).resizable().scaledToFit().frame(width: 26, height: 26).foregroundStyle(Theme.ink)53                        VStack(alignment: .leading, spacing: 2) {54                            Text(cat.label).font(.editorial(19)).foregroundStyle(Theme.ink).multilineTextAlignment(.leading)55                            Text(Fmt.products(cat.n) + (cat.stores.map { " · " + Fmt.stores($0) } ?? ""))56                                .font(.footnote).num().foregroundStyle(Theme.ink3)57                        }58                        Spacer(minLength: 8)59                    }60                    .padding(.vertical, 13)61                    .contentShape(Rectangle())62                }63                .buttonStyle(.plain)64                .accessibilityIdentifier("category-\(cat.key)")65                if !cat.subcategories.isEmpty {66                    Button { withAnimation(.easeOut(duration: 0.2)) { open = isOpen ? nil : cat.key } } label: {67                        Image(systemName: "chevron.down").font(.footnote.weight(.semibold)).foregroundStyle(Theme.ink3)68                            .rotationEffect(.degrees(isOpen ? 180 : 0))69                            .frame(width: 44, height: 44).contentShape(Rectangle())70                    }71                    .buttonStyle(.plain)72                    .accessibilityLabel(isOpen ? "Replier les sous-catégories de \(cat.label)" : "Voir les sous-catégories de \(cat.label)")73                }74            }75            if isOpen {76                FlowLayout(spacing: 8) {77                    ForEach(cat.subcategories.prefix(40), id: \.slug) { s in78                        Chip(label: s.label, count: s.n) { model.openCategory(key: cat.key, label: cat.label, sub: (s.slug, s.label)) }79                    }80                }81                .padding(.leading, 38).padding(.bottom, 14)82            }83            Hairline()84        }85    }86}8788/// Les dix-sept régions administratives, même vides ; pas de carte du Québec en pictogramme.89struct RegionsView: View {90    @Environment(AppModel.self) private var model91    @State private var state: Loadable<Regions> = .loading9293    var body: some View {94        ScrollView {95            VStack(alignment: .leading, spacing: 0) {96                switch state {97                case .loading: LoadingSign(label: "Chargement des régions")98                case .failed(let e): ErrorState(error: e) { Task { await load() } }99                case .loaded(let r, let stale):100                    if stale { StaleBanner().padding(.bottom, 12) }101                    SignGrid(items: r.regions.sorted { $0.stores > $1.stores }, spacing: 22) { region in102                        RegionPlaque(name: region.name, line: region.stores == 0 ? "Aucune boutique pour l'instant" : region.countLine) {103                            model.open(.region(region.slug))104                        }105                        .accessibilityIdentifier("region-\(region.slug)")106                    }107                    .padding(.top, 8)108                    if let s = r.unknownStores, s > 0 {109                        HonestNote(text: "\(Fmt.stores(s))" + (r.unknownProducts.map { " (\(Fmt.products($0)))" } ?? "") + " n'ont pas de région connue : elles n'apparaissent dans aucune de ces plaques.")110                            .padding(.top, 28)111                    }112                }113            }114            .pageColumn(920)115            .padding(.bottom, 40)116        }117        .linen()118        .navigationTitle("Régions")119        .task { if state.value == nil { await load() } }120    }121122    private func load() async {123        if let s = await Loadable.from({ try await APIClient.shared.regions() }) { state = s }124    }125}126127/// Page d'une région ou d'une ville.128struct PlaceView: View {129    enum Kind { case region, city }130    let slug: String131    let kind: Kind132133    @Environment(AppModel.self) private var model134    @State private var state: Loadable<Place> = .loading135136    var body: some View {137        ScrollView {138            VStack(alignment: .leading, spacing: 0) {139                switch state {140                case .loading: LoadingSign(label: "Chargement").pageColumn()141                case .failed(let e): ErrorState(error: e) { Task { await load() } }.pageColumn()142                case .loaded(let p, let stale):143                    if stale { StaleBanner().pageColumn().padding(.bottom, 12) }144                    content(p)145                }146            }147            .padding(.top, 10).padding(.bottom, 44)148        }149        .linen()150        .navigationTitle(state.value?.name ?? "")151        .navigationBarTitleDisplayMode(.inline)152        .task { if state.value == nil { await load() } }153    }154155    private func load() async {156        let s = kind == .region157            ? await Loadable.from({ try await APIClient.shared.region(slug) })158            : await Loadable.from({ try await APIClient.shared.city(slug) })159        if let s { state = s }160    }161162    private func filters(_ p: Place) -> SearchFilters {163        var f = SearchFilters()164        if kind == .region { f.region = p.slug; f.regionName = p.name } else { f.city = p.slug; f.cityName = p.name }165        return f166    }167168    @ViewBuilder169    private func content(_ p: Place) -> some View {170        VStack(alignment: .leading, spacing: 0) {171            HangingSign(metrics: .page) {172                Plaque(radius: 8, padding: EdgeInsets(top: 16, leading: 20, bottom: 18, trailing: 18)) { tone in173                    PlaqueText(tone: tone, eyebrow: kind == .region ? "Région" : (p.region.map { "Lieu · \($0)" } ?? "Lieu"), name: p.name,174                               line: p.countLine, nameSize: 30)175                }176            }177            .padding(.leading, -6)178            .accessibilityElement(children: .ignore)179            .accessibilityLabel("\(p.name), \(p.countLine)")180            .accessibilityAddTraits(.isHeader)181            if kind == .city {182                HonestNote(text: "Un « lieu » est le nom du secteur postal de la boutique : un quartier, une ville ou le village-centre d'une zone rurale.")183                    .padding(.top, 16)184            }185            Button("Voir les \(Fmt.products(p.products))") { model.openSearch(filters(p)) }186                .buttonStyle(PrimaryButtonStyle()).num().frame(maxWidth: 380).padding(.top, 20)187                .disabled(p.products == 0)188                .accessibilityIdentifier("place-products")189        }190        .pageColumn()191192        if !p.latest.isEmpty {193            VStack(alignment: .leading, spacing: 14) {194                SectionHeader("Vus récemment pour la première fois", note: "Un produit par boutique.").pageColumn()195                ProductStrip(products: p.latest)196                    .frame(maxWidth: Theme.readable + 2 * Theme.margin).frame(maxWidth: .infinity)197            }198            .padding(.top, 34)199        }200201        VStack(alignment: .leading, spacing: 0) {202            if !p.categories.isEmpty {203                SectionHeader("Ce qu'on y trouve le plus", note: "Part des produits du lieu ; le chiffre dit sur combien de boutiques il repose.")204                    .padding(.top, 34).padding(.bottom, 4)205                ForEach(p.categories.prefix(6)) { c in206                    NavRow(icon: CategoryIcon.name(for: c.key), title: c.label, detail: strength(c)) {207                        var f = filters(p)208                        f.category = c.key; f.categoryName = c.label209                        model.openSearch(f)210                    }211                }212            }213            if !p.topStores.isEmpty {214                SectionHeader(kind == .region ? "Ses plus grands catalogues" : "Ses boutiques").padding(.top, 34).padding(.bottom, 18)215                SignGrid(items: Array(p.topStores.prefix(8))) { StoreCard(store: $0) }216            }217            if !p.points.isEmpty {218                SectionHeader("Sur la carte", note: Fmt.stores(p.points.count) + " positionnées, au centre de leur secteur postal.")219                    .padding(.top, 34).padding(.bottom, 12)220                StoresMap(points: p.points, height: 320)221                    .clipShape(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous))222                    .overlay(RoundedRectangle(cornerRadius: Theme.radius, style: .continuous).strokeBorder(Theme.line2, lineWidth: 1))223            }224            let cities = kind == .region ? p.cities : p.nearbyCities225            if !cities.isEmpty {226                SectionHeader(kind == .region ? "Ses lieux" : "Lieux voisins").padding(.top, 34).padding(.bottom, 8)227                FlowLayout(spacing: 8) {228                    ForEach(cities.prefix(30)) { c in229                        Chip(label: c.name, count: c.stores) { model.open(.city(c.slug)) }230                    }231                }232            }233        }234        .pageColumn()235    }236237    private func strength(_ c: FacetItem) -> String {238        var parts = [Fmt.products(c.n)]239        if let s = c.stores { parts.append(Fmt.stores(s)) }240        if let share = c.sharePct { parts.append(Fmt.pct(share, digits: share < 10 ? 1 : 0) + " du lieu") }241        if let v = c.vsQuebec, v >= 1.5 { parts.append("\(Fmt.number(v)) fois plus présent qu'ailleurs") }242        return parts.joined(separator: " · ")243    }244}245
Files main
Menu

Theme