import { MIN_WIDTH_COL_RESIZE } from '@squirrel/components/p-table/p-table.types'; import { nextTick, onBeforeUnmount, onMounted, type Ref, ref, watch } from 'vue'; type Options = { enabled: Ref; ths: Ref; }; export const usePTableColResize = (options: Options) => { const { enabled, ths } = options; const isColResizing = ref(false); const colResizeHandleLeft = ref('0px'); const colResizingWidth = ref(0); const colResizingIndex = ref(-1); const colResize = (e: MouseEvent) => { colResizeHandleLeft.value = `${e.clientX}px`; if (isColResizing.value) { document.body.classList.add('cursor-col-resize'); const th = ths.value[colResizingIndex.value]; const rect = th.getBoundingClientRect(); const diff = e.clientX - rect.left - th.offsetWidth; const widthToSet = th.offsetWidth + diff; setColResizingWidth(widthToSet); colResizeHandleLeft.value = e.clientX < rect.left ? '0px' : `${e.clientX}px`; } }; const colResizeStart = (e: MouseEvent, i: number) => { // We want to preventDefault only for the single click to disable selection while dragging // This still allows for the double click to fire if (e.detail === 1) { e.preventDefault(); isColResizing.value = true; colResizingWidth.value = ths.value[i].offsetWidth; colResizingIndex.value = i; } }; const colResizeStop = () => { if (!isColResizing.value) { return; } isColResizing.value = false; document.body.classList.remove('cursor-col-resize'); }; const colResizeFitToData = (colIndex: number) => { isColResizing.value = true; const tds = ths.value[colIndex] .closest('table') ?.querySelectorAll('tbody tr td:nth-child(' + (colIndex + 1) + ') div.w-max'); if (!tds) { return; } const maxWidth = [...tds].reduce((max, td) => { const width = td.getBoundingClientRect().width; return width > max ? width : max; }, 0); setColResizingWidth(maxWidth); nextTick(() => { isColResizing.value = false; }); }; const setColResizingWidth = (width: number) => { colResizingWidth.value = width > MIN_WIDTH_COL_RESIZE ? Math.ceil(width) : MIN_WIDTH_COL_RESIZE; }; onMounted(() => { enabled.value && document.addEventListener('mouseup', colResizeStop); }); onBeforeUnmount(() => { enabled.value && document.removeEventListener('mouseup', colResizeStop); }); watch(enabled, (nV) => { if (nV) { document.addEventListener('mouseup', colResizeStop); } else { document.removeEventListener('mouseup', colResizeStop); } }); return { isColResizing, colResizeHandleLeft, colResizingIndex, colResizingWidth, colResize, colResizeStart, colResizeStop, colResizeFitToData, }; };