layout-observer.mjs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { computed, getCurrentInstance, onBeforeMount, onMounted, onUnmounted, onUpdated } from "vue";
  2. //#region ../../packages/components/table/src/layout-observer.ts
  3. function useLayoutObserver(root) {
  4. const instance = getCurrentInstance();
  5. onBeforeMount(() => {
  6. tableLayout.value.addObserver(instance);
  7. });
  8. onMounted(() => {
  9. onColumnsChange(tableLayout.value);
  10. onScrollableChange(tableLayout.value);
  11. });
  12. onUpdated(() => {
  13. onColumnsChange(tableLayout.value);
  14. onScrollableChange(tableLayout.value);
  15. });
  16. onUnmounted(() => {
  17. tableLayout.value.removeObserver(instance);
  18. });
  19. const tableLayout = computed(() => {
  20. const layout = root.layout;
  21. if (!layout) throw new Error("Can not find table layout.");
  22. return layout;
  23. });
  24. const onColumnsChange = (layout) => {
  25. const cols = root.vnode.el?.querySelectorAll("colgroup > col") || [];
  26. if (!cols.length) return;
  27. const flattenColumns = layout.getFlattenColumns();
  28. const columnsMap = {};
  29. flattenColumns.forEach((column) => {
  30. columnsMap[column.id] = column;
  31. });
  32. for (let i = 0, j = cols.length; i < j; i++) {
  33. const col = cols[i];
  34. const column = columnsMap[col.getAttribute("name")];
  35. if (column) col.setAttribute("width", column.realWidth || column.width);
  36. }
  37. };
  38. const onScrollableChange = (layout) => {
  39. const cols = root.vnode.el?.querySelectorAll("colgroup > col[name=gutter]") || [];
  40. for (let i = 0, j = cols.length; i < j; i++) cols[i].setAttribute("width", layout.scrollY.value ? layout.gutterWidth : "0");
  41. const ths = root.vnode.el?.querySelectorAll("th.gutter") || [];
  42. for (let i = 0, j = ths.length; i < j; i++) {
  43. const th = ths[i];
  44. th.style.width = layout.scrollY.value ? `${layout.gutterWidth}px` : "0";
  45. th.style.display = layout.scrollY.value ? "" : "none";
  46. }
  47. };
  48. return {
  49. tableLayout: tableLayout.value,
  50. onColumnsChange,
  51. onScrollableChange
  52. };
  53. }
  54. //#endregion
  55. export { useLayoutObserver as default };
  56. //# sourceMappingURL=layout-observer.mjs.map