SPB Git

Repository Public

CommandPalette.swift 15.2 KB 191 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Home/CommandPalette.swift3// Description: The command palette (⌘K): every action of the app by name, plus jumping to any folder or file of the local mirror. Entirely keyboard-driven; the commands are the real ones (the same closures as menus and toolbar), not shortcuts to them.4import AppKit5import SPDriveCore6import SwiftUI78struct PaletteCommand: Identifiable {9    enum Group: String { case go = "Aller à", selection = "Sélection", file = "Fichier", view = "Présentation", sync = "Synchronisation", app = "Application", item = "Dans votre Drive" }10    let id: String11    let title: String12    var subtitle = ""13    let symbol: String14    var shortcut = ""15    let group: Group16    var keywords = ""17    let run: @MainActor () -> Void18    var haystack: String { NameRules.searchKey(title + " " + keywords + " " + group.rawValue) }19}2021@MainActor enum CommandCatalog {22    /// Every command that makes sense right now, in the order they are listed when nothing is typed.23    static func commands(model: AppModel, nav: Navigator, openWindow: @escaping @MainActor () -> Void, openSettings: @escaping @MainActor () -> Void) -> [PaletteCommand] {24        var out: [PaletteCommand] = []25        let selection = nav.selection.compactMap { model.item($0) }26        let live = selection.filter { !$0.isTrashed }27        let folder = nav.section == .drive ? (nav.folderID ?? model.rootID) : model.rootID28        func add(_ id: String, _ title: String, _ symbol: String, _ group: PaletteCommand.Group, shortcut: String = "", subtitle: String = "", keywords: String = "", _ run: @escaping @MainActor () -> Void) {29            out.append(PaletteCommand(id: id, title: title, subtitle: subtitle, symbol: symbol, shortcut: shortcut, group: group, keywords: keywords, run: run))30        }31        if !live.isEmpty, live.count == selection.count {32            let what = live.count == 1 ? "« \(live[0].name) »" : "\(live.count) éléments"33            if let s = live.first, live.count == 1 {34                add("sel.open", "Ouvrir \(what)", s.isFolder ? "folder" : "arrow.up.forward.app", .selection, shortcut: "⌘↓") { if s.isFolder { nav.go(to: s.id) } else { Task { await model.open(s) } } }35                add("sel.share", "Partager \(what) par lien…", "link", .selection, shortcut: "⇧⌘L", keywords: "lien") { nav.sheet = .share(s) }36                if s.isFolder, model.has(.collab) { add("sel.members", "Membres de \(what)…", "person.2", .selection, keywords: "partage privé rôle inviter") { nav.sheet = .members(s) } }37                if model.has(.ai) { add("sel.ask", "Demander à \(what)…", "sparkles", .selection, keywords: "question ia") { nav.sheet = .ask(s) } }38                add("sel.rename", "Renommer \(what)", "pencil", .selection, shortcut: "↩") { nav.renamingID = s.id }39                if !s.isFolder { add("sel.versions", "Historique des versions de \(what)…", "clock.arrow.circlepath", .selection) { nav.sheet = .versions(s) } }40                add("sel.reveal", "Afficher \(what) dans le Finder", "macwindow", .selection, shortcut: "⇧⌘R") { Task { await model.revealInFinder(s) } }41            }42            add("sel.download", "Télécharger \(what)", "arrow.down.circle", .selection, shortcut: "⌥⌘D") { Task { await model.download(live) } }43            if model.has(.ai), live.contains(where: { !$0.isFolder }) { add("sel.suggest", "Suggestions de rangement pour \(what)…", "sparkles", .selection, keywords: "ia ranger renommer classer organiser") { nav.sheet = .suggest(live.filter { !$0.isFolder }) } }44            add("sel.move", "Déplacer \(what)…", "folder.badge.gearshape", .selection, shortcut: "⇧⌘M") { nav.sheet = .move(live) }45            add("sel.duplicate", "Dupliquer \(what)", "plus.square.on.square", .selection, shortcut: "⌘D") { model.duplicate(live) }46            let starred = live.allSatisfy(\.starred)47            add("sel.star", starred ? "Retirer \(what) des favoris" : "Ajouter \(what) aux favoris", starred ? "star.slash" : "star", .selection, shortcut: "⌃⌘F", keywords: "étoile favori") { model.setStarred(live, !starred) }48            let pinned = live.allSatisfy { model.isPinnedItself($0.id) }49            add("sel.pin", pinned ? "Ne plus garder \(what) hors ligne" : "Garder \(what) disponible hors ligne", pinned ? "pin.slash" : "pin", .selection, shortcut: "⇧⌘P", keywords: "épingler offline") { Task { await model.setPinned(live, !pinned) } }50            add("sel.info", "Lire les informations", "info.circle", .selection, shortcut: "⌘I") { nav.showInspector = true }51            add("sel.trash", "Supprimer \(what) du Drive", "trash", .selection, shortcut: "⌘⌫", keywords: "corbeille effacer") { model.trash(live) }52        }53        for s in [SidebarItem.drive, .recent, .favorites, .offline, .shared, .sharedWithMe, .portals, .collections, .transfers, .conflicts, .activity, .trash, .storage, .admin] where model.isAvailable(s) {54            add("go.\(s.rawValue)", s.title, s.symbol, .go, keywords: "aller ouvrir section") { nav.section = s }55        }56        if nav.section == .drive, let id = nav.folderID, let f = model.item(id) { add("go.parent", "Dossier parent", "arrow.up", .go, shortcut: "⌘↑") { nav.go(to: f.parentID == model.rootID ? nil : f.parentID, direction: .shallower) } }57        if nav.canGoBack { add("go.back", "Précédent", "chevron.left", .go, shortcut: "⌘[") { nav.back() } }58        if let folder {59            add("file.newFolder", "Nouveau dossier", "folder.badge.plus", .file, shortcut: "⇧⌘N", keywords: "créer") { if nav.section != .drive { nav.section = .drive }; nav.sheet = .newFolder(parent: folder) }60            add("file.upload", "Téléverser des fichiers ou des dossiers…", "arrow.up.doc", .file, shortcut: "⌘U", keywords: "envoyer ajouter importer upload") {61                let urls = Pickers.chooseUploads(); if !urls.isEmpty { Task { await model.upload(urls, to: folder) } }62            }63            if let f = model.item(folder) { add("file.portal", "Créer un lien de dépôt…", "tray.and.arrow.down", .file, keywords: "portail recevoir") { nav.sheet = .portal(folder: f) } }64        }65        if model.has(.ai) { add("ai.ask", "Demander à mon Drive…", "sparkles", .file, shortcut: "⌥⌘A", keywords: "question ia ai intelligence modèle") { AskWindow.open() } }66        if model.has(.collections) { add("file.collection", "Nouvelle collection…", "square.stack.3d.up", .file, keywords: "règle intelligente") { nav.sheet = .collection(nil) } }67        add("file.window", "Nouvelle fenêtre", "macwindow.badge.plus", .file, shortcut: "⌘N") { openWindow() }68        add("view.list", "Afficher en liste", "list.bullet", .view, shortcut: "⌘1") { model.settings.gridView = false }69        add("view.grid", "Afficher en grille", "square.grid.2x2", .view, shortcut: "⌘2", keywords: "vignettes icônes") { model.settings.gridView = true }70        add("view.inspector", nav.showInspector ? "Masquer les informations" : "Afficher les informations", "sidebar.trailing", .view, shortcut: "⌘I", keywords: "inspecteur") { nav.showInspector.toggle() }71        add("view.search", "Rechercher dans le Drive", "magnifyingglass", .view, shortcut: "⌘F") { DispatchQueue.main.async { WindowTools.focusSearch(in: WindowTools.keyBrowserWindow) } }72        add("sync.now", "Synchroniser maintenant", "arrow.clockwise", .sync, shortcut: "⌘R") { Task { await model.syncNow() } }73        add("sync.pause", model.settings.syncPaused ? "Reprendre la synchronisation" : "Mettre la synchronisation en pause", model.settings.syncPaused ? "play.fill" : "pause.fill", .sync, keywords: "pause reprendre transferts") { Task { await model.setPaused(!model.settings.syncPaused) } }74        if model.transfers.contains(where: { $0.state == .failed }) { add("sync.retry", "Réessayer les transferts en échec", "arrow.clockwise.circle", .sync) { Task { await model.retryAllFailed() } } }75        if model.transfers.contains(where: { $0.state == .done || $0.state == .cancelled }) { add("sync.clear", "Effacer les transferts terminés", "checkmark.circle.badge.xmark", .sync) { Task { await model.clearFinishedTransfers() } } }76        if let c = model.conflicts.first(where: \.isOpen) { add("sync.conflict", "Régler le conflit sur « \(c.itemName) »…", "exclamationmark.triangle", .sync) { nav.sheet = .conflict(c) } }77        if model.finderReady { add("app.finder", "Ouvrir SP Drive dans le Finder", "folder", .app, shortcut: "⇧⌘O") { Task { await DriveDomain.shared.openInFinder() } } }78        if !model.trash().isEmpty { add("app.emptyTrash", "Vider la corbeille…", "trash.slash", .app) { nav.section = .trash; nav.confirmEmptyTrash = true } }79        add("app.settings", "Paramètres…", "gearshape", .app, shortcut: "⌘,", keywords: "réglages préférences") { openSettings() }80        return out81    }82    /// Commands and items matching what was typed (every word must appear, accents and case ignored).83    static func results(for query: String, commands: [PaletteCommand], model: AppModel, nav: Navigator) -> [PaletteCommand] {84        let words = NameRules.searchKey(query).split(separator: " ").map(String.init)85        guard !words.isEmpty else { return commands }86        var hits = commands.filter { c in let h = c.haystack; return words.allSatisfy { h.contains($0) } }87        // commands whose title starts with what was typed come first88        let first = words[0]89        hits.sort { a, b in let pa = NameRules.searchKey(a.title).hasPrefix(first), pb = NameRules.searchKey(b.title).hasPrefix(first); return pa && !pb }90        if query.trimmingCharacters(in: .whitespaces).count >= 2 {91            var q = LocalSearch(); q.text = query; q.limit = 892            for item in model.search(q) {93                let path = model.path(to: item.id).dropLast().map(\.name).joined(separator: " › ")94                hits.append(PaletteCommand(id: "item.\(item.id)", title: item.name, subtitle: path.isEmpty ? "Mon Drive" : "Mon Drive › " + path, symbol: item.isFolder ? "folder" : "doc", group: .item) {95                    if item.isFolder { nav.go(to: item.id) }96                    else { nav.go(to: item.parentID == model.rootID ? nil : item.parentID); nav.selection = [item.id] }97                })98            }99        }100        return hits101    }102}103104struct CommandPalette: View {105    let model: AppModel106    let nav: Navigator107    @Environment(\.openWindow) private var openWindow108    @Environment(\.openSettings) private var openSettings109    @State private var query = ""110    @State private var index = 0111    @FocusState private var focused: Bool112113    var body: some View {114        let all = CommandCatalog.commands(model: model, nav: nav, openWindow: { openWindow(id: "main") }, openSettings: { NSApp.activate(ignoringOtherApps: true); openSettings() })115        let results = CommandCatalog.results(for: query, commands: all, model: model, nav: nav)116        VStack(spacing: 0) {117            HStack(spacing: SPDTheme.Space.sm) {118                Image(systemName: "command").foregroundStyle(SPDTheme.brand).font(.system(size: 15, weight: .medium))119                TextField("Une commande, un dossier, un fichier…", text: $query).textFieldStyle(.plain).font(.system(size: 17)).focused($focused)120                    .onSubmit { run(results) }.accessibilityIdentifier("palette-field")121                Text("esc").font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textTertiary).padding(.horizontal, 5).padding(.vertical, 1).overlay(RoundedRectangle(cornerRadius: 4).strokeBorder(SPDTheme.hairline))122            }123            .padding(.horizontal, SPDTheme.Space.lg).frame(height: 50)124            Rectangle().fill(SPDTheme.hairline).frame(height: 1)125            if results.isEmpty {126                Text("Aucune commande ni aucun élément pour « \(query) ».").font(SPDTheme.Typo.callout).foregroundStyle(SPDTheme.textSecondary).padding(SPDTheme.Space.xl)127            } else {128                ScrollViewReader { proxy in129                    ScrollView {130                        LazyVStack(alignment: .leading, spacing: 1) {131                            ForEach(Array(results.enumerated()), id: \.element.id) { i, c in132                                if i == 0 || results[i - 1].group != c.group { Text(c.group.rawValue).spdEyebrow().padding(.horizontal, SPDTheme.Space.md).padding(.top, SPDTheme.Space.sm).padding(.bottom, 2) }133                                PaletteRow(command: c, selected: i == index).id(c.id)134                                    .onTapGesture { index = i; run(results) }135                            }136                        }137                        .padding(SPDTheme.Space.sm)138                    }139                    .frame(maxHeight: 380)140                    .onChange(of: index) { _, i in if results.indices.contains(i) { proxy.scrollTo(results[i].id) } }141                }142            }143        }144        .frame(width: SPDTheme.Size.palette)145        .background(.regularMaterial, in: RoundedRectangle(cornerRadius: SPDTheme.Radius.lg, style: .continuous))146        .overlay(RoundedRectangle(cornerRadius: SPDTheme.Radius.lg, style: .continuous).strokeBorder(SPDTheme.hairline))147        .spdElevation(.e2)148        .background(KeyCatcher { e in149            guard nav.showPalette else { return false }150            switch e.keyCode {151            case Key.down: index = min(index + 1, max(results.count - 1, 0)); return true152            case Key.up: index = max(index - 1, 0); return true153            case Key.escape: close(); return true154            case Key.return, Key.enter: run(results); return true155            default: return false156            }157        })158        .onChange(of: query) { _, _ in index = 0 }159        .onAppear { focused = true }160        .accessibilityAddTraits(.isModal).accessibilityLabel("Palette de commandes")161    }162    private func close() { spdAnimate(.dismiss) { nav.showPalette = false } }163    private func run(_ results: [PaletteCommand]) {164        guard results.indices.contains(index) else { return }165        let c = results[index]166        close()167        c.run()168    }169}170171private struct PaletteRow: View {172    let command: PaletteCommand173    let selected: Bool174    var body: some View {175        HStack(spacing: SPDTheme.Space.md) {176            Image(systemName: command.symbol).frame(width: 20).foregroundStyle(selected ? SPDTheme.onBrand : SPDTheme.brand)177            VStack(alignment: .leading, spacing: 0) {178                Text(command.title).font(SPDTheme.Typo.body).lineLimit(1).truncationMode(.middle)179                if !command.subtitle.isEmpty { Text(command.subtitle).font(SPDTheme.Typo.caption).foregroundStyle(selected ? SPDTheme.onBrand.opacity(0.8) : SPDTheme.textTertiary).lineLimit(1).truncationMode(.head) }180            }181            Spacer()182            if !command.shortcut.isEmpty { Text(command.shortcut).font(SPDTheme.Typo.callout).foregroundStyle(selected ? SPDTheme.onBrand.opacity(0.85) : SPDTheme.textTertiary) }183        }184        .padding(.horizontal, SPDTheme.Space.md).padding(.vertical, 6)185        .foregroundStyle(selected ? SPDTheme.onBrand : SPDTheme.textPrimary)186        .background(selected ? SPDTheme.brand : .clear, in: RoundedRectangle(cornerRadius: SPDTheme.Radius.sm, style: .continuous))187        .contentShape(Rectangle())188        .accessibilityElement(children: .combine).accessibilityAddTraits(selected ? [.isSelected, .isButton] : .isButton)189    }190}191
Files main
Menu

Theme