SPB Git

Repository Public

MarkdownView.swift 13.9 KB 281 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Components/MarkdownView.swift3// Description: Native rendering of assistant Markdown: paragraphs with inline math, headings, lists, quotes, tables, highlighted code blocks. No web view.4import SwiftUI5import SPChatCore67/// Renders a message body. The text is parsed in independent chunks; while it streams only the last chunk changes, and8/// SwiftUI skips every chunk whose source is unchanged (`Equatable`).9struct MarkdownView: View {10    let text: String11    var body: some View {12        let chunks = MarkdownParser.shared.chunks(text)13        VStack(alignment: .leading, spacing: 10) {14            ForEach(chunks) { chunk in ChunkView(chunk: chunk).equatable() }15        }16        .frame(maxWidth: .infinity, alignment: .leading)17    }18}1920struct ChunkView: View, Equatable {21    let chunk: MDChunk22    nonisolated static func == (a: ChunkView, b: ChunkView) -> Bool { a.chunk.source == b.chunk.source }23    var body: some View { BlockList(blocks: chunk.blocks) }24}2526struct BlockList: View {27    let blocks: [MDBlock]28    var spacing: CGFloat = 1029    var body: some View {30        VStack(alignment: .leading, spacing: spacing) {31            ForEach(Array(blocks.enumerated()), id: \.offset) { _, block in BlockView(block: block) }32        }33    }34}3536struct BlockView: View {37    let block: MDBlock38    @Environment(\.transcriptFontSize) private var size3940    var body: some View {41        switch block {42        case .paragraph(let inlines):43            InlineText(inlines: inlines, size: size)44        case .heading(let level, let inlines):45            InlineText(inlines: inlines, size: size * [1.45, 1.28, 1.14, 1.05, 1.0, 1.0][min(max(level, 1), 6) - 1], weight: .semibold)46                .padding(.top, level <= 2 ? 6 : 2).accessibilityAddTraits(.isHeader)47        case .code(let language, let text):48            CodeBlockView(language: language, code: text)49        case .quote(let blocks):50            HStack(alignment: .top, spacing: 10) {51                RoundedRectangle(cornerRadius: 1.5).fill(Palette.iris.opacity(0.55)).frame(width: 3)52                BlockList(blocks: blocks, spacing: 8).foregroundStyle(.secondary)53            }54            .fixedSize(horizontal: false, vertical: true)55        case .list(let ordered, let start, let items):56            VStack(alignment: .leading, spacing: 5) {57                ForEach(Array(items.enumerated()), id: \.offset) { n, item in58                    HStack(alignment: .firstTextBaseline, spacing: 7) {59                        marker(ordered: ordered, number: start + n, checkbox: item.checkbox)60                        BlockList(blocks: item.blocks, spacing: 6)61                    }62                }63            }64            .padding(.leading, 4)65        case .table(let table):66            TableBlockView(table: table)67        case .rule:68            Divider().padding(.vertical, 4)69        case .math(let tex):70            MathBlockView(tex: tex)71        case .html(let raw):72            Text(raw).font(.system(size: size * 0.9, design: .monospaced)).foregroundStyle(.secondary).textSelection(.enabled)73        }74    }7576    @ViewBuilder private func marker(ordered: Bool, number: Int, checkbox: Bool?) -> some View {77        if let checkbox {78            Image(systemName: checkbox ? "checkmark.square.fill" : "square").foregroundStyle(checkbox ? Palette.iris : .secondary).font(.system(size: size * 0.95))79                .accessibilityLabel(checkbox ? "Fait" : "À faire")80        } else if ordered {81            Text("\(number).").font(.system(size: size).monospacedDigit()).foregroundStyle(.secondary).frame(minWidth: size * 1.4, alignment: .trailing)82        } else {83            Text("•").font(.system(size: size)).foregroundStyle(.secondary).frame(width: size * 0.9)84        }85    }86}8788// MARK: - Inline text8990struct InlineText: View {91    let inlines: [MDInline]92    let size: CGFloat93    var weight: Font.Weight = .regular94    @Environment(\.openURL) private var openURL9596    var body: some View {97        InlineBuilder(size: size, weight: weight).text(inlines)98            .lineSpacing(size * 0.28)99            .textSelection(.enabled)100            .fixedSize(horizontal: false, vertical: true)101            .frame(maxWidth: .infinity, alignment: .leading)102            .environment(\.openURL, OpenURLAction { url in103                // only http(s) and mailto links leave the app; anything else found in model output is ignored104                guard LinkPolicy.safeURL(url.absoluteString) != nil else { return .discarded }105                return .systemAction106            })107    }108}109110/// Builds one `Text` from inline nodes: attributed runs for styled text, template images for inline math.111struct InlineBuilder {112    let size: CGFloat113    var weight: Font.Weight = .regular114115    struct Style { var bold = false; var italic = false; var strike = false; var link: URL? }116117    func text(_ inlines: [MDInline]) -> Text {118        var pieces: [Text] = []; var run = AttributedString()119        func flush() { if !run.characters.isEmpty { pieces.append(Text(run)); run = AttributedString() } }120        func walk(_ nodes: [MDInline], _ style: Style) {121            for node in nodes {122                switch node {123                case .text(let s): run += styled(s, style)124                case .softBreak: run += styled(" ", style)125                case .lineBreak: run += styled("\n", style)126                case .emphasis(let c): var s = style; s.italic = true; walk(c, s)127                case .strong(let c): var s = style; s.bold = true; walk(c, s)128                case .strikethrough(let c): var s = style; s.strike = true; walk(c, s)129                case .code(let code):130                    var a = AttributedString(code)131                    a.font = .system(size: size * 0.92, design: .monospaced)132                    a.backgroundColor = Color.primary.opacity(0.07)133                    if let l = style.link { a.link = l }134                    run += a135                case .link(let destination, let children):136                    var s = style; s.link = LinkPolicy.safeURL(destination)137                    walk(children.isEmpty ? [.text(destination)] : children, s)138                    if s.link == nil, !destination.isEmpty { run += styled(" (\(destination))", style) } // unsafe target: shown, not clickable139                case .image(let source, let alt):140                    // remote images are never fetched automatically (privacy): the link is offered instead141                    var s = style; s.link = LinkPolicy.safeURL(source)142                    run += styled("🖼 " + (alt.isEmpty ? source : alt), s)143                case .math(let tex, let display):144                    if let m = MathRenderer.render(tex, fontSize: size * (display ? 1.1 : 1.0), display: false) {145                        flush()146                        pieces.append(Text(Image(nsImage: m.image).renderingMode(.template)).baselineOffset(-m.descent).accessibilityLabel(Text("formule \(tex)")))147                    } else {148                        var a = AttributedString(tex); a.font = .system(size: size * 0.92, design: .monospaced); a.foregroundColor = .secondary; run += a149                    }150                }151            }152        }153        walk(inlines, Style()); flush()154        return pieces.reduce(Text("")) { Text("\($0)\($1)") }155    }156157    private func styled(_ s: String, _ style: Style) -> AttributedString {158        var a = AttributedString(s)159        var font = Font.system(size: size, weight: style.bold ? .semibold : weight)160        if style.italic { font = font.italic() }161        a.font = font162        if style.strike { a.strikethroughStyle = .single }163        if let l = style.link { a.link = l; a.foregroundColor = Palette.iris; a.underlineStyle = .single }164        return a165    }166}167168// MARK: - Code blocks169170struct CodeBlockView: View {171    let language: String?172    let code: String173    @Environment(\.transcriptFontSize) private var size174    @State private var copied = false175    @State private var wrap = false176177    var body: some View {178        VStack(alignment: .leading, spacing: 0) {179            HStack(spacing: 10) {180                Text(language?.lowercased() ?? "texte").font(DS.F.mono(11, weight: .medium)).foregroundStyle(DS.C.muted)181                Spacer()182                Button { wrap.toggle() } label: { Image(systemName: wrap ? "arrow.left.and.right.text.vertical" : "text.word.spacing").font(.system(size: 11)) }183                    .buttonStyle(.borderless).foregroundStyle(wrap ? DS.C.accent : DS.C.muted).help(wrap ? "Ne plus couper les lignes" : "Couper les lignes longues").accessibilityLabel("Retour à la ligne automatique")184                Button { Pasteboard.copy(code); copied = true; Task { try? await Task.sleep(for: .seconds(1.6)); copied = false } } label: {185                    Label(copied ? "Copié" : "Copier", systemImage: copied ? "checkmark" : "doc.on.doc").font(DS.F.caption).contentTransition(.symbolEffect(.replace))186                }187                .buttonStyle(.borderless).foregroundStyle(copied ? DS.C.ok : DS.C.text2).accessibilityLabel("Copier le code").accessibilityIdentifier("copy-code")188            }189            .padding(.horizontal, 12).padding(.vertical, 6).background(DS.C.surface2)190            Rectangle().fill(DS.C.border).frame(height: 1)191            if wrap {192                Text(CodeHighlighting.attributed(code, language: language))193                    .font(.system(size: size * 0.9, design: .monospaced)).lineSpacing(2).textSelection(.enabled)194                    .frame(maxWidth: .infinity, alignment: .leading).padding(12)195            } else {196                ScrollView(.horizontal) {197                    Text(CodeHighlighting.attributed(code, language: language))198                        .font(.system(size: size * 0.9, design: .monospaced)).lineSpacing(2)199                        .textSelection(.enabled).fixedSize(horizontal: true, vertical: true)200                        .padding(12)201                }202                .scrollBounceBehavior(.basedOnSize, axes: .horizontal)203            }204        }205        .background(DS.C.surface, in: RoundedRectangle(cornerRadius: DS.R.card, style: .continuous))206        .clipShape(RoundedRectangle(cornerRadius: DS.R.card, style: .continuous))207        .overlay(RoundedRectangle(cornerRadius: DS.R.card, style: .continuous).strokeBorder(DS.C.border, lineWidth: 1))208        .accessibilityElement(children: .contain).accessibilityLabel("Bloc de code \(language ?? "")")209    }210}211212enum CodeHighlighting {213    private static let cache: NSCache<NSString, Box> = { let c = NSCache<NSString, Box>(); c.countLimit = 300; return c }()214    private final class Box { let value: AttributedString; init(_ v: AttributedString) { value = v } }215216    /// Colours come from dynamic system colours, so one attributed string is right in light and dark appearances.217    static func color(_ kind: TokenKind) -> Color? {218        switch kind {219        case .plain, .punctuation: nil220        case .keyword: Color(nsColor: .systemPurple)221        case .string: Color(nsColor: .systemRed)222        case .comment: Color(nsColor: .secondaryLabelColor)223        case .number: Color(nsColor: .systemOrange)224        case .type: Color(nsColor: .systemTeal)225        case .function: Color(nsColor: .systemBlue)226        case .attribute: Color(nsColor: .systemBrown)227        }228    }229230    static func attributed(_ code: String, language: String?) -> AttributedString {231        let key = "\(language ?? "")|\(code.count)|\(code.hashValue)" as NSString232        if let hit = cache.object(forKey: key) { return hit.value }233        var out = AttributedString()234        for token in SyntaxHighlighter.tokens(code, language: language) {235            var a = AttributedString(token.text)236            if let c = color(token.kind) { a.foregroundColor = c }237            out += a238        }239        cache.setObject(Box(out), forKey: key)240        return out241    }242}243244// MARK: - Tables245246struct TableBlockView: View {247    let table: MDTable248    @Environment(\.transcriptFontSize) private var size249250    var body: some View {251        ScrollView(.horizontal) {252            Grid(alignment: .leading, horizontalSpacing: 0, verticalSpacing: 0) {253                GridRow { ForEach(0..<table.columnCount, id: \.self) { c in cell(c < table.header.count ? table.header[c] : [], column: c, header: true) } }254                    .background(DS.C.surface2)255                ForEach(Array(table.rows.enumerated()), id: \.offset) { r, row in256                    Rectangle().fill(DS.C.border).frame(height: 1).gridCellUnsizedAxes(.horizontal)257                    GridRow { ForEach(0..<table.columnCount, id: \.self) { c in cell(c < row.count ? row[c] : [], column: c, header: false) } }258                        .background(r % 2 == 1 ? DS.C.surface2.opacity(0.45) : .clear)259                }260            }261            .background(DS.C.surface)262            .clipShape(RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))263            .overlay(RoundedRectangle(cornerRadius: DS.R.control, style: .continuous).strokeBorder(DS.C.border, lineWidth: 1))264            .padding(1)265        }266        .scrollBounceBehavior(.basedOnSize, axes: .horizontal)267        .accessibilityElement(children: .contain).accessibilityLabel("Tableau de \(table.rows.count) lignes et \(table.columnCount) colonnes")268        .contextMenu { Button("Copier le tableau (TSV)") { Pasteboard.copy(MDBlock.table(table).plainText) } }269    }270271    private func cell(_ inlines: [MDInline], column: Int, header: Bool) -> some View {272        let alignment = column < table.alignments.count ? table.alignments[column] : .leading273        return InlineBuilder(size: size * 0.95, weight: header ? .semibold : .regular).text(inlines)274            .textSelection(.enabled)275            .multilineTextAlignment(alignment == .trailing ? .trailing : alignment == .center ? .center : .leading)276            .frame(minWidth: 40, maxWidth: 340, alignment: alignment == .trailing ? .trailing : alignment == .center ? .center : .leading)277            .fixedSize(horizontal: false, vertical: true)278            .padding(.horizontal, 10).padding(.vertical, 6)279    }280}281
Files main
Menu

Theme