Sources/OrgApp/RoamGraphView.swift
185 lines · 8642 bytes
1import OrgIndex
2import SwiftUI
3
4/// The graph of the workspace's nodes: a dot for each node, sized by its links, and a line for
5/// each link. Dragging moves the picture, pinching and the buttons zoom it, and a click or tap
6/// on a node opens it.
7public struct RoamGraphView: View {
8 /// The whole graph as it is now.
9 let load: @MainActor () -> RoamGraph
10 /// The node the caret is in, which is marked, and whose links the picture can be limited to.
11 let current: String?
12 /// Changes when the files or their unsaved text change.
13 let version: Int
14 let open: (HeadingLocation) -> Void
15
16 @State private var graph = RoamGraph()
17 @State private var points: [CGPoint] = []
18 @State private var degrees: [Int] = []
19 @State private var loaded = false
20 @AppStorage("roamGraphLocal") private var local = false
21 @State private var zoom: CGFloat = 1
22 @State private var pinch: CGFloat = 1
23 @State private var offset: CGSize = .zero
24 @State private var drag: CGSize = .zero
25
26 public init(load: @escaping @MainActor () -> RoamGraph, current: String?, version: Int, open: @escaping (HeadingLocation) -> Void) {
27 self.load = load
28 self.current = current
29 self.version = version
30 self.open = open
31 }
32
33 private struct Key: Equatable {
34 var version: Int
35 var local: Bool
36 var current: String?
37 }
38
39 public var body: some View {
40 VStack(spacing: 0) {
41 HStack {
42 Toggle("Only the Open Note's Links", isOn: $local)
43 #if os(macOS)
44 .toggleStyle(.checkbox)
45 #endif
46 Spacer()
47 Text("Nodes: \(graph.nodes.count) · Links: \(graph.edges.count)").foregroundStyle(.secondary).monospacedDigit()
48 }
49 .font(.callout)
50 .padding(.horizontal, 12)
51 .padding(.vertical, 8)
52 Divider()
53 if graph.nodes.isEmpty, loaded {
54 ContentUnavailableView {
55 Label("No Nodes", systemImage: "point.3.connected.trianglepath.dotted")
56 } description: {
57 Text(local ? "The open note isn't a node, or nothing is open." : "Headings and files with an ID, or notes named as Denote names them, show here.")
58 }
59 } else {
60 picture
61 }
62 }
63 // The neighbours change with the caret's node only while the picture is limited to them.
64 .task(id: Key(version: version, local: local, current: local ? current : nil)) { await reload() }
65 }
66
67 private var picture: some View {
68 GeometryReader { geometry in
69 let placed = place(in: geometry.size)
70 Canvas { context, _ in
71 var lines = Path()
72 for edge in graph.edges where edge.a < placed.count && edge.b < placed.count {
73 lines.move(to: placed[edge.a])
74 lines.addLine(to: placed[edge.b])
75 }
76 context.stroke(lines, with: .color(.secondary.opacity(0.4)), lineWidth: 1)
77 let labelled = labels(placed)
78 for (index, point) in placed.enumerated() {
79 let radius = radius(index)
80 let dot = Path(ellipseIn: CGRect(x: point.x - radius, y: point.y - radius, width: radius * 2, height: radius * 2))
81 let isCurrent = graph.nodes[index].id == current
82 context.fill(dot, with: .color(isCurrent ? .orange : .accentColor))
83 if isCurrent { context.stroke(dot, with: .color(.primary), lineWidth: 2) }
84 }
85 // Over the dots, so a neighbour doesn't cover a title.
86 for index in labelled.sorted() {
87 let text = context.resolve(Text(Self.short(graph.nodes[index].title)).font(.caption).foregroundStyle(.primary))
88 context.draw(text, at: CGPoint(x: placed[index].x, y: placed[index].y + radius(index) + 2), anchor: .top)
89 }
90 }
91 .contentShape(Rectangle())
92 .gesture(SpatialTapGesture().onEnded { tap in
93 if let index = nearest(to: tap.location, in: placed) { open(graph.nodes[index].location) }
94 })
95 .simultaneousGesture(DragGesture(minimumDistance: 4)
96 .onChanged { drag = $0.translation }
97 .onEnded { value in
98 offset = CGSize(width: offset.width + value.translation.width, height: offset.height + value.translation.height)
99 drag = .zero
100 })
101 .simultaneousGesture(MagnifyGesture()
102 .onChanged { pinch = $0.magnification }
103 .onEnded { value in
104 zoom = min(20, max(0.2, zoom * value.magnification))
105 pinch = 1
106 })
107 .overlay(alignment: .bottomTrailing) { zoomButtons }
108 .accessibilityRepresentation {
109 List(graph.nodes) { node in
110 Button(node.title.isEmpty ? "(untitled)" : node.title) { open(node.location) }
111 }
112 }
113 }
114 }
115
116 private var zoomButtons: some View {
117 HStack(spacing: 4) {
118 Button { zoom = max(0.2, zoom / 1.5) } label: { Image(systemName: "minus.magnifyingglass") }
119 .accessibilityLabel("Zoom Out")
120 Button {
121 zoom = 1
122 offset = .zero
123 } label: { Image(systemName: "arrow.up.left.and.down.right.magnifyingglass") }
124 .accessibilityLabel("Zoom to Fit")
125 Button { zoom = min(20, zoom * 1.5) } label: { Image(systemName: "plus.magnifyingglass") }
126 .accessibilityLabel("Zoom In")
127 }
128 .buttonStyle(.bordered)
129 .padding(10)
130 }
131
132 private func reload() async {
133 let whole = load()
134 let shown = local ? (current.map { whole.neighbourhood(of: $0) } ?? RoamGraph()) : whole
135 let laidOut = await Task.detached { shown.layout() }.value
136 guard !Task.isCancelled else { return }
137 (graph, points, degrees, loaded) = (shown, laidOut, shown.degrees, true)
138 }
139
140 /// The nodes' places in a view of `size`: the layout fitted inside it, then zoomed and moved.
141 private func place(in size: CGSize) -> [CGPoint] {
142 guard !points.isEmpty, points.count == graph.nodes.count else { return [] }
143 let xs = points.map(\.x), ys = points.map(\.y)
144 let (minX, maxX, minY, maxY) = (xs.min() ?? 0, xs.max() ?? 0, ys.min() ?? 0, ys.max() ?? 0)
145 let margin: CGFloat = 48
146 let fit = min((size.width - margin * 2) / max(maxX - minX, 1), (size.height - margin * 2) / max(maxY - minY, 1))
147 let scale = max(fit, 1) * zoom * pinch
148 let centre = CGPoint(x: (minX + maxX) / 2, y: (minY + maxY) / 2)
149 return points.map {
150 CGPoint(x: size.width / 2 + ($0.x - centre.x) * scale + offset.width + drag.width,
151 y: size.height / 2 + ($0.y - centre.y) * scale + offset.height + drag.height)
152 }
153 }
154
155 private func radius(_ index: Int) -> CGFloat {
156 4 + min(8, CGFloat(index < degrees.count ? degrees[index] : 0).squareRoot() * 2)
157 }
158
159 /// The nodes whose titles are drawn: all of them while they have room, else the node the
160 /// caret is in and those with the most links, none closer than a title's width to another.
161 private func labels(_ placed: [CGPoint]) -> Set<Int> {
162 var shown: [Int] = []
163 let order = placed.indices.sorted { a, b in
164 let (first, second) = (graph.nodes[a].id == current, graph.nodes[b].id == current)
165 if first != second { return first }
166 return degrees[a] != degrees[b] ? degrees[a] > degrees[b] : a < b
167 }
168 for index in order where shown.allSatisfy({ abs(placed[$0].x - placed[index].x) > 90 || abs(placed[$0].y - placed[index].y) > 22 }) {
169 shown.append(index)
170 }
171 return Set(shown)
172 }
173
174 private func nearest(to point: CGPoint, in placed: [CGPoint]) -> Int? {
175 let near = placed.enumerated().map { (index: $0.offset, distance: hypot($0.element.x - point.x, $0.element.y - point.y)) }
176 .min { $0.distance < $1.distance }
177 guard let near, near.distance <= max(22, radius(near.index) + 8) else { return nil }
178 return near.index
179 }
180
181 static func short(_ title: String) -> String {
182 let title = title.isEmpty ? String(localized: "(untitled)") : title
183 return title.count > 24 ? title.prefix(23) + "…" : title
184 }
185}