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

ProjectAndArchiveViews.swift

952 lines34.8 KB

1import SwiftUI
2​
3public struct AddProjectView: View {
4 private struct PendingCloneRegistration: Equatable {
5 let environmentID: String
6 let remoteURL: String
7 let destinationPath: String
8 let clonedPath: String
9 }
10​
11 private enum ProjectMode: String, CaseIterable, Identifiable {
12 case folder
13 case repository
14​
15 var id: String { rawValue }
16 var label: String { self == .folder ? "Folder" : "Clone" }
17 var icon: String { self == .folder ? "folder" : "arrow.down.circle" }
18 }
19​
20 private enum Field: Hashable {
21 case localPath
22 case repository
23 case destination
24 }
25​
26 @SwiftUI.Environment(\.dismiss) private var dismiss
27 @Bindable var model: FeatureRootModel
28​
29 @State private var selectedEnvironmentID: String?
30 @State private var mode = ProjectMode.folder
31 @State private var localPath = "~/"
32 @State private var source = ProjectRemoteSource.url
33 @State private var repositoryInput = ""
34 @State private var destinationPath = "~/"
35 @State private var resolvedRepository: SourceControlRepositoryInfo?
36 @State private var didEditDestination = false
37 @State private var pendingCloneRegistration: PendingCloneRegistration?
38​
39 @State private var browsePath = "~/"
40 @State private var browseResult: FilesystemBrowseResult?
41 @State private var isBrowsing = false
42 @State private var browseError: String?
43 @State private var browseRequestID: UUID?
44​
45 @State private var discovery: SourceControlDiscoveryResult?
46 @State private var isDiscovering = false
47 @State private var discoveryError: String?
48 @State private var discoveryRequestID: UUID?
49​
50 @State private var isSubmitting = false
51 @State private var errorMessage: String?
52 @State private var cloneRequestID: UUID?
53 @FocusState private var focusedField: Field?
54​
55 public init(model: FeatureRootModel) {
56 self.model = model
57 }
58​
59 public var body: some View {
60 NavigationStack {
61 Group {
62 if let environment = selectedEnvironment {
63 ScrollView {
64 LazyVStack(alignment: .leading, spacing: 22) {
65 if environments.count > 1 {
66 environmentPicker(environment)
67 }
68 modePicker
69 if let errorMessage {
70 errorBanner(errorMessage)
71 }
72 switch mode {
73 case .folder:
74 localProjectForm(environment)
75 case .repository:
76 repositoryProjectForm(environment)
77 }
78 if showsFolderBrowser {
79 folderBrowser(environment)
80 }
81 }
82 .padding(.horizontal, 18)
83 .padding(.top, 14)
84 .padding(.bottom, 32)
85 .disabled(isSubmitting)
86 }
87 .scrollDismissesKeyboard(.interactively)
88 } else {
89 ContentUnavailableView(
90 "Environment unavailable",
91 systemImage: "server.rack",
92 description: Text("Reconnect a T3 environment before adding a project.")
93 )
94 }
95 }
96 .background(T3Colors.background)
97 .navigationTitle("Add project")
98 .navigationBarTitleDisplayMode(.inline)
99 .t3NavigationChrome()
100 .toolbar {
101 ToolbarItem(placement: .cancellationAction) {
102 Button("Cancel") { dismiss() }
103 }
104 }
105 }
106 .onAppear(perform: selectEnvironmentIfNeeded)
107 .onChange(of: model.snapshot.environments) {
108 selectEnvironmentIfNeeded()
109 }
110 .onChange(of: source) {
111 resolvedRepository = nil
112 pendingCloneRegistration = nil
113 cloneRequestID = nil
114 updateSuggestedDestination()
115 errorMessage = nil
116 }
117 .onChange(of: repositoryInput) {
118 resolvedRepository = nil
119 pendingCloneRegistration = nil
120 cloneRequestID = nil
121 updateSuggestedDestination()
122 errorMessage = nil
123 }
124 .task(id: selectedEnvironmentID) {
125 guard selectedEnvironmentID != nil else { return }
126 resetEnvironmentState()
127 await loadDirectory(browsePath, updateSelection: false)
128 await loadDiscovery()
129 }
130 }
131​
132 private var projectClient: (any FeatureProjectCreationClient)? {
133 model.client as? any FeatureProjectCreationClient
134 }
135​
136 private var environments: [FeatureEnvironment] {
137 model.snapshot.environments
138 .filter(\.isEnabled)
139 .sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
140 }
141​
142 private var selectedEnvironment: FeatureEnvironment? {
143 environments.first { $0.id == selectedEnvironmentID && canCreateProject(in: $0) }
144 }
145​
146 private var sourceOptions: [ProjectRemoteSourceOption] {
147 ProjectRemoteSourceOptions.options(discovery: discovery)
148 }
149​
150 private var selectedSourceOption: ProjectRemoteSourceOption? {
151 sourceOptions.first { $0.source == source }
152 }
153​
154 private var needsRepositoryLookup: Bool {
155 source.provider != nil && resolvedRepository == nil
156 }
157​
158 private var showsFolderBrowser: Bool {
159 mode == .folder || !needsRepositoryLookup
160 }
161​
162 private var repositoryName: String {
163 ProjectCreationPath.repositoryName(
164 from: resolvedRepository?.nameWithOwner ?? repositoryInput
165 )
166 }
167​
168 private var modePicker: some View {
169 HStack(spacing: 24) {
170 ForEach(ProjectMode.allCases) { candidate in
171 Button {
172 focusedField = nil
173 errorMessage = nil
174 mode = candidate
175 } label: {
176 VStack(spacing: 9) {
177 Label(candidate.label, systemImage: candidate.icon)
178 .font(T3Typography.control)
179 .foregroundStyle(
180 mode == candidate ? T3Colors.textPrimary : T3Colors.textTertiary
181 )
182 Rectangle()
183 .fill(mode == candidate ? T3Colors.textPrimary : Color.clear)
184 .frame(height: 2)
185 }
186 .frame(maxWidth: .infinity)
187 .contentShape(Rectangle())
188 }
189 .buttonStyle(.plain)
190 }
191 }
192 .accessibilityElement(children: .contain)
193 }
194​
195 private func environmentPicker(_ environment: FeatureEnvironment) -> some View {
196 VStack(alignment: .leading, spacing: 8) {
197 sectionTitle("Environment")
198 Menu {
199 ForEach(environments) { option in
200 Button {
201 selectedEnvironmentID = option.id
202 } label: {
203 if option.id == environment.id {
204 Label(option.name, systemImage: "checkmark")
205 } else {
206 Text(option.name)
207 }
208 }
209 .disabled(!canCreateProject(in: option))
210 }
211 } label: {
212 HStack(spacing: 10) {
213 Image(systemName: environment.systemImage)
214 VStack(alignment: .leading, spacing: 2) {
215 Text(environment.name)
216 .font(T3Typography.control)
217 .foregroundStyle(T3Colors.textPrimary)
218 Text(environment.endpoint)
219 .font(T3Typography.supporting)
220 .foregroundStyle(T3Colors.textTertiary)
221 .lineLimit(1)
222 }
223 Spacer(minLength: 12)
224 Image(systemName: "chevron.up.chevron.down")
225 .font(.caption.weight(.semibold))
226 .foregroundStyle(T3Colors.textTertiary)
227 }
228 .padding(.horizontal, 13)
229 .frame(minHeight: 52)
230 .background(T3Colors.input, in: RoundedRectangle(cornerRadius: 12))
231 .overlay {
232 RoundedRectangle(cornerRadius: 12).stroke(T3Colors.border, lineWidth: 1)
233 }
234 }
235 .buttonStyle(.plain)
236 }
237 }
238​
239 private func localProjectForm(_ environment: FeatureEnvironment) -> some View {
240 VStack(alignment: .leading, spacing: 10) {
241 HStack(alignment: .firstTextBaseline) {
242 sectionTitle("Workspace path")
243 Spacer()
244 Text("on \(environment.name)")
245 .font(T3Typography.supporting)
246 .foregroundStyle(T3Colors.textTertiary)
247 }
248 pathField(
249 placeholder: "~/projects/my-app",
250 text: $localPath,
251 field: .localPath,
252 browseAction: {
253 Task {
254 await loadDirectory(
255 ProjectCreationPath.directoryBrowsePath(localPath),
256 updateSelection: false
257 )
258 }
259 }
260 )
261 primaryAction(label: "Add project", icon: "plus") {
262 await addLocalProject(environment)
263 }
264 }
265 }
266​
267 private func repositoryProjectForm(_ environment: FeatureEnvironment) -> some View {
268 VStack(alignment: .leading, spacing: 16) {
269 VStack(alignment: .leading, spacing: 8) {
270 HStack {
271 sectionTitle("Repository source")
272 if isDiscovering {
273 ProgressView().controlSize(.small)
274 }
275 }
276 sourcePicker
277 if let discoveryError {
278 Label(discoveryError, systemImage: "info.circle")
279 .font(T3Typography.supporting)
280 .foregroundStyle(T3Colors.textTertiary)
281 }
282 }
283​
284 VStack(alignment: .leading, spacing: 8) {
285 sectionTitle(source == .url ? "Remote URL" : "Repository")
286 TextField(source.prompt, text: $repositoryInput)
287 .textInputAutocapitalization(.never)
288 .autocorrectionDisabled()
289 .keyboardType(source == .url ? .URL : .default)
290 .submitLabel(needsRepositoryLookup ? .next : .done)
291 .focused($focusedField, equals: .repository)
292 .onSubmit {
293 Task {
294 if needsRepositoryLookup {
295 await resolveRepository(environment)
296 } else {
297 focusedField = .destination
298 }
299 }
300 }
301 .t3ProjectInput()
302 }
303​
304 if let resolvedRepository {
305 repositorySummary(resolvedRepository)
306 }
307​
308 if needsRepositoryLookup {
309 primaryAction(label: "Find repository", icon: "magnifyingglass") {
310 await resolveRepository(environment)
311 }
312 } else {
313 VStack(alignment: .leading, spacing: 8) {
314 HStack(alignment: .firstTextBaseline) {
315 sectionTitle("Clone destination")
316 Spacer()
317 Text("on \(environment.name)")
318 .font(T3Typography.supporting)
319 .foregroundStyle(T3Colors.textTertiary)
320 }
321 pathField(
322 placeholder: "~/projects/\(repositoryName)",
323 text: destinationBinding,
324 field: .destination,
325 browseAction: nil
326 )
327 }
328 primaryAction(label: "Clone and add", icon: "arrow.down.circle") {
329 await cloneProject(environment)
330 }
331 }
332 }
333 }
334​
335 private var sourcePicker: some View {
336 Menu {
337 ForEach(sourceOptions) { option in
338 Button {
339 source = option.source
340 } label: {
341 if option.source == source {
342 Label(option.source.label, systemImage: "checkmark")
343 } else if let detail = option.detail {
344 Text("\(option.source.label) · \(detail)")
345 } else {
346 Text(option.source.label)
347 }
348 }
349 .disabled(!option.isReady)
350 }
351 } label: {
352 HStack(spacing: 10) {
353 Image(systemName: sourceIcon(source))
354 .frame(width: 22)
355 VStack(alignment: .leading, spacing: 2) {
356 Text(source.label)
357 .font(T3Typography.control)
358 .foregroundStyle(T3Colors.textPrimary)
359 if let detail = selectedSourceOption?.detail {
360 Text(detail)
361 .font(T3Typography.supporting)
362 .foregroundStyle(T3Colors.textTertiary)
363 .lineLimit(1)
364 }
365 }
366 Spacer(minLength: 12)
367 Image(systemName: "chevron.up.chevron.down")
368 .font(.caption.weight(.semibold))
369 .foregroundStyle(T3Colors.textTertiary)
370 }
371 .padding(.horizontal, 13)
372 .frame(minHeight: 52)
373 .background(T3Colors.input, in: RoundedRectangle(cornerRadius: 12))
374 .overlay {
375 RoundedRectangle(cornerRadius: 12).stroke(T3Colors.border, lineWidth: 1)
376 }
377 }
378 .buttonStyle(.plain)
379 }
380​
381 private func repositorySummary(_ repository: SourceControlRepositoryInfo) -> some View {
382 HStack(alignment: .top, spacing: 11) {
383 Image(systemName: sourceIcon(source))
384 .font(.body.weight(.semibold))
385 .foregroundStyle(T3Colors.textSecondary)
386 .frame(width: 24)
387 VStack(alignment: .leading, spacing: 3) {
388 Text(repository.nameWithOwner)
389 .font(T3Typography.control)
390 .foregroundStyle(T3Colors.textPrimary)
391 Text(repository.sshUrl)
392 .font(T3Typography.supporting.monospaced())
393 .foregroundStyle(T3Colors.textTertiary)
394 .lineLimit(2)
395 }
396 Spacer(minLength: 0)
397 Image(systemName: "checkmark.circle.fill")
398 .foregroundStyle(T3Colors.success)
399 }
400 .padding(.vertical, 4)
401 }
402​
403 private func folderBrowser(_ environment: FeatureEnvironment) -> some View {
404 VStack(alignment: .leading, spacing: 8) {
405 HStack {
406 sectionTitle("Folders on \(environment.name)")
407 Spacer()
408 if isBrowsing {
409 ProgressView().controlSize(.small)
410 } else {
411 Button {
412 Task { await loadDirectory(browsePath, updateSelection: false) }
413 } label: {
414 Image(systemName: "arrow.clockwise")
415 .frame(width: 32, height: 32)
416 }
417 .buttonStyle(.plain)
418 .foregroundStyle(T3Colors.textSecondary)
419 .accessibilityLabel("Refresh folders")
420 }
421 }
422​
423 Text(browsePath)
424 .font(T3Typography.supporting.monospaced())
425 .foregroundStyle(T3Colors.textTertiary)
426 .lineLimit(1)
427 .truncationMode(.middle)
428​
429 Divider().overlay(T3Colors.separator)
430 if let browseError {
431 Text(browseError)
432 .font(T3Typography.supporting)
433 .foregroundStyle(T3Colors.warning)
434 .padding(.vertical, 8)
435 }
436 if let parentPath = ProjectCreationPath.parentBrowsePath(of: browsePath) {
437 folderRow(name: "..", icon: "arrow.turn.left.up") {
438 await loadDirectory(parentPath, updateSelection: true)
439 }
440 }
441 if let entries = browseResult?.entries, !entries.isEmpty {
442 ForEach(entries, id: \.fullPath) { entry in
443 Divider().overlay(T3Colors.separator)
444 folderRow(name: entry.name, icon: "folder") {
445 await loadDirectory(
446 ProjectCreationPath.directoryBrowsePath(entry.fullPath),
447 updateSelection: true
448 )
449 }
450 }
451 } else if !isBrowsing, browseError == nil {
452 Text("No folders here")
453 .font(T3Typography.supporting)
454 .foregroundStyle(T3Colors.textTertiary)
455 .frame(maxWidth: .infinity, minHeight: 54, alignment: .center)
456 }
457 }
458 }
459​
460 private func folderRow(
461 name: String,
462 icon: String,
463 action: @escaping @MainActor () async -> Void
464 ) -> some View {
465 Button {
466 focusedField = nil
467 Task { await action() }
468 } label: {
469 HStack(spacing: 11) {
470 Image(systemName: icon)
471 .font(.body.weight(.medium))
472 .foregroundStyle(T3Colors.textSecondary)
473 .frame(width: 24)
474 Text(name)
475 .font(.body.weight(.medium))
476 .foregroundStyle(T3Colors.textPrimary)
477 .lineLimit(1)
478 Spacer(minLength: 12)
479 Image(systemName: "chevron.right")
480 .font(.caption.weight(.semibold))
481 .foregroundStyle(T3Colors.textTertiary)
482 }
483 .frame(minHeight: T3Metrics.minimumTapTarget)
484 .contentShape(Rectangle())
485 }
486 .buttonStyle(.plain)
487 .disabled(isBrowsing)
488 }
489​
490 private func sectionTitle(_ title: String) -> some View {
491 Text(title)
492 .font(T3Typography.supportingStrong)
493 .foregroundStyle(T3Colors.textSecondary)
494 }
495​
496 private func pathField(
497 placeholder: String,
498 text: Binding<String>,
499 field: Field,
500 browseAction: (() -> Void)?
501 ) -> some View {
502 HStack(spacing: 4) {
503 TextField(placeholder, text: text)
504 .textInputAutocapitalization(.never)
505 .autocorrectionDisabled()
506 .submitLabel(.done)
507 .focused($focusedField, equals: field)
508 if let browseAction {
509 Button(action: browseAction) {
510 Image(systemName: "folder")
511 .frame(width: 36, height: 36)
512 }
513 .buttonStyle(.plain)
514 .foregroundStyle(T3Colors.textSecondary)
515 .accessibilityLabel("Browse entered path")
516 }
517 }
518 .t3ProjectInput()
519 }
520​
521 private func primaryAction(
522 label: String,
523 icon: String,
524 action: @escaping @MainActor () async -> Void
525 ) -> some View {
526 Button {
527 focusedField = nil
528 Task { await action() }
529 } label: {
530 HStack(spacing: 8) {
531 if isSubmitting {
532 ProgressView()
533 .tint(T3Colors.primaryActionForeground)
534 } else {
535 Image(systemName: icon)
536 }
537 Text(isSubmitting ? "Working…" : label)
538 }
539 .font(.body.weight(.semibold))
540 .foregroundStyle(T3Colors.primaryActionForeground)
541 .frame(maxWidth: .infinity, minHeight: 48)
542 .background(T3Colors.primaryAction, in: RoundedRectangle(cornerRadius: 12))
543 }
544 .buttonStyle(.plain)
545 .disabled(isSubmitting)
546 .opacity(isSubmitting ? 0.66 : 1)
547 }
548​
549 private func errorBanner(_ message: String) -> some View {
550 HStack(alignment: .top, spacing: 9) {
551 Image(systemName: "exclamationmark.triangle.fill")
552 Text(message)
553 .font(T3Typography.supporting)
554 .frame(maxWidth: .infinity, alignment: .leading)
555 }
556 .foregroundStyle(T3Colors.danger)
557 .padding(12)
558 .background(T3Colors.danger.opacity(0.08), in: RoundedRectangle(cornerRadius: 10))
559 }
560​
561 private var destinationBinding: Binding<String> {
562 Binding(
563 get: { destinationPath },
564 set: { value in
565 didEditDestination = true
566 destinationPath = value
567 pendingCloneRegistration = nil
568 cloneRequestID = nil
569 }
570 )
571 }
572​
573 private func canCreateProject(in environment: FeatureEnvironment) -> Bool {
574 environment.isEnabled && environment.connectionState != .disconnected
575 }
576​
577 private func selectEnvironmentIfNeeded() {
578 if let selectedEnvironmentID,
579 environments.contains(where: {
580 $0.id == selectedEnvironmentID && canCreateProject(in: $0)
581 }) {
582 return
583 }
584 selectedEnvironmentID = environments.first(where: canCreateProject)?.id
585 }
586​
587 private func resetEnvironmentState() {
588 browsePath = "~/"
589 browseResult = nil
590 browseError = nil
591 browseRequestID = nil
592 discovery = nil
593 discoveryError = nil
594 discoveryRequestID = nil
595 source = .url
596 resolvedRepository = nil
597 pendingCloneRegistration = nil
598 cloneRequestID = nil
599 didEditDestination = false
600 localPath = "~/"
601 destinationPath = repositoryInput.isEmpty
602 ? "~/"
603 : ProjectCreationPath.appending(repositoryName, to: "~/")
604 errorMessage = nil
605 }
606​
607 private func loadDiscovery() async {
608 guard let environmentID = selectedEnvironmentID,
609 let projectClient else {
610 discoveryError = "Git URL cloning is available. Provider discovery is unavailable."
611 return
612 }
613 let requestID = UUID()
614 discoveryRequestID = requestID
615 isDiscovering = true
616 defer {
617 if discoveryRequestID == requestID {
618 isDiscovering = false
619 }
620 }
621 do {
622 let result = try await projectClient.discoverProjectSources(
623 environmentID: environmentID
624 )
625 guard discoveryRequestID == requestID,
626 selectedEnvironmentID == environmentID else {
627 return
628 }
629 discovery = result
630 discoveryError = nil
631 } catch is CancellationError {
632 return
633 } catch {
634 guard discoveryRequestID == requestID,
635 selectedEnvironmentID == environmentID else {
636 return
637 }
638 discovery = nil
639 discoveryError = "Provider discovery unavailable. Git URL still works."
640 }
641 }
642​
643 private func loadDirectory(_ path: String, updateSelection: Bool) async {
644 guard let environmentID = selectedEnvironmentID,
645 let projectClient else {
646 browseError = "Folder browsing is unavailable. You can still enter a path directly."
647 return
648 }
649 let requestedPath = path.trimmingCharacters(in: .whitespacesAndNewlines)
650 guard !requestedPath.isEmpty else { return }
651 let requestID = UUID()
652 browseRequestID = requestID
653 isBrowsing = true
654 browseError = nil
655 defer {
656 if browseRequestID == requestID {
657 isBrowsing = false
658 }
659 }
660 do {
661 let result = try await projectClient.browseProjectFolders(
662 environmentID: environmentID,
663 partialPath: requestedPath
664 )
665 guard browseRequestID == requestID,
666 selectedEnvironmentID == environmentID else {
667 return
668 }
669 let selectedDirectory = result.parentPath
670 browsePath = ProjectCreationPath.directoryBrowsePath(selectedDirectory)
671 browseResult = result
672 if updateSelection {
673 switch mode {
674 case .folder:
675 localPath = selectedDirectory
676 case .repository:
677 if !didEditDestination {
678 pendingCloneRegistration = nil
679 destinationPath = ProjectCreationPath.appending(
680 repositoryName,
681 to: selectedDirectory
682 )
683 }
684 }
685 }
686 } catch is CancellationError {
687 return
688 } catch {
689 guard browseRequestID == requestID,
690 selectedEnvironmentID == environmentID else {
691 return
692 }
693 browseError = "Couldn’t browse that folder. Direct path entry still works."
694 }
695 }
696​
697 private func addLocalProject(_ environment: FeatureEnvironment) async {
698 errorMessage = nil
699 let validated: String
700 switch ProjectCreationPath.validated(localPath) {
701 case let .success(path): validated = path
702 case let .failure(error):
703 errorMessage = error.localizedDescription
704 return
705 }
706 if let serverPath = browseResult?.parentPath,
707 !ProjectCreationPath.isCompatibleWithServerPath(
708 validated,
709 serverPath: serverPath
710 ) {
711 errorMessage = "Use a path that matches \(environment.name)’s filesystem."
712 return
713 }
714 if let existing = existingProject(environmentID: environment.id, path: validated) {
715 errorMessage = "\(existing.name) already uses this folder."
716 return
717 }
718​
719 isSubmitting = true
720 defer { isSubmitting = false }
721 do {
722 if let projectClient {
723 try await projectClient.addProject(
724 environmentID: environment.id,
725 path: validated
726 )
727 dismiss()
728 } else if environments.count == 1, await model.addProject(path: validated) {
729 dismiss()
730 } else {
731 errorMessage = model.errorMessage ?? "The project could not be added."
732 }
733 } catch is CancellationError {
734 return
735 } catch {
736 errorMessage = projectErrorMessage(error)
737 }
738 }
739​
740 private func resolveRepository(_ environment: FeatureEnvironment) async {
741 guard let provider = source.provider else { return }
742 let repository = repositoryInput.trimmingCharacters(in: .whitespacesAndNewlines)
743 guard !repository.isEmpty else {
744 errorMessage = "Enter a repository name."
745 return
746 }
747 guard let projectClient else {
748 errorMessage = "Repository lookup is unavailable on this connection."
749 return
750 }
751​
752 errorMessage = nil
753 isSubmitting = true
754 defer { isSubmitting = false }
755 do {
756 let result = try await projectClient.lookupProjectRepository(
757 environmentID: environment.id,
758 provider: provider,
759 repository: repository
760 )
761 guard selectedEnvironmentID == environment.id,
762 source.provider == provider,
763 repositoryInput.trimmingCharacters(in: .whitespacesAndNewlines)
764 == repository else {
765 return
766 }
767 resolvedRepository = result
768 updateSuggestedDestination()
769 focusedField = .destination
770 } catch is CancellationError {
771 return
772 } catch {
773 guard selectedEnvironmentID == environment.id,
774 source.provider == provider,
775 repositoryInput.trimmingCharacters(in: .whitespacesAndNewlines)
776 == repository else {
777 return
778 }
779 errorMessage = projectErrorMessage(error)
780 }
781 }
782​
783 private func cloneProject(_ environment: FeatureEnvironment) async {
784 let remoteURL = resolvedRepository.map(ProjectCreationPath.defaultCloneURL)
785 ?? ProjectCreationPath.normalizedCloneURL(repositoryInput)
786 guard !remoteURL.isEmpty else {
787 errorMessage = "Enter a Git remote URL."
788 return
789 }
790 let validatedDestination: String
791 switch ProjectCreationPath.validated(destinationPath) {
792 case let .success(path): validatedDestination = path
793 case let .failure(error):
794 errorMessage = error.localizedDescription
795 return
796 }
797 if let serverPath = browseResult?.parentPath,
798 !ProjectCreationPath.isCompatibleWithServerPath(
799 validatedDestination,
800 serverPath: serverPath
801 ) {
802 errorMessage = "Use a path that matches \(environment.name)’s filesystem."
803 return
804 }
805 if let existing = existingProject(
806 environmentID: environment.id,
807 path: validatedDestination
808 ) {
809 errorMessage = "\(existing.name) already uses this destination."
810 return
811 }
812 guard let projectClient else {
813 errorMessage = "Repository cloning is unavailable on this connection."
814 return
815 }
816​
817 errorMessage = nil
818 let requestID = UUID()
819 cloneRequestID = requestID
820 isSubmitting = true
821 defer {
822 isSubmitting = false
823 if cloneRequestID == requestID {
824 cloneRequestID = nil
825 }
826 }
827 do {
828 let clonedPath: String
829 if let pending = pendingCloneRegistration,
830 pending.environmentID == environment.id,
831 pending.remoteURL == remoteURL,
832 pending.destinationPath == validatedDestination {
833 clonedPath = pending.clonedPath
834 } else {
835 let result = try await projectClient.cloneProjectRepository(
836 environmentID: environment.id,
837 remoteURL: remoteURL,
838 destinationPath: validatedDestination
839 )
840 guard cloneRequestIsCurrent(
841 requestID,
842 environmentID: environment.id,
843 remoteURL: remoteURL,
844 destinationPath: validatedDestination
845 ) else {
846 return
847 }
848 clonedPath = result.cwd
849 pendingCloneRegistration = PendingCloneRegistration(
850 environmentID: environment.id,
851 remoteURL: remoteURL,
852 destinationPath: validatedDestination,
853 clonedPath: result.cwd
854 )
855 }
856 guard cloneRequestIsCurrent(
857 requestID,
858 environmentID: environment.id,
859 remoteURL: remoteURL,
860 destinationPath: validatedDestination
861 ) else {
862 return
863 }
864 try await projectClient.addProject(
865 environmentID: environment.id,
866 path: clonedPath
867 )
868 guard cloneRequestIsCurrent(
869 requestID,
870 environmentID: environment.id,
871 remoteURL: remoteURL,
872 destinationPath: validatedDestination
873 ) else {
874 return
875 }
876 pendingCloneRegistration = nil
877 dismiss()
878 } catch is CancellationError {
879 return
880 } catch {
881 guard cloneRequestIsCurrent(
882 requestID,
883 environmentID: environment.id,
884 remoteURL: remoteURL,
885 destinationPath: validatedDestination
886 ) else {
887 return
888 }
889 if pendingCloneRegistration != nil {
890 errorMessage = "Repository cloned. Try again to finish adding the project."
891 } else {
892 errorMessage = projectErrorMessage(error)
893 }
894 }
895 }
896​
897 private func cloneRequestIsCurrent(
898 _ requestID: UUID,
899 environmentID: String,
900 remoteURL: String,
901 destinationPath: String
902 ) -> Bool {
903 let currentRemoteURL = resolvedRepository?.sshUrl
904 ?? ProjectCreationPath.normalizedCloneURL(repositoryInput)
905 return cloneRequestID == requestID
906 && selectedEnvironmentID == environmentID
907 && currentRemoteURL == remoteURL
908 && self.destinationPath.trimmingCharacters(in: .whitespacesAndNewlines)
909 == destinationPath
910 }
911​
912 private func updateSuggestedDestination() {
913 guard !didEditDestination, !repositoryInput.isEmpty else { return }
914 destinationPath = ProjectCreationPath.appending(repositoryName, to: browsePath)
915 }
916​
917 private func existingProject(environmentID: String, path: String) -> FeatureProject? {
918 let normalized = ProjectCreationPath.normalizedForComparison(path)
919 return model.snapshot.projects.first {
920 $0.environmentID == environmentID
921 && ProjectCreationPath.normalizedForComparison($0.path) == normalized
922 }
923 }
924​
925 private func sourceIcon(_ source: ProjectRemoteSource) -> String {
926 switch source {
927 case .url: "link"
928 case .github: "chevron.left.forwardslash.chevron.right"
929 case .gitlab: "shippingbox"
930 case .bitbucket: "shippingbox.fill"
931 case .azureDevOps: "point.3.connected.trianglepath.dotted"
932 }
933 }
934​
935 private func projectErrorMessage(_ error: Error) -> String {
936 let message = error.localizedDescription.trimmingCharacters(in: .whitespacesAndNewlines)
937 return message.isEmpty ? "The server could not complete that request." : message
938 }
940​
941private extension View {
942 func t3ProjectInput() -> some View {
943 font(.body)
944 .foregroundStyle(T3Colors.textPrimary)
945 .padding(.horizontal, 13)
946 .frame(minHeight: 48)
947 .background(T3Colors.input, in: RoundedRectangle(cornerRadius: 12))
948 .overlay {
949 RoundedRectangle(cornerRadius: 12).stroke(T3Colors.border, lineWidth: 1)
950 }
951 }