SPB Git

Repository Public

AgentBits.swift 13.4 KB 305 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet9// File             : Features/TradingAgents/AgentBits.swift10// Description      : Small views shared by the trading-agent screens: the mode11//                    badge and the mode band that heads every workspace, the12//                    state label, a figure with its mode written next to it,13//                    typed-limit fields, the single confirmation dialog of an14//                    action, and the labelled display of raw server detail.15// Module           : Features16// Repository       : https://git.spboucher.ai/sp-wallet-ios17// Created          : 2026-11-1818// Last Modified    : 2026-11-1819//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author           : Simon-Pierre Boucher25// Position         : Professor of Finance26// Institution      : Université du Québec en Outaouais (UQO)27// Department       : Département des sciences administratives28// Organization     : SP Boucher29//30// Website          : https://spboucher.ai31// Git              : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General          : info@spboucher.ai38// Professional     : contact@spboucher.ai39// Direct           : simon@spboucher.ai40// Research         : research@spboucher.ai41// Development      : dev@spboucher.ai42// Support          : support@spboucher.ai43// Security/Admin   : admin@spboucher.ai44// Notifications    : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification   : Public71// Distribution     : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License          : None specified (no license file in this repository)85// Maintainer       : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import SwiftUI93import SPWalletCore9495struct ModeBadgeView: View {96    let badge: AgentModeBadge97    var body: some View {98        Pill(text: badge.text, tone: badge.tone, icon: badge.icon)99            .accessibilityElement(children: .ignore)100            .accessibilityLabel(String(localized: "Mode : \(badge.text)"))101    }102}103104struct StateLabelView: View {105    let state: String106    var body: some View {107        let l = AgentStateLabel.of(state)108        Label(l.text, systemImage: l.icon).font(.system(size: 12.5, weight: .medium)).foregroundStyle(l.tone.color).lineLimit(2)109    }110}111112/** Heads a workspace: everything under it belongs to this mode and to no other. */113struct AgentModeBand: View {114    let mode: AgentMode115    var detail: String?116    private var tone: Tone { mode == .live ? .danger : mode == .paper ? .warn : mode == .research ? .info : .neutral }117    private var icon: String { mode == .live ? "bolt.fill" : mode == .paper ? "doc.plaintext.fill" : mode == .research ? "flask.fill" : "questionmark.circle" }118    var body: some View {119        HStack(alignment: .top, spacing: 10) {120            Image(systemName: icon).font(.system(size: 16, weight: .bold)).foregroundStyle(tone.color).padding(.top, 1)121            VStack(alignment: .leading, spacing: 2) {122                Text(AgentModeBadge.name(mode) + (detail.map { " · " + $0 } ?? "")).font(.system(size: 14.5, weight: .bold)).tracking(0.6).foregroundStyle(tone.color)123                Text(AgentModeBadge.meaning(mode)).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)124            }125            Spacer(minLength: 0)126        }127        .padding(12)128        .background(tone.color.opacity(0.10), in: RoundedRectangle(cornerRadius: Theme.Radius.control, style: .continuous))129        .overlay(RoundedRectangle(cornerRadius: Theme.Radius.control, style: .continuous).strokeBorder(tone.color.opacity(0.5), lineWidth: 1))130        .accessibilityElement(children: .combine)131        .accessibilityIdentifier("agent.band.\(mode.rawValue)")132    }133}134135/** One statistic, its value or the reason it is missing, and ALWAYS the mode it belongs to. */136struct FigureCell: View {137    let title: String138    let value: String?139    let reason: String?140    let mode: AgentMode141    var body: some View {142        VStack(alignment: .leading, spacing: 3) {143            Text(title).font(.spFootnote).foregroundStyle(Theme.mute)144            Text(value ?? "—").font(.system(size: 18, weight: .semibold)).monospacedDigit().foregroundStyle(Theme.ink).lineLimit(1).minimumScaleFactor(0.6)145            if value == nil, let reason { Text(reason).font(.system(size: 11.5)).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true) }146            Text(ModeGuard.label(mode)).font(.system(size: 10.5, weight: .semibold)).foregroundStyle(mode == .live ? Theme.danger : Theme.warn).fixedSize(horizontal: false, vertical: true)147        }148        .frame(maxWidth: .infinity, alignment: .leading)149        .padding(12)150        .background(Theme.elev.opacity(0.6), in: RoundedRectangle(cornerRadius: Theme.Radius.small, style: .continuous))151        .accessibilityElement(children: .combine)152    }153}154155/** A limit the owner types. Empty at start; the hint never fills the field. */156struct LimitField: View {157    let label: String158    @Binding var text: String159    var unit: String?160    var hint: String?161    var problem: String?162    var integer = false163    var id: String164    var body: some View {165        VStack(alignment: .leading, spacing: 5) {166            Text(label).font(.spCallout.weight(.medium)).foregroundStyle(Theme.ink)167            HStack(spacing: 8) {168                TextField(String(localized: "à saisir"), text: $text)169                    .keyboardType(integer ? .numberPad : .decimalPad).font(.system(size: 17, weight: .semibold)).monospacedDigit()170                    .textInputAutocapitalization(.never).autocorrectionDisabled()171                    .accessibilityIdentifier(id)172                if let unit { Text(unit).font(.spCallout).foregroundStyle(Theme.mute) }173            }174            .padding(.horizontal, 12).frame(minHeight: 46)175            .background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small, style: .continuous))176            .overlay(RoundedRectangle(cornerRadius: Theme.Radius.small, style: .continuous).strokeBorder(problem == nil ? Color.clear : Theme.danger, lineWidth: 1))177            if let problem { Label(problem, systemImage: "exclamationmark.triangle.fill").font(.spFootnote).foregroundStyle(Theme.danger).fixedSize(horizontal: false, vertical: true) }178            else if let hint { Text(hint).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true) }179        }180    }181}182183struct TextEntry: View {184    let label: String185    @Binding var text: String186    var id: String187    var body: some View {188        VStack(alignment: .leading, spacing: 5) {189            Text(label).font(.spCallout.weight(.medium)).foregroundStyle(Theme.ink)190            TextField("", text: $text).autocorrectionDisabled()191                .padding(.horizontal, 12).frame(minHeight: 46)192                .background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small, style: .continuous))193                .accessibilityIdentifier(id)194        }195    }196}197198/** A tick the owner sets himself (never pre-set). */199struct AgentCheckRow: View {200    let title: String201    var subtitle: String?202    let on: Bool203    var id: String204    let toggle: () -> Void205    var body: some View {206        Button(action: toggle) {207            HStack(alignment: .top, spacing: 10) {208                Image(systemName: on ? "checkmark.square.fill" : "square").font(.system(size: 21)).foregroundStyle(on ? Theme.blue : Theme.mute)209                VStack(alignment: .leading, spacing: 2) {210                    Text(title).font(.spBody.weight(.medium)).foregroundStyle(Theme.ink).multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true)211                    if let subtitle { Text(subtitle).font(.system(size: 11.5, design: .monospaced)).foregroundStyle(Theme.mute).multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true) }212                }213                Spacer(minLength: 0)214            }215            .frame(minHeight: 44).contentShape(Rectangle())216        }217        .buttonStyle(.plain)218        .accessibilityIdentifier(id)219        .accessibilityValue(on ? String(localized: "coché") : String(localized: "non coché"))220        .accessibilityAddTraits(on ? .isSelected : [])221    }222}223224/** One pending confirmation: what will happen, in words, before the single tap that does it. */225struct AgentConfirmation: Identifiable {226    let id = UUID()227    let title: String228    let message: String229    let button: String230    var destructive = false231    let run: () async -> Void232}233234extension View {235    func agentConfirmation(_ item: Binding<AgentConfirmation?>) -> some View {236        confirmationDialog(item.wrappedValue?.title ?? "", isPresented: Binding(get: { item.wrappedValue != nil }, set: { if !$0 { item.wrappedValue = nil } }), titleVisibility: .visible, presenting: item.wrappedValue) { c in237            Button(c.button, role: c.destructive ? .destructive : nil) { Task { await c.run() } }.accessibilityIdentifier("agent.confirm")238            Button(String(localized: "Annuler"), role: .cancel) {}239        } message: { c in Text(c.message) }240    }241}242243/** Raw detail from the server, labelled as such. */244struct ServerDetail: View {245    let title: String246    let value: JSONValue?247    var note: String?248    var body: some View {249        if let value, !value.isNull, !(value.objectValue?.isEmpty ?? false), !(value.arrayValue?.isEmpty ?? false) {250            VStack(alignment: .leading, spacing: 4) {251                Text(title).font(.spCallout.weight(.semibold)).foregroundStyle(Theme.ink)252                if let note { Text(note).font(.spFootnote).foregroundStyle(Theme.mute) }253                JSONFields(value: value)254                Text(String(localized: "Détail brut du serveur.")).font(.system(size: 11)).foregroundStyle(Theme.mute)255            }256        }257    }258}259260/** Card with a title. */261struct AgentCard<Content: View>: View {262    let title: String263    var action: (title: String, run: () -> Void)?264    @ViewBuilder var content: Content265    var body: some View {266        VStack(alignment: .leading, spacing: 10) {267            SectionHeader(title: title, action: action)268            content269        }.spCard()270    }271}272273/** A list of rows separated by hairlines. */274struct AgentRows<Item, Row: View>: View {275    let items: [Item]276    @ViewBuilder let row: (Item) -> Row277    var body: some View {278        VStack(alignment: .leading, spacing: 0) {279            ForEach(Array(items.enumerated()), id: \.offset) { i, item in280                if i > 0 { Divider() }281                row(item)282            }283        }284    }285}286287/** Result of the last action, in the server's own terms. */288struct ActionOutcome: View {289    let text: String?290    let error: Error?291    var body: some View {292        if let error { ErrorNotice(error: error).accessibilityIdentifier("agent.error") }293        else if let text { Notice(tone: .info, title: String(localized: "Réponse du serveur"), message: text).accessibilityIdentifier("agent.outcome") }294    }295}296297struct OfflineActionsNotice: View {298    @Environment(AppModel.self) private var model299    var body: some View {300        if !model.canOperate {301            Notice(tone: .warn, title: String(localized: "Lecture seule"), message: String(localized: "Sans connexion au serveur, aucune action sur les agents n’est possible. Les données affichées sont les dernières synchronisées."), icon: "wifi.slash")302        }303    }304}305
Files main
Menu

Theme