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

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,530 @@
1
+ package org.nativescript.kit
2
+
3
+ /**
4
+ * An Angular component view: a listener or `markForCheck` marks it and the views above it dirty (`markViewDirty`), a
5
+ * signal one of its bindings read marks it to refresh, and [Zone] refreshes what is marked in `EffectOrder` key order:
6
+ * every binding ([Check]), hook and region of the view's template and of its embedded views, applying what is no longer
7
+ * `Object.is` the value last applied.
8
+ */
9
+ class AngularView internal constructor(
10
+ internal val parent: AngularView?,
11
+ internal val prefix: List<Int>,
12
+ internal val onPush: Boolean = false,
13
+ ) {
14
+ /** Checked OnPush: a tick refreshes it only while it is `dirty`, or marked to `refresh`. */
15
+ internal var dirty = false
16
+ /** Angular's `RefreshView`: a signal one of its bindings read changed, or `detectChanges()`. */
17
+ internal var refresh = false
18
+ /** True while one of this view's effects is executing in a check pass (prevents self-deferral). */
19
+ internal var refreshing = false
20
+ /** True while this view is already active in the current pass (prevents ancestor re-dirtying loops from `ngDoCheck`). */
21
+ internal var inPass = false
22
+ /** Set when a `@let` in this view throws during its check pass; remaining bindings in this view skip until next pass. */
23
+ internal var aborted = false
24
+ /** Component-scoped `effect()`s created during construction, flushed between `ngDoCheck` and `ngAfterContentInit`. */
25
+ internal val initialEffects = mutableListOf<Effect>()
26
+
27
+ /** Marks this view dirty and walks up to its root host view without re-dirtying ancestors already active in this pass. */
28
+ internal fun markDirty() {
29
+ dirty = true
30
+ var view = parent
31
+ while (view != null) {
32
+ if (!view.inPass) view.dirty = true
33
+ view = view.parent
34
+ }
35
+ }
36
+
37
+ internal class ConstructionFrame {
38
+ val refs = mutableListOf<ChangeDetectorRef>()
39
+ val initialEffects = mutableListOf<Effect>()
40
+ }
41
+
42
+ companion object {
43
+ internal val frames = mutableListOf<ConstructionFrame>()
44
+ internal val pending = java.util.WeakHashMap<Any, ConstructionFrame>()
45
+
46
+ /**
47
+ * Runs a component's construction inside an exception-safe, re-entrant scope frame so `inject(ChangeDetectorRef)`
48
+ * and `effect()` bind to the component's own view regardless of inheritance or constructor helpers.
49
+ */
50
+ fun <T : Any> construct(make: () -> T): T {
51
+ val frame = ConstructionFrame()
52
+ frames.add(frame)
53
+ val instance = try {
54
+ make()
55
+ } catch (e: Throwable) {
56
+ frames.removeAt(frames.lastIndex)
57
+ for (fx in frame.initialEffects) fx.destroy()
58
+ throw e
59
+ }
60
+ frames.removeAt(frames.lastIndex)
61
+ if (frame.refs.isNotEmpty() || frame.initialEffects.isNotEmpty()) {
62
+ pending[instance] = frame
63
+ }
64
+ return instance
65
+ }
66
+ }
67
+ }
68
+
69
+ /** The component view whose bindings this scope's checks are. */
70
+ val EffectOrder.Scope.view: AngularView? get() = context as? AngularView
71
+
72
+ /** The component view it is a binding of. */
73
+ internal val Effect.view: AngularView? get() = context as? AngularView
74
+
75
+ /** A root component's host view scope: isolates each root's host hooks and `markForCheck` state from other roots. */
76
+ fun <T> EffectOrder.root(body: () -> T): T {
77
+ Zone.install()
78
+ val prefix = current.next(CHILD_PHASE)
79
+ val host = AngularView(null, prefix, false)
80
+ return run(EffectOrder.Scope(prefix, null, current.ambient, host), body)
81
+ }
82
+
83
+ /**
84
+ * Angular's component view: after its parent view's bindings and embedded views. [injector] is the component's own
85
+ * (`providers`); without one, the view's children inject from the injector the component was made in.
86
+ */
87
+ fun <T> EffectOrder.view(injector: Injector? = null, component: Any? = null, onPush: Boolean = false, body: () -> T): T {
88
+ Zone.install()
89
+ val prefix = current.next(CHILD_PHASE)
90
+ val view = AngularView(current.view, prefix, onPush)
91
+ if (component != null) {
92
+ Zone.views[component] = view
93
+ val frame = AngularView.pending.remove(component)
94
+ if (frame != null) {
95
+ for (ref in frame.refs) ref.view = view
96
+ view.initialEffects.addAll(frame.initialEffects)
97
+ }
98
+ }
99
+ return run(EffectOrder.Scope(prefix, null, injector ?: Injector.current, view), body)
100
+ }
101
+
102
+ /** Angular's embedded view (`@if`, `@for` content): after its declaring view's own bindings. */
103
+ fun <T> EffectOrder.embedded(view: EffectOrder.Scope, body: () -> T): T = run(EffectOrder.Scope(view.next(EMBEDDED_PHASE), null, view.ambient, view.context), body)
104
+
105
+ /**
106
+ * The phases of a view's scope ([EffectOrder.Scope.next]), in the order a check of the view runs them: its own bindings
107
+ * (0), its embedded views, the content hooks of what it holds, its child views, their after-view hooks.
108
+ */
109
+ private const val EMBEDDED_PHASE = 1
110
+ private const val CONTENT_PHASE = 2
111
+ private const val CHILD_PHASE = 3
112
+ private const val VIEW_PHASE = 4
113
+
114
+ /** Angular's `effect()`: created during component construction it flushes between `ngDoCheck` and `ngAfterContentInit`; otherwise its first run is in the next update. */
115
+ fun Effect.Companion.deferred(body: () -> Unit): Effect {
116
+ Zone.install()
117
+ // Not a binding: a tick does not re-run it, only a signal it read.
118
+ val created = Effect.created
119
+ Effect.created = null
120
+ try {
121
+ val frame = AngularView.frames.lastOrNull()
122
+ if (frame != null) {
123
+ val fx = Effect(EffectOrder.key(), false, body, deferred = true, schedule = false)
124
+ frame.initialEffects.add(fx)
125
+ return fx
126
+ }
127
+ return Effect(EffectOrder.key(), false, body, deferred = true)
128
+ } finally {
129
+ Effect.created = created
130
+ }
131
+ }
132
+
133
+ /** A listener of a zoneless Angular template: the update it schedules refreshes [view] and every view above it. */
134
+ fun Reactivity.event(view: AngularView?, handler: () -> Unit) {
135
+ Zone.install()
136
+ Zone.markDirty(view)
137
+ event { site(handler) }
138
+ }
139
+
140
+ /**
141
+ * `ChangeDetectorRef.markForCheck()` on a zoneless view: an update refreshes it and the views above it, scheduled as a
142
+ * write schedules one, or run at once.
143
+ */
144
+ internal fun Reactivity.markForCheck(view: AngularView?, now: Boolean = false) {
145
+ Zone.markDirty(view)
146
+ requestUpdate(now)
147
+ }
148
+
149
+ /**
150
+ * Angular's change detection. With zone.js, after every JavaScript task (an event handler, a timer callback, a promise
151
+ * job) and the jobs it queued, `ApplicationRef.tick()` refreshes every Eager view from the roots; zoneless, a tick runs
152
+ * in the update a listener, `markForCheck` or a signal a binding read schedules, and refreshes only what they marked.
153
+ * Every effect a view's template makes is re-run in `EffectOrder` key order, deciding each view lazily when entered.
154
+ */
155
+ object Zone {
156
+ var enabled = false
157
+ set(value) {
158
+ field = value
159
+ install()
160
+ Microtasks.onStable = if (value) ({ tick() }) else null
161
+ }
162
+
163
+ /** Held until disposed: a binding reads no signal that would keep it alive. */
164
+ private val effects = mutableListOf<Effect>()
165
+
166
+ private var handing = false
167
+ private var installed = false
168
+
169
+ /**
170
+ * Hands uncaught errors to Angular ([handOff]), keeps every view-scoped effect, and installs the unified signal
171
+ * deferral hook so `Check`, `Choose`, `ForEach`, and `listItems` all refresh in view order.
172
+ */
173
+ internal fun install() {
174
+ if (jsUncaughtHandOff == null) jsUncaughtHandOff = ::handOff
175
+ if (installed) return
176
+ installed = true
177
+ Effect.created = { if (it.view != null) effects.add(it) }
178
+ Reactivity.shouldDeferEffect = { effect ->
179
+ val view = effect.view
180
+ if (view != null && !view.refreshing) {
181
+ refresh(view)
182
+ true
183
+ } else {
184
+ false
185
+ }
186
+ }
187
+ Reactivity.rerunsUnchanged = true
188
+ }
189
+
190
+ /**
191
+ * An uncaught error as Angular takes it: with zone.js every task's error goes to the ErrorHandler (the app's,
192
+ * else Angular's) and never reaches the runtime; without it only an Angular catch site's does. False when it is
193
+ * the runtime's, as is what the handler itself throws.
194
+ */
195
+ fun handOff(error: Any?): Boolean {
196
+ if (handing || !(enabled || Reactivity.sites > 0)) return false
197
+ handing = true
198
+ try {
199
+ (Injector.providedErrorHandler() ?: ErrorHandler.shared).handleError(error)
200
+ } catch (t: Throwable) {
201
+ jsReportUncaught(jsCaught(t))
202
+ } finally {
203
+ handing = false
204
+ }
205
+ return true
206
+ }
207
+
208
+ /** Component views by component instance. */
209
+ internal val views = java.util.WeakHashMap<Any, AngularView>()
210
+
211
+ /**
212
+ * An input of an OnPush component set to a value not `Object.is` the last (`markDirtyIfOnPush`); not its first
213
+ * value, which its view's first update follows, as Angular's creation does.
214
+ */
215
+ fun inputChanged(component: Any) {
216
+ if (!creating) views[component]?.dirty = true
217
+ }
218
+
219
+ /** Flushes construction-scoped `effect()`s of [component] between `ngDoCheck` and `ngAfterContentInit`. */
220
+ fun flushEffects(component: Any) {
221
+ val view = views[component] ?: return
222
+ if (view.initialEffects.isEmpty()) return
223
+ val pending = view.initialEffects.toList()
224
+ view.initialEffects.clear()
225
+ for (fx in pending) {
226
+ Reactivity.site { fx.runIfStale() }
227
+ }
228
+ }
229
+
230
+ private var creating = false
231
+
232
+ internal inline fun applying(first: Boolean, apply: () -> Unit) {
233
+ val outer = creating
234
+ creating = first
235
+ try { apply() } finally { creating = outer }
236
+ }
237
+
238
+ /** Zoneless `markViewDirty`: [view] and the views up to its root host view, refreshed by the tick in the update the caller schedules. */
239
+ internal fun markDirty(view: AngularView?) {
240
+ if (view == null) return
241
+ view.markDirty()
242
+ if (!enabled) scheduleTick()
243
+ }
244
+
245
+ /** A binding/region of [view] read a signal that changed. */
246
+ internal fun refresh(view: AngularView) {
247
+ view.refresh = true
248
+ if (!enabled) scheduleTick()
249
+ }
250
+
251
+ /** The zoneless tick, an effect keyed after every other, so in an update it runs once user `effect()`s have run. */
252
+ private var ticker: Effect? = null
253
+
254
+ private fun scheduleTick() {
255
+ if (ticker == null) {
256
+ val created = Effect.created
257
+ Effect.created = null
258
+ try {
259
+ ticker = Owner(null).run { EffectOrder.run(EffectOrder.Scope(listOf(Int.MAX_VALUE), null, null, null)) { Effect(listOf(Int.MAX_VALUE), false, { untrack { runCycle(null) } }) } }
260
+ } finally {
261
+ Effect.created = created
262
+ }
263
+ }
264
+ ticker?.invalidate()
265
+ }
266
+
267
+ /** `ApplicationRef.tick()` with zone.js (Angular 22 `detectChangesInViewWhileDirty`/`detectChangesInView`), run at once. */
268
+ fun tick() {
269
+ runCycle(null)
270
+ }
271
+
272
+ /** Subtree-scoped `ChangeDetectorRef.detectChanges()` for both zone.js and zoneless modes. */
273
+ internal fun detectChanges(view: AngularView) {
274
+ val scoped = java.util.Collections.newSetFromMap(java.util.IdentityHashMap<AngularView, Boolean>())
275
+ scoped.add(view)
276
+ runCycle(scoped)
277
+ }
278
+
279
+ private fun isDescendant(view: AngularView, roots: Set<AngularView>): Boolean {
280
+ var cur = view.parent
281
+ while (cur != null) {
282
+ if (cur in roots) return true
283
+ cur = cur.parent
284
+ }
285
+ return false
286
+ }
287
+
288
+ private fun runCycle(roots: Set<AngularView>?) {
289
+ val checked = java.util.Collections.newSetFromMap(java.util.IdentityHashMap<AngularView, Boolean>())
290
+ for (pass in 0 until 100) {
291
+ if (!runPass(roots, pass == 0 && roots == null, checked)) break
292
+ }
293
+ }
294
+
295
+ /**
296
+ * Runs one in-order `EffectOrder` pass, evaluating each view's eligibility lazily when entered so OnPush inputs
297
+ * and `ngDoCheck` `markForCheck()` take effect in the same pass before `ngAfterViewChecked`, and wrapping each
298
+ * Phase 0 scope in [EmbeddedViews.begin]/[EmbeddedViews.flush].
299
+ */
300
+ private fun runPass(roots: Set<AngularView>?, isRootPass: Boolean, checked: MutableSet<AngularView>): Boolean {
301
+ effects.removeAll { it.disposed }
302
+ val snapshot = effects.sortedWith { a, b -> EffectOrder.compare(a.key, b.key) }
303
+ val decision = java.util.IdentityHashMap<AngularView, Boolean>()
304
+ val enteredViews = mutableListOf<AngularView>()
305
+ var ranAny = false
306
+
307
+ fun enter(view: AngularView): Boolean {
308
+ decision[view]?.let { return it }
309
+ if (roots != null && view !in roots && !isDescendant(view, roots)) {
310
+ decision[view] = false
311
+ return false
312
+ }
313
+ val isTarget = roots != null && view in roots && view !in checked
314
+ val parent = view.parent
315
+ val parentActive: Boolean
316
+ val parentDone: Boolean
317
+ if (parent != null) {
318
+ parentActive = enter(parent)
319
+ parentDone = parent in checked
320
+ } else {
321
+ parentActive = isRootPass && enabled
322
+ parentDone = true
323
+ }
324
+ val active = isTarget || view.refresh || ((parentActive || parentDone) && view.dirty) || (parentActive && !view.onPush)
325
+ decision[view] = active
326
+ if (active) {
327
+ view.inPass = true
328
+ view.dirty = false
329
+ view.refresh = false
330
+ view.aborted = false
331
+ checked.add(view)
332
+ enteredViews.add(view)
333
+ }
334
+ return active
335
+ }
336
+
337
+ var openPrefix: List<Int>? = null
338
+ try {
339
+ for (effect in snapshot) {
340
+ if (effect.disposed) continue
341
+ val view = effect.view ?: continue
342
+ if (!enter(view) || view.aborted) continue
343
+ val phase0Prefix: List<Int>? = if (effect.key.size >= 2 && effect.key[effect.key.size - 2] == 0) effect.key.subList(0, effect.key.size - 2) else null
344
+ if (phase0Prefix != openPrefix) {
345
+ if (openPrefix != null) jsReport { EmbeddedViews.flush() }
346
+ if (phase0Prefix != null) EmbeddedViews.begin()
347
+ openPrefix = phase0Prefix
348
+ }
349
+ ranAny = true
350
+ view.refreshing = true
351
+ try {
352
+ effect.runNow()
353
+ } finally {
354
+ view.refreshing = false
355
+ }
356
+ }
357
+ } finally {
358
+ if (openPrefix != null) {
359
+ openPrefix = null
360
+ jsReport { EmbeddedViews.flush() }
361
+ }
362
+ for (v in enteredViews) {
363
+ v.inPass = false
364
+ v.refreshing = false
365
+ }
366
+ }
367
+ return ranAny
368
+ }
369
+ }
370
+
371
+ /**
372
+ * A binding as Angular checks it (`bindingUpdated`): re-read on every check of its view,
373
+ * applied only when the value is not `Object.is` the last one applied. With [abortOnThrow], a throw aborts the rest
374
+ * of the view's pass.
375
+ */
376
+ fun <T> Check(read: () -> T, apply: (T) -> Unit) = Check(false, read, apply)
377
+
378
+ fun <T> Check(abortOnThrow: Boolean, read: () -> T, apply: (T) -> Unit) {
379
+ var last: Any? = UNCHECKED
380
+ var started = false
381
+ Effect {
382
+ if (EffectOrder.current.view?.aborted == true) return@Effect
383
+ val first = !started
384
+ started = true
385
+ val value = try {
386
+ read()
387
+ } catch (e: Throwable) {
388
+ if (abortOnThrow) EffectOrder.current.view?.aborted = true
389
+ throw e
390
+ }
391
+ if (last !== UNCHECKED && jsSameValue(last, value)) return@Effect
392
+ last = value
393
+ untrack { Zone.applying(first) { apply(value) } }
394
+ }
395
+ }
396
+
397
+ private val UNCHECKED = Any()
398
+
399
+ /**
400
+ * A hook Angular runs on every check of the view its component or directive is in (`ngDoCheck`): now, after the init
401
+ * hook, then each time the view is checked, at its place among the view's bindings.
402
+ */
403
+ fun EveryCheck(hook: () -> Unit) = everyCheck(0, hook)
404
+
405
+ /** `ngAfterContentChecked`: now, after `ngAfterContentInit`, then on every check of the view, after its embedded views. */
406
+ fun ContentChecked(hook: () -> Unit) = everyCheck(CONTENT_PHASE, hook)
407
+
408
+ /** `ngAfterViewChecked`: now, after `ngAfterViewInit`, then on every check of the view, after its child views. */
409
+ fun ViewChecked(hook: () -> Unit) = everyCheck(VIEW_PHASE, hook)
410
+
411
+ private fun everyCheck(phase: Int, hook: () -> Unit) {
412
+ Effect(EffectOrder.current.next(phase), false, { untrack(hook) })
413
+ }
414
+
415
+ /**
416
+ * A template's `@let`, made in its view's creation pass from the closure reading its value: [store], at its place in
417
+ * the update pass, reads it once on every check of the view as a binding does ([Check]), and its readers read [value],
418
+ * tracking it. Before a read has given it a value, [value] throws as Angular's does.
419
+ */
420
+ class LetSlot<T>(private val read: () -> T) {
421
+ @Suppress("UNCHECKED_CAST")
422
+ private val held = Signal(null as T).unset("NG0314: Attempting to access a @let declaration whose value is not available yet")
423
+
424
+ val value: T get() = held.value
425
+
426
+ fun store() = Check(true, read) { held.value = it }
427
+ }
428
+
429
+ /**
430
+ * Angular refreshes an embedded view (an `@if` branch, a `@for` row) after the bindings of the view declaring it, in
431
+ * the order its containers hold them, before that view's child components: [collect] runs a view's bindings, then the
432
+ * update passes of the branches and rows they made ([later]), each in the owner and scope it was made in. A branch a
433
+ * re-run condition makes outside any [collect] is updated at once.
434
+ */
435
+ object EmbeddedViews {
436
+ private class Held(val owner: Owner?, val scope: EffectOrder.Scope, val update: () -> Unit)
437
+
438
+ private val held = mutableListOf<MutableList<Held>>()
439
+
440
+ internal fun begin() {
441
+ held.add(mutableListOf())
442
+ }
443
+
444
+ internal fun flush() {
445
+ if (held.isEmpty()) return
446
+ val updates = held.removeAt(held.lastIndex)
447
+ for (h in updates) {
448
+ untrack {
449
+ EffectOrder.resume(h.scope) {
450
+ val owner = h.owner
451
+ if (owner != null) owner.run(h.update) else h.update()
452
+ }
453
+ }
454
+ }
455
+ }
456
+
457
+ fun collect(bindings: () -> Unit) {
458
+ begin()
459
+ try {
460
+ bindings()
461
+ } catch (e: Throwable) {
462
+ if (held.isNotEmpty()) held.removeAt(held.lastIndex)
463
+ throw e
464
+ }
465
+ flush()
466
+ }
467
+
468
+ fun later(update: () -> Unit) {
469
+ if (held.isEmpty()) return update()
470
+ held.last().add(Held(Owner.current, EffectOrder.current, update))
471
+ }
472
+ }
473
+
474
+ /**
475
+ * A pure Angular pipe at one binding site (`ɵɵpipeBind1`…): `transform` runs when an argument is no longer
476
+ * `Object.is` the one it last ran with, and otherwise the result it gave is returned. What it throws is not kept.
477
+ */
478
+ class PurePipeCache {
479
+ private var arguments: List<Any?>? = null
480
+ private var result: Any? = null
481
+
482
+ @Suppress("UNCHECKED_CAST")
483
+ private inline fun <R> run(given: List<Any?>, transform: () -> R): R {
484
+ val last = arguments
485
+ if (last != null && last.size == given.size && last.indices.all { jsSameValue(last[it], given[it]) }) return result as R
486
+ val value = transform()
487
+ arguments = given
488
+ result = value
489
+ return value
490
+ }
491
+
492
+ fun <A, R> pure1(a: A, transform: (A) -> R): R = run(listOf(a)) { transform(a) }
493
+ fun <A, B, R> pure2(a: A, b: B, transform: (A, B) -> R): R = run(listOf(a, b)) { transform(a, b) }
494
+ 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) }
495
+ 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) }
496
+ 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) }
497
+ }
498
+
499
+ /**
500
+ * `inject(ChangeDetectorRef)`: binds to the component's own view when injected inside [AngularView.construct], or the
501
+ * declaring view otherwise (directives, pipes). `markForCheck` marks it and its ancestors up to its root host view
502
+ * dirty; `detectChanges` refreshes only its own view subtree.
503
+ */
504
+ class ChangeDetectorRef internal constructor(internal var view: AngularView?) {
505
+ fun markForCheck() {
506
+ if (Zone.enabled) view?.markDirty() else Reactivity.markForCheck(view)
507
+ }
508
+
509
+ /** Refreshes this view subtree now, under both zone.js and zoneless modes. */
510
+ fun detectChanges() {
511
+ val v = view ?: return
512
+ Zone.detectChanges(v)
513
+ }
514
+
515
+ fun detach() {}
516
+ fun reattach() {}
517
+ fun checkNoChanges() {}
518
+
519
+ companion object {
520
+ fun current(): ChangeDetectorRef {
521
+ val frame = AngularView.frames.lastOrNull()
522
+ if (frame != null) {
523
+ val ref = ChangeDetectorRef(null)
524
+ frame.refs.add(ref)
525
+ return ref
526
+ }
527
+ return ChangeDetectorRef(EffectOrder.current.view)
528
+ }
529
+ }
530
+ }