@amazon-devices/react-native-worklets 1.0.1 → 1.0.2

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 (95) hide show
  1. package/kepler-compatibility.json +2 -1
  2. package/lib/module/index.js +0 -25
  3. package/package.json +1 -1
  4. package/src/index.ts +0 -52
  5. package/bundleMode/index.js +0 -59
  6. package/lib/module/PlatformChecker/PlatformChecker.js +0 -8
  7. package/lib/module/PlatformChecker/index.js +0 -18
  8. package/lib/module/WorkletsError.js +0 -29
  9. package/lib/module/WorkletsModule/JSWorklets.js +0 -111
  10. package/lib/module/WorkletsModule/NativeWorklets.js +0 -126
  11. package/lib/module/WorkletsModule/index.js +0 -4
  12. package/lib/module/WorkletsModule/workletsModuleInstance.js +0 -7
  13. package/lib/module/WorkletsModule/workletsModuleInstance.web.js +0 -5
  14. package/lib/module/WorkletsModule/workletsModuleProxy.js +0 -4
  15. package/lib/module/bundleUnpacker.js +0 -47
  16. package/lib/module/callGuard.js +0 -30
  17. package/lib/module/deprecated.js +0 -20
  18. package/lib/module/errors.js +0 -69
  19. package/lib/module/featureFlags/index.js +0 -48
  20. package/lib/module/initializers.js +0 -221
  21. package/lib/module/isSynchronizable.js +0 -6
  22. package/lib/module/logger.js +0 -15
  23. package/lib/module/privateGlobals.d.js +0 -7
  24. package/lib/module/publicGlobals.js +0 -6
  25. package/lib/module/runLoop/common/setImmediatePolyfill.js +0 -15
  26. package/lib/module/runLoop/common/setIntervalPolyfill.js +0 -26
  27. package/lib/module/runLoop/uiRuntime/mockedRequestAnimationFrame.js +0 -10
  28. package/lib/module/runLoop/uiRuntime/requestAnimationFrame.js +0 -52
  29. package/lib/module/runLoop/uiRuntime/setTimeoutPolyfill.js +0 -32
  30. package/lib/module/runLoop/workletRuntime/index.js +0 -19
  31. package/lib/module/runLoop/workletRuntime/queueMicrotask.js +0 -11
  32. package/lib/module/runLoop/workletRuntime/requestAnimationFramePolyfill.js +0 -48
  33. package/lib/module/runLoop/workletRuntime/setTimeout.js +0 -28
  34. package/lib/module/runLoop/workletRuntime/taskQueue.js +0 -37
  35. package/lib/module/runtimeKind.js +0 -39
  36. package/lib/module/runtimes.js +0 -100
  37. package/lib/module/serializable.js +0 -568
  38. package/lib/module/serializableMappingCache.js +0 -37
  39. package/lib/module/specs/NativeWorkletsModule.js +0 -5
  40. package/lib/module/specs/NativeWorkletsModule.kepler.js +0 -7
  41. package/lib/module/specs/index.js +0 -10
  42. package/lib/module/synchronizable.js +0 -9
  43. package/lib/module/synchronizableUnpacker.js +0 -42
  44. package/lib/module/threads.js +0 -347
  45. package/lib/module/utils/checkCppVersion.js +0 -30
  46. package/lib/module/utils/jsVersion.js +0 -9
  47. package/lib/module/valueUnpacker.js +0 -60
  48. package/lib/module/workletFunction.js +0 -37
  49. package/lib/module/workletRuntimeEntry.js +0 -32
  50. package/lib/module/workletTypes.js +0 -12
  51. package/scripts/validate-react-native-version.js +0 -43
  52. package/src/PlatformChecker/PlatformChecker.ts +0 -7
  53. package/src/PlatformChecker/index.ts +0 -30
  54. package/src/WorkletsError.ts +0 -36
  55. package/src/WorkletsModule/JSWorklets.ts +0 -200
  56. package/src/WorkletsModule/NativeWorklets.ts +0 -256
  57. package/src/WorkletsModule/index.ts +0 -7
  58. package/src/WorkletsModule/workletsModuleInstance.ts +0 -9
  59. package/src/WorkletsModule/workletsModuleInstance.web.ts +0 -5
  60. package/src/WorkletsModule/workletsModuleProxy.ts +0 -126
  61. package/src/bundleUnpacker.ts +0 -75
  62. package/src/callGuard.ts +0 -33
  63. package/src/deprecated.ts +0 -32
  64. package/src/errors.ts +0 -80
  65. package/src/featureFlags/index.ts +0 -72
  66. package/src/initializers.ts +0 -262
  67. package/src/isSynchronizable.ts +0 -13
  68. package/src/logger.ts +0 -16
  69. package/src/publicGlobals.ts +0 -39
  70. package/src/runLoop/common/setImmediatePolyfill.ts +0 -20
  71. package/src/runLoop/common/setIntervalPolyfill.ts +0 -38
  72. package/src/runLoop/uiRuntime/mockedRequestAnimationFrame.ts +0 -11
  73. package/src/runLoop/uiRuntime/requestAnimationFrame.ts +0 -66
  74. package/src/runLoop/uiRuntime/setTimeoutPolyfill.ts +0 -40
  75. package/src/runLoop/workletRuntime/index.ts +0 -18
  76. package/src/runLoop/workletRuntime/queueMicrotask.ts +0 -13
  77. package/src/runLoop/workletRuntime/requestAnimationFramePolyfill.ts +0 -61
  78. package/src/runLoop/workletRuntime/setTimeout.ts +0 -37
  79. package/src/runLoop/workletRuntime/taskQueue.ts +0 -44
  80. package/src/runtimeKind.ts +0 -37
  81. package/src/runtimes.ts +0 -193
  82. package/src/serializable.ts +0 -801
  83. package/src/serializableMappingCache.ts +0 -42
  84. package/src/specs/NativeWorkletsModule.kepler.ts +0 -11
  85. package/src/specs/NativeWorkletsModule.ts +0 -9
  86. package/src/specs/index.ts +0 -13
  87. package/src/synchronizable.ts +0 -32
  88. package/src/synchronizableUnpacker.ts +0 -67
  89. package/src/threads.ts +0 -452
  90. package/src/utils/checkCppVersion.ts +0 -34
  91. package/src/utils/jsVersion.ts +0 -7
  92. package/src/valueUnpacker.ts +0 -90
  93. package/src/workletFunction.ts +0 -42
  94. package/src/workletRuntimeEntry.ts +0 -35
  95. package/src/workletTypes.ts +0 -81
@@ -1,42 +0,0 @@
1
- 'use strict';
2
- import { SHOULD_BE_USE_WEB } from './PlatformChecker';
3
- import type { SerializableRef } from './workletTypes';
4
-
5
- /**
6
- * This symbol is used to represent a mapping from the value to itself.
7
- *
8
- * It's used to prevent converting a serializable that's already converted - for
9
- * example a Shared Value that's in worklet's closure.
10
- */
11
- export const serializableMappingFlag = Symbol('serializable flag');
12
-
13
- /*
14
- During a fast refresh, React holds the same instance of a Mutable
15
- (that's guaranteed by `useRef`) but `serializableCache` gets regenerated and thus
16
- becoming empty. This happens when editing the file that contains the definition of this cache.
17
-
18
- Because of it, `createSerializable` can't find given mapping
19
- in `serializableCache` for the Mutable and tries to clone it as if it was a regular JS object.
20
- During cloning we use `Object.entries` to iterate over the keys which throws an error on accessing `_value`.
21
- For convenience we moved this cache to a separate file so it doesn't scare us with red squiggles.
22
- */
23
-
24
- const cache = SHOULD_BE_USE_WEB
25
- ? null
26
- : new WeakMap<object, SerializableRef | symbol>();
27
-
28
- export const serializableMappingCache = SHOULD_BE_USE_WEB
29
- ? {
30
- set() {
31
- // NOOP
32
- },
33
- get() {
34
- return null;
35
- },
36
- }
37
- : {
38
- set(serializable: object, serializableRef?: SerializableRef): void {
39
- cache!.set(serializable, serializableRef || serializableMappingFlag);
40
- },
41
- get: cache!.get.bind(cache),
42
- };
@@ -1,11 +0,0 @@
1
- 'use strict';
2
- // @ts-ignore No type definitions for KeplerTurboModule
3
- import type { KeplerTurboModule } from '@amazon-devices/react-native-kepler/Libraries/TurboModule/KeplerTurboModule';
4
- // @ts-ignore No type definitions for TurboModuleRegistry
5
- import * as TurboModuleRegistry from '@amazon-devices/react-native-kepler/Libraries/TurboModule/TurboModuleRegistry';
6
-
7
- interface Spec extends KeplerTurboModule {
8
- readonly installTurboModule: () => boolean;
9
- }
10
-
11
- export default TurboModuleRegistry.get<Spec>('WorkletsModule');
@@ -1,9 +0,0 @@
1
- 'use strict';
2
- import type { TurboModule } from 'react-native';
3
- import { TurboModuleRegistry } from 'react-native';
4
-
5
- export interface Spec extends TurboModule {
6
- installTurboModule: () => boolean;
7
- }
8
-
9
- export default TurboModuleRegistry.get<Spec>('WorkletsModule');
@@ -1,13 +0,0 @@
1
- 'use strict';
2
-
3
- import { RuntimeKind } from '../runtimeKind';
4
- import type { Spec } from './NativeWorkletsModule';
5
- import RNWorkletsTurboModule from './NativeWorkletsModule';
6
-
7
- export const WorkletsTurboModule: Spec | null =
8
- globalThis.__RUNTIME_KIND === RuntimeKind.ReactNative
9
- ? RNWorkletsTurboModule
10
- : // In Bundle Mode, on Worklet Runtimes `RNWorkletsTurboModule` isn't
11
- // available and shouldn't be accessed. We return null here
12
- // to keep the same codebase for the Bundle Mode and legacy behavior.
13
- null;
@@ -1,32 +0,0 @@
1
- 'use strict';
2
-
3
- import { createSerializable } from './serializable';
4
- import { WorkletsModule } from './WorkletsModule';
5
- import type { SerializableRef } from './workletTypes';
6
-
7
- export function createSynchronizable<TValue>(
8
- initialValue: TValue
9
- ): Synchronizable<TValue> {
10
- const synchronizableRef = WorkletsModule.createSynchronizable(
11
- createSerializable(initialValue)
12
- );
13
-
14
- return globalThis.__synchronizableUnpacker(
15
- synchronizableRef
16
- ) as unknown as Synchronizable<TValue>;
17
- }
18
-
19
- export type SynchronizableRef<TValue = unknown> = {
20
- __synchronizableRef: true;
21
- __nativeStateSynchronizableJSRef: TValue;
22
- };
23
-
24
- export type Synchronizable<TValue = unknown> = SerializableRef<TValue> &
25
- SynchronizableRef<TValue> & {
26
- __synchronizableRef: true;
27
- getDirty(): TValue;
28
- getBlocking(): TValue;
29
- setBlocking(value: TValue | ((prev: TValue) => TValue)): void;
30
- lock(): void;
31
- unlock(): void;
32
- };
@@ -1,67 +0,0 @@
1
- 'use strict';
2
-
3
- import { createSerializable } from './serializable';
4
- import type { Synchronizable, SynchronizableRef } from './synchronizable';
5
-
6
- export function __installUnpacker() {
7
- // TODO: Add cache for synchronizables.
8
- const serializer =
9
- !globalThis._WORKLET || globalThis._WORKLETS_BUNDLE_MODE
10
- ? (value: unknown, _: unknown) => createSerializable(value)
11
- : globalThis._createSerializable;
12
-
13
- function synchronizableUnpacker<TValue>(
14
- synchronizableRef: SynchronizableRef<TValue>
15
- ): Synchronizable<TValue> {
16
- const synchronizable =
17
- synchronizableRef as unknown as Synchronizable<TValue>;
18
- const proxy = globalThis.__workletsModuleProxy!;
19
-
20
- synchronizable.__synchronizableRef = true;
21
- synchronizable.getDirty = () => {
22
- return proxy.synchronizableGetDirty(synchronizable);
23
- };
24
- synchronizable.getBlocking = () => {
25
- return proxy.synchronizableGetBlocking(synchronizable);
26
- };
27
- synchronizable.setBlocking = (
28
- valueOrFunction: TValue | ((prev: TValue) => TValue)
29
- ) => {
30
- let newValue: TValue;
31
- if (typeof valueOrFunction === 'function') {
32
- const func = valueOrFunction as (prev: TValue) => TValue;
33
- synchronizable.lock();
34
- const prev = synchronizable.getBlocking();
35
- newValue = func(prev);
36
-
37
- proxy.synchronizableSetBlocking(
38
- synchronizable,
39
- serializer(newValue, undefined)
40
- );
41
-
42
- synchronizable.unlock();
43
- } else {
44
- const value = valueOrFunction;
45
- newValue = value;
46
- proxy.synchronizableSetBlocking(
47
- synchronizable,
48
- serializer(newValue, undefined)
49
- );
50
- }
51
- };
52
- synchronizable.lock = () => {
53
- proxy.synchronizableLock(synchronizable);
54
- };
55
- synchronizable.unlock = () => {
56
- proxy.synchronizableUnlock(synchronizable);
57
- };
58
-
59
- return synchronizable;
60
- }
61
-
62
- globalThis.__synchronizableUnpacker = synchronizableUnpacker;
63
- }
64
-
65
- export type SynchronizableUnpacker = <TValue>(
66
- synchronizableRef: SynchronizableRef<TValue>
67
- ) => Synchronizable<TValue>;
package/src/threads.ts DELETED
@@ -1,452 +0,0 @@
1
- 'use strict';
2
- import { IS_JEST, SHOULD_BE_USE_WEB } from './PlatformChecker';
3
- import { RuntimeKind } from './runtimeKind';
4
- import {
5
- createSerializable,
6
- makeShareableCloneOnUIRecursive,
7
- } from './serializable';
8
- import { serializableMappingCache } from './serializableMappingCache';
9
- import { isWorkletFunction } from './workletFunction';
10
- import { WorkletsError } from './WorkletsError';
11
- import { WorkletsModule } from './WorkletsModule';
12
- import type { WorkletFunction, WorkletImport } from './workletTypes';
13
-
14
- type UIJob<Args extends unknown[] = unknown[], ReturnValue = unknown> = [
15
- worklet: WorkletFunction<Args, ReturnValue>,
16
- args: Args,
17
- resolve?: (value: ReturnValue) => void,
18
- ];
19
-
20
- let runOnUIQueue: UIJob[] = [];
21
-
22
- export function setupMicrotasks() {
23
- 'worklet';
24
-
25
- let microtasksQueue: Array<() => void> = [];
26
- let isExecutingMicrotasksQueue = false;
27
- global.queueMicrotask = (callback: () => void) => {
28
- microtasksQueue.push(callback);
29
- };
30
- global._microtaskQueueFinalizers = [];
31
-
32
- global.__callMicrotasks = () => {
33
- if (isExecutingMicrotasksQueue) {
34
- return;
35
- }
36
- try {
37
- isExecutingMicrotasksQueue = true;
38
- for (let index = 0; index < microtasksQueue.length; index += 1) {
39
- // we use classic 'for' loop because the size of the currentTasks array may change while executing some of the callbacks due to queueMicrotask calls
40
- microtasksQueue[index]();
41
- }
42
- microtasksQueue = [];
43
- global._microtaskQueueFinalizers.forEach((finalizer) => finalizer());
44
- } finally {
45
- isExecutingMicrotasksQueue = false;
46
- }
47
- };
48
- }
49
-
50
- function callMicrotasksOnUIThread() {
51
- 'worklet';
52
- global.__callMicrotasks();
53
- }
54
-
55
- export const callMicrotasks = SHOULD_BE_USE_WEB
56
- ? () => {
57
- // on web flushing is a noop as immediates are handled by the browser
58
- }
59
- : callMicrotasksOnUIThread;
60
-
61
- /**
62
- * Lets you schedule a function to be executed on the [UI
63
- * Runtime](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/glossary#ui-runtime).
64
- *
65
- * - The callback executes asynchronously and doesn't return a value.
66
- * - Passed function and args are automatically
67
- * [workletized](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/glossary#to-workletize)
68
- * and serialized.
69
- * - This function cannot be called from the [UI
70
- * Runtime](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/glossary#ui-runtime)
71
- * or [Worker
72
- * Runtime](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/glossary#worker-worklet-runtime---worker-runtime),
73
- * unless you have the [Bundle Mode](/docs/experimental/bundleMode) enabled.
74
- *
75
- * @param fun - A reference to a function you want to schedule on the [UI
76
- * Runtime](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/glossary#ui-runtime).
77
- * @param args - Arguments to pass to the function.
78
- * @see https://docs.swmansion.com/react-native-worklets/docs/threading/scheduleOnUI
79
- */
80
- export function scheduleOnUI<Args extends unknown[], ReturnValue>(
81
- worklet: (...args: Args) => ReturnValue,
82
- ...args: Args
83
- ): void {
84
- runOnUI(worklet)(...args);
85
- }
86
-
87
- /**
88
- * Lets you asynchronously run
89
- * [workletized](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/glossary#to-workletize)
90
- * functions on the [UI
91
- * thread](https://docs.swmansion.com/react-native-worklets/docs/threading/runOnUI/).
92
- *
93
- * This method does not schedule the work immediately but instead waits for
94
- * other worklets to be scheduled within the same JS loop. It uses
95
- * queueMicrotask to schedule all the worklets at once making sure they will run
96
- * within the same frame boundaries on the UI thread.
97
- *
98
- * @param fun - A reference to a function you want to execute on the [UI
99
- * thread](https://docs.swmansion.com/react-native-worklets/docs/threading/runOnUI/)
100
- * from the [JavaScript
101
- * thread](https://docs.swmansion.com/react-native-worklets/docs/threading/runOnUI/).
102
- * @returns A function that accepts arguments for the function passed as the
103
- * first argument.
104
- * @see https://docs.swmansion.com/react-native-worklets/docs/threading/runOnUI @deprecated Use `scheduleOnUI` instead.
105
- */
106
- // @ts-expect-error This overload is correct since it's what user sees in his code
107
- // before it's transformed by Reanimated Babel plugin.
108
- export function runOnUI<Args extends unknown[], ReturnValue>(
109
- worklet: (...args: Args) => ReturnValue
110
- ): (...args: Args) => void;
111
-
112
- export function runOnUI<Args extends unknown[], ReturnValue>(
113
- worklet: WorkletFunction<Args, ReturnValue>
114
- ): (...args: Args) => void {
115
- if (
116
- __DEV__ &&
117
- !SHOULD_BE_USE_WEB &&
118
- !isWorkletFunction(worklet) &&
119
- !(worklet as unknown as WorkletImport).__bundleData
120
- ) {
121
- throw new WorkletsError('`runOnUI` can only be used with worklets.');
122
- }
123
- return (...args) => {
124
- if (IS_JEST) {
125
- // Mocking time in Jest is tricky as both requestAnimationFrame and queueMicrotask
126
- // callbacks run on the same queue and can be interleaved. There is no way
127
- // to flush particular queue in Jest and the only control over mocked timers
128
- // is by using jest.advanceTimersByTime() method which advances all types
129
- // of timers including immediate and animation callbacks. Ideally we'd like
130
- // to have some way here to schedule work along with React updates, but
131
- // that's not possible, and hence in Jest environment instead of using scheduling
132
- // mechanism we just schedule the work ommiting the queue. This is ok for the
133
- // uses that we currently have but may not be ok for future tests that we write.
134
- WorkletsModule.scheduleOnUI(
135
- createSerializable(() => {
136
- 'worklet';
137
- worklet(...args);
138
- })
139
- );
140
- return;
141
- }
142
- if (__DEV__) {
143
- // in DEV mode we call serializable conversion here because in case the object
144
- // can't be converted, we will get a meaningful stack-trace as opposed to the
145
- // situation when conversion is only done via microtask queue. This does not
146
- // make the app particularily less efficient as converted objects are cached
147
- // and for a given worklet the conversion only happens once.
148
- createSerializable(worklet);
149
- createSerializable(args);
150
- }
151
-
152
- enqueueUI(worklet, args);
153
- };
154
- }
155
-
156
- if (__DEV__) {
157
- function runOnUIWorklet(): void {
158
- 'worklet';
159
- throw new WorkletsError(
160
- '`runOnUI` cannot be called on the UI runtime. Please call the function synchronously or use `queueMicrotask` or `requestAnimationFrame` instead.'
161
- );
162
- }
163
-
164
- const serializableRunOnUIWorklet = createSerializable(runOnUIWorklet);
165
- serializableMappingCache.set(runOnUI, serializableRunOnUIWorklet);
166
- }
167
-
168
- /**
169
- * Lets you run a function synchronously on the [UI
170
- * Runtime](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/glossary#ui-runtime)
171
- * from the [RN
172
- * Runtime](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/glossary#react-native-runtime-rn-runtime).
173
- * Passed function and args are automatically
174
- * [workletized](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/glossary#to-workletize)
175
- * and serialized.
176
- *
177
- * - This function cannot be called from the [UI
178
- * Runtime](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/glossary#ui-runtime).
179
- * - This function cannot be called from a [Worker
180
- * Runtime](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/glossary#worker-worklet-runtime---worker-runtime).
181
- *
182
- * @param fun - A reference to a function you want to execute on the [UI
183
- * Runtime](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/glossary#ui-runtime).
184
- * @param args - Arguments to pass to the function.
185
- * @returns The return value of the function passed as the first argument.
186
- * @see https://docs.swmansion.com/react-native-worklets/docs/threading/runOnUISync
187
- */
188
- export function runOnUISync<Args extends unknown[], ReturnValue>(
189
- worklet: (...args: Args) => ReturnValue,
190
- ...args: Args
191
- ): ReturnValue {
192
- return executeOnUIRuntimeSync(worklet)(...args);
193
- }
194
-
195
- // @ts-expect-error Check `executeOnUIRuntimeSync` overload above.
196
- export function executeOnUIRuntimeSync<Args extends unknown[], ReturnValue>(
197
- worklet: (...args: Args) => ReturnValue
198
- ): (...args: Args) => ReturnValue;
199
-
200
- export function executeOnUIRuntimeSync<Args extends unknown[], ReturnValue>(
201
- worklet: WorkletFunction<Args, ReturnValue>
202
- ): (...args: Args) => ReturnValue {
203
- return (...args) => {
204
- return WorkletsModule.executeOnUIRuntimeSync(
205
- createSerializable(() => {
206
- 'worklet';
207
- const result = worklet(...args);
208
- return makeShareableCloneOnUIRecursive(result);
209
- })
210
- );
211
- };
212
- }
213
-
214
- type ReleaseRemoteFunction<Args extends unknown[], ReturnValue> = {
215
- (...args: Args): ReturnValue;
216
- };
217
-
218
- type DevRemoteFunction<Args extends unknown[], ReturnValue> = {
219
- __remoteFunction: (...args: Args) => ReturnValue;
220
- };
221
-
222
- type RemoteFunction<Args extends unknown[], ReturnValue> =
223
- | ReleaseRemoteFunction<Args, ReturnValue>
224
- | DevRemoteFunction<Args, ReturnValue>;
225
-
226
- function runWorkletOnJS<Args extends unknown[], ReturnValue>(
227
- worklet: WorkletFunction<Args, ReturnValue>,
228
- ...args: Args
229
- ): void {
230
- // remote function that calls a worklet synchronously on the JS runtime
231
- worklet(...args);
232
- }
233
-
234
- /**
235
- * Lets you asynchronously run
236
- * non-[workletized](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/glossary#to-workletize)
237
- * functions that couldn't otherwise run on the [UI
238
- * thread](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/glossary#ui-thread).
239
- * This applies to most external libraries as they don't have their functions
240
- * marked with "worklet"; directive.
241
- *
242
- * @param fun - A reference to a function you want to execute on the JavaScript
243
- * thread from the UI thread.
244
- * @returns A function that accepts arguments for the function passed as the
245
- * first argument.
246
- * @see https://docs.swmansion.com/react-native-worklets/docs/threading/runOnJS
247
- */
248
- /** @deprecated Use `scheduleOnRN` instead. */
249
- export function runOnJS<Args extends unknown[], ReturnValue>(
250
- fun:
251
- | ((...args: Args) => ReturnValue)
252
- | RemoteFunction<Args, ReturnValue>
253
- | WorkletFunction<Args, ReturnValue>
254
- ): (...args: Args) => void {
255
- 'worklet';
256
- type FunDevRemote = Extract<typeof fun, DevRemoteFunction<Args, ReturnValue>>;
257
- if (
258
- SHOULD_BE_USE_WEB ||
259
- globalThis.__RUNTIME_KIND === RuntimeKind.ReactNative
260
- ) {
261
- // if we are already on the JS thread, we just schedule the worklet on the JS queue
262
- return (...args) =>
263
- queueMicrotask(
264
- args.length
265
- ? () => (fun as (...args: Args) => ReturnValue)(...args)
266
- : (fun as () => ReturnValue)
267
- );
268
- }
269
- if (isWorkletFunction<Args, ReturnValue>(fun)) {
270
- // If `fun` is a worklet, we schedule a call of a remote function `runWorkletOnJS`
271
- // and pass the worklet as a first argument followed by original arguments.
272
-
273
- return (...args) =>
274
- runOnJS(runWorkletOnJS<Args, ReturnValue>)(
275
- fun as WorkletFunction<Args, ReturnValue>,
276
- ...args
277
- );
278
- }
279
- if ((fun as FunDevRemote).__remoteFunction) {
280
- // In development mode the function provided as `fun` throws an error message
281
- // such that when someone accidentally calls it directly on the UI runtime, they
282
- // see that they should use `runOnJS` instead. To facilitate that we put the
283
- // reference to the original remote function in the `__remoteFunction` property.
284
- fun = (fun as FunDevRemote).__remoteFunction;
285
- }
286
-
287
- const scheduleOnJS =
288
- typeof fun === 'function'
289
- ? global._scheduleHostFunctionOnJS
290
- : global._scheduleRemoteFunctionOnJS;
291
-
292
- return (...args) => {
293
- scheduleOnJS(
294
- fun as
295
- | ((...args: Args) => ReturnValue)
296
- | WorkletFunction<Args, ReturnValue>,
297
- args.length > 0 ? makeShareableCloneOnUIRecursive(args) : undefined
298
- );
299
- };
300
- }
301
-
302
- /**
303
- * Lets you schedule a function to be executed on the RN runtime from any
304
- * runtime. Check
305
- * {@link https://docs.swmansion.com/react-native-worklets/docs/fundamentals/runtimeKinds}
306
- * for more information about the different runtime kinds.
307
- *
308
- * Scheduling function from the RN Runtime (we are already on RN Runtime) simply
309
- * uses `queueMicrotask`.
310
- *
311
- * When functions need to be scheduled from the UI Runtime, first function and
312
- * args are serialized and then the system passes the scheduling responsibility
313
- * to the JSScheduler. The JSScheduler then uses the RN CallInvoker to schedule
314
- * the function asynchronously on the JavaScript thread by calling
315
- * `jsCallInvoker_->invokeAsync()`.
316
- *
317
- * When called from a Worker Runtime, it uses the same JSScheduler mechanism.
318
- *
319
- * @param fun - A function you want to schedule on the RN runtime. A function
320
- * can be a worklet, a remote function or a regular function.
321
- * @param args - Arguments to pass to the function.
322
- * @see https://docs.swmansion.com/react-native-worklets/docs/threading/scheduleOnRN
323
- */
324
- export function scheduleOnRN<Args extends unknown[], ReturnValue>(
325
- fun:
326
- | ((...args: Args) => ReturnValue)
327
- | RemoteFunction<Args, ReturnValue>
328
- | WorkletFunction<Args, ReturnValue>,
329
- ...args: Args
330
- ): void {
331
- 'worklet';
332
- runOnJS(fun)(...args);
333
- }
334
-
335
- /**
336
- * Lets you asynchronously run
337
- * [workletized](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/glossary#to-workletize)
338
- * functions on the [UI
339
- * Runtime](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/glossary#ui-runtime).
340
- *
341
- * This method does not schedule the work immediately but instead waits for
342
- * other worklets to be scheduled within the same JS loop. It uses
343
- * queueMicrotask to schedule all the worklets at once making sure they will run
344
- * within the same frame boundaries on the UI thread.
345
- *
346
- * @param fun - A reference to a function you want to execute on the [UI
347
- * Runtime](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/glossary#ui-runtime).
348
- * from the [JavaScript
349
- * Runtime](https://docs.swmansion.com/react-native-worklets/docs/fundamentals/glossary#javascript-runtime).
350
- * @returns A promise that resolves to the return value of the function passed
351
- * as the first argument.
352
- * @see https://docs.swmansion.com/react-native-worklets/docs/threading/runOnUIAsync
353
- */
354
- export function runOnUIAsync<Args extends unknown[], ReturnValue>(
355
- worklet: (...args: Args) => ReturnValue
356
- ): (...args: Args) => Promise<ReturnValue> {
357
- if (__DEV__ && !SHOULD_BE_USE_WEB && !isWorkletFunction(worklet)) {
358
- throw new WorkletsError('`runOnUIAsync` can only be used with worklets.');
359
- }
360
- return (...args: Args) => {
361
- return new Promise<ReturnValue>((resolve) => {
362
- if (IS_JEST) {
363
- // Mocking time in Jest is tricky as both requestAnimationFrame and queueMicrotask
364
- // callbacks run on the same queue and can be interleaved. There is no way
365
- // to flush particular queue in Jest and the only control over mocked timers
366
- // is by using jest.advanceTimersByTime() method which advances all types
367
- // of timers including immediate and animation callbacks. Ideally we'd like
368
- // to have some way here to schedule work along with React updates, but
369
- // that's not possible, and hence in Jest environment instead of using scheduling
370
- // mechanism we just schedule the work ommiting the queue. This is ok for the
371
- // uses that we currently have but may not be ok for future tests that we write.
372
- WorkletsModule.scheduleOnUI(
373
- createSerializable(() => {
374
- 'worklet';
375
- worklet(...args);
376
- })
377
- );
378
- return;
379
- }
380
- if (__DEV__) {
381
- // in DEV mode we call serializable conversion here because in case the object
382
- // can't be converted, we will get a meaningful stack-trace as opposed to the
383
- // situation when conversion is only done via microtask queue. This does not
384
- // make the app particularily less efficient as converted objects are cached
385
- // and for a given worklet the conversion only happens once.
386
- createSerializable(worklet);
387
- createSerializable(args);
388
- }
389
-
390
- enqueueUI(worklet as WorkletFunction<Args, ReturnValue>, args, resolve);
391
- });
392
- };
393
- }
394
-
395
- if (__DEV__) {
396
- function runOnUIAsyncWorklet(): void {
397
- 'worklet';
398
- throw new WorkletsError(
399
- '`runOnUIAsync` cannot be called on the UI runtime. Please call the function synchronously or use `queueMicrotask` or `requestAnimationFrame` instead.'
400
- );
401
- }
402
-
403
- const serializableRunOnUIAsyncWorklet =
404
- createSerializable(runOnUIAsyncWorklet);
405
- serializableMappingCache.set(runOnUIAsync, serializableRunOnUIAsyncWorklet);
406
- }
407
-
408
- function enqueueUI<Args extends unknown[], ReturnValue>(
409
- worklet: WorkletFunction<Args, ReturnValue>,
410
- args: Args,
411
- resolve?: (value: ReturnValue) => void
412
- ): void {
413
- const job = [worklet, args, resolve] as UIJob<Args, ReturnValue>;
414
- runOnUIQueue.push(job as unknown as UIJob);
415
- if (runOnUIQueue.length === 1) {
416
- flushUIQueue();
417
- }
418
- }
419
-
420
- function flushUIQueue(): void {
421
- queueMicrotask(() => {
422
- const queue = runOnUIQueue;
423
- runOnUIQueue = [];
424
- WorkletsModule.scheduleOnUI(
425
- createSerializable(() => {
426
- 'worklet';
427
- queue.forEach(([workletFunction, workletArgs, jobResolve]) => {
428
- const result = workletFunction(...workletArgs);
429
- if (jobResolve) {
430
- runOnJS(jobResolve)(result);
431
- }
432
- });
433
- callMicrotasks();
434
- })
435
- );
436
- });
437
- }
438
-
439
- /**
440
- * Added temporarily for integration with `react-native-audio-api`. Don't depend
441
- * on this API as it may change without notice.
442
- */
443
- // eslint-disable-next-line camelcase
444
- export function unstable_eventLoopTask<TArgs extends unknown[], TRet>(
445
- worklet: (...args: TArgs) => TRet
446
- ) {
447
- return (...args: TArgs) => {
448
- 'worklet';
449
- worklet(...args);
450
- callMicrotasks();
451
- };
452
- }
@@ -1,34 +0,0 @@
1
- 'use strict';
2
- import { logger } from '../logger';
3
- import { WorkletsError } from '../WorkletsError';
4
- import { jsVersion } from './jsVersion';
5
-
6
- export function checkCppVersion() {
7
- const cppVersion = global._WORKLETS_VERSION_CPP;
8
- if (cppVersion === undefined) {
9
- logger.warn(
10
- `Couldn't determine the version of the native part of Worklets.
11
- See \`https://docs.swmansion.com/react-native-worklets/docs/guides/troubleshooting#couldnt-determine-the-version-of-the-native-part-of-worklets\` for more details.`
12
- );
13
- return;
14
- }
15
- const ok = matchVersion(jsVersion, cppVersion);
16
- if (!ok) {
17
- throw new WorkletsError(
18
- `Mismatch between JavaScript part and native part of Worklets (${jsVersion} vs ${cppVersion}).
19
- See \`https://docs.swmansion.com/react-native-worklets/docs/guides/troubleshooting#mismatch-between-javascript-part-and-native-part-of-worklets\` for more details.`
20
- );
21
- }
22
- }
23
-
24
- export function matchVersion(version1: string, version2: string) {
25
- if (version1.match(/^\d+\.\d+\.\d+$/) && version2.match(/^\d+\.\d+\.\d+$/)) {
26
- // x.y.z, compare only major and minor, skip patch
27
- const [major1, minor1] = version1.split('.');
28
- const [major2, minor2] = version2.split('.');
29
- return major1 === major2 && minor1 === minor2;
30
- } else {
31
- // alpha, beta or rc, compare everything
32
- return version1 === version2;
33
- }
34
- }
@@ -1,7 +0,0 @@
1
- 'use strict';
2
- /**
3
- * We hardcode the version of Worklets here in order to compare it with the
4
- * version used to build the native part of the library in runtime. Remember to
5
- * keep this in sync with the version declared in `package.json`
6
- */
7
- export const jsVersion = '1.0.0+0.6.0';