index.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var vue = require('vue');
  4. var vnode = require('../../utils/vue/vnode.js');
  5. const getOrderedChildren = (vm, childComponentName, children) => {
  6. const nodes = vnode.flattedChildren(vm.subTree).filter(
  7. (n) => {
  8. var _a;
  9. return vue.isVNode(n) && ((_a = n.type) == null ? void 0 : _a.name) === childComponentName && !!n.component;
  10. }
  11. );
  12. const uids = nodes.map((n) => n.component.uid);
  13. return uids.map((uid) => children[uid]).filter((p) => !!p);
  14. };
  15. const useOrderedChildren = (vm, childComponentName) => {
  16. const children = vue.shallowRef({});
  17. const orderedChildren = vue.shallowRef([]);
  18. const nodesMap = /* @__PURE__ */ new WeakMap();
  19. const addChild = (child) => {
  20. children.value[child.uid] = child;
  21. vue.triggerRef(children);
  22. vue.onMounted(() => {
  23. const childNode = child.getVnode().el;
  24. const parentNode = childNode.parentNode;
  25. if (!nodesMap.has(parentNode)) {
  26. nodesMap.set(parentNode, []);
  27. const originalFn = parentNode.insertBefore.bind(parentNode);
  28. parentNode.insertBefore = (node, anchor) => {
  29. const shouldSortChildren = nodesMap.get(parentNode).some((el) => node === el || anchor === el);
  30. if (shouldSortChildren)
  31. vue.triggerRef(children);
  32. return originalFn(node, anchor);
  33. };
  34. }
  35. nodesMap.get(parentNode).push(childNode);
  36. });
  37. };
  38. const removeChild = (child) => {
  39. delete children.value[child.uid];
  40. vue.triggerRef(children);
  41. const childNode = child.getVnode().el;
  42. const parentNode = childNode.parentNode;
  43. const childNodes = nodesMap.get(parentNode);
  44. const index = childNodes.indexOf(childNode);
  45. childNodes.splice(index, 1);
  46. };
  47. const sortChildren = () => {
  48. orderedChildren.value = getOrderedChildren(
  49. vm,
  50. childComponentName,
  51. children.value
  52. );
  53. };
  54. const IsolatedRenderer = (props) => {
  55. return props.render();
  56. };
  57. const ChildrenSorter = vue.defineComponent({
  58. setup(_, { slots }) {
  59. return () => {
  60. sortChildren();
  61. return slots.default ? vue.h(IsolatedRenderer, {
  62. render: slots.default
  63. }) : null;
  64. };
  65. }
  66. });
  67. return {
  68. children: orderedChildren,
  69. addChild,
  70. removeChild,
  71. ChildrenSorter
  72. };
  73. };
  74. exports.useOrderedChildren = useOrderedChildren;
  75. //# sourceMappingURL=index.js.map