The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Fix table column widths resetting on column reorder (#84673)
Denis Berezin505200053482
diff --git a/e2e/test/scenarios/visualizations/tabular/table.cy.spec.js b/e2e/test/scenarios/visualizations/tabular/table.cy.spec.jsindex 1aa7d328609..e3ab33b6205 100644--- a/e2e/test/scenarios/visualizations/tabular/table.cy.spec.js+++ b/e2e/test/scenarios/visualizations/tabular/table.cy.spec.js@@ -203,6 +203,63 @@ describe("scenarios > visualizations > table", () => {headerCells().contains("QUANTITY").should("not.exist");});+ it("should preserve set widths after reordering", () => {+ cy.intercept(+ "GET",+ "/api/search?models=dataset&models=table&table_db_id=*",+ ).as("getSearchResults");+ cy.intercept("POST", "/api/dataset").as("getDataset");+ H.startNewNativeQuestion({+ query: 'select 1 "first_column", 2 "second_column"',+ display: "table",+ });++ cy.findByTestId("native-query-editor-container").icon("play").click();+ cy.wait(["@getSearchResults", "@getDataset"]);++ // Resizing a single column stores a widths array shorter than the column count+ H.resizeTableColumn("first_column", 100);++ H.getColumnWidth("first_column")+ .should("be.gt", 150)+ .as("firstWidth", { type: "static" });+ H.getColumnWidth("second_column").as("secondWidth", { type: "static" });++ H.tableHeaderColumn("first_column").as("dragElement");+ // The drop target is found by pointer position, so the pointer has to end inside the second column+ cy.get("@dragElement").then(($dragElement) => {+ headerCells()+ .filter(":contains(second_column)")+ .then(($target) => {+ const targetRect = $target[0].getBoundingClientRect();+ const dragRect = $dragElement[0].getBoundingClientRect();+ H.moveDnDKitElementByAlias("@dragElement", {+ horizontal: targetRect.left + targetRect.width / 2 - dragRect.left,+ });+ });+ });+ headerCells().eq(0).should("contain.text", "second_column");++ const assertUnchangedWidths = () => {+ cy.get("@firstWidth").then((firstWidth) => {+ H.getColumnWidth("first_column").should("eq", firstWidth);+ });++ cy.get("@secondWidth").then((secondWidth) => {+ H.getColumnWidth("second_column").should("eq", secondWidth);+ });+ };++ assertUnchangedWidths();+ cy.reload();++ cy.findByTestId("native-query-editor-container").icon("play").click();+ // Wait for column widths to be set+ cy.wait(["@getSearchResults", "@getDataset"]);+ H.tableHeaderColumn("first_column").should("be.visible");+ assertUnchangedWidths();+ });+it("should close the column popover on subsequent click and display any column as link with extrapolated url and text (metabase#16789)", () => {H.openPeopleTable({ limit: 2 });diff --git a/frontend/src/metabase/data-grid/hooks/use-data-grid-instance.tsx b/frontend/src/metabase/data-grid/hooks/use-data-grid-instance.tsxindex 79fac14857f..e45e093dcea 100644--- a/frontend/src/metabase/data-grid/hooks/use-data-grid-instance.tsx+++ b/frontend/src/metabase/data-grid/hooks/use-data-grid-instance.tsx@@ -563,11 +563,26 @@ export const useDataGridInstance = <TData, TValue>({]);// Reset column widths if controlled sizing map is removed+ const prevControlledColumnSizingMap = usePrevious(controlledColumnSizingMap);useUpdateEffect(() => {- if (Object.keys(controlledColumnSizingMap ?? {}).length === 0) {+ const controlledSizing = controlledColumnSizingMap ?? {};+ if (Object.keys(controlledSizing).length === 0) {applyMeasuredColumnWidths({}, true);} else {- setColumnSizingMap((prev) => ({ ...prev, ...controlledColumnSizingMap }));+ // A column whose controlled width went away falls back to its measured width instead of keeping the+ // width it had, e.g. after a reorder moved a saved width to another column+ const releasedColumnIds = Object.keys(+ prevControlledColumnSizingMap ?? {},+ ).filter((columnId) => !(columnId in controlledSizing));+ const releasedColumnSizing = getTruncatedColumnSizing(+ _.pick(measuredColumnSizingMap, releasedColumnIds),+ truncateLongCellWidth,+ );+ setColumnSizingMap((prev) => ({+ ..._.omit(prev, releasedColumnIds),+ ...releasedColumnSizing,+ ...controlledSizing,+ }));}}, [controlledColumnSizingMap]);diff --git a/frontend/src/metabase/data-grid/hooks/use-data-grid-instance.unit.spec.tsx b/frontend/src/metabase/data-grid/hooks/use-data-grid-instance.unit.spec.tsxindex a00d2f0d409..1052bf71b86 100644--- a/frontend/src/metabase/data-grid/hooks/use-data-grid-instance.unit.spec.tsx+++ b/frontend/src/metabase/data-grid/hooks/use-data-grid-instance.unit.spec.tsx@@ -3,6 +3,7 @@ import { act, renderHook } from "@testing-library/react";import { useDataGridInstance } from "./use-data-grid-instance";type TestRow = { value: string };+type TwoColumnRow = { a: string; b: string };// Module scope so the hook sees a stable reference across renders, which is// what the fix relies on@@ -15,7 +16,38 @@ const COLUMNS_OPTIONS = [},];+const TWO_COLUMN_DATA: TwoColumnRow[] = [{ a: "1", b: "2" }];+const TWO_COLUMNS_OPTIONS = [+ { id: "a", name: "a", accessorFn: (row: TwoColumnRow) => row.a },+ { id: "b", name: "b", accessorFn: (row: TwoColumnRow) => row.b },+];+describe("useDataGridInstance", () => {+ describe("controlled column widths", () => {+ it("drops the width of a column whose controlled width was removed instead of keeping it", () => {+ const initialProps: { columnSizingMap: Record<string, number> } = {+ columnSizingMap: { a: 300 },+ };+ const { result, rerender } = renderHook(+ ({ columnSizingMap }: typeof initialProps) =>+ useDataGridInstance<TwoColumnRow, string>({+ data: TWO_COLUMN_DATA,+ columnsOptions: TWO_COLUMNS_OPTIONS,+ columnSizingMap,+ }),+ { initialProps },+ );++ expect(result.current.table.getState().columnSizing.a).toBe(300);++ rerender({ columnSizingMap: { b: 300 } });++ const { columnSizing } = result.current.table.getState();+ expect(columnSizing.b).toBe(300);+ expect(columnSizing.a).not.toBe(300);+ });+ });+describe("issue 78557", () => {it("keeps cell and header component identity across a column resize", () => {const { result } = renderHook(() =>diff --git a/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsx b/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsxindex fc21c788d73..586ca36ae96 100644--- a/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsx+++ b/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsx@@ -86,7 +86,7 @@ import {type HeaderCellWithColumnInfoProps,} from "./cells/HeaderCellWithColumnInfo";import { MiniBarCell } from "./cells/MiniBarCell";-import { useResetWidthsOnColumnsChange } from "./hooks/use-reset-widths-on-columns-change";+import { useSyncColumnWidths } from "./hooks/use-sync-column-widths";import { getInfoPopoversDisabled } from "./utils/get-info-popovers-disabled";import { tableThemeToDataGridTheme } from "./utils/table-theme-to-data-grid-theme";@@ -455,22 +455,9 @@ export const TableInteractiveInner = forwardRef(function TableInteractiveInner(}});- const newEnabledColumns = newColumns.filter((col) => col.enabled);- const savedWidths = settings["table.column_widths"];- const newWidths =- Array.isArray(savedWidths) &&- savedWidths.length === newEnabledColumns.length- ? newEnabledColumns.map((c) => columnSizingMap[c.name])- : undefined;-- const settingsUpdate = {- "table.columns": newColumns,- "table.column_widths": newWidths,- };-- onUpdateVisualizationSettings(settingsUpdate);+ onUpdateVisualizationSettings({ "table.columns": newColumns });},- [onUpdateVisualizationSettings, settings, columnSizingMap],+ [onUpdateVisualizationSettings, settings],);const handleAddColumnButtonClick = useMemo(() => {@@ -828,9 +815,7 @@ export const TableInteractiveInner = forwardRef(function TableInteractiveInner([infoPopoversDisabled],);- // If the data changes we reset saved column widths as it is no longer relevant- // except for the case where question is converted from a model to a question and back.- useResetWidthsOnColumnsChange(onUpdateVisualizationSettings, data, question);+ useSyncColumnWidths(onUpdateVisualizationSettings, data, columnWidths);const scrolledColumnRef = useRef<number | null>(null);useEffect(() => {diff --git a/frontend/src/metabase/visualizations/components/TableInteractive/hooks/use-reset-widths-on-columns-change.ts b/frontend/src/metabase/visualizations/components/TableInteractive/hooks/use-reset-widths-on-columns-change.tsdeleted file mode 100644index 78feab7c0d1..00000000000--- a/frontend/src/metabase/visualizations/components/TableInteractive/hooks/use-reset-widths-on-columns-change.ts+++ /dev/null@@ -1,91 +0,0 @@-import { useEffect, useRef } from "react";-import _ from "underscore";--import type Question from "metabase-lib/v1/Question";-import { isAdHocModelOrMetricQuestion } from "metabase-lib/v1/metadata/utils/models";-import type {- DatasetColumn,- DatasetData,- VisualizationSettings,-} from "metabase-types/api";--// Only select fields that define column data identity, excluding technical fields like `ident` or `model/inner_ident`-// that could be added in the future and break column comparison. For example, duplicating a model would produce-// different model/inner_ident values-const DATA_COLUMN_KEYS: (keyof DatasetColumn)[] = [- "active",- "base_type",- "coercion_strategy",- "database_type",- "description",- "binning_info",- "display_name",- "effective_type",- "aggregation_type",- "entity_id",- "field_ref",- "fk_field_id",- "fk_target_field_id",- "id",- "name",- "nfc_path",- "parent_id",- "position",- "semantic_type",- "settings",- "source",- "table_id",- "visibility_type",-];--const getColumnDataFields = (datasetColumn: DatasetColumn) => {- return _.pick(datasetColumn, DATA_COLUMN_KEYS);-};--/**- * Reset table column widths when the dataset columns change- * unless it is due to the question <-> model conversion- */-export function useResetWidthsOnColumnsChange(- onUpdateVisualizationSettings: (- settingsUpdate: Partial<VisualizationSettings>,- ) => void,- data?: DatasetData,- question?: Question,-) {- const prevData = useRef<DatasetData>(undefined);- const prevDataQuestion = useRef<Question>(undefined);-- useEffect(() => {- const isDataChange =- prevData.current &&- data &&- !_.isEqual(- prevData.current.cols.map(getColumnDataFields),- data.cols.map(getColumnDataFields),- );-- if (isDataChange) {- // Check whether question <-> model conversion happened. If so dataset columns change should be ignored- const isDatasetStatusChange =- prevDataQuestion.current &&- (isAdHocModelOrMetricQuestion(question, prevDataQuestion.current) ||- isAdHocModelOrMetricQuestion(prevDataQuestion.current, question));-- if (!isDatasetStatusChange) {- onUpdateVisualizationSettings({ "table.column_widths": undefined });- }-- // Save the current dataset and question for the next comparison.- // We update these only on a dataset change which happens after question update.- // Between question update and dataset update there could be rerenders so- // a simple usePrevious hook would pair the wrong question with the data.- prevDataQuestion.current = question;- prevData.current = data;- } else if (prevData.current == null && data) {- // Sets initial prevData and prevDataQuestion- prevDataQuestion.current = question;- prevData.current = data;- }- }, [data, question, onUpdateVisualizationSettings]);-}diff --git a/frontend/src/metabase/visualizations/components/TableInteractive/hooks/use-sync-column-widths.ts b/frontend/src/metabase/visualizations/components/TableInteractive/hooks/use-sync-column-widths.tsnew file mode 100644index 00000000000..5a40a16707e--- /dev/null+++ b/frontend/src/metabase/visualizations/components/TableInteractive/hooks/use-sync-column-widths.ts@@ -0,0 +1,65 @@+import { useEffect, useRef } from "react";+import _ from "underscore";++import type {+ DatasetColumn,+ DatasetData,+ VisualizationSettings,+} from "metabase-types/api";++const getColumnNames = (cols: DatasetColumn[]) => cols.map((col) => col.name);++const remapWidthsByName = (+ prevCols: DatasetColumn[],+ prevWidths: number[],+ cols: DatasetColumn[],+) => {+ const widthByName = new Map(+ prevCols.map((col, index) => [col.name, prevWidths[index]] as const),+ );+ return cols.map((col) => widthByName.get(col.name));+};++/**+ * Keeps `table.column_widths` aligned with the dataset columns when their names change: a reorder (drag and+ * drop, viz settings, or a changed query), added or removed columns, and hidden or shown columns all move each+ * saved width along with its column. Widths that changed together with the columns, as on browser history+ * navigation, are already aligned and are left alone.+ */+export function useSyncColumnWidths(+ onUpdateVisualizationSettings: (+ settingsUpdate: Partial<VisualizationSettings>,+ ) => void,+ data?: DatasetData,+ columnWidths?: number[],+) {+ const prevCols = useRef<DatasetColumn[]>(undefined);+ const prevWidths = useRef<number[]>(undefined);++ useEffect(() => {+ if (!data) {+ return;+ }++ const previousCols = prevCols.current;+ const previousWidths = prevWidths.current;+ prevCols.current = data.cols;+ prevWidths.current = columnWidths;++ const isColumnListChange =+ previousCols != null &&+ !_.isEqual(getColumnNames(previousCols), getColumnNames(data.cols));+ const areWidthsAlignedWithPreviousCols =+ previousWidths != null && _.isEqual(columnWidths, previousWidths);+ if (!isColumnListChange || !areWidthsAlignedWithPreviousCols) {+ return;+ }++ const widths = remapWidthsByName(previousCols, previousWidths, data.cols);+ onUpdateVisualizationSettings({+ "table.column_widths": widths.some((width) => width != null)+ ? widths+ : undefined,+ });+ }, [data, columnWidths, onUpdateVisualizationSettings]);+}diff --git a/frontend/src/metabase/visualizations/components/TableInteractive/hooks/use-sync-column-widths.unit.spec.ts b/frontend/src/metabase/visualizations/components/TableInteractive/hooks/use-sync-column-widths.unit.spec.tsnew file mode 100644index 00000000000..0bab360670a--- /dev/null+++ b/frontend/src/metabase/visualizations/components/TableInteractive/hooks/use-sync-column-widths.unit.spec.ts@@ -0,0 +1,207 @@+import { renderHook } from "@testing-library/react";++import type {+ DatasetColumn,+ DatasetData,+ VisualizationSettings,+} from "metabase-types/api";+import {+ createMockColumn,+ createMockDatasetData,+} from "metabase-types/api/mocks";++import { useSyncColumnWidths } from "./use-sync-column-widths";++const COLUMN_A = createMockColumn({ id: 1, name: "a", display_name: "a" });+const COLUMN_B = createMockColumn({ id: 2, name: "b", display_name: "b" });+const COLUMN_C = createMockColumn({ id: 3, name: "c", display_name: "c" });++type HookProps = {+ data: DatasetData;+ columnWidths?: number[];+};++type SetupOpts = {+ cols: DatasetColumn[];+ columnWidths?: number[];+};++function setup({ cols, columnWidths }: SetupOpts) {+ const onUpdateVisualizationSettings = jest.fn<+ void,+ [Partial<VisualizationSettings>]+ >();++ const { rerender } = renderHook(+ ({ data, columnWidths }: HookProps) =>+ useSyncColumnWidths(onUpdateVisualizationSettings, data, columnWidths),+ {+ initialProps: { data: createMockDatasetData({ cols }), columnWidths },+ },+ );++ const rerenderWith = (nextCols: DatasetColumn[], nextWidths?: number[]) =>+ rerender({+ data: createMockDatasetData({ cols: nextCols }),+ columnWidths: nextWidths,+ });++ return { onUpdateVisualizationSettings, rerenderWith };+}++describe("useSyncColumnWidths", () => {+ it("does nothing on the initial data", () => {+ const { onUpdateVisualizationSettings } = setup({+ cols: [COLUMN_A, COLUMN_B],+ columnWidths: [100, 200],+ });++ expect(onUpdateVisualizationSettings).not.toHaveBeenCalled();+ });++ it("does nothing when the same columns arrive in the same order", () => {+ const { onUpdateVisualizationSettings, rerenderWith } = setup({+ cols: [COLUMN_A, COLUMN_B],+ columnWidths: [100, 200],+ });++ rerenderWith([COLUMN_A, COLUMN_B], [100, 200]);++ expect(onUpdateVisualizationSettings).not.toHaveBeenCalled();+ });++ it("does nothing when only the widths change, as on a resize", () => {+ const { onUpdateVisualizationSettings, rerenderWith } = setup({+ cols: [COLUMN_A, COLUMN_B],+ columnWidths: [100, 200],+ });++ rerenderWith([COLUMN_A, COLUMN_B], [150, 200]);++ expect(onUpdateVisualizationSettings).not.toHaveBeenCalled();+ });++ it("moves saved widths with their columns when the columns are reordered", () => {+ const { onUpdateVisualizationSettings, rerenderWith } = setup({+ cols: [COLUMN_A, COLUMN_B],+ columnWidths: [100, 200],+ });++ rerenderWith([COLUMN_B, COLUMN_A], [100, 200]);++ expect(onUpdateVisualizationSettings).toHaveBeenCalledTimes(1);+ expect(onUpdateVisualizationSettings).toHaveBeenCalledWith({+ "table.column_widths": [200, 100],+ });+ });++ it("keeps unsized columns auto-sized when only one column has a saved width", () => {+ const { onUpdateVisualizationSettings, rerenderWith } = setup({+ cols: [COLUMN_A, COLUMN_B],+ columnWidths: [212],+ });++ rerenderWith([COLUMN_B, COLUMN_A], [212]);++ expect(onUpdateVisualizationSettings).toHaveBeenCalledTimes(1);+ expect(onUpdateVisualizationSettings).toHaveBeenCalledWith({+ "table.column_widths": [undefined, 212],+ });+ });++ it("does not touch settings on a reorder without saved widths", () => {+ const { onUpdateVisualizationSettings, rerenderWith } = setup({+ cols: [COLUMN_A, COLUMN_B],+ });++ rerenderWith([COLUMN_B, COLUMN_A]);++ expect(onUpdateVisualizationSettings).not.toHaveBeenCalled();+ });++ it("remaps against the latest order on consecutive reorders", () => {+ const { onUpdateVisualizationSettings, rerenderWith } = setup({+ cols: [COLUMN_A, COLUMN_B, COLUMN_C],+ columnWidths: [100, 200, 300],+ });++ rerenderWith([COLUMN_B, COLUMN_A, COLUMN_C], [100, 200, 300]);+ // The settings update from the first reorder renders before the next reorder+ rerenderWith([COLUMN_B, COLUMN_A, COLUMN_C], [200, 100, 300]);+ rerenderWith([COLUMN_C, COLUMN_B, COLUMN_A], [200, 100, 300]);++ expect(onUpdateVisualizationSettings).toHaveBeenNthCalledWith(1, {+ "table.column_widths": [200, 100, 300],+ });+ expect(onUpdateVisualizationSettings).toHaveBeenNthCalledWith(2, {+ "table.column_widths": [300, 200, 100],+ });+ });++ it("leaves widths alone when they changed together with the columns, as on history navigation", () => {+ const { onUpdateVisualizationSettings, rerenderWith } = setup({+ cols: [COLUMN_A, COLUMN_B],+ columnWidths: [100, 200],+ });++ rerenderWith([COLUMN_B, COLUMN_A], [200, 100]);++ expect(onUpdateVisualizationSettings).not.toHaveBeenCalled();+ });++ it("keeps the widths of existing columns when a column is added", () => {+ const { onUpdateVisualizationSettings, rerenderWith } = setup({+ cols: [COLUMN_A, COLUMN_B],+ columnWidths: [100, 200],+ });++ rerenderWith([COLUMN_A, COLUMN_C, COLUMN_B], [100, 200]);++ expect(onUpdateVisualizationSettings).toHaveBeenCalledTimes(1);+ expect(onUpdateVisualizationSettings).toHaveBeenCalledWith({+ "table.column_widths": [100, undefined, 200],+ });+ });++ it("drops the width of a removed column and keeps the others", () => {+ const { onUpdateVisualizationSettings, rerenderWith } = setup({+ cols: [COLUMN_A, COLUMN_B, COLUMN_C],+ columnWidths: [100, 200, 300],+ });++ rerenderWith([COLUMN_A, COLUMN_C], [100, 200, 300]);++ expect(onUpdateVisualizationSettings).toHaveBeenCalledTimes(1);+ expect(onUpdateVisualizationSettings).toHaveBeenCalledWith({+ "table.column_widths": [100, 300],+ });+ });++ it("resets the setting when no remaining column has a saved width", () => {+ const { onUpdateVisualizationSettings, rerenderWith } = setup({+ cols: [COLUMN_A, COLUMN_B],+ columnWidths: [212],+ });++ rerenderWith([COLUMN_B], [212]);++ expect(onUpdateVisualizationSettings).toHaveBeenCalledTimes(1);+ expect(onUpdateVisualizationSettings).toHaveBeenCalledWith({+ "table.column_widths": undefined,+ });+ });++ it("keeps a column's width when its metadata changes but its name does not", () => {+ const { onUpdateVisualizationSettings, rerenderWith } = setup({+ cols: [COLUMN_A, COLUMN_B],+ columnWidths: [100, 200],+ });++ rerenderWith(+ [{ ...COLUMN_A, display_name: "renamed" }, COLUMN_B],+ [100, 200],+ );++ expect(onUpdateVisualizationSettings).not.toHaveBeenCalled();+ });+});