Sources/OrgApp/CaptureModel.swift
103 lines · 5729 bytes
1import Foundation
2import Observation
3import OrgConfig
4import OrgCore
5import OrgDocument
6
7extension DocumentSession {
8 /// Places captured `text` with `template`: through the buffer when the target is open,
9 /// otherwise in the file, created if missing, through the save path. `id` and `clock`
10 /// targets must be resolved first (`file` names the ID's file). Returns the file and where
11 /// the entry starts.
12 public func capture(_ text: String, template: CaptureTemplate, root: String?, file: String? = nil, now: Date = Date()) -> Result<(path: String, offset: Int), CaptureError> {
13 let path = file ?? Self.resolve(template.target.file, root: root)
14 if !isOpen(path), !FileManager.default.fileExists(atPath: path) {
15 do {
16 try FileManager.default.createDirectory(at: URL(fileURLWithPath: path).deletingLastPathComponent(), withIntermediateDirectories: true)
17 try Data().write(to: URL(fileURLWithPath: path))
18 } catch {
19 return .failure(CaptureError(message: "Can't create \(path): \(error.localizedDescription)"))
20 }
21 }
22 switch perform(CapturePlacement(text: text, template: template), path: path, at: 0, expect: nil, now: now) {
23 case .commit(let result): return .success((path, result.selection?.first?.lowerBound ?? 0))
24 case .failed(let message): return .failure(CaptureError(message: message))
25 default: return .failure(CaptureError(message: "Can't capture there."))
26 }
27 }
28
29 /// A template's file: absolute, `~/…`, or relative to `root`.
30 public static func resolve(_ file: String, root: String?) -> String {
31 CaptureTemplates.path(file, root: root)
32 }
33
34 /// `%a`: a link to the heading at the caret, as `org-store-link` makes one.
35 public func captureAnnotation() -> String {
36 guard let path, self.document != nil else { return "" }
37 let abbreviated = path.hasPrefix(OrgPaths.home) ? "~" + path.dropFirst(OrgPaths.home.count) : Substring(path)
38 guard let entry = outline.last(where: { $0.start <= caret }) else { return "[[file:\(abbreviated)]]" }
39 return "[[file:\(abbreviated)::*\(entry.title)][\(entry.title)]]"
40 }
41}
42
43public struct CaptureError: Error, Equatable {
44 public let message: String
45 public init(message: String) { self.message = message }
46}
47
48extension DocumentSession {
49 /// Shortcuts' "Capture to Orgstar": `text` as `%i` in the template keyed `key` (the first
50 /// when nil or empty), its prompts taking their defaults, filed without the capture window.
51 /// The template used.
52 public func capture(
53 _ text: String, templateKey key: String?, templates: [CaptureTemplate], workspace: WorkspaceModel, clock: ClockModel,
54 clipboard: String, userName: String
55 ) -> Result<CaptureTemplate, CaptureError> {
56 capture(text, templateKey: key, templates: templates, workspace: workspace, clock: clock, clipboard: clipboard, userName: userName).map(\.template)
57 }
58
59 /// `capture(_:templateKey:…)` with prompts answered by their prompt text (`%^{What}` by
60 /// `answers["What"]`, empty when missing) and org-protocol's link properties for `%a`,
61 /// `%:link` and the like. The template used, and the file and offset of the entry.
62 public func capture(
63 _ text: String, templateKey key: String?, templates: [CaptureTemplate], workspace: WorkspaceModel, clock: ClockModel,
64 clipboard: String, userName: String, answers: [String: String] = [:], properties: [String: String] = [:]
65 ) -> Result<(template: CaptureTemplate, path: String, offset: Int), CaptureError> {
66 let key = key.flatMap { $0.isEmpty ? nil : $0 }
67 guard let chosen = key.map({ key in templates.first { $0.key == key } }) ?? templates.first else {
68 return .failure(CaptureError(message: "No capture template \"\(key ?? "")\""))
69 }
70 var context = CaptureContext(initial: text, clipboard: clipboard, userName: userName, allTags: (try? workspace.index.tags()) ?? [])
71 if let annotation = properties["annotation"] { context.annotation = annotation }
72 context.linkProperties = properties
73 context.readsTemplateFiles()
74 let answers = Capture.questions(chosen.template, context: context).map { answers[$0.prompt] ?? "" }
75 guard case .success(let filled) = Capture.fill(chosen.template, context: context, answers: answers) else {
76 return .failure(CaptureError(message: "Can't fill template \"\(chosen.key)\""))
77 }
78 return chosen.resolved(workspace: workspace, session: self, clock: clock).flatMap { resolved in
79 capture(filled.text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file)
80 }.map { (chosen, $0.path, $0.offset) }
81 }
82}
83
84extension CaptureTemplate {
85 /// `id` and `clock` targets as a file and a heading.
86 @MainActor
87 public func resolved(
88 workspace: WorkspaceModel, session: DocumentSession, clock: ClockModel
89 ) -> Result<(template: CaptureTemplate, file: String?), CaptureError> {
90 switch target {
91 case .id(let id):
92 guard let location = try? workspace.index.headings(withID: id).first else {
93 return .failure(CaptureError(message: "Cannot find target ID \"\(id)\""))
94 }
95 return .success((self, location.path))
96 case .clock:
97 guard let entry = clock.entry(session) else { return .failure(CaptureError(message: "No running clock")) }
98 return .success((retargeted(.heading(file: entry.path, offset: entry.offset)), entry.path))
99 default:
100 return .success((self, nil))
101 }
102 }
103}