Sources/Orgstar/LinkOpener.swift

31 lines · 1490 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        #if APPSTORE
12        // A file outside the sidebar's folders needs access to its folder first.
13        if link.type == "file", !link.path.isEmpty,
14           !GrantAccess.reach([DocumentSession.resolve(link.path, from: session.path)], workspace: workspace) { return nil }
15        #endif
16        switch session.follow(link, workspace: workspace, isText: FileTypes.isText) {
17        case .shown: return nil
18        case .openExternally(let url):
19            NSWorkspace.shared.open(url)
20            return nil
21        case .message(let message): return message
22        case .choose(let prompt, let paths):
23            let labels = paths.map { ($0 as NSString).lastPathComponent }
24            ask(Prompt(key: "file", message: prompt, choices: labels)) { answer in
25                guard let answer, let index = labels.firstIndex(of: answer) else { return }
26                _ = open(OrgLink(type: "file", path: paths[index], raw: "file:" + paths[index]), session: session, workspace: workspace, ask: ask)
27            }
28            return nil
29        }
30    }
31}