Sources/OrgApp/DiagramBlocks.swift
164 lines · 8235 bytes
1#if canImport(WebKit)
2import Foundation
3import OrgCore
4import WebKit
5
6/// dot and mermaid blocks drawn in a web view, for builds that can't start `dot` or `mmdc`: dot
7/// with Viz.js (Graphviz as WebAssembly), mermaid with mermaid.js. They write SVG and PNG; other
8/// formats and most of `:cmdline` are refused. Mermaid labels are SVG text rather than HTML, so
9/// the SVG shows outside a browser and can be drawn into the PNG.
10public enum DiagramBlocks {
11 /// `viz-global.js` and `mermaid.min.js`, which the app sets from `OrgMathJax`.
12 nonisolated(unsafe) public static var vizURL: URL?
13 nonisolated(unsafe) public static var mermaidURL: URL?
14
15 /// The width of `mmdc`'s page, which a wider mermaid diagram is scaled down to.
16 static let pageWidth = 800
17
18 /// Draws `job` into its `:file` when it is a dot or mermaid block, in `directory` or its
19 /// `:dir`; nil for other jobs.
20 @MainActor
21 public static func run(_ job: BabelJob, directory: URL) async throws -> BabelOutput? {
22 guard let diagram = job.diagram else { return nil }
23 let folder = job.directory.map { URL(fileURLWithPath: $0, relativeTo: directory).standardizedFileURL } ?? directory
24 let target = diagram.file.hasPrefix("/") ? URL(fileURLWithPath: diagram.file) : folder.appendingPathComponent(diagram.file)
25 let data = try await draw(language: job.language, source: diagram.source, cmdline: diagram.cmdline, format: target.pathExtension)
26 do {
27 try data.write(to: target)
28 } catch {
29 throw Babel.Failure.message(error.localizedDescription)
30 }
31 return BabelOutput(stdout: "")
32 }
33
34 /// What `:cmdline` asks for.
35 struct Options: Equatable {
36 /// dot's `-K`.
37 var engine = "dot"
38 /// mmdc's `-t` and `-b`.
39 var theme = "default"
40 var background = "white"
41
42 /// `-Kengine` for dot; `-t theme` and `-b color` for mermaid, in their long forms too.
43 /// Nil for anything else.
44 init?(language: String, cmdline: String?) {
45 var words = (cmdline ?? "").split(whereSeparator: \.isWhitespace).map(String.init)[...]
46 while let word = words.popFirst() {
47 if language == "dot", word.hasPrefix("-K"), word.count > 2 {
48 engine = String(word.dropFirst(2))
49 } else if language == "mermaid", ["-t", "--theme"].contains(word), let value = words.popFirst() {
50 theme = value
51 } else if language == "mermaid", ["-b", "--backgroundColor"].contains(word), let value = words.popFirst() {
52 background = value
53 } else {
54 return nil
55 }
56 }
57 }
58 }
59
60 /// The picture as SVG text or PNG data; `format` is the file's extension, PNG when empty.
61 @MainActor
62 static func draw(language: String, source: String, cmdline: String?, format: String) async throws -> Data {
63 let format = format.isEmpty ? "png" : format.lowercased()
64 guard ["svg", "png"].contains(format) else {
65 throw Babel.Failure.message(String(localized: "\(language) blocks draw only SVG and PNG files in this version of orgstar."))
66 }
67 guard let options = Options(language: language, cmdline: cmdline) else {
68 throw Babel.Failure.message(String(localized: "\(language) blocks with this :cmdline don't run in this version of orgstar."))
69 }
70 guard let library = language == "dot" ? vizURL : mermaidURL, let script = try? String(contentsOf: library, encoding: .utf8) else {
71 throw Babel.Failure.message("The \(language) library is missing from the app.")
72 }
73 let configuration = WKWebViewConfiguration()
74 configuration.userContentController.addUserScript(WKUserScript(source: script, injectionTime: .atDocumentEnd, forMainFrameOnly: true))
75 let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: pageWidth, height: 600), configuration: configuration)
76 let loader = Loader()
77 webView.navigationDelegate = loader
78 // Viz.js resolves its own name against the page's address; nothing is fetched.
79 webView.loadHTMLString("<!doctype html><html><body style=\"margin:0\"></body></html>", baseURL: URL(string: "https://localhost/"))
80 try await loader.loaded()
81 do {
82 let result = try await webView.callAsyncJavaScript(
83 (language == "dot" ? dot : mermaid) + raster,
84 arguments: ["source": source, "format": format, "engine": options.engine, "theme": options.theme, "background": options.background],
85 contentWorld: .page
86 )
87 guard let text = result as? String else { throw Babel.Failure.message("The \(language) block drew nothing.") }
88 if format == "svg" { return Data(text.utf8) }
89 guard let png = Data(base64Encoded: text) else { throw Babel.Failure.message("The \(language) block drew nothing.") }
90 return png
91 } catch let error as NSError where error.domain == WKErrorDomain {
92 throw Babel.Failure.message((error.userInfo["WKJavaScriptExceptionMessage"] as? String) ?? error.localizedDescription)
93 }
94 }
95
96 /// Leaves the SVG in `svg`.
97 private static let dot = """
98 const viz = await Viz.instance();
99 const result = viz.render(source, { format: "svg", engine: engine });
100 if (result.status !== "success") {
101 throw new Error(result.errors.map(error => error.message).join("\\n") || "dot failed");
102 }
103 const svg = result.output;
104
105 """
106
107 private static let mermaid = """
108 mermaid.initialize({ startOnLoad: false, theme: theme, htmlLabels: false, flowchart: { htmlLabels: false } });
109 await mermaid.parse(source);
110 const svg = (await mermaid.render("my-svg", source)).svg;
111
112 """
113
114 /// Returns `svg`, or for PNG its picture at the size it has on the page, as base64.
115 private static let raster = """
116 if (format === "svg") { return svg; }
117 const holder = document.createElement("div");
118 holder.innerHTML = svg;
119 document.body.replaceChildren(holder);
120 const element = holder.querySelector("svg");
121 const box = element.getBoundingClientRect();
122 const width = Math.max(1, Math.ceil(box.width)), height = Math.max(1, Math.ceil(box.height));
123 element.setAttribute("width", width);
124 element.setAttribute("height", height);
125 element.removeAttribute("style");
126 const image = new Image();
127 image.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(new XMLSerializer().serializeToString(element));
128 await image.decode();
129 const canvas = document.createElement("canvas");
130 canvas.width = width;
131 canvas.height = height;
132 const context = canvas.getContext("2d");
133 if (background !== "transparent") {
134 context.fillStyle = background;
135 context.fillRect(0, 0, width, height);
136 }
137 context.drawImage(image, 0, 0, width, height);
138 return canvas.toDataURL("image/png").split(",")[1];
139 """
140
141 private final class Loader: NSObject, WKNavigationDelegate {
142 private var continuation: CheckedContinuation<Void, Error>?
143 private var result: Result<Void, Error>?
144
145 func loaded() async throws {
146 if let result { return try result.get() }
147 try await withCheckedThrowingContinuation { self.continuation = $0 }
148 }
149
150 private func finish(_ result: Result<Void, Error>) {
151 if let continuation {
152 continuation.resume(with: result)
153 self.continuation = nil
154 } else {
155 self.result = result
156 }
157 }
158
159 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { finish(.success(())) }
160 func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { finish(.failure(error)) }
161 func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { finish(.failure(error)) }
162 }
163}
164#endif