forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNewCodeBlock.swift
More file actions
289 lines (246 loc) · 9.46 KB
/
NewCodeBlock.swift
File metadata and controls
289 lines (246 loc) · 9.46 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import STTextView
import SwiftUI
private let insetBottom = 12 as Double
private let insetTop = 12 as Double
/// This SwiftUI view can be used to view and edit rich text.
struct _CodeBlock: View {
@Binding private var selection: NSRange?
@State private var contentHeight: Double = 500
let fontSize: Double
let commonPrecedingSpaceCount: Int
let highlightedCode: AttributedString
let colorScheme: ColorScheme
/// Create a text edit view with a certain text that uses a certain options.
/// - Parameters:
/// - text: The attributed string content
/// - options: Editor options
/// - plugins: Editor plugins
public init(
code: String,
language: String,
firstLinePrecedingSpaceCount: Int,
colorScheme: ColorScheme,
fontSize: Double,
selection: Binding<NSRange?> = .constant(nil)
) {
_selection = selection
self.fontSize = fontSize
self.colorScheme = colorScheme
let padding = firstLinePrecedingSpaceCount > 0
? String(repeating: " ", count: firstLinePrecedingSpaceCount)
: ""
let result = Self.highlight(
code: padding + code,
language: language,
colorScheme: colorScheme,
fontSize: fontSize
)
commonPrecedingSpaceCount = result.commonLeadingSpaceCount
highlightedCode = result.code
}
public var body: some View {
_CodeBlockRepresentable(
text: highlightedCode,
selection: $selection,
fontSize: fontSize,
onHeightChange: { height in
print("Q", height)
contentHeight = height
}
)
.frame(height: contentHeight, alignment: .topLeading)
.background(.background)
.colorScheme(colorScheme)
.onAppear {
print("")
}
}
static func highlight(
code: String,
language: String,
colorScheme: ColorScheme,
fontSize: Double
) -> (code: AttributedString, commonLeadingSpaceCount: Int) {
let (lines, commonLeadingSpaceCount) = highlighted(
code: code,
language: language,
brightMode: colorScheme != .dark,
droppingLeadingSpaces: UserDefaults.shared
.value(for: \.hideCommonPrecedingSpacesInSuggestion),
fontSize: fontSize,
replaceSpacesWithMiddleDots: false
)
let string = NSMutableAttributedString()
for (index, line) in lines.enumerated() {
string.append(line)
if index < lines.count - 1 {
string.append(NSAttributedString(string: "\n"))
}
}
return (code: .init(string), commonLeadingSpaceCount: commonLeadingSpaceCount)
}
}
private struct _CodeBlockRepresentable: NSViewRepresentable {
@Environment(\.isEnabled) private var isEnabled
@Environment(\.lineSpacing) private var lineSpacing
@Binding private var selection: NSRange?
let text: AttributedString
let fontSize: Double
let onHeightChange: (Double) -> Void
init(
text: AttributedString,
selection: Binding<NSRange?>,
fontSize: Double,
onHeightChange: @escaping (Double) -> Void
) {
self.text = text
_selection = selection
self.fontSize = fontSize
self.onHeightChange = onHeightChange
}
func makeNSView(context: Context) -> NSScrollView {
let scrollView = STTextViewFrameObservable.scrollableTextView()
scrollView.contentInsets = .init(top: 0, left: 0, bottom: insetBottom, right: 0)
scrollView.automaticallyAdjustsContentInsets = false
let textView = scrollView.documentView as! STTextView
textView.delegate = context.coordinator
textView.highlightSelectedLine = false
textView.widthTracksTextView = true
textView.heightTracksTextView = true
textView.isEditable = true
textView.setSelectedRange(NSRange())
let lineNumberRuler = STLineNumberRulerView(textView: textView)
lineNumberRuler.backgroundColor = .clear
lineNumberRuler.separatorColor = .clear
lineNumberRuler.rulerInsets = .init(leading: 10, trailing: 10)
scrollView.verticalRulerView = lineNumberRuler
let columnNumberRuler = ColumnRuler(textView: textView)
scrollView.horizontalRulerView = columnNumberRuler
scrollView.rulersVisible = true
context.coordinator.isUpdating = true
textView.setAttributedString(NSAttributedString(text))
context.coordinator.isUpdating = false
return scrollView
}
func updateNSView(_ scrollView: NSScrollView, context: Context) {
context.coordinator.parent = self
let textView = scrollView.documentView as! STTextViewFrameObservable
textView.onHeightChange = onHeightChange
textView.showsInvisibleCharacters = true
textView.textContainer.lineBreakMode = .byCharWrapping
if let columnNumberRuler = scrollView.horizontalRulerView as? ColumnRuler {
columnNumberRuler.columnNumber = 5
}
do {
context.coordinator.isUpdating = true
if context.coordinator.isDidChangeText == false {
textView.setAttributedString(.init(text))
}
context.coordinator.isUpdating = false
context.coordinator.isDidChangeText = false
}
if textView.selectedRange() != selection, let selection {
textView.setSelectedRange(selection)
}
if textView.isSelectable != isEnabled {
textView.isSelectable = isEnabled
}
textView.isEditable = false
if !textView.widthTracksTextView {
textView.widthTracksTextView = false
}
if !textView.heightTracksTextView {
textView.heightTracksTextView = true
}
let font = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
if textView.font != font {
textView.font = font
}
}
func makeCoordinator() -> TextCoordinator {
TextCoordinator(parent: self)
}
private func styledAttributedString(_ typingAttributes: [NSAttributedString.Key: Any])
-> AttributedString
{
let paragraph = (typingAttributes[.paragraphStyle] as! NSParagraphStyle)
.mutableCopy() as! NSMutableParagraphStyle
if paragraph.lineSpacing != lineSpacing {
paragraph.lineSpacing = lineSpacing
var typingAttributes = typingAttributes
typingAttributes[.paragraphStyle] = paragraph
let attributeContainer = AttributeContainer(typingAttributes)
var styledText = text
styledText.mergeAttributes(attributeContainer, mergePolicy: .keepNew)
return styledText
}
return text
}
class TextCoordinator: STTextViewDelegate {
var parent: _CodeBlockRepresentable
var isUpdating: Bool = false
var isDidChangeText: Bool = false
var enqueuedValue: AttributedString?
init(parent: _CodeBlockRepresentable) {
self.parent = parent
}
func textViewDidChangeText(_ notification: Notification) {
guard let textView = notification.object as? STTextView else {
return
}
(textView as! STTextViewFrameObservable).recalculateSize()
}
func textViewDidChangeSelection(_ notification: Notification) {
guard let textView = notification.object as? STTextView else {
return
}
Task { @MainActor in
self.parent.selection = textView.selectedRange()
}
}
}
}
private class STTextViewFrameObservable: STTextView {
var onHeightChange: ((Double) -> Void)?
func recalculateSize() {
var maxY = 0 as Double
textLayoutManager.enumerateTextLayoutFragments(in: textLayoutManager.documentRange, options: [.ensuresLayout]) { fragment in
print(fragment.layoutFragmentFrame)
maxY = max(maxY, fragment.layoutFragmentFrame.maxY)
return true
}
onHeightChange?(maxY)
}
}
private final class ColumnRuler: NSRulerView {
var columnNumber: Int = 0
private var textView: STTextView? {
clientView as? STTextView
}
public required init(textView: STTextView, scrollView: NSScrollView? = nil) {
super.init(
scrollView: scrollView ?? textView.enclosingScrollView,
orientation: .verticalRuler
)
clientView = textView
ruleThickness = insetBottom
}
@available(*, unavailable)
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_: NSRect) {
guard let context: CGContext = NSGraphicsContext.current?.cgContext else { return }
NSColor.windowBackgroundColor.withAlphaComponent(0.6).setFill()
context.fill(bounds)
let insetLeft = scrollView?.verticalRulerView?.bounds.width ?? 0
var drawingBounds = bounds
drawingBounds.origin.x += insetLeft + 4
let fontSize = 10 as Double
drawingBounds.origin.y = (insetTop - fontSize) / 2
NSString(string: "\(columnNumber)").draw(in: drawingBounds, withAttributes: [
.font: NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular),
.foregroundColor: NSColor.tertiaryLabelColor,
])
}
}