@@ -11,11 +11,13 @@ struct AsyncCodeBlockView: View {
1111 class Storage : ObservableObject {
1212 static let queue = DispatchQueue (
1313 label: " chat-code-block-highlight " ,
14- qos: . userInteractive
14+ qos: . userInteractive,
15+ attributes: . concurrent
1516 )
1617
1718 @Published var highlighted : AttributedString ?
1819 var debounceFunction : DebounceFunction < AsyncCodeBlockView > ?
20+ private var highlightTask : Task < Void , Error > ?
1921
2022 init ( ) {
2123 self . debounceFunction = . init( duration: 0.5 , block: { [ weak self] view in
@@ -32,20 +34,26 @@ struct AsyncCodeBlockView: View {
3234 }
3335
3436 func highlight( for view: AsyncCodeBlockView ) {
37+ highlightTask? . cancel ( )
3538 let content = view. content
3639 let language = view. fenceInfo ?? " "
3740 let brightMode = view. colorScheme != . dark
3841 let font = view. font
39- Self . queue. async {
40- let content = highlightedCodeBlock (
41- code: content,
42- language: language,
43- scenario: " chat " ,
44- brightMode: brightMode,
45- font: font
46- )
47- let string = AttributedString ( content)
48- DispatchQueue . main. async {
42+ highlightTask = Task {
43+ let string = await withUnsafeContinuation { continuation in
44+ Self . queue. async {
45+ let content = highlightedCodeBlock (
46+ code: content,
47+ language: language,
48+ scenario: " chat " ,
49+ brightMode: brightMode,
50+ font: font
51+ )
52+ continuation. resume ( returning: AttributedString ( content) )
53+ }
54+ }
55+ try Task . checkCancellation ( )
56+ await MainActor . run {
4957 self . highlighted = string
5058 }
5159 }
0 commit comments