aoye 0.0.2 → 0.0.4

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