@lynx-js/react 0.105.0 → 0.105.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 (152) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +57 -5
  3. package/package.json +7 -2
  4. package/refresh/.turbo/turbo-build.log +1 -1
  5. package/refresh/package.json +1 -1
  6. package/runtime/lib/backgroundSnapshot.d.ts +1 -1
  7. package/runtime/lib/backgroundSnapshot.js +2 -2
  8. package/runtime/lib/backgroundSnapshot.js.map +1 -1
  9. package/runtime/lib/compat/initData.js +0 -2
  10. package/runtime/lib/compat/initData.js.map +1 -1
  11. package/runtime/lib/gesture/processGesture.js +3 -0
  12. package/runtime/lib/gesture/processGesture.js.map +1 -1
  13. package/runtime/lib/gesture/types.d.ts +2 -0
  14. package/runtime/lib/internal.d.ts +3 -2
  15. package/runtime/lib/internal.js +4 -3
  16. package/runtime/lib/internal.js.map +1 -1
  17. package/runtime/lib/legacy-react-runtime/index.js +4 -2
  18. package/runtime/lib/legacy-react-runtime/index.js.map +1 -1
  19. package/runtime/lib/lifecycle/destroy.js +1 -1
  20. package/runtime/lib/lifecycle/destroy.js.map +1 -1
  21. package/runtime/lib/lifecycle/{patchUpdate.d.ts → patch/commit.d.ts} +1 -3
  22. package/runtime/lib/lifecycle/{patchUpdate.js → patch/commit.js} +12 -56
  23. package/runtime/lib/lifecycle/patch/commit.js.map +1 -0
  24. package/runtime/lib/lifecycle/patch/snapshotPatch.js.map +1 -0
  25. package/runtime/lib/{snapshotPatchApply.js → lifecycle/patch/snapshotPatchApply.js} +1 -4
  26. package/runtime/lib/lifecycle/patch/snapshotPatchApply.js.map +1 -0
  27. package/runtime/lib/lifecycle/patch/updateMainThread.d.ts +3 -0
  28. package/runtime/lib/lifecycle/patch/updateMainThread.js +55 -0
  29. package/runtime/lib/lifecycle/patch/updateMainThread.js.map +1 -0
  30. package/runtime/lib/lifecycle/reload.js +3 -1
  31. package/runtime/lib/lifecycle/reload.js.map +1 -1
  32. package/runtime/lib/lifecycle/render.js.map +1 -1
  33. package/runtime/lib/list.js +1 -1
  34. package/runtime/lib/list.js.map +1 -1
  35. package/runtime/lib/lynx/component.js +3 -3
  36. package/runtime/lib/lynx/component.js.map +1 -1
  37. package/runtime/lib/lynx/dynamic-js.js +0 -1
  38. package/runtime/lib/lynx/dynamic-js.js.map +1 -1
  39. package/runtime/lib/lynx/env.js +1 -2
  40. package/runtime/lib/lynx/env.js.map +1 -1
  41. package/runtime/lib/lynx/lazy-bundle.js.map +1 -1
  42. package/runtime/lib/lynx/performance.js +1 -1
  43. package/runtime/lib/lynx/performance.js.map +1 -1
  44. package/runtime/lib/lynx/tt.d.ts +1 -0
  45. package/runtime/lib/lynx/tt.js +46 -5
  46. package/runtime/lib/lynx/tt.js.map +1 -1
  47. package/runtime/lib/lynx-api.d.ts +3 -2
  48. package/runtime/lib/lynx-api.js +4 -4
  49. package/runtime/lib/lynx-api.js.map +1 -1
  50. package/runtime/lib/lynx.d.ts +0 -1
  51. package/runtime/lib/lynx.js +4 -46
  52. package/runtime/lib/lynx.js.map +1 -1
  53. package/runtime/lib/snapshot/ref.d.ts +2 -2
  54. package/runtime/lib/snapshot/ref.js +6 -7
  55. package/runtime/lib/snapshot/ref.js.map +1 -1
  56. package/runtime/lib/snapshot.js +1 -1
  57. package/runtime/lib/snapshot.js.map +1 -1
  58. package/runtime/lib/worklet/ctx.js +5 -5
  59. package/runtime/lib/worklet/ctx.js.map +1 -1
  60. package/runtime/lib/worklet/destroy.d.ts +2 -0
  61. package/runtime/lib/worklet/destroy.js +13 -0
  62. package/runtime/lib/worklet/destroy.js.map +1 -0
  63. package/runtime/lib/worklet/functionCall.d.ts +1 -0
  64. package/runtime/lib/worklet/functionCall.js +33 -0
  65. package/runtime/lib/worklet/functionCall.js.map +1 -0
  66. package/runtime/lib/worklet/functionality.d.ts +2 -1
  67. package/runtime/lib/worklet/functionality.js +21 -2
  68. package/runtime/lib/worklet/functionality.js.map +1 -1
  69. package/runtime/lib/worklet/hmr.js +1 -1
  70. package/runtime/lib/worklet/hmr.js.map +1 -1
  71. package/runtime/lib/worklet/runOnBackground.d.ts +20 -0
  72. package/runtime/lib/worklet/runOnBackground.js +105 -0
  73. package/runtime/lib/worklet/runOnBackground.js.map +1 -0
  74. package/runtime/lib/worklet/runOnMainThread.d.ts +19 -0
  75. package/runtime/lib/worklet/runOnMainThread.js +45 -0
  76. package/runtime/lib/worklet/runOnMainThread.js.map +1 -0
  77. package/runtime/lib/worklet/transformToWorklet.d.ts +1 -0
  78. package/runtime/lib/worklet/transformToWorklet.js +21 -0
  79. package/runtime/lib/worklet/transformToWorklet.js.map +1 -0
  80. package/runtime/lib/worklet/workletRef.js +3 -4
  81. package/runtime/lib/worklet/workletRef.js.map +1 -1
  82. package/runtime/lib/worklet/workletRefPool.d.ts +1 -2
  83. package/runtime/lib/worklet/workletRefPool.js +14 -11
  84. package/runtime/lib/worklet/workletRefPool.js.map +1 -1
  85. package/runtime/src/backgroundSnapshot.ts +3 -3
  86. package/runtime/src/compat/initData.ts +5 -6
  87. package/runtime/src/gesture/processGesture.ts +4 -0
  88. package/runtime/src/gesture/types.ts +2 -0
  89. package/runtime/src/internal.ts +5 -3
  90. package/runtime/src/legacy-react-runtime/index.ts +4 -2
  91. package/runtime/src/lifecycle/destroy.ts +1 -1
  92. package/runtime/src/lifecycle/{patchUpdate.ts → patch/commit.ts} +18 -71
  93. package/runtime/src/{snapshotPatchApply.ts → lifecycle/patch/snapshotPatchApply.ts} +2 -2
  94. package/runtime/src/lifecycle/patch/updateMainThread.ts +69 -0
  95. package/runtime/src/lifecycle/reload.ts +3 -1
  96. package/runtime/src/lifecycle/render.ts +1 -1
  97. package/runtime/src/list.ts +1 -1
  98. package/runtime/src/lynx/component.ts +3 -3
  99. package/runtime/src/lynx/dynamic-js.ts +2 -3
  100. package/runtime/src/lynx/env.ts +2 -2
  101. package/runtime/src/lynx/lazy-bundle.ts +1 -1
  102. package/runtime/src/lynx/performance.ts +3 -2
  103. package/runtime/src/lynx/tt.ts +56 -7
  104. package/runtime/src/lynx-api.ts +6 -5
  105. package/runtime/src/lynx.ts +5 -55
  106. package/runtime/src/snapshot/ref.ts +6 -9
  107. package/runtime/src/snapshot.ts +1 -1
  108. package/runtime/src/worklet/ctx.ts +5 -5
  109. package/runtime/src/worklet/destroy.ts +16 -0
  110. package/runtime/src/worklet/functionCall.ts +42 -0
  111. package/runtime/src/worklet/functionality.ts +25 -2
  112. package/runtime/src/worklet/hmr.ts +1 -1
  113. package/runtime/src/worklet/runOnBackground.ts +125 -0
  114. package/runtime/src/worklet/runOnMainThread.ts +50 -0
  115. package/runtime/src/worklet/transformToWorklet.ts +26 -0
  116. package/runtime/src/worklet/workletRef.ts +4 -4
  117. package/runtime/src/worklet/workletRefPool.ts +16 -12
  118. package/transform/dist/wasm.cjs +1 -1
  119. package/transform/index.d.ts +5 -1
  120. package/worklet-runtime/dist/dev.js +10 -3
  121. package/worklet-runtime/dist/dev.js.map +2 -2
  122. package/worklet-runtime/dist/main.js +10 -3
  123. package/worklet-runtime/dist/main.js.map +2 -2
  124. package/worklet-runtime/lib/bindings/events.d.ts +12 -1
  125. package/worklet-runtime/lib/bindings/events.js +1 -0
  126. package/worklet-runtime/lib/bindings/events.js.map +1 -1
  127. package/worklet-runtime/lib/bindings/index.d.ts +1 -1
  128. package/worklet-runtime/lib/bindings/index.js.map +1 -1
  129. package/worklet-runtime/lib/bindings/types.d.ts +1 -1
  130. package/worklet-runtime/lib/global.d.ts +1 -1
  131. package/worklet-runtime/lib/jsFunctionLifecycle.d.ts +2 -2
  132. package/worklet-runtime/lib/jsFunctionLifecycle.js +2 -2
  133. package/worklet-runtime/lib/jsFunctionLifecycle.js.map +1 -1
  134. package/worklet-runtime/lib/listeners.js +9 -2
  135. package/worklet-runtime/lib/listeners.js.map +1 -1
  136. package/worklet-runtime/lib/workletRuntime.js +2 -2
  137. package/worklet-runtime/lib/workletRuntime.js.map +1 -1
  138. package/runtime/lib/lifecycle/patchUpdate.js.map +0 -1
  139. package/runtime/lib/snapshotPatch.js.map +0 -1
  140. package/runtime/lib/snapshotPatchApply.js.map +0 -1
  141. package/runtime/lib/worklet/jsImpl.d.ts +0 -11
  142. package/runtime/lib/worklet/jsImpl.js +0 -68
  143. package/runtime/lib/worklet/jsImpl.js.map +0 -1
  144. package/runtime/lib/worklet/runWorklet.d.ts +0 -14
  145. package/runtime/lib/worklet/runWorklet.js +0 -82
  146. package/runtime/lib/worklet/runWorklet.js.map +0 -1
  147. package/runtime/src/worklet/jsImpl.ts +0 -86
  148. package/runtime/src/worklet/runWorklet.ts +0 -88
  149. /package/runtime/lib/{snapshotPatch.d.ts → lifecycle/patch/snapshotPatch.d.ts} +0 -0
  150. /package/runtime/lib/{snapshotPatch.js → lifecycle/patch/snapshotPatch.js} +0 -0
  151. /package/runtime/lib/{snapshotPatchApply.d.ts → lifecycle/patch/snapshotPatchApply.d.ts} +0 -0
  152. /package/runtime/src/{snapshotPatch.ts → lifecycle/patch/snapshotPatch.ts} +0 -0
@@ -3,13 +3,13 @@
3
3
  // LICENSE file in the root directory of this source tree.
4
4
  import type { Worklet, WorkletRef } from '@lynx-js/react/worklet-runtime/bindings';
5
5
 
6
- import { nextCommitTaskId } from '../lifecycle/patchUpdate.js';
6
+ import { nextCommitTaskId } from '../lifecycle/patch/commit.js';
7
7
  import { SnapshotInstance, backgroundSnapshotInstanceManager } from '../snapshot.js';
8
8
  import { workletUnRef } from './workletRef.js';
9
9
 
10
10
  let globalRefPatch: Record<string, number | null> = {};
11
- let globalRefsToRemove: Map</* commitId */ number, Map</* sign */ string, /* ref */ any>> = /* @__PURE__ */ new Map();
12
- let globalRefsToSet: Map</* commitId */ number, Record<string, number>> = /* @__PURE__ */ new Map();
11
+ const globalRefsToRemove: Map</* commitId */ number, Map</* sign */ string, /* ref */ any>> = /* @__PURE__ */ new Map();
12
+ const globalRefsToSet: Map</* commitId */ number, Record<string, number>> = /* @__PURE__ */ new Map();
13
13
  let nextRefId = 1;
14
14
 
15
15
  function unref(snapshot: SnapshotInstance, recursive: boolean): void {
@@ -35,7 +35,7 @@ function unref(snapshot: SnapshotInstance, recursive: boolean): void {
35
35
  function applyRef(ref: any, value: any) {
36
36
  // TODO: ref: exceptions thrown in user functions should be able to be caught by an Error Boundary
37
37
  if (typeof ref == 'function') {
38
- let hasRefUnmount = typeof ref._unmount == 'function';
38
+ const hasRefUnmount = typeof ref._unmount == 'function';
39
39
  if (hasRefUnmount) {
40
40
  // @ts-ignore TS doesn't like moving narrowing checks into variables
41
41
  ref._unmount();
@@ -54,7 +54,7 @@ function updateBackgroundRefs(commitId: number): void {
54
54
  const oldRefMap = globalRefsToRemove.get(commitId);
55
55
  if (oldRefMap) {
56
56
  globalRefsToRemove.delete(commitId);
57
- for (let ref of oldRefMap.values()) {
57
+ for (const ref of oldRefMap.values()) {
58
58
  applyRef(ref, null);
59
59
  }
60
60
  }
@@ -65,10 +65,7 @@ function updateBackgroundRefs(commitId: number): void {
65
65
  const ref = backgroundSnapshotInstanceManager.getValueBySign(sign);
66
66
  if (ref) {
67
67
  // TODO: ref: support __REF_FIRE_IMMEDIATELY__
68
- const v = newRefMap[sign]
69
- && lynx.createSelectorQuery().selectUniqueID(
70
- newRefMap[sign],
71
- );
68
+ const v = newRefMap[sign] && lynx.createSelectorQuery().selectUniqueID(newRefMap[sign]);
72
69
  applyRef(ref, v);
73
70
  }
74
71
  }
@@ -6,7 +6,7 @@ import type { Worklet, WorkletRefImpl } from '@lynx-js/react/worklet-runtime/bin
6
6
  import type { BackgroundSnapshotInstance } from './backgroundSnapshot.js';
7
7
  import { ListUpdateInfoRecording, __pendingListUpdates, snapshotDestroyList } from './list.js';
8
8
  import { unref } from './snapshot/ref.js';
9
- import { SnapshotOperation, __globalSnapshotPatch } from './snapshotPatch.js';
9
+ import { SnapshotOperation, __globalSnapshotPatch } from './lifecycle/patch/snapshotPatch.js';
10
10
  import { isDirectOrDeepEqual } from './utils.js';
11
11
 
12
12
  export const enum DynamicPartType {
@@ -3,20 +3,20 @@
3
3
  // LICENSE file in the root directory of this source tree.
4
4
  import type { Worklet } from '@lynx-js/react/worklet-runtime/bindings';
5
5
 
6
- import { lynxWorkletJsImpl } from './jsImpl.js';
6
+ import { isMtsEnabled, isRunOnBackgroundEnabled } from './functionality.js';
7
+ import { registerWorkletCtx } from './runOnBackground.js';
7
8
 
8
9
  /**
9
10
  * @internal
10
11
  */
11
12
  export function onPostWorkletCtx(afterValue: Worklet | null): Worklet | null {
12
- const impl = lynxWorkletJsImpl();
13
- if (!impl && afterValue) {
13
+ if (!isMtsEnabled() && afterValue) {
14
14
  lynx.reportError(new Error('Main thread script requires Lynx sdk version 2.14'));
15
15
  return null;
16
16
  }
17
- if (!afterValue) {
17
+ if (!afterValue || !isRunOnBackgroundEnabled()) {
18
18
  return afterValue;
19
19
  }
20
- impl?._workletExecIdMap?.add(afterValue);
20
+ registerWorkletCtx(afterValue);
21
21
  return afterValue;
22
22
  }
@@ -0,0 +1,16 @@
1
+ // Copyright 2024 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+
5
+ import { takeWorkletRefInitValuePatch } from './workletRefPool.js';
6
+
7
+ export const destroyTasks: (() => void)[] = [];
8
+
9
+ export function destroyWorklet(): void {
10
+ takeWorkletRefInitValuePatch();
11
+
12
+ for (const task of destroyTasks) {
13
+ task();
14
+ }
15
+ destroyTasks.length = 0;
16
+ }
@@ -0,0 +1,42 @@
1
+ // Copyright 2025 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+
5
+ import { WorkletEvents } from '@lynx-js/react/worklet-runtime/bindings';
6
+ import type { RunWorkletCtxRetData } from '@lynx-js/react/worklet-runtime/bindings';
7
+
8
+ import { destroyTasks } from './destroy.js';
9
+ import { IndexMap } from './indexMap.js';
10
+
11
+ let resolveMap: IndexMap<(value: any) => void> | undefined;
12
+
13
+ function initReturnValueListener(): void {
14
+ const context: RuntimeProxy = __JS__ ? lynx.getCoreContext!() : lynx.getJSContext!();
15
+
16
+ resolveMap = new IndexMap();
17
+ context.addEventListener(WorkletEvents.FunctionCallRet, onFunctionCallRet);
18
+
19
+ destroyTasks.push(() => {
20
+ context.removeEventListener(WorkletEvents.FunctionCallRet, onFunctionCallRet);
21
+ resolveMap = undefined;
22
+ });
23
+ }
24
+
25
+ /**
26
+ * @internal
27
+ */
28
+ function onFunctionCall(resolve: (value: any) => void): number {
29
+ if (!resolveMap) {
30
+ initReturnValueListener();
31
+ }
32
+ return resolveMap!.add(resolve);
33
+ }
34
+
35
+ function onFunctionCallRet(event: RuntimeProxy.Event): void {
36
+ const data = JSON.parse(event.data as string) as RunWorkletCtxRetData;
37
+ const resolve = resolveMap!.get(data.resolveId)!;
38
+ resolveMap!.remove(data.resolveId);
39
+ resolve(data.returnValue);
40
+ }
41
+
42
+ export { onFunctionCall };
@@ -4,9 +4,32 @@
4
4
 
5
5
  import { isSdkVersionGt } from '../utils.js';
6
6
 
7
+ let mtsEnabled: boolean | undefined;
8
+ let runOnBackgroundEnabled: boolean | undefined;
9
+
7
10
  /**
8
11
  * @internal
9
12
  */
10
- export function enableRunOnBackground(): boolean {
11
- return isSdkVersionGt(2, 15);
13
+ function isMtsEnabled(): boolean {
14
+ if (mtsEnabled === undefined) {
15
+ mtsEnabled = isSdkVersionGt(2, 13);
16
+ }
17
+ return mtsEnabled;
12
18
  }
19
+
20
+ /**
21
+ * @internal
22
+ */
23
+ function isRunOnBackgroundEnabled(): boolean {
24
+ if (runOnBackgroundEnabled === undefined) {
25
+ runOnBackgroundEnabled = isSdkVersionGt(2, 15);
26
+ }
27
+ return runOnBackgroundEnabled;
28
+ }
29
+
30
+ function clearConfigCacheForTesting(): void {
31
+ mtsEnabled = undefined;
32
+ runOnBackgroundEnabled = undefined;
33
+ }
34
+
35
+ export { isMtsEnabled, isRunOnBackgroundEnabled, clearConfigCacheForTesting };
@@ -1,7 +1,7 @@
1
1
  // Copyright 2024 The Lynx Authors. All rights reserved.
2
2
  // Licensed under the Apache License Version 2.0 that can be found in the
3
3
  // LICENSE file in the root directory of this source tree.
4
- import { SnapshotOperation, __globalSnapshotPatch } from '../snapshotPatch.js';
4
+ import { SnapshotOperation, __globalSnapshotPatch } from '../lifecycle/patch/snapshotPatch.js';
5
5
 
6
6
  const workletHashSet: Set<string> = /* @__PURE__ */ new Set();
7
7
 
@@ -0,0 +1,125 @@
1
+ // Copyright 2024 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+
5
+ import type { JsFnHandle, RunWorkletCtxRetData, Worklet } from '@lynx-js/react/worklet-runtime/bindings';
6
+ import { WorkletEvents } from '@lynx-js/react/worklet-runtime/bindings';
7
+
8
+ import { destroyTasks } from './destroy.js';
9
+ import { WorkletExecIdMap } from './execMap.js';
10
+ import { isRunOnBackgroundEnabled } from './functionality.js';
11
+ import { onFunctionCall } from './functionCall.js';
12
+
13
+ /**
14
+ * @internal
15
+ */
16
+ interface RunOnBackgroundData {
17
+ obj: JsFnHandle;
18
+ params: unknown[];
19
+ resolveId: number;
20
+ }
21
+
22
+ let execIdMap: WorkletExecIdMap | undefined;
23
+
24
+ function init() {
25
+ 'background only';
26
+ if (execIdMap) {
27
+ return;
28
+ }
29
+
30
+ execIdMap = new WorkletExecIdMap();
31
+ lynx.getCoreContext!().addEventListener(WorkletEvents.runOnBackground, runJSFunction);
32
+ lynx.getCoreContext!().addEventListener(WorkletEvents.releaseBackgroundWorkletCtx, releaseBackgroundWorkletCtx);
33
+
34
+ destroyTasks.push(() => {
35
+ lynx.getCoreContext!().removeEventListener(WorkletEvents.runOnBackground, runJSFunction);
36
+ lynx.getCoreContext!().removeEventListener(WorkletEvents.releaseBackgroundWorkletCtx, releaseBackgroundWorkletCtx);
37
+ execIdMap = undefined;
38
+ });
39
+ }
40
+
41
+ /**
42
+ * @internal
43
+ */
44
+ function runJSFunction(event: RuntimeProxy.Event): void {
45
+ 'background only';
46
+ const data = JSON.parse(event.data as string) as RunOnBackgroundData;
47
+ const obj = execIdMap!.findJsFnHandle(data.obj._execId!, data.obj._jsFnId);
48
+ const f = obj?._fn;
49
+ if (!f) {
50
+ throw new Error('runOnBackground: JS function not found: ' + JSON.stringify(data.obj));
51
+ }
52
+ const returnValue = f(...data.params);
53
+ lynx.getCoreContext!().dispatchEvent({
54
+ type: WorkletEvents.FunctionCallRet,
55
+ data: JSON.stringify({
56
+ resolveId: data.resolveId,
57
+ returnValue,
58
+ } as RunWorkletCtxRetData),
59
+ });
60
+ }
61
+
62
+ function releaseBackgroundWorkletCtx(event: RuntimeProxy.Event): void {
63
+ 'background only';
64
+ for (const id of event.data) {
65
+ execIdMap!.remove(id as number);
66
+ }
67
+ }
68
+
69
+ /**
70
+ * @internal
71
+ */
72
+ function registerWorkletCtx(ctx: Worklet): void {
73
+ 'background only';
74
+ init();
75
+ execIdMap!.add(ctx);
76
+ }
77
+
78
+ /**
79
+ * `runOnBackground` allows triggering js functions on the background thread asynchronously.
80
+ * @param f - The js function to be called.
81
+ * @returns A function. Calling which with the arguments to be passed to the js function to trigger it on the background thread. This function returns a promise that resolves to the return value of the js function.
82
+ * @example
83
+ * ```ts
84
+ * import { runOnBackground } from '@lynx-js/react';
85
+ *
86
+ * async function someMainthreadFunction() {
87
+ * 'main thread';
88
+ * const fn = runOnBackground(() => {
89
+ * return 'hello';
90
+ * });
91
+ * const result = await fn();
92
+ }
93
+ * ```
94
+ * @public
95
+ */
96
+ function runOnBackground<R, Fn extends (...args: any[]) => R>(f: Fn): (...args: Parameters<Fn>) => Promise<R> {
97
+ if (!isRunOnBackgroundEnabled()) {
98
+ throw new Error('runOnBackground requires Lynx sdk version 2.16.');
99
+ }
100
+ if (__JS__) {
101
+ throw new Error('runOnBackground can only be used on the main thread.');
102
+ }
103
+ const obj = f as any as JsFnHandle;
104
+ if (obj._error) {
105
+ throw new Error(obj._error);
106
+ }
107
+ return async (...params: any[]): Promise<R> => {
108
+ return new Promise((resolve) => {
109
+ const resolveId = onFunctionCall(resolve);
110
+ lynx.getJSContext!().dispatchEvent({
111
+ type: WorkletEvents.runOnBackground,
112
+ data: JSON.stringify({
113
+ obj: {
114
+ _jsFnId: obj._jsFnId,
115
+ _execId: obj._execId!,
116
+ },
117
+ params,
118
+ resolveId,
119
+ } as RunOnBackgroundData),
120
+ });
121
+ });
122
+ };
123
+ }
124
+
125
+ export { registerWorkletCtx, runJSFunction, runOnBackground };
@@ -0,0 +1,50 @@
1
+ // Copyright 2024 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+ import type { RunWorkletCtxData, Worklet } from '@lynx-js/react/worklet-runtime/bindings';
5
+ import { WorkletEvents } from '@lynx-js/react/worklet-runtime/bindings';
6
+
7
+ import { onPostWorkletCtx } from './ctx.js';
8
+ import { isMtsEnabled } from './functionality.js';
9
+ import { onFunctionCall } from './functionCall.js';
10
+
11
+ /**
12
+ * `runOnMainThread` allows triggering main thread functions on the main thread asynchronously.
13
+ * @param fn - The main thread functions to be called.
14
+ * @returns A function. Calling which with the arguments to be passed to the main thread function to trigger it on the main thread. This function returns a promise that resolves to the return value of the main thread function.
15
+ * @example
16
+ * ```ts
17
+ * import { runOnMainThread } from '@lynx-js/react';
18
+ *
19
+ * async function someFunction() {
20
+ * const fn = runOnMainThread(() => {
21
+ * 'main thread';
22
+ * return 'hello';
23
+ * });
24
+ * const result = await fn();
25
+ * }
26
+ * ```
27
+ * @public
28
+ */
29
+ export function runOnMainThread<R, Fn extends (...args: any[]) => R>(fn: Fn): (...args: Parameters<Fn>) => Promise<R> {
30
+ if (__LEPUS__) {
31
+ throw new Error('runOnMainThread can only be used on the background thread.');
32
+ }
33
+ if (!isMtsEnabled()) {
34
+ throw new Error('runOnMainThread requires Lynx sdk version 2.14.');
35
+ }
36
+ return async (...params: any[]): Promise<R> => {
37
+ return new Promise((resolve) => {
38
+ onPostWorkletCtx(fn as any as Worklet);
39
+ const resolveId = onFunctionCall(resolve);
40
+ lynx.getCoreContext!().dispatchEvent({
41
+ type: WorkletEvents.runWorkletCtx,
42
+ data: JSON.stringify({
43
+ worklet: fn as any as Worklet,
44
+ params,
45
+ resolveId,
46
+ } as RunWorkletCtxData),
47
+ });
48
+ });
49
+ };
50
+ }
@@ -0,0 +1,26 @@
1
+ // Copyright 2024 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+ import type { JsFnHandle } from '@lynx-js/react/worklet-runtime/bindings';
5
+
6
+ let lastId = 0;
7
+
8
+ /**
9
+ * transform args of `runOnBackground()`.
10
+ *
11
+ * @internal
12
+ */
13
+ export function transformToWorklet(obj: (...args: any[]) => any): JsFnHandle {
14
+ const id = ++lastId;
15
+ if (typeof obj !== 'function') {
16
+ // We save the error message in the object, so that we can throw it later when the function is called on the main thread.
17
+ return {
18
+ _jsFnId: id,
19
+ _error: `Argument of runOnBackground should be a function, but got [${typeof obj}] instead`,
20
+ };
21
+ }
22
+ return {
23
+ _jsFnId: id,
24
+ _fn: obj,
25
+ };
26
+ }
@@ -6,10 +6,11 @@ import type { RefObject } from 'react';
6
6
  import type { WorkletRefImpl } from '@lynx-js/react/worklet-runtime/bindings';
7
7
  import { WorkletEvents } from '@lynx-js/react/worklet-runtime/bindings';
8
8
 
9
- import { lynxWorkletJsImpl } from './jsImpl.js';
10
9
  import { addWorkletRefInitValue } from './workletRefPool.js';
11
10
  import { useMemo } from '../hooks/react.js';
12
11
 
12
+ let lastId = 0;
13
+
13
14
  abstract class WorkletRef<T> {
14
15
  /**
15
16
  * @internal
@@ -33,8 +34,7 @@ abstract class WorkletRef<T> {
33
34
  */
34
35
  protected constructor(initValue: T, type: string) {
35
36
  if (__JS__) {
36
- const impl = lynxWorkletJsImpl();
37
- this._id = impl ? ++impl._workletRefLastId : 0;
37
+ this._id = ++lastId;
38
38
  this._initValue = initValue;
39
39
  this._type = type;
40
40
  addWorkletRefInitValue(this._id, initValue);
@@ -89,7 +89,7 @@ export class MainThreadRef<T> extends WorkletRef<T> {
89
89
  super(initValue, 'main-thread');
90
90
  if (__JS__) {
91
91
  const id = this._id;
92
- this._lifecycleObserver = lynx.getNativeApp().createJSObjectDestructionObserver(() => {
92
+ this._lifecycleObserver = lynx.getNativeApp().createJSObjectDestructionObserver?.(() => {
93
93
  lynx.getCoreContext?.().dispatchEvent({
94
94
  type: WorkletEvents.releaseWorkletRef,
95
95
  data: {
@@ -1,25 +1,29 @@
1
1
  // Copyright 2024 The Lynx Authors. All rights reserved.
2
2
  // Licensed under the Apache License Version 2.0 that can be found in the
3
3
  // LICENSE file in the root directory of this source tree.
4
- import { lynxWorkletJsImpl } from './jsImpl.js';
5
4
 
5
+ import { isMtsEnabled } from './functionality.js';
6
+
7
+ let initValuePatch: [number, unknown][] = [];
8
+ const initValueIdSet = /*#__PURE__*/ new Set<number>();
9
+
10
+ /**
11
+ * @internal
12
+ */
6
13
  export function addWorkletRefInitValue(id: number, value: unknown): void {
7
- const impl = lynxWorkletJsImpl();
8
- if (!impl) {
14
+ if (!isMtsEnabled()) {
9
15
  return;
10
16
  }
11
17
 
12
- impl._workletRefInitValueSet.add(id);
13
- impl._workletRefInitValuePatch.push([id, value]);
18
+ initValueIdSet.add(id);
19
+ initValuePatch.push([id, value]);
14
20
  }
15
21
 
22
+ /**
23
+ * @internal
24
+ */
16
25
  export function takeWorkletRefInitValuePatch(): [number, unknown][] {
17
- const impl = lynxWorkletJsImpl(false);
18
- if (!impl) {
19
- return [];
20
- }
21
-
22
- const res = impl._workletRefInitValuePatch;
23
- impl._workletRefInitValuePatch = [];
26
+ const res = initValuePatch;
27
+ initValuePatch = [];
24
28
  return res;
25
29
  }