SPB Git

Repository Public

StatusViews.swift 11.6 KB 227 lines swift

1// SP Wallet iOS2// File: Components/StatusViews.swift3// Description: Honest state display: notices (info, warning, danger), the freshness banner of offline / stale data, the security4//              indicator of the isolated signer, proposal state pills, empty and error states. Each state has an icon and a word.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import SPWalletCore1011enum Tone { case info, ok, warn, danger, neutral12    var color: Color { switch self { case .info: Theme.blue; case .ok: Theme.emerald; case .warn: Theme.warn; case .danger: Theme.danger; case .neutral: Theme.mute } }13    var icon: String { switch self { case .info: "info.circle.fill"; case .ok: "checkmark.circle.fill"; case .warn: "exclamationmark.triangle.fill"; case .danger: "xmark.octagon.fill"; case .neutral: "circle.dashed" } }14}1516struct Notice: View {17    let tone: Tone18    let title: String19    var message: String?20    var icon: String?21    var body: some View {22        HStack(alignment: .top, spacing: 10) {23            Image(systemName: icon ?? tone.icon).foregroundStyle(tone.color).font(.system(size: 17, weight: .semibold)).padding(.top, 1)24            VStack(alignment: .leading, spacing: 3) {25                Text(title).font(.system(size: 14.5, weight: .semibold)).foregroundStyle(Theme.ink)26                if let message, !message.isEmpty { Text(message).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true) }27            }28            Spacer(minLength: 0)29        }30        .padding(14)31        .background(tone.color.opacity(0.10), in: RoundedRectangle(cornerRadius: Theme.Radius.control, style: .continuous))32        .accessibilityElement(children: .combine)33    }34}3536struct Pill: View {37    let text: String38    var tone: Tone = .neutral39    var icon: String?40    var body: some View {41        HStack(spacing: 4) {42            if let icon { Image(systemName: icon).font(.system(size: 10, weight: .bold)) }43            Text(text).font(.system(size: 11.5, weight: .semibold))44        }45        .foregroundStyle(tone.color)46        .padding(.horizontal, 8).padding(.vertical, 4)47        .background(tone.color.opacity(0.12), in: Capsule())48    }49}5051/** Shown at the top of every data screen when what is displayed is not live. */52struct FreshnessBanner: View {53    @Environment(AppModel.self) private var model54    var body: some View {55        if model.offlineBrowsing || model.offline {56            Notice(tone: .warn, title: String(localized: "Consultation hors ligne"),57                   message: model.portfolio.savedAt.map { String(localized: "Dernière synchronisation \(Money.age($0)). Les soldes et les prix peuvent être périmés. Aucune opération n’est possible.") }58                    ?? String(localized: "Les données affichées peuvent être périmées. Aucune opération n’est possible."),59                   icon: "wifi.slash")60            .accessibilityIdentifier("banner.offline")61        } else if let p = model.portfolio.value, p.pricesStale {62            Notice(tone: .warn, title: String(localized: "Prix périmés"),63                   message: p.pricesAsOf.map { String(localized: "Dernière mise à jour de la source de prix : \(Money.age($0)). Les valeurs en devise sont des estimations anciennes.") })64        }65    }66}6768/** State of the isolated signer, as the server reports it. */69struct SecurityIndicator: View {70    let reachable: Bool?71    let halted: Bool?72    var compact = false73    private var tone: Tone { halted == true ? .danger : reachable == false ? .warn : reachable == true ? .ok : .neutral }74    private var label: String {75        if halted == true { return String(localized: "Arrêt d’urgence actif") }76        if reachable == false { return String(localized: "Signataire injoignable") }77        if reachable == true { return String(localized: "Signataire isolé en service") }78        return String(localized: "État du signataire inconnu")79    }80    private var symbol: String { halted == true ? "hand.raised.fill" : reachable == false ? "bolt.horizontal.circle" : reachable == true ? "lock.shield.fill" : "questionmark.circle" }81    var body: some View {82        if compact { Pill(text: label, tone: tone, icon: symbol) }83        else { Label(label, systemImage: symbol).font(.spFootnote.weight(.semibold)).foregroundStyle(tone.color) }84    }85}8687extension ProposalState {88    var label: String {89        switch self {90        case .draft: String(localized: "Brouillon")91        case .pendingApproval: String(localized: "En attente d’approbation")92        case .approved: String(localized: "Approuvée, signature en cours")93        case .signed: String(localized: "Signée, pas encore diffusée")94        case .broadcast: String(localized: "Diffusée, non confirmée")95        case .confirming: String(localized: "En cours de confirmation")96        case .finalized: String(localized: "Confirmée")97        case .rejected: String(localized: "Refusée")98        case .expired: String(localized: "Expirée")99        case .failed: String(localized: "Échouée")100        case .replaced: String(localized: "Remplacée")101        case .reorged: String(localized: "Réorganisation de chaîne, à reconfirmer")102        case .notBroadcast: String(localized: "Signée, non diffusée (diffusion désactivée)")103        case .unknown: String(localized: "État inconnu")104        }105    }106    var tone: Tone { isSuccess ? .ok : isFailure ? .danger : self == .notBroadcast || self == .reorged ? .warn : self == .unknown ? .neutral : .info }107    var symbol: String {108        switch self {109        case .finalized: "checkmark.circle.fill"110        case .rejected, .failed, .expired, .replaced: "xmark.circle.fill"111        case .broadcast, .confirming, .approved, .signed: "clock.arrow.2.circlepath"112        case .reorged, .notBroadcast: "exclamationmark.triangle.fill"113        default: "circle.dashed"114        }115    }116}117118/** State text of an activity row: a proposal state, or the deposit vocabulary (`confirming` / `finalized`). Unknown text is shown verbatim. */119func activityStateLabel(_ item: ActivityItem) -> (String, Tone, String) {120    if item.isIncoming {121        return item.state == "finalized" ? (String(localized: "Reçu, confirmé"), .ok, "checkmark.circle.fill") : (String(localized: "Reçu, en cours de confirmation"), .info, "clock.arrow.2.circlepath")122    }123    if let s = item.proposalState { return (s.label, s.tone, s.symbol) }124    return (item.state, .neutral, "circle.dashed")125}126127struct EmptyState: View {128    let icon: String129    let title: String130    var message: String?131    var body: some View {132        VStack(spacing: 10) {133            Image(systemName: icon).font(.system(size: 34, weight: .regular)).foregroundStyle(Theme.mute)134            Text(title).font(.spHeadline).foregroundStyle(Theme.ink)135            if let message { Text(message).font(.spCallout).foregroundStyle(Theme.mute).multilineTextAlignment(.center) }136        }137        .frame(maxWidth: .infinity).padding(.vertical, 36).padding(.horizontal, 24)138    }139}140141/** A server or transport error, with the server's own words. */142struct ErrorNotice: View {143    let error: Error144    var retry: (() -> Void)?145    var body: some View {146        VStack(alignment: .leading, spacing: 10) {147            Notice(tone: .danger, title: Self.title(error), message: Self.detail(error))148            if let retry { Button(String(localized: "Réessayer"), action: retry).buttonStyle(.spSecondary) }149        }150    }151    static func title(_ e: Error) -> String {152        if let a = e as? APIError {153            if a.isOffline { return String(localized: "Serveur injoignable") }154            switch a.code {155            case "policy": return String(localized: "Refusé par les limites du signataire")156            case "halted": return String(localized: "Arrêt d’urgence actif")157            case "bad_address": return String(localized: "Adresse refusée")158            case "bad_amount": return String(localized: "Montant refusé")159            case "bad_memo": return String(localized: "Mémo refusé")160            case "pending_tx": return String(localized: "Une opération est déjà en cours sur ce réseau")161            case "expired": return String(localized: "Fenêtre d’approbation expirée")162            case "signer_unreachable": return String(localized: "Signataire injoignable")163            case "rate_limited": return String(localized: "Trop de requêtes")164            case "unauthenticated": return String(localized: "Session terminée")165            case "quote_moved": return String(localized: "Le prix a bougé : rien n’a été préparé")166            default: return String(localized: "Opération refusée")167            }168        }169        if e is ApprovalError { return String(localized: "Approbation bloquée par l’app") }170        if let p = e as? PasskeyError, case .cancelled = p { return String(localized: "Approbation annulée") }171        return String(localized: "Erreur")172    }173    static func detail(_ e: Error) -> String {174        if let a = e as? APIError { return a.isOffline ? String(localized: "Vérifie la connexion. Rien n’a été envoyé.") : "\(a.message) (\(a.code))" }175        if let a = e as? ApprovalError {176            switch a {177            case .challengeMismatch: return String(localized: "Le défi reçu du serveur ne correspond pas à l’opération affichée. Rien n’a été signé.")178            case .wrongRelyingParty: return String(localized: "Le défi a été émis pour un autre domaine. Rien n’a été signé.")179            case .userVerificationNotRequired: return String(localized: "Le défi n’exige pas la vérification de l’utilisateur. Rien n’a été signé.")180            case .expired: return String(localized: "La fenêtre d’approbation est expirée. Recommence l’opération.")181            case .unsupported(let s): return String(localized: "Cette version de l’app ne sait pas vérifier cette opération ; elle refuse de l’approuver à l’aveugle.") + " (\(s))"182            case .inconsistent(let s): return String(localized: "L’opération à approuver diffère de ce qui a été demandé. Rien n’a été signé.") + " (\(s))"183            }184        }185        if let p = e as? PasskeyError {186            switch p {187            case .cancelled: return String(localized: "Rien n’a été signé.")188            case .noCredential: return String(localized: "Aucune clé d’accès de ce portefeuille sur cet appareil.")189            case .notAvailable(let s), .failed(let s): return s190            }191        }192        return e.localizedDescription193    }194}195196/** A labelled value row; `mono` values (addresses, hashes) wrap in full and can be copied. */197struct FieldRow: View {198    let label: String199    let value: String200    var mono = false201    var tone: Tone?202    var copyable = false203    var body: some View {204        VStack(alignment: .leading, spacing: 3) {205            Text(label).font(.spFootnote).foregroundStyle(Theme.mute)206            Text(value).font(mono ? .spMono : .spBody.weight(.medium)).foregroundStyle(tone?.color ?? Theme.ink)207                .textSelection(.enabled).fixedSize(horizontal: false, vertical: true)208                .frame(maxWidth: .infinity, alignment: .leading)209        }210        .padding(.vertical, 7)211        .contextMenu { if copyable { Button { UIPasteboard.general.string = value } label: { Label(String(localized: "Copier"), systemImage: "doc.on.doc") } } }212        .accessibilityElement(children: .combine)213    }214}215216struct SectionHeader: View {217    let title: String218    var action: (title: String, run: () -> Void)?219    var body: some View {220        HStack {221            Text(title).font(.spHeadline).foregroundStyle(Theme.ink)222            Spacer()223            if let action { Button(action.title, action: action.run).font(.spCallout.weight(.semibold)).foregroundStyle(Theme.blue) }224        }225    }226}227
Files main
Menu

Theme