Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet9// File : Features/Futures/FuturesBits.swift10// Description : Small pieces shared by the screens of the perp terminal:11// the PAPIER / RÉEL band shown on every screen, the tag that12// accompanies every simulated figure, the server's refusals13// shown verbatim, explicit checkboxes, typed decimal fields14// (never pre-filled), stat tiles, the countdown of an15// approval window, freshness marks.16// Module : Features17// 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 SPWalletCore9596/** The mode of what is on screen: word + icon + colour + frame, never colour alone. */97struct ModeBand: View {98 let mode: TradingMode99 /** `mainnet` / `testnet` of the live account in use; nil when no live account is selected. */100 var network: String?101 var compact = false102103 private var live: Bool { mode == .live }104 private var tone: Tone { live ? (network == "testnet" ? .warn : .danger) : .info }105 private var title: String {106 guard live else { return TradingMode.paper.badge }107 return network.map { TradingMode.live.badge + " · " + FuturesAccountRef.networkBadge($0) } ?? TradingMode.live.badge108 }109 private var detail: String {110 if !live { return String(localized: "Simulation — aucun fonds réel, rien n’est envoyé à une plateforme.") }111 if network == "testnet" { return String(localized: "Réseau de test de la plateforme — jetons sans valeur.") }112 if network == nil { return String(localized: "Comptes réels sur la plateforme — aucun compte sélectionné.") }113 return String(localized: "Compte réel — fonds réels sur la plateforme.")114 }115116 var body: some View {117 HStack(spacing: 8) {118 Image(systemName: live ? "bolt.shield.fill" : "doc.plaintext.fill").font(.system(size: compact ? 12 : 14, weight: .bold))119 Text(title).font(.system(size: compact ? 12 : 13.5, weight: .heavy)).tracking(0.8)120 if !compact { Text(detail).font(.system(size: 12)).fixedSize(horizontal: false, vertical: true) }121 Spacer(minLength: 0)122 }123 .foregroundStyle(tone.color)124 .padding(.horizontal, 12).padding(.vertical, compact ? 6 : 9)125 .frame(maxWidth: compact ? nil : .infinity, alignment: .leading)126 .background(tone.color.opacity(0.12), in: RoundedRectangle(cornerRadius: Theme.Radius.small, style: .continuous))127 .overlay(RoundedRectangle(cornerRadius: Theme.Radius.small, style: .continuous).strokeBorder(tone.color.opacity(live ? 0.9 : 0.45), style: StrokeStyle(lineWidth: live ? 1.5 : 1, dash: live ? [] : [5, 3])))128 .accessibilityElement(children: .ignore)129 .accessibilityLabel(title + ". " + detail)130 .accessibilityIdentifier("futures.mode.band")131 }132}133134/** Next to every figure of a paper account. */135struct PaperTag: View {136 var body: some View { Pill(text: TradingMode.paper.badge, tone: .info, icon: "doc.plaintext.fill") }137}138139struct AccountTag: View {140 let ref: FuturesAccountRef141 var body: some View {142 switch ref {143 case .paper: PaperTag()144 case .live(_, let network): Pill(text: ref.badge, tone: network == "testnet" ? .warn : .danger, icon: "bolt.shield.fill")145 }146 }147}148149/** A refusal of the server, verbatim: its sentence and its code, with the kind of refusal as the title. */150struct RefusalNotice: View {151 let refusal: DerivativesRefusal152 var body: some View {153 Notice(tone: refusal.kind == .lock || refusal.kind == .jurisdiction ? .warn : .danger, title: Self.title(refusal.kind),154 message: (refusal.reason.isEmpty ? "" : refusal.reason + " ") + "(\(refusal.code))", icon: Self.icon(refusal.kind))155 }156 static func title(_ k: DerivativesRefusal.Kind) -> String {157 switch k {158 case .risk: String(localized: "Refusé par le contrôle de risque")159 case .lock: String(localized: "Verrou serveur fermé")160 case .halted: String(localized: "Arrêt en vigueur")161 case .jurisdiction: String(localized: "Restriction de juridiction")162 case .authorization: String(localized: "Autorisation insuffisante")163 case .signer: String(localized: "Refusé par le signataire isolé")164 case .venue: String(localized: "Plateforme ou réseau indisponible")165 case .expired: String(localized: "Fenêtre d’approbation expirée")166 case .other: String(localized: "Refusé par le serveur")167 }168 }169 static func icon(_ k: DerivativesRefusal.Kind) -> String {170 switch k {171 case .lock: "lock.fill"172 case .halted: "hand.raised.fill"173 case .jurisdiction: "globe.americas.fill"174 case .authorization: "person.badge.key.fill"175 case .signer: "lock.shield.fill"176 default: "xmark.octagon.fill"177 }178 }179}180181/** An error of a futures call: a typed refusal when the server answered one, the shared `ErrorNotice` otherwise. */182struct FuturesError: View {183 let error: Error184 var retry: (() -> Void)?185 var body: some View {186 if let r = error as? DerivativesRefusal { RefusalNotice(refusal: r) }187 else if let r = DerivativesRefusal(error), r.kind != .other {188 VStack(alignment: .leading, spacing: 10) {189 RefusalNotice(refusal: r)190 if let retry { Button(String(localized: "Réessayer"), action: retry).buttonStyle(.spSecondary) }191 }192 } else { ErrorNotice(error: error, retry: retry) }193 }194}195196/** An explicit checkbox: off at the start, a 44 pt target, the whole sentence visible. */197struct CheckRow: View {198 @Binding var isOn: Bool199 let text: String200 var tone: Tone = .info201 var id: String202 var body: some View {203 Button { isOn.toggle() } label: {204 HStack(alignment: .top, spacing: 10) {205 Image(systemName: isOn ? "checkmark.square.fill" : "square").font(.system(size: 22)).foregroundStyle(isOn ? tone.color : Theme.mute)206 Text(text).font(.spCallout).foregroundStyle(Theme.ink).multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true)207 Spacer(minLength: 0)208 }209 .frame(minHeight: 44).contentShape(Rectangle())210 }211 .buttonStyle(.plain)212 .accessibilityIdentifier(id)213 .accessibilityAddTraits(isOn ? .isSelected : [])214 .accessibilityValue(isOn ? String(localized: "coché") : String(localized: "non coché"))215 }216}217218/** A typed number: empty at the start, the unit beside it, the hint under it. Nothing is ever pre-filled. */219struct TypedField: View {220 let label: String221 @Binding var text: String222 var unit: String?223 var hint: String?224 var integer = false225 var id: String226 var body: some View {227 VStack(alignment: .leading, spacing: 5) {228 Text(label).font(.spFootnote).foregroundStyle(Theme.mute)229 HStack(spacing: 8) {230 TextField(String(localized: "à saisir"), text: $text)231 .keyboardType(integer ? .numberPad : .decimalPad).font(.system(size: 17, weight: .semibold)).monospacedDigit()232 .textInputAutocapitalization(.never).autocorrectionDisabled()233 .accessibilityIdentifier(id)234 if let unit { Text(unit).font(.spCallout.weight(.semibold)).foregroundStyle(Theme.mute) }235 }236 .padding(.horizontal, 12).frame(minHeight: 46)237 .background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small, style: .continuous))238 if let hint { Text(hint).font(.system(size: 12)).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true) }239 }240 }241}242243struct StatTile: View {244 let label: String245 let value: String246 var tone: Tone?247 var tag: FuturesAccountRef?248 var body: some View {249 VStack(alignment: .leading, spacing: 3) {250 Text(label).font(.system(size: 11.5)).foregroundStyle(Theme.mute).lineLimit(1).minimumScaleFactor(0.8)251 Text(value).font(.system(size: 15, weight: .semibold)).monospacedDigit().foregroundStyle(tone?.color ?? Theme.ink).lineLimit(1).minimumScaleFactor(0.6)252 if let tag { Text(tag.badge).font(.system(size: 9.5, weight: .heavy)).tracking(0.5).foregroundStyle(tag.mode == .paper ? Theme.blue : Theme.danger) }253 }254 .frame(maxWidth: .infinity, alignment: .leading)255 .accessibilityElement(children: .combine)256 }257}258259/** Seconds left of an approval window; the content decides what to offer once it is over. */260struct Countdown<Content: View>: View {261 let until: Date262 @ViewBuilder var content: (_ secondsLeft: Int) -> Content263 var body: some View {264 TimelineView(.periodic(from: .now, by: 1)) { ctx in content(Int(until.timeIntervalSince(ctx.date).rounded(.down))) }265 }266}267268struct ExpiryRow: View {269 let until: Date270 var body: some View {271 Countdown(until: until) { left in272 FieldRow(label: String(localized: "Fenêtre d’approbation"), value: left > 0 ? String(localized: "expire dans \(left) s") : String(localized: "expirée"), tone: left > 15 ? nil : .danger)273 }274 }275}276277/** live / différé / périmé / reconnexion — a word and an icon. Nothing is shown for a figure that never came from the stream. */278struct FreshnessMark: View {279 let freshness: StreamFreshness280 var showLive = true281 var body: some View {282 switch freshness.state {283 case .live: if showLive { Label(String(localized: "en direct"), systemImage: "dot.radiowaves.left.and.right").labelStyle(.titleAndIcon).font(.system(size: 11, weight: .semibold)).foregroundStyle(Theme.emerald) }284 case .delayed: Label(String(localized: "différé"), systemImage: "clock").font(.system(size: 11, weight: .semibold)).foregroundStyle(Theme.warn)285 case .stale: Label(String(localized: "périmé"), systemImage: "clock.badge.exclamationmark").font(.system(size: 11, weight: .semibold)).foregroundStyle(Theme.warn)286 case .reconnecting: Label(String(localized: "reconnexion"), systemImage: "arrow.triangle.2.circlepath").font(.system(size: 11, weight: .semibold)).foregroundStyle(Theme.warn)287 case .none: EmptyView()288 }289 }290}291292/** A liquidation price with where it comes from; « non fourni » when none was served. */293struct LiquidationRow: View {294 let price: String?295 let provenance: LiquidationProvenance?296 /** False on a paper account: there is no venue that could report one. */297 var venueApplies = true298 var body: some View {299 if let price, let provenance {300 VStack(alignment: .leading, spacing: 2) {301 FieldRow(label: String(localized: "Prix de liquidation — \(provenance.label)"), value: Fx.exact(price), tone: provenance.tone)302 if case .serverEstimate(let method?) = provenance { Text(String(localized: "Méthode déclarée par le serveur : \(method)")).font(.system(size: 12)).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true) }303 }304 } else {305 FieldRow(label: String(localized: "Prix de liquidation"), value: venueApplies ? String(localized: "non fourni par le serveur ni par la plateforme") : String(localized: "non fourni par le serveur pour cet ordre ou cette position"), tone: .neutral)306 }307 }308}309310/** Card of rows separated by hairlines. */311struct Rows<Content: View>: View {312 @ViewBuilder var content: Content313 var body: some View { VStack(alignment: .leading, spacing: 0) { content }.spCard(padding: 16) }314}315316extension View {317 /** Standard page container of the terminal's sheets. */318 func futuresSheetPage() -> some View {319 self.padding(.horizontal, Theme.Space.gutter).padding(.vertical, 12).frame(maxWidth: 640).frame(maxWidth: .infinity)320 .toolbar { ToolbarItemGroup(placement: .keyboard) { Spacer(); KeyboardDoneButton() } }321 }322}323324/** Closes the number pad (it has no return key). */325struct KeyboardDoneButton: View {326 var body: some View {327 Button(String(localized: "Terminé")) { UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) }328 .accessibilityIdentifier("futures.keyboardDone")329 }330}331332/** The busy label of a primary button. */333struct BusyLabel: View {334 let title: String335 var icon: String?336 let busy: Bool337 var body: some View {338 HStack { if busy { ProgressView().tint(Theme.onPrimary) } else if let icon { Image(systemName: icon) }; Text(title) }339 }340}341