SPB Git

Repository Public

CommandPalette.swift 21.1 KB 351 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Terminal/CommandPalette.swift3// Description: The command palette (⌘K): one field over the universal search of the server (symbols, conversations, projects, notes, watchlists, portfolios, charts, actions) merged with this app's own commands; grouped results, keyboard navigation, recent searches kept in the synced preference.4import SwiftUI5import VQuantCore6import VQuantKit7import VQuantUI89struct CommandPalette: View {10    let app: AppEnvironment11    @Bindable var model: WindowModel1213    @State private var query = ""14    @State private var results: VQSearchResults?15    /// The query `results` answers (results of an older query stay on screen while the next one is asked).16    @State private var answered = ""17    @State private var searching = false18    @State private var failure: String?19    @State private var highlighted = 020    @FocusState private var focused: Bool21    @Environment(\.openWindow) private var openWindow22    @Environment(\.openSettings) private var openSettings2324    enum Group: Int, CaseIterable {25        case recent, symbols, conversations, projects, notes, watchlists, portfolios, charts, actions26        var title: String {27            switch self {28            case .recent: "Recent searches"; case .symbols: "Symbols"; case .conversations: "Conversations"; case .projects: "Projects"; case .notes: "Notes"29            case .watchlists: "Watchlists"; case .portfolios: "Portfolios"; case .charts: "Charts"; case .actions: "Actions"30            }31        }32    }3334    struct Entry: Identifiable {35        var id: String36        var group: Group37        var title: String38        var subtitle: String?39        var icon: String40        var hint: String?41        var mono = false42        /// Keeps the palette open (a recent search refills the field).43        var staysOpen = false44        var run: () -> Void45        /// ⌘↩ (symbols: statements).46        var alternate: (() -> Void)?47    }4849    var body: some View {50        let entries = self.entries51        ZStack(alignment: .top) {52            TP.scrim.opacity(0.28).ignoresSafeArea().contentShape(Rectangle()).onTapGesture { close() }.accessibilityHidden(true)53            VStack(spacing: 0) {54                field(entries)55                Hairline(strong: true)56                list(entries)57                Hairline()58                footer59            }60            .frame(width: 660)61            .background(.regularMaterial, in: RoundedRectangle(cornerRadius: VQTokens.Radius.lg, style: .continuous))62            .overlay { RoundedRectangle(cornerRadius: VQTokens.Radius.lg, style: .continuous).strokeBorder(TP.lineStrong, lineWidth: 1) }63            .shadow(color: .black.opacity(0.35), radius: 32, y: 18)64            .padding(.top, 64)65            .accessibilityElement(children: .contain)66            .accessibilityIdentifier("palette")67        }68        .onAppear { query = model.paletteQuery }69        // focus set in onAppear is lost while the overlay is being inserted (found by the UI test: ⌘K, then typing went70        // nowhere): ask once the field is in the window, and once more after the insertion animation71        .task { focused = true; try? await Task.sleep(for: .milliseconds(180)); if !focused { focused = true } }72        .onChange(of: query) { _, _ in highlighted = 0 }73        .onExitCommand { close() }74        .task(id: query) { await search() }75    }7677    // MARK: field, list, footer7879    private func field(_ entries: [Entry]) -> some View {80        HStack(spacing: TS.s3) {81            Image(systemName: "magnifyingglass").font(.system(size: 16)).foregroundStyle(TP.text3)82            TextField("Search symbols, conversations, projects… or run a command", text: $query)83                .textFieldStyle(.plain).font(.system(size: 17))84                .focused($focused)85                .onSubmit { run(entries, at: highlighted, alternate: NSEvent.modifierFlags.contains(.command)) }86                .onKeyPress(keys: [.return]) { press in87                    guard press.modifiers.contains(.command) else { return .ignored }88                    run(entries, at: highlighted, alternate: true); return .handled89                }90                .onKeyPress(.downArrow) { move(1, entries.count); return .handled }91                .onKeyPress(.upArrow) { move(-1, entries.count); return .handled }92                .onKeyPress(.escape) { close(); return .handled }93                .accessibilityIdentifier("palette.field")94            if searching { ProgressView().controlSize(.small) }95            Text("esc").font(.system(size: 10.5, weight: .medium, design: .monospaced)).foregroundStyle(TP.text3)96                .padding(.horizontal, 5).padding(.vertical, 2).overlay { RoundedRectangle(cornerRadius: 4).strokeBorder(TP.lineStrong, lineWidth: 1) }97        }98        .padding(.horizontal, TS.s4).frame(height: 52)99    }100101    private func list(_ entries: [Entry]) -> some View {102        ScrollViewReader { proxy in103            ScrollView {104                VStack(alignment: .leading, spacing: 0) {105                    if entries.isEmpty {106                        Text(searching ? "Searching…" : failure ?? "Nothing matches “\(query)”.").font(TT.bodySm.font).foregroundStyle(TP.text2).padding(TS.s4)107                            .accessibilityIdentifier("palette.empty")108                    }109                    ForEach(Array(entries.enumerated()), id: \.element.id) { i, e in110                        if i == 0 || entries[i - 1].group != e.group {111                            Text(e.group.title).font(TT.overline.font).tracking(TT.overline.tracking).textCase(.uppercase).foregroundStyle(TP.text3)112                                .padding(.horizontal, TS.s4).padding(.top, i == 0 ? TS.s2 : TS.s3).padding(.bottom, 4)113                        }114                        row(e, on: i == highlighted)115                            .id(e.id)116                            .onTapGesture { run(entries, at: i, alternate: NSEvent.modifierFlags.contains(.command)) }117                            .onHover { if $0 { highlighted = i } }118                    }119                }120                .padding(.bottom, TS.s2)121            }122            .frame(maxHeight: 420)123            .onChange(of: highlighted) { _, i in if entries.indices.contains(i) { proxy.scrollTo(entries[i].id) } }124        }125    }126127    private func row(_ e: Entry, on: Bool) -> some View {128        HStack(spacing: TS.s3) {129            Image(systemName: e.icon).font(.system(size: 13)).foregroundStyle(e.icon == "sparkles" ? TP.accentText : TP.text2).frame(width: 20)130            Text(e.title).font(e.mono ? .system(size: 13, weight: .semibold, design: .monospaced) : .system(size: 13, weight: .medium)).foregroundStyle(TP.text1).lineLimit(1)131            if let s = e.subtitle { Text(s).font(.system(size: 12)).foregroundStyle(TP.text2).lineLimit(1) }132            Spacer(minLength: TS.s2)133            if let h = e.hint { Text(h).font(.system(size: 11, design: .monospaced)).foregroundStyle(TP.text3).lineLimit(1) }134            if on { Image(systemName: "return").font(.system(size: 10, weight: .semibold)).foregroundStyle(TP.text3) }135        }136        .padding(.horizontal, TS.s3).frame(height: 32)137        .background(RoundedRectangle(cornerRadius: 7, style: .continuous).fill(on ? TP.text1.opacity(0.09) : Color.clear))138        .padding(.horizontal, TS.s2)139        .contentShape(Rectangle())140        .accessibilityElement(children: .ignore)141        .accessibilityLabel([e.title, e.subtitle].compactMap { $0 }.joined(separator: ", "))142        .accessibilityAddTraits(on ? [.isButton, .isSelected] : .isButton)143        .accessibilityValue(on ? "highlighted" : "")144        .accessibilityIdentifier("palette.row.\(e.id)")145    }146147    private var footer: some View {148        HStack(spacing: TS.s3) {149            hint("↑↓", "navigate"); hint("↩", "open"); hint("⌘↩", "statements of a symbol")150            Spacer(minLength: TS.s2)151            if let u = results?.unavailable, !u.isEmpty, answered == trimmed {152                // the server says which sources did not answer in time: the other results are complete153                Label("\(u.map(Self.sourceName).joined(separator: ", ")) did not answer in time", systemImage: "exclamationmark.circle")154                    .font(TT.caption.font).foregroundStyle(TP.warn).lineLimit(1).accessibilityIdentifier("palette.unavailable")155            } else if let failure, !trimmed.isEmpty {156                Label(failure, systemImage: "wifi.exclamationmark").font(TT.caption.font).foregroundStyle(TP.warn).lineLimit(1).help("The commands of this Mac still work.")157            }158        }159        .padding(.horizontal, TS.s4).frame(height: 30)160    }161162    private func hint(_ key: String, _ text: String) -> some View {163        HStack(spacing: 4) {164            Text(key).font(.system(size: 11, weight: .medium)).foregroundStyle(TP.text2)165            Text(text).font(.system(size: 11)).foregroundStyle(TP.text3)166        }167    }168169    private static func sourceName(_ type: String) -> String {170        switch type { case "symbol": "Symbol search"; case "conversation": "Conversations"; default: type.capitalized + "s" }171    }172173    // MARK: search174175    private var trimmed: String { query.trimmingCharacters(in: .whitespacesAndNewlines) }176177    private func search() async {178        let q = trimmed179        guard q.count >= 2 else { results = nil; answered = ""; failure = nil; searching = false; return }180        try? await Task.sleep(for: .milliseconds(220))     // debounce: one request per pause in typing181        guard !Task.isCancelled else { return }182        searching = true; defer { if !Task.isCancelled { searching = false } }183        do {184            let r = try await app.vq.data.search(q, types: [.symbol, .conversation, .project, .note, .watchlist, .portfolio, .chart, .action], limit: 40)185            guard !Task.isCancelled else { return }186            results = r; answered = q; failure = nil187        } catch is CancellationError {} catch {188            guard !Task.isCancelled else { return }189            results = nil; answered = q190            failure = (error as? VQError)?.kind == .network ? "The server cannot be reached: showing this Mac's commands only" : ((error as? VQError)?.userMessage ?? error.localizedDescription)191        }192    }193194    // MARK: entries195196    private var entries: [Entry] {197        let q = trimmed198        let commands = localCommands()199        guard !q.isEmpty else {200            let recent = (app.sync.active?.preference.recentSearches ?? []).prefix(5).map { text in201                Entry(id: "recent:\(text)", group: .recent, title: text, icon: "clock.arrow.circlepath", staysOpen: true, run: { query = text })202            }203            return recent + commands.map(\.entry)204        }205        var scored = commands.compactMap { c -> (Double, Entry)? in206            let s = PaletteMatch.score(query: q, title: c.entry.title, keywords: c.keywords)207            return s > 0 ? (s, c.entry) : nil208        }209        var byGroup: [Group: [Entry]] = [:]210        for r in results?.results ?? [] {211            switch r.type.known {212            case .symbol?:213                let s = r.symbol ?? r.resultId214                byGroup[.symbols, default: []].append(Entry(id: "symbol:\(s)", group: .symbols, title: s, subtitle: r.subtitle, icon: "chart.xyaxis.line", hint: r.assetClass, mono: true,215                                                            run: { model.show(.charting, symbol: s) }, alternate: { model.show(.statements, symbol: s) }))216            case .conversation?:217                byGroup[.conversations, default: []].append(Entry(id: r.id, group: .conversations, title: r.title, subtitle: r.subtitle, icon: "bubble.left", run: { model.openConversation(r.resultId) }))218            case .project?:219                byGroup[.projects, default: []].append(Entry(id: r.id, group: .projects, title: r.title, subtitle: r.subtitle, icon: "books.vertical", run: { model.openProject(r.resultId) }))220            case .note?:221                byGroup[.notes, default: []].append(Entry(id: r.id, group: .notes, title: r.title, subtitle: r.subtitle, icon: "note.text", run: {222                    // a note lives in its project of the Research Studio when it has one223                    if let p = app.sync.active?.notes[r.resultId]?.data.projectId, !p.isEmpty { model.openProject(p) } else { model.show(.studio) }224                }))225            case .watchlist?:226                byGroup[.watchlists, default: []].append(Entry(id: r.id, group: .watchlists, title: r.title, subtitle: r.subtitle, icon: "star", run: { model.watchlistId = r.resultId; model.show(.watchlists) }))227            case .portfolio?:228                byGroup[.portfolios, default: []].append(Entry(id: r.id, group: .portfolios, title: r.title, subtitle: r.subtitle, icon: "briefcase", run: { model.openPortfolio(r.resultId) }))229            case .chart?:230                let symbol = r.symbol ?? app.sync.active?.charts[r.resultId]?.data.symbol231                byGroup[.charts, default: []].append(Entry(id: r.id, group: .charts, title: r.title, subtitle: r.subtitle, icon: "chart.line.uptrend.xyaxis", run: { model.show(.charting, symbol: symbol) }))232            case .action?:233                // the server matches its own (French) vocabulary; the destination is shown under this app's name234                guard let id = serverActionID(r), !scored.contains(where: { $0.1.id == id }) else { continue }235                if let c = commands.first(where: { $0.entry.id == id }) { scored.append((r.score * 0.7, c.entry)) }236                else if case .openEngine(let engine)? = r.action {237                    scored.append((r.score * 0.7, Entry(id: id, group: .actions, title: "Quant Lab: \(r.title)", subtitle: nil, icon: "function", run: { model.openLabTool(engine) })))238                }239            case .report?, .indicator?, nil: continue240            }241        }242        // symbols: the ticker as typed first, then primary listings (no exchange suffix), then the server's order243        var symbols = byGroup[.symbols] ?? []244        let typed = Watchlist.normalize(q)245        symbols = symbols.enumerated().sorted { a, b in246            func rank(_ e: Entry) -> Int { e.title == typed ? 0 : e.title.contains(".") ? 2 : 1 }247            return (rank(a.element), a.offset) < (rank(b.element), b.offset)248        }.map(\.element)249        if let t = typed, !q.contains(" "), q.count <= 12, symbols.first?.title != t {250            symbols.insert(Entry(id: "symbol:\(t)", group: .symbols, title: t, subtitle: "Open the ticker as typed", icon: "chart.xyaxis.line", mono: true,251                                 run: { model.show(.charting, symbol: t) }, alternate: { model.show(.statements, symbol: t) }), at: 0)252        }253        byGroup[.symbols] = Array(symbols.prefix(8))254        scored.sort { $0.0 > $1.0 }255        byGroup[.actions] = scored.prefix(9).map(\.1)256        // a command named by what was typed comes before data that merely contains it257        let actionsFirst = (scored.first?.0 ?? 0) >= 0.8258        let order: [Group] = actionsFirst ? [.actions] + Group.allCases.filter { $0 != .actions } : Group.allCases259        return order.flatMap { g in (byGroup[g] ?? []).prefix(g == .conversations ? 6 : 8) }260    }261262    /// The id of the local command a server `action` result stands for.263    private func serverActionID(_ r: VQSearchResult) -> String? {264        switch r.action {265        case .openEngine(let id)?: return "engine:\(id)"266        case .navigate(let place)?:267            switch PaletteDestination.forPlace(place) {268            case .section(let raw)?: return "section:\(raw)"269            case .newConversation?: return "new-conversation"270            case .labTool(let id)?: return "engine:\(id)"271            case .settings?: return "settings"272            case nil: return nil273            }274        default: return nil275        }276    }277278    private struct Command { var entry: Entry; var keywords: [String] = [] }279280    private func localCommands() -> [Command] {281        var out: [Command] = []282        let extra: [AppSection: [String]] = [283            .research: ["chat", "ask", "agent", "analysis", "home"], .studio: ["projects", "notes", "research"], .overview: ["market", "macro", "calendar", "yield", "terminal"],284            .markets: ["movers", "exchanges", "indices"], .watchlists: ["lists", "symbols"], .charting: ["chart", "graph", "candles"], .statements: ["income", "balance", "cash flow", "ratios", "financials"],285            .quant: ["engines", "lab", "garch", "var", "backtest"], .portfolio: ["positions", "holdings"], .data: ["datasets", "tables"], .risk: ["var", "drawdown"],286            .jobs: ["running", "computations"], .agent: ["memory", "watches"], .documents: ["reports", "pdf"],287        ]288        for (i, s) in AppSection.allCases.enumerated() {289            out.append(Command(entry: Entry(id: "section:\(s.rawValue)", group: .actions, title: "Go to \(s.title)", icon: s.symbol, hint: i < 9 ? "⌘\(i + 1)" : nil, run: { model.show(s) }),290                               keywords: [s.title, s.rawValue] + (extra[s] ?? [])))291        }292        let symbol = model.symbol293        out.append(Command(entry: Entry(id: "new-conversation", group: .actions, title: "New Conversation", subtitle: "Ask the research agent", icon: "sparkles", hint: "⌥⌘N", run: { model.openConversation(nil) }), keywords: ["chat", "ask", "question", "analysis"]))294        out.append(Command(entry: Entry(id: "new-chart-window", group: .actions, title: "New Chart Window", subtitle: symbol, icon: "macwindow.badge.plus", hint: "⇧⌘N", run: { openWindow(id: "chart", value: ChartSpec(symbol: symbol)) }), keywords: ["detach", "window"]))295        out.append(Command(entry: Entry(id: "chart-current", group: .actions, title: "Chart \(symbol)", icon: "chart.xyaxis.line", hint: "⌘G", run: { model.show(.charting) }), keywords: ["chart"]))296        out.append(Command(entry: Entry(id: "statements-current", group: .actions, title: "Statements of \(symbol)", icon: "doc.text.magnifyingglass", run: { model.show(.statements) }), keywords: ["financials", "income", "balance"]))297        out.append(Command(entry: Entry(id: "sync-now", group: .actions, title: "Sync Now", subtitle: app.sync.indicator.label, icon: "arrow.triangle.2.circlepath", hint: "⌥⌘S", run: { Task { await app.sync.syncNow() } }), keywords: ["synchronise", "synchronize", "account"]))298        out.append(Command(entry: Entry(id: "refresh", group: .actions, title: "Refresh Market Data", icon: "arrow.clockwise", hint: "⌘R", run: { Task { await app.market.refresh(); await app.terminal.loadOverview() } }), keywords: ["reload", "quotes"]))299        let dark = isDark300        out.append(Command(entry: Entry(id: "toggle-theme", group: .actions, title: "Toggle Theme", subtitle: dark ? "Switch to the light appearance" : "Switch to the dark appearance", icon: "circle.lefthalf.filled", run: {301            app.settings.theme = dark ? .light : .dark302            app.sync.pushSettings()303        }), keywords: ["dark", "light", "appearance", "mode"]))304        out.append(Command(entry: Entry(id: "settings", group: .actions, title: "Settings…", icon: "gearshape", hint: "⌘,", run: { openSettings() }), keywords: ["preferences", "options", "security", "usage", "devices"]))305        out.append(Command(entry: Entry(id: "lock", group: .actions, title: "Lock VQuant", subtitle: app.settings.appLock ? nil : "App lock is off: opens Settings", icon: "lock", hint: "⌃⌘L", run: {306            if app.settings.appLock { app.session.lock() } else { app.toasts.show("Turn on the app lock in Settings to lock VQuant."); openSettings() }307        }), keywords: ["touch id", "secure"]))308        for t in app.quant.catalogue?.tools ?? [] {309            out.append(Command(entry: Entry(id: "engine:\(t.id)", group: .actions, title: "Quant Lab: \(t.title)", icon: "function", run: { model.openLabTool(t.id) }), keywords: [t.id, t.id.replacingOccurrences(of: "_", with: " "), "engine"]))310        }311        return out312    }313314    private var isDark: Bool {315        switch app.settings.theme {316        case .dark: true317        case .light: false318        case .system: NSApp.effectiveAppearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua319        }320    }321322    // MARK: running323324    private func move(_ delta: Int, _ count: Int) {325        guard count > 0 else { return }326        highlighted = (highlighted + delta + count) % count327    }328329    private func run(_ entries: [Entry], at index: Int, alternate: Bool) {330        guard entries.indices.contains(index) else { return }331        let e = entries[index]332        if e.staysOpen { e.run(); return }333        remember()334        close()335        if alternate, let a = e.alternate { a() } else { e.run() }336    }337338    /// Keeps what was searched in `preference.recentSearches` (synced). Not during automated checks, and never339    /// before the preference object of the account has been read: an empty local copy must not replace it.340    private func remember() {341        let q = trimmed342        guard q.count >= 2, !app.options.isUITest, let s = app.sync.active else { return }343        guard s.preferences[VQObjectID.defaultPreference] != nil || s.status.status.cursor > 0 else { return }344        let next = RecentSearches.adding(q, to: s.preference.recentSearches)345        guard next != s.preference.recentSearches else { return }346        Task { await s.updatePreference { $0.recentSearches = next } }347    }348349    private func close() { model.paletteOpen = false; model.paletteQuery = "" }350}351
Files main
Menu

Theme