Skip to content

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.

improvement: show dtype and column count in table (#2270)

Myles Scolnick3ebfffc2308b
diff --git a/frontend/src/components/data-table/column-header.tsx b/frontend/src/components/data-table/column-header.tsx
index 9f55fa6504..daf481cb8f 100644
--- a/frontend/src/components/data-table/column-header.tsx
+++ b/frontend/src/components/data-table/column-header.tsx
@@ -37,6 +37,7 @@ import { formatOptions } from "./column-formatting/types";
import { DATA_TYPE_ICON } from "../datasets/icons";
import { formattingExample } from "./column-formatting/feature";
import { PinLeftIcon, PinRightIcon } from "@radix-ui/react-icons";
+import { NAMELESS_COLUMN_PREFIX } from "./columns";
interface DataTableColumnHeaderProps<TData, TValue>
extends React.HTMLAttributes<HTMLDivElement> {
@@ -209,7 +210,7 @@ export const DataTableColumnHeader = <TData, TValue>({
<DropdownMenuTrigger asChild={true}>
<div
className={cn(
- "group flex items-center my-1 space-between w-full select-none gap-2 border hover:border-border border-transparent hover:bg-[var(--slate-3)] data-[state=open]:bg-[var(--slate-3)] data-[state=open]:border-border rounded px-2 -mx-1",
+ "group flex items-center my-1 space-between w-full select-none gap-2 border hover:border-border border-transparent hover:bg-[var(--slate-3)] data-[state=open]:bg-[var(--slate-3)] data-[state=open]:border-border rounded px-1 -mx-1",
className,
)}
data-testid="data-table-sort-button"
@@ -217,7 +218,7 @@ export const DataTableColumnHeader = <TData, TValue>({
<span className="flex-1">{header}</span>
<span
className={cn(
- "h-5 py-1 px-2 mr-2",
+ "h-5 py-1 px-1",
!column.getIsSorted() &&
"invisible group-hover:visible data-[state=open]:visible",
)}
@@ -242,16 +243,18 @@ export const DataTableColumnHeader = <TData, TValue>({
</>
)}
{renderSorts()}
- <DropdownMenuItem
- onClick={() =>
- navigator.clipboard.writeText(
- typeof header === "string" ? header : column.id,
- )
- }
- >
- <CopyIcon className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" />
- Copy column name
- </DropdownMenuItem>
+ {!column.id.startsWith(NAMELESS_COLUMN_PREFIX) && (
+ <DropdownMenuItem
+ onClick={() =>
+ navigator.clipboard.writeText(
+ typeof header === "string" ? header : column.id,
+ )
+ }
+ >
+ <CopyIcon className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" />
+ Copy column name
+ </DropdownMenuItem>
+ )}
{renderColumnPinning()}
{renderColumnWrapping()}
{renderFormatOptions()}
diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsx
index 009a1c1f96..a207718536 100644
--- a/frontend/src/components/data-table/columns.tsx
+++ b/frontend/src/components/data-table/columns.tsx
@@ -65,6 +65,8 @@ function getColumnInfo<T>(items: T[]): ColumnInfo[] {
return [...keys.values()];
}
+export const NAMELESS_COLUMN_PREFIX = "__m_column__";
+
export function generateColumns<T>({
items,
rowHeaders,
@@ -83,7 +85,7 @@ export function generateColumns<T>({
const columns = columnInfo.map(
(info, idx): ColumnDef<T> => ({
- id: info.key || `__m_column__${idx}`,
+ id: info.key || `${NAMELESS_COLUMN_PREFIX}${idx}`,
// Use an accessorFn instead of an accessorKey because column names
// may have periods in them ...
// https://github.com/TanStack/table/issues/1671
@@ -93,18 +95,32 @@ export function generateColumns<T>({
},
header: ({ column }) => {
+ const dtype = column.columnDef.meta?.dtype;
+ const headerWithType = (
+ <div className="flex flex-col">
+ <span className="font-bold">{info.key}</span>
+ {dtype && (
+ <span className="text-xs text-muted-foreground">{dtype}</span>
+ )}
+ </div>
+ );
+
// Row headers have no summaries
if (rowHeadersSet.has(info.key)) {
- return <DataTableColumnHeader header={info.key} column={column} />;
+ return (
+ <DataTableColumnHeader header={headerWithType} column={column} />
+ );
}
if (!showColumnSummaries) {
- return <DataTableColumnHeader header={info.key} column={column} />;
+ return (
+ <DataTableColumnHeader header={headerWithType} column={column} />
+ );
}
return (
<DataTableColumnHeaderWithSummary
- header={info.key}
+ header={headerWithType}
column={column}
summary={<TableColumnSummary columnId={info.key} />}
/>
@@ -162,7 +178,7 @@ export function generateColumns<T>({
table.toggleAllPageRowsSelected(!!value)
}
aria-label="Select all"
- className="mx-2"
+ className="mx-1.5 my-4"
/>
) : null,
cell: ({ row }) => (
diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsx
index be2aeded12..f011cab1a6 100644
--- a/frontend/src/components/data-table/data-table.tsx
+++ b/frontend/src/components/data-table/data-table.tsx
@@ -80,6 +80,7 @@ const DataTableInternal = <TData,>({
className,
columns,
data,
+ selection,
totalRows,
manualSorting = false,
sorting,
@@ -246,7 +247,7 @@ const DataTableInternal = <TData,>({
<TableHead
key={header.id}
className={cn(
- "h-auto min-h-10 whitespace-pre align-baseline",
+ "h-auto min-h-10 whitespace-pre align-top",
className,
)}
style={style}
@@ -359,6 +360,7 @@ const DataTableInternal = <TData,>({
)}
{pagination ? (
<DataTablePagination
+ selection={selection}
onSelectAllRowsChange={
onRowSelectionChange
? (value) => {
diff --git a/frontend/src/components/data-table/pagination.tsx b/frontend/src/components/data-table/pagination.tsx
index ee96e1fa07..7ea7c2e609 100644
--- a/frontend/src/components/data-table/pagination.tsx
+++ b/frontend/src/components/data-table/pagination.tsx
@@ -13,11 +13,13 @@ import { range } from "lodash-es";
interface DataTablePaginationProps<TData> {
table: Table<TData>;
+ selection?: "single" | "multi" | null;
onSelectAllRowsChange?: (value: boolean) => void;
}
export const DataTablePagination = <TData,>({
table,
+ selection,
onSelectAllRowsChange,
}: DataTablePaginationProps<TData>) => {
const renderTotal = () => {
@@ -72,11 +74,15 @@ export const DataTablePagination = <TData,>({
);
}
- return (
- <span>
- {prettyNumber(numRows)} {new PluralWord("row").pluralize(numRows)}
- </span>
- );
+ let numColumns = table.getAllColumns().length;
+ // If we have a selection column, subtract one from the total columns
+ if (selection != null) {
+ numColumns -= 1;
+ }
+ const rowsLabel = `${prettyNumber(numRows)} ${new PluralWord("row").pluralize(numRows)}`;
+ const columnsLabel = `${prettyNumber(numColumns)} ${new PluralWord("column").pluralize(numColumns)}`;
+
+ return <span>{[rowsLabel, columnsLabel].join(", ")}</span>;
};
const currentPage = Math.min(
table.getState().pagination.pageIndex + 1,
diff --git a/frontend/src/core/codemirror/go-to-definition/underline.ts b/frontend/src/core/codemirror/go-to-definition/underline.ts
index eb4363cc63..724f3e620e 100644
--- a/frontend/src/core/codemirror/go-to-definition/underline.ts
+++ b/frontend/src/core/codemirror/go-to-definition/underline.ts
@@ -87,26 +87,33 @@ class MetaUnderlineVariablePlugin {
// Exit the cmd+click mode
private keyup = (event: KeyboardEvent) => {
if (event.key === "Meta" || event.key === "Control") {
- this.commandClickMode = false;
- this.view.dom.removeEventListener("mousemove", this.mousemove);
- this.view.dom.removeEventListener("click", this.click);
- this.clearUnderline();
+ this.exitCommandClickMode();
}
};
// Handle window blur event to reset state
private windowBlur = () => {
if (this.commandClickMode) {
- this.commandClickMode = false;
- this.view.dom.removeEventListener("mousemove", this.mousemove);
- this.view.dom.removeEventListener("click", this.click);
- this.clearUnderline();
+ this.exitCommandClickMode();
}
};
+ private exitCommandClickMode() {
+ this.commandClickMode = false;
+ this.view.dom.removeEventListener("mousemove", this.mousemove);
+ this.view.dom.removeEventListener("click", this.click);
+ this.clearUnderline();
+ }
+
// While moving the mouse in cmd+click mode,
// Track the variables we are hovering
private mousemove = (event: MouseEvent) => {
+ // Check if the key is still pressed
+ if (!event.metaKey && !event.ctrlKey) {
+ this.exitCommandClickMode();
+ return;
+ }
+
if (!this.commandClickMode) {
this.clearUnderline();
return;
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index aaee5f5a8f..2dc844e474 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -514,6 +514,7 @@ const DataTableComponent = ({
setSorting={setSorting}
pagination={pagination}
manualPagination={true}
+ selection={selection}
paginationState={paginationState}
setPaginationState={setPaginationState}
rowSelection={rowSelection}
diff --git a/marimo/_smoke_tests/_polars/polars_to_csv.py b/marimo/_smoke_tests/_polars/polars_to_csv.py
index 3c52c05111..39f64c6774 100644
--- a/marimo/_smoke_tests/_polars/polars_to_csv.py
+++ b/marimo/_smoke_tests/_polars/polars_to_csv.py
@@ -1,3 +1,10 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = [
+# "marimo",
+# "polars",
+# ]
+# ///
# Copyright 2024 Marimo. All rights reserved.
import marimo
diff --git a/marimo/_smoke_tests/datasources.py b/marimo/_smoke_tests/datasources.py
index 35a23aaaac..5b809b7d99 100644
--- a/marimo/_smoke_tests/datasources.py
+++ b/marimo/_smoke_tests/datasources.py
@@ -11,7 +11,7 @@
import marimo
-__generated_with = "0.6.19"
+__generated_with = "0.8.13"
app = marimo.App(width="full")
@@ -84,5 +84,35 @@ def __(df, mo):
return
+def __(mo, polars_df):
+ _df = mo.sql(
+ f"""
+ SELECT * FROM polars_df
+ """
+ )
+ return
+
+
+def __(mo):
+ mo.ui.table({"a": [2, 2, 12], "b": [2, 5, 6]})
+ return
+
+
+def __(mo, polars_df):
+ mo.plain(polars_df)
+ return
+
+
+def __(pd):
+ date_range = pd.date_range(start="2023-01-01", periods=10, freq="D")
+ date_indexed_df = pd.DataFrame({"Data": range(10)}, index=date_range)
+ date_indexed_df
+ return date_indexed_df, date_range
+
+
if __name__ == "__main__":
app.run()
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index 66244c713d..758cf9e879 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -2142,7 +2142,7 @@ class TestSQL:
)
# make sure cell 1 executed, defining df
- assert k.globals["df"].to_dict(as_series=False) == {"a": [42]}
+ assert k.globals["t1_df"].to_dict(as_series=False) == {"a": [42]}
await k.delete_cell(DeleteCellRequest(cell_id="3"))
# t1 should be dropped since it's an in-memory table;