11import SwiftUI
22
33struct CodeBlock : View {
4- @ObservedObject var suggestion : SuggestionProvider
54 @Environment ( \. colorScheme) var colorScheme
65
6+ let code : String
7+ let language : String
8+ let startLineIndex : Int
9+
10+ @State var commonPrecedingSpaceCount : Int = 0
11+ @State var highlightedCode : [ NSAttributedString ] = [ ]
12+
713 var body : some View {
814 VStack ( spacing: 4 ) {
9- let code = suggestion. highlightedCode ( colorScheme: colorScheme)
10- ForEach ( 0 ..< code. endIndex, id: \. self) { index in
15+ ForEach ( 0 ..< highlightedCode. endIndex, id: \. self) { index in
1116 HStack ( alignment: . firstTextBaseline, spacing: 4 ) {
12- Text ( " \( index + suggestion . startLineIndex + 1 ) " )
17+ Text ( " \( index + startLineIndex + 1 ) " )
1318 . multilineTextAlignment ( . trailing)
1419 . foregroundColor ( . secondary)
1520 . frame ( minWidth: 40 )
16- Text ( AttributedString ( code [ index] ) )
21+ Text ( AttributedString ( highlightedCode [ index] ) )
1722 . foregroundColor ( . white. opacity ( 0.1 ) )
1823 . frame ( maxWidth: . infinity, alignment: . leading)
1924 . multilineTextAlignment ( . leading)
2025 . lineSpacing ( 4 )
2126 . overlay ( alignment: . topLeading) {
22- if index == 0 , suggestion . commonPrecedingSpaceCount > 0 {
23- Text ( " \( suggestion . commonPrecedingSpaceCount + 1 ) " )
27+ if index == 0 , commonPrecedingSpaceCount > 0 {
28+ Text ( " \( commonPrecedingSpaceCount + 1 ) " )
2429 . padding ( . top, - 12 )
2530 . font ( . footnote)
2631 . foregroundStyle ( colorScheme == . dark ? . white : . black)
@@ -34,6 +39,30 @@ struct CodeBlock: View {
3439 . font ( . system( size: 12 , design: . monospaced) )
3540 . padding ( . leading, 4 )
3641 . padding ( [ . trailing, . top, . bottom] )
42+ . onChange ( of: code) { _ in
43+ highlightCode ( )
44+ }
45+ . onChange ( of: colorScheme) { _ in
46+ highlightCode ( )
47+ }
48+ . onChange ( of: language) { _ in
49+ highlightCode ( )
50+ }
51+ . onAppear {
52+ highlightCode ( )
53+ }
54+ }
55+
56+ func highlightCode( ) {
57+ let ( new, spaceCount) = highlighted (
58+ code: code,
59+ language: language,
60+ brightMode: colorScheme != . dark,
61+ droppingLeadingSpaces: UserDefaults . shared
62+ . value ( for: \. hideCommonPrecedingSpacesInSuggestion)
63+ )
64+ highlightedCode = new
65+ commonPrecedingSpaceCount = spaceCount
3766 }
3867}
3968
@@ -85,8 +114,12 @@ struct CodeBlockSuggestionPanel: View {
85114 var body : some View {
86115 VStack ( spacing: 0 ) {
87116 ScrollView {
88- CodeBlock ( suggestion: suggestion)
89- . frame ( maxWidth: . infinity)
117+ CodeBlock (
118+ code: suggestion. code,
119+ language: suggestion. language,
120+ startLineIndex: suggestion. startLineIndex
121+ )
122+ . frame ( maxWidth: . infinity)
90123 }
91124 . background ( Color . contentBackground)
92125
0 commit comments