Sources/OrgApp/SnippetLibrary.swift
80 lines · 3933 bytes
6 symbols in this file
1import Foundation
2import Observation
3import OrgCore
4
5/// The snippets of `snippets.toml` in the configuration folder, read at launch and whenever
6/// the file changes. A file that isn't valid TOML is reported and the snippets read before
7/// stay; a snippet with a problem is reported and left out.
8///
9/// For the iOS key bar and other places that offer snippets: `snippets` lists them, and
10/// `Snippet.commandID` (`org.snippet:<trigger>`) is a command any editor runs to expand one at
11/// the caret. `org.snippet.next-field` and `org.snippet.previous-field` move between fields.
12@MainActor
13@Observable
14public final class SnippetLibrary {
15 public static let shared = SnippetLibrary()
16
17 /// Snippets and file templates, in the file's order.
18 public private(set) var snippets: [Snippet] = []
19 /// Problems in the file, from the last time it was read, each starting with its name.
20 public private(set) var problems: [String] = []
21 /// File templates waiting for their new file to open in an editor, by path.
22 @ObservationIgnored private var pending: [String: Snippet] = [:]
23
24 public init() {}
25
26 public static var userFile: URL { UserConfig.file(Snippets.fileName) }
27
28 /// The snippets typed in files, without the file templates.
29 public var typed: [Snippet] { snippets.filter { !$0.file } }
30 /// The templates New File from Template… offers.
31 public var templates: [Snippet] { snippets.filter(\.file) }
32
33 /// Reads `file`; `read` returns nil when there is none, which leaves no snippets.
34 public func reload(from file: URL = userFile, read: (URL) -> String? = { try? String(contentsOf: $0, encoding: .utf8) }) {
35 guard let text = read(file) else {
36 snippets = []
37 problems = []
38 return
39 }
40 do {
41 let parsed = try Snippets.parse(text)
42 if parsed.snippets != snippets { snippets = parsed.snippets }
43 problems = parsed.problems.map { "\(Snippets.fileName) \($0)" }
44 } catch {
45 problems = ["\(Snippets.fileName) \(error)"]
46 }
47 }
48
49 /// Notes that the new file at `path` is to be filled from `template` when it opens.
50 public func expand(_ template: Snippet, intoNewFile path: String) {
51 pending[URL(fileURLWithPath: path).standardizedFileURL.path] = template
52 }
53
54 /// The template that fills the new file at `path`, once; nil for other files. Its editor
55 /// performs `ExpandNamedSnippet(snippet:)` at the start.
56 public func takeTemplate(for path: String) -> Snippet? {
57 pending.removeValue(forKey: URL(fileURLWithPath: path).standardizedFileURL.path)
58 }
59
60 /// The folders a new file can go in: the added folders and the folders holding their files,
61 /// each with its name below its added folder's.
62 public static func folders(in workspace: WorkspaceModel) -> [(path: String, title: String)] {
63 let roots = workspace.rootPaths
64 var paths = Set(roots)
65 for file in workspace.files { paths.insert((file.path as NSString).deletingLastPathComponent) }
66 return paths.compactMap { path -> (path: String, title: String)? in
67 guard let root = roots.first(where: { path == $0 || path.hasPrefix($0 + "/") }) else { return nil }
68 let name = (root as NSString).lastPathComponent
69 return (path, path == root ? name : name + "/" + path.dropFirst(root.count + 1))
70 }.sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending }
71 }
72
73 /// Creates the file `name` in `folder`, as New File does, and notes that `template` fills
74 /// it when it opens. Returns its path.
75 public func createFile(named name: String, in folder: String, from template: Snippet, workspace: WorkspaceModel) async throws -> String {
76 let path = try await workspace.createFile(named: name, in: folder)
77 expand(template, intoNewFile: path)
78 return path
79 }
80}