SPB Git

Repository Public

AgentStyle.swift 14.9 KB 306 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/TradingAgents/AgentStyle.swift3// Description: The visual vocabulary of the trading agents. The three execution modes (research, paper, real) each own ONE colour and ONE label, used on every row, header, figure and button, so that a simulated number can never be read as money. Also the shared small views of the section (mode-tagged figures and buttons, verbatim rendering of server JSON, server locks).4import SwiftUI5import SPWalletCore67/// A mode as it must be shown: the mode itself plus, for a live perp agent, whether the venue network is the test network.8struct ModeKind: Hashable {9    let mode: AgentMode10    var liveNetwork: String?1112    init(_ mode: AgentMode, liveNetwork: String? = nil) { self.mode = mode; self.liveNetwork = mode == .live ? liveNetwork : nil }13    init(agent a: Agent) { self.init(a.mode, liveNetwork: a.liveNetwork) }1415    var isTestnet: Bool { mode == .live && liveNetwork == "testnet" }16    /// Real money is at stake: live, and not on a venue's test network.17    var isRealMoney: Bool { mode == .live && !isTestnet }1819    var color: Color {20        switch mode {21        case .research: Color(red: 0.33, green: 0.36, blue: 0.80)22        case .paper: Color(red: 0.05, green: 0.55, blue: 0.62)23        case .live: isTestnet ? Color(red: 0.62, green: 0.45, blue: 0.10) : Color(red: 0.78, green: 0.12, blue: 0.24)24        case .unknown: .gray25        }26    }27    /// The label written on bands, headers and tags.28    var title: String {29        switch mode {30        case .research: "RECHERCHE — simulation"31        case .paper: "PAPIER — simulé"32        case .live: isTestnet ? "RÉEL · TESTNET — argent fictif" : "RÉEL — argent réel"33        case .unknown: "MODE INCONNU"34        }35    }36    /// The suffix written on buttons and next to figures.37    var short: String {38        switch mode {39        case .research: "RECHERCHE"40        case .paper: "PAPIER"41        case .live: isTestnet ? "RÉEL · TESTNET" : "RÉEL"42        case .unknown: "INCONNU"43        }44    }45    var symbol: String {46        switch mode { case .research: "testtube.2"; case .paper: "doc.plaintext"; case .live: isTestnet ? "hammer" : "bolt.fill"; case .unknown: "questionmark" }47    }48    var explanation: String {49        switch mode {50        case .research: "Recherche : backtests et décisions sur données historiques. Aucun ordre n’est émis, rien n’est signé."51        case .paper: "Papier : ordres et exécutions simulés sur des prix réels. Aucun argent ne bouge, rien n’est signé."52        case .live: isTestnet ? "Réel sur le réseau de test de la plateforme : les ordres sont signés et envoyés, mais l’argent est fictif." : "Réel : des ordres signés sous mandat atteignent une chaîne ou une plateforme. L’argent engagé peut être perdu."53        case .unknown: "Mode inconnu de cette version de l’app : rien n’est présumé simulé ni réel."54        }55    }56}5758/// The capsule that names the mode. Never colour alone: the label is always written.59struct ModeTag: View {60    let kind: ModeKind61    var compact = false62    var body: some View {63        Label(compact ? kind.short : kind.title, systemImage: kind.symbol)64            .font(.caption.weight(.bold)).foregroundStyle(.white)65            .padding(.horizontal, 8).padding(.vertical, 3).background(kind.color, in: Capsule())66            .help(kind.explanation)67            .accessibilityLabel("Mode : \(kind.title)")68    }69}7071/// A full-width band under a header: colour, label and what the mode means.72struct ModeHeaderBand: View {73    let kind: ModeKind74    var body: some View {75        HStack(spacing: 10) {76            Image(systemName: kind.symbol).font(.title3)77            VStack(alignment: .leading, spacing: 1) {78                Text(kind.title).font(.headline)79                Text(kind.explanation).font(.caption).opacity(0.92).fixedSize(horizontal: false, vertical: true)80            }81            Spacer(minLength: 0)82        }83        .foregroundStyle(.white).padding(.horizontal, 14).padding(.vertical, 9)84        .frame(maxWidth: .infinity, alignment: .leading).background(kind.color, in: RoundedRectangle(cornerRadius: 10))85        .accessibilityElement(children: .combine)86    }87}8889extension View {90    /// Frames a block of content that belongs to ONE mode: a coloured band on the leading edge and a tinted stroke.91    func modeFramed(_ kind: ModeKind) -> some View {92        self.padding(.leading, 12)93            .overlay(alignment: .leading) { RoundedRectangle(cornerRadius: 2).fill(kind.color).frame(width: 5) }94    }95}9697/// One figure with its mode written under it. A missing value shows the server's reason, never zero.98struct ModeFigure: View {99    let label: String100    let value: String?101    let kind: ModeKind102    var reason: String?103    var partial = false104    var tint: Color?105    var body: some View {106        VStack(alignment: .leading, spacing: 3) {107            Text(label).font(.caption).foregroundStyle(.secondary)108            Text(value ?? "—").font(.title3.weight(.semibold)).monospacedDigit().foregroundStyle(value == nil ? Color.secondary : (tint ?? .primary)).textSelection(.enabled)109            HStack(spacing: 4) {110                ModeTag(kind: kind, compact: true)111                if partial { Label("Partiel", systemImage: "exclamationmark.triangle.fill").font(.caption2.weight(.medium)).foregroundStyle(Theme.warning) }112            }113            if value == nil, let reason { Text(reason).font(.caption2).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }114        }115        .frame(minWidth: 150, alignment: .leading).padding(10)116        .background(kind.color.opacity(0.07), in: RoundedRectangle(cornerRadius: 8))117        .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(kind.color.opacity(0.35)))118        .accessibilityElement(children: .combine)119    }120}121122/// A button whose colour and title carry the mode it acts in.123struct ModeButton: View {124    let title: String125    let kind: ModeKind126    var systemImage: String?127    var prominent = false128    var role: ButtonRole?129    let action: () -> Void130    var body: some View {131        let label = "\(title) · \(kind.short)"132        Group {133            if prominent {134                Button(role: role, action: action) { if let systemImage { Label(label, systemImage: systemImage) } else { Text(label) } }.buttonStyle(.borderedProminent)135            } else {136                Button(role: role, action: action) { if let systemImage { Label(label, systemImage: systemImage) } else { Text(label) } }.buttonStyle(.bordered)137            }138        }.tint(kind.color)139    }140}141142enum AgentText {143    /// The historical state text of the server, in French when known, verbatim otherwise.144    static func phase(_ s: String) -> String {145        switch s {146        case "CREATED": "Créé"147        case "RESEARCH", "RESEARCHING": "En recherche"148        case "BACKTESTING": "Backtest en cours"149        case "AWAITING_APPROVAL": "En attente d’approbation de la stratégie"150        case "PAPER_TRADING", "PAPER": "Actif sur papier"151        case "LIVE": "Actif en réel"152        case "RUNNING": "En marche"153        case "PAUSED": "En pause"154        case "STOPPING": "Arrêt en cours (fermeture des positions)"155        case "STOPPED": "Arrêté"156        default: s157        }158    }159    static func lifecycle(_ s: AgentLifecycle) -> String {160        switch s { case .active: "Actif"; case .paused: "En pause"; case .stopped: "Arrêté"; case .unknown: "État inconnu" }161    }162    static func kind(_ k: AgentKind) -> String {163        switch k { case .spot: "Comptant (coffre)"; case .perp: "Perpétuels"; case .stream: "Règle en flux"; case .supervisor: "Superviseur de risque"; case .unknown: "Type inconnu" }164    }165    static func family(_ f: String?) -> String {166        switch f { case "market_making": "Tenue de marché"; case nil: "—"; default: f!.replacingOccurrences(of: "_", with: " ") }167    }168    static func returnState(_ s: VaultReturnState) -> String {169        switch s {170        case .requested: "Demandé, pas encore signé"171        case .signed: "Signé, non diffusé"172        case .broadcast: "Diffusé, non confirmé"173        case .confirmed: "Confirmé par la chaîne"174        case .failed: "Échoué"175        case .notSent: "Signé, NON diffusé (diffusion désactivée sur ce serveur)"176        case .unknown: "État inconnu"177        }178    }179    static func ms(_ v: Int?) -> Date? { v.map { Date(timeIntervalSince1970: TimeInterval($0) / 1000) } }180    static func seconds(_ v: Int) -> Date { Date(timeIntervalSince1970: TimeInterval(v)) }181    static func hex(_ d: Data) -> String { d.map { String(format: "%02x", $0) }.joined() }182    static func number(_ v: Double?, fraction: Int = 2) -> String? { v.map { $0.formatted(.number.precision(.fractionLength(0...fraction))) } }183    static func usd(_ v: Double?) -> String? { v.map { $0.formatted(.currency(code: "USD").precision(.fractionLength(2))) } }184    /// A ratio served as a fraction (0.12) shown as a percentage.185    static func ratio(_ v: Double?) -> String? { v.map { ($0 * 100).formatted(.number.precision(.fractionLength(2))) + " %" } }186    /// Parses a typed decimal ("1 000,5" or "1000.5"). Nil when it is not a finite number.187    static func decimal(_ s: String) -> Double? {188        let t = s.trimmingCharacters(in: .whitespaces).replacingOccurrences(of: ",", with: ".").replacingOccurrences(of: "\u{202F}", with: "").replacingOccurrences(of: " ", with: "")189        guard t.range(of: #"^\d+(\.\d+)?$"#, options: .regularExpression) != nil, let d = Double(t), d.isFinite else { return nil }190        return d191    }192    /// The same typed decimal as canonical text for exact comparison by the Core.193    static func decimalText(_ s: String) -> String { s.trimmingCharacters(in: .whitespaces).replacingOccurrences(of: ",", with: ".").replacingOccurrences(of: "\u{202F}", with: "").replacingOccurrences(of: " ", with: "") }194    static func https(_ s: String?) -> URL? { guard let s, let u = URL(string: s), u.scheme == "https" else { return nil }; return u }195}196197/// Server JSON shown as it is: keys and values, nothing interpreted, nothing dropped.198enum JSONFlat {199    static func text(_ v: JSONValue) -> String {200        switch v {201        case .null: "—"202        case .bool(let b): b ? "oui" : "non"203        case .int(let i): String(i)204        case .double(let d): d.formatted(.number.precision(.significantDigits(1...8)))205        case .string(let s): s.isEmpty ? "(vide)" : s206        case .array(let a): a.isEmpty ? "(aucun)" : a.allSatisfy({ $0.objectValue == nil && $0.arrayValue == nil }) ? a.map(text).joined(separator: ", ") : v.displayText207        case .object: v.displayText208        }209    }210    /// Flattens an object to `path → text` rows, in key order, down to `depth` levels.211    static func rows(_ v: JSONValue?, prefix: String = "", depth: Int = 2) -> [(key: String, value: String)] {212        guard let v, !v.isNull else { return [] }213        guard let o = v.objectValue else { return [(prefix.isEmpty ? "valeur" : prefix, text(v))] }214        var out: [(String, String)] = []215        for k in o.keys.sorted() {216            let path = prefix.isEmpty ? k : "\(prefix).\(k)", child = o[k]!217            if depth > 1, child.objectValue != nil { out += rows(child, prefix: path, depth: depth - 1) } else { out.append((path, text(child))) }218        }219        return out220    }221}222223/// A block of verbatim server data, as label/value lines.224struct JSONFacts: View {225    let value: JSONValue?226    var depth = 2227    var empty = "Aucune donnée."228    var body: some View {229        let rows = JSONFlat.rows(value, depth: depth)230        if rows.isEmpty { Text(empty).foregroundStyle(.secondary).font(.callout) }231        else {232            VStack(alignment: .leading, spacing: 5) {233                ForEach(Array(rows.enumerated()), id: \.offset) { _, r in234                    HStack(alignment: .firstTextBaseline, spacing: 12) {235                        Text(r.key).font(.callout).foregroundStyle(.secondary).frame(width: 230, alignment: .leading)236                        Text(r.value).font(Theme.monoSmall).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading).fixedSize(horizontal: false, vertical: true)237                    }238                }239            }240        }241    }242}243244/// A list of JSON objects (positions, orders of a simulated account…) as one small block each.245struct JSONList: View {246    let items: [JSONValue]247    var limit = 50248    var empty = "Aucun élément."249    var body: some View {250        if items.isEmpty { Text(empty).foregroundStyle(.secondary).font(.callout) }251        else {252            VStack(alignment: .leading, spacing: 8) {253                ForEach(Array(items.prefix(limit).enumerated()), id: \.offset) { _, it in254                    JSONFacts(value: it, depth: 1).padding(8).frame(maxWidth: .infinity, alignment: .leading).background(Color.secondary.opacity(0.06), in: RoundedRectangle(cornerRadius: 6))255                }256                if items.count > limit { Text("\(items.count - limit) autres éléments non affichés.").font(.caption).foregroundStyle(.secondary) }257            }258        }259    }260}261262/// A server lock: its state and the server's own reason. A closed path is shown closed, never hidden.263struct LockRow: View {264    let name: String265    let open: Bool266    let reason: String?267    var body: some View {268        HStack(alignment: .top, spacing: 8) {269            Image(systemName: open ? "lock.open.fill" : "lock.fill").foregroundStyle(open ? Theme.positive : Theme.warning).frame(width: 18)270            VStack(alignment: .leading, spacing: 1) {271                HStack(spacing: 6) { Text(name).font(Theme.monoSmall); Text(open ? "ouvert sur le serveur" : "FERMÉ sur le serveur").font(.caption.weight(.semibold)).foregroundStyle(open ? Theme.positive : Theme.warning) }272                if let reason, !reason.isEmpty { Text(reason).font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true).textSelection(.enabled) }273            }274            Spacer(minLength: 0)275        }.accessibilityElement(children: .combine)276    }277}278279/// A checkbox the owner must tick before an approval button enables.280struct AckToggle: View {281    @Binding var isOn: Bool282    let text: String283    var body: some View {284        Toggle(isOn: $isOn) { Text(text).fixedSize(horizontal: false, vertical: true) }.toggleStyle(.checkbox)285    }286}287288/// Title + scrolling body + pinned footer: the shape of every sheet of this section.289struct SheetScaffold<Content: View, Footer: View>: View {290    let title: String291    var width: CGFloat = 760292    var height: CGFloat = 780293    @ViewBuilder var content: Content294    @ViewBuilder var footer: Footer295    var body: some View {296        VStack(alignment: .leading, spacing: 0) {297            Text(title).font(.title2.weight(.semibold)).padding(20)298            Divider()299            ScrollView { VStack(alignment: .leading, spacing: 14) { content }.padding(20).frame(maxWidth: .infinity, alignment: .leading) }300            Divider()301            VStack(alignment: .leading, spacing: 8) { footer }.padding(16)302        }303        .frame(width: width, height: height)304    }305}306
Files main
Menu

Theme