index.js 2.3 KB

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