Sources/OrgApp/CitationActions.swift
156 lines · 8581 bytes
8 symbols in this file
1import OrgCore
2import SwiftUI
3
4/// A followed citation's bibliography entry and what it offers to open.
5public struct CitationEntry: Identifiable, Sendable {
6 public var id: String { key }
7 public var key: String
8 public var summary: String
9 /// The entry's files, its DOI and URL, then the entry in its bibliography file.
10 public var links: [(label: String, link: OrgLink)]
11
12 public init(_ entry: BibEntry, text: String? = nil) {
13 key = entry.key
14 summary = entry.summary
15 var links: [(String, OrgLink)] = entry.files.map { file in
16 (String(localized: "Open \((file as NSString).lastPathComponent)", comment: "Opens a citation's file"), OrgLink(type: "file", path: file, raw: "file:" + file))
17 }
18 if let doi = entry.doi { links.append((String(localized: "Open DOI", comment: "Opens a citation's DOI"), OrgLink(type: "doi", path: doi, raw: "doi:" + doi))) }
19 if let url = entry.url, url.contains(":") { links.append((String(localized: "Open URL", comment: "Opens a citation's URL"), Links.parse(plain: url))) }
20 let line = text.flatMap { Bibliography.line(of: entry.key, in: $0, json: (entry.file as NSString).pathExtension.lowercased() == "json") }
21 links.append((String(localized: "Show in Bibliography", comment: "Opens the bibliography file at a citation's entry"),
22 OrgLink(type: "file", path: entry.file, searchOption: line.map(String.init), raw: "file:" + entry.file)))
23 self.links = links
24 }
25}
26
27/// Insert Citation… and following citations, as `org-cite-insert` and `org-cite-follow` with
28/// the basic processor, with the platform's questions. Bibliography files are read off the
29/// main thread.
30@MainActor
31public struct CitationActions {
32 public var session: DocumentSession
33 /// The editor's text and caret.
34 public var context: () -> EditContext?
35 /// Runs a command in the editor.
36 public var perform: (any OrgCommand) -> Void
37 public var show: (String) -> Void
38 public var ask: (Prompt, @escaping (String?) -> Void) -> Void
39 /// Shows a followed citation's entry.
40 public var present: (CitationEntry) -> Void
41 /// In the Mac sandbox, asks for access to bibliography files outside the sidebar's
42 /// folders. False when one is still out of reach.
43 public var reach: ([String]) -> Bool = { _ in true }
44 public var cache = BibliographyCache.shared
45
46 public init(
47 session: DocumentSession, context: @escaping () -> EditContext?, perform: @escaping (any OrgCommand) -> Void, show: @escaping (String) -> Void,
48 ask: @escaping (Prompt, @escaping (String?) -> Void) -> Void, present: @escaping (CitationEntry) -> Void
49 ) {
50 self.session = session
51 self.context = context
52 self.perform = perform
53 self.show = show
54 self.ask = ask
55 self.present = present
56 }
57
58 /// `org-cite-basic`'s styles, as `org-cite-basic--complete-style` offers them.
59 nonisolated static let styles = ["author", "noauthor", "nocite", "note", "numeric", "text", "nil"]
60
61 /// The bibliography files of `text`, a file at `path`: its `#+bibliography:` files, then
62 /// `org-cite-global-bibliography`'s.
63 nonisolated static func files(_ text: String, path: String?) -> [String] {
64 Bibliography.files(in: text, directory: path.map { ($0 as NSString).deletingLastPathComponent }, global: OrgPreferences.citeGlobalBibliography())
65 }
66
67 /// Insert Citation…: on a citation's style a new style; otherwise a key from the
68 /// bibliography, and for a new citation a style; for a new reference a prefix and suffix.
69 public func insert() {
70 guard let context = context() else { return show(String(localized: "No file is open")) }
71 let place = Citations.place(at: context.caret, tree: context.tree)
72 let stylePrompt = Prompt(key: "style", message: String(localized: "Style (empty for default): ", comment: "Insert Citation… asks for a citation style"),
73 choices: Self.styles, requireMatch: false)
74 if place == .style {
75 return ask(stylePrompt) { style in
76 guard let style else { return }
77 perform(InsertCitation(key: nil, style: style))
78 }
79 }
80 let files = Self.files(context.text, path: session.path)
81 guard !files.isEmpty else { return show(String(localized: "No bibliography set", comment: "Insert Citation… in a file without #+bibliography")) }
82 guard reach(files) else { return }
83 let cache = cache
84 Task {
85 let entries = await cache.load(files)
86 guard !entries.isEmpty else { return show(String(localized: "No bibliography set", comment: "Insert Citation… in a file without #+bibliography")) }
87 let labels = entries.map(\.label)
88 ask(Prompt(key: "key", message: String(localized: "Key: ", comment: "Insert Citation… asks for a bibliography entry"), choices: labels)) { answer in
89 guard let answer, let index = labels.firstIndex(of: answer) else { return }
90 let key = entries[index].key
91 guard place != .key else { return perform(InsertCitation(key: key)) }
92 affixes { prefix, suffix in
93 guard place == .new else { return perform(InsertCitation(key: key, prefix: prefix, suffix: suffix)) }
94 ask(stylePrompt) { style in
95 guard let style else { return }
96 perform(InsertCitation(key: key, style: style, prefix: prefix, suffix: suffix))
97 }
98 }
99 }
100 }
101 }
102
103 /// Asks for the new reference's prefix and suffix, either of which may be empty.
104 private func affixes(_ then: @escaping (String, String) -> Void) {
105 ask(Prompt(key: "prefix", message: String(localized: "Prefix (empty for none): ", comment: "Insert Citation… asks for text before the key"), requireMatch: false)) { prefix in
106 guard let prefix else { return }
107 ask(Prompt(key: "suffix", message: String(localized: "Suffix (empty for none): ", comment: "Insert Citation… asks for text after the key"), requireMatch: false)) { suffix in
108 guard let suffix else { return }
109 then(prefix, suffix)
110 }
111 }
112 }
113
114 /// Following a citation: its entry, from the file's bibliographies, with its file, DOI,
115 /// URL and place in the bibliography file. Of several keys, one is asked for first, as
116 /// `org-cite-basic-goto` does.
117 public func follow(_ keys: [String]) {
118 guard keys.count == 1 else {
119 return ask(Prompt(key: "key", message: String(localized: "Select citation key: ", comment: "Following a citation with several keys"), choices: keys)) { key in
120 guard let key else { return }
121 follow([key])
122 }
123 }
124 let key = keys[0]
125 guard let document = session.document else { return show(String(localized: "No file is open")) }
126 let files = Self.files(document.text, path: session.path)
127 guard reach(files) else { return }
128 let cache = cache
129 Task {
130 let found = await Self.find(key, in: files, cache: cache)
131 guard let found else { return show(String(localized: "Cannot find citation key: \(key)", comment: "Following a citation whose key no bibliography has")) }
132 present(found)
133 }
134 }
135
136 @concurrent
137 nonisolated static func find(_ key: String, in files: [String], cache: BibliographyCache) async -> CitationEntry? {
138 guard let entry = cache.entries(files).first(where: { $0.key == key }) else { return nil }
139 return CitationEntry(entry, text: (try? String(contentsOfFile: entry.file, encoding: .utf8)))
140 }
141}
142
143extension View {
144 /// Shows a followed citation's entry with a button for each thing it offers to open.
145 public func citationAlert(_ entry: Binding<CitationEntry?>, open: @escaping (OrgLink) -> Void) -> some View {
146 alert(entry.wrappedValue.map { "@" + $0.key } ?? "", isPresented: Binding(get: { entry.wrappedValue != nil }, set: { if !$0 { entry.wrappedValue = nil } }),
147 presenting: entry.wrappedValue) { shown in
148 ForEach(shown.links.indices, id: \.self) { index in
149 Button(shown.links[index].label) { open(shown.links[index].link) }
150 }
151 Button("Cancel", role: .cancel) {}
152 } message: { shown in
153 Text(shown.summary)
154 }
155 }
156}