|
| 1 | +import { traverseDFS } from "./utils/traverse-dom"; |
| 2 | +import { DOM_TYPES, hFragment } from "./h"; |
| 3 | + |
| 4 | +// Replaces the slot nodes with the external content (or their default content). |
| 5 | +// You want to traverse the virtual DOM tree and if the encountered node is a slot, |
| 6 | +// replace it with the external or default content. |
| 7 | +export function fillSlots(vdom, externalContent = []) { |
| 8 | + function processNodeFn(node, parent, index) { |
| 9 | + insertViewInSlot(node, parent, index, externalContent); |
| 10 | + } |
| 11 | + |
| 12 | + traverseDFS(vdom, processNodeFn, shouldSkipBranch); |
| 13 | +} |
| 14 | + |
| 15 | +function insertViewInSlot(node, parent, index, externalContent) { |
| 16 | + if (node.type !== DOM_TYPES.SLOT) return; |
| 17 | + |
| 18 | + const defaultValue = node.children; |
| 19 | + const views = externalContent.length > 0 ? externalContent : defaultValue; |
| 20 | + |
| 21 | + const hasContent = views.length > 0; |
| 22 | + if (hasContent) { |
| 23 | + parent.children.splice(index, 1, hFragment(views)); |
| 24 | + } else { |
| 25 | + parent.children.splice(index, 1); |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +function shouldSkipBranch(node) { |
| 30 | + return node.type === DOM_TYPES.COMPONENT; |
| 31 | +} |
| 32 | + |
| 33 | +// processNode |
| 34 | +// node: the node being processed. |
| 35 | +// parent: the parent node of the node being processed. |
| 36 | +// index: the index of the node being processed in the parent’s children array. |
0 commit comments