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

PlatformRootView.swift

420 lines17.0 KB

1import SwiftUI
2​
3struct PlatformRootView: View {
4 @SwiftUI.Environment(\.scenePhase) private var scenePhase
5 @Bindable private var model: FeatureRootModel
6​
7 @State private var navigationRequest: FeatureWorkspaceNavigationRequest?
8 @State private var pendingRoute: PlatformRoute?
9 @State private var previousThreadMembership: [PlatformRecentThreadChangeKey] = []
10 @State private var previousThreadStates: [String: FeatureThreadState]?
11 @State private var lastNotificationPreference: Bool?
12 @State private var incomingShareCoordinator = PlatformIncomingShareCoordinator()
13 @State private var incomingShareNeedsProject = false
14 @State private var importedShareProjectID: String?
15 @State private var recentThreadsPersistenceTask: Task<Void, Never>?
16 @State private var subscriptionUsage = PlatformSubscriptionUsageCoordinator()
17​
18 init(model: FeatureRootModel) {
19 self.model = model
20 }
21​
22 var body: some View {
23 FeatureRootView(
24 model: model,
25 navigationRequest: navigationRequest,
26 onNavigationRequestConsumed: { requestID in
27 guard navigationRequest?.id == requestID else { return }
28 navigationRequest = nil
29 }
30 )
31 .environment(\.openURL, OpenURLAction { url in
32 // Links tapped inside the app (message Markdown above all) would
33 // otherwise leave for Safari or be rejected by an unregistered
34 // scheme, so keep the ones this device can already show.
35 guard let route = PlatformInAppLinkRouter.route(for: url, in: model.snapshot) else {
36 return .systemAction
37 }
38 handle(route)
39 return .handled
40 })
41 .onOpenURL { url in
42 handle(url: url, letOnboardingConfirmConnection: true)
43 }
44 .task(id: subscriptionUsageKey) {
45 guard subscriptionUsageKey.isActive else { return }
46 await subscriptionUsage.observe(
47 client: model.client,
48 key: subscriptionUsageKey
49 )
50 }
51 .onContinueUserActivity(NSUserActivityTypeBrowsingWeb) { activity in
52 guard let url = activity.webpageURL else { return }
53 handle(url: url, letOnboardingConfirmConnection: false)
54 }
55 .onReceive(NotificationCenter.default.publisher(for: .platformRouteReceived)) { note in
56 guard let route = note.userInfo?["route"] as? PlatformRoute else { return }
57 _ = PlatformRouteMailbox.shared.take()
58 handle(route)
59 }
60 .onReceive(NotificationCenter.default.publisher(for: .t3ConnectSessionChanged)) { note in
61 guard let capability = model.client as? any T3ConnectCapable,
62 let controller = note.object as? T3ConnectController,
63 controller === capability.t3ConnectController else { return }
64 let previousAccountID = note.userInfo?["previousAccountID"] as? String
65 let accountID = note.userInfo?["accountID"] as? String
66 guard Self.shouldRemoveManagedEnvironments(
67 previousAccountID: previousAccountID,
68 accountID: accountID,
69 isSigningOut: model.isSigningOutT3Connect
70 ) else { return }
71 Task { @MainActor in
72 guard !model.isSigningOutT3Connect else { return }
73 await model.removeManagedEnvironmentsAfterAccountChange()
74 }
75 }
76 .onChange(of: model.isLoading, initial: true) { _, isLoading in
77 guard !isLoading else { return }
78 processThreadChanges()
79 synchronizeNotificationPreference()
80 synchronizeCloudDelivery()
81 consumePendingRouteIfPossible()
82 consumeMailboxRouteIfAvailable()
83 refreshIncomingShares()
84 }
85 .onChange(of: model.homePresentationRevision) { _, _ in
86 processThreadChanges()
87 }
88 .onChange(of: model.threadRowRevision) { _, _ in
89 processThreadChanges()
90 }
91 .onChange(of: scenePhase) { _, phase in
92 if phase == .active {
93 Task { await model.applicationDidBecomeActive() }
94 consumeMailboxRouteIfAvailable()
95 synchronizeNotificationPreference()
96 synchronizeCloudDelivery()
97 refreshIncomingShares()
98 } else if phase == .background {
99 model.applicationDidEnterBackground()
100 PlatformBackgroundRefreshCoordinator.shared.schedule()
101 }
102 }
103 .onChange(of: model.snapshot.settings.notificationsEnabled) { _, _ in
104 synchronizeNotificationPreference()
105 synchronizeCloudDelivery()
106 }
107 .onChange(of: model.snapshot.settings.liveActivitiesEnabled) { _, _ in
108 synchronizeAgentAwareness()
109 synchronizeCloudDelivery()
110 }
111 .onChange(of: model.snapshot.projects.map(\.id)) { _, _ in
112 refreshIncomingShares()
113 }
114 .sheet(item: presentedIncomingShare, onDismiss: openImportedShareDraft) { envelope in
115 PlatformIncomingShareDestinationSheet(
116 envelope: envelope,
117 projects: incomingShareProjects,
118 environments: model.snapshot.environments,
119 isImporting: incomingShareCoordinator.isImporting,
120 onCancel: incomingShareCoordinator.dismissDestination,
121 onSelect: importIncomingShare(into:)
122 )
123 }
124 .alert("Create a project to continue", isPresented: $incomingShareNeedsProject) {
125 Button("Not now", role: .cancel) {}
126 Button("Create project") {
127 navigationRequest = FeatureWorkspaceNavigationRequest(
128 destination: .newTask(projectID: nil)
129 )
130 }
131 } message: {
132 Text("Your share is saved. Connect an environment and create a project to finish importing it.")
133 }
134 }
135​
136 static func shouldRemoveManagedEnvironments(
137 previousAccountID: String?,
138 accountID: String?,
139 isSigningOut: Bool
140 ) -> Bool {
141 guard !isSigningOut, let previousAccountID else { return false }
142 return previousAccountID != accountID
143 }
144​
145 private var subscriptionUsageKey: PlatformSubscriptionUsageObservationKey {
146 .init(
147 isActive: scenePhase == .active && !model.isLoading,
148 environments: model.snapshot.environments.filter(\.isEnabled),
149 accountID: (model.client as? any T3ConnectCapable)?.t3ConnectController.account?.id
150 )
151 }
152​
153 private var incomingShareProjects: [FeatureProject] {
154 DailyUXCreationContext.projects(in: model.snapshot).sorted {
155 if $0.name.localizedStandardCompare($1.name) == .orderedSame {
156 return $0.environmentID < $1.environmentID
157 }
158 return $0.name.localizedStandardCompare($1.name) == .orderedAscending
159 }
160 }
161​
162 private var presentedIncomingShare: Binding<T3IncomingShareEnvelope?> {
163 Binding(
164 get: {
165 guard !incomingShareProjects.isEmpty else { return nil }
166 return incomingShareCoordinator.pendingEnvelope
167 },
168 set: { value in
169 guard value == nil, importedShareProjectID == nil else { return }
170 incomingShareCoordinator.dismissDestination()
171 }
172 )
173 }
174​
175 private var shouldShowWorkspace: Bool {
176 FeatureRootPresentation.showsWorkspace(
177 snapshot: model.snapshot,
178 isManagingConnections: model.isManagingConnections
179 )
180 }
181​
182 private func handle(url: URL, letOnboardingConfirmConnection: Bool) {
183 do {
184 let route = try PlatformDeepLinkParser.parse(url)
185 if case .connection = route,
186 letOnboardingConfirmConnection,
187 !shouldShowWorkspace {
188 // ConnectionOnboardingView owns the confirmation UI for cold pairing links.
189 return
190 }
191 handle(route)
192 } catch {
193 model.errorMessage = error.localizedDescription
194 }
195 }
196​
197 private func handle(_ route: PlatformRoute) {
198 guard !model.isLoading else {
199 pendingRoute = route
200 return
201 }
202 Task { @MainActor in
203 await consume(route)
204 }
205 }
206​
207 private func consumePendingRouteIfPossible() {
208 guard let route = pendingRoute else { return }
209 pendingRoute = nil
210 handle(route)
211 }
212​
213 private func consumeMailboxRouteIfAvailable() {
214 guard !model.isLoading, let route = PlatformRouteMailbox.shared.take() else { return }
215 handle(route)
216 }
217​
218 private func synchronizeNotificationPreference() {
219 guard !model.isLoading else { return }
220 let preference = model.snapshot.settings.notificationsEnabled
221 let previous = lastNotificationPreference
222 lastNotificationPreference = preference
223​
224 Task {
225 let authorized: Bool?
226 if preference, previous == false {
227 // Ask for permission when the user enables notifications.
228 authorized = await PlatformNotificationService.shared.requestAuthorization()
229 } else {
230 authorized = await PlatformNotificationService.shared.synchronize(enabled: preference)
231 }
232 guard let authorized, preference, !authorized,
233 model.snapshot.settings.notificationsEnabled else {
234 return
235 }
236​
237 // Keep the app toggle honest when authorization is absent or revoked.
238 await model.savePreference(\.notificationsEnabled, value: false)
239 }
240 }
241​
242 private func synchronizeCloudDelivery() {
243 guard !model.isLoading else { return }
244 PlatformCloudDeliveryCoordinator.shared.synchronize(
245 settings: model.snapshot.settings
246 )
247 }
248​
249 private func refreshIncomingShares() {
250 guard !model.isLoading else { return }
251 let hasProjects = !incomingShareProjects.isEmpty
252 Task { @MainActor in
253 if await incomingShareCoordinator.refresh(hasProjects: hasProjects) {
254 incomingShareNeedsProject = true
255 }
256 }
257 }
258​
259 private func importIncomingShare(into project: FeatureProject) {
260 guard !incomingShareCoordinator.isImporting else { return }
261 importedShareProjectID = project.id
262 Task { @MainActor in
263 do {
264 try await incomingShareCoordinator.importPending(
265 into: project,
266 draftKey: FeatureComposerDraftStore.newTaskKey(
267 project: project,
268 in: model.snapshot
269 )
270 )
271 } catch {
272 importedShareProjectID = nil
273 model.errorMessage = error.localizedDescription
274 }
275 }
276 }
277​
278 private func openImportedShareDraft() {
279 guard let projectID = importedShareProjectID else { return }
280 importedShareProjectID = nil
281 navigationRequest = FeatureWorkspaceNavigationRequest(
282 destination: .newTask(projectID: projectID)
283 )
284 PlatformHapticEngine.shared.emit(
285 .success,
286 enabled: model.snapshot.settings.hapticsEnabled
287 )
288 }
289​
290 @MainActor
291 private func consume(_ route: PlatformRoute) async {
292 switch route {
293 case .usageLimits:
294 navigationRequest = FeatureWorkspaceNavigationRequest(destination: .usageLimits)
295 case let .connection(endpoint, token):
296 if await model.pair(endpoint: endpoint, token: token) {
297 PlatformHapticEngine.shared.emit(
298 .success,
299 enabled: model.snapshot.settings.hapticsEnabled
300 )
301 }
302 case let .environment(id):
303 guard await enableEnvironmentIfNeeded(id) else { return }
304 PlatformHapticEngine.shared.selection(
305 enabled: model.snapshot.settings.hapticsEnabled
306 )
307 case let .thread(environmentID, threadID):
308 guard await enableEnvironmentIfNeeded(environmentID),
309 let thread = PlatformRouteResolver.thread(
310 in: model.snapshot,
311 environmentID: environmentID,
312 id: threadID
313 )
314 else {
315 if model.errorMessage == nil { model.errorMessage = "That thread is not available on this device." }
316 return
317 }
318 navigationRequest = FeatureWorkspaceNavigationRequest(
319 destination: .thread(id: thread.id)
320 )
321 PlatformHapticEngine.shared.selection(
322 enabled: model.snapshot.settings.hapticsEnabled
323 )
324 case let .project(environmentID, projectID):
325 guard await enableEnvironmentIfNeeded(environmentID),
326 let project = PlatformRouteResolver.project(
327 in: model.snapshot,
328 environmentID: environmentID,
329 id: projectID
330 )
331 else {
332 if model.errorMessage == nil { model.errorMessage = "That project is not available on this device." }
333 return
334 }
335 navigationRequest = FeatureWorkspaceNavigationRequest(
336 destination: .project(id: project.id)
337 )
338 PlatformHapticEngine.shared.selection(
339 enabled: model.snapshot.settings.hapticsEnabled
340 )
341 case let .newTask(environmentID, projectID):
342 guard await enableEnvironmentIfNeeded(environmentID) else { return }
343 let resolvedProject = projectID.flatMap {
344 PlatformRouteResolver.project(
345 in: model.snapshot,
346 environmentID: environmentID,
347 id: $0
348 )
349 }
350 if projectID != nil, resolvedProject == nil {
351 model.errorMessage = "That project is not available on this device."
352 return
353 }
354 navigationRequest = FeatureWorkspaceNavigationRequest(
355 destination: .newTask(projectID: resolvedProject?.id)
356 )
357 PlatformHapticEngine.shared.selection(
358 enabled: model.snapshot.settings.hapticsEnabled
359 )
360 }
361 }
362​
363 @MainActor
364 private func enableEnvironmentIfNeeded(_ id: String?) async -> Bool {
365 guard let id else { return true }
366 guard let environment = model.snapshot.environments.first(where: { $0.id == id }) else {
367 model.errorMessage = "That environment is not saved on this device."
368 return false
369 }
370 guard !environment.isEnabled else { return true }
371 return await model.setEnvironmentEnabled(id, enabled: true)
372 }
373​
374 /// Home revisions are coalesced by FeatureRootModel, so this performs one
375 /// bounded scan per meaningful snapshot change rather than on every render.
376 private func processThreadChanges() {
377 let current = model.snapshot.threads.reduce(into: [String: FeatureThreadState]()) {
378 $0[$1.id] = $1.state
379 }
380 let signals = PlatformThreadTransitionClassifier.signals(
381 previous: previousThreadStates,
382 current: model.snapshot.threads
383 )
384 let statesChanged = current != previousThreadStates
385 previousThreadStates = current
386 // Streaming turns advance the row revision several times a second
387 // without changing any thread's state. The recent-thread store and
388 // the Live Activity only care about state and membership.
389 let membership = model.snapshot.threads.map(PlatformRecentThreadChangeKey.init)
390 let membershipChanged = membership != previousThreadMembership
391 previousThreadMembership = membership
392 // The awareness coordinator compares its own visible fields and limits
393 // writes. Project names and provider changes must reach that comparison.
394 synchronizeAgentAwareness()
395 guard statesChanged || membershipChanged else { return }
396 recentThreadsPersistenceTask?.cancel()
397 let threads = model.snapshot.threads
398 recentThreadsPersistenceTask = Task.detached(priority: .utility) {
399 guard !Task.isCancelled else { return }
400 PlatformRecentThreadStore.shared.update(from: threads)
401 }
402 for signal in signals {
403 if scenePhase == .active {
404 PlatformHapticEngine.shared.emit(
405 signal.kind,
406 enabled: model.snapshot.settings.hapticsEnabled
407 )
408 } else if model.snapshot.settings.notificationsEnabled {
409 Task { await PlatformNotificationService.shared.schedule(signal) }
410 }
411 }
412 }
413​
414 private func synchronizeAgentAwareness() {
415 PlatformAgentAwarenessCoordinator.shared.synchronize(
416 snapshot: model.snapshot,
417 liveActivitiesEnabled: model.snapshot.settings.liveActivitiesEnabled
418 )
419 }