aoye 0.0.1 → 0.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.
package/dist/aoye.esm.js CHANGED
@@ -1,58 +1,21 @@
1
- function Queue() {
2
- return {
3
- len: 0,
4
- push: Queue_$$$_push,
5
- shift: Queue_$$$_shift,
6
- get first() {
7
- var _a;
8
- return (_a = this._first) === null || _a === void 0 ? void 0 : _a.v;
9
- },
10
- get last() {
11
- var _a;
12
- return (_a = this._last) === null || _a === void 0 ? void 0 : _a.v;
13
- }
14
- };
15
- }
16
- function Queue_$$$_push(it) {
17
- this.len++;
18
- const {
19
- _last: last
20
- } = this;
21
- const item = {
22
- v: it
23
- };
24
- if (!last) {
25
- this._first = this._last = item;
26
- return;
1
+ class SortMap {
2
+ constructor() {
3
+ this.data = {};
27
4
  }
28
- item.prev = this._last;
29
- last.next = item;
30
- this._last = item;
31
- }
32
- function Queue_$$$_shift() {
33
- const {
34
- _first: first
35
- } = this;
36
- if (!first) return undefined;
37
- this.len--;
38
- const {
39
- next
40
- } = first;
41
- first.next = undefined;
42
- if (next) {
43
- next.prev = undefined;
44
- } else {
45
- this._last = undefined;
5
+ clear() {
6
+ this.data = {};
7
+ }
8
+ add(key, value) {
9
+ const {
10
+ data
11
+ } = this;
12
+ let list = data[key];
13
+ if (!list) {
14
+ list = [];
15
+ data[key] = list;
16
+ }
17
+ list.push(value);
46
18
  }
47
- this._first = next;
48
- return first.v;
49
- }
50
- function SortMap() {
51
- return {
52
- data: {},
53
- clear: SortMap_$$$_clear,
54
- add: SortMap_$$$_add
55
- };
56
19
  }
57
20
  // const queue = new Queue([1,2,3,4]);
58
21
  // queue.shift()
@@ -69,21 +32,157 @@ function SortMap() {
69
32
  // queue.pop()
70
33
  // queue.push(10)
71
34
  // queue.array();
72
- function SortMap_$$$_clear() {
73
- this.data = {};
74
- }
75
- function SortMap_$$$_add(key, value) {
76
- const {
77
- data
78
- } = this;
79
- let list = data[key];
80
- if (!list) {
81
- list = [];
82
- data[key] = list;
35
+
36
+ const timestamp = globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now;
37
+ var EventMode;
38
+ (function (EventMode) {
39
+ EventMode[EventMode["Immediate"] = 0] = "Immediate";
40
+ EventMode[EventMode["Queue"] = 1] = "Queue";
41
+ })(EventMode || (EventMode = {}));
42
+ var ProcessStatus;
43
+ (function (ProcessStatus) {
44
+ ProcessStatus[ProcessStatus["None"] = 0] = "None";
45
+ ProcessStatus[ProcessStatus["Processing"] = 1] = "Processing";
46
+ ProcessStatus[ProcessStatus["Paused"] = 2] = "Paused";
47
+ })(ProcessStatus || (ProcessStatus = {}));
48
+ const DefaultEventOpt = {
49
+ mode: EventMode.Immediate
50
+ };
51
+ const ALL = '__ALL_KEY';
52
+ class BaseEvent {
53
+ constructor(opt = {}) {
54
+ this.opt = opt;
55
+ this.eventQueue = [];
56
+ this.status = ProcessStatus.None;
57
+ this.subMap = new Map();
58
+ this.on = (type, fn) => {
59
+ if (type == null) type = ALL;
60
+ const suber = this.subMap.get(type) || new Set();
61
+ suber.add(fn);
62
+ this.subMap.set(type, suber);
63
+ };
64
+ this.off = (type, fn) => {
65
+ const suber = this.subMap.get(type !== null && type !== void 0 ? type : ALL);
66
+ if (!suber) return;
67
+ suber.delete(fn);
68
+ };
69
+ this.once = (type, fn) => {
70
+ fn['once'] = true;
71
+ this.on(type, fn);
72
+ };
73
+ this.promiseOnce = type => {
74
+ return new Promise(resolve => {
75
+ this.once(type, (...args) => {
76
+ resolve(args);
77
+ });
78
+ });
79
+ };
80
+ this.setScheduler = (type, scheduler) => {
81
+ if (typeof type !== 'string') {
82
+ this.scheduler = type;
83
+ return;
84
+ }
85
+ const set = this.subMap.get(type) || new Set();
86
+ set['scheduler'] = scheduler;
87
+ this.subMap.set(type, set);
88
+ };
89
+ // construct 会初始化为下面其中一种
90
+ this.emit = (type, ...args) => {
91
+ this.opt.mode === EventMode.Immediate ? this.emitImmediate(type, ...args) : this.emitQueue(type, ...args);
92
+ };
93
+ this.pause = () => this.status = ProcessStatus.Paused;
94
+ this.unPause = () => this.status = ProcessStatus.None;
95
+ this.start = () => {
96
+ this.status = ProcessStatus.None;
97
+ this.processQueue();
98
+ };
99
+ this.process = () => {
100
+ if (this.scheduler) {
101
+ return this.scheduler(this.recallScheduler);
102
+ }
103
+ return this.processQueue();
104
+ };
105
+ this.recallScheduler = () => {
106
+ this.scheduler(this.recallScheduler);
107
+ };
108
+ this.processQueue = () => {
109
+ // 如果是挂起状态则直接结束
110
+ if (this.status === ProcessStatus.Paused) return;
111
+ this.status = ProcessStatus.Processing;
112
+ let {
113
+ type,
114
+ args
115
+ } = this.eventQueue.shift() || {};
116
+ if (type) {
117
+ // 在此过程中用户可通过 pause 和 start 同步控制事件处理
118
+ const fns = this.subMap.get(type);
119
+ const allSub = this.subMap.get(ALL);
120
+ fns === null || fns === void 0 ? void 0 : fns.forEach(it => this.callSub(it, fns, args));
121
+ allSub === null || allSub === void 0 ? void 0 : allSub.forEach(it => this.callSub(it, allSub, args));
122
+ if (this.eventQueue.length > 0) {
123
+ this.processQueue();
124
+ }
125
+ }
126
+ //@ts-ignore 队列全部处理完成,如果执行过程中被 pause
127
+ if (this.status !== ProcessStatus.Paused) {
128
+ this.status = ProcessStatus.None;
129
+ }
130
+ };
131
+ this.dispatchEvent = iList => {
132
+ // 从大到小排序
133
+ iList.sort((a, b) => b - a);
134
+ iList.forEach(idx => {
135
+ const [item] = this.eventQueue.splice(idx, 1);
136
+ const {
137
+ type,
138
+ args
139
+ } = item || {};
140
+ if (type && args) {
141
+ this.emitImmediate(type, ...args);
142
+ }
143
+ });
144
+ };
145
+ this.clear = () => {
146
+ this.subMap.clear();
147
+ this.eventQueue = [];
148
+ this.scheduler = undefined;
149
+ };
150
+ this.opt = {
151
+ ...DefaultEventOpt,
152
+ ...opt
153
+ };
154
+ }
155
+ callSub(it, fns, args) {
156
+ const doCall = (...args) => {
157
+ it(...args);
158
+ if (it['once'] === true) fns.delete(it);
159
+ };
160
+ const scheduler = it['scheduler'] || fns['scheduler'];
161
+ if (scheduler) {
162
+ scheduler(doCall, ...args);
163
+ } else {
164
+ it(...args);
165
+ if (it['once'] === true) fns.delete(it);
166
+ }
167
+ }
168
+ emitImmediate(type, ...args) {
169
+ const fns = this.subMap.get(type);
170
+ const allSub = this.subMap.get(ALL);
171
+ fns === null || fns === void 0 ? void 0 : fns.forEach(it => this.callSub(it, fns, args));
172
+ allSub === null || allSub === void 0 ? void 0 : allSub.forEach(it => this.callSub(it, allSub, args));
173
+ }
174
+ emitQueue(type, ...args) {
175
+ this.eventQueue.push({
176
+ type,
177
+ args,
178
+ time: timestamp()
179
+ });
180
+ this.process();
83
181
  }
84
- list.push(value);
85
182
  }
183
+ BaseEvent.a = 19;
86
184
 
185
+ const evt = new BaseEvent();
87
186
  const G = {
88
187
  /** 原子 signal 更新次数 */
89
188
  version: 0,
@@ -91,11 +190,12 @@ const G = {
91
190
  /** scope 销毁任务序号 */
92
191
  scopeDisposeI: 0
93
192
  };
94
- const dirtyLeafs = SortMap();
193
+ const dirtyLeafs = new SortMap();
95
194
  var State;
96
195
  (function (State) {
97
196
  State[State["Clean"] = 0] = "Clean";
98
197
  /** 仅用于 scope 节点是否 abort */
198
+ State[State["ScopeAborted"] = 64] = "ScopeAborted";
99
199
  State[State["ScopeAbort"] = 32] = "ScopeAbort";
100
200
  State[State["OutLink"] = 16] = "OutLink";
101
201
  State[State["Unknown"] = 8] = "Unknown";
@@ -104,294 +204,7 @@ var State;
104
204
  State[State["ScopeReady"] = 1] = "ScopeReady";
105
205
  })(State || (State = {}));
106
206
  const DirtyState = State.Unknown | State.Dirty;
107
-
108
- var Scheduler;
109
- (function (Scheduler) {
110
- Scheduler["Sync"] = "__Sync_";
111
- Scheduler["Layout"] = "__Layout_";
112
- Scheduler["Micro"] = "__Micro_";
113
- Scheduler["Macro"] = "__Macro_";
114
- })(Scheduler || (Scheduler = {}));
115
- const _scheduler = {
116
- [Scheduler.Sync]: defaultScheduler,
117
- [Scheduler.Micro]: microScheduler,
118
- [Scheduler.Macro]: macroScheduler,
119
- [Scheduler.Layout]: schedulerLayout
120
- };
121
- const scheduler = (key, value) => _scheduler[key] = value;
122
- function defaultScheduler(effects) {
123
- for (const effect of effects) {
124
- effect.runIfDirty();
125
- }
126
- }
127
- const p = Promise.resolve();
128
- let hasMicroTask = false;
129
- function microScheduler(effects) {
130
- if (hasMicroTask) return;
131
- p.then(() => {
132
- defaultScheduler(effects);
133
- hasMicroTask = false;
134
- });
135
- hasMicroTask = true;
136
- }
137
- let channel, macroQueue;
138
- if (globalThis.MessageChannel) {
139
- channel = new MessageChannel();
140
- macroQueue = Queue();
141
- channel.port2.onmessage = () => {
142
- while (macroQueue.first) {
143
- macroQueue.shift()();
144
- }
145
- };
146
- }
147
- function macroScheduler(effects) {
148
- if (channel) {
149
- macroQueue.push(() => defaultScheduler(effects));
150
- channel.port1.postMessage('');
151
- }
152
- setTimeout(() => {
153
- defaultScheduler(effects);
154
- });
155
- }
156
- function schedulerLayout(effects) {
157
- requestAnimationFrame(() => {
158
- defaultScheduler(effects);
159
- });
160
- }
161
-
162
- const DefaultDFSOpt = {
163
- isUp: false,
164
- begin: undefined,
165
- complete: undefined,
166
- breakStack: [],
167
- breakLine: undefined,
168
- breakNode: undefined
169
- };
170
- function dfs(root, opt = {}) {
171
- const {
172
- isUp,
173
- begin,
174
- complete,
175
- breakStack: lineStack,
176
- breakLine
177
- } = {
178
- ...DefaultDFSOpt,
179
- ...opt
180
- };
181
- let node = opt.breakNode || root;
182
- let line = breakLine;
183
- const listKey = isUp ? 'recStart' : 'emitStart';
184
- const nodeKey = isUp ? 'upstream' : 'downstream';
185
- // 向上意味着要找所有节点的入度
186
- const nextLineKey = isUp ? 'nextRecLine' : 'nextEmitLine';
187
- const reverseNodeKey = isUp ? 'downstream' : 'upstream';
188
- while (1) {
189
- let notGoDeep = begin === null || begin === void 0 ? void 0 : begin({
190
- node: node,
191
- lineFromUp: line,
192
- walkedLine: lineStack
193
- });
194
- lineStack.push(line);
195
- line = node[listKey];
196
- if (line && !notGoDeep) {
197
- const firstChild = line[nodeKey];
198
- node = firstChild;
199
- continue;
200
- }
201
- while (1) {
202
- const noGoSibling = complete === null || complete === void 0 ? void 0 : complete({
203
- node: node,
204
- lineToDeep: line,
205
- walkedLine: lineStack,
206
- notGoDeep
207
- });
208
- // 只对当前不下钻的节点生效
209
- // notGoDeep = false;
210
- line = lineStack.pop();
211
- // 递归出口,回到起点
212
- if (node === root) {
213
- return;
214
- }
215
- notGoDeep = false;
216
- const nextLine = line[nextLineKey];
217
- // 有兄弟节点, 进入外循环,向下遍历兄弟节点
218
- if (!noGoSibling && nextLine) {
219
- // 外层循环后会把 sibling line 入栈,这里不需要处理
220
- line = nextLine;
221
- node = nextLine[nodeKey];
222
- break;
223
- }
224
- // 没有兄弟节点就上浮
225
- node = line[reverseNodeKey];
226
- }
227
- }
228
- }
229
-
230
- function Line_$$$_link(v1, v2) {
231
- let {
232
- emitEnd
233
- } = v1,
234
- {
235
- recEnd,
236
- recStart
237
- } = v2,
238
- noRecEnd = !recEnd,
239
- /** 模拟头节点 */
240
- head = {
241
- nextRecLine: recStart
242
- },
243
- line;
244
- recEnd = recEnd || head;
245
- const {
246
- nextRecLine
247
- } = recEnd || {};
248
- // 没有下一个收到的线
249
- if (!nextRecLine) {
250
- line = Line();
251
- // 内部会处理空链表的情况,即同步头部
252
- Line.emit_line(v1, line);
253
- Line.rec_line(v2, line);
254
- emitEnd && Line.line_line_emit(emitEnd, line);
255
- !noRecEnd && Line.line_line_rec(recEnd, line);
256
- }
257
- // 复用
258
- else if (nextRecLine.upstream === v1) {
259
- v2.recEnd = nextRecLine;
260
- // TODO: link 版本标记
261
- }
262
- // 插入(这么做): v1 和 下一个 入度(订阅)节点不同
263
- // TODO: v2上次真依赖了 v1 只是没检查出来,需要删除原依赖
264
- else {
265
- line = Line();
266
- Line.emit_line(v1, line);
267
- Line.rec_line(v2, line);
268
- emitEnd && Line.line_line_emit(emitEnd, line);
269
- Line.insert_line_rec(recEnd, nextRecLine, line);
270
- }
271
- // 消除 head
272
- for (const key in head) {
273
- head[key] = undefined;
274
- }
275
- }
276
- Line.link = Line_$$$_link;
277
- function Line_$$$_unlink(line) {
278
- let {
279
- prevEmitLine,
280
- nextEmitLine,
281
- prevRecLine,
282
- nextRecLine,
283
- upstream,
284
- downstream
285
- } = line;
286
- line.prevEmitLine = undefined;
287
- line.nextEmitLine = undefined;
288
- line.prevRecLine = undefined;
289
- line.nextRecLine = undefined;
290
- line.upstream = undefined;
291
- line.downstream = undefined;
292
- /** 上游节点发出的线 前一条 关联 后一条 */
293
- if (prevEmitLine) {
294
- prevEmitLine.nextEmitLine = nextEmitLine;
295
- } else {
296
- // 删除的是首个节点
297
- upstream.emitStart = nextEmitLine;
298
- }
299
- if (nextEmitLine) {
300
- nextEmitLine.prevEmitLine = prevEmitLine;
301
- } else {
302
- // 删除尾节点
303
- upstream.emitEnd = prevEmitLine;
304
- }
305
- /** 下游节点接收的线,我们从 recEnd 开始删除的,
306
- * 接收信息,不需要设置 recEnd ,
307
- * 因为 recStart ~ recEnd 是经过上级 get 确认的有用依赖
308
- * */
309
- if (prevRecLine) {
310
- prevRecLine.nextRecLine = nextRecLine;
311
- } else {
312
- // 删除的是首个节点,大概率不可能从有依赖 变成无依赖
313
- downstream.recStart = nextRecLine;
314
- }
315
- if (nextRecLine) {
316
- nextRecLine.prevRecLine = prevRecLine;
317
- } else {
318
- // 删除尾节点
319
- downstream.recEnd = prevRecLine;
320
- }
321
- }
322
- Line.unlink = Line_$$$_unlink;
323
- function Line_$$$_unlinkRec(line) {
324
- // 作为下游,执行完 get 上游节点已经完成了依赖更新,把 recEnd 后的依赖删除即可
325
- let toDel = line;
326
- while (toDel) {
327
- const memoNext = toDel.nextRecLine;
328
- Line.unlink(toDel);
329
- toDel = memoNext;
330
- }
331
- }
332
- Line.unlinkRec = Line_$$$_unlinkRec;
333
- function Line_$$$_unlinkEmit(line) {
334
- // 作为下游,执行完 get 上游节点已经完成了依赖更新,把 recEnd 后的依赖删除即可
335
- let toDel = line;
336
- while (toDel) {
337
- const memoNext = toDel.nextEmitLine;
338
- Line.unlink(toDel);
339
- toDel = memoNext;
340
- }
341
- }
342
- Line.unlinkEmit = Line_$$$_unlinkEmit;
343
- function Line_$$$_emit_line(upstream, line) {
344
- if (!upstream.emitStart) {
345
- upstream.emitStart = line;
346
- }
347
- upstream.emitEnd = line;
348
- line.upstream = upstream;
349
- }
350
- Line.emit_line = Line_$$$_emit_line;
351
- function Line_$$$_rec_line(downstream, line) {
352
- if (!downstream.recStart) {
353
- downstream.recStart = line;
354
- }
355
- downstream.recEnd = line;
356
- line.downstream = downstream;
357
- }
358
- Line.rec_line = Line_$$$_rec_line;
359
- function Line_$$$_line_line_emit(l1, l2) {
360
- if (!l1 || !l2) return;
361
- l1.nextEmitLine = l2;
362
- l2.prevEmitLine = l1;
363
- }
364
- Line.line_line_emit = Line_$$$_line_line_emit;
365
- function Line_$$$_line_line_rec(l1, l2) {
366
- if (!l1 || !l2) return;
367
- l1.nextRecLine = l2;
368
- l2.prevRecLine = l1;
369
- }
370
- Line.line_line_rec = Line_$$$_line_line_rec;
371
- function Line_$$$_insert_line_emit(l1, l2, ins) {
372
- l1.nextEmitLine = ins;
373
- ins.prevEmitLine = l1;
374
- l2.prevEmitLine = ins;
375
- ins.nextEmitLine = l2;
376
- }
377
- Line.insert_line_emit = Line_$$$_insert_line_emit;
378
- function Line_$$$_insert_line_rec(l1, l2, ins) {
379
- l1.nextRecLine = ins;
380
- ins.prevRecLine = l1;
381
- l2.prevRecLine = ins;
382
- ins.nextRecLine = l2;
383
- }
384
- Line.insert_line_rec = Line_$$$_insert_line_rec;
385
- function Line() {
386
- return {
387
- upstream: null,
388
- prevEmitLine: null,
389
- nextEmitLine: null,
390
- downstream: null,
391
- prevRecLine: null,
392
- nextRecLine: null
393
- };
394
- }
207
+ const ScopeExecuted = State.ScopeReady | State.ScopeAbort | State.ScopeAborted;
395
208
 
396
209
  /**
397
210
  * 这是一个优先队列 (满足子节点总是比父节点大)
@@ -432,11 +245,13 @@ const getLeft = (x, max) => leakI(x * 2 + 1, max);
432
245
  const getRight = (x, max) => leakI(x * 2 + 2, max);
433
246
  const getParent = (x, max) => leakI(x - 1 >>> 1, max);
434
247
  const exchange = (arr, i, j) => [arr[i], arr[j]] = [arr[j], arr[i]];
435
- function PriorityQueue(aIsUrgent) {
436
- return {
437
- aIsUrgent: aIsUrgent,
438
- arr: [],
439
- goUp: (arr, current, len) => {
248
+ class PriorityQueue {
249
+ // 构造函数接受一个compare函数
250
+ // compare返回的-1, 0, 1决定元素是否优先被去除
251
+ constructor(aIsUrgent) {
252
+ this.aIsUrgent = aIsUrgent;
253
+ this.arr = [];
254
+ this.goUp = (arr, current, len) => {
440
255
  let i = len - 1;
441
256
  while (i > 0) {
442
257
  const item = arr[i];
@@ -452,8 +267,8 @@ function PriorityQueue(aIsUrgent) {
452
267
  break;
453
268
  }
454
269
  }
455
- },
456
- goDown: (arr, i) => {
270
+ };
271
+ this.goDown = (arr, i) => {
457
272
  const len = this.size();
458
273
  const half = len >>> 1;
459
274
  while (i < half) {
@@ -474,14 +289,71 @@ function PriorityQueue(aIsUrgent) {
474
289
  // this.logTree();
475
290
  i = point;
476
291
  }
477
- },
478
- _add: PriorityQueue_$$$__add,
479
- add: PriorityQueue_$$$_add,
480
- poll: PriorityQueue_$$$_poll,
481
- peek: PriorityQueue_$$$_peek,
482
- size: PriorityQueue_$$$_size,
483
- logTree: PriorityQueue_$$$_logTree
484
- };
292
+ };
293
+ }
294
+ // 添加一个元素
295
+ _add(current) {
296
+ // console.log(`加入 ${current}`);
297
+ this.arr.push(current);
298
+ const len = this.size();
299
+ // this.logTree();
300
+ if (len === 1) {
301
+ return;
302
+ }
303
+ this.goUp(this.arr, current, len);
304
+ }
305
+ add(...items) {
306
+ items.forEach(it => this._add(it));
307
+ }
308
+ // 去除头元素并返回
309
+ poll() {
310
+ const {
311
+ arr
312
+ } = this;
313
+ // console.log(`弹出 ${arr[0]} 把 ${arr[arr.length - 1]} 放置到队头 `);
314
+ const len = this.size();
315
+ if (len <= 2) {
316
+ return arr.shift();
317
+ }
318
+ const last = arr.pop();
319
+ const first = arr[0];
320
+ arr[0] = last;
321
+ // this.logTree();
322
+ this.goDown(this.arr, 0);
323
+ return first;
324
+ }
325
+ // 取得头元素
326
+ peek() {
327
+ return this.arr[0];
328
+ }
329
+ // 取得元素数量
330
+ size() {
331
+ return this.arr.length;
332
+ }
333
+ logTree() {
334
+ const {
335
+ arr
336
+ } = this;
337
+ let i = 0;
338
+ let j = 1;
339
+ let level = 0;
340
+ const matrix = [];
341
+ do {
342
+ matrix.push(arr.slice(i, j));
343
+ i = i * 2 + 1;
344
+ j = i + Math.pow(2, level) + 1;
345
+ level++;
346
+ } while (i < arr.length);
347
+ const last = Math.pow(2, matrix.length - 1);
348
+ const arrStr = JSON.stringify(last);
349
+ const halfLen = arrStr.length >>> 1;
350
+ matrix.forEach(it => {
351
+ const str = JSON.stringify(it);
352
+ const halfIt = str.length >>> 1;
353
+ console.log(str.padStart(halfLen + halfIt, ' '));
354
+ });
355
+ console.log('\n');
356
+ }
485
357
  }
486
358
  // case 1
487
359
  // const pq = new PriorityQueue((a, b) => a - b)
@@ -509,113 +381,55 @@ function PriorityQueue(aIsUrgent) {
509
381
  // }
510
382
  // console.log(result);
511
383
  // [5,4,3,2,1]
512
- function PriorityQueue_$$$__add(current) {
513
- // console.log(`加入 ${current}`);
514
- this.arr.push(current);
515
- const len = this.size();
516
- // this.logTree();
517
- if (len === 1) {
518
- return;
384
+
385
+ class TaskQueue {
386
+ constructor(callbackAble, aIsUrgent) {
387
+ this.callbackAble = callbackAble;
388
+ this.aIsUrgent = aIsUrgent;
389
+ this.isScheduling = false;
519
390
  }
520
- this.goUp(this.arr, current, len);
521
- }
522
- function PriorityQueue_$$$_add(...items) {
523
- items.forEach(it => this._add(it));
524
- }
525
- function PriorityQueue_$$$_poll() {
526
- const {
527
- arr
528
- } = this;
529
- // console.log(`弹出 ${arr[0]} 把 ${arr[arr.length - 1]} 放置到队头 `);
530
- const len = this.size();
531
- if (len <= 2) {
532
- return arr.shift();
391
+ static create({
392
+ callbackAble,
393
+ aIsUrgent
394
+ }) {
395
+ const queue = new TaskQueue(callbackAble, aIsUrgent);
396
+ queue.taskQueue = new PriorityQueue(aIsUrgent);
397
+ return queue;
533
398
  }
534
- const last = arr.pop();
535
- const first = arr[0];
536
- arr[0] = last;
537
- // this.logTree();
538
- this.goDown(this.arr, 0);
539
- return first;
540
- }
541
- function PriorityQueue_$$$_peek() {
542
- return this.arr[0];
543
- }
544
- function PriorityQueue_$$$_size() {
545
- return this.arr.length;
546
- }
547
- function PriorityQueue_$$$_logTree() {
548
- const {
549
- arr
550
- } = this;
551
- let i = 0;
552
- let j = 1;
553
- let level = 0;
554
- const matrix = [];
555
- do {
556
- matrix.push(arr.slice(i, j));
557
- i = i * 2 + 1;
558
- j = i + Math.pow(2, level) + 1;
559
- level++;
560
- } while (i < arr.length);
561
- const last = Math.pow(2, matrix.length - 1);
562
- const arrStr = JSON.stringify(last);
563
- const halfLen = arrStr.length >>> 1;
564
- matrix.forEach(it => {
565
- const str = JSON.stringify(it);
566
- const halfIt = str.length >>> 1;
567
- console.log(str.padStart(halfLen + halfIt, ' '));
568
- });
569
- console.log('\n');
570
- }
571
-
572
- function TaskQueue_$$$_create({
573
- callbackAble,
574
- aIsUrgent
575
- }) {
576
- const queue = TaskQueue(callbackAble, aIsUrgent);
577
- queue.taskQueue = PriorityQueue(aIsUrgent);
578
- return queue;
579
- }
580
- TaskQueue.create = TaskQueue_$$$_create;
581
- function TaskQueue(callbackAble, aIsUrgent) {
582
- return {
583
- callbackAble: callbackAble,
584
- aIsUrgent: aIsUrgent,
585
- isScheduling: false,
586
- pushTask: TaskQueue_$$$_pushTask,
587
- scheduleTask: TaskQueue_$$$_scheduleTask
588
- };
589
- }
590
- function TaskQueue_$$$_pushTask(task) {
591
- const {
592
- taskQueue,
593
- isScheduling
594
- } = this;
595
- taskQueue._add(task);
596
- if (!isScheduling) {
597
- this.callbackAble(this.scheduleTask.bind(this));
598
- this.isScheduling = true;
399
+ pushTask(task) {
400
+ const {
401
+ taskQueue,
402
+ isScheduling
403
+ } = this;
404
+ taskQueue._add(task);
405
+ if (!isScheduling) {
406
+ this.callbackAble(this.scheduleTask.bind(this));
407
+ this.isScheduling = true;
408
+ }
599
409
  }
600
- }
601
- function TaskQueue_$$$_scheduleTask() {
602
- const {
603
- taskQueue
604
- } = this;
605
- // console.log('调度 dispose');
606
- const fn = taskQueue.peek();
607
- if (!fn) return this.isScheduling = false;
608
- const hasRemain = fn();
609
- // 未完成
610
- if (hasRemain) {
410
+ scheduleTask() {
411
+ const {
412
+ taskQueue
413
+ } = this;
414
+ // console.log('调度 dispose');
415
+ const fn = taskQueue.peek();
416
+ if (!fn) return this.isScheduling = false;
417
+ const hasRemain = fn();
418
+ // 未完成
419
+ if (hasRemain) {
420
+ this.callbackAble(this.scheduleTask.bind(this));
421
+ return;
422
+ }
423
+ // 完成
424
+ taskQueue.poll();
425
+ evt.emit('one', fn);
426
+ if (taskQueue.size() === 0) {
427
+ evt.emit('done', fn);
428
+ return this.isScheduling = false;
429
+ }
430
+ // 任务列表中还有任务
611
431
  this.callbackAble(this.scheduleTask.bind(this));
612
- return;
613
432
  }
614
- // 完成
615
- taskQueue.poll();
616
- if (taskQueue.size() === 0) return this.isScheduling = false;
617
- // 任务列表中还有任务
618
- this.callbackAble(this.scheduleTask.bind(this));
619
433
  }
620
434
 
621
435
  const ide = globalThis.requestIdleCallback || (globalThis.requestAnimationFrame ? fn => globalThis.requestAnimationFrame(() => {
@@ -627,37 +441,308 @@ const now = () => {
627
441
  const timer = globalThis.performance || globalThis.Date;
628
442
  return timer.now();
629
443
  };
444
+ let channel = globalThis.MessageChannel ? new MessageChannel() : null;
445
+ if (globalThis.MessageChannel) {
446
+ channel = new MessageChannel();
447
+ }
448
+ let msgId = 0;
449
+ const macro = fn => {
450
+ if (!channel) {
451
+ setTimeout(fn);
452
+ }
453
+ const memoId = msgId;
454
+ function onMessage(e) {
455
+ if (memoId === e.data) {
456
+ fn();
457
+ channel.port2.removeEventListener('message', onMessage);
458
+ }
459
+ }
460
+ channel.port2.addEventListener('message', onMessage);
461
+ channel.port1.postMessage(msgId++);
462
+ };
463
+ const p = Promise.resolve();
464
+ const micro = cb => {
465
+ p.then(cb);
466
+ };
467
+
468
+ var Scheduler;
469
+ (function (Scheduler) {
470
+ Scheduler["Sync"] = "__Sync_";
471
+ Scheduler["Layout"] = "__Layout_";
472
+ Scheduler["Micro"] = "__Micro_";
473
+ Scheduler["Macro"] = "__Macro_";
474
+ })(Scheduler || (Scheduler = {}));
475
+ const _scheduler = {
476
+ [Scheduler.Sync]: defaultScheduler,
477
+ [Scheduler.Micro]: microScheduler,
478
+ [Scheduler.Macro]: macroScheduler,
479
+ [Scheduler.Layout]: layoutScheduler
480
+ };
481
+ const scheduler = (key, value) => _scheduler[key] = value;
482
+ function defaultScheduler(effects) {
483
+ for (const effect of effects) {
484
+ effect.runIfDirty();
485
+ }
486
+ }
487
+ let microSTaskQueue;
488
+ let macroSTaskQueue;
489
+ let layoutSTaskQueue;
490
+ function microScheduler(effects) {
491
+ microSTaskQueue = microSTaskQueue || TaskQueue.create({
492
+ callbackAble: micro,
493
+ aIsUrgent: (a, b) => a.time < b.time
494
+ });
495
+ microSTaskQueue.pushTask(defaultScheduler.bind(undefined, effects));
496
+ }
497
+ function macroScheduler(effects) {
498
+ macroSTaskQueue = macroSTaskQueue || TaskQueue.create({
499
+ callbackAble: macro,
500
+ aIsUrgent: (a, b) => a.time < b.time
501
+ });
502
+ macroSTaskQueue.pushTask(defaultScheduler.bind(undefined, effects));
503
+ }
504
+ function layoutScheduler(effects) {
505
+ layoutSTaskQueue = layoutSTaskQueue || TaskQueue.create({
506
+ callbackAble: macro,
507
+ aIsUrgent: (a, b) => a.time < b.time
508
+ });
509
+ layoutSTaskQueue.pushTask(defaultScheduler.bind(undefined, effects));
510
+ }
511
+
512
+ const DefaultDFSOpt = {
513
+ isUp: false,
514
+ begin: undefined,
515
+ complete: undefined,
516
+ breakStack: [],
517
+ breakLine: undefined,
518
+ breakNode: undefined
519
+ };
520
+ function dfs(root, opt = {}) {
521
+ const {
522
+ isUp,
523
+ begin,
524
+ complete,
525
+ breakStack: lineStack,
526
+ breakLine
527
+ } = {
528
+ ...DefaultDFSOpt,
529
+ ...opt
530
+ };
531
+ let node = opt.breakNode || root;
532
+ let line = breakLine;
533
+ const listKey = isUp ? 'recStart' : 'emitStart';
534
+ const nodeKey = isUp ? 'upstream' : 'downstream';
535
+ // 向上意味着要找所有节点的入度
536
+ const nextLineKey = isUp ? 'nextRecLine' : 'nextEmitLine';
537
+ const reverseNodeKey = isUp ? 'downstream' : 'upstream';
538
+ while (1) {
539
+ let notGoDeep = begin === null || begin === void 0 ? void 0 : begin({
540
+ node: node,
541
+ lineFromUp: line,
542
+ walkedLine: lineStack
543
+ });
544
+ lineStack.push(line);
545
+ line = node[listKey];
546
+ if (line && !notGoDeep) {
547
+ const firstChild = line[nodeKey];
548
+ node = firstChild;
549
+ continue;
550
+ }
551
+ while (1) {
552
+ const noGoSibling = complete === null || complete === void 0 ? void 0 : complete({
553
+ node: node,
554
+ lineToDeep: line,
555
+ walkedLine: lineStack,
556
+ notGoDeep
557
+ });
558
+ // 只对当前不下钻的节点生效
559
+ // notGoDeep = false;
560
+ line = lineStack.pop();
561
+ // 递归出口,回到起点
562
+ if (node === root) {
563
+ return;
564
+ }
565
+ notGoDeep = false;
566
+ const nextLine = line[nextLineKey];
567
+ // 有兄弟节点, 进入外循环,向下遍历兄弟节点
568
+ if (!noGoSibling && nextLine) {
569
+ // 外层循环后会把 sibling line 入栈,这里不需要处理
570
+ line = nextLine;
571
+ node = nextLine[nodeKey];
572
+ break;
573
+ }
574
+ // 没有兄弟节点就上浮
575
+ node = line[reverseNodeKey];
576
+ }
577
+ }
578
+ }
579
+
580
+ class Line {
581
+ static link(v1, v2) {
582
+ let {
583
+ emitEnd
584
+ } = v1,
585
+ {
586
+ recEnd,
587
+ recStart
588
+ } = v2,
589
+ noRecEnd = !recEnd,
590
+ /** 模拟头节点 */
591
+ head = {
592
+ nextRecLine: recStart
593
+ },
594
+ line;
595
+ recEnd = recEnd || head;
596
+ const {
597
+ nextRecLine
598
+ } = recEnd || {};
599
+ // 没有下一个收到的线
600
+ if (!nextRecLine) {
601
+ line = new Line();
602
+ // 内部会处理空链表的情况,即同步头部
603
+ Line.emit_line(v1, line);
604
+ Line.rec_line(v2, line);
605
+ emitEnd && Line.line_line_emit(emitEnd, line);
606
+ !noRecEnd && Line.line_line_rec(recEnd, line);
607
+ }
608
+ // 复用
609
+ else if (nextRecLine.upstream === v1) {
610
+ v2.recEnd = nextRecLine;
611
+ // TODO: link 版本标记
612
+ }
613
+ // 插入(这么做): v1 和 下一个 入度(订阅)节点不同
614
+ // TODO: v2上次真依赖了 v1 只是没检查出来,需要删除原依赖
615
+ else {
616
+ line = new Line();
617
+ Line.emit_line(v1, line);
618
+ Line.rec_line(v2, line);
619
+ emitEnd && Line.line_line_emit(emitEnd, line);
620
+ Line.insert_line_rec(recEnd, nextRecLine, line);
621
+ }
622
+ // 消除 head
623
+ for (const key in head) {
624
+ head[key] = undefined;
625
+ }
626
+ }
627
+ static unlink(line) {
628
+ let {
629
+ prevEmitLine,
630
+ nextEmitLine,
631
+ prevRecLine,
632
+ nextRecLine,
633
+ upstream,
634
+ downstream
635
+ } = line;
636
+ line.prevEmitLine = undefined;
637
+ line.nextEmitLine = undefined;
638
+ line.prevRecLine = undefined;
639
+ line.nextRecLine = undefined;
640
+ line.upstream = undefined;
641
+ line.downstream = undefined;
642
+ /** 上游节点发出的线 前一条 关联 后一条 */
643
+ if (prevEmitLine) {
644
+ prevEmitLine.nextEmitLine = nextEmitLine;
645
+ } else {
646
+ // 删除的是首个节点
647
+ upstream.emitStart = nextEmitLine;
648
+ }
649
+ if (nextEmitLine) {
650
+ nextEmitLine.prevEmitLine = prevEmitLine;
651
+ } else {
652
+ // 删除尾节点
653
+ upstream.emitEnd = prevEmitLine;
654
+ }
655
+ /** 下游节点接收的线,我们从 recEnd 开始删除的,
656
+ * 接收信息,不需要设置 recEnd ,
657
+ * 因为 recStart ~ recEnd 是经过上级 get 确认的有用依赖
658
+ * */
659
+ if (prevRecLine) {
660
+ prevRecLine.nextRecLine = nextRecLine;
661
+ } else {
662
+ // 删除的是首个节点,大概率不可能从有依赖 变成无依赖
663
+ downstream.recStart = nextRecLine;
664
+ }
665
+ if (nextRecLine) {
666
+ nextRecLine.prevRecLine = prevRecLine;
667
+ } else {
668
+ // 删除尾节点
669
+ downstream.recEnd = prevRecLine;
670
+ }
671
+ }
672
+ static unlinkRec(line) {
673
+ // 作为下游,执行完 get 上游节点已经完成了依赖更新,把 recEnd 后的依赖删除即可
674
+ let toDel = line;
675
+ while (toDel) {
676
+ const memoNext = toDel.nextRecLine;
677
+ Line.unlink(toDel);
678
+ toDel = memoNext;
679
+ }
680
+ }
681
+ static unlinkEmit(line) {
682
+ // 作为下游,执行完 get 上游节点已经完成了依赖更新,把 recEnd 后的依赖删除即可
683
+ let toDel = line;
684
+ while (toDel) {
685
+ const memoNext = toDel.nextEmitLine;
686
+ Line.unlink(toDel);
687
+ toDel = memoNext;
688
+ }
689
+ }
690
+ /** 上游节点 连 link */
691
+ static emit_line(upstream, line) {
692
+ if (!upstream.emitStart) {
693
+ upstream.emitStart = line;
694
+ }
695
+ upstream.emitEnd = line;
696
+ line.upstream = upstream;
697
+ }
698
+ /** 下游节点 连 link */
699
+ static rec_line(downstream, line) {
700
+ if (!downstream.recStart) {
701
+ downstream.recStart = line;
702
+ }
703
+ downstream.recEnd = line;
704
+ line.downstream = downstream;
705
+ }
706
+ /** 同一节点发出的 两个条线 相连 */
707
+ static line_line_emit(l1, l2) {
708
+ if (!l1 || !l2) return;
709
+ l1.nextEmitLine = l2;
710
+ l2.prevEmitLine = l1;
711
+ }
712
+ /** 同一节点接收的 两个条线 相连 */
713
+ static line_line_rec(l1, l2) {
714
+ if (!l1 || !l2) return;
715
+ l1.nextRecLine = l2;
716
+ l2.prevRecLine = l1;
717
+ }
718
+ static insert_line_emit(l1, l2, ins) {
719
+ l1.nextEmitLine = ins;
720
+ ins.prevEmitLine = l1;
721
+ l2.prevEmitLine = ins;
722
+ ins.nextEmitLine = l2;
723
+ }
724
+ static insert_line_rec(l1, l2, ins) {
725
+ l1.nextRecLine = ins;
726
+ ins.prevRecLine = l1;
727
+ l2.prevRecLine = ins;
728
+ ins.nextRecLine = l2;
729
+ }
730
+ constructor() {
731
+ /** 上游顶点 */
732
+ this.upstream = null;
733
+ /** 上游节点 发出的上一条线 */
734
+ this.prevEmitLine = null;
735
+ /** 上游节点 发出的下一条线 */
736
+ this.nextEmitLine = null;
737
+ /** 下游顶点 */
738
+ this.downstream = null;
739
+ /** 下游节点 接收的上一条线 */
740
+ this.prevRecLine = null;
741
+ /** 下游节点 接收的下一条线 */
742
+ this.nextRecLine = null;
743
+ }
744
+ }
630
745
 
631
- // export class IdeScheduler {
632
- // constructor() {}
633
- // isScheduling = false;
634
- // taskQueue = new Queue<Function>();
635
- // pushTask(task: Function) {
636
- // const { taskQueue, isScheduling } = this;
637
- // taskQueue.push(task);
638
- // if (!isScheduling) {
639
- // ide(this.scheduleTask.bind(this));
640
- // this.isScheduling = true;
641
- // }
642
- // }
643
- // scheduleTask() {
644
- // const { taskQueue } = this;
645
- // // console.log('调度 dispose');
646
- // const fn = taskQueue.first;
647
- // if (!fn) return (this.isScheduling = false);
648
- // const hasRemain = fn();
649
- // // 未完成
650
- // if (hasRemain) {
651
- // ide(this.scheduleTask.bind(this));
652
- // return;
653
- // }
654
- // // 完成
655
- // taskQueue.shift();
656
- // if (taskQueue.len === 0) return (this.isScheduling = false);
657
- // // 任务列表中还有任务
658
- // ide(this.scheduleTask.bind(this));
659
- // }
660
- // }
661
746
  /** scope 捕获,引用外部 signal 孤岛 */
662
747
  const unTrackIsland = signal => {
663
748
  // 原来是孤岛,且被 scope 管理的要恢复
@@ -667,7 +752,7 @@ const unTrackIsland = signal => {
667
752
  };
668
753
  /** scope 释放,被重新连接的孤岛 */
669
754
  const trackIsland = signal => {
670
- const line = Line();
755
+ const line = new Line();
671
756
  // 上游节点处于孤岛状态,切有引用外部信号,需要被 scope 管理来删除外部依赖
672
757
  if (!signal.emitStart && signal.state & State.OutLink) {
673
758
  const {
@@ -678,6 +763,16 @@ const trackIsland = signal => {
678
763
  Line.line_line_rec(recEnd, line);
679
764
  }
680
765
  };
766
+ /** 子 scope 释放,把其 only 被其持有的 signal 挂回其属于的 scope */
767
+ const trackByOtherScopeDispose = signal => {
768
+ const line = new Line();
769
+ const {
770
+ recEnd
771
+ } = signal.scope;
772
+ Line.emit_line(signal, line);
773
+ Line.rec_line(signal.scope, line);
774
+ Line.line_line_rec(recEnd, line);
775
+ };
681
776
  const markOutLink = (signal, downstream) => {
682
777
  // 上游是外部节点,或者上游引用了外部节点的, 做传播
683
778
  if (signal.scope !== downstream.scope || signal.state & State.OutLink) {
@@ -699,13 +794,16 @@ const ideScheduler = TaskQueue.create({
699
794
  return a.index < b.index;
700
795
  }
701
796
  });
702
- function handleOneTask(s, breakStack) {
797
+ function handleOneTask(scope, breakStack) {
703
798
  breakStack = remain.stack || breakStack;
704
799
  // 将 s 同步到 remainRoot
705
800
  let lineToRemove = null;
706
801
  const startTime = now();
802
+ if (scope.emitStart) {
803
+ Line.unlink(scope.emitStart);
804
+ }
707
805
  try {
708
- dfs(s, {
806
+ dfs(scope, {
709
807
  breakStack,
710
808
  breakNode: remain.node,
711
809
  breakLine: remain.line,
@@ -727,9 +825,28 @@ function handleOneTask(s, breakStack) {
727
825
  };
728
826
  throw BreakErr;
729
827
  }
828
+ // 1. 未标记的节点,是外部节点
730
829
  if (!(node.state & State.OutLink)) {
731
830
  return true;
732
831
  }
832
+ // 2. 标记的节点,但是 scope 不一样,说明外部节点也引用了 另一 scope 的节点
833
+ if (lineFromUp && node.scope !== lineFromUp.downstream['scope']) {
834
+ // 是仅被 node 引用的外部节点
835
+ if (node.emitStart === node.emitEnd) {
836
+ // 已经 abort 只能继续释放
837
+ if (scope.state & State.ScopeAborted) {
838
+ const bound = handleOneTask.bind(undefined, node, []);
839
+ bound.index = G.scopeDisposeI++;
840
+ ideScheduler.pushTask(bound);
841
+ }
842
+ // 可以将其交给 原 scope 释放
843
+ else {
844
+ trackByOtherScopeDispose(node);
845
+ }
846
+ }
847
+ // 任何外部引用都应该被断开
848
+ return true;
849
+ }
733
850
  // 对于嵌套作用域不允许重复进入
734
851
  node.state &= ~State.OutLink;
735
852
  },
@@ -757,6 +874,7 @@ function handleOneTask(s, breakStack) {
757
874
  node: null,
758
875
  line: null
759
876
  };
877
+ scope.state |= State.ScopeAborted;
760
878
  } catch (error) {
761
879
  if (error === BreakErr) return true;
762
880
  remain = {
@@ -780,20 +898,6 @@ function unlinkRecWithScope(line) {
780
898
  }
781
899
  }
782
900
 
783
- function Signal_$$$_create(nextValue, {
784
- customPull,
785
- isScope,
786
- ...rest
787
- }) {
788
- const s = Signal(nextValue, customPull);
789
- s.pull = s.customPull || s.DEFAULT_PULL;
790
- Object.assign(s, rest);
791
- if (isScope) {
792
- s.scope = s;
793
- }
794
- return s;
795
- }
796
- Signal.create = Signal_$$$_create;
797
901
  const markDeep = signal => {
798
902
  let level = 0;
799
903
  dfs(signal, {
@@ -830,200 +934,208 @@ const markDeep = signal => {
830
934
  }
831
935
  dirtyLeafs.clear();
832
936
  };
833
- function Signal(nextValue,
834
- /** 为什么是 shallow,因为 pullDeep 会把
835
- * 上游节点 get 执行完成,让其可以直接拿到缓存值
836
- */
837
- customPull) {
838
- return {
839
- nextValue: nextValue,
840
- customPull: customPull,
841
- version: -1,
842
- id: G.id++,
843
- state: State.Clean,
844
- scope: Signal.Pulling,
845
- recEnd: null,
846
- recStart: null,
847
- emitStart: null,
848
- emitEnd: null,
849
- scheduler: null,
850
- value: null,
851
- pull: null,
852
- DEFAULT_PULL: Signal_$$$_DEFAULT_PULL,
853
- pullRecurse: Signal_$$$_pullRecurse,
854
- pullDeep: Signal_$$$_pullDeep,
855
- get: Signal_$$$_get,
856
- markDownStreamsDirty: Signal_$$$_markDownStreamsDirty,
857
- set: Signal_$$$_set,
858
- run: Signal_$$$_run,
859
- runIfDirty: Signal_$$$_runIfDirty,
860
- isAbort: Signal_$$$_isAbort
861
- };
862
- }
863
- function Signal_$$$_DEFAULT_PULL() {
864
- return this.nextValue;
865
- }
866
- function Signal_$$$_pullRecurse(shouldLink = true) {
867
- var _a;
868
- let downstream = Signal.Pulling;
869
- if (shouldLink && downstream) {
870
- // 如果上游节点被 scope 管理了,解除管理
871
- unTrackIsland(this);
872
- Line.link(this, downstream);
937
+ class Signal {
938
+ constructor(nextValue,
939
+ /** 为什么是 shallow,因为 pullDeep 会把
940
+ * 上游节点 get 执行完成,让其可以直接拿到缓存值
941
+ */
942
+ customPull) {
943
+ this.nextValue = nextValue;
944
+ this.customPull = customPull;
945
+ this.version = -1;
946
+ this.id = G.id++;
947
+ this.state = State.Clean;
948
+ /** 当前节点创建时处于的 effect 就是 scope */
949
+ this.scope = Signal.Pulling;
950
+ this.recEnd = null;
951
+ this.recStart = null;
952
+ this.emitStart = null;
953
+ this.emitEnd = null;
954
+ this.scheduler = null;
955
+ this.value = null;
956
+ this.pull = null;
873
957
  }
874
- try {
875
- if (this.version === G.version) {
876
- return this.value;
877
- }
878
- this.state &= ~State.OutLink;
879
- // pullShallow 前重置 recEnd,让子 getter 重构订阅链表
880
- this.recEnd = undefined;
881
- Signal.Pulling = this;
882
- const v = this.pull();
883
- // 如果使用了 DEFAULT_PULL,处理一次 set 的取值后,替换回 customPull,如果有的话
884
- this.pull = this.customPull || this.DEFAULT_PULL;
885
- this.value = v;
886
- // 依赖上游的 版本号
887
- this.version = G.version;
888
- // if (this.value !== v) {
889
- // }
890
- return this.value;
891
- } catch (error) {
892
- console.error('计算属性报错这次不触发,后续状态可能出错', error);
893
- return this.value;
894
- } finally {
895
- // 本 getter 执行完成时上游 getter 通过 link,完成对下游 recLines 的更新
896
- const toDel = (_a = this.recEnd) === null || _a === void 0 ? void 0 : _a.nextRecLine;
897
- unlinkRecWithScope(toDel);
898
- if (shouldLink && downstream) {
899
- // 用于 scope 指示哪些节点依赖 scope 外部
900
- markOutLink(this, downstream);
958
+ static create(nextValue, {
959
+ customPull,
960
+ isScope,
961
+ ...rest
962
+ }) {
963
+ const s = new Signal(nextValue, customPull);
964
+ s.pull = s.customPull || s.DEFAULT_PULL;
965
+ Object.assign(s, rest);
966
+ if (isScope) {
967
+ s.scope = s;
901
968
  }
902
- Signal.Pulling = downstream;
969
+ return s;
903
970
  }
904
- }
905
- function Signal_$$$_pullDeep() {
906
- /*----------------- 有上游节点,通过 dfs 重新计算结果 -----------------*/
907
- const signal = this;
908
- // 优化执行
909
- if (!(signal.state & DirtyState)) {
910
- return this.value;
971
+ DEFAULT_PULL() {
972
+ return this.nextValue;
911
973
  }
912
- dfs(signal, {
913
- isUp: true,
914
- begin: ({
915
- node
916
- }) => {
917
- // console.log('begin', node.id);
918
- /**
919
- * 不需要检查
920
- * 1. 正在查
921
- * 2. 干净
922
- * 3. 放弃 或者为 scope 节点
923
- */
924
- if (node.state & State.Check || !(node.state & DirtyState) || node.isAbort()) {
925
- return true;
974
+ /**
975
+ * 递归拉取负责建立以来链
976
+ */
977
+ pullRecurse(shouldLink = true) {
978
+ var _a;
979
+ let downstream = Signal.Pulling;
980
+ if (shouldLink && downstream) {
981
+ // 如果上游节点被 scope 管理了,解除管理
982
+ unTrackIsland(this);
983
+ Line.link(this, downstream);
984
+ }
985
+ try {
986
+ if (this.version === G.version) {
987
+ return this.value;
926
988
  }
927
- node.state |= State.Check;
928
- // 交给下游重新计算是否 引用外部节点
929
- node.state &= ~State.OutLink;
930
- },
931
- complete: ({
932
- node,
933
- notGoDeep: currentClean,
934
- walkedLine
935
- }) => {
936
- let noGoSibling = false;
937
- const last = walkedLine[walkedLine.length - 1];
938
- const downstream = last === null || last === void 0 ? void 0 : last.downstream;
939
- // 当前正在检查,生成检查屏障,同时避免重新标记 和
940
- if (currentClean) ;
941
- // 当前节点需要重新计算
942
- else if (node.state & State.Dirty) {
943
- // 优化:源节点变化,直接让下游节点重新计算
944
- if (!node.recStart && node.value !== node.nextValue) {
945
- node.markDownStreamsDirty();
946
- node.state &= ~State.Dirty;
947
- node.state &= ~State.Check;
948
- return;
989
+ this.state &= ~State.OutLink;
990
+ // pullShallow 前重置 recEnd,让子 getter 重构订阅链表
991
+ this.recEnd = undefined;
992
+ Signal.Pulling = this;
993
+ const v = this.pull();
994
+ // 如果使用了 DEFAULT_PULL,处理一次 set 的取值后,替换回 customPull,如果有的话
995
+ this.pull = this.customPull || this.DEFAULT_PULL;
996
+ this.value = v;
997
+ // 依赖上游的 版本号
998
+ this.version = G.version;
999
+ // if (this.value !== v) {
1000
+ // }
1001
+ return this.value;
1002
+ } catch (error) {
1003
+ console.error('计算属性报错这次不触发,后续状态可能出错', error);
1004
+ return this.value;
1005
+ } finally {
1006
+ // getter 执行完成时上游 getter 通过 link,完成对下游 recLines 的更新
1007
+ const toDel = (_a = this.recEnd) === null || _a === void 0 ? void 0 : _a.nextRecLine;
1008
+ unlinkRecWithScope(toDel);
1009
+ if (shouldLink && downstream) {
1010
+ // 用于 scope 指示哪些节点依赖 scope 外部
1011
+ markOutLink(this, downstream);
1012
+ }
1013
+ Signal.Pulling = downstream;
1014
+ }
1015
+ }
1016
+ pullDeep() {
1017
+ /*----------------- 有上游节点,通过 dfs 重新计算结果 -----------------*/
1018
+ const signal = this;
1019
+ // 优化执行
1020
+ if (!(signal.state & DirtyState)) {
1021
+ return this.value;
1022
+ }
1023
+ dfs(signal, {
1024
+ isUp: true,
1025
+ begin: ({
1026
+ node
1027
+ }) => {
1028
+ // console.log('begin', node.id);
1029
+ /**
1030
+ * 不需要检查
1031
+ * 1. 正在查
1032
+ * 2. 干净
1033
+ * 3. 放弃 或者为 scope 节点
1034
+ */
1035
+ if (node.state & State.Check || !(node.state & DirtyState) || node.isAbort()) {
1036
+ return true;
949
1037
  }
950
- // 预检数据
951
- else {
952
- const prevPulling = Signal.Pulling;
953
- Signal.Pulling = downstream;
954
- const prevValue = node.value;
955
- // 递归转用递归拉取,且不需要重建 link 因为dfs的前提就是上游节点依赖于 本节点
956
- node.pullRecurse(false);
957
- // dirty 传播, 由于本节点值已被计算出,因此消除 dirty
958
- if (prevValue !== node.value) {
1038
+ node.state |= State.Check;
1039
+ // 交给下游重新计算是否 引用外部节点
1040
+ node.state &= ~State.OutLink;
1041
+ },
1042
+ complete: ({
1043
+ node,
1044
+ notGoDeep: currentClean,
1045
+ walkedLine
1046
+ }) => {
1047
+ let noGoSibling = false;
1048
+ const last = walkedLine[walkedLine.length - 1];
1049
+ const downstream = last === null || last === void 0 ? void 0 : last.downstream;
1050
+ // 当前正在检查,生成检查屏障,同时避免重新标记 和
1051
+ if (currentClean) ;
1052
+ // 当前节点需要重新计算
1053
+ else if (node.state & State.Dirty) {
1054
+ // 优化:源节点变化,直接让下游节点重新计算
1055
+ if (!node.recStart && node.value !== node.nextValue) {
959
1056
  node.markDownStreamsDirty();
1057
+ node.state &= ~State.Dirty;
1058
+ node.state &= ~State.Check;
1059
+ return;
1060
+ }
1061
+ // 预检数据
1062
+ else {
1063
+ const prevPulling = Signal.Pulling;
1064
+ Signal.Pulling = downstream;
1065
+ const prevValue = node.value;
1066
+ // 递归转用递归拉取,且不需要重建 link 因为dfs的前提就是上游节点依赖于 本节点
1067
+ node.pullRecurse(false);
1068
+ // dirty 传播, 由于本节点值已被计算出,因此消除 dirty
1069
+ if (prevValue !== node.value) {
1070
+ node.markDownStreamsDirty();
1071
+ }
1072
+ node.state &= ~State.Dirty;
1073
+ Signal.Pulling = prevPulling;
1074
+ // 立刻返回父节点重新计算
1075
+ noGoSibling = true;
960
1076
  }
961
- node.state &= ~State.Dirty;
962
- Signal.Pulling = prevPulling;
963
- // 立刻返回父节点重新计算
964
- noGoSibling = true;
965
1077
  }
1078
+ // 没被上游节点标记为 Dirty,说明是干净的
1079
+ else if (node.state & State.Unknown) {
1080
+ node.state &= ~State.Unknown;
1081
+ }
1082
+ node.version = G.version;
1083
+ node.state &= ~State.Check;
1084
+ if (downstream) {
1085
+ markOutLink(node, downstream);
1086
+ }
1087
+ return noGoSibling;
966
1088
  }
967
- // 没被上游节点标记为 Dirty,说明是干净的
968
- else if (node.state & State.Unknown) {
969
- node.state &= ~State.Unknown;
970
- }
971
- node.version = G.version;
972
- node.state &= ~State.Check;
973
- if (downstream) {
974
- markOutLink(node, downstream);
975
- }
976
- return noGoSibling;
977
- }
978
- });
979
- return this.value;
980
- }
981
- function Signal_$$$_get() {
982
- if (this.isAbort()) {
1089
+ });
983
1090
  return this.value;
984
1091
  }
985
- // 没有上游节点,应该通过递归重新建立
986
- if (!this.recStart) {
987
- return this.pullRecurse(true);
1092
+ get() {
1093
+ if (this.isAbort()) {
1094
+ return this.value;
1095
+ }
1096
+ // 没有上游节点,应该通过递归重新建立
1097
+ if (!this.recStart) {
1098
+ return this.pullRecurse(true);
1099
+ }
1100
+ // 有上游节点则采用 dfs 直接遍历,查看情况
1101
+ return this.pullDeep();
988
1102
  }
989
- // 有上游节点则采用 dfs 直接遍历,查看情况
990
- return this.pullDeep();
991
- }
992
- function Signal_$$$_markDownStreamsDirty() {
993
- let point = this.emitStart;
994
- while (point != null) {
995
- const downstream = point.downstream;
996
- downstream.state |= State.Dirty;
997
- downstream.state &= ~State.Unknown;
998
- point = point.nextEmitLine;
1103
+ markDownStreamsDirty() {
1104
+ let point = this.emitStart;
1105
+ while (point != null) {
1106
+ const downstream = point.downstream;
1107
+ downstream.state |= State.Dirty;
1108
+ downstream.state &= ~State.Unknown;
1109
+ point = point.nextEmitLine;
1110
+ }
999
1111
  }
1000
- }
1001
- function Signal_$$$_set(v) {
1002
- if (this.isAbort() || this.nextValue === v) {
1003
- return;
1112
+ set(v) {
1113
+ if (this.isAbort() || this.nextValue === v) {
1114
+ return;
1115
+ }
1116
+ this.nextValue = v;
1117
+ // 手动设值后,采用默认拉取,能拉取到设置的值,拉取完成后在替换回 customPull
1118
+ this.pull = this.DEFAULT_PULL;
1119
+ G.version++;
1120
+ markDeep(this);
1004
1121
  }
1005
- this.nextValue = v;
1006
- // 手动设值后,采用默认拉取,能拉取到设置的值,拉取完成后在替换回 customPull
1007
- this.pull = this.DEFAULT_PULL;
1008
- G.version++;
1009
- markDeep(this);
1010
- }
1011
- function Signal_$$$_run(...args) {
1012
- if (args.length) {
1013
- return this.set(args[0]);
1122
+ run(...args) {
1123
+ if (args.length) {
1124
+ return this.set(args[0]);
1125
+ }
1126
+ return this.get();
1127
+ }
1128
+ runIfDirty() {
1129
+ this.state & (State.Unknown | State.Dirty) && this.run();
1130
+ }
1131
+ isAbort() {
1132
+ return (
1133
+ // scope 被取消
1134
+ this.scope && this.scope.state & State.ScopeAbort ||
1135
+ // 是 scope 节点,且处于 ready 状态,不需要重复执行
1136
+ this === this.scope && this.state & ScopeExecuted
1137
+ );
1014
1138
  }
1015
- return this.get();
1016
- }
1017
- function Signal_$$$_runIfDirty() {
1018
- this.state & (State.Unknown | State.Dirty) && this.run();
1019
- }
1020
- function Signal_$$$_isAbort() {
1021
- return (
1022
- // scope 被取消
1023
- this.scope && this.scope.state & State.ScopeAbort ||
1024
- // 是 scope 节点,且处于 ready 状态,不需要重复执行
1025
- this === this.scope && this.state & (State.ScopeAbort | State.ScopeReady)
1026
- );
1027
1139
  }
1028
1140
  Signal.Pulling = null;
1029
1141
  function runWithPulling(fn, signal) {
@@ -1108,5 +1220,50 @@ const customSignal = opt => {
1108
1220
  return s;
1109
1221
  };
1110
1222
  };
1223
+ // const globalSignal = $(10);
1224
+ // let outerA, outerB, innerX, innerY, outerResult, innerResult, innerDispose;
1225
+ // const outerDispose = scope(() => {
1226
+ // outerA = $(1);
1227
+ // outerB = $(2);
1228
+ // // 外层计算信号
1229
+ // outerResult = $(() => {
1230
+ // const res = globalSignal.v + outerA.v + outerB.v;
1231
+ // return res;
1232
+ // });
1233
+ // innerDispose = scope(() => {
1234
+ // innerX = $(3);
1235
+ // innerY = $(4);
1236
+ // // 内层计算信号,既依赖内层也依赖外层信号
1237
+ // innerResult = $(() => {
1238
+ // const res = outerA.v + innerX.v + innerY.v;
1239
+ // return res;
1240
+ // });
1241
+ // // 访问信号以建立依赖关系
1242
+ // innerResult();
1243
+ // });
1244
+ // // 访问外层信号
1245
+ // outerResult();
1246
+ // // 将内层dispose函数绑定到外层scope,这样可以测试嵌套行为
1247
+ // (outerResult as any).innerDispose = innerDispose;
1248
+ // });
1249
+ // outerA.v = 5;
1250
+ // innerX.v = 6;
1251
+ // globalSignal.v = 20;
1252
+ // // 先释放内层scope
1253
+ // innerDispose();
1254
+ // innerX.v = 7;
1255
+ // outerA.v = 8;
1256
+ // outerDispose();
1257
+ // evt.on('one', ({ index }) => {
1258
+ // switch (index) {
1259
+ // case 0:
1260
+ // console.log({ index });
1261
+ // break;
1262
+ // case 1:
1263
+ // console.log({ index });
1264
+ // default:
1265
+ // break;
1266
+ // }
1267
+ // });
1111
1268
 
1112
- export { $, Scheduler, customSignal, scheduler, scope, watch };
1269
+ export { $, Scheduler, TaskQueue, customSignal, scheduler, scope, watch };