cb9d836227
集中保留原版权声明,移除文件头检查和全局测试忽略规则。验证:全量单测、受影响用例复测及静态检查通过。
89 lines
2.5 KiB
JavaScript
89 lines
2.5 KiB
JavaScript
import assert from 'node:assert/strict';
|
|
import React from 'react';
|
|
|
|
// A deterministic controller harness, not a replacement for React's DOM scheduler.
|
|
export function createHookRuntime() {
|
|
const slots = [];
|
|
let cursor = 0;
|
|
let dirty = false;
|
|
let renderCurrent;
|
|
let output;
|
|
let pending = [];
|
|
const changed = (before, after) =>
|
|
!before ||
|
|
!after ||
|
|
before.length !== after.length ||
|
|
after.some((v, i) => !Object.is(v, before[i]));
|
|
const react = {
|
|
...React,
|
|
useState(initial) {
|
|
const index = cursor++;
|
|
if (!slots[index]) {
|
|
const slot = {
|
|
value: typeof initial === 'function' ? initial() : initial,
|
|
};
|
|
slot.set = (next) => {
|
|
const value = typeof next === 'function' ? next(slot.value) : next;
|
|
if (!Object.is(value, slot.value)) {
|
|
slot.value = value;
|
|
dirty = true;
|
|
}
|
|
};
|
|
slots[index] = slot;
|
|
}
|
|
return [slots[index].value, slots[index].set];
|
|
},
|
|
useRef(initial) {
|
|
const index = cursor++;
|
|
slots[index] ??= { current: initial };
|
|
return slots[index];
|
|
},
|
|
useMemo(factory, dependencies) {
|
|
const index = cursor++;
|
|
if (changed(slots[index]?.dependencies, dependencies))
|
|
slots[index] = { value: factory(), dependencies };
|
|
return slots[index].value;
|
|
},
|
|
useCallback(callback, dependencies) {
|
|
return react.useMemo(() => callback, dependencies);
|
|
},
|
|
useEffect(callback, dependencies) {
|
|
const index = cursor++;
|
|
if (changed(slots[index]?.dependencies, dependencies))
|
|
pending.push({ index, callback, dependencies });
|
|
},
|
|
};
|
|
react.useLayoutEffect = react.useEffect;
|
|
const runtime = {
|
|
react,
|
|
render(component, props = {}) {
|
|
cursor = 0;
|
|
pending = [];
|
|
dirty = false;
|
|
renderCurrent = () => runtime.render(component, props);
|
|
output = component(props);
|
|
return output;
|
|
},
|
|
commit() {
|
|
const effects = pending;
|
|
pending = [];
|
|
for (const { index, callback, dependencies } of effects) {
|
|
slots[index]?.cleanup?.();
|
|
slots[index] = { dependencies, cleanup: callback() };
|
|
}
|
|
},
|
|
flush() {
|
|
for (let i = 0; ; i++) {
|
|
assert.ok(i < 20, 'Effects must settle without a render/request loop');
|
|
runtime.commit();
|
|
if (!dirty) return output;
|
|
renderCurrent();
|
|
}
|
|
},
|
|
unmount() {
|
|
for (const slot of slots) slot?.cleanup?.();
|
|
},
|
|
};
|
|
return runtime;
|
|
}
|