Repository Public
1//2// Food-Ka iOS v23// File: FoodKa/Features/Product/ProductView.swift4// Description: fiche produit, dans l'ordre standard — photo posée sur sa tablette, prix et enseigne sur l'étiquette,5// nom, format et prix unitaire, comparaison entre enseignes (le rail des prix), historique, verdict,6// nutrition et détails, produits équivalents et semblables. Le geste « la mise en tablette » se joue7// à l'ouverture, selon la règle de fréquence.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11//1213import SwiftUI1415struct ProductView: View {16 let id: String17 @Environment(AppModel.self) private var model18 @Environment(Library.self) private var library19 @Environment(GroceryList.self) private var list20 @Environment(MotionCenter.self) private var motion21 @Environment(\.accessibilityReduceMotion) private var reduceMotion22 @Environment(\.dynamicTypeSize) private var typeSize2324 @State private var detail: ProductDetail?25 @State private var failure: APIError?26 @State private var stale = false27 @State private var seed: ShelfSeed?28 @State private var level: ShelfLevel = .none29 @State private var started = false30 /// temps du geste, en ms31 @State private var t: Double = 032 @State private var revealed = false33 @State private var haptics: Task<Void, Never>?34 @State private var safari: IdentifiedURL?35 @State private var openedAt = Date()3637 /// La carte connue : celle de la fiche chargée, sinon celle de la vignette touchée.38 private var card: Product? {39 if let d = detail { return d.card }40 if let s = seed, !s.product.name.isEmpty { return s.product }41 return nil42 }4344 var body: some View {45 ScrollViewReader { proxy in46 ScrollView {47 VStack(alignment: .leading, spacing: 0) {48 if let card {49 if let d = detail, !(d.isPublic && d.active) {50 withdrawn(d)51 } else {52 scene(card)53 .zIndex(1)54 sections(card)55 .opacity(revealed ? 1 : 0)56 .offset(y: revealed ? 0 : 8)57 }58 } else if let failure {59 ErrorState(error: failure) { Task { await load() } }60 } else {61 LoadingShelves(rows: 3)62 }63 }64 .pageColumn()65 .padding(.top, 8)66 .padding(.bottom, 40)67 }68 .onScrollPhaseChange { _, phase in69 if phase == .interacting { finishGesture() }70 }71 .onChange(of: detail?.card.id) { _, _ in72 // ancre demandée au lancement (captures d'une section précise)73 if let a = model.launchAnchor {74 Task { @MainActor in75 try? await Task.sleep(for: .milliseconds(500))76 proxy.scrollTo(a, anchor: .top)77 }78 }79 }80 }81 .paper()82 .navigationBarTitleDisplayMode(.inline)83 .toolbar {84 ToolbarItemGroup(placement: .topBarTrailing) {85 if let card, detail.map({ $0.isPublic && $0.active }) ?? true {86 Button { toggleFollow(card) } label: {87 Image(systemName: library.isFollowed(card.id) ? "heart.fill" : "heart")88 }89 .accessibilityLabel(library.isFollowed(card.id) ? "Ne plus suivre ce produit" : "Suivre ce produit")90 .accessibilityIdentifier("follow-button")91 ShareLink(item: shareURL, subject: Text(card.name), message: Text(shareText(card))) {92 Image(systemName: "square.and.arrow.up")93 }94 .accessibilityLabel("Partager")95 }96 }97 }98 // interruptible : un toucher amène l'état final99 .simultaneousGesture(TapGesture().onEnded { finishGesture() })100 .sheet(item: $safari) { SafariView(url: $0.url).ignoresSafeArea() }101 .task { await start() }102 .onDisappear { haptics?.cancel() }103 }104105 // --- Le geste ---------------------------------------------------------------------------------------106107 private func scene(_ card: Product) -> some View {108 ShelfScene(image: detail?.photo ?? card.image, icon: Category.icon(name: card.category), flyer: card.isFlyer,109 tag: tagContent(card), choreo: level.choreo, source: seed?.source, t: t)110 }111112 private func tagContent(_ card: Product) -> ShelfTagContent {113 if let d = detail {114 let best = d.cheapest115 return ShelfTagContent.make(for: d.card, storesCount: d.offersSummary?.stores ?? (d.offers.count + 1),116 bestStoreName: best.id == d.card.id ? nil : best.storeName)117 }118 return ShelfTagContent.make(for: card)119 }120121 private func start() async {122 guard !started else { return }123 started = true124 seed = motion.consume(id)125 level = motion.level(for: seed?.trigger ?? .direct, reduceMotion: reduceMotion)126 if card != nil { play() }127 await load()128 if detail != nil, !revealed, level == .none || t == 0 { play() }129 }130131 /// Joue le geste depuis le début, ou pose l'état final.132 private func play() {133 guard let c = level.choreo else {134 // sans mouvement : état final d'emblée, fondu de 140 ms135 withAnimation(reduceMotion || motion.preference == .off ? .easeOut(duration: 0.14) : nil) { revealed = true }136 return137 }138 if let frozen = motion.frozenT {139 t = min(frozen, c.total)140 revealed = frozen >= c.title.a141 return142 }143 guard t == 0 else { return }144 withAnimation(.linear(duration: c.total / 1000)) { t = c.total }145 withAnimation(.timingCurve(0.2, 0.7, 0.2, 1, duration: (c.title.b - c.title.a) / 1000).delay(c.title.a / 1000)) { revealed = true }146 haptics = Task { @MainActor in147 // la pose : le produit touche la tablette148 try? await Task.sleep(for: .milliseconds(Int(c.touch)))149 if Task.isCancelled { return }150 Haptics.tap()151 guard c.fullTag else { return }152 // la butée : l'étiquette s'arrête153 try? await Task.sleep(for: .milliseconds(Int(c.stop - c.touch)))154 if Task.isCancelled { return }155 Haptics.select()156 }157 }158159 private func finishGesture() {160 guard let c = level.choreo, motion.frozenT == nil, t > 0, !revealed || haptics != nil else { return }161 haptics?.cancel(); haptics = nil162 var tx = Transaction()163 tx.disablesAnimations = true164 withTransaction(tx) { t = c.total; revealed = true }165 }166167 private func load() async {168 failure = nil169 do {170 let r = try await APIClient.shared.product(id)171 detail = r.value172 stale = r.stale173 if r.value.isPublic && r.value.active { library.visit(r.value.card) }174 } catch is CancellationError {175 } catch {176 failure = (error as? APIError) ?? .offline177 if card != nil { revealed = true }178 }179 }180181 // --- Sections, dans l'ordre standard ------------------------------------------------------------------182183 @ViewBuilder184 private func sections(_ card: Product) -> some View {185 VStack(alignment: .leading, spacing: 0) {186 title(card).padding(.top, 22)187 actions(card).padding(.top, 18)188 if stale { StaleBanner().padding(.top, 16) }189 if let d = detail {190 ComparisonSection(detail: d, level: level, opened: openedAt).padding(.top, 34).id("compare")191 HistorySection(detail: d).padding(.top, 36).id("history")192 DetailsSection(detail: d, safari: $safari).padding(.top, 36).id("details")193 if !d.similar.isEmpty {194 VStack(alignment: .leading, spacing: 6) {195 SectionHeader("Produits semblables", note: "Rapprochés par le nom : marque et format peuvent différer.")196 ForEach(d.similar) { p in197 ProductRow(product: p, trigger: .secondary)198 Hairline()199 }200 }201 .padding(.top, 36).id("similar")202 }203 footer(d).padding(.top, 30)204 } else if let failure {205 ErrorState(error: failure) { Task { await load() } }.padding(.top, 10)206 } else {207 LoadingShelves(rows: 2).padding(.top, 20)208 }209 }210 }211212 private func title(_ card: Product) -> some View {213 VStack(alignment: .leading, spacing: 8) {214 if let c = card.category {215 Text([c, card.subcategory].compactMap { $0 }.joined(separator: " · ")).eyebrowStyle()216 }217 Text(card.name).font(.editorial(26)).foregroundStyle(Theme.ink)218 .fixedSize(horizontal: false, vertical: true)219 .accessibilityAddTraits(.isHeader)220 .accessibilityIdentifier("product-title")221 if let s = formatLine(card) {222 Text(s).font(.subheadline).monospacedDigit().foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)223 }224 FlowLayout(spacing: 8) {225 if let d = detail?.card.deal ?? card.deal { DealBadge(deal: d, long: true) }226 if let v = detail?.verdict, let position = v.position {227 VerdictBadge(position: position, label: v.label, scorePct: v.scorePct)228 } else if detail == nil, let v = card.verdictPosition {229 VerdictBadge(position: v, label: card.verdictLabel)230 }231 if detail?.inStock == false {232 Text("Rupture de stock signalée").font(.caption.weight(.semibold)).foregroundStyle(Theme.high)233 .padding(.horizontal, 8).padding(.vertical, 5)234 .background(Theme.highSoft, in: RoundedRectangle(cornerRadius: Theme.radiusTag, style: .continuous))235 }236 }237 if let v = detail?.validity {238 VStack(alignment: .leading, spacing: 3) {239 if let r = Fmt.range(v.from, v.to) {240 Text("Prix de circulaire, valide \(r)" + (Fmt.remaining(v.to).map { " (\($0))" } ?? "") + ".")241 .font(.footnote).foregroundStyle(Theme.ink2)242 }243 // conditions de l'enseigne, telles quelles (membre, limite, taxes)244 if let f = v.finePrint { Text(f).font(.footnote).foregroundStyle(Theme.ink3) }245 }246 .fixedSize(horizontal: false, vertical: true)247 }248 if let scope = detail?.priceScope, scope.needsWarning, let note = scope.note {249 // prix relevé hors Québec : dit en tête de fiche, avec la note du service telle quelle250 VStack(alignment: .leading, spacing: 4) {251 Text(scope.label ?? "Prix relevé hors Québec").font(.subheadline.weight(.semibold)).foregroundStyle(Theme.high)252 Text(note).font(.footnote).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)253 }254 .padding(12)255 .frame(maxWidth: .infinity, alignment: .leading)256 .background(Theme.highSoft, in: RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous))257 .padding(.top, 4)258 .accessibilityElement(children: .combine)259 .accessibilityIdentifier("price-scope-note")260 }261 if card.byWeight {262 HonestNote(text: "Produit vendu au poids : le prix affiché est une estimation à la pièce, un prix au kilo ou à la livre. Le prix unitaire fait foi.")263 }264 }265 }266267 private func formatLine(_ card: Product) -> String? {268 var parts: [String] = []269 if let b = card.brand {270 parts.append(b + (card.storeBrand ? " (marque maison)" : "") + (detail?.brandInferred == true ? " (marque déduite du nom)" : ""))271 }272 if let s = card.size { parts.append(s) }273 if let u = card.unitPrice { parts.append(u.label + (u.approximate ? " environ" : "")) }274 return parts.isEmpty ? nil : parts.joined(separator: " · ")275 }276277 private func actions(_ card: Product) -> some View {278 let item = list.item(for: card.id)279 let row = typeSize.isAccessibilitySize ? AnyLayout(VStackLayout(spacing: 10)) : AnyLayout(HStackLayout(spacing: 10))280 return VStack(spacing: 10) {281 Button {282 if list.add(card) {283 Haptics.soft()284 model.showToast(item == nil ? "Ajouté à la liste" : "Quantité : \(Fmt.quantity((item?.quantity ?? 0) + 1))")285 } else {286 model.showToast("La liste est pleine (\(GroceryList.maxItems) articles)")287 }288 } label: {289 HStack(spacing: 8) {290 Image("ic-panier").resizable().scaledToFit().frame(width: 20, height: 20)291 Text(item == nil ? "Ajouter à la liste" : "Dans la liste (\(Fmt.quantity(item?.quantity ?? 1))) · en ajouter un")292 }293 }294 .buttonStyle(PrimaryButtonStyle())295 .accessibilityIdentifier("add-to-list")296 row {297 Button { toggleFollow(card) } label: {298 Label(library.isFollowed(card.id) ? "Suivi" : "Suivre", systemImage: library.isFollowed(card.id) ? "heart.fill" : "heart")299 }300 .buttonStyle(SecondaryButtonStyle())301 if let u = detail?.url.flatMap(URL.init(string:)), u.scheme == "https" {302 Button { safari = IdentifiedURL(url: u) } label: {303 Label("Voir chez \(card.storeName)", systemImage: "arrow.up.right").lineLimit(1).minimumScaleFactor(0.8)304 }305 .buttonStyle(SecondaryButtonStyle())306 .accessibilityIdentifier("store-link")307 }308 }309 }310 }311312 private func toggleFollow(_ card: Product) {313 let on = library.toggleFollow(card)314 Haptics.select()315 model.showToast(on ? "Produit suivi : une baisse sera signalée à l'ouverture" : "Produit retiré des suivis")316 }317318 private var shareURL: URL {319 APIClient.site.appending(path: "produit").appending(path: id)320 }321322 private func shareText(_ card: Product) -> String {323 var s = "\(card.name) : \(Fmt.price(card.price)) chez \(card.storeName)"324 if let u = card.unitPrice { s += " (\(u.label))" }325 return s + ", relevé par Food-Ka."326 }327328 private func footer(_ d: ProductDetail) -> some View {329 VStack(alignment: .leading, spacing: 4) {330 Hairline(color: Theme.line2)331 if let seen = d.lastSeen {332 Text("Prix relevé le \(Fmt.date(seen)) sur le site de \(d.card.storeName). Food-Ka constate un prix ; il ne vend rien.")333 .font(.footnote).foregroundStyle(Theme.ink3).fixedSize(horizontal: false, vertical: true).padding(.top, 12)334 }335 HStack(spacing: 18) {336 Button("Méthode") { model.open(.method) }337 if let mail = URL(string: "mailto:contact@spboucher.ai?subject=" + ("Erreur sur la fiche " + d.card.id).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!) {338 Link("Signaler une erreur", destination: mail)339 }340 }341 .font(.footnote.weight(.medium)).foregroundStyle(Theme.brand).frame(minHeight: 44)342 }343 }344345 /// Produit retiré ou non public : dernier prix connu, raison, et une recherche pour le retrouver ailleurs.346 private func withdrawn(_ d: ProductDetail) -> some View {347 VStack(alignment: .leading, spacing: 14) {348 EmptyShelf(title: d.active ? "Ce produit n'est pas publié" : "Ce produit n'est plus offert",349 message: [d.card.name + (d.card.price.map { " : dernier prix relevé, \(Fmt.price($0))" } ?? "") + " chez \(d.card.storeName)" + (d.lastSeen.map { ", le \(Fmt.date($0))." } ?? "."),350 d.reasonLabel.map { "Raison : \($0)." }].compactMap { $0 }.joined(separator: " "),351 actionLabel: "Chercher un produit du même nom") {352 var f = SearchFilters(); f.q = d.card.name353 model.openSearch(f)354 }355 }356 .accessibilityIdentifier("product-withdrawn")357 }358}359