@nativue/core 0.1.0 → 0.3.0

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.
Files changed (42) hide show
  1. package/Package.swift +26 -2
  2. package/android/build.gradle.kts +2 -2
  3. package/android/consumer-rules.pro +3 -0
  4. package/android/nativue.settings.gradle.kts +56 -0
  5. package/android/src/main/java/dev/nativue/Bridge.kt +51 -7
  6. package/android/src/main/java/dev/nativue/ModalHost.kt +2 -2
  7. package/android/src/main/java/dev/nativue/NativueActivity.kt +8 -0
  8. package/android/src/main/java/dev/nativue/Navigation.kt +32 -24
  9. package/android/src/main/java/dev/nativue/Plugins.kt +75 -0
  10. package/android/src/main/java/dev/nativue/Style.kt +5 -1
  11. package/android/src/main/java/dev/nativue/Theme.kt +61 -0
  12. package/android/src/main/java/dev/nativue/Views.kt +14 -2
  13. package/cli/config.d.mts +19 -0
  14. package/cli/config.mjs +4 -0
  15. package/cli/link.mjs +129 -0
  16. package/cli/nativue.mjs +67 -20
  17. package/cli/symbolicate.mjs +3 -5
  18. package/ios/Bridge.swift +207 -102
  19. package/ios/JavaScriptRuntime/JavaScriptRuntime.mm +231 -0
  20. package/ios/JavaScriptRuntime/include/NativueJavaScriptRuntime.h +29 -0
  21. package/ios/JavaScriptRuntime/vendor/hermes/LICENSE +21 -0
  22. package/ios/JavaScriptRuntime/vendor/hermes/Public/CrashManager.h +107 -0
  23. package/ios/JavaScriptRuntime/vendor/hermes/Public/CtorConfig.h +145 -0
  24. package/ios/JavaScriptRuntime/vendor/hermes/Public/GCConfig.h +211 -0
  25. package/ios/JavaScriptRuntime/vendor/hermes/Public/GCTripwireContext.h +40 -0
  26. package/ios/JavaScriptRuntime/vendor/hermes/Public/HermesExport.h +14 -0
  27. package/ios/JavaScriptRuntime/vendor/hermes/Public/RuntimeConfig.h +141 -0
  28. package/ios/JavaScriptRuntime/vendor/hermes/Public/SamplingProfiler.h +270 -0
  29. package/ios/JavaScriptRuntime/vendor/hermes/hermes.h +242 -0
  30. package/ios/NativeNode.swift +1 -0
  31. package/ios/NativueView.swift +10 -3
  32. package/ios/Plugins.swift +45 -0
  33. package/ios/Style.swift +14 -1
  34. package/package.json +7 -2
  35. package/src/appearance.ts +49 -0
  36. package/src/components.ts +3 -1
  37. package/src/entry.ts +2 -1
  38. package/src/globals.ts +3 -0
  39. package/src/native-functions.ts +41 -0
  40. package/src/renderer.ts +58 -1
  41. package/src/types.ts +2 -0
  42. package/src/virtual-modules.d.ts +2 -0
@@ -0,0 +1,242 @@
1
+ /*
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ #pragma once
9
+
10
+ #include <exception>
11
+ #include <list>
12
+ #include <map>
13
+ #include <memory>
14
+ #include <ostream>
15
+ #include <string>
16
+
17
+ #include <hermes/Public/HermesExport.h>
18
+ #include <hermes/Public/RuntimeConfig.h>
19
+ #include <hermes/Public/SamplingProfiler.h>
20
+ #include <jsi/hermes-interfaces.h>
21
+ #include <jsi/jsi.h>
22
+ #include <unordered_map>
23
+
24
+ struct HermesTestHelper;
25
+ struct SHUnit;
26
+ struct SHRuntime;
27
+
28
+ namespace hermes {
29
+ namespace vm {
30
+ class GCExecTrace;
31
+ class Runtime;
32
+ class SerializedValue;
33
+ } // namespace vm
34
+ } // namespace hermes
35
+
36
+ namespace facebook {
37
+ namespace jsi {
38
+
39
+ class ThreadSafeRuntime;
40
+
41
+ }
42
+
43
+ namespace hermes {
44
+
45
+ namespace debugger {
46
+ class Debugger;
47
+ }
48
+
49
+ class HermesRuntime;
50
+ /// The Hermes Root API interface. This is the entry point to create the Hermes
51
+ /// runtime and to access Hermes-specific methods that do not rely on a runtime
52
+ /// instance.
53
+ class HERMES_EXPORT IHermesRootAPI : public jsi::ICast {
54
+ public:
55
+ static constexpr jsi::UUID uuid{
56
+ 0xb654d898,
57
+ 0xdfad,
58
+ 0x11ef,
59
+ 0x859a,
60
+ 0x325096b39f47};
61
+
62
+ // Returns an instance of Hermes Runtime.
63
+ virtual std::unique_ptr<HermesRuntime> makeHermesRuntime(
64
+ const ::hermes::vm::RuntimeConfig &runtimeConfig) = 0;
65
+
66
+ virtual bool isHermesBytecode(const uint8_t *data, size_t len) = 0;
67
+
68
+ // Returns the supported bytecode version.
69
+ virtual uint32_t getBytecodeVersion() = 0;
70
+
71
+ // (EXPERIMENTAL) Issues madvise calls for portions of the given
72
+ // bytecode file that will likely be used when loading the bytecode
73
+ // file and running its global function.
74
+ virtual void prefetchHermesBytecode(const uint8_t *data, size_t len) = 0;
75
+
76
+ // Returns whether the data is valid HBC with more extensive checks than
77
+ // isHermesBytecode and returns why it isn't in errorMessage (if nonnull)
78
+ // if not.
79
+ virtual bool hermesBytecodeSanityCheck(
80
+ const uint8_t *data,
81
+ size_t len,
82
+ std::string *errorMessage = nullptr) = 0;
83
+
84
+ /// Sets a global fatal handler that is shared across all active Hermes
85
+ /// runtimes. Setting fatal handler in multiple places will override the
86
+ /// previous fatal handler set by this functionality.
87
+ /// The fatal handler must not throw exceptions, as Hermes is compiled without
88
+ /// exceptions.
89
+ virtual void setFatalHandler(void (*handler)(const std::string &)) = 0;
90
+
91
+ // Assuming that \p data is valid HBC bytecode data, returns a pointer to the
92
+ // first element of the epilogue, data append to the end of the bytecode
93
+ // stream. Return pair contain ptr to data and header.
94
+ virtual std::pair<const uint8_t *, size_t> getBytecodeEpilogue(
95
+ const uint8_t *data,
96
+ size_t len) = 0;
97
+
98
+ /// Enable sampling profiler.
99
+ /// Starts a separate thread that polls VM state with \p meanHzFreq frequency.
100
+ /// Any subsequent call to \c enableSamplingProfiler() is ignored until
101
+ /// next call to \c disableSamplingProfiler()
102
+ virtual void enableSamplingProfiler(double meanHzFreq = 100) = 0;
103
+
104
+ /// Disable the sampling profiler
105
+ virtual void disableSamplingProfiler() = 0;
106
+
107
+ /// Dump sampled stack trace to the given file name.
108
+ virtual void dumpSampledTraceToFile(const std::string &fileName) = 0;
109
+
110
+ /// Dump sampled stack trace to the given stream.
111
+ virtual void dumpSampledTraceToStream(std::ostream &stream) = 0;
112
+
113
+ /// Return the executed JavaScript function info.
114
+ /// This information holds the segmentID, Virtualoffset and sourceURL.
115
+ /// This information is needed specifically to be able to symbolicate non-CJS
116
+ /// bundles correctly. This API will be simplified later to simply return a
117
+ /// segmentID and virtualOffset, when we are able to only support CJS bundles.
118
+ virtual std::unordered_map<std::string, std::vector<std::string>>
119
+ getExecutedFunctions() = 0;
120
+
121
+ /// \return whether code coverage profiler is enabled or not.
122
+ virtual bool isCodeCoverageProfilerEnabled() = 0;
123
+
124
+ /// Enable code coverage profiler.
125
+ virtual void enableCodeCoverageProfiler() = 0;
126
+
127
+ /// Disable code coverage profiler.
128
+ virtual void disableCodeCoverageProfiler() = 0;
129
+
130
+ protected:
131
+ /// The destructor is protected as delete calls on interfaces must not occur.
132
+ /// It is also non-virtual to simplify the v-table.
133
+ ~IHermesRootAPI() {}
134
+ };
135
+
136
+ /// The setFatalHandler functionality has global effects, which may cause
137
+ /// unintended or surprising behavior for users of this API. For this reason, it
138
+ /// is not recommended and the functionality is provided by the optional
139
+ /// interface ISetFatalHandler.
140
+ class HERMES_EXPORT ISetFatalHandler : public jsi::ICast {
141
+ public:
142
+ static constexpr jsi::UUID uuid{
143
+ 0xda98a610,
144
+ 0x09cb,
145
+ 0x11f0,
146
+ 0x87bf,
147
+ 0x325096b39f47};
148
+ /// Sets a global fatal handler that is shared across all active Hermes
149
+ /// runtimes. Setting fatal handler in multiple places will override the
150
+ /// previous fatal handler set by this functionality.
151
+ /// The fatal handler must not throw exceptions, as Hermes is compiled without
152
+ /// exceptions.
153
+ virtual void setFatalHandler(void (*handler)(const std::string &)) = 0;
154
+
155
+ protected:
156
+ ~ISetFatalHandler() = default;
157
+ };
158
+
159
+ /// Interface for methods that are exposed for test purposes.
160
+ class HERMES_EXPORT IHermesTestHelpers : public jsi::ICast {
161
+ public:
162
+ static constexpr jsi::UUID uuid{
163
+ 0x664e489a,
164
+ 0xf941,
165
+ 0x11ef,
166
+ 0xa44c,
167
+ 0x325096b39f47};
168
+
169
+ virtual size_t rootsListLengthForTests() const = 0;
170
+
171
+ protected:
172
+ ~IHermesTestHelpers() = default;
173
+ };
174
+
175
+ #ifdef JSI_UNSTABLE
176
+ // Interface for methods that are exposed for tracing purposes.
177
+ class IHermesTracingHelpers : public jsi::ICast {
178
+ public:
179
+ static constexpr jsi::UUID uuid{
180
+ 0x74ac2c4e,
181
+ 0xc660,
182
+ 0x11f0,
183
+ 0x8de9,
184
+ 0x0242ac120002};
185
+
186
+ // Returns the secret for obtaining the underlying SerializedValue object
187
+ virtual const ::hermes::vm::SerializedValue *getHermesSerializedValue(
188
+ const jsi::Serialized &serialized) const = 0;
189
+ virtual const std::shared_ptr<jsi::Serialized> makeSerialized(
190
+ ::hermes::vm::SerializedValue &value) const = 0;
191
+
192
+ protected:
193
+ ~IHermesTracingHelpers() = default;
194
+ };
195
+ #endif
196
+
197
+ class HermesRuntime : public jsi::Runtime,
198
+ public IHermes,
199
+ public IHermesSHUnit {
200
+ public:
201
+ /// Similar to jsi::Runtime, HermesRuntime is treated as an object, rather
202
+ /// than a pure interface. This is to prevent breaking usages of
203
+ /// HermesRuntime prior to the introduction of jsi::IRuntime, IHermes, and
204
+ /// other interfaces.
205
+ ~HermesRuntime() override = default;
206
+
207
+ using jsi::Runtime::castInterface;
208
+ };
209
+
210
+ /// Returns a pointer to an object that can be cast into IHermesRootAPI, which
211
+ /// can be used to create a Hermes runtime and to access global Hermes-specific
212
+ /// methods. This object has static lifetime.
213
+ HERMES_EXPORT jsi::ICast *makeHermesRootAPI();
214
+
215
+ /// Return a RuntimeConfig that is more suited for running untrusted JS than
216
+ /// the default config. Disables some language features and may trade off some
217
+ /// performance for security.
218
+ ///
219
+ /// Can serve as a starting point with tweaks to re-enable needed features:
220
+ /// auto conf = hardenedHermesRuntimeConfig().rebuild();
221
+ /// conf.withArrayBuffer(true);
222
+ /// ...
223
+ /// auto runtime = makeHermesRuntime(conf.build());
224
+ HERMES_EXPORT ::hermes::vm::RuntimeConfig hardenedHermesRuntimeConfig();
225
+
226
+ HERMES_EXPORT std::unique_ptr<HermesRuntime> makeHermesRuntime(
227
+ const ::hermes::vm::RuntimeConfig &runtimeConfig =
228
+ ::hermes::vm::RuntimeConfig());
229
+
230
+ /// Create a HermesRuntime for the given config without throwing any exceptions.
231
+ /// This is safe to be called from code that is compiled without exceptions.
232
+ /// Returns nullptr on failure.
233
+ HERMES_EXPORT std::unique_ptr<HermesRuntime> makeHermesRuntimeNoThrow(
234
+ const ::hermes::vm::RuntimeConfig &runtimeConfig =
235
+ ::hermes::vm::RuntimeConfig()) noexcept;
236
+
237
+ HERMES_EXPORT std::unique_ptr<jsi::ThreadSafeRuntime>
238
+ makeThreadSafeHermesRuntime(
239
+ const ::hermes::vm::RuntimeConfig &runtimeConfig =
240
+ ::hermes::vm::RuntimeConfig());
241
+ } // namespace hermes
242
+ } // namespace facebook
@@ -119,6 +119,7 @@ final class NativeNode {
119
119
  childView.bounds.size = frame.size
120
120
  childView.center = CGPoint(x: frame.midX, y: frame.midY)
121
121
  }
122
+ childView.applyCornerRadius()
122
123
 
123
124
  applyFrames(of: child)
124
125
 
@@ -3,18 +3,25 @@ import SwiftUI
3
3
  /// The whole app: runs main.bundle.js (or the dev server's bundle) and shows what it renders.
4
4
  /// It fills the whole screen; <SafeAreaView> opts into the safe area.
5
5
  public struct NativueView: View {
6
- public init() {}
6
+ private let plugins: [NativuePlugin]
7
+
8
+ /// plugins: the native side of the app's packages, `nativuePlugins` from ios/NativuePlugins.
9
+ public init(plugins: [NativuePlugin] = []) {
10
+ self.plugins = plugins
11
+ }
7
12
 
8
13
  public var body: some View {
9
- VueRoot()
14
+ VueRoot(plugins: plugins)
10
15
  .ignoresSafeArea()
11
16
  .onOpenURL { url in NotificationCenter.default.post(name: Bridge.openURLNotification, object: url) }
12
17
  }
13
18
  }
14
19
 
15
20
  struct VueRoot: UIViewRepresentable {
21
+ let plugins: [NativuePlugin]
22
+
16
23
  func makeCoordinator() -> Bridge {
17
- Bridge()
24
+ Bridge(plugins: plugins)
18
25
  }
19
26
 
20
27
  func makeUIView(context: Context) -> RootView {
@@ -0,0 +1,45 @@
1
+ import UIKit
2
+
3
+ /// The native side of a package: functions JavaScript calls (`requireNativeFunction`) and views it
4
+ /// renders. Packages declare their plugin in package.json; the CLI links them into the app
5
+ /// (ios/NativuePlugins) and the app passes them on: `NativueView(plugins: nativuePlugins)`.
6
+ public protocol NativuePlugin {
7
+ func register(in registry: PluginRegistry)
8
+ }
9
+
10
+ public final class PluginRegistry {
11
+ public typealias Function = (_ arguments: [Any]) -> Any?
12
+ /// Its result resolves the JavaScript call's Promise; a thrown error rejects it.
13
+ public typealias AsyncFunction = (_ arguments: [Any]) async throws -> Any?
14
+ /// sendEvent("change", payload) reaches the element's @change; event names are lowercase.
15
+ public typealias SendEvent = (_ eventName: String, _ payload: Any?) -> Void
16
+ public typealias MakeView = (_ sendEvent: @escaping SendEvent) -> UIView
17
+
18
+ private(set) var functions: [String: Function] = [:]
19
+ private(set) var asyncFunctions: [String: AsyncFunction] = [:]
20
+ private(set) var viewMakers: [String: MakeView] = [:]
21
+
22
+ init(plugins: [NativuePlugin]) {
23
+ plugins.forEach { $0.register(in: self) }
24
+ }
25
+
26
+ /// Runs on the JavaScript thread and returns synchronously: hop to the main thread for UIKit.
27
+ public func addFunction(_ name: String, _ function: @escaping Function) {
28
+ functions[name] = function
29
+ }
30
+
31
+ /// For work that takes time (a permission prompt, the camera): JavaScript gets a Promise.
32
+ public func addAsyncFunction(_ name: String, _ function: @escaping AsyncFunction) {
33
+ asyncFunctions[name] = function
34
+ }
35
+
36
+ /// `type` is the element's tag, e.g. "MapView" for h('MapView'). Created on the main thread.
37
+ public func addView(_ type: String, _ makeView: @escaping MakeView) {
38
+ viewMakers[type] = makeView
39
+ }
40
+ }
41
+
42
+ /// A plugin view gets its props here, all but `style`, which nativue applies (layout included).
43
+ public protocol PluginView: UIView {
44
+ func setProp(_ key: String, value: Any?)
45
+ }
package/ios/Style.swift CHANGED
@@ -35,7 +35,8 @@ extension NativeNode {
35
35
  view.backgroundColor = UIColor(rgba: value)
36
36
 
37
37
  case "borderRadius":
38
- view.layer.cornerRadius = CGFloat(number(value) ?? 0)
38
+ view.layer.setValue(CGFloat(number(value) ?? 0), forKey: UIView.requestedCornerRadiusKey)
39
+ view.applyCornerRadius()
39
40
 
40
41
  case "borderWidth":
41
42
  view.layer.borderWidth = CGFloat(number(value) ?? 0)
@@ -355,3 +356,15 @@ extension NativeNode {
355
356
  return text.hasSuffix("deg") ? number * .pi / 180 : number
356
357
  }
357
358
  }
359
+
360
+ extension UIView {
361
+ static let requestedCornerRadiusKey = "nativueCornerRadius"
362
+
363
+ /// A radius over half the view's side (rounded-full is 9999) makes Core Animation draw nothing:
364
+ /// capped to a circle's, and applied again as the frame changes.
365
+ func applyCornerRadius() {
366
+ guard let requestedRadius = layer.value(forKey: Self.requestedCornerRadiusKey) as? CGFloat else { return }
367
+
368
+ layer.cornerRadius = min(requestedRadius, min(bounds.width, bounds.height) / 2)
369
+ }
370
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nativue/core",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Vue rendering real native views on iOS and Android",
5
5
  "keywords": [
6
6
  "vue",
@@ -25,7 +25,11 @@
25
25
  "exports": {
26
26
  ".": "./src/renderer.ts",
27
27
  "./router": "./src/router.ts",
28
- "./tsconfig.base.json": "./tsconfig.base.json"
28
+ "./tsconfig.base.json": "./tsconfig.base.json",
29
+ "./config": {
30
+ "types": "./cli/config.d.mts",
31
+ "default": "./cli/config.mjs"
32
+ }
29
33
  },
30
34
  "scripts": {
31
35
  "test": "(cd ../../examples/demo && nativue build) && node test/test.mjs",
@@ -50,6 +54,7 @@
50
54
  "tsconfig.base.json",
51
55
  "android/build.gradle.kts",
52
56
  "android/consumer-rules.pro",
57
+ "android/nativue.settings.gradle.kts",
53
58
  "android/src"
54
59
  ],
55
60
  "publishConfig": {
@@ -0,0 +1,49 @@
1
+ // The platform the app runs on, and the system's light or dark appearance.
2
+ import { readonly, shallowRef, type Ref } from '@vue/runtime-core'
3
+
4
+ export type ColorScheme = 'light' | 'dark'
5
+ export type PlatformOS = 'ios' | 'android'
6
+ type ColorSchemeListener = (colorScheme: ColorScheme) => void
7
+
8
+ const colorSchemeListeners = new Set<ColorSchemeListener>()
9
+ let colorScheme: ColorScheme = __native.colorScheme()
10
+ const colorSchemeRef = shallowRef(colorScheme)
11
+
12
+ // Platform.OS === 'ios'
13
+ // Platform.select({ ios: 17, android: 16 })
14
+ export const Platform = {
15
+ OS: __native.platform(),
16
+
17
+ select<Value>(values: { ios?: Value; android?: Value; default?: Value }): Value | undefined {
18
+ return values[Platform.OS] ?? values.default
19
+ },
20
+ }
21
+
22
+ // Appearance.getColorScheme() -> 'light' | 'dark'
23
+ // const stop = Appearance.addChangeListener((colorScheme) => …)
24
+ export const Appearance = {
25
+ getColorScheme(): ColorScheme {
26
+ return colorScheme
27
+ },
28
+
29
+ /** Returns a function that removes the listener. */
30
+ addChangeListener(listener: ColorSchemeListener): () => void {
31
+ colorSchemeListeners.add(listener)
32
+
33
+ return () => colorSchemeListeners.delete(listener)
34
+ },
35
+ }
36
+
37
+ // const colorScheme = useColorScheme() 'light' | 'dark', follows the system
38
+ export function useColorScheme(): Readonly<Ref<ColorScheme>> {
39
+ return readonly(colorSchemeRef)
40
+ }
41
+
42
+ // Native calls it when the system switches between light and dark.
43
+ globalThis.__colorSchemeChanged = (nextColorScheme) => {
44
+ if (nextColorScheme === colorScheme) return
45
+
46
+ colorScheme = nextColorScheme
47
+ colorSchemeRef.value = nextColorScheme
48
+ colorSchemeListeners.forEach((listener) => listener(nextColorScheme))
49
+ }
package/src/components.ts CHANGED
@@ -13,7 +13,8 @@ import type { ScrollEvent, Style } from './types'
13
13
  type Listener = ((payload: unknown) => void) | undefined
14
14
 
15
15
  // Vue's template compiler normalizes `:style`, so it can't be a function of the pressed state: the pressed
16
- // look goes in `pressed-style`, merged over `style` while pressed. The slot also receives { pressed }.
16
+ // look goes in `pressed-style`, merged over `style` while pressed. The slot also receives { pressed },
17
+ // and the class its pressed styles (Tailwind's active:).
17
18
  export const Pressable = defineComponent({
18
19
  name: 'Pressable',
19
20
  inheritAttrs: false,
@@ -38,6 +39,7 @@ export const Pressable = defineComponent({
38
39
  {
39
40
  ...attrs,
40
41
  style,
42
+ pressed: pressed.value,
41
43
  onPressIn: setPressed(true, attrs.onPressIn as Listener),
42
44
  onPressOut: setPressed(false, attrs.onPressOut as Listener),
43
45
  },
package/src/entry.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  // The app's entry, added by the CLI: every .vue file under the project's src/app/ is a route, so
2
- // projects have no main.js.
2
+ // projects have no main.js. The runtime modules of nativue.config's plugins run first.
3
+ import 'virtual:nativue/plugin-runtimes'
3
4
  import { createRouterApp } from './router'
4
5
 
5
6
  createRouterApp(import.meta.glob('/src/app/**/*.vue', { eager: true })).mount()
package/src/globals.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  // What the JavaScript engine has globally: the bridge, the hooks native calls into, and the web APIs
2
2
  // prelude.ts (timers, console) and fetch.ts provide. No DOM.
3
+ import type { ColorScheme } from './appearance'
3
4
  import type { NativeModule } from './types'
4
5
 
5
6
  declare global {
@@ -7,6 +8,8 @@ declare global {
7
8
  var __dispatch: (nodeId: number, eventName: string, payload: unknown) => void
8
9
  var __openURL: (url: string) => void
9
10
  var __fireTimer: (timerId: number) => void
11
+ var __colorSchemeChanged: (colorScheme: ColorScheme) => void
12
+ var __asyncFunctionFinished: (callId: number, value: unknown, errorMessage: string | null) => void
10
13
  var __animationFinished: (animationId: number, finished: boolean) => void
11
14
  var __fetchFinished: (
12
15
  requestId: number,
@@ -0,0 +1,41 @@
1
+ // The functions packages add natively, for their JS side to call:
2
+ // const impact = requireNativeFunction<(style: string) => void>('haptics.impact')
3
+ // const takePhoto = requireNativeFunction<() => Promise<string>>('camera.takePhoto')
4
+ // Native addFunction ones return synchronously, addAsyncFunction ones return a Promise.
5
+ type AnyFunction = (...args: never[]) => unknown
6
+ type NativeFunctions = Record<string, ((...args: unknown[]) => unknown) | undefined>
7
+ type PendingCall = { resolve: (value: unknown) => void; reject: (error: Error) => void }
8
+
9
+ const pendingCalls = new Map<number, PendingCall>()
10
+ let nextCallId = 1
11
+
12
+ globalThis.__asyncFunctionFinished = (callId, value, errorMessage) => {
13
+ const call = pendingCalls.get(callId)
14
+ if (!call) return
15
+
16
+ pendingCalls.delete(callId)
17
+ if (errorMessage === null) call.resolve(value)
18
+ else call.reject(new Error(errorMessage))
19
+ }
20
+
21
+ function asyncCaller(nativeFunction: (...args: unknown[]) => unknown) {
22
+ return (...args: unknown[]) =>
23
+ new Promise((resolve, reject) => {
24
+ const callId = nextCallId++
25
+ pendingCalls.set(callId, { resolve, reject })
26
+ nativeFunction(callId, ...args)
27
+ })
28
+ }
29
+
30
+ export function requireNativeFunction<Function extends AnyFunction>(name: string): Function {
31
+ const nativeFunctions = __native as unknown as NativeFunctions
32
+ const syncFunction = nativeFunctions[`plugin:${name}`]
33
+ const asyncFunction = nativeFunctions[`pluginAsync:${name}`]
34
+
35
+ if (syncFunction) return syncFunction as unknown as Function
36
+ if (asyncFunction) return asyncCaller(asyncFunction) as unknown as Function
37
+
38
+ throw new Error(
39
+ `The native function "${name}" isn't in the app. A package's native code is added when the app is built: rebuild it (npx nativue run ios / android).`,
40
+ )
41
+ }
package/src/renderer.ts CHANGED
@@ -14,11 +14,20 @@ import {
14
14
  type Directive,
15
15
  } from '@vue/runtime-core'
16
16
  import { animatedEventMapping, animatedStyleBinding, isAnimatedEvent } from './animated'
17
+ import { Appearance } from './appearance'
17
18
  import { COLOR_PROPERTIES, processColor } from './colors'
18
19
  import { FlatList, Pressable, Swipeable } from './components'
19
20
  import type { LayoutAnimationConfig, Style } from './types'
20
21
  export * from '@vue/runtime-core'
21
22
  export { Animated } from './animated'
23
+ export {
24
+ Appearance,
25
+ Platform,
26
+ useColorScheme,
27
+ type ColorScheme,
28
+ type PlatformOS,
29
+ } from './appearance'
30
+ export { requireNativeFunction } from './native-functions'
22
31
  export { AsyncStorage } from './storage'
23
32
  export type * from './types'
24
33
  export type { SvgElement, SvgIcon } from './native-components'
@@ -29,14 +38,31 @@ interface Node {
29
38
  parent: Node | null
30
39
  children: Node[]
31
40
  text: string
41
+ style?: Style | null
42
+ className?: string
43
+ /** A <Pressable>'s pressed state, for its class's pressed styles (Tailwind's active:). */
44
+ pressed?: boolean
45
+ classStyle?: Style
32
46
  }
33
47
 
34
48
  type EventHandler = (payload: unknown) => void
49
+ type ClassStyleResolver = (className: string, state: { pressed: boolean }) => Style
35
50
 
36
51
  const native = globalThis.__native
37
52
  let nextNodeId = 1
38
53
  // ponytail: handlers of removed nodes are never cleaned up; clean them on remove when it matters.
39
54
  const eventHandlersByNodeId: Record<number, Record<string, EventHandler | undefined>> = {}
55
+ let resolveClassStyle: ClassStyleResolver | null = null
56
+ // ponytail: a removed node leaves the set, its descendants stay; track them if apps churn many.
57
+ const nodesWithClass = new Set<Node>()
58
+
59
+ /**
60
+ * Gives `class` its styles, for a nativue.config plugin (@nativue/tailwind). Class styles may depend
61
+ * on the color scheme: they're resolved again when it changes.
62
+ */
63
+ export function setClassStyleResolver(resolver: ClassStyleResolver): void {
64
+ resolveClassStyle = resolver
65
+ }
40
66
 
41
67
  function createNode(type: string): Node {
42
68
  return { id: nextNodeId++, type, parent: null, children: [], text: '' }
@@ -115,6 +141,34 @@ function withoutAnimatedProperties(
115
141
  return staticStyle
116
142
  }
117
143
 
144
+ // The class's styles come first, so the style prop overrides them, as inline styles do on the web.
145
+ function combinedStyle(element: Node): Style | null {
146
+ if (!element.classStyle) return element.style ?? null
147
+
148
+ return { ...element.classStyle, ...element.style }
149
+ }
150
+
151
+ function classStyleOf(element: Node): Style | undefined {
152
+ if (!element.className || !resolveClassStyle) return undefined
153
+
154
+ return resolveClassStyle(element.className, { pressed: element.pressed ?? false })
155
+ }
156
+
157
+ /** Applies a change to what makes up the style (style, class, pressed state), sending only the diff. */
158
+ function updateStyle(element: Node, change: Pick<Node, 'style' | 'className' | 'pressed'>) {
159
+ const previousStyle = combinedStyle(element)
160
+
161
+ Object.assign(element, change)
162
+ element.classStyle = classStyleOf(element)
163
+
164
+ if (element.className) nodesWithClass.add(element)
165
+ else nodesWithClass.delete(element)
166
+
167
+ patchStyle(element, previousStyle, combinedStyle(element))
168
+ }
169
+
170
+ Appearance.addChangeListener(() => nodesWithClass.forEach((node) => updateStyle(node, {})))
171
+
118
172
  function patchStyle(element: Node, previousStyle: Style | null, nextStyle: Style | null) {
119
173
  const previousBinding = animatedStyleBinding(previousStyle)
120
174
  const nextBinding = animatedStyleBinding(nextStyle)
@@ -215,6 +269,7 @@ const { createApp: createBaseApp } = createRenderer<Node, Node>({
215
269
 
216
270
  remove(child) {
217
271
  const parent = detachFromParent(child)
272
+ nodesWithClass.delete(child)
218
273
 
219
274
  if (isNativeNode(child)) native.remove(child.id)
220
275
  else syncTextContent(parent)
@@ -231,7 +286,9 @@ const { createApp: createBaseApp } = createRenderer<Node, Node>({
231
286
  },
232
287
 
233
288
  patchProp(element, key, previousValue, nextValue, _namespace, component) {
234
- if (key === 'style') patchStyle(element, previousValue, nextValue)
289
+ if (key === 'style') updateStyle(element, { style: nextValue })
290
+ else if (key === 'class') updateStyle(element, { className: nextValue ?? undefined })
291
+ else if (key === 'pressed') updateStyle(element, { pressed: nextValue })
235
292
  // :on-pan="..." (v-bind, used for Animated.event) arrives kebab-case.
236
293
  else if (isEventProp(camelize(key))) {
237
294
  patchEventHandler(element, camelize(key), previousValue, nextValue, component ?? null)
package/src/types.ts CHANGED
@@ -104,6 +104,8 @@ export interface NativeModule {
104
104
  log(message: string): void
105
105
  reportError(message: string, details: string): void
106
106
  windowSize(): { width: number; height: number }
107
+ platform(): 'ios' | 'android'
108
+ colorScheme(): 'light' | 'dark'
107
109
  create(id: number, type: string): void
108
110
  insert(parentId: number, childId: number, index: number): void
109
111
  remove(id: number): void
@@ -0,0 +1,2 @@
1
+ // Generated by the CLI from nativue.config's plugins (cli/nativue.mjs).
2
+ declare module 'virtual:nativue/plugin-runtimes'