Branchwell

Jotley / app / Shared / Extensions / String+MarkdownStripping.swift

1import Foundation
2
3extension String {
4 /// Single-line plain-text snippet for list row previews. Bounds source length
5 /// before running regex passes so long transcripts don't block the main thread,
6 /// and caches results so LazyVStack row recycling is free on the second render.
7 func previewSnippet(maxSourceLength: Int = 400) -> String {
8 // `prefix` advances at most `maxSourceLength` Characters (O(maxSourceLength)).
9 // The previous `count > maxSourceLength` guard walked the ENTIRE string on
10 // every call — and this runs per visible row on every list render — which is
11 // why the list-row main-thread hang (JOTLEY-MACOS-N) survived the cache.
12 let bounded = String(prefix(maxSourceLength))
13 return MarkdownPreviewSnippetCache.shared.snippet(for: bounded)
14 }
15}
16
17private final class MarkdownPreviewSnippetCache {
18 static let shared = MarkdownPreviewSnippetCache()
19
20 private let cache: NSCache<NSString, NSString> = {
21 let c = NSCache<NSString, NSString>()
22 c.countLimit = 500
23 return c
24 }()
25
26 func snippet(for source: String) -> String {
27 let key = source as NSString
28 if let cached = cache.object(forKey: key) {
29 return cached as String
30 }
31 let result = Self.stripToPlainText(source)
32 cache.setObject(result as NSString, forKey: key)
33 return result
34 }
35
36 private static func stripToPlainText(_ markdown: String) -> String {
37 var text = LocalSummary.markdownForDisplay(markdown)
38 // Structured summaries open with a "Summary" heading; previews start with its words.
39 text = text.replacingOccurrences(of: "^\\s{0,3}#{1,6}\\s*(?i:summary|overview|résumé|resumen|resumo|riassunto|zusammenfassung|概要|要約|摘要|요약)\\s*\n", with: "", options: .regularExpression)
40 text = text.replacingOccurrences(of: "(?m)^\\s{0,3}#{1,6}\\s*", with: "", options: .regularExpression)
41 text = text.replacingOccurrences(of: "(?m)^\\s*>\\s*", with: "", options: .regularExpression)
42 text = text.replacingOccurrences(of: #"(?m)^[ \t]*(?:[-*+]|\d+[.)])[ \t]+\[[ xX]\](?:[ \t]+|$)"#, with: "", options: .regularExpression)
43 text = text.replacingOccurrences(of: "(?m)^\\s*(?:[-*+]\\s+|\\d+\\.\\s+)", with: "", options: .regularExpression)
44 text = text.replacingOccurrences(of: "\\[([^\\]]+)\\]\\([^\\)]+\\)", with: "$1", options: .regularExpression)
45 text = text.replacingOccurrences(of: "`([^`]*)`", with: "$1", options: .regularExpression)
46 text = text.replacingOccurrences(of: "(\\*\\*|__)(.*?)\\1", with: "$2", options: .regularExpression)
47 text = text.replacingOccurrences(of: "(\\*|_)(.*?)\\1", with: "$2", options: .regularExpression)
48 text = text.replacingOccurrences(of: "~~(.*?)~~", with: "$1", options: .regularExpression)
49 text = text.replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression)
50 return text.trimmingCharacters(in: .whitespacesAndNewlines)
51 }
52}