Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Components/MathView.swift4// Description: LaTeX math typeset natively (CoreText, SwiftMath) for display equations and inline formulas.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//910import SwiftMath11import SwiftUI12import UIKit1314@MainActor15enum MathRenderer {16 struct Rendered { let image: UIImage; let descent: CGFloat }17 private final class Box: NSObject { let value: Rendered?; init(_ v: Rendered?) { value = v } }18 private static let cache: NSCache<NSString, Box> = { let c = NSCache<NSString, Box>(); c.countLimit = 500; return c }()1920 /// Typesets `latex` to a template image (tinted with the text colour at draw time, so one image serves light and dark).21 /// Returns nil when the formula cannot be parsed — callers then show the source.22 static func render(_ latex: String, fontSize: CGFloat, display: Bool) -> Rendered? {23 let key = "\(display ? "D" : "I")\(Int(fontSize * 10))\u{0}\(latex)" as NSString24 if let b = cache.object(forKey: key) { return b.value }25 var math = MathImage(latex: normalize(latex), fontSize: fontSize, textColor: .black, labelMode: display ? .display : .text, textAlignment: .left)26 let (error, image, info) = math.asImage()27 var out: Rendered?28 if error == nil, let image, image.size.width > 0, image.size.height > 0 {29 out = Rendered(image: image.withRenderingMode(.alwaysTemplate), descent: info?.descent ?? 0)30 }31 cache.setObject(Box(out), forKey: key)32 return out33 }3435 /// A few constructs models write that the typesetter does not know are mapped to equivalents.36 private static func normalize(_ s: String) -> String {37 var t = s.trimmingCharacters(in: .whitespacesAndNewlines)38 for (a, b) in [("\\dfrac", "\\frac"), ("\\tfrac", "\\frac"), ("\\displaystyle", ""), ("\\textstyle", ""), ("\\nonumber", ""), ("\\notag", ""), ("\\,", "\\,"), ("\\lvert", "|"), ("\\rvert", "|"), ("\\lVert", "\\|"), ("\\rVert", "\\|"), ("\\operatorname", "\\mathrm"), ("\\boldsymbol", "\\mathbf"), ("\\bm", "\\mathbf"), ("\\mathbb{E}", "\\mathbb{E}")] where a != b {39 t = t.replacingOccurrences(of: a, with: b)40 }41 for env in ["align*", "align", "equation*", "equation", "gather*", "gather"] {42 t = t.replacingOccurrences(of: "\\begin{\(env)}", with: "\\begin{aligned}").replacingOccurrences(of: "\\end{\(env)}", with: "\\end{aligned}")43 }44 return t45 }4647 static func clear() { cache.removeAllObjects() }48}4950/// A display equation, horizontally scrollable when wider than the screen.51struct MathBlockView: View {52 let latex: String53 @ScaledMetric(relativeTo: .body) private var fontSize: CGFloat = 195455 var body: some View {56 if let r = MathRenderer.render(latex, fontSize: fontSize, display: true) {57 // centred when it fits; a wide equation scrolls sideways on its own instead of being shrunk58 ViewThatFits(in: .horizontal) {59 Image(uiImage: r.image).foregroundStyle(Color("TextPrimary")).padding(.vertical, 6).frame(maxWidth: .infinity, alignment: .center)60 ScrollView(.horizontal, showsIndicators: false) {61 Image(uiImage: r.image).foregroundStyle(Color("TextPrimary")).padding(.vertical, 6)62 }63 }64 .accessibilityElement()65 .accessibilityLabel(String(localized: "Équation : \(latex)"))66 .contextMenu { Button { UIPasteboard.general.string = latex } label: { Label("Copier le LaTeX", systemImage: "square.on.square") } }67 } else {68 // not parseable (or still streaming): show the source rather than nothing69 Text(latex).font(.system(.callout, design: .monospaced)).foregroundStyle(Color("TextSecondary")).textSelection(.enabled)70 }71 }72}73