Sources/OrgApp/RoamActions.swift

172 lines · 8589 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: ") { choice in
 77                switch choice {
 78                case .existing(let node): open(node.location.path, node.location.start)
 79                case .created(let path, _, _): open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0)
 80                }
 81            }
 82        case "app.node.insert":
 83            chooseNode("Node: ") { choice in
 84                switch choice {
 85                case .existing(let node): insertLink("id:" + node.id, node.title)
 86                case .created(_, let id, let title): insertLink("id:" + id, title)
 87                }
 88            }
 89        default:
 90            show("Unknown command \(id)")
 91        }
 92    }
 93
 94    /// `org-roam-dailies-goto-*`: the day's file, made if missing.
 95    func goto(_ day: Date) {
 96        guard let dailies else { return show("No folder for daily notes") }
 97        do {
 98            let (path, created) = try dailies.ensure(day)
 99            if created { refresh() }
100            open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0)
101        } catch {
102            show("Can't make the daily note: \(error.localizedDescription)")
103        }
104    }
105
106    /// `org-roam-dailies-capture-*`: the entry template filed at the end of the day's file,
107    /// which opens with the caret at `%?`.
108    func capture(_ day: Date) {
109        guard let dailies else { return show("No folder for daily notes") }
110        let context = CaptureContext(now: day, file: session.path ?? "", userName: NSFullUserName())
111        let questions = Capture.questions(dailies.entry, context: context)
112        func ask(_ answers: [String]) {
113            guard answers.count < questions.count else { return file(answers) }
114            let question = questions[answers.count]
115            self.ask(Prompt(key: "q\(answers.count)", message: question.prompt + ": ", initial: question.defaultValue, requireMatch: false)) { answer in
116                if let answer { ask(answers + [answer]) }
117            }
118        }
119        func file(_ answers: [String]) {
120            do {
121                let (path, created) = try dailies.ensure(day)
122                if created { refresh() }
123                guard let text = session.text(of: path) else { return show("Can't read \((path as NSString).lastPathComponent)") }
124                let filled: (text: String, cursor: Int)
125                switch Capture.fill(dailies.entry, context: context, answers: answers) {
126                case .success(let result): filled = result
127                case .failure(.message(let message)): return show(message)
128                }
129                let template = CaptureTemplate(key: "d", name: "daily", target: .file(path), template: dailies.entry)
130                switch Capture.placement(filled.text, template: template, in: text, now: day) {
131                case .failure(.message(let message)): show(message)
132                case .success(let placed):
133                    if case .failed(let message) = session.perform(ReplaceText(old: text, new: placed.text), path: path, at: 0, expect: nil) { return show(message) }
134                    open(path, placed.start + filled.cursor)
135                }
136            } catch {
137                show("Can't make the daily note: \(error.localizedDescription)")
138            }
139        }
140        ask([])
141    }
142
143    enum NodeChoice {
144        case existing(IndexStore.Node)
145        case created(path: String, id: String, title: String)
146    }
147
148    /// `org-roam-node-read`: a node by its title, with its file's name when titles repeat. A
149    /// title no node has makes a node with it, as org-roam's default capture template does.
150    private func chooseNode(_ message: String, _ then: @escaping (NodeChoice) -> Void) {
151        let all = nodes()
152        let counts = Dictionary(all.map { ($0.title, 1) }, uniquingKeysWith: +)
153        let labels = all.map { node in
154            counts[node.title, default: 0] > 1 ? "\(node.title) (\((node.location.path as NSString).lastPathComponent))" : node.title
155        }
156        ask(Prompt(key: "node", message: message, choices: labels, requireMatch: false)) { answer in
157            guard let answer else { return }
158            if let index = labels.firstIndex(of: answer) { return then(.existing(all[index])) }
159            let title = answer.trimmingCharacters(in: .whitespaces)
160            guard !title.isEmpty else { return }
161            guard let folder = RoamNode.directory(roots: roots()) else { return show("No folder for new nodes") }
162            do {
163                let node = try RoamNode.create(title: title, in: folder)
164                refresh()
165                show("Created \((node.path as NSString).lastPathComponent)")
166                then(.created(path: node.path, id: node.id, title: title))
167            } catch {
168                show("Can't make the node: \(error)")
169            }
170        }
171    }
172}