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

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