@lynx-js/react 0.111.1 → 0.111.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 (134) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/components/lib/DeferredListItem.d.ts +3 -1
  3. package/components/lib/DeferredListItem.jsx +4 -2
  4. package/components/lib/DeferredListItem.jsx.map +1 -1
  5. package/components/src/DeferredListItem.tsx +5 -3
  6. package/package.json +6 -1
  7. package/refresh/.turbo/turbo-build.log +1 -1
  8. package/runtime/debug/index.cjs +8 -0
  9. package/runtime/debug/index.d.ts +4 -0
  10. package/runtime/debug/index.js +5 -0
  11. package/runtime/lib/alog/index.d.ts +1 -0
  12. package/runtime/lib/alog/index.js +8 -0
  13. package/runtime/lib/alog/index.js.map +1 -0
  14. package/runtime/lib/alog/render.d.ts +1 -0
  15. package/runtime/lib/alog/render.js +19 -0
  16. package/runtime/lib/alog/render.js.map +1 -0
  17. package/runtime/lib/backgroundSnapshot.d.ts +1 -0
  18. package/runtime/lib/backgroundSnapshot.js +31 -17
  19. package/runtime/lib/backgroundSnapshot.js.map +1 -1
  20. package/runtime/lib/debug/component-stack.d.ts +33 -0
  21. package/runtime/lib/debug/component-stack.js +145 -0
  22. package/runtime/lib/debug/component-stack.js.map +1 -0
  23. package/runtime/lib/debug/formatPatch.d.ts +2 -0
  24. package/runtime/lib/debug/formatPatch.js +27 -0
  25. package/runtime/lib/debug/formatPatch.js.map +1 -0
  26. package/runtime/lib/debug/printSnapshot.d.ts +1 -1
  27. package/runtime/lib/debug/printSnapshot.js +0 -4
  28. package/runtime/lib/debug/printSnapshot.js.map +1 -1
  29. package/runtime/lib/debug/profile.js +1 -3
  30. package/runtime/lib/debug/profile.js.map +1 -1
  31. package/runtime/lib/hydrate.js +11 -7
  32. package/runtime/lib/hydrate.js.map +1 -1
  33. package/runtime/lib/lifecycle/patch/commit.js +1 -1
  34. package/runtime/lib/lifecycle/patch/commit.js.map +1 -1
  35. package/runtime/lib/lifecycle/patch/snapshotPatch.d.ts +4 -0
  36. package/runtime/lib/lifecycle/patch/snapshotPatch.js +28 -0
  37. package/runtime/lib/lifecycle/patch/snapshotPatch.js.map +1 -1
  38. package/runtime/lib/lynx.js +9 -0
  39. package/runtime/lib/lynx.js.map +1 -1
  40. package/runtime/lib/pendingListUpdates.d.ts +2 -1
  41. package/runtime/lib/pendingListUpdates.js +16 -4
  42. package/runtime/lib/pendingListUpdates.js.map +1 -1
  43. package/runtime/lib/renderToOpcodes/constants.d.ts +2 -0
  44. package/runtime/lib/renderToOpcodes/constants.js +2 -0
  45. package/runtime/lib/renderToOpcodes/constants.js.map +1 -1
  46. package/runtime/lib/root.d.ts +6 -0
  47. package/runtime/lib/root.js +4 -0
  48. package/runtime/lib/root.js.map +1 -1
  49. package/runtime/lib/snapshot/platformInfo.js +5 -3
  50. package/runtime/lib/snapshot/platformInfo.js.map +1 -1
  51. package/runtime/lib/snapshot/ref.d.ts +2 -2
  52. package/runtime/lib/snapshot/spread.js +3 -1
  53. package/runtime/lib/snapshot/spread.js.map +1 -1
  54. package/runtime/lib/snapshot.js +13 -7
  55. package/runtime/lib/snapshot.js.map +1 -1
  56. package/runtime/lib/utils.d.ts +2 -0
  57. package/runtime/lib/utils.js +23 -2
  58. package/runtime/lib/utils.js.map +1 -1
  59. package/testing-library/dist/env/vitest.js +12 -4
  60. package/types/react.d.ts +13 -1
  61. package/runtime/src/backgroundSnapshot.ts +0 -501
  62. package/runtime/src/compat/componentIs.ts +0 -30
  63. package/runtime/src/compat/initData.ts +0 -150
  64. package/runtime/src/compat/lynxComponent.ts +0 -79
  65. package/runtime/src/debug/debug.ts +0 -9
  66. package/runtime/src/debug/printSnapshot.ts +0 -28
  67. package/runtime/src/debug/profile.ts +0 -55
  68. package/runtime/src/document.ts +0 -84
  69. package/runtime/src/gesture/processGesture.ts +0 -89
  70. package/runtime/src/gesture/processGestureBagkround.ts +0 -19
  71. package/runtime/src/gesture/types.ts +0 -44
  72. package/runtime/src/hooks/react.ts +0 -62
  73. package/runtime/src/hooks/useLynxGlobalEventListener.ts +0 -59
  74. package/runtime/src/hydrate.ts +0 -368
  75. package/runtime/src/index.ts +0 -94
  76. package/runtime/src/internal.ts +0 -63
  77. package/runtime/src/legacy-react-runtime/index.ts +0 -42
  78. package/runtime/src/lifecycle/destroy.ts +0 -34
  79. package/runtime/src/lifecycle/event/delayEvents.ts +0 -11
  80. package/runtime/src/lifecycle/event/delayLifecycleEvents.ts +0 -15
  81. package/runtime/src/lifecycle/event/jsReady.ts +0 -34
  82. package/runtime/src/lifecycle/pass.ts +0 -14
  83. package/runtime/src/lifecycle/patch/commit.ts +0 -214
  84. package/runtime/src/lifecycle/patch/error.ts +0 -61
  85. package/runtime/src/lifecycle/patch/isMainThreadHydrationFinished.ts +0 -13
  86. package/runtime/src/lifecycle/patch/snapshotPatch.ts +0 -65
  87. package/runtime/src/lifecycle/patch/snapshotPatchApply.ts +0 -145
  88. package/runtime/src/lifecycle/patch/updateMainThread.ts +0 -64
  89. package/runtime/src/lifecycle/ref/delay.ts +0 -99
  90. package/runtime/src/lifecycle/reload.ts +0 -97
  91. package/runtime/src/lifecycle/render.ts +0 -54
  92. package/runtime/src/lifecycleConstant.ts +0 -21
  93. package/runtime/src/list.ts +0 -307
  94. package/runtime/src/listUpdateInfo.ts +0 -221
  95. package/runtime/src/lynx/calledByNative.ts +0 -160
  96. package/runtime/src/lynx/component.ts +0 -113
  97. package/runtime/src/lynx/dynamic-js.ts +0 -36
  98. package/runtime/src/lynx/env.ts +0 -109
  99. package/runtime/src/lynx/injectLepusMethods.ts +0 -53
  100. package/runtime/src/lynx/lazy-bundle.ts +0 -175
  101. package/runtime/src/lynx/performance.ts +0 -148
  102. package/runtime/src/lynx/runWithForce.ts +0 -67
  103. package/runtime/src/lynx/tt.ts +0 -215
  104. package/runtime/src/lynx-api.ts +0 -455
  105. package/runtime/src/lynx.ts +0 -58
  106. package/runtime/src/opcodes.ts +0 -155
  107. package/runtime/src/pendingListUpdates.ts +0 -18
  108. package/runtime/src/renderToOpcodes/constants.ts +0 -24
  109. package/runtime/src/renderToOpcodes/index.ts +0 -306
  110. package/runtime/src/root.ts +0 -23
  111. package/runtime/src/snapshot/dynamicPartType.ts +0 -16
  112. package/runtime/src/snapshot/event.ts +0 -33
  113. package/runtime/src/snapshot/gesture.ts +0 -30
  114. package/runtime/src/snapshot/list.ts +0 -36
  115. package/runtime/src/snapshot/platformInfo.ts +0 -62
  116. package/runtime/src/snapshot/ref.ts +0 -139
  117. package/runtime/src/snapshot/spread.ts +0 -330
  118. package/runtime/src/snapshot/workletEvent.ts +0 -35
  119. package/runtime/src/snapshot/workletRef.ts +0 -88
  120. package/runtime/src/snapshot.ts +0 -634
  121. package/runtime/src/snapshotInstanceHydrationMap.ts +0 -17
  122. package/runtime/src/utils.ts +0 -44
  123. package/runtime/src/worklet/ctx.ts +0 -22
  124. package/runtime/src/worklet/destroy.ts +0 -16
  125. package/runtime/src/worklet/execMap.ts +0 -51
  126. package/runtime/src/worklet/functionCall.ts +0 -42
  127. package/runtime/src/worklet/functionality.ts +0 -29
  128. package/runtime/src/worklet/hmr.ts +0 -34
  129. package/runtime/src/worklet/indexMap.ts +0 -23
  130. package/runtime/src/worklet/runOnBackground.ts +0 -147
  131. package/runtime/src/worklet/runOnMainThread.ts +0 -50
  132. package/runtime/src/worklet/transformToWorklet.ts +0 -26
  133. package/runtime/src/worklet/workletRef.ts +0 -231
  134. package/runtime/src/worklet/workletRefPool.ts +0 -29
@@ -1,22 +0,0 @@
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 { Worklet } from '@lynx-js/react/worklet-runtime/bindings';
5
-
6
- import { isMtsEnabled, isRunOnBackgroundEnabled } from './functionality.js';
7
- import { registerWorkletCtx } from './runOnBackground.js';
8
-
9
- /**
10
- * @internal
11
- */
12
- export function onPostWorkletCtx(afterValue: Worklet | null): Worklet | null {
13
- if (!isMtsEnabled() && afterValue) {
14
- lynx.reportError(new Error('Main thread script requires Lynx sdk version 2.14'));
15
- return null;
16
- }
17
- if (!afterValue || !isRunOnBackgroundEnabled()) {
18
- return afterValue;
19
- }
20
- registerWorkletCtx(afterValue);
21
- return afterValue;
22
- }
@@ -1,16 +0,0 @@
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
- }
@@ -1,51 +0,0 @@
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, Worklet } from '@lynx-js/react/worklet-runtime/bindings';
5
-
6
- import { IndexMap } from './indexMap.js';
7
-
8
- /**
9
- * `WorkletExecIdMap` ensures the worklet object is not released in js context when the main thread is still holding the
10
- * worklet object (or any of its jsFnHandles). The worklet object holds the js functions which might be called by `runOnBackground()`.
11
- * If the worklet object is incorrectly released earlier, the `runOnBackground()` would result in failure.
12
- *
13
- * Every time a worklet object is sent to the main thread, an `execId` is distributed and will be sent to element
14
- * context with the worklet object. This relationship is recorded in this class. When all the references to the
15
- * worklet object are released in the main thread, a message will be sent back to remove the record here.
16
- *
17
- * @internal
18
- */
19
- export class WorkletExecIdMap extends IndexMap<Worklet> {
20
- public override add(worklet: Worklet): number {
21
- const execId = super.add(worklet);
22
- worklet._execId = execId;
23
- return execId;
24
- }
25
-
26
- public findJsFnHandle(execId: number, fnId: number): JsFnHandle | undefined {
27
- const worklet = this.get(execId);
28
- if (!worklet) {
29
- return undefined;
30
- }
31
-
32
- const f = (value: unknown): JsFnHandle | undefined => {
33
- if (value === null || typeof value !== 'object') {
34
- return undefined;
35
- }
36
- const obj = value as Record<string, unknown>;
37
- if ('_jsFnId' in obj && obj['_jsFnId'] === fnId) {
38
- return obj as JsFnHandle;
39
- }
40
- for (const i in obj) {
41
- const result = f(obj[i]);
42
- if (result) {
43
- return result;
44
- }
45
- }
46
- return undefined;
47
- };
48
-
49
- return f(worklet);
50
- }
51
- }
@@ -1,42 +0,0 @@
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 };
@@ -1,29 +0,0 @@
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 { isSdkVersionGt } from '../utils.js';
6
-
7
- let mtsEnabled: boolean | undefined;
8
- let runOnBackgroundEnabled: boolean | undefined;
9
-
10
- /**
11
- * @internal
12
- */
13
- function isMtsEnabled(): boolean {
14
- return mtsEnabled ??= isSdkVersionGt(2, 13);
15
- }
16
-
17
- /**
18
- * @internal
19
- */
20
- function isRunOnBackgroundEnabled(): boolean {
21
- return runOnBackgroundEnabled ??= isSdkVersionGt(2, 15);
22
- }
23
-
24
- function clearConfigCacheForTesting(): void {
25
- mtsEnabled = undefined;
26
- runOnBackgroundEnabled = undefined;
27
- }
28
-
29
- export { isMtsEnabled, isRunOnBackgroundEnabled, clearConfigCacheForTesting };
@@ -1,34 +0,0 @@
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 { __globalSnapshotPatch } from '../lifecycle/patch/snapshotPatch.js';
5
-
6
- // const workletHashSet: Set<string> = /* @__PURE__ */ new Set();
7
-
8
- /* v8 ignore start */
9
- /**
10
- * @internal
11
- */
12
- // disable hmr until bugs are fixed
13
- // TODO: re-enable hmr or change a way to impl it; also need to fix the test case DEV_ONLY_RegisterWorklet
14
- function registerWorkletOnBackground(
15
- _type: string,
16
- _hash: string,
17
- _fn: (...args: unknown[]) => unknown,
18
- ) {
19
- // if (workletHashSet.has(hash)) {
20
- // return;
21
- // }
22
- // workletHashSet.add(hash);
23
- // if (__globalSnapshotPatch) {
24
- // __globalSnapshotPatch.push(
25
- // SnapshotOperation.DEV_ONLY_RegisterWorklet,
26
- // hash,
27
- // // We use `Function.prototype.toString` to serialize the function for Lepus.
28
- // fn.toString(),
29
- // );
30
- // }
31
- }
32
- /* v8 ignore stop */
33
-
34
- export { registerWorkletOnBackground };
@@ -1,23 +0,0 @@
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
- class IndexMap<T> {
5
- protected lastIndex = 0;
6
- protected indexMap: Map<number, T> = new Map<number, T>();
7
-
8
- public add(value: T): number {
9
- const index = ++this.lastIndex;
10
- this.indexMap.set(index, value);
11
- return index;
12
- }
13
-
14
- public get(index: number): T | undefined {
15
- return this.indexMap.get(index);
16
- }
17
-
18
- public remove(index: number): void {
19
- this.indexMap.delete(index);
20
- }
21
- }
22
-
23
- export { IndexMap };
@@ -1,147 +0,0 @@
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 {
6
- ClosureValueType,
7
- JsFnHandle,
8
- RunWorkletCtxRetData,
9
- Worklet,
10
- } from '@lynx-js/react/worklet-runtime/bindings';
11
- import { WorkletEvents, delayRunOnBackground } from '@lynx-js/react/worklet-runtime/bindings';
12
-
13
- import { destroyTasks } from './destroy.js';
14
- import { WorkletExecIdMap } from './execMap.js';
15
- import { isRunOnBackgroundEnabled } from './functionality.js';
16
- import { onFunctionCall } from './functionCall.js';
17
-
18
- /**
19
- * @internal
20
- */
21
- interface RunOnBackgroundData {
22
- obj: JsFnHandle;
23
- params: unknown[];
24
- resolveId: number;
25
- }
26
-
27
- let execIdMap: WorkletExecIdMap | undefined;
28
-
29
- function init() {
30
- 'background only';
31
- if (execIdMap) {
32
- return;
33
- }
34
-
35
- execIdMap = new WorkletExecIdMap();
36
- lynx.getCoreContext!().addEventListener(WorkletEvents.runOnBackground, runJSFunction);
37
- lynx.getCoreContext!().addEventListener(WorkletEvents.releaseBackgroundWorkletCtx, releaseBackgroundWorkletCtx);
38
-
39
- destroyTasks.push(() => {
40
- lynx.getCoreContext!().removeEventListener(WorkletEvents.runOnBackground, runJSFunction);
41
- lynx.getCoreContext!().removeEventListener(WorkletEvents.releaseBackgroundWorkletCtx, releaseBackgroundWorkletCtx);
42
- execIdMap = undefined;
43
- });
44
- }
45
-
46
- /**
47
- * @internal
48
- */
49
- function runJSFunction(event: RuntimeProxy.Event): void {
50
- 'background only';
51
- const data = JSON.parse(event.data as string) as RunOnBackgroundData;
52
- const obj = execIdMap!.findJsFnHandle(data.obj._execId!, data.obj._jsFnId!);
53
- const f = obj?._fn;
54
- if (!f) {
55
- throw new Error('runOnBackground: JS function not found: ' + JSON.stringify(data.obj));
56
- }
57
- const returnValue = f(...data.params);
58
- lynx.getCoreContext!().dispatchEvent({
59
- type: WorkletEvents.FunctionCallRet,
60
- data: JSON.stringify({
61
- resolveId: data.resolveId,
62
- returnValue,
63
- } as RunWorkletCtxRetData),
64
- });
65
- }
66
-
67
- function releaseBackgroundWorkletCtx(event: RuntimeProxy.Event): void {
68
- 'background only';
69
- for (const id of event.data) {
70
- execIdMap!.remove(id as number);
71
- }
72
- }
73
-
74
- /**
75
- * @internal
76
- */
77
- function registerWorkletCtx(ctx: Worklet): void {
78
- 'background only';
79
- init();
80
- execIdMap!.add(ctx);
81
- }
82
-
83
- /**
84
- * `runOnBackground` allows triggering js functions on the background thread asynchronously.
85
- * @param f - The js function to be called.
86
- * @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.
87
- * @example
88
- * ```ts
89
- * import { runOnBackground } from '@lynx-js/react';
90
- *
91
- * async function someMainthreadFunction() {
92
- * 'main thread';
93
- * const fn = runOnBackground(() => {
94
- * return 'hello';
95
- * });
96
- * const result = await fn();
97
- }
98
- * ```
99
- * @public
100
- */
101
- function runOnBackground<R, Fn extends (...args: any[]) => R>(f: Fn): (...args: Parameters<Fn>) => Promise<R> {
102
- if (!isRunOnBackgroundEnabled()) {
103
- throw new Error('runOnBackground requires Lynx sdk version 2.16.');
104
- }
105
- if (__JS__) {
106
- throw new Error('runOnBackground can only be used on the main thread.');
107
- }
108
- const obj = f as any as JsFnHandle;
109
- if (obj._error) {
110
- throw new Error(obj._error);
111
- }
112
- return async (...params: ClosureValueType[]): Promise<R> => {
113
- return new Promise((resolve) => {
114
- const resolveId = onFunctionCall(resolve);
115
-
116
- if (obj._isFirstScreen) {
117
- delayRunOnBackground(obj, (fnId: number, execId: number) => {
118
- dispatchRunBackgroundFunctionEvent(fnId, params, execId, resolveId);
119
- });
120
- return;
121
- }
122
-
123
- dispatchRunBackgroundFunctionEvent(obj._jsFnId!, params, obj._execId!, resolveId);
124
- });
125
- };
126
- }
127
-
128
- function dispatchRunBackgroundFunctionEvent(
129
- fnId: number,
130
- params: ClosureValueType[],
131
- execId: number,
132
- resolveId: number,
133
- ): void {
134
- lynx.getJSContext!().dispatchEvent({
135
- type: WorkletEvents.runOnBackground,
136
- data: JSON.stringify({
137
- obj: {
138
- _jsFnId: fnId,
139
- _execId: execId,
140
- },
141
- params,
142
- resolveId,
143
- } as RunOnBackgroundData),
144
- });
145
- }
146
-
147
- export { registerWorkletCtx, runJSFunction, runOnBackground };
@@ -1,50 +0,0 @@
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
- }
@@ -1,26 +0,0 @@
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
- }
@@ -1,231 +0,0 @@
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 { RefObject } from 'react';
5
-
6
- import type { WorkletRefImpl } from '@lynx-js/react/worklet-runtime/bindings';
7
- import { WorkletEvents } from '@lynx-js/react/worklet-runtime/bindings';
8
-
9
- import { addWorkletRefInitValue } from './workletRefPool.js';
10
- import { useMemo } from '../hooks/react.js';
11
-
12
- // Split into two variables for testing purposes
13
- let lastIdBG = 0;
14
- let lastIdMT = 0;
15
-
16
- export function clearWorkletRefLastIdForTesting(): void {
17
- lastIdBG = lastIdMT = 0;
18
- }
19
-
20
- abstract class WorkletRef<T> {
21
- /**
22
- * @internal
23
- */
24
- protected _wvid: number;
25
- /**
26
- * @internal
27
- */
28
- protected _initValue: T | undefined;
29
- /**
30
- * @internal
31
- */
32
- protected _type: string;
33
- /**
34
- * @internal
35
- */
36
- protected _lifecycleObserver: unknown;
37
-
38
- /**
39
- * @internal
40
- */
41
- protected constructor(initValue: T, type: string) {
42
- this._initValue = initValue;
43
- this._type = type;
44
- if (__JS__) {
45
- this._wvid = ++lastIdBG;
46
- addWorkletRefInitValue(this._wvid, initValue);
47
- } else {
48
- this._wvid = --lastIdMT;
49
- }
50
- }
51
-
52
- get current(): T {
53
- if (__JS__ && __DEV__) {
54
- throw new Error('MainThreadRef: value of a MainThreadRef cannot be accessed in the background thread.');
55
- }
56
- if (__LEPUS__ && __DEV__) {
57
- /* v8 ignore next 3 */
58
- throw new Error('MainThreadRef: value of a MainThreadRef cannot be accessed outside of main thread script.');
59
- }
60
- return undefined as T;
61
- }
62
-
63
- set current(_: T) {
64
- if (__JS__ && __DEV__) {
65
- throw new Error('MainThreadRef: value of a MainThreadRef cannot be accessed in the background thread.');
66
- }
67
- if (__LEPUS__ && __DEV__) {
68
- throw new Error('MainThreadRef: value of a MainThreadRef cannot be accessed outside of main thread script.');
69
- }
70
- }
71
-
72
- /**
73
- * @internal
74
- */
75
- toJSON(): { _wvid: WorkletRefImpl<T>['_wvid'] } {
76
- return {
77
- _wvid: this._wvid,
78
- };
79
- }
80
- }
81
-
82
- /**
83
- * A `MainThreadRef` is a ref that can only be accessed on the main thread. It is used to preserve
84
- * states between main thread function calls.
85
- * The data saved in `current` property of the `MainThreadRef` can be read and written in
86
- * multiple main thread functions.
87
- * @public
88
- */
89
- export class MainThreadRef<T> extends WorkletRef<T> {
90
- constructor(initValue: T) {
91
- super(initValue, 'main-thread');
92
- if (__JS__) {
93
- const id = this._wvid;
94
- this._lifecycleObserver = lynx.getNativeApp().createJSObjectDestructionObserver?.(() => {
95
- lynx.getCoreContext?.().dispatchEvent({
96
- type: WorkletEvents.releaseWorkletRef,
97
- data: {
98
- id,
99
- },
100
- });
101
- });
102
- }
103
- }
104
- }
105
-
106
- /**
107
- * Create A `MainThreadRef`.
108
- *
109
- * A `MainThreadRef` is a ref that can only be accessed on the main thread. It is used to preserve
110
- * states between main thread function calls.
111
- * The data saved in `current` property of the `MainThreadRef` can be read and written in
112
- * multiple main thread functions.
113
- *
114
- * It is a hook and it should only be called at the top level of your component.
115
- *
116
- * @param initValue - The init value of the `MainThreadRef`.
117
- *
118
- * @example
119
- *
120
- * ```ts
121
- * import { useMainThreadRef } from '@lynx-js/react'
122
- * import type { MainThread } from '@lynx-js/types'
123
- *
124
- * export function App() {
125
- * const ref = useMainThreadRef<MainThread.Element>(null)
126
- *
127
- * const handleTap = () => {
128
- * 'main thread'
129
- * ref.current?.setStyleProperty('background-color', 'blue')
130
- * }
131
- *
132
- * return (
133
- * <view
134
- * main-thread:ref={ref}
135
- * main-thread:bindtap={handleTap}
136
- * style={{ width: '300px', height: '300px' }}
137
- * />
138
- * )
139
- * }
140
- * ```
141
- *
142
- * @public
143
- */
144
- export function useMainThreadRef<T>(initValue: T): MainThreadRef<T>;
145
-
146
- // convenience overload for refs given as a ref prop as they typically start with a null value
147
- /**
148
- * Create A `MainThreadRef`.
149
- *
150
- * A `MainThreadRef` is a ref that can only be accessed on the main thread. It is used to preserve
151
- * states between main thread function calls.
152
- * The data saved in `current` property of the `MainThreadRef` can be read and written in
153
- * multiple main thread functions.
154
- *
155
- * It is a hook and it should only be called at the top level of your component.
156
- *
157
- * @param initValue - The init value of the `MainThreadRef`.
158
- *
159
- * @example
160
- *
161
- * ```ts
162
- * import { useMainThreadRef } from '@lynx-js/react'
163
- * import type { MainThread } from '@lynx-js/types'
164
- *
165
- * export function App() {
166
- * const ref = useMainThreadRef<MainThread.Element>(null)
167
- *
168
- * const handleTap = () => {
169
- * 'main thread'
170
- * ref.current?.setStyleProperty('background-color', 'blue')
171
- * }
172
- *
173
- * return (
174
- * <view
175
- * main-thread:ref={ref}
176
- * main-thread:bindtap={handleTap}
177
- * style={{ width: '300px', height: '300px' }}
178
- * />
179
- * )
180
- * }
181
- * ```
182
- *
183
- * @public
184
- */
185
- export function useMainThreadRef<T>(initValue: T | null): RefObject<T>;
186
-
187
- // convenience overload for potentially undefined initialValue / call with 0 arguments
188
- // has a default to stop it from defaulting to {} instead
189
- /**
190
- * Create A `MainThreadRef`.
191
- *
192
- * A `MainThreadRef` is a ref that can only be accessed on the main thread. It is used to preserve
193
- * states between main thread function calls.
194
- * The data saved in `current` property of the `MainThreadRef` can be read and written in
195
- * multiple main thread functions.
196
- *
197
- * It is a hook and it should only be called at the top level of your component.
198
- *
199
- * @example
200
- *
201
- * ```ts
202
- * import { useMainThreadRef } from '@lynx-js/react'
203
- * import type { MainThread } from '@lynx-js/types'
204
- *
205
- * export function App() {
206
- * const ref = useMainThreadRef<MainThread.Element>(null)
207
- *
208
- * const handleTap = () => {
209
- * 'main thread'
210
- * ref.current?.setStyleProperty('background-color', 'blue')
211
- * }
212
- *
213
- * return (
214
- * <view
215
- * main-thread:ref={ref}
216
- * main-thread:bindtap={handleTap}
217
- * style={{ width: '300px', height: '300px' }}
218
- * />
219
- * )
220
- * }
221
- * ```
222
- *
223
- * @public
224
- */
225
- export function useMainThreadRef<T = undefined>(): MainThreadRef<T | undefined>;
226
-
227
- export function useMainThreadRef<T>(initValue?: T): MainThreadRef<T | undefined> {
228
- return useMemo(() => {
229
- return new MainThreadRef(initValue);
230
- }, []);
231
- }