Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

FeatureSourceControlView.swift

433 lines16.6 KB

1import SwiftUI
2​
3@MainActor
4func runFeatureSourceControlAction<Value>(
5 setRunning: (Bool) -> Void,
6 operation: () async throws -> Value
7) async -> Result<Value, Error> {
8 setRunning(true)
9 defer { setRunning(false) }
10​
11 do {
12 return .success(try await operation())
13 } catch {
14 return .failure(error)
15 }
17​
18public struct FeatureSourceControlView: View {
19 let client: any FeatureClient
20 let threadID: String
21​
22 @State private var status: FeatureSourceControlStatus?
23 @State private var isLoading = true
24 @State private var isRunningAction = false
25 @State private var runState = FeatureToolRunState<FeatureSourceControlOperation>()
26 @State private var recovery = FeatureToolFailureState<FeatureSourceControlOperation>()
27 @State private var errorMessage: String?
28 @State private var loadGeneration = 0
29 @State private var statusGeneration = 0
30 @State private var commitMessage = ""
31 @State private var pendingCommitAction: FeatureSourceControlAction?
32 @AccessibilityFocusState private var recoveryFocus: FeatureToolRecoveryFocus?
33​
34 public init(client: any FeatureClient, threadID: String) {
35 self.client = client
36 self.threadID = threadID
37 }
38​
39 public var body: some View {
40 VStack(spacing: 0) {
41 if let failure = recovery.failure {
42 failureBanner(failure)
43 }
44 Group {
45 if isLoading, status == nil {
46 ProgressView("Loading repository…")
47 .frame(maxWidth: .infinity, maxHeight: .infinity)
48 } else if let status, status.isRepository {
49 statusList(status)
50 } else {
51 ContentUnavailableView(
52 "Source control unavailable",
53 systemImage: "arrow.triangle.branch",
54 description: Text(
55 status?.isRepository == false
56 ? "This workspace is not a Git repository."
57 : "Repository status could not be loaded."
58 )
59 )
60 }
61 }
62 .frame(maxWidth: .infinity, maxHeight: .infinity)
63 }
64 .background(T3Colors.background)
65 .navigationTitle("Source Control")
66 .navigationBarTitleDisplayMode(.inline)
67 .toolbar {
68 ToolbarItem(placement: .topBarTrailing) {
69 Button { Task { await reload() } } label: {
70 if isLoading {
71 ProgressView()
72 } else {
73 Image(systemName: "arrow.clockwise")
74 }
75 }
76 .disabled(runState.isBusy)
77 .accessibilityLabel("Reload source control")
78 }
79 }
80 .alert("Commit changes", isPresented: Binding(
81 get: { pendingCommitAction != nil },
82 set: { if !$0 { pendingCommitAction = nil } }
83 )) {
84 TextField("Commit message", text: $commitMessage)
85 Button("Cancel", role: .cancel) { pendingCommitAction = nil }
86 Button("Commit") {
87 if let action = pendingCommitAction {
88 Task { await perform(action, message: commitMessage) }
89 }
90 pendingCommitAction = nil
91 }
92 .disabled(
93 commitMessage.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
94 || runState.isBusy
95 )
96 }
97 .onChange(of: recovery.failure?.id) { _, failureID in
98 guard failureID != nil else { return }
99 recoveryFocus = .failure
100 }
101 .onChange(of: recovery.recoveryAnnouncement) { _, _ in
102 guard let announcement = recovery.takeRecoveryAnnouncement() else { return }
103 recoveryFocus = .recoveredContent
104 AccessibilityNotification.Announcement(announcement).post()
105 }
106 .task { await load() }
107 }
108​
109 /// Keeps the failed output on screen — including while its retry runs — with a labelled
110 /// Retry control immediately after it in the accessibility order.
111 private func failureBanner(_ failure: FeatureToolFailure) -> some View {
112 VStack(alignment: .leading, spacing: 10) {
113 VStack(alignment: .leading, spacing: 6) {
114 Label(failure.title, systemImage: "exclamationmark.triangle.fill")
115 .font(T3Typography.supportingStrong)
116 .foregroundStyle(T3Colors.danger)
117 ScrollView {
118 Text(failure.message)
119 .font(T3Typography.tool)
120 .foregroundStyle(T3Colors.textSecondary)
121 .textSelection(.enabled)
122 .fixedSize(horizontal: false, vertical: true)
123 .frame(maxWidth: .infinity, alignment: .leading)
124 }
125 .frame(maxHeight: T3Metrics.maximumToolFailureMessageHeight)
126 }
127 .accessibilityElement(children: .combine)
128 .accessibilityLabel(failure.accessibilityLabel)
129 .accessibilityIdentifier("source-control-failure")
130 .accessibilityFocused($recoveryFocus, equals: .failure)
131​
132 HStack(spacing: 10) {
133 Button {
134 guard let operation = recovery.retryOperation else { return }
135 Task { await run(operation) }
136 } label: {
137 Label("Retry", systemImage: "arrow.clockwise")
138 .font(T3Typography.control)
139 .frame(minHeight: T3Metrics.minimumTapTarget)
140 }
141 .buttonStyle(.borderedProminent)
142 .disabled(failure.isRetrying || runState.isBusy)
143 .accessibilityLabel(failure.retryAccessibilityLabel)
144 .accessibilityIdentifier("source-control-failure-retry")
145​
146 if failure.isRetrying {
147 ProgressView()
148 Text("Retrying…")
149 .font(T3Typography.supporting)
150 .foregroundStyle(T3Colors.textSecondary)
151 }
152 }
153 }
154 .padding(14)
155 .frame(maxWidth: .infinity, alignment: .leading)
156 .background(T3Colors.surfaceRaised, in: RoundedRectangle(cornerRadius: 12))
157 .overlay {
158 RoundedRectangle(cornerRadius: 12)
159 .stroke(T3Colors.danger.opacity(0.4), lineWidth: 1)
160 }
161 .padding(.horizontal, 16)
162 .padding(.top, 12)
163 }
164​
165 private func statusList(_ status: FeatureSourceControlStatus) -> some View {
166 List {
167 // Once a status is on screen the unavailable-state view is
168 // unreachable, so a later failure needs its own inline surface.
169 if let errorMessage {
170 Section {
171 Label(errorMessage, systemImage: "exclamationmark.triangle")
172 .font(T3Typography.supporting)
173 .foregroundStyle(.orange)
174 }
175 }
176​
177 Section("Repository") {
178 LabeledContent("Branch", value: status.branch ?? "Detached HEAD")
179 .accessibilityFocused($recoveryFocus, equals: .recoveredContent)
180 if let upstream = status.upstream {
181 LabeledContent("Upstream", value: upstream)
182 }
183 if status.isRemoteKnown {
184 HStack {
185 Label("\(status.aheadCount) ahead", systemImage: "arrow.up")
186 Spacer()
187 Label("\(status.behindCount) behind", systemImage: "arrow.down")
188 }
189 .font(T3Typography.supporting)
190 .foregroundStyle(T3Colors.textSecondary)
191 } else {
192 // Only claim to be checking while something actually is.
193 Label(
194 isLoading ? "Checking remote…" : "Remote status unavailable",
195 systemImage: isLoading
196 ? "arrow.triangle.2.circlepath"
197 : "exclamationmark.triangle"
198 )
199 .font(T3Typography.supporting)
200 .foregroundStyle(T3Colors.textSecondary)
201 }
202 if let pullRequest = status.pullRequest {
203 if let url = pullRequest.url {
204 Link(destination: url) {
205 Label("PR #\(pullRequest.number) · \(pullRequest.title)", systemImage: "arrow.up.right.square")
206 }
207 } else {
208 LabeledContent("Pull Request", value: "#\(pullRequest.number) · \(pullRequest.state)")
209 }
210 }
211 }
212​
213 Section("Actions") {
214 if status.availableActions.isEmpty {
215 Text(status.isBusy ? "Source control operation in progress" : "No actions available")
216 .foregroundStyle(T3Colors.textSecondary)
217 }
218 ForEach(status.availableActions, id: \.self) { action in
219 Button {
220 begin(action)
221 } label: {
222 Label(action.title, systemImage: action.icon)
223 .frame(maxWidth: .infinity, alignment: .leading)
224 }
225 .disabled(runState.isBusy)
226 }
227 }
228​
229 Section("\(status.files.count) changed \(status.files.count == 1 ? "file" : "files")") {
230 if status.files.isEmpty {
231 Label("Working tree clean", systemImage: "checkmark.circle")
232 .foregroundStyle(T3Colors.textSecondary)
233 }
234 ForEach(status.files) { file in
235 HStack(spacing: 10) {
236 Text(file.state.shortLabel)
237 .font(.caption2.monospaced().weight(.bold))
238 .foregroundStyle(file.state.color)
239 .frame(width: 18)
240 Text(file.path)
241 .font(T3Typography.threadBody)
242 .lineLimit(1)
243 Spacer()
244 if file.isStaged {
245 Text("STAGED")
246 .font(T3Typography.eyebrow)
247 .foregroundStyle(.green)
248 }
249 }
250 .accessibilityElement(children: .combine)
251 }
252 }
253 }
254 .listStyle(.insetGrouped)
255 .scrollContentBackground(.hidden)
256 .refreshable { await reload() }
257 .overlay {
258 if isRunningAction {
259 ProgressView()
260 .padding(12)
261 .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 10))
262 }
263 }
264 }
265​
266 private func begin(_ action: FeatureSourceControlAction) {
267 if action.requiresMessage {
268 commitMessage = ""
269 pendingCommitAction = action
270 } else {
271 Task { await perform(action, message: nil) }
272 }
273 }
274​
275 /// Cached loading can be replaced by an action or an explicit refresh.
276 private func load() async {
277 await load(force: false)
278 }
279​
280 private func reload() async {
281 await load(force: true)
282 }
283​
284 private func load(force: Bool) async {
285 guard !runState.isBusy else { return }
286 if force, !runState.begin(.load) { return }
287 loadGeneration += 1
288 statusGeneration += 1
289 let loadID = loadGeneration
290 let statusID = statusGeneration
291 isLoading = true
292 recovery.begin(.load)
293 defer {
294 if loadID == loadGeneration { isLoading = false }
295 if force { runState.finish(.load) }
296 }
297 do {
298 try Task.checkCancellation()
299 if force {
300 let refreshed = try await client.sourceControlStatus(threadID: threadID)
301 guard statusID == statusGeneration else { return }
302 status = refreshed
303 errorMessage = nil
304 recovery.recordSuccess(.load)
305 } else {
306 let statuses = try await client.sourceControlStatuses(threadID: threadID)
307 for try await nextStatus in statuses {
308 guard statusID == statusGeneration else { return }
309 status = nextStatus
310 errorMessage = nil
311 if nextStatus.isRemoteKnown { recovery.recordSuccess(.load) }
312 }
313 }
314 } catch {
315 guard statusID == statusGeneration else { return }
316 if FeatureToolFailureState<FeatureSourceControlOperation>.isCancellation(error) {
317 recovery.recordFailure(.load, error: error)
318 return
319 }
320 // An unrelated status failure must not discard a failed action's retry.
321 if let retained = recovery.retryOperation, !retained.isLoad {
322 errorMessage = error.localizedDescription
323 } else {
324 recovery.recordFailure(.load, error: error)
325 }
326 guard !force, status?.isRemoteKnown == false else { return }
327 if loadID == loadGeneration { isLoading = false }
328 for await recoveredStatus in client.sourceControlStatusEvents(threadID: threadID) {
329 guard statusID == statusGeneration else { return }
330 status = recoveredStatus
331 if recoveredStatus.isRemoteKnown {
332 errorMessage = nil
333 recovery.recordSuccess(.load)
334 return
335 }
336 }
337 }
338 }
339​
340 private func perform(_ action: FeatureSourceControlAction, message: String?) async {
341 await run(
342 .action(action, message: message?.trimmingCharacters(in: .whitespacesAndNewlines))
343 )
344 }
345​
346 /// Mutations finish before refresh so Retry cannot repeat completed work.
347 private func run(_ operation: FeatureSourceControlOperation) async {
348 guard case let .action(action, message) = operation else {
349 await reload()
350 return
351 }
352 guard runState.begin(operation) else { return }
353 loadGeneration += 1
354 statusGeneration += 1
355 isLoading = false
356 recovery.begin(operation)
357 let result = await runFeatureSourceControlAction(
358 setRunning: { isRunningAction = $0 }
359 ) {
360 try await client.performSourceControlAction(
361 threadID: threadID,
362 action: action,
363 message: message
364 )
365 }
366 var shouldRecoverStatus = false
367 switch result {
368 case .success:
369 do {
370 status = try await client.sourceControlStatus(threadID: threadID)
371 errorMessage = nil
372 recovery.recordSuccess(operation, .load)
373 } catch {
374 recovery.recordFollowUpFailure(
375 .load,
376 afterCompletionOf: operation,
377 error: error
378 )
379 }
380 case let .failure(error):
381 recovery.recordFailure(operation, error: error)
382 shouldRecoverStatus = !FeatureToolFailureState<FeatureSourceControlOperation>
383 .isCancellation(error)
384 }
385 runState.finish(operation)
386 if shouldRecoverStatus {
387 await load(force: false)
388 }
389 }
391​
392private extension FeatureSourceControlAction {
393 var requiresMessage: Bool {
394 switch self {
395 case .commit, .commitAndPush, .commitPushAndCreatePullRequest: true
396 case .push, .pull, .createPullRequest: false
397 }
398 }
399​
400 var icon: String {
401 switch self {
402 case .commit: "checkmark.circle"
403 case .push: "arrow.up.circle"
404 case .pull: "arrow.down.circle"
405 case .createPullRequest: "arrow.triangle.pull"
406 case .commitAndPush: "arrow.up.circle.fill"
407 case .commitPushAndCreatePullRequest: "point.3.connected.trianglepath.dotted"
408 }
409 }
411​
412private extension FeatureSourceControlFileState {
413 var shortLabel: String {
414 switch self {
415 case .added: "A"
416 case .modified: "M"
417 case .deleted: "D"
418 case .renamed: "R"
419 case .untracked: "?"
420 case .conflicted: "!"
421 }
422 }
423​
424 var color: Color {
425 switch self {
426 case .added: .green
427 case .modified: .orange
428 case .deleted, .conflicted: .red
429 case .renamed: .blue
430 case .untracked: .secondary
431 }
432 }