index.mjs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { flattedChildren } from "../../utils/vue/vnode.mjs";
  2. import { defineComponent, h, isVNode, onMounted, shallowRef, triggerRef } from "vue";
  3. //#region ../../packages/hooks/use-ordered-children/index.ts
  4. const getOrderedChildren = (vm, childComponentName, children) => {
  5. return flattedChildren(vm.subTree).filter((n) => isVNode(n) && n.type?.name === childComponentName && !!n.component).map((n) => n.component.uid).map((uid) => children[uid]).filter((p) => !!p);
  6. };
  7. const useOrderedChildren = (vm, childComponentName) => {
  8. const children = shallowRef({});
  9. const orderedChildren = shallowRef([]);
  10. const nodesMap = /* @__PURE__ */ new WeakMap();
  11. const addChild = (child) => {
  12. children.value[child.uid] = child;
  13. triggerRef(children);
  14. onMounted(() => {
  15. const childNode = child.getVnode().el;
  16. const parentNode = childNode.parentNode;
  17. if (!nodesMap.has(parentNode)) {
  18. nodesMap.set(parentNode, []);
  19. const originalFn = parentNode.insertBefore.bind(parentNode);
  20. parentNode.insertBefore = (node, anchor) => {
  21. if (nodesMap.get(parentNode).some((el) => node === el || anchor === el)) triggerRef(children);
  22. return originalFn(node, anchor);
  23. };
  24. }
  25. nodesMap.get(parentNode).push(childNode);
  26. });
  27. };
  28. const removeChild = (child) => {
  29. delete children.value[child.uid];
  30. triggerRef(children);
  31. const childNode = child.getVnode().el;
  32. const parentNode = childNode.parentNode;
  33. const childNodes = nodesMap.get(parentNode);
  34. const index = childNodes.indexOf(childNode);
  35. childNodes.splice(index, 1);
  36. };
  37. const sortChildren = () => {
  38. orderedChildren.value = getOrderedChildren(vm, childComponentName, children.value);
  39. };
  40. const IsolatedRenderer = (props) => {
  41. return props.render();
  42. };
  43. return {
  44. children: orderedChildren,
  45. addChild,
  46. removeChild,
  47. ChildrenSorter: defineComponent({ setup(_, { slots }) {
  48. return () => {
  49. sortChildren();
  50. return slots.default ? h(IsolatedRenderer, { render: slots.default }) : null;
  51. };
  52. } })
  53. };
  54. };
  55. //#endregion
  56. export { useOrderedChildren };
  57. //# sourceMappingURL=index.mjs.map