@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,224 @@
1
+ package org.nativescript.kit
2
+
3
+ // The RxJS subset Angular services use, with RxJS 7's semantics: subscribers
4
+ // are called synchronously in subscription order, a BehaviorSubject replays
5
+ // its value to each new subscriber, and an operator subscribes to its source
6
+ // once per subscriber.
7
+
8
+ // Covariant: compiled code holds a source of any element type (`RxSubject<NavigationEnd>`) as `RxObservable<Any?>`.
9
+ open class RxObservable<out T> private constructor(
10
+ private val producer: ((T) -> Unit) -> TeardownHandle,
11
+ private val ending: (((T) -> Unit, (Any?) -> Unit, () -> Unit) -> TeardownHandle)?,
12
+ ) {
13
+ constructor(producer: ((T) -> Unit) -> TeardownHandle) : this(producer, null)
14
+
15
+ /** A source that settles once (an HTTP request): its value or its error, for `firstValueFrom`. */
16
+ var first: (() -> JSPromise<@UnsafeVariance T>)? = null
17
+
18
+ open fun subscribe(next: (T) -> Unit): TeardownHandle = producer(next)
19
+
20
+ /** A source made with [ending] reports its error and completion; any other only its values. */
21
+ open fun subscribe(next: (T) -> Unit, error: (Any?) -> Unit, complete: () -> Unit): TeardownHandle = ending?.invoke(next, error, complete) ?: subscribe(next)
22
+
23
+ companion object {
24
+ /** A source that also ends, with an error or by completing (kit-apple's `RxObservable(full:)`). */
25
+ fun <T> ending(producer: ((T) -> Unit, (Any?) -> Unit, () -> Unit) -> TeardownHandle): RxObservable<T> =
26
+ RxObservable({ next -> producer(next, {}, {}) }, producer)
27
+ }
28
+
29
+ /** Each value converted: how a typed `get<T>()` reads the parsed body. */
30
+ fun <R> mapValues(transform: (T) -> R): RxObservable<R> {
31
+ val mapped = RxObservable<R> { next -> subscribe { next(transform(it)) } }
32
+ first?.let { settle -> mapped.first = { settle().then { transform(it) } } }
33
+ return mapped
34
+ }
35
+
36
+ fun <A> pipe(a: RxOperatorFunction<T, A>): RxObservable<A> = a.apply(this)
37
+
38
+ fun <A, B> pipe(a: RxOperatorFunction<T, A>, b: RxOperatorFunction<A, B>): RxObservable<B> = b.apply(a.apply(this))
39
+
40
+ fun <A, B, C> pipe(a: RxOperatorFunction<T, A>, b: RxOperatorFunction<A, B>, c: RxOperatorFunction<B, C>): RxObservable<C> = c.apply(b.apply(a.apply(this)))
41
+ }
42
+
43
+ class RxOperatorFunction<in T, out R> internal constructor(internal val apply: (RxObservable<T>) -> RxObservable<R>)
44
+
45
+ /** `map(project)`: each value projected, with its index among the values this subscription saw. */
46
+ fun <T, R> map(project: (T, Double) -> R): RxOperatorFunction<T, R> = RxOperatorFunction { source ->
47
+ RxObservable { next ->
48
+ var index = 0.0
49
+ source.subscribe { value ->
50
+ val i = index
51
+ index += 1
52
+ next(project(value, i))
53
+ }
54
+ }
55
+ }
56
+
57
+ @JvmName("mapValue")
58
+ fun <T, R> map(project: (T) -> R): RxOperatorFunction<T, R> = map { value: T, _: Double -> project(value) }
59
+
60
+ /** `filter(predicate)`: the values the predicate holds for, with each value's index among those this subscription saw. */
61
+ fun <T> filter(predicate: (T, Double) -> Boolean): RxOperatorFunction<T, T> = RxOperatorFunction { source ->
62
+ RxObservable { next ->
63
+ var index = 0.0
64
+ source.subscribe { value ->
65
+ val i = index
66
+ index += 1
67
+ try {
68
+ if (predicate(value, i)) next(value)
69
+ } catch (e: Throwable) {
70
+ jsReportUncaught(jsCaught(e))
71
+ }
72
+ }
73
+ }
74
+ }
75
+
76
+ @JvmName("filterValue")
77
+ fun <T> filter(predicate: (T) -> Boolean): RxOperatorFunction<T, T> = filter { value: T, _: Double -> predicate(value) }
78
+
79
+ /** `take(count)`: the first `count` values of each subscription, then none. */
80
+ fun <T> take(count: Double): RxOperatorFunction<T, T> = RxOperatorFunction { source ->
81
+ RxObservable { next ->
82
+ var taken = 0.0
83
+ var subscription: TeardownHandle? = null
84
+ var done = false
85
+ subscription = source.subscribe { value ->
86
+ if (taken >= count) return@subscribe
87
+ taken += 1
88
+ next(value)
89
+ if (taken >= count) { done = true; subscription?.unsubscribe() }
90
+ }
91
+ if (done) subscription?.unsubscribe()
92
+ TeardownHandle { subscription?.unsubscribe() }
93
+ }
94
+ }
95
+
96
+ /** `firstValueFrom(source)`: settles with the source's first value. */
97
+ fun <T> rxFirstValueFrom(source: RxObservable<T>): JSPromise<T> {
98
+ source.first?.let { return it() }
99
+ val (promise, resolvers) = JSPromise.pending<T>()
100
+ var subscription: TeardownHandle? = null
101
+ var settled = false
102
+ subscription = source.subscribe { value ->
103
+ if (settled) return@subscribe
104
+ settled = true
105
+ resolvers.resolve(value)
106
+ subscription?.unsubscribe()
107
+ }
108
+ if (settled) subscription?.unsubscribe()
109
+ return promise
110
+ }
111
+
112
+ /**
113
+ * `toSignal(source, { initialValue })`: a signal holding the source's latest value, subscribed for as
114
+ * long as the scope it was made in lives, its writes compared with `Object.is` as Angular's signals compare them.
115
+ */
116
+ fun <T> toSignal(source: RxObservable<T>, initialValue: T): Signal<T> {
117
+ val signal = Signal(initialValue) { a, b -> jsSameValue(a, b) }
118
+ val subscription = source.subscribe { value -> signal.value = value }
119
+ Owner.current?.onCleanup { subscription.unsubscribe() }
120
+ return signal
121
+ }
122
+
123
+ open class RxSubject<T> : RxObservable<T>({ TeardownHandle() }) {
124
+ private class Observer<T>(val next: (T) -> Unit)
125
+
126
+ private val observers = mutableListOf<Observer<T>>()
127
+
128
+ override fun subscribe(next: (T) -> Unit): TeardownHandle = add(next)
129
+
130
+ internal open fun add(next: (T) -> Unit): TeardownHandle {
131
+ val observer = Observer(next)
132
+ observers.add(observer)
133
+ return TeardownHandle { observers.remove(observer) }
134
+ }
135
+
136
+ /** Calls the observers subscribed when `next` is called, as RxJS copies its observer list. */
137
+ open fun next(value: T) {
138
+ for (observer in observers.toList()) observer.next(value)
139
+ }
140
+
141
+ fun asObservable(): RxObservable<T> = RxObservable { next -> subscribe(next) }
142
+ }
143
+
144
+ class RxBehaviorSubject<T>(private var current: T) : RxSubject<T>() {
145
+ val value: T get() = current
146
+
147
+ @JvmName("currentValue")
148
+ fun getValue(): T = current
149
+
150
+ override fun add(next: (T) -> Unit): TeardownHandle {
151
+ val subscription = super.add(next)
152
+ if (!subscription.closed) next(current)
153
+ return subscription
154
+ }
155
+
156
+ override fun next(value: T) {
157
+ current = value
158
+ super.next(value)
159
+ }
160
+ }
161
+
162
+ /** `new ReplaySubject(bufferSize)`: replays the last `bufferSize` values to each new subscriber. */
163
+ class RxReplaySubject<T>(bufferSize: Double = Double.POSITIVE_INFINITY) : RxSubject<T>() {
164
+ private val buffer = ArrayDeque<T>()
165
+ private val size = if (bufferSize.isFinite()) maxOf(1, bufferSize.toInt()) else Int.MAX_VALUE
166
+
167
+ override fun add(next: (T) -> Unit): TeardownHandle {
168
+ val subscription = super.add(next)
169
+ for (value in buffer.toList()) if (!subscription.closed) next(value)
170
+ return subscription
171
+ }
172
+
173
+ override fun next(value: T) {
174
+ buffer.addLast(value)
175
+ while (buffer.size > size) buffer.removeFirst()
176
+ super.next(value)
177
+ }
178
+ }
179
+
180
+ /**
181
+ * Angular's `async` pipe at one binding site: subscribes to the observable
182
+ * it is given (again when given another), and returns its latest value.
183
+ */
184
+ class AsyncPipe {
185
+ private var source: Any? = null
186
+ private var subscription: TeardownHandle? = null
187
+ private var latest: Any? = null
188
+
189
+ init {
190
+ Owner.current?.onCleanup { dispose() }
191
+ }
192
+
193
+ @Suppress("UNCHECKED_CAST")
194
+ fun <T> transform(observable: RxObservable<T>?): T? {
195
+ if (observable !== source) {
196
+ dispose()
197
+ source = observable
198
+ subscription = observable?.subscribe { value -> latest = value }
199
+ }
200
+ return latest as T?
201
+ }
202
+
203
+ private fun dispose() {
204
+ subscription?.unsubscribe()
205
+ subscription = null
206
+ source = null
207
+ latest = null
208
+ }
209
+ }
210
+
211
+ /** `takeUntilDestroyed(destroyRef?)`: the source's values until the scope it was called in (or `destroyRef`'s) ends. */
212
+ fun <T> takeUntilDestroyed(destroyRef: DestroyRef? = null): RxOperatorFunction<T, T> {
213
+ val ref = destroyRef ?: DestroyRef.current()
214
+ return RxOperatorFunction { source ->
215
+ RxObservable { next ->
216
+ val subscription = source.subscribe(next)
217
+ val stop = ref.onDestroy { subscription.unsubscribe() }
218
+ TeardownHandle {
219
+ stop()
220
+ subscription.unsubscribe()
221
+ }
222
+ }
223
+ }
224
+ }
@@ -0,0 +1,224 @@
1
+ import Foundation
2
+
3
+ // Angular's dependency injection and the @nativescript/angular services an app
4
+ // injects, for components and services compiled to classes with a `shared`
5
+ // instance (`providedIn: 'root'`).
6
+
7
+ /// A component class used as a value (`dialog.open(SheetComponent)`): what creating and rendering it gives.
8
+ public final class ComponentFactory {
9
+ nonisolated deinit {}
10
+ let make: () throws -> View
11
+ public init(_ make: @escaping () throws -> View) { self.make = make }
12
+ }
13
+
14
+ /// `NativeDialogRef`: the open dialog a component was created in.
15
+ public final class NativeDialogRef {
16
+ nonisolated deinit {}
17
+ /// `inject(NativeDialogRef)`: the dialog being created; outside one, a ref to no dialog, whose `close` does nothing.
18
+ public static var current: NativeDialogRef { open ?? NativeDialogRef(detached: true) }
19
+ static var open: NativeDialogRef?
20
+ private let detached: Bool
21
+ init(detached: Bool = false) { self.detached = detached }
22
+ /// `NATIVE_DIALOG_DATA`: the `data` the dialog was opened with.
23
+ public internal(set) var data: Any? = nil
24
+ private let closed = RxReplaySubject<Any?>(1)
25
+
26
+ public func close(_ result: Any? = nil) { if !detached { Modal.close(result) } }
27
+ public func afterClosed() -> RxObservable<Any?> { closed.asObservable() }
28
+ func didClose(_ result: Any?) { closed.next(result) }
29
+ }
30
+
31
+ /// `NativeDialog` (`NativeDialogService`): a component shown as a native modal, with `nativeOptions` as `showModal` takes them.
32
+ public final class NativeDialogService {
33
+ nonisolated deinit {}
34
+ public static let shared = NativeDialogService()
35
+
36
+ @discardableResult
37
+ public func open(_ component: Any?, _ config: Any? = nil) -> NativeDialogRef {
38
+ let ref = NativeDialogRef()
39
+ ref.data = (try? jsGet(config, "data")) ?? nil
40
+ guard let factory = jsFlat(component) as? ComponentFactory else { return ref }
41
+ let options = (try? jsGet(config, "nativeOptions")) ?? nil
42
+ Modal.show(options: options, closeCallback: { result in ref.didClose(jsFlat(result)) }) {
43
+ let previous = NativeDialogRef.open
44
+ NativeDialogRef.open = ref
45
+ defer { NativeDialogRef.open = previous }
46
+ // The component in a ContentView of its own, the modal's root, as @nativescript/angular presents it:
47
+ // the root takes the safe area its content then lays out within.
48
+ let pending = Reactivity.pending()
49
+ let host = try ContentView()
50
+ host.content = try factory.make()
51
+ Reactivity.detectChanges(after: pending)
52
+ return host
53
+ }
54
+ return ref
55
+ }
56
+ }
57
+
58
+ /// `HttpClient` through core's `Http.request`, the request @nativescript/angular's backend sends through
59
+ /// core's XMLHttpRequest: the body parsed as JSON unless `responseType` is `'text'`, a status of 400 or more an error.
60
+ public final class HttpClient {
61
+ nonisolated deinit {}
62
+ public static let shared = HttpClient()
63
+
64
+ private func send(_ method: String, _ url: String, _ body: Any? = nil, _ options: Any? = nil) -> RxObservable<Any?> {
65
+ let flatOpts = jsFlat(options)
66
+ let text = jsToString((try? jsGet(flatOpts, "responseType")) ?? nil) == "text"
67
+ let observe = jsToString((try? jsGet(flatOpts, "observe")) ?? "body")
68
+ let rawHeaders = (try? jsGet(flatOpts, "headers")) ?? nil
69
+ let rawParams = (try? jsGet(flatOpts, "params")) ?? nil
70
+
71
+ var fullUrl = url
72
+ if !jsIsNullish(rawParams) {
73
+ let q = (jsFlat(rawParams) as? HttpParams)?.toString() ?? HttpParams(rawParams).toString()
74
+ if !q.isEmpty {
75
+ fullUrl = fullUrl.contains("?") ? "\(fullUrl)&\(q)" : "\(fullUrl)?\(q)"
76
+ }
77
+ }
78
+
79
+ var headersObj: Any? = (jsFlat(rawHeaders) as? HttpHeaders)?.toJSObject() ?? rawHeaders
80
+ let payloadBody = body ?? ((try? jsGet(flatOpts, "body")) ?? nil)
81
+ let upperMethod = method.uppercased()
82
+
83
+ let request: () -> JSPromise<Any?> = {
84
+ let failure = { (status: Double, reason: String) in JSError("Http failure response for \(fullUrl): \(jsToString(status)) \(reason)") }
85
+ let (promise, resolvers) = JSPromise<Any?>.pending()
86
+ var settings: [(String, Any?)] = [("url", fullUrl), ("method", upperMethod)]
87
+ if !jsIsNullish(payloadBody) && upperMethod != "GET" && upperMethod != "HEAD" {
88
+ if let s = payloadBody as? String {
89
+ settings.append(("content", s))
90
+ } else if let json = try? jsJSONStringifyChecked(payloadBody) {
91
+ settings.append(("content", json))
92
+ if jsIsNullish(headersObj) {
93
+ headersObj = JSObject([("Content-Type", "application/json")])
94
+ }
95
+ }
96
+ }
97
+ if !jsIsNullish(headersObj) { settings.append(("headers", headersObj)) }
98
+ let sent: JSPromise<Any?>
99
+ do { sent = try jsUnwrap(Core_http_http_request_index.request(JSObject(settings)), "then") } catch {
100
+ resolvers.reject(jsCaught(error))
101
+ return promise
102
+ }
103
+ _ = sent.then({ (response: Any?) -> Void in
104
+ do {
105
+ let status = jsToNumber(try jsGet(response, "statusCode"))
106
+ let reason = status == 0 ? "Unknown Error" : HTTPURLResponse.localizedString(forStatusCode: Int(status)).capitalized
107
+ if status >= 400 || status == 0 {
108
+ resolvers.reject(failure(status, reason))
109
+ return
110
+ }
111
+ let rawContent = jsToString(try jsCallMethod(try jsGet(response, "content"), "toString"))
112
+ let parsed: Any? = text ? rawContent : (rawContent.isEmpty ? nil : try jsJSONParse(rawContent))
113
+ if observe == "response" {
114
+ resolvers.resolve(HttpResponse(JSObject([
115
+ ("body", parsed),
116
+ ("status", status),
117
+ ("statusText", reason),
118
+ ("url", fullUrl),
119
+ ])))
120
+ } else {
121
+ resolvers.resolve(parsed)
122
+ }
123
+ } catch {
124
+ resolvers.reject(jsCaught(error))
125
+ }
126
+ }, { (_: Any?) -> Void in resolvers.reject(failure(0, "Unknown Error")) })
127
+ return promise
128
+ }
129
+ let observable = RxObservable<Any?>(full: { next, error, complete in
130
+ let subscription = TeardownHandle()
131
+ _ = request().then({ value in
132
+ if !subscription.closed {
133
+ next(value)
134
+ complete()
135
+ }
136
+ }, { err in
137
+ if !subscription.closed { error(err) }
138
+ })
139
+ return subscription
140
+ })
141
+ observable.first = request
142
+ return observable
143
+ }
144
+
145
+ public func request(_ first: Any?, _ url: String? = nil, _ options: Any? = nil) -> RxObservable<Any?> {
146
+ if let req = jsFlat(first) as? HttpRequest {
147
+ return send(req.method, req.url, req.body, JSObject([
148
+ ("headers", req.headers),
149
+ ("params", req.params),
150
+ ("responseType", req.responseType),
151
+ ("observe", "response"),
152
+ ]))
153
+ }
154
+ return send(jsToString(first), url ?? "", nil, options)
155
+ }
156
+
157
+ public func get(_ url: String, _ options: Any? = nil) -> RxObservable<Any?> {
158
+ send("GET", url, nil, options)
159
+ }
160
+
161
+ public func delete(_ url: String, _ options: Any? = nil) -> RxObservable<Any?> {
162
+ send("DELETE", url, nil, options)
163
+ }
164
+
165
+ public func head(_ url: String, _ options: Any? = nil) -> RxObservable<Any?> {
166
+ send("HEAD", url, nil, options)
167
+ }
168
+
169
+ public func options(_ url: String, _ options: Any? = nil) -> RxObservable<Any?> {
170
+ send("OPTIONS", url, nil, options)
171
+ }
172
+
173
+ public func post(_ url: String, _ body: Any? = nil, _ options: Any? = nil) -> RxObservable<Any?> {
174
+ send("POST", url, body, options)
175
+ }
176
+
177
+ public func put(_ url: String, _ body: Any? = nil, _ options: Any? = nil) -> RxObservable<Any?> {
178
+ send("PUT", url, body, options)
179
+ }
180
+
181
+ public func patch(_ url: String, _ body: Any? = nil, _ options: Any? = nil) -> RxObservable<Any?> {
182
+ send("PATCH", url, body, options)
183
+ }
184
+
185
+ public func jsonp(_ url: String, _ callbackParam: String) -> RxObservable<Any?> {
186
+ let sep = url.contains("?") ? "&" : "?"
187
+ return get("\(url)\(sep)\(jsEncodeURIComponent(callbackParam))=JSONP_CALLBACK")
188
+ }
189
+ }
190
+
191
+ public typealias KitHttpClient = HttpClient
192
+ public typealias KitNativeDialogRef = NativeDialogRef
193
+ public typealias KitNativeDialogService = NativeDialogService
194
+
195
+ // MARK: @angular/core/rxjs-interop
196
+
197
+ /// `toSignal(source, { initialValue })`: a signal holding the source's latest value, subscribed for as
198
+ /// long as the injecting scope lives, its writes compared with `Object.is` as Angular's signals compare them.
199
+ public func toSignal<T>(_ source: RxObservable<T>, initialValue: T) -> Signal<T> {
200
+ let signal = Signal(initialValue, equals: { jsSameValue($0, $1) })
201
+ let subscription = source.subscribe { (value: T) in signal.value = value }
202
+ Owner.current?.onCleanup { subscription.unsubscribe() }
203
+ return signal
204
+ }
205
+
206
+ /// `toSignal(source)`: undefined until the source's first value.
207
+ public func toSignal<T>(_ source: RxObservable<T>) -> Signal<T?> {
208
+ toSignal(source.mapValues { Optional($0) }, initialValue: nil)
209
+ }
210
+
211
+ /// `takeUntilDestroyed(destroyRef?)`: the source's values until the scope it was called in (or `destroyRef`'s) ends.
212
+ public func takeUntilDestroyed<T>(_ destroyRef: DestroyRef? = nil) -> RxOperatorFunction<T, T> {
213
+ let ref = destroyRef ?? DestroyRef.current()
214
+ return RxOperatorFunction { source in
215
+ RxObservable { next in
216
+ let subscription = source.subscribe(next)
217
+ let stop = ref.onDestroy { subscription.unsubscribe() }
218
+ return TeardownHandle {
219
+ stop()
220
+ subscription.unsubscribe()
221
+ }
222
+ }
223
+ }
224
+ }