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(sql-editor): mass query result data rendering in SQL Editor (#13880)
Liu Ji15b020a08b88
diff --git a/frontend/package.json b/frontend/package.jsonindex 03e624cb3e..f6410ad677 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -52,7 +52,7 @@"monaco-editor": "0.45.0","monaco-editor-workers": "0.45.0","monaco-languageclient": "7.3.0",- "naive-ui": "2.39.0",+ "naive-ui": "2.40.1","nice-grpc-common": "^2.0.2","nice-grpc-error-details": "^0.2.4","nice-grpc-web": "^3.3.2",@@ -71,6 +71,7 @@"slug": "9.1.0","splitpanes": "3.1.5","sql-formatter": "15.4.1",+ "string-width": "^7.2.0","uuid": "10.0.0","vdirs": "^0.1.8","vscode": "npm:@codingame/[email protected]",@@ -82,7 +83,7 @@"vscode-ws-jsonrpc": "3.3.2","vue": "3.4.31","vuedraggable": "^4.1.0",- "vueuc": "0.4.58"+ "vueuc": "0.4.64"},"devDependencies": {"@iconify/json": "2.2.232",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex cb7e5ae7d6..17d28ceea4 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -105,8 +105,8 @@ importers:specifier: 7.3.0version: 7.3.0(@codingame/[email protected])([email protected])naive-ui:- specifier: 2.39.0- version: 2.39.0([email protected]([email protected]))+ specifier: 2.40.1+ version: 2.40.1([email protected]([email protected]))nice-grpc-common:specifier: ^2.0.2version: 2.0.2@@ -161,6 +161,9 @@ importers:sql-formatter:specifier: 15.4.1version: 15.4.1+ string-width:+ specifier: ^7.2.0+ version: 7.2.0uuid:specifier: 10.0.0version: 10.0.0@@ -195,8 +198,8 @@ importers:specifier: ^4.1.0version: 4.1.0([email protected]([email protected]))vueuc:- specifier: 0.4.58- version: 0.4.58([email protected]([email protected]))+ specifier: 0.4.64+ version: 0.4.64([email protected]([email protected]))devDependencies:'@iconify/json':specifier: 2.2.232@@ -1982,14 +1985,13 @@ packages:resolution: {integrity: sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==}engines: {node: '>=18'}- resolution: {integrity: sha512-fJCG3Pwx8HUoLhkepdsP7Z5RsucUi+ZBOxyM5d0ZZ6c4SdYustq0VMmOu6Wf7bli+yS/Jwp91TOCqn9jMcVrUA==}+ resolution: {integrity: sha512-ZfbMu+nbzW0mEzC8VZrLiSWvUIaI3aRHeq33mTe7Y38UctKukgqPR4nTDwcwS4d64Gf8GghnVsroBuMY3eiTeA==}peerDependencies:- date-fns: 2.x+ date-fns: ^3.0.0- resolution: {integrity: sha512-fnULvOpxnC5/Vg3NCiWelDsLiUc9bRwAPs/+LfTLNvetFCtCTN+yQz15C/fs4AwX1R9K5GLtLfn8QW+dWisaAw==}- engines: {node: '>=0.11'}+ resolution: {integrity: sha512-fRHTG8g/Gif+kSh50gaGEdToemgfj74aRX3swtiouboip5JDLAyDE9F11nHMIcvOaXeOC6D7SpNhi7uFyB7Uww==}resolution: {integrity: sha512-okzr3f11N6WuqYtZSvm+F776mB41wRZMhKP+hc34YdW+KmtYYK9iqvHSwo2k9FEH3fhGXvOPV6yz2IcSrfRUDg==}@@ -2125,6 +2127,9 @@ packages:resolution: {integrity: sha512-tJdCJitoy2lrC2ldJcqN4vkqJ00lT+tOWNT1hBJjO/3FDMJa5TTIiYGCKGkn/WfCyOzUMObeohbVTj00fhiLiA==}engines: {node: '>=14.16'}+ resolution: {integrity: sha512-EC+0oUMY1Rqm4O6LLrgjtYDvcVYTy7chDnM4Q7030tP4Kwj3u/pR6gP9ygnp2CJMK5Gq+9Q2oqmrFJAz01DXjw==}+resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==}@@ -2366,6 +2371,10 @@ packages:resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==}engines: {node: 6.* || 8.* || >= 10.*}+ resolution: {integrity: sha512-2nk+7SIVb14QrgXFHcm84tD4bKQz0RxPuMT8Ag5KPOq7J5fEmAg0UbXdTOSHqNuHSU28k55qnceesxXRZGzKWA==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==}@@ -2916,8 +2925,8 @@ packages:resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==}- resolution: {integrity: sha512-5oUJzRG+rtLSH8eRU+fJvVYiQids2BxF9jp+fwGoAqHOptEINrBlgBu9uy+95RHE5FLJ7Q/z41o+qkoGnUrKxQ==}+ resolution: {integrity: sha512-3NkL+vLRQZKQxCHXa+7xiD6oM74OrQELaehDkGYRYpr6kjT+JJB+Z7h+5LC70gn8VkbgCAETv0+uRWF+6MLlgQ==}peerDependencies:vue: ^3.0.0@@ -3512,6 +3521,10 @@ packages:resolution: {integrity: sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==}engines: {node: '>=12'}+ resolution: {integrity: sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-ev2QzSzWPYmy9GuqfIVildA4OdcGLeFZQrq5ys6RtiuF+RQQiZWr8TZNyAcuVXyQRYfEO+MsoB/1BuQVhOJuoQ==}@@ -3955,8 +3968,8 @@ packages:peerDependencies:vue: ^3.0.1- resolution: {integrity: sha512-Wnj/N8WbPRSxSt+9ji1jtDHPzda5h2OH/0sFBhvdxDRuyCZbjGg3/cKMaKqEoe+dErTexG2R+i6Q8S/Toq1MYg==}+ resolution: {integrity: sha512-wlJQj7fIwKK2pOEoOq4Aro8JdPOGpX8aWQhV8YkTW9OgWD2uj2O8ANzvSsIGjx7LTOc7QbS7sXdxHi6XvRnHPA==}peerDependencies:vue: ^3.0.11@@ -5845,13 +5858,11 @@ snapshots:whatwg-mimetype: 4.0.0whatwg-url: 14.0.0dependencies:- date-fns: 2.30.0+ date-fns: 3.6.0- dependencies:- '@babel/runtime': 7.24.6+ [email protected]: {}@@ -5951,6 +5962,8 @@ snapshots:+ [email protected]: {}+@@ -6248,6 +6261,8 @@ snapshots:+ [email protected]: {}+@@ -6771,7 +6786,7 @@ snapshots:object-assign: 4.1.1thenify-all: 1.6.0dependencies:'@css-render/plugin-bem': 0.15.14([email protected])'@css-render/vue3-ssr': 0.15.14([email protected]([email protected]))@@ -6781,8 +6796,8 @@ snapshots:async-validator: 4.2.5css-render: 0.15.14csstype: 3.1.3- date-fns: 2.30.0- date-fns-tz: 2.0.1([email protected])+ date-fns: 3.6.0+ date-fns-tz: 3.1.3([email protected])evtd: 0.2.4highlight.js: 11.10.0lodash: 4.17.21@@ -6792,7 +6807,7 @@ snapshots:vdirs: 0.1.8([email protected]([email protected]))vooks: 0.2.12([email protected]([email protected]))vue: 3.4.31([email protected])- vueuc: 0.4.58([email protected]([email protected]))+ vueuc: 0.4.64([email protected]([email protected]))@@ -7408,6 +7423,12 @@ snapshots:emoji-regex: 9.2.2strip-ansi: 7.1.0+ dependencies:+ emoji-regex: 10.4.0+ get-east-asian-width: 1.2.0+ strip-ansi: 7.1.0+@@ -7864,7 +7885,7 @@ snapshots:sortablejs: 1.14.0vue: 3.4.31([email protected])dependencies:'@css-render/vue3-ssr': 0.15.14([email protected]([email protected]))'@juggle/resize-observer': 3.4.0diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTableLite/DataTableLite.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTableLite/DataTableLite.vueindex 78ce50d6b9..d2d056f23e 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTableLite/DataTableLite.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTableLite/DataTableLite.vue@@ -1,32 +1,40 @@<template><div- ref="containerElRef"+ ref="containerRef"class="relative w-full flex-1 overflow-hidden flex flex-col":data-width="containerWidth":data-height="containerHeight"><divtag="div"- class="header-track absolute z-0 left-0 top-0 right-0 h-[34px] border border-block-border bg-gray-50 dark:bg-gray-700"+ class="header-track absolute z-0 left-0 top-0 right-0 h-[34px] border border-block-border rounded-t-sm bg-gray-50 dark:bg-gray-700"/><NDataTableref="dataTableRef":columns="columns"- :data="layoutReady ? rows : []"- :max-height="tableBodyHeight"+ :data="rows":row-props="rowProps":virtual-scroll="true"+ :virtual-scroll-x="true"+ :virtual-scroll-header="true"+ :header-height="HEADER_HEIGHT"+ :max-height="maxTableHeight"+ :min-row-height="ROW_HEIGHT"+ :height-for-row="() => ROW_HEIGHT"+ :scroll-x="tableResize.getTableScrollWidth()"table-layout="fixed"size="small"class="relative z-[1]"style="--n-th-padding: 0;--n-td-padding: 0;- --n-border-radius: 0;+ --n-border-radius: 2px;--n-border-color: rgb(var(--color-block-border));"- v-bind="tableResize.getTableProps()"+ :style="{+ width: `${tableResize.getTableRenderWidth()}px`,+ }"/></div></template>@@ -34,20 +42,22 @@<script lang="ts" setup>import type { Header, Row, Table } from "@tanstack/vue-table";import { useElementSize } from "@vueuse/core";-import { type DataTableColumn, NDataTable } from "naive-ui";-import { computed, h, nextTick, watch } from "vue";+import { type DataTableColumn, type DataTableInst, NDataTable } from "naive-ui";+import { computed, h, nextTick, ref, toRef, watch } from "vue";import { QueryRow, type RowValue } from "@/types/proto/v1/sql_service";-import {- nextAnimationFrame,- useAutoHeightDataTable,- usePreventBackAndForward,-} from "@/utils";+import { nextAnimationFrame, usePreventBackAndForward } from "@/utils";import { useSQLResultViewContext } from "../context";import ColumnHeader from "./ColumnHeader.vue";import TableCell from "./TableCell.vue";import useTableColumnWidthLogic from "./useTableResize";-const DEFAULT_COLUMN_WIDTH = 128; // 8rem+const COLUMN_WIDTH = {+ DEFAULT: 128, // 8rem+ MIN: 64, // 4rem+ MAX: 640, // 40rem+};+const HEADER_HEIGHT = 33;+const ROW_HEIGHT = 28;const props = defineProps<{table: Table<QueryRow>;@@ -65,43 +75,60 @@ const headers = computed(() => {const rows = computed(() => {return props.table.getRowModel().rows;});-const {- dataTableRef,- containerElRef,- tableBodyHeight,- scrollerRef,- layoutReady,-} = useAutoHeightDataTable(rows);+const dataTableRef = ref<DataTableInst>();+const containerRef = ref<HTMLElement>();+const scrollerRef = computed(() => {+ const getter = (dataTableRef.value as any)?.$refs.mainTableInstRef.$refs+ .bodyInstRef.virtualListContainer;+ if (typeof getter === "function") {+ return getter() as HTMLElement | undefined;+ }+ return undefined;+});const { height: containerHeight, width: containerWidth } =- useElementSize(containerElRef);+ useElementSize(containerRef);usePreventBackAndForward(scrollerRef);+const maxTableHeight = computed(() => {+ const GAP_AND_BORDER_HEIGHT = 2;+ return containerHeight.value - HEADER_HEIGHT - GAP_AND_BORDER_HEIGHT;+});+const queryTableHeaderElement = () => {- return containerElRef.value?.querySelector(+ return containerRef.value?.querySelector(".n-data-table-base-table-header table.n-data-table-table") as HTMLElement | undefined;};const queryTableBodyElement = () => {- return containerElRef.value?.querySelector(+ return containerRef.value?.querySelector(".n-data-table-base-table-body table.n-data-table-table") as HTMLElement | undefined;};const tableResize = useTableColumnWidthLogic({+ table: toRef(props, "table"),+ containerWidth,scrollerRef,queryTableHeaderElement,queryTableBodyElement,columnCount: computed(() => headers.value.length),- defaultWidth: DEFAULT_COLUMN_WIDTH,- minWidth: 64, // 4rem- maxWidth: 640, // 40rem+ defaultWidth: COLUMN_WIDTH.DEFAULT,+ minWidth: COLUMN_WIDTH.MIN,+ maxWidth: COLUMN_WIDTH.MAX,});const columns = computed(() => {return headers.value.map<DataTableColumn<Row<QueryRow>>>((header, colIndex) => {return {- key: header.id,+ key: colIndex,+ cellProps: (row) => {+ return {+ class: "truncate",+ "data-row-index": row.index,+ "data-col-index": colIndex,+ };+ },title: () => {return h(ColumnHeader, {header,@@ -115,25 +142,23 @@ const columns = computed(() => {},});},- render: (row, rowIndex) => {+ render: (row) => {const cell = row.getVisibleCells()[colIndex];const value = cell.getValue() as RowValue;return h(TableCell, {table: props.table,value,- width:- tableResize.state.columns[colIndex]?.width ??- DEFAULT_COLUMN_WIDTH,+ width: tableResize.getColumnWidth(colIndex),keyword: keyword.value,setIndex: props.setIndex,- rowIndex: props.offset + rowIndex,+ rowIndex: props.offset + row.index,colIndex,+ class: row.index % 2 === 0 && "bg-gray-100/50 dark:bg-gray-700/50",});},width: tableResize.state.autoAdjusting.has(colIndex)- ? undefined- : (tableResize.state.columns[colIndex]?.width ??- DEFAULT_COLUMN_WIDTH),+ ? COLUMN_WIDTH.DEFAULT+ : tableResize.getColumnWidth(colIndex),};});@@ -181,4 +206,10 @@ watch(:deep(.n-data-table-th .n-data-table-resize-button::after) {@apply bg-control-bg h-2/3;}+:deep(.n-data-table-th:not(.n-data-table-th--last)) {+ border-right: 1px solid var(--n-merged-border-color);+}+:deep(.n-data-table-td:not(.n-data-table-td--last-col)) {+ border-right: 1px solid var(--n-merged-border-color);+}</style>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTableLite/TableCell.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTableLite/TableCell.vueindex 300b95e730..145d72e9a8 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTableLite/TableCell.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTableLite/TableCell.vue@@ -1,7 +1,7 @@<!-- eslint-disable vue/no-v-html --><template><div- class="relative px-2 py-1 text-sm dark:text-gray-100 leading-5 whitespace-nowrap break-all group-even:bg-gray-50/50 dark:group-even:bg-gray-700/50"+ class="relative px-2 py-1 text-sm dark:text-gray-100 leading-5 whitespace-nowrap break-all":class="classes"@click="handleClick">@@ -29,6 +29,7 @@import { type Table } from "@tanstack/vue-table";import { escape } from "lodash-es";import { NButton } from "naive-ui";+import stringWidth from "string-width";import { computed, ref } from "vue";import { useConnectionOfCurrentSQLEditorTab } from "@/store";import { Engine } from "@/types/proto/v1/common";@@ -53,9 +54,12 @@ const plainValue = computed(() => {});const truncated = computed(() => {// not that accurate- const xPadding = 8;- const availChars = (props.width - xPadding * 2) / 8;- return String(plainValue.value).length >= availChars;+ const content = String(plainValue.value);+ const em = 8;+ const padding = 8;+ const guessedContentWidth = stringWidth(content) * em + padding * 2;++ return guessedContentWidth > props.width;});const { database } = useConnectionOfCurrentSQLEditorTab();diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTableLite/useTableResize.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTableLite/useTableResize.tsindex 2177cc2c9c..9c3349f901 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTableLite/useTableResize.ts+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTableLite/useTableResize.ts@@ -1,13 +1,18 @@+import type { Header, Table } from "@tanstack/vue-table";import { useEventListener, usePointer } from "@vueuse/core";-import { reject, sumBy } from "lodash-es";-import type { Ref } from "vue";+import { reject } from "lodash-es";+import stringWidth from "string-width";+import type { MaybeRef, Ref } from "vue";import { computed, onBeforeUnmount, reactive, unref, watch } from "vue";-import { minmax } from "@/utils";+import type { QueryRow, RowValue } from "@/types/proto/v1/sql_service";+import { extractSQLRowValue, minmax, wrapRefAsPromise } from "@/utils";-const MAX_AUTO_ADJUST_SCAN_ROWS = 20;-const MAX_AUTO_ADJUST_COLUMNS = 20;+const MAX_AUTO_ADJUST_ROW_COUNT = 20;+const MAX_AUTO_ADJUST_COL_COUNT = 50;export type TableResizeOptions = {+ table: MaybeRef<Table<QueryRow>>;+ containerWidth: Ref<number>;scrollerRef: Ref<HTMLElement | undefined>;queryTableHeaderElement: () => HTMLElement | undefined;queryTableBodyElement: () => HTMLElement | undefined;@@ -41,90 +46,156 @@ const useTableResize = (options: TableResizeOptions) => {});const pointer = usePointer();const scroller = options.scrollerRef;-- const containerWidth = computed(() => {- return scroller.value?.scrollWidth || 0;- });+ const layoutReady = wrapRefAsPromise(+ computed(() => options.containerWidth.value > 0),+ true+ );const normalizeWidth = (width: number) => {if (state.columns.length === 1) {// When there is only one column, display it with full width.// minus 1px to avoid unexpected horizontal scrollbar.- return containerWidth.value - 1;+ return options.containerWidth.value - 1;}return minmax(width, options.minWidth, options.maxWidth);};- const reset = () => {- state.drag = undefined;-- state.autoAdjusting.clear();-- const columnCount = unref(options.columnCount);- state.columns = new Array(columnCount);+ const maxAutoAdjustColCount = computed(() => {+ return Math.min(+ options.columnCount.value,+ Math.ceil(options.containerWidth.value / options.minWidth),+ MAX_AUTO_ADJUST_COL_COUNT+ );+ });+ const maxAutoAdjustRowCount = computed(() => {+ return Math.min(+ unref(options.table).getRowCount(),+ MAX_AUTO_ADJUST_ROW_COUNT+ );+ });- const indexList: number[] = [];- for (let i = 0; i < columnCount; i++) {- indexList.push(i);- state.columns[i] = {- width: i < MAX_AUTO_ADJUST_COLUMNS ? 0 : options.defaultWidth, // For auto adjust below- };- }+ const reset = () => {+ layoutReady.then(() => {+ // reset state+ state.drag = undefined;+ state.autoAdjusting.clear();+ state.columns = new Array(options.columnCount.value);++ // set initial column widths+ const indexList: number[] = [];+ for (let index = 0; index < options.columnCount.value; index++) {+ if (index < maxAutoAdjustColCount.value) {+ // for columns that will be rendered in the first screen+ // set their widths to minWidth for further render-based auto-width+ state.columns[index] = {+ width: options.minWidth,+ };+ indexList.push(index);+ } else {+ // for columns that won't be rendered in the first screen+ // guess their widths by characters+ state.columns[index] = {+ width: guessColumnWidth(index),+ };+ }+ }- // Calculate a friendly width for every column when the first render happened.- const scanner = async (n = 0) => {- // Wait for several frames for the initial render of the table- requestAnimationFrame(() => {- const headerTable = options.queryTableHeaderElement();- const bodyTable = options.queryTableBodyElement();- if (headerTable && bodyTable) {- autoAdjustColumnWidth(- indexList.slice(0, MAX_AUTO_ADJUST_COLUMNS)- ).catch(() => {- for (let i = 0; i < state.columns.length; i++) {- state.columns[i].width = options.defaultWidth;+ // Calculate a friendly width for every column when the first render happened.+ const scanner = async (n = 0) => {+ // Wait for several frames for the initial render of the table+ requestAnimationFrame(() => {+ const headerTable = options.queryTableHeaderElement();+ const bodyTable = options.queryTableBodyElement();+ const trList = [+ ...Array.from(headerTable?.querySelectorAll("tr") || []),+ ...Array.from(+ bodyTable?.querySelectorAll("tr.n-data-table-tr") || []+ ),+ ] as HTMLElement[];+ if (!headerTable || !bodyTable || trList.length === 0) {+ return scanner(n + 1);+ }+ autoAdjustColumnWidth(indexList).catch(() => {+ // auto adjust failed, fallback to guessing column width.+ for (let index = 0; index < state.columns.length; index++) {+ state.columns[index].width = guessColumnWidth(index);}});- return;- }- scanner(n + 1);- });- };- scanner();+ });+ };+ scanner();+ });};// 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[]> => {+ const autoAdjustColumnWidth = (+ indexList: number[]+ ): Promise<Map<number, number>> => {return new Promise((resolve) => {+ if (indexList.length === 0) {+ return resolve(new Map());+ }+const headerTable = options.queryTableHeaderElement();const bodyTable = options.queryTableBodyElement();const trList = [...Array.from(headerTable?.querySelectorAll("tr") || []),- ...Array.from(bodyTable?.querySelectorAll("tr") || []),+ ...Array.from(+ bodyTable?.querySelectorAll("tr.n-data-table-tr") || []+ ).slice(0, maxAutoAdjustRowCount.value), // Do not adjust too many rows] as HTMLElement[];+ console.debug(+ "[autoAdjustColumnWidth]",+ indexList.join("|"),+ `(${trList.length} rows)`+ );if (!headerTable || !bodyTable || trList.length === 0) {return reject(undefined);}- const numScanRows = Math.min(trList.length, MAX_AUTO_ADJUST_SCAN_ROWS);- const cellsMapByColumn = new Map<number, HTMLElement[]>();+ const cellsMapByColumn = new Map<number, Array<HTMLElement>>();indexList.forEach((index) => {- const cells: HTMLElement[] = [];- for (let row = 0; row < numScanRows; row++) {+ const cells: Array<HTMLElement> = [];+ for (let row = 0; row < trList.length; row++) {const tr = trList[row];- const cell = tr.children[index] as HTMLElement;- if (cell && ["th", "td"].includes(cell.tagName.toLowerCase())) {+ const children = Array.from(tr.children).filter((child) => {+ return isNDataTableCell(child);+ });+ if (children.length === 0) {+ return;+ }+ // When the table is scrolled horizontally, some left columns will not+ // be actually rendered.+ // So we need to find out the col index of the first rendered column+ // to get the column with offset.+ const first = children[0];+ const offset = parseInt(+ first.getAttribute("data-col-key") || "0",+ 10+ );+ const cell = children[index - offset];+ if (cell) {cells.push(cell);}}- cellsMapByColumn.set(index, cells);- return cells;+ if (cells.length > 0) {+ cellsMapByColumn.set(index, cells);+ }});+ console.debug(+ "[autoAdjustColumnWidth] found cells",+ Array.from(cellsMapByColumn.entries())+ .map(([index, cells]) => `${index}(${cells.length})`)+ .join("|")+ );// Update the cells' and table's style to estimate the width.- indexList.forEach((colIndex) => state.autoAdjusting.add(colIndex));+ for (const index of cellsMapByColumn.keys()) {+ state.autoAdjusting.add(index);+ }+for (const [_index, cells] of cellsMapByColumn.entries()) {cells.forEach((cell) => {cell.style.whiteSpace = "nowrap";@@ -139,42 +210,57 @@ const useTableResize = (options: TableResizeOptions) => {headerTable.style.width = "auto";bodyTable.style.width = "auto";- // Wait for the next render frame.- requestAnimationFrame(() => {- // Read the rendered widths.- const widthList = indexList.map((index) => {- const cells = cellsMapByColumn.get(index) ?? [];- const stretchedWidths = cells.map((cell) => getElementWidth(cell));- const finalWidth = normalizeWidth(Math.max(...stretchedWidths));-- const column = state.columns[index];- if (column) {- // Sometimes the `columns` is out-of-sync with the `indexList`- // so we need to detect and suppress errors here.- // Only occurs in dev hot reload mode.- column.width = finalWidth;- }+ // Read the rendered widths.+ const widthMapByColumn = new Map<number, number>();+ indexList.forEach((index) => {+ const cells = cellsMapByColumn.get(index);+ if (!cells) {+ return;+ }- return finalWidth;- });+ const stretchedWidths = cells.map((cell) => getElementWidth(cell));+ const finalWidth = normalizeWidth(Math.max(...stretchedWidths));+ console.debug(`col#${index}`, stretchedWidths.join("|"), finalWidth);- // Reset the cells' and table's style.- for (const [_index, cells] of cellsMapByColumn.entries()) {- cells.forEach((cell) => {- cell.style.whiteSpace = "";- cell.style.overflow = "";- cell.style.width = "";- cell.style.maxWidth = "";- cell.style.minWidth = "";- });- }- headerTable.style.width = headerTableWidthBackup;- bodyTable.style.width = bodyTableWidthBackup;- state.autoAdjusting.clear();+ widthMapByColumn.set(index, finalWidth);+ });- resolve(widthList);- // Style bindings will be automatically updated next frame.+ console.debug(+ Array.from(widthMapByColumn.entries())+ .map(([index, width]) => `${index}:${width}`)+ .join("|")+ );++ indexList.forEach((index) => {+ const width = widthMapByColumn.get(index) ?? guessColumnWidth(index);++ const column = state.columns[index];+ if (!column) {+ // Sometimes the `columns` is out-of-sync with the `indexList`+ // so we need to detect and suppress errors here.+ // Only occurs in dev hot reload mode.+ return;+ }+ column.width = width;});++ // Reset the cells' and table's style.+ for (const [_index, cells] of cellsMapByColumn.entries()) {+ cells.forEach((cell) => {+ if (!cell) return;+ cell.style.whiteSpace = "";+ cell.style.overflow = "";+ cell.style.width = "";+ cell.style.maxWidth = "";+ cell.style.minWidth = "";+ });+ }+ headerTable.style.width = headerTableWidthBackup;+ bodyTable.style.width = bodyTableWidthBackup;+ state.autoAdjusting.clear();++ resolve(widthMapByColumn);+ // Style bindings will be automatically updated next frame.});};@@ -212,28 +298,66 @@ const useTableResize = (options: TableResizeOptions) => {}});- const getCellProps = (index: number) => {- const column = state.columns[index];- if (!column) return {};- return {- style: {- width: `${column.width}px`,- },- class: "truncate",- "data-index": index,- };+ const getColumnWidth = (index: number) => {+ return state.columns[index]?.width ?? options.defaultWidth;};- const getTableProps = () => {- const width =- state.autoAdjusting.size > 0- ? "auto"- : `calc(min(100%, ${sumBy(state.columns, (col) => col.width) + 2}px))`;- return {- style: {- width,- },+ const totalWidth = computed(() => {+ let totalWidth = 0;+ for (let index = 0; index < options.columnCount.value; index++) {+ const columnWidth = state.autoAdjusting.has(index)+ ? options.maxWidth+ : getColumnWidth(index);+ totalWidth += columnWidth;+ }+ return totalWidth;+ });++ const getTableRenderWidth = () => {+ return Math.min(options.containerWidth.value, totalWidth.value + 2);+ };++ const getTableScrollWidth = () => {+ return totalWidth.value;+ };++ const guessColumnWidth = (+ index: number,+ opts = {+ em: 8,+ padding: 8,+ }+ ) => {+ const table = unref(options.table);+ const maxAutoAdjustRowCount = Math.min(+ table.getRowCount(),+ MAX_AUTO_ADJUST_ROW_COUNT+ );++ const charsWidth = (content: string) => {+ return stringWidth(content) * opts.em + opts.padding * 2;};++ const widths: number[] = [];++ const header = table.getFlatHeaders()[index] as Header<QueryRow, RowValue>;+ if (header) {+ const content = String(header.column.columnDef.header);+ const width = charsWidth(content) + 4 + 16; // plus sort icon and gap+ widths.push(width);+ }++ for (let r = 0; r < maxAutoAdjustRowCount; r++) {+ const row = table.getRowModel().rows[r];+ const cell = row?.getVisibleCells()[index];+ if (!cell) continue;+ const value = cell.getValue() as RowValue;+ const content = String(extractSQLRowValue(value).plain);+ widths.push(charsWidth(content));+ }++ const guessed = Math.max(...widths);+ return normalizeWidth(guessed);};onBeforeUnmount(() => {@@ -241,10 +365,12 @@ const useTableResize = (options: TableResizeOptions) => {});return {- reset,state,- getCellProps,- getTableProps,+ layoutReady,+ reset,+ getColumnWidth,+ getTableRenderWidth,+ getTableScrollWidth,startResizing,autoAdjustColumnWidth,};@@ -258,7 +384,7 @@ const scrollMaxX = (elem: HTMLElement | undefined) => {elem.scrollTo(max, elem.scrollTop);};-const getElementWidth = (elem: HTMLElement) => {+const getElementWidth = (elem: HTMLElement | undefined) => {if (!elem) return 0;const rect = elem.getBoundingClientRect();return rect.width;@@ -270,13 +396,20 @@ const toggleDragStyle = () => {if (on) {// Prevent text selection while dragging.- element.value?.classList.add("select-none");+ document.body.classList.add("select-none");// Set the cursor style.document.body.classList.add("cursor-col-resize");} else {requestAnimationFrame(() => {- element.value?.classList.remove("select-none");+ document.body.classList.remove("select-none");document.body.classList.remove("cursor-col-resize");});}};++const isNDataTableCell = (elem: Element): elem is HTMLElement => {+ return (+ elem.classList.contains("n-data-table-th") ||+ elem.classList.contains("n-data-table-td")+ );+};