Repository Public
1// SP Wallet iOS2// File: Features/Assets/AssetDetailView.swift3// Description: One asset: price chart (the server's price source, labelled), market figures, the wallet's balance on each network4// with the token contract in full, actions, and this asset's history. Listed tokens are those of the wallet's5// verified registry; a name or a logo is never presented as a proof.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SwiftUI10import Charts11import SPWalletCore1213struct AssetDetailView: View {14 @Environment(AppModel.self) private var model15 @Environment(Router.self) private var router16 let symbol: String17 @State private var days = 718 @State private var chart: MarketChart?19 @State private var chartError: Error?20 @State private var selected: MarketChart.Point?2122 private var balances: [Balance] { (model.portfolio.value?.balances ?? []).filter { $0.symbol == symbol } }23 private var price: MarketPrice? { model.portfolio.value?.prices?[symbol] }2425 var body: some View {26 ScrollView {27 VStack(alignment: .leading, spacing: Theme.Space.section) {28 FreshnessBanner()29 header30 chartCard31 if let m = chart?.market ?? price { marketCard(m) }32 balancesCard33 historyCard34 }35 .padding(.horizontal, Theme.Space.gutter).padding(.bottom, 28)36 .frame(maxWidth: 900).frame(maxWidth: .infinity)37 }38 .spPage()39 .navigationTitle(symbol).navigationBarTitleDisplayMode(.inline)40 .task(id: days) { await loadChart() }41 }4243 private var header: some View {44 HStack(spacing: 14) {45 AssetIcon(symbol: symbol, size: 52)46 VStack(alignment: .leading, spacing: 3) {47 Text(balances.first?.name ?? symbol).font(.spHeadline).foregroundStyle(Theme.ink)48 if let p = selected.map({ $0.p }) ?? price?.value(in: model.currency) {49 Text(Money.price(p, model.currency)).font(.system(size: 30, weight: .semibold)).tracking(-0.6).monospacedDigit().foregroundStyle(Theme.ink)50 }51 if let s = selected { Text(s.date.formatted(date: .abbreviated, time: .shortened)).font(.spFootnote).foregroundStyle(Theme.mute) }52 else if let c = price?.change24h, let t = Money.change(c) { Text(t + " · 24 h").font(.spCallout.weight(.semibold)).foregroundStyle(c >= 0 ? Theme.emerald : Theme.danger) }53 }54 Spacer()55 }56 }5758 private var chartCard: some View {59 VStack(alignment: .leading, spacing: 12) {60 if let c = chart, c.points.count > 1 {61 let lo = c.points.map(\.p).min() ?? 0, hi = c.points.map(\.p).max() ?? 162 let up = (c.points.last?.p ?? 0) >= (c.points.first?.p ?? 0)63 Chart(c.points, id: \.t) { pt in64 LineMark(x: .value("t", pt.date), y: .value("p", pt.p)).foregroundStyle(up ? Theme.emerald : Theme.danger).interpolationMethod(.monotone)65 if let s = selected, s.t == pt.t { RuleMark(x: .value("t", s.date)).foregroundStyle(Theme.mute.opacity(0.5)) ; PointMark(x: .value("t", s.date), y: .value("p", s.p)).foregroundStyle(Theme.ink) }66 }67 .chartYScale(domain: (lo - (hi - lo) * 0.05)...(hi + (hi - lo) * 0.05 + .leastNonzeroMagnitude))68 .chartXAxis { AxisMarks(values: .automatic(desiredCount: 4)) { _ in AxisValueLabel().font(.system(size: 11)) } }69 .chartYAxis { AxisMarks(position: .trailing, values: .automatic(desiredCount: 4)) { _ in AxisGridLine().foregroundStyle(Theme.hairline); AxisValueLabel().font(.system(size: 11)) } }70 .chartOverlay { proxy in71 GeometryReader { geo in72 Rectangle().fill(.clear).contentShape(Rectangle())73 .gesture(DragGesture(minimumDistance: 0).onChanged { v in74 guard let plot = proxy.plotFrame else { return }75 let x = v.location.x - geo[plot].origin.x76 if let d: Date = proxy.value(atX: x) { selected = c.points.min { abs($0.date.timeIntervalSince(d)) < abs($1.date.timeIntervalSince(d)) } }77 }.onEnded { _ in selected = nil })78 }79 }80 .frame(height: 210)81 .accessibilityLabel(String(localized: "Graphique du prix de \(symbol) sur \(days) jours"))82 } else if let chartError { ErrorNotice(error: chartError) }83 else if chart != nil { EmptyState(icon: "chart.xyaxis.line", title: String(localized: "Pas d’historique de prix pour cet actif")) }84 else { ProgressView().frame(maxWidth: .infinity, minHeight: 210) }85 Picker(String(localized: "Période"), selection: $days) {86 Text("24 h").tag(1); Text(String(localized: "7 j")).tag(7); Text(String(localized: "30 j")).tag(30); Text(String(localized: "1 an")).tag(365)87 }.pickerStyle(.segmented)88 Text(String(localized: "Prix observés par la source \(price?.source ?? "CoinGecko"), en \(model.currency.rawValue). Ce n’est pas un prix d’exécution."))89 .font(.system(size: 12)).foregroundStyle(Theme.mute)90 }.spCard()91 }9293 private func marketCard(_ m: MarketPrice) -> some View {94 VStack(alignment: .leading, spacing: 0) {95 SectionHeader(title: String(localized: "Marché")).padding(.bottom, 6)96 if m.stale { Notice(tone: .warn, title: String(localized: "Prix périmé"), message: m.priceAt.map { String(localized: "Dernière mise à jour de la source : \($0.formatted(date: .abbreviated, time: .shortened)).") }) .padding(.bottom, 8) }97 if m.divergent == true { Notice(tone: .warn, title: String(localized: "Les deux sources de prix divergent"), message: String(localized: "Le prix affiché est celui de la source principale ; l’écart avec la seconde dépasse le seuil.")).padding(.bottom, 8) }98 let c = FiatCurrency.usd99 if let v = m.marketCap { FieldRow(label: String(localized: "Capitalisation (USD)"), value: Money.fiat(v, c, compact: true)); Divider() }100 if let v = m.volume24h { FieldRow(label: String(localized: "Volume 24 h (USD)"), value: Money.fiat(v, c, compact: true)); Divider() }101 if let h = m.high24h, let l = m.low24h { FieldRow(label: String(localized: "Haut / bas 24 h (USD)"), value: Money.price(h, c) + " / " + Money.price(l, c)); Divider() }102 if let v = m.change7d, let t = Money.change(v) { FieldRow(label: String(localized: "Variation 7 j"), value: t, tone: v >= 0 ? .ok : .danger); Divider() }103 if let r = m.rank { FieldRow(label: String(localized: "Rang"), value: "#\(r)") }104 }.spCard()105 }106107 private var balancesCard: some View {108 VStack(alignment: .leading, spacing: 4) {109 SectionHeader(title: String(localized: "Tes soldes"))110 if balances.isEmpty { Text(String(localized: "Cet actif n’est pas dans le registre du portefeuille.")).font(.spCallout).foregroundStyle(Theme.mute) }111 ForEach(balances) { b in112 VStack(alignment: .leading, spacing: 8) {113 HStack(spacing: 10) {114 NetworkIcon(network: b.network, size: 30)115 VStack(alignment: .leading, spacing: 1) {116 Text(b.networkName).font(.system(size: 15, weight: .semibold)).foregroundStyle(Theme.ink)117 if let d = b.display { Masked(text: Money.exact(d) + " " + b.symbol).font(.spFootnote).monospacedDigit().foregroundStyle(Theme.mute) }118 else { Text(String(localized: "Lecture de la chaîne indisponible")).font(.spFootnote).foregroundStyle(Theme.warn) }119 }120 Spacer()121 if let v = model.portfolio.value?.estimatedValue(of: b, in: model.currency) { Masked(text: Money.fiat(v, model.currency)).font(.system(size: 15, weight: .semibold)).monospacedDigit() }122 }123 if b.asset != "native" {124 HStack(alignment: .top, spacing: 6) {125 Pill(text: String(localized: "Registre vérifié"), tone: .ok, icon: "checkmark.seal.fill")126 Text(b.asset).font(.system(size: 11.5, design: .monospaced)).foregroundStyle(Theme.mute).textSelection(.enabled)127 }128 }129 HStack(spacing: 8) {130 Button { router.sheet = .send(network: b.network, asset: b.asset) } label: { Label(String(localized: "Envoyer"), systemImage: "arrow.up.right").font(.spCallout.weight(.semibold)) }131 .buttonStyle(.bordered).disabled(!model.canOperate || !b.isNonZero)132 Button { router.sheet = .receive(network: b.network) } label: { Label(String(localized: "Recevoir"), systemImage: "arrow.down.left").font(.spCallout.weight(.semibold)) }.buttonStyle(.bordered)133 }134 }135 .padding(.vertical, 8)136 if b.id != balances.last?.id { Divider() }137 }138 }.spCard()139 }140141 private var historyCard: some View {142 let items = (model.activity.value ?? []).filter { $0.symbol == symbol }.prefix(20)143 return VStack(alignment: .leading, spacing: 6) {144 SectionHeader(title: String(localized: "Historique de cet actif"))145 if items.isEmpty { Text(String(localized: "Aucune transaction.")).font(.spCallout).foregroundStyle(Theme.mute) }146 ForEach(items) { i in NavigationLink(value: i) { TransactionRow(item: i) }.buttonStyle(.plain) }147 }148 .spCard()149 .navigationDestination(for: ActivityItem.self) { ActivityDetailView(item: $0).wallet(model) }150 }151152 private func loadChart() async {153 guard !model.offlineBrowsing else { chart = await model.env.cache.load(MarketChart.self, key: "chart-\(symbol)-\(days)")?.value; return }154 do {155 let c = try await model.env.wallet.chart(symbol: symbol, days: days, currency: model.currency)156 chart = c; chartError = nil157 await model.env.cache.save(c, key: "chart-\(symbol)-\(days)")158 } catch {159 if let cached = await model.env.cache.load(MarketChart.self, key: "chart-\(symbol)-\(days)") { chart = cached.value } else { chartError = error }160 }161 }162}163