SPB Git

Repository Public

HomeView.swift 11.2 KB 221 lines swift

1// SP Wallet iOS2// File: Features/Dashboard/HomeView.swift3// Description: The dashboard: estimated total with its freshness, quick actions, allocation, operations in progress, main holdings,4//              recent activity, per-network balances. On iPad the same blocks flow into a two-column grid.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import Charts10import SPWalletCore1112struct HomeView: View {13    @Environment(AppModel.self) private var model14    @Environment(Router.self) private var router15    @Environment(\.horizontalSizeClass) private var sizeClass1617    var body: some View {18        ScrollView {19            VStack(spacing: Theme.Space.section) {20                FreshnessBanner()21                if let p = model.portfolio.value {22                    if p.halted == true {23                        Notice(tone: .danger, title: String(localized: "Arrêt d’urgence actif"),24                               message: String(localized: "Le signataire refuse toute opération qui sort des fonds. Seul l’opérateur peut le lever, sur la machine du signataire."), icon: "hand.raised.fill")25                    }26                    BalanceCard(portfolio: p, savedAt: model.portfolio.savedAt, live: model.portfolio.live)27                    QuickActions()28                    let wide = sizeClass == .regular29                    let layout = wide ? AnyLayout(HStackLayout(alignment: .top, spacing: Theme.Space.section)) : AnyLayout(VStackLayout(spacing: Theme.Space.section))30                    layout {31                        VStack(spacing: Theme.Space.section) {32                            if !p.pending.isEmpty { PendingCard(pending: p.pending) }33                            AllocationCard(portfolio: p)34                            HoldingsCard(portfolio: p)35                        }36                        VStack(spacing: Theme.Space.section) {37                            RecentActivityCard()38                            NetworksCard(portfolio: p)39                        }40                    }41                } else if let e = model.portfolio.error {42                    ErrorNotice(error: e) { Task { await model.refreshAll() } }43                } else {44                    ProgressView().padding(.top, 80)45                }46            }47            .padding(.horizontal, Theme.Space.gutter).padding(.bottom, 28)48            .frame(maxWidth: 1100).frame(maxWidth: .infinity)49        }50        .spPage()51        .refreshable { await model.refreshAll() }52        .navigationTitle(AppSection.home.title)53        .toolbar {54            ToolbarItem(placement: .topBarTrailing) {55                AlertBellButton()56            }57        }58    }59}6061private struct QuickActions: View {62    @Environment(AppModel.self) private var model63    @Environment(Router.self) private var router64    var body: some View {65        HStack(spacing: 10) {66            action(String(localized: "Envoyer"), "arrow.up.right", "quick.send", enabled: model.canOperate) { router.sheet = .send(network: nil, asset: nil) }67            action(String(localized: "Recevoir"), "arrow.down.left", "quick.receive", enabled: model.accounts.value != nil) { router.sheet = .receive(network: nil) }68            action(String(localized: "Échanger"), "arrow.left.arrow.right", "quick.swap", enabled: model.canOperate) { router.go(.swap) }69            action(String(localized: "Pont"), "point.topleft.down.to.point.bottomright.curvepath", "quick.bridge", enabled: model.canOperate) { router.go(.bridge) }70        }71    }72    private func action(_ title: String, _ icon: String, _ id: String, enabled: Bool, _ run: @escaping () -> Void) -> some View {73        Button(action: run) {74            VStack(spacing: 7) {75                Image(systemName: icon).font(.system(size: 18, weight: .semibold)).frame(width: 48, height: 48)76                    .foregroundStyle(Theme.onPrimary).background(Theme.primary, in: Circle())77                Text(title).font(.system(size: 12.5, weight: .semibold)).foregroundStyle(Theme.ink)78            }79            .frame(maxWidth: .infinity, minHeight: 78)80        }81        .buttonStyle(.plain).disabled(!enabled).opacity(enabled ? 1 : 0.4)82        .accessibilityIdentifier(id)83    }84}8586private struct PendingCard: View {87    @Environment(AppModel.self) private var model88    let pending: [Proposal]89    var body: some View {90        VStack(alignment: .leading, spacing: 8) {91            SectionHeader(title: String(localized: "En cours"))92            ForEach(pending) { p in93                NavigationLink(value: ProposalRoute(id: p.id)) {94                    HStack(spacing: 10) {95                        if p.state.isInFlight { ProgressView().controlSize(.small) } else { Image(systemName: p.state.symbol).foregroundStyle(p.state.tone.color) }96                        VStack(alignment: .leading, spacing: 1) {97                            Text(Money.brief(p.amountDisplay) + " " + p.symbol + " · " + (p.networkName ?? p.network)).font(.system(size: 15, weight: .semibold)).foregroundStyle(Theme.ink)98                            Text(p.state.label).font(.spFootnote).foregroundStyle(p.state.tone.color)99                        }100                        Spacer()101                        Image(systemName: "chevron.right").font(.system(size: 12, weight: .semibold)).foregroundStyle(Theme.mute)102                    }.frame(minHeight: 48)103                }.buttonStyle(.plain)104            }105        }106        .spCard()107        .navigationDestination(for: ProposalRoute.self) { ProposalDetailView(proposalId: $0.id).wallet(model) }108    }109}110struct ProposalRoute: Hashable { let id: String }111112struct AllocationSlice: Identifiable { let id: String; let value: Double; let share: Double; let color: Color }113114func allocation(_ p: Portfolio, currency: FiatCurrency) -> [AllocationSlice] {115    let holdings = Holding.group(p, currency: currency).compactMap { h in h.value.flatMap { $0 > 0 ? (h.symbol, $0) : nil } }116    let total = holdings.reduce(0) { $0 + $1.1 }117    guard total > 0 else { return [] }118    var slices = holdings.prefix(5).enumerated().map { i, h in AllocationSlice(id: h.0, value: h.1, share: h.1 / total, color: Theme.series[i]) }119    let rest = holdings.dropFirst(5).reduce(0) { $0 + $1.1 }120    if rest > 0 { slices.append(AllocationSlice(id: String(localized: "Autres"), value: rest, share: rest / total, color: Theme.seriesOther)) }121    return slices122}123124private struct AllocationCard: View {125    @Environment(AppModel.self) private var model126    let portfolio: Portfolio127    var body: some View {128        let slices = allocation(portfolio, currency: model.currency)129        if !slices.isEmpty {130            VStack(alignment: .leading, spacing: 12) {131                SectionHeader(title: String(localized: "Répartition"))132                Chart(slices) { s in133                    BarMark(x: .value("part", s.share)).foregroundStyle(s.color).cornerRadius(3)134                }135                .chartXScale(domain: 0...1).chartXAxis(.hidden).chartLegend(.hidden).frame(height: 14)136                .clipShape(Capsule()).accessibilityHidden(true)137                // every part is named with its share in text: colour is never the only carrier138                ForEach(slices) { s in139                    HStack(spacing: 8) {140                        Circle().fill(s.color).frame(width: 9, height: 9)141                        Text(s.id).font(.spCallout.weight(.medium)).foregroundStyle(Theme.ink)142                        Spacer()143                        Text(s.share.formatted(.percent.precision(.fractionLength(1)))).font(.spCallout).monospacedDigit().foregroundStyle(Theme.mute)144                    }145                }146            }.spCard()147        }148    }149}150151private struct HoldingsCard: View {152    @Environment(AppModel.self) private var model153    @Environment(Router.self) private var router154    let portfolio: Portfolio155    var body: some View {156        let held = Holding.group(portfolio, currency: model.currency).filter(\.isHeld)157        VStack(alignment: .leading, spacing: 6) {158            SectionHeader(title: String(localized: "Actifs"), action: (String(localized: "Tout voir"), { router.go(.portfolio) }))159            if held.isEmpty {160                EmptyState(icon: "tray", title: String(localized: "Aucun actif détenu"), message: String(localized: "Reçois des fonds sur l’une de tes adresses pour commencer."))161            } else {162                ForEach(held.prefix(6)) { h in163                    Button { router.pendingAsset = h.symbol; router.go(.portfolio) } label: { AssetRow(holding: h, price: portfolio.prices?[h.symbol]) }.buttonStyle(.plain)164                    if h.id != held.prefix(6).last?.id { Divider() }165                }166            }167        }.spCard()168    }169}170171private struct RecentActivityCard: View {172    @Environment(AppModel.self) private var model173    @Environment(Router.self) private var router174    var body: some View {175        let items = (model.activity.value ?? []).prefix(5)176        VStack(alignment: .leading, spacing: 6) {177            SectionHeader(title: String(localized: "Activité récente"), action: (String(localized: "Tout voir"), { router.go(.activity) }))178            if items.isEmpty { EmptyState(icon: "clock", title: String(localized: "Aucune transaction")) }179            else {180                ForEach(items) { i in181                    NavigationLink(value: i) { TransactionRow(item: i) }.buttonStyle(.plain)182                    if i.id != items.last?.id { Divider() }183                }184            }185        }186        .spCard()187        .navigationDestination(for: ActivityItem.self) { ActivityDetailView(item: $0).wallet(model) }188    }189}190191private struct NetworksCard: View {192    @Environment(AppModel.self) private var model193    let portfolio: Portfolio194    var body: some View {195        let byNet = Dictionary(grouping: portfolio.balances, by: \.network)196        let rows: [(Network, Double?, Bool)] = (model.networks.value ?? []).compactMap { n in197            guard let bs = byNet[n.id] else { return nil }198            let failed = bs.contains { !$0.isAvailable }199            let vals = bs.compactMap { portfolio.estimatedValue(of: $0, in: model.currency) }200            let held = bs.contains { $0.isNonZero }201            guard held || failed else { return nil }202            return (n, vals.isEmpty ? nil : vals.reduce(0, +), failed)203        }204        if !rows.isEmpty {205            VStack(alignment: .leading, spacing: 6) {206                SectionHeader(title: String(localized: "Par réseau"))207                ForEach(rows, id: \.0.id) { n, v, failed in208                    HStack(spacing: 10) {209                        NetworkIcon(network: n.id, size: 30)210                        Text(n.name).font(.system(size: 15, weight: .medium)).foregroundStyle(Theme.ink)211                        if n.health?.ok == false { Image(systemName: "exclamationmark.triangle.fill").font(.system(size: 12)).foregroundStyle(Theme.warn).accessibilityLabel(String(localized: "RPC en panne")) }212                        Spacer()213                        if failed { Text(String(localized: "lecture indisponible")).font(.spFootnote).foregroundStyle(Theme.warn) }214                        else if let v { Masked(text: Money.fiat(v, model.currency)).font(.system(size: 15, weight: .semibold)).monospacedDigit().foregroundStyle(Theme.ink) }215                    }.frame(minHeight: 44)216                }217            }.spCard()218        }219    }220}221
Files main
Menu

Theme