parent
70a421d5e9
commit
6589b44618
|
@ -0,0 +1,558 @@
|
|||
import Inula, { computed, createRef, reactive, watchReactive } from '../../../../src/index';
|
||||
import { template as _$template, insert as _$insert, setAttribute as _$setAttribute } from '../../../../src/no-vnode/dom';
|
||||
import { createComponent as _$createComponent, render } from '../../../../src/no-vnode/core';
|
||||
import { delegateEvents as _$delegateEvents, addEventListener as _$addEventListener } from '../../../../src/no-vnode/event';
|
||||
|
||||
import { Show } from '../../../../src/no-vnode/components/Show';
|
||||
import { For } from '../../../../src/no-vnode/components/For';
|
||||
|
||||
describe('测试 no-vnode', () => {
|
||||
it('简单的使用signal', () => {
|
||||
/**
|
||||
* 源码:
|
||||
* const CountingComponent = () => {
|
||||
* const [count, setCount] = useSignal(0);
|
||||
*
|
||||
* return <div id="count">Count value is {count()}.</div>;
|
||||
* };
|
||||
*
|
||||
* render(() => <CountingComponent />, container);
|
||||
*/
|
||||
|
||||
let g_count;
|
||||
|
||||
// 编译后:
|
||||
const _tmpl$ = /*#__PURE__*/ _$template(`<div id="count">Count value is <!>.`);
|
||||
const CountingComponent = () => {
|
||||
const count = reactive(0);
|
||||
g_count = count;
|
||||
|
||||
return (() => {
|
||||
const _el$ = _tmpl$(),
|
||||
_el$2 = _el$.firstChild,
|
||||
_el$4 = _el$2.nextSibling,
|
||||
_el$3 = _el$4.nextSibling;
|
||||
_$insert(_el$, count, _el$4);
|
||||
return _el$;
|
||||
})();
|
||||
};
|
||||
render(() => _$createComponent(CountingComponent, {}), container);
|
||||
|
||||
_$delegateEvents(['click']);
|
||||
|
||||
expect(container.querySelector('#count').innerHTML).toEqual('Count value is 0<!---->.');
|
||||
|
||||
g_count.set(c => c + 1);
|
||||
|
||||
expect(container.querySelector('#count').innerHTML).toEqual('Count value is 1<!---->.');
|
||||
});
|
||||
|
||||
it('return数组,click事件', () => {
|
||||
/**
|
||||
* 源码:
|
||||
* const CountingComponent = () => {
|
||||
* const [count, setCount] = createSignal(0);
|
||||
* const add = () => {
|
||||
* setCount((c) => c + 1);
|
||||
* }
|
||||
* return <>
|
||||
* <div id="count">Count value is {count()}.</div>
|
||||
* <div><button onClick={add}>add</button></div>
|
||||
* </>;
|
||||
* };
|
||||
*/
|
||||
|
||||
// 编译后:
|
||||
const _tmpl$ = /*#__PURE__*/ _$template(`<div id="count">Count value is <!>.`),
|
||||
_tmpl$2 = /*#__PURE__*/ _$template(`<div><button id="btn">add`);
|
||||
const CountingComponent = () => {
|
||||
const count = reactive(0);
|
||||
const add = () => {
|
||||
count.set(c => c + 1);
|
||||
};
|
||||
return [
|
||||
(() => {
|
||||
const _el$ = _tmpl$(),
|
||||
_el$2 = _el$.firstChild,
|
||||
_el$4 = _el$2.nextSibling,
|
||||
_el$3 = _el$4.nextSibling;
|
||||
_$insert(_el$, count, _el$4);
|
||||
return _el$;
|
||||
})(),
|
||||
(() => {
|
||||
const _el$5 = _tmpl$2(),
|
||||
_el$6 = _el$5.firstChild;
|
||||
_el$6.$$click = add;
|
||||
return _el$5;
|
||||
})(),
|
||||
];
|
||||
};
|
||||
render(() => _$createComponent(CountingComponent, {}), container);
|
||||
|
||||
_$delegateEvents(['click']);
|
||||
|
||||
container.querySelector('#btn').click();
|
||||
|
||||
expect(container.querySelector('#count').innerHTML).toEqual('Count value is 1<!---->.');
|
||||
});
|
||||
|
||||
it('return 自定义组件', () => {
|
||||
/**
|
||||
* 源码:
|
||||
* const CountValue = (props) => {
|
||||
* return <div>Count value is {props.count} .</div>;
|
||||
* }
|
||||
*
|
||||
* const CountingComponent = () => {
|
||||
* const [count, setCount] = createSignal(0);
|
||||
* const add = () => {
|
||||
* setCount((c) => c + 1);
|
||||
* }
|
||||
*
|
||||
* return <div>
|
||||
* <CountValue count={count} />
|
||||
* <div><button onClick={add}>add</button></div>
|
||||
* </div>;
|
||||
* };
|
||||
*
|
||||
* render(() => <CountingComponent />, document.getElementById("app"));
|
||||
*/
|
||||
|
||||
// 编译后:
|
||||
const _tmpl$ = /*#__PURE__*/ _$template(`<div id="count">Count value is <!>.`),
|
||||
_tmpl$2 = /*#__PURE__*/ _$template(`<div><div><button id="btn">add`);
|
||||
const CountValue = props => {
|
||||
return (() => {
|
||||
const _el$ = _tmpl$(),
|
||||
_el$2 = _el$.firstChild,
|
||||
_el$4 = _el$2.nextSibling,
|
||||
_el$3 = _el$4.nextSibling;
|
||||
_$insert(_el$, () => props.count, _el$4);
|
||||
return _el$;
|
||||
})();
|
||||
};
|
||||
const CountingComponent = () => {
|
||||
const count = reactive(0);
|
||||
const add = () => {
|
||||
count.set(c => c + 1);
|
||||
};
|
||||
return (() => {
|
||||
const _el$5 = _tmpl$2(),
|
||||
_el$6 = _el$5.firstChild,
|
||||
_el$7 = _el$6.firstChild;
|
||||
_$insert(
|
||||
_el$5,
|
||||
_$createComponent(CountValue, {
|
||||
count: count,
|
||||
}),
|
||||
_el$6
|
||||
);
|
||||
_el$7.$$click = add;
|
||||
return _el$5;
|
||||
})();
|
||||
};
|
||||
render(() => _$createComponent(CountingComponent, {}), container);
|
||||
_$delegateEvents(['click']);
|
||||
|
||||
container.querySelector('#btn').click();
|
||||
|
||||
expect(container.querySelector('#count').innerHTML).toEqual('Count value is 1<!---->.');
|
||||
});
|
||||
|
||||
it('使用Show组件', () => {
|
||||
/**
|
||||
* 源码:
|
||||
* const CountValue = (props) => {
|
||||
* return <div id="count">Count value is {props.count()}.</div>;
|
||||
* }
|
||||
*
|
||||
* const CountingComponent = () => {
|
||||
* const [count, setCount] = createSignal(0);
|
||||
* const add = () => {
|
||||
* setCount((c) => c + 1);
|
||||
* }
|
||||
*
|
||||
* return <div>
|
||||
* <Show when={count() > 0} fallback={<CountValue count={999} />}>
|
||||
* <CountValue count={count} />
|
||||
* </Show>
|
||||
* <div><button id="btn" onClick={add}>add</button></div>
|
||||
* </div>;
|
||||
* };
|
||||
*
|
||||
* render(() => <CountingComponent />, document.getElementById("app"));
|
||||
*/
|
||||
|
||||
// 编译后:
|
||||
const _tmpl$ = /*#__PURE__*/ _$template(`<div id="count">Count value is <!>.`),
|
||||
_tmpl$2 = /*#__PURE__*/ _$template(`<div><div><button id="btn">add`);
|
||||
const CountValue = props => {
|
||||
return (() => {
|
||||
const _el$ = _tmpl$(),
|
||||
_el$2 = _el$.firstChild,
|
||||
_el$4 = _el$2.nextSibling,
|
||||
_el$3 = _el$4.nextSibling;
|
||||
_$insert(_el$, () => props.count, _el$4);
|
||||
return _el$;
|
||||
})();
|
||||
};
|
||||
const CountingComponent = () => {
|
||||
const count = reactive(0);
|
||||
const add = () => {
|
||||
count.set(c => c + 1);
|
||||
};
|
||||
return (() => {
|
||||
const _el$5 = _tmpl$2(),
|
||||
_el$6 = _el$5.firstChild,
|
||||
_el$7 = _el$6.firstChild;
|
||||
_$insert(
|
||||
_el$5,
|
||||
_$createComponent(Show, {
|
||||
get if() {
|
||||
return computed(() => count.get() > 0);
|
||||
},
|
||||
get else() {
|
||||
return _$createComponent(CountValue, {
|
||||
count: 999,
|
||||
});
|
||||
},
|
||||
get children() {
|
||||
return _$createComponent(CountValue, {
|
||||
count: count,
|
||||
});
|
||||
},
|
||||
}),
|
||||
_el$6
|
||||
);
|
||||
_el$7.$$click = add;
|
||||
return _el$5;
|
||||
})();
|
||||
};
|
||||
render(() => _$createComponent(CountingComponent, {}), container);
|
||||
_$delegateEvents(['click']);
|
||||
|
||||
expect(container.querySelector('#count').innerHTML).toEqual('Count value is 999<!---->.');
|
||||
|
||||
container.querySelector('#btn').click();
|
||||
|
||||
expect(container.querySelector('#count').innerHTML).toEqual('Count value is 1<!---->.');
|
||||
});
|
||||
|
||||
it('使用For组件', () => {
|
||||
/**
|
||||
* 源码:
|
||||
* const Todo = (props) => {
|
||||
* return <div>Count value is {props.todo.title}.</div>;
|
||||
* }
|
||||
*
|
||||
* const CountingComponent = () => {
|
||||
* const [state, setState] = createStore({
|
||||
* counter: 2,
|
||||
* todoList: [
|
||||
* { id: 23, title: 'Birds' },
|
||||
* { id: 27, title: 'Fish' }
|
||||
* ]
|
||||
* });
|
||||
*
|
||||
* const add = () => {
|
||||
* setState('todoList', () => {
|
||||
* return [
|
||||
* { id: 23, title: 'Birds' },
|
||||
* { id: 27, title: 'Fish' },
|
||||
* { id: 27, title: 'Cat' }
|
||||
* ];
|
||||
* });
|
||||
* }
|
||||
*
|
||||
* const push = () => {
|
||||
* state.todoList.push({
|
||||
* id: 27,
|
||||
* title: 'Pig',
|
||||
* },);
|
||||
* };
|
||||
*
|
||||
* return <div>
|
||||
* <div id="todos">
|
||||
* <For each={state.todoList}>
|
||||
* {todo => <><Todo todo={todo} /><Todo todo={todo} /></>}
|
||||
* </For>
|
||||
* </div>
|
||||
* <div><button id="btn" onClick={add}>add</button></div>
|
||||
* <div><button id="btn-push" onClick={push}>push</button></div>
|
||||
* </div>;
|
||||
* };
|
||||
*
|
||||
* render(() => <CountingComponent />, document.getElementById("app"));
|
||||
*/
|
||||
|
||||
// 编译后:
|
||||
const _tmpl$ = /*#__PURE__*/_$template(`<div>Count value is <!>.`),
|
||||
_tmpl$2 = /*#__PURE__*/_$template(`<div><div id="todos"></div><div><button id="btn">add</button></div><div><button id="btn-push">push`);
|
||||
const Todo = props => {
|
||||
return (() => {
|
||||
const _el$ = _tmpl$(),
|
||||
_el$2 = _el$.firstChild,
|
||||
_el$4 = _el$2.nextSibling,
|
||||
_el$3 = _el$4.nextSibling;
|
||||
_$insert(_el$, () => props.todo.title, _el$4);
|
||||
return _el$;
|
||||
})();
|
||||
};
|
||||
const CountingComponent = () => {
|
||||
const state = reactive({
|
||||
counter: 2,
|
||||
todoList: [
|
||||
{
|
||||
id: 23,
|
||||
title: 'Birds',
|
||||
},
|
||||
{
|
||||
id: 27,
|
||||
title: 'Fish',
|
||||
},
|
||||
],
|
||||
});
|
||||
const add = () => {
|
||||
state.todoList.set(() => {
|
||||
return [
|
||||
{
|
||||
id: 23,
|
||||
title: 'Birds',
|
||||
},
|
||||
{
|
||||
id: 27,
|
||||
title: 'Fish',
|
||||
},
|
||||
{
|
||||
id: 27,
|
||||
title: 'Cat',
|
||||
},
|
||||
];
|
||||
});
|
||||
};
|
||||
|
||||
const push = () => {
|
||||
state.todoList.push({
|
||||
id: 27,
|
||||
title: 'Pig',
|
||||
},);
|
||||
};
|
||||
return (() => {
|
||||
const _el$5 = _tmpl$2(),
|
||||
_el$6 = _el$5.firstChild,
|
||||
_el$7 = _el$6.nextSibling,
|
||||
_el$8 = _el$7.firstChild,
|
||||
_el$9 = _el$7.nextSibling,
|
||||
_el$10 = _el$9.firstChild;
|
||||
_$insert(
|
||||
_el$6,
|
||||
_$createComponent(For, {
|
||||
get each() {
|
||||
return state.todoList;
|
||||
},
|
||||
children: todo => [
|
||||
_$createComponent(Todo, {
|
||||
todo: todo,
|
||||
}),
|
||||
_$createComponent(Todo, {
|
||||
todo: todo,
|
||||
}),
|
||||
],
|
||||
})
|
||||
);
|
||||
_el$8.$$click = add;
|
||||
_el$10.$$click = push;
|
||||
return _el$5;
|
||||
})();
|
||||
};
|
||||
render(() => _$createComponent(CountingComponent, {}), container);
|
||||
_$delegateEvents(['click']);
|
||||
|
||||
expect(container.querySelector('#todos').innerHTML).toEqual(
|
||||
'<div>Count value is Birds<!---->.</div><div>Count value is Birds<!---->.</div><div>Count value is Fish<!---->.</div><div>Count value is Fish<!---->.</div>'
|
||||
);
|
||||
|
||||
container.querySelector('#btn').click();
|
||||
|
||||
expect(container.querySelector('#todos').innerHTML).toEqual(
|
||||
'<div>Count value is Birds<!---->.</div><div>Count value is Birds<!---->.</div><div>Count value is Fish<!---->.</div><div>Count value is Fish<!---->.</div><div>Count value is Cat<!---->.</div><div>Count value is Cat<!---->.</div>'
|
||||
);
|
||||
|
||||
container.querySelector('#btn-push').click();
|
||||
|
||||
expect(container.querySelector('#todos').innerHTML).toEqual(
|
||||
'<div>Count value is Birds<!---->.</div><div>Count value is Birds<!---->.</div><div>Count value is Fish<!---->.</div><div>Count value is Fish<!---->.</div><div>Count value is Cat<!---->.</div><div>Count value is Cat<!---->.</div><div>Count value is Pig<!---->.</div><div>Count value is Pig<!---->.</div>'
|
||||
);
|
||||
});
|
||||
|
||||
it('使用effect, setAttribute, addEventListener', () => {
|
||||
/**
|
||||
* 源码:
|
||||
* const A = ['pretty', 'large', 'big', 'small', 'tall', 'short', 'long', 'handsome', 'plain', 'quaint', 'clean',
|
||||
* 'elegant', 'easy', 'angry', 'crazy', 'helpful', 'mushy', 'odd', 'unsightly', 'adorable', 'important', 'inexpensive',
|
||||
* 'cheap', 'expensive', 'fancy'];
|
||||
*
|
||||
* const random = (max: any) => Math.round(Math.random() * 1000) % max;
|
||||
*
|
||||
* let nextId = 1;
|
||||
*
|
||||
* function buildData(count: number) {
|
||||
* let data = new Array(count);
|
||||
*
|
||||
* for (let i = 0; i < count; i++) {
|
||||
* data[i] = {
|
||||
* id: nextId++,
|
||||
* label: `${A[random(A.length)]}`,
|
||||
* }
|
||||
* }
|
||||
* return data;
|
||||
* }
|
||||
*
|
||||
* const Row = (props) => {
|
||||
* const selected = createMemo(() => {
|
||||
* return props.item.selected ? 'danger' : '';
|
||||
* });
|
||||
*
|
||||
* return (
|
||||
* <tr class={selected()}>
|
||||
* <td class="col-md-1">{props.item.label}</td>
|
||||
* </tr>
|
||||
* )
|
||||
* };
|
||||
*
|
||||
* const RowList = (props) => {
|
||||
* return <For each={props.list}>
|
||||
* {(item) => <Row item={item}/>}
|
||||
* </For>;
|
||||
* };
|
||||
*
|
||||
* const Button = (props) => (
|
||||
* <div class="col-sm-6">
|
||||
* <button type="button" id={props.id} onClick={props.cb}>{props.title}</button>
|
||||
* </div>
|
||||
* );
|
||||
*
|
||||
* const Main = () => {
|
||||
* const [state, setState] = createStore({data: [{id: 1, label: '111', selected: false}, {id: 2, label: '222', selected: false}], num: 2});
|
||||
*
|
||||
* function run() {
|
||||
* setState('data', buildData(5));
|
||||
* }
|
||||
*
|
||||
* return (
|
||||
* <div>
|
||||
* <div>
|
||||
* <div>
|
||||
* <div><h1>Horizon-reactive-novnode</h1></div>
|
||||
* <div>
|
||||
* <div>
|
||||
* <Button id="run" title="Create 1,000 rows" cb={run}/>
|
||||
* </div>
|
||||
* </div>
|
||||
* </div>
|
||||
* </div>
|
||||
* <table>
|
||||
* <tbody id="tbody"><RowList list={state.data}/></tbody>
|
||||
* </table>
|
||||
* </div>
|
||||
* );
|
||||
* };
|
||||
*
|
||||
* render(() => <Main />, document.getElementById("app"));
|
||||
*/
|
||||
|
||||
// 编译后:
|
||||
const _tmpl$ = /*#__PURE__*/_$template(`<tr><td class="col-md-1">`),
|
||||
_tmpl$2 = /*#__PURE__*/_$template(`<div class="col-sm-6"><button type="button">`),
|
||||
_tmpl$3 = /*#__PURE__*/_$template(`<div><div><div><div><h1>Horizon-reactive-novnode</h1></div><div><div></div></div></div></div><table><tbody id="tbody">`);
|
||||
const A = ['pretty', 'large', 'big', 'small', 'tall', 'short', 'long', 'handsome', 'plain', 'quaint', 'clean', 'elegant', 'easy', 'angry', 'crazy', 'helpful', 'mushy', 'odd', 'unsightly', 'adorable', 'important', 'inexpensive', 'cheap', 'expensive', 'fancy'];
|
||||
const random = max => Math.round(Math.random() * 1000) % max;
|
||||
let nextId = 1;
|
||||
function buildData(count) {
|
||||
let data = new Array(count);
|
||||
for (let i = 0; i < count; i++) {
|
||||
data[i] = {
|
||||
id: nextId++,
|
||||
label: `${A[random(A.length)]}`
|
||||
};
|
||||
}
|
||||
return data;
|
||||
}
|
||||
const Row = props => {
|
||||
const selected = computed(() => {
|
||||
return props.item.selected.get() ? "danger" : "";
|
||||
});
|
||||
|
||||
return (() => {
|
||||
const _el$ = _tmpl$(),
|
||||
_el$2 = _el$.firstChild;
|
||||
_$insert(_el$2, () => props.item.label);
|
||||
return _el$;
|
||||
})();
|
||||
};
|
||||
const RowList = props => {
|
||||
return _$createComponent(For, {
|
||||
get each() {
|
||||
return props.list;
|
||||
},
|
||||
children: item => _$createComponent(Row, {
|
||||
item: item
|
||||
})
|
||||
});
|
||||
};
|
||||
const Button = props => (() => {
|
||||
const _el$3 = _tmpl$2(),
|
||||
_el$4 = _el$3.firstChild;
|
||||
_$addEventListener(_el$4, "click", props.cb, true);
|
||||
_$insert(_el$4, () => props.title);
|
||||
watchReactive(() => _$setAttribute(_el$4, "id", props.id));
|
||||
return _el$3;
|
||||
})();
|
||||
const Main = () => {
|
||||
const state = reactive({
|
||||
list: [{
|
||||
id: 1,
|
||||
label: '111'
|
||||
}, {
|
||||
id: 2,
|
||||
label: '222'
|
||||
}],
|
||||
num: 2
|
||||
});
|
||||
function run() {
|
||||
state.list.set(buildData(5));
|
||||
}
|
||||
return (() => {
|
||||
const _el$5 = _tmpl$3(),
|
||||
_el$6 = _el$5.firstChild,
|
||||
_el$7 = _el$6.firstChild,
|
||||
_el$8 = _el$7.firstChild,
|
||||
_el$9 = _el$8.nextSibling,
|
||||
_el$10 = _el$9.firstChild,
|
||||
_el$11 = _el$6.nextSibling,
|
||||
_el$12 = _el$11.firstChild;
|
||||
_$insert(_el$10, _$createComponent(Button, {
|
||||
id: "run",
|
||||
title: "Create 1,000 rows",
|
||||
cb: run
|
||||
}));
|
||||
_$insert(_el$12, _$createComponent(RowList, {
|
||||
get list() {
|
||||
return state.list;
|
||||
}
|
||||
}));
|
||||
return _el$5;
|
||||
})();
|
||||
};
|
||||
render(() => _$createComponent(Main, {}), container);
|
||||
_$delegateEvents(["click"]);
|
||||
|
||||
expect(container.querySelector('#tbody').innerHTML).toEqual(
|
||||
'<tr><td class="col-md-1">111</td></tr><tr><td class="col-md-1">222</td></tr>'
|
||||
);
|
||||
|
||||
container.querySelector('#run').click();
|
||||
|
||||
expect(container.querySelector('#tbody').children.length).toEqual(5);
|
||||
});
|
||||
});
|
|
@ -13,7 +13,7 @@
|
|||
* See the Mulan PSL v2 for more details.
|
||||
*/
|
||||
|
||||
import Inula, {createRef, render, useReactive, useState, Show} from '../../../src/index';
|
||||
import Inula, {createRef, render, useReactive, useState, useEffect, useRef, Show} from '../../../src/index';
|
||||
|
||||
describe('传统API和响应式API混合使用', () => {
|
||||
it('混合使用1', () => {
|
||||
|
@ -57,4 +57,133 @@ describe('传统API和响应式API混合使用', () => {
|
|||
});
|
||||
|
||||
|
||||
it('混合使用2', () => {
|
||||
// 全局变量来监听更新次数
|
||||
let guid = 0;
|
||||
|
||||
function ReactiveComponent() {
|
||||
const data = useReactive({ count: 0 });
|
||||
const [count, setCount] = useState(0);
|
||||
|
||||
const [dir, setDir] = useState("asc"); // 用于排序方向
|
||||
|
||||
function add() {
|
||||
data.count.set((c) => c + 1);
|
||||
}
|
||||
function addCount() {
|
||||
setCount((c) => c + 1);
|
||||
}
|
||||
|
||||
function toggleDir() {
|
||||
setDir((d) => (d === "asc" ? "desc" : "asc"));
|
||||
}
|
||||
|
||||
const vnode1 = <div id={"count"}>我是静态数据:{count}</div>;
|
||||
|
||||
const vnode2 = <div id={"rCount"}>我是响应数据:{data.count}</div>;
|
||||
|
||||
|
||||
return (
|
||||
<div>
|
||||
<button id={"reorder"} onClick={toggleDir}>点击切换顺序</button>
|
||||
<button id={"addRCount"} onClick={add}>点击++</button>
|
||||
<button id={"addCount"} onClick={addCount}>点击 count++</button>
|
||||
<div id={"content"}>
|
||||
{dir === "asc" ? [vnode1, vnode2] : [vnode2, vnode1]}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
render(<ReactiveComponent />, container);
|
||||
|
||||
// 点击按钮触发reactive count加1
|
||||
container.querySelector('#addRCount').click();
|
||||
expect(container.querySelector('#rCount').innerHTML).toEqual('我是响应数据:1');
|
||||
|
||||
// // 点击按钮触发count加1
|
||||
container.querySelector('#addCount').click();
|
||||
container.querySelector('#addCount').click();
|
||||
container.querySelector('#addCount').click();
|
||||
expect(container.querySelector('#count').innerHTML).toEqual('我是静态数据:3');
|
||||
expect(container.querySelector('#rCount').innerHTML).toEqual('我是响应数据:1');
|
||||
|
||||
expect(container.querySelector('#content').innerHTML).toEqual('<div id="count">我是静态数据:3</div><div id="rCount">我是响应数据:1</div>');
|
||||
|
||||
container.querySelector('#reorder').click();
|
||||
|
||||
expect(container.querySelector('#content').innerHTML).toEqual('<div id="rCount">我是响应数据:1</div><div id="count">我是静态数据:3</div>');
|
||||
|
||||
});
|
||||
|
||||
|
||||
it('混合使用3', () => {
|
||||
// 全局变量来监听更新次数
|
||||
let guid = 0;
|
||||
|
||||
function ReactiveComponent() {
|
||||
const renderCount = ++useRef(0).current;
|
||||
|
||||
const data = useReactive({ count: 0 });
|
||||
const [state, setState] = useState(0);
|
||||
|
||||
const showData = useReactive({show:true});
|
||||
|
||||
|
||||
// 切换显示
|
||||
function handleClick() {
|
||||
showData.show.set(s=> !s)
|
||||
}
|
||||
function add() {
|
||||
data.count.set((c) => c + 1);
|
||||
}
|
||||
function addState() {
|
||||
setState((c) => c + 1);
|
||||
}
|
||||
// 监听生命周期
|
||||
const mounted = useRef();
|
||||
|
||||
useEffect(() => {
|
||||
if (!mounted.current) {
|
||||
console.log("组件Mounted", guid++);
|
||||
mounted.current = true;
|
||||
} else {
|
||||
console.log("组件Updated", guid++);
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div>响应式数据:{data.count} </div>
|
||||
<div>传统state: {state}</div>
|
||||
<div>
|
||||
组件渲染次数renderCount:{renderCount} 或guid=:{guid}
|
||||
</div>
|
||||
<hr />
|
||||
<button onClick={handleClick}>点击切换显示</button>
|
||||
<button onClick={add}>点击++</button>
|
||||
<button onClick={addState}>点击state++</button>
|
||||
<hr />
|
||||
<div className="border">
|
||||
<Show if={showData.show}>
|
||||
<div>
|
||||
<h1>我会被隐藏</h1>
|
||||
<div> 我是响应式数据:{data.count}</div>
|
||||
</div>
|
||||
</Show>
|
||||
|
||||
{showData.show.get() && (
|
||||
<div>
|
||||
<h1>我会被隐藏</h1>
|
||||
<div> 我是响应式数据:{data.count}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
render(<ReactiveComponent />, container);
|
||||
|
||||
});
|
||||
});
|
||||
|
|
|
@ -0,0 +1,90 @@
|
|||
import { reactively as r } from '../../../../src/reactively/Reactively';
|
||||
import Inula, { createRef, render } from '../../../../src/index';
|
||||
|
||||
describe('测试 reactively', () => {
|
||||
it('two signals, one computed', () => {
|
||||
const a = r.reactive(7);
|
||||
const b = r.reactive(1);
|
||||
let callCount = 0;
|
||||
|
||||
const c = r.computed(() => {
|
||||
callCount++;
|
||||
return a.get() * b.get();
|
||||
});
|
||||
|
||||
r.watch(() => {
|
||||
console.log(a.get());
|
||||
});
|
||||
|
||||
a.set(2);
|
||||
expect(c.get()).toBe(2);
|
||||
|
||||
b.set(3);
|
||||
expect(c.get()).toBe(6);
|
||||
|
||||
expect(callCount).toBe(2);
|
||||
c.read();
|
||||
expect(callCount).toBe(2);
|
||||
});
|
||||
|
||||
it('using reactive with components', () => {
|
||||
let _color;
|
||||
const ref = createRef();
|
||||
const fn = jest.fn();
|
||||
const App = () => {
|
||||
const color = r.reactive('blue');
|
||||
_color = color;
|
||||
|
||||
color.set('red');
|
||||
|
||||
fn();
|
||||
|
||||
return <div ref={ref}>{color}</div>;
|
||||
};
|
||||
|
||||
render(<App />, container);
|
||||
expect(ref.current.innerHTML).toEqual('red');
|
||||
_color.set('blue');
|
||||
expect(_color.get()).toEqual('blue');
|
||||
expect(ref.current.innerHTML).toEqual('blue');
|
||||
expect(fn).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('reactive is a obj', () => {
|
||||
const rObj = r.reactive({ count: 1 });
|
||||
|
||||
const double = r.computed(() => {
|
||||
return 2 * rObj.count.get();
|
||||
});
|
||||
|
||||
r.watch(() => {
|
||||
console.log('count: ', rObj.count.get(), 'double: ', double.get());
|
||||
});
|
||||
|
||||
expect(double.read()).toBe(2);
|
||||
|
||||
rObj.count.set(2);
|
||||
|
||||
expect(rObj.count.read()).toBe(2);
|
||||
expect(double.read()).toBe(4);
|
||||
});
|
||||
|
||||
it('reactive is a array', () => {
|
||||
const rObj = r.reactive({
|
||||
items: [
|
||||
{ name: 'p1', id: 1 },
|
||||
{ name: 'p2', id: 2 },
|
||||
],
|
||||
});
|
||||
|
||||
const doubleId = r.computed(() => {
|
||||
return 2 * rObj.items[0].id.get();
|
||||
});
|
||||
|
||||
expect(doubleId.get()).toBe(2);
|
||||
|
||||
rObj.items.set([{ name: 'p11', id: 11 }]);
|
||||
|
||||
expect(doubleId.get()).toBe(22);
|
||||
});
|
||||
});
|
|
@ -0,0 +1,125 @@
|
|||
/*
|
||||
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
|
||||
*
|
||||
* openGauss is licensed under Mulan PSL v2.
|
||||
* You can use this software according to the terms and conditions of the Mulan PSL v2.
|
||||
* You may obtain a copy of Mulan PSL v2 at:
|
||||
*
|
||||
* http://license.coscl.org.cn/MulanPSL2
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
|
||||
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
|
||||
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
|
||||
* See the Mulan PSL v2 for more details.
|
||||
*/
|
||||
|
||||
import { JSXElement } from '../../renderer/Types';
|
||||
import { computed } from '../../reactive/Computed';
|
||||
import { untrack } from '../../reactive/RNode';
|
||||
|
||||
// TODO 需要优化为精细更新
|
||||
export function For<T>(props: { each: any; children?: (value: any, index: number) => JSXElement }) {
|
||||
let list = props.each,
|
||||
mapFn = props.children,
|
||||
items = [],
|
||||
mapped = [],
|
||||
disposers = [],
|
||||
len = 0;
|
||||
|
||||
return () => {
|
||||
let newItems = list.get() || [];
|
||||
|
||||
untrack(() => {
|
||||
let i, j;
|
||||
|
||||
let newLen = newItems.length,
|
||||
newIndices,
|
||||
newIndicesNext,
|
||||
temp,
|
||||
start,
|
||||
end,
|
||||
newEnd,
|
||||
item;
|
||||
|
||||
if (newLen === 0) {
|
||||
// 没新数据
|
||||
if (len !== 0) {
|
||||
disposers = [];
|
||||
items = [];
|
||||
mapped = [];
|
||||
len = 0;
|
||||
}
|
||||
} else if (len === 0) {
|
||||
// 上一次没有数据
|
||||
mapped = new Array(newLen);
|
||||
for (j = 0; j < newLen; j++) {
|
||||
items[j] = newItems[j];
|
||||
mapped[j] = mapFn(list[j]);
|
||||
}
|
||||
len = newLen;
|
||||
} else { // 都有数据
|
||||
// temp = new Array(newLen);
|
||||
//
|
||||
// // 从前往后,判断相等。但是这种前度比较经常是不生效的,比如数组的值相同,指针不一样
|
||||
// for (start = 0, end = Math.min(len, newLen); start < end && items[start] === newItems[start]; start++);
|
||||
//
|
||||
// // 从后往前
|
||||
// for (
|
||||
// end = len - 1, newEnd = newLen - 1;
|
||||
// end >= start && newEnd >= start && items[end] === newItems[newEnd]; // 值相等
|
||||
// end--, newEnd--
|
||||
// ) {
|
||||
// temp[newEnd] = mapped[end]; // 把dom取出来
|
||||
// }
|
||||
// // 从start -> newEnd就是不相等的
|
||||
//
|
||||
// newIndices = new Map();
|
||||
// newIndicesNext = new Array(newEnd + 1);
|
||||
// for (j = newEnd; j >= start; j--) {
|
||||
// item = newItems[j];
|
||||
// i = newIndices.get(item);
|
||||
// newIndicesNext[j] = i === undefined ? -1 : i; // item数据可能指针相同,重复。因为是倒序遍历,所以i就是相同数据下一个位置。
|
||||
// newIndices.set(item, j); // 新数据,放到map中
|
||||
// }
|
||||
//
|
||||
// // 遍历旧数据
|
||||
// for (i = start; i <= end; i++) {
|
||||
// item = items[i];
|
||||
// j = newIndices.get(item); // j 是相同数据的第一个
|
||||
// // 旧行数据,在新数据中存在,在j位置
|
||||
// if (j !== undefined && j !== -1) {
|
||||
// temp[j] = mapped[i]; // 把就dom放到新的j位置
|
||||
// j = newIndicesNext[j];
|
||||
// newIndices.set(item, j); // 修改map里面的位置,改为下一个
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // 往mapped中放入start - newLen的dom数据
|
||||
// for (j = start; j < newLen; j++) { // 按新数据来遍历
|
||||
// if (j in temp) {
|
||||
// mapped[j] = temp[j]; // 直接取旧的
|
||||
// } else {
|
||||
// mapped[j] = mapFn(list[j]); // 创建新的dom
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // 0 - start 数据没有变动
|
||||
// mapped = mapped.slice(0, (len = newLen)); // 如果newLen小于len,就截断
|
||||
// items = newItems.slice(0);
|
||||
|
||||
// 假设新旧相同行数据已经更新
|
||||
if (newLen > len) {
|
||||
for (let i = len; i < newLen; i++) {
|
||||
mapped[i] = mapFn(list[i]); // 创建新的dom
|
||||
}
|
||||
}
|
||||
|
||||
// 0 - start 数据没有变动
|
||||
mapped = mapped.slice(0, (len = newLen)); // 如果newLen小于len,就截断
|
||||
items = newItems.slice(0);
|
||||
}
|
||||
});
|
||||
|
||||
return mapped;
|
||||
};
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
/*
|
||||
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
|
||||
*
|
||||
* openGauss is licensed under Mulan PSL v2.
|
||||
* You can use this software according to the terms and conditions of the Mulan PSL v2.
|
||||
* You may obtain a copy of Mulan PSL v2 at:
|
||||
*
|
||||
* http://license.coscl.org.cn/MulanPSL2
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
|
||||
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
|
||||
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
|
||||
* See the Mulan PSL v2 for more details.
|
||||
*/
|
||||
|
||||
import { JSXElement } from '../../renderer/Types';
|
||||
import { Show as RShow } from '../../reactive/components/Show';
|
||||
|
||||
export function Show<T>(props: {
|
||||
if: any | (() => T);
|
||||
else?: any;
|
||||
children: JSXElement | (() => JSXElement);
|
||||
}): any {
|
||||
return () => RShow(props);
|
||||
}
|
|
@ -0,0 +1,91 @@
|
|||
/*
|
||||
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
|
||||
*
|
||||
* openGauss is licensed under Mulan PSL v2.
|
||||
* You can use this software according to the terms and conditions of the Mulan PSL v2.
|
||||
* You may obtain a copy of Mulan PSL v2 at:
|
||||
*
|
||||
* http://license.coscl.org.cn/MulanPSL2
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
|
||||
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
|
||||
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
|
||||
* See the Mulan PSL v2 for more details.
|
||||
*/
|
||||
|
||||
import { insert } from './dom';
|
||||
|
||||
export function createComponent<T>(Comp, props) {
|
||||
return Comp(props || ({} as T));
|
||||
}
|
||||
|
||||
export function render(code, element, init, options = {}) {
|
||||
let disposer;
|
||||
|
||||
createRoot(dispose => {
|
||||
disposer = dispose;
|
||||
if (element === document) {
|
||||
code();
|
||||
} else {
|
||||
insert(element, code(), element.firstChild ? null : undefined, init);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
disposer();
|
||||
element.textContent = '';
|
||||
};
|
||||
}
|
||||
|
||||
let Owner;
|
||||
let Listener;
|
||||
|
||||
function createRoot(fn) {
|
||||
const listener = Listener;
|
||||
const owner = Owner;
|
||||
const unowned = fn.length === 0;
|
||||
const current = owner;
|
||||
const root = {
|
||||
owned: null,
|
||||
cleanups: null,
|
||||
context: current ? current.context : null,
|
||||
owner: current,
|
||||
};
|
||||
const updateFn = () => {
|
||||
// fn(() => cleanNode(root));
|
||||
fn(() => {});
|
||||
};
|
||||
|
||||
Owner = root;
|
||||
Listener = null;
|
||||
try {
|
||||
return runUpdates(updateFn, true);
|
||||
} finally {
|
||||
Listener = listener;
|
||||
Owner = owner;
|
||||
}
|
||||
}
|
||||
|
||||
let Updates, Effects;
|
||||
let ExecCount = 0;
|
||||
|
||||
function runUpdates(fn, init) {
|
||||
if (Updates) return fn();
|
||||
let wait = false;
|
||||
if (!init) Updates = [];
|
||||
if (Effects) {
|
||||
wait = true;
|
||||
} else {
|
||||
Effects = [];
|
||||
}
|
||||
ExecCount++;
|
||||
// try {
|
||||
const res = fn();
|
||||
// completeUpdates(wait);
|
||||
return res;
|
||||
// } catch (err) {
|
||||
// if (!wait) Effects = null;
|
||||
// Updates = null;
|
||||
// // handleError(err);
|
||||
// }
|
||||
}
|
|
@ -0,0 +1,295 @@
|
|||
/*
|
||||
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
|
||||
*
|
||||
* openGauss is licensed under Mulan PSL v2.
|
||||
* You can use this software according to the terms and conditions of the Mulan PSL v2.
|
||||
* You may obtain a copy of Mulan PSL v2 at:
|
||||
*
|
||||
* http://license.coscl.org.cn/MulanPSL2
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
|
||||
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
|
||||
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
|
||||
* See the Mulan PSL v2 for more details.
|
||||
*/
|
||||
|
||||
import { watch } from '../reactive/Watch';
|
||||
import { isReactiveObj } from '../reactive/Utils';
|
||||
|
||||
export function template(html) {
|
||||
let node;
|
||||
const create = () => {
|
||||
const t = document.createElement('template');
|
||||
t.innerHTML = html;
|
||||
return t.content.firstChild;
|
||||
};
|
||||
|
||||
const fn = () => (node || (node = create())).cloneNode(true);
|
||||
fn.cloneNode = fn;
|
||||
return fn;
|
||||
}
|
||||
|
||||
export function insert(parent, accessor, marker, initial) {
|
||||
if (marker !== undefined && !initial) {
|
||||
initial = [];
|
||||
}
|
||||
|
||||
if (isReactiveObj(accessor)) {
|
||||
watchRender(current => {
|
||||
return insertExpression(parent, accessor.get(), current, marker);
|
||||
}, initial);
|
||||
} else {
|
||||
return insertExpression(parent, accessor, initial, marker);
|
||||
}
|
||||
}
|
||||
|
||||
function watchRender(fn, prevValue) {
|
||||
let nextValue = prevValue;
|
||||
watch(() => {
|
||||
nextValue = fn(nextValue);
|
||||
});
|
||||
}
|
||||
|
||||
function insertExpression(parent, value, current, marker, unwrapArray) {
|
||||
while (typeof current === 'function') current = current();
|
||||
if (value === current) return value;
|
||||
|
||||
const t = typeof value,
|
||||
multi = marker !== undefined;
|
||||
|
||||
if (t === 'string' || t === 'number') {
|
||||
if (t === 'number') value = value.toString();
|
||||
if (multi) {
|
||||
let node = current[0];
|
||||
if (node && node.nodeType === 3) {
|
||||
node.data = value;
|
||||
} else {
|
||||
node = document.createTextNode(value);
|
||||
}
|
||||
current = cleanChildren(parent, current, marker, node);
|
||||
} else {
|
||||
if (current !== '' && typeof current === 'string') {
|
||||
current = parent.firstChild.data = value;
|
||||
} else current = parent.textContent = value;
|
||||
}
|
||||
} else if (value == null || t === 'boolean') {
|
||||
current = cleanChildren(parent, current, marker);
|
||||
} else if (t === 'function') {
|
||||
// 在watch里面执行
|
||||
watch(() => {
|
||||
let v = value();
|
||||
while (isReactiveObj(v)) {
|
||||
v = v.get();
|
||||
}
|
||||
|
||||
current = insertExpression(parent, v, current, marker);
|
||||
});
|
||||
return () => current;
|
||||
} else if (Array.isArray(value)) {
|
||||
// return [() => {}, () => {}, ...]
|
||||
const array = [];
|
||||
const currentArray = current && Array.isArray(current);
|
||||
if (normalizeIncomingArray(array, value, current, unwrapArray)) {
|
||||
watchRender(() => (current = insertExpression(parent, array, current, marker, true)));
|
||||
return () => current;
|
||||
}
|
||||
|
||||
if (array.length === 0) {
|
||||
// 当前没有节点
|
||||
current = cleanChildren(parent, current, marker);
|
||||
if (multi) return current;
|
||||
} else if (currentArray) {
|
||||
if (current.length === 0) {
|
||||
appendNodes(parent, array, marker); // 原来没有节点
|
||||
} else {
|
||||
reconcileArrays(parent, current, array); // 原本有节点,现在也有节点
|
||||
}
|
||||
} else {
|
||||
current && cleanChildren(parent);
|
||||
appendNodes(parent, array);
|
||||
}
|
||||
current = array;
|
||||
} else if (value.nodeType) {
|
||||
if (Array.isArray(current)) {
|
||||
if (multi) return (current = cleanChildren(parent, current, marker, value));
|
||||
cleanChildren(parent, current, null, value);
|
||||
} else if (current == null || current === '' || !parent.firstChild) {
|
||||
parent.appendChild(value);
|
||||
} else {
|
||||
parent.replaceChild(value, parent.firstChild);
|
||||
}
|
||||
current = value;
|
||||
}
|
||||
|
||||
return current;
|
||||
}
|
||||
|
||||
function cleanChildren(parent, current, marker, replacement) {
|
||||
if (marker === undefined) {
|
||||
return (parent.textContent = '');
|
||||
}
|
||||
|
||||
const node = replacement || document.createTextNode('');
|
||||
if (current.length) {
|
||||
let inserted = false;
|
||||
for (let i = current.length - 1; i >= 0; i--) {
|
||||
const el = current[i];
|
||||
if (node !== el) {
|
||||
const isParent = el.parentNode === parent;
|
||||
if (!inserted && !i) {
|
||||
isParent ? parent.replaceChild(node, el) : parent.insertBefore(node, marker);
|
||||
} else {
|
||||
isParent && el.remove();
|
||||
}
|
||||
} else {
|
||||
inserted = true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
parent.insertBefore(node, marker);
|
||||
}
|
||||
|
||||
return [node];
|
||||
}
|
||||
|
||||
function appendNodes(parent, array, marker = null) {
|
||||
for (let i = 0, len = array.length; i < len; i++) {
|
||||
parent.insertBefore(array[i], marker);
|
||||
}
|
||||
}
|
||||
|
||||
// 拆解数组,如:[[a, b], [c, d], ...] to [a, b, c, d]
|
||||
function normalizeIncomingArray(normalized, array, unwrap) {
|
||||
let dynamic = false;
|
||||
for (let i = 0, len = array.length; i < len; i++) {
|
||||
let item = array[i],
|
||||
t;
|
||||
if (item == null || item === true || item === false) {
|
||||
// matches null, undefined, true or false
|
||||
// skip
|
||||
} else if (Array.isArray(item)) {
|
||||
dynamic = normalizeIncomingArray(normalized, item) || dynamic;
|
||||
} else if ((t = typeof item) === 'string' || t === 'number') {
|
||||
normalized.push(document.createTextNode(item));
|
||||
} else if (t === 'function') {
|
||||
if (unwrap) {
|
||||
while (typeof item === 'function') item = item();
|
||||
dynamic = normalizeIncomingArray(normalized, Array.isArray(item) ? item : [item]) || dynamic;
|
||||
} else {
|
||||
normalized.push(item);
|
||||
dynamic = true;
|
||||
}
|
||||
} else {
|
||||
normalized.push(item);
|
||||
}
|
||||
}
|
||||
return dynamic;
|
||||
}
|
||||
|
||||
// 原本有节点,现在也有节点
|
||||
export default function reconcileArrays(parentNode, oldChildren, newChildren) {
|
||||
let nLength = newChildren.length,
|
||||
oEnd = oldChildren.length,
|
||||
nEnd = nLength,
|
||||
oStart = 0,
|
||||
nStart = 0,
|
||||
after = oldChildren[oEnd - 1].nextSibling,
|
||||
map = null;
|
||||
|
||||
while (oStart < oEnd || nStart < nEnd) {
|
||||
// 从前到后对比相同内容
|
||||
if (oldChildren[oStart] === newChildren[nStart]) {
|
||||
oStart++;
|
||||
nStart++;
|
||||
continue;
|
||||
}
|
||||
// 从后往前对比相同内容
|
||||
while (oldChildren[oEnd - 1] === newChildren[nEnd - 1]) {
|
||||
oEnd--;
|
||||
nEnd--;
|
||||
}
|
||||
// append
|
||||
if (oEnd === oStart) {
|
||||
// 旧节点全部和新节点相同(不是完全相同, 如:旧 abcd 新 abefcd)
|
||||
const node = nEnd < nLength ? (nStart ? newChildren[nStart - 1].nextSibling : newChildren[nEnd - nStart]) : after;
|
||||
|
||||
while (nStart < nEnd) {
|
||||
parentNode.insertBefore(newChildren[nStart++], node);
|
||||
}
|
||||
// remove
|
||||
} else if (nEnd === nStart) {
|
||||
// 新节点全部和新节点相同(不是完全相同, 如:旧 abefcd 新 abcd)
|
||||
while (oStart < oEnd) {
|
||||
if (!map || !map.has(oldChildren[oStart])) {
|
||||
oldChildren[oStart].remove();
|
||||
}
|
||||
oStart++;
|
||||
}
|
||||
// swap backward
|
||||
} else if (oldChildren[oStart] === newChildren[nEnd - 1] && newChildren[nStart] === oldChildren[oEnd - 1]) {
|
||||
// 如:旧 ab ef cd 新 ab fe cd
|
||||
const node = oldChildren[--oEnd].nextSibling;
|
||||
parentNode.insertBefore(newChildren[nStart++], oldChildren[oStart++].nextSibling); // 如:旧 abe f fcd
|
||||
parentNode.insertBefore(newChildren[--nEnd], node); // 如:旧 abeff e cd
|
||||
|
||||
oldChildren[oEnd] = newChildren[nEnd];
|
||||
// fallback to map
|
||||
} else {
|
||||
// 如:旧 ab feww cd 新 ab hgeht cd
|
||||
if (!map) {
|
||||
map = new Map();
|
||||
let i = nStart;
|
||||
|
||||
while (i < nEnd) {
|
||||
map.set(newChildren[i], i++); // 收集 hgeht
|
||||
}
|
||||
}
|
||||
|
||||
const index = map.get(oldChildren[oStart]);
|
||||
if (index != null) {
|
||||
// 如:e就在newChildren中
|
||||
if (nStart < index && index < nEnd) {
|
||||
// 且位置在新节点 之间
|
||||
let i = oStart,
|
||||
sequence = 1,
|
||||
t;
|
||||
|
||||
while (++i < oEnd && i < nEnd) {
|
||||
// 如:旧 ab feww cd 新 ab hgeht cd, e 的 sequence 是 2 ?
|
||||
if ((t = map.get(oldChildren[i])) == null || t !== index + sequence) break;
|
||||
sequence++;
|
||||
}
|
||||
|
||||
if (sequence > index - nStart) {
|
||||
const node = oldChildren[oStart];
|
||||
while (nStart < index) {
|
||||
parentNode.insertBefore(newChildren[nStart++], node);
|
||||
}
|
||||
} else {
|
||||
parentNode.replaceChild(newChildren[nStart++], oldChildren[oStart++]);
|
||||
}
|
||||
} else {
|
||||
oStart++;
|
||||
}
|
||||
} else {
|
||||
oldChildren[oStart++].remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function setAttribute(node, name, value) {
|
||||
if (value == null) {
|
||||
node.removeAttribute(name);
|
||||
} else {
|
||||
node.setAttribute(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
export function className(node, value) {
|
||||
if (value == null) {
|
||||
node.removeAttribute('class');
|
||||
} else {
|
||||
node.className = value;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,85 @@
|
|||
/*
|
||||
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
|
||||
*
|
||||
* openGauss is licensed under Mulan PSL v2.
|
||||
* You can use this software according to the terms and conditions of the Mulan PSL v2.
|
||||
* You may obtain a copy of Mulan PSL v2 at:
|
||||
*
|
||||
* http://license.coscl.org.cn/MulanPSL2
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
|
||||
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
|
||||
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
|
||||
* See the Mulan PSL v2 for more details.
|
||||
*/
|
||||
|
||||
const $$EVENTS = "_$DX_DELEGATE";
|
||||
|
||||
/**
|
||||
* 在 document上注册事件
|
||||
* @param eventNames
|
||||
* @param document
|
||||
*/
|
||||
export function delegateEvents(eventNames, document = window.document) {
|
||||
const e = document[$$EVENTS] || (document[$$EVENTS] = new Set());
|
||||
for (let i = 0, l = eventNames.length; i < l; i++) {
|
||||
const name = eventNames[i];
|
||||
if (!e.has(name)) {
|
||||
e.add(name);
|
||||
document.addEventListener(name, eventHandler);
|
||||
}
|
||||
}
|
||||
}
|
||||
export function clearDelegatedEvents(document = window.document) {
|
||||
if (document[$$EVENTS]) {
|
||||
for (let name of document[$$EVENTS].keys()) document.removeEventListener(name, eventHandler);
|
||||
delete document[$$EVENTS];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function eventHandler(e) {
|
||||
const key = `$$${e.type}`;
|
||||
let node = (e.composedPath && e.composedPath()[0]) || e.target;
|
||||
if (e.target !== node) {
|
||||
Object.defineProperty(e, "target", {
|
||||
configurable: true,
|
||||
value: node
|
||||
});
|
||||
}
|
||||
Object.defineProperty(e, "currentTarget", {
|
||||
configurable: true,
|
||||
get() {
|
||||
return node || document;
|
||||
}
|
||||
});
|
||||
|
||||
// 冒泡执行事件
|
||||
while (node) {
|
||||
const handler = node[key];
|
||||
if (handler && !node.disabled) {
|
||||
const data = node[`${key}Data`];
|
||||
data !== undefined ? handler.call(node, data, e) : handler.call(node, e);
|
||||
if (e.cancelBubble) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
node = node._$host || node.parentNode || node.host;
|
||||
}
|
||||
}
|
||||
|
||||
export function addEventListener(node, name, handler, delegate) {
|
||||
if (delegate) {
|
||||
if (Array.isArray(handler)) {
|
||||
node[`$$${name}`] = handler[0];
|
||||
node[`$$${name}Data`] = handler[1];
|
||||
} else {
|
||||
node[`$$${name}`] = handler;
|
||||
}
|
||||
} else if (Array.isArray(handler)) {
|
||||
const handlerFn = handler[0];
|
||||
node.addEventListener(name, (handler[0] = e => handlerFn.call(node, handler[1], e)));
|
||||
} else {
|
||||
node.addEventListener(name, handler);
|
||||
}
|
||||
}
|
|
@ -20,7 +20,7 @@ import { ArrayState, RContextCallback, RContextParam, Reactive, RNode } from './
|
|||
import { getOrCreateChildNode } from './RNode';
|
||||
import {addToBatch, startBatch, endBatch, BatchItem} from './Batch';
|
||||
|
||||
export let currentDependent: RContext | null = null;
|
||||
export let currentRContext: RContext | null = null;
|
||||
|
||||
const reactiveContextStack: RContext[] = [];
|
||||
export type RContextSet = Set<RContext>;
|
||||
|
@ -48,7 +48,7 @@ export class RContext {
|
|||
|
||||
start() {
|
||||
cleanupRContext(this);
|
||||
currentDependent = this;
|
||||
currentRContext = this;
|
||||
reactiveContextStack.push(this);
|
||||
|
||||
return endEffect;
|
||||
|
@ -57,7 +57,11 @@ export class RContext {
|
|||
|
||||
function endEffect() {
|
||||
reactiveContextStack.pop();
|
||||
currentDependent = reactiveContextStack[reactiveContextStack.length - 1] ?? null;
|
||||
currentRContext = reactiveContextStack[reactiveContextStack.length - 1] ?? null;
|
||||
}
|
||||
|
||||
export function setRContext(val: RContext | null) {
|
||||
currentRContext = val;
|
||||
}
|
||||
|
||||
// 清除 RContext和响应式数据的绑定,双向清除
|
||||
|
@ -99,6 +103,7 @@ export function triggerRContexts(reactive: Reactive, prevValue: any, value: any,
|
|||
callRContexts(reactive);
|
||||
|
||||
// 触发父数据的RContext,不希望触发组件刷新(只触发computed和watch)
|
||||
// TODO 暂时删除, 跑no-vnode方式的js-framework-benchmark用例
|
||||
triggerParents(reactive.parent);
|
||||
|
||||
endBatch();
|
||||
|
|
|
@ -24,6 +24,8 @@ import { updateInputValue } from '../dom/valueHandler/InputValueHandler';
|
|||
import { updateTextareaValue } from '../dom/valueHandler/TextareaValueHandler';
|
||||
import { setDomProps } from '../dom/DOMPropertiesHandler/DOMPropertiesHandler';
|
||||
import { getRNodeFromProxy, isAtom, isReactiveProxy } from './Utils';
|
||||
import { isReactively } from '../reactively/utils';
|
||||
import { reactively } from '../reactively/Reactively';
|
||||
|
||||
const vNodeEffectMap = new WeakMap<VNode, RContext>();
|
||||
|
||||
|
@ -117,10 +119,52 @@ function subscribeAttr(dom: Element, propName: string, propVal: Reactive, styleN
|
|||
saveAttrRContexts(vNode, attrRContext);
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅DOM的属性(props或children),创建一个专门更新该属性的上下文,当响应式数据变化就触发该上下文的callback
|
||||
* @param dom DOM元素
|
||||
* @param propName 属性名字
|
||||
* @param propVal 属性值,是响应式数据
|
||||
* @param styleName style里面的某个属性
|
||||
*/
|
||||
function subscribeAttrForReactively(dom: Element, propName: string, propVal, styleName?: string) {
|
||||
const attrRContext = reactively.watch(
|
||||
() => {
|
||||
let changeList;
|
||||
if (propName === 'style' && styleName) {
|
||||
changeList = {
|
||||
style: {
|
||||
[styleName]: propVal.get(),
|
||||
},
|
||||
};
|
||||
} else {
|
||||
changeList = {
|
||||
[propName]: propVal.get(),
|
||||
};
|
||||
}
|
||||
|
||||
const type = getVNode(dom)?.type;
|
||||
if (type === 'input' && propName === 'value') {
|
||||
updateInputValue(dom as HTMLInputElement, changeList);
|
||||
} else if (type === 'textarea' && propName === 'value') {
|
||||
updateTextareaValue(dom as HTMLTextAreaElement, changeList);
|
||||
} else {
|
||||
setDomProps(dom, changeList, true, false);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// bindReactiveWithContext(propVal, attrRContext);
|
||||
//
|
||||
// // vNode保存RContext,用于cleanup
|
||||
// const vNode = getVNode(dom);
|
||||
// saveAttrRContexts(vNode, attrRContext);
|
||||
}
|
||||
|
||||
export function handleReactiveProp(dom: Element, propName: string, propVal: any, styleName?: string): any {
|
||||
let rawVal = propVal;
|
||||
const isA = isAtom(propVal);
|
||||
const isProxy = isReactiveProxy(propVal);
|
||||
const isRy = isReactively(propVal);
|
||||
|
||||
if (isA || isProxy) {
|
||||
let reactive = propVal;
|
||||
|
@ -131,6 +175,11 @@ export function handleReactiveProp(dom: Element, propName: string, propVal: any,
|
|||
subscribeAttr(dom, propName, reactive, styleName);
|
||||
}
|
||||
|
||||
if (isRy) {
|
||||
subscribeAttrForReactively(dom, propName, propVal, styleName);
|
||||
rawVal = propVal.get();
|
||||
}
|
||||
|
||||
return rawVal;
|
||||
}
|
||||
|
||||
|
|
|
@ -13,7 +13,7 @@
|
|||
* See the Mulan PSL v2 for more details.
|
||||
*/
|
||||
|
||||
import { bindReactiveWithContext, currentDependent, triggerRContexts } from './RContext';
|
||||
import { bindReactiveWithContext, currentRContext, setRContext, triggerRContexts } from './RContext';
|
||||
import { isAtom, isFunction, isRNode, isPrimitive } from './Utils';
|
||||
import { createProxy } from './proxy/RProxyHandler';
|
||||
import { Atom } from './Atom';
|
||||
|
@ -104,10 +104,25 @@ export function getOrCreateChildProxy(value: unknown, parent: RNode, key: string
|
|||
// }
|
||||
}
|
||||
|
||||
// 最终响应式数据的使用
|
||||
// 追踪响应式数据的使用
|
||||
export function trackReactiveData(reactive: Reactive) {
|
||||
if (currentDependent !== null) {
|
||||
bindReactiveWithContext(reactive, currentDependent);
|
||||
if (currentRContext !== null) {
|
||||
bindReactiveWithContext(reactive, currentRContext);
|
||||
}
|
||||
}
|
||||
|
||||
// 不进行响应式数据的使用追踪
|
||||
export function untrack(fn) {
|
||||
if (currentRContext === null) {
|
||||
return fn();
|
||||
}
|
||||
|
||||
const preRContext = currentRContext;
|
||||
setRContext(null);
|
||||
try {
|
||||
return fn();
|
||||
} finally {
|
||||
setRContext(preRContext);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -17,6 +17,7 @@ import {Atom} from './Atom';
|
|||
import {getRNodeVal, nodeSymbol} from './RNode';
|
||||
import {AtomNode, AtomNodeFn, ProxyRNode, ProxyRNodeFn, Reactive, ReactiveProxy, RNode} from './types';
|
||||
import {GET_R_NODE} from './proxy/RProxyHandler';
|
||||
import {isReactively} from '../reactively/utils';
|
||||
|
||||
export function isAtom(val: unknown): val is Atom {
|
||||
return val instanceof Atom;
|
||||
|
@ -31,7 +32,7 @@ export function isReactiveProxy(val: unknown): val is RNode {
|
|||
}
|
||||
|
||||
export function isReactiveObj(val: unknown): val is ProxyRNodeFn<any> | AtomNodeFn<any> {
|
||||
return isAtom(val) || isReactiveProxy(val);
|
||||
return isAtom(val) || isReactiveProxy(val) || isReactively(val);
|
||||
}
|
||||
|
||||
export function isObject(obj: unknown): boolean {
|
||||
|
|
|
@ -27,7 +27,7 @@ export interface Root<T> {
|
|||
$?: T;
|
||||
|
||||
/**
|
||||
* 下面属性computed使用
|
||||
* computed使用
|
||||
* @param {readOnly} 标识computed 是否处于写入状态
|
||||
*/
|
||||
readOnly?: boolean;
|
||||
|
|
|
@ -0,0 +1,335 @@
|
|||
/*
|
||||
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
|
||||
*
|
||||
* openGauss is licensed under Mulan PSL v2.
|
||||
* You can use this software according to the terms and conditions of the Mulan PSL v2.
|
||||
* You may obtain a copy of Mulan PSL v2 at:
|
||||
*
|
||||
* http://license.coscl.org.cn/MulanPSL2
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
|
||||
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
|
||||
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
|
||||
* See the Mulan PSL v2 for more details.
|
||||
*/
|
||||
|
||||
import { createProxy } from './proxy/RProxyHandler';
|
||||
import { isFunction } from '../reactive/Utils';
|
||||
import {getRNodeVal, preciseCompare, setRNodeVal} from "./RNodeAccessor";
|
||||
import {isObject} from "./Utils";
|
||||
|
||||
/** current capture context for identifying @reactive sources (other reactive elements) and cleanups
|
||||
* - active while evaluating a reactive function body */
|
||||
let CurrentReaction: RNode<any> | undefined = undefined;
|
||||
let CurrentGets: RNode<any>[] | null = null;
|
||||
let CurrentGetsIndex = 0;
|
||||
|
||||
/** A list of non-clean 'effect' nodes that will be updated when stabilize() is called */
|
||||
const EffectQueue: RNode<any>[] = [];
|
||||
|
||||
export const CacheClean = 0; // reactive value is valid, no need to recompute
|
||||
export const CacheCheck = 1; // reactive value might be stale, check parent nodes to decide whether to recompute
|
||||
export const CacheDirty = 2; // reactive value is invalid, parents have changed, valueneeds to be recomputed
|
||||
export type CacheState = typeof CacheClean | typeof CacheCheck | typeof CacheDirty;
|
||||
type CacheNonClean = typeof CacheCheck | typeof CacheDirty;
|
||||
|
||||
export interface RNodeOptions {
|
||||
root?: Root<any> | null;
|
||||
isSignal?: boolean;
|
||||
isEffect?: boolean;
|
||||
isComputed?: boolean;
|
||||
isProxy?: boolean;
|
||||
parent?: RNode<any> | null;
|
||||
key?: KEY | null;
|
||||
equals?: (a: any, b: any) => boolean;
|
||||
}
|
||||
|
||||
export interface Root<T> {
|
||||
$?: T;
|
||||
}
|
||||
|
||||
export type KEY = string | symbol;
|
||||
|
||||
function defaultEquality(a: any, b: any) {
|
||||
return a === b;
|
||||
}
|
||||
|
||||
export class RNode<T = any> {
|
||||
private _value: T;
|
||||
private fn?: () => T;
|
||||
|
||||
root: Root<T> | null;
|
||||
|
||||
parent: RNode | null = null;
|
||||
key: KEY | null;
|
||||
children: Map<KEY, RNode> | null = null;
|
||||
|
||||
proxy: any = null;
|
||||
|
||||
private observers: RNode[] | null = null; // 被谁用
|
||||
private sources: RNode[] | null = null; // 使用谁
|
||||
|
||||
private state: CacheState;
|
||||
private isSignal = false;
|
||||
private isEffect = false;
|
||||
private isComputed = false;
|
||||
private isProxy = false;
|
||||
|
||||
cleanups: ((oldValue: T) => void)[] = [];
|
||||
equals = defaultEquality;
|
||||
|
||||
constructor(fnOrValue: (() => T) | T, options?: RNodeOptions) {
|
||||
this.isSignal = options?.isSignal || false;
|
||||
this.isEffect = options?.isEffect || false;
|
||||
this.isProxy = options?.isProxy || false;
|
||||
this.isComputed = options?.isComputed || false;
|
||||
|
||||
if (typeof fnOrValue === 'function') {
|
||||
this.fn = fnOrValue as () => T;
|
||||
this._value = undefined as any;
|
||||
this.state = CacheDirty;
|
||||
|
||||
if (this.isEffect) {
|
||||
EffectQueue.push(this);
|
||||
}
|
||||
} else {
|
||||
this.fn = undefined;
|
||||
this._value = fnOrValue;
|
||||
this.state = CacheClean;
|
||||
}
|
||||
|
||||
// large-scale object scene
|
||||
if (this.isProxy) {
|
||||
this.proxy = createProxy(this);
|
||||
this.parent = options?.parent || null;
|
||||
this.key = options?.key as KEY;
|
||||
this.root = options?.root || null;
|
||||
|
||||
if (this.parent && !this.parent.children) {
|
||||
this.parent.children = new Map();
|
||||
this.parent.children.set(this.key, this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
get value(): T {
|
||||
return this.get();
|
||||
}
|
||||
|
||||
set value(v: T) {
|
||||
this.set(v);
|
||||
}
|
||||
|
||||
get(): T {
|
||||
if (CurrentReaction) {
|
||||
if (!CurrentGets && CurrentReaction.sources && CurrentReaction.sources[CurrentGetsIndex] == this) {
|
||||
CurrentGetsIndex++;
|
||||
} else {
|
||||
if (!CurrentGets) {
|
||||
CurrentGets = [this];
|
||||
} else {
|
||||
CurrentGets.push(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this.fn) {
|
||||
this.updateIfNecessary();
|
||||
}
|
||||
|
||||
return this.getValue();
|
||||
}
|
||||
|
||||
set(fnOrValue: T | (() => T)): void {
|
||||
if (typeof fnOrValue === 'function') {
|
||||
const fn = fnOrValue as () => T;
|
||||
if (fn !== this.fn) {
|
||||
this.stale(CacheDirty);
|
||||
}
|
||||
this.fn = fn;
|
||||
} else {
|
||||
if (this.fn) {
|
||||
this.removeParentObservers(0);
|
||||
this.sources = null;
|
||||
this.fn = undefined;
|
||||
}
|
||||
|
||||
const value = fnOrValue as T;
|
||||
const prevValue = this.getValue();
|
||||
|
||||
const isObj = isObject(value);
|
||||
const isPrevObj = isObject(prevValue);
|
||||
|
||||
// 新旧数据都是 对象或数组
|
||||
if (isObj && isPrevObj) {
|
||||
preciseCompare(this, value, prevValue, false);
|
||||
|
||||
this.setValue(value);
|
||||
} else {
|
||||
if (!this.equals(prevValue, value)) {
|
||||
this.setDirty();
|
||||
|
||||
this.setValue(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 运行EffectQueue
|
||||
runEffects();
|
||||
}
|
||||
|
||||
setDirty() {
|
||||
if (this.observers) {
|
||||
for (let i = 0; i < this.observers.length; i++) {
|
||||
const observer = this.observers[i];
|
||||
observer.stale(CacheDirty);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private stale(state: CacheNonClean): void {
|
||||
if (this.state < state) {
|
||||
// If we were previously clean, then we know that we may need to update to get the new value
|
||||
if (this.state === CacheClean && this.isEffect) {
|
||||
EffectQueue.push(this);
|
||||
}
|
||||
|
||||
this.state = state;
|
||||
if (this.observers) {
|
||||
for (let i = 0; i < this.observers.length; i++) {
|
||||
this.observers[i].stale(CacheCheck);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** run the computation fn, updating the cached value */
|
||||
private update(): void {
|
||||
const prevValue = this.getValue();
|
||||
|
||||
/* Evalute the reactive function body, dynamically capturing any other reactives used */
|
||||
const prevReaction = CurrentReaction;
|
||||
const prevGets = CurrentGets;
|
||||
const prevIndex = CurrentGetsIndex;
|
||||
|
||||
CurrentReaction = this;
|
||||
CurrentGets = null as any; // prevent TS from thinking CurrentGets is null below
|
||||
CurrentGetsIndex = 0;
|
||||
|
||||
try {
|
||||
if (this.cleanups.length) {
|
||||
this.cleanups.forEach(c => c(this._value));
|
||||
this.cleanups = [];
|
||||
}
|
||||
|
||||
if (this.isComputed) {
|
||||
this.root = { $: this.fn!() };
|
||||
} else {
|
||||
this._value = this.fn!();
|
||||
}
|
||||
|
||||
// if the sources have changed, update source & observer links
|
||||
if (CurrentGets) {
|
||||
// remove all old sources' .observers links to us
|
||||
this.removeParentObservers(CurrentGetsIndex);
|
||||
// update source up links
|
||||
if (this.sources && CurrentGetsIndex > 0) {
|
||||
this.sources.length = CurrentGetsIndex + CurrentGets.length;
|
||||
for (let i = 0; i < CurrentGets.length; i++) {
|
||||
this.sources[CurrentGetsIndex + i] = CurrentGets[i];
|
||||
}
|
||||
} else {
|
||||
this.sources = CurrentGets;
|
||||
}
|
||||
|
||||
for (let i = CurrentGetsIndex; i < this.sources.length; i++) {
|
||||
// Add ourselves to the end of the parent .observers array
|
||||
const source = this.sources[i];
|
||||
if (!source.observers) {
|
||||
source.observers = [this];
|
||||
} else {
|
||||
source.observers.push(this);
|
||||
}
|
||||
}
|
||||
} else if (this.sources && CurrentGetsIndex < this.sources.length) {
|
||||
// remove all old sources' .observers links to us
|
||||
this.removeParentObservers(CurrentGetsIndex);
|
||||
this.sources.length = CurrentGetsIndex;
|
||||
}
|
||||
} finally {
|
||||
CurrentGets = prevGets;
|
||||
CurrentReaction = prevReaction;
|
||||
CurrentGetsIndex = prevIndex;
|
||||
}
|
||||
|
||||
// handles diamond depenendencies if we're the parent of a diamond.
|
||||
if (!this.equals(prevValue, this.getValue()) && this.observers) {
|
||||
// We've changed value, so mark our children as dirty so they'll reevaluate
|
||||
for (let i = 0; i < this.observers.length; i++) {
|
||||
const observer = this.observers[i];
|
||||
observer.state = CacheDirty;
|
||||
}
|
||||
}
|
||||
|
||||
// We've rerun with the latest values from all of our sources.
|
||||
// This means that we no longer need to update until a signal changes
|
||||
this.state = CacheClean;
|
||||
}
|
||||
|
||||
/** update() if dirty, or a parent turns out to be dirty. */
|
||||
private updateIfNecessary(): void {
|
||||
if (this.state === CacheCheck) {
|
||||
for (const source of this.sources!) {
|
||||
source.updateIfNecessary(); // updateIfNecessary() can change this.state
|
||||
if ((this.state as CacheState) === CacheDirty) {
|
||||
// Stop the loop here so we won't trigger updates on other parents unnecessarily
|
||||
// If our computation changes to no longer use some sources, we don't
|
||||
// want to update() a source we used last time, but now don't use.
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we were already dirty or marked dirty by the step above, update.
|
||||
if (this.state === CacheDirty) {
|
||||
this.update();
|
||||
}
|
||||
|
||||
// By now, we're clean
|
||||
this.state = CacheClean;
|
||||
}
|
||||
|
||||
private removeParentObservers(index: number): void {
|
||||
if (!this.sources) return;
|
||||
for (let i = index; i < this.sources.length; i++) {
|
||||
const source: RNode<any> = this.sources[i]; // We don't actually delete sources here because we're replacing the entire array soon
|
||||
const swap = source.observers!.findIndex(v => v === this);
|
||||
source.observers![swap] = source.observers![source.observers!.length - 1];
|
||||
source.observers!.pop();
|
||||
}
|
||||
}
|
||||
|
||||
private getValue() {
|
||||
return this.isProxy ? getRNodeVal(this) : this._value;
|
||||
}
|
||||
|
||||
private setValue(value: any) {
|
||||
this.isProxy ? setRNodeVal(this, value) : (this._value = value);
|
||||
}
|
||||
}
|
||||
|
||||
export function onCleanup<T = any>(fn: (oldValue: T) => void): void {
|
||||
if (CurrentReaction) {
|
||||
CurrentReaction.cleanups.push(fn);
|
||||
} else {
|
||||
console.error('onCleanup must be called from within a @reactive function');
|
||||
}
|
||||
}
|
||||
|
||||
/** run all non-clean effect nodes */
|
||||
export function runEffects(): void {
|
||||
for (let i = 0; i < EffectQueue.length; i++) {
|
||||
EffectQueue[i].get();
|
||||
}
|
||||
EffectQueue.length = 0;
|
||||
}
|
|
@ -0,0 +1,270 @@
|
|||
/*
|
||||
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
|
||||
*
|
||||
* openGauss is licensed under Mulan PSL v2.
|
||||
* You can use this software according to the terms and conditions of the Mulan PSL v2.
|
||||
* You may obtain a copy of Mulan PSL v2 at:
|
||||
*
|
||||
* http://license.coscl.org.cn/MulanPSL2
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
|
||||
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
|
||||
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
|
||||
* See the Mulan PSL v2 for more details.
|
||||
*/
|
||||
|
||||
import { RNode } from './RNode';
|
||||
import { isFunction } from '../reactive/Utils';
|
||||
import { isObject } from './Utils';
|
||||
import { isArray } from '../inulax/CommonUtils';
|
||||
import { arrayDiff, DiffOperator, Operation } from '../reactive/DiffUtils';
|
||||
import { ArrayState } from '../reactive/types';
|
||||
import { getOrCreateChildRNode } from './RNodeCreator';
|
||||
|
||||
export function getRNodeVal(node: RNode<any>): any {
|
||||
let currentNode = node;
|
||||
const keys: (string | symbol)[] = [];
|
||||
while (currentNode.key !== null && currentNode.parent !== null) {
|
||||
keys.push(currentNode.key);
|
||||
currentNode = currentNode.parent;
|
||||
}
|
||||
|
||||
let rawObj = node.root?.$;
|
||||
for (let i = keys.length - 1; i >= 0; i--) {
|
||||
if (keys[i] !== undefined && rawObj) {
|
||||
rawObj = rawObj[keys[i]];
|
||||
}
|
||||
}
|
||||
|
||||
return rawObj;
|
||||
}
|
||||
|
||||
export function setRNodeVal(rNode: RNode<any>, value: unknown): void {
|
||||
const parent = rNode.parent;
|
||||
const key = rNode.key!;
|
||||
const isRoot = parent === null;
|
||||
let prevValue: unknown;
|
||||
let newValue: unknown;
|
||||
|
||||
if (isRoot) {
|
||||
prevValue = rNode.root!.$;
|
||||
newValue = isFunction<(...prev: any) => any>(value) ? value(prevValue) : value;
|
||||
rNode.root!.$ = newValue;
|
||||
} else {
|
||||
const parentVal = getRNodeVal(parent!);
|
||||
prevValue = parentVal[key];
|
||||
newValue = isFunction<(...prev: any) => any>(value) ? value(prevValue) : value;
|
||||
parentVal[key] = newValue;
|
||||
}
|
||||
}
|
||||
|
||||
// 递归触发依赖这reactive数据的所有RContext
|
||||
export function preciseCompare(rNode: RNode<any>, value: any, prevValue: any, isFromArrModify?: boolean) {
|
||||
preciseCompareChildren(rNode, value, prevValue, isFromArrModify);
|
||||
|
||||
// 触发父数据的RContext,不希望触发组件刷新(只触发computed和watch)
|
||||
// TODO 暂时删除
|
||||
// triggerParents(reactive.parent);
|
||||
}
|
||||
|
||||
// 当value和prevValue都是对象或数组时,才触发
|
||||
function preciseCompareChildren(rNode: RNode, value: any, prevValue: any, isFromArrModify?: boolean): boolean {
|
||||
// 可以精准更新
|
||||
let canPreciseUpdate = true;
|
||||
|
||||
const isArr = isArray(value);
|
||||
const isPrevArr = isArray(prevValue);
|
||||
|
||||
// 1、变化来自数组的Modify方法(某些行可能完全不变)
|
||||
if (isFromArrModify) {
|
||||
// // 获取数组间差异,RNode只能增删不能修改,修改会导致Effect不会随数据的位置变化
|
||||
// const diffOperator = arrayDiff(prevValue, value);
|
||||
// const states: ArrayState[] = [];
|
||||
//
|
||||
// let childIndex = 0;
|
||||
//
|
||||
// for (const opt of diffOperator.opts) {
|
||||
// const idx = String(opt.index);
|
||||
// switch (opt.action) {
|
||||
// // 从已有RNode中取值
|
||||
// case Operation.Nop: {
|
||||
// const childRNode = rNode.children?.get(idx);
|
||||
//
|
||||
// // children没有使用时,可以为undefined或没有该child
|
||||
// if (childRNode !== undefined) {
|
||||
// childRNode.key = String(childIndex);
|
||||
// states.push(ArrayState.Fresh);
|
||||
// childIndex++;
|
||||
//
|
||||
// // 删除旧的,重设新值。处理场景:元素还在,但是在数组中的位置变化了。
|
||||
// rNode.children?.delete(String(opt.index));
|
||||
// rNode.children?.set(childRNode.key, childRNode);
|
||||
// }
|
||||
// break;
|
||||
// }
|
||||
// // 从Value中新建RNode
|
||||
// case Operation.Insert: {
|
||||
// getOrCreateChildRNode(rNode, idx);
|
||||
// states.push(ArrayState.NotFresh);
|
||||
// childIndex++;
|
||||
// break;
|
||||
// }
|
||||
// case Operation.Delete: {
|
||||
// rNode.children?.delete(idx);
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// rNode.diffOperator = diffOperator;
|
||||
// if (!rNode.diffOperators) {
|
||||
// rNode.diffOperators = [];
|
||||
// }
|
||||
// rNode.diffOperators.push(diffOperator);
|
||||
// // 记录:新数据,哪些需要处理,哪些不需要
|
||||
// rNode.states = states;
|
||||
// // 数组长度不同,确定会产生变化,调用callDependents一次
|
||||
// callRContexts(rNode);
|
||||
//
|
||||
// return canPreciseUpdate;
|
||||
}
|
||||
|
||||
// 2、都是数组
|
||||
if (isArr && isPrevArr) {
|
||||
const minLen = Math.min(value.length, prevValue.length);
|
||||
|
||||
// 遍历数组或对象,触发子数据的Effects
|
||||
const canPreciseUpdates = updateSameLengthArray(rNode, value, prevValue, minLen);
|
||||
|
||||
const maxLen = Math.max(value.length, prevValue.length);
|
||||
if (maxLen !== minLen || canPreciseUpdates.includes(false)) {
|
||||
canPreciseUpdate = false;
|
||||
}
|
||||
|
||||
// 在reactive中保存opts
|
||||
const diffOperator: DiffOperator = {
|
||||
isOnlyNop: false,
|
||||
opts: [],
|
||||
};
|
||||
const states: ArrayState[] = [];
|
||||
|
||||
// 相同长度的部分
|
||||
for (let i = 0; i < minLen; i++) {
|
||||
diffOperator.opts.push({ action: Operation.Nop, index: i });
|
||||
// 如果该行数据无法精准更新,设置为NotFresh
|
||||
states.push(canPreciseUpdates[i] ? ArrayState.Fresh : ArrayState.NotFresh);
|
||||
}
|
||||
|
||||
// 超出部分:新增
|
||||
if (value.length > prevValue.length) {
|
||||
for (let i = minLen; i < maxLen; i++) {
|
||||
diffOperator.opts.push({ action: Operation.Insert, index: i });
|
||||
states.push(ArrayState.NotFresh);
|
||||
getOrCreateChildRNode(rNode, String(i));
|
||||
}
|
||||
} else if (value.length < prevValue.length) {
|
||||
// 减少部分:删除
|
||||
for (let i = minLen; i < maxLen; i++) {
|
||||
diffOperator.opts.push({ action: Operation.Delete, index: i });
|
||||
states.push(ArrayState.NotFresh);
|
||||
}
|
||||
}
|
||||
|
||||
diffOperator.isOnlyNop = !states.includes(ArrayState.NotFresh);
|
||||
rNode.diffOperator = diffOperator;
|
||||
rNode.states = states;
|
||||
|
||||
return canPreciseUpdate;
|
||||
}
|
||||
|
||||
// 都是对象
|
||||
if (!isArr && !isPrevArr) {
|
||||
const keys = Object.keys(value);
|
||||
const prevKeys = Object.keys(prevValue);
|
||||
|
||||
// 合并keys和prevKeys
|
||||
const keySet = new Set(keys.concat(prevKeys));
|
||||
|
||||
keySet.forEach(key => {
|
||||
const val = value[key];
|
||||
const prevVal = prevValue[key];
|
||||
const isChanged = val !== prevVal;
|
||||
|
||||
// 如果数据有变化,就触发Effects
|
||||
if (isChanged) {
|
||||
const childRNode = rNode.children?.get(key);
|
||||
|
||||
const isObj = isObject(val);
|
||||
const isPrevObj = isObject(prevVal);
|
||||
// val和prevVal都是对象或数组
|
||||
if (isObj) {
|
||||
// 1、如果上一个属性无法精准更新,就不再递归下一个属性了
|
||||
// 2、如果childRNode为空,说明这个数据未被引用过,也不需要调用RContexts
|
||||
if (canPreciseUpdate && childRNode !== undefined) {
|
||||
canPreciseUpdate = preciseCompareChildren(childRNode as RNode, val, prevVal);
|
||||
}
|
||||
} else if (!isObj && !isPrevObj) {
|
||||
// val和prevVal都不是对象或数组
|
||||
canPreciseUpdate = true;
|
||||
} else {
|
||||
// 类型不同(一个是对象或数组,另外一个不是)
|
||||
canPreciseUpdate = false;
|
||||
}
|
||||
|
||||
// 有childRNode,说明这个数据被使引用过
|
||||
if (childRNode) {
|
||||
childRNode.setDirty();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return canPreciseUpdate;
|
||||
}
|
||||
|
||||
// 一个是对象,一个是数组
|
||||
canPreciseUpdate = false;
|
||||
|
||||
return canPreciseUpdate;
|
||||
}
|
||||
|
||||
// 对于数组的变更,尽量尝试精准更新,会记录每行数据是否能够精准更新
|
||||
function updateSameLengthArray(rNode: RNode, value: any, prevValue: any, len: number): boolean[] {
|
||||
const canPreciseUpdates: boolean[] = [];
|
||||
|
||||
// 遍历数组或对象,触发子数据的RContexts
|
||||
for (let i = 0; i < len; i++) {
|
||||
const val = value[i];
|
||||
const prevVal = prevValue[i];
|
||||
const isChanged = val !== prevVal;
|
||||
|
||||
// 如果数据有变化,就触发RContexts
|
||||
if (isChanged) {
|
||||
const childRNode = rNode.children?.get(String(i));
|
||||
|
||||
const isObj = isObject(val);
|
||||
const isPrevObj = isObject(prevVal);
|
||||
// val和prevVal都是对象或数组时
|
||||
if (isObj && isPrevObj) {
|
||||
// 如果childRNode为空,说明这个数据未被引用过,也不需要调用RContexts
|
||||
if (childRNode !== undefined) {
|
||||
canPreciseUpdates[i] = preciseCompareChildren(childRNode, val, prevVal);
|
||||
}
|
||||
} else if (!isObj && !isPrevObj) {
|
||||
// val和prevVal都不是对象或数组
|
||||
canPreciseUpdates[i] = true;
|
||||
} else {
|
||||
// 类型不同(一个是对象或数组,另外一个不是)
|
||||
canPreciseUpdates[i] = false;
|
||||
}
|
||||
|
||||
// 有childRNode,说明这个数据被使引用过
|
||||
if (childRNode) {
|
||||
childRNode.setDirty();
|
||||
}
|
||||
} else {
|
||||
canPreciseUpdates[i] = true;
|
||||
}
|
||||
}
|
||||
|
||||
return canPreciseUpdates;
|
||||
}
|
|
@ -0,0 +1,73 @@
|
|||
/*
|
||||
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
|
||||
*
|
||||
* openGauss is licensed under Mulan PSL v2.
|
||||
* You can use this software according to the terms and conditions of the Mulan PSL v2.
|
||||
* You may obtain a copy of Mulan PSL v2 at:
|
||||
*
|
||||
* http://license.coscl.org.cn/MulanPSL2
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
|
||||
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
|
||||
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
|
||||
* See the Mulan PSL v2 for more details.
|
||||
*/
|
||||
|
||||
import { ProxyRNode, ReactiveProxy } from '../reactive/types';
|
||||
import { isPrimitive } from '../reactive/Utils';
|
||||
import { Atom } from '../reactive/Atom';
|
||||
import { RNode } from './RNode';
|
||||
|
||||
export type Reactive<T = any> = RNode<T> | Atom<T>;
|
||||
|
||||
export const nodeSymbol = Symbol('ReactiveNode');
|
||||
|
||||
export function createReactive<T extends any>(raw?: T): ReactiveProxy<T> {
|
||||
if (isPrimitive(raw) || raw === null || raw === undefined) {
|
||||
return new RNode(raw, { isSignal: true });
|
||||
} else {
|
||||
const node = new RNode(null, {
|
||||
isProxy: true,
|
||||
root: { $: raw },
|
||||
});
|
||||
return node.proxy as ReactiveProxy<T>;
|
||||
}
|
||||
}
|
||||
|
||||
export function createComputed<T>(fn: T) {
|
||||
const rNode = new RNode(fn, { isProxy: true, isComputed: true });
|
||||
return rNode.proxy;
|
||||
}
|
||||
|
||||
export function createWatch<T>(fn: T) {
|
||||
const rNode = new RNode(fn, {
|
||||
isEffect: true,
|
||||
});
|
||||
|
||||
rNode.get();
|
||||
}
|
||||
|
||||
export function getOrCreateChildProxy(
|
||||
value: unknown,
|
||||
parent: RNode<any>,
|
||||
key: string | symbol
|
||||
): Atom | ProxyRNode<any> {
|
||||
const child = getOrCreateChildRNode(parent, key);
|
||||
|
||||
return child.proxy;
|
||||
}
|
||||
|
||||
export function getOrCreateChildRNode(node: RNode<any>, key: string | symbol): RNode<any> {
|
||||
let child = node.children?.get(key);
|
||||
|
||||
if (!child) {
|
||||
child = new RNode(null, {
|
||||
isProxy: true,
|
||||
parent: node,
|
||||
key: key,
|
||||
root: node.root,
|
||||
});
|
||||
}
|
||||
|
||||
return child;
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
import { createComputed, createReactive, createWatch } from './RNodeCreator';
|
||||
import { RNode } from './RNode';
|
||||
|
||||
/**
|
||||
*
|
||||
* interface for a reactive framework
|
||||
*/
|
||||
export interface Reactively {
|
||||
reactive<T>(initialValue: T): RNode<T>;
|
||||
|
||||
watch(fn: () => void): void;
|
||||
|
||||
computed<T>(fn: () => T): RNode<T>;
|
||||
}
|
||||
|
||||
export interface Computed<T> {
|
||||
read(): T;
|
||||
}
|
||||
|
||||
export const reactively: Reactively = {
|
||||
reactive: createReactive,
|
||||
watch: createWatch,
|
||||
computed: createComputed,
|
||||
};
|
|
@ -0,0 +1,25 @@
|
|||
/*
|
||||
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
|
||||
*
|
||||
* openGauss is licensed under Mulan PSL v2.
|
||||
* You can use this software according to the terms and conditions of the Mulan PSL v2.
|
||||
* You may obtain a copy of Mulan PSL v2 at:
|
||||
*
|
||||
* http://license.coscl.org.cn/MulanPSL2
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
|
||||
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
|
||||
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
|
||||
* See the Mulan PSL v2 for more details.
|
||||
*/
|
||||
|
||||
import { RNode } from './RNode';
|
||||
|
||||
export function isReactively(obj: any) {
|
||||
return obj instanceof RNode;
|
||||
}
|
||||
|
||||
export function isObject(obj: unknown): boolean {
|
||||
const type = typeof obj;
|
||||
return obj != null && (type === 'object' || type === 'function');
|
||||
}
|
|
@ -0,0 +1,147 @@
|
|||
/*
|
||||
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
|
||||
*
|
||||
* openGauss is licensed under Mulan PSL v2.
|
||||
* You can use this software according to the terms and conditions of the Mulan PSL v2.
|
||||
* You may obtain a copy of Mulan PSL v2 at:
|
||||
*
|
||||
* http://license.coscl.org.cn/MulanPSL2
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
|
||||
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
|
||||
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
|
||||
* See the Mulan PSL v2 for more details.
|
||||
*/
|
||||
|
||||
import { getOrCreateChildProxy } from '../RNodeCreator';
|
||||
import { getRNodeVal } from '../RNodeAccessor';
|
||||
import { isArray } from '../../inulax/CommonUtils';
|
||||
import { RNode } from '../RNode';
|
||||
|
||||
const GET = 'get';
|
||||
const SET = 'set';
|
||||
const READ = 'read';
|
||||
const DELETE = 'delete';
|
||||
const ONCHANGE = 'onChange';
|
||||
export const GET_R_NODE = '$$getRNode';
|
||||
const PROTOTYPE = 'prototype';
|
||||
|
||||
// 数组的修改方法
|
||||
const MODIFY_ARR_FNS = new Set<string | symbol>([
|
||||
'push',
|
||||
'pop',
|
||||
'splice',
|
||||
'shift',
|
||||
'unshift',
|
||||
'reverse',
|
||||
'sort',
|
||||
'fill',
|
||||
'from',
|
||||
'copyWithin',
|
||||
]);
|
||||
|
||||
// 数组的遍历方法
|
||||
const LOOP_ARR_FNS = new Set<string | symbol>(['forEach', 'map', 'every', 'some', 'filter', 'join']);
|
||||
|
||||
export function createProxy<T extends any>(proxyNode: RNode) {
|
||||
return new Proxy(proxyNode, {
|
||||
get,
|
||||
set,
|
||||
});
|
||||
}
|
||||
|
||||
const FNS: Record<typeof GET | typeof READ | typeof DELETE | typeof ONCHANGE, (args: RNode) => any> = {
|
||||
[GET]: getFn,
|
||||
[READ]: readFn,
|
||||
[DELETE]: deleteFn,
|
||||
[ONCHANGE]: onChangeFn,
|
||||
};
|
||||
|
||||
function get(rNode: RNode, key: string | symbol): any {
|
||||
// 处理 get, read, delete, onchange 方法
|
||||
const fn = FNS[key];
|
||||
if (fn) {
|
||||
return () => fn(rNode);
|
||||
}
|
||||
|
||||
// 调用set()方法
|
||||
if (key === SET) {
|
||||
return function (val: any) {
|
||||
rNode.set(val);
|
||||
};
|
||||
}
|
||||
|
||||
if (key === GET_R_NODE) {
|
||||
return rNode;
|
||||
}
|
||||
|
||||
const rawObj = getRNodeVal(rNode);
|
||||
|
||||
// const value = rawObj !== undefined ? Reflect.get(rawObj, key) : rawObj;
|
||||
const value = rawObj !== undefined ? rawObj[key] : rawObj;
|
||||
|
||||
// 对于prototype不做代理
|
||||
if (key === PROTOTYPE) {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (isArray(rawObj) && key === 'length') {
|
||||
// 标记依赖
|
||||
// trackReactiveData(rNode);
|
||||
return value;
|
||||
}
|
||||
|
||||
// 处理数组的方法
|
||||
if (typeof value === 'function') {
|
||||
if (isArray(rawObj)) {
|
||||
// 处理数组的修改方法
|
||||
if (MODIFY_ARR_FNS.has(key)) {
|
||||
return (...args: any[]) => {
|
||||
// 调用数组方法的时候,前后是相同的引用,所以需要先浅拷贝数组,并在浅拷贝的数组上进行操作
|
||||
const value = rawObj.slice();
|
||||
const ret = value[key](...args);
|
||||
// 调用了数组的修改方法,默认值有变化
|
||||
// setRNodeVal(rNode, value, true, true);
|
||||
|
||||
return ret;
|
||||
};
|
||||
} else if (LOOP_ARR_FNS.has(key)) {
|
||||
// 处理数组的遍历方法
|
||||
// 标记被使用了
|
||||
// trackReactiveData(rNode);
|
||||
|
||||
return function (callBackFn: any, thisArg?: any) {
|
||||
function cb(_: any, index: number, array: any[]) {
|
||||
const idx = String(index);
|
||||
const itemProxy = getOrCreateChildProxy(array[idx], rNode, idx);
|
||||
return callBackFn(itemProxy, index, array);
|
||||
}
|
||||
|
||||
return rawObj[key](cb, thisArg);
|
||||
};
|
||||
}
|
||||
}
|
||||
return value.bind(rawObj);
|
||||
}
|
||||
|
||||
return getOrCreateChildProxy(value, rNode, key);
|
||||
}
|
||||
|
||||
function set(proxyNode: any, key: string, value: any, receiver: any): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
// get()调用的处理
|
||||
function getFn(node: RNode) {
|
||||
return node.get();
|
||||
}
|
||||
|
||||
function readFn(node: RNode) {
|
||||
return getRNodeVal(node);
|
||||
}
|
||||
|
||||
// delete()调用的处理
|
||||
function deleteFn() {}
|
||||
|
||||
// onChange()调用的处理
|
||||
function onChangeFn() {}
|
|
@ -145,10 +145,10 @@ export type VNode = {
|
|||
|
||||
belongClassVNode: VNode | null, // 记录JSXElement所属class vNode,处理ref的时候使用
|
||||
|
||||
// 状态管理器HorizonX使用
|
||||
// 状态管理器InulaX使用
|
||||
isStoreChange: boolean,
|
||||
observers: Set<any> | null, // 记录这个函数组件/类组件依赖哪些Observer
|
||||
classComponentWillUnmount: Function | null, // HorizonX会在classComponentWillUnmount中清除对VNode的引入用
|
||||
classComponentWillUnmount: Function | null, // InulaX会在classComponentWillUnmount中清除对VNode的引入用
|
||||
src: Source | null, // 节点所在代码位置
|
||||
|
||||
// reactive
|
||||
|
|
|
@ -16,7 +16,7 @@
|
|||
import type { VNode } from '../Types';
|
||||
import { FlagUtils } from '../vnode/VNodeFlags';
|
||||
import { TYPE_COMMON_ELEMENT, TYPE_FRAGMENT, TYPE_PORTAL } from '../../external/JSXElementType';
|
||||
import { DomText, DomPortal, Fragment, DomComponent } from '../vnode/VNodeTags';
|
||||
import { ReactiveComponent, DomText, DomPortal, Fragment, DomComponent } from '../vnode/VNodeTags';
|
||||
import {
|
||||
updateVNode,
|
||||
createVNodeFromElement,
|
||||
|
|
|
@ -13,7 +13,7 @@
|
|||
* See the Mulan PSL v2 for more details.
|
||||
*/
|
||||
|
||||
import { watch } from '../../horizonx/proxy/watch';
|
||||
import { watch } from '../../inulax/proxy/watch';
|
||||
|
||||
export function useWatchImpl(fn: () => void) {
|
||||
watch(fn);
|
||||
|
|
|
@ -30,7 +30,7 @@ import {
|
|||
DomText,
|
||||
DomPortal,
|
||||
SuspenseComponent,
|
||||
MemoComponent,
|
||||
MemoComponent, ReactiveComponent,
|
||||
} from '../vnode/VNodeTags';
|
||||
import { FlagUtils, ResetText, Clear, Update, DirectAddition } from '../vnode/VNodeFlags';
|
||||
import { mergeDefaultProps } from '../render/LazyComponent';
|
||||
|
@ -224,7 +224,7 @@ function unmountDomComponents(vNode: VNode): void {
|
|||
currentParentIsValid = true;
|
||||
}
|
||||
|
||||
if (node.tag === DomComponent || node.tag === DomText) {
|
||||
if (node.tag === DomComponent || node.tag === DomText || node.tag === ReactiveComponent) {
|
||||
let nd = node;
|
||||
|
||||
// 卸载vNode,递归遍历子vNode
|
||||
|
|
Loading…
Reference in New Issue