import Foundation import UniformTypeIdentifiers public enum MarkdownPreview { public static func html(for source: String, fileURL: URL?) -> String { let options = AttributedString.MarkdownParsingOptions(interpretedSyntax: .full) guard let markdown = try? AttributedString(markdown: source, options: options) else { return page("
" + escape(source) + "") } var output = "" var stack: [PresentationIntent.IntentType] = [] for run in markdown.runs { let chain = Array((run.presentationIntent?.components ?? []).reversed()) let shared = zip(stack, chain).prefix { $0.identity == $1.identity }.count for component in stack.dropFirst(shared).reversed() { output += closingTag(component.kind) } for component in chain.dropFirst(shared) { output += openingTag(component.kind) } stack = chain if chain.last?.kind == .thematicBreak { continue } let raw = String(markdown[run.range].characters) var inline = escape(raw) let style = run.inlinePresentationIntent ?? [] if let imageURL = run.imageURL { let alt = escape(run.alternateDescription ?? raw) if let dataURL = localImage(imageURL, fileURL: fileURL) { inline = "
" + inline + "" }
if style.contains(.emphasized) { inline = "" + inline + "" }
if style.contains(.stronglyEmphasized) { inline = "" + inline + "" }
if style.contains(.strikethrough) { inline = ""
case .header(let level): return ""
case .unorderedList: return "
"
case .listItem(let ordinal): return "
"
case .blockQuote: return ""
case .thematicBreak: return "
"
case .table: return ""
case .tableHeaderRow, .tableRow: return "
"
case .tableHeaderRow, .tableRow: return ""
case .tableCell: return ""
@unknown default: return ""
}
}
private static func localImage(_ reference: URL, fileURL: URL?) -> String? {
guard let directory = fileURL?.deletingLastPathComponent(), reference.scheme == nil,
!reference.relativePath.hasPrefix("/"), reference.host == nil else { return nil }
let url = directory.appendingPathComponent(reference.relativePath).standardizedFileURL
guard let mime = UTType(filenameExtension: url.pathExtension)?.preferredMIMEType,
["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif"].contains(mime),
let metadata = try? url.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]),
metadata.isRegularFile == true, let bytes = metadata.fileSize, bytes <= 10_000_000,
let data = try? Data(contentsOf: url), data.count <= 10_000_000 else { return nil }
return "data:" + mime + ";base64," + data.base64EncodedString()
}
private static func escape(_ text: String) -> String {
text.replacingOccurrences(of: "&", with: "&")
.replacingOccurrences(of: "<", with: "<")
.replacingOccurrences(of: ">", with: ">")
.replacingOccurrences(of: "\"", with: """)
.replacingOccurrences(of: "'", with: "'")
}
private static func page(_ body: String) -> String {
"""
\(body)
"""
}
}
"
case .tableCell: return " "
@unknown default: return ""
}
}
private static func closingTag(_ kind: PresentationIntent.Kind) -> String {
switch kind {
case .paragraph: return ""
case .header(let level): return ""
case .orderedList: return ""
case .unorderedList: return ""
case .listItem: return ""
case .codeBlock: return ""
case .blockQuote: return ""
case .thematicBreak: return ""
case .table: return "