Sources/Orgstar/LinkOpener.swift
26 lines · 1195 bytes
1import AppKit
2import OrgApp
3import OrgCore
4
5/// Follows a link, handing addresses and files Orgstar doesn't edit to macOS.
6@MainActor
7enum LinkOpener {
8 /// Returns a message when the link can't be followed.
9 /// `ask` picks among a query link's matches.
10 static func open(_ link: OrgLink, session: DocumentSession, workspace: WorkspaceModel, ask: @escaping (Prompt, @escaping (String?) -> Void) -> Void) -> String? {
11 switch session.follow(link, workspace: workspace, isText: FileTypes.isText) {
12 case .shown: return nil
13 case .openExternally(let url):
14 NSWorkspace.shared.open(url)
15 return nil
16 case .message(let message): return message
17 case .choose(let prompt, let paths):
18 let labels = paths.map { ($0 as NSString).lastPathComponent }
19 ask(Prompt(key: "file", message: prompt, choices: labels)) { answer in
20 guard let answer, let index = labels.firstIndex(of: answer) else { return }
21 _ = open(OrgLink(type: "file", path: paths[index], raw: "file:" + paths[index]), session: session, workspace: workspace, ask: ask)
22 }
23 return nil
24 }
25 }
26}