SPB Git

Repository Public

ActivityView.swift 14.4 KB 310 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/Activity/ActivityView.swift8// Module           : Activity9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0513//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import SwiftUI42import QyvoraWallet43import QyvoraUI4445/// History of every active chain in one list, grouped by day. Chains without a history source are named with the46/// service's reason; the list never shows "no transactions" for a chain whose history could not be read.47struct ActivityView: View {48    enum Filter: String, CaseIterable, Identifiable {49        case all = "All", tokens = "Tokens", pending = "Pending", failed = "Failed"50        var id: String { rawValue }51    }5253    /// When set, the screen is the history of that chain alone (pushed from the chain's screen).54    var fixedChain: ChainID?5556    @Environment(WalletStore.self) private var wallet57    @HideAmounts private var hideAmounts58    @State private var filter: Filter = .all59    @State private var chainFilter: ChainID?60    @State private var showsReasons = false61    @Namespace private var zoom6263    var body: some View {64        Group {65            if let snapshot = wallet.snapshot, snapshot.hasWallet {66                content(snapshot)67            } else {68                EmptyStateView(systemImage: "list.bullet.rectangle", title: "No wallet", message: "The history appears once a wallet exists on this device.")69                    .padding(QSpace.xl).frame(maxWidth: .infinity, maxHeight: .infinity)70            }71        }72        .qScreen()73        .navigationTitle(fixedChain?.descriptor.map { "\($0.displayName) activity" } ?? "Activity")74        .navigationBarTitleDisplayMode(.inline)75        .modifier(ActivityDestinations(isRoot: fixedChain == nil, namespace: zoom))76        .task { if fixedChain == nil { await wallet.synchronizeOnceIfNeeded() } }77        #if DEBUG78        .task(id: DebugNavigator.shared.serial) {79            if let name = DebugLaunch.defaults.string(forKey: "QYFilter") {80                if let known = Filter(rawValue: name) { filter = known; chainFilter = nil } else { chainFilter = ChainID(name) }81            }82        }83        #endif84    }8586    func chains(_ snapshot: WalletSnapshot) -> [ChainSnapshot] {87        if let fixedChain { return snapshot.chains.filter { $0.id == fixedChain } }88        if let chainFilter { return snapshot.chains.filter { $0.id == chainFilter } }89        return snapshot.chains90    }9192    func items(_ snapshot: WalletSnapshot) -> [ActivityItem] {93        let all = ActivityItem.sorted(chains(snapshot).flatMap { ActivityItem.of($0) })94        switch filter {95        case .all: return all96        case .tokens: return all.filter(\.entry.isToken)97        case .pending: return all.filter(\.isPending)98        case .failed: return all.filter(\.isFailed)99        }100    }101102    func content(_ snapshot: WalletSnapshot) -> some View {103        let shown = chains(snapshot)104        let items = items(snapshot)105        let unavailable = shown.compactMap { chain -> (ChainSnapshot, String)? in106            chain.data.value?.historyUnavailableReason.map { (chain, $0) }107        }108        let unread = shown.filter { $0.data.value == nil }109        return ScrollView {110            LazyVStack(alignment: .leading, spacing: QSpace.xl) {111                filters(snapshot)112                if !unavailable.isEmpty { unavailableNotice(unavailable) }113                if !unread.isEmpty { unreadNotice(unread) }114                if items.isEmpty {115                    emptyState(shown: shown, unavailable: unavailable.count, unread: unread.count)116                } else {117                    ForEach(groups(items), id: \.title) { group in118                        QListSection(group.title) {119                            ForEach(group.items) { item in120                                NavigationLink(value: item.route) { ActivityRow(item: item, hidden: hideAmounts) }121                                    .buttonStyle(.qRow)122                                    .qMatchedSource(id: item.route, in: zoom)123                            }124                        }125                    }126                }127            }128            .padding(.horizontal, QMetric.screenPadding)129            .padding(.vertical, QSpace.m)130            .frame(maxWidth: 640)131            .frame(maxWidth: .infinity)132        }133        .refreshable {134            if let fixedChain { await wallet.synchronize(chains: [fixedChain]) } else { await wallet.synchronize() }135        }136        .qAnimation(value: filter)137        .qHaptic(.selection, trigger: filter)138        .qHaptic(.selection, trigger: chainFilter)139    }140141    // MARK: Filters142143    func filters(_ snapshot: WalletSnapshot) -> some View {144        ScrollView(.horizontal, showsIndicators: false) {145            HStack(spacing: QSpace.s) {146                if fixedChain == nil, snapshot.chains.count > 1 { chainMenu(snapshot) }147                ForEach(Filter.allCases) { option in148                    Button { filter = option } label: { chip(option.rawValue, selected: filter == option) }149                        .buttonStyle(.qPressable)150                        .accessibilityAddTraits(filter == option ? .isSelected : [])151                }152            }153            .padding(.vertical, 2)154        }155        .scrollClipDisabled()156        .accessibilityElement(children: .contain)157        .accessibilityLabel("Filters")158    }159160    func chainMenu(_ snapshot: WalletSnapshot) -> some View {161        Menu {162            Picker("Network", selection: $chainFilter) {163                Text("All networks").tag(ChainID?.none)164                ForEach(snapshot.chains) { chain in Text(chain.chain.displayName).tag(ChainID?.some(chain.id)) }165            }166        } label: {167            HStack(spacing: 6) {168                if let id = chainFilter, let descriptor = id.descriptor {169                    ChainGlyph(descriptor.qNetwork, size: .mini)170                    Text(descriptor.qNetwork.fullName)171                } else {172                    Image(systemName: "point.3.connected.trianglepath.dotted").imageScale(.small)173                    Text("All networks")174                }175                Image(systemName: "chevron.down").imageScale(.small)176            }177            .font(QFont.captionStrong)178            .foregroundStyle(QColor.textPrimary)179            .padding(.horizontal, 12)180            .frame(minHeight: 36)181            .background(Capsule().fill(chainFilter == nil ? QColor.surface : QColor.surfaceRaised))182            .overlay(Capsule().strokeBorder(chainFilter == nil ? QColor.stroke : QColor.strokeStrong, lineWidth: 1))183        }184        .accessibilityLabel("Network filter: \(chainFilter?.descriptor?.displayName ?? "all networks")")185    }186187    func chip(_ title: String, selected: Bool) -> some View {188        Text(title)189            .font(QFont.captionStrong)190            .foregroundStyle(selected ? QColor.onAccent : QColor.textPrimary)191            .padding(.horizontal, 14)192            .frame(minHeight: 36)193            .background(Capsule().fill(selected ? AnyShapeStyle(QColor.accentGradient) : AnyShapeStyle(QColor.surface)))194            .overlay(Capsule().strokeBorder(selected ? Color.clear : QColor.stroke, lineWidth: 1))195            .contentShape(Capsule())196    }197198    // MARK: Notices199200    /// "History is not available on N networks", with each reason one tap away.201    func unavailableNotice(_ entries: [(ChainSnapshot, String)]) -> some View {202        let shape = RoundedRectangle(cornerRadius: QMetric.radius, style: .continuous)203        return VStack(alignment: .leading, spacing: 0) {204            Button { showsReasons.toggle() } label: {205                HStack(alignment: .firstTextBaseline, spacing: QSpace.m) {206                    Image(systemName: "clock.badge.questionmark").foregroundStyle(QColor.textSecondary)207                    VStack(alignment: .leading, spacing: 2) {208                        Text(entries.count == 1 ? "History is not available on \(entries[0].0.chain.displayName)" : "History is not available on \(entries.count) networks")209                            .font(QFont.subheadline).foregroundStyle(QColor.textPrimary).multilineTextAlignment(.leading)210                        Text("Balances are read on chain and are complete. Payments on these networks are not listed here.")211                            .font(QFont.caption).foregroundStyle(QColor.textSecondary).multilineTextAlignment(.leading)212                    }213                    Spacer(minLength: QSpace.s)214                    Image(systemName: "chevron.down").font(.footnote.weight(.semibold)).foregroundStyle(QColor.textTertiary)215                        .rotationEffect(.degrees(showsReasons ? 180 : 0))216                }217                .padding(QMetric.padding)218                .contentShape(Rectangle())219            }220            .buttonStyle(.plain)221            .accessibilityHint(showsReasons ? "Hides the reasons" : "Shows the reason for each network")222            if showsReasons {223                ForEach(entries, id: \.0.id) { chain, reason in224                    QSeparator()225                    HStack(alignment: .top, spacing: QSpace.m) {226                        ChainGlyph(chain.network, size: .small)227                        VStack(alignment: .leading, spacing: 2) {228                            Text(chain.network.fullName).font(QFont.captionStrong).foregroundStyle(QColor.textPrimary)229                            Text(reason).font(QFont.caption).foregroundStyle(QColor.textSecondary).fixedSize(horizontal: false, vertical: true)230                        }231                    }232                    .padding(QMetric.padding)233                    .accessibilityElement(children: .combine)234                }235            }236        }237        .background(QColor.surface)238        .clipShape(shape)239        .overlay(shape.strokeBorder(QColor.stroke, lineWidth: 1))240        .qAnimation(value: showsReasons)241        .id("unavailable")242    }243244    func unreadNotice(_ chains: [ChainSnapshot]) -> some View {245        let syncing = chains.filter { chain in246            if case .syncing = wallet.syncState(of: chain) { return true }247            return false248        }249        let failed = chains.filter { $0.syncError != nil }250        return VStack(alignment: .leading, spacing: QSpace.m) {251            if !syncing.isEmpty {252                SyncBanner(.syncing(progress: nil), title: syncing.count == 1 ? "Reading \(syncing[0].chain.displayName)" : "Reading \(syncing.count) networks")253            }254            if !failed.isEmpty {255                SyncBanner(.failed(reason: failed.count == 1 ? (failed[0].syncError ?? "") : failed.map(\.chain.displayName).joined(separator: ", ")),256                           title: failed.count == 1 ? "\(failed[0].chain.displayName) could not be read" : "\(failed.count) networks could not be read") {257                    Task { await wallet.synchronize(chains: failed.map(\.id)) }258                }259            }260        }261    }262263    @ViewBuilder264    func emptyState(shown: [ChainSnapshot], unavailable: Int, unread: Int) -> some View {265        let readable = shown.count - unavailable - unread266        if unread == shown.count, shown.contains(where: { chain in267            if case .syncing = wallet.syncState(of: chain) { return true }268            return false269        }) {270            QListSection { ForEach(0..<5, id: \.self) { _ in QSkeletonRow() } }271        } else if readable > 0 {272            EmptyStateView(systemImage: "tray", title: filter == .all ? "No transaction" : "Nothing matches this filter",273                           message: filter == .all274                            ? "No transaction was found on " + (readable == 1 ? "the network whose history could be read." : "the \(readable) networks whose history could be read.")275                            : "No \(filter.rawValue.lowercased()) entry in the history that was read.")276                .frame(maxWidth: .infinity)277                .padding(.vertical, QSpace.xxl)278        } else if unread == shown.count {279            EmptyStateView(systemImage: "arrow.triangle.2.circlepath", title: "Not synchronized yet", message: "Pull down to read the history of the enabled networks.")280                .frame(maxWidth: .infinity)281                .padding(.vertical, QSpace.xxl)282        }283    }284285    // MARK: Grouping286287    struct DayGroup { let title: String; let items: [ActivityItem] }288289    func groups(_ items: [ActivityItem]) -> [DayGroup] {290        var order = [String](), buckets = [String: [ActivityItem]]()291        for item in items {292            let title: String293            if let time = item.entry.time { title = WalletFormat.day(time) } else { title = item.isPending ? "Pending" : "Date not reported" }294            if buckets[title] == nil { order.append(title) }295            buckets[title, default: []].append(item)296        }297        return order.map { DayGroup(title: $0, items: buckets[$0] ?? []) }298    }299}300301/// The root list registers the wallet destinations on its own stack; a pushed per-chain list is already inside one.302private struct ActivityDestinations: ViewModifier {303    let isRoot: Bool304    let namespace: Namespace.ID305306    func body(content: Content) -> some View {307        if isRoot { content.walletDestinations(namespace: namespace) } else { content }308    }309}310
Files main
Menu

Theme