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