@nativescript/compiler-angular 0.0.0-stage → 9.2.0-alpha.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,626 @@
1
+ import Foundation
2
+
3
+ /// The route a component was created for (Angular `ActivatedRoute`): set by the
4
+ /// router before it constructs the routed component.
5
+ public final class ActivatedRoute {
6
+ nonisolated deinit {}
7
+ public typealias Snapshot = ActivatedRouteSnapshot
8
+ public let snapshot: ActivatedRouteSnapshot
9
+ /// `route.params`: the route's parameters, replayed to each subscriber.
10
+ public let params: RxBehaviorSubject<JSRecord<String>>
11
+ public let queryParams: RxBehaviorSubject<JSRecord<String>>
12
+ public let data: RxBehaviorSubject<JSRecord<Any?>>
13
+ public let paramMap: RxBehaviorSubject<ParamMap>
14
+ public let queryParamMap: RxBehaviorSubject<ParamMap>
15
+ public let fragment: RxBehaviorSubject<String?>
16
+ public let title: RxBehaviorSubject<String?>
17
+ /// The outlet the route renders in, and the URL segments within that outlet up to and including the route's own.
18
+ public let outlet: String
19
+ public var routeConfig: JSObject? = nil
20
+ let url: [String]
21
+ public static var current = ActivatedRoute(params: [:])
22
+
23
+ public init(params: [String: String], outlet: String = Router.primary, url: [String] = [], queryParams: [String: String] = [:], data: [(String, Any?)] = []) {
24
+ let record = JSRecord(params)
25
+ let queryRecord = JSRecord(queryParams)
26
+ let dataRecord = JSRecord(data)
27
+ let segs = JSArray(url.map { UrlSegment($0) })
28
+ snapshot = ActivatedRouteSnapshot(params: record, queryParams: queryRecord, data: dataRecord, url: segs, fragment: nil, outlet: outlet)
29
+ self.params = RxBehaviorSubject(record)
30
+ self.queryParams = RxBehaviorSubject(queryRecord)
31
+ self.data = RxBehaviorSubject(dataRecord)
32
+ self.paramMap = RxBehaviorSubject(ParamMap(record))
33
+ self.queryParamMap = RxBehaviorSubject(ParamMap(queryRecord))
34
+ self.fragment = RxBehaviorSubject(nil)
35
+ self.title = RxBehaviorSubject(nil)
36
+ self.outlet = outlet
37
+ self.url = url
38
+ }
39
+
40
+ public var root: ActivatedRoute { self }
41
+ public var parent: ActivatedRoute? { nil }
42
+ public var firstChild: ActivatedRoute? { nil }
43
+ public var children: JSArray<ActivatedRoute> { JSArray() }
44
+ public var pathFromRoot: JSArray<ActivatedRoute> { JSArray([self]) }
45
+ }
46
+
47
+ public struct Route {
48
+ let segments: [String]
49
+ let make: () throws -> View
50
+ public init(_ path: String, _ make: @escaping () throws -> View) {
51
+ segments = path.split(separator: "/").map(String.init)
52
+ self.make = make
53
+ }
54
+ }
55
+
56
+ /// A route of the app's configuration (Angular's `Route`), lazy children and components resolved at compile time.
57
+ public final class RouteConfig {
58
+ nonisolated deinit {}
59
+ let segments: [String]
60
+ let outlet: String
61
+ let redirectTo: String?
62
+ let full: Bool
63
+ let children: [RouteConfig]
64
+ let make: (() throws -> View)?
65
+ /// `NSEmptyOutletComponent`: its children show in a frame of their own, on a page of the outlet's frame.
66
+ let emptyOutlet: Bool
67
+ /// The id the route's guards are registered under (`Router.addGuard`).
68
+ let guards: Int?
69
+ /// The route's data with what it inherits from its parents.
70
+ let data: [(String, Any?)]
71
+
72
+ public init(_ path: String, outlet: String = Router.primary, redirectTo: String? = nil, full: Bool = false, emptyOutlet: Bool = false, guards: Int? = nil, data: [(String, Any?)] = [], children: [RouteConfig] = [], _ make: (() throws -> View)? = nil) {
73
+ segments = path.split(separator: "/").map(String.init)
74
+ self.outlet = outlet
75
+ self.redirectTo = redirectTo
76
+ self.full = full
77
+ self.emptyOutlet = emptyOutlet
78
+ self.guards = guards
79
+ self.data = data
80
+ self.children = children
81
+ self.make = make
82
+ }
83
+ }
84
+
85
+ /// Angular's `RouterStateSnapshot`, as guards receive it: a URL and the route it shows.
86
+ public final class RouterStateSnapshot: CustomStringConvertible {
87
+ nonisolated deinit {}
88
+ public let url: String
89
+ public let root: ActivatedRouteSnapshot
90
+ public init(_ url: String, _ root: ActivatedRouteSnapshot = ActivatedRouteSnapshot()) {
91
+ self.url = url
92
+ self.root = root
93
+ }
94
+ public func toString() -> String { url }
95
+ public var description: String { url }
96
+ }
97
+
98
+ /// A route guard compiled from the app, called with Angular's arguments for its kind (two, or four for canDeactivate).
99
+ public typealias RouteGuard = (Any?, Any?, Any?, Any?) throws -> Any?
100
+
101
+ private let routeKey = JSSymbol("NativeScriptKit:route")
102
+
103
+ extension Page {
104
+ /// `inject(Page)`: the routed page being built, else the page shown.
105
+ public static func injected() throws -> Page {
106
+ if let page = building.last { return page }
107
+ if let page = (try? Frame.topmost()?.currentPage) ?? nil { return page }
108
+ return try Page()
109
+ }
110
+
111
+ /// The route the router created the page for.
112
+ var route: ActivatedRoute? {
113
+ get { self[jsKey: routeKey.key] as? ActivatedRoute }
114
+ set { self[jsKey: routeKey.key] = newValue }
115
+ }
116
+ }
117
+
118
+ /// Angular's router with @nativescript/angular's `page-router-outlet`s and `RouterExtensions`, over core's
119
+ /// `Frame`: each outlet is a frame, a URL within an outlet resolves through the configuration to a component,
120
+ /// and navigating to a URL the outlet does not show creates a `Page`, renders the component into it and
121
+ /// navigates the frame to it with the extras' `animated`, `clearHistory` and `transition`, as `PageRouterOutlet`
122
+ /// does. Going back is the frame's: when a page is navigated from going back, its component is destroyed and
123
+ /// the outlet shows the URL of the page under it, as `PageRouterOutlet` and `NSLocationStrategy` handle it.
124
+ public final class Router {
125
+ nonisolated deinit {}
126
+ public static let primary = "primary"
127
+ public static let shared = Router()
128
+ /// The flat table of apps configured without a route tree.
129
+ public var routes: [Route] = []
130
+ public var initial = "/"
131
+ public var config: [RouteConfig] = []
132
+ /// `router.events`: a `NavigationEnd` after each navigation, back navigations included.
133
+ public let events = RxSubject<NavigationEnd>()
134
+ private var navigationId = 0.0
135
+
136
+ private final class Entry {
137
+ nonisolated deinit {}
138
+ let owner: Owner
139
+ let route: ActivatedRoute
140
+ /// The routes the page's URL resolved through, and the segments each consumed.
141
+ let match: Match?
142
+ /// The routed component, kept for canDeactivate guards.
143
+ var component: AnyObject?
144
+ init(owner: Owner, route: ActivatedRoute, match: Match?) { self.owner = owner; self.route = route; self.match = match }
145
+ }
146
+
147
+ /// A URL resolved through the configuration: the routes, root first, the segments each consumed, the parameters and
148
+ /// the URL once redirects applied.
149
+ private struct Match {
150
+ var chain: [RouteConfig]
151
+ var consumed: [[String]]
152
+ var params: [String: String]
153
+ var url: [String]
154
+ }
155
+
156
+ /// What a route's guards decided.
157
+ private enum Verdict { case pass, cancel, redirect(UrlTree) }
158
+
159
+ /// How an outlet's navigation ended.
160
+ private enum Shown { case unmatched, already, navigated, cancelled }
161
+
162
+ private var guardTable: [Int: [String: [RouteGuard]]] = [:]
163
+ /// The latest navigation: one whose guards settle after a newer one started is cancelled.
164
+ private var navigations = 0
165
+ /// The components of the pages being built, innermost last.
166
+ private var rendering: [AnyObject?] = []
167
+
168
+ private final class Outlet {
169
+ nonisolated deinit {}
170
+ weak var frame: Frame?
171
+ /// The frame of the `NSEmptyOutletComponent` page the outlet shows, where its routes' pages go.
172
+ weak var inner: Frame?
173
+ /// The frame the outlet's pages are in.
174
+ var shown: Frame? { inner ?? frame }
175
+ /// The configuration the outlet's URLs resolve against.
176
+ let routes: [RouteConfig]
177
+ /// The pages navigated to in this outlet and not navigated back from, the shown one last.
178
+ var entries: [Entry] = []
179
+ /// The injector of the view holding the outlet, which its routed components inject from.
180
+ let injector: Injector?
181
+ init(frame: Frame, routes: [RouteConfig], injector: Injector?) { self.frame = frame; self.routes = routes; self.injector = injector }
182
+ }
183
+ private var outlets: [String: Outlet] = [:]
184
+ /// Navigations to outlets not created yet, applied when they are.
185
+ private var pending: [String: [String]] = [:]
186
+ /// The outlets in the order they were last navigated, for `back()`.
187
+ private var history: [String] = []
188
+ /// A flat route table's outlet: the injector of the view holding it.
189
+ private var flatInjector: Injector?
190
+
191
+ /// A route guard of the route registered under `route` (`RouteConfig.guards`).
192
+ public func addGuard(_ route: Double, _ kind: String, _ run: @escaping RouteGuard) {
193
+ guardTable[Int(route), default: [:]][kind, default: []].append(run)
194
+ }
195
+
196
+ /// A routed component whose route has canDeactivate guards, kept as the page's component.
197
+ public func activating<C: AnyObject>(_ component: C) -> C {
198
+ if !rendering.isEmpty { rendering[rendering.count - 1] = component }
199
+ return component
200
+ }
201
+
202
+ /// A `page-router-outlet`: a frame showing its outlet's URL. A route that fails to render is reported and the frame stays empty.
203
+ public func outlet(_ name: String = Router.primary) throws -> View {
204
+ let frame = try Frame()
205
+ if config.isEmpty {
206
+ flatInjector = Injector.current
207
+ if let (route, params) = resolveFlatRoute(initial) { jsReport { try push(route.make, ActivatedRoute(params: params), into: frame, extras: nil, injector: flatInjector) } }
208
+ return frame
209
+ }
210
+ outlets[name] = Outlet(frame: frame, routes: name == Router.primary ? config : Router.routes(in: config, outlet: name), injector: Injector.current)
211
+ let url = name == Router.primary ? [] : pending.removeValue(forKey: name)
212
+ if let url {
213
+ show(name, url, extras: nil, token: begin(), { [weak self] shown in
214
+ if case .redirect(let tree) = shown { self?.navigateByUrl(tree); return }
215
+ if name == Router.primary, case .done(.navigated) = shown { self?.ended(url: "/") }
216
+ }, jsReportUncaught)
217
+ }
218
+ return frame
219
+ }
220
+
221
+ /// A navigation whose component throws shows nothing new, and its promise rejects with the error, as Angular's router's does.
222
+ @discardableResult
223
+ public func navigate(_ commands: [Any], _ extras: Any? = nil) -> JSPromise<Bool> {
224
+ let (promise, resolvers) = JSPromise<Bool>.pending()
225
+ do { try navigation(commands, extras, { resolvers.resolve($0) }, { resolvers.reject($0) }) } catch { resolvers.reject(jsCaught(error)) }
226
+ return promise
227
+ }
228
+
229
+ /// A navigation's token: navigations a component starts while its page is built belong to the one building it.
230
+ private func begin() -> Int {
231
+ if Page.building.isEmpty { navigations += 1 }
232
+ return navigations
233
+ }
234
+
235
+ private func navigation(_ commands: [Any], _ extras: Any?, _ done: @escaping (Bool) -> Void, _ fail: @escaping (Any?) -> Void) throws {
236
+ if config.isEmpty {
237
+ let path = commands.map { jsToString($0) }.joined(separator: "/")
238
+ guard let (route, params) = resolveFlatRoute(path), let frame = (try? Frame.topmost()) as? Frame else { return done(false) }
239
+ try push(route.make, ActivatedRoute(params: params), into: frame, extras: extras, injector: flatInjector)
240
+ ended(url: "/" + path.split(separator: "/").joined(separator: "/"))
241
+ return done(true)
242
+ }
243
+ let relativeTo = (field(extras, "relativeTo") as? ActivatedRoute) ?? (field(field(extras, "relativeTo"), "_kit") as? ActivatedRoute)
244
+ var targets: [(outlet: String, url: [String])] = []
245
+ var segments: [String] = []
246
+ var absolute = false
247
+ for (i, command) in commands.enumerated() {
248
+ if let text = command as? String {
249
+ if i == 0, text.hasPrefix("/") { absolute = true }
250
+ segments += text.split(separator: "/").map(String.init)
251
+ } else if let outlets = field(command, "outlets") {
252
+ for key in jsKeysOf(outlets) {
253
+ let commands = (try? jsItemsOf(field(outlets, key))) ?? []
254
+ let url = commands.flatMap { jsToString($0).split(separator: "/").map(String.init) }
255
+ targets.append((key, url))
256
+ }
257
+ } else {
258
+ segments.append(jsToString(command))
259
+ }
260
+ }
261
+ if !segments.isEmpty {
262
+ if absolute || relativeTo == nil {
263
+ targets.insert((Router.primary, segments), at: 0)
264
+ } else if let base = relativeTo {
265
+ var url = base.url
266
+ for s in segments {
267
+ if s == ".." { if !url.isEmpty { url.removeLast() } } else if s != "." { url.append(s) }
268
+ }
269
+ targets.insert((base.outlet, url), at: 0)
270
+ }
271
+ }
272
+ let token = begin()
273
+ let several = targets.count > 1
274
+ var ok = true
275
+ var navigated = false
276
+ var rest = targets[...]
277
+ // Outlet by outlet: one whose guards return a promise continues when it settles.
278
+ func next() {
279
+ guard let (name, url) = rest.popFirst() else {
280
+ if navigated { ended(url: absolute || relativeTo == nil ? "/" + segments.joined(separator: "/") : self.url) }
281
+ return done(ok)
282
+ }
283
+ // The primary URL `/home` with outlets names the route holding them, already shown.
284
+ if name == Router.primary, several, current(Router.primary)?.first == url.first { return next() }
285
+ guard outlets[name]?.frame != nil else {
286
+ pending[name] = url
287
+ return next()
288
+ }
289
+ show(name, url, extras: extras, token: token, { [weak self] outcome in
290
+ switch outcome {
291
+ case .redirect(let tree):
292
+ // The first navigation's promise takes the redirect's result, as Angular's does.
293
+ guard let self else { return done(false) }
294
+ let str = tree.toString()
295
+ do { try self.navigation([str.hasPrefix("/") ? str : "/" + str], extras, done, fail) } catch { fail(jsCaught(error)) }
296
+ case .done(.cancelled):
297
+ done(false)
298
+ case .done(let shown):
299
+ ok = shown != .unmatched && ok
300
+ navigated = navigated || shown == .navigated
301
+ next()
302
+ }
303
+ }, fail)
304
+ }
305
+ next()
306
+ }
307
+
308
+ /// `navigate(['/recipe', id])` as translated code passes it.
309
+ @discardableResult
310
+ public func navigate(_ commands: JSArray<Any?>, _ extras: Any? = nil) -> JSPromise<Bool> {
311
+ navigate(commands.storage.map { $0 ?? "" }, extras)
312
+ }
313
+
314
+ /// `navigateByUrl(url, extras)`.
315
+ @discardableResult
316
+ public func navigateByUrl(_ url: Any?, _ extras: Any? = nil) -> JSPromise<Bool> {
317
+ let str = (jsFlat(url) as? UrlTree)?.toString() ?? jsToString(url)
318
+ return navigate([str.hasPrefix("/") ? str : "/" + str], extras)
319
+ }
320
+
321
+ /// `back()`: the outlet of the given route, else the one navigated last that can go back, else the topmost frame.
322
+ public func back(_ options: Any? = nil) {
323
+ jsReport {
324
+ if let route = (field(options, "relativeTo") as? ActivatedRoute) ?? (field(field(options, "relativeTo"), "_kit") as? ActivatedRoute), let frame = outlets[route.outlet]?.shown, try frame.canGoBack() {
325
+ try frame.goBack()
326
+ return
327
+ }
328
+ for name in history.reversed() {
329
+ if let frame = outlets[name]?.shown, try frame.canGoBack() { try frame.goBack(); return }
330
+ }
331
+ _ = try Frame.goBack()
332
+ }
333
+ }
334
+
335
+ public func backToPreviousPage() {
336
+ back()
337
+ }
338
+
339
+ /// `RouterExtensions.router`: the router itself.
340
+ public var router: Router { self }
341
+
342
+ /// `router.url`: the primary outlet's URL.
343
+ public var url: String { "/" + (current(Router.primary) ?? []).joined(separator: "/") }
344
+
345
+ public var routerState: JSObject {
346
+ JSObject([
347
+ ("snapshot", JSObject([("url", url), ("root", ActivatedRoute.current.snapshot)])),
348
+ ("root", ActivatedRoute.current),
349
+ ])
350
+ }
351
+
352
+ public func createUrlTree(_ commands: Any?, _ extras: Any? = nil) -> UrlTree {
353
+ let items = (jsFlat(commands) as? JSArrayProtocol)?.jsAnyElements ?? []
354
+ let joined = items.map { jsToString($0) }.joined(separator: "/").trimmingCharacters(in: CharacterSet(charactersIn: "/"))
355
+ let path = "/" + joined
356
+ let q = field(extras, "queryParams")
357
+ let f = field(extras, "fragment") as? String
358
+ return UrlTree(path, q, f)
359
+ }
360
+
361
+ public func serializeUrl(_ tree: Any?) -> String {
362
+ (jsFlat(tree) as? UrlTree)?.toString() ?? jsToString(tree)
363
+ }
364
+
365
+ public func parseUrl(_ url: String) -> UrlTree {
366
+ DefaultUrlSerializer().parse(url)
367
+ }
368
+
369
+ public func isActive(_ url: Any?, _ exact: Any? = false) -> Bool {
370
+ let target = (jsFlat(url) as? UrlTree)?.toString() ?? jsToString(url)
371
+ let isExact: Bool = {
372
+ if let b = jsFlat(exact) as? Bool { return b }
373
+ return (field(exact, "paths") as? String) == "exact"
374
+ }()
375
+ return isExact ? self.url == target : self.url.hasPrefix(target)
376
+ }
377
+
378
+ public func canGoBack(_ options: Any? = nil) -> Bool {
379
+ history.contains { name in (try? outlets[name]?.shown?.canGoBack()) ?? false }
380
+ }
381
+
382
+ public func canGoBackToPreviousPage() -> Bool {
383
+ canGoBack()
384
+ }
385
+
386
+ /// The routes of a named outlet, wherever in the configuration they are.
387
+ private static func routes(in routes: [RouteConfig], outlet: String) -> [RouteConfig] {
388
+ routes.filter { $0.outlet == outlet } + routes.flatMap { Router.routes(in: $0.children, outlet: outlet) }
389
+ }
390
+
391
+ /// The URL an outlet shows: its last page's.
392
+ private func current(_ name: String) -> [String]? { outlets[name]?.entries.last?.route.url }
393
+
394
+ private func ended(url: String) {
395
+ navigationId += 1
396
+ events.next(NavigationEnd(id: navigationId, url: url, urlAfterRedirects: self.url))
397
+ }
398
+
399
+ private enum Outcome { case done(Shown), redirect(UrlTree) }
400
+
401
+ /// An outlet's navigation to a URL, as Angular's router runs it: canMatch while the URL is matched (a route whose
402
+ /// guards return false is passed over), canDeactivate of the routes the outlet leaves, then canActivateChild and
403
+ /// canActivate of each route it activates, root first. Guards that all return synchronously keep the navigation
404
+ /// synchronous. A navigation is never guarded going back: the frame has gone back already, as with
405
+ /// @nativescript/angular, which lets the router catch up after the frame.
406
+ private func show(_ name: String, _ url: [String], extras: Any?, token: Int, _ done: @escaping (Outcome) -> Void, _ fail: @escaping (Any?) -> Void) {
407
+ guard let outlet = outlets[name] else { return done(.done(.unmatched)) }
408
+ let candidates = matches(outlet.routes, url, outlet: name == Router.primary ? Router.primary : nil).filter { $0.chain.last?.make != nil }
409
+ let current = outlet.entries.last
410
+ let currentUrl = "/" + (current?.route.url ?? []).joined(separator: "/")
411
+ var matched: [ObjectIdentifier: Bool] = [:]
412
+ var index = 0
413
+ func candidate() {
414
+ guard token == navigations else { return done(.done(.cancelled)) }
415
+ guard index < candidates.count else { return done(.done(.unmatched)) }
416
+ let found = candidates[index]
417
+ index += 1
418
+ if found.chain.contains(where: { matched[ObjectIdentifier($0)] == false }) { return candidate() }
419
+ let segments = JSArray(url.map { UrlSegment($0) })
420
+ let unchecked = found.chain.filter { matched[ObjectIdentifier($0)] == nil && !guards($0, "canMatch").isEmpty }
421
+ var routes = unchecked[...]
422
+ func canMatch() {
423
+ guard let route = routes.popFirst() else { return activate(found) }
424
+ check([guards(route, "canMatch").map { g in { try g(JSObject([("path", route.segments.joined(separator: "/"))]), segments, nil, nil) } }], outlet: outlet, { verdict in
425
+ switch verdict {
426
+ case .pass: matched[ObjectIdentifier(route)] = true; canMatch()
427
+ case .cancel: matched[ObjectIdentifier(route)] = false; candidate()
428
+ case .redirect(let tree): done(.redirect(tree))
429
+ }
430
+ }, fail)
431
+ }
432
+ canMatch()
433
+ }
434
+ func activate(_ found: Match) {
435
+ guard token == navigations else { return done(.done(.cancelled)) }
436
+ if current?.route.url == found.url { return done(.done(.already)) }
437
+ let route = ActivatedRoute(params: found.params, outlet: name, url: found.url, data: found.chain.last?.data ?? [])
438
+ let nextUrl = "/" + found.url.joined(separator: "/")
439
+ // Routes the outlet shows already, with the same segments, are reused: their guards don't run again.
440
+ var reused = 0
441
+ if let old = current?.match {
442
+ while reused < min(old.chain.count, found.chain.count), old.chain[reused] === found.chain[reused], old.consumed[reused] == found.consumed[reused] { reused += 1 }
443
+ }
444
+ var groups: [[() throws -> Any?]] = []
445
+ if let current, let old = current.match {
446
+ let currentState = RouterStateSnapshot(currentUrl, current.route.snapshot)
447
+ let nextState = RouterStateSnapshot(nextUrl, route.snapshot)
448
+ for (i, left) in old.chain.enumerated().dropFirst(reused).reversed() {
449
+ let component = i == old.chain.count - 1 ? current.component : nil
450
+ let calls = guards(left, "canDeactivate").map { g in { try g(component, current.route.snapshot, currentState, nextState) } }
451
+ if !calls.isEmpty { groups.append(calls) }
452
+ }
453
+ }
454
+ let state = RouterStateSnapshot(nextUrl, route.snapshot)
455
+ for i in reused..<found.chain.count {
456
+ let children = found.chain[..<i].reversed().flatMap { guards($0, "canActivateChild") }.map { g in { try g(route.snapshot, state, nil, nil) } }
457
+ if !children.isEmpty { groups.append(children) }
458
+ let calls = guards(found.chain[i], "canActivate").map { g in { try g(route.snapshot, state, nil, nil) } }
459
+ if !calls.isEmpty { groups.append(calls) }
460
+ }
461
+ check(groups, outlet: outlet, { [weak self] verdict in
462
+ guard let self, token == self.navigations else { return done(.done(.cancelled)) }
463
+ switch verdict {
464
+ case .cancel: return done(.done(.cancelled))
465
+ case .redirect(let tree): return done(.redirect(tree))
466
+ case .pass: break
467
+ }
468
+ guard var frame = outlet.frame, let make = found.chain.last?.make else { return done(.done(.unmatched)) }
469
+ if found.chain.contains(where: { $0.emptyOutlet }) {
470
+ if outlet.inner == nil { outlet.inner = self.emptyOutlet(in: frame) }
471
+ if let inner = outlet.inner { frame = inner }
472
+ }
473
+ self.history.removeAll { $0 == name }
474
+ self.history.append(name)
475
+ do { try self.push(make, route, into: frame, extras: extras, outlet: outlet, injector: outlet.injector, match: found) } catch { return fail(jsCaught(error)) }
476
+ done(.done(.navigated))
477
+ }, fail)
478
+ }
479
+ candidate()
480
+ }
481
+
482
+ private func guards(_ route: RouteConfig, _ kind: String) -> [RouteGuard] {
483
+ route.guards.flatMap { guardTable[$0]?[kind] } ?? []
484
+ }
485
+
486
+ /// Guards group by group, in the outlet's injection context. Each group's guards are all called first, then the first
487
+ /// result that isn't true decides (Angular's prioritizedGuardValue): false cancels, a UrlTree redirects, and anything
488
+ /// else passes. A promise defers what follows until it settles.
489
+ private func check(_ groups: [[() throws -> Any?]], outlet: Outlet, _ next: @escaping (Verdict) -> Void, _ fail: @escaping (Any?) -> Void) {
490
+ var rest = groups[...]
491
+ func group() {
492
+ guard let calls = rest.popFirst() else { return next(.pass) }
493
+ let results: [Any?]
494
+ do { results = try Injector.runInContext(outlet.injector) { try calls.map { try $0() } } } catch { return fail(jsCaught(error)) }
495
+ func result(_ i: Int) {
496
+ guard i < results.count else { return group() }
497
+ let decide = { (value: Any?) in
498
+ if let tree = jsFlat(value) as? UrlTree { next(.redirect(tree)) } else if (jsFlat(value) as? Bool) == false { next(.cancel) } else { result(i + 1) }
499
+ }
500
+ if let promise = jsFlat(results[i]) as? JSThenable { promise.jsSubscribe(decide, fail) } else { decide(results[i]) }
501
+ }
502
+ result(0)
503
+ }
504
+ group()
505
+ }
506
+
507
+ /// `PageRouterOutlet.activateOnGoForward` and `loadComponentInPage`: a new page, the component rendered into
508
+ /// it in a scope of its own, and the frame navigated to it. A component that throws leaves the outlet as it was.
509
+ private func push(_ make: () throws -> View, _ route: ActivatedRoute, into frame: Frame, extras: Any?, outlet: Outlet? = nil, injector: Injector?, match: Match? = nil) throws {
510
+ let page = try Page()
511
+ page.route = route
512
+ let owner = Owner(parent: nil)
513
+ // Shown before the component renders, as Angular's URL is current by activation: a navigation the
514
+ // component makes while rendering (a tab view filling its outlets) finds this route already there.
515
+ let entry = Entry(owner: owner, route: route, match: match)
516
+ outlet?.entries.append(entry)
517
+ let previousRoute = ActivatedRoute.current
518
+ ActivatedRoute.current = route
519
+ Page.building.append(page)
520
+ rendering.append(nil)
521
+ let pending = Reactivity.pending()
522
+ let view: View
523
+ do {
524
+ defer {
525
+ Page.building.removeLast()
526
+ entry.component = rendering.removeLast()
527
+ }
528
+ view = try owner.run { try Injector.runInContext(injector, make) }
529
+ } catch {
530
+ owner.dispose()
531
+ outlet?.entries.removeAll { $0 === entry }
532
+ ActivatedRoute.current = previousRoute
533
+ throw error
534
+ }
535
+ if view !== page { page.content = view }
536
+ if Reactivity.schedule == .task { Reactivity.detectChanges(after: pending) }
537
+ try page.on(Page.navigatedFromEvent, { [weak self, weak outlet] (data: EventData?) in
538
+ guard jsTruthy(data?[jsKey: "isBackNavigation"]) else { return }
539
+ owner.dispose()
540
+ guard let self, let outlet, let at = outlet.entries.firstIndex(where: { $0 === entry }) else { return }
541
+ outlet.entries.remove(at: at)
542
+ self.ended(url: self.url)
543
+ })
544
+ let clearHistory = jsTruthy(field(extras, "clearHistory"))
545
+ if clearHistory, let outlet {
546
+ try page.once(Page.navigatedToEvent, { [weak outlet] (_: EventData?) in
547
+ guard let outlet else { return }
548
+ let cleared = outlet.entries.filter { $0 !== entry }
549
+ outlet.entries.removeAll { $0 !== entry }
550
+ for old in cleared { old.owner.dispose() }
551
+ })
552
+ }
553
+ var navigation: [(String, Any?)] = [
554
+ ("create", { (_: [Any?]) throws -> Any? in page } as JSFunction),
555
+ ("clearHistory", clearHistory),
556
+ ("animated", field(extras, "animated").map { jsTruthy($0) } ?? true),
557
+ ]
558
+ if let transition = field(extras, "transition") { navigation.append(("transition", transition)) }
559
+ try frame.navigate(JSObject(navigation))
560
+ }
561
+
562
+ /// `NSEmptyOutletComponent` in `frame`: a page without an action bar holding a `page-router-outlet` that takes the
563
+ /// outer outlet's action bar visibility.
564
+ private func emptyOutlet(in frame: Frame) -> Frame? {
565
+ jsReported {
566
+ let page = try Page()
567
+ page.actionBarHidden = true
568
+ let inner = try Frame()
569
+ let visibility = frame.actionBarVisibility
570
+ if ["auto", "always", "never"].contains(visibility) { inner.actionBarVisibility = visibility }
571
+ page.content = inner
572
+ try frame.navigate(JSObject([("create", { (_: [Any?]) throws -> Any? in page } as JSFunction), ("clearHistory", false), ("animated", true)]))
573
+ return inner
574
+ }
575
+ }
576
+
577
+ /// Every way a URL resolves through the routes, in the order Angular's router tries them. A redirect that applies
578
+ /// ends the search, as in Angular.
579
+ private func matches(_ routes: [RouteConfig], _ url: [String], outlet: String?) -> [Match] {
580
+ var found: [Match] = []
581
+ for route in routes where outlet == nil || route.outlet == outlet {
582
+ if let redirect = route.redirectTo {
583
+ let applies = route.full ? url == route.segments : Array(url.prefix(route.segments.count)) == route.segments
584
+ guard applies else { continue }
585
+ let target = redirect.split(separator: "/").map(String.init) + url.dropFirst(route.segments.count)
586
+ return found + (redirect.hasPrefix("/") ? matches(config, target, outlet: Router.primary) : matches(routes, target, outlet: outlet))
587
+ }
588
+ guard url.count >= route.segments.count else { continue }
589
+ var params: [String: String] = [:]
590
+ var matched = true
591
+ for (pattern, part) in zip(route.segments, url) {
592
+ if pattern.hasPrefix(":") { params[String(pattern.dropFirst())] = part.removingPercentEncoding ?? part }
593
+ else if pattern != part { matched = false; break }
594
+ }
595
+ guard matched else { continue }
596
+ let own = Array(url.prefix(route.segments.count))
597
+ let rest = Array(url.dropFirst(route.segments.count))
598
+ if route.make != nil && rest.isEmpty { found.append(Match(chain: [route], consumed: [own], params: params, url: route.segments.isEmpty ? [] : url)) }
599
+ let children = route.children.filter { $0.outlet == Router.primary }
600
+ for inner in children.isEmpty ? [] : matches(children, rest, outlet: Router.primary) {
601
+ found.append(Match(chain: [route] + inner.chain, consumed: [own] + inner.consumed, params: params.merging(inner.params) { $1 }, url: own + inner.url))
602
+ }
603
+ }
604
+ return found
605
+ }
606
+
607
+ private func resolveFlatRoute(_ path: String) -> (Route, [String: String])? {
608
+ let parts = path.split(separator: "/").map(String.init)
609
+ for route in routes where route.segments.count == parts.count {
610
+ var params: [String: String] = [:]
611
+ var matched = true
612
+ for (pattern, part) in zip(route.segments, parts) {
613
+ if pattern.hasPrefix(":") { params[String(pattern.dropFirst())] = part.removingPercentEncoding ?? part }
614
+ else if pattern != part { matched = false; break }
615
+ }
616
+ if matched { return (route, params) }
617
+ }
618
+ return nil
619
+ }
620
+ }
621
+
622
+ /// A key of an options object script passes, nil when absent.
623
+ private func field(_ object: Any?, _ key: String) -> Any? { object == nil ? nil : (try? jsGet(object, key)) ?? nil }
624
+
625
+ public typealias KitRouter = Router
626
+ public typealias KitActivatedRoute = ActivatedRoute