Sources/OrgApp/RoamActions.swift
146 lines · 7400 bytes
1import Foundation
2import OrgCore
3import OrgIndex
4
5/// The `app.dailies.` and `app.node.` commands: org-roam's daily notes, and finding and
6/// linking ID nodes, with the platform's questions and file opening.
7@MainActor
8public struct RoamActions {
9 public var session: DocumentSession
10 /// The sidebar folders, the first being `org-roam-directory` unless it's set.
11 public var roots: () -> [String]
12 /// Headings and files with IDs.
13 public var nodes: () -> [IndexStore.Node]
14 public var show: (String) -> Void
15 public var ask: (Prompt, @escaping (String?) -> Void) -> Void
16 /// Opens a file with the caret at an offset.
17 public var open: (_ path: String, _ offset: Int) -> Void
18 /// Puts a link at the caret, in place of the selection, which describes it; without one,
19 /// the title does.
20 public var insertLink: (_ link: String, _ title: String) -> Void
21 /// The index reads new files.
22 public var refresh: () -> Void
23
24 public init(
25 session: DocumentSession, roots: @escaping () -> [String], nodes: @escaping () -> [IndexStore.Node], show: @escaping (String) -> Void,
26 ask: @escaping (Prompt, @escaping (String?) -> Void) -> Void, open: @escaping (String, Int) -> Void,
27 insertLink: @escaping (String, String) -> Void, refresh: @escaping () -> Void
28 ) {
29 self.session = session
30 self.roots = roots
31 self.nodes = nodes
32 self.show = show
33 self.ask = ask
34 self.open = open
35 self.insertLink = insertLink
36 self.refresh = refresh
37 }
38
39 private var dailies: Dailies? { Dailies.configured(roots: roots()) }
40
41 private func day(_ offset: Int, from now: Date = Date()) -> Date {
42 Calendar.current.date(byAdding: .day, value: offset, to: now) ?? now
43 }
44
45 public func run(_ id: String) {
46 switch id {
47 case "app.dailies.today": goto(day(0))
48 case "app.dailies.yesterday": goto(day(-1))
49 case "app.dailies.tomorrow": goto(day(1))
50 case "app.dailies.capture-today": capture(day(0))
51 case "app.dailies.capture-yesterday": capture(day(-1))
52 case "app.dailies.capture-tomorrow": capture(day(1))
53 case "app.dailies.date", "app.dailies.capture-date":
54 let goto = id == "app.dailies.date"
55 ask(Prompt(key: "date", message: goto ? "Find daily-note: " : "Capture to daily-note: ", date: Prompt.DateRead(defaultDate: nil))) { answer in
56 guard let answer else { return }
57 let now = Date()
58 let read = ReadDate.read(answer, default: nil, now: now, calendar: .current)
59 guard let chosen = Calendar.current.date(from: read.components(.current)) else { return }
60 // The time of day stays now's, as `org-read-date` with `to-time` keeps it.
61 let time = Calendar.current.dateComponents([.hour, .minute, .second], from: now)
62 let date = Calendar.current.date(bySettingHour: read.timeGiven ? read.hour : time.hour!, minute: read.timeGiven ? read.minute : time.minute!,
63 second: read.timeGiven ? 0 : time.second!, of: chosen) ?? chosen
64 if goto { self.goto(date) } else { capture(date) }
65 }
66 case "app.dailies.next", "app.dailies.previous":
67 guard let dailies else { return show("No folder for daily notes") }
68 guard let path = session.path else { return show("Not in a daily-note") }
69 do {
70 let note = try dailies.neighbor(of: path, by: id == "app.dailies.next" ? 1 : -1)
71 open(note, 0)
72 } catch {
73 show("\(error)")
74 }
75 case "app.node.find":
76 chooseNode("Node: ") { node in open(node.location.path, node.location.start) }
77 case "app.node.insert":
78 chooseNode("Node: ") { node in insertLink("id:" + node.id, node.title) }
79 default:
80 show("Unknown command \(id)")
81 }
82 }
83
84 /// `org-roam-dailies-goto-*`: the day's file, made if missing.
85 func goto(_ day: Date) {
86 guard let dailies else { return show("No folder for daily notes") }
87 do {
88 let (path, created) = try dailies.ensure(day)
89 if created { refresh() }
90 open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0)
91 } catch {
92 show("Can't make the daily note: \(error.localizedDescription)")
93 }
94 }
95
96 /// `org-roam-dailies-capture-*`: the entry template filed at the end of the day's file,
97 /// which opens with the caret at `%?`.
98 func capture(_ day: Date) {
99 guard let dailies else { return show("No folder for daily notes") }
100 let context = CaptureContext(now: day, file: session.path ?? "", userName: NSFullUserName())
101 let questions = Capture.questions(dailies.entry, context: context)
102 func ask(_ answers: [String]) {
103 guard answers.count < questions.count else { return file(answers) }
104 let question = questions[answers.count]
105 self.ask(Prompt(key: "q\(answers.count)", message: question.prompt + ": ", initial: question.defaultValue, requireMatch: false)) { answer in
106 if let answer { ask(answers + [answer]) }
107 }
108 }
109 func file(_ answers: [String]) {
110 do {
111 let (path, created) = try dailies.ensure(day)
112 if created { refresh() }
113 guard let text = session.text(of: path) else { return show("Can't read \((path as NSString).lastPathComponent)") }
114 let filled: (text: String, cursor: Int)
115 switch Capture.fill(dailies.entry, context: context, answers: answers) {
116 case .success(let result): filled = result
117 case .failure(.message(let message)): return show(message)
118 }
119 let template = CaptureTemplate(key: "d", name: "daily", target: .file(path), template: dailies.entry)
120 switch Capture.placement(filled.text, template: template, in: text, now: day) {
121 case .failure(.message(let message)): show(message)
122 case .success(let placed):
123 if case .failed(let message) = session.perform(ReplaceText(old: text, new: placed.text), path: path, at: 0, expect: nil) { return show(message) }
124 open(path, placed.start + filled.cursor)
125 }
126 } catch {
127 show("Can't make the daily note: \(error.localizedDescription)")
128 }
129 }
130 ask([])
131 }
132
133 /// `org-roam-node-read`: a node by its title, with its file's name when titles repeat.
134 private func chooseNode(_ message: String, _ then: @escaping (IndexStore.Node) -> Void) {
135 let all = nodes()
136 guard !all.isEmpty else { return show("No headings or files have IDs") }
137 let counts = Dictionary(all.map { ($0.title, 1) }, uniquingKeysWith: +)
138 let labels = all.map { node in
139 counts[node.title, default: 0] > 1 ? "\(node.title) (\((node.location.path as NSString).lastPathComponent))" : node.title
140 }
141 ask(Prompt(key: "node", message: message, choices: labels)) { answer in
142 guard let answer, let index = labels.firstIndex(of: answer) else { return }
143 then(all[index])
144 }
145 }
146}