SPB Git

Repository Public

AssetsView.swift 10.2 KB 132 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Assets/AssetsView.swift3// Description: Tokens and coins: every asset of the backend's registry with its network, contract, decimals, exact balance and estimated value; a detail pane with the price chart (observed market data, labelled with its source), market facts and the asset's transactions. The registry is curated server-side: this app cannot add an arbitrary token, and says so.4import SwiftUI5import Charts6import SPWalletCore78struct AssetsView: View {9    let model: AppModel10    @Bindable var nav: Navigator11    @State private var search = ""12    @State private var heldOnly = true13    @State private var selection: String?1415    private var rows: [Balance] {16        guard let p = model.portfolio?.value else { return [] }17        let q = search.trimmingCharacters(in: .whitespaces).lowercased()18        return p.balances.filter { b in19            (!heldOnly || b.isNonZero || !b.isAvailable) &&20            (q.isEmpty || b.symbol.lowercased().contains(q) || b.name.lowercased().contains(q) || b.networkName.lowercased().contains(q) || b.asset.lowercased() == q)21        }.sorted { a, b in (p.estimatedValue(of: a, in: model.currency) ?? -1) > (p.estimatedValue(of: b, in: model.currency) ?? -1) }22    }2324    var body: some View {25        // an HStack, not an HSplitView: the AppKit split view ignores the detail column's safe-area insets and its minimum widths push the sidebar out of the window26        HStack(spacing: 0) {27            VStack(spacing: 0) {28                HStack {29                    TextField("Rechercher (symbole, nom, réseau, contrat)", text: $search).textFieldStyle(.roundedBorder)30                    Toggle("Détenus", isOn: $heldOnly).toggleStyle(.checkbox)31                }.padding(12)32                Divider()33                if let p = model.portfolio?.value {34                    List(rows, selection: $selection) { b in35                        AssetRow(balance: b, portfolio: p, currency: model.currency, hide: model.settings.hideBalances, cached: model.portfolio?.fromCache ?? false).tag(b.id)36                    }37                    .overlay { if rows.isEmpty { EmptyState(symbol: "magnifyingglass", title: heldOnly ? "Aucun actif détenu ne correspond" : "Aucun actif ne correspond", detail: "Les jetons affichés sont ceux du registre vérifié du backend (émetteur, CoinGecko et chaîne concordants).") } }38                } else { EmptyState(symbol: "tray", title: "Soldes non synchronisés") }39                Divider()40                Text("Le registre des jetons est tenu côté serveur et vérifié contre l’émetteur et la chaîne. L’ajout d’un jeton personnalisé n’est pas pris en charge par le backend : un nom ou un logo ne prouve rien, seul le contrat identifie un jeton.")41                    .font(.caption).foregroundStyle(.secondary).padding(10).frame(maxWidth: .infinity, alignment: .leading)42            }43            .frame(width: 500)44            Divider()45            Group {46                if let id = selection, let b = model.portfolio?.value.balances.first(where: { $0.id == id }) { AssetDetail(model: model, nav: nav, balance: b).id(id) }47                else { EmptyState(symbol: "bitcoinsign.circle", title: "Choisissez un actif") }48            }.frame(maxWidth: .infinity, maxHeight: .infinity)49        }50        .background(Backdrop())51        .onAppear { if let f = nav.assetFocus { selection = f; heldOnly = false; nav.assetFocus = nil } }52        .onChange(of: nav.assetFocus) { if let f = nav.assetFocus { selection = f; nav.assetFocus = nil } }53    }54}5556struct AssetDetail: View {57    let model: AppModel58    @Bindable var nav: Navigator59    let balance: Balance60    @State private var days = 761    @State private var chart: MarketChart?62    @State private var chartError: String?6364    var body: some View {65        let net = model.network(balance.network), def = net?.asset(balance.asset)66        let p = model.portfolio?.value, price = model.price(balance.symbol)67        ScrollView {68            VStack(alignment: .leading, spacing: 14) {69                HStack(spacing: 12) {70                    AssetBadge(symbol: balance.symbol, size: 44)71                    VStack(alignment: .leading) { Text(balance.name).font(.title2.weight(.semibold)); Text("\(balance.symbol) sur \(balance.networkName)").foregroundStyle(.secondary) }72                    Spacer()73                    Button("Envoyer") { nav.send(network: balance.network, asset: balance.asset) }.disabled(!model.canOperate || !balance.isNonZero)74                    Button("Recevoir") { nav.section = .receive }75                }76                Card("Solde") {77                    if balance.isAvailable {78                        Text(model.settings.hideBalances ? "••••" : "\(Fmt.amount(balance.display)) \(balance.symbol)").font(.title.weight(.semibold)).monospacedDigit().textSelection(.enabled)79                        HStack { ProvenanceTag(p: model.portfolio?.fromCache == true ? .stale : .verified, text: model.portfolio?.fromCache == true ? "Synchronisé le \(Fmt.date(model.portfolio?.fetchedAt))" : "Lu sur la chaîne \(Fmt.relative(p?.asOf))")80                            if let p, let v = p.estimatedValue(of: balance, in: model.currency) { Text(model.settings.hideBalances ? "" : Fmt.fiat(v, model.currency)).foregroundStyle(.secondary) } }81                    } else { Banner(.danger, "Solde indisponible : la lecture de la chaîne a échoué (\(balance.error ?? "sans détail")). Ce n’est pas un solde nul.") }82                }83                Card("Identité de l’actif") {84                    Field(label: "Réseau", value: "\(balance.networkName) (\(balance.network))")85                    Field(label: balance.asset == "native" ? "Type" : "Contrat", value: balance.asset == "native" ? "Monnaie native du réseau" : balance.asset, mono: balance.asset != "native")86                    Field(label: "Décimales", value: String(balance.decimals))87                    if let o = def?.onchainSymbol, o != balance.symbol { Field(label: "Symbole sur la chaîne", value: o) }88                    if let prog = def?.program { Field(label: "Programme", value: prog, mono: true) }89                    ProvenanceTag(p: .verified, text: "Jeton du registre vérifié du backend")90                    if balance.asset != "native", let ex = net?.explorerAddr, let u = URL(string: ex + balance.asset), u.scheme == "https" { Link("Voir le contrat dans l’explorateur", destination: u) }91                }92                Card("Prix", trailing: AnyView(Picker("", selection: $days) { Text("24 h").tag(1); Text("7 j").tag(7); Text("30 j").tag(30); Text("1 an").tag(365) }.pickerStyle(.segmented).frame(width: 220))) {93                    if let price {94                        HStack(alignment: .firstTextBaseline, spacing: 10) {95                            Text(Fmt.price(price.value(in: model.currency), model.currency)).font(.title2.weight(.semibold)).monospacedDigit()96                            Text("24 h \(Fmt.percent(price.change24h))").foregroundStyle(Theme.change(price.change24h))97                            Text("7 j \(Fmt.percent(price.change7d))").foregroundStyle(Theme.change(price.change7d))98                            Spacer()99                            ProvenanceTag(p: price.stale ? .stale : .estimate, text: "Observé · \(price.source ?? "source inconnue")\(price.fallback == true ? " (secours)" : "") · \(Fmt.relative(price.priceAt))")100                        }101                        if price.divergent == true { Banner(.warning, "Les deux sources de prix divergent au-delà du seuil : traitez ce prix avec prudence.") }102                    } else { Text(model.settings.prices ? "Aucun prix pour cet actif." : "Prix désactivés dans les réglages.").foregroundStyle(.secondary) }103                    if let c = chart, c.points.count > 1 {104                        Chart(c.points, id: \.t) { LineMark(x: .value("Date", $0.date), y: .value("Prix", $0.p)).foregroundStyle(Theme.accent) }105                            .chartYScale(domain: .automatic(includesZero: false)).frame(height: 200)106                    } else if let e = chartError { Text("Graphique indisponible : \(e)").foregroundStyle(.secondary) }107                    else if price != nil { Text(model.isOffline ? "Graphique indisponible hors connexion." : "Aucune série de prix.").foregroundStyle(.secondary).frame(height: 40) }108                    if let m = price {109                        Grid(alignment: .leading, horizontalSpacing: 24, verticalSpacing: 4) {110                            GridRow { Text("Capitalisation").foregroundStyle(.secondary); Text(Fmt.compact(m.marketCap, .usd)); Text("Volume 24 h").foregroundStyle(.secondary); Text(Fmt.compact(m.volume24h, .usd)) }111                            GridRow { Text("Plus haut 24 h").foregroundStyle(.secondary); Text(Fmt.price(m.high24h, .usd)); Text("Plus bas 24 h").foregroundStyle(.secondary); Text(Fmt.price(m.low24h, .usd)) }112                            GridRow { Text("Rang").foregroundStyle(.secondary); Text(m.rank.map(String.init) ?? "—"); Text("Sommet historique").foregroundStyle(.secondary); Text(Fmt.price(m.ath, .usd)) }113                        }.font(.callout)114                        Text("Données de marché observées (en USD), non vérifiées par cette app ; ce ne sont ni des conseils ni des prévisions.").font(.caption).foregroundStyle(.secondary)115                    }116                }117                Card("Transactions de cet actif") {118                    let items = (model.activity?.value ?? []).filter { $0.network == balance.network && ($0.asset == balance.asset || ($0.asset == nil && $0.symbol == balance.symbol)) }119                    if items.isEmpty { Text("Aucune transaction enregistrée pour cet actif.").foregroundStyle(.secondary) }120                    ForEach(items.prefix(25)) { TransactionRow(item: $0) }121                    if items.count > 25 { Button("Voir tout dans Activité") { nav.section = .activity }.buttonStyle(.link) }122                }123            }.padding(20)124        }125        .task(id: days) { await loadChart() }126    }127    private func loadChart() async {128        guard model.phase == .signedIn, !model.isOffline, model.settings.prices else { return }129        do { chart = try await model.wallet.chart(symbol: balance.symbol, days: days, currency: model.currency); chartError = nil } catch { chartError = model.describe(error) }130    }131}132
Files main
Menu

Theme