Sources/OrgApp/RoamGraph.swift
168 lines · 7834 bytes
1import CoreGraphics
2import Foundation
3import OrgCore
4import OrgIndex
5
6/// org-roam's nodes, or Denote's notes, and the links between them.
7public struct RoamGraph: Sendable, Equatable {
8 public struct Node: Sendable, Equatable, Identifiable {
9 public let id: String
10 public let title: String
11 public let location: HeadingLocation
12 }
13
14 /// A link from one node to another, as indices into `nodes`, the lower one first.
15 public struct Edge: Sendable, Hashable {
16 public let a: Int
17 public let b: Int
18 }
19
20 public let nodes: [Node]
21 public let edges: [Edge]
22
23 public init(nodes: [Node] = [], edges: [Edge] = []) {
24 self.nodes = nodes
25 self.edges = edges
26 }
27
28 /// The graph of `nodes`: an edge for each `id:` link, or `denote:` link with `denote`,
29 /// from the node it is written in to the node it names. A link is written in the innermost
30 /// heading with an ID around it (`sections`), else in its file's node. Links between the
31 /// same two nodes make one edge; links to a node from itself and to unknown nodes make none.
32 public init(
33 nodes: [IndexStore.Node], links: [(source: HeadingLocation, target: String)],
34 sections: [String: [(id: String, range: Range<Int>)]] = [:], denote: Bool = false
35 ) {
36 var index: [String: Int] = [:]
37 var unique: [Node] = []
38 for node in nodes where index[node.id] == nil {
39 index[node.id] = unique.count
40 unique.append(Node(id: node.id, title: node.title, location: node.location))
41 }
42 var fileNode: [String: Int] = [:]
43 for (position, node) in unique.enumerated() where node.location.ordinal == HeadingLocation.fileOrdinal {
44 fileNode[node.location.path] = position
45 }
46 func source(_ location: HeadingLocation) -> Int? {
47 if !denote, location.ordinal != HeadingLocation.fileOrdinal,
48 let inner = sections[location.path]?.filter({ $0.range.contains(location.start) }).max(by: { $0.range.lowerBound < $1.range.lowerBound }),
49 let position = index[inner.id] {
50 return position
51 }
52 return fileNode[location.path]
53 }
54 func target(_ link: String) -> Int? {
55 let prefix = denote ? "denote:" : "id:"
56 guard link.lowercased().hasPrefix(prefix) else { return nil }
57 return index[link.dropFirst(prefix.count).components(separatedBy: "::")[0]]
58 }
59 var seen = Set<Edge>()
60 var edges: [Edge] = []
61 for link in links {
62 guard let from = source(link.source), let to = target(link.target), from != to else { continue }
63 let edge = Edge(a: min(from, to), b: max(from, to))
64 if seen.insert(edge).inserted { edges.append(edge) }
65 }
66 self.init(nodes: unique, edges: edges)
67 }
68
69 /// How many edges each node has.
70 public var degrees: [Int] {
71 var degrees = [Int](repeating: 0, count: nodes.count)
72 for edge in edges {
73 degrees[edge.a] += 1
74 degrees[edge.b] += 1
75 }
76 return degrees
77 }
78
79 /// The node `id` and the nodes it shares an edge with; empty when there is no such node.
80 public func neighbourhood(of id: String) -> RoamGraph {
81 guard let centre = nodes.firstIndex(where: { $0.id == id }) else { return RoamGraph() }
82 var kept = [centre]
83 for edge in edges where edge.a == centre || edge.b == centre { kept.append(edge.a == centre ? edge.b : edge.a) }
84 kept.sort()
85 let position = Dictionary(uniqueKeysWithValues: kept.enumerated().map { ($1, $0) })
86 return RoamGraph(nodes: kept.map { nodes[$0] }, edges: edges.compactMap { edge in
87 guard let a = position[edge.a], let b = position[edge.b] else { return nil }
88 return Edge(a: a, b: b)
89 })
90 }
91
92 /// The node the caret is in: the innermost heading with an ID around `offset`, else the
93 /// file's ID; with `denote`, the identifier in the file's name.
94 public static func current(tree: OrgTree, at offset: Int, path: String, denote: Bool) -> String? {
95 if denote { return Denote.identifier(ofFile: path) }
96 let model = DocumentModel(tree: tree)
97 let inner = model.headings.filter { $0.id != nil && $0.sectionRange.contains(offset) }.max { $0.sectionRange.lowerBound < $1.sectionRange.lowerBound }
98 return inner?.id ?? model.property("ID", of: nil)?.value
99 }
100
101 /// A place for each node, by Fruchterman and Reingold's force-directed method: nodes push
102 /// each other apart, edges pull theirs together, and all are held around the origin. The
103 /// same graph gives the same picture. About one unit lies between neighbours. Nodes more
104 /// than `reach` units apart don't push, so parts with no link between them settle beside
105 /// each other instead of far away.
106 static let reach = 4.0
107
108 public func layout(iterations: Int? = nil) -> [CGPoint] {
109 let count = nodes.count
110 guard count > 1 else { return [CGPoint](repeating: .zero, count: count) }
111 // Started on a spiral, which has no two nodes in one place.
112 var x = [Double](repeating: 0, count: count), y = [Double](repeating: 0, count: count)
113 for i in 0..<count {
114 let radius = (Double(i) + 0.5).squareRoot(), angle = Double(i) * 2.399963229728653
115 x[i] = radius * cos(angle)
116 y[i] = radius * sin(angle)
117 }
118 // Each round compares every pair, so large graphs get fewer rounds.
119 let rounds = iterations ?? max(30, min(300, 40_000_000 / (count * count)))
120 var temperature = Double(count).squareRoot()
121 let cooling = temperature / Double(rounds + 1)
122 var dx = [Double](repeating: 0, count: count), dy = [Double](repeating: 0, count: count)
123 for _ in 0..<rounds {
124 for i in 0..<count {
125 // Gravity, so that parts with no edge between them stay in view.
126 dx[i] = -x[i] * 0.05
127 dy[i] = -y[i] * 0.05
128 }
129 for i in 0..<count {
130 for j in (i + 1)..<count {
131 let ex = x[i] - x[j], ey = y[i] - y[j]
132 let squared = max(ex * ex + ey * ey, 1e-4)
133 if squared > Self.reach * Self.reach { continue }
134 let fx = ex / squared, fy = ey / squared
135 dx[i] += fx
136 dy[i] += fy
137 dx[j] -= fx
138 dy[j] -= fy
139 }
140 }
141 for edge in edges {
142 let ex = x[edge.a] - x[edge.b], ey = y[edge.a] - y[edge.b]
143 let distance = (ex * ex + ey * ey).squareRoot()
144 let fx = ex * distance, fy = ey * distance
145 dx[edge.a] -= fx
146 dy[edge.a] -= fy
147 dx[edge.b] += fx
148 dy[edge.b] += fy
149 }
150 for i in 0..<count {
151 let length = max((dx[i] * dx[i] + dy[i] * dy[i]).squareRoot(), 1e-9)
152 let step = min(length, temperature)
153 x[i] += dx[i] / length * step
154 y[i] += dy[i] / length * step
155 }
156 temperature -= cooling
157 }
158 return (0..<count).map { CGPoint(x: x[$0], y: y[$0]) }
159 }
160}
161
162extension WorkspaceModel {
163 /// The graph of the workspace's nodes, with unsaved buffers' in place of their files'.
164 public func roamGraph(overlay: [String: FileRecord] = [:], denote: Bool = OrgPreferences.usesDenote()) -> RoamGraph {
165 RoamGraph(nodes: nodes(overlay: overlay, denote: denote), links: (try? index.links(overlay: overlay)) ?? [],
166 sections: denote ? [:] : (try? index.nodeSections(overlay: overlay)) ?? [:], denote: denote)
167 }
168}