Tests/OrgAppTests/RoamGraphTests.swift

90 lines · 5479 bytes

 1import CoreGraphics
 2import Foundation
 3import OrgCore
 4@testable import OrgIndex
 5import Testing
 6@testable import OrgApp
 7
 8struct RoamGraphTests {
 9    private func store(_ files: [String: String]) throws -> IndexStore {
10        let store = try IndexStore()
11        for (path, text) in files.sorted(by: { $0.key < $1.key }) {
12            try store.write(FileRecord(path: path, root: "/notes", kind: .org, bytes: Array(text.utf8), mtime: 1, settings: IndexSettings()))
13        }
14        return store
15    }
16
17    private func graph(_ store: IndexStore, denote: Bool = false) throws -> RoamGraph {
18        RoamGraph(nodes: denote ? try store.denoteNodes() : try store.nodes(), links: try store.links(),
19                  sections: try store.nodeSections(), denote: denote)
20    }
21
22    private func pairs(_ graph: RoamGraph) -> Set<[String]> {
23        Set(graph.edges.map { [graph.nodes[$0.a].title, graph.nodes[$0.b].title].sorted() })
24    }
25
26    @Test func linksJoinTheNodesTheyAreWrittenInAndName() throws {
27        let store = try store([
28            "/notes/a.org": ":PROPERTIES:\n:ID: a\n:END:\n#+TITLE: Alpha\nSee [[id:b]] and [[id:missing]] and [[https://x.org]].\n",
29            "/notes/b.org": ":PROPERTIES:\n:ID: b\n:END:\n#+TITLE: Beta\nBack to [[id:a]], and [[id:b][myself]].\n"
30                + "* Outer\n:PROPERTIES:\n:ID: outer\n:END:\n** Plain\n[[id:c]]\n** Inner\n:PROPERTIES:\n:ID: inner\n:END:\n[[id:a]]\n* After\n[[id:c]]\n",
31            "/notes/c.org": ":PROPERTIES:\n:ID: c\n:END:\n#+TITLE: Gamma\n",
32            "/notes/loose.org": "No ID here, so [[id:a]] is written in no node.\n",
33        ])
34        let graph = try graph(store)
35        #expect(Set(graph.nodes.map(\.title)) == ["Alpha", "Beta", "Gamma", "Outer", "Inner"])
36        // Both directions between Alpha and Beta are one edge. The link under Plain belongs to
37        // Outer, the heading with an ID around it; the one under After to the file, Beta.
38        #expect(pairs(graph) == [["Alpha", "Beta"], ["Gamma", "Outer"], ["Alpha", "Inner"], ["Beta", "Gamma"]])
39        #expect(graph.degrees.reduce(0, +) == 8)
40    }
41
42    @Test func denoteLinksJoinNotesByIdentifier() throws {
43        let store = try store([
44            "/notes/20240101T100000--first__a.org": "#+title: First\n[[denote:20240102T100000][second]] and [[id:x]]\n* H\n[[denote:20240102T100000::*There]]\n",
45            "/notes/20240102T100000--second.org": "#+title: Second\n",
46            "/notes/plain.org": "[[denote:20240101T100000]]\n",
47        ])
48        let graph = try graph(store, denote: true)
49        #expect(graph.nodes.map(\.title) == ["First", "Second"])
50        #expect(pairs(graph) == [["First", "Second"]])
51    }
52
53    @Test func neighbourhoodKeepsANodeAndItsNeighbours() {
54        func node(_ id: String) -> IndexStore.Node { IndexStore.Node(id: id, title: id, location: .file("/n/\(id).org", contentHash: "")) }
55        func link(_ from: String, _ to: String) -> (source: HeadingLocation, target: String) { (.file("/n/\(from).org", contentHash: ""), "id:" + to) }
56        let graph = RoamGraph(nodes: ["a", "b", "c", "d", "e"].map(node), links: [link("a", "b"), link("b", "c"), link("c", "d"), link("a", "c")])
57        let near = graph.neighbourhood(of: "b")
58        #expect(near.nodes.map(\.id) == ["a", "b", "c"])
59        #expect(Set(near.edges.map { [near.nodes[$0.a].id, near.nodes[$0.b].id] }) == [["a", "b"], ["b", "c"], ["a", "c"]])
60        #expect(graph.neighbourhood(of: "e").nodes.map(\.id) == ["e"])
61        #expect(graph.neighbourhood(of: "nope").nodes.isEmpty)
62    }
63
64    @Test func currentNodeIsTheInnermostHeadingWithAnIDElseTheFile() {
65        let text = ":PROPERTIES:\n:ID: file\n:END:\nTop.\n* Outer\n:PROPERTIES:\n:ID: outer\n:END:\n** Plain\nHere.\n* Other\nThere.\n"
66        let tree = OrgParser.parse(text)
67        let ns = text as NSString
68        #expect(RoamGraph.current(tree: tree, at: ns.range(of: "Here.").location, path: "/n/a.org", denote: false) == "outer")
69        #expect(RoamGraph.current(tree: tree, at: ns.range(of: "There.").location, path: "/n/a.org", denote: false) == "file")
70        #expect(RoamGraph.current(tree: tree, at: 0, path: "/n/20240101T100000--a.org", denote: true) == "20240101T100000")
71    }
72
73    @Test func layoutSeparatesNodesAndKeepsNeighboursClose() {
74        func node(_ id: Int) -> IndexStore.Node { IndexStore.Node(id: "\(id)", title: "\(id)", location: .file("/n/\(id).org", contentHash: "")) }
75        func link(_ from: Int, _ to: Int) -> (source: HeadingLocation, target: String) { (.file("/n/\(from).org", contentHash: ""), "id:\(to)") }
76        // Two chains of ten with nothing between them, and five nodes with no links.
77        let links = (0..<9).map { link($0, $0 + 1) } + (10..<19).map { link($0, $0 + 1) }
78        let graph = RoamGraph(nodes: (0..<25).map(node), links: links)
79        let points = graph.layout()
80        #expect(points == graph.layout())
81        func distance(_ a: Int, _ b: Int) -> Double { Double(hypot(points[a].x - points[b].x, points[a].y - points[b].y)) }
82        var nearest = Double.infinity
83        for a in 0..<25 { for b in (a + 1)..<25 { nearest = min(nearest, distance(a, b)) } }
84        #expect(nearest > 0.2)
85        let linked = graph.edges.map { distance($0.a, $0.b) }.reduce(0, +) / Double(graph.edges.count)
86        #expect(linked < distance(0, 9))
87        #expect(points.allSatisfy { abs($0.x) < 40 && abs($0.y) < 40 && $0.x.isFinite && $0.y.isFinite })
88        #expect(RoamGraph().layout().isEmpty)
89    }
90}