SPB Git

Repository Public

VQMarkdownText.swift 10.0 KB 174 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantUI/Components/VQMarkdownText.swift3// Description: Markdown for methodology notes: paragraphs, headings, lists, code blocks, inline emphasis, and4//              `$…$` formulas shown in the mono face.5//6// LIMITATION (stated in the README): formulas are NOT typeset. The LaTeX between `$…$` is made readable — Greek7// letters and common operators become their Unicode characters — and set in SF Mono on a tinted background.8import SwiftUI9import VQuantKit1011public enum VQMarkdown {12    public enum Block: Equatable, Sendable {13        case heading(level: Int, text: String)14        case paragraph(String)15        case bullets([String])16        case numbered([String])17        case code(String)18    }1920    /// Block structure of a small Markdown document.21    public static func blocks(_ source: String) -> [Block] {22        var out: [Block] = []23        var paragraph: [String] = [], bullets: [String] = [], numbered: [String] = [], code: [String]? = nil24        func flush() {25            if !paragraph.isEmpty { out.append(.paragraph(paragraph.joined(separator: " "))); paragraph = [] }26            if !bullets.isEmpty { out.append(.bullets(bullets)); bullets = [] }27            if !numbered.isEmpty { out.append(.numbered(numbered)); numbered = [] }28        }29        for raw in source.components(separatedBy: "\n") {30            let line = raw.trimmingCharacters(in: .whitespaces)31            if line.hasPrefix("```") {32                if let c = code { out.append(.code(c.joined(separator: "\n"))); code = nil } else { flush(); code = [] }33                continue34            }35            if code != nil { code!.append(raw); continue }36            if line.isEmpty { flush(); continue }37            if line.hasPrefix("#") {38                let level = line.prefix { $0 == "#" }.count39                if level <= 6, line.dropFirst(level).first == " " { flush(); out.append(.heading(level: level, text: String(line.dropFirst(level + 1)))); continue }40            }41            if line.hasPrefix("- ") || line.hasPrefix("* ") || line.hasPrefix("• ") {42                if !paragraph.isEmpty || !numbered.isEmpty { flush() }43                bullets.append(String(line.dropFirst(2))); continue44            }45            if let dot = line.firstIndex(of: "."), line[..<dot].allSatisfy(\.isNumber), !line[..<dot].isEmpty, line[line.index(after: dot)...].first == " " {46                if !paragraph.isEmpty || !bullets.isEmpty { flush() }47                numbered.append(String(line[line.index(dot, offsetBy: 2)...])); continue48            }49            if !bullets.isEmpty { bullets[bullets.count - 1] += " " + line; continue }50            if !numbered.isEmpty { numbered[numbered.count - 1] += " " + line; continue }51            paragraph.append(line)52        }53        if let c = code { out.append(.code(c.joined(separator: "\n"))) }54        flush()55        return out56    }5758    /// Splits text into prose and `$…$` formulas (a `$` followed by a digit and no closing `$` is money, not math).59    public static func segments(_ text: String) -> [(text: String, isMath: Bool)] {60        var out: [(String, Bool)] = []61        var rest = Substring(text)62        while let open = rest.firstIndex(of: "$") {63            let after = rest.index(after: open)64            guard let close = rest[after...].firstIndex(of: "$"), close > after else { break }65            if open > rest.startIndex { out.append((String(rest[..<open]), false)) }66            out.append((String(rest[after..<close]), true))67            rest = rest[rest.index(after: close)...]68        }69        if !rest.isEmpty { out.append((String(rest), false)) }70        return out71    }7273    /// LaTeX source made readable as plain text: `\sigma_t^2` → `σ_t^2`, `\sqrt{A}` → `√(A)`, `\frac{a}{b}` → `(a)/(b)`.74    public static func readableMath(_ latex: String) -> String {75        var s = latex76        // \frac{a}{b} → (a)/(b) for simple (non-nested) arguments77        while let r = s.range(of: #"\\frac\{([^{}]*)\}\{([^{}]*)\}"#, options: .regularExpression) {78            let inner = String(s[r]).dropFirst(6).dropLast(1)79            let parts = inner.components(separatedBy: "}{")80            s.replaceSubrange(r, with: parts.count == 2 ? "(\(parts[0]))/(\(parts[1]))" : String(inner))81        }82        for (pattern, replacement) in [(#"\\sqrt\{([^{}]*)\}"#, "√($1)"), (#"\\(?:mathbf|mathrm|mathbb|mathcal|text|operatorname|bar|hat|tilde)\{([^{}]*)\}"#, "$1"),83                                       (#"\\hat\s*([A-Za-zα-ω])"#, "$1̂"), (#"\\bar\s*([A-Za-zα-ω\\]+)"#, "$1̄"), (#"\\tilde\s*([A-Za-zα-ω])"#, "$1̃")] {84            s = s.replacingOccurrences(of: pattern, with: replacement, options: .regularExpression)85        }86        let symbols: [(String, String)] = [87            ("\\varepsilon", "ε"), ("\\epsilon", "ε"), ("\\alpha", "α"), ("\\beta", "β"), ("\\gamma", "γ"), ("\\delta", "δ"), ("\\Delta", "Δ"), ("\\theta", "θ"),88            ("\\kappa", "κ"), ("\\lambda", "λ"), ("\\Lambda", "Λ"), ("\\mu", "μ"), ("\\nu", "ν"), ("\\omega", "ω"), ("\\Omega", "Ω"), ("\\phi", "φ"), ("\\Phi", "Φ"),89            ("\\pi", "π"), ("\\Pi", "Π"), ("\\rho", "ρ"), ("\\sigma", "σ"), ("\\Sigma", "Σ"), ("\\tau", "τ"), ("\\xi", "ξ"), ("\\chi", "χ"), ("\\psi", "ψ"), ("\\eta", "η"),90            ("\\zeta", "ζ"), ("\\Gamma", "Γ"), ("\\Theta", "Θ"), ("\\sum", "∑"), ("\\prod", "∏"), ("\\int", "∫"), ("\\infty", "∞"), ("\\partial", "∂"), ("\\nabla", "∇"),91            ("\\leq", "≤"), ("\\geq", "≥"), ("\\le", "≤"), ("\\ge", "≥"), ("\\neq", "≠"), ("\\ne", "≠"), ("\\approx", "≈"), ("\\sim", "∼"), ("\\times", "×"), ("\\cdot", "·"),92            ("\\pm", "±"), ("\\to", "→"), ("\\rightarrow", "→"), ("\\in", "∈"), ("\\sqrt", "√"), ("\\ldots", "…"), ("\\dots", "…"), ("\\cdots", "⋯"), ("\\top", "ᵀ"),93            ("\\prime", "′"), ("\\ln", "ln"), ("\\log", "log"), ("\\exp", "exp"), ("\\max", "max"), ("\\min", "min"), ("\\left", ""), ("\\right", ""),94            ("\\,", " "), ("\\;", " "), ("\\!", ""), ("\\quad", "  "), ("\\ ", " "), ("\\|", "‖"), ("\\{", "{"), ("\\}", "}"), ("\\%", "%"),95        ]96        for (command, glyph) in symbols {97            // a command name must not be the prefix of a longer one (\in vs \infty, \le vs \left)98            let needsBoundary = command.last!.isLetter99            s = needsBoundary ? s.replacingOccurrences(of: NSRegularExpression.escapedPattern(for: command) + "(?![A-Za-z])", with: glyph, options: .regularExpression)100                              : s.replacingOccurrences(of: command, with: glyph)101        }102        return s.replacingOccurrences(of: "  ", with: " ").trimmingCharacters(in: .whitespaces)103    }104105    /// Inline Markdown with formulas in the mono face.106    public static func attributed(_ text: String, mathBackground: Color = VQTokens.Palette.ink3) -> AttributedString {107        var out = AttributedString()108        for segment in segments(text) {109            if segment.isMath {110                var math = AttributedString("\u{2009}" + readableMath(segment.text) + "\u{2009}")111                math.font = .system(.callout, design: .monospaced)112                math.backgroundColor = mathBackground113                out += math114            } else {115                let options = AttributedString.MarkdownParsingOptions(interpretedSyntax: .inlineOnlyPreservingWhitespace)116                out += (try? AttributedString(markdown: segment.text, options: options)) ?? AttributedString(segment.text)117            }118        }119        return out120    }121}122123/// Renders a Markdown note (methodology, review verdicts). Text is selectable.124public struct VQMarkdownText: View {125    private let blocks: [VQMarkdown.Block]126    public init(_ source: String) { blocks = VQMarkdown.blocks(source) }127128    private func prose(_ text: String) -> some View {129        Text(VQMarkdown.attributed(text)).vqFont(VQTokens.Typography.bodySm).lineSpacing(4).foregroundStyle(VQP.text1)130            .fixedSize(horizontal: false, vertical: true).frame(maxWidth: .infinity, alignment: .leading)131    }132133    public var body: some View {134        VStack(alignment: .leading, spacing: VQS.s3) {135            ForEach(Array(blocks.enumerated()), id: \.offset) { _, block in136                switch block {137                case .heading(let level, let text):138                    Text(VQMarkdown.attributed(text)).vqFont(level <= 2 ? VQTokens.Typography.title : VQTokens.Typography.heading).foregroundStyle(VQP.text1)139                        .accessibilityAddTraits(.isHeader)140                case .paragraph(let text): prose(text)141                case .bullets(let items):142                    VStack(alignment: .leading, spacing: VQS.s1) {143                        ForEach(Array(items.enumerated()), id: \.offset) { _, item in144                            HStack(alignment: .firstTextBaseline, spacing: VQS.s2) { Text("–").foregroundStyle(VQP.text3).vqFont(VQTokens.Typography.bodySm); prose(item) }145                        }146                    }147                case .numbered(let items):148                    VStack(alignment: .leading, spacing: VQS.s1) {149                        ForEach(Array(items.enumerated()), id: \.offset) { i, item in150                            HStack(alignment: .firstTextBaseline, spacing: VQS.s2) { Text("\(i + 1).").vqFont(VQTokens.Typography.numSm).foregroundStyle(VQP.text3); prose(item) }151                        }152                    }153                case .code(let code): VQCodeBlock(code)154                }155            }156        }157        .textSelection(.enabled)158    }159}160161/// Mono text on a tinted plate.162public struct VQCodeBlock: View {163    private let code: String164    public init(_ code: String) { self.code = code }165    public var body: some View {166        Text(code).font(.system(size: 11.5, design: .monospaced)).foregroundStyle(VQP.text1).lineSpacing(3)167            .fixedSize(horizontal: false, vertical: true)168            .frame(maxWidth: .infinity, alignment: .leading)169            .padding(VQS.s3)170            .background(RoundedRectangle(cornerRadius: VQTokens.Radius.sm, style: .continuous).fill(VQP.ink3))171            .textSelection(.enabled)172    }173}174
Files main
Menu

Theme