Repository Public
1//2// VQuant iOS3// File: VQuant/Next/NextComponents.swift4// Description: Interface pieces shared by the VQuant Next screens: sync status, editorial section headers, the Ember5// primary button, draggable symbols, model badges, kit job statuses.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import SwiftUI12import UniformTypeIdentifiers13import VQuantKit14import VQuantUI1516/// The state of the account's synchronisation on this device, in one line: synced, queued writes, offline, locked.17struct SyncStatusChip: View {18 @Environment(AppModel.self) private var model19 var showsLabel = true2021 struct Spec { var text: String; var detail: String; var symbol: String; var color: Color }22 static func spec(_ s: VQSyncStatus, online: Bool) -> Spec {23 let queued = s.pendingWrites24 let q = queued == 0 ? "" : " · \(queued) modification\(queued > 1 ? "s" : "") en attente"25 switch s.connection {26 case .locked: return Spec(text: "Session fermée", detail: "Reconnectez-vous : les modifications en attente sont conservées.", symbol: "lock", color: Theme.down)27 case .connected:28 return queued == 0 ? Spec(text: "Synchronisé", detail: "Ce que vous voyez est l’état du compte.", symbol: "checkmark.circle", color: Theme.textSecondary)29 : Spec(text: "Envoi\(q)", detail: "Les modifications partent vers le serveur.", symbol: "arrow.up.circle", color: Theme.orange)30 case .connecting: return Spec(text: "Connexion\(q)", detail: "Ouverture du flux de synchronisation.", symbol: "arrow.triangle.2.circlepath", color: Theme.textSecondary)31 case .reconnecting, .stopped:32 return Spec(text: (online ? "Hors synchronisation" : "Hors ligne") + q, detail: "Vos modifications sont gardées sur l’appareil et partiront au retour de la connexion.", symbol: "wifi.slash", color: Theme.warning)33 }34 }3536 var body: some View {37 let s = Self.spec(model.next.sync.status.status, online: model.network.isOnline)38 let conflicts = model.next.sync.status.conflicts.filter(\.needsAttention).count39 HStack(spacing: 6) {40 Image(systemName: s.symbol).imageScale(.small)41 if showsLabel { Text(s.text).lineLimit(1) }42 if conflicts > 0 {43 Label("\(conflicts)", systemImage: "exclamationmark.triangle.fill").labelStyle(.titleAndIcon).foregroundStyle(Theme.warning)44 .accessibilityLabel("\(conflicts) conflit\(conflicts > 1 ? "s" : "") à examiner")45 }46 }47 .font(.caption.weight(.medium))48 .foregroundStyle(s.color)49 .accessibilityElement(children: .combine)50 .accessibilityAddTraits(.isStaticText)51 .accessibilityLabel("Synchronisation : \(s.text). \(s.detail)")52 .accessibilityIdentifier("sync-chip")53 }54}5556/// Opening of a section in the editorial style of the design system: hairline, overline, serif title.57struct EditorialHeader<Trailing: View>: View {58 var title: String59 var overline: String?60 @ViewBuilder var trailing: Trailing61 init(_ title: String, overline: String? = nil, @ViewBuilder trailing: () -> Trailing = { EmptyView() }) {62 self.title = title; self.overline = overline; self.trailing = trailing()63 }64 var body: some View {65 VStack(alignment: .leading, spacing: 6) {66 Rectangle().fill(Color.primary).frame(height: 1).accessibilityHidden(true)67 ViewThatFits(in: .horizontal) {68 HStack(alignment: .firstTextBaseline, spacing: 10) { titles; Spacer(minLength: 8); trailing }69 VStack(alignment: .leading, spacing: 6) { titles; trailing }70 }71 }72 }73 private var titles: some View {74 VStack(alignment: .leading, spacing: 1) {75 if let overline { Text(overline.uppercased()).font(.caption2.weight(.semibold)).tracking(0.9).foregroundStyle(Theme.textSecondary) }76 Text(title).font(.serif(.title3)).accessibilityAddTraits(.isHeader)77 }78 }79}8081/// The primary action of a screen: the Ember fill with dark ink on top (the only place the brand orange is a fill).82struct EmberButtonStyle: ButtonStyle {83 @Environment(\.isEnabled) private var enabled84 func makeBody(configuration: Configuration) -> some View {85 configuration.label86 .font(.subheadline.weight(.semibold))87 .foregroundStyle(enabled ? Theme.emberInk : Theme.textSecondary)88 .padding(.horizontal, 16).frame(minHeight: 44)89 .background(enabled ? Theme.ember.opacity(configuration.isPressed ? 0.8 : 1) : Theme.surface2, in: RoundedRectangle(cornerRadius: 10, style: .continuous))90 .contentShape(Rectangle())91 .hoverEffect(.lift)92 }93}9495/// A quiet bordered control on the paper surface.96struct QuietButtonStyle: ButtonStyle {97 func makeBody(configuration: Configuration) -> some View {98 configuration.label99 .font(.subheadline.weight(.medium))100 .foregroundStyle(Color.primary)101 .padding(.horizontal, 12).frame(minHeight: 44)102 .background(configuration.isPressed ? Theme.surface2 : Theme.surface, in: RoundedRectangle(cornerRadius: 10, style: .continuous))103 .overlay(RoundedRectangle(cornerRadius: 10, style: .continuous).strokeBorder(Theme.border, lineWidth: 1))104 .contentShape(Rectangle())105 .hoverEffect(.highlight)106 }107}108109/// A small label in a hairline capsule (mode, model, status).110struct Tag: View {111 var text: String112 var systemImage: String?113 var color: Color = Theme.textSecondary114 var body: some View {115 HStack(spacing: 4) {116 if let systemImage { Image(systemName: systemImage).imageScale(.small) }117 Text(text)118 }119 .font(.caption2.weight(.semibold)).foregroundStyle(color)120 .padding(.horizontal, 7).padding(.vertical, 3)121 .overlay(Capsule().strokeBorder(color.opacity(0.45), lineWidth: 1))122 .accessibilityElement(children: .combine)123 .accessibilityAddTraits(.isStaticText)124 }125}126127/// Model with its provider's mark.128struct ModelBadge: View {129 @Environment(AppModel.self) private var model130 var id: String?131 var body: some View {132 HStack(spacing: 5) {133 if id == "auto" { Image(systemName: "wand.and.stars").imageScale(.small) }134 else if let p = model.next.models.provider(of: id) { VQProviderLogo(provider: p, size: 12) }135 Text(model.next.models.label(id)).lineLimit(1)136 }137 .font(.caption.weight(.medium)).foregroundStyle(Theme.textSecondary)138 .accessibilityElement(children: .combine)139 .accessibilityLabel("Modèle : \(model.next.models.label(id))")140 }141}142143extension JobStatusBadge {144 static func lab(_ s: VQOpen<VQQuantJob.Status>) -> JobStatusBadge {145 switch s.known {146 case .running: JobStatusBadge(text: "En cours", color: Theme.orange, running: true)147 case .done: JobStatusBadge(text: "Terminé", color: Theme.up)148 case .error: JobStatusBadge(text: "Échec", color: Theme.down)149 case .cancelled: JobStatusBadge(text: "Annulé", color: Theme.textSecondary)150 case .interrupted: JobStatusBadge(text: "Interrompu", color: Theme.warning)151 case nil: JobStatusBadge(text: s.rawValue.isEmpty ? "État inconnu" : s.rawValue, color: Theme.textSecondary)152 }153 }154}155156/// A ticker that can be dragged: onto the watchlist, a chart, the composer, or another app (as text).157struct DraggableSymbol: ViewModifier {158 let symbol: String159 func body(content: Content) -> some View {160 content.draggable(symbol) {161 Text(symbol).font(.mono(.callout, weight: .semibold)).padding(.horizontal, 12).padding(.vertical, 8)162 .background(Theme.surface, in: Capsule()).overlay(Capsule().strokeBorder(Theme.border, lineWidth: 1))163 }164 }165}166extension View {167 func draggableSymbol(_ symbol: String) -> some View { modifier(DraggableSymbol(symbol: symbol)) }168 /// Accepts dropped tickers (plain text that is a valid symbol).169 func symbolDrop(_ accept: @escaping @MainActor (String) -> Void) -> some View {170 dropDestination(for: String.self) { items, _ in171 let symbols = items.flatMap { $0.split(whereSeparator: { ", \n".contains($0) }) }.compactMap { WatchlistFile.normalise(String($0)) }172 guard !symbols.isEmpty else { return false }173 for s in symbols { accept(s) }174 return true175 }176 }177 /// Lists and forms on the paper tone of the design system instead of the system's grouped grey.178 func paperBackground() -> some View { scrollContentBackground(.hidden).background(Theme.background.ignoresSafeArea()) }179 /// A surface of the design system: paper fill, hairline border.180 func paperCard(padding: CGFloat = 14, radius: CGFloat = Theme.corner) -> some View {181 self.padding(padding)182 .frame(maxWidth: .infinity, alignment: .leading)183 .background(Theme.surface, in: RoundedRectangle(cornerRadius: radius, style: .continuous))184 .overlay(RoundedRectangle(cornerRadius: radius, style: .continuous).strokeBorder(Theme.border, lineWidth: 1))185 }186}187188/// The shared provenance chip (freshness kind, provider, as-of time), read by VoiceOver as one static sentence with189/// the meaning of the freshness kind.190struct ProvenanceChip: View {191 let freshness: VQFreshness192 init(_ freshness: VQFreshness) { self.freshness = freshness }193 init(kind: VQFreshness.Kind, provider: String?, asOf: Date?) { freshness = VQFreshness(kind: kind, asOf: asOf, provider: provider) }194 var body: some View {195 VQProvenanceChip(freshness)196 .accessibilityElement(children: .ignore)197 .accessibilityAddTraits(.isStaticText)198 .accessibilityLabel(freshness.displayText(.fr) + (freshness.kind.known.map { ". " + $0.explanation(.fr) } ?? ""))199 }200}201202/// iPad: opens a destination in its own window (Stage Manager, external display, side by side). Hidden where the203/// system has no multiple windows (iPhone).204struct OpenWindowButton: View {205 let route: Route206 @Environment(\.openWindow) private var openWindow207 @Environment(\.supportsMultipleWindows) private var multiWindow208 var body: some View {209 if multiWindow {210 Button { openWindow(id: "route", value: route) } label: { Label("Ouvrir dans une nouvelle fenêtre", systemImage: "macwindow.badge.plus") }211 .accessibilityIdentifier("open-window")212 }213 }214}215216/// "Copie locale" for a kit value read from the device because the network failed.217struct CachedNotice: View {218 var at: Date?219 var body: some View {220 if let at { FreshnessBadge(freshness: .cached(savedAt: at)) }221 }222}223224/// Banner listing sync conflicts that need a decision (text that differed on two devices).225struct ConflictBanner: View {226 @Environment(AppModel.self) private var model227 var body: some View {228 let list = model.next.sync.status.conflicts.filter(\.needsAttention)229 if !list.isEmpty {230 RouteLink(.syncStatus) {231 Label("\(list.count) conflit\(list.count > 1 ? "s" : "") de synchronisation à examiner", systemImage: "exclamationmark.triangle")232 .font(.footnote.weight(.medium)).foregroundStyle(Theme.warning)233 .frame(maxWidth: .infinity, alignment: .leading)234 .padding(.horizontal, 14).padding(.vertical, 10)235 .background(Theme.warning.opacity(0.12), in: RoundedRectangle(cornerRadius: 10))236 }237 .buttonStyle(.plain)238 .accessibilityIdentifier("conflict-banner")239 }240 }241}242243extension VQFormat {244 /// "il y a 3 min" in the app's language.245 static func ago(_ d: Date?) -> String { Fmt.relative(d) }246}247248/// Maps the `nav:<place>` results of the universal search onto this app's destinations.249enum SearchRouting {250 @MainActor static func open(_ r: VQSearchResult, router: Router, compact: Bool) {251 switch r.type.known {252 case .symbol: if let s = WatchlistFile.normalise(r.symbol ?? r.resultId) { router.open(.asset(s), compact: compact) }253 case .conversation: router.open(.conversation(r.resultId), compact: compact)254 case .project: router.open(.project(r.resultId), compact: compact)255 case .note: router.open(.note(r.resultId), compact: compact)256 case .watchlist: router.section = .markets257 case .portfolio: router.open(.portfolio(r.resultId), compact: compact)258 case .chart: if let s = r.symbol.flatMap(WatchlistFile.normalise) { router.open(.chart(s), compact: compact) }259 case .action:260 switch r.action {261 case .navigate(let place): navigate(place, router: router, compact: compact)262 case .openEngine(let id): router.open(.quantTool(id), compact: compact)263 default: break264 }265 default: break266 }267 }268 @MainActor static func navigate(_ place: String, router: Router, compact: Bool) {269 switch place {270 case "home": router.section = .home271 case "chat", "research", "history": router.section = .research272 case "terminal", "macro": router.open(.terminal, compact: compact)273 case "markets", "watchlists", "charts", "statements", "options": router.section = .markets274 case "quant": router.open(.quant, compact: compact)275 case "portfolio": router.section = .portfolio276 case "notes": router.open(.studio, compact: compact)277 case "agent": router.open(.agent, compact: compact)278 case "usage": router.open(.usage, compact: compact)279 case "settings", "security": router.open(.settings, compact: compact)280 default: break281 }282 }283 static func icon(_ r: VQSearchResult) -> String {284 switch r.type.known {285 case .symbol: "chart.xyaxis.line"; case .conversation: "text.bubble"; case .project: "books.vertical"; case .note: "note.text"286 case .watchlist: "star"; case .portfolio: "briefcase"; case .chart: "chart.bar.xaxis"; case .report: "doc.richtext"287 case .indicator: "waveform.path.ecg"; case .action: r.resultId.hasPrefix("engine:") ? "function" : "arrow.turn.down.right"; case nil: "questionmark"288 }289 }290 static func kind(_ r: VQSearchResult) -> String {291 switch r.type.known {292 case .symbol: "Actif"; case .conversation: "Analyse"; case .project: "Projet"; case .note: "Note"; case .watchlist: "Liste"293 case .portfolio: "Portefeuille"; case .chart: "Graphique"; case .report: "Rapport"; case .indicator: "Indicateur"294 case .action: r.resultId.hasPrefix("engine:") ? "Moteur" : "Aller à"; case nil: r.type.rawValue295 }296 }297}298