Branchwell

Textley / app · textley.ai / Sources / TextleyCore / MarkdownPreview.swift

Raw 6.3 KB on 63b71f34cfe61bc6553e8463e803a45424bff4d3
1import Foundation
2import UniformTypeIdentifiers
3
4public enum MarkdownPreview {
5 public static func html(for source: String, fileURL: URL?) -> String {
6 let options = AttributedString.MarkdownParsingOptions(interpretedSyntax: .full)
7 guard let markdown = try? AttributedString(markdown: source, options: options) else {
8 return page("<pre>" + escape(source) + "</pre>")
9 }
10
11 var output = ""
12 var stack: [PresentationIntent.IntentType] = []
13 for run in markdown.runs {
14 let chain = Array((run.presentationIntent?.components ?? []).reversed())
15 let shared = zip(stack, chain).prefix { $0.identity == $1.identity }.count
16 for component in stack.dropFirst(shared).reversed() { output += closingTag(component.kind) }
17 for component in chain.dropFirst(shared) { output += openingTag(component.kind) }
18 stack = chain
19
20 if chain.last?.kind == .thematicBreak { continue }
21 let raw = String(markdown[run.range].characters)
22 var inline = escape(raw)
23 let style = run.inlinePresentationIntent ?? []
24 if let imageURL = run.imageURL {
25 let alt = escape(run.alternateDescription ?? raw)
26 if let dataURL = localImage(imageURL, fileURL: fileURL) {
27 inline = "<img alt=\"" + alt + "\" src=\"" + dataURL + "\">"
28 } else {
29 inline = "<span class=\"image-alt\">" + (alt.isEmpty ? "Image" : alt) + "</span>"
30 }
31 } else if style.contains(.lineBreak) {
32 inline = "<br>"
33 } else if style.contains(.softBreak) {
34 inline = "\n"
35 }
36 if style.contains(.code) { inline = "<code>" + inline + "</code>" }
37 if style.contains(.emphasized) { inline = "<em>" + inline + "</em>" }
38 if style.contains(.stronglyEmphasized) { inline = "<strong>" + inline + "</strong>" }
39 if style.contains(.strikethrough) { inline = "<del>" + inline + "</del>" }
40 if let url = run.link, ["http", "https", "mailto"].contains(url.scheme?.lowercased() ?? "") {
41 inline = "<a href=\"" + escape(url.absoluteString) + "\">" + inline + "</a>"
42 } else if let url = run.link, url.absoluteString.hasPrefix("#") {
43 inline = "<a href=\"" + escape(url.absoluteString) + "\">" + inline + "</a>"
44 }
45 output += inline
46 }
47 for component in stack.reversed() { output += closingTag(component.kind) }
48 return page(output)
49 }
50
51 private static func openingTag(_ kind: PresentationIntent.Kind) -> String {
52 switch kind {
53 case .paragraph: return "<p>"
54 case .header(let level): return "<h\(level)>"
55 case .orderedList: return "<ol>"
56 case .unorderedList: return "<ul>"
57 case .listItem(let ordinal): return "<li value=\"\(ordinal)\">"
58 case .codeBlock: return "<pre><code>"
59 case .blockQuote: return "<blockquote>"
60 case .thematicBreak: return "<hr>"
61 case .table: return "<table>"
62 case .tableHeaderRow, .tableRow: return "<tr>"
63 case .tableCell: return "<td>"
64 @unknown default: return ""
65 }
66 }
67
68 private static func closingTag(_ kind: PresentationIntent.Kind) -> String {
69 switch kind {
70 case .paragraph: return "</p>"
71 case .header(let level): return "</h\(level)>"
72 case .orderedList: return "</ol>"
73 case .unorderedList: return "</ul>"
74 case .listItem: return "</li>"
75 case .codeBlock: return "</code></pre>"
76 case .blockQuote: return "</blockquote>"
77 case .thematicBreak: return ""
78 case .table: return "</table>"
79 case .tableHeaderRow, .tableRow: return "</tr>"
80 case .tableCell: return "</td>"
81 @unknown default: return ""
82 }
83 }
84
85 private static func localImage(_ reference: URL, fileURL: URL?) -> String? {
86 guard let directory = fileURL?.deletingLastPathComponent(), reference.scheme == nil,
87 !reference.relativePath.hasPrefix("/"), reference.host == nil else { return nil }
88 let url = directory.appendingPathComponent(reference.relativePath).standardizedFileURL
89 guard let mime = UTType(filenameExtension: url.pathExtension)?.preferredMIMEType,
90 ["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif"].contains(mime),
91 let metadata = try? url.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]),
92 metadata.isRegularFile == true, let bytes = metadata.fileSize, bytes <= 10_000_000,
93 let data = try? Data(contentsOf: url), data.count <= 10_000_000 else { return nil }
94 return "data:" + mime + ";base64," + data.base64EncodedString()
95 }
96
97 private static func escape(_ text: String) -> String {
98 text.replacingOccurrences(of: "&", with: "&amp;")
99 .replacingOccurrences(of: "<", with: "&lt;")
100 .replacingOccurrences(of: ">", with: "&gt;")
101 .replacingOccurrences(of: "\"", with: "&quot;")
102 .replacingOccurrences(of: "'", with: "&#39;")
103 }
104
105 private static func page(_ body: String) -> String {
106 """
107 <!doctype html><html lang="en"><head><meta charset="utf-8">
108 <meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data:; style-src 'unsafe-inline'">
109 <style>
110 :root { color-scheme: light dark; }
111 body { font: 15px/1.6 -apple-system, sans-serif; margin: 24px auto; padding: 0 24px; max-width: 50rem; overflow-wrap: anywhere; }
112 h1, h2, h3, h4, h5, h6 { line-height: 1.25; }
113 p, blockquote, pre, table { margin-block: 0 1em; }
114 code { font-family: ui-monospace, monospace; font-size: .9em; }
115 pre { overflow: auto; background: color-mix(in srgb, CanvasText 7%, Canvas); padding: 12px; border-radius: 5px; }
116 blockquote { padding-inline-start: 12px; border-inline-start: 3px solid GrayText; margin-inline-start: 0; }
117 table { border-collapse: collapse; }
118 td { border: 1px solid GrayText; padding: 4px 8px; }
119 tr:first-child { font-weight: 600; }
120 img { max-width: 100%; height: auto; }
121 .image-alt { color: GrayText; font-style: italic; }
122 </style></head><body>\(body)</body></html>
123 """
124 }
125}