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