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

ConnectionOnboardingView.swift

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