Repository Public
1// ORIX DJ2// File: App/Sources/Features/Docs/MarkdownView.swift3// Description: Native SwiftUI renderer for parsed Markdown: headings, paragraphs, lists, quotes, rules, wide tables4// with horizontal scrolling and fenced code blocks. Text is selectable and scales with the reader's zoom.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import ORIXDJCore9import SwiftUI1011struct MarkdownStyle: Equatable {12 /// Chapter the text belongs to, for relative links; nil outside the documentation.13 var file: String?14 var scale: CGFloat = 115 var markedNode: Int?16 /// Code-block actions that need the app model (Open in Editor, Run in Simulator).17 var scriptActions = true1819 static let linkScheme = "orixdoc"2021 func url(for destination: String) -> URL? {22 if DocsStore.isExternal(destination) { return URL(string: destination) }23 guard let file else { return nil }24 let target = DocsStore.resolve(destination, from: file)25 var c = URLComponents()26 c.scheme = Self.linkScheme; c.host = "chapter"; c.path = "/" + target.file27 if let a = target.anchor, !a.isEmpty { c.fragment = a }28 return c.url29 }3031 func attributed(_ inlines: [MDInline], size: CGFloat, weight: Font.Weight = .regular, color: Color = ORIX.Palette.textPrimary) -> AttributedString {32 var out = AttributedString()33 func walk(_ list: [MDInline], bold: Bool, italic: Bool, link: URL?) {34 for i in list {35 switch i {36 case let .text(s):37 var a = AttributedString(s)38 var f = Font.system(size: size * scale, weight: bold ? .semibold : weight)39 if italic { f = f.italic() }40 a.font = f41 a.foregroundColor = link == nil ? color : ORIX.Palette.accent42 if let link { a.link = link; a.underlineStyle = .single }43 out.append(a)44 case let .code(s):45 var a = AttributedString(s)46 a.font = .system(size: (size - 0.5) * scale, weight: bold ? .semibold : .regular, design: .monospaced)47 a.foregroundColor = link == nil ? ORIX.Palette.textPrimary : ORIX.Palette.accent48 a.backgroundColor = ORIX.Palette.surfaceRaised49 if let link { a.link = link; a.underlineStyle = .single }50 out.append(a)51 case let .strong(c): walk(c, bold: true, italic: italic, link: link)52 case let .emphasis(c): walk(c, bold: bold, italic: true, link: link)53 case let .link(c, destination): walk(c, bold: bold, italic: italic, link: url(for: destination) ?? link)54 case .lineBreak: out.append(AttributedString("\n"))55 }56 }57 }58 walk(inlines, bold: false, italic: false, link: nil)59 return out60 }61}6263/// A list of blocks, stacked.64struct MarkdownBlocks: View {65 var nodes: [MDNode]66 var style: MarkdownStyle67 var spacing: CGFloat = 126869 var body: some View {70 VStack(alignment: .leading, spacing: spacing * style.scale) {71 ForEach(nodes) { node in MarkdownNodeView(node: node, style: style) }72 }73 .frame(maxWidth: .infinity, alignment: .leading)74 }75}7677struct MarkdownNodeView: View {78 var node: MDNode79 var style: MarkdownStyle8081 var body: some View {82 content83 .padding(.leading, style.markedNode == node.id ? 10 : 0)84 .overlay(alignment: .leading) {85 if style.markedNode == node.id {86 RoundedRectangle(cornerRadius: 1.5).fill(ORIX.Palette.accent).frame(width: 3)87 .accessibilityLabel("Search match")88 }89 }90 }9192 @ViewBuilder private var content: some View {93 switch node.block {94 case let .heading(level, text, _):95 let sizes: [CGFloat] = [24, 18, 15, 13]96 let size = sizes[min(max(level, 1), 4) - 1]97 VStack(alignment: .leading, spacing: 6 * style.scale) {98 Text(style.attributed(text, size: size, weight: level == 1 ? .bold : .semibold))99 .textSelection(.enabled)100 .fixedSize(horizontal: false, vertical: true)101 .accessibilityAddTraits(.isHeader)102 if level <= 2 { Rectangle().fill(ORIX.Palette.hairline).frame(height: 1) }103 }104 .padding(.top, (level == 1 ? 4 : (level == 2 ? 12 : 6)) * style.scale)105 case let .paragraph(text):106 Text(style.attributed(text, size: 13.5, color: ORIX.Palette.textPrimary))107 .lineSpacing(3.5 * style.scale)108 .textSelection(.enabled)109 .fixedSize(horizontal: false, vertical: true)110 .frame(maxWidth: 820 * style.scale, alignment: .leading)111 case let .code(language, text):112 DocsCodeBlock(language: language, source: text, style: style)113 case let .quote(children):114 HStack(alignment: .top, spacing: 10) {115 RoundedRectangle(cornerRadius: 1.5).fill(ORIX.Palette.accentSecondary).frame(width: 3)116 MarkdownBlocks(nodes: children, style: style, spacing: 8)117 }118 .padding(.vertical, 8).padding(.horizontal, 10)119 .background(ORIX.Palette.surfaceRaised.opacity(0.6), in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))120 .fixedSize(horizontal: false, vertical: true)121 case let .list(ordered, items):122 VStack(alignment: .leading, spacing: 6 * style.scale) {123 ForEach(Array(items.enumerated()), id: \.offset) { _, item in124 HStack(alignment: .firstTextBaseline, spacing: 8) {125 Text(verbatim: ordered ? item.marker : "•")126 .font(.system(size: 13.5 * style.scale, weight: ordered ? .medium : .bold).monospacedDigit())127 .foregroundStyle(ORIX.Palette.textSecondary)128 .frame(minWidth: (ordered ? 22 : 12) * style.scale, alignment: .trailing)129 .accessibilityHidden(!ordered)130 MarkdownBlocks(nodes: item.nodes, style: style, spacing: 6)131 }132 }133 }134 .padding(.leading, 4)135 case let .table(header, alignments, rows):136 MarkdownTable(header: header, alignments: alignments, rows: rows, style: style)137 case .rule:138 Rectangle().fill(ORIX.Palette.hairline).frame(height: 1).padding(.vertical, 6 * style.scale)139 .accessibilityHidden(true)140 }141 }142}143144/// A table with a header row and aligned columns. Wide tables scroll horizontally instead of squeezing their text.145struct MarkdownTable: View {146 var header: [[MDInline]]147 var alignments: [MDAlignment]148 var rows: [[[MDInline]]]149 var style: MarkdownStyle150151 private func width(_ column: Int) -> CGFloat {152 var longest = header[column].map(\.plain).joined().count + 2153 var hasCode = false154 for r in rows where column < r.count {155 let cell = r[column]156 longest = max(longest, cell.map(\.plain).joined().count)157 if case .code = cell.first { hasCode = true }158 }159 let perCharacter: CGFloat = hasCode ? 7.4 : 6.6160 return min(max(CGFloat(longest) * perCharacter + 22, 64), 380) * style.scale161 }162163 private func alignment(_ column: Int) -> Alignment {164 switch column < alignments.count ? alignments[column] : .leading {165 case .leading: .topLeading166 case .center: .top167 case .trailing: .topTrailing168 }169 }170171 private func textAlignment(_ column: Int) -> TextAlignment {172 switch column < alignments.count ? alignments[column] : .leading {173 case .leading: .leading174 case .center: .center175 case .trailing: .trailing176 }177 }178179 var body: some View {180 let widths = header.indices.map(width)181 ScrollView(.horizontal, showsIndicators: true) {182 Grid(alignment: .topLeading, horizontalSpacing: 0, verticalSpacing: 0) {183 GridRow {184 ForEach(header.indices, id: \.self) { c in185 Text(style.attributed(header[c], size: 11.5, weight: .semibold, color: ORIX.Palette.textSecondary))186 .multilineTextAlignment(textAlignment(c))187 .textSelection(.enabled)188 .padding(.horizontal, 10).padding(.vertical, 7)189 .frame(width: widths[c], alignment: alignment(c))190 }191 }192 .background(ORIX.Palette.surfaceRaised)193 ForEach(rows.indices, id: \.self) { r in194 Rectangle().fill(ORIX.Palette.hairline).frame(height: 1).gridCellColumns(max(1, header.count)).gridCellUnsizedAxes(.horizontal)195 GridRow {196 ForEach(header.indices, id: \.self) { c in197 Text(style.attributed(c < rows[r].count ? rows[r][c] : [], size: 12.5))198 .multilineTextAlignment(textAlignment(c))199 .lineSpacing(2)200 .textSelection(.enabled)201 .fixedSize(horizontal: false, vertical: true)202 .padding(.horizontal, 10).padding(.vertical, 6)203 .frame(width: widths[c], alignment: alignment(c))204 }205 }206 }207 }208 .background(ORIX.Palette.surface)209 .clipShape(RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))210 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous).strokeBorder(ORIX.Palette.hairline, lineWidth: 1))211 .padding(.bottom, 10)212 }213 .accessibilityElement(children: .contain)214 .accessibilityLabel(Text("Table, \(header.count) columns, \(rows.count) rows"))215 }216}217