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.5.0
org-swift/Sources/OrgSwift/AST/OrgHTMLTreeRenderer.swift history · blame · raw

307 lines · 14344 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 !item.content.isEmpty {
147                    html += "<dd>" + renderItemContent(item, &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            html += renderItemContent(item, &notes)
165            html += "</li>\n"
166        }
167        return html + "</\(tag)>\n"
168    }
169
170    /// A list item's body. A lone paragraph renders bare inside the `<li>`; two or more get
171    /// their own `<p>`, matching org's exporter. Anything that is not a paragraph — a nested
172    /// list, a source block, a table — renders as the block it is, in source order.
173    private func renderItemContent(_ item: OrgListItem, _ notes: inout OrgFootnotes) -> String {
174        let wrapParagraphs = item.paragraphs.count > 1
175        var parts: [String] = []
176        for child in item.content {
177            if case .paragraph(let objects) = child {
178                let text = renderInline(objects, &notes)
179                parts.append(wrapParagraphs ? "<p>" + text + "</p>" : text)
180            } else {
181                parts.append(element(child, &notes))
182            }
183        }
184        return parts.joined(separator: "\n")
185    }
186
187    private func renderTable(_ table: OrgTable, _ notes: inout OrgFootnotes) -> String {
188        var html = "<table>\n"
189        var wroteHeader = false
190        var inBody = false
191        let headerCount = table.headerRowCount
192
193        for (index, row) in table.rows.enumerated() {
194            switch row {
195            case .rule:
196                if wroteHeader, !inBody { html += "</thead>\n<tbody>\n"; inBody = true }
197            case .cells(let cells):
198                let isHeader = headerCount > 0 && index < headerCount
199                if isHeader, !wroteHeader { html += "<thead>\n"; wroteHeader = true }
200                if !isHeader, !inBody { html += "<tbody>\n"; inBody = true }
201                html += "<tr>\n"
202                for (column, cell) in cells.enumerated() {
203                    let tag = isHeader ? "th" : "td"
204                    let alignment = column < table.alignments.count ? table.alignments[column] : nil
205                    let style = alignment.map { #" style="text-align: \#($0.rawValue);""# } ?? ""
206                    html += "<\(tag)\(style)>" + renderInline(cell, &notes) + "</\(tag)>\n"
207                }
208                html += "</tr>\n"
209            }
210        }
211        if inBody { html += "</tbody>\n" }
212        return html + "</table>\n"
213    }
214
215    /// The `<img>` for a figure, or nil when the source cannot be resolved to a safe URL —
216    /// in which case the caller falls back to text rather than pointing at something unsafe.
217    private func imageTag(_ figure: OrgFigure, caption: [OrgObject]?) -> String? {
218        guard let source = resolver.imageSource(figure.source) else { return nil }
219        let alt = figure.alt ?? caption.map { plainText($0) } ?? ""
220        var html = #"<img src="\#(source)" alt="\#(escapeHTMLAttribute(alt))""#
221        for (key, value) in figure.attributes where key != "alt" {
222            html += " \(escapeHTMLAttribute(key))=\"\(escapeHTMLAttribute(value))\""
223        }
224        return html + ">"
225    }
226
227    // MARK: - Inline
228
229    func renderInline(_ objects: [OrgObject], _ notes: inout OrgFootnotes) -> String {
230        var html = ""
231        for object in objects {
232            switch object {
233            case .text(let text): html += escapeHTML(text)
234            case .bold(let children): html += "<strong>" + renderInline(children, &notes) + "</strong>"
235            case .italic(let children): html += "<em>" + renderInline(children, &notes) + "</em>"
236            case .underline(let children): html += "<u>" + renderInline(children, &notes) + "</u>"
237            case .strikeThrough(let children): html += "<del>" + renderInline(children, &notes) + "</del>"
238            case .verbatim(let text), .code(let text): html += "<code>" + escapeHTML(text) + "</code>"
239            case .superscript(let children): html += "<sup>" + renderInline(children, &notes) + "</sup>"
240            case .lineBreak: html += "<br>"
241            case .image(let figure):
242                html += imageTag(figure, caption: nil) ?? escapeHTML(figure.alt ?? figure.source)
243            case .timestamp(let stamp):
244                let cssClass = stamp.active ? "timestamp" : "timestamp inactive"
245                func time(_ machine: String, _ display: String) -> String {
246                    #"<time class="\#(cssClass)" datetime="\#(machine)">\#(display)</time>"#
247                }
248                html += time(stamp.machineValue, stamp.displayValue)
249                // A range is two <time> elements joined by an en-dash, as org exports it.
250                if let end = stamp.end {
251                    html += "&#8211;" + time(end.machineValue, end.displayValue)
252                }
253            case .footnoteRef(let label, let inline):
254                let number = notes.number(for: label, inline: inline)
255                html += ##"<sup class="footnote-ref"><a id="fnr-\##(number)" href="#fn-\##(number)">\##(number)</a></sup>"##
256            case .link(let link):
257                let text = link.description.map { renderInline($0, &notes) }
258                    ?? escapeHTML(resolver.displayValue(link.target))
259                // An unsafe or unresolvable target degrades to its text, never a bad anchor.
260                if let href = resolver.href(for: link.target) {
261                    html += #"<a href="\#(href)">\#(text)</a>"#
262                } else {
263                    html += text
264                }
265            }
266        }
267        return html
268    }
269
270    /// Inline objects reduced to plain text, for an `alt` attribute.
271    func plainText(_ objects: [OrgObject]) -> String {
272        objects.map { object in
273            switch object {
274            case .text(let text): return text
275            case .verbatim(let text), .code(let text): return text
276            case .bold(let c), .italic(let c), .underline(let c), .strikeThrough(let c), .superscript(let c):
277                return plainText(c)
278            case .link(let link): return link.description.map { plainText($0) } ?? resolver.displayValue(link.target)
279            case .timestamp(let stamp): return stamp.displayValue
280            case .image(let figure): return figure.alt ?? ""
281            case .footnoteRef, .lineBreak: return ""
282            }
283        }.joined()
284    }
285}
286
287// MARK: - Footnote section
288
289private extension OrgHTMLTreeRenderer {
290    /// The `<section class="footnotes">` org's exporter puts at the end of a document.
291    func renderFootnoteSection(_ notes: inout OrgFootnotes) -> String {
292        let collected = notes.notes
293        guard !collected.isEmpty else { return "" }
294        var html = "<section class=\"footnotes\" aria-label=\"Footnotes\">\n<hr>\n<ol>\n"
295        for note in collected {
296            let n = note.number
297            let back = ##"<a class="footnote-back" href="#fnr-\##(n)" aria-label="Back to reference \##(n)">&#8617;</a>"##
298            let body = renderInline(note.content, &notes)
299            if note.isInline {
300                html += "<li id=\"fn-\(n)\">\(body) \(back)</li>\n"
301            } else {
302                html += "<li id=\"fn-\(n)\"><p>\(body)</p>\n \(back)</li>\n"
303            }
304        }
305        return html + "</ol>\n</section>\n"
306    }
307}