Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Components/MarkdownRenderer.swift4// Description: SwiftUI rendering of parsed Markdown: text with inline math, lists, quotes, adaptive tables, code, equations.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//910import SwiftUI11import UIKit1213/// Renders Markdown natively. Blocks are identified by position, so while an answer streams SwiftUI only re-evaluates14/// the last block; everything above it is served from `RenderCache`.15struct MarkdownView: View {16 let text: String1718 var body: some View {19 MarkdownBlocksView(blocks: RenderCache.shared.markdown(text))20 }21}2223struct MarkdownBlocksView: View {24 let blocks: [MarkdownBlock]25 var spacing: CGFloat = 122627 var body: some View {28 VStack(alignment: .leading, spacing: spacing) {29 ForEach(Array(blocks.enumerated()), id: \.offset) { _, block in30 MarkdownBlockView(block: block)31 }32 }33 .frame(maxWidth: .infinity, alignment: .leading)34 }35}3637struct MarkdownBlockView: View {38 let block: MarkdownBlock3940 var body: some View {41 switch block {42 case .heading(let level, let text):43 InlineText(source: text)44 .font(headingFont(level))45 .fontWeight(level <= 2 ? .bold : .semibold)46 .padding(.top, level <= 2 ? 6 : 2)47 .accessibilityAddTraits(.isHeader)48 case .paragraph(let text):49 InlineText(source: text).font(.body).lineSpacing(3)50 case .code(let language, let code, let closed):51 CodeBlockView(language: language, code: code, closed: closed)52 case .quote(let inner):53 HStack(alignment: .top, spacing: 12) {54 RoundedRectangle(cornerRadius: 1.5).fill(Color.accentColor.opacity(0.55)).frame(width: 3)55 MarkdownBlocksView(blocks: inner, spacing: 8).foregroundStyle(Color("TextSecondary"))56 }57 .fixedSize(horizontal: false, vertical: true)58 case .list(let ordered, let start, let items):59 MarkdownListView(ordered: ordered, start: start, items: items)60 case .table(let header, let alignments, let rows):61 MarkdownTableView(header: header, alignments: alignments, rows: rows)62 case .math(let latex):63 MathBlockView(latex: latex)64 case .rule:65 Rectangle().fill(Color("Border")).frame(height: 1).padding(.vertical, 4)66 }67 }6869 private func headingFont(_ level: Int) -> Font {70 switch level { case 1: .title2; case 2: .title3; case 3: .headline; default: .subheadline }71 }72}7374struct MarkdownListView: View {75 let ordered: Bool76 let start: Int77 let items: [MarkdownListItem]7879 var body: some View {80 VStack(alignment: .leading, spacing: 7) {81 ForEach(Array(items.enumerated()), id: \.offset) { index, item in82 HStack(alignment: .firstTextBaseline, spacing: 8) {83 marker(index: index, item: item)84 MarkdownBlocksView(blocks: item.blocks, spacing: 7)85 }86 .accessibilityElement(children: .combine)87 }88 }89 }9091 @ViewBuilder private func marker(index: Int, item: MarkdownListItem) -> some View {92 if let checked = item.checked {93 Image(systemName: checked ? "checkmark.square.fill" : "square")94 .foregroundStyle(checked ? Color.accentColor : Color("Muted"))95 .accessibilityLabel(checked ? String(localized: "Fait") : String(localized: "À faire"))96 } else if ordered {97 Text("\(start + index).").font(.body.monospacedDigit()).foregroundStyle(Color("TextSecondary")).frame(minWidth: 22, alignment: .trailing)98 } else {99 Text("•").font(.body.weight(.bold)).foregroundStyle(Color("Muted")).frame(minWidth: 14, alignment: .center)100 }101 }102}103104/// A table that keeps its natural column widths and scrolls sideways on its own when wider than the screen —105/// the page itself never scrolls horizontally.106struct MarkdownTableView: View {107 let header: [String]108 let alignments: [ColumnAlignment]109 let rows: [[String]]110111 var body: some View {112 ScrollView(.horizontal, showsIndicators: false) {113 Grid(alignment: .leading, horizontalSpacing: 0, verticalSpacing: 0) {114 GridRow {115 ForEach(Array(header.enumerated()), id: \.offset) { i, cell in116 self.cell(cell, column: i).fontWeight(.semibold)117 }118 }119 .background(Color("Surface2"))120 ForEach(Array(rows.enumerated()), id: \.offset) { r, row in121 Rectangle().fill(Color("Border")).frame(height: 1).gridCellColumns(max(header.count, 1)).gridCellUnsizedAxes(.horizontal)122 GridRow {123 ForEach(Array(row.enumerated()), id: \.offset) { i, cell in self.cell(cell, column: i) }124 }125 .background(r % 2 == 1 ? Color("Surface2").opacity(0.45) : Color.clear)126 }127 }128 .clipShape(.rect(cornerRadius: 10, style: .continuous))129 .overlay(RoundedRectangle(cornerRadius: 10, style: .continuous).strokeBorder(Color("Border")))130 }131 .scrollBounceBehavior(.basedOnSize, axes: .horizontal)132 .accessibilityElement(children: .contain)133 .accessibilityLabel(String(localized: "Tableau, \(rows.count) lignes, \(header.count) colonnes"))134 }135136 private func cell(_ text: String, column: Int) -> some View {137 let alignment: Alignment = column < alignments.count ? (alignments[column] == .center ? .center : alignments[column] == .trailing ? .trailing : .leading) : .leading138 return InlineText(source: text)139 .font(.callout)140 .multilineTextAlignment(alignment == .center ? .center : alignment == .trailing ? .trailing : .leading)141 .frame(minWidth: 44, maxWidth: 280, alignment: alignment)142 .fixedSize(horizontal: false, vertical: true)143 .padding(.horizontal, 12).padding(.vertical, 9)144 .gridColumnAlignment(alignment == .center ? .center : alignment == .trailing ? .trailing : .leading)145 }146}147148/// One run of inline Markdown (emphasis, code, links, strikethrough) with inline math typeset in place.149struct InlineText: View {150 let source: String151 @ScaledMetric(relativeTo: .body) private var mathSize: CGFloat = 17152153 var body: some View {154 let segments = InlineMath.split(source)155 Group {156 if segments.count == 1, case .text(let t) = segments[0] {157 Text(RenderCache.shared.inline(t, accent: .accentColor))158 } else {159 segments.reduce(Text("")) { acc, seg in160 switch seg {161 case .text(let t): return Text("\(acc)\(Text(RenderCache.shared.inline(t, accent: .accentColor)))")162 case .math(let latex):163 if let r = MathRenderer.render(latex, fontSize: mathSize, display: false) {164 return Text("\(acc)\(Text(Image(uiImage: r.image)).baselineOffset(-r.descent))")165 }166 return Text("\(acc)\(Text(latex).font(.system(.body, design: .monospaced)))")167 }168 }169 }170 }171 .tint(.accentColor)172 .frame(maxWidth: .infinity, alignment: .leading)173 .fixedSize(horizontal: false, vertical: true)174 }175}176177enum InlineMarkdown {178 /// Foundation's CommonMark parser for the inline level only; inline code gets a monospaced face and a soft background.179 static func attributed(_ source: String, accent: Color) -> AttributedString {180 let options = AttributedString.MarkdownParsingOptions(allowsExtendedAttributes: false, interpretedSyntax: .inlineOnlyPreservingWhitespace, failurePolicy: .returnPartiallyParsedIfPossible)181 guard var a = try? AttributedString(markdown: source, options: options) else { return AttributedString(source) }182 for run in a.runs {183 if let intent = run.inlinePresentationIntent, intent.contains(.code) {184 a[run.range].font = .system(.callout, design: .monospaced)185 a[run.range].backgroundColor = Color("Surface2")186 }187 if run.link != nil {188 a[run.range].foregroundColor = accent189 a[run.range].underlineStyle = .single190 }191 }192 return a193 }194}195