SPB Git

Repository Public

SPWalletWidgets.swift 12.3 KB 252 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet9// File             : Widgets/SPWalletWidgets.swift10// Description      : WidgetKit widgets: portfolio value, main holdings, latest11//                    transactions, wallet state. They read the dated summary12//                    the app wrote in the App Group and never contact the13//                    server. Figures appear only if the owner allowed them, and14//                    every figure is marked privacy-sensitive (redacted on the15//                    lock screen and in the always-on display).16// Module           : Widgets17// Repository       : https://git.spboucher.ai/sp-wallet-ios18// Created          : 2026-11-1819// Last Modified    : 2026-11-1820//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author           : Simon-Pierre Boucher26// Position         : Professor of Finance27// Institution      : Université du Québec en Outaouais (UQO)28// Department       : Département des sciences administratives29// Organization     : SP Boucher30//31// Website          : https://spboucher.ai32// Git              : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General          : info@spboucher.ai39// Professional     : contact@spboucher.ai40// Direct           : simon@spboucher.ai41// Research         : research@spboucher.ai42// Development      : dev@spboucher.ai43// Support          : support@spboucher.ai44// Security/Admin   : admin@spboucher.ai45// Notifications    : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification   : Public72// Distribution     : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License          : None specified (no license file in this repository)86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import SwiftUI94import WidgetKit9596struct WalletEntry: TimelineEntry {97    let date: Date98    let snapshot: WidgetSnapshot?99}100101struct WalletProvider: TimelineProvider {102    func placeholder(in context: Context) -> WalletEntry { WalletEntry(date: .now, snapshot: nil) }103    func getSnapshot(in context: Context, completion: @escaping (WalletEntry) -> Void) {104        completion(WalletEntry(date: .now, snapshot: WidgetSnapshot.read(appGroup: WidgetSnapshot.appGroup)))105    }106    func getTimeline(in context: Context, completion: @escaping (Timeline<WalletEntry>) -> Void) {107        // the app reloads the timelines when it refreshes; this policy only re-reads the file now and then108        completion(Timeline(entries: [WalletEntry(date: .now, snapshot: WidgetSnapshot.read(appGroup: WidgetSnapshot.appGroup))], policy: .after(.now.addingTimeInterval(1800))))109    }110}111112private let ink = Color.primary113private let mute = Color.secondary114private let emerald = Color(red: 0.03, green: 0.48, blue: 0.33)115private let danger = Color(red: 0.76, green: 0.16, blue: 0.25)116117private func changeText(_ c: Double?) -> String? {118    guard let c else { return nil }119    return (c > 0 ? "▲ " : c < 0 ? "▼ " : "") + abs(c).formatted(.number.precision(.fractionLength(2))) + " %"120}121122private struct Stamp: View {123    let snapshot: WidgetSnapshot124    var body: some View {125        // always dated: a widget is a snapshot, never a live figure126        Text(String(localized: "Instantané") + " · " + snapshot.savedAt.formatted(date: .omitted, time: .shortened))127            .font(.system(size: 10)).foregroundStyle(mute).lineLimit(1)128    }129}130131private struct SignedOut: View {132    var body: some View {133        VStack(alignment: .leading, spacing: 6) {134            Image(systemName: "lock.shield.fill").font(.title3).foregroundStyle(mute)135            Text("SP Wallet").font(.headline)136            Text(String(localized: "Ouvre l’app pour synchroniser.")).font(.caption).foregroundStyle(mute)137        }.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)138    }139}140141struct ValueWidgetView: View {142    let entry: WalletEntry143    var body: some View {144        if let s = entry.snapshot, s.signedIn {145            VStack(alignment: .leading, spacing: 4) {146                HStack { Image(systemName: s.halted == true ? "hand.raised.fill" : "lock.shield.fill").foregroundStyle(s.halted == true ? danger : emerald); Text("SP Wallet").font(.caption.weight(.semibold)).foregroundStyle(mute) }147                Spacer(minLength: 0)148                if let t = s.total {149                    Text(t).font(.system(size: 24, weight: .semibold)).minimumScaleFactor(0.5).lineLimit(1).privacySensitive()150                    if let c = changeText(s.change24h) { Text(c + " · 24 h").font(.caption.weight(.semibold)).foregroundStyle((s.change24h ?? 0) >= 0 ? emerald : danger).privacySensitive() }151                    if !s.totalComplete { Text(String(localized: "partiel")).font(.system(size: 10)).foregroundStyle(.orange) }152                } else {153                    Text(String(localized: "Montants masqués")).font(.subheadline.weight(.semibold))154                    Text(String(localized: "Réglages → Montants dans les widgets")).font(.system(size: 10)).foregroundStyle(mute)155                }156                if s.pricesStale { Text(String(localized: "prix périmés")).font(.system(size: 10)).foregroundStyle(.orange) }157                Stamp(snapshot: s)158            }159            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)160            .widgetURL(URL(string: "spwallet://home"))161        } else { SignedOut() }162    }163}164165struct AssetsWidgetView: View {166    let entry: WalletEntry167    var body: some View {168        if let s = entry.snapshot, s.signedIn {169            VStack(alignment: .leading, spacing: 6) {170                HStack { Text(String(localized: "Principaux actifs")).font(.caption.weight(.semibold)).foregroundStyle(mute); Spacer(); Stamp(snapshot: s) }171                if s.assets.isEmpty { Text(String(localized: "Aucun actif détenu")).font(.subheadline).foregroundStyle(mute) }172                ForEach(s.assets) { a in173                    Link(destination: URL(string: "spwallet://asset/\(a.symbol)")!) {174                        HStack {175                            Text(a.symbol).font(.subheadline.weight(.semibold)).foregroundStyle(ink)176                            Text(a.share.formatted(.percent.precision(.fractionLength(0)))).font(.caption).foregroundStyle(mute)177                            Spacer()178                            if let c = changeText(a.change24h) { Text(c).font(.caption).foregroundStyle((a.change24h ?? 0) >= 0 ? emerald : danger) }179                            if let v = a.value { Text(v).font(.subheadline.weight(.medium)).monospacedDigit().foregroundStyle(ink).privacySensitive() }180                        }181                    }182                }183                Spacer(minLength: 0)184            }.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)185        } else { SignedOut() }186    }187}188189struct ActivityWidgetView: View {190    let entry: WalletEntry191    private func title(_ k: String) -> String {192        switch k { case "receive": String(localized: "Reçu"); case "swap": String(localized: "Échange"); case "bridge": String(localized: "Pont"); case "send": String(localized: "Envoyé"); default: k }193    }194    var body: some View {195        if let s = entry.snapshot, s.signedIn {196            VStack(alignment: .leading, spacing: 6) {197                HStack { Text(String(localized: "Dernières transactions")).font(.caption.weight(.semibold)).foregroundStyle(mute); Spacer(); Stamp(snapshot: s) }198                if let c = s.criticalAlert { Label(c, systemImage: "exclamationmark.triangle.fill").font(.caption.weight(.semibold)).foregroundStyle(danger).lineLimit(1) }199                if s.transactions.isEmpty { Text(String(localized: "Aucune transaction")).font(.subheadline).foregroundStyle(mute) }200                ForEach(s.transactions) { t in201                    HStack {202                        // only a settled transaction gets the check mark203                        Image(systemName: t.settled ? "checkmark.circle.fill" : "clock").font(.caption).foregroundStyle(t.settled ? emerald : mute)204                        Text(title(t.kind) + " " + t.symbol).font(.subheadline.weight(.medium)).foregroundStyle(ink).lineLimit(1)205                        Spacer()206                        if let a = t.amount { Text(a).font(.caption).monospacedDigit().foregroundStyle(mute).lineLimit(1).privacySensitive() }207                    }208                }209                Spacer(minLength: 0)210            }211            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)212            .widgetURL(URL(string: "spwallet://activity"))213        } else { SignedOut() }214    }215}216217struct ValueWidget: Widget {218    var body: some WidgetConfiguration {219        StaticConfiguration(kind: WidgetSnapshot.kind + ".value", provider: WalletProvider()) { e in220            ValueWidgetView(entry: e).containerBackground(Color("WidgetBackground"), for: .widget)221        }222        .configurationDisplayName(String(localized: "Valeur du portefeuille"))223        .description(String(localized: "Valeur estimée au dernier rafraîchissement de l’app. Les montants s’activent dans les réglages."))224        .supportedFamilies([.systemSmall])225    }226}227struct AssetsWidget: Widget {228    var body: some WidgetConfiguration {229        StaticConfiguration(kind: WidgetSnapshot.kind + ".assets", provider: WalletProvider()) { e in230            AssetsWidgetView(entry: e).containerBackground(Color("WidgetBackground"), for: .widget)231        }232        .configurationDisplayName(String(localized: "Principaux actifs"))233        .description(String(localized: "Tes principaux actifs et leur part."))234        .supportedFamilies([.systemMedium])235    }236}237struct ActivityWidget: Widget {238    var body: some WidgetConfiguration {239        StaticConfiguration(kind: WidgetSnapshot.kind + ".activity", provider: WalletProvider()) { e in240            ActivityWidgetView(entry: e).containerBackground(Color("WidgetBackground"), for: .widget)241        }242        .configurationDisplayName(String(localized: "Dernières transactions"))243        .description(String(localized: "Les dernières transactions et leur état réel."))244        .supportedFamilies([.systemMedium, .systemLarge])245    }246}247248@main249struct SPWalletWidgetBundle: WidgetBundle {250    var body: some Widget { ValueWidget(); AssetsWidget(); ActivityWidget() }251}252
Files main
Menu

Theme