SPB Git

Repository Public MIT

MarkdownView.swift 17.4 KB 368 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraUI/Sources/Markdown/MarkdownView.swift10// Module           : Markdown11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import SwiftUI89import AstraDesign909192/// Renders a message body. The text is parsed in independent chunks; while it streams only the last chunk changes, and93/// SwiftUI skips every chunk whose source is unchanged (`Equatable`).94struct MarkdownView: View {95    let text: String96    var body: some View {97        let chunks = MarkdownParser.shared.chunks(text)98        VStack(alignment: .leading, spacing: 10) {99            ForEach(chunks) { chunk in ChunkView(chunk: chunk).equatable() }100        }101        .frame(maxWidth: .infinity, alignment: .leading)102    }103}104105struct ChunkView: View, Equatable {106    let chunk: MDChunk107    nonisolated static func == (a: ChunkView, b: ChunkView) -> Bool { a.chunk.source == b.chunk.source }108    var body: some View { BlockList(blocks: chunk.blocks) }109}110111struct BlockList: View {112    let blocks: [MDBlock]113    var spacing: CGFloat = 10114    var body: some View {115        VStack(alignment: .leading, spacing: spacing) {116            ForEach(Array(blocks.enumerated()), id: \.offset) { _, block in BlockView(block: block) }117        }118    }119}120121struct BlockView: View {122    let block: MDBlock123    @Environment(\.transcriptFontSize) private var size124125    var body: some View {126        switch block {127        case .paragraph(let inlines):128            InlineText(inlines: inlines, size: size)129        case .heading(let level, let inlines):130            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)131                .padding(.top, level <= 2 ? 6 : 2).accessibilityAddTraits(.isHeader)132        case .code(let language, let text):133            CodeBlockView(language: language, code: text)134        case .quote(let blocks):135            HStack(alignment: .top, spacing: 10) {136                RoundedRectangle(cornerRadius: 1.5).fill(AstraColor.violet.opacity(0.55)).frame(width: 3)137                BlockList(blocks: blocks, spacing: 8).foregroundStyle(.secondary)138            }139            .fixedSize(horizontal: false, vertical: true)140        case .list(let ordered, let start, let items):141            VStack(alignment: .leading, spacing: 5) {142                ForEach(Array(items.enumerated()), id: \.offset) { n, item in143                    HStack(alignment: .firstTextBaseline, spacing: 7) {144                        marker(ordered: ordered, number: start + n, checkbox: item.checkbox)145                        BlockList(blocks: item.blocks, spacing: 6)146                    }147                }148            }149            .padding(.leading, 4)150        case .table(let table):151            TableBlockView(table: table)152        case .rule:153            Divider().padding(.vertical, 4)154        case .math(let tex):155            MathBlockView(tex: tex)156        case .html(let raw):157            Text(raw).font(.system(size: size * 0.9, design: .monospaced)).foregroundStyle(.secondary).textSelection(.enabled)158        }159    }160161    @ViewBuilder private func marker(ordered: Bool, number: Int, checkbox: Bool?) -> some View {162        if let checkbox {163            Image(systemName: checkbox ? "checkmark.square.fill" : "square").foregroundStyle(checkbox ? AstraColor.violet : .secondary).font(.system(size: size * 0.95))164                .accessibilityLabel(checkbox ? "Done" : "To do")165        } else if ordered {166            Text("\(number).").font(.system(size: size).monospacedDigit()).foregroundStyle(.secondary).frame(minWidth: size * 1.4, alignment: .trailing)167        } else {168            Text("•").font(.system(size: size)).foregroundStyle(.secondary).frame(width: size * 0.9)169        }170    }171}172173// MARK: - Inline text174175struct InlineText: View {176    let inlines: [MDInline]177    let size: CGFloat178    var weight: Font.Weight = .regular179    @Environment(\.openURL) private var openURL180181    var body: some View {182        InlineBuilder(size: size, weight: weight).text(inlines)183            .lineSpacing(size * 0.28)184            .textSelection(.enabled)185            .fixedSize(horizontal: false, vertical: true)186            .frame(maxWidth: .infinity, alignment: .leading)187            .environment(\.openURL, OpenURLAction { url in188                // only http(s) and mailto links leave the app; anything else found in model output is ignored189                guard LinkPolicy.safeURL(url.absoluteString) != nil else { return .discarded }190                return .systemAction191            })192    }193}194195/// Builds one `Text` from inline nodes: attributed runs for styled text, template images for inline math.196@MainActor struct InlineBuilder {197    let size: CGFloat198    var weight: Font.Weight = .regular199200    struct Style { var bold = false; var italic = false; var strike = false; var link: URL? }201202    func text(_ inlines: [MDInline]) -> Text {203        var pieces: [Text] = []; var run = AttributedString()204        func flush() { if !run.characters.isEmpty { pieces.append(Text(run)); run = AttributedString() } }205        func walk(_ nodes: [MDInline], _ style: Style) {206            for node in nodes {207                switch node {208                case .text(let s): run += styled(s, style)209                case .softBreak: run += styled(" ", style)210                case .lineBreak: run += styled("\n", style)211                case .emphasis(let c): var s = style; s.italic = true; walk(c, s)212                case .strong(let c): var s = style; s.bold = true; walk(c, s)213                case .strikethrough(let c): var s = style; s.strike = true; walk(c, s)214                case .code(let code):215                    var a = AttributedString(code)216                    a.font = .system(size: size * 0.92, design: .monospaced)217                    a.backgroundColor = Color.primary.opacity(0.07)218                    if let l = style.link { a.link = l }219                    run += a220                case .link(let destination, let children):221                    var s = style; s.link = LinkPolicy.safeURL(destination)222                    walk(children.isEmpty ? [.text(destination)] : children, s)223                    if s.link == nil, !destination.isEmpty { run += styled(" (\(destination))", style) } // unsafe target: shown, not clickable224                case .image(let source, let alt):225                    // remote images are never fetched automatically (privacy): the link is offered instead226                    var s = style; s.link = LinkPolicy.safeURL(source)227                    run += styled("[image: " + (alt.isEmpty ? source : alt) + "]", s)228                case .math(let tex, let display):229                    if let m = MathRenderer.render(tex, fontSize: size * (display ? 1.1 : 1.0), display: false) {230                        flush()231                        pieces.append(Text(m.swiftUIImage.renderingMode(.template)).baselineOffset(-m.descent).accessibilityLabel(Text("formula \(tex)")))232                    } else {233                        var a = AttributedString(tex); a.font = .system(size: size * 0.92, design: .monospaced); a.foregroundColor = .secondary; run += a234                    }235                }236            }237        }238        walk(inlines, Style()); flush()239        return pieces.reduce(Text("")) { Text("\($0)\($1)") }240    }241242    private func styled(_ s: String, _ style: Style) -> AttributedString {243        var a = AttributedString(s)244        var font = Font.system(size: size, weight: style.bold ? .semibold : weight)245        if style.italic { font = font.italic() }246        a.font = font247        if style.strike { a.strikethroughStyle = .single }248        if let l = style.link { a.link = l; a.foregroundColor = AstraColor.violet; a.underlineStyle = .single }249        return a250    }251}252253// MARK: - Code blocks254255struct CodeBlockView: View {256    let language: String?257    let code: String258    @Environment(\.transcriptFontSize) private var size259    @State private var copied = false260    @State private var wrap = false261262    var body: some View {263        VStack(alignment: .leading, spacing: 0) {264            HStack(spacing: 10) {265                Text(language?.lowercased() ?? "text").font(AstraFont.micro.monospaced()).foregroundStyle(AstraColor.textTertiary)266                Spacer()267                Button { wrap.toggle() } label: { Image(systemName: wrap ? "arrow.left.and.right.text.vertical" : "text.word.spacing").font(.system(size: 11)) }268                    .buttonStyle(.borderless).foregroundStyle(wrap ? AstraColor.violet : AstraColor.textTertiary).frame(minWidth: 40, minHeight: 40).contentShape(Rectangle())269                    .accessibilityLabel(wrap ? "Stop wrapping lines" : "Wrap long lines")270                Button { Pasteboard.copy(code); copied = true; Task { try? await Task.sleep(for: .seconds(1.6)); copied = false } } label: {271                    Label(copied ? "Copied" : "Copy", systemImage: copied ? "checkmark" : "doc.on.doc").font(AstraFont.caption).contentTransition(.symbolEffect(.replace))272                }273                .buttonStyle(.borderless).foregroundStyle(copied ? AstraColor.success : AstraColor.textSecondary).frame(minHeight: 40).contentShape(Rectangle())274                .accessibilityLabel("Copy code").accessibilityIdentifier("copy-code")275            }276            .padding(.leading, 12).padding(.trailing, 6).background(AstraColor.surfaceRaised)277            Rectangle().fill(AstraColor.stroke).frame(height: 1)278            if wrap {279                Text(CodeHighlighting.attributed(code, language: language))280                    .font(.system(size: size * 0.9, design: .monospaced)).lineSpacing(2).textSelection(.enabled)281                    .frame(maxWidth: .infinity, alignment: .leading).padding(12)282            } else {283                ScrollView(.horizontal) {284                    Text(CodeHighlighting.attributed(code, language: language))285                        .font(.system(size: size * 0.9, design: .monospaced)).lineSpacing(2)286                        .textSelection(.enabled).fixedSize(horizontal: true, vertical: true)287                        .padding(12)288                }289                .scrollBounceBehavior(.basedOnSize, axes: .horizontal)290            }291        }292        .background(AstraColor.codeBackground, in: RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous))293        .clipShape(RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous))294        .overlay(RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous).strokeBorder(AstraColor.stroke, lineWidth: 1))295        .accessibilityElement(children: .contain).accessibilityLabel("Code block \(language ?? "")")296    }297}298299@MainActor enum CodeHighlighting {300    private static let cache: NSCache<NSString, Box> = { let c = NSCache<NSString, Box>(); c.countLimit = 300; return c }()301    private final class Box { let value: AttributedString; init(_ v: AttributedString) { value = v } }302303    /// Colours come from dynamic system colours, so one attributed string is right in light and dark appearances.304    static func color(_ kind: TokenKind) -> Color? {305        switch kind {306        case .plain, .punctuation: nil307        case .keyword: AstraColor.codeKeyword308        case .string: AstraColor.codeString309        case .comment: AstraColor.textTertiary310        case .number: AstraColor.codeNumber311        case .type: AstraColor.codeType312        case .function: AstraColor.violet313        case .attribute: Color(light: 0x8A5A2B, dark: 0xD9A066)314        }315    }316317    static func attributed(_ code: String, language: String?) -> AttributedString {318        let key = "\(language ?? "")|\(code.count)|\(code.hashValue)" as NSString319        if let hit = cache.object(forKey: key) { return hit.value }320        var out = AttributedString()321        for token in SyntaxHighlighter.tokens(code, language: language) {322            var a = AttributedString(token.text)323            if let c = color(token.kind) { a.foregroundColor = c }324            out += a325        }326        cache.setObject(Box(out), forKey: key)327        return out328    }329}330331// MARK: - Tables332333struct TableBlockView: View {334    let table: MDTable335    @Environment(\.transcriptFontSize) private var size336337    var body: some View {338        ScrollView(.horizontal) {339            Grid(alignment: .leading, horizontalSpacing: 0, verticalSpacing: 0) {340                GridRow { ForEach(0..<table.columnCount, id: \.self) { c in cell(c < table.header.count ? table.header[c] : [], column: c, header: true) } }341                    .background(AstraColor.surfaceRaised)342                ForEach(Array(table.rows.enumerated()), id: \.offset) { r, row in343                    Rectangle().fill(AstraColor.stroke).frame(height: 1).gridCellUnsizedAxes(.horizontal)344                    GridRow { ForEach(0..<table.columnCount, id: \.self) { c in cell(c < row.count ? row[c] : [], column: c, header: false) } }345                        .background(r % 2 == 1 ? AstraColor.surfaceRaised.opacity(0.45) : .clear)346                }347            }348            .background(AstraColor.codeBackground)349            .clipShape(RoundedRectangle(cornerRadius: AstraRadius.sm, style: .continuous))350            .overlay(RoundedRectangle(cornerRadius: AstraRadius.sm, style: .continuous).strokeBorder(AstraColor.stroke, lineWidth: 1))351            .padding(1)352        }353        .scrollBounceBehavior(.basedOnSize, axes: .horizontal)354        .accessibilityElement(children: .contain).accessibilityLabel("Table, \(table.rows.count) rows, \(table.columnCount) columns")355        .contextMenu { Button("Copy table (TSV)") { Pasteboard.copy(MDBlock.table(table).plainText) } }356    }357358    private func cell(_ inlines: [MDInline], column: Int, header: Bool) -> some View {359        let alignment = column < table.alignments.count ? table.alignments[column] : .leading360        return InlineBuilder(size: size * 0.95, weight: header ? .semibold : .regular).text(inlines)361            .textSelection(.enabled)362            .multilineTextAlignment(alignment == .trailing ? .trailing : alignment == .center ? .center : .leading)363            .frame(minWidth: 40, maxWidth: 340, alignment: alignment == .trailing ? .trailing : alignment == .center ? .center : .leading)364            .fixedSize(horizontal: false, vertical: true)365            .padding(.horizontal, 10).padding(.vertical, 6)366    }367}368
Files main
Menu

Theme