-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathChatSection.swift
More file actions
383 lines (322 loc) · 12.5 KB
/
ChatSection.swift
File metadata and controls
383 lines (322 loc) · 12.5 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
import Client
import ComposableArchitecture
import SwiftUI
import Toast
import XcodeInspector
import SharedUIComponents
import Logger
struct ChatSection: View {
@AppStorage(\.autoAttachChatToXcode) var autoAttachChatToXcode
@AppStorage(\.enableFixError) var enableFixError
@State private var isEditorPreviewEnabled: Bool = false
var body: some View {
SettingsSection(title: "Chat Settings") {
// Copilot instructions - .github/copilot-instructions.md
CopilotInstructionSetting()
.padding(SettingsToggle.defaultPadding)
Divider()
// Custom Instructions - .github/instructions/*.instructions.md
PromptFileSetting(promptType: .instructions)
.padding(SettingsToggle.defaultPadding)
Divider()
if isEditorPreviewEnabled {
// Custom Prompts - .github/prompts/*.prompt.md
PromptFileSetting(promptType: .prompt)
.padding(SettingsToggle.defaultPadding)
Divider()
}
// Auto Attach toggle
SettingsToggle(
title: "Auto-attach Chat Window to Xcode",
isOn: $autoAttachChatToXcode
)
Divider()
// Fix error toggle
SettingsToggle(
title: "Quick fix for error",
isOn: $enableFixError
)
Divider()
// Response language picker
ResponseLanguageSetting()
.padding(SettingsToggle.defaultPadding)
Divider()
// Font Size
FontSizeSetting()
.padding(SettingsToggle.defaultPadding)
}
.onAppear {
Task {
await updateEditorPreviewFeatureFlag()
}
}
.onReceive(DistributedNotificationCenter.default()
.publisher(for: .gitHubCopilotFeatureFlagsDidChange)) { _ in
Task {
await updateEditorPreviewFeatureFlag()
}
}
}
private func updateEditorPreviewFeatureFlag() async {
do {
let service = try getService()
if let featureFlags = try await service.getCopilotFeatureFlags() {
isEditorPreviewEnabled = featureFlags.editorPreviewFeatures
}
} catch {
Logger.client.error("Failed to get copilot feature flags: \(error)")
}
}
}
struct ResponseLanguageSetting: View {
@AppStorage(\.chatResponseLocale) var chatResponseLocale
// Locale codes mapped to language display names
// reference: https://code.visualstudio.com/docs/configure/locales#_available-locales
private let localeLanguageMap: [String: String] = [
"en": "English",
"zh-cn": "Chinese, Simplified",
"zh-tw": "Chinese, Traditional",
"fr": "French",
"de": "German",
"it": "Italian",
"es": "Spanish",
"ja": "Japanese",
"ko": "Korean",
"ru": "Russian",
"pt-br": "Portuguese (Brazil)",
"tr": "Turkish",
"pl": "Polish",
"cs": "Czech",
"hu": "Hungarian",
]
var selectedLanguage: String {
if chatResponseLocale == "" {
return "English"
}
return localeLanguageMap[chatResponseLocale] ?? "English"
}
// Display name to locale code mapping (for the picker UI)
var sortedLanguageOptions: [(displayName: String, localeCode: String)] {
localeLanguageMap.map { (displayName: $0.value, localeCode: $0.key) }
.sorted { $0.displayName < $1.displayName }
}
var body: some View {
WithPerceptionTracking {
HStack {
VStack(alignment: .leading) {
Text("Response Language")
.font(.body)
Text("This change applies only to new chat sessions. Existing ones won't be impacted.")
.font(.footnote)
}
Spacer()
Picker("", selection: $chatResponseLocale) {
ForEach(sortedLanguageOptions, id: \.localeCode) { option in
Text(option.displayName).tag(option.localeCode)
}
}
.frame(maxWidth: 200, alignment: .trailing)
}
}
}
}
struct FontSizeSetting: View {
static let defaultSliderThumbRadius: CGFloat = Font.body.builtinSize
@AppStorage(\.chatFontSize) var chatFontSize
@ScaledMetric(relativeTo: .body) var scaledPadding: CGFloat = 100
@State private var sliderValue: Double = 0
@State private var textWidth: CGFloat = 0
@State private var sliderWidth: CGFloat = 0
@StateObject private var fontScaleManager: FontScaleManager = .shared
var maxSliderValue: Double {
FontScaleManager.maxScale * 100
}
var minSliderValue: Double {
FontScaleManager.minScale * 100
}
var defaultSliderValue: Double {
FontScaleManager.defaultScale * 100
}
var sliderFontSize: Double {
chatFontSize * sliderValue / 100
}
var maxScaleFontSize: Double {
FontScaleManager.maxScale * chatFontSize
}
var body: some View {
WithPerceptionTracking {
HStack {
VStack(alignment: .leading) {
Text("Font Size")
.font(.body)
Text("Use the slider to set the preferred size.")
.font(.footnote)
}
Spacer()
VStack(alignment: .leading, spacing: 0) {
HStack(alignment: .center, spacing: 8) {
Text("A")
.font(.system(size: sliderFontSize))
.frame(width: maxScaleFontSize)
Slider(value: $sliderValue, in: minSliderValue...maxSliderValue, step: 10) { _ in
fontScaleManager.setFontScale(sliderValue / 100)
}
.background(
GeometryReader { geometry in
Color.clear
.onAppear {
sliderWidth = geometry.size.width
}
}
)
Text("\(Int(sliderValue))%")
.font(.body)
.foregroundColor(.primary)
.frame(width: 40, alignment: .center)
}
.frame(height: maxScaleFontSize)
Text("Default")
.font(.caption)
.foregroundColor(.primary)
.background(
GeometryReader { geometry in
Color.clear
.onAppear {
textWidth = geometry.size.width
}
}
)
.padding(.leading, calculateDefaultMarkerXPosition() + 6)
.onHover {
if $0 {
NSCursor.pointingHand.push()
} else {
NSCursor.pop()
}
}
.onTapGesture {
fontScaleManager.resetFontScale()
}
}
.frame(width: 350, height: 35)
}
.onAppear {
sliderValue = fontScaleManager.currentScale * 100
}
.onChange(of: fontScaleManager.currentScale) {
// Use rounded value for floating-point precision issue
sliderValue = round($0 * 10) / 10 * 100
}
}
}
private func calculateDefaultMarkerXPosition() -> CGFloat {
let sliderRange = maxSliderValue - minSliderValue
let normalizedPosition = (defaultSliderValue - minSliderValue) / sliderRange
let usableWidth = sliderWidth - (Self.defaultSliderThumbRadius * 2)
let markerPosition = Self.defaultSliderThumbRadius + (CGFloat(normalizedPosition) * usableWidth)
return markerPosition - textWidth / 2 + maxScaleFontSize
}
}
struct CopilotInstructionSetting: View {
@State var isGlobalInstructionsViewOpen = false
@Environment(\.toast) var toast
var body: some View {
WithPerceptionTracking {
HStack {
VStack(alignment: .leading) {
Text("Copilot Instructions")
.font(.body)
Text("Configure `.github/copilot-instructions.md` to apply to all chat requests.")
.font(.footnote)
}
Spacer()
Button("Current Workspace") {
openCustomInstructions()
}
Button("Global") {
isGlobalInstructionsViewOpen = true
}
}
.sheet(isPresented: $isGlobalInstructionsViewOpen) {
GlobalInstructionsView(isOpen: $isGlobalInstructionsViewOpen)
}
}
}
func openCustomInstructions() {
Task {
guard let projectURL = await getCurrentProjectURL() else {
toast("No active workspace found", .error)
return
}
let configFile = projectURL.appendingPathComponent(".github/copilot-instructions.md")
// If the file doesn't exist, create one with a proper structure
if !FileManager.default.fileExists(atPath: configFile.path) {
do {
// Create directory if it doesn't exist using reusable helper
let gitHubDir = projectURL.appendingPathComponent(".github")
try ensureDirectoryExists(at: gitHubDir)
// Create empty file
try "".write(to: configFile, atomically: true, encoding: .utf8)
} catch {
toast("Failed to create config file .github/copilot-instructions.md: \(error)", .error)
}
}
if FileManager.default.fileExists(atPath: configFile.path) {
NSWorkspace.shared.open(configFile)
}
}
}
}
struct PromptFileSetting: View {
let promptType: PromptType
@State private var isCreateSheetPresented = false
@Environment(\.toast) var toast
var body: some View {
WithPerceptionTracking {
HStack {
VStack(alignment: .leading) {
Text(promptType.settingTitle)
.font(.body)
Text(
(try? AttributedString(markdown: promptType.description)) ?? AttributedString(
promptType.description
)
)
.font(.footnote)
}
Spacer()
Button("Create") {
isCreateSheetPresented = true
}
Button("Open \(promptType.directoryName.capitalized) Folder") {
openDirectory()
}
}
.sheet(isPresented: $isCreateSheetPresented) {
CreateCustomCopilotFileView(
isOpen: $isCreateSheetPresented,
promptType: promptType
)
}
}
}
private func openDirectory() {
Task {
guard let projectURL = await getCurrentProjectURL() else {
toast("No active workspace found", .error)
return
}
let directory = promptType.getDirectoryPath(projectURL: projectURL)
do {
try ensureDirectoryExists(at: directory)
NSWorkspace.shared.open(directory)
} catch {
toast("Failed to create \(promptType.directoryName) directory: \(error)", .error)
}
}
}
}
#Preview {
ChatSection()
.frame(width: 600)
}