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

ConnectionOnboardingView.swift

717 lines25.8 KB

1import SwiftUI
2import UIKit
3​
4public struct ConnectionOnboardingView: View {
5 @SwiftUI.Environment(\.scenePhase) private var scenePhase
6 @Bindable private var model: FeatureRootModel
7​
8 private let readinessChecker: any ConnectionReadinessChecking
9 private let onConnected: @MainActor () -> Void
10 private let onCancel: (@MainActor () -> Void)?
11 private let showsT3ConnectOption: Bool
12​
13 @State private var stage = ConnectionStage.welcome
14 @State private var endpoint = ""
15 @State private var pairingCode = ""
16 @State private var errorMessage: String?
17 @State private var showsPermissionAction = false
18 @State private var showingScanner = false
19 @State private var entryHeading = "Connect manually"
20 @State private var connectionReturnStage = ConnectionStage.details
21 @State private var connectionTask: Task<Void, Never>?
22 @State private var connectionAttemptID: UUID?
23 @FocusState private var focusedField: ConnectionField?
24​
25 public init(
26 model: FeatureRootModel,
27 showsT3ConnectOption: Bool = true,
28 onConnected: @escaping @MainActor () -> Void = {},
29 onCancel: (@MainActor () -> Void)? = nil
30 ) {
31 self.model = model
32 readinessChecker = LocalNetworkAccessChecker()
33 self.showsT3ConnectOption = showsT3ConnectOption
34 self.onConnected = onConnected
35 self.onCancel = onCancel
36 }
37​
38 init(
39 model: FeatureRootModel,
40 readinessChecker: any ConnectionReadinessChecking,
41 showsT3ConnectOption: Bool = true,
42 onConnected: @escaping @MainActor () -> Void = {},
43 onCancel: (@MainActor () -> Void)? = nil
44 ) {
45 self.model = model
46 self.readinessChecker = readinessChecker
47 self.showsT3ConnectOption = showsT3ConnectOption
48 self.onConnected = onConnected
49 self.onCancel = onCancel
50 }
51​
52 public var body: some View {
53 NavigationStack {
54 Group {
55 switch stage {
56 case .welcome:
57 welcomeView
58 case .details:
59 detailsView
60 case .checking, .connecting:
61 progressView
62 case .success:
63 successView
64 }
65 }
66 .frame(maxWidth: .infinity, maxHeight: .infinity)
67 .background(T3Colors.background.ignoresSafeArea())
68 .animation(.snappy(duration: 0.24), value: stage)
69 .toolbarBackground(T3Colors.background, for: .navigationBar)
70 .toolbarBackground(.visible, for: .navigationBar)
71 .toolbar {
72 if stage == .welcome, let onCancel {
73 ToolbarItem(placement: .cancellationAction) {
74 Button("Close", action: onCancel)
75 .accessibilityIdentifier("connection-onboarding-close")
76 }
77 } else if stage == .checking || stage == .connecting {
78 ToolbarItem(placement: .cancellationAction) {
79 Button("Cancel") {
80 cancelConnectionAttempt()
81 model.errorMessage = nil
82 stage = connectionReturnStage
83 }
84 .accessibilityIdentifier("connection-onboarding-cancel")
85 }
86 }
87 }
88 }
89 .fullScreenCover(isPresented: $showingScanner) {
90 QRCodeScannerView(
91 onScan: { value in
92 showingScanner = false
93 applyConnectionString(
94 value,
95 heading: "Confirm connection",
96 connectAutomatically: true
97 )
98 },
99 onCancel: {
100 showingScanner = false
101 },
102 onPaste: {
103 showingScanner = false
104 pasteConnectionLink()
105 }
106 )
107 }
108 .onOpenURL { url in
109 applyConnectionString(url.absoluteString, heading: "Confirm connection")
110 }
111 .onChange(of: scenePhase) { _, newPhase in
112 if newPhase == .active, showsPermissionAction {
113 showsPermissionAction = false
114 errorMessage = nil
115 }
116 }
117 .interactiveDismissDisabled(stage == .checking || stage == .connecting)
118 .onDisappear {
119 cancelConnectionAttempt()
120 }
121 }
122​
123 private var welcomeView: some View {
124 ScrollView {
125 VStack(alignment: .leading, spacing: 0) {
126 Spacer(minLength: 36)
127​
128 Text("T3")
129 .font(.system(size: 34, weight: .black, design: .rounded))
130 .foregroundStyle(Color(red: 0.02, green: 0.74, blue: 0.5))
131 .accessibilityLabel("T3 Code")
132​
133 Text("Connect an environment")
134 .font(.largeTitle.bold())
135 .foregroundStyle(T3Colors.textPrimary)
136 .padding(.top, 20)
137​
138 Text("Choose how to connect to T3 Code.")
139 .font(.body)
140 .foregroundStyle(T3Colors.textSecondary)
141 .padding(.top, 8)
142​
143 if let errorMessage {
144 connectionError(message: errorMessage)
145 .padding(.top, 20)
146 }
147​
148 if showsT3ConnectOption,
149 let capability = model.client as? any T3ConnectCapable,
150 capability.t3ConnectController.unavailableReason == nil {
151 NavigationLink {
152 T3ConnectView(capability: capability, model: model) {
153 await model.reloadAfterConnection()
154 onConnected()
155 }
156 } label: {
157 Label("T3 Connect", systemImage: "cloud")
158 .frame(maxWidth: .infinity)
159 }
160 .buttonStyle(ConnectionPrimaryButtonStyle())
161 .padding(.top, 32)
162 .accessibilityHint("Sign in to connect a linked environment")
163 .accessibilityIdentifier("connection-onboarding-t3-connect")
164 }
165​
166 VStack(spacing: 0) {
167 connectionAction(
168 title: "Scan QR code",
169 subtitle: "Use the code on your computer",
170 systemImage: "qrcode.viewfinder"
171 ) {
172 errorMessage = nil
173 showsPermissionAction = false
174 showingScanner = true
175 }
176​
177 Divider().overlay(T3Colors.border)
178​
179 connectionAction(
180 title: "Paste connection link",
181 subtitle: "Use a link from your computer",
182 systemImage: "doc.on.clipboard"
183 ) {
184 pasteConnectionLink()
185 }
186​
187 Divider().overlay(T3Colors.border)
188​
189 connectionAction(
190 title: "Enter details",
191 subtitle: "Use an address and pairing code",
192 systemImage: "keyboard"
193 ) {
194 entryHeading = "Connect manually"
195 errorMessage = nil
196 showsPermissionAction = false
197 stage = .details
198 }
199 }
200 .padding(.top, showsT3ConnectOption ? 20 : 28)
201​
202 knownEnvironments
203 }
204 .padding(.horizontal, 24)
205 .padding(.bottom, 40)
206 .frame(maxWidth: 520)
207 .frame(maxWidth: .infinity)
208 }
209 .scrollDismissesKeyboard(.interactively)
210 }
211​
212 @ViewBuilder
213 private var knownEnvironments: some View {
214 if !knownEnvironmentValues.isEmpty {
215 VStack(alignment: .leading, spacing: 0) {
216 Text("Saved environments")
217 .font(.headline)
218 .foregroundStyle(T3Colors.textPrimary)
219 .padding(.top, 36)
220 .padding(.bottom, 8)
221​
222 ForEach(knownEnvironmentValues) { environment in
223 Button {
224 connect(
225 .activate(
226 id: environment.id,
227 endpoint: environment.endpoint
228 )
229 )
230 } label: {
231 HStack(spacing: 12) {
232 Image(systemName: "desktopcomputer")
233 .font(.body)
234 .foregroundStyle(.secondary)
235 .frame(width: 24)
236 VStack(alignment: .leading, spacing: 2) {
237 Text(environment.name)
238 .font(T3Typography.threadBody)
239 .foregroundStyle(.primary)
240 Text(environment.endpoint)
241 .font(T3Typography.supporting)
242 .foregroundStyle(T3Colors.textSecondary)
243 .lineLimit(1)
244 }
245 Spacer()
246 Image(systemName: "arrow.right")
247 .font(.caption.weight(.semibold))
248 .foregroundStyle(.tertiary)
249 }
250 .contentShape(Rectangle())
251 .padding(.vertical, 12)
252 }
253 .buttonStyle(.plain)
254 .accessibilityLabel(environment.name)
255 .accessibilityValue(environment.endpoint)
256 .accessibilityHint("Connects to this saved environment")
257​
258 if environment.id != knownEnvironmentValues.last?.id {
259 Divider().overlay(T3Colors.border)
260 }
261 }
262 }
263 }
264 }
265​
266 private var knownEnvironmentValues: [FeatureEnvironment] {
267 guard showsT3ConnectOption else { return [] }
268 return model.snapshot.environments
269 }
270​
271 private var detailsView: some View {
272 ScrollView {
273 VStack(alignment: .leading, spacing: 24) {
274 VStack(alignment: .leading, spacing: 8) {
275 Text(entryHeading)
276 .font(.largeTitle.bold())
277 .foregroundStyle(T3Colors.textPrimary)
278 Text("Find these details in T3 Code on your computer.")
279 .font(T3Typography.threadBody)
280 .foregroundStyle(T3Colors.textSecondary)
281 }
282​
283 VStack(alignment: .leading, spacing: 8) {
284 Text("Server address")
285 .font(T3Typography.control)
286 .foregroundStyle(T3Colors.textPrimary)
287​
288 TextField(
289 "Server address",
290 text: $endpoint,
291 prompt: Text("http://192.168.1.5:3773")
292 .foregroundStyle(T3Colors.placeholder)
293 )
294 .textInputAutocapitalization(.never)
295 .keyboardType(.URL)
296 .autocorrectionDisabled()
297 .focused($focusedField, equals: .endpoint)
298 .connectionInput()
299 .accessibilityLabel("Server address")
300 .accessibilityIdentifier("connection-onboarding-address")
301 .submitLabel(.next)
302 .onSubmit { focusedField = .pairingCode }
303 .onChange(of: endpoint) { _, value in
304 autofillIfPairingLink(value)
305 }
306 }
307​
308 VStack(alignment: .leading, spacing: 8) {
309 Text("Pairing code")
310 .font(T3Typography.control)
311 .foregroundStyle(T3Colors.textPrimary)
312​
313 TextField(
314 "Pairing code",
315 text: $pairingCode,
316 prompt: Text("Enter pairing code")
317 .foregroundStyle(T3Colors.placeholder)
318 )
319 .textInputAutocapitalization(.never)
320 .textContentType(.oneTimeCode)
321 .autocorrectionDisabled()
322 .focused($focusedField, equals: .pairingCode)
323 .connectionInput()
324 .privacySensitive()
325 .accessibilityLabel("Pairing code")
326 .accessibilityIdentifier("connection-onboarding-pairing-code")
327 .submitLabel(.go)
328 .onSubmit {
329 if canSubmit { submitDetails() }
330 }
331 }
332​
333 Button {
334 pasteConnectionLink()
335 } label: {
336 Label("Paste connection link", systemImage: "doc.on.clipboard")
337 .font(T3Typography.control.weight(.semibold))
338 }
339 .buttonStyle(.plain)
340 .frame(minHeight: T3Metrics.minimumTapTarget, alignment: .leading)
341 .accessibilityIdentifier("connection-onboarding-paste-link")
342​
343 if let errorMessage {
344 connectionError(message: errorMessage)
345 }
346​
347 Button {
348 submitDetails()
349 } label: {
350 Text("Connect")
351 .frame(maxWidth: .infinity)
352 }
353 .buttonStyle(ConnectionPrimaryButtonStyle())
354 .disabled(!canSubmit)
355 .opacity(canSubmit ? 1 : 0.45)
356 .accessibilityIdentifier("connection-onboarding-submit")
357 }
358 .padding(.horizontal, 24)
359 .padding(.top, 24)
360 .padding(.bottom, 40)
361 .frame(maxWidth: 520)
362 .frame(maxWidth: .infinity)
363 }
364 .scrollDismissesKeyboard(.interactively)
365 .navigationTitle("Add environment")
366 .navigationBarTitleDisplayMode(.inline)
367 .toolbar {
368 ToolbarItem(placement: .cancellationAction) {
369 Button {
370 errorMessage = nil
371 showsPermissionAction = false
372 focusedField = nil
373 stage = .welcome
374 } label: {
375 Label("Back", systemImage: "chevron.left")
376 }
377 }
378 }
379 }
380​
381 private var progressView: some View {
382 VStack(alignment: .leading, spacing: 34) {
383 Spacer()
384​
385 Text(stage == .checking ? "Checking connection" : "Connecting")
386 .font(.largeTitle.bold())
387 .foregroundStyle(T3Colors.textPrimary)
388​
389 VStack(alignment: .leading, spacing: 20) {
390 progressRow(
391 title: "Server address",
392 state: .complete
393 )
394 progressRow(
395 title: EndpointNetworkScope.isLocal(endpoint)
396 ? "Local network access"
397 : "Network access",
398 state: stage == .checking ? .active : .complete
399 )
400 progressRow(
401 title: "Pairing",
402 state: stage == .connecting ? .active : .waiting
403 )
404 }
405​
406 Spacer()
407​
408 Text(endpoint)
409 .font(T3Typography.supporting)
410 .foregroundStyle(T3Colors.textSecondary)
411 .lineLimit(1)
412 }
413 .padding(.horizontal, 32)
414 .padding(.vertical, 28)
415 .frame(maxWidth: 520)
416 .accessibilityElement(children: .contain)
417 }
418​
419 private var successView: some View {
420 VStack(spacing: 18) {
421 Image(systemName: "checkmark.circle.fill")
422 .font(.system(size: 54))
423 .foregroundStyle(.green)
424 Text("Connected")
425 .font(.title.bold())
426 Text("Loading your projects.")
427 .font(T3Typography.threadBody)
428 .foregroundStyle(T3Colors.textSecondary)
429 }
430 .accessibilityElement(children: .combine)
431 }
432​
433 private func connectionAction(
434 title: String,
435 subtitle: String,
436 systemImage: String,
437 action: @escaping () -> Void
438 ) -> some View {
439 Button(action: action) {
440 HStack(spacing: 14) {
441 Image(systemName: systemImage)
442 .font(.system(size: 18, weight: .medium))
443 .frame(width: 28)
444 VStack(alignment: .leading, spacing: 3) {
445 Text(title)
446 .font(.body.weight(.semibold))
447 Text(subtitle)
448 .font(T3Typography.supporting)
449 .foregroundStyle(T3Colors.textSecondary)
450 }
451 Spacer()
452 Image(systemName: "chevron.right")
453 .font(.caption.weight(.semibold))
454 .foregroundStyle(.tertiary)
455 }
456 .foregroundStyle(.primary)
457 .contentShape(Rectangle())
458 .padding(.vertical, 14)
459 }
460 .buttonStyle(.plain)
461 .frame(minHeight: T3Metrics.minimumTapTarget)
462 .accessibilityElement(children: .combine)
463 }
464​
465 private func connectionError(message: String) -> some View {
466 VStack(alignment: .leading, spacing: 10) {
467 Label(message, systemImage: showsPermissionAction ? "network.slash" : "exclamationmark.circle")
468 .font(T3Typography.control)
469 .foregroundStyle(Color(red: 1, green: 0.58, blue: 0.2))
470​
471 if showsPermissionAction {
472 Button("Open Settings") {
473 guard let url = URL(string: UIApplication.openSettingsURLString) else { return }
474 UIApplication.shared.open(url)
475 }
476 .font(T3Typography.control.weight(.semibold))
477 }
478 }
479 .accessibilityElement(children: .contain)
480 }
481​
482 private func progressRow(title: String, state: ProgressRowState) -> some View {
483 HStack(spacing: 14) {
484 Group {
485 switch state {
486 case .complete:
487 Image(systemName: "checkmark.circle.fill")
488 .foregroundStyle(.green)
489 case .active:
490 ProgressView()
491 .controlSize(.small)
492 case .waiting:
493 Image(systemName: "circle")
494 .foregroundStyle(.tertiary)
495 }
496 }
497 .frame(width: 22)
498​
499 Text(title)
500 .font(.body.weight(state == .active ? .semibold : .regular))
501 .foregroundStyle(state == .waiting ? .secondary : .primary)
502 }
503 }
504​
505 private var canSubmit: Bool {
506 !endpoint.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
507 && !pairingCode.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
508 }
509​
510 @MainActor
511 private func submitDetails() {
512 do {
513 let normalized = try ConnectionDetailsParser.normalizedEndpoint(endpoint)
514 endpoint = normalized
515 errorMessage = nil
516 showsPermissionAction = false
517 focusedField = nil
518 connect(
519 .pair(
520 endpoint: normalized,
521 code: pairingCode.trimmingCharacters(in: .whitespacesAndNewlines)
522 )
523 )
524 } catch {
525 errorMessage = error.localizedDescription
526 }
527 }
528​
529 @MainActor
530 private func pasteConnectionLink() {
531 guard let value = UIPasteboard.general.string, !value.isEmpty else {
532 entryHeading = "Connect manually"
533 stage = .details
534 errorMessage = "Copy a T3 pairing link first, or enter the details below."
535 focusedField = .endpoint
536 return
537 }
538 applyConnectionString(value, heading: "Confirm connection")
539 }
540​
541 @MainActor
542 private func applyConnectionString(
543 _ value: String,
544 heading: String,
545 connectAutomatically: Bool = false
546 ) {
547 cancelConnectionAttempt()
548 do {
549 let details = try ConnectionDetailsParser.parse(value)
550 endpoint = details.endpoint
551 pairingCode = details.pairingCode ?? ""
552 entryHeading = heading
553 errorMessage = details.pairingCode == nil
554 ? "The link did not include a pairing code. Enter it below."
555 : nil
556 showsPermissionAction = false
557 if connectAutomatically, let code = details.pairingCode {
558 focusedField = nil
559 connect(.pair(endpoint: details.endpoint, code: code))
560 } else {
561 stage = .details
562 focusedField = details.pairingCode == nil ? .pairingCode : nil
563 }
564 } catch {
565 entryHeading = "Connect manually"
566 errorMessage = error.localizedDescription
567 stage = .details
568 focusedField = .endpoint
569 }
570 }
571​
572 @MainActor
573 private func autofillIfPairingLink(_ value: String) {
574 guard let details = try? ConnectionDetailsParser.parse(value),
575 let code = details.pairingCode
576 else {
577 return
578 }
579 endpoint = details.endpoint
580 pairingCode = code
581 errorMessage = nil
582 focusedField = nil
583 }
584​
585 @MainActor
586 private func connect(_ action: ConnectionAction) {
587 cancelConnectionAttempt()
588 let attemptID = UUID()
589 connectionAttemptID = attemptID
590 switch action {
591 case .pair:
592 connectionReturnStage = .details
593 case .activate:
594 connectionReturnStage = .welcome
595 }
596 endpoint = action.endpoint
597 errorMessage = nil
598 showsPermissionAction = false
599 stage = .checking
600​
601 connectionTask = Task {
602 let readiness = await readinessChecker.check(endpoint: action.endpoint)
603 guard !Task.isCancelled, connectionAttemptID == attemptID else { return }
604 switch readiness {
605 case .ready:
606 stage = .connecting
607 case .localNetworkDenied:
608 errorMessage = "Allow Local Network access to connect to this environment."
609 showsPermissionAction = true
610 connectionAttemptID = nil
611 connectionTask = nil
612 stage = connectionReturnStage
613 return
614 case .unreachable:
615 errorMessage = "Cannot reach this environment. Check the address and network connection."
616 connectionAttemptID = nil
617 connectionTask = nil
618 stage = connectionReturnStage
619 return
620 }
621​
622 model.errorMessage = nil
623 let didConnect: Bool
624 switch action {
625 case let .pair(endpoint, code):
626 didConnect = await model.pair(endpoint: endpoint, token: code)
627 case let .activate(id, _):
628 didConnect = await model.setEnvironmentEnabled(id, enabled: true)
629 }
630 guard !Task.isCancelled, connectionAttemptID == attemptID else { return }
631​
632 if didConnect {
633 connectionAttemptID = nil
634 connectionTask = nil
635 stage = .success
636 onConnected()
637 } else {
638 let rawError = model.errorMessage
639 model.errorMessage = nil
640 errorMessage = ConnectionErrorCopy.message(for: rawError)
641 connectionAttemptID = nil
642 connectionTask = nil
643 stage = connectionReturnStage
644 }
645 }
646 }
647​
648 @MainActor
649 private func cancelConnectionAttempt() {
650 connectionTask?.cancel()
651 connectionTask = nil
652 connectionAttemptID = nil
653 }
655​
656private enum ConnectionStage: Equatable {
657 case welcome
658 case details
659 case checking
660 case connecting
661 case success
663​
664private enum ConnectionField: Hashable {
665 case endpoint
666 case pairingCode
668​
669private enum ProgressRowState {
670 case complete
671 case active
672 case waiting
674​
675private enum ConnectionAction {
676 case pair(endpoint: String, code: String)
677 case activate(id: String, endpoint: String)
678​
679 var endpoint: String {
680 switch self {
681 case let .pair(endpoint, _), let .activate(_, endpoint):
682 endpoint
683 }
684 }
686​
687private extension View {
688 func connectionInput() -> some View {
689 self
690 .font(.body.monospaced())
691 .foregroundStyle(T3Colors.textPrimary)
692 .padding(.horizontal, 14)
693 .frame(minHeight: 50)
694 .background(T3Colors.input)
695 .overlay(alignment: .bottom) {
696 Rectangle()
697 .fill(T3Colors.inputBorder)
698 .frame(height: 1)
699 }
700 }
702​
703private struct ConnectionPrimaryButtonStyle: ButtonStyle {
704 func makeBody(configuration: Configuration) -> some View {
705 configuration.label
706 .font(.body.weight(.semibold))
707 .foregroundStyle(T3Colors.primaryActionForeground)
708 .padding(.horizontal, 16)
709 .frame(minHeight: 52)
710 .background(
711 configuration.isPressed
712 ? T3Colors.primaryAction.opacity(0.76)
713 : T3Colors.primaryAction
714 )
715 .clipShape(RoundedRectangle(cornerRadius: 12))
716 }