Sources/Orgstar/BacklinksPane.swift
78 lines · 3132 bytes
1import OrgApp
2import OrgCore
3import OrgIndex
4import OrgPresentation
5import SwiftUI
6
7/// Headings that link to the heading at the caret, and to the file.
8struct BacklinksPane: View {
9 let workspace: WorkspaceModel
10 let session: DocumentSession
11 let commands: AppCommands
12 let open: (HeadingLocation) -> Void
13 @State private var toHeading: [HeadingLocation] = []
14 @State private var toFile: [HeadingLocation] = []
15 @Environment(\.orgTheme) private var theme
16 @Environment(\.colorScheme) private var colorScheme
17
18 /// The heading at the caret.
19 private var heading: OutlineEntry? { session.outline.last { $0.start <= commands.selection.location } }
20
21 private struct Key: Equatable {
22 var path: String?
23 var heading: Int?
24 var version: Int
25 }
26
27 var body: some View {
28 List {
29 if let heading {
30 Section("Links to \(heading.title.isEmpty ? "(untitled)" : heading.title)") { rows(toHeading) }
31 }
32 Section("Links to this file") { rows(toFile) }
33 }
34 .themedListBackground(theme.color("sidebar-background", in: colorScheme))
35 .task(id: Key(path: session.path, heading: heading?.start, version: session.editVersion)) { refresh() }
36 }
37
38 @ViewBuilder
39 private func rows(_ locations: [HeadingLocation]) -> some View {
40 if locations.isEmpty {
41 Text("None").foregroundStyle(.secondary)
42 }
43 ForEach(locations, id: \.self) { location in
44 Button {
45 open(location)
46 } label: {
47 VStack(alignment: .leading, spacing: 2) {
48 Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1)
49 if let snippet = location.snippet {
50 Text(snippet.attributed).font(.callout).foregroundStyle(.secondary).lineLimit(3)
51 }
52 Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.tertiary)
53 }
54 }
55 .buttonStyle(.plain)
56 }
57 }
58
59 private func refresh() {
60 guard let path = session.path else {
61 toHeading = []
62 toFile = []
63 return
64 }
65 let overlay = workspace.overlay(session.openDocuments)
66 // The file's own ID, as an org-roam file node.
67 let fileID = session.document.map { DocumentModel(tree: $0.tree).property("ID", of: nil)?.value }
68 toFile = workspace.backlinks(to: Backlinks.Target(path: path, id: fileID ?? nil), overlay: overlay)
69 guard let heading, let tree = session.document?.tree,
70 let info = DocumentModel(tree: tree).headings.first(where: { $0.headingRange.lowerBound == heading.start }) else {
71 toHeading = []
72 return
73 }
74 let customID = info.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value
75 let target = Backlinks.Target(path: path, title: info.title, id: info.id, customID: customID)
76 toHeading = workspace.backlinks(to: target, excluding: heading.start, overlay: overlay)
77 }
78}