krz/org-swift

A dependency-free Swift library that renders org-mode to sanitized HTML. html library org-mode swift

Sources/OrgSwift/AST/OrgHTMLTreeRenderer.swift

v0.4.0
org-swift/Sources/OrgSwift/AST/OrgHTMLTreeRenderer.swift history · blame · raw

297 lines · 13838 bytes

  1import Foundation
  2
  3/// Renders an ``OrgDocument`` to HTML by walking the tree.
  4///
  5/// The point of the prototype: this produces the same shape of output as the shipped
  6/// single-pass ``OrgRenderer``, but from a parsed tree rather than from source, so a second
  7/// renderer (see ``OrgAttributedStringRenderer``) can share the parse instead of re-deriving it.
  8///
  9/// Not `Sendable`: it holds a ``CodeHighlighter``, and a real one wraps a thread-confined
 10/// engine (Highlightr's JavaScriptCore context, say). Sending the renderer across isolation
 11/// domains would call that engine off its thread. Make one where you render.
 12public struct OrgHTMLTreeRenderer {
 13    /// The same options the shipped ``OrgRenderer`` takes, so this renderer is a drop-in for it.
 14    public var options: OrgRenderOptions
 15    public var highlighter: CodeHighlighter
 16
 17    public init(options: OrgRenderOptions = .init(), highlighter: CodeHighlighter = PlainCodeHighlighter()) {
 18        self.options = options
 19        self.highlighter = highlighter
 20    }
 21
 22    public func render(_ document: OrgDocument) -> String {
 23        var footnotes = OrgFootnotes(document: document)
 24        var html = metadataHeader(document)
 25        html += document.elements.map { element($0, &footnotes) }.joined()
 26        html += renderFootnoteSection(&footnotes)
 27        return html
 28    }
 29
 30    /// The leading `#+TITLE`/`#+AUTHOR`/`#+DATE` block, when the caller wants one. orgo treats
 31    /// these as document metadata carried by a page template, so the corpus renders with this
 32    /// off; an app showing a README title turns it on.
 33    private func metadataHeader(_ document: OrgDocument) -> String {
 34        guard options.metadataHeader else { return "" }
 35        let title = document.keyword("title")
 36        let author = document.keyword("author")
 37        let date = document.keyword("date")
 38        guard title != nil || author != nil || date != nil else { return "" }
 39
 40        var html = "<div class=\"org-metadata\">\n"
 41        if let title { html += "<h1 class=\"org-title\">" + escapeHTML(title) + "</h1>\n" }
 42        if let author { html += "<p class=\"org-author\">" + escapeHTML(author) + "</p>\n" }
 43        if let date { html += "<p class=\"org-date\">" + escapeHTML(date) + "</p>\n" }
 44        return html + "</div>\n"
 45    }
 46
 47    // MARK: - URL resolution
 48
 49    /// Link and image resolution is shared with the other renderers; see ``OrgURLResolver``.
 50    private var resolver: OrgURLResolver { OrgURLResolver(options: options) }
 51
 52    // MARK: - Blocks
 53
 54    private func element(_ element: OrgElement, _ notes: inout OrgFootnotes) -> String {
 55        switch element {
 56        case .heading(let heading):
 57            let level = min(6, max(1, heading.level + options.headingLevelOffset))
 58            var inner = ""
 59            if let todo = heading.todo {
 60                inner += #"<span class="\#(todo.lowercased()) \#(todo)">\#(todo)</span> "#
 61            }
 62            if let priority = heading.priority {
 63                inner += #"<span class="priority">[#\#(priority)]</span> "#
 64            }
 65            inner += renderInline(heading.title, &notes)
 66            for tag in heading.tags {
 67                inner += #" <span class="tag">\#(escapeHTML(tag))</span>"#
 68            }
 69            return "<h\(level)>\(inner)</h\(level)>\n"
 70
 71        case .paragraph(let objects):
 72            return "<p>" + renderInline(objects, &notes) + "</p>\n"
 73
 74        case .list(let list):
 75            return renderList(list, &notes)
 76
 77        case .table(let table):
 78            return renderTable(table, &notes)
 79
 80        case .srcBlock(let language, let code):
 81            let classAttribute = language.map { #" class="language-\#(escapeHTMLAttribute($0))""# } ?? ""
 82            let body = highlighter.highlightedHTML(code: code, language: language) ?? escapeHTML(code)
 83            return "<pre><code\(classAttribute)>\(body)</code></pre>\n"
 84
 85        case .exampleBlock(let text):
 86            return "<pre>\(escapeHTML(text))</pre>\n"
 87
 88        case .quoteBlock(let children):
 89            return "<blockquote>\n" + children.map { self.element($0, &notes) }.joined() + "</blockquote>\n"
 90
 91        case .centerBlock(let children):
 92            return #"<div class="center">"# + "\n" + children.map { self.element($0, &notes) }.joined() + "</div>\n"
 93
 94        case .verseBlock(let lines):
 95            let body = lines.map { renderInline($0, &notes) }.joined(separator: "<br>\n")
 96            return #"<p class="verse">"# + "\n" + body + "\n</p>\n"
 97
 98        case .specialBlock(let name, let children):
 99            return #"<div class="\#(escapeHTMLAttribute(name))">"# + "\n"
100                + children.map { self.element($0, &notes) }.joined() + "</div>\n"
101
102        case .exportBlock(let backend, let raw):
103            return backend == "html" ? raw + "\n" : ""
104
105        case .figure(let figure):
106            guard let tag = imageTag(figure, caption: figure.caption) else {
107                return "<p>" + escapeHTML(figure.alt ?? figure.source) + "</p>\n"
108            }
109            // A bare image is a paragraph; a caption or explicit attributes promote it to a
110            // <figure>, matching org's exporter.
111            guard figure.caption != nil || !figure.attributes.isEmpty else {
112                return "<p>" + tag + "</p>\n"
113            }
114            var html = "<figure>" + tag
115            if let caption = figure.caption {
116                notes.figureNumber += 1
117                html += #"<figcaption><span class="figure-number">Figure \#(notes.figureNumber): </span>"#
118                    + renderInline(caption, &notes) + "</figcaption>"
119            }
120            return html + "</figure>\n"
121
122        case .captioned(let name, let caption, let content):
123            let idAttribute = name.map { #" id="\#(escapeHTMLAttribute($0))""# } ?? ""
124            var html = #"<figure class="org-block"\#(idAttribute)>"# + "\n"
125            html += self.element(content, &notes)
126            if let caption {
127                html += "<figcaption>" + renderInline(caption, &notes) + "</figcaption>\n"
128            }
129            return html + "</figure>\n"
130
131        case .horizontalRule:
132            return "<hr>\n"
133
134        case .footnoteDefinition:
135            return ""  // collected and emitted in the notes section
136        }
137    }
138
139    private func renderList(_ list: OrgList, _ notes: inout OrgFootnotes) -> String {
140        if list.kind == .description {
141            var html = "<dl>\n"
142            for item in list.items {
143                if let term = item.term {
144                    html += "<dt>" + renderInline(term, &notes) + "</dt>\n"
145                }
146                if let first = item.content.first {
147                    html += "<dd>" + renderInline(first, &notes) + "</dd>\n"
148                }
149            }
150            return html + "</dl>\n"
151        }
152
153        let tag = list.kind == .ordered ? "ol" : "ul"
154        var html = "<\(tag)>\n"
155        for item in list.items {
156            html += "<li>"
157            if let checkbox = item.checkbox {
158                switch checkbox {
159                case .off: html += "<code>[&nbsp;]</code> "
160                case .on: html += "<code>[X]</code> "
161                case .partial: html += "<code>[-]</code> "
162                }
163            }
164            if item.content.count <= 1 {
165                html += renderInline(item.content.first ?? [], &notes)
166            } else {
167                html += item.content.map { "<p>" + renderInline($0, &notes) + "</p>" }.joined(separator: "\n")
168            }
169            if let sublist = item.sublist {
170                html += "\n" + renderList(sublist, &notes)
171            }
172            html += "</li>\n"
173        }
174        return html + "</\(tag)>\n"
175    }
176
177    private func renderTable(_ table: OrgTable, _ notes: inout OrgFootnotes) -> String {
178        var html = "<table>\n"
179        var wroteHeader = false
180        var inBody = false
181        let headerCount = table.headerRowCount
182
183        for (index, row) in table.rows.enumerated() {
184            switch row {
185            case .rule:
186                if wroteHeader, !inBody { html += "</thead>\n<tbody>\n"; inBody = true }
187            case .cells(let cells):
188                let isHeader = headerCount > 0 && index < headerCount
189                if isHeader, !wroteHeader { html += "<thead>\n"; wroteHeader = true }
190                if !isHeader, !inBody { html += "<tbody>\n"; inBody = true }
191                html += "<tr>\n"
192                for (column, cell) in cells.enumerated() {
193                    let tag = isHeader ? "th" : "td"
194                    let alignment = column < table.alignments.count ? table.alignments[column] : nil
195                    let style = alignment.map { #" style="text-align: \#($0.rawValue);""# } ?? ""
196                    html += "<\(tag)\(style)>" + renderInline(cell, &notes) + "</\(tag)>\n"
197                }
198                html += "</tr>\n"
199            }
200        }
201        if inBody { html += "</tbody>\n" }
202        return html + "</table>\n"
203    }
204
205    /// The `<img>` for a figure, or nil when the source cannot be resolved to a safe URL —
206    /// in which case the caller falls back to text rather than pointing at something unsafe.
207    private func imageTag(_ figure: OrgFigure, caption: [OrgObject]?) -> String? {
208        guard let source = resolver.imageSource(figure.source) else { return nil }
209        let alt = figure.alt ?? caption.map { plainText($0) } ?? ""
210        var html = #"<img src="\#(source)" alt="\#(escapeHTMLAttribute(alt))""#
211        for (key, value) in figure.attributes where key != "alt" {
212            html += " \(escapeHTMLAttribute(key))=\"\(escapeHTMLAttribute(value))\""
213        }
214        return html + ">"
215    }
216
217    // MARK: - Inline
218
219    func renderInline(_ objects: [OrgObject], _ notes: inout OrgFootnotes) -> String {
220        var html = ""
221        for object in objects {
222            switch object {
223            case .text(let text): html += escapeHTML(text)
224            case .bold(let children): html += "<strong>" + renderInline(children, &notes) + "</strong>"
225            case .italic(let children): html += "<em>" + renderInline(children, &notes) + "</em>"
226            case .underline(let children): html += "<u>" + renderInline(children, &notes) + "</u>"
227            case .strikeThrough(let children): html += "<del>" + renderInline(children, &notes) + "</del>"
228            case .verbatim(let text), .code(let text): html += "<code>" + escapeHTML(text) + "</code>"
229            case .superscript(let children): html += "<sup>" + renderInline(children, &notes) + "</sup>"
230            case .lineBreak: html += "<br>"
231            case .image(let figure):
232                html += imageTag(figure, caption: nil) ?? escapeHTML(figure.alt ?? figure.source)
233            case .timestamp(let stamp):
234                let cssClass = stamp.active ? "timestamp" : "timestamp inactive"
235                func time(_ machine: String, _ display: String) -> String {
236                    #"<time class="\#(cssClass)" datetime="\#(machine)">\#(display)</time>"#
237                }
238                html += time(stamp.machineValue, stamp.displayValue)
239                // A range is two <time> elements joined by an en-dash, as org exports it.
240                if let end = stamp.end {
241                    html += "&#8211;" + time(end.machineValue, end.displayValue)
242                }
243            case .footnoteRef(let label, let inline):
244                let number = notes.number(for: label, inline: inline)
245                html += ##"<sup class="footnote-ref"><a id="fnr-\##(number)" href="#fn-\##(number)">\##(number)</a></sup>"##
246            case .link(let link):
247                let text = link.description.map { renderInline($0, &notes) }
248                    ?? escapeHTML(resolver.displayValue(link.target))
249                // An unsafe or unresolvable target degrades to its text, never a bad anchor.
250                if let href = resolver.href(for: link.target) {
251                    html += #"<a href="\#(href)">\#(text)</a>"#
252                } else {
253                    html += text
254                }
255            }
256        }
257        return html
258    }
259
260    /// Inline objects reduced to plain text, for an `alt` attribute.
261    func plainText(_ objects: [OrgObject]) -> String {
262        objects.map { object in
263            switch object {
264            case .text(let text): return text
265            case .verbatim(let text), .code(let text): return text
266            case .bold(let c), .italic(let c), .underline(let c), .strikeThrough(let c), .superscript(let c):
267                return plainText(c)
268            case .link(let link): return link.description.map { plainText($0) } ?? resolver.displayValue(link.target)
269            case .timestamp(let stamp): return stamp.displayValue
270            case .image(let figure): return figure.alt ?? ""
271            case .footnoteRef, .lineBreak: return ""
272            }
273        }.joined()
274    }
275}
276
277// MARK: - Footnote section
278
279private extension OrgHTMLTreeRenderer {
280    /// The `<section class="footnotes">` org's exporter puts at the end of a document.
281    func renderFootnoteSection(_ notes: inout OrgFootnotes) -> String {
282        let collected = notes.notes
283        guard !collected.isEmpty else { return "" }
284        var html = "<section class=\"footnotes\" aria-label=\"Footnotes\">\n<hr>\n<ol>\n"
285        for note in collected {
286            let n = note.number
287            let back = ##"<a class="footnote-back" href="#fnr-\##(n)" aria-label="Back to reference \##(n)">&#8617;</a>"##
288            let body = renderInline(note.content, &notes)
289            if note.isInline {
290                html += "<li id=\"fn-\(n)\">\(body) \(back)</li>\n"
291            } else {
292                html += "<li id=\"fn-\(n)\"><p>\(body)</p>\n \(back)</li>\n"
293            }
294        }
295        return html + "</ol>\n</section>\n"
296    }
297}