Repository Public
1//2// Food-Ka iOS v23// File: FoodKa/Design/Shelf/ShelfParts.swift4// Description: les pièces nées du symbole — la tablette (le filet sur lequel repose toute photo), la petite5// étiquette des rails, les étiquettes de verdict et de baisse, la ligne et la carte de produit.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import SwiftUI1213/// La tablette : un filet à bouts ronds, de la couleur du texte.14struct ShelfBar: View {15 var thickness: CGFloat = 316 var color: Color = Theme.shelf17 var body: some View {18 Capsule().fill(color).frame(height: thickness).accessibilityHidden(true)19 }20}2122/// Petite étiquette de rail : pleine = la moins chère ; papier bordé = les autres ; pointillé et tiret = absent.23struct SmallTag: View {24 enum Kind { case full, paper, absent }25 let text: String26 var kind: Kind = .paper27 /// opacité de la couche pleine (la dernière arrivée devient pleine)28 var fullOpacity: Double = 129 var width: CGFloat = 7030 var height: CGFloat = 283132 var body: some View {33 let shape = RoundedRectangle(cornerRadius: Theme.radiusTag, style: .continuous)34 ZStack {35 switch kind {36 case .absent:37 shape.strokeBorder(Theme.line2, style: StrokeStyle(lineWidth: 1, dash: [4, 3]))38 Text("—").foregroundStyle(Theme.ink3)39 case .paper:40 shape.fill(Theme.tagPaper)41 shape.strokeBorder(Theme.line2, lineWidth: 1)42 Text(text).foregroundStyle(Theme.ink)43 case .full:44 shape.fill(Theme.tagPaper)45 shape.strokeBorder(Theme.line2, lineWidth: 1)46 Text(text).foregroundStyle(Theme.ink)47 shape.fill(Theme.tag).opacity(fullOpacity)48 Text(text).foregroundStyle(Theme.tagInk).opacity(fullOpacity)49 }50 }51 .font(.system(size: min(Font.scaled(14), 24), weight: .semibold)).monospacedDigit()52 .lineLimit(1).minimumScaleFactor(0.7)53 .frame(width: width, height: height)54 }55}5657/// Étiquette de verdict : icône de position + libellé du serveur + écart signé. Jamais la couleur seule.58struct VerdictBadge: View {59 let position: VerdictPosition60 /// libellé du serveur (`verdict_label`) ; à défaut, celui que publie `/api/version`61 var label: String?62 var scorePct: Double?63 var compact = false6465 private var code: VerdictPosition { position }6667 var body: some View {68 HStack(spacing: 6) {69 Image(Theme.icon(for: code)).resizable().scaledToFit().frame(width: 15, height: 15)70 Text(text).lineLimit(compact ? 1 : 2).fixedSize(horizontal: false, vertical: true)71 }72 .font(.caption.weight(.semibold)).monospacedDigit()73 .foregroundStyle(Theme.color(for: code))74 .padding(.horizontal, 8).padding(.vertical, 5)75 .background(Theme.softColor(for: code), in: RoundedRectangle(cornerRadius: Theme.radiusTag, style: .continuous))76 .accessibilityElement(children: .ignore)77 .accessibilityLabel(text)78 }7980 private var text: String {81 var t = label ?? ServiceInfo.positionLabel(position)82 if let s = scorePct { t += " · " + Fmt.pct(s) }83 return t84 }85}8687/// Étiquette de baisse : le statut vient du serveur. Seule « vérifiée » porte la faïence ; les autres disent88/// ce qu'elles sont (annoncé sans recul, prix inchangé, prix régulier gonflé).89struct DealBadge: View {90 let deal: Deal91 var long = false9293 var body: some View {94 if let status = deal.status {95 HStack(spacing: 6) {96 Image(status == .verifiee ? "ic-solde-verifie" : "ic-verdict-habituel").resizable().scaledToFit().frame(width: 15, height: 15)97 Text(DealBadge.text(deal, long: long)).lineLimit(long ? 3 : 1).fixedSize(horizontal: false, vertical: true)98 }99 .font(.caption.weight(.semibold)).monospacedDigit()100 .foregroundStyle(fg(status))101 .padding(.horizontal, 8).padding(.vertical, 5)102 .background(bg(status), in: RoundedRectangle(cornerRadius: Theme.radiusTag, style: .continuous))103 .accessibilityElement(children: .ignore)104 .accessibilityLabel(DealBadge.text(deal, long: true))105 }106 }107108 private func fg(_ s: Deal.Status) -> Color {109 switch s {110 case .verifiee: Theme.good111 case .gonflee, .habituelle: Theme.high112 case .declaree, .circulaire: Theme.fair113 }114 }115116 private func bg(_ s: Deal.Status) -> Color {117 switch s {118 case .verifiee: Theme.goodSoft119 case .gonflee, .habituelle: Theme.highSoft120 case .declaree, .circulaire: Theme.fairSoft121 }122 }123124 static func text(_ deal: Deal, long: Bool) -> String {125 switch deal.status {126 case .verifiee:127 // une baisse vérifiée de 60 % et plus est une liquidation : le service le dit, l'app la nomme ainsi128 var t = deal.clearance ? "Liquidation" : "Baisse vérifiée"129 if let d = deal.dropPct { t += " · " + Fmt.pct(-d) }130 if long, let s = deal.since { t += " depuis le " + Fmt.dayMonth(s) }131 return t132 case .declaree: return long ? "Solde annoncé, pas encore vérifiable" : "Solde annoncé"133 case .gonflee: return long ? "Prix régulier annoncé plus haut que le prix observé : pas une baisse" : "Pas une baisse réelle"134 case .habituelle: return "Solde affiché, prix inchangé"135 case .circulaire: return long ? "En circulaire, sans prix de référence" : "En circulaire"136 case nil: return ""137 }138 }139}140141/// Mini-rail : un trait par enseigne, placé selon son prix ; le plein est la moins chère, le trait à l'encre est142/// l'enseigne de la carte.143struct MiniRail: View {144 let compare: CompareInfo145 var width: CGFloat = 64146147 var body: some View {148 let prices = compare.prices149 let lo = prices.first?.price ?? 0, hi = prices.last?.price ?? 0150 ZStack(alignment: .bottomLeading) {151 Rectangle().fill(Theme.line2).frame(width: width, height: 1).offset(y: -9)152 if prices.count > 1 {153 ForEach(Array(prices.enumerated()), id: \.offset) { i, p in154 let f = RailMath.fraction(price: p.price, min: lo, max: hi)155 RoundedRectangle(cornerRadius: 1)156 .fill(i == 0 ? Theme.tag : (p.current == true ? Theme.ink : Theme.line2))157 .frame(width: i == 0 ? 7 : 4, height: i == 0 ? 8 : 6)158 .offset(x: (width - 7) * f)159 }160 } else {161 // réponse sans le détail des prix : un trait par enseigne, sans position162 ForEach(0..<min(compare.stores, 6), id: \.self) { i in163 RoundedRectangle(cornerRadius: 1).fill(i == 0 ? Theme.tag : Theme.line2)164 .frame(width: i == 0 ? 7 : 4, height: i == 0 ? 8 : 6)165 .offset(x: CGFloat(i) * 10)166 }167 }168 }169 .frame(width: width, height: 10, alignment: .bottomLeading)170 .accessibilityHidden(true)171 }172}173174/// Boîte à rectangle : la position de la vignette est lue au toucher, sans invalider la vue pendant le défilement.175@MainActor176final class FrameBox {177 var rect: CGRect = .zero178}179180extension View {181 func sourceFrame(_ box: FrameBox) -> some View {182 onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { box.rect = $0 }183 }184}185186/// Ajout à la liste en un geste, depuis partout.187struct AddToListButton: View {188 let product: Product189 var size: CGFloat = 36190 @Environment(GroceryList.self) private var list191 @Environment(AppModel.self) private var model192193 var body: some View {194 let item = list.item(for: product.id)195 Button {196 if list.add(product) {197 Haptics.soft()198 model.showToast(item == nil ? "Ajouté à la liste" : "Quantité : \(Fmt.quantity((item?.quantity ?? 0) + 1))")199 } else {200 Haptics.warning()201 model.showToast("La liste est pleine (\(GroceryList.maxItems) articles)")202 }203 } label: {204 ZStack {205 RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous)206 .fill(item == nil ? Theme.surface : Theme.brandSoft)207 RoundedRectangle(cornerRadius: Theme.radiusSmall, style: .continuous)208 .strokeBorder(item == nil ? Theme.line2 : Theme.brand.opacity(0.4), lineWidth: 1)209 if let item {210 Text(Fmt.quantity(item.quantity)).font(.footnote.weight(.bold)).monospacedDigit().foregroundStyle(Theme.brandStrong)211 } else {212 Image(systemName: "plus").font(.system(size: 15, weight: .semibold)).foregroundStyle(Theme.brand)213 }214 }215 .frame(width: size, height: size)216 .frame(minWidth: 44, minHeight: 44)217 .contentShape(Rectangle())218 }219 .buttonStyle(.plain)220 .accessibilityLabel(item == nil ? "Ajouter \(product.name) à la liste" : "\(product.name) : \(Fmt.quantity(item?.quantity ?? 1)) dans la liste. Ajouter un autre")221 .accessibilityIdentifier("add-\(product.id)")222 }223}224225/// Ligne de produit dense : vignette sur sa petite tablette, nom, marque et format, enseigne, prix et prix226/// unitaire alignés à droite (la forme du symbole), ajout à la liste.227struct ProductRow: View {228 let product: Product229 var trigger: ShelfTrigger = .card230 /// ligne complémentaire (écart, ancien prix, similarité) à la place de l'enseigne231 var note: String?232 var showAdd = true233 var showStore = true234 @Environment(AppModel.self) private var model235 @Environment(\.dynamicTypeSize) private var typeSize236 @State private var box = FrameBox()237238 var body: some View {239 HStack(alignment: .top, spacing: 12) {240 Button { model.openProduct(product, from: box.rect, trigger: trigger) } label: {241 HStack(alignment: .top, spacing: 12) {242 thumb243 if typeSize.isAccessibilitySize {244 VStack(alignment: .leading, spacing: 4) { texts; prices(.leading); badge }245 } else {246 // l'étiquette de baisse ou de verdict court sous le nom et le prix, sur toute la largeur247 VStack(alignment: .leading, spacing: 5) {248 HStack(alignment: .top, spacing: 8) {249 texts250 Spacer(minLength: 4)251 prices(.trailing)252 }253 badge254 }255 }256 }257 .frame(maxWidth: .infinity, alignment: .leading)258 .contentShape(Rectangle())259 }260 .buttonStyle(.plain)261 .accessibilityElement(children: .ignore)262 .accessibilityLabel(a11y)263 .accessibilityAddTraits(.isButton)264 .accessibilityIdentifier("product-\(product.id)")265 if showAdd { AddToListButton(product: product).padding(.top, 2) }266 }267 .padding(.vertical, 10)268 }269270 private var thumb: some View {271 VStack(spacing: 0) {272 ProductPhoto(source: product.image, maxPixel: 160, icon: Category.icon(name: product.category), flyer: product.isFlyer)273 .frame(width: 56, height: 52)274 .sourceFrame(box)275 ShelfBar(thickness: 2.5).frame(width: 60)276 }277 }278279 private var texts: some View {280 VStack(alignment: .leading, spacing: 3) {281 Text(product.name).font(.editorial(16)).foregroundStyle(Theme.ink)282 .lineLimit(typeSize.isAccessibilitySize ? 4 : 2).multilineTextAlignment(.leading)283 if let s = product.brandAndSize {284 Text(s).font(.caption).foregroundStyle(Theme.ink3).lineLimit(1)285 }286 if let note {287 Text(note).font(.caption).monospacedDigit().foregroundStyle(Theme.ink2).lineLimit(3).multilineTextAlignment(.leading)288 } else if showStore {289 HStack(spacing: 6) {290 Text(storeLine).font(.caption).foregroundStyle(Theme.ink2).lineLimit(1)291 if let c = product.compare, c.stores > 1 { MiniRail(compare: c) }292 }293 }294 }295 }296297 @ViewBuilder private var badge: some View {298 if let d = product.deal, d.status == .verifiee {299 DealBadge(deal: d)300 } else if let v = product.verdictPosition, v != .dans {301 // « à son prix habituel » n'est pas un signal : il n'est pas affiché dans les listes302 VerdictBadge(position: v, label: product.verdictLabel, compact: true)303 } else if !product.comparable {304 Text(ServiceInfo.scopeLabel(product.priceScopeCode) ?? "Prix relevé hors Québec")305 .font(.caption.weight(.semibold)).foregroundStyle(Theme.high)306 .padding(.horizontal, 8).padding(.vertical, 5)307 .background(Theme.highSoft, in: RoundedRectangle(cornerRadius: Theme.radiusTag, style: .continuous))308 }309 }310311 private func prices(_ alignment: HorizontalAlignment) -> some View {312 VStack(alignment: alignment, spacing: 2) {313 Text(Fmt.price(product.price)).font(.display(17)).monospacedDigit().foregroundStyle(Theme.ink)314 if let u = product.unitPrice {315 Text(u.label).font(.caption).monospacedDigit().foregroundStyle(Theme.ink2)316 } else if product.byWeight {317 Text("au poids").font(.caption).foregroundStyle(Theme.ink3)318 }319 if product.isFlyer {320 Text("circulaire").font(.caption2).foregroundStyle(Theme.ink3)321 }322 if product.inStock == false {323 Text("rupture").font(.caption2.weight(.medium)).foregroundStyle(Theme.high)324 }325 }326 .fixedSize(horizontal: true, vertical: false)327 }328329 private var storeLine: String {330 if let c = product.compare, c.stores > 1 { return "\(product.storeName) · \(c.stores) enseignes" }331 return product.storeName332 }333334 private var a11y: String {335 var parts = [product.name]336 if let s = product.brandAndSize { parts.append(s) }337 parts.append(Fmt.price(product.price) + " chez " + product.storeName)338 if let u = product.unitPrice { parts.append(u.label) }339 if product.isFlyer { parts.append("prix de circulaire") }340 if let c = product.compare, c.stores > 1 { parts.append(c.isBest ? "le moins cher de \(c.stores) enseignes" : "suivi dans \(c.stores) enseignes") }341 if let d = product.deal, d.status == .verifiee { parts.append(DealBadge.text(d, long: false)) }342 if let note { parts.append(note) }343 return parts.joined(separator: ", ")344 }345}346347/// Carte de produit : la photo repose sur la tablette, l'étiquette est dessous (prix, prix unitaire à droite).348struct ProductTile: View {349 let product: Product350 var width: CGFloat = 156351 var trigger: ShelfTrigger = .card352 @Environment(AppModel.self) private var model353 @State private var box = FrameBox()354355 var body: some View {356 VStack(alignment: .leading, spacing: 0) {357 Button { model.openProduct(product, from: box.rect, trigger: trigger) } label: {358 VStack(alignment: .leading, spacing: 0) {359 ProductPhoto(source: product.image, maxPixel: 320, icon: Category.icon(name: product.category), flyer: product.isFlyer)360 .frame(height: 112)361 .frame(maxWidth: .infinity)362 .padding(.horizontal, 14)363 .sourceFrame(box)364 ShelfBar(thickness: 3)365 VStack(alignment: .leading, spacing: 3) {366 HStack(alignment: .firstTextBaseline, spacing: 4) {367 Text(Fmt.price(product.price)).font(.display(18)).monospacedDigit().foregroundStyle(Theme.ink)368 Spacer(minLength: 2)369 if let u = product.unitPrice {370 Text(u.label).font(.caption2).monospacedDigit().foregroundStyle(Theme.ink2).lineLimit(1).minimumScaleFactor(0.8)371 }372 }373 Text(product.name).font(.editorial(15)).foregroundStyle(Theme.ink).lineLimit(2).multilineTextAlignment(.leading)374 .frame(minHeight: 38, alignment: .topLeading)375 Text(product.brandAndSize ?? " ").font(.caption).foregroundStyle(Theme.ink3).lineLimit(1)376 Text(product.storeName).font(.caption).foregroundStyle(Theme.ink2).lineLimit(1)377 }378 .padding(.top, 8)379 }380 .contentShape(Rectangle())381 }382 .buttonStyle(.plain)383 .accessibilityElement(children: .ignore)384 .accessibilityLabel(a11y)385 .accessibilityAddTraits(.isButton)386 .accessibilityIdentifier("tile-\(product.id)")387 HStack(alignment: .center, spacing: 4) {388 if let d = product.deal, d.status == .verifiee, let pct = d.dropPct {389 HStack(spacing: 4) {390 Image("ic-baisse-prix").resizable().scaledToFit().frame(width: 14, height: 14)391 Text(Fmt.pct(-pct)).font(.caption.weight(.semibold)).monospacedDigit()392 }393 .foregroundStyle(Theme.good)394 .accessibilityElement(children: .ignore)395 .accessibilityLabel("Baisse vérifiée de \(Fmt.pct(pct, signed: false))")396 }397 Spacer(minLength: 0)398 AddToListButton(product: product, size: 32)399 }400 .padding(.top, 2)401 }402 .frame(width: width, alignment: .leading)403 }404405 private var a11y: String {406 var parts = [product.name]407 if let s = product.brandAndSize { parts.append(s) }408 parts.append(Fmt.price(product.price) + " chez " + product.storeName)409 if let u = product.unitPrice { parts.append(u.label) }410 return parts.joined(separator: ", ")411 }412}413414/// Rangée horizontale de cartes de produit.415struct ProductShelfRow: View {416 let products: [Product]417 var trigger: ShelfTrigger = .card418419 var body: some View {420 ScrollView(.horizontal, showsIndicators: false) {421 LazyHStack(alignment: .top, spacing: 14) {422 ForEach(products) { p in ProductTile(product: p, trigger: trigger) }423 }424 .padding(.horizontal, Theme.margin)425 }426 .scrollClipDisabled()427 }428}429