SPB Git

Repository Public

BlocksCommandTests.swift 12.1 KB 209 lines swift

1// SP Notes Core2// File: Tests/SPNotesFeaturesTests/BlocksCommandTests.swift3// Description: The command centre: the fuzzy matcher (the cases of the web tests `tests/unit/next-web-core.test.ts`, ported,4//              plus French and edge cases), the ranking, the recents, the registry (register / replace / unregister /5//              availability / run) and the palette model (sections, selection, page search, activation).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import SPNotesSync11import Testing12@testable import SPNotesFeatures13@testable import SPNotesFeaturesCatalog1415@Suite("Blocks · command centre: fuzzy search")16struct FuzzyTests {17    private func score(_ query: String, _ text: String) -> Int { Fuzzy.match(query, text)?.score ?? -1 }1819    @Test("exact > prefix > substring > subsequence; accents and case ignored; non-matches rejected (web cases)")20    func ordering() {21        #expect(score("home", "Home") > score("home", "Homework"))22        #expect(score("home", "Homework") > score("home", "Go home"))23        #expect(score("home", "Go home") > score("hm", "Home"))24        #expect(Fuzzy.match("xyz", "Home") == nil)25        #expect(Fuzzy.match("", "anything")?.score == 0)26        #expect(Fuzzy.match("references", "Références") != nil)27        #expect(Fuzzy.match("REF", "références") != nil)28        #expect(Fuzzy.match("np", "New page")?.positions == [0, 4])29        #expect(score("np", "New page") > score("np", "snapshot"))30        #expect(Fuzzy.match("dark mode", "Dark theme mode sombre") != nil)31        #expect(Fuzzy.match("dark zzz", "Dark theme") == nil)32        #expect(Fuzzy.match("abc", "a-b-c")?.positions.count == 3)33    }3435    @Test("the exact scores of the web rules")36    func exactScores() {37        #expect(score("home", "Home") == 1000)38        #expect(score("home", "Homework") == 800 + 50)                      // prefix + coverage 4/839        #expect(score("home", "Go home") == 600 + 80 - 3)                   // substring on a word boundary at 340        #expect(score("ome", "Go home") == 600 - 4)                         // substring inside a word at 441        #expect(score("np", "New page") == 16 + 16 - 3 - 1)                 // two boundaries, gap 3, length 8/12 → 142        #expect(score("hm", "Home") == 16 + 2 - 1 - 0)                      // boundary, then a loose character after a gap of 143        #expect(Fuzzy.match("  Home  ", "home")?.score == 1000)             // the query is trimmed44        #expect(Fuzzy.match("a", "") == nil)45    }4647    @Test("French: diacritics on both sides, positions index the original characters, camelCase boundaries")48    func french() {49        #expect(Fuzzy.match("tache", "Tâches")?.positions == [0, 1, 2, 3, 4])50        #expect(Fuzzy.match("tâche", "Taches")?.score == score("tache", "Taches"))51        #expect(score("sante", "Santé des connaissances") > score("sante", "Présentation de santé"))52        #expect(Fuzzy.match("cc", "CommandCenter")?.positions == [0, 7])53        #expect(Fuzzy.match("bd", "Base de données")?.positions == [0, 5])54        #expect(Fuzzy.match("œuvre", "Œuvre complète") != nil)55        // A boundary jump never loses a match the plain subsequence would find.56        #expect(Fuzzy.match("abx", "a b abx") != nil)57        #expect(Fuzzy.match("pas", "page spas") != nil)58    }5960    @Test("rank: title beats keywords, boost applies to matches only, stable order, limit (web cases)")61    func rank() {62        struct Item { var t: String; var k: String }63        let items = [Item(t: "Trash", k: "deleted"), Item(t: "Insert diagram", k: "mermaid flowchart"), Item(t: "Diagram notes", k: ""), Item(t: "Settings", k: "diagram")]64        let ranked = Fuzzy.rank("diagram", items, title: { $0.t }, keywords: { $0.k })65        #expect(ranked.map(\.item.t) == ["Diagram notes", "Insert diagram", "Settings"])66        #expect(ranked.last?.positions.isEmpty == true)      // matched through its keywords: nothing to highlight67        let boosted = Fuzzy.rank("diagram", items, title: { $0.t }, keywords: { $0.k }, boost: { $0.t == "Settings" ? 1000 : 0 })68        #expect(boosted.first?.item.t == "Settings")69        #expect(Fuzzy.rank("", items, title: { $0.t }).count == 4)70        #expect(Fuzzy.rank("", items, title: { $0.t }).map(\.item.t) == items.map(\.t))71        #expect(Fuzzy.rank("", items, title: { $0.t }, limit: 2).count == 2)72        #expect(Fuzzy.rank("zzz", items, title: { $0.t }).isEmpty)73        // A boost never makes a non-match appear.74        #expect(Fuzzy.rank("zzz", items, title: { $0.t }, boost: { _ in 5000 }).isEmpty)75    }7677    @Test("recents: most recent first, de-duplicated, capped at 12; boost decreases with rank (web cases)")78    func recents() {79        var list: [CommandRecent] = []80        for index in 0..<15 { list = CommandRecents.push(list, CommandRecent(kind: .command, id: "c\(index)", at: Date(timeIntervalSince1970: Double(index)))) }81        list = CommandRecents.push(list, CommandRecent(kind: .command, id: "c10", at: Date(timeIntervalSince1970: 99)))82        #expect(list.count == 12)83        #expect(list.first?.id == "c10")84        #expect(list.filter { $0.id == "c10" }.count == 1)85        #expect(CommandRecents.boost(list, kind: .command, id: "c10") == 40)86        #expect(CommandRecents.boost(list, kind: .command, id: "c10") > CommandRecents.boost(list, kind: .command, id: "c14"))87        #expect(CommandRecents.boost(list, kind: .page, id: "c10") == 0)88        #expect(CommandRecents.boost(list, kind: .command, id: list.last!.id) == 4)89    }90}9192@Suite("Blocks · command centre: registry and palette")93@MainActor94struct CommandRegistryTests {95    private func command(_ id: String, _ title: String, section: String = "G", keywords: String = "", priority: Int = 0, enabled: Bool = true,96                         run: @escaping @MainActor () -> Void = {}) -> FeatureCommand {97        FeatureCommand(id: id, title: title, keywords: keywords, section: section, priority: priority, isEnabled: { enabled }, action: { run() })98    }99100    @Test("register / replace / unregister by token and owner, availability, run remembers (web cases)")101    func registry() async {102        let store = InMemoryCommandRecents()103        let registry = CommandRegistry(recents: store)104        var ran = 0105        let first = registry.register([command("a", "Alpha") { ran += 1 }, command("b", "Beta", enabled: false)])106        #expect(registry.commands.count == 2)107        #expect(registry.available.map(\.id) == ["a"])108        let second = registry.register([command("a", "Alpha 2")])109        #expect(registry.command(id: "a")?.title == "Alpha 2")110        #expect(registry.commands.map(\.id) == ["a", "b"])          // a replaced command keeps its place111        registry.unregister(first)112        #expect(registry.commands.map(\.id) == ["a"])               // the first registration does not remove its replacement113        registry.unregister(second)114        #expect(registry.commands.isEmpty)115116        registry.register([command("x", "Exporter") { ran += 10 }, command("off", "Indisponible", enabled: false)], owner: "screen")117        #expect(await registry.run(id: "x"))118        #expect(ran == 10)119        #expect(await registry.run(id: "off") == false)120        #expect(await registry.run(id: "nope") == false)121        #expect(registry.recents.map(\.id) == ["x"])122        #expect(store.load().map(\.id) == ["x"])                    // persisted123        registry.unregister(owner: "screen")124        #expect(registry.commands.isEmpty)125        registry.clearRecents()126        #expect(store.load().isEmpty)127    }128129    @Test("ranking uses the section as a keyword, the priority and the recency")130    func ranking() async {131        let registry = CommandRegistry(recents: InMemoryCommandRecents())132        registry.register([command("t", "Tâches", section: "Aller à"), command("g", "Graphe", section: "Aller à"), command("n", "Nouvelle page", section: "Créer", priority: 3),133                           command("c", "Nouveau canevas", section: "Créer")])134        #expect(registry.ranked("taches").first?.item.id == "t")135        #expect(Set(registry.ranked("aller").map(\.item.id)) == ["t", "g"])       // matched by their section136        #expect(registry.ranked("nouv").map(\.item.id) == ["n", "c"])              // the priority breaks the near-tie137        _ = await registry.run(id: "c")138        #expect(registry.ranked("nouv").map(\.item.id) == ["c", "n"])              // recency (+40) wins over priority 3139    }140141    @Test("palette: empty query = recents then sections in registration order; a query = ranked commands; selection wraps; running dismisses")142    func palette() async {143        let registry = CommandRegistry(recents: InMemoryCommandRecents())144        var opened: [FeatureDestination] = []145        registry.register(FeatureCommands.destinations { opened.append($0) }, owner: FeatureCommands.ownerDestinations)146        registry.register([command("page.new", "Nouvelle page", section: "Créer")])147        var dismissed = 0148        let model = CommandCenterModel(registry: registry, onDismiss: { dismissed += 1 })149        #expect(model.sections.map(\.title) == ["Aller à", "Créer"])150        #expect(model.sections.first?.rows.count == FeatureDestination.allCases.count)151        #expect(model.selectedId == model.rows.first?.id)152153        model.query = "graph"154        #expect(model.sections.map(\.title) == ["Commandes"])155        #expect(model.rows.first?.title == "Graphe de connaissances")156        #expect(model.rows.first?.positions == [0, 1, 2, 3, 4])157        model.moveSelection(-1)158        #expect(model.selectedId == model.rows.last?.id)             // wraps159        model.moveSelection(1)160        #expect(model.selectedId == model.rows.first?.id)161        #expect(await model.runSelected())162        #expect(opened == [.graph])163        #expect(dismissed == 1)164165        model.query = ""166        #expect(model.sections.first?.title == "Récents")167        #expect(model.sections.first?.rows.first?.title == "Graphe de connaissances")168        model.query = "zzzz"169        #expect(model.isEmpty)170        #expect(await model.runSelected() == false)171    }172173    @Test("palette: pages of the device are found locally, opened through the router and remembered; offline changes nothing")174    func pages() async throws {175        let world = try await FeatureWorld()176        world.setOffline(true)                                        // the page search is local177        let router = FeatureRouterRecorder()178        let registry = CommandRegistry(recents: InMemoryCommandRecents())179        registry.register(await FeatureCommands.standard(repositories: world.repositories, router: router))180        #expect(registry.command(id: "sync.now") != nil)181        let model = CommandCenterModel(registry: registry, repositories: world.repositories, router: router)182        model.query = "Plan de l'étude"183        await model.waitForPages()184        #expect(model.sections.first?.title == "Pages")                // an exact title beats loose command matches185        #expect(model.selectedRow?.title == "Plan de l'étude")          // the best row is selected when the pages arrive186        let pages = model.sections.first { $0.title == "Pages" }187        let row = try #require(pages?.rows.first { $0.title == "Plan de l'étude" })188        #expect(await model.run(row))189        #expect(router.calls == [.page(id: BlockSamples.sourcePageId, blockId: nil)])190        #expect(registry.recents.first?.kind == .page)191        model.query = ""192        #expect(model.sections.first?.rows.first?.title == "Plan de l'étude")193194        // Database commands open the database through the router.195        if let database = registry.commands.first(where: { $0.id.hasPrefix("database.") }) {196            #expect(await registry.run(id: database.id))197            if case .database = router.calls.last {} else { Issue.record("expected a database call, got \(String(describing: router.calls.last))") }198        }199    }200201    @Test("highlighting marks exactly the matched characters")202    func highlight() {203        let text = CommandRowView.highlighted("Tâches", positions: [0, 1])204        #expect(String(text.characters) == "Tâches")205        #expect(text.runs.filter { $0.inlinePresentationIntent == .stronglyEmphasized }.count >= 1)206        #expect(String(CommandRowView.highlighted("Graphe", positions: []).characters) == "Graphe")207    }208}209
Files main
Menu

Theme