gitbay/Views/Repos/MarkdownView.swift

v1.6.2
gitbay-ios/gitbay/Views/Repos/MarkdownView.swift history · blame · raw

405 lines · 16372 bytes

  1import OrgSwift
  2import SwiftUI
  3
  4/// Block-level markdown for READMEs: headings, fenced code, lists, quotes,
  5/// tables, paragraphs. Inline styling comes from AttributedString's own markdown
  6/// parsing; blocks are split here because it only does inline.
  7struct MarkdownView: View {
  8
  9    let markdown: String
 10    /// Repository context for resolving relative link targets. Nil leaves them as authored,
 11    /// which is right for a body with no file to be relative to.
 12    var linkOptions: OrgRenderOptions?
 13
 14    var body: some View {
 15        VStack(alignment: .leading, spacing: 12) {
 16            ForEach(Array(blocks.enumerated()), id: \.offset) { _, block in
 17                blockView(block)
 18            }
 19        }
 20    }
 21
 22    // MARK: - Block model
 23
 24    enum Block: Equatable {
 25        case heading(level: Int, text: String)
 26        case code(String)
 27        case quote(String)
 28        case bullet([String])
 29        case ordered([String])
 30        case table(Table)
 31        case rule
 32        case paragraph(String)
 33    }
 34
 35    /// A GitHub-flavored table: a header row, a body, and one alignment per
 36    /// column taken from the `|:---:|` separator row.
 37    struct Table: Equatable {
 38        var header: [String]
 39        var rows: [[String]]
 40        var alignments: [Alignment]
 41
 42        enum Alignment: Equatable { case leading, center, trailing }
 43
 44        var columnCount: Int { header.count }
 45    }
 46
 47    var blocks: [Block] {
 48        var blocks: [Block] = []
 49        var lines = markdown.components(separatedBy: "\n")[...]
 50
 51        while let line = lines.first {
 52            let trimmed = line.trimmingCharacters(in: .whitespaces)
 53
 54            if trimmed.hasPrefix("```") {
 55                lines = lines.dropFirst()
 56                var code: [String] = []
 57                while let next = lines.first,
 58                      !next.trimmingCharacters(in: .whitespaces).hasPrefix("```") {
 59                    code.append(next)
 60                    lines = lines.dropFirst()
 61                }
 62                lines = lines.dropFirst() // closing fence
 63                blocks.append(.code(code.joined(separator: "\n")))
 64                continue
 65            }
 66            if trimmed.hasPrefix("#") {
 67                let level = trimmed.prefix(while: { $0 == "#" }).count
 68                let text = trimmed.drop(while: { $0 == "#" }).trimmingCharacters(in: .whitespaces)
 69                blocks.append(.heading(level: min(level, 4), text: text))
 70                lines = lines.dropFirst()
 71                continue
 72            }
 73            if trimmed == "---" || trimmed == "***" || trimmed == "___" {
 74                blocks.append(.rule)
 75                lines = lines.dropFirst()
 76                continue
 77            }
 78            if trimmed.hasPrefix(">") {
 79                var quote: [String] = []
 80                while let next = lines.first?.trimmingCharacters(in: .whitespaces), next.hasPrefix(">") {
 81                    quote.append(next.dropFirst().trimmingCharacters(in: .whitespaces))
 82                    lines = lines.dropFirst()
 83                }
 84                blocks.append(.quote(quote.joined(separator: " ")))
 85                continue
 86            }
 87            if trimmed.hasPrefix("- ") || trimmed.hasPrefix("* ") || trimmed.hasPrefix("+ ") {
 88                var items: [String] = []
 89                while let next = lines.first?.trimmingCharacters(in: .whitespaces) {
 90                    if next.hasPrefix("- ") || next.hasPrefix("* ") || next.hasPrefix("+ ") {
 91                        items.append(String(next.dropFirst(2)))
 92                    } else if Self.continuesItem(lines) {
 93                        items[items.count - 1] += " " + next
 94                    } else {
 95                        break
 96                    }
 97                    lines = lines.dropFirst()
 98                }
 99                blocks.append(.bullet(items))
100                continue
101            }
102            if trimmed.range(of: #"^\d+\. "#, options: .regularExpression) != nil {
103                var items: [String] = []
104                while let next = lines.first?.trimmingCharacters(in: .whitespaces) {
105                    if let range = next.range(of: #"^\d+\. "#, options: .regularExpression) {
106                        items.append(String(next[range.upperBound...]))
107                    } else if Self.continuesItem(lines) {
108                        items[items.count - 1] += " " + next
109                    } else {
110                        break
111                    }
112                    lines = lines.dropFirst()
113                }
114                blocks.append(.ordered(items))
115                continue
116            }
117            if let table = Self.tableStart(lines) {
118                lines = lines.dropFirst(2) // header and separator
119                var rows: [[String]] = []
120                while let next = lines.first, next.contains("|") {
121                    var cells = Self.cells(next)
122                    // Ragged rows are padded, not dropped, so a short row leaves
123                    // blanks rather than shifting the grid.
124                    cells += Array(repeating: "", count: max(0, table.header.count - cells.count))
125                    rows.append(Array(cells.prefix(table.header.count)))
126                    lines = lines.dropFirst()
127                }
128                blocks.append(.table(Table(
129                    header: table.header, rows: rows, alignments: table.alignments
130                )))
131                continue
132            }
133            if trimmed.isEmpty {
134                lines = lines.dropFirst()
135                continue
136            }
137            // Paragraph: consume until a blank line or another block start.
138            var paragraph: [String] = []
139            while let next = lines.first {
140                let t = next.trimmingCharacters(in: .whitespaces)
141                if t.isEmpty || t.hasPrefix("#") || t.hasPrefix("```") || t.hasPrefix(">")
142                    || t.hasPrefix("- ") || t.hasPrefix("* ") || Self.tableStart(lines) != nil {
143                    break
144                }
145                paragraph.append(t)
146                lines = lines.dropFirst()
147            }
148            blocks.append(.paragraph(paragraph.joined(separator: " ")))
149        }
150        return blocks
151    }
152
153    /// A line that wraps the list item above it: anything but a blank line or
154    /// the start of another block, indented or not, as in CommonMark.
155    private static func continuesItem(_ lines: ArraySlice<String>) -> Bool {
156        guard let line = lines.first?.trimmingCharacters(in: .whitespaces), !line.isEmpty
157        else { return false }
158        let startsBlock = line.hasPrefix("#") || line.hasPrefix("```") || line.hasPrefix(">")
159            || line.hasPrefix("- ") || line.hasPrefix("* ") || line.hasPrefix("+ ")
160            || line == "---" || line == "***" || line == "___"
161            || line.range(of: #"^\d+\. "#, options: .regularExpression) != nil
162            || tableStart(lines) != nil
163        return !startsBlock
164    }
165
166    // MARK: - Tables
167
168    /// A table begins where a row of cells is followed by a separator row with the
169    /// same number of cells. Anything else containing a pipe stays a paragraph.
170    private static func tableStart(
171        _ lines: ArraySlice<String>
172    ) -> (header: [String], alignments: [Table.Alignment])? {
173        guard let head = lines.first, head.contains("|"),
174              let separator = lines.dropFirst().first
175        else { return nil }
176        let header = cells(head)
177        let rules = cells(separator)
178        guard header.count == rules.count, !header.isEmpty,
179              rules.allSatisfy({ $0.range(of: #"^:?-+:?$"#, options: .regularExpression) != nil })
180        else { return nil }
181        return (header, rules.map(alignment))
182    }
183
184    private static func alignment(of rule: String) -> Table.Alignment {
185        switch (rule.hasPrefix(":"), rule.hasSuffix(":")) {
186        case (true, true): .center
187        case (false, true): .trailing
188        default: .leading
189        }
190    }
191
192    /// Split a row on its unescaped pipes. The outer pipes are optional in GFM, and
193    /// a `\|` stays escaped so the inline parser turns it into a literal pipe.
194    private static func cells(_ line: String) -> [String] {
195        var row = Substring(line.trimmingCharacters(in: .whitespaces))
196        if row.hasPrefix("|") { row = row.dropFirst() }
197        if row.hasSuffix("|"), !row.hasSuffix("\\|") { row = row.dropLast() }
198
199        var cells: [String] = []
200        var current = ""
201        var escaped = false
202        for character in row {
203            if escaped {
204                current.append(character)
205                escaped = false
206            } else if character == "\\" {
207                current.append(character)
208                escaped = true
209            } else if character == "|" {
210                cells.append(current)
211                current = ""
212            } else {
213                current.append(character)
214            }
215        }
216        cells.append(current)
217        return cells.map { $0.trimmingCharacters(in: .whitespaces) }
218    }
219
220    // MARK: - Rendering
221
222    @ViewBuilder
223    private func blockView(_ block: Block) -> some View {
224        switch block {
225        case .heading(let level, let text):
226            Self.inline(text, codeStyle: headingCodeStyle(level), linkOptions: linkOptions)
227                .font(headingFont(level))
228                .padding(.top, level <= 2 ? 8 : 4)
229        case .code(let code):
230            ScrollView(.horizontal) {
231                Text(code)
232                    .font(.gbMono(.caption))
233                    .padding(10)
234            }
235            .background(Color.gbCodeBackground, in: RoundedRectangle(cornerRadius: 2))
236        case .quote(let text):
237            HStack(spacing: 10) {
238                RoundedRectangle(cornerRadius: 2)
239                    .fill(.tertiary)
240                    .frame(width: 3)
241                Self.inline(text, linkOptions: linkOptions).foregroundStyle(.secondary)
242            }
243            .fixedSize(horizontal: false, vertical: true)
244        case .bullet(let items):
245            VStack(alignment: .leading, spacing: 4) {
246                ForEach(Array(items.enumerated()), id: \.offset) { _, item in
247                    HStack(alignment: .firstTextBaseline, spacing: 8) {
248                        Text("•")
249                        Self.inline(item, linkOptions: linkOptions)
250                            .fixedSize(horizontal: false, vertical: true)
251                    }
252                }
253            }
254        case .ordered(let items):
255            VStack(alignment: .leading, spacing: 4) {
256                ForEach(Array(items.enumerated()), id: \.offset) { index, item in
257                    HStack(alignment: .firstTextBaseline, spacing: 8) {
258                        Text("\(index + 1).").monospacedDigit()
259                        Self.inline(item, linkOptions: linkOptions)
260                            .fixedSize(horizontal: false, vertical: true)
261                    }
262                }
263            }
264        case .table(let table):
265            MarkdownTableView(table: table, linkOptions: linkOptions)
266        case .rule:
267            Divider()
268        case .paragraph(let text):
269            Self.inline(text, linkOptions: linkOptions)
270        }
271    }
272
273    /// Inline code is set explicitly rather than left to the substitution
274    /// AttributedString makes for a custom face, which comes out optically larger
275    /// than the surrounding sans. `codeStyle` is a step below the block's own style,
276    /// the ratio the web uses (`--fs-1` against `--fs-3`).
277    static func inline(
278        _ text: String,
279        codeStyle: Font.TextStyle = .subheadline,
280        linkOptions: OrgRenderOptions? = nil
281    ) -> Text {
282        Text(attributed(text, codeStyle: codeStyle, linkOptions: linkOptions))
283    }
284
285    static func attributed(
286        _ text: String,
287        codeStyle: Font.TextStyle = .subheadline,
288        linkOptions: OrgRenderOptions? = nil
289    ) -> AttributedString {
290        guard var attributed = try? AttributedString(
291            markdown: text,
292            options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace)
293        ) else {
294            return AttributedString(text)
295        }
296        for range in attributed.runs.map(\.range) {
297            if attributed[range].inlinePresentationIntent?.contains(.code) == true {
298                attributed[range].font = .gbMono(codeStyle)
299            }
300            // `[x](ARCHITECTURE.md)` parses to a scheme-less URL that `openURL` cannot open,
301            // so the text renders as a link and the tap does nothing. Resolve through the
302            // same options the org renderer uses, so both formats reach the same file page.
303            if let link = attributed[range].link,
304               let resolved = linkOptions?.resolvedLinkURL(link.absoluteString),
305               let url = URL(string: resolved) {
306                attributed[range].link = url
307            }
308        }
309        return attributed
310    }
311
312    private func headingFont(_ level: Int) -> Font {
313        switch level {
314        case 1: .title2.bold()
315        case 2: .title3.bold()
316        case 3: .headline
317        default: .subheadline.bold()
318        }
319    }
320
321    /// One step below the heading's own size, so code in a heading tracks it.
322    private func headingCodeStyle(_ level: Int) -> Font.TextStyle {
323        switch level {
324        case 1: .title3
325        case 2: .headline
326        case 3: .subheadline
327        default: .footnote
328        }
329    }
330}
331
332/// A table, in a `Grid` that scrolls sideways when it is wider than the screen.
333///
334/// A multi-column table is laid out two columns to a screen, so long prose wraps
335/// inside its cell instead of running off the edge and wider tables scroll. A cell
336/// needs a width proposed to it, not a cap: with only a cap it reports the height of
337/// a single line and rows overlap.
338private struct MarkdownTableView: View {
339    let table: MarkdownView.Table
340    var linkOptions: OrgRenderOptions?
341
342    private static let spacing: CGFloat = 14
343
344    @State private var containerWidth: CGFloat = 0
345
346    private var cellWidth: CGFloat? {
347        guard containerWidth > 0, table.columnCount > 1 else { return nil }
348        return (containerWidth - Self.spacing) / 2
349    }
350
351    var body: some View {
352        ScrollView(.horizontal, showsIndicators: false) {
353            Grid(alignment: .topLeading, horizontalSpacing: Self.spacing, verticalSpacing: 7) {
354                GridRow {
355                    ForEach(Array(table.header.enumerated()), id: \.offset) { column, text in
356                        cell(text, column).bold()
357                    }
358                }
359                Divider().gridCellColumns(table.columnCount)
360                ForEach(Array(table.rows.enumerated()), id: \.offset) { _, row in
361                    GridRow {
362                        ForEach(Array(row.enumerated()), id: \.offset) { column, text in
363                            cell(text, column)
364                        }
365                    }
366                }
367            }
368            .padding(.vertical, 2)
369        }
370        .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { containerWidth = $0 }
371    }
372
373    private func cell(_ text: String, _ column: Int) -> some View {
374        let alignment = table.alignments[column]
375        return MarkdownView.inline(text, linkOptions: linkOptions)
376            .multilineTextAlignment(Self.textAlignment(alignment))
377            .frame(width: cellWidth, alignment: Self.frameAlignment(alignment))
378            .fixedSize(horizontal: cellWidth == nil, vertical: true)
379            .gridColumnAlignment(Self.gridAlignment(alignment))
380    }
381
382    private static func gridAlignment(_ alignment: MarkdownView.Table.Alignment) -> HorizontalAlignment {
383        switch alignment {
384        case .leading: .leading
385        case .center: .center
386        case .trailing: .trailing
387        }
388    }
389
390    private static func frameAlignment(_ alignment: MarkdownView.Table.Alignment) -> Alignment {
391        switch alignment {
392        case .leading: .leading
393        case .center: .center
394        case .trailing: .trailing
395        }
396    }
397
398    private static func textAlignment(_ alignment: MarkdownView.Table.Alignment) -> TextAlignment {
399        switch alignment {
400        case .leading: .leading
401        case .center: .center
402        case .trailing: .trailing
403        }
404    }
405}