Repository Public
1// SP Notes iOS2// File: Features/Root/RouteCoordinator.swift3// Description: Decides which window handles a navigation request coming from outside the screens (links, widgets, Siri,4// notifications, Handoff, a mention tapped in a note). 1.0 had one app-global `pendingRoute` observed by every5// window, so with several windows the one that consumed it was not defined. Here the windows register themselves;6// a route is delivered exactly once: to the window it names, otherwise to the key window when it can show it,7// otherwise to the most recently used active shell window. A route nobody can take yet (app in the background,8// signed out, no window) waits in a short queue. Pure logic: no UIKit, unit-tested with several scenes.9//10// Author: Simon-Pierre Boucher11// Contact: contact@spboucher.ai12import Foundation1314@MainActor15final class RouteCoordinator {16 typealias SceneID = UUID1718 enum SceneKind: Equatable, Sendable {19 /// A full window (tabs or columns): shows every route.20 case shell21 /// A window that shows one note: takes only `.note` routes (it never swallows a shell route).22 case noteWindow2324 func canHandle(_ route: AppRoute) -> Bool {25 switch self {26 case .shell: return true27 case .noteWindow: if case .note = route { return true } else { return false }28 }29 }30 }3132 private struct Entry {33 var kind: SceneKind34 var isActive: Bool35 /// Larger = used more recently (activation, key window).36 var recency: Int37 var handler: @MainActor (AppRoute) -> Void38 }3940 private struct Queued { var route: AppRoute; var target: SceneID? }4142 private var scenes: [SceneID: Entry] = [:]43 private var queue: [Queued] = []44 private var clock = 045 private var askedForShell = false46 /// Routes are held while this is false (signed out: the welcome screen cannot show them).47 var isAccepting: @MainActor () -> Bool = { true }48 /// Called when a route needs a shell window and none is registered (only note windows are open).49 var onNeedsShell: (@MainActor () -> Void)?50 static let queueLimit = 85152 // MARK: scenes5354 func register(_ id: SceneID, kind: SceneKind, isActive: Bool, handler: @escaping @MainActor (AppRoute) -> Void) {55 clock += 156 scenes[id] = Entry(kind: kind, isActive: isActive, recency: isActive ? clock : 0, handler: handler)57 if kind == .shell { askedForShell = false }58 flush()59 }6061 func unregister(_ id: SceneID) {62 scenes[id] = nil63 // a route that named this window goes to whoever can take it64 for index in queue.indices where queue[index].target == id { queue[index].target = nil }65 }6667 /// The window became foreground-active (or left the foreground).68 func setActive(_ id: SceneID, _ active: Bool) {69 guard var entry = scenes[id] else { return }70 if active, !entry.isActive { clock += 1; entry.recency = clock }71 entry.isActive = active72 scenes[id] = entry73 if active { flush() }74 }7576 /// The window became the key window (the one the user is interacting with).77 func noteKey(_ id: SceneID) {78 guard var entry = scenes[id] else { return }79 clock += 180 entry.recency = clock81 scenes[id] = entry82 }8384 var registeredScenes: Int { scenes.count }8586 // MARK: routes8788 /// Delivers a route. `origin` names the window the request arrived in (its `onOpenURL`, its activity), when known.89 /// Returns the window that handled it, or nil when it waits in the queue.90 @discardableResult91 func dispatch(_ route: AppRoute, from origin: SceneID? = nil) -> SceneID? {92 if let id = deliver(route, target: origin) { return id }93 if queue.last?.route != route || queue.last?.target != origin {94 queue.append(Queued(route: route, target: origin))95 if queue.count > Self.queueLimit { queue.removeFirst(queue.count - Self.queueLimit) }96 }97 return nil98 }99100 /// Tries the waiting routes again, in order (a window appeared or became active, the session started).101 func flush() {102 guard !queue.isEmpty else { return }103 let waiting = queue104 queue = []105 for item in waiting where deliver(item.route, target: item.target) == nil { queue.append(item) }106 }107108 /// The most recent route still waiting (what 1.0 exposed as `pendingRoute`).109 var pending: AppRoute? { queue.last?.route }110 var pendingCount: Int { queue.count }111 func clearPending() { queue.removeAll() }112113 /// The window a route would go to now, without delivering it.114 func destination(for route: AppRoute, from origin: SceneID? = nil) -> SceneID? {115 guard isAccepting() else { return nil }116 if let origin, let entry = scenes[origin], entry.kind.canHandle(route) { return origin }117 let active = scenes.filter(\.value.isActive)118 // the key window first, when it can show the route (a mention tapped in a note window opens there)…119 if let key = active.max(by: { $0.value.recency < $1.value.recency }), key.value.kind.canHandle(route) { return key.key }120 // …otherwise the most recently used active shell121 return active.filter { $0.value.kind == .shell }.max(by: { $0.value.recency < $1.value.recency })?.key122 }123124 private func deliver(_ route: AppRoute, target: SceneID?) -> SceneID? {125 guard let id = destination(for: route, from: target), let entry = scenes[id] else {126 if isAccepting(), !askedForShell, !scenes.isEmpty, !scenes.values.contains(where: { $0.kind == .shell }) {127 askedForShell = true128 onNeedsShell?()129 }130 return nil131 }132 entry.handler(route)133 return id134 }135}136