SPB Git

Repository Public

Rows.swift 10.9 KB 208 lines swift

1// SP Wallet iOS2// File: Components/Rows.swift3// Description: List rows and cards shared by the wallet screens: the balance hero, asset rows, transaction rows, network picker.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import SwiftUI8import SPWalletCore910/** Masks figures when the owner chose to hide balances. */11struct Masked: View {12    let text: String13    @Environment(AppModel.self) private var model14    var body: some View { Text(model.hideBalances ? "••••••" : text).accessibilityLabel(model.hideBalances ? String(localized: "Montant masqué") : text) }15}1617struct BalanceCard: View {18    @Environment(AppModel.self) private var model19    let portfolio: Portfolio20    let savedAt: Date?21    let live: Bool2223    var body: some View {24        let total = portfolio.estimatedTotal(in: model.currency)25        let change = weightedChange26        VStack(alignment: .leading, spacing: 10) {27            HStack {28                Text(String(localized: "Valeur estimée")).font(.spFootnote.weight(.semibold)).foregroundStyle(.white.opacity(0.7))29                Spacer()30                SecurityIndicatorOnDark(reachable: portfolio.signer?.reachable, halted: portfolio.halted)31            }32            Masked(text: Money.fiat(total.value, model.currency))33                .font(.spDisplay).tracking(-1.4).foregroundStyle(.white).minimumScaleFactor(0.5).lineLimit(1)34                .accessibilityIdentifier("home.total")35            HStack(spacing: 8) {36                if let c = Money.change(change), !model.hideBalances {37                    Text(c + " · 24 h").font(.spCallout.weight(.semibold)).foregroundStyle((change ?? 0) >= 0 ? Color(hex: 0x35e7ac) : Color(hex: 0xff7d88))38                }39                if !total.complete { Text(String(localized: "partiel : un solde ou un prix manque")).font(.spFootnote).foregroundStyle(Color(hex: 0xf4b65b)) }40            }41            Text(freshness).font(.system(size: 12)).foregroundStyle(.white.opacity(0.6))42        }43        .padding(22)44        .frame(maxWidth: .infinity, alignment: .leading)45        .background {46            ZStack {47                Theme.heroBase48                Circle().fill(Color(hex: (change ?? 0) >= 0 ? 0x35e7ac : 0xff7d88).opacity(0.28)).frame(width: 240).blur(radius: 70).offset(x: 110, y: -70)49                Circle().fill(Color(hex: 0x4d83ff).opacity(0.32)).frame(width: 220).blur(radius: 70).offset(x: -120, y: 80)50            }51        }52        .clipShape(RoundedRectangle(cornerRadius: Theme.Radius.hero, style: .continuous))53        .accessibilityElement(children: .combine)54    }5556    private var freshness: String {57        let src = portfolio.priceSource.map { " · " + String(localized: "prix : \($0)") } ?? ""58        guard let savedAt else { return String(localized: "Estimation") + src }59        return (live ? String(localized: "Mis à jour \(Money.age(savedAt))") : String(localized: "Instantané du \(savedAt.formatted(date: .abbreviated, time: .shortened))")) + src60    }6162    private var weightedChange: Double? {63        var total = 0.0, acc = 0.064        for b in portfolio.balances {65            guard let v = portfolio.estimatedValue(of: b, in: model.currency), v > 0, let c = portfolio.prices?[b.symbol]?.change24h else { continue }66            total += v; acc += v * c67        }68        return total > 0 ? acc / total : nil69    }70}7172private struct SecurityIndicatorOnDark: View {73    let reachable: Bool?; let halted: Bool?74    var body: some View {75        let (t, s, c): (String, String, UInt32) = halted == true ? (String(localized: "Arrêt d’urgence"), "hand.raised.fill", 0xff7d88)76            : reachable == false ? (String(localized: "Signataire injoignable"), "bolt.horizontal.circle", 0xf4b65b)77            : reachable == true ? (String(localized: "Signataire isolé"), "lock.shield.fill", 0x35e7ac) : (String(localized: "Signataire : inconnu"), "questionmark.circle", 0x98a2b6)78        Label(t, systemImage: s).font(.system(size: 11.5, weight: .semibold)).foregroundStyle(Color(hex: c))79            .padding(.horizontal, 9).padding(.vertical, 5).background(.white.opacity(0.10), in: Capsule())80    }81}8283extension Color { init(hex: UInt32) { self.init(uiColor: UIColor(hex: hex)) } }8485/** One holding, possibly aggregated over several networks. */86struct Holding: Identifiable, Hashable {87    let symbol: String88    let name: String89    var balances: [Balance]90    var value: Double?91    var hasUnavailable: Bool92    var id: String { symbol }9394    static func group(_ p: Portfolio, currency: FiatCurrency) -> [Holding] {95        var map: [String: Holding] = [:]96        for b in p.balances {97            var h = map[b.symbol] ?? Holding(symbol: b.symbol, name: b.name, balances: [], value: nil, hasUnavailable: false)98            h.balances.append(b)99            if !b.isAvailable { h.hasUnavailable = true }100            if let v = p.estimatedValue(of: b, in: currency) { h.value = (h.value ?? 0) + v }101            map[b.symbol] = h102        }103        return map.values.sorted { ($0.value ?? -1, $1.symbol) > ($1.value ?? -1, $0.symbol) }104    }105    var isHeld: Bool { balances.contains { $0.isNonZero } }106    /** Sum of the exact amounts when every network uses the same decimals; otherwise nil (shown per network). */107    var totalDisplay: String? {108        guard let d = balances.first?.decimals, balances.allSatisfy({ $0.decimals == d }) else { return nil }109        var sum = BaseUnits.zero110        for b in balances { if let u = b.units { sum = sum + u } }111        return sum.formatted(decimals: d)112    }113}114115struct AssetRow: View {116    @Environment(AppModel.self) private var model117    let holding: Holding118    let price: MarketPrice?119    var body: some View {120        HStack(spacing: 12) {121            AssetIcon(symbol: holding.symbol, network: holding.balances.count == 1 ? holding.balances[0].network : nil)122            VStack(alignment: .leading, spacing: 2) {123                Text(holding.name).font(.system(size: 15.5, weight: .semibold)).foregroundStyle(Theme.ink).lineLimit(1)124                HStack(spacing: 6) {125                    if let p = price { Text(Money.price(p.value(in: model.currency), model.currency)).font(.spFootnote).foregroundStyle(Theme.mute).lineLimit(1).fixedSize() }126                    if let c = price?.change24h, let t = Money.change(c) { Text(t).font(.spFootnote.weight(.medium)).foregroundStyle(c >= 0 ? Theme.emerald : Theme.danger).lineLimit(1).fixedSize() }127                    if price?.stale == true { Image(systemName: "clock.badge.exclamationmark").font(.system(size: 11)).foregroundStyle(Theme.warn).accessibilityLabel(String(localized: "prix périmé")) }128                }129            }130            Spacer(minLength: 8)131            VStack(alignment: .trailing, spacing: 2) {132                if let v = holding.value { Masked(text: Money.fiat(v, model.currency)).font(.system(size: 15.5, weight: .semibold)).monospacedDigit().foregroundStyle(Theme.ink) }133                else if holding.hasUnavailable { Text(String(localized: "indisponible")).font(.spFootnote).foregroundStyle(Theme.warn) }134                if let t = holding.totalDisplay { Masked(text: Money.brief(t) + " " + holding.symbol).font(.spFootnote).monospacedDigit().foregroundStyle(Theme.mute).lineLimit(1) }135            }136        }137        .frame(minHeight: 60)138        .contentShape(Rectangle())139        .accessibilityElement(children: .combine)140    }141}142143struct TransactionRow: View {144    @Environment(AppModel.self) private var model145    let item: ActivityItem146    private var icon: String {147        switch item.kind { case "receive": "arrow.down.left"; case "swap": "arrow.left.arrow.right"; case "bridge": "point.topleft.down.to.point.bottomright.curvepath"; case "gmx": "chart.line.uptrend.xyaxis"; default: "arrow.up.right" }148    }149    private var title: String {150        switch item.kind {151        case "receive": String(localized: "Reçu")152        case "swap": String(localized: "Échange")153        case "bridge": String(localized: "Transfert entre réseaux")154        case "gmx": String(localized: "Ordre GMX")155        case "send": String(localized: "Envoyé")156        default: item.kind157        }158    }159    var body: some View {160        let (label, tone, symbol) = activityStateLabel(item)161        HStack(spacing: 12) {162            ZStack(alignment: .bottomTrailing) {163                Circle().fill(Theme.elev).frame(width: 40, height: 40).overlay(Image(systemName: icon).font(.system(size: 15, weight: .semibold)).foregroundStyle(Theme.ink))164                NetworkIcon(network: item.network, size: 17).overlay(Circle().strokeBorder(Theme.surface, lineWidth: 1.5)).offset(x: 3, y: 3)165            }166            VStack(alignment: .leading, spacing: 2) {167                Text(title).font(.system(size: 15.5, weight: .semibold)).foregroundStyle(Theme.ink)168                Label(label, systemImage: symbol).font(.system(size: 12.5, weight: .medium)).foregroundStyle(tone.color).lineLimit(2).fixedSize(horizontal: false, vertical: true)169            }170            Spacer(minLength: 8)171            VStack(alignment: .trailing, spacing: 2) {172                Masked(text: (item.isIncoming ? "+" : "−") + Money.brief(item.amountDisplay ?? item.amount) + " " + item.symbol)173                    .font(.system(size: 15, weight: .semibold)).monospacedDigit().foregroundStyle(item.isIncoming && item.isSettled ? Theme.emerald : Theme.ink).lineLimit(1)174                Text(item.at.formatted(date: .abbreviated, time: .shortened)).font(.system(size: 12)).foregroundStyle(Theme.mute).lineLimit(1).fixedSize()175            }176        }177        .frame(minHeight: 58)178        .contentShape(Rectangle())179        .accessibilityElement(children: .combine)180    }181}182183/** Network choice with health and the wallet's own address; never implies that a network supports every feature. */184struct NetworkPicker: View {185    @Environment(AppModel.self) private var model186    @Binding var selection: String?187    var filter: (Network) -> Bool = { _ in true }188    var body: some View {189        ForEach((model.networks.value ?? []).filter(filter)) { n in190            Button { selection = n.id } label: {191                HStack(spacing: 12) {192                    NetworkIcon(network: n.id, size: 34)193                    VStack(alignment: .leading, spacing: 2) {194                        Text(n.name).font(.system(size: 15.5, weight: .semibold)).foregroundStyle(Theme.ink)195                        Text(n.native.symbol + (n.tokens.isEmpty ? "" : " + \(n.tokens.count) " + String(localized: "jetons"))).font(.spFootnote).foregroundStyle(Theme.mute)196                    }197                    Spacer()198                    if n.health?.ok == false { Pill(text: String(localized: "RPC en panne"), tone: .warn, icon: "exclamationmark.triangle.fill") }199                    if selection == n.id { Image(systemName: "checkmark").font(.system(size: 14, weight: .bold)).foregroundStyle(Theme.blue) }200                }201                .frame(minHeight: 52).contentShape(Rectangle())202            }203            .buttonStyle(.plain)204            .accessibilityIdentifier("network.\(n.id)")205        }206    }207}208
Files main
Menu

Theme