SPB Git

Repository Public

PriceRail.swift 8.3 KB 184 lines swift

1//2//  Food-Ka iOS v23//  File: FoodKa/Design/Shelf/PriceRail.swift4//  Description: « le rail des prix » — une tablette par enseigne, de la moins chère à la plus chère ; la position de5//               l'étiquette sur son rail est le prix. Les étiquettes partent ensemble du bout droit ; la moins6//               chère va le plus loin, s'arrête la dernière et devient pleine. Sert à la comparaison entre7//               enseignes et aux totaux du panier.8//9//  Author: Simon-Pierre Boucher10//  Contact: contact@spboucher.ai11//1213import SwiftUI1415struct RailRow: Identifiable, Hashable, Sendable {16    var id: String17    var name: String18    /// sous le nom : prix unitaire, « circulaire », « rég. … », nombre d'articles comptés19    var detail: String?20    var value: Double21    /// précision dite à côté de l'écart (confiance de l'appariement)22    var caption: String?23    /// cette ligne est le produit de la fiche24    var isCurrent = false25}2627struct PriceRail: View, @preconcurrency Animatable {28    let rows: [RailRow]29    /// progression de la variante, de 0 à 130    var progress: Double31    var bestLabel = "le moins cher"32    var onTap: ((RailRow) -> Void)?3334    @Environment(\.dynamicTypeSize) private var typeSize35    @Environment(\.horizontalSizeClass) private var hSize3637    var animatableData: Double {38        get { progress }39        set { progress = newValue }40    }4142    private var sorted: [RailRow] { rows.sorted { ($0.value, $0.name) < ($1.value, $1.name) } }43    private var scale: CGFloat { Font.scaled(14) / 14 }44    private var tagW: CGFloat { min(typeSize.isAccessibilitySize ? 150 : 104, (hSize == .regular ? 86 : 68) * max(1, scale * 0.92)) }45    private var tagH: CGFloat { min(typeSize.isAccessibilitySize ? 48 : 40, 28 * max(1, scale * 0.92)) }46    private var nameW: CGFloat { hSize == .regular ? 190 : 100 }47    private var diffW: CGFloat { hSize == .regular ? 120 : 86 }4849    var body: some View {50        let list = sorted51        let lo = list.first?.value ?? 0, hi = list.last?.value ?? 052        VStack(spacing: 0) {53            ForEach(Array(list.enumerated()), id: \.element.id) { i, row in54                let f = RailMath.fraction(price: row.value, min: lo, max: hi)55                Group {56                    if typeSize.isAccessibilitySize {57                        stacked(row, i, list.count, f, lo)58                    } else {59                        inline(row, i, list.count, f, lo)60                    }61                }62                .contentShape(Rectangle())63                .onTapGesture { onTap?(row) }64                .accessibilityElement(children: .ignore)65                .accessibilityLabel(spoken(row, i, lo))66                .accessibilityAddTraits(onTap != nil && !row.isCurrent ? .isButton : [])67                .accessibilityIdentifier("rail-row-\(i)")68            }69        }70    }7172    // --- Mise en page courante : nom · rail · écart --------------------------------------------------7374    private func inline(_ row: RailRow, _ i: Int, _ n: Int, _ f: Double, _ lo: Double) -> some View {75        HStack(alignment: .center, spacing: 10) {76            names(row).frame(width: nameW, alignment: .leading)77            rail(row, i, n, f)78            diff(row, i, n, lo).frame(width: diffW, alignment: .trailing)79        }80        .frame(minHeight: 54)81    }8283    private func stacked(_ row: RailRow, _ i: Int, _ n: Int, _ f: Double, _ lo: Double) -> some View {84        VStack(alignment: .leading, spacing: 6) {85            names(row)86            rail(row, i, n, f).frame(height: tagH + 14)87            diff(row, i, n, lo)88        }89        .frame(maxWidth: .infinity, alignment: .leading)90        .padding(.vertical, 10)91    }9293    private func names(_ row: RailRow) -> some View {94        VStack(alignment: .leading, spacing: 2) {95            Text(row.name).font(.subheadline.weight(.semibold)).foregroundStyle(Theme.ink).lineLimit(2).minimumScaleFactor(0.85)96            if let d = row.detail {97                Text(d).font(.caption2).monospacedDigit().foregroundStyle(Theme.ink3).lineLimit(2).fixedSize(horizontal: false, vertical: true)98            }99        }100        .opacity(RailMath.names(progress))101    }102103    private func rail(_ row: RailRow, _ i: Int, _ n: Int, _ f: Double) -> some View {104        GeometryReader { geo in105            let span = max(0, geo.size.width - tagW)106            let pos = RailMath.position(fraction: f, progress: progress)107            ZStack(alignment: .topLeading) {108                // la tablette de la ligne109                Rectangle().fill(Theme.line2).frame(height: 2)110                    .scaleEffect(x: RailMath.rail(line: i, progress: progress), y: 1, anchor: .leading)111                // le repère : un pointillé betterave descend de la moins chère à travers les lignes112                if n > 1 {113                    let m = max(0, min(1, RailMath.marker(progress) * Double(n) - Double(i)))114                    Path { p in115                        p.move(to: CGPoint(x: tagW / 2, y: i == 0 ? geo.size.height / 2 : 0))116                        p.addLine(to: CGPoint(x: tagW / 2, y: (i == 0 ? geo.size.height / 2 : 0) + (geo.size.height * (i == 0 ? 0.5 : 1)) * m))117                    }118                    .stroke(Theme.tag.opacity(0.8), style: StrokeStyle(lineWidth: 1, dash: [3, 3]))119                }120                SmallTag(text: Fmt.price(row.value), kind: i == 0 ? .full : .paper, fullOpacity: RailMath.full(progress), width: tagW, height: tagH)121                    .offset(x: span * pos, y: (geo.size.height - tagH) / 2 + 1)122                    .opacity(min(1, progress / 0.08))123            }124        }125        .frame(minHeight: tagH + 12)126    }127128    @ViewBuilder129    private func diff(_ row: RailRow, _ i: Int, _ n: Int, _ lo: Double) -> some View {130        VStack(alignment: typeSize.isAccessibilitySize ? .leading : .trailing, spacing: 1) {131            if i == 0 {132                Text(n > 1 ? bestLabel : "seule offre").font(.caption.weight(.semibold)).foregroundStyle(Theme.brand)133                    .multilineTextAlignment(.trailing).lineLimit(1).minimumScaleFactor(0.75)134            } else {135                Text(Fmt.diff(row.value - lo)).font(.footnote.weight(.medium)).monospacedDigit().foregroundStyle(Theme.ink2)136            }137            if let c = row.caption {138                Text(c).font(.caption2).foregroundStyle(Theme.ink3).multilineTextAlignment(.trailing).lineLimit(2).minimumScaleFactor(0.8)139            }140        }141        .opacity(RailMath.diff(line: i, of: n, progress: progress))142    }143144    private func spoken(_ row: RailRow, _ i: Int, _ lo: Double) -> String {145        var parts = [row.name, Fmt.price(row.value)]146        parts.append(i == 0 ? bestLabel : Fmt.diff(row.value - lo) + " de plus")147        if let d = row.detail { parts.append(d) }148        if let c = row.caption { parts.append(c) }149        if row.isCurrent { parts.append("cette fiche") }150        return parts.joined(separator: ", ")151    }152}153154/// Le rail qui se joue une fois, à son entrée dans la fenêtre.155struct AnimatedPriceRail: View {156    let rows: [RailRow]157    var bestLabel = "le moins cher"158    /// durée de la variante, en secondes (1,6 s seule)159    var duration: Double = 1.6160    /// pas avant cet instant (la comparaison attend sa fenêtre dans le geste de la fiche)161    var notBefore: Date?162    var onTap: ((RailRow) -> Void)?163    let allowed = MotionAllowed()164    @State private var progress: Double = 0165    @State private var played = false166167    var body: some View {168        PriceRail(rows: rows, progress: allowed.value ? progress : 1, bestLabel: bestLabel, onTap: onTap)169            .onScrollVisibilityChange(threshold: 0.25) { visible in170                guard visible, !played else { return }171                played = true172                if UserDefaults.standard.object(forKey: "FKRailP") != nil {173                    // capture d'un instant figé de la glissade174                    progress = UserDefaults.standard.double(forKey: "FKRailP")175                    return176                }177                guard allowed.value, duration > 0 else { progress = 1; return }178                withAnimation(.linear(duration: duration).delay(max(0, notBefore?.timeIntervalSinceNow ?? 0))) { progress = 1 }179            }180            // un changement de liste (article ajouté ou retiré) : les étiquettes glissent à leur nouvelle place181            .animation(played && allowed.value ? .timingCurve(0.3, 0, 0.15, 1, duration: 0.24) : nil, value: rows)182    }183}184
Files main
Menu

Theme