SPB Git

Repository Public

MainWindow.swift 11.2 KB 213 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Shell/MainWindow.swift3// Description: The workstation window: sidebar, section content, symbol search, connection and data-status bar.4import SwiftUI5import VQuantCore6import VQuantKit7import VQuantUI89struct MainWindow: View {10    let app: AppEnvironment11    @Bindable var model: WindowModel12    @Environment(\.openWindow) private var openWindow13    @State private var columns: NavigationSplitViewVisibility = .all1415    var body: some View {16        NavigationSplitView(columnVisibility: $columns) {17            List {18                ForEach(AppSection.groups, id: \.0) { group, sections in19                    Section(group) {20                        ForEach(sections) { s in21                            SelectableRow(isSelected: model.section == s) { model.section = s } content: {22                                // the Ember accent is kept for the selected destination and primary actions: icons stay ink23                                Label { Text(s.title) } icon: { Image(systemName: s.symbol).foregroundStyle(model.section == s ? VQTokens.Palette.accentText : VQTokens.Palette.text2) }.badge(badge(s))24                            }25                                .accessibilityIdentifier("sidebar.\(s.rawValue)")26                        }27                    }28                }29            }30            .listStyle(.sidebar)31            .navigationSplitViewColumnWidth(min: 170, ideal: 200, max: 260)32            .safeAreaInset(edge: .bottom) { AccountFooter(app: app) }33        } detail: {34            VStack(spacing: 0) {35                if !app.connectivity.isOnline { NoticeBar(kind: .offline, text: "This Mac is offline. Cached content stays readable; computations, analyses and edits need the server.") }36                else if app.session.unverified { NoticeBar(kind: .offline, text: "The VQuant server could not be reached. Showing what this Mac last received.") { Task { await app.session.verify(); await app.market.refresh() } } }37                content.frame(maxWidth: .infinity, maxHeight: .infinity)38                StatusBar(app: app)39            }40            .navigationTitle(model.section.title)41            .navigationSubtitle(subtitle)42            .toolbar {43                ToolbarItem(placement: .principal) { SymbolSearchField(app: app, focusTick: model.searchFocusTick) { model.show(sectionForSymbol, symbol: $0) }.frame(width: 300) }44                ToolbarItem { SyncStatusButton(app: app) }45                ToolbarItem {46                    Button { model.paletteOpen = true } label: { Label("Command Palette", systemImage: "command") }.help("Search everything and run commands (⌘K)")47                        .accessibilityIdentifier("toolbar.palette")48                }49                ToolbarItem {50                    Button { openWindow(id: "chart", value: ChartSpec(symbol: model.symbol)) } label: { Label("Detach Chart", systemImage: "rectangle.portrait.on.rectangle.portrait") }51                        .help("Open \(model.symbol) in its own chart window")52                }53                ToolbarItem {54                    Button { Task { await app.market.refresh() } } label: { Label("Refresh", systemImage: "arrow.clockwise") }.help("Refresh market data now").disabled(app.market.refreshing)55                }56            }57        }58        .overlay { if model.paletteOpen { CommandPalette(app: app, model: model) } }59        .modifier(ChartAskReceiver(app: app, model: model))60        .background(WindowAccessor { w in61            model.window = w62            WorkspaceLayouts.register(w) { [weak model] in model.map { SavedWorkspace.Window(section: $0.section.rawValue, symbol: $0.symbol, frame: nil, kind: "main") } }63        })64    }6566    /// A symbol picked in the toolbar opens in the current section when it is about one symbol, in Charting otherwise.67    private var sectionForSymbol: AppSection { [.charting, .data, .quant, .statements].contains(model.section) ? model.section : .charting }6869    private var subtitle: String {70        switch model.section {71        case .charting, .data, .statements: model.symbol72        case .research: model.sessionId.flatMap { id in app.research.sessions.first { $0.sessionId == id }?.title } ?? "New conversation"73        default: ""74        }75    }7677    private func badge(_ s: AppSection) -> Int {78        switch s { case .jobs: app.research.runningCount + app.quant.runningCount; default: 0 }79    }8081    @ViewBuilder private var content: some View {82        switch model.section {83        case .overview: OverviewView(app: app, model: model)84        case .markets: MarketsView(app: app, model: model)85        case .watchlists: WatchlistsView(app: app, model: model)86        case .charting: ChartSection(app: app, model: model)87        case .research: ResearchView(app: app, model: model)88        case .quant: QuantView(app: app, model: model)89        case .data: DataExplorerView(app: app, model: model)90        case .portfolio: PortfolioView(app: app, model: model)91        case .risk: RiskView(app: app, model: model)92        case .agent: AgentView(app: app, model: model)93        case .jobs: JobsView(app: app, model: model)94        case .documents: DocumentsView(app: app, model: model)95        case .studio: StudioView(app: app, model: model)96        case .statements: StatementsView(app: app, model: model)97        }98    }99}100101private struct AccountFooter: View {102    let app: AppEnvironment103    var body: some View {104        HStack(spacing: 8) {105            Image(systemName: "person.crop.circle.fill").font(.title3).foregroundStyle(.secondary)106            VStack(alignment: .leading, spacing: 0) {107                Text(app.session.account?.name ?? "").font(.callout.weight(.medium)).lineLimit(1)108                Text(app.options.server.host ?? "").font(.caption2).foregroundStyle(.tertiary).lineLimit(1)109            }110            Spacer()111            SettingsLink { Image(systemName: "gearshape") }.buttonStyle(.borderless).help("Settings")112        }113        .padding(.horizontal, 12).padding(.vertical, 8)114        .overlay(alignment: .top) { Divider() }115    }116}117118/// Always-visible account of where the numbers on screen come from and how old they are.119struct StatusBar: View {120    let app: AppEnvironment121    var body: some View {122        HStack(spacing: 14) {123            HStack(spacing: 5) {124                Circle().fill(connectionColor).frame(width: 7, height: 7)125                Text(connectionText).font(.caption)126            }127            .help("Connection to \(app.options.server.host ?? "the server")")128            if let open = app.market.usMarketOpen {129                Text(open ? "US market open" : "US market closed").font(.caption).foregroundStyle(.secondary)130            }131            if let t = app.market.lastSuccess {132                Text("Quotes received \(Fmt.time(t)) · polled every \(app.settings.quoteRefresh > 0 ? "\(app.settings.quoteRefresh) s" : "manual refresh")").font(.caption).foregroundStyle(.secondary)133                    .help("Market data is fetched over HTTPS from the VQuant server (provider: Financial Modeling Prep). There is no streaming feed.")134            }135            Spacer()136            let running = app.research.runningCount + app.quant.runningCount137            if running > 0 {138                HStack(spacing: 5) { ProgressView().controlSize(.mini); Text("\(running) job\(running == 1 ? "" : "s") running on the server").font(.caption) }139            }140        }141        .padding(.horizontal, 12).frame(height: 24)142        .background(.bar)143        .overlay(alignment: .top) { Divider() }144        .accessibilityElement(children: .combine)145    }146    private var connectionColor: Color { !app.connectivity.isOnline ? Palette.red : app.market.lastError != nil || app.session.unverified ? .orange : Palette.green }147    private var connectionText: String { !app.connectivity.isOnline ? "Offline" : app.session.unverified ? "Server unreachable" : app.market.lastError != nil ? "Degraded" : "Connected" }148}149150/// Symbol entry with server-side search (ticker or company name). Return accepts what was typed as a ticker.151struct SymbolSearchField: View {152    let app: AppEnvironment153    var focusTick = 0154    var placeholder = "Symbol or company"155    let onPick: (String) -> Void156157    @State private var text = ""158    @State private var results: [SymbolMatch] = []159    @State private var searching = false160    @State private var open = false161    @State private var failure: String?162    @FocusState private var focused: Bool163164    var body: some View {165        TextField(placeholder, text: $text)166            .textFieldStyle(.roundedBorder)167            .focused($focused)168            .onSubmit { accept(text) }169            .onChange(of: focusTick) { _, _ in focused = true }170            .task(id: text) {171                let q = text.trimmingCharacters(in: .whitespaces)172                guard q.count >= 2, focused else { results = []; open = false; return }173                try? await Task.sleep(for: .milliseconds(350))   // debounce174                guard !Task.isCancelled else { return }175                searching = true; defer { searching = false }176                do {177                    let r = try await app.api.search(q)178                    guard !Task.isCancelled else { return }179                    // listings in USD first: they are what the server's engines and charts cover best180                    results = r.sorted { ($0.currency == "USD" ? 0 : 1, $0.symbol.count) < ($1.currency == "USD" ? 0 : 1, $1.symbol.count) }181                    failure = nil; open = true182                } catch is CancellationError {} catch { failure = error.localizedDescription; results = []; open = true }183            }184            .popover(isPresented: $open, arrowEdge: .bottom) {185                VStack(alignment: .leading, spacing: 0) {186                    if let failure { Text(failure).font(.callout).foregroundStyle(.secondary).padding(10) }187                    else if results.isEmpty { Text("No match. Press Return to use “\(text.uppercased())” as a ticker.").font(.callout).foregroundStyle(.secondary).padding(10) }188                    ForEach(results) { m in189                        Button { accept(m.symbol) } label: {190                            HStack {191                                Text(m.symbol).font(.system(.body, design: .monospaced).weight(.medium)).frame(width: 90, alignment: .leading)192                                Text(m.name).lineLimit(1)193                                Spacer()194                                Text([m.exchange, m.currency].compactMap { $0 }.joined(separator: " · ")).font(.caption).foregroundStyle(.secondary)195                            }196                            .contentShape(Rectangle())197                        }198                        .buttonStyle(.plain).padding(.horizontal, 10).padding(.vertical, 5)199                    }200                }201                .frame(width: 420).padding(.vertical, 4)202            }203            .overlay(alignment: .trailing) { if searching { ProgressView().controlSize(.mini).padding(.trailing, 6) } }204            .accessibilityIdentifier("symbol.search")205    }206207    private func accept(_ raw: String) {208        guard let s = Watchlist.normalize(raw) else { if !raw.isEmpty { app.toasts.show("“\(raw)” is not a ticker symbol.", error: true) }; return }209        open = false; text = ""; focused = false210        onPick(s)211    }212}213
Files main
Menu

Theme