SPB Git

Repository Public

CodeBlockView.swift 5.8 KB 125 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/Components/CodeBlockView.swift4//  Description: Code block with language label, copy button, syntax colouring and horizontal scrolling.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//910import SwiftUI11import UIKit1213struct CodeBlockView: View {14    let language: String?15    let code: String16    /// False while the closing fence has not arrived: colouring of big blocks waits for the end of the stream.17    var closed = true1819    @Environment(AppEnvironment.self) private var env: AppEnvironment?20    @State private var copied = false21    @State private var wrap = false22    @ScaledMetric(relativeTo: .footnote) private var fontSize: CGFloat = 13.52324    var body: some View {25        VStack(alignment: .leading, spacing: 0) {26            HStack(spacing: 8) {27                Text(language?.lowercased() ?? String(localized: "code"))28                    .font(.caption.monospaced().weight(.medium))29                    .foregroundStyle(Color.muted)30                Spacer(minLength: 8)31                Button { wrap.toggle() } label: {32                    Image(systemName: wrap ? "arrow.right.to.line" : "text.word.spacing").font(.caption.weight(.medium)).foregroundStyle(wrap ? Color.accentColor : Color.textSecondary)33                        .frame(width: 36, height: 32).contentShape(.rect)34                }35                .buttonStyle(.plain)36                .accessibilityLabel(wrap ? String(localized: "Ne plus replier les lignes") : String(localized: "Replier les lignes longues"))37                Button {38                    UIPasteboard.general.string = code39                    env?.haptics.soften()40                    withAnimation(.snappy) { copied = true }41                    Task { try? await Task.sleep(for: .seconds(1.6)); withAnimation(.snappy) { copied = false } }42                } label: {43                    Label(copied ? String(localized: "Copié") : String(localized: "Copier"), systemImage: copied ? "checkmark" : "square.on.square")44                        .font(.caption.weight(.medium))45                        .foregroundStyle(copied ? Color.success : Color.textSecondary)46                        .contentTransition(.symbolEffect(.replace))47                        .padding(.vertical, 6).padding(.horizontal, 4)48                        .contentShape(.rect)49                }50                .buttonStyle(.plain)51                .accessibilityLabel(copied ? String(localized: "Code copié") : String(localized: "Copier le code"))52            }53            .padding(.leading, 14).padding(.trailing, 10).padding(.vertical, 2)54            .background(Color("CodeHeader"))5556            if wrap {57                Text(highlighted)58                    .font(.system(size: fontSize, design: .monospaced))59                    .lineSpacing(3)60                    .frame(maxWidth: .infinity, alignment: .leading)61                    .padding(.horizontal, 14).padding(.vertical, 12)62            } else {63                ScrollView(.horizontal, showsIndicators: false) {64                    Text(highlighted)65                        .font(.system(size: fontSize, design: .monospaced))66                        .lineSpacing(3)67                        .fixedSize(horizontal: true, vertical: true)68                        .padding(.horizontal, 14).padding(.vertical, 12)69                }70            }71        }72        .background(Color("CodeBackground"))73        .clipShape(.rect(cornerRadius: Radius.card, style: .continuous))74        .overlay(RoundedRectangle(cornerRadius: Radius.card, style: .continuous).strokeBorder(Color.hairline, lineWidth: 0.75))75        .accessibilityElement(children: .contain)76        .accessibilityLabel(String(localized: "Bloc de code \(language ?? "")"))77    }7879    private var highlighted: AttributedString {80        // while a long block is still streaming, re-colouring it on every frame would be wasted work81        if !closed && code.utf8.count > 6000 { var a = AttributedString(code); a.foregroundColor = SyntaxHighlighter.Theme().plain; return a }82        return RenderCache.shared.code(code, language: language)83    }84}8586/// Memoises the expensive, pure parts of rendering (parsing, colouring, inline attributed strings, math images).87/// Keys are the source strings themselves: a message that did not change is never parsed twice, and while an answer88/// streams only its last block misses the cache.89@MainActor90final class RenderCache {91    static let shared = RenderCache()92    private let blocks = NSCache<NSString, Box<[MarkdownBlock]>>()93    private let codes = NSCache<NSString, Box<AttributedString>>()94    private let inlines = NSCache<NSString, Box<AttributedString>>()95    final class Box<T>: NSObject { let value: T; init(_ v: T) { value = v } }9697    private init() { blocks.countLimit = 600; codes.countLimit = 300; inlines.countLimit = 4000 }9899    func markdown(_ text: String) -> [MarkdownBlock] {100        let key = text as NSString101        if let b = blocks.object(forKey: key) { return b.value }102        let parsed = MarkdownParser.parse(text)103        blocks.setObject(Box(parsed), forKey: key)104        return parsed105    }106107    func code(_ code: String, language: String?) -> AttributedString {108        let key = "\(language ?? "")\u{0}\(code)" as NSString109        if let b = codes.object(forKey: key) { return b.value }110        let a = SyntaxHighlighter.highlight(code, language: language)111        codes.setObject(Box(a), forKey: key)112        return a113    }114115    func inline(_ source: String, accent: Color) -> AttributedString {116        let key = source as NSString117        if let b = inlines.object(forKey: key) { return b.value }118        let a = InlineMarkdown.attributed(source, accent: accent)119        inlines.setObject(Box(a), forKey: key)120        return a121    }122123    func clear() { blocks.removeAllObjects(); codes.removeAllObjects(); inlines.removeAllObjects(); MathRenderer.clear() }124}125
Files main
Menu

Theme