SPB Git

Repository Public

OverviewView.swift 38.7 KB 695 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Terminal/OverviewView.swift3// Description: The market overview of the Terminal (GET /api/v2/market/overview): session status, indices, the Treasury curve, rates, currencies, commodities, crypto, volatility, sectors, movers and the economic calendar, each with its freshness or the server's reason for being unavailable; then what 1.0.1 showed of the person's own work (analyses in progress, portfolio, watchlist, conversations).4import SwiftUI5import VQuantCore6import VQuantKit7import VQuantUI89struct OverviewView: View {10    let app: AppEnvironment11    let model: WindowModel1213    var body: some View {14        let store = app.terminal15        GeometryReader { g in16            ScrollViewReader { proxy in17            ScrollView {18                VStack(alignment: .leading, spacing: TS.s8) {19                    OverviewHeader(app: app, store: store)20                    RunningStrip(app: app, model: model)21                    if let read = store.overview {22                        OverviewSections(app: app, model: model, overview: read.value, width: g.size.width - 2 * TS.s8)23                    } else if let e = store.overviewError {24                        VQEmptyState(systemImage: "exclamationmark.triangle", title: "The market overview is unavailable", message: e) {25                            Button("Try Again") { Task { await store.loadOverview() } }26                        }27                        .accessibilityIdentifier("overview.error")28                    } else {29                        VStack(alignment: .leading, spacing: TS.s4) { VQSkeletonRows(rows: 3, columns: 5); VQSkeletonChart(height: 200); VQSkeletonRows(rows: 6, columns: 4) }30                    }31                    WorkspaceRow(app: app, model: model, wide: g.size.width >= 900).id("overview.anchor.workspace")32                }33                .padding(.horizontal, TS.s8).padding(.top, TS.s6).padding(.bottom, TS.s10)34                .frame(maxWidth: 1480, alignment: .leading)35                .frame(maxWidth: .infinity)36            }37            // DEBUG launch argument for captures: `-VQXOverviewAnchor fx|sectors|movers|workspace` opens the page lower down38            .task(id: store.overview != nil) {39                guard store.overview != nil, let a = app.options.extra["OverviewAnchor"] else { return }40                try? await Task.sleep(for: .milliseconds(400))41                proxy.scrollTo("overview.anchor.\(a)", anchor: .top)42            }43            }44        }45        .background(TP.ink0)46        .task {47            // the server keeps the overview 45 s; asking more often than that returns the same snapshot48            while !Task.isCancelled {49                let offlineCheck = app.options.extra["TerminalOffline"] != nil      // DEBUG: reload soon, to look at the cached state50                if NSApp.isActive || store.overview == nil || offlineCheck { await store.loadOverview() }51                let every = app.settings.quoteRefresh52                try? await Task.sleep(for: .seconds(offlineCheck ? 4 : every > 0 ? max(45, every) : 3600))53            }54        }55    }56}5758// MARK: - header5960private struct OverviewHeader: View {61    let app: AppEnvironment62    let store: TerminalStore6364    var body: some View {65        HStack(alignment: .lastTextBaseline, spacing: TS.s3) {66            VStack(alignment: .leading, spacing: 6) {67                Text("Market overview").font(TT.displayMd.font).tracking(TT.displayMd.tracking).foregroundStyle(TP.text1)68                HStack(spacing: TS.s2) {69                    if let s = store.overview?.value.status {70                        SessionBadge(status: s)71                        if let n = s.note { Text(n).font(TT.caption.font).foregroundStyle(TP.text2).lineLimit(1) }72                    }73                }74            }75            Spacer(minLength: TS.s3)76            if let read = store.overview {77                if read.fromCache { CachedChip(received: read.receivedAt) }78                else if let t = read.value.asOf {79                    Text("Server snapshot \(VQFormat.asOf(t, language: .en))").font(TT.caption.font).monospacedDigit().foregroundStyle(TP.text3)80                        .help("The server assembles the overview from its providers and keeps it 45 seconds. Each section states its own freshness.")81                }82            }83            Button { Task { await store.loadOverview() } } label: { Image(systemName: "arrow.clockwise") }84                .buttonStyle(.borderless).disabled(store.overviewLoading).help("Ask the server for the overview again")85                .accessibilityLabel("Refresh the overview").accessibilityIdentifier("overview.refresh")86        }87    }88}8990/// The session of the US equity market as the server states it. Never "live": the feed is polled.91private struct SessionBadge: View {92    let status: VQMarketOverview.Status93    @Environment(\.vqTheme) private var theme9495    private var label: String {96        switch status.session {97        case .known(.pre): "Pre-market"98        case .known(.regular): "Regular session"99        case .known(.post): "After-hours"100        case .known(.closed): "Closed"101        case .unknown(let raw): raw.capitalized102        }103    }104    var body: some View {105        HStack(spacing: 5) {106            Circle().fill(status.isOpen ? theme.color(.up) : Color.clear).overlay { Circle().strokeBorder(status.isOpen ? Color.clear : TP.text3, lineWidth: 1.2) }.frame(width: 7, height: 7)107            Text("US equities").font(.system(size: 11)).foregroundStyle(TP.text2)108            Text(label).font(.system(size: 11, weight: .semibold)).foregroundStyle(TP.text1)109        }110        .padding(.horizontal, 8).padding(.vertical, 3)111        .background(Capsule(style: .continuous).fill(TP.ink2))112        .overlay { Capsule(style: .continuous).strokeBorder(TP.line, lineWidth: 1) }113        .fixedSize()114        .accessibilityElement(children: .ignore)115        .accessibilityLabel("US equities: \(label)")116        .accessibilityIdentifier("overview.session")117    }118}119120// MARK: - sections121122private struct OverviewSections: View {123    let app: AppEnvironment124    let model: WindowModel125    let overview: VQMarketOverview126    let width: CGFloat127128    private var known: Set<String> { ["indices", "sectors", "rates", "fx", "commodities", "crypto", "volatility", "movers"] }129130    var body: some View {131        let wide = width >= 900, medium = width >= 640132        VStack(alignment: .leading, spacing: TS.s8) {133            if let s = overview.section("indices") { IndicesSection(app: app, model: model, section: s) }134135            Columns(horizontal: wide) {136                YieldCurveSection(app: app, curve: overview.yieldCurve).frame(maxWidth: .infinity, alignment: .topLeading)137                VStack(alignment: .leading, spacing: TS.s6) {138                    if let s = overview.section("rates") { ItemList(app: app, model: model, section: s) }139                    if let s = overview.section("volatility") { ItemList(app: app, model: model, section: s) }140                }141                .frame(maxWidth: wide ? 400 : .infinity, alignment: .topLeading)142            }143144            Columns(horizontal: medium) {145                ForEach(["fx", "commodities", "crypto"], id: \.self) { id in146                    if let s = overview.section(id) { ItemList(app: app, model: model, section: s).frame(maxWidth: .infinity, alignment: .topLeading) }147                }148            }149            .id("overview.anchor.fx")150151            Columns(horizontal: wide) {152                if let s = overview.section("sectors") { SectorsSection(app: app, section: s).frame(maxWidth: wide ? 400 : .infinity, alignment: .topLeading) }153                CalendarSection(app: app, events: overview.calendar, freshness: overview.calendarFreshness).frame(maxWidth: .infinity, alignment: .topLeading)154            }155            .id("overview.anchor.sectors")156157            if let s = overview.section("movers") { MoversSection(app: app, model: model, section: s, horizontal: medium).id("overview.anchor.movers") }158159            // a section added by the server later is shown as a plain list rather than dropped160            ForEach(overview.sections.filter { !known.contains($0.id) }) { s in ItemList(app: app, model: model, section: s) }161        }162    }163}164165private struct Columns<Content: View>: View {166    let horizontal: Bool167    @ViewBuilder var content: Content168    var body: some View {169        if horizontal { HStack(alignment: .top, spacing: TS.s8) { content } } else { VStack(alignment: .leading, spacing: TS.s8) { content } }170    }171}172173/// "Unavailable" with the reason the server gave, in place of a section's rows.174private struct UnavailableRow: View {175    let reason: String?176    var body: some View {177        HStack(alignment: .firstTextBaseline, spacing: 6) {178            Image(systemName: "minus.circle").foregroundStyle(TP.text3)179            Text("Unavailable").font(TT.bodySm.font.weight(.semibold)).foregroundStyle(TP.text2)180            Text(reason ?? "The provider did not return this section.").font(TT.bodySm.font).foregroundStyle(TP.text2).fixedSize(horizontal: false, vertical: true)181        }182        .padding(.vertical, 6)183        .accessibilityElement(children: .combine)184    }185}186187/// Hover fill and pointer feedback of a row that opens something.188private struct RowHover: ViewModifier {189    @State private var over = false190    func body(content: Content) -> some View {191        content.background(RoundedRectangle(cornerRadius: 4, style: .continuous).fill(over ? TP.ink3 : Color.clear).padding(.horizontal, -6)).onHover { over = $0 }192    }193}194195/// A change with its arrow and the person's up/down colour; the text is formatted by the caller (points, basis points…).196struct TDelta: View {197    let value: Double?198    let text: String199    var size: CGFloat = 12200    @Environment(\.vqTheme) private var theme201    private var direction: VQDirection { guard let value, value != 0 else { return .flat }; return value > 0 ? .up : .down }202    var body: some View {203        HStack(spacing: 3) {204            if value != nil, direction != .flat { VQDirectionGlyph(direction, size: size * 0.62) }205            Text(value == nil ? VQFormat.nullText : text).font(.system(size: size, design: .monospaced)).monospacedDigit()206        }207        .foregroundStyle(value == nil || direction == .flat ? TP.text3 : theme.color(direction))208        .fixedSize()209        .accessibilityElement(children: .ignore)210        .accessibilityLabel(value == nil ? "change not available" : direction == .up ? "up \(text)" : direction == .down ? "down \(text)" : "unchanged")211    }212}213214private func chartable(_ item: VQMarketOverview.Item) -> String? {215    // Treasury yields and the 2s10s spread are levels of the overview, not series the data layer charts216    guard let s = item.symbol, item.unit != .yieldPct else { return nil }217    return s218}219220private func itemContext(_ item: VQMarketOverview.Item, section: VQMarketOverview.Section, locale: VQNumberLocale) -> String {221    var parts = ["Market overview, section \(section.title): \(item.name)" + (item.symbol.map { " (\($0))" } ?? "")]222    if let p = item.price { parts.append("level \(TerminalFormat.level(p, unit: item.unit?.known, locale: .enCA))") }223    if let c = item.changePct { parts.append("change \(VQFormat.percentValue(c, signed: true, locale: .enCA))") }224    if let f = section.freshness { parts.append("freshness: \(f.displayText(.en))") }225    return parts.joined(separator: "; ") + "."226}227228// MARK: indices229230private struct IndicesSection: View {231    let app: AppEnvironment232    let model: WindowModel233    let section: VQMarketOverview.Section234235    var body: some View {236        let locale = app.vqTheme.numberLocale237        VStack(alignment: .leading, spacing: TS.s3) {238            TerminalSectionHeader(section.title, freshness: section.freshness)239            if !section.available || section.items.isEmpty { UnavailableRow(reason: section.freshness?.note) } else {240                // a hairline grid: each cell draws its right and bottom edge on one shared surface241                LazyVGrid(columns: [GridItem(.adaptive(minimum: 172), spacing: 0)], spacing: 0) {242                    ForEach(section.items) { item in243                        Button { if let s = chartable(item) { model.show(.charting, symbol: s) } } label: {244                            VStack(alignment: .leading, spacing: 3) {245                                Text(item.name).font(TT.caption.font).foregroundStyle(TP.text2).lineLimit(1)246                                Text(TerminalFormat.level(item.price, unit: item.unit?.known, locale: locale)).font(TT.numMd.font).monospacedDigit().foregroundStyle(TP.text1).lineLimit(1)247                                HStack(spacing: 8) {248                                    TDelta(value: item.change, text: VQFormat.number(item.change, decimals: 2, signed: true, locale: locale), size: 11.5)249                                    TDelta(value: item.changePct, text: VQFormat.percentValue(item.changePct, signed: true, locale: locale), size: 11.5)250                                }251                            }252                            .padding(.horizontal, 12).padding(.vertical, 10)253                            .frame(maxWidth: .infinity, alignment: .leading)254                            .overlay(alignment: .trailing) { Rectangle().fill(TP.line).frame(width: VQTokens.hairline) }255                            .overlay(alignment: .bottom) { Hairline() }256                            .contentShape(Rectangle())257                        }258                        .buttonStyle(.plain)259                        .contextMenu { if let s = chartable(item) { SymbolContextMenu(app: app, model: model, symbol: s, name: item.name, hasStatements: false, context: itemContext(item, section: section, locale: locale)) } }260                        .accessibilityElement(children: .ignore)261                        .accessibilityLabel("\(item.name), \(TerminalFormat.level(item.price, unit: item.unit?.known, locale: locale)), \(VQFormat.percentValue(item.changePct, signed: true, locale: locale))")262                        .accessibilityAddTraits(.isButton)263                        .accessibilityIdentifier("overview.item.\(item.symbol ?? item.name)")264                    }265                }266                .background(TP.ink1)267                .overlay { Rectangle().strokeBorder(TP.line, lineWidth: 1) }268            }269        }270    }271}272273// MARK: lists (rates, volatility, currencies, commodities, crypto)274275private struct ItemList: View {276    let app: AppEnvironment277    let model: WindowModel278    let section: VQMarketOverview.Section279280    var body: some View {281        let locale = app.vqTheme.numberLocale282        VStack(alignment: .leading, spacing: TS.s2) {283            TerminalSectionHeader(section.title, freshness: section.freshness)284            if !section.available || section.items.isEmpty { UnavailableRow(reason: section.freshness?.note) } else {285                VStack(spacing: 0) {286                    ForEach(Array(section.items.enumerated()), id: \.offset) { i, item in287                        if i > 0 { Hairline() }288                        row(item, locale)289                    }290                }291            }292        }293    }294295    @ViewBuilder private func row(_ item: VQMarketOverview.Item, _ locale: VQNumberLocale) -> some View {296        let unit = item.unit?.known297        let content = HStack(spacing: 8) {298            Text(item.name).font(TT.bodySm.font).foregroundStyle(TP.text1).lineLimit(1)299            Spacer(minLength: 4)300            Text(TerminalFormat.level(item.price, unit: unit, locale: locale)).font(.system(size: 12.5, weight: .medium, design: .monospaced)).monospacedDigit().foregroundStyle(TP.text1)301            if unit == .yieldPct {302                // yields: the change is in percentage points; said in basis points, the unit rates are read in303                TDelta(value: item.change, text: VQFormat.number(item.change.map { $0 * 100 }, decimals: 0, signed: true, locale: locale) + "\u{00A0}bp").frame(width: 92, alignment: .trailing)304                    .help("Change against the previous day, in basis points")305            } else {306                TDelta(value: item.changePct, text: VQFormat.percentValue(item.changePct, signed: true, locale: locale)).frame(width: 92, alignment: .trailing)307            }308        }309        .frame(height: 28)310        .contentShape(Rectangle())311        if let s = chartable(item) {312            Button { model.show(.charting, symbol: s) } label: { content }313                .buttonStyle(.plain).modifier(RowHover())314                .contextMenu { SymbolContextMenu(app: app, model: model, symbol: s, name: item.name, hasStatements: false, context: itemContext(item, section: section, locale: locale)) }315                .help(detail(item, locale))316                .accessibilityIdentifier("overview.item.\(s)")317        } else {318            content.help(item.extra["formula"]?.stringValue ?? detail(item, locale)).accessibilityElement(children: .combine)319        }320    }321322    private func detail(_ item: VQMarketOverview.Item, _ locale: VQNumberLocale) -> String {323        let unit = item.unit?.known324        var parts: [String] = []325        if let s = item.symbol { parts.append(s) }326        if let lo = item.extra["dayLow"]?.doubleValue, let hi = item.extra["dayHigh"]?.doubleValue { parts.append("day range \(TerminalFormat.level(lo, unit: unit, locale: locale)) – \(TerminalFormat.level(hi, unit: unit, locale: locale))") }327        if let p = item.extra["previousClose"]?.doubleValue { parts.append("previous close \(TerminalFormat.level(p, unit: unit, locale: locale))") }328        if let c = item.change, unit != .yieldPct { parts.append("change \(VQFormat.number(c, decimals: TerminalFormat.changeDecimals(level: item.price, unit: unit), signed: true, locale: locale))") }329        if let d = item.extra["previousDate"]?.stringValue { parts.append("against \(d)") }330        return parts.joined(separator: " · ")331    }332}333334// MARK: yield curve335336private struct YieldCurveSection: View {337    let app: AppEnvironment338    let curve: VQMarketOverview.YieldCurve?339340    private func day(_ iso: String) -> String {341        VQISODate.parse(iso).map { $0.formatted(Date.FormatStyle(date: .abbreviated, time: .omitted, locale: Locale(identifier: "en_US"), timeZone: TimeZone(identifier: "UTC")!)) } ?? iso342    }343344    var body: some View {345        VStack(alignment: .leading, spacing: TS.s3) {346            TerminalSectionHeader("US Treasury yield curve", freshness: curve?.freshness)347            if let curve, curve.points.contains(where: { $0.yield != nil }) {348                HStack(spacing: TS.s4) {349                    legend(dashed: false, text: day(curve.date))350                    if let p = curve.previous { legend(dashed: true, text: day(p.date)).help("The latest day at least four weeks before the curve's date") }351                    Spacer()352                    Text("Par yields, % · log maturity axis").font(TT.caption.font).foregroundStyle(TP.text3).lineLimit(1)353                }354                YieldCurveChart(curve: curve, locale: app.vqTheme.numberLocale).frame(height: 250)355            } else {356                UnavailableRow(reason: curve?.freshness?.note ?? "The provider returned no Treasury curve.")357            }358        }359    }360361    private func legend(dashed: Bool, text: String) -> some View {362        HStack(spacing: 6) {363            ZStack {364                Path { p in p.move(to: CGPoint(x: 0, y: 5)); p.addLine(to: CGPoint(x: 22, y: 5)) }365                    .stroke(dashed ? TP.text3 : TP.text1, style: StrokeStyle(lineWidth: dashed ? 1.25 : 2, dash: dashed ? [4, 3] : []))366                Circle().fill(dashed ? TP.ink0 : TP.text1).overlay { Circle().strokeBorder(dashed ? TP.text3 : TP.text1, lineWidth: 1.25) }.frame(width: 6, height: 6)367            }368            .frame(width: 22, height: 10)369            Text(text).font(TT.caption.font).foregroundStyle(dashed ? TP.text2 : TP.text1)370        }371        .accessibilityElement(children: .combine)372    }373}374375// MARK: sectors376377private struct SectorsSection: View {378    let app: AppEnvironment379    let section: VQMarketOverview.Section380    @Environment(\.vqTheme) private var theme381382    var body: some View {383        let locale = app.vqTheme.numberLocale384        let items = section.items.sorted { ($0.changePct ?? -.infinity) > ($1.changePct ?? -.infinity) }385        let scale = max(items.compactMap { $0.changePct.map(abs) }.max() ?? 1, 0.01)386        VStack(alignment: .leading, spacing: TS.s2) {387            TerminalSectionHeader(section.title, freshness: section.freshness, note: section.freshness?.note)388            if !section.available || items.isEmpty { UnavailableRow(reason: section.freshness?.note) } else {389                VStack(spacing: 0) {390                    ForEach(Array(items.enumerated()), id: \.offset) { i, item in391                        if i > 0 { Hairline() }392                        HStack(spacing: 8) {393                            Text(item.name).font(TT.bodySm.font).foregroundStyle(TP.text1).lineLimit(1).frame(maxWidth: .infinity, alignment: .leading)394                            // a diverging bar around zero: length is the change, the side is its sign395                            GeometryReader { g in396                                let half = g.size.width / 2, v = item.changePct ?? 0, w = max(1, CGFloat(abs(v) / scale) * half)397                                ZStack(alignment: .leading) {398                                    Rectangle().fill(TP.lineStrong).frame(width: 1).offset(x: half)399                                    Rectangle().fill(theme.color(v >= 0 ? .up : .down).opacity(0.85)).frame(width: w, height: 8).offset(x: v >= 0 ? half : half - w)400                                }401                                .frame(maxHeight: .infinity)402                            }403                            .frame(width: 96, height: 14).accessibilityHidden(true)404                            TDelta(value: item.changePct, text: VQFormat.percentValue(item.changePct, signed: true, locale: locale)).frame(width: 78, alignment: .trailing)405                        }406                        .frame(height: 26)407                        .accessibilityElement(children: .combine)408                    }409                }410            }411        }412    }413}414415// MARK: movers416417private struct MoversSection: View {418    let app: AppEnvironment419    let model: WindowModel420    let section: VQMarketOverview.Section421    let horizontal: Bool422423    private let groups = [("gainers", "Gainers"), ("losers", "Losers"), ("actives", "Most active")]424425    var body: some View {426        let locale = app.vqTheme.numberLocale427        VStack(alignment: .leading, spacing: TS.s3) {428            TerminalSectionHeader(section.title, freshness: section.freshness, note: section.freshness?.note)429            if !section.available || section.items.isEmpty { UnavailableRow(reason: section.freshness?.note) } else {430                Columns(horizontal: horizontal) {431                    ForEach(groups, id: \.0) { key, title in432                        let items = section.items.filter { $0.group == key }433                        VStack(alignment: .leading, spacing: 4) {434                            Text(title).font(TT.overline.font).tracking(TT.overline.tracking).textCase(.uppercase).foregroundStyle(TP.text3)435                            VStack(spacing: 0) {436                                ForEach(Array(items.enumerated()), id: \.offset) { i, item in437                                    if i > 0 { Hairline() }438                                    if let s = item.symbol {439                                        Button { model.show(.charting, symbol: s) } label: {440                                            HStack(spacing: 8) {441                                                Text(s).font(.system(size: 12, weight: .semibold, design: .monospaced)).foregroundStyle(TP.text1).frame(width: 52, alignment: .leading)442                                                Text(item.name).font(TT.caption.font).foregroundStyle(TP.text2).lineLimit(1).frame(maxWidth: .infinity, alignment: .leading)443                                                Text(TerminalFormat.price(item.price, locale: locale)).font(.system(size: 12, design: .monospaced)).monospacedDigit().foregroundStyle(TP.text1)444                                                TDelta(value: item.changePct, text: VQFormat.percentValue(item.changePct, signed: true, locale: locale)).frame(width: 86, alignment: .trailing)445                                            }446                                            .frame(height: 26).contentShape(Rectangle())447                                        }448                                        .buttonStyle(.plain).modifier(RowHover())449                                        .contextMenu { SymbolContextMenu(app: app, model: model, symbol: s, name: item.name, context: itemContext(item, section: section, locale: locale)) }450                                        .accessibilityIdentifier("overview.mover.\(key).\(s)")451                                    }452                                }453                            }454                            if items.isEmpty { Text("None reported.").font(TT.caption.font).foregroundStyle(TP.text3) }455                        }456                        .frame(maxWidth: .infinity, alignment: .topLeading)457                    }458                }459            }460        }461    }462}463464// MARK: calendar465466private struct CalendarSection: View {467    let app: AppEnvironment468    let events: [VQMarketOverview.CalendarEvent]469    let freshness: VQFreshness?470    @State private var highOnly = true471    @State private var expanded = false472473    private static let dayFormat: Date.FormatStyle = .dateTime.weekday(.wide).month(.wide).day().locale(Locale(identifier: "en_US"))474    private static let timeFormat: Date.FormatStyle = .dateTime.hour(.twoDigits(amPM: .omitted)).minute(.twoDigits).locale(Locale(identifier: "en_GB"))475476    private struct Day: Identifiable { let id: String; var events: [(Int, VQMarketOverview.CalendarEvent, Date)] }477478    var body: some View {479        let locale = app.vqTheme.numberLocale480        let now = Date()481        // releases of the last six hours stay on screen: their actual figure has just been published482        let dated = events.enumerated().compactMap { i, e in e.when.map { (i, e, $0) } }.sorted { $0.2 < $1.2 }483        let relevant = dated.filter { $0.2 > now.addingTimeInterval(-6 * 3600) && (!highOnly || ($0.1.impact ?? "").lowercased() == "high") }484        let shown = expanded ? relevant : Array(relevant.prefix(12))485        let days = shown.reduce(into: [Day]()) { out, x in486            let key = x.2.formatted(Self.dayFormat)487            if out.last?.id == key { out[out.count - 1].events.append(x) } else { out.append(Day(id: key, events: [x])) }488        }489        VStack(alignment: .leading, spacing: TS.s2) {490            TerminalSectionHeader("Economic calendar", freshness: freshness) {491                VQSegmentedControl("Impact", selection: $highOnly, options: [.init(true, "High impact"), .init(false, "All")]).scaleEffect(0.9, anchor: .trailing)492            }493            if events.isEmpty { UnavailableRow(reason: freshness?.note ?? "The provider returned no scheduled release.") }494            else if relevant.isEmpty { Text(highOnly ? "No high-impact release is scheduled in the coming days." : "No release is scheduled in the coming days.").font(TT.bodySm.font).foregroundStyle(TP.text2).padding(.vertical, 6) }495            else {496                HStack(spacing: 8) {497                    Text("Time").frame(width: 44, alignment: .leading)498                    Text("").frame(width: 26)499                    Text("Release").frame(maxWidth: .infinity, alignment: .leading)500                    Text("Actual").frame(width: 70, alignment: .trailing)501                    Text("Consensus").frame(width: 88, alignment: .trailing)502                    Text("Previous").frame(width: 76, alignment: .trailing)503                }504                .font(TT.overline.font).tracking(TT.overline.tracking).textCase(.uppercase).foregroundStyle(TP.text3).padding(.top, 2)505                ForEach(days) { day in506                    VStack(spacing: 0) {507                        Text(day.id).font(.system(size: 11, weight: .semibold)).foregroundStyle(TP.text2).frame(maxWidth: .infinity, alignment: .leading).padding(.top, 6).padding(.bottom, 3)508                        Hairline(strong: true)509                        ForEach(Array(day.events.enumerated()), id: \.element.0) { i, x in510                            if i > 0 { Hairline() }511                            row(x.1, at: x.2, past: x.2 <= now, locale)512                        }513                    }514                }515                HStack(spacing: TS.s3) {516                    if relevant.count > 12 {517                        Button(expanded ? "Show fewer" : "Show all \(relevant.count)") { expanded.toggle() }.buttonStyle(.link).font(TT.caption.font)518                    }519                    Text("Times in your time zone (\(TimeZone.current.abbreviation() ?? "local")). Consensus figures are estimates, not observations.").font(TT.caption.font).foregroundStyle(TP.text3)520                }521                .padding(.top, 4)522            }523        }524    }525526    private func figure(_ v: Double?, _ unit: String?, _ locale: VQNumberLocale) -> String {527        guard let v else { return VQFormat.nullText }528        let decimals = v.rounded() == v ? 0 : abs(v) < 10 ? 2 : 1529        // short units (%, K, M, B) sit next to the figure; a worded unit ("Index", "Points") is in the row's tooltip530        return VQFormat.number(v, decimals: decimals, locale: locale) + (unit.flatMap { $0.count <= 2 ? "\u{00A0}" + $0 : nil } ?? "")531    }532533    private func row(_ e: VQMarketOverview.CalendarEvent, at when: Date, past: Bool, _ locale: VQNumberLocale) -> some View {534        let high = (e.impact ?? "").lowercased() == "high"535        return HStack(spacing: 8) {536            Text(when.formatted(Self.timeFormat)).font(.system(size: 12, design: .monospaced)).monospacedDigit().foregroundStyle(past ? TP.text3 : TP.text1).frame(width: 44, alignment: .leading)537            Text(e.country ?? "").font(.system(size: 10.5, weight: .semibold, design: .monospaced)).foregroundStyle(TP.text2).frame(width: 26, alignment: .leading)538            HStack(spacing: 5) {539                // impact is said with a shape, not a colour: filled = high, hollow = medium540                Circle().fill(high ? TP.text1 : Color.clear).overlay { Circle().strokeBorder(high ? TP.text1 : TP.text3, lineWidth: 1) }.frame(width: 6, height: 6)541                    .help("\(e.impact ?? "Unrated") impact").accessibilityLabel("\(e.impact ?? "unrated") impact")542                Text(e.event).font(TT.bodySm.font).foregroundStyle(TP.text1).lineLimit(1).help([e.event, e.unit.flatMap { $0.count > 2 ? "unit: \($0)" : nil }, e.currency].compactMap { $0 }.joined(separator: " · "))543            }544            .frame(maxWidth: .infinity, alignment: .leading)545            Text(figure(e.actual, e.unit, locale)).fontWeight(e.actual == nil ? .regular : .semibold).foregroundStyle(e.actual == nil ? TP.text3 : TP.text1).frame(width: 70, alignment: .trailing)546            Text(figure(e.estimate, e.unit, locale)).foregroundStyle(e.estimate == nil ? TP.text3 : TP.text2).frame(width: 88, alignment: .trailing)547            Text(figure(e.previous, e.unit, locale)).foregroundStyle(e.previous == nil ? TP.text3 : TP.text2).frame(width: 76, alignment: .trailing)548        }549        .font(.system(size: 12, design: .monospaced)).monospacedDigit()550        .frame(height: 26)551        .accessibilityElement(children: .combine)552    }553}554555// MARK: - the person's own work (kept from 1.0.1)556557/// Analyses and computations running on the server, shown only while there are some.558private struct RunningStrip: View {559    let app: AppEnvironment560    let model: WindowModel561    var body: some View {562        let gens = app.research.generations.filter { $0.status == .running }563        let jobs = app.quant.jobs.filter { $0.status == .running }564        if !gens.isEmpty || !jobs.isEmpty {565            VStack(alignment: .leading, spacing: TS.s2) {566                TerminalSectionHeader("In progress") { Button("Open Jobs") { model.show(.jobs) }.buttonStyle(.link).font(TT.caption.font) }567                ForEach(gens) { g in568                    Button { app.research.attach(g); model.openConversation(g.sessionId) } label: {569                        HStack(spacing: TS.s3) { VQAIActivity(g.query, detail: g.step); Spacer() }.contentShape(Rectangle())570                    }571                    .buttonStyle(.plain)572                }573                ForEach(jobs) { j in574                    Button { model.openQuantJob(j.id) } label: {575                        HStack(spacing: TS.s2) { ProgressView().controlSize(.mini); Text("\(app.quant.tool(j.tool)?.title ?? j.tool) · \(j.subject)").font(TT.bodySm.font).lineLimit(1); Spacer() }.contentShape(Rectangle())576                    }577                    .buttonStyle(.plain)578                }579            }580            .accessibilityIdentifier("overview.running")581        }582    }583}584585private struct WorkspaceRow: View {586    let app: AppEnvironment587    let model: WindowModel588    let wide: Bool589    var body: some View {590        Columns(horizontal: wide) {591            PortfolioSummary(app: app, model: model).frame(maxWidth: .infinity, alignment: .topLeading)592            WatchlistPreview(app: app, model: model).frame(maxWidth: .infinity, alignment: .topLeading)593            RecentConversations(app: app, model: model).frame(maxWidth: .infinity, alignment: .topLeading)594        }595    }596}597598private struct PortfolioSummary: View {599    let app: AppEnvironment600    let model: WindowModel601    var body: some View {602        let positions = app.workspace.positions603        let v = PortfolioValuation(positions: positions, quotes: app.market.quotes.mapValues(\.quote))604        let locale = app.vqTheme.numberLocale605        VStack(alignment: .leading, spacing: TS.s2) {606            TerminalSectionHeader("Portfolio") { Button("Open") { model.show(.portfolio) }.buttonStyle(.link).font(TT.caption.font) }607            if positions.isEmpty {608                Text(app.workspace.workspace == nil ? (app.workspace.error ?? "Loading…") : "No position recorded. Positions are entered in Portfolios or by the agent.").font(TT.bodySm.font).foregroundStyle(TP.text2)609            } else {610                line("Market value", VQFormat.number(v.marketValue, locale: locale), nil)611                Hairline()612                line("Day change", VQFormat.number(v.dayChange, signed: true, locale: locale), v.dayChange)613                Hairline()614                line("Unrealised P&L", VQFormat.number(v.unrealized, signed: true, locale: locale), v.unrealized)615                if !v.unpriced.isEmpty { Text("Not priced: \(v.unpriced.joined(separator: ", ")) (excluded from the totals)").font(TT.caption.font).foregroundStyle(TP.warn) }616                if let d = v.asOf { FreshnessBadge(freshness: .ofQuote(asOf: d)) }617            }618        }619        .onAppear { app.market.watch(positions.map(\.symbol)) }620        .onDisappear { app.market.unwatch(positions.map(\.symbol)) }621        .onChange(of: positions.map(\.symbol)) { old, new in app.market.unwatch(old); app.market.watch(new) }622    }623    private func line(_ label: String, _ value: String, _ signed: Double?) -> some View {624        HStack {625            Text(label).font(TT.bodySm.font).foregroundStyle(TP.text2)626            Spacer()627            if let signed { TDelta(value: signed, text: value, size: 12.5) } else { Text(value).font(.system(size: 12.5, weight: .medium, design: .monospaced)).monospacedDigit().foregroundStyle(TP.text1) }628        }629        .frame(height: 26)630    }631}632633/// The first synced watchlist with quotes of the data layer.634private struct WatchlistPreview: View {635    let app: AppEnvironment636    let model: WindowModel637    var body: some View {638        let list = app.syncedWatchlists.first639        let symbols = Array((list?.data.symbols ?? []).prefix(6))640        let store = app.terminal641        let locale = app.vqTheme.numberLocale642        VStack(alignment: .leading, spacing: TS.s2) {643            TerminalSectionHeader(list?.data.name ?? "Watchlist", freshness: symbols.isEmpty ? nil : store.quotesFreshness) {644                Button("Open") { model.watchlistId = list?.id; model.show(.watchlists) }.buttonStyle(.link).font(TT.caption.font)645            }646            VStack(spacing: 0) {647                ForEach(Array(symbols.enumerated()), id: \.element) { i, s in648                    if i > 0 { Hairline() }649                    Button { model.show(.charting, symbol: s) } label: {650                        HStack(spacing: 8) {651                            Text(s).font(.system(size: 12, weight: .semibold, design: .monospaced)).foregroundStyle(TP.text1).frame(width: 60, alignment: .leading)652                            Spacer(minLength: 4)653                            if let q = store.quotes[s] {654                                Text(TerminalFormat.price(q.price, locale: locale)).font(.system(size: 12.5, weight: .medium, design: .monospaced)).monospacedDigit().foregroundStyle(TP.text1)655                                TDelta(value: q.changePct, text: VQFormat.percentValue(q.changePct, signed: true, locale: locale)).frame(width: 86, alignment: .trailing)656                            } else { Text(store.missing.contains(s) ? "no quote" : "…").font(TT.caption.font).foregroundStyle(TP.text3) }657                        }658                        .frame(height: 26).contentShape(Rectangle())659                    }660                    .buttonStyle(.plain).modifier(RowHover())661                    .contextMenu { SymbolContextMenu(app: app, model: model, symbol: s) }662                }663            }664            if symbols.isEmpty { Text(list == nil ? "No watchlist yet." : "This watchlist is empty.").font(TT.bodySm.font).foregroundStyle(TP.text2) }665        }666        .task(id: symbols) { await store.loadQuotes(symbols) }667    }668}669670private struct RecentConversations: View {671    let app: AppEnvironment672    let model: WindowModel673    var body: some View {674        VStack(alignment: .leading, spacing: TS.s2) {675            TerminalSectionHeader("Recent conversations") { Button("New") { model.openConversation(nil) }.buttonStyle(.link).font(TT.caption.font) }676            VStack(spacing: 0) {677                ForEach(Array(app.research.sessions.prefix(6).enumerated()), id: \.element.id) { i, s in678                    if i > 0 { Hairline() }679                    Button { model.openConversation(s.sessionId) } label: {680                        HStack(spacing: 6) {681                            if s.pinned { Image(systemName: "pin.fill").font(.caption2).foregroundStyle(TP.text3) }682                            Text(s.title).font(TT.bodySm.font).foregroundStyle(TP.text1).lineLimit(1)683                            Spacer(minLength: 4)684                            Text(VQFormat.relative(s.updated, language: .en)).font(TT.caption.font).foregroundStyle(TP.text3).lineLimit(1).fixedSize()685                        }686                        .frame(height: 26).contentShape(Rectangle())687                    }688                    .buttonStyle(.plain).modifier(RowHover())689                }690            }691            if app.research.sessions.isEmpty { Text(app.research.sessionsError ?? "No conversation yet.").font(TT.bodySm.font).foregroundStyle(TP.text2) }692        }693    }694}695
Files main
Menu

Theme