Sources/Orgstar/LinkOpener.swift

design-themes-widgets
orgstar/Sources/Orgstar/LinkOpener.swift history · blame · raw

36 lines · 1744 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; `elisp` runs an `elisp:` link's form.
10    static func open(_ link: OrgLink, session: DocumentSession, workspace: WorkspaceModel, ask: @escaping (Prompt, @escaping (String?) -> Void) -> Void,
11                     elisp: ((String) -> Void)? = nil) -> String? {
12        #if APPSTORE
13        // A file outside the sidebar's folders needs access to its folder first.
14        if link.type == "file", !link.path.isEmpty,
15           !GrantAccess.reach([DocumentSession.resolve(link.path, from: session.path)], workspace: workspace) { return nil }
16        #endif
17        switch session.follow(link, workspace: workspace, isText: FileTypes.isText) {
18        case .shown: return nil
19        case .openExternally(let url):
20            NSWorkspace.shared.open(url)
21            return nil
22        case .message(let message): return message
23        case .choose(let prompt, let paths):
24            let labels = paths.map { ($0 as NSString).lastPathComponent }
25            ask(Prompt(key: "file", message: prompt, choices: labels)) { answer in
26                guard let answer, let index = labels.firstIndex(of: answer) else { return }
27                _ = open(OrgLink(type: "file", path: paths[index], raw: "file:" + paths[index]), session: session, workspace: workspace, ask: ask)
28            }
29            return nil
30        case .elisp(let form):
31            guard let elisp else { return "orgstar doesn't run elisp links here" }
32            elisp(form)
33            return nil
34        }
35    }
36}