Sources/OrgstarMobile/BacklinksScreen.swift

design-themes-widgets
orgstar/Sources/OrgstarMobile/BacklinksScreen.swift history · blame · raw

86 lines · 3736 bytes

 1#if os(iOS)
 2import OrgApp
 3import OrgCore
 4import OrgIndex
 5import SwiftUI
 6
 7/// Headings that link to the heading at the caret, and to the file, as the Mac's backlinks
 8/// pane lists them.
 9struct BacklinksScreen: View {
10    let workspace: WorkspaceModel
11    let session: DocumentSession
12    let path: String
13    let caret: Int
14    let open: (HeadingLocation) -> Void
15    @State private var heading: (title: String, links: [HeadingLocation])?
16    @State private var toFile: [HeadingLocation] = []
17    /// Why the index couldn't be read, shown in place of the lists.
18    @State private var failure: String?
19    @Environment(\.dismiss) private var dismiss
20
21    var body: some View {
22        NavigationStack {
23            List {
24                if let failure {
25                    Text(failure).foregroundStyle(.secondary)
26                } else {
27                    if let heading {
28                        Section("Links to \(heading.title.isEmpty ? "(untitled)" : heading.title)") { rows(heading.links) }
29                    }
30                    Section("Links to this file") { rows(toFile) }
31                }
32            }
33            .navigationTitle("Backlinks")
34            .navigationBarTitleDisplayMode(.inline)
35            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Done") { dismiss() } } }
36        }
37        .task { await refresh() }
38    }
39
40    @ViewBuilder
41    private func rows(_ locations: [HeadingLocation]) -> some View {
42        if locations.isEmpty {
43            Text("None").foregroundStyle(.secondary)
44        }
45        ForEach(locations, id: \.self) { location in
46            Button {
47                dismiss()
48                open(location)
49            } label: {
50                VStack(alignment: .leading, spacing: 2) {
51                    Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1).foregroundStyle(.primary)
52                    if let snippet = location.snippet {
53                        Text(snippet.attributed).font(.subheadline).foregroundStyle(.secondary).lineLimit(3)
54                    }
55                    Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.tertiary)
56                }
57            }
58        }
59    }
60
61    private func refresh() async {
62        let overlay = workspace.overlay(session.openDocuments)
63        guard let document = session.openDocuments.first(where: { $0.path == path })?.document else { return }
64        do {
65            let found = try await Self.backlinks(in: workspace, path: path, tree: document.tree, caret: caret, overlay: overlay)
66            guard !Task.isCancelled else { return }
67            (toFile, heading) = found
68        } catch {
69            guard !Task.isCancelled else { return }
70            failure = error.localizedDescription
71        }
72    }
73
74    @concurrent
75    private nonisolated static func backlinks(
76        in workspace: WorkspaceModel, path: String, tree: OrgTree, caret: Int, overlay: [String: FileRecord]
77    ) async throws -> (toFile: [HeadingLocation], heading: (title: String, links: [HeadingLocation])?) {
78        let model = DocumentModel(tree: tree)
79        let toFile = try workspace.backlinks(to: Backlinks.Target(path: path, id: model.property("ID", of: nil)?.value), overlay: overlay)
80        guard let info = model.headings.last(where: { $0.headingRange.lowerBound <= caret }) else { return (toFile, nil) }
81        let customID = info.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value
82        let target = Backlinks.Target(path: path, title: info.title, id: info.id, customID: customID)
83        return (toFile, (info.title, try workspace.backlinks(to: target, excluding: info.headingRange.lowerBound, overlay: overlay)))
84    }
85}
86#endif