SPB Git

Repository Public

CommandPalette.swift 6.3 KB 101 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatUI/Sources/Features/Shell/CommandPalette.swift3// Description: Floating command palette (⌘K): navigation, new chat, model switching and loading, conversation search — keyboard first.4import SwiftUI5import LocalChatCore67struct CommandPalette: View {8    @Environment(AppModel.self) private var app9    @Bindable var router: AppRouter10    @State private var query = ""11    @State private var highlighted = 012    @FocusState private var focused: Bool1314    struct Command: Identifiable {15        let id: String; let title: String; let subtitle: String?; let symbol: String; let run: @MainActor () -> Void16    }1718    private var commands: [Command] {19        var list: [Command] = [Command(id: "new", title: "New chat", subtitle: "⌘N", symbol: "square.and.pencil") { router.newChat(in: app) }]20        list += AppSection.allCases.map { section in Command(id: "go-\(section.rawValue)", title: "Go to \(section.title)", subtitle: nil, symbol: section.symbol) { router.open(section) } }21        list.append(Command(id: "inspector", title: router.showInspector ? "Hide inspector" : "Show inspector", subtitle: nil, symbol: "sidebar.trailing") { router.showInspector.toggle() })22        if !app.snapshot.loaded.isEmpty {23            list.append(Command(id: "unload", title: "Unload all models", subtitle: "Free memory", symbol: "eject") { Task { await app.engine.unloadAll() } })24        }25        if let id = router.conversationID, let controller = app.controller(for: id) {26            for model in app.chatModels.prefix(30) {27                list.append(Command(id: "model-\(model.id)", title: "Use \(model.name)", subtitle: "\(model.backend.displayName)\(model.quantization.map { " · \($0)" } ?? "")", symbol: "cpu") {28                    controller.setModel(model.id); router.open(.chat)29                })30            }31            for preset in InferencePreset.allCases {32                list.append(Command(id: "preset-\(preset.rawValue)", title: "Preset: \(preset.title)", subtitle: preset.summary, symbol: preset.symbol) { controller.setPreset(preset) })33            }34        }35        for model in app.installedModels.prefix(20) where !app.snapshot.isLoaded(model.id) {36            list.append(Command(id: "load-\(model.id)", title: "Load \(model.name)", subtitle: "Into memory", symbol: "arrow.down.circle") { Task { _ = try? await app.engine.load(model) } })37        }38        for conversation in app.conversations.prefix(200) {39            list.append(Command(id: "c-\(conversation.id)", title: conversation.title, subtitle: "Conversation", symbol: "bubble.left") { router.open(conversation: conversation.id) })40        }41        let q = query.trimmingCharacters(in: .whitespaces).lowercased()42        guard !q.isEmpty else { return Array(list.prefix(14)) }43        let terms = q.split(separator: " ")44        return Array(list.filter { command in terms.allSatisfy { command.title.lowercased().contains($0) || (command.subtitle?.lowercased().contains($0) ?? false) } }.prefix(40))45    }4647    var body: some View {48        let items = commands49        ZStack(alignment: .top) {50            Color.black.opacity(0.28).ignoresSafeArea().onTapGesture { close() }51            VStack(spacing: 0) {52                HStack(spacing: 10) {53                    Image(systemName: "command").foregroundStyle(DS.G.accent)54                    TextField("Type a command, a model or a conversation…", text: $query).textFieldStyle(.plain).font(.system(size: 16)).focused($focused)55                        .onSubmit { run(items) }.accessibilityIdentifier("palette-field")56                    Text("esc").font(DS.F.micro).foregroundStyle(DS.C.muted).padding(.horizontal, 6).padding(.vertical, 3).background(DS.C.surface3, in: RoundedRectangle(cornerRadius: 4))57                }58                .padding(14)59                Divider().overlay(DS.C.border)60                ScrollViewReader { proxy in61                    ScrollView {62                        LazyVStack(spacing: 2) {63                            ForEach(Array(items.enumerated()), id: \.element.id) { index, command in64                                Button { command.run(); close() } label: {65                                    HStack(spacing: 10) {66                                        Image(systemName: command.symbol).frame(width: 22).foregroundStyle(index == highlighted ? AnyShapeStyle(DS.G.accent) : AnyShapeStyle(DS.C.text2))67                                        Text(command.title).font(DS.F.body).foregroundStyle(DS.C.text).lineLimit(1)68                                        Spacer()69                                        if let subtitle = command.subtitle { Text(subtitle).font(DS.F.caption).foregroundStyle(DS.C.muted).lineLimit(1) }70                                    }71                                    .padding(.horizontal, 12).padding(.vertical, 8)72                                    .background(index == highlighted ? DS.C.accent.opacity(0.14) : .clear, in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))73                                    .contentShape(Rectangle())74                                }75                                .buttonStyle(.plain).id(index)76                            }77                            if items.isEmpty { Text("No matching command").font(DS.F.callout).foregroundStyle(DS.C.muted).padding(20) }78                        }79                        .padding(6)80                    }81                    .frame(maxHeight: 380)82                    .onChange(of: highlighted) { _, value in proxy.scrollTo(value, anchor: .center) }83                }84            }85            .frame(maxWidth: 620).glassPanel().padding(.top, 80).padding(.horizontal, 20)86        }87        .onAppear { focused = true; highlighted = 0 }88        .onChange(of: query) { highlighted = 0 }89        .onKeyPress(.downArrow) { highlighted = min(highlighted + 1, max(0, items.count - 1)); return .handled }90        .onKeyPress(.upArrow) { highlighted = max(highlighted - 1, 0); return .handled }91        .onKeyPress(.escape) { close(); return .handled }92        .accessibilityAddTraits(.isModal)93    }9495    private func run(_ items: [Command]) {96        guard items.indices.contains(highlighted) else { return }97        items[highlighted].run(); close()98    }99    private func close() { router.showPalette = false; query = "" }100}101
Files main
Menu

Theme