Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Terminal/TerminalSupport.swift3// Description: What the Terminal's screens share: token shorthands, number formats in the person's number locale, the cached-data chip, section headers with their freshness chip, the synced-watchlist helpers and the context menu of a symbol.4import SwiftUI5import VQuantCore6import VQuantKit7import VQuantUI89typealias TP = VQTokens.Palette10typealias TS = VQTokens.Space11typealias TT = VQTokens.Typography1213// `Hairline` lives in Components/InlineEditing.swift (shared by every feature).1415enum TerminalFormat {16 /// A level by the unit the server declared: yields in percent, FX rates with the precision pairs are quoted at.17 static func level(_ v: Double?, unit: VQMarketOverview.Item.Unit?, locale: VQNumberLocale) -> String {18 guard let v else { return VQFormat.nullText }19 switch unit {20 case .yieldPct?: return VQFormat.percentValue(v, decimals: 2, locale: locale)21 case .rate?: return VQFormat.number(v, decimals: abs(v) >= 20 ? 3 : 5, locale: locale)22 default: return price(v, locale: locale)23 }24 }25 static func price(_ v: Double?, locale: VQNumberLocale) -> String {26 guard let v else { return VQFormat.nullText }27 return VQFormat.number(v, decimals: abs(v) >= 1 ? 2 : 4, locale: locale)28 }29 /// The decimals a change needs to be read next to its level.30 static func changeDecimals(level: Double?, unit: VQMarketOverview.Item.Unit?) -> Int {31 switch unit {32 case .rate?: return abs(level ?? 1) >= 20 ? 3 : 533 default: return abs(level ?? 1) >= 1 ? 2 : 434 }35 }36 /// 79.8 M, 4.98 T — volume and market capitalisation (English suffixes: the interface is in English).37 static func compact(_ v: Double?, locale: VQNumberLocale) -> String {38 guard let v, v.isFinite else { return VQFormat.nullText }39 let a = abs(v)40 let (d, s): (Double, String) = a >= 1e12 ? (1e12, "T") : a >= 1e9 ? (1e9, "B") : a >= 1e6 ? (1e6, "M") : a >= 1e3 ? (1e3, "K") : (1, "")41 return VQFormat.number(v / d, decimals: d == 1 ? 0 : 2, locale: locale) + (s.isEmpty ? "" : "\u{00A0}" + s)42 }43}4445/// "Cached · received 14:05": the server could not be reached and this is the last answer this Mac received.46struct CachedChip: View {47 let received: Date48 var body: some View {49 HStack(spacing: 4) {50 Image(systemName: "clock.arrow.circlepath").font(.system(size: 9, weight: .semibold))51 Text("Cached").font(.system(size: 10.5, weight: .semibold))52 Text("·").font(.system(size: 10.5))53 Text("received \(VQFormat.asOf(received, language: .en))").font(.system(size: 10.5, design: .monospaced))54 }55 .foregroundStyle(TP.warn)56 .padding(.horizontal, 7).padding(.vertical, 2.5)57 .overlay { Capsule(style: .continuous).strokeBorder(TP.warn.opacity(0.55), lineWidth: 1) }58 .fixedSize()59 .help("The server could not be reached. This is the last answer this Mac received, read from its encrypted cache.")60 .accessibilityElement(children: .ignore)61 .accessibilityLabel("Cached, received \(VQFormat.asOf(received, language: .en))")62 .accessibilityIdentifier("terminal.cached")63 }64}6566/// A rule in full ink, a serif title, the freshness of what follows.67struct TerminalSectionHeader<Trailing: View>: View {68 let title: String69 var freshness: VQFreshness?70 var note: String?71 @ViewBuilder var trailing: Trailing7273 init(_ title: String, freshness: VQFreshness? = nil, note: String? = nil, @ViewBuilder trailing: () -> Trailing = { EmptyView() }) {74 self.title = title; self.freshness = freshness; self.note = note; self.trailing = trailing()75 }7677 var body: some View {78 VStack(alignment: .leading, spacing: 6) {79 Rectangle().fill(TP.text1).frame(height: VQTokens.hairline).accessibilityHidden(true)80 HStack(alignment: .firstTextBaseline, spacing: TS.s2) {81 Text(title).font(TT.title.font).tracking(TT.title.tracking).foregroundStyle(TP.text1).lineLimit(1).accessibilityAddTraits(.isHeader)82 Spacer(minLength: TS.s2)83 trailing84 if let freshness { VQProvenanceChip(freshness) }85 }86 if let note, !note.isEmpty { Text(note).font(TT.caption.font).foregroundStyle(TP.text3).lineLimit(2).fixedSize(horizontal: false, vertical: true) }87 }88 }89}9091// MARK: - synced watchlists9293extension AppEnvironment {94 /// The person's watchlists in a stable order (oldest first): a list does not jump when it is edited.95 var syncedWatchlists: [VQObject<VQWatchlist>] {96 (sync.active?.watchlists.items ?? []).sorted { ($0.createdAt, $0.id) < ($1.createdAt, $1.id) }97 }9899 /// Adds a symbol to a synced watchlist and says what happened.100 func addToWatchlist(_ raw: String, list id: String) {101 guard let lists = sync.active?.watchlists, let list = lists[id] else { toasts.show("That watchlist no longer exists.", error: true); return }102 guard let s = Watchlist.normalize(raw) else { toasts.show("“\(raw)” is not a ticker symbol.", error: true); return }103 if list.data.symbols.contains(s) { toasts.show("\(s) is already in \(list.data.name)."); return }104 if list.data.symbols.count >= VQWatchlist.maxSymbols { toasts.show("\(list.data.name) is full (\(VQWatchlist.maxSymbols) symbols).", error: true); return }105 Task {106 await lists.update(id) { $0.add(s) }107 if let e = lists.lastError { toasts.show(e.userMessage, error: true) } else { toasts.show("\(s) added to \(list.data.name).") }108 }109 }110}111112/// "Add to Watchlist ▸ <lists>" for menus and context menus.113struct WatchlistAddMenu: View {114 let app: AppEnvironment115 let symbol: String116 var body: some View {117 Menu("Add to Watchlist") {118 let lists = app.syncedWatchlists119 ForEach(lists) { w in Button(w.data.name.isEmpty ? "Untitled" : w.data.name) { app.addToWatchlist(symbol, list: w.id) } }120 if lists.isEmpty { Text(app.sync.active == nil ? "Watchlists are not loaded" : "No watchlist yet") }121 }122 }123}124125/// The context menu of a symbol anywhere in the Terminal: chart, statements, watchlist, the agent.126struct SymbolContextMenu: View {127 let app: AppEnvironment128 let model: WindowModel129 let symbol: String130 var name: String?131 /// Statements exist for operating companies only.132 var hasStatements = true133 /// What the agent is told about where the question comes from.134 var context = ""135 @Environment(\.openWindow) private var openWindow136137 var body: some View {138 Button("Chart \(symbol)") { model.show(.charting, symbol: symbol) }139 Button("Open Chart in New Window") { openWindow(id: "chart", value: ChartSpec(symbol: symbol)) }140 Button("Statements") { model.show(.statements, symbol: symbol) }.disabled(!hasStatements)141 WatchlistAddMenu(app: app, symbol: symbol)142 Divider()143 Button("Ask the Agent About \(symbol)") {144 let label = name.map { "\($0) (\(symbol))" } ?? symbol145 model.symbol = symbol146 model.ask(AskDraft(text: "What is driving \(label) right now, and what should I watch?", context: context))147 }148 Divider()149 Button("Copy Symbol") { VQPasteboard.copy(symbol) }150 }151}152