Sources/Orgstar/BacklinksPane.swift

design-themes-widgets
orgstar/Sources/Orgstar/BacklinksPane.swift history · blame · raw

98 lines · 4061 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    /// Why the index couldn't be read, shown in place of the lists.
16    @State private var failure: String?
17    @Environment(\.orgTheme) private var theme
18    @Environment(\.colorScheme) private var colorScheme
19
20    /// The heading at the caret.
21    private var heading: OutlineEntry? { session.outline.last { $0.start <= commands.selection.location } }
22
23    private struct Key: Equatable {
24        var path: String?
25        var heading: Int?
26        var title: String?
27        var index: Int
28    }
29
30    var body: some View {
31        List {
32            if let failure {
33                Text(failure).foregroundStyle(.secondary)
34            } else {
35                if let heading {
36                    Section("Links to \(heading.title.isEmpty ? "(untitled)" : heading.title)") { rows(toHeading) }
37                }
38                Section("Links to this file") { rows(toFile) }
39            }
40        }
41        .themedListBackground(theme.color("sidebar-background", in: colorScheme))
42        .task(id: Key(path: session.path, heading: heading?.start, title: heading?.title, index: workspace.indexVersion)) { await refresh() }
43    }
44
45    @ViewBuilder
46    private func rows(_ locations: [HeadingLocation]) -> some View {
47        if locations.isEmpty {
48            Text("None").foregroundStyle(.secondary)
49        }
50        ForEach(locations, id: \.self) { location in
51            Button {
52                open(location)
53            } label: {
54                VStack(alignment: .leading, spacing: 2) {
55                    Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1)
56                    if let snippet = location.snippet {
57                        Text(snippet.attributed).font(.callout).foregroundStyle(.secondary).lineLimit(3)
58                    }
59                    Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.tertiary)
60                }
61            }
62            .buttonStyle(.plain)
63        }
64    }
65
66    private func refresh() async {
67        guard let path = session.path else {
68            toHeading = []
69            toFile = []
70            failure = nil
71            return
72        }
73        let overlay = workspace.overlay(session.openDocuments)
74        do {
75            let found = try await Self.backlinks(in: workspace, path: path, tree: session.document?.tree, heading: heading?.start, overlay: overlay)
76            guard !Task.isCancelled else { return }
77            (toFile, toHeading) = found
78            failure = nil
79        } catch {
80            guard !Task.isCancelled else { return }
81            (toFile, toHeading) = ([], [])
82            failure = error.localizedDescription
83        }
84    }
85
86    @concurrent
87    private nonisolated static func backlinks(
88        in workspace: WorkspaceModel, path: String, tree: OrgTree?, heading: Int?, overlay: [String: FileRecord]
89    ) async throws -> (toFile: [HeadingLocation], toHeading: [HeadingLocation]) {
90        let model = tree.map { DocumentModel(tree: $0) }
91        // The file's own ID, as an org-roam file node.
92        let toFile = try workspace.backlinks(to: Backlinks.Target(path: path, id: model?.property("ID", of: nil)?.value), overlay: overlay)
93        guard let heading, let info = model?.headings.first(where: { $0.headingRange.lowerBound == heading }) else { return (toFile, []) }
94        let customID = info.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value
95        let target = Backlinks.Target(path: path, title: info.title, id: info.id, customID: customID)
96        return (toFile, try workspace.backlinks(to: target, excluding: heading, overlay: overlay))
97    }
98}