SPB Git

Repository Public

CommandPaletteView.swift 14.9 KB 288 lines swift

1import AIAssistant2import DesignSystem3import SwiftUI4import TerminalCore5import WorkspaceKit67struct PaletteItem: Identifiable {8    let id: String9    var title: String10    var subtitle: String = ""11    var shortcut: String = ""12    var icon: String = "command"13    var run: @MainActor () -> Void14}1516/// Looks for developer tools in the usual install locations (a GUI app's PATH is minimal).17enum ToolLocator {18    static var searchDirectories: [String] {19        let home = NSHomeDirectory()20        let fromEnvironment = AgentCLICatalog.directories(fromPATH: ProcessInfo.processInfo.environment["PATH"] ?? "")21        let extra = ["/opt/homebrew/bin", "/usr/local/bin", "\(home)/.local/bin", "\(home)/bin", "\(home)/.claude/local", "\(home)/.npm-global/bin",22                     "\(home)/.bun/bin", "\(home)/.cargo/bin", "/usr/bin", "/bin"]23        var seen = Set<String>()24        return (fromEnvironment + extra).filter { seen.insert($0).inserted }25    }2627    /// Results of the file-system probes, kept for a minute: the palette opens often and the set28    /// of installed tools changes rarely.29    @MainActor private static var cache: (at: Date, found: [String: String?], agents: [DetectedAgentCLI]?) = (.distantPast, [:], nil)30    @MainActor private static func fresh() {31        if Date().timeIntervalSince(cache.at) > 60 { cache = (Date(), [:], nil) }32    }3334    @MainActor static func find(_ name: String) -> String? {35        fresh()36        if let known = cache.found[name] { return known }37        let path = searchDirectories.map { $0 + "/" + name }.first { FileManager.default.isExecutableFile(atPath: $0) }38        cache.found[name] = .some(path)39        return path40    }4142    /// Installed agent CLIs. Detection only: nothing is launched and no credential is touched.43    @MainActor static func agents() -> [DetectedAgentCLI] {44        fresh()45        if let known = cache.agents { return known }46        let detected = AgentCLICatalog().detect(in: searchDirectories)47        cache.agents = detected48        return detected49    }50}5152extension AppModel {53    /// Everything the command palette can do right now.54    func paletteItems(for window: WindowState) -> [PaletteItem] {55        var items: [PaletteItem] = AppAction.allCases.map { action in56            PaletteItem(id: "action." + action.rawValue, title: action.title, subtitle: action.category.rawValue,57                        shortcut: action.chord(in: settings)?.symbolic ?? "", icon: action.symbol) { [weak self, weak window] in58                self?.perform(action, in: window)59            }60        }61        for preset in WorkspacePreset.allCases {62            items.append(PaletteItem(id: "preset." + preset.rawValue, title: "Open Preset: " + preset.title, subtitle: preset.summary, icon: "square.grid.2x2") { [weak self, weak window] in63                guard let self, let window else { return }64                if preset == .sshFleet { window.sheet = .fleetPicker } else { self.open(preset: preset, replacing: window) }65            })66        }67        for workspace in savedWorkspaces {68            items.append(PaletteItem(id: "workspace." + workspace.id.uuidString, title: "Open Workspace: " + workspace.name,69                                     subtitle: "\(workspace.paneCount) sessions — starts new processes", icon: "rectangle.3.group") { [weak self] in70                self?.open(workspace: workspace)71            })72        }73        for host in hosts {74            items.append(PaletteItem(id: "ssh." + host.id.uuidString, title: "SSH: " + host.label, subtitle: host.group ?? "OpenSSH", icon: "network") { [weak self, weak window] in75                guard let self, let window else { return }76                self.openSSH(host, in: window)77            })78        }79        for snippet in snippets {80            items.append(PaletteItem(id: "snippet." + snippet.id.uuidString, title: "Snippet: " + snippet.name, subtitle: snippet.template, icon: "text.badge.plus") { [weak window] in81                window?.sheet = .snippet(SnippetRun(snippetID: snippet.id, pane: window?.focusedPane))82            })83        }84        for shell in ShellCatalog.installedShells() {85            items.append(PaletteItem(id: "shell." + shell.path, title: "New Tab: " + shell.name, subtitle: shell.path, icon: "terminal") { [weak self, weak window] in86                guard let self, let window else { return }87                self.newTab(in: window, kind: .localShell(path: shell.path))88            })89        }90        for agent in ToolLocator.agents() {91            items.append(PaletteItem(id: "agent." + agent.cli.id, title: "Run Agent CLI: " + agent.cli.displayName,92                                     subtitle: agent.executablePath + " — in a new pane, with its own PTY", icon: "sparkle") { [weak self, weak window] in93                guard let self, let window else { return }94                self.split(axis: .horizontal, in: window, kind: .command(line: agent.executablePath))95            })96        }97        if let tmux = ToolLocator.find("tmux") {98            items.append(PaletteItem(id: "tmux.attach", title: "tmux: Attach or Create Persistent Session “spterm”",99                                     subtitle: "Real persistence across app restarts is provided by tmux (\(tmux))", icon: "pin") { [weak self, weak window] in100                guard let self, let window else { return }101                self.newTab(in: window, kind: .command(line: "\(tmux) new-session -A -s spterm"))102            })103        }104        if let zellij = ToolLocator.find("zellij") {105            items.append(PaletteItem(id: "zellij.attach", title: "zellij: Attach or Create Session “spterm”", subtitle: zellij, icon: "pin") { [weak self, weak window] in106                guard let self, let window else { return }107                self.newTab(in: window, kind: .command(line: "\(zellij) attach -c spterm"))108            })109        }110        for theme in ThemeCatalog.all {111            items.append(PaletteItem(id: "theme." + theme.id, title: "Theme: " + theme.name, subtitle: theme.isDark ? "Dark" : "Light", icon: "paintpalette") { [weak self] in112                guard let self else { return }113                if theme.isDark { self.settings.darkThemeID = theme.id; self.settings.appearance = .dark }114                else { self.settings.lightThemeID = theme.id; self.settings.appearance = .light }115            })116        }117        for screen in screens() {118            items.append(PaletteItem(id: "screen.new.\(screen.id)", title: "New Window on " + screen.name, subtitle: "Display", icon: "display") { [weak self] in119                self?.openWindow(on: screen.id)120            })121            items.append(PaletteItem(id: "screen.move.\(screen.id)", title: "Move Window to " + screen.name, subtitle: "Display", icon: "display") { [weak self, weak window] in122                guard let self, let window else { return }123                self.moveWindow(window, toScreen: screen.id)124            })125        }126        for other in windows where other.id != window.id {127            items.append(PaletteItem(id: "merge.\(other.id)", title: "Merge Window Here: " + (other.selectedTab.map(tabTitle) ?? "window"),128                                     subtitle: "Brings its tabs into this window without ending sessions", icon: "arrow.triangle.merge") { [weak self, weak window, weak other] in129                guard let self, let window, let other else { return }130                self.mergeWindow(other, into: window)131            })132        }133        for owner in windows {134            for tab in owner.tabs {135                for pane in tab.layout.panes where pane != window.focusedPane {136                    items.append(PaletteItem(id: "goto.\(pane)", title: "Go to Session: " + paneTitle(pane), subtitle: tabTitle(tab), icon: "arrow.right.circle") { [weak self, weak owner] in137                        guard let self, let owner else { return }138                        self.selectTab(tab.id, in: owner)139                        self.focus(pane, in: owner)140                        owner.controller?.window?.makeKeyAndOrderFront(nil)141                    })142                }143            }144        }145        return items146    }147}148149enum Fuzzy {150    /// Subsequence match score (higher is better), `nil` when `query` does not match.151    static func score(_ query: String, in text: String) -> Int? {152        if query.isEmpty { return 0 }153        let needle = Array(query.lowercased()), haystack = Array(text.lowercased())154        var score = 0, position = 0, streak = 0155        for character in needle {156            guard let found = haystack[position...].firstIndex(of: character) else { return nil }157            streak = found == position ? streak + 1 : 0158            score += 10 + streak * 6 - min(found - position, 8)159            if found == 0 || haystack[found - 1] == " " || haystack[found - 1] == ":" { score += 8 }160            position = found + 1161        }162        return score - haystack.count / 8163    }164}165166struct CommandPaletteView: View {167    @Bindable var state: WindowState168    let model: AppModel169    let palette: Palette170    @State private var query = ""171    @State private var selection = 0172    @State private var items: [PaletteItem] = []173    @FocusState private var focused: Bool174    @Environment(\.chrome) private var chrome175176    private var filtered: [PaletteItem] {177        guard !query.isEmpty else { return Array(items.prefix(60)) }178        return items.compactMap { item in Fuzzy.score(query, in: item.title).map { ($0, item) } }179            .sorted { $0.0 > $1.0 }.prefix(60).map(\.1)180    }181182    var body: some View {183        let results = filtered184        let shape = RoundedRectangle(cornerRadius: Radius.xl, style: .continuous)185        VStack(spacing: 0) {186            HStack(spacing: 10) {187                Image(systemName: "command").font(.system(size: TypeScale.title, weight: .medium)).foregroundStyle(palette.accent)188                TextField("Type a command, host, snippet, workspace…", text: $query)189                    .textFieldStyle(.plain).font(.system(size: TypeScale.title))190                    .focused($focused)191                    .onSubmit { run(results) }192                    .accessibilityLabel("Command palette search")193                if !query.isEmpty {194                    Text("\(results.count)").font(.system(size: TypeScale.footnote, design: .rounded)).monospacedDigit()195                        .foregroundStyle(palette.secondary).transition(.opacity)196                }197            }198            .padding(.horizontal, 16).padding(.vertical, 13)199            Rectangle().fill(palette.hairline).frame(height: 1)200            ScrollViewReader { proxy in201                ScrollView {202                    LazyVStack(spacing: 1) {203                        ForEach(Array(results.enumerated()), id: \.element.id) { index, item in204                            let current = index == selection205                            HStack(spacing: 10) {206                                Image(systemName: item.icon).font(.system(size: TypeScale.body))207                                    .frame(width: 24, height: 24)208                                    .foregroundStyle(current ? palette.accent : palette.secondary)209                                    .background(RoundedRectangle(cornerRadius: Radius.s, style: .continuous)210                                        .fill(current ? palette.accent.opacity(0.16) : palette.hover))211                                VStack(alignment: .leading, spacing: 1) {212                                    Text(item.title).font(.system(size: TypeScale.callout, weight: current ? .medium : .regular)).lineLimit(1)213                                    if !item.subtitle.isEmpty {214                                        Text(item.subtitle).font(.system(size: TypeScale.caption)).foregroundStyle(palette.secondary).lineLimit(1)215                                    }216                                }217                                Spacer()218                                if !item.shortcut.isEmpty { KeyCaps(text: item.shortcut, palette: palette) }219                            }220                            .padding(.horizontal, 10).padding(.vertical, 5)221                            .background(RoundedRectangle(cornerRadius: Radius.m, style: .continuous).fill(current ? palette.selected : .clear))222                            .contentShape(Rectangle())223                            .onTapGesture { selection = index; run(results) }224                            .id(item.id)225                            .accessibilityElement(children: .combine)226                            .accessibilityAddTraits(current ? [.isSelected, .isButton] : .isButton)227                        }228                        if results.isEmpty {229                            EmptyStateView(icon: "questionmark.circle", title: "No matching command",230                                           message: "Try a shorter query: actions, hosts, snippets, workspaces and themes are searched by name.", palette: palette)231                                .padding(.vertical, 10)232                        }233                    }234                    .padding(6)235                    .animation(chrome.motion.snappy, value: selection)236                }237                .frame(height: min(352, CGFloat(max(results.count, 3)) * 37 + 12))238                .onChange(of: selection) { _, value in239                    if results.indices.contains(value) { proxy.scrollTo(results[value].id) }240                }241            }242            Rectangle().fill(palette.hairline).frame(height: 1)243            HStack(spacing: 12) {244                hint("↑↓", "Navigate")245                hint("↩", "Run")246                hint("esc", "Close")247                Spacer()248                Text("SP Term").font(.system(size: TypeScale.caption, weight: .medium)).foregroundStyle(palette.secondary.opacity(0.7))249            }250            .padding(.horizontal, 14).padding(.vertical, 7)251            .accessibilityHidden(true)252        }253        .frame(width: 600)254        .floatingSurface(shape, stroke: palette.hairline)255        .clipShape(shape)256        .shadow(color: .black.opacity(0.38), radius: 30, y: 14)257        .onAppear {258            items = model.paletteItems(for: state)259            focused = true260        }261        .onChange(of: query) { _, _ in selection = 0 }262        .onKeyPress(.downArrow) { selection = min(selection + 1, max(results.count - 1, 0)); return .handled }263        .onKeyPress(.upArrow) { selection = max(selection - 1, 0); return .handled }264        .onKeyPress(.escape) { close(); return .handled }265        .onExitCommand { close() }266        .accessibilityAddTraits(.isModal)267    }268269    private func hint(_ key: String, _ label: String) -> some View {270        HStack(spacing: 5) {271            KeyCaps(text: key, palette: palette)272            Text(label).font(.system(size: TypeScale.caption)).foregroundStyle(palette.secondary)273        }274    }275276    private func run(_ results: [PaletteItem]) {277        guard results.indices.contains(selection) else { return }278        let item = results[selection]279        close()280        item.run()281    }282283    private func close() {284        state.paletteVisible = false285        model.focusCurrentPane(in: state)286    }287}288
Files main
Menu

Theme