Tests/OrgAppTests/RoamCaptureTests.swift
cmc org-roam: aliases, refs, excludes, chooser tags, template choice, capture buffer
ed22b081d6 2 hours ago277 lines · 15265 bytes
22 symbols in this file
RoamPropertiesTestssplitsAsSplitStringAndUnquotereadsRefsAsOrgRoamDoesexcludeIsAnyValueButNilindexedNodesHaveAliasesRefsAndTagsAndLeaveExcludedOutRoamCaptureTestsfoldernodeRecorderactionsnewNodeFileFromTheDefaultTemplatenewNodesWaitForTheCaptureWindowseveralTemplatesAreAllOfferedcandidatesShowAliasesAndTagsaliasesFindTheirNoderefsFindTheirNodeprotocolRefsOpenOrMakeNodesdailyGotoAsksOnlyWhenTemplatesNameDifferentFilestemplatesLoadFromCaptureTomlRoamLinkTestsroamLinksFollowTitlesAndAliasesfollow
1import Foundation
2import OrgCore
3import OrgDocument
4@testable import OrgIndex
5import Testing
6@testable import OrgApp
7
8struct RoamPropertiesTests {
9 @Test func splitsAsSplitStringAndUnquote() {
10 #expect(RoamProperties.split(#""Alias One" two three"#) == ["Alias One", "two", "three"])
11 #expect(RoamProperties.split(#"a"b c"d"#) == ["a", "b c", "d"])
12 #expect(RoamProperties.split(#""say \"hi\"" "back\\slash""#) == [#"say "hi""#, #"back\slash"#])
13 #expect(RoamProperties.split(" ") == [])
14 }
15
16 @Test func readsRefsAsOrgRoamDoes() {
17 let refs = RoamProperties(refs: #"https://example.com @key2020 [cite:@a;@b] [[https://x.org/p][Page]] junk "file:/tmp/a b.pdf""#).refList
18 #expect(refs == ["https://example.com", "cite:key2020", "cite:a", "cite:b", "https://x.org/p", "file:/tmp/a"])
19 }
20
21 @Test func excludeIsAnyValueButNil() {
22 #expect(RoamProperties(exclude: "t").excluded)
23 #expect(RoamProperties(exclude: "").excluded)
24 #expect(!RoamProperties(exclude: "nil").excluded)
25 #expect(!RoamProperties().excluded)
26 }
27
28 @Test func indexedNodesHaveAliasesRefsAndTagsAndLeaveExcludedOut() throws {
29 let store = try IndexStore()
30 let text = """
31 :PROPERTIES:
32 :ID: f1
33 :ROAM_ALIASES: "Alias One" two
34 :ROAM_REFS: @key
35 :END:
36 #+title: File One
37 #+filetags: :alpha:
38 * Head :beta:
39 :PROPERTIES:
40 :ID: h1
41 :ROAM_EXCLUDE: t
42 :END:
43 ** Child
44 :PROPERTIES:
45 :ID: h2
46 :END:
47
48 """
49 let record = FileRecord(path: "/n/a.org", root: "/n", kind: .org, bytes: Array(text.utf8), mtime: 1, settings: IndexSettings())
50 try store.write(record)
51 for nodes in [try store.nodes(), try store.nodes(overlay: ["/n/a.org": record])] {
52 #expect(nodes.map(\.id) == ["f1", "h2"])
53 #expect(nodes.first?.aliases == ["Alias One", "two"])
54 #expect(nodes.first?.refs == ["cite:key"])
55 #expect(nodes.first?.tags == ["alpha"])
56 #expect(nodes.last?.tags == ["alpha", "beta"])
57 }
58 #expect(try store.nodeSections()["/n/a.org"]?.map(\.id) == ["h2"])
59 }
60}
61
62@MainActor
63struct RoamCaptureTests {
64 static var now: Date { Calendar.current.date(from: DateComponents(year: 2026, month: 10, day: 13, hour: 9, minute: 5, second: 7))! }
65
66 static func folder() throws -> URL {
67 let url = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-roam-\(UUID().uuidString)").resolvingSymlinksInPath()
68 try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
69 return url
70 }
71
72 static func node(_ id: String, _ title: String, aliases: [String] = [], refs: [String] = [], tags: [String] = [], path: String? = nil) -> IndexStore.Node {
73 IndexStore.Node(id: id, title: title, location: .file(path ?? "/n/\(id).org", contentHash: ""), aliases: aliases, refs: refs, tags: tags)
74 }
75
76 /// Actions answering each question with the next of `answers`, keeping what they did.
77 final class Recorder {
78 var answers: [String?] = []
79 var asked: [Prompt] = []
80 var shown: [String] = []
81 var opened: [(String, Int)] = []
82 var links: [(String, String)] = []
83 var captures: [RoamCapture] = []
84 }
85
86 static func actions(_ folder: URL, nodes: [IndexStore.Node] = [], templates: [RoamTemplate.Set: [RoamTemplate]] = [:], _ recorder: Recorder) -> RoamActions {
87 let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent(".r")))
88 var actions = RoamActions(session: session, roots: { [folder.path] }, nodes: { nodes }, show: { recorder.shown.append($0) },
89 ask: { prompt, reply in
90 recorder.asked.append(prompt)
91 reply(recorder.answers.isEmpty ? nil : recorder.answers.removeFirst())
92 },
93 open: { recorder.opened.append(($0, $1)) }, insertLink: { recorder.links.append(($0, $1)) }, refresh: {})
94 actions.capture = { recorder.captures.append($0) }
95 actions.templates = { set in (templates[set] ?? RoamTemplate.defaults(set), []) }
96 return actions
97 }
98
99 @Test func newNodeFileFromTheDefaultTemplate() throws {
100 let folder = try Self.folder()
101 defer { try? FileManager.default.removeItem(at: folder) }
102 let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent(".r")))
103 var filed: (String, Int, String)?
104 let capture = RoamCapture(RoamTemplate.defaults(.node), title: "Field Notes", directory: folder.path, now: Self.now, session: session, refresh: {},
105 newID: "abc-123") { filed = ($0, $1, $2) }
106 #expect(capture.templates.map(\.target) == [.file(folder.appendingPathComponent("20261013090507-field_notes.org").path)])
107 #expect(capture.isNew(capture.templates[0]))
108 guard case .success(let entry) = capture.file("First line", with: capture.templates[0]) else { Issue.record("not filed"); return }
109 let text = try String(contentsOfFile: entry.path, encoding: .utf8)
110 #expect(text == ":PROPERTIES:\n:ID: abc-123\n:END:\n#+title: Field Notes\nFirst line\n")
111 #expect(filed?.0 == entry.path && filed?.2 == "abc-123")
112 }
113
114 /// Find Node… with a new title shows the capture window; nothing is written until it files,
115 /// and then the node opens. Insert Node Link… links to it only once it's filed.
116 @Test func newNodesWaitForTheCaptureWindow() throws {
117 let folder = try Self.folder()
118 defer { try? FileManager.default.removeItem(at: folder) }
119 let recorder = Recorder()
120 recorder.answers = ["Fresh Idea", "Fresh Idea"]
121 let actions = Self.actions(folder, recorder)
122 actions.run("app.node.find")
123 #expect(recorder.captures.count == 1)
124 #expect(try FileManager.default.contentsOfDirectory(atPath: folder.path).filter { $0.hasSuffix(".org") }.isEmpty)
125 let capture = recorder.captures[0]
126 guard case .success(let entry) = capture.file("", with: capture.templates[0]) else { Issue.record("not filed"); return }
127 #expect(recorder.opened.map(\.0) == [entry.path])
128
129 actions.run("app.node.insert")
130 #expect(recorder.links.isEmpty)
131 let second = recorder.captures[1]
132 guard case .success = second.file("", with: second.templates[0]) else { Issue.record("not filed"); return }
133 #expect(recorder.links.first?.1 == "Fresh Idea")
134 #expect(recorder.links.first?.0.hasPrefix("id:") == true)
135 }
136
137 @Test func severalTemplatesAreAllOffered() throws {
138 let folder = try Self.folder()
139 defer { try? FileManager.default.removeItem(at: folder) }
140 let recorder = Recorder()
141 recorder.answers = ["Topic"]
142 let templates = [RoamTemplate(key: "d", name: "default", kind: .plain, template: "%?", file: "${slug}.org", head: "#+title: ${title}\n"),
143 RoamTemplate(key: "p", name: "person", kind: .plain, template: "* About ${title}", file: "people/${slug}.org", head: "#+title: ${title}\n")]
144 Self.actions(folder, templates: [.node: templates], recorder).run("app.node.find")
145 #expect(recorder.captures.first?.templates.map(\.key) == ["d", "p"])
146 #expect(recorder.captures.first?.templates.map(\.target.file) == [folder.path + "/topic.org", folder.path + "/people/topic.org"])
147 #expect(recorder.captures.first?.templates.last?.template == "* About Topic")
148 }
149
150 @Test func candidatesShowAliasesAndTags() {
151 let nodes = [Self.node("1", "Apple", aliases: ["Malus"], tags: ["fruit", "tree"]), Self.node("2", "Pear"), Self.node("3", "Pear")]
152 #expect(RoamActions.candidates(nodes).map(\.label) == ["Apple #fruit #tree", "Malus #fruit #tree", "Pear (2.org)", "Pear (3.org)"])
153 }
154
155 /// An alias finds its node, and the link it inserts is described by the alias, as
156 /// `org-roam-node-insert` does; a title typed without the tags shown still matches.
157 @Test func aliasesFindTheirNode() throws {
158 let folder = try Self.folder()
159 defer { try? FileManager.default.removeItem(at: folder) }
160 let recorder = Recorder()
161 recorder.answers = ["Malus #fruit", "Apple"]
162 let actions = Self.actions(folder, nodes: [Self.node("1", "Apple", aliases: ["Malus"], tags: ["fruit"])], recorder)
163 actions.run("app.node.insert")
164 actions.run("app.node.find")
165 #expect(recorder.links.map(\.1) == ["Malus"] && recorder.links.map(\.0) == ["id:1"])
166 #expect(recorder.opened.map(\.0) == ["/n/1.org"])
167 #expect(recorder.captures.isEmpty)
168 }
169
170 @Test func refsFindTheirNode() throws {
171 let folder = try Self.folder()
172 defer { try? FileManager.default.removeItem(at: folder) }
173 let recorder = Recorder()
174 recorder.answers = ["cite:key2020 Paper"]
175 Self.actions(folder, nodes: [Self.node("1", "Paper", refs: ["https://example.com", "cite:key2020"]), Self.node("2", "Other")], recorder).run("app.node.find-ref")
176 #expect(recorder.asked.first?.choices == ["https://example.com Paper", "cite:key2020 Paper"])
177 #expect(recorder.opened.map(\.0) == ["/n/1.org"])
178 }
179
180 /// org-protocol's `roam-ref`: the node with the ref opens; another ref makes a node with
181 /// it in `ROAM_REFS` through the capture window. `roam-node` opens the node with the ID.
182 @Test func protocolRefsOpenOrMakeNodes() throws {
183 let folder = try Self.folder()
184 defer { try? FileManager.default.removeItem(at: folder) }
185 let recorder = Recorder()
186 let actions = Self.actions(folder, nodes: [Self.node("1", "Paper", refs: ["https://example.com"])], recorder)
187 actions.follow(.roamRef(ref: "https://example.com", title: "Example", body: nil, template: nil))
188 actions.follow(.roamNode(id: "1"))
189 #expect(recorder.opened.map(\.0) == ["/n/1.org", "/n/1.org"])
190 actions.follow(.roamRef(ref: "https://new.example/a b", title: "New Page", body: "quoted", template: nil))
191 let capture = try #require(recorder.captures.first)
192 guard case .success(let entry) = capture.file("", with: capture.templates[0]) else { Issue.record("not filed"); return }
193 let text = try String(contentsOfFile: entry.path, encoding: .utf8)
194 #expect((entry.path as NSString).lastPathComponent == "new_page.org")
195 #expect(text.contains(":ROAM_REFS: \"https://new.example/a b\"\n:END:\n#+title: New Page\n"))
196 }
197
198 @Test func dailyGotoAsksOnlyWhenTemplatesNameDifferentFiles() throws {
199 let folder = try Self.folder()
200 defer { try? FileManager.default.removeItem(at: folder) }
201 let same = [RoamTemplate(key: "d", name: "default", kind: .entry, template: "* %?", file: "%<%Y-%m-%d>.org", head: "#+title: %<%Y-%m-%d>\n"),
202 RoamTemplate(key: "t", name: "task", kind: .entry, template: "* TODO %?", file: "%<%Y-%m-%d>.org", head: "#+title: %<%Y-%m-%d>\n")]
203 let recorder = Recorder()
204 Self.actions(folder, templates: [.dailies: same], recorder).goto(DailiesTests.day)
205 #expect(recorder.asked.isEmpty && recorder.opened.map(\.0) == [folder.path + "/daily/2026-10-11.org"])
206
207 let different = [same[0], RoamTemplate(key: "w", name: "work", kind: .entry, template: "* %?", file: "work-%<%Y-%m-%d>.org", head: "#+title: Work\n")]
208 let asking = Recorder()
209 asking.answers = ["[w] work"]
210 let actions = Self.actions(folder, templates: [.dailies: different], asking)
211 actions.goto(DailiesTests.day)
212 #expect(asking.asked.first?.choices == ["[d] default", "[w] work"])
213 #expect(asking.opened.map(\.0) == [folder.path + "/daily/work-2026-10-11.org"])
214 #expect(try String(contentsOfFile: folder.path + "/daily/work-2026-10-11.org", encoding: .utf8).hasSuffix(":END:\n#+title: Work\n"))
215
216 actions.capture(DailiesTests.day)
217 #expect(asking.captures.first?.templates.map(\.key) == ["d", "w"])
218 #expect(asking.captures.first?.now == DailiesTests.day)
219 }
220
221 @Test func templatesLoadFromCaptureToml() throws {
222 let folder = try Self.folder()
223 defer { try? FileManager.default.removeItem(at: folder) }
224 let file = folder.appendingPathComponent("capture.toml")
225 try #"""
226 [[template]]
227 key = "t"
228 name = "Todo"
229 file = "todo.org"
230 template = "* TODO %?"
231
232 [[roam-template]]
233 key = "p"
234 name = "person"
235 template = "* Notes"
236 file = "people/${slug}.org"
237 head = "#+title: ${title}\n#+filetags: :person:\n"
238 type = "entry"
239
240 [[roam-template]]
241 key = "x"
242
243 [[roam-dailies-template]]
244 key = "j"
245 name = "journal"
246 template = "* %<%H:%M> %?"
247 olp = "Journal/Log"
248 """#.write(to: file, atomically: true, encoding: .utf8)
249 let nodes = RoamTemplate.load(.node, userFile: file)
250 #expect(nodes.templates == [RoamTemplate(key: "p", name: "person", kind: .entry, template: "* Notes", file: "people/${slug}.org", head: "#+title: ${title}\n#+filetags: :person:\n")])
251 #expect(nodes.problems.count == 1)
252 let defaults = TestDefaults("orgstar-roam-templates")
253 let dailies = RoamTemplate.load(.dailies, userFile: file, defaults: defaults).templates
254 #expect(dailies.map(\.olp) == [["Journal", "Log"]] && dailies.map(\.kind) == [.entry] && dailies.map(\.file) == ["%<%Y-%m-%d>.org"])
255 #expect(RoamTemplate.load(.ref, userFile: file).templates == RoamTemplate.defaults(.ref))
256 let capture = CaptureTemplates.load(userFile: file)
257 #expect(capture.templates.map(\.key) == ["t"] && capture.problems.isEmpty)
258 }
259}
260
261@MainActor
262struct RoamLinkTests {
263 @Test func roamLinksFollowTitlesAndAliases() async throws {
264 let notes = try Folder()
265 let a = try notes.write("a.org", ":PROPERTIES:\n:ID: a1\n:ROAM_ALIASES: \"Second Name\"\n:END:\n#+title: First\n")
266 _ = try notes.write("b.org", ":PROPERTIES:\n:ID: b1\n:END:\n#+title: Twice\n")
267 _ = try notes.write("c.org", ":PROPERTIES:\n:ID: c1\n:END:\n#+title: Twice\n")
268 let workspace = try WorkspaceModel(directory: nil)
269 try await workspace.addRoot(notes.url)
270 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
271 func follow(_ raw: String) -> LinkFollow { session.follow(Links.parse(bracket: raw), workspace: workspace, isText: { $0.hasSuffix(".org") }) }
272 #expect(follow("roam:Second Name") == .shown && session.path == a.path)
273 #expect(follow("roam:First") == .shown)
274 #expect(follow("roam:Nobody") == .message("No node has the title or alias Nobody"))
275 #expect(follow("roam:Twice") == .message("Multiple nodes exist with title or alias \"Twice\""))
276 }
277}