forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodeBlockHighlighter.swift
More file actions
67 lines (57 loc) · 1.79 KB
/
CodeBlockHighlighter.swift
File metadata and controls
67 lines (57 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import Foundation
import MarkdownUI
import SharedUIComponents
import SwiftUI
final class CodeBlockHighlighterCacheController {
private var cache: [String: AttributedString] = [:]
func get(_ key: String) -> AttributedString? {
cache[key]
}
func set(_ key: String, _ value: AttributedString) {
cache[key] = value
}
}
struct CodeHighlightCacheEnvironmentKey: EnvironmentKey {
static var defaultValue: CodeBlockHighlighterCacheController = .init()
}
extension EnvironmentValues {
var codeHighlightCacheController: CodeBlockHighlighterCacheController {
get { self[CodeHighlightCacheEnvironmentKey.self] }
set { self[CodeHighlightCacheEnvironmentKey.self] = newValue }
}
}
struct ChatCodeSyntaxHighlighter: CodeSyntaxHighlighter {
let brightMode: Bool
let font: NSFont
let colorChange: Color?
var cacheController: CodeBlockHighlighterCacheController
init(
brightMode: Bool,
font: NSFont,
colorChange: Color?,
cacheController: CodeBlockHighlighterCacheController
) {
self.brightMode = brightMode
self.font = font
self.colorChange = colorChange
self.cacheController = cacheController
}
func highlightCode(_ code: String, language: String?) -> Text {
let key = "\(language ?? "unknown") - \(code)"
if let text = cacheController.get(key) {
return Text(text)
}
let content = highlightedCodeBlock(
code: code,
language: language ?? "",
scenario: "chat",
brightMode: brightMode,
font: font
)
let string = AttributedString(content)
Task { @MainActor in
cacheController.set(key, string)
}
return Text(string)
}
}