SPB Git

Repository Public

CommandPalette.swift 5.9 KB 123 lines swift

1import MCCCore2import SwiftUI34/// One entry of the command palette: a navigation target, a command, or a search result.5struct PaletteEntry: Identifiable {6    enum Kind { case section(SidebarItem), command, result(API.SearchResult) }7    let id: String8    let title: String9    let subtitle: String10    let symbol: String11    let kind: Kind12    let run: @MainActor () -> Void13}1415/// ⌘K: type to jump to a section, run a command or find any object through `GET /search`.16struct CommandPaletteView: View {17    @Environment(AppModel.self) private var app18    @Environment(\.mccTheme) private var theme19    @Environment(\.dismiss) private var dismiss20    @State private var search: SearchModel?21    @State private var text = ""22    @State private var highlighted = 023    @FocusState private var focused: Bool2425    private var entries: [PaletteEntry] {26        let q = text.trimmingCharacters(in: .whitespaces)27        var out: [PaletteEntry] = Self.staticEntries(app: app, dismiss: { dismiss() })28            .filter { q.isEmpty || $0.title.localizedCaseInsensitiveContains(q) }29        for r in search?.results ?? [] {30            out.append(PaletteEntry(id: "r-\(r.kind.rawValue)-\(r.id)", title: r.title,31                                    subtitle: [r.kind.label, r.subtitle, r.state].compactMap { $0 }.joined(separator: " · "),32                                    symbol: r.kind.symbol, kind: .result(r)) { app.open(r); dismiss() })33        }34        return out35    }3637    @MainActor38    static func staticEntries(app: AppModel, dismiss: @escaping @MainActor () -> Void) -> [PaletteEntry] {39        var out = SidebarItem.allCases.filter { $0.permission.map(app.session.can) ?? true }.map { item in40            PaletteEntry(id: "s-\(item.rawValue)", title: item.title, subtitle: tr("palette.go"), symbol: item.symbol, kind: .section(item)) {41                app.show(item); dismiss()42            }43        }44        out.append(PaletteEntry(id: "c-refresh", title: tr("menu.refresh"), subtitle: tr("palette.command"), symbol: "arrow.clockwise", kind: .command) {45            app.session.reloadAll(); dismiss()46        })47        out.append(PaletteEntry(id: "c-ops", title: tr("menu.operations_centre.enter"), subtitle: tr("palette.command"), symbol: "rectangle.inset.filled", kind: .command) {48            app.operationsCentre = true; app.show(.overview); dismiss()49        })50        if app.session.canMutate, app.session.can("maintenance.write") {51            out.append(PaletteEntry(id: "c-note", title: tr("menu.quick_note"), subtitle: tr("palette.command"), symbol: "note.text.badge.plus", kind: .command) {52                app.quickNoteRequested = true; app.show(.maintenance); dismiss()53            })54        }55        if app.lock.isEnabled {56            out.append(PaletteEntry(id: "c-lock", title: tr("menu.lock"), subtitle: tr("palette.command"), symbol: "lock", kind: .command) {57                app.lock.lockNow(); dismiss()58            })59        }60        return out61    }6263    var body: some View {64        let list = entries65        VStack(spacing: 0) {66            HStack(spacing: Tokens.Space.s3) {67                Image(systemName: "magnifyingglass").foregroundStyle(theme.textSecondary).accessibilityHidden(true)68                TextField(tr("palette.prompt"), text: $text)69                    .textFieldStyle(.plain)70                    .font(.title3)71                    .focused($focused)72                    .onSubmit { run(list) }73                    .accessibilityIdentifier("palette-field")74                if search?.state.isLoading == true { ProgressView().controlSize(.small) }75            }76            .padding(Tokens.Space.s5)77            Divider()78            ScrollViewReader { proxy in79                List {80                    ForEach(Array(list.enumerated()), id: \.element.id) { index, entry in81                        Button { entry.run() } label: {82                            HStack(spacing: Tokens.Space.s3) {83                                Image(systemName: entry.symbol).frame(width: 22).foregroundStyle(theme.textSecondary).accessibilityHidden(true)84                                VStack(alignment: .leading, spacing: 1) {85                                    Text(entry.title).foregroundStyle(theme.textPrimary)86                                    Text(entry.subtitle).font(.caption).foregroundStyle(theme.textSecondary)87                                }88                                Spacer()89                                if index == highlighted { Image(systemName: "return").foregroundStyle(theme.textTertiary).accessibilityHidden(true) }90                            }91                            .contentShape(Rectangle())92                        }93                        .buttonStyle(.plain)94                        .listRowBackground(index == highlighted ? theme.hover : Color.clear)95                        .id(entry.id)96                        .accessibilityAddTraits(index == highlighted ? .isSelected : [])97                    }98                    if list.isEmpty {99                        Text(search?.state.error != nil ? tr("search.unavailable") : tr("search.no_results")).foregroundStyle(theme.textSecondary)100                    }101                }102                .listStyle(.plain)103                .onChange(of: highlighted) { _, i in if list.indices.contains(i) { proxy.scrollTo(list[i].id) } }104            }105        }106        .frame(width: 560, height: 420)107        .background(theme.surface)108        .onAppear {109            if search == nil { search = SearchModel(session: app.session) }110            focused = true111        }112        .onChange(of: text) { _, new in search?.query = new; highlighted = 0 }113        .onKeyPress(.downArrow) { highlighted = min(highlighted + 1, max(0, list.count - 1)); return .handled }114        .onKeyPress(.upArrow) { highlighted = max(highlighted - 1, 0); return .handled }115        .onExitCommand { dismiss() }116    }117118    private func run(_ list: [PaletteEntry]) {119        guard list.indices.contains(highlighted) else { return }120        list[highlighted].run()121    }122}123
Files main
Menu

Theme