@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,151 @@
1
+ package org.nativescript.kit
2
+
3
+ import java.net.URLDecoder
4
+
5
+ /**
6
+ * The route a component was created for (Angular `ActivatedRoute`): set by the
7
+ * router before it constructs the routed component.
8
+ */
9
+ class ActivatedRoute(
10
+ params: Map<String, String>,
11
+ val outlet: String = "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
+ val params = RxBehaviorSubject(snapshot.params)
26
+ val queryParams = RxBehaviorSubject(snapshot.queryParams)
27
+ val data = RxBehaviorSubject(snapshot.data)
28
+ val paramMap = RxBehaviorSubject(ParamMap(snapshot.params))
29
+ val queryParamMap = RxBehaviorSubject(ParamMap(snapshot.queryParams))
30
+ val fragment = RxBehaviorSubject<String?>(null)
31
+ val title = RxBehaviorSubject<String?>(null)
32
+ var routeConfig: JSObject? = null
33
+
34
+ val root: ActivatedRoute get() = this
35
+ val parent: ActivatedRoute? get() = null
36
+ val firstChild: ActivatedRoute? get() = null
37
+ val children: JSArray<ActivatedRoute> get() = JSArray()
38
+ val pathFromRoot: JSArray<ActivatedRoute> get() = JSArray(mutableListOf(this))
39
+
40
+ companion object {
41
+ var current = ActivatedRoute(emptyMap())
42
+ }
43
+ }
44
+
45
+ class Route(path: String, internal val make: () -> View) {
46
+ internal val segments = path.split("/").filter { it.isNotEmpty() }
47
+ }
48
+
49
+ /**
50
+ * Path-based navigation (Angular `RouterExtensions`, `page-router-outlet`):
51
+ * a path resolves to a route, its `:params` to the activated route, and the
52
+ * routed page is pushed on the frame.
53
+ */
54
+ class Router {
55
+ var routes: List<Route> = emptyList()
56
+ var initial = "/"
57
+ val events = RxSubject<NavigationEnd>()
58
+ private var navigationId = 0.0
59
+ var url = "/"
60
+ private set
61
+
62
+ val router: Router get() = this
63
+ val routerState: JSObject
64
+ get() = JSObject(
65
+ "snapshot" to JSObject("url" to url, "root" to ActivatedRoute.current.snapshot),
66
+ "root" to ActivatedRoute.current,
67
+ )
68
+
69
+ /** A named outlet: this flat table has one. */
70
+ fun outlet(@Suppress("UNUSED_PARAMETER") name: String): View = outlet()
71
+
72
+ /** The outlet: a frame showing the initial route's page. */
73
+ fun outlet(): View {
74
+ val frame = Frame()
75
+ resolve(initial)?.let { frame.addChild(it) }
76
+ return frame
77
+ }
78
+
79
+ fun navigate(commands: JSArray<*>, extras: Any? = null): JSPromise<Boolean> = navigate(commands.elements, extras)
80
+
81
+ fun navigate(commands: List<Any?>, @Suppress("UNUSED_PARAMETER") extras: Any? = null): JSPromise<Boolean> {
82
+ val path = commands.joinToString("/") { jsToString(it) }
83
+ if (resolveRoute(path) == null) return JSPromise.resolve(false)
84
+ Frame.topmost()?.navigate { resolve(path)!! }
85
+ url = "/" + path.split("/").filter { it.isNotEmpty() }.joinToString("/")
86
+ navigationId += 1
87
+ events.next(NavigationEnd(navigationId, url, url))
88
+ return JSPromise.resolve(true)
89
+ }
90
+
91
+ fun navigateByUrl(urlTarget: Any?, extras: Any? = null): JSPromise<Boolean> {
92
+ val str = (jsBox(urlTarget) as? UrlTree)?.toString() ?: jsToString(urlTarget)
93
+ return navigate(listOf(if (str.startsWith("/")) str else "/$str"), extras)
94
+ }
95
+
96
+ fun createUrlTree(commands: Any?, extras: Any? = null): UrlTree {
97
+ val items = (jsBox(commands) as? JSArray<*>)?.storage ?: emptyList<Any?>()
98
+ val joined = items.joinToString("/") { jsToString(it) }.trim('/')
99
+ val q = jsGetOptional(extras, "queryParams")
100
+ val f = jsGetOptional(extras, "fragment") as? String
101
+ return UrlTree("/$joined", q, f)
102
+ }
103
+
104
+ fun serializeUrl(tree: Any?): String = (jsBox(tree) as? UrlTree)?.toString() ?: jsToString(tree)
105
+
106
+ fun parseUrl(raw: String): UrlTree = DefaultUrlSerializer().parse(raw)
107
+
108
+ fun isActive(targetUrl: Any?, exact: Any? = false): Boolean {
109
+ val target = (jsBox(targetUrl) as? UrlTree)?.toString() ?: jsToString(targetUrl)
110
+ val isExact = (jsBox(exact) as? Boolean) ?: (jsGetOptional(exact, "paths") == "exact")
111
+ return if (isExact) url == target else url.startsWith(target)
112
+ }
113
+
114
+ fun back(@Suppress("UNUSED_PARAMETER") options: Any? = null) {
115
+ Frame.topmost()?.goBack()
116
+ }
117
+
118
+ fun backToPreviousPage() = back()
119
+
120
+ fun canGoBack(@Suppress("UNUSED_PARAMETER") options: Any? = null): Boolean = false
121
+
122
+ fun canGoBackToPreviousPage(): Boolean = canGoBack()
123
+
124
+ internal fun resolve(path: String): View? {
125
+ val (route, params) = resolveRoute(path) ?: return null
126
+ ActivatedRoute.current = ActivatedRoute(params)
127
+ return route.make()
128
+ }
129
+
130
+ private fun resolveRoute(path: String): Pair<Route, Map<String, String>>? {
131
+ val parts = path.split("/").filter { it.isNotEmpty() }
132
+ for (route in routes) {
133
+ if (route.segments.size != parts.size) continue
134
+ val params = HashMap<String, String>()
135
+ var matched = true
136
+ for ((pattern, part) in route.segments.zip(parts)) {
137
+ if (pattern.startsWith(":")) params[pattern.substring(1)] = URLDecoder.decode(part, "UTF-8")
138
+ else if (pattern != part) { matched = false; break }
139
+ }
140
+ if (matched) return Pair(route, params)
141
+ }
142
+ return null
143
+ }
144
+
145
+ companion object {
146
+ val shared = Router()
147
+ }
148
+ }
149
+
150
+ /** `inject(Page)`. */
151
+ fun injectedPage(): Page = routedPage()
@@ -0,0 +1,250 @@
1
+ package org.nativescript.kit
2
+
3
+ /**
4
+ * An Angular component view as zoneless change detection refreshes it: a listener marks its view and the views above it
5
+ * dirty, and refreshing a view re-checks every binding (`Check`) of its template and of its embedded views, applying what
6
+ * is no longer `Object.is` the value last applied. Child components are refreshed only through their own inputs, which
7
+ * are signals here. A binding that reads no signal has no source holding it, so the view holds its checks until they are
8
+ * disposed.
9
+ */
10
+ class AngularView internal constructor(internal val parent: AngularView?, internal val onPush: Boolean = false) {
11
+ private val checks = mutableListOf<Effect>()
12
+ /** With zone.js: checked OnPush, a tick refreshes it only while it is `dirty`, or marked to `refresh`. */
13
+ internal var dirty = false
14
+ /** Angular's `RefreshView`: a signal one of its bindings read changed, or `detectChanges()`. */
15
+ internal var refresh = false
16
+ /** Being refreshed by a tick: a binding re-read now is not a signal's. */
17
+ internal var refreshing = false
18
+ /** Rows and branches a signal re-renders dispose their checks without any listener running here. */
19
+ private var pruneAt = 64
20
+
21
+ internal fun add(effect: Effect) {
22
+ if (checks.size >= pruneAt) {
23
+ checks.removeAll { it.disposed }
24
+ pruneAt = maxOf(64, checks.size * 2)
25
+ }
26
+ checks.add(effect)
27
+ }
28
+
29
+ internal fun markDirty() {
30
+ var view: AngularView? = this
31
+ while (view != null) {
32
+ if (Zone.enabled) {
33
+ view.dirty = true
34
+ } else {
35
+ view.checks.removeAll { it.disposed }
36
+ for (check in view.checks) check.invalidate()
37
+ }
38
+ view = view.parent
39
+ }
40
+ }
41
+ }
42
+
43
+ /** The component view whose bindings this scope's checks are. */
44
+ val EffectOrder.Scope.view: AngularView? get() = context as? AngularView
45
+
46
+ /** The component view it is a binding of. */
47
+ internal val Effect.view: AngularView? get() = context as? AngularView
48
+
49
+ /**
50
+ * Angular's component view: after its parent view's bindings and embedded views. [injector] is the component's own
51
+ * (`providers`); without one, the view's children inject from the injector the component was made in.
52
+ * [onPush]: the component, checked OnPush under zone.js, whose inputs mark this view dirty (`Zone.inputChanged`).
53
+ */
54
+ fun <T> EffectOrder.view(injector: Injector? = null, onPush: Any? = null, body: () -> T): T {
55
+ Zone.install()
56
+ val view = AngularView(current.view, onPush != null)
57
+ if (onPush != null) Zone.views[onPush] = view
58
+ return run(EffectOrder.Scope(current.next(2), null, injector ?: Injector.current, view), body)
59
+ }
60
+
61
+ /** Angular's embedded view (`@if`, `@for` content): after its declaring view's own bindings. */
62
+ fun <T> EffectOrder.embedded(view: EffectOrder.Scope, body: () -> T): T = run(EffectOrder.Scope(view.next(1), null, view.ambient, view.context), body)
63
+
64
+ /** Angular's `effect()`: its first run is in the next update, as change detection runs it, not at creation. */
65
+ fun Effect.Companion.deferred(body: () -> Unit): Effect {
66
+ Zone.install()
67
+ return Effect(EffectOrder.key(), false, body, deferred = true)
68
+ }
69
+
70
+ /** A listener of a zoneless Angular template: the update it schedules re-checks the bindings of [view] and of every view above it. */
71
+ fun Reactivity.event(view: AngularView?, handler: () -> Unit) {
72
+ Zone.install()
73
+ view?.markDirty()
74
+ event { site(handler) }
75
+ }
76
+
77
+ /**
78
+ * `ChangeDetectorRef.markForCheck()` on a zoneless view: an update re-checks it and the views above it, scheduled as
79
+ * a write schedules one, or run at once.
80
+ */
81
+ internal fun Reactivity.markForCheck(view: AngularView?, now: Boolean = false) {
82
+ view?.markDirty()
83
+ requestUpdate(now)
84
+ }
85
+
86
+ /**
87
+ * Angular's zone-based change detection: after every JavaScript task (an
88
+ * event handler, a timer callback, a promise job) and the jobs it queued,
89
+ * `ApplicationRef.tick()` re-reads every binding in view order and applies
90
+ * the ones whose value changed. In a zone app every effect is a binding
91
+ * re-run on each tick, in its `EffectOrder` key order, which is that order.
92
+ */
93
+ object Zone {
94
+ var enabled = false
95
+ set(value) {
96
+ field = value
97
+ install()
98
+ Microtasks.onStable = if (value) ({ tick() }) else null
99
+ Effect.created = if (value) ({ effects.add(it) }) else null
100
+ Reactivity.rerunsUnchanged = value
101
+ }
102
+
103
+ /** Held until disposed: a binding reads no signal that would keep it alive. */
104
+ private val effects = mutableListOf<Effect>()
105
+
106
+ private var handing = false
107
+
108
+ /**
109
+ * Hands uncaught errors to Angular ([handOff]). Called where Angular's catch sites ([Reactivity.site]: a template
110
+ * listener, a check of a view, an `effect()`) and zone.js are first set up, so it is in place before either can
111
+ * catch anything.
112
+ */
113
+ internal fun install() {
114
+ if (jsUncaughtHandOff == null) jsUncaughtHandOff = ::handOff
115
+ }
116
+
117
+ /**
118
+ * An uncaught error as Angular takes it: with zone.js every task's error goes to the ErrorHandler (the app's,
119
+ * else Angular's) and never reaches the runtime; without it only an Angular catch site's does. False when it is
120
+ * the runtime's, as is what the handler itself throws.
121
+ */
122
+ fun handOff(error: Any?): Boolean {
123
+ if (handing || !(enabled || Reactivity.sites > 0)) return false
124
+ handing = true
125
+ try {
126
+ (Injector.providedErrorHandler() ?: ErrorHandler.shared).handleError(error)
127
+ } catch (t: Throwable) {
128
+ jsReportUncaught(jsCaught(t))
129
+ } finally {
130
+ handing = false
131
+ }
132
+ return true
133
+ }
134
+
135
+ /** The views of OnPush components, by component. */
136
+ internal val views = java.util.WeakHashMap<Any, AngularView>()
137
+
138
+ /** An input of an OnPush component set to a value not `Object.is` the last (`markDirtyIfOnPush`). */
139
+ fun inputChanged(component: Any) {
140
+ views[component]?.dirty = true
141
+ }
142
+
143
+ /**
144
+ * `ApplicationRef.tick()` (Angular 22 `detectChangesInViewWhileDirty`/`detectChangesInView`): from the root, a view
145
+ * is refreshed when it is checked always (Eager) or dirty and the view above it is refreshed, or on its own when
146
+ * marked to refresh; a view not refreshed leaves its dirty mark and skips the views below it. Views marked while
147
+ * the pass ran (an OnPush child's input) are refreshed in a further pass, as Angular re-runs while views need it.
148
+ */
149
+ fun tick() {
150
+ effects.removeAll { it.disposed }
151
+ val done = HashSet<AngularView>()
152
+ for (pass in 0 until 100) {
153
+ val known = HashMap<AngularView, Boolean>()
154
+ fun refreshes(view: AngularView): Boolean {
155
+ known[view]?.let { return it }
156
+ val above = view.parent?.let { refreshes(it) || it in done } ?: true
157
+ val r = view.refresh || above && (view.dirty || pass == 0 && !view.onPush)
158
+ known[view] = r
159
+ return r
160
+ }
161
+ val live = effects.filter { e -> e.view?.let { refreshes(it) } ?: (pass == 0) }
162
+ if (live.isEmpty()) return
163
+ val views = mutableListOf<AngularView>()
164
+ for (effect in live) {
165
+ val view = effect.view ?: continue
166
+ if (view.refreshing) continue
167
+ view.refreshing = true
168
+ view.dirty = false
169
+ view.refresh = false
170
+ done.add(view)
171
+ views.add(view)
172
+ }
173
+ try {
174
+ batch { for (effect in live) effect.invalidate() }
175
+ } finally {
176
+ for (view in views) view.refreshing = false
177
+ }
178
+ }
179
+ }
180
+ }
181
+
182
+ /**
183
+ * A binding as Angular checks it (`bindingUpdated`): re-read on every check of its view,
184
+ * applied only when the value is not `Object.is` the last one applied.
185
+ */
186
+ fun <T> Check(read: () -> T, apply: (T) -> Unit) {
187
+ var last: Any? = UNCHECKED
188
+ var started = false
189
+ val effect = Effect {
190
+ // A signal it read changed: the tick refreshes its whole view, in template order.
191
+ if (started && Zone.enabled) EffectOrder.current.view?.let { if (!it.refreshing) { it.refresh = true; return@Effect } }
192
+ started = true
193
+ val value = read()
194
+ if (last !== UNCHECKED && jsSameValue(last, value)) return@Effect
195
+ last = value
196
+ untrack { apply(value) }
197
+ }
198
+ EffectOrder.current.view?.add(effect)
199
+ }
200
+
201
+ private val UNCHECKED = Any()
202
+
203
+ /**
204
+ * A pure Angular pipe at one binding site (`ɵɵpipeBind1`…): `transform` runs when an argument is no longer
205
+ * `Object.is` the one it last ran with, and otherwise the result it gave is returned. What it throws is not kept.
206
+ */
207
+ class PurePipeCache {
208
+ private var arguments: List<Any?>? = null
209
+ private var result: Any? = null
210
+
211
+ @Suppress("UNCHECKED_CAST")
212
+ private inline fun <R> run(given: List<Any?>, transform: () -> R): R {
213
+ val last = arguments
214
+ if (last != null && last.size == given.size && last.indices.all { jsSameValue(last[it], given[it]) }) return result as R
215
+ val value = transform()
216
+ arguments = given
217
+ result = value
218
+ return value
219
+ }
220
+
221
+ fun <A, R> pure1(a: A, transform: (A) -> R): R = run(listOf(a)) { transform(a) }
222
+ fun <A, B, R> pure2(a: A, b: B, transform: (A, B) -> R): R = run(listOf(a, b)) { transform(a, b) }
223
+ fun <A, B, C, R> pure3(a: A, b: B, c: C, transform: (A, B, C) -> R): R = run(listOf(a, b, c)) { transform(a, b, c) }
224
+ fun <A, B, C, D, R> pure4(a: A, b: B, c: C, d: D, transform: (A, B, C, D) -> R): R = run(listOf(a, b, c, d)) { transform(a, b, c, d) }
225
+ fun <A, B, C, D, E, R> pure5(a: A, b: B, c: C, d: D, e: E, transform: (A, B, C, D, E) -> R): R = run(listOf(a, b, c, d, e)) { transform(a, b, c, d, e) }
226
+ }
227
+
228
+ /**
229
+ * `inject(ChangeDetectorRef)`: the view being created when it is injected (a component's, or the embedded view a pipe is
230
+ * in). `markForCheck` marks it and the views above it dirty; zoneless, it schedules the update that re-checks them,
231
+ * and with zone.js the tick after the task refreshes them.
232
+ */
233
+ class ChangeDetectorRef internal constructor(private val view: AngularView?) {
234
+ fun markForCheck() {
235
+ if (Zone.enabled) view?.markDirty() else Reactivity.markForCheck(view)
236
+ }
237
+
238
+ /** Checks the view now: its bindings and the views above it, which is more than Angular checks and gives the same values. */
239
+ fun detectChanges() {
240
+ if (Zone.enabled) { view?.refresh = true; Zone.tick() } else Reactivity.markForCheck(view, now = true)
241
+ }
242
+
243
+ fun detach() {}
244
+ fun reattach() {}
245
+ fun checkNoChanges() {}
246
+
247
+ companion object {
248
+ fun current(): ChangeDetectorRef = ChangeDetectorRef(EffectOrder.current.view)
249
+ }
250
+ }