import OrgSwift import SwiftUI /// Block-level markdown for READMEs: headings, fenced code, lists, quotes, /// tables, paragraphs. Inline styling comes from AttributedString's own markdown /// parsing; blocks are split here because it only does inline. struct MarkdownView: View { let markdown: String /// Repository context for resolving relative link targets. Nil leaves them as authored, /// which is right for a body with no file to be relative to. var linkOptions: OrgRenderOptions? var body: some View { VStack(alignment: .leading, spacing: 12) { ForEach(Array(blocks.enumerated()), id: \.offset) { _, block in blockView(block) } } } // MARK: - Block model enum Block: Equatable { case heading(level: Int, text: String) case code(String) case quote(String) case bullet([String]) case ordered([String]) case table(Table) case rule case paragraph(String) } /// A GitHub-flavored table: a header row, a body, and one alignment per /// column taken from the `|:---:|` separator row. struct Table: Equatable { var header: [String] var rows: [[String]] var alignments: [Alignment] enum Alignment: Equatable { case leading, center, trailing } var columnCount: Int { header.count } } var blocks: [Block] { var blocks: [Block] = [] var lines = markdown.components(separatedBy: "\n")[...] while let line = lines.first { let trimmed = line.trimmingCharacters(in: .whitespaces) if trimmed.hasPrefix("```") { lines = lines.dropFirst() var code: [String] = [] while let next = lines.first, !next.trimmingCharacters(in: .whitespaces).hasPrefix("```") { code.append(next) lines = lines.dropFirst() } lines = lines.dropFirst() // closing fence blocks.append(.code(code.joined(separator: "\n"))) continue } if trimmed.hasPrefix("#") { let level = trimmed.prefix(while: { $0 == "#" }).count let text = trimmed.drop(while: { $0 == "#" }).trimmingCharacters(in: .whitespaces) blocks.append(.heading(level: min(level, 4), text: text)) lines = lines.dropFirst() continue } if trimmed == "---" || trimmed == "***" || trimmed == "___" { blocks.append(.rule) lines = lines.dropFirst() continue } if trimmed.hasPrefix(">") { var quote: [String] = [] while let next = lines.first?.trimmingCharacters(in: .whitespaces), next.hasPrefix(">") { quote.append(next.dropFirst().trimmingCharacters(in: .whitespaces)) lines = lines.dropFirst() } blocks.append(.quote(quote.joined(separator: " "))) continue } if trimmed.hasPrefix("- ") || trimmed.hasPrefix("* ") || trimmed.hasPrefix("+ ") { var items: [String] = [] while let next = lines.first?.trimmingCharacters(in: .whitespaces) { if next.hasPrefix("- ") || next.hasPrefix("* ") || next.hasPrefix("+ ") { items.append(String(next.dropFirst(2))) } else if Self.continuesItem(lines) { items[items.count - 1] += " " + next } else { break } lines = lines.dropFirst() } blocks.append(.bullet(items)) continue } if trimmed.range(of: #"^\d+\. "#, options: .regularExpression) != nil { var items: [String] = [] while let next = lines.first?.trimmingCharacters(in: .whitespaces) { if let range = next.range(of: #"^\d+\. "#, options: .regularExpression) { items.append(String(next[range.upperBound...])) } else if Self.continuesItem(lines) { items[items.count - 1] += " " + next } else { break } lines = lines.dropFirst() } blocks.append(.ordered(items)) continue } if let table = Self.tableStart(lines) { lines = lines.dropFirst(2) // header and separator var rows: [[String]] = [] while let next = lines.first, next.contains("|") { var cells = Self.cells(next) // Ragged rows are padded, not dropped, so a short row leaves // blanks rather than shifting the grid. cells += Array(repeating: "", count: max(0, table.header.count - cells.count)) rows.append(Array(cells.prefix(table.header.count))) lines = lines.dropFirst() } blocks.append(.table(Table( header: table.header, rows: rows, alignments: table.alignments ))) continue } if trimmed.isEmpty { lines = lines.dropFirst() continue } // Paragraph: consume until a blank line or another block start. var paragraph: [String] = [] while let next = lines.first { let t = next.trimmingCharacters(in: .whitespaces) if t.isEmpty || t.hasPrefix("#") || t.hasPrefix("```") || t.hasPrefix(">") || t.hasPrefix("- ") || t.hasPrefix("* ") || Self.tableStart(lines) != nil { break } paragraph.append(t) lines = lines.dropFirst() } blocks.append(.paragraph(paragraph.joined(separator: " "))) } return blocks } /// A line that wraps the list item above it: anything but a blank line or /// the start of another block, indented or not, as in CommonMark. private static func continuesItem(_ lines: ArraySlice) -> Bool { guard let line = lines.first?.trimmingCharacters(in: .whitespaces), !line.isEmpty else { return false } let startsBlock = line.hasPrefix("#") || line.hasPrefix("```") || line.hasPrefix(">") || line.hasPrefix("- ") || line.hasPrefix("* ") || line.hasPrefix("+ ") || line == "---" || line == "***" || line == "___" || line.range(of: #"^\d+\. "#, options: .regularExpression) != nil || tableStart(lines) != nil return !startsBlock } // MARK: - Tables /// A table begins where a row of cells is followed by a separator row with the /// same number of cells. Anything else containing a pipe stays a paragraph. private static func tableStart( _ lines: ArraySlice ) -> (header: [String], alignments: [Table.Alignment])? { guard let head = lines.first, head.contains("|"), let separator = lines.dropFirst().first else { return nil } let header = cells(head) let rules = cells(separator) guard header.count == rules.count, !header.isEmpty, rules.allSatisfy({ $0.range(of: #"^:?-+:?$"#, options: .regularExpression) != nil }) else { return nil } return (header, rules.map(alignment)) } private static func alignment(of rule: String) -> Table.Alignment { switch (rule.hasPrefix(":"), rule.hasSuffix(":")) { case (true, true): .center case (false, true): .trailing default: .leading } } /// Split a row on its unescaped pipes. The outer pipes are optional in GFM, and /// a `\|` stays escaped so the inline parser turns it into a literal pipe. private static func cells(_ line: String) -> [String] { var row = Substring(line.trimmingCharacters(in: .whitespaces)) if row.hasPrefix("|") { row = row.dropFirst() } if row.hasSuffix("|"), !row.hasSuffix("\\|") { row = row.dropLast() } var cells: [String] = [] var current = "" var escaped = false for character in row { if escaped { current.append(character) escaped = false } else if character == "\\" { current.append(character) escaped = true } else if character == "|" { cells.append(current) current = "" } else { current.append(character) } } cells.append(current) return cells.map { $0.trimmingCharacters(in: .whitespaces) } } // MARK: - Rendering @ViewBuilder private func blockView(_ block: Block) -> some View { switch block { case .heading(let level, let text): Self.inline(text, codeStyle: headingCodeStyle(level), linkOptions: linkOptions) .font(headingFont(level)) .padding(.top, level <= 2 ? 8 : 4) case .code(let code): ScrollView(.horizontal) { Text(code) .font(.gbMono(.caption)) .padding(10) } .background(Color.gbCodeBackground, in: RoundedRectangle(cornerRadius: 2)) case .quote(let text): HStack(spacing: 10) { RoundedRectangle(cornerRadius: 2) .fill(.tertiary) .frame(width: 3) Self.inline(text, linkOptions: linkOptions).foregroundStyle(.secondary) } .fixedSize(horizontal: false, vertical: true) case .bullet(let items): VStack(alignment: .leading, spacing: 4) { ForEach(Array(items.enumerated()), id: \.offset) { _, item in HStack(alignment: .firstTextBaseline, spacing: 8) { Text("•") Self.inline(item, linkOptions: linkOptions) .fixedSize(horizontal: false, vertical: true) } } } case .ordered(let items): VStack(alignment: .leading, spacing: 4) { ForEach(Array(items.enumerated()), id: \.offset) { index, item in HStack(alignment: .firstTextBaseline, spacing: 8) { Text("\(index + 1).").monospacedDigit() Self.inline(item, linkOptions: linkOptions) .fixedSize(horizontal: false, vertical: true) } } } case .table(let table): MarkdownTableView(table: table, linkOptions: linkOptions) case .rule: Divider() case .paragraph(let text): Self.inline(text, linkOptions: linkOptions) } } /// Inline code is set explicitly rather than left to the substitution /// AttributedString makes for a custom face, which comes out optically larger /// than the surrounding sans. `codeStyle` is a step below the block's own style, /// the ratio the web uses (`--fs-1` against `--fs-3`). static func inline( _ text: String, codeStyle: Font.TextStyle = .subheadline, linkOptions: OrgRenderOptions? = nil ) -> Text { Text(attributed(text, codeStyle: codeStyle, linkOptions: linkOptions)) } static func attributed( _ text: String, codeStyle: Font.TextStyle = .subheadline, linkOptions: OrgRenderOptions? = nil ) -> AttributedString { guard var attributed = try? AttributedString( markdown: text, options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace) ) else { return AttributedString(text) } for range in attributed.runs.map(\.range) { if attributed[range].inlinePresentationIntent?.contains(.code) == true { attributed[range].font = .gbMono(codeStyle) } // `[x](ARCHITECTURE.md)` parses to a scheme-less URL that `openURL` cannot open, // so the text renders as a link and the tap does nothing. Resolve through the // same options the org renderer uses, so both formats reach the same file page. if let link = attributed[range].link, let resolved = linkOptions?.resolvedLinkURL(link.absoluteString), let url = URL(string: resolved) { attributed[range].link = url } } return attributed } private func headingFont(_ level: Int) -> Font { switch level { case 1: .title2.bold() case 2: .title3.bold() case 3: .headline default: .subheadline.bold() } } /// One step below the heading's own size, so code in a heading tracks it. private func headingCodeStyle(_ level: Int) -> Font.TextStyle { switch level { case 1: .title3 case 2: .headline case 3: .subheadline default: .footnote } } } /// A table, in a `Grid` that scrolls sideways when it is wider than the screen. /// /// A multi-column table is laid out two columns to a screen, so long prose wraps /// inside its cell instead of running off the edge and wider tables scroll. A cell /// needs a width proposed to it, not a cap: with only a cap it reports the height of /// a single line and rows overlap. private struct MarkdownTableView: View { let table: MarkdownView.Table var linkOptions: OrgRenderOptions? private static let spacing: CGFloat = 14 @State private var containerWidth: CGFloat = 0 private var cellWidth: CGFloat? { guard containerWidth > 0, table.columnCount > 1 else { return nil } return (containerWidth - Self.spacing) / 2 } var body: some View { ScrollView(.horizontal, showsIndicators: false) { Grid(alignment: .topLeading, horizontalSpacing: Self.spacing, verticalSpacing: 7) { GridRow { ForEach(Array(table.header.enumerated()), id: \.offset) { column, text in cell(text, column).bold() } } Divider().gridCellColumns(table.columnCount) ForEach(Array(table.rows.enumerated()), id: \.offset) { _, row in GridRow { ForEach(Array(row.enumerated()), id: \.offset) { column, text in cell(text, column) } } } } .padding(.vertical, 2) } .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { containerWidth = $0 } } private func cell(_ text: String, _ column: Int) -> some View { let alignment = table.alignments[column] return MarkdownView.inline(text, linkOptions: linkOptions) .multilineTextAlignment(Self.textAlignment(alignment)) .frame(width: cellWidth, alignment: Self.frameAlignment(alignment)) .fixedSize(horizontal: cellWidth == nil, vertical: true) .gridColumnAlignment(Self.gridAlignment(alignment)) } private static func gridAlignment(_ alignment: MarkdownView.Table.Alignment) -> HorizontalAlignment { switch alignment { case .leading: .leading case .center: .center case .trailing: .trailing } } private static func frameAlignment(_ alignment: MarkdownView.Table.Alignment) -> Alignment { switch alignment { case .leading: .leading case .center: .center case .trailing: .trailing } } private static func textAlignment(_ alignment: MarkdownView.Table.Alignment) -> TextAlignment { switch alignment { case .leading: .leading case .center: .center case .trailing: .trailing } } }