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
improvement: Add text justification and wrapping option for `mo.ui.table` (#2730)
eugene1c0e0ef670af
diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsxindex 2aeb9cb354..736e6cd00c 100644--- a/frontend/src/components/data-table/columns.tsx+++ b/frontend/src/components/data-table/columns.tsx@@ -13,6 +13,7 @@ import type { FilterType } from "./filters";import type { FieldTypesWithExternalType } from "./types";import { UrlDetector } from "./url-detector";import { Arrays } from "@/utils/arrays";+import { cn } from "@/utils/cn";interface ColumnInfo {key: string;@@ -73,11 +74,15 @@ export function generateColumns<T>({rowHeaders,selection,fieldTypes,+ textJustifyColumns,+ wrappedColumns,}: {items: T[];rowHeaders: string[];selection: "single" | "multi" | null;fieldTypes?: FieldTypesWithExternalType;+ textJustifyColumns?: Record<string, "left" | "center" | "right">;+ wrappedColumns?: string[];}): Array<ColumnDef<T>> {const columnInfo = getColumnInfo(items);const rowHeadersSet = new Set(rowHeaders);@@ -127,23 +132,37 @@ export function generateColumns<T>({}const value = getValue();+ const justify = textJustifyColumns?.[info.key];+ const wrapped = wrappedColumns?.includes(info.key);const format = column.getColumnFormatting?.();if (format) {- return column.applyColumnFormatting(value);+ return (+ <div className={getCellStyleClass(justify, wrapped)}>+ {column.applyColumnFormatting(value)}+ </div>+ );}if (isPrimitiveOrNullish(value)) {const rendered = renderValue();- if (rendered == null) {- return "";- }- if (typeof rendered === "string") {- return <UrlDetector text={rendered} />;- }- return String(rendered);+ return (+ <div className={getCellStyleClass(justify, wrapped)}>+ {rendered == null ? (+ ""+ ) : typeof rendered === "string" ? (+ <UrlDetector text={rendered} />+ ) : (+ String(rendered)+ )}+ </div>+ );}- return <MimeCell value={value} />;+ return (+ <div className={getCellStyleClass(justify, wrapped)}>+ <MimeCell value={value} />+ </div>+ );},// Only enable sorting for primitive types and non-row headersenableSorting: info.type === "primitive" && !rowHeadersSet.has(info.key),@@ -225,3 +244,16 @@ function getFilterTypeForFieldType(return undefined;}}++function getCellStyleClass(+ justify: "left" | "center" | "right" | undefined,+ wrapped: boolean | undefined,+): string {+ return cn(+ "w-full",+ "text-left",+ justify === "center" && "text-center",+ justify === "right" && "text-right",+ wrapped && "whitespace-pre-wrap min-w-[200px]",+ );+}diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex 99c6b0bd0e..1b43600bfa 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -70,6 +70,8 @@ interface Data<T> {fieldTypes?: FieldTypesWithExternalType | null;freezeColumnsLeft?: string[];freezeColumnsRight?: string[];+ textJustifyColumns?: Record<string, "left" | "center" | "right">;+ wrappedColumns?: string[];}// eslint-disable-next-line @typescript-eslint/consistent-type-definitions@@ -109,6 +111,10 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")rowHeaders: z.array(z.string()),freezeColumnsLeft: z.array(z.string()).optional(),freezeColumnsRight: z.array(z.string()).optional(),+ textJustifyColumns: z+ .record(z.enum(["left", "center", "right"]))+ .optional(),+ wrappedColumns: z.array(z.string()).optional(),fieldTypes: z.record(z.tuple([z.enum(DATA_TYPES), z.string()])).nullish(),}),)@@ -421,6 +427,8 @@ const DataTableComponent = ({reloading,freezeColumnsLeft,freezeColumnsRight,+ textJustifyColumns,+ wrappedColumns,}: DataTableProps<unknown> &DataTableSearchProps & {data: unknown[];@@ -454,9 +462,21 @@ const DataTableComponent = ({rowHeaders: rowHeaders,selection,fieldTypes: fieldTypes ?? {},+ textJustifyColumns,+ wrappedColumns,}),- // eslint-disable-next-line react-hooks/exhaustive-deps- [data, useDeepCompareMemoize([selection, fieldTypes, rowHeaders])],+ /* eslint-disable react-hooks/exhaustive-deps */+ [+ data,+ useDeepCompareMemoize([+ selection,+ fieldTypes,+ rowHeaders,+ textJustifyColumns,+ wrappedColumns,+ ]),+ ],+ /* eslint-enable react-hooks/exhaustive-deps */);const rowSelection = useMemo(diff --git a/marimo/_islands/__init__.py b/marimo/_islands/__init__.pyindex 61acf554fa..92fba771d5 100644--- a/marimo/_islands/__init__.py+++ b/marimo/_islands/__init__.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations__all__ = [diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.pyindex c80161c75b..93e12c8882 100644--- a/marimo/_plugins/ui/_impl/table.py+++ b/marimo/_plugins/ui/_impl/table.py@@ -200,6 +200,9 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):or functions- `freeze_columns_left`: list of column names to freeze on the left- `freeze_columns_right`: list of column names to freeze on the right+ - `text_justify_columns`: dictionary of column names to text justification+ options: `left`, `center`, `right`+ - `wrapped_columns`: list of column names to wrap- `label`: markdown label for the element- `on_change`: optional callback to run when this element's value changes"""@@ -223,6 +226,10 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):] = None,freeze_columns_left: Optional[Sequence[str]] = None,freeze_columns_right: Optional[Sequence[str]] = None,+ text_justify_columns: Optional[+ Dict[str, Literal["left", "center", "right"]]+ ] = None,+ wrapped_columns: Optional[List[str]] = None,show_download: bool = True,*,label: str = "",@@ -335,6 +342,25 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):f"Column '{column}' not found in table.")+ if text_justify_columns:+ valid_justifications = {"left", "center", "right"}+ column_names = self._manager.get_column_names()++ for column, justify in text_justify_columns.items():+ if column not in column_names:+ raise ValueError(f"Column '{column}' not found in table.")+ if justify not in valid_justifications:+ raise ValueError(+ f"Invalid justification '{justify}' for column '{column}'. "+ f"Must be one of: {', '.join(valid_justifications)}."+ )++ if wrapped_columns:+ column_names = self._manager.get_column_names()+ for column in wrapped_columns:+ if column not in column_names:+ raise ValueError(f"Column '{column}' not found in table.")+super().__init__(component_name=table._name,label=label,@@ -355,6 +381,8 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):"row-headers": self._manager.get_row_headers(),"freeze-columns-left": freeze_columns_left,"freeze-columns-right": freeze_columns_right,+ "text-justify-columns": text_justify_columns,+ "wrapped-columns": wrapped_columns,},on_change=on_change,functions=(