Sources/Orgstar/CaptureIntent.swift
62 lines · 3060 bytes
1import AppIntents
2import AppKit
3import OrgApp
4import OrgCore
5
6/// Shortcuts' "Capture to Orgstar": files text with a capture template without the capture
7/// window. Prompts in the template take their defaults.
8struct CaptureIntent: AppIntent {
9 static let title: LocalizedStringResource = "Capture to Orgstar"
10 static let description = IntentDescription("Files text with one of your capture templates.")
11
12 @Parameter(title: "Text")
13 var text: String
14
15 @Parameter(title: "Template Key", description: "A template's key in capture.toml; the first template when empty.")
16 var template: String?
17
18 /// The app's models, once its window is up.
19 @MainActor static var environment: (workspace: WorkspaceModel, session: DocumentSession, clock: ClockModel, commands: AppCommands)?
20
21 struct Failure: Error, CustomLocalizedStringResourceConvertible {
22 let message: String
23 var localizedStringResource: LocalizedStringResource { "\(message)" }
24 }
25
26 @MainActor
27 func perform() async throws -> some IntentResult & ReturnsValue<String> & ProvidesDialog {
28 // Launched for the intent, the window sets the models up shortly.
29 for _ in 0..<50 where Self.environment == nil { try? await Task.sleep(for: .milliseconds(100)) }
30 guard let (workspace, session, clock, commands) = Self.environment else { throw Failure(message: "Orgstar isn't ready") }
31 let templates = CaptureTemplates.load().templates
32 let key = template.flatMap { $0.isEmpty ? nil : $0 }
33 guard let chosen = key.map({ key in templates.first { $0.key == key } }) ?? templates.first else {
34 throw Failure(message: "No capture template \"\(key ?? "")\"")
35 }
36 let context = CaptureContext(
37 initial: text, clipboard: NSPasteboard.general.string(forType: .string) ?? "", userName: NSFullUserName(),
38 allTags: (try? workspace.index.tags()) ?? []
39 )
40 let answers = Capture.questions(chosen.template, context: context).map { _ in "" }
41 guard case .success(let filled) = Capture.fill(chosen.template, context: context, answers: answers) else {
42 throw Failure(message: "Can't fill template \"\(chosen.key)\"")
43 }
44 let placed = CaptureView.resolved(chosen, workspace: workspace, session: session, clock: clock).flatMap { resolved in
45 session.capture(filled.text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file)
46 }
47 switch placed {
48 case .failure(let error):
49 throw Failure(message: error.message)
50 case .success:
51 let message = "Captured to \(CaptureView.target(chosen))"
52 commands.show(message)
53 return .result(value: message, dialog: "\(message)")
54 }
55 }
56}
57
58struct OrgstarShortcuts: AppShortcutsProvider {
59 static var appShortcuts: [AppShortcut] {
60 AppShortcut(intent: CaptureIntent(), phrases: ["Capture to \(.applicationName)"], shortTitle: "Capture", systemImageName: "tray.and.arrow.down")
61 }
62}