krz/org-swift

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

Sources/OrgSwiftUI/OrgLayoutBuilder.swift

v0.3.1
org-swift/Sources/OrgSwiftUI/OrgLayoutBuilder.swift history · blame · raw

179 lines · 7308 bytes

  1import OrgSwift
  2import SwiftUI
  3
  4/// Walks an ``OrgDocument`` into an ``OrgLayout``.
  5///
  6/// The third renderer over the shared tree, alongside HTML and `AttributedString`. It
  7/// resolves URLs through the same ``OrgURLResolver`` and numbers footnotes through the same
  8/// ``OrgFootnotes``, so a link that works in the HTML output works here and note 1 is note 1
  9/// in both.
 10@MainActor
 11struct OrgLayoutBuilder {
 12    var options: OrgRenderOptions
 13    var styler: OrgCodeStyler
 14    var keywords: OrgKeywordStyle
 15
 16    private var inline: OrgInlineStyler { OrgInlineStyler(options: options) }
 17    private var resolver: OrgURLResolver { OrgURLResolver(options: options) }
 18
 19    func layout(_ document: OrgDocument) -> OrgLayout {
 20        var notes = OrgFootnotes(document: document)
 21        var layout = OrgLayout()
 22        layout.blocks = document.elements.flatMap { block($0, &notes) }
 23        // Numbering is complete only after the whole body is walked, so the notes section is
 24        // built last — exactly as the HTML renderer does it.
 25        layout.footnotes = notes.notes.map {
 26            OrgFootnote(number: $0.number, text: text($0.content, &notes, style: .footnote))
 27        }
 28        return layout
 29    }
 30
 31    private func text(
 32        _ objects: [OrgObject], _ notes: inout OrgFootnotes,
 33        style: Font.TextStyle = .body, bold: Bool = false
 34    ) -> AttributedString {
 35        inline.attributed(objects, &notes, style: style, bold: bold)
 36    }
 37
 38    /// One element to zero or more blocks. Zero for a footnote definition (it moves to the
 39    /// notes section) and for an export block aimed at another backend.
 40    private func block(_ element: OrgElement, _ notes: inout OrgFootnotes) -> [OrgBlock] {
 41        switch element {
 42        case .heading(let heading):
 43            var title = AttributedString()
 44            if let todo = heading.todo {
 45                var keyword = AttributedString(todo + " ")
 46                keyword.foregroundColor = keywords.color(for: todo)
 47                title += keyword
 48            }
 49            if let priority = heading.priority {
 50                var cookie = AttributedString("[#\(priority)] ")
 51                cookie.foregroundColor = .secondary
 52                title += cookie
 53            }
 54            let level = min(6, max(1, heading.level + options.headingLevelOffset))
 55            title += text(heading.title, &notes, style: Self.headingStyle(level), bold: true)
 56            for tag in heading.tags {
 57                var chip = AttributedString("  \(tag)")
 58                chip.foregroundColor = .secondary
 59                chip.font = .system(.caption, design: .monospaced)
 60                title += chip
 61            }
 62            return [.heading(text: title, level: level)]
 63
 64        case .paragraph(let objects):
 65            return [.paragraph(text(objects, &notes))]
 66
 67        case .list(let list):
 68            return [.list(listLayout(list, &notes))]
 69
 70        case .table(let table):
 71            return [.table(tableLayout(table, &notes))]
 72
 73        case .srcBlock(let language, let code):
 74            return [.code(styled(code: code, language: language))]
 75
 76        case .exampleBlock(let raw):
 77            return [.code(styled(code: raw, language: nil))]
 78
 79        case .quoteBlock(let children):
 80            return [.quote(children.flatMap { block($0, &notes) })]
 81
 82        case .centerBlock(let children):
 83            return [.center(children.flatMap { block($0, &notes) })]
 84
 85        case .verseBlock(let lines):
 86            return [.verse(lines.map { text($0, &notes) })]
 87
 88        case .specialBlock(let name, let children):
 89            return [.special(name: name, blocks: children.flatMap { block($0, &notes) })]
 90
 91        case .exportBlock(let backend, let raw):
 92            // HTML passes through verbatim in the HTML renderer; natively there is nothing to
 93            // pass it to, so it shows as the literal block it is rather than vanishing.
 94            return backend == "html" ? [.code(styled(code: raw, language: nil))] : []
 95
 96        case .figure(let figure):
 97            return [imageBlock(figure, &notes)]
 98
 99        case .captioned(_, let caption, let content):
100            return [.captioned(
101                caption: caption.map { text($0, &notes, style: .footnote) },
102                blocks: block(content, &notes)
103            )]
104
105        case .horizontalRule:
106            return [.rule]
107
108        case .footnoteDefinition:
109            return []  // collected into the notes section
110        }
111    }
112
113    /// An image whose source will not resolve to a safe absolute URL degrades to its alt
114    /// text, the same trade the HTML renderer makes rather than pointing at something unsafe.
115    ///
116    /// The absolute requirement is the one place this diverges from HTML, which may emit a
117    /// relative `src` for a document base URL to resolve. A view has no base, so a relative
118    /// source is unloadable and showing the text beats showing a broken image.
119    private func imageBlock(_ figure: OrgFigure, _ notes: inout OrgFootnotes) -> OrgBlock {
120        let caption = figure.caption.map { text($0, &notes, style: .footnote) }
121        guard let string = resolver.imageSource(figure.source),
122              let url = URL(string: string), url.scheme != nil else {
123            return .paragraph(AttributedString(figure.alt ?? figure.source))
124        }
125        let alt = figure.alt ?? figure.caption.map { OrgParser.plain($0) } ?? ""
126        return .image(source: url, alt: alt, caption: caption)
127    }
128
129    private func styled(code: String, language: String?) -> AttributedString {
130        if let highlighted = styler.highlighted(code: code, language: language) {
131            return highlighted
132        }
133        var plain = AttributedString(code)
134        plain.font = .system(.footnote, design: .monospaced)
135        return plain
136    }
137
138    private func listLayout(_ list: OrgList, _ notes: inout OrgFootnotes) -> OrgListLayout {
139        var items: [OrgListLayout.Item] = []
140        for item in list.items {
141            items.append(OrgListLayout.Item(
142                checkbox: item.checkbox,
143                term: item.term.map { term in
144                    var styled = text(term, &notes)
145                    styled.font = .body.bold()
146                    return styled
147                },
148                paragraphs: item.content.map { text($0, &notes) },
149                sublist: item.sublist.map { listLayout($0, &notes) }
150            ))
151        }
152        return OrgListLayout(kind: list.kind, items: items)
153    }
154
155    private func tableLayout(_ table: OrgTable, _ notes: inout OrgFootnotes) -> OrgTableLayout {
156        var rows: [OrgTableLayout.Row] = []
157        for row in table.rows {
158            guard case .cells(let cells) = row else { continue }
159            rows.append(OrgTableLayout.Row(cells: cells.map {
160                OrgTableLayout.Cell(text: text($0, &notes, style: .subheadline))
161            }))
162        }
163        return OrgTableLayout(
164            rows: rows,
165            headerRowCount: table.headerRowCount,
166            alignments: table.alignments
167        )
168    }
169
170    private static func headingStyle(_ level: Int) -> Font.TextStyle {
171        switch level {
172        case 1: .title
173        case 2: .title2
174        case 3: .title3
175        case 4: .headline
176        default: .subheadline
177        }
178    }
179}