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 = "\""" } else { inline = "" + (alt.isEmpty ? "Image" : alt) + "" } } else if style.contains(.lineBreak) { inline = "
" } else if style.contains(.softBreak) { inline = "\n" } if style.contains(.code) { inline = "" + inline + "" } if style.contains(.emphasized) { inline = "" + inline + "" } if style.contains(.stronglyEmphasized) { inline = "" + inline + "" } if style.contains(.strikethrough) { inline = "" + inline + "" } if let url = run.link, ["http", "https", "mailto"].contains(url.scheme?.lowercased() ?? "") { inline = "" + inline + "" } else if let url = run.link, url.absoluteString.hasPrefix("#") { inline = "" + inline + "" } output += inline } for component in stack.reversed() { output += closingTag(component.kind) } return page(output) } private static func openingTag(_ kind: PresentationIntent.Kind) -> String { switch kind { case .paragraph: return "

" case .header(let level): return "" case .orderedList: return "

    " case .unorderedList: return "