2024-01-19 16:38:41 +08:00
|
|
|
import { renderWatch } from './renderWatch'
|
2024-03-16 18:54:36 +08:00
|
|
|
import { type Block, type Fragment, fragmentKey } from './apiRender'
|
2024-01-30 04:15:52 +08:00
|
|
|
import { type EffectScope, effectScope } from '@vue/reactivity'
|
2024-02-26 21:38:04 +08:00
|
|
|
import { createComment, createTextNode, insert, remove } from './dom/element'
|
2024-01-19 16:38:41 +08:00
|
|
|
|
2024-01-30 04:15:52 +08:00
|
|
|
type BlockFn = () => Block
|
|
|
|
|
2024-02-08 23:22:03 +08:00
|
|
|
/*! #__NO_SIDE_EFFECTS__ */
|
2024-01-19 16:38:41 +08:00
|
|
|
export const createIf = (
|
|
|
|
condition: () => any,
|
|
|
|
b1: BlockFn,
|
|
|
|
b2?: BlockFn,
|
|
|
|
// hydrationNode?: Node,
|
|
|
|
): Fragment => {
|
|
|
|
let branch: BlockFn | undefined
|
|
|
|
let parent: ParentNode | undefined | null
|
2024-01-30 04:15:52 +08:00
|
|
|
let block: Block | undefined
|
|
|
|
let scope: EffectScope | undefined
|
2024-01-31 13:16:03 +08:00
|
|
|
const anchor = __DEV__ ? createComment('if') : createTextNode()
|
2024-01-30 04:15:52 +08:00
|
|
|
const fragment: Fragment = {
|
|
|
|
nodes: [],
|
|
|
|
anchor,
|
|
|
|
[fragmentKey]: true,
|
|
|
|
}
|
2024-01-19 16:38:41 +08:00
|
|
|
|
|
|
|
// TODO: SSR
|
|
|
|
// if (isHydrating) {
|
|
|
|
// parent = hydrationNode!.parentNode
|
|
|
|
// setCurrentHydrationNode(hydrationNode!)
|
|
|
|
// }
|
|
|
|
|
|
|
|
renderWatch(
|
|
|
|
() => !!condition(),
|
2024-01-29 03:11:30 +08:00
|
|
|
value => {
|
2024-01-19 16:38:41 +08:00
|
|
|
parent ||= anchor.parentNode
|
2024-01-30 04:15:52 +08:00
|
|
|
if (block) {
|
|
|
|
scope!.stop()
|
|
|
|
remove(block, parent!)
|
|
|
|
}
|
2024-01-19 16:38:41 +08:00
|
|
|
if ((branch = value ? b1 : b2)) {
|
2024-01-30 04:15:52 +08:00
|
|
|
scope = effectScope()
|
|
|
|
fragment.nodes = block = scope.run(branch)!
|
2024-01-19 16:38:41 +08:00
|
|
|
parent && insert(block, parent, anchor)
|
|
|
|
} else {
|
2024-01-30 04:15:52 +08:00
|
|
|
scope = block = undefined
|
2024-01-19 16:38:41 +08:00
|
|
|
fragment.nodes = []
|
|
|
|
}
|
|
|
|
},
|
|
|
|
{ immediate: true },
|
|
|
|
)
|
|
|
|
|
|
|
|
// TODO: SSR
|
|
|
|
// if (isHydrating) {
|
|
|
|
// parent!.insertBefore(anchor, currentHydrationNode)
|
|
|
|
// }
|
|
|
|
|
|
|
|
return fragment
|
|
|
|
}
|