krz/org-swift

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

Sources/OrgSwiftUI/OrgLayout.swift

v0.3.0
org-swift/Sources/OrgSwiftUI/OrgLayout.swift history · blame · raw

77 lines · 2482 bytes

 1import OrgSwift
 2import SwiftUI
 3
 4/// A document prepared for display: inline runs already styled, footnotes already numbered,
 5/// image URLs already resolved, code already highlighted.
 6///
 7/// The walk happens once, ahead of `body`, because three things it does must not happen per
 8/// layout pass — footnote numbering is sequential and document-wide, syntax highlighting is
 9/// expensive, and both would otherwise re-run every time SwiftUI recomputes a view.
10struct OrgLayout {
11    var blocks: [OrgBlock] = []
12    var footnotes: [OrgFootnote] = []
13}
14
15struct OrgFootnote: Identifiable {
16    var number: Int
17    var text: AttributedString
18    var id: Int { number }
19}
20
21/// A block ready to render. Mirrors ``OrgElement`` minus the cases that resolve away:
22/// footnote definitions move to ``OrgLayout/footnotes``, and an export block for another
23/// backend drops entirely.
24indirect enum OrgBlock: Identifiable {
25    case heading(text: AttributedString, level: Int)
26    case paragraph(AttributedString)
27    case code(AttributedString)
28    case quote([OrgBlock])
29    case center([OrgBlock])
30    case verse([AttributedString])
31    case special(name: String, blocks: [OrgBlock])
32    case list(OrgListLayout)
33    case table(OrgTableLayout)
34    case image(source: URL, alt: String, caption: AttributedString?)
35    case captioned(caption: AttributedString?, blocks: [OrgBlock])
36    case rule
37
38    /// Positional identity. Blocks are rebuilt wholesale when the source changes, so their
39    /// index in the layout is stable for as long as the layout is.
40    var id: String { String(describing: self).prefix(64).description }
41}
42
43struct OrgListLayout {
44    var kind: OrgListKind
45    var items: [Item]
46
47    struct Item: Identifiable {
48        var checkbox: OrgCheckbox?
49        var term: AttributedString?
50        var paragraphs: [AttributedString]
51        var sublist: OrgListLayout?
52        var id = UUID()
53    }
54}
55
56struct OrgTableLayout {
57    /// Cell rows only; org's `|---|` rule rows are structure, carried by ``headerRowCount``.
58    var rows: [Row]
59    var headerRowCount: Int
60    var alignments: [OrgAlignment?]
61
62    struct Row: Identifiable {
63        var cells: [Cell]
64        var id = UUID()
65    }
66
67    struct Cell: Identifiable {
68        var text: AttributedString
69        var id = UUID()
70    }
71
72    var columnCount: Int { rows.map(\.cells.count).max() ?? 0 }
73
74    func alignment(column: Int) -> OrgAlignment? {
75        column < alignments.count ? alignments[column] : nil
76    }
77}