SPB Git

Repository Public

CommandCenterModel.swift 9.3 KB 195 lines swift

1// SP Notes Core2// File: Sources/SPNotesFeatures/Command/CommandCenterModel.swift3// Description: View model of the command centre: the query, the sections of rows (recents and commands by section when4//              the query is empty; ranked commands and local pages otherwise), the keyboard selection and activation.5//              Pages come from the local full-text index only (free, offline) and are re-ranked by title like the web6//              palette does (+6, + recency).7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import Observation12import SPNotesSync1314public struct CommandRow: Identifiable {15    public enum Target {16        case command(FeatureCommand)17        case page(id: String, blockId: String?)18    }1920    public var id: String21    public var title: String22    public var subtitle: String?23    public var systemImage: String?24    /// An emoji icon (pages).25    public var emoji: String?26    public var shortcut: String?27    /// Matched characters of the title (Character indexes) for highlighting.28    public var positions: [Int]29    public var target: Target30}3132public struct CommandSection: Identifiable {33    public var title: String34    public var rows: [CommandRow]35    public var id: String { title }36}3738@Observable @MainActor39public final class CommandCenterModel {40    public let registry: CommandRegistry41    public private(set) var sections: [CommandSection] = []42    public private(set) var selectedId: String?43    public var query: String = "" {44        didSet { if query != oldValue { selectionMoved = false; refresh() } }45    }46    /// Called after a row ran (the host closes the palette).47    public var onDismiss: (() -> Void)?4849    private let search: SearchRepository?50    private weak var router: (any FeatureRouter)?51    private var pages: [CommandRow] = []52    private var pagesQuery = ""53    private var pagesTopScore = -154    /// The user moved the selection since the query changed: results arriving later must not move it.55    private var selectionMoved = false56    private var pageTask: Task<Void, Never>?5758    public static let recentLimit = 559    public static let pageLimit = 106061    /// - Parameter repositories: when given, pages of the device are searchable from the palette (needs `router`).62    public init(registry: CommandRegistry, repositories: NotesRepositories? = nil, router: (any FeatureRouter)? = nil, onDismiss: (() -> Void)? = nil) {63        self.registry = registry64        search = router == nil ? nil : repositories?.search65        self.router = router66        self.onDismiss = onDismiss67        refresh()68    }6970    public var rows: [CommandRow] { sections.flatMap(\.rows) }71    public var isEmpty: Bool { sections.allSatisfy { $0.rows.isEmpty } }72    public var selectedRow: CommandRow? { rows.first { $0.id == selectedId } }7374    /// Rebuilds the rows (also call it when the palette opens: availability may have changed).75    public func refresh() {76        let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines)77        var built: [CommandSection] = []78        if trimmed.isEmpty {79            pageTask?.cancel()80            pages = []81            pagesQuery = ""82            let available = registry.available83            let byId = Dictionary(available.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })84            var recentRows: [CommandRow] = []85            for recent in registry.recents {86                guard recentRows.count < Self.recentLimit else { break }87                switch recent.kind {88                case .command:89                    if let command = byId[recent.id] { recentRows.append(Self.row(command, positions: [], prefix: "recent.")) }90                case .page:91                    guard router != nil else { continue }92                    recentRows.append(CommandRow(id: "recent.page." + recent.id, title: recent.title ?? L("Sans titre"), subtitle: L("Page"), systemImage: "doc.text",93                                                 emoji: recent.icon, shortcut: nil, positions: [], target: .page(id: recent.id, blockId: nil)))94                }95            }96            if !recentRows.isEmpty { built.append(CommandSection(title: L("Récents"), rows: recentRows)) }97            var order: [String] = []98            var groups: [String: [CommandRow]] = [:]99            for command in available.sorted(by: { $0.priority > $1.priority }) {100                if groups[command.section] == nil { order.append(command.section) }101                groups[command.section, default: []].append(Self.row(command, positions: []))102            }103            // Sections keep the registration order of their first command.104            let firstSeen = Dictionary(available.enumerated().map { ($0.element.section, $0.offset) }, uniquingKeysWith: { a, _ in a })105            for section in order.sorted(by: { (firstSeen[$0] ?? 0) < (firstSeen[$1] ?? 0) }) {106                built.append(CommandSection(title: section, rows: groups[section] ?? []))107            }108        } else {109            let ranked = registry.ranked(trimmed)110            if !ranked.isEmpty {111                built.append(CommandSection(title: L("Commandes"), rows: ranked.map { Self.row($0.item, positions: $0.positions, subtitle: $0.item.subtitle ?? $0.item.section) }))112            }113            if pagesQuery == trimmed, !pages.isEmpty {114                // The section with the best match comes first (a page whose title starts with the query beats a loose command match).115                let pagesSection = CommandSection(title: L("Pages"), rows: pages)116                if pagesTopScore > (ranked.first?.score ?? -1) { built.insert(pagesSection, at: 0) } else { built.append(pagesSection) }117            }118            searchPages(trimmed)119        }120        sections = built121        let all = built.flatMap(\.rows)122        if !selectionMoved || selectedId == nil || !all.contains(where: { $0.id == selectedId }) { selectedId = all.first?.id }123    }124125    private static func row(_ command: FeatureCommand, positions: [Int], prefix: String = "", subtitle: String? = nil) -> CommandRow {126        CommandRow(id: prefix + "command." + command.id, title: command.title, subtitle: subtitle ?? command.subtitle, systemImage: command.systemImage, emoji: nil,127                   shortcut: command.shortcut, positions: positions, target: .command(command))128    }129130    private func searchPages(_ text: String) {131        guard let search, pagesQuery != text else { return }132        pageTask?.cancel()133        let recents = registry.recents134        pageTask = Task { [weak self] in135            let hits = (try? await search.local(text, limit: 30)) ?? []136            guard !Task.isCancelled, let self else { return }137            var seen = Set<String>()138            let unique = hits.filter { seen.insert($0.pageId).inserted }139            let ranked = Fuzzy.rank(text, unique, title: { $0.title.isEmpty ? L("Sans titre") : $0.title },140                                    boost: { CommandRecents.boost(recents, kind: .page, id: $0.pageId) + 6 }, limit: Self.pageLimit)141            // A page found by its content but not by its title still belongs to the list, after the title matches.142            let rankedIds = Set(ranked.map(\.item.pageId))143            let rest = unique.filter { !rankedIds.contains($0.pageId) }.prefix(max(0, Self.pageLimit - ranked.count))144            self.pages = ranked.map { Self.pageRow($0.item, positions: $0.positions) } + rest.map { Self.pageRow($0, positions: []) }145            self.pagesQuery = text146            self.pagesTopScore = ranked.first?.score ?? -1147            self.pageTask = nil148            if self.query.trimmingCharacters(in: .whitespacesAndNewlines) == text { self.refresh() }149        }150    }151152    private static func pageRow(_ hit: UnifiedSearchResult, positions: [Int]) -> CommandRow {153        CommandRow(id: "page." + hit.pageId, title: hit.title.isEmpty ? L("Sans titre") : hit.title, subtitle: L("Page"), systemImage: "doc.text", emoji: hit.icon,154                   shortcut: nil, positions: positions, target: .page(id: hit.pageId, blockId: nil))155    }156157    /// For the tests: the end of the page search in flight.158    public func waitForPages() async { await pageTask?.value }159160    // MARK: selection161162    public func moveSelection(_ delta: Int) {163        let all = rows164        guard !all.isEmpty else { selectedId = nil; return }165        let current = all.firstIndex { $0.id == selectedId } ?? (delta > 0 ? -1 : 0)166        let next = ((current + delta) % all.count + all.count) % all.count167        selectedId = all[next].id168        selectionMoved = true169    }170171    public func select(_ row: CommandRow) { selectedId = row.id; selectionMoved = true }172173    @discardableResult174    public func runSelected() async -> Bool {175        guard let row = selectedRow else { return false }176        return await run(row)177    }178179    @discardableResult180    public func run(_ row: CommandRow) async -> Bool {181        switch row.target {182        case .command(let command):183            // Close first: the command may present something of its own.184            onDismiss?()185            return await registry.run(id: command.id)186        case .page(let id, let blockId):187            guard let router else { return false }188            registry.remember(CommandRecent(kind: .page, id: id, title: row.title, icon: row.emoji))189            onDismiss?()190            router.openPage(id: id, blockId: blockId)191            return true192        }193    }194}195
Files main
Menu

Theme