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

T3ConnectView.swift

668 lines23.4 KB

1import ClerkKit
2import ClerkKitUI
3import SwiftUI
4​
5public struct T3ConnectView: View {
6 public enum Purpose: Sendable {
7 case connect
8 case manage
9 }
10​
11 @SwiftUI.Environment(\.dismiss) private var dismiss
12 @Bindable private var controller: T3ConnectController
13 @State private var isAuthPresented = false
14 @State private var didFinishInitialRefresh = false
15 @State private var connectingEnvironmentID: String?
16 @State private var isSigningOut = false
17 private let connectEnvironment:
18 @MainActor (T3ConnectManagedEnvironmentCredential) async throws -> Void
19 private let signOut: @MainActor () async -> Void
20 private let onConnected: @MainActor () async -> Void
21 private let onUnlinked: @MainActor (String) async -> Void
22 private let purpose: Purpose
23​
24 public init(
25 capability: any T3ConnectCapable,
26 model: FeatureRootModel? = nil,
27 purpose: Purpose = .connect,
28 onConnected: @escaping @MainActor () async -> Void = {},
29 onUnlinked: @escaping @MainActor (String) async -> Void = { _ in }
30 ) {
31 controller = capability.t3ConnectController
32 connectEnvironment = capability.connectT3Environment
33 signOut = if let model {
34 model.signOutT3Connect
35 } else {
36 capability.signOutT3Connect
37 }
38 self.purpose = purpose
39 self.onConnected = onConnected
40 self.onUnlinked = onUnlinked
41 }
42​
43 public var body: some View {
44 content
45 .navigationTitle("T3 Connect")
46 .navigationBarTitleDisplayMode(.inline)
47 .toolbarBackground(T3Colors.background, for: .navigationBar)
48 .toolbarBackground(.visible, for: .navigationBar)
49 .refreshable {
50 await controller.refresh()
51 }
52 .task {
53 await controller.refresh()
54 guard !Task.isCancelled else { return }
55 didFinishInitialRefresh = true
56 presentAuthenticationIfNeeded()
57 }
58 .onChange(of: controller.account?.id) { _, accountID in
59 guard didFinishInitialRefresh,
60 !isSigningOut,
61 accountID == nil,
62 controller.unavailableReason == nil else { return }
63 isAuthPresented = true
64 }
65 .fullScreenCover(
66 isPresented: $isAuthPresented,
67 onDismiss: handleAuthenticationDismissal
68 ) {
69 authenticationView
70 }
71 .alert(
72 "T3 Connect",
73 isPresented: Binding(
74 get: { controller.errorMessage != nil },
75 set: { if !$0 { controller.errorMessage = nil } }
76 )
77 ) {
78 Button("OK") { controller.errorMessage = nil }
79 } message: {
80 Text(controller.errorMessage ?? "Something went wrong.")
81 }
82 }
83​
84 @ViewBuilder
85 private var content: some View {
86 if let reason = controller.unavailableReason {
87 connectList {
88 unavailableSection(reason)
89 }
90 } else if let account = controller.account {
91 connectList {
92 environmentSection
93 accountSection(account)
94 }
95 } else if isSigningOut {
96 loadingView("Signing out")
97 } else if didFinishInitialRefresh {
98 signedOutView
99 } else {
100 loadingView("Checking account")
101 }
102 }
103​
104 private func connectList<Content: View>(
105 @ViewBuilder content: () -> Content
106 ) -> some View {
107 List {
108 content()
109 }
110 .listStyle(.plain)
111 .listSectionSpacing(28)
112 .scrollContentBackground(.hidden)
113 .background(T3Colors.background.ignoresSafeArea())
114 }
115​
116 private var signedOutView: some View {
117 VStack(alignment: .leading, spacing: 12) {
118 Text("Sign in to T3 Connect")
119 .font(.title2.bold())
120 .foregroundStyle(T3Colors.textPrimary)
121​
122 Text("Access environments linked to your account.")
123 .font(T3Typography.threadBody)
124 .foregroundStyle(T3Colors.textSecondary)
125​
126 Button("Sign in") {
127 isAuthPresented = true
128 }
129 .font(T3Typography.control.weight(.semibold))
130 .frame(minHeight: T3Metrics.minimumTapTarget)
131 .padding(.top, 4)
132 .accessibilityIdentifier("t3-connect-sign-in")
133 }
134 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
135 .padding(24)
136 .background(T3Colors.background.ignoresSafeArea())
137 }
138​
139 private func loadingView(_ message: String) -> some View {
140 VStack(spacing: 12) {
141 ProgressView()
142 .tint(T3Colors.textPrimary)
143 Text(message)
144 .font(T3Typography.supporting)
145 .foregroundStyle(T3Colors.textSecondary)
146 }
147 .frame(maxWidth: .infinity, maxHeight: .infinity)
148 .background(T3Colors.background.ignoresSafeArea())
149 .accessibilityElement(children: .combine)
150 }
151​
152 @ViewBuilder
153 private var authenticationView: some View {
154 if let clerk = controller.clerk {
155 T3ConnectAuthenticationView {
156 await controller.refreshAfterAuthentication()
157 if controller.account != nil {
158 isAuthPresented = false
159 return true
160 }
161 return false
162 }
163 .environment(\.clerkTheme, T3ConnectClerkAppearance.theme)
164 .environment(clerk)
165 } else {
166 loadingView("Loading sign-in")
167 }
168 }
169​
170 private func presentAuthenticationIfNeeded() {
171 guard controller.unavailableReason == nil,
172 controller.account == nil else { return }
173 isAuthPresented = true
174 }
175​
176 private func handleAuthenticationDismissal() {
177 Task {
178 await controller.refresh()
179 if controller.account == nil {
180 dismiss()
181 }
182 }
183 }
184​
185 private func unavailableSection(_ reason: String) -> some View {
186 Section {
187 VStack(alignment: .leading, spacing: 10) {
188 Label("T3 Connect unavailable", systemImage: "cloud.slash")
189 .font(T3Typography.homeTitle)
190 Text(reason)
191 .font(T3Typography.threadBody)
192 .foregroundStyle(T3Colors.textSecondary)
193 Text("You can still connect directly.")
194 .font(T3Typography.supporting)
195 .foregroundStyle(T3Colors.textTertiary)
196 }
197 .padding(.vertical, 8)
198 .listRowBackground(T3Colors.background)
199 }
200 }
201​
202 private func accountSection(_ account: T3ConnectAccount) -> some View {
203 Section("Account") {
204 HStack(spacing: 12) {
205 Image(systemName: "person.crop.circle.fill")
206 .font(.title2)
207 .foregroundStyle(T3Colors.textSecondary)
208 VStack(alignment: .leading, spacing: 2) {
209 Text(account.email ?? "T3 account")
210 .font(T3Typography.homeTitle)
211 Text("Signed in")
212 .font(T3Typography.supporting)
213 .foregroundStyle(T3Colors.textSecondary)
214 }
215 }
216 .padding(.vertical, 3)
217 .listRowBackground(T3Colors.background)
218 .accessibilityElement(children: .combine)
219​
220 Button(role: .destructive) {
221 handleSignOut()
222 } label: {
223 HStack {
224 Text("Sign out")
225 Spacer()
226 if isSigningOut {
227 ProgressView()
228 .controlSize(.small)
229 }
230 }
231 .frame(minHeight: T3Metrics.minimumTapTarget)
232 }
233 .disabled(controller.isRefreshing || isSigningOut || connectingEnvironmentID != nil)
234 .listRowBackground(T3Colors.background)
235 .accessibilityIdentifier("t3-connect-sign-out")
236 }
237 }
238​
239 private var environmentSection: some View {
240 Section("Environments") {
241 if controller.environments.isEmpty, !controller.isRefreshing {
242 VStack(alignment: .leading, spacing: 8) {
243 Text("No linked environments")
244 .font(T3Typography.homeTitle)
245 Text("Link an environment in T3 Code on your computer.")
246 .font(T3Typography.supporting)
247 .foregroundStyle(T3Colors.textSecondary)
248​
249 Button("Refresh") {
250 Task { await controller.refresh() }
251 }
252 .font(T3Typography.control)
253 .frame(minHeight: T3Metrics.minimumTapTarget)
254 .accessibilityIdentifier("t3-connect-refresh")
255 }
256 .padding(.top, 8)
257 .listRowBackground(T3Colors.background)
258 }
259​
260 ForEach(controller.environments) { item in
261 environmentRow(item)
262 .listRowBackground(T3Colors.background)
263 .swipeActions {
264 Button(role: .destructive) {
265 Task {
266 if await controller.unlink(item.environment) {
267 await onUnlinked(item.id)
268 }
269 }
270 } label: {
271 Label("Unlink", systemImage: "link.badge.minus")
272 }
273 }
274 }
275​
276 if controller.isRefreshing {
277 HStack(spacing: 10) {
278 ProgressView()
279 .controlSize(.small)
280 Text("Checking environments")
281 .font(T3Typography.supporting)
282 .foregroundStyle(T3Colors.textSecondary)
283 }
284 .frame(minHeight: T3Metrics.minimumTapTarget)
285 .listRowBackground(T3Colors.background)
286 .accessibilityElement(children: .combine)
287 }
288 }
289 }
290​
291 private func environmentRow(_ item: T3ConnectCloudEnvironment) -> some View {
292 HStack(spacing: 12) {
293 Circle()
294 .fill(statusColor(item))
295 .frame(width: 8, height: 8)
296 .accessibilityHidden(true)
297​
298 VStack(alignment: .leading, spacing: 3) {
299 Text(item.environment.label)
300 .font(T3Typography.homeTitle)
301 .foregroundStyle(T3Colors.textPrimary)
302 .lineLimit(1)
303 Text(statusText(item))
304 .font(T3Typography.supporting)
305 .foregroundStyle(
306 item.statusError == nil ? T3Colors.textSecondary : T3Colors.danger
307 )
308 .lineLimit(2)
309 }
310 .accessibilityElement(children: .combine)
311​
312 Spacer(minLength: 8)
313​
314 if purpose == .connect {
315 Button {
316 Task { await handleConnect(item.environment) }
317 } label: {
318 if controller.busyEnvironmentID == item.id
319 || connectingEnvironmentID == item.id {
320 ProgressView()
321 .frame(width: 54)
322 .accessibilityLabel("Connecting to \(item.environment.label)")
323 } else {
324 Text("Connect")
325 .font(T3Typography.supportingStrong)
326 }
327 }
328 .buttonStyle(.borderless)
329 .frame(minHeight: T3Metrics.minimumTapTarget)
330 .disabled(
331 controller.busyEnvironmentID != nil
332 || connectingEnvironmentID != nil
333 || item.status?.status == .offline
334 )
335 .accessibilityLabel("Connect to \(item.environment.label)")
336 .accessibilityHint(item.status?.status == .offline ? "Environment is offline" : "")
337 .accessibilityIdentifier("t3-connect-environment-\(item.id)")
338 }
339 }
340 .padding(.vertical, 5)
341 }
342​
343 private func handleSignOut() {
344 guard !isSigningOut else { return }
345 isSigningOut = true
346 Task {
347 await signOut()
348 isSigningOut = false
349 if controller.account == nil {
350 dismiss()
351 }
352 }
353 }
354​
355 private func handleConnect(_ environment: T3ConnectRelayEnvironment) async {
356 guard connectingEnvironmentID == nil else { return }
357 connectingEnvironmentID = environment.environmentId
358 defer {
359 if connectingEnvironmentID == environment.environmentId {
360 connectingEnvironmentID = nil
361 }
362 }
363 do {
364 let credential = try await controller.credential(for: environment)
365 try await connectEnvironment(credential)
366 await onConnected()
367 } catch {
368 controller.errorMessage = error.localizedDescription
369 }
370 }
371​
372 private func statusText(_ item: T3ConnectCloudEnvironment) -> String {
373 if let error = item.statusError { return error }
374 switch item.status?.status {
375 case .online: return "Online"
376 case .offline: return item.status?.error ?? "Offline"
377 case nil: return "Checking"
378 }
379 }
380​
381 private func statusColor(_ item: T3ConnectCloudEnvironment) -> Color {
382 if item.statusError != nil {
383 return T3Colors.danger
384 }
385 return switch item.status?.status {
386 case .online: T3Colors.success
387 case .offline: T3Colors.danger
388 case nil: T3Colors.textTertiary
389 }
390 }
392​
393@MainActor
394private struct T3ConnectAuthenticationView: View {
395 @SwiftUI.Environment(\.dismiss) private var dismiss
396 @SwiftUI.Environment(Clerk.self) private var clerk
397 @State private var activeProvider: OAuthProvider?
398 @State private var errorMessage: String?
399 @State private var isEmailPresented = false
400​
401 private let onAuthenticationChanged: @MainActor () async -> Bool
402 private let preferredProviders: [OAuthProvider] = [
403 .apple,
404 .github,
405 .google,
406 .microsoft,
407 ]
408​
409 init(
410 onAuthenticationChanged: @escaping @MainActor () async -> Bool
411 ) {
412 self.onAuthenticationChanged = onAuthenticationChanged
413 }
414​
415 var body: some View {
416 NavigationStack {
417 ScrollView {
418 VStack(alignment: .leading, spacing: 0) {
419 brand
420 .padding(.bottom, 38)
421​
422 Text("Sign in to T3 Connect")
423 .font(.system(.largeTitle, design: .default, weight: .bold))
424 .foregroundStyle(T3Colors.textPrimary)
425 .padding(.bottom, 10)
426​
427 Text("Access your linked environments.")
428 .font(T3Typography.threadBody)
429 .foregroundStyle(T3Colors.textSecondary)
430 .fixedSize(horizontal: false, vertical: true)
431 .padding(.bottom, 34)
432​
433 providerButtons
434​
435 emailButton
436 .padding(.top, 24)
437 }
438 .frame(maxWidth: 440, alignment: .leading)
439 .padding(.horizontal, 24)
440 .padding(.top, 34)
441 .padding(.bottom, 40)
442 .frame(maxWidth: .infinity)
443 }
444 .scrollBounceBehavior(.basedOnSize)
445 .background(T3Colors.background.ignoresSafeArea())
446 .toolbar {
447 ToolbarItem(placement: .topBarTrailing) {
448 Button {
449 dismiss()
450 } label: {
451 Image(systemName: "xmark")
452 .font(.system(size: 15, weight: .semibold))
453 .foregroundStyle(T3Colors.textSecondary)
454 .frame(width: T3Metrics.minimumTapTarget, height: T3Metrics.minimumTapTarget)
455 }
456 .buttonStyle(.plain)
457 .accessibilityLabel("Close")
458 .accessibilityIdentifier("t3-connect-auth-close")
459 }
460 }
461 .toolbarBackground(.hidden, for: .navigationBar)
462 }
463 .task {
464 if clerk.environment == nil {
465 _ = try? await clerk.refreshEnvironment()
466 }
467 }
468 .sheet(isPresented: $isEmailPresented, onDismiss: authenticationDidFinish) {
469 AuthView(mode: .signInOrUp)
470 .prefetchClerkImages()
471 .environment(\.clerkTheme, T3ConnectClerkAppearance.theme)
472 .environment(clerk)
473 }
474 .alert(
475 "Couldn’t sign in",
476 isPresented: Binding(
477 get: { errorMessage != nil },
478 set: { if !$0 { errorMessage = nil } }
479 )
480 ) {
481 Button("OK") { errorMessage = nil }
482 } message: {
483 Text(errorMessage ?? "Please try again.")
484 }
485 }
486​
487 private var brand: some View {
488 HStack(spacing: 10) {
489 Text("T3")
490 .font(.system(size: 14, weight: .heavy, design: .rounded))
491 .foregroundStyle(T3Colors.primaryActionForeground)
492 .frame(width: 32, height: 32)
493 .background(T3Colors.primaryAction)
494 .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
495​
496 Text("T3 Connect")
497 .font(T3Typography.homeTitle)
498 .foregroundStyle(T3Colors.textPrimary)
499 }
500 .accessibilityElement(children: .combine)
501 }
502​
503 @ViewBuilder
504 private var providerButtons: some View {
505 if clerk.environment == nil {
506 HStack(spacing: 10) {
507 ProgressView()
508 .tint(T3Colors.textPrimary)
509 Text("Loading sign-in options")
510 .font(T3Typography.control)
511 .foregroundStyle(T3Colors.textSecondary)
512 }
513 .frame(maxWidth: .infinity, minHeight: 56)
514 } else {
515 VStack(spacing: 12) {
516 ForEach(availableProviders) { provider in
517 providerButton(provider)
518 }
519 }
520 }
521 }
522​
523 private func providerButton(_ provider: OAuthProvider) -> some View {
524 Button {
525 Task { await signIn(with: provider) }
526 } label: {
527 HStack(spacing: 12) {
528 T3ConnectAuthProviderIcon(provider: provider)
529 .frame(width: 22, height: 22)
530​
531 Text("Continue with \(provider.name)")
532 .font(.system(.body, design: .default, weight: .semibold))
533 .foregroundStyle(T3Colors.textPrimary)
534​
535 Spacer(minLength: 8)
536​
537 if activeProvider == provider {
538 ProgressView()
539 .tint(T3Colors.textPrimary)
540 }
541 }
542 .padding(.horizontal, 18)
543 .frame(maxWidth: .infinity, minHeight: 56)
544 .background(T3Colors.surfaceRaised)
545 .overlay {
546 RoundedRectangle(cornerRadius: 14, style: .continuous)
547 .stroke(T3Colors.border, lineWidth: 1)
548 }
549 .clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))
550 .contentShape(RoundedRectangle(cornerRadius: 14, style: .continuous))
551 }
552 .buttonStyle(.plain)
553 .disabled(activeProvider != nil)
554 .opacity(activeProvider == nil || activeProvider == provider ? 1 : 0.55)
555 .accessibilityIdentifier("t3-connect-auth-\(provider.strategy)")
556 }
557​
558 private var emailButton: some View {
559 Button {
560 isEmailPresented = true
561 } label: {
562 HStack(spacing: 10) {
563 Image(systemName: "envelope")
564 .font(.system(size: 15, weight: .medium))
565 Text(availableProviders.isEmpty ? "Continue with email" : "Use email")
566 .font(T3Typography.control)
567 Spacer()
568 Image(systemName: "chevron.right")
569 .font(.system(size: 13, weight: .semibold))
570 }
571 .foregroundStyle(T3Colors.textSecondary)
572 .frame(maxWidth: .infinity, minHeight: T3Metrics.minimumTapTarget)
573 .contentShape(Rectangle())
574 }
575 .buttonStyle(.plain)
576 .disabled(activeProvider != nil)
577 .accessibilityIdentifier("t3-connect-auth-email")
578 }
579​
580 private var availableProviders: [OAuthProvider] {
581 guard let environment = clerk.environment else { return [] }
582 let enabledStrategies = Set(
583 environment.userSettings.social.values
584 .filter { $0.enabled && $0.authenticatable }
585 .map(\.strategy)
586 )
587 return preferredProviders.filter { enabledStrategies.contains($0.strategy) }
588 }
589​
590 private func signIn(with provider: OAuthProvider) async {
591 activeProvider = provider
592 defer { activeProvider = nil }
593​
594 do {
595 if provider == .apple {
596 try await clerk.auth.signInWithApple()
597 } else {
598 try await clerk.auth.signInWithOAuth(provider: provider)
599 }
600​
601 if !(await onAuthenticationChanged()) {
602 isEmailPresented = true
603 }
604 } catch {
605 errorMessage = error.localizedDescription
606 }
607 }
608​
609 private func authenticationDidFinish() {
610 Task { _ = await onAuthenticationChanged() }
611 }
613​
614private struct T3ConnectAuthProviderIcon: View {
615 let provider: OAuthProvider
616​
617 @ViewBuilder
618 var body: some View {
619 switch provider {
620 case .apple:
621 Image(systemName: "apple.logo")
622 .resizable()
623 .scaledToFit()
624 .foregroundStyle(T3Colors.textPrimary)
625 case .github:
626 Image("AuthGitHub")
627 .resizable()
628 .scaledToFit()
629 case .google:
630 Image("AuthGoogle")
631 .resizable()
632 .scaledToFit()
633 case .microsoft:
634 Image("AuthMicrosoft")
635 .resizable()
636 .scaledToFit()
637 default:
638 Image(systemName: "person.crop.circle")
639 .resizable()
640 .scaledToFit()
641 .foregroundStyle(T3Colors.textPrimary)
642 }
643 }
645​
646@MainActor
647private enum T3ConnectClerkAppearance {
648 static let theme = ClerkTheme(
649 colors: .init(
650 primary: T3Colors.primaryAction,
651 background: T3Colors.background,
652 input: T3Colors.input,
653 danger: T3Colors.danger,
654 success: T3Colors.success,
655 warning: T3Colors.warning,
656 foreground: T3Colors.textPrimary,
657 mutedForeground: T3Colors.textSecondary,
658 primaryForeground: T3Colors.primaryActionForeground,
659 inputForeground: T3Colors.textPrimary,
660 neutral: T3Colors.textPrimary,
661 ring: T3Colors.textPrimary,
662 muted: T3Colors.surfaceRaised,
663 shadow: T3Colors.border,
664 border: T3Colors.border
665 ),
666 design: .init(borderRadius: 12)
667 )