Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: support table column resizing (#2507)
Liu Ji390f0478bcc4
diff --git a/frontend/src/views/sql-editor/TablePanel/DataTable.vue b/frontend/src/views/sql-editor/TablePanel/DataTable.vueindex e358d95df7..3cd29547b1 100644--- a/frontend/src/views/sql-editor/TablePanel/DataTable.vue+++ b/frontend/src/views/sql-editor/TablePanel/DataTable.vue@@ -2,20 +2,37 @@<divclass="bb-data-table relative w-full h-full overflow-hidden flex flex-col">- <div ref="wrapperRef" class="w-full flex-1 overflow-hidden">+ <div class="w-full flex-1 overflow-hidden"><div- class="inner-wrapper max-h-full overflow-auto border-y border-block-border"- :class="data.length === 0 && 'border-b-0'"+ ref="scrollerRef"+ class="inner-wrapper max-h-full w-full overflow-auto border-y border-r border-block-border"+ :class="data.length === 0 && 'border-b-0 border-r-0'">- <table class="border-collapse min-w-full">+ <div+ class="header-track absolute z-0 left-0 top-0 right-0 h-[34px] border border-block-border bg-gray-50"+ />++ <table+ ref="tableRef"+ class="relative border-collapse table-fixed z-[1]"+ v-bind="tableResize.getTableProps()"+ ><thead class="sticky top-0 z-[1] shadow"><tr><thv-for="header of table.getFlatHeaders()":key="header.index"- class="relative px-2 py-2 min-w-[2rem] truncate text-left bg-gray-50 text-xs font-medium text-gray-500 tracking-wider border border-t-0 border-block-border border-b-0"+ class="relative px-2 py-2 min-w-[2rem] text-left bg-gray-50 text-xs font-medium text-gray-500 tracking-wider border border-t-0 border-block-border border-b-0"+ v-bind="tableResize.getColumnProps(header.index)">{{ header.column.columnDef.header }}++ <!-- The drag-to-resize handler -->+ <div+ class="absolute w-[8px] right-0 top-0 bottom-0 cursor-col-resize"+ @dblclick="tableResize.autoAdjustColumnWidth([header.index])"+ @pointerdown="tableResize.startResizing(header.index)"+ /></th></tr></thead>@@ -23,11 +40,12 @@<trv-for="(row, rowIndex) of table.getRowModel().rows":key="rowIndex"+ class="group"><tdv-for="(cell, cellIndex) of row.getVisibleCells()":key="cellIndex"- class="px-2 py-2 text-sm leading-5 whitespace-pre-wrap border border-block-border"+ class="px-2 py-1 text-sm leading-5 whitespace-pre-wrap break-all border border-block-border group-last:border-b-0 group-even:bg-gray-50/50">{{ cell.getValue() }}</td>@@ -67,6 +85,7 @@ import {ColumnDef,} from "@tanstack/vue-table";import { NPagination } from "naive-ui";+import useTableColumnWidthLogic from "./useTableResize";export type DataTableColumn = {key: string;@@ -87,7 +106,15 @@ const props = defineProps({},});-const wrapperRef = ref<HTMLDivElement>();+const scrollerRef = ref<HTMLDivElement>();+const tableRef = ref<HTMLTableElement>();++const tableResize = useTableColumnWidthLogic({+ tableRef,+ scrollerRef,+ minWidth: 64, // 4rem+ maxWidth: 640, // 40rem+});const data = computed(() => props.data);const columns = computed(() =>@@ -114,21 +141,18 @@ const showPagination = computed(() => props.data.length > PAGE_SIZES[0]);const handleChangePage = (page: number) => {table.setPageIndex(page - 1);- wrapperRef.value?.scrollTo(0, 0);+ scrollerRef.value?.scrollTo(0, 0);};-watch(data, () => {- nextTick(() => {- wrapperRef.value?.scrollTo(0, 0);- });-});+watch(+ () => props.columns.map((col) => col.title).join("|"),+ () => {+ nextTick(() => {+ // Re-calculate the column widths once the column definition changed.+ scrollerRef.value?.scrollTo(0, 0);+ tableResize.reset();+ });+ },+ { immediate: true }+);</script>--<style>-.bb-data-table tbody tr:first-child td {- @apply border-t-0;-}-.bb-data-table tbody tr:last-child td {- @apply border-b-0;-}-</style>diff --git a/frontend/src/views/sql-editor/TablePanel/useTableResize.ts b/frontend/src/views/sql-editor/TablePanel/useTableResize.tsnew file mode 100644index 0000000000..8fdccd573c--- /dev/null+++ b/frontend/src/views/sql-editor/TablePanel/useTableResize.ts@@ -0,0 +1,228 @@+import { computed, onBeforeUnmount, reactive, Ref, watch } from "vue";+import { useEventListener, usePointer } from "@vueuse/core";+import { sumBy } from "lodash-es";++export type TableResizeOptions = {+ tableRef: Ref<HTMLTableElement | undefined>;+ scrollerRef: Ref<HTMLElement | undefined>;+ minWidth: number;+ maxWidth: number;+};++type ColumnProps = {+ width: number;+};++type DragState = {+ start: number;+ index: number;+ initialWidth: number;+};++type LocalState = {+ columns: ColumnProps[];+ drag?: DragState;+ isAutoAdjusting: boolean;+};++const useTableResize = (options: TableResizeOptions) => {+ const state = reactive<LocalState>({+ columns: [],+ drag: undefined,+ isAutoAdjusting: false,+ });+ const pointer = usePointer();++ const table = computed(() => options.tableRef.value!);++ const normalizeWidth = (width: number) => {+ const { maxWidth, minWidth } = options;+ if (width > maxWidth) return maxWidth;+ if (width < minWidth) return minWidth;+ return width;+ };++ const reset = () => {+ if (!table.value) return;++ state.drag = undefined;+ state.isAutoAdjusting = false;++ const thList = Array.from(table.value.querySelectorAll("th"));+ const columnCount = thList.length;+ state.columns = new Array(columnCount);++ const indexList: number[] = [];+ for (let i = 0; i < columnCount; i++) {+ indexList.push(i);+ state.columns[i] = {+ width: 0, // For auto adjust below+ };+ }++ // Calculate a friendly width for every column when the first render happened.+ requestAnimationFrame(() => {+ autoAdjustColumnWidth(indexList);+ });+ };++ // Automatically estimate the width of a column.+ // Like double-clicking a cell border of Excel.+ // Able to estimate multiple columns in a time.+ const autoAdjustColumnWidth = (indexList: number[]): Promise<number[]> => {+ return new Promise((resolve) => {+ const cellListOfEachColumn = indexList.map((index, i) => {+ const pseudo = `:nth-child(${index + 1})`;+ // Find all cells in this column+ const cellList = Array.from(+ table.value.querySelectorAll(`th${pseudo}, td${pseudo}`)+ ) as HTMLElement[];+ return cellList;+ });++ // Update the cells' and table's style to estimate the width.+ state.isAutoAdjusting = true;+ cellListOfEachColumn.forEach((cellList) => {+ cellList.forEach((cell) => {+ cell.style.whiteSpace = "nowrap";+ cell.style.overflow = "visible";+ cell.style.width = "auto";+ cell.style.maxWidth = `${options.maxWidth}px`;+ cell.style.minWidth = `${options.minWidth}px`;+ });+ });+ const tableWidthBackup = table.value.style.width;+ table.value.style.width = "auto";++ // Wait for the next render frame.+ requestAnimationFrame(() => {+ // Read the rendered widths.++ const widthList = indexList.map((index, i) => {+ const cellList = cellListOfEachColumn[i];+ const th = cellList[0];+ const stretchedWidth = getElementWidth(th);+ const finalWidth = normalizeWidth(stretchedWidth);++ state.columns[index].width = finalWidth;++ return finalWidth;+ });++ // Reset the cells' and table's style.+ cellListOfEachColumn.forEach((cellList) => {+ cellList.forEach((cell) => {+ cell.style.whiteSpace = "";+ cell.style.overflow = "";+ cell.style.width = "";+ cell.style.maxWidth = "";+ cell.style.minWidth = "";+ });+ });+ table.value.style.width = tableWidthBackup;+ state.isAutoAdjusting = false;++ resolve(widthList);+ // Style bindings will be automatically updated next frame.+ });+ });+ };++ // Record the initial state of dragging.+ const startResizing = (index: number) => {+ state.drag = {+ start: pointer.x.value,+ index,+ initialWidth: state.columns[index].width,+ };+ toggleDragStyle(table, true);+ };++ // Watch the drag moving.+ watch(pointer.x, () => {+ const { drag } = state;+ if (!drag) return;+ const { start, index, initialWidth } = drag;++ // Calculate the expectedWidth according to the pointer's position.+ const offset = pointer.x.value - start;+ const expectedWidth = initialWidth + offset;+ state.columns[index].width = normalizeWidth(expectedWidth);+ if (index === state.columns.length - 1) {+ // When resizing the last column, Keep the horizontal scroll at the end of the container.+ scrollMaxX(options.scrollerRef.value);+ }+ });++ // Reset dragging state when mouse button released.+ useEventListener("pointerup", () => {+ if (state.drag) {+ state.drag = undefined;+ toggleDragStyle(table, false);+ }+ });++ const getColumnProps = (index: number) => {+ const column = state.columns[index];+ if (!column) return {};+ return {+ style: {+ width: `${column.width}px`,+ },+ class: "truncate",+ "data-index": index,+ };+ };++ const getTableProps = () => {+ if (state.isAutoAdjusting) {+ return {};+ }+ const totalWidth = sumBy(state.columns, (col) => col.width);+ return {+ style: {+ width: `${totalWidth}px`,+ },+ };+ };++ onBeforeUnmount(() => {+ toggleDragStyle(table, false);+ });++ return {+ reset,+ getColumnProps,+ getTableProps,+ autoAdjustColumnWidth,+ startResizing,+ };+};++export default useTableResize;++const getElementWidth = (elem: HTMLElement) => {+ const rect = elem.getBoundingClientRect();+ return rect.width;+};++const scrollMaxX = (elem: HTMLElement | undefined) => {+ if (!elem) return;+ const max = elem.scrollWidth;+ elem.scrollTo(max, elem.scrollTop);+};++const toggleDragStyle = (+ table: Ref<HTMLTableElement | undefined>,+ on: boolean+) => {+ if (on) {+ // Prevent text selection while dragging.+ table.value?.classList.add("select-none");+ // Set the cursor style.+ document.body.classList.add("cursor-col-resize");+ } else {+ table.value?.classList.remove("select-none");+ document.body.classList.remove("cursor-col-resize");+ }+};