Repository Public
1// SP Wallet iOS2// File: Features/Settings/SettingsView.swift3// Description: Settings: display currency and privacy (stored on the server, shared with the web and macOS apps), device lock,4// widget privacy, notifications, address book, diagnostics, sign-out.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import SPWalletCore1011struct SettingsView: View {12 @Environment(AppModel.self) private var model13 @Environment(Router.self) private var router14 @Environment(Preferences.self) private var prefs15 @State private var confirmSignOut = false1617 var body: some View {18 @Bindable var prefs = prefs19 Form {20 if model.offlineBrowsing {21 Section {22 Notice(tone: .warn, title: String(localized: "Consultation hors ligne"), message: String(localized: "Connecte-toi pour modifier les réglages du portefeuille."))23 Button(String(localized: "Se connecter")) { model.leaveOfflineBrowsing() }24 }25 }26 if let s = model.settings.value {27 Section(String(localized: "Affichage")) {28 Picker(String(localized: "Devise"), selection: Binding(get: { s.currency }, set: { v in var n = s; n.currency = v; Task { await model.update(settings: n) } })) {29 ForEach(FiatCurrency.allCases, id: \.self) { Text($0.rawValue).tag($0) }30 }.accessibilityIdentifier("settings.currency")31 Toggle(String(localized: "Masquer les soldes"), isOn: Binding(get: { s.hideBalances }, set: { v in var n = s; n.hideBalances = v; Task { await model.update(settings: n) } }))32 .accessibilityIdentifier("settings.hide")33 Toggle(String(localized: "Afficher les prix et valeurs estimées"), isOn: Binding(get: { s.prices }, set: { v in var n = s; n.prices = v; Task { await model.update(settings: n); await model.refreshPortfolio() } }))34 }35 .disabled(!model.canOperate)36 }37 Section {38 Toggle(lockTitle, isOn: $prefs.deviceLock).disabled(DeviceLock.available() == .none).accessibilityIdentifier("settings.lock")39 Toggle(String(localized: "Montants dans les widgets"), isOn: $prefs.widgetAmounts).onChange(of: prefs.widgetAmounts) { _, _ in model.publishWidgetSnapshot() }40 } header: { Text(String(localized: "Confidentialité sur cet appareil")) } footer: {41 Text(String(localized: "Le verrou protège l’affichage. Il n’autorise aucune opération : chaque transaction exige une clé d’accès liée à son contenu. Sans l’option « montants », les widgets n’affichent aucun chiffre."))42 }43 Section(String(localized: "Notifications")) { NotificationSettingsRows() }44 Section(String(localized: "Portefeuille")) {45 NavigationLink { AddressBookView().wallet(model) } label: { Label(String(localized: "Carnet d’adresses"), systemImage: "book.closed") }46 Button { router.go(.security) } label: { Label(AppSection.security.title, systemImage: AppSection.security.icon) }47 Button { router.go(.risk) } label: { Label(AppSection.risk.title, systemImage: AppSection.risk.icon) }48 NavigationLink { NetworkStatusView().wallet(model) } label: { Label(String(localized: "Réseaux et état RPC"), systemImage: "network") }49 }50 Section(String(localized: "À propos")) {51 LabeledContent(String(localized: "Version"), value: (Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "") + " (" + (Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "") + ")")52 LabeledContent(String(localized: "Serveur"), value: model.env.configuration.api.originHeader)53 if let k = model.accounts.value?.keyId { LabeledContent(String(localized: "Clé du signataire"), value: k) }54 NavigationLink { AboutCustodyView().wallet(model) } label: { Text(String(localized: "Modèle de garde et limites connues")) }55 }56 Section {57 Button(role: .destructive) { confirmSignOut = true } label: { Label(String(localized: "Se déconnecter"), systemImage: "rectangle.portrait.and.arrow.right") }58 .accessibilityIdentifier("settings.signout")59 } footer: { Text(String(localized: "La session est révoquée sur le serveur et toutes les données du portefeuille sont effacées de cet appareil.")) }60 }61 .navigationTitle(AppSection.settings.title)62 .confirmationDialog(String(localized: "Se déconnecter ?"), isPresented: $confirmSignOut, titleVisibility: .visible) {63 Button(String(localized: "Se déconnecter et effacer les données locales"), role: .destructive) { Task { await model.signOut() } }64 }65 }6667 private var lockTitle: String {68 switch DeviceLock.available() {69 case .faceID: String(localized: "Verrouiller avec Face ID")70 case .touchID: String(localized: "Verrouiller avec Touch ID")71 case .opticID: String(localized: "Verrouiller avec Optic ID")72 case .passcode: String(localized: "Verrouiller avec le code de l’appareil")73 case .none: String(localized: "Verrou indisponible (aucun code sur l’appareil)")74 }75 }76}7778struct AddressBookView: View {79 @Environment(AppModel.self) private var model80 @State private var entries: [AddressBookEntry]?81 @State private var error: Error?82 @State private var adding = false83 @State private var network: String?84 @State private var address = ""85 @State private var label = ""86 var body: some View {87 List {88 if let error { ErrorNotice(error: error) }89 if let entries {90 if entries.isEmpty { EmptyState(icon: "book.closed", title: String(localized: "Carnet vide"), message: String(localized: "Les adresses enregistrées ne déclenchent plus l’avertissement « nouvelle destination ».")).listRowBackground(Color.clear) }91 ForEach(entries) { e in92 VStack(alignment: .leading, spacing: 3) {93 HStack { NetworkIcon(network: e.network, size: 20); Text(e.label).font(.system(size: 15.5, weight: .semibold)); Spacer(); Text(model.network(e.network)?.name ?? e.network).font(.spFootnote).foregroundStyle(Theme.mute) }94 Text(e.address).font(.system(size: 12, design: .monospaced)).foregroundStyle(Theme.mute).textSelection(.enabled)95 }96 .swipeActions { Button(role: .destructive) { Task { try? await model.env.wallet.deleteAddress(id: e.id); await load() } } label: { Label(String(localized: "Supprimer"), systemImage: "trash") } }97 }98 } else if error == nil { ProgressView() }99 }100 .navigationTitle(String(localized: "Carnet d’adresses"))101 .toolbar { ToolbarItem(placement: .topBarTrailing) { Button { adding = true } label: { Image(systemName: "plus") }.disabled(!model.canOperate) } }102 .task { await load() }103 .sheet(isPresented: $adding) {104 NavigationStack {105 Form {106 Picker(String(localized: "Réseau"), selection: $network) { Text("—").tag(String?.none); ForEach(model.networks.value ?? []) { Text($0.name).tag(String?($0.id)) } }107 TextField(String(localized: "Adresse"), text: $address, axis: .vertical).font(.spMono).textInputAutocapitalization(.never).autocorrectionDisabled()108 TextField(String(localized: "Nom"), text: $label)109 if let error { ErrorNotice(error: error) }110 }111 .wallet(model)112 .navigationTitle(String(localized: "Nouvelle adresse")).navigationBarTitleDisplayMode(.inline)113 .toolbar {114 ToolbarItem(placement: .cancellationAction) { Button(String(localized: "Annuler")) { adding = false } }115 ToolbarItem(placement: .confirmationAction) {116 Button(String(localized: "Enregistrer")) { Task {117 // the server validates and normalizes the address for that network; an invalid one is refused118 do { _ = try await model.env.wallet.saveAddress(network: network ?? "", address: address, label: String(label.prefix(40))); adding = false; address = ""; label = ""; error = nil; await load() } catch let e { error = e }119 } }.disabled(network == nil || address.isEmpty || label.isEmpty)120 }121 }122 }123 }124 }125 private func load() async { do { entries = try await model.env.wallet.addressBook() } catch let e { error = e } }126}127128struct NetworkStatusView: View {129 @Environment(AppModel.self) private var model130 var body: some View {131 List(model.networks.value ?? []) { n in132 HStack(spacing: 12) {133 NetworkIcon(network: n.id, size: 32)134 VStack(alignment: .leading, spacing: 2) {135 Text(n.name).font(.system(size: 15.5, weight: .semibold))136 Text("\(n.family) · \(n.native.symbol) · " + String(localized: "\(n.tokens.count) jetons") + " · " + String(localized: "\(n.minConf) confirmations")).font(.spFootnote).foregroundStyle(Theme.mute)137 if let a = model.account(n.id)?.address { Text(a).font(.system(size: 11.5, design: .monospaced)).foregroundStyle(Theme.mute).lineLimit(1).truncationMode(.middle) }138 }139 Spacer()140 switch n.health?.ok {141 case true?: Pill(text: n.health?.identityVerified == false ? String(localized: "identité non vérifiée") : String(localized: "RPC OK"), tone: n.health?.identityVerified == false ? .warn : .ok, icon: "checkmark")142 case false?: Pill(text: String(localized: "en panne"), tone: .danger, icon: "xmark")143 default: Pill(text: String(localized: "inconnu"), tone: .neutral)144 }145 }146 }147 .navigationTitle(String(localized: "Réseaux"))148 .refreshable { await model.refreshAll() }149 }150}151152struct AboutCustodyView: View {153 var body: some View {154 ScrollView {155 VStack(alignment: .leading, spacing: 14) {156 Group {157 Text(String(localized: "Où sont les clés")).font(.spHeadline)158 Text(String(localized: "Les clés privées du portefeuille existent uniquement dans le signataire isolé, un processus seul sur une machine du cluster MacLustr. Ni cette app, ni le site, ni l’API ne les détiennent ou ne peuvent les télécharger."))159 Text(String(localized: "Ce qu’autorise ta clé d’accès")).font(.spHeadline)160 Text(String(localized: "Chaque opération est décrite par une intention canonique. Son empreinte SHA-256 est le défi que ta clé d’accès signe. L’app recalcule cette empreinte depuis les champs qu’elle t’affiche et refuse de continuer si elle ne correspond pas. Le signataire vérifie lui-même la signature, l’origine, les limites et l’anti-rejeu avant de signer."))161 Text(String(localized: "Ce que Face ID ne fait pas")).font(.spHeadline)162 Text(String(localized: "Le verrou de l’app (Face ID, Touch ID, code) ne protège que l’affichage sur cet appareil. Il n’approuve jamais une transaction à lui seul."))163 Text(String(localized: "Limites connues")).font(.spHeadline)164 Text(String(localized: "La garde repose sur une clé logicielle chiffrée sur une machine isolée : un accès administrateur à cette machine équivaut aux clés. Les limites par transfert et par jour du signataire bornent la perte possible. Les prix affichés sont des observations de sources tierces, pas des prix d’exécution."))165 }.font(.spCallout).foregroundStyle(Theme.ink)166 }.padding(Theme.Space.gutter).frame(maxWidth: 720)167 }168 .spPage().navigationTitle(String(localized: "Modèle de garde")).navigationBarTitleDisplayMode(.inline)169 }170}171