summaryrefslogtreecommitdiffhomepage
path: root/ios/Routing/Router/ApplicationRouter.swift
blob: 3baffa572aa4e47a21e5d39b35b7ef2b348214cf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
//
//  ApplicationRouter.swift
//  MullvadVPN
//
//  Created by pronebird on 16/03/2023.
//  Copyright © 2025 Mullvad VPN AB. All rights reserved.
//

import Foundation
import MullvadLogging
import UIKit

/**
 Main application router.
 */
@MainActor
public final class ApplicationRouter<RouteType: AppRouteProtocol> {
    nonisolated(unsafe) private let logger = Logger(label: "ApplicationRouter")

    private(set) var modalStack: [RouteType.RouteGroupType] = []
    private(set) var presentedRoutes: [RouteType.RouteGroupType: [PresentedRoute<RouteType>]] = [:]

    private var pendingRoutes = [PendingRoute<RouteType>]()
    private var isProcessingPendingRoutes = false

    private unowned let delegate: any ApplicationRouterDelegate<RouteType>

    /**
     Designated initializer.
    
     Delegate object is unonwed and the caller has to guarantee that the router does not outlive it.
     */
    public init(_ delegate: some ApplicationRouterDelegate<RouteType>) {
        self.delegate = delegate
    }

    /**
     Returns `true` is the given route group is currently being presented.
     */
    public func isPresenting(group: RouteType.RouteGroupType) -> Bool {
        modalStack.contains(group)
    }

    /**
     Returns `true` if is the given route  is currently being presented.
     */
    public func isPresenting(route: RouteType) -> Bool {
        guard let presentedRoute = presentedRoutes[route.routeGroup] else {
            return false
        }
        return presentedRoute.contains(where: { $0.route == route })
    }

    /**
     Enqueue route for presetnation.
     */
    public func present(_ route: RouteType, animated: Bool = true, metadata: Any? = nil) {
        enqueue(
            PendingRoute(
                operation: .present(route),
                animated: animated,
                metadata: metadata
            ))
    }

    /**
     Enqueue dismissal of the route.
     */
    public func dismiss(_ route: RouteType, animated: Bool = true) {
        enqueue(
            PendingRoute(
                operation: .dismiss(.singleRoute(route)),
                animated: animated
            ))
    }

    /**
     Enqueue dismissal of a group of routes.
     */
    public func dismissAll(_ group: RouteType.RouteGroupType, animated: Bool = true) {
        enqueue(
            PendingRoute(
                operation: .dismiss(.group(group)),
                animated: animated
            ))
    }

    private func enqueue(_ pendingRoute: PendingRoute<RouteType>) {
        logger.debug("\(pendingRoute.operation).")

        pendingRoutes.append(pendingRoute)

        if !isProcessingPendingRoutes {
            processPendingRoutes()
        }
    }

    private func presentRoute(
        _ route: RouteType,
        animated: Bool,
        metadata: Any?,
        completion: @escaping @Sendable @MainActor (PendingPresentationResult) -> Void
    ) {
        /**
         Pass sub-route for routes supporting sub-navigation.
         */
        if route.supportsSubNavigation, modalStack.contains(route.routeGroup),
            var presentedRoute = presentedRoutes[route.routeGroup]?.first
        {
            let context = RouteSubnavigationContext(
                presentedRoute: presentedRoute,
                route: route,
                isAnimated: animated
            )

            presentedRoute.route = route
            presentedRoutes[route.routeGroup] = [presentedRoute]

            delegate.applicationRouter(self, handleSubNavigationWithContext: context) {
                completion(.success)
            }

            return
        }

        /**
         Drop duplicate exclusive routes.
         */
        if route.isExclusive, modalStack.contains(route.routeGroup) {
            completion(.drop)
            return
        }

        /**
         Drop if the last presented route within the group is the same.
         */
        if !route.isExclusive, presentedRoutes[route.routeGroup]?.last?.route == route {
            completion(.drop)
            return
        }

        /**
         Check if route can be presented above the last route in the modal stack.
         */
        if let
            // Get current modal route.
            lastRouteGroup = modalStack.last,
            // Check if incoming route is modal.
            route.routeGroup.isModal,
            // Check whether incoming route can be presented on top of current.
            (lastRouteGroup > route.routeGroup)
                // OR, check whether incoming exclusive route can be presented on top of current.
                || (lastRouteGroup >= route.routeGroup && route.isExclusive)
        {
            completion(.blockedByModalContext)
            return
        }

        /**
         Consult with delegate whether the route should still be presented.
         */
        if delegate.applicationRouter(self, shouldPresent: route) {
            let context = RoutePresentationContext(route: route, isAnimated: animated, metadata: metadata)

            delegate.applicationRouter(self, presentWithContext: context, animated: animated) { coordinator in
                /// Synchronize router when modal controllers are removed by swipe.
                /// The delegate (`ApplicationCoordinator`) is `@MainActor` by virtue of being a `Coordinator`
                MainActor.assumeIsolated {
                    if let presentable = coordinator as? Presentable {
                        presentable.onInteractiveDismissal { [weak self] coordinator in
                            MainActor.assumeIsolated {
                                self?.handleInteractiveDismissal(route: route, coordinator: coordinator)
                            }
                        }
                    }

                    self.addPresentedRoute(PresentedRoute(route: route, coordinator: coordinator))

                    completion(.success)
                }
            }
        } else {
            completion(.drop)
        }
    }

    private func dismissGroup(
        _ dismissGroup: RouteType.RouteGroupType,
        animated: Bool,
        completion: @escaping @Sendable (PendingDismissalResult) -> Void
    ) {
        /**
         Check if routes corresponding to the group requested for dismissal are present.
         */
        guard modalStack.contains(dismissGroup) else {
            completion(.drop)
            return
        }

        /**
         Check if the group can be dismissed and it's not blocked by another group presented above.
         */
        if modalStack.last != dismissGroup, dismissGroup.isModal {
            completion(.blockedByModalAbove)
            return
        }

        let dismissedRoutes = presentedRoutes[dismissGroup] ?? []
        assert(!dismissedRoutes.isEmpty)

        let context = RouteDismissalContext(
            dismissedRoutes: dismissedRoutes,
            isClosing: true,
            isAnimated: animated
        )

        /**
         Consult with delegate whether the route should still be dismissed.
         */
        guard delegate.applicationRouter(self, shouldDismissWithContext: context) else {
            completion(.drop)
            return
        }

        presentedRoutes.removeValue(forKey: dismissGroup)
        modalStack.removeAll { $0 == dismissGroup }

        delegate.applicationRouter(self, dismissWithContext: context) {
            completion(.success)
        }
    }

    private func dismissRoute(
        _ dismissRoute: RouteType,
        animated: Bool,
        completion: @escaping @Sendable (PendingDismissalResult) -> Void
    ) {
        var routes = presentedRoutes[dismissRoute.routeGroup] ?? []

        // Find the index of route to pop.
        guard let index = routes.lastIndex(where: { $0.route == dismissRoute }) else {
            completion(.drop)
            return
        }

        // Check if dismissing the last route in horizontal navigation group.
        let isLastRoute = routes.count == 1

        // Check if the route can be dismissed and there is no other modal above.
        if let lastModalGroup = modalStack.last,
            lastModalGroup != dismissRoute.routeGroup,
            dismissRoute.routeGroup.isModal,
            isLastRoute
        {
            completion(.blockedByModalAbove)
            return
        }

        let context = RouteDismissalContext(
            dismissedRoutes: [routes[index]],
            isClosing: isLastRoute,
            isAnimated: animated
        )

        /**
         Consult with delegate whether the route should still be dismissed.
         */
        guard delegate.applicationRouter(self, shouldDismissWithContext: context) else {
            completion(.drop)
            return
        }

        if isLastRoute {
            presentedRoutes.removeValue(forKey: dismissRoute.routeGroup)
            modalStack.removeAll { $0 == dismissRoute.routeGroup }
        } else {
            routes.remove(at: index)
            presentedRoutes[dismissRoute.routeGroup] = routes
        }

        delegate.applicationRouter(self, dismissWithContext: context) {
            completion(.success)
        }
    }

    private func processPendingRoutes(skipRouteGroups: Set<RouteType.RouteGroupType> = []) {
        isProcessingPendingRoutes = true

        let pendingRoute = pendingRoutes.first { pendingRoute in
            !skipRouteGroups.contains(pendingRoute.operation.routeGroup)
        }

        guard let pendingRoute else {
            isProcessingPendingRoutes = false
            return
        }

        switch pendingRoute.operation {
        case let .present(route):
            presentRoute(route, animated: pendingRoute.animated, metadata: pendingRoute.metadata) { result in
                switch result {
                case .success, .drop:
                    self.finishPendingRoute(pendingRoute)

                case .blockedByModalContext:
                    /**
                     Present next route if this one is not ready to be presented.
                     */
                    self.processPendingRoutes(
                        skipRouteGroups: skipRouteGroups.union([route.routeGroup])
                    )
                }
            }

        case let .dismiss(dismissMatch):
            handleDismissal(dismissMatch, animated: pendingRoute.animated) { result in
                MainActor.assumeIsolated {
                    switch result {
                    case .success, .drop:
                        self.finishPendingRoute(pendingRoute)

                    case .blockedByModalAbove:
                        /**
                         If router cannot dismiss modal because there is one above,
                         try walking down the queue and see if there is a dismissal request that could
                         resolve that.
                         */
                        self.processPendingRoutes(
                            skipRouteGroups: skipRouteGroups.union([dismissMatch.routeGroup])
                        )
                    }
                }
            }
        }
    }

    private func handleDismissal(
        _ dismissMatch: DismissMatch<RouteType>,
        animated: Bool,
        completion: @escaping @Sendable (PendingDismissalResult) -> Void
    ) {
        switch dismissMatch {
        case let .singleRoute(route):
            dismissRoute(route, animated: animated, completion: completion)

        case let .group(group):
            dismissGroup(group, animated: animated, completion: completion)
        }
    }

    private func finishPendingRoute(_ pendingRoute: PendingRoute<RouteType>) {
        if let index = pendingRoutes.firstIndex(of: pendingRoute) {
            pendingRoutes.remove(at: index)
        }

        processPendingRoutes()
    }

    private func handleInteractiveDismissal(route: RouteType, coordinator: Coordinator) {
        var routes = presentedRoutes[route.routeGroup] ?? []

        routes.removeAll { presentedRoute in
            presentedRoute.coordinator == coordinator
        }

        if routes.isEmpty {
            presentedRoutes.removeValue(forKey: route.routeGroup)
            modalStack.removeAll { $0 == route.routeGroup }
        } else {
            presentedRoutes[route.routeGroup] = routes
        }

        if !isProcessingPendingRoutes {
            processPendingRoutes()
        }
    }

    private func addPresentedRoute(_ presented: PresentedRoute<RouteType>) {
        let group = presented.route.routeGroup
        var routes = presentedRoutes[group] ?? []

        if presented.route.isExclusive {
            routes = [presented]
        } else {
            routes.append(presented)
        }

        presentedRoutes[group] = routes

        if !modalStack.contains(group) {
            if group.isModal {
                modalStack.append(group)
            } else {
                modalStack.insert(group, at: 0)
            }
        }
    }
}