SPB Git

Repository Public

CommandPaletteView.swift 7.6 KB 156 lines swift

1// SP Notes iOS2// File: Features/Commands/CommandPaletteView.swift3// Description: The command palette (⌘K): a native overlay with a text field and the commands that match, the best first — go to4//              a place, open a note by its title, new note, capture, sync, appearance, settings. Entirely usable from the5//              keyboard (↑ ↓ Return Esc) and by touch (« Plus », the search screen).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SPNotesCore10import SPNotesDesign11import SwiftUI1213struct CommandPaletteOverlay: View {14    @Environment(AppModel.self) private var app15    @Environment(ShellState.self) private var shell16    @Environment(\.accessibilityReduceMotion) private var reduceMotion17    @AppStorage("appearance") private var appearanceRaw = Appearance.system.rawValue18    let actions: ShellActions1920    var body: some View {21        ZStack(alignment: .top) {22            if shell.isPaletteOpen {23                Color.black.opacity(0.28).ignoresSafeArea()24                    .onTapGesture { close() }25                    .accessibilityLabel("Fermer la palette")26                    .accessibilityAddTraits(.isButton)27                    .transition(.opacity)28                CommandPalettePanel(model: CommandPaletteModel(29                    commands: CommandRegistry.commands(sections: shell.sections, appearance: Appearance(rawValue: appearanceRaw) ?? .system),30                    notes: Self.noteSearch(store: app.store)), onRun: run, onClose: close)31                    .padding(.horizontal, NVSpace.lg)32                    .padding(.top, shell.isCompact ? NVSpace.sm : 72)33                    .transition(reduceMotion ? .opacity : .opacity.combined(with: .scale(scale: 0.97, anchor: .top)))34            }35        }36        .nvAnimation(.fast, value: shell.isPaletteOpen)37    }3839    private func close() { shell.isPaletteOpen = false }4041    private func run(_ command: PaletteCommand) {42        close()43        Haptics.selection()44        actions.run(command.action)45    }4647    /// Notes by title or text from the local store (recent ones when nothing is typed).48    static func noteSearch(store: NotesStore) -> @Sendable (String) async -> [PaletteCommand] {49        { text in50            let trimmed = text.trimmingCharacters(in: .whitespaces)51            if trimmed.isEmpty {52                let recent = ((try? await store.summaries(list: .recent, limit: 8)) ?? []).filter { $0.kind.isLinkable }53                return recent.prefix(4).map { .note(id: $0.id, title: $0.title, subtitle: String(localized: "Note récente")) }54            }55            let hits = (try? await store.search(query: trimmed, limit: 12)) ?? []56            return hits.map(\.page).filter { $0.kind.isLinkable && $0.deletedAt == nil }.map { .note(id: $0.id, title: $0.title, subtitle: nil) }57        }58    }59}6061struct CommandPalettePanel: View {62    @State var model: CommandPaletteModel63    let onRun: (PaletteCommand) -> Void64    let onClose: () -> Void65    @FocusState private var focused: Bool6667    var body: some View {68        VStack(spacing: 0) {69            HStack(spacing: NVSpace.sm) {70                Image(systemName: "command").foregroundStyle(NVColor.fgMuted).accessibilityHidden(true)71                TextField("Aller à, ouvrir une note, lancer une action…", text: $model.query)72                    .textFieldStyle(.plain)73                    .font(.title3)74                    .autocorrectionDisabled()75                    .textInputAutocapitalization(.never)76                    .submitLabel(.go)77                    .focused($focused)78                    .onSubmit { if let command = model.selected { onRun(command) } }79                    .onKeyPress(.downArrow) { model.move(1); return .handled }80                    .onKeyPress(.upArrow) { model.move(-1); return .handled }81                    .onKeyPress(.escape) { onClose(); return .handled }82                    .onKeyPress(.return) { if let command = model.selected { onRun(command) }; return .handled }83                    .accessibilityIdentifier("palette-field")84                Button { onClose() } label: {85                    Image(systemName: "xmark.circle.fill").font(.title3).foregroundStyle(NVColor.fgMuted).frame(minWidth: 44, minHeight: 44)86                }87                .buttonStyle(.plain)88                .accessibilityLabel("Fermer la palette")89                .accessibilityIdentifier("palette-close")90            }91            .padding(.leading, NVSpace.lg)92            .padding(.trailing, NVSpace.xs)93            .padding(.vertical, NVSpace.xs)94            Divider().overlay(NVColor.line)95            if model.results.isEmpty {96                Text("Aucune commande ni note ne correspond.")97                    .font(.subheadline).foregroundStyle(NVColor.fgMuted)98                    .frame(maxWidth: .infinity, alignment: .leading)99                    .padding(NVSpace.lg)100                    .accessibilityIdentifier("palette-empty")101            } else {102                ScrollViewReader { proxy in103                    ScrollView {104                        LazyVStack(spacing: 2) {105                            ForEach(Array(model.results.enumerated()), id: \.element.id) { index, command in106                                row(command, isSelected: index == model.selection).id(command.id)107                            }108                        }109                        .padding(NVSpace.sm)110                    }111                    // as tall as its rows, up to a limit (a scroll view alone would take all the height offered)112                    .frame(height: min(CGFloat(model.results.count) * 50 + 2 * NVSpace.sm, 420))113                    .onChange(of: model.selection) { _, _ in if let id = model.selected?.id { proxy.scrollTo(id) } }114                }115            }116        }117        .frame(maxWidth: 620)118        .nvGlass(radius: NVRadius.xl)119        .shadow(color: .black.opacity(0.18), radius: 28, y: 12)120        .accessibilityElement(children: .contain)121        .accessibilityIdentifier("command-palette")122        .accessibilityAddTraits(.isModal)123        .onAppear { focused = true }124    }125126    private func row(_ command: PaletteCommand, isSelected: Bool) -> some View {127        Button { onRun(command) } label: {128            HStack(spacing: NVSpace.md) {129                Image(systemName: command.symbol)130                    .font(.body)131                    .foregroundStyle(isSelected ? NVColor.accentFg : NVColor.accent)132                    .frame(width: 28)133                    .accessibilityHidden(true)134                VStack(alignment: .leading, spacing: 1) {135                    Text(command.title).font(.body).foregroundStyle(isSelected ? NVColor.accentFg : NVColor.fg).lineLimit(2)136                    if let subtitle = command.subtitle {137                        Text(subtitle).font(.caption).foregroundStyle(isSelected ? NVColor.accentFg.opacity(0.85) : NVColor.fgMuted).lineLimit(1)138                    }139                }140                Spacer(minLength: NVSpace.sm)141                if let shortcut = command.shortcut {142                    Text(shortcut).font(.caption.monospaced()).foregroundStyle(isSelected ? NVColor.accentFg.opacity(0.9) : NVColor.fgMuted)143                        .accessibilityLabel("Raccourci \(shortcut)")144                }145            }146            .padding(.horizontal, NVSpace.md)147            .frame(minHeight: 44)148            .background(isSelected ? NVColor.accent : Color.clear, in: NVRadius.shape(NVRadius.md))149            .contentShape(NVRadius.shape(NVRadius.md))150        }151        .buttonStyle(.plain)152        .accessibilityIdentifier("palette-row")153        .accessibilityAddTraits(isSelected ? .isSelected : [])154    }155}156
Files main
Menu

Theme