Sources/OrgSwiftUI/OrgLayoutBuilder.swift
220 lines · 9238 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 var textTransform: ((inout AttributedString) -> Void)? = nil
16
17 private var inline: OrgInlineStyler { OrgInlineStyler(options: options) }
18 private var resolver: OrgURLResolver { OrgURLResolver(options: options) }
19
20 func layout(_ document: OrgDocument) -> OrgLayout {
21 var notes = OrgFootnotes(document: document)
22 var layout = OrgLayout()
23 layout.blocks = document.elements.flatMap { block($0, ¬es) }
24 // Numbering is complete only after the whole body is walked, so the notes section is
25 // built last — exactly as the HTML renderer does it.
26 layout.footnotes = notes.notes.map {
27 OrgFootnote(number: $0.number, text: text($0.content, ¬es, style: .footnote))
28 }
29 return layout
30 }
31
32 private func text(
33 _ objects: [OrgObject], _ notes: inout OrgFootnotes,
34 style: Font.TextStyle = .body, bold: Bool = false
35 ) -> AttributedString {
36 var string = inline.attributed(objects, ¬es, style: style, bold: bold)
37 textTransform?(&string)
38 return string
39 }
40
41 /// One element to zero or more blocks. Zero for a footnote definition (it moves to the
42 /// notes section) and for an export block aimed at another backend.
43 private func block(_ element: OrgElement, _ notes: inout OrgFootnotes) -> [OrgBlock] {
44 switch element {
45 case .heading(let heading):
46 var title = AttributedString()
47 if let todo = heading.todo {
48 var keyword = AttributedString(todo + " ")
49 keyword.foregroundColor = keywords.color(for: todo)
50 title += keyword
51 }
52 if let priority = heading.priority {
53 var cookie = AttributedString("[#\(priority)] ")
54 cookie.foregroundColor = .secondary
55 title += cookie
56 }
57 let level = min(6, max(1, heading.level + options.headingLevelOffset))
58 title += text(heading.title, ¬es, style: Self.headingStyle(level), bold: true)
59 for tag in heading.tags {
60 var chip = AttributedString(" \(tag)")
61 chip.foregroundColor = .secondary
62 chip.font = .system(.caption, design: .monospaced)
63 title += chip
64 }
65 return [.heading(text: title, level: level)]
66
67 case .paragraph(let objects):
68 if let badges = badgeRow(objects) { return [.badges(badges)] }
69 return [.paragraph(text(objects, ¬es))]
70
71 case .list(let list):
72 return [.list(listLayout(list, ¬es))]
73
74 case .table(let table):
75 return [.table(tableLayout(table, ¬es))]
76
77 case .srcBlock(let language, let code):
78 return [.code(styled(code: code, language: language))]
79
80 case .exampleBlock(let raw):
81 return [.code(styled(code: raw, language: nil))]
82
83 case .quoteBlock(let children):
84 return [.quote(children.flatMap { block($0, ¬es) })]
85
86 case .centerBlock(let children):
87 return [.center(children.flatMap { block($0, ¬es) })]
88
89 case .verseBlock(let lines):
90 return [.verse(lines.map { text($0, ¬es) })]
91
92 case .specialBlock(let name, let children):
93 return [.special(name: name, blocks: children.flatMap { block($0, ¬es) })]
94
95 case .exportBlock(let backend, let raw):
96 // HTML passes through verbatim in the HTML renderer; natively there is nothing to
97 // pass it to, so it shows as the literal block it is rather than vanishing.
98 return backend == "html" ? [.code(styled(code: raw, language: nil))] : []
99
100 case .figure(let figure):
101 return [imageBlock(figure, ¬es)]
102
103 case .captioned(_, let caption, let content):
104 return [.captioned(
105 caption: caption.map { text($0, ¬es, style: .footnote) },
106 blocks: block(content, ¬es)
107 )]
108
109 case .horizontalRule:
110 return [.rule]
111
112 case .footnoteDefinition:
113 return [] // collected into the notes section
114 }
115 }
116
117 /// A paragraph holding nothing but images and image links is the badge row a README
118 /// opens with. It renders as a row of images at their own size rather than as prose —
119 /// the inline styler can only show an image's alt text, and a figure block would blow a
120 /// 95×20 badge up to the column width.
121 ///
122 /// Anything else in the paragraph, a word of prose included, means it is prose.
123 private func badgeRow(_ objects: [OrgObject]) -> [OrgBadge]? {
124 var badges: [OrgBadge] = []
125 for object in objects {
126 switch object {
127 case .text(let string) where string.trimmingCharacters(in: .whitespaces).isEmpty:
128 continue
129 case .image(let figure):
130 guard let badge = badge(figure, link: nil) else { return nil }
131 badges.append(badge)
132 case .link(let link):
133 guard link.description?.count == 1,
134 case .image(let figure) = link.description?.first
135 else { return nil }
136 // A badge whose link will not resolve is still a badge; it just is not
137 // tappable.
138 let href = resolver.href(for: link.target).flatMap { URL(string: $0) }
139 guard let badge = badge(figure, link: href) else { return nil }
140 badges.append(badge)
141 default:
142 return nil
143 }
144 }
145 return badges.isEmpty ? nil : badges
146 }
147
148 private func badge(_ figure: OrgFigure, link: URL?) -> OrgBadge? {
149 guard let string = resolver.imageSource(figure.source),
150 let url = URL(string: string), url.scheme != nil
151 else { return nil }
152 return OrgBadge(source: url, alt: figure.alt ?? "", link: link)
153 }
154
155 /// An image whose source will not resolve to a safe absolute URL degrades to its alt
156 /// text, the same trade the HTML renderer makes rather than pointing at something unsafe.
157 ///
158 /// The absolute requirement is the one place this diverges from HTML, which may emit a
159 /// relative `src` for a document base URL to resolve. A view has no base, so a relative
160 /// source is unloadable and showing the text beats showing a broken image.
161 private func imageBlock(_ figure: OrgFigure, _ notes: inout OrgFootnotes) -> OrgBlock {
162 let caption = figure.caption.map { text($0, ¬es, style: .footnote) }
163 guard let string = resolver.imageSource(figure.source),
164 let url = URL(string: string), url.scheme != nil else {
165 return .paragraph(AttributedString(figure.alt ?? figure.source))
166 }
167 let alt = figure.alt ?? figure.caption.map { OrgParser.plain($0) } ?? ""
168 return .image(source: url, alt: alt, caption: caption)
169 }
170
171 private func styled(code: String, language: String?) -> AttributedString {
172 if let highlighted = styler.highlighted(code: code, language: language) {
173 return highlighted
174 }
175 var plain = AttributedString(code)
176 plain.font = .system(.footnote, design: .monospaced)
177 return plain
178 }
179
180 private func listLayout(_ list: OrgList, _ notes: inout OrgFootnotes) -> OrgListLayout {
181 var items: [OrgListLayout.Item] = []
182 for item in list.items {
183 items.append(OrgListLayout.Item(
184 checkbox: item.checkbox,
185 term: item.term.map { term in
186 var styled = text(term, ¬es)
187 styled.font = .body.bold()
188 return styled
189 },
190 blocks: item.content.flatMap { block($0, ¬es) }
191 ))
192 }
193 return OrgListLayout(kind: list.kind, items: items)
194 }
195
196 private func tableLayout(_ table: OrgTable, _ notes: inout OrgFootnotes) -> OrgTableLayout {
197 var rows: [OrgTableLayout.Row] = []
198 for row in table.rows {
199 guard case .cells(let cells) = row else { continue }
200 rows.append(OrgTableLayout.Row(cells: cells.map {
201 OrgTableLayout.Cell(text: text($0, ¬es, style: .subheadline))
202 }))
203 }
204 return OrgTableLayout(
205 rows: rows,
206 headerRowCount: table.headerRowCount,
207 alignments: table.alignments
208 )
209 }
210
211 private static func headingStyle(_ level: Int) -> Font.TextStyle {
212 switch level {
213 case 1: .title
214 case 2: .title2
215 case 3: .title3
216 case 4: .headline
217 default: .subheadline
218 }
219 }
220}