@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.
- package/dist/angular-libraries.js +173 -0
- package/dist/angular.js +2895 -0
- package/dist/component-bases.js +746 -0
- package/dist/core-api.js +8 -0
- package/dist/entry.js +118 -0
- package/dist/index.js +157 -0
- package/dist/kotlin.js +280 -0
- package/dist/modules.js +698 -0
- package/dist/ng-modules.js +66 -0
- package/dist/package.js +15 -0
- package/dist/refusals.js +5 -0
- package/dist/semantics.js +213 -0
- package/dist/swift.js +340 -0
- package/kit-android/fromcore/AngularAPI.kt +172 -0
- package/kit-android/fromcore/AngularRouter.kt +587 -0
- package/kit-android/handport/Router.kt +151 -0
- package/kit-android/main/AngularChangeDetection.kt +250 -0
- package/kit-android/main/AngularCore.kt +685 -0
- package/kit-android/main/AngularHttp.kt +431 -0
- package/kit-android/main/AngularRouterValues.kt +154 -0
- package/kit-android/main/AngularRx.kt +224 -0
- package/kit-apple/AngularAPI.swift +224 -0
- package/kit-apple/AngularChangeDetection.swift +248 -0
- package/kit-apple/AngularCore.swift +764 -0
- package/kit-apple/AngularHttp.swift +467 -0
- package/kit-apple/AngularRouter.swift +626 -0
- package/kit-apple/AngularRouterValues.swift +285 -0
- package/kit-apple/AngularRx.swift +246 -0
- package/kit-apple/kit-index.json +739 -0
- package/package.json +53 -4
- package/runtime/angular-forms.ts +3099 -0
- package/runtime/angular-rx.ts +550 -0
- package/runtime/angular.ts +826 -0
- package/README.md +0 -3
|
@@ -0,0 +1,587 @@
|
|
|
1
|
+
package org.nativescript.kit
|
|
2
|
+
|
|
3
|
+
import java.net.URLDecoder
|
|
4
|
+
|
|
5
|
+
// Angular's router with @nativescript/angular's page-router-outlets and RouterExtensions, over the
|
|
6
|
+
// Frame and Page compiled from core (kit-apple's Router.swift).
|
|
7
|
+
|
|
8
|
+
/** The route a component was created for (Angular `ActivatedRoute`): set by the router before it constructs the routed component. */
|
|
9
|
+
class ActivatedRoute(
|
|
10
|
+
params: Map<String, String>,
|
|
11
|
+
val outlet: String = Router.PRIMARY,
|
|
12
|
+
internal val url: List<String> = emptyList(),
|
|
13
|
+
queryParams: Map<String, String> = emptyMap(),
|
|
14
|
+
data: Map<String, Any?> = emptyMap(),
|
|
15
|
+
) {
|
|
16
|
+
val snapshot = ActivatedRouteSnapshot(
|
|
17
|
+
params = JSRecord(params.toList()),
|
|
18
|
+
queryParams = JSRecord(queryParams.toList()),
|
|
19
|
+
data = JSRecord(data.toList()),
|
|
20
|
+
url = JSArray(url.map { UrlSegment(it) }.toMutableList()),
|
|
21
|
+
fragment = null,
|
|
22
|
+
outlet = outlet,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
/** `route.params`: the route's parameters, replayed to each subscriber. */
|
|
26
|
+
val params = RxBehaviorSubject(snapshot.params)
|
|
27
|
+
val queryParams = RxBehaviorSubject(snapshot.queryParams)
|
|
28
|
+
val data = RxBehaviorSubject(snapshot.data)
|
|
29
|
+
val paramMap = RxBehaviorSubject(ParamMap(snapshot.params))
|
|
30
|
+
val queryParamMap = RxBehaviorSubject(ParamMap(snapshot.queryParams))
|
|
31
|
+
val fragment = RxBehaviorSubject<String?>(null)
|
|
32
|
+
val title = RxBehaviorSubject<String?>(null)
|
|
33
|
+
var routeConfig: JSObject? = null
|
|
34
|
+
|
|
35
|
+
val root: ActivatedRoute get() = this
|
|
36
|
+
val parent: ActivatedRoute? get() = null
|
|
37
|
+
val firstChild: ActivatedRoute? get() = null
|
|
38
|
+
val children: JSArray<ActivatedRoute> get() = JSArray()
|
|
39
|
+
val pathFromRoot: JSArray<ActivatedRoute> get() = JSArray(mutableListOf(this))
|
|
40
|
+
|
|
41
|
+
companion object {
|
|
42
|
+
var current = ActivatedRoute(emptyMap())
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** A route of a flat table (an app configured without a route tree). */
|
|
47
|
+
class Route(path: String, internal val make: () -> View) {
|
|
48
|
+
internal val segments = path.split("/").filter { it.isNotEmpty() }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* A route of the app's configuration (Angular's `Route`), lazy children and components resolved at compile time; [data]
|
|
53
|
+
* is the route's with what it inherits from its parents.
|
|
54
|
+
*/
|
|
55
|
+
class RouteConfig(path: String, internal val outlet: String = Router.PRIMARY, internal val redirectTo: String? = null, internal val full: Boolean = false, internal val guards: Int? = null, internal val data: List<Pair<String, Any?>> = emptyList(), internal val children: List<RouteConfig> = emptyList(), internal val make: (() -> View)? = null) {
|
|
56
|
+
internal val segments = path.split("/").filter { it.isNotEmpty() }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Angular's `RouterStateSnapshot`, as guards receive it: a URL and the route it shows. */
|
|
60
|
+
class RouterStateSnapshot(val url: String, val root: ActivatedRouteSnapshot = ActivatedRouteSnapshot()) {
|
|
61
|
+
override fun toString(): String = url
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** A route guard compiled from the app, called with Angular's arguments for its kind (two, or four for canDeactivate). */
|
|
65
|
+
typealias RouteGuard = (Any?, Any?, Any?, Any?) -> Any?
|
|
66
|
+
|
|
67
|
+
private val routeKey = jsSymbol("NativeScriptKit:route")
|
|
68
|
+
|
|
69
|
+
/** `inject(Page)`: the routed page being built, else the page shown. */
|
|
70
|
+
fun injectedPage(): Page = pagesBuilding.lastOrNull() ?: (FrameBase.topmost()?.currentPage as? Page) ?: Page()
|
|
71
|
+
|
|
72
|
+
private var Page.route: ActivatedRoute?
|
|
73
|
+
get() = jsGet(this, routeKey.key) as? ActivatedRoute
|
|
74
|
+
set(value) = jsSet(this, routeKey.key, value)
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Each outlet is a frame; a URL within an outlet resolves through the configuration to a component, and
|
|
78
|
+
* navigating to a URL the outlet does not show creates a Page, renders the component into it and navigates
|
|
79
|
+
* the frame to it with the extras' `animated`, `clearHistory` and `transition`, as PageRouterOutlet does.
|
|
80
|
+
* Going back is the frame's: when a page is navigated from going back, its component is destroyed and the
|
|
81
|
+
* outlet shows the URL of the page under it.
|
|
82
|
+
*/
|
|
83
|
+
class Router {
|
|
84
|
+
/** The flat table of apps configured without a route tree. */
|
|
85
|
+
var routes: List<Route> = emptyList()
|
|
86
|
+
var initial = "/"
|
|
87
|
+
var config: List<RouteConfig> = emptyList()
|
|
88
|
+
/** `router.events`: a NavigationEnd after each navigation, back navigations included. */
|
|
89
|
+
val events = RxSubject<NavigationEnd>()
|
|
90
|
+
private var navigationId = 0.0
|
|
91
|
+
|
|
92
|
+
/** [match]: the routes the page's URL resolved through; [component]: the routed component, kept for canDeactivate guards. */
|
|
93
|
+
private class Entry(val owner: Owner, val route: ActivatedRoute, val match: Match?) {
|
|
94
|
+
var component: Any? = null
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** A URL resolved through the configuration: the routes, root first, the segments each consumed, the parameters and the URL once redirects applied. */
|
|
98
|
+
private class Match(val chain: List<RouteConfig>, val consumed: List<List<String>>, val params: Map<String, String>, val url: List<String>)
|
|
99
|
+
|
|
100
|
+
/** How an outlet's navigation ended, or where its guards redirect it. */
|
|
101
|
+
private sealed class Outcome {
|
|
102
|
+
class Done(val shown: Shown) : Outcome()
|
|
103
|
+
class Redirect(val tree: UrlTree) : Outcome()
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** How an outlet's navigation ended. */
|
|
107
|
+
private enum class Shown { UNMATCHED, ALREADY, NAVIGATED, CANCELLED }
|
|
108
|
+
|
|
109
|
+
private val guardTable = HashMap<Int, HashMap<String, MutableList<RouteGuard>>>()
|
|
110
|
+
/** The latest navigation: one whose guards settle after a newer one started is cancelled. */
|
|
111
|
+
private var navigations = 0
|
|
112
|
+
/** The components of the pages being built, innermost last. */
|
|
113
|
+
private val rendering = ArrayList<Any?>()
|
|
114
|
+
|
|
115
|
+
/** [injector]: the injector of the view holding the outlet, which its routed components inject from. */
|
|
116
|
+
private class Outlet(frame: Frame, val routes: List<RouteConfig>, val injector: Injector?) {
|
|
117
|
+
private val frameRef = java.lang.ref.WeakReference(frame)
|
|
118
|
+
val frame: Frame? get() = frameRef.get()
|
|
119
|
+
/** The pages navigated to in this outlet and not navigated back from, the shown one last. */
|
|
120
|
+
val entries = ArrayList<Entry>()
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
private val outlets = HashMap<String, Outlet>()
|
|
124
|
+
/** Navigations to outlets not created yet, applied when they are. */
|
|
125
|
+
private val pending = HashMap<String, List<String>>()
|
|
126
|
+
/** The outlets in the order they were last navigated, for `back()`. */
|
|
127
|
+
private val history = ArrayList<String>()
|
|
128
|
+
/** A flat route table's outlet: the injector of the view holding it. */
|
|
129
|
+
private var flatInjector: Injector? = null
|
|
130
|
+
|
|
131
|
+
/** The app ended (core's exit event): every routed component is destroyed, newest first, and the outlets forgotten. */
|
|
132
|
+
fun destroy() {
|
|
133
|
+
for (outlet in outlets.values) for (entry in outlet.entries.asReversed()) entry.owner.dispose()
|
|
134
|
+
outlets.clear()
|
|
135
|
+
pending.clear()
|
|
136
|
+
history.clear()
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** A route guard of the route registered under [route] (`RouteConfig.guards`). */
|
|
140
|
+
fun addGuard(route: Double, kind: String, guard: RouteGuard) {
|
|
141
|
+
guardTable.getOrPut(route.toInt()) { HashMap() }.getOrPut(kind) { ArrayList() }.add(guard)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** A routed component whose route has canDeactivate guards, kept as the page's component. */
|
|
145
|
+
fun <C> activating(component: C): C {
|
|
146
|
+
if (rendering.isNotEmpty()) rendering[rendering.size - 1] = component
|
|
147
|
+
return component
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** A `page-router-outlet`: a frame showing its outlet's URL. A route that fails to render is reported and the frame stays empty. */
|
|
151
|
+
fun outlet(name: String = PRIMARY): View {
|
|
152
|
+
val frame = Frame()
|
|
153
|
+
if (config.isEmpty()) {
|
|
154
|
+
flatInjector = Injector.current
|
|
155
|
+
resolveFlatRoute(initial)?.let { (route, params) -> jsReport { push(route.make, ActivatedRoute(params), frame, null, injector = flatInjector) } }
|
|
156
|
+
return frame
|
|
157
|
+
}
|
|
158
|
+
outlets[name] = Outlet(frame, if (name == PRIMARY) config else routesIn(config, name), Injector.current)
|
|
159
|
+
val url = if (name == PRIMARY) emptyList() else pending.remove(name)
|
|
160
|
+
if (url != null) {
|
|
161
|
+
show(name, url, null, begin(), { outcome ->
|
|
162
|
+
if (outcome is Outcome.Redirect) navigateByUrl(outcome.tree)
|
|
163
|
+
else if (name == PRIMARY && (outcome as Outcome.Done).shown == Shown.NAVIGATED) ended("/")
|
|
164
|
+
}, ::jsReportUncaught)
|
|
165
|
+
}
|
|
166
|
+
return frame
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
fun navigate(commands: JSArray<*>, extras: Any? = null): JSPromise<Boolean> = navigate(commands.storage.toList(), extras)
|
|
170
|
+
|
|
171
|
+
/** A navigation whose component throws shows nothing new, and its promise rejects with the error, as Angular's router's does. */
|
|
172
|
+
fun navigate(commands: List<Any?>, extras: Any? = null): JSPromise<Boolean> {
|
|
173
|
+
val (promise, resolvers) = JSPromise.pending<Boolean>()
|
|
174
|
+
try {
|
|
175
|
+
navigation(commands, extras, { resolvers.resolve(it) }, { resolvers.reject(it) })
|
|
176
|
+
} catch (e: Throwable) {
|
|
177
|
+
resolvers.reject(jsCaught(e))
|
|
178
|
+
}
|
|
179
|
+
return promise
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** A navigation's token: navigations a component starts while its page is built belong to the one building it. */
|
|
183
|
+
private fun begin(): Int {
|
|
184
|
+
if (pagesBuilding.isEmpty()) navigations += 1
|
|
185
|
+
return navigations
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
private fun navigation(commands: List<Any?>, extras: Any?, done: (Boolean) -> Unit, fail: (Any?) -> Unit) {
|
|
189
|
+
if (config.isEmpty()) {
|
|
190
|
+
val path = commands.joinToString("/") { jsToString(it) }
|
|
191
|
+
val (route, params) = resolveFlatRoute(path) ?: return done(false)
|
|
192
|
+
val frame = FrameBase.topmost() as? Frame ?: return done(false)
|
|
193
|
+
push(route.make, ActivatedRoute(params), frame, extras, injector = flatInjector)
|
|
194
|
+
ended("/" + path.split("/").filter { it.isNotEmpty() }.joinToString("/"))
|
|
195
|
+
return done(true)
|
|
196
|
+
}
|
|
197
|
+
val relativeTo = routeOf(field(extras, "relativeTo"))
|
|
198
|
+
val targets = ArrayList<Pair<String, List<String>>>()
|
|
199
|
+
val segments = ArrayList<String>()
|
|
200
|
+
var absolute = false
|
|
201
|
+
for ((i, command) in commands.withIndex()) {
|
|
202
|
+
val outletsOf = if (command is String) null else field(command, "outlets")
|
|
203
|
+
when {
|
|
204
|
+
command is String -> {
|
|
205
|
+
if (i == 0 && command.startsWith("/")) absolute = true
|
|
206
|
+
segments += command.split("/").filter { it.isNotEmpty() }
|
|
207
|
+
}
|
|
208
|
+
outletsOf != null -> for (key in (outletsOf as? JSDynamic)?.jsKeys ?: emptyList()) {
|
|
209
|
+
val items = (jsBox(field(outletsOf, key)) as? JSArray<*>)?.storage ?: emptyList<Any?>()
|
|
210
|
+
targets.add(key to items.flatMap { jsToString(it).split("/").filter { s -> s.isNotEmpty() } })
|
|
211
|
+
}
|
|
212
|
+
else -> segments.add(jsToString(command))
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
if (segments.isNotEmpty()) {
|
|
216
|
+
if (absolute || relativeTo == null) {
|
|
217
|
+
targets.add(0, PRIMARY to segments)
|
|
218
|
+
} else {
|
|
219
|
+
val url = relativeTo.url.toMutableList()
|
|
220
|
+
for (s in segments) {
|
|
221
|
+
if (s == "..") { if (url.isNotEmpty()) url.removeAt(url.size - 1) } else if (s != ".") url.add(s)
|
|
222
|
+
}
|
|
223
|
+
targets.add(0, relativeTo.outlet to url)
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
val token = begin()
|
|
227
|
+
var ok = true
|
|
228
|
+
var navigated = false
|
|
229
|
+
var index = 0
|
|
230
|
+
// Outlet by outlet: one whose guards return a promise continues when it settles.
|
|
231
|
+
fun next() {
|
|
232
|
+
if (index == targets.size) {
|
|
233
|
+
if (navigated) ended(if (absolute || relativeTo == null) "/" + segments.joinToString("/") else this.url)
|
|
234
|
+
return done(ok)
|
|
235
|
+
}
|
|
236
|
+
val (name, url) = targets[index++]
|
|
237
|
+
// The primary URL `/home` with outlets names the route holding them, already shown.
|
|
238
|
+
if (name == PRIMARY && index == 1 && targets.size > 1 && current(PRIMARY)?.firstOrNull() == url.firstOrNull()) return next()
|
|
239
|
+
if (outlets[name]?.frame == null) {
|
|
240
|
+
pending[name] = url
|
|
241
|
+
return next()
|
|
242
|
+
}
|
|
243
|
+
show(name, url, extras, token, { outcome ->
|
|
244
|
+
when {
|
|
245
|
+
// The first navigation's promise takes the redirect's result, as Angular's does.
|
|
246
|
+
outcome is Outcome.Redirect -> {
|
|
247
|
+
val str = outcome.tree.toString()
|
|
248
|
+
try { navigation(listOf(if (str.startsWith("/")) str else "/$str"), extras, done, fail) } catch (e: Throwable) { fail(jsCaught(e)) }
|
|
249
|
+
}
|
|
250
|
+
(outcome as Outcome.Done).shown == Shown.CANCELLED -> done(false)
|
|
251
|
+
else -> {
|
|
252
|
+
ok = outcome.shown != Shown.UNMATCHED && ok
|
|
253
|
+
navigated = navigated || outcome.shown == Shown.NAVIGATED
|
|
254
|
+
next()
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}, fail)
|
|
258
|
+
}
|
|
259
|
+
next()
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
fun navigateByUrl(urlTarget: Any?, extras: Any? = null): JSPromise<Boolean> {
|
|
263
|
+
val str = (jsBox(urlTarget) as? UrlTree)?.toString() ?: jsToString(urlTarget)
|
|
264
|
+
return navigate(listOf(if (str.startsWith("/")) str else "/$str"), extras)
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** `back()`: the outlet of the given route, else the one navigated last that can go back, else the topmost frame. */
|
|
268
|
+
fun back(options: Any? = null) {
|
|
269
|
+
jsReport {
|
|
270
|
+
val route = routeOf(field(options, "relativeTo"))
|
|
271
|
+
val own = route?.let { outlets[it.outlet]?.frame }
|
|
272
|
+
if (own != null && own.canGoBack()) {
|
|
273
|
+
own.goBack()
|
|
274
|
+
return@jsReport
|
|
275
|
+
}
|
|
276
|
+
for (name in history.reversed()) {
|
|
277
|
+
val frame = outlets[name]?.frame ?: continue
|
|
278
|
+
if (frame.canGoBack()) { frame.goBack(); return@jsReport }
|
|
279
|
+
}
|
|
280
|
+
FrameBase.goBack()
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
fun backToPreviousPage() = back()
|
|
285
|
+
|
|
286
|
+
/** `RouterExtensions.router`: the router itself. */
|
|
287
|
+
val router: Router get() = this
|
|
288
|
+
|
|
289
|
+
/** `router.url`: the primary outlet's URL. */
|
|
290
|
+
val url: String get() = "/" + (current(PRIMARY) ?: emptyList()).joinToString("/")
|
|
291
|
+
|
|
292
|
+
val routerState: JSObject
|
|
293
|
+
get() = JSObject(
|
|
294
|
+
"snapshot" to JSObject("url" to url, "root" to ActivatedRoute.current.snapshot),
|
|
295
|
+
"root" to ActivatedRoute.current,
|
|
296
|
+
)
|
|
297
|
+
|
|
298
|
+
fun createUrlTree(commands: Any?, extras: Any? = null): UrlTree {
|
|
299
|
+
val items = (jsBox(commands) as? JSArray<*>)?.storage ?: emptyList<Any?>()
|
|
300
|
+
val joined = items.joinToString("/") { jsToString(it) }.trim('/')
|
|
301
|
+
val q = field(extras, "queryParams")
|
|
302
|
+
val f = field(extras, "fragment") as? String
|
|
303
|
+
return UrlTree("/$joined", q, f)
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
fun serializeUrl(tree: Any?): String = (jsBox(tree) as? UrlTree)?.toString() ?: jsToString(tree)
|
|
307
|
+
|
|
308
|
+
fun parseUrl(raw: String): UrlTree = DefaultUrlSerializer().parse(raw)
|
|
309
|
+
|
|
310
|
+
fun isActive(targetUrl: Any?, exact: Any? = false): Boolean {
|
|
311
|
+
val target = (jsBox(targetUrl) as? UrlTree)?.toString() ?: jsToString(targetUrl)
|
|
312
|
+
val isExact = (jsBox(exact) as? Boolean) ?: (field(exact, "paths") == "exact")
|
|
313
|
+
return if (isExact) url == target else url.startsWith(target)
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
fun canGoBack(@Suppress("UNUSED_PARAMETER") options: Any? = null): Boolean = history.any { outlets[it]?.frame?.canGoBack() == true }
|
|
317
|
+
|
|
318
|
+
fun canGoBackToPreviousPage(): Boolean = canGoBack()
|
|
319
|
+
|
|
320
|
+
private fun routesIn(routes: List<RouteConfig>, outlet: String): List<RouteConfig> =
|
|
321
|
+
routes.filter { it.outlet == outlet } + routes.flatMap { routesIn(it.children, outlet) }
|
|
322
|
+
|
|
323
|
+
private fun current(name: String): List<String>? = outlets[name]?.entries?.lastOrNull()?.route?.url
|
|
324
|
+
|
|
325
|
+
private fun ended(url: String) {
|
|
326
|
+
navigationId += 1
|
|
327
|
+
events.next(NavigationEnd(navigationId, url, this.url))
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* An outlet's navigation to a URL, as Angular's router runs it: canMatch while the URL is matched (a route whose guards
|
|
332
|
+
* return false is passed over), canDeactivate of the routes the outlet leaves, then canActivateChild and canActivate of
|
|
333
|
+
* each route it activates, root first. Guards that all return synchronously keep the navigation synchronous. A
|
|
334
|
+
* navigation is never guarded going back: the frame has gone back already, as with @nativescript/angular, which lets
|
|
335
|
+
* the router catch up after the frame.
|
|
336
|
+
*/
|
|
337
|
+
private fun show(name: String, url: List<String>, extras: Any?, token: Int, done: (Outcome) -> Unit, fail: (Any?) -> Unit) {
|
|
338
|
+
val outlet = outlets[name] ?: return done(Outcome.Done(Shown.UNMATCHED))
|
|
339
|
+
val candidates = matches(outlet.routes, url, if (name == PRIMARY) PRIMARY else null).filter { it.chain.lastOrNull()?.make != null }
|
|
340
|
+
val current = outlet.entries.lastOrNull()
|
|
341
|
+
val currentUrl = "/" + (current?.route?.url ?: emptyList()).joinToString("/")
|
|
342
|
+
val matched = java.util.IdentityHashMap<RouteConfig, Boolean>()
|
|
343
|
+
|
|
344
|
+
fun activate(found: Match) {
|
|
345
|
+
if (token != navigations) return done(Outcome.Done(Shown.CANCELLED))
|
|
346
|
+
if (current?.route?.url == found.url) return done(Outcome.Done(Shown.ALREADY))
|
|
347
|
+
val route = ActivatedRoute(found.params, name, found.url, data = found.chain.last().data.toMap())
|
|
348
|
+
val nextUrl = "/" + found.url.joinToString("/")
|
|
349
|
+
// Routes the outlet shows already, with the same segments, are reused: their guards don't run again.
|
|
350
|
+
var reused = 0
|
|
351
|
+
val old = current?.match
|
|
352
|
+
if (old != null) {
|
|
353
|
+
while (reused < minOf(old.chain.size, found.chain.size) && old.chain[reused] === found.chain[reused] && old.consumed[reused] == found.consumed[reused]) reused++
|
|
354
|
+
}
|
|
355
|
+
val groups = ArrayList<List<() -> Any?>>()
|
|
356
|
+
if (current != null && old != null) {
|
|
357
|
+
val currentState = RouterStateSnapshot(currentUrl, current.route.snapshot)
|
|
358
|
+
val nextState = RouterStateSnapshot(nextUrl, route.snapshot)
|
|
359
|
+
for (i in old.chain.indices.reversed()) {
|
|
360
|
+
if (i < reused) break
|
|
361
|
+
val component = if (i == old.chain.size - 1) current.component else null
|
|
362
|
+
val calls = guards(old.chain[i], "canDeactivate").map { g -> { g(component, current.route.snapshot, currentState, nextState) } }
|
|
363
|
+
if (calls.isNotEmpty()) groups.add(calls)
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
val state = RouterStateSnapshot(nextUrl, route.snapshot)
|
|
367
|
+
for (i in reused until found.chain.size) {
|
|
368
|
+
val children = found.chain.subList(0, i).asReversed().flatMap { guards(it, "canActivateChild") }.map { g -> { g(route.snapshot, state, null, null) } }
|
|
369
|
+
if (children.isNotEmpty()) groups.add(children)
|
|
370
|
+
val calls = guards(found.chain[i], "canActivate").map { g -> { g(route.snapshot, state, null, null) } }
|
|
371
|
+
if (calls.isNotEmpty()) groups.add(calls)
|
|
372
|
+
}
|
|
373
|
+
check(groups, outlet, { verdict ->
|
|
374
|
+
if (token != navigations || verdict == false) return@check done(Outcome.Done(Shown.CANCELLED))
|
|
375
|
+
if (verdict is UrlTree) return@check done(Outcome.Redirect(verdict))
|
|
376
|
+
val frame = outlet.frame
|
|
377
|
+
val make = found.chain.lastOrNull()?.make
|
|
378
|
+
if (frame == null || make == null) return@check done(Outcome.Done(Shown.UNMATCHED))
|
|
379
|
+
history.remove(name)
|
|
380
|
+
history.add(name)
|
|
381
|
+
try {
|
|
382
|
+
push(make, route, frame, extras, outlet, outlet.injector, found)
|
|
383
|
+
} catch (e: Throwable) {
|
|
384
|
+
return@check fail(jsCaught(e))
|
|
385
|
+
}
|
|
386
|
+
done(Outcome.Done(Shown.NAVIGATED))
|
|
387
|
+
}, fail)
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
var index = 0
|
|
391
|
+
fun candidate() {
|
|
392
|
+
if (token != navigations) return done(Outcome.Done(Shown.CANCELLED))
|
|
393
|
+
if (index >= candidates.size) return done(Outcome.Done(Shown.UNMATCHED))
|
|
394
|
+
val found = candidates[index++]
|
|
395
|
+
if (found.chain.any { matched[it] == false }) return candidate()
|
|
396
|
+
val segments = JSArray(url.map { UrlSegment(it) }.toMutableList())
|
|
397
|
+
val unchecked = found.chain.filter { matched[it] == null && guards(it, "canMatch").isNotEmpty() }
|
|
398
|
+
var at = 0
|
|
399
|
+
fun canMatch() {
|
|
400
|
+
if (at == unchecked.size) return activate(found)
|
|
401
|
+
val route = unchecked[at++]
|
|
402
|
+
val calls = guards(route, "canMatch").map { g -> { g(JSObject("path" to route.segments.joinToString("/")), segments, null, null) } }
|
|
403
|
+
check(listOf(calls), outlet, { verdict ->
|
|
404
|
+
when (verdict) {
|
|
405
|
+
null -> { matched[route] = true; canMatch() }
|
|
406
|
+
is UrlTree -> done(Outcome.Redirect(verdict))
|
|
407
|
+
else -> { matched[route] = false; candidate() }
|
|
408
|
+
}
|
|
409
|
+
}, fail)
|
|
410
|
+
}
|
|
411
|
+
canMatch()
|
|
412
|
+
}
|
|
413
|
+
candidate()
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
private fun guards(route: RouteConfig, kind: String): List<RouteGuard> = route.guards?.let { guardTable[it]?.get(kind) } ?: emptyList()
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* Guards group by group, in the outlet's injection context. Each group's guards are all called first, then the first
|
|
420
|
+
* result that isn't true decides (Angular's prioritizedGuardValue): false cancels, a UrlTree redirects, and anything
|
|
421
|
+
* else passes. A promise, or an Observable's first value, defers what follows until it settles. [next] takes null
|
|
422
|
+
* (passed), false or the UrlTree.
|
|
423
|
+
*/
|
|
424
|
+
private fun check(groups: List<List<() -> Any?>>, outlet: Outlet, next: (Any?) -> Unit, fail: (Any?) -> Unit) {
|
|
425
|
+
var at = 0
|
|
426
|
+
fun group() {
|
|
427
|
+
if (at == groups.size) return next(null)
|
|
428
|
+
val calls = groups[at++]
|
|
429
|
+
val results = try {
|
|
430
|
+
Injector.runInContext(outlet.injector) { calls.map { it() } }
|
|
431
|
+
} catch (e: Throwable) {
|
|
432
|
+
return fail(jsCaught(e))
|
|
433
|
+
}
|
|
434
|
+
fun result(i: Int) {
|
|
435
|
+
if (i == results.size) return group()
|
|
436
|
+
val decide = { value: Any? ->
|
|
437
|
+
val v = jsBox(value)
|
|
438
|
+
if (v is UrlTree || v == false) next(v) else result(i + 1)
|
|
439
|
+
}
|
|
440
|
+
when (val r = jsBox(results[i])) {
|
|
441
|
+
is JSThenable -> r.jsSubscribe(decide, fail)
|
|
442
|
+
is RxObservable<*> -> first(r, decide)
|
|
443
|
+
else -> decide(r)
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
result(0)
|
|
447
|
+
}
|
|
448
|
+
group()
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/** An Observable's first value (Angular's `first()`): the kit's Observables complete with no value only by never emitting. */
|
|
452
|
+
@Suppress("UNCHECKED_CAST")
|
|
453
|
+
private fun first(source: RxObservable<*>, next: (Any?) -> Unit) {
|
|
454
|
+
var taken = false
|
|
455
|
+
var subscription: TeardownHandle? = null
|
|
456
|
+
subscription = (source as RxObservable<Any?>).subscribe { value ->
|
|
457
|
+
if (!taken) {
|
|
458
|
+
taken = true
|
|
459
|
+
subscription?.unsubscribe()
|
|
460
|
+
next(value)
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
if (taken) subscription.unsubscribe()
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* PageRouterOutlet's `activateOnGoForward`: a new page, the component rendered into it in a scope of its own, and the frame navigated to it.
|
|
468
|
+
* A component that throws leaves the outlet as it was.
|
|
469
|
+
*/
|
|
470
|
+
private fun push(make: () -> View, route: ActivatedRoute, frame: Frame, extras: Any?, outlet: Outlet? = null, injector: Injector?, match: Match? = null) {
|
|
471
|
+
val page = Page()
|
|
472
|
+
page.route = route
|
|
473
|
+
val owner = Owner(null)
|
|
474
|
+
// Shown before the component renders, as Angular's URL is current by activation: a navigation the
|
|
475
|
+
// component makes while rendering (a tab view filling its outlets) finds this route already there.
|
|
476
|
+
val entry = Entry(owner, route, match)
|
|
477
|
+
outlet?.entries?.add(entry)
|
|
478
|
+
val previousRoute = ActivatedRoute.current
|
|
479
|
+
ActivatedRoute.current = route
|
|
480
|
+
pagesBuilding.add(page)
|
|
481
|
+
rendering.add(null)
|
|
482
|
+
val view = try {
|
|
483
|
+
owner.run { Injector.runInContext(injector, make) }
|
|
484
|
+
} catch (e: Throwable) {
|
|
485
|
+
owner.dispose()
|
|
486
|
+
outlet?.entries?.remove(entry)
|
|
487
|
+
ActivatedRoute.current = previousRoute
|
|
488
|
+
throw e
|
|
489
|
+
} finally {
|
|
490
|
+
pagesBuilding.removeAt(pagesBuilding.size - 1)
|
|
491
|
+
entry.component = rendering.removeAt(rendering.size - 1)
|
|
492
|
+
}
|
|
493
|
+
if (view !== page) page.content = view
|
|
494
|
+
val outletRef = outlet?.let { java.lang.ref.WeakReference(it) }
|
|
495
|
+
page.on(PageBase.navigatedFromEvent, { data ->
|
|
496
|
+
if (jsTruthy(jsGet(data, "isBackNavigation"))) {
|
|
497
|
+
owner.dispose()
|
|
498
|
+
val o = outletRef?.get()
|
|
499
|
+
if (o != null && o.entries.remove(entry)) ended(url)
|
|
500
|
+
}
|
|
501
|
+
})
|
|
502
|
+
val clearHistory = jsTruthy(field(extras, "clearHistory"))
|
|
503
|
+
if (clearHistory && outletRef != null) {
|
|
504
|
+
page.once(PageBase.navigatedToEvent, { _ ->
|
|
505
|
+
val o = outletRef.get() ?: return@once
|
|
506
|
+
val cleared = o.entries.filter { it !== entry }
|
|
507
|
+
o.entries.retainAll { it === entry }
|
|
508
|
+
for (old in cleared) old.owner.dispose()
|
|
509
|
+
})
|
|
510
|
+
}
|
|
511
|
+
val animated = field(extras, "animated")
|
|
512
|
+
val navigation = mutableListOf<Pair<String, Any?>>(
|
|
513
|
+
"create" to jsFunction { page },
|
|
514
|
+
"clearHistory" to clearHistory,
|
|
515
|
+
"animated" to (if (animated == null) true else jsTruthy(animated)),
|
|
516
|
+
)
|
|
517
|
+
field(extras, "transition")?.let { navigation.add("transition" to it) }
|
|
518
|
+
frame.navigate(JSObject(navigation))
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/** Every way a URL resolves through the routes, in the order Angular's router tries them. A redirect that applies ends the search, as in Angular. */
|
|
522
|
+
private fun matches(routes: List<RouteConfig>, url: List<String>, outlet: String?): List<Match> {
|
|
523
|
+
val found = ArrayList<Match>()
|
|
524
|
+
for (route in routes) {
|
|
525
|
+
if (outlet != null && route.outlet != outlet) continue
|
|
526
|
+
val redirect = route.redirectTo
|
|
527
|
+
if (redirect != null) {
|
|
528
|
+
val applies = if (route.full) url == route.segments else url.take(route.segments.size) == route.segments
|
|
529
|
+
if (!applies) continue
|
|
530
|
+
val target = redirect.split("/").filter { it.isNotEmpty() } + url.drop(route.segments.size)
|
|
531
|
+
return found + if (redirect.startsWith("/")) matches(config, target, PRIMARY) else matches(routes, target, outlet)
|
|
532
|
+
}
|
|
533
|
+
if (url.size < route.segments.size) continue
|
|
534
|
+
val params = HashMap<String, String>()
|
|
535
|
+
var matched = true
|
|
536
|
+
for ((pattern, part) in route.segments.zip(url)) {
|
|
537
|
+
if (pattern.startsWith(":")) params[pattern.substring(1)] = URLDecoder.decode(part, "UTF-8")
|
|
538
|
+
else if (pattern != part) { matched = false; break }
|
|
539
|
+
}
|
|
540
|
+
if (!matched) continue
|
|
541
|
+
val own = url.take(route.segments.size)
|
|
542
|
+
val rest = url.drop(route.segments.size)
|
|
543
|
+
if (route.make != null && rest.isEmpty()) found.add(Match(listOf(route), listOf(own), params, if (route.segments.isEmpty()) emptyList() else url))
|
|
544
|
+
val children = route.children.filter { it.outlet == PRIMARY }
|
|
545
|
+
if (children.isNotEmpty()) {
|
|
546
|
+
for (inner in matches(children, rest, PRIMARY)) found.add(Match(listOf(route) + inner.chain, listOf(own) + inner.consumed, params + inner.params, own + inner.url))
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
return found
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
private fun resolveFlatRoute(path: String): Pair<Route, Map<String, String>>? {
|
|
553
|
+
val parts = path.split("/").filter { it.isNotEmpty() }
|
|
554
|
+
for (route in routes) {
|
|
555
|
+
if (route.segments.size != parts.size) continue
|
|
556
|
+
val params = HashMap<String, String>()
|
|
557
|
+
var matched = true
|
|
558
|
+
for ((pattern, part) in route.segments.zip(parts)) {
|
|
559
|
+
if (pattern.startsWith(":")) params[pattern.substring(1)] = URLDecoder.decode(part, "UTF-8")
|
|
560
|
+
else if (pattern != part) { matched = false; break }
|
|
561
|
+
}
|
|
562
|
+
if (matched) return route to params
|
|
563
|
+
}
|
|
564
|
+
return null
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
companion object {
|
|
568
|
+
const val PRIMARY = "primary"
|
|
569
|
+
// An Angular app's entry sets the routes before its root view is made, so this registers the app's teardown first.
|
|
570
|
+
val shared = Router().also { router ->
|
|
571
|
+
NativeScriptApplication.beforeExit.add { router.destroy() }
|
|
572
|
+
NativeScriptApplication.afterExit.add { AppInjector.destroy() }
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
typealias KitRouter = Router
|
|
578
|
+
typealias KitActivatedRoute = ActivatedRoute
|
|
579
|
+
|
|
580
|
+
/** `relativeTo`: the kit's route, or the compiled Angular `ActivatedRoute` that wraps it as `_kit`. */
|
|
581
|
+
private fun routeOf(value: Any?): ActivatedRoute? = value as? ActivatedRoute ?: field(value, "_kit") as? ActivatedRoute
|
|
582
|
+
|
|
583
|
+
/** A key of an options object script passes, null when absent. */
|
|
584
|
+
private fun field(target: Any?, key: String): Any? = if (jsIsNullish(target)) null else jsBox(jsGet(target, key)).let { if (it === JSNull) null else it }
|
|
585
|
+
|
|
586
|
+
/** `registerElement(tag, () => Class)`: compiled templates name each view's class already. */
|
|
587
|
+
fun registerElement(@Suppress("UNUSED_PARAMETER") tag: String, @Suppress("UNUSED_PARAMETER") type: Any?) {}
|