A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat(table): add column_widths to mo.ui.table (#9982)
Kiran Gadhave8cafa49e1f3b
diff --git a/frontend/src/components/data-table/__tests__/columns.test.tsx b/frontend/src/components/data-table/__tests__/columns.test.tsxindex 7cf503a4b1..2a4e4f75a8 100644--- a/frontend/src/components/data-table/__tests__/columns.test.tsx+++ b/frontend/src/components/data-table/__tests__/columns.test.tsx@@ -1082,3 +1082,23 @@ describe("renderCellValue with datetime values", () => {});});});++test("column_widths sets fixed size and meta.width", () => {+ const cols = generateColumns({+ rowHeaders: [],+ selection: null,+ fieldTypes: [+ ["a", ["number", "int64"]],+ ["b", ["string", "str"]],+ ],+ columnWidths: { a: 120 },+ });+ const a = cols.find((c) => c.id === "a");+ const b = cols.find((c) => c.id === "b");+ expect(a?.size).toBe(120);+ expect(a?.minSize).toBe(120);+ expect(a?.maxSize).toBe(120);+ expect(a?.meta?.width).toBe(120);+ expect(b?.size).toBeUndefined();+ expect(b?.meta?.width).toBeUndefined();+});diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsxindex eb6e6962ae..5fae2734be 100644--- a/frontend/src/components/data-table/columns.tsx+++ b/frontend/src/components/data-table/columns.tsx@@ -118,6 +118,7 @@ export function generateColumns<T>({showDataTypes,calculateTopKRows,fractionDigitsByColumn,+ columnWidths,}: {rowHeaders: FieldTypesWithExternalType;selection: DataTableSelection;@@ -129,6 +130,7 @@ export function generateColumns<T>({showDataTypes?: boolean;calculateTopKRows?: CalculateTopKRows;fractionDigitsByColumn?: Record<string, number>;+ columnWidths?: Record<string, number>;}): ColumnDef<T>[] {// Row-headers are typically index columnsconst rowHeadersSet = new Set(rowHeaders.map(([columnName]) => columnName));@@ -311,7 +313,20 @@ export function generateColumns<T>({// Can only sort if key is defined// For example, unnamed index columns, won't be sortableenableSorting: !!key,- meta: getMeta(key),+ meta: {+ ...getMeta(key),+ width: columnWidths?.[key],+ },+ // size seeds the width before measurement; minSize/maxSize pin+ // getSize() to the fixed width so the per-paint measurement writeback+ // cannot drift the header width or sticky-pin offsets.+ ...(columnWidths?.[key] !== undefined+ ? {+ size: columnWidths[key],+ minSize: columnWidths[key],+ maxSize: columnWidths[key],+ }+ : {}),}),);diff --git a/frontend/src/components/data-table/filters/types.ts b/frontend/src/components/data-table/filters/types.tsindex c6b25fc08f..b8c958c8f6 100644--- a/frontend/src/components/data-table/filters/types.ts+++ b/frontend/src/components/data-table/filters/types.ts@@ -11,6 +11,7 @@ declare module "@tanstack/react-table" {dataType?: DataType;filterType?: FilterType;minFractionDigits?: number;+ width?: number;}}diff --git a/frontend/src/components/data-table/renderers.tsx b/frontend/src/components/data-table/renderers.tsxindex 7f3f7f475e..247b311d1f 100644--- a/frontend/src/components/data-table/renderers.tsx+++ b/frontend/src/components/data-table/renderers.tsx@@ -141,6 +141,7 @@ export const DataTableBody = <TData,>({const renderCells = (cells: Cell<TData, unknown>[]) => {return cells.map((cell) => {const { className, style: pinningstyle } = getPinningStyles(cell.column);+ const fixedWidth = cell.column.columnDef.meta?.width;const style = Object.assign({},cell.getUserStyling?.() || {},@@ -153,7 +154,8 @@ export const DataTableBody = <TData,>({{...getCellDomProps(cell.id)}key={cell.id}className={cn(- "whitespace-pre truncate max-w-[300px] outline-hidden border-r border-r-border/75",+ "whitespace-pre truncate outline-hidden border-r border-r-border/75",+ !fixedWidth && "max-w-[300px]",cell.column.getColumnWrapping &&cell.column.getColumnWrapping?.() === "wrap" &&COLUMN_WRAPPING_STYLES,@@ -297,6 +299,7 @@ function getPinningStyles<TData>(isPinned === "left" && column.getIsLastColumn("left");const isFirstRightPinnedColumn =isPinned === "right" && column.getIsFirstColumn("right");+ const fixedWidth = column.columnDef.meta?.width;return {className: cn(isPinned && "bg-inherit", "shadow-r z-10"),@@ -313,6 +316,7 @@ function getPinningStyles<TData>(position: isPinned ? "sticky" : "relative",zIndex: isPinned ? 1 : 0,width: column.getSize(),+ ...(fixedWidth ? { minWidth: fixedWidth, maxWidth: fixedWidth } : {}),},};}diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex a2ace84949..156fe10a00 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -195,6 +195,7 @@ interface Data<T> {hiddenColumns?: string[];textJustifyColumns?: Record<string, "left" | "center" | "right">;wrappedColumns?: string[];+ columnWidths?: Record<string, number>;headerTooltip?: Record<string, string>;totalColumns: number;maxColumns: number | "all";@@ -274,6 +275,9 @@ export const DataTablePlugin = createPlugin<S>("marimo-table").record(z.string(), z.enum(["left", "center", "right"])).optional(),wrappedColumns: z.array(z.string()).optional(),+ columnWidths: z+ .record(z.string(), z.number().int().positive())+ .optional(),headerTooltip: z.record(z.string(), z.string()).optional(),fieldTypes: columnToFieldTypesSchema.nullish(),totalColumns: z.number(),@@ -848,6 +852,7 @@ const DataTableComponent = ({hiddenColumns,textJustifyColumns,wrappedColumns,+ columnWidths,headerTooltip,totalColumns,get_row_ids,@@ -935,6 +940,7 @@ const DataTableComponent = ({const memoizedRowHeaders = useDeepCompareMemoize(rowHeaders);const memoizedTextJustifyColumns = useDeepCompareMemoize(textJustifyColumns);const memoizedWrappedColumns = useDeepCompareMemoize(wrappedColumns);+ const memoizedColumnWidths = useDeepCompareMemoize(columnWidths);const memoizedChartSpecModel = useDeepCompareMemoize(chartSpecModel);const fractionDigitsByColumn = useDeepCompareMemoize(computedFractionDigits);const shownColumns = memoizedClampedFieldTypes.length;@@ -953,6 +959,7 @@ const DataTableComponent = ({fieldTypes: memoizedClampedFieldTypes,textJustifyColumns: memoizedTextJustifyColumns,wrappedColumns: memoizedWrappedColumns,+ columnWidths: memoizedColumnWidths,headerTooltip: headerTooltip,// Only show data types if they are explicitly setshowDataTypes: showDataTypes,@@ -967,6 +974,7 @@ const DataTableComponent = ({memoizedClampedFieldTypes,memoizedTextJustifyColumns,memoizedWrappedColumns,+ memoizedColumnWidths,headerTooltip,calculate_top_k_rows,fractionDigitsByColumn,diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.pyindex b23c599672..3e936d5d95 100644--- a/marimo/_plugins/ui/_impl/table.py+++ b/marimo/_plugins/ui/_impl/table.py@@ -463,6 +463,9 @@ class table(text_justify_columns (Dict[str, Literal["left", "center", "right"]], optional):Dictionary of column names to text justification options: left, center, right.wrapped_columns (List[str], optional): List of column names to wrap.+ column_widths (Dict[str, int], optional): Mapping of column name to+ fixed pixel width. Listed columns render at exactly that width;+ unlisted columns size to their content.header_tooltip (Dict[str, str], optional): Mapping from column names to tooltip text on the column header.label (str, optional): Markdown label for the element. Defaults to "".on_change (Callable[[Union[List[JSONType], Dict[str, List[JSONType]], IntoDataFrame, List[TableCell]]], None], optional):@@ -528,6 +531,7 @@ class table(freeze_columns_right=None,text_justify_columns=None,wrapped_columns=None,+ column_widths=None,label="",on_change=None,style_cell=None,@@ -561,6 +565,7 @@ class table(text_justify_columns: dict[str, Literal["left", "center", "right"]]| None = None,wrapped_columns: list[str] | None = None,+ column_widths: dict[str, int] | None = None,hidden_columns: Sequence[str] | None = None,visible_columns: Sequence[str] | None = None,header_tooltip: dict[str, str] | None = None,@@ -801,6 +806,7 @@ class table(_validate_column_formatting(text_justify_columns, wrapped_columns, column_names_set)+ _validate_column_widths(column_widths, column_names_set)_validate_header_tooltip(header_tooltip, column_names_set)field_types = self._manager.get_field_types()@@ -849,6 +855,7 @@ class table("hidden-columns": hidden_columns_list,"text-justify-columns": text_justify_columns,"wrapped-columns": wrapped_columns,+ "column-widths": column_widths,"header-tooltip": header_tooltip,"has-stable-row-id": self._has_stable_row_id,"cell-styles": search_result_styles,@@ -1899,6 +1906,26 @@ def _validate_column_formatting()+def _validate_column_widths(+ column_widths: dict[str, int] | None,+ column_names_set: set[str],+) -> None:+ """Validate column width mapping.++ Ensures all specified columns exist in the table and widths are positive integers.+ """+ if not column_widths:+ return++ for column, width in column_widths.items():+ if column not in column_names_set:+ raise ValueError(f"Column '{column}' not found in table.")+ if not isinstance(width, int) or isinstance(width, bool) or width <= 0:+ raise ValueError(+ f"Width for column '{column}' must be a positive integer, got {width}."+ )++def _validate_header_tooltip(header_tooltip: dict[str, str] | None,column_names_set: set[str],diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.pyindex 557231e21e..8ca3503a91 100644--- a/tests/_plugins/ui/_impl/test_table.py+++ b/tests/_plugins/ui/_impl/test_table.py@@ -3269,3 +3269,18 @@ def test_search_raw_data_with_query_and_format_mapping() -> None:assert json.loads(result.raw_data) == [{"name": "bob", "score": 20},]+++def test_column_widths_valid():+ t = ui.table({"a": [1, 2], "b": [3, 4]}, column_widths={"a": 100})+ assert t._component_args["column-widths"] == {"a": 100}+++def test_column_widths_unknown_column():+ with pytest.raises(ValueError, match="not found in table"):+ ui.table({"a": [1, 2]}, column_widths={"missing": 100})+++def test_column_widths_non_positive():+ with pytest.raises(ValueError, match="positive integer"):+ ui.table({"a": [1, 2]}, column_widths={"a": 0})