]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
feat(runtime-vapor): export createBranch
author三咲智子 Kevin Deng <sxzz@sxzz.moe>
Thu, 14 Nov 2024 20:49:06 +0000 (04:49 +0800)
committer三咲智子 Kevin Deng <sxzz@sxzz.moe>
Thu, 14 Nov 2024 20:49:06 +0000 (04:49 +0800)
packages/runtime-vapor/src/apiCreateIf.ts
packages/runtime-vapor/src/index.ts

index 4356fbf292469368f8a21af55199a54cfb587129..63d733b20609197e1df54abe5f45a1c8821d65b8 100644 (file)
@@ -6,19 +6,21 @@ import { createComment, createTextNode, insert, remove } from './dom/element'
 type BlockFn = () => Block
 
 /*! #__NO_SIDE_EFFECTS__ */
-export const createIf = (
-  condition: () => any,
-  b1: BlockFn,
-  b2?: BlockFn,
+export function createBranch(
+  expression: () => any,
+  render: (value: any) => BlockFn | undefined,
   once?: boolean,
+  commentLabel?: string,
   // hydrationNode?: Node,
-): Fragment => {
+): Fragment {
   let newValue: any
   let oldValue: any
   let branch: BlockFn | undefined
   let block: Block | undefined
   let scope: EffectScope | undefined
-  const anchor = __DEV__ ? createComment('if') : createTextNode()
+  const anchor = __DEV__
+    ? createComment(commentLabel || 'dynamic')
+    : createTextNode()
   const fragment: Fragment = shallowReactive({
     nodes: [],
     anchor,
@@ -32,9 +34,9 @@ export const createIf = (
   // }
 
   if (once) {
-    doIf()
+    doChange()
   } else {
-    renderEffect(() => doIf())
+    renderEffect(() => doChange())
   }
 
   // TODO: SSR
@@ -44,14 +46,15 @@ export const createIf = (
 
   return fragment
 
-  function doIf() {
-    if ((newValue = !!condition()) !== oldValue) {
+  function doChange() {
+    if ((newValue = expression()) !== oldValue) {
       const parent = anchor.parentNode
       if (block) {
         scope!.stop()
         remove(block, parent!)
       }
-      if ((branch = (oldValue = newValue) ? b1 : b2)) {
+      oldValue = newValue
+      if ((branch = render(newValue))) {
         scope = effectScope()
         fragment.nodes = block = scope.run(branch)!
         parent && insert(block, parent, anchor)
@@ -62,3 +65,19 @@ export const createIf = (
     }
   }
 }
+
+/*! #__NO_SIDE_EFFECTS__ */
+export function createIf(
+  condition: () => any,
+  b1: BlockFn,
+  b2?: BlockFn,
+  once?: boolean,
+  // hydrationNode?: Node,
+): Fragment {
+  return createBranch(
+    () => !!condition(),
+    value => (value ? b1 : b2),
+    once,
+    __DEV__ ? 'if' : undefined,
+  )
+}
index f1d77f2ee8f16acce487102a2b10b063815f7733..d9afed312abc1fe95708ae83a7c1f6e0eaa901b5 100644 (file)
@@ -126,7 +126,7 @@ export {
   type ObjectPlugin,
   type FunctionPlugin,
 } from './apiCreateVaporApp'
-export { createIf } from './apiCreateIf'
+export { createBranch, createIf } from './apiCreateIf'
 export { createFor, createForSlots } from './apiCreateFor'
 export { createComponent } from './apiCreateComponent'
 export { createSelector } from './apiCreateSelector'