collection.mjs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { ref, provide, inject, onMounted, unref, onBeforeUnmount } from 'vue';
  2. import Collection from './collection2.mjs';
  3. import CollectionItem from './collection-item.mjs';
  4. const COLLECTION_ITEM_SIGN = `data-el-collection-item`;
  5. const createCollectionWithScope = (name) => {
  6. const COLLECTION_NAME = `El${name}Collection`;
  7. const COLLECTION_ITEM_NAME = `${COLLECTION_NAME}Item`;
  8. const COLLECTION_INJECTION_KEY = Symbol(COLLECTION_NAME);
  9. const COLLECTION_ITEM_INJECTION_KEY = Symbol(COLLECTION_ITEM_NAME);
  10. const ElCollection = Object.assign({}, Collection, {
  11. name: COLLECTION_NAME,
  12. setup() {
  13. const collectionRef = ref();
  14. const itemMap = /* @__PURE__ */ new Map();
  15. const getItems = () => {
  16. const collectionEl = unref(collectionRef);
  17. if (!collectionEl)
  18. return [];
  19. const orderedNodes = Array.from(
  20. collectionEl.querySelectorAll(`[${COLLECTION_ITEM_SIGN}]`)
  21. );
  22. const items = [...itemMap.values()];
  23. return items.sort(
  24. (a, b) => orderedNodes.indexOf(a.ref) - orderedNodes.indexOf(b.ref)
  25. );
  26. };
  27. provide(COLLECTION_INJECTION_KEY, {
  28. itemMap,
  29. getItems,
  30. collectionRef
  31. });
  32. }
  33. });
  34. const ElCollectionItem = Object.assign({}, CollectionItem, {
  35. name: COLLECTION_ITEM_NAME,
  36. setup(_, { attrs }) {
  37. const collectionItemRef = ref();
  38. const collectionInjection = inject(COLLECTION_INJECTION_KEY, void 0);
  39. provide(COLLECTION_ITEM_INJECTION_KEY, {
  40. collectionItemRef
  41. });
  42. onMounted(() => {
  43. const collectionItemEl = unref(collectionItemRef);
  44. if (collectionItemEl) {
  45. collectionInjection.itemMap.set(collectionItemEl, {
  46. ref: collectionItemEl,
  47. ...attrs
  48. });
  49. }
  50. });
  51. onBeforeUnmount(() => {
  52. const collectionItemEl = unref(collectionItemRef);
  53. collectionInjection.itemMap.delete(collectionItemEl);
  54. });
  55. }
  56. });
  57. return {
  58. COLLECTION_INJECTION_KEY,
  59. COLLECTION_ITEM_INJECTION_KEY,
  60. ElCollection,
  61. ElCollectionItem
  62. };
  63. };
  64. export { COLLECTION_ITEM_SIGN, createCollectionWithScope };
  65. //# sourceMappingURL=collection.mjs.map