plug-code 1.1.9 → 1.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/core/plcAPI.tsx +29 -17
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "plug-code",
3
- "version": "1.1.9",
3
+ "version": "1.1.11",
4
4
  "description": "",
5
5
  "main": "src/plug-code.tsx",
6
6
  "types": "types/plug-code.d.ts",
@@ -63,28 +63,40 @@ export class PlcAPI<S extends ObjectType> {
63
63
  }
64
64
  }
65
65
 
66
- derive<K extends string>(outputKey: K, dependencies: string[], calculator: () => any) {
67
- let isRunning = false;
66
+ derive<K extends string>(
67
+ outputKey: K,
68
+ dependencies: string[],
69
+ calculator: () => any
70
+ ) {
71
+ let lastValue: any
68
72
 
69
- const runUpdate = () => {
70
- if (isRunning) return;
73
+ let isRunning = false
74
+ let idleHandle: number | null = null
71
75
 
72
- isRunning = true;
73
- try {
74
- const result = calculator();
75
- this.replace("root" as any, { [outputKey]: result });
76
- } finally {
77
- isRunning = false;
78
- }
79
- };
76
+ const runUpdate = () => {
77
+ if (isRunning) return
78
+ if (idleHandle) cancelIdleCallback(idleHandle)
79
+
80
+ idleHandle = requestIdleCallback(() => {
81
+ isRunning = true
82
+ try {
83
+ const result = calculator()
84
+ lastValue = result
85
+ this.replace("root" as any, { [outputKey]: result })
86
+ } finally {
87
+ isRunning = false
88
+ idleHandle = null
89
+ }
90
+ }, { timeout: 100 })
91
+ }
80
92
 
81
93
  dependencies.forEach(dep => {
82
- this.store.subscribe(dep as any, () => {
83
- runUpdate();
84
- });
85
- });
94
+ this.store.subscribe(dep as any, () => runUpdate())
95
+ })
96
+
97
+ runUpdate()
86
98
 
87
- runUpdate();
99
+ return () => lastValue
88
100
  }
89
101
 
90
102
  register(slot: SlotKey, node: () => React.ReactNode): void;