Repository Public
1//2// VQuant iOS3// File: VQuant/Features/Markets/MarketsView.swift4// Description: Markets tab: watchlist, indices, movers, exchange hours, and symbol search.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//910import SwiftUI11import VQuantKit12import VQuantUI1314struct MarketsView: View {15 @Environment(AppModel.self) private var model16 @State private var mover: MoverKind = .gainers17 @State private var query = ""18 @State private var results: [SymbolMatch] = []19 @State private var searching = false20 @State private var searchError: String?21 @State private var creatingList = false22 @State private var listName = ""2324 var body: some View {25 List {26 if !query.isEmpty {27 searchSection28 } else {29 Section { OfflineBanner().listRowInsets(EdgeInsets()) }30 watchlistSection31 indicesSection32 moversSection33 hoursSection34 }35 }36 .listStyle(.insetGrouped)37 .navigationTitle("Marchés")38 .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always), prompt: "Symbole ou société")39 .textInputAutocapitalization(.characters)40 .autocorrectionDisabled()41 .task(id: query) { await search() }42 .refreshable { await refresh() }43 .task { await refresh() }44 .onAppear { model.startQuotePolling { model.watchlist.symbols } }45 .onDisappear { model.stopQuotePolling() }46 .task(id: model.watchlist.symbols) { await model.market.refreshQuotes(model.watchlist.symbols) }47 .toolbar {48 ToolbarItemGroup(placement: .topBarTrailing) {49 RouteLink(.terminal) { Label("Terminal", systemImage: "rectangle.grid.2x2") }.accessibilityIdentifier("markets-terminal")50 Button { model.router.showSearch = true } label: { Label("Rechercher partout", systemImage: "magnifyingglass") }.accessibilityIdentifier("markets-search-all")51 EditButton()52 }53 }54 .alert("Nouvelle liste de suivi", isPresented: $creatingList) {55 TextField("Nom", text: $listName)56 Button("Créer") { let n = listName.trimmingCharacters(in: .whitespaces); if !n.isEmpty { Task { _ = await model.watchlist.create(name: n) } } }57 Button("Annuler", role: .cancel) {}58 }59 .accessibilityIdentifier("markets")60 }6162 private func refresh() async {63 async let a: Void = model.market.refreshOverview()64 async let b: Void = model.market.refreshQuotes(model.watchlist.symbols)65 async let c: Void = model.market.refreshMovers(mover)66 _ = await (a, b, c)67 Spotlight.index(watchlist: model.watchlist.entries)68 }6970 private func search() async {71 let text = query.trimmingCharacters(in: .whitespaces)72 guard !text.isEmpty else { results = []; searchError = nil; return }73 try? await Task.sleep(for: .milliseconds(300)) // debounce; a newer keystroke cancels this task74 if Task.isCancelled { return }75 searching = true; defer { searching = false }76 do { results = try await model.market.search(text); searchError = nil }77 catch { let e = APIError.from(error); if e.kind != .cancelled { searchError = e.message; results = [] } }78 }7980 @ViewBuilder private var searchSection: some View {81 Section("Résultats") {82 if let searchError { Label(searchError, systemImage: "exclamationmark.triangle").foregroundStyle(Theme.down).font(.footnote) }83 else if results.isEmpty && searching { ProgressView() }84 else if results.isEmpty { Text("Aucun résultat pour « \(query) ».").foregroundStyle(Theme.textSecondary) }85 ForEach(results) { m in86 RouteLink(.asset(m.symbol)) { SymbolMatchRow(match: m) }87 .swipeActions { watchButton(m.symbol, m.name) }88 }89 }90 }9192 private func watchButton(_ symbol: String, _ name: String?) -> some View {93 Button {94 model.watchlist.toggle(symbol, name: name)95 Task { await model.market.refreshQuote(symbol) }96 } label: {97 Label(model.watchlist.contains(symbol) ? "Retirer" : "Suivre", systemImage: model.watchlist.contains(symbol) ? "star.slash" : "star")98 }99 .tint(Theme.orange)100 }101102 /// The synced watchlist shown here (and on Home and in the widget). Edits are queued when offline.103 private var watchlistSection: some View {104 Section {105 if model.watchlist.symbols.isEmpty {106 Text(model.watchlist.isLoaded ? "Recherchez un actif puis touchez l’étoile pour le suivre, ou glissez un symbole ici." : "Chargement de vos listes…").font(.footnote).foregroundStyle(Theme.textSecondary)107 }108 ForEach(model.watchlist.entries) { e in109 RouteLink(.asset(e.symbol)) {110 QuoteRow(symbol: e.symbol, name: e.name, quote: model.market.quotes[e.symbol]?.value, failed: model.market.quoteErrors[e.symbol] != nil)111 }112 .draggableSymbol(e.symbol)113 .accessibilityIdentifier("watch-\(e.symbol)")114 }115 .onDelete { model.watchlist.remove(at: $0) }116 .onMove { model.watchlist.move(from: $0, to: $1) }117 } header: {118 HStack {119 Menu {120 Picker("Liste", selection: Binding(get: { model.watchlist.active?.id ?? "" }, set: { model.watchlist.selectedId = $0 })) {121 ForEach(model.watchlist.lists) { l in Text(l.data.name.isEmpty ? l.id : l.data.name).tag(l.id) }122 }123 Button { listName = ""; creatingList = true } label: { Label("Nouvelle liste", systemImage: "plus") }124 if let a = model.watchlist.active, model.watchlist.lists.count > 1 {125 Button(role: .destructive) { Task { await model.watchlist.delete(a.id) } } label: { Label("Supprimer « \(a.data.name) »", systemImage: "trash") }126 }127 } label: {128 HStack(spacing: 4) { Text(model.watchlist.active?.data.name ?? "Liste de suivi").lineLimit(1); Image(systemName: "chevron.up.chevron.down").imageScale(.small) }129 .frame(minHeight: 44).contentShape(Rectangle())130 }131 .accessibilityIdentifier("watchlist-menu")132 Spacer()133 if model.watchlist.isPending { Tag(text: "En attente d’envoi", systemImage: "arrow.up.circle", color: Theme.orange).accessibilityIdentifier("watchlist-pending") }134 else if let f = model.watchlist.symbols.compactMap({ model.market.quoteFreshness[$0] }).first { ProvenanceChip(f) }135 }136 }137 .symbolDrop { model.watchlist.add($0, name: nil) }138 }139140 private var indicesSection: some View {141 Section {142 if let list = model.market.indices.value {143 ForEach(list) { q in RouteLink(.asset(q.symbol)) { QuoteRow(symbol: q.symbol, name: q.name, quote: q) } }144 } else if model.market.indices.isUnavailable {145 StateView(kind: .failed, title: "Indices indisponibles", message: model.market.indices.error?.message) { Task { await model.market.refreshOverview() } }146 } else { ProgressView() }147 } header: {148 HStack { Text("Indices"); Spacer(); FreshnessBadge(freshness: model.market.freshness(of: model.market.indices), compact: true) }149 }150 }151152 private var moversSection: some View {153 Section {154 Picker("Mouvements", selection: $mover) {155 Text("Hausses").tag(MoverKind.gainers); Text("Baisses").tag(MoverKind.losers); Text("Volumes").tag(MoverKind.actives)156 }157 .pickerStyle(.segmented)158 .onChange(of: mover) { _, k in Task { await model.market.refreshMovers(k) } }159 let state = model.market.movers[mover] ?? LoadState()160 if let list = state.value {161 ForEach(list.prefix(12)) { q in RouteLink(.asset(q.symbol)) { QuoteRow(symbol: q.symbol, name: q.name, quote: q) } }162 if state.loaded?.isFromCache == true { FreshnessBadge(freshness: .cached(savedAt: state.loaded!.fetchedAt)) }163 } else if state.isUnavailable {164 Text(state.error?.message ?? "Indisponible").font(.footnote).foregroundStyle(Theme.textSecondary)165 } else { ProgressView() }166 } header: { Text("Mouvements du jour (marché américain)") }167 }168169 @ViewBuilder private var hoursSection: some View {170 if let hours = model.market.hours.value, !hours.isEmpty {171 Section("Places boursières") {172 DisclosureGroup("Heures d’ouverture (\(hours.filter(\.isMarketOpen).count) ouvertes)") {173 ForEach(hours) { h in174 HStack {175 VStack(alignment: .leading) {176 Text(h.name ?? h.exchange).font(.subheadline)177 Text("\(h.openingHour ?? "—") – \(h.closingHour ?? "—")").font(.caption).foregroundStyle(Theme.textSecondary)178 }179 Spacer()180 Text(h.isMarketOpen ? "Ouverte" : "Fermée").font(.caption.weight(.semibold)).foregroundStyle(h.isMarketOpen ? Theme.up : Theme.textSecondary)181 }182 .accessibilityElement(children: .combine)183 }184 }185 }186 }187 }188}189190struct SymbolMatchRow: View {191 let match: SymbolMatch192 var body: some View {193 HStack {194 VStack(alignment: .leading, spacing: 2) {195 Text(match.symbol).font(.body.weight(.semibold))196 if let n = match.name { Text(n).font(.caption).foregroundStyle(Theme.textSecondary).lineLimit(1) }197 }198 Spacer()199 Text([match.exchangeCode, match.currency].compactMap { $0 }.joined(separator: " · ")).font(.caption).foregroundStyle(Theme.textSecondary)200 }201 .accessibilityElement(children: .combine)202 }203}204205/// Stand-alone search screen (quick action, ⌘K, Shortcuts).206struct SymbolSearchView: View {207 @Environment(AppModel.self) private var model208 @State private var query = ""209 @State private var results: [SymbolMatch] = []210 @State private var error: String?211 @State private var searching = false212 @FocusState private var focused: Bool213214 var body: some View {215 List {216 Section {217 TextField("Symbole ou société", text: $query)218 .textInputAutocapitalization(.characters).autocorrectionDisabled().focused($focused).submitLabel(.search)219 .accessibilityIdentifier("search-field")220 }221 if let error { Label(error, systemImage: "exclamationmark.triangle").foregroundStyle(Theme.down).font(.footnote) }222 if searching && results.isEmpty { ProgressView() }223 Section {224 ForEach(results) { m in225 RouteLink(.asset(m.symbol)) { SymbolMatchRow(match: m) }.accessibilityIdentifier("result-\(m.symbol)")226 }227 } footer: {228 if !query.isEmpty, results.isEmpty, !searching, error == nil { Text("Aucun résultat.") }229 }230 }231 .navigationTitle("Rechercher")232 .onAppear { focused = true }233 .task(id: query) {234 let text = query.trimmingCharacters(in: .whitespaces)235 guard !text.isEmpty else { results = []; error = nil; return }236 try? await Task.sleep(for: .milliseconds(300))237 if Task.isCancelled { return }238 searching = true; defer { searching = false }239 do { results = try await model.market.search(text); error = nil }240 catch let e { let a = APIError.from(e); if a.kind != .cancelled { error = a.message; results = [] } }241 }242 }243}244