SPB Git

Repository Public

MenuBarExtraView.swift 13.1 KB 252 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/MenuBar/MenuBarExtraView.swift3// Description: The menu-bar extra: market session with its as-of time, a few index quotes with their freshness, the analyses and computations running on the server (stop, open), and a quick-ask field that opens Research with the question ready. Shows nothing personal while signed out or locked, and asks the server nothing while its panel is closed.4import SwiftUI5import VQuantCore6import VQuantKit7import VQuantUI89/// What the panel shows of the market. Loaded only while the panel is open.10@Observable final class MenuBarStore: SessionScoped {11    private(set) var overview: VQMarketOverview?12    private(set) var error: String?13    private(set) var loading = false14    private(set) var fetchedAt: Date?15    /// Requests made since launch (the cadence is checked with it in development).16    private(set) var requests = 017    @ObservationIgnored private let app: AppEnvironment1819    init(app: AppEnvironment) { self.app = app }20    func reset() { overview = nil; error = nil; fetchedAt = nil }2122    /// Asks the server unless what is shown is younger than `maxAge` seconds.23    func refresh(maxAge: TimeInterval = 0) async {24        guard app.session.isSignedIn, !loading else { return }25        if let t = fetchedAt, Date().timeIntervalSince(t) < maxAge { return }26        loading = true; defer { loading = false }27        requests += 128        do { overview = try await app.vq.data.marketOverview(); error = nil; fetchedAt = Date() }29        catch is CancellationError {} catch { self.error = paneError(error) }30        #if DEBUG31        if app.options.extra["MenuBarLog"] != nil { NSLog("VQ menu bar: market overview request #%d", requests) }32        #endif33    }34}3536extension AppEnvironment { var menuBar: MenuBarStore { store { MenuBarStore(app: self) } } }3738/// The status item: the app's mark, and the number of things running on the server when there are any.39struct MenuBarLabel: View {40    let app: AppEnvironment41    var body: some View {42        let running = app.session.isSignedIn ? app.research.runningCount + app.quant.runningCount : 043        HStack(spacing: 3) {44            Image(systemName: "chart.line.uptrend.xyaxis")45            if running > 0 { Text("\(running)").monospacedDigit() }46        }47        .accessibilityLabel(running > 0 ? "VQuant, \(running) running" : "VQuant")48    }49}5051struct MenuBarPanel: View {52    let app: AppEnvironment53    /// Preview in an ordinary window (development captures): no status item to dismiss.54    var isPreview = false55    @State private var question = ""56    @State private var window: NSWindow?57    @FocusState private var askFocused: Bool58    @Environment(\.openSettings) private var openSettings5960    /// Seconds between two requests while the panel stays open.61    static let openCadence: TimeInterval = 606263    var body: some View {64        VStack(alignment: .leading, spacing: 0) {65            switch app.session.phase {66            case .signedIn: signedIn67            case .locked: gate("VQuant is locked", "Unlock VQuant to see the market and your analyses.", "Unlock…")68            case .signedOut: gate("Not signed in", "Sign in to VQuant to see the market and your analyses.", "Open VQuant")69            case .starting: gate("Starting…", "VQuant is contacting its server.", "Open VQuant")70            }71            Rectangle().fill(VQTokens.Palette.line).frame(height: 1)72            HStack(spacing: 14) {73                Button("Open VQuant") { WindowRouter.open(.front); dismiss() }.accessibilityIdentifier("menubar.open")74                Button("Settings…") { NSApp.activate(ignoringOtherApps: true); openSettings(); dismiss() }75                Spacer()76                Button("Quit") { NSApp.terminate(nil) }77            }78            .buttonStyle(.link).font(.callout).padding(.horizontal, 14).padding(.vertical, 9)79        }80        .frame(width: 348)81        .background(WindowAccessor { w in window = w })82        .vqTheme(app.vqTheme)83        .preferredColorScheme(app.settings.theme.scheme)84        // the server is asked only while the panel is on screen: when it opens (if what it shows is older than 20 s),85        // then once a minute; closed, this loop only sleeps86        .task(id: app.session.isSignedIn) {87            guard app.session.isSignedIn else { return }88            while !Task.isCancelled {89                if isPreview || window?.isVisible == true { await app.menuBar.refresh(maxAge: 20) }90                try? await Task.sleep(for: .seconds(Self.openCadence))91            }92        }93        .onReceive(NotificationCenter.default.publisher(for: NSWindow.didBecomeKeyNotification)) { n in94            guard let w = n.object as? NSWindow, w === window, app.session.isSignedIn else { return }95            Task { await app.menuBar.refresh(maxAge: 20); await app.research.refreshGenerations(); await app.quant.refresh() }96        }97    }9899    private func dismiss() { if !isPreview { window?.close() } }100101    private func gate(_ title: String, _ text: String, _ action: String) -> some View {102        VStack(alignment: .leading, spacing: 6) {103            Text(title).font(VQTokens.Typography.title.font)104            Text(text).font(.callout).foregroundStyle(VQTokens.Palette.text2).fixedSize(horizontal: false, vertical: true)105        }106        .padding(14).frame(maxWidth: .infinity, alignment: .leading)107        .accessibilityElement(children: .combine).accessibilityIdentifier("menubar.gate")108    }109110    // signed in111112    @ViewBuilder private var signedIn: some View {113        let store = app.menuBar114        VStack(alignment: .leading, spacing: 10) {115            HStack(alignment: .firstTextBaseline) {116                Text("Markets").font(VQTokens.Typography.title.font)117                Spacer()118                if store.loading { ProgressView().controlSize(.mini) }119                if let o = store.overview { session(o) }120            }121            if let o = store.overview {122                if let note = o.status.note { Text(note).font(.caption).foregroundStyle(VQTokens.Palette.text3).fixedSize(horizontal: false, vertical: true) }123                quotes(o)124            } else if let e = store.error {125                Text(e).font(.callout).foregroundStyle(VQTokens.Palette.text2).fixedSize(horizontal: false, vertical: true)126                Button("Retry") { Task { await store.refresh() } }.controlSize(.small)127            } else { VQSkeletonRows(rows: 4, columns: 3) }128            if store.overview != nil, let e = store.error { Text("Not refreshed: \(e)").font(.caption).foregroundStyle(VQTokens.Palette.warn).lineLimit(2) }129        }130        .padding(14)131        Rectangle().fill(VQTokens.Palette.line).frame(height: 1)132        running.padding(14)133        Rectangle().fill(VQTokens.Palette.line).frame(height: 1)134        ask.padding(14)135    }136137    private func session(_ o: VQMarketOverview) -> some View {138        let word: String = switch o.status.session.known {139        case .regular?: "US market open"; case .pre?: "Pre-market"; case .post?: "After hours"; case .closed?: "US market closed"140        case nil: o.status.session.rawValue.capitalized141        }142        return HStack(spacing: 5) {143            Image(systemName: o.status.isOpen ? "circle.fill" : "moon.fill").font(.system(size: 7)).foregroundStyle(o.status.isOpen ? VQTokens.Palette.text1 : VQTokens.Palette.text3)144            Text(word).font(.system(size: 11.5, weight: .medium))145            if let t = o.asOf { Text("· as of \(VQFormat.time(t, language: .en))").font(.system(size: 11, design: .monospaced)).foregroundStyle(VQTokens.Palette.text3) }146        }147        .accessibilityElement(children: .combine).accessibilityIdentifier("menubar.session")148    }149150    /// The first indices of the overview and the VIX, each group with the chip that says how fresh it is.151    @ViewBuilder private func quotes(_ o: VQMarketOverview) -> some View {152        let indices = o.section("indices"), vol = o.section("volatility")153        let rows = Array((indices?.items ?? []).prefix(4)) + Array((vol?.items ?? []).prefix(1))154        if rows.isEmpty { Text("The server returned no index quote.").font(.callout).foregroundStyle(VQTokens.Palette.text3) }155        else {156            VStack(spacing: 5) {157                ForEach(rows) { item in158                    HStack(spacing: 8) {159                        Text(item.name).font(.callout).lineLimit(1)160                        Spacer(minLength: 6)161                        Text(VQFormat.number(item.price, decimals: 2, locale: app.vqTheme.numberLocale)).font(VQTokens.Typography.numSm.font)162                        VQDelta(percentPoints: item.changePct).frame(width: 74, alignment: .trailing)163                    }164                    .accessibilityElement(children: .combine)165                }166            }167            // one chip per source of the rows above: what kind of value, from whom, as of when168            VStack(alignment: .leading, spacing: 4) {169                if let f = indices?.freshness { chip("Indices", f) }170                if let f = vol?.freshness, f.asOf != indices?.freshness?.asOf { chip("Volatility index", f) }171            }172        }173    }174175    private func chip(_ what: String, _ f: VQFreshness) -> some View {176        HStack(spacing: 6) {177            VQProvenanceChip(f)178            Text(what).font(.system(size: 10.5)).foregroundStyle(VQTokens.Palette.text3).fixedSize()179            Spacer(minLength: 0)180        }181    }182183    @ViewBuilder private var running: some View {184        let analyses = app.research.generations.filter { $0.status == .running }185        let jobs = app.quant.jobs.filter { $0.status == .running }186        VStack(alignment: .leading, spacing: 8) {187            Text("Running on the server").font(VQTokens.Typography.overline.font).textCase(.uppercase).foregroundStyle(VQTokens.Palette.text3)188            if analyses.isEmpty && jobs.isEmpty {189                Text("Nothing is running.").font(.callout).foregroundStyle(VQTokens.Palette.text2).accessibilityIdentifier("menubar.idle")190            }191            ForEach(analyses) { g in192                runningRow(symbol: "sparkles", title: g.query, detail: "Analysis · \(g.mode)") { Task { await app.research.cancelGeneration(g.id) } } open: { WindowRouter.open(.conversation(g.sessionId)); dismiss() }193            }194            ForEach(jobs) { j in195                runningRow(symbol: "function", title: "\(app.quant.tool(j.tool)?.title ?? j.tool) · \(j.subject)", detail: "Computation") {196                    Task { do { _ = try await app.vq.lab.cancel(j.id) } catch { app.toasts.show((error as? VQError)?.userMessage ?? error.localizedDescription, error: true) }; await app.quant.refresh() }197                } open: { WindowRouter.open(.quantJob(j.id)); dismiss() }198            }199        }200        .frame(maxWidth: .infinity, alignment: .leading)201    }202203    private func runningRow(symbol: String, title: String, detail: String, stop: @escaping () -> Void, open: @escaping () -> Void) -> some View {204        HStack(spacing: 8) {205            Image(systemName: symbol).foregroundStyle(VQTokens.Palette.accentText).frame(width: 16)206            VStack(alignment: .leading, spacing: 1) {207                Text(title).font(.callout).lineLimit(1)208                Text(detail).font(.caption).foregroundStyle(VQTokens.Palette.text3)209            }210            Spacer(minLength: 6)211            Button("Stop", action: stop).controlSize(.small)212            Button("Open", action: open).controlSize(.small)213        }214    }215216    private var ask: some View {217        VStack(alignment: .leading, spacing: 6) {218            HStack(spacing: 6) {219                TextField("Ask VQuant…", text: $question).textFieldStyle(.roundedBorder).focused($askFocused).onSubmit(openAsk).accessibilityIdentifier("menubar.ask")220                Button(action: openAsk) { Image(systemName: "arrow.up.forward.app") }.help("Open Research with this question")221                    .disabled(question.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty).accessibilityIdentifier("menubar.ask.open").accessibilityLabel("Open in Research")222            }223            Text("Opens Research with your question in the composer. Nothing is sent until you send it there.").font(.caption).foregroundStyle(VQTokens.Palette.text3).fixedSize(horizontal: false, vertical: true)224        }225    }226227    private func openAsk() {228        let q = question.trimmingCharacters(in: .whitespacesAndNewlines)229        guard !q.isEmpty else { return }230        question = ""231        // prepared, never sent from here: `sendImmediately` stays false232        WindowRouter.open(.ask(AskDraft(text: q)))233        dismiss()234    }235}236237#if DEBUG238/// `-VQXMenuBarPreview 1`: the panel in an ordinary window, so a development capture can show it in light and dark.239enum MenuBarPreview {240    private static var window: NSWindow?241    static func show(app: AppEnvironment) {242        guard window == nil else { return }243        let host = NSHostingController(rootView: MenuBarPanel(app: app, isPreview: true).background(.regularMaterial))244        let w = NSWindow(contentViewController: host)245        w.title = "Menu-bar extra (preview)"; w.styleMask = [.titled, .closable]; w.isReleasedWhenClosed = false246        w.appearance = app.settings.theme.scheme.map { NSAppearance(named: $0 == .dark ? .darkAqua : .aqua) } ?? nil247        w.center(); w.makeKeyAndOrderFront(nil)248        window = w249    }250}251#endif252
Files main
Menu

Theme