Sources/OrgstarMobile/BacklinksScreen.swift
63 lines · 2620 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 @Environment(\.dismiss) private var dismiss
18
19 var body: some View {
20 NavigationStack {
21 List {
22 if let heading {
23 Section("Links to \(heading.title.isEmpty ? "(untitled)" : heading.title)") { rows(heading.links) }
24 }
25 Section("Links to this file") { rows(toFile) }
26 }
27 .navigationTitle("Backlinks")
28 .navigationBarTitleDisplayMode(.inline)
29 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Done") { dismiss() } } }
30 }
31 .task { refresh() }
32 }
33
34 @ViewBuilder
35 private func rows(_ locations: [HeadingLocation]) -> some View {
36 if locations.isEmpty {
37 Text("None").foregroundStyle(.secondary)
38 }
39 ForEach(locations, id: \.self) { location in
40 Button {
41 dismiss()
42 open(location)
43 } label: {
44 VStack(alignment: .leading, spacing: 2) {
45 Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1).foregroundStyle(.primary)
46 Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.secondary)
47 }
48 }
49 }
50 }
51
52 private func refresh() {
53 let overlay = workspace.overlay(session.openDocuments)
54 guard let document = session.openDocuments.first(where: { $0.path == path })?.document else { return }
55 let model = DocumentModel(tree: document.tree)
56 toFile = workspace.backlinks(to: Backlinks.Target(path: path, id: model.property("ID", of: nil)?.value), overlay: overlay)
57 guard let info = model.headings.last(where: { $0.headingRange.lowerBound <= caret }) else { return heading = nil }
58 let customID = info.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value
59 let target = Backlinks.Target(path: path, title: info.title, id: info.id, customID: customID)
60 heading = (info.title, workspace.backlinks(to: target, excluding: info.headingRange.lowerBound, overlay: overlay))
61 }
62}
63#endif