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.

feat: mo.ui.table() column chart previews (#1553)

Myles Scolnick5503f41af16d
diff --git a/frontend/src/components/charts/chart-skeleton.tsx b/frontend/src/components/charts/chart-skeleton.tsx
new file mode 100644
index 0000000000..e085dbc038
--- /dev/null
+++ b/frontend/src/components/charts/chart-skeleton.tsx
@@ -0,0 +1,49 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import React from "react";
+
+interface Props {
+ seed: string;
+ width: number;
+ height: number;
+}
+
+// Simple hash function to convert a string to a number
+const hashString = (str: string) => {
+ let hash = 0;
+ for (let i = 0; i < str.length; i++) {
+ const char = str.charCodeAt(i);
+ hash = (hash << 5) - hash + char;
+ hash = Math.trunc(hash); // Convert to 32bit integer
+ }
+ return hash;
+};
+
+// Utility function to generate deterministic random heights based on a seed
+const generateHeights = (numBars: number, maxHeight: number, seed: string) => {
+ const heights = [];
+ let randomSeed = hashString(seed);
+ for (let i = 0; i < numBars; i++) {
+ randomSeed = (randomSeed * 9301 + 49_297) % 233_280;
+ const random = randomSeed / 233_280;
+ const height = Math.abs(Math.floor(random * maxHeight));
+ heights.push(height);
+ }
+ return heights;
+};
+
+export const ChartSkeleton: React.FC<Props> = ({ seed, width, height }) => {
+ const numBars = 9;
+ const barWidth = width / numBars;
+ const heights = generateHeights(numBars, height - 15, seed);
+ return (
+ <div className="flex items-end gap-[1px] pb-2" style={{ width, height }}>
+ {heights.map((barHeight, index) => (
+ <div
+ key={index}
+ className="bg-[var(--slate-5)] animate-pulse"
+ style={{ width: barWidth - 2, height: barHeight }}
+ />
+ ))}
+ </div>
+ );
+};
diff --git a/frontend/src/components/data-table/chart-spec-model.tsx b/frontend/src/components/data-table/chart-spec-model.tsx
new file mode 100644
index 0000000000..9adbde85a1
--- /dev/null
+++ b/frontend/src/components/data-table/chart-spec-model.tsx
@@ -0,0 +1,166 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { TopLevelFacetedUnitSpec } from "@/plugins/impl/data-explorer/queries/types";
+import { VegaType } from "@/plugins/impl/vega/vega-loader";
+import { mint, orange, slate } from "@radix-ui/colors";
+import { ColumnHeaderSummary } from "./types";
+
+export class ColumnChartSpecModel<T> {
+ private columnSummaries = new Map<string | number, ColumnHeaderSummary>();
+
+ public static readonly EMPTY = new ColumnChartSpecModel([], {}, [], {
+ includeCharts: false,
+ });
+
+ constructor(
+ private readonly data: T[],
+ private readonly fieldTypes: Record<string, VegaType>,
+ readonly summaries: ColumnHeaderSummary[],
+ private readonly opts: {
+ includeCharts: boolean;
+ },
+ ) {
+ this.columnSummaries = new Map(summaries.map((s) => [s.column, s]));
+ }
+
+ public getHeaderSummary(column: string) {
+ return {
+ summary: this.columnSummaries.get(column),
+ type: this.fieldTypes[column],
+ spec: this.opts.includeCharts ? this.getVegaSpec(column) : undefined,
+ };
+ }
+
+ private getVegaSpec<T>(column: string): TopLevelFacetedUnitSpec | null {
+ const base: Omit<TopLevelFacetedUnitSpec, "mark"> = {
+ data: {
+ name: "values",
+ },
+ datasets: {
+ values: this.data,
+ },
+ background: "transparent",
+ config: {
+ view: {
+ stroke: "transparent",
+ },
+ axis: {
+ domain: false,
+ },
+ },
+ height: 100,
+ };
+ const type = this.fieldTypes[column];
+
+ switch (type) {
+ case "date":
+ return {
+ ...base,
+ mark: { type: "bar", color: mint.mint11 },
+ encoding: {
+ x: { field: column, type: "temporal", axis: null, bin: true },
+ y: { aggregate: "count", type: "quantitative", axis: null },
+ tooltip: [
+ {
+ field: column,
+ type: "temporal",
+ format: "%Y-%m-%d",
+ bin: true,
+ title: column,
+ },
+ {
+ aggregate: "count",
+ type: "quantitative",
+ title: "Count",
+ format: ",d",
+ },
+ ],
+ // Color nulls
+ color: {
+ condition: {
+ test: `datum["bin_maxbins_10_${column}_range"] === "null"`,
+ value: orange.orange11,
+ },
+ value: mint.mint11,
+ },
+ },
+ };
+ case "integer":
+ case "number": {
+ const format = type === "integer" ? ",d" : ".2f";
+ return {
+ ...base,
+ mark: { type: "bar", color: mint.mint11 },
+ encoding: {
+ x: { field: column, type: "nominal", axis: null, bin: true },
+ y: {
+ aggregate: "count",
+ type: "quantitative",
+ axis: null,
+ scale: { type: "symlog" },
+ },
+ tooltip: [
+ {
+ field: column,
+ type: "nominal",
+ format: format,
+ bin: true,
+ title: column,
+ },
+ {
+ aggregate: "count",
+ type: "quantitative",
+ title: "Count",
+ format: ",d",
+ },
+ ],
+ // Color nulls
+ color: {
+ condition: {
+ test: `datum["bin_maxbins_10_${column}_range"] === "null"`,
+ value: orange.orange11,
+ },
+ value: mint.mint11,
+ },
+ },
+ };
+ }
+ case "boolean":
+ return {
+ ...base,
+ mark: { type: "bar", color: mint.mint11 },
+ encoding: {
+ y: {
+ field: column,
+ type: "nominal",
+ axis: {
+ labelExpr: "datum.label === 'true' ? 'True' : 'False'",
+ tickWidth: 0,
+ title: null,
+ labelColor: slate.slate9,
+ },
+ },
+ x: {
+ aggregate: "count",
+ type: "quantitative",
+ axis: null,
+ scale: { type: "symlog" },
+ },
+ tooltip: [
+ { field: column, type: "nominal", format: ",d", title: "Value" },
+ {
+ aggregate: "count",
+ type: "quantitative",
+ title: "Count",
+ format: ",d",
+ },
+ ],
+ },
+ };
+ case "unknown":
+ case "string":
+ return null;
+ default:
+ return null;
+ }
+ }
+}
diff --git a/frontend/src/components/data-table/column-header.tsx b/frontend/src/components/data-table/column-header.tsx
index 95af9172d7..26650967ec 100644
--- a/frontend/src/components/data-table/column-header.tsx
+++ b/frontend/src/components/data-table/column-header.tsx
@@ -6,10 +6,10 @@ import {
ArrowDownWideNarrowIcon,
ArrowDown10Icon,
ArrowDown01Icon,
+ CopyIcon,
} from "lucide-react";
import { cn } from "@/utils/cn";
-import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
@@ -40,16 +40,19 @@ export const DataTableColumnHeader = <TData, TValue>({
sortFn === sortingFns.basic ? ArrowDown10Icon : ArrowDownWideNarrowIcon;
return (
- <div className={cn("group flex items-center space-x-2", className)}>
- <span className="flex-1">{header}</span>
- <DropdownMenu modal={false}>
- <DropdownMenuTrigger asChild={true}>
- <Button
- variant="ghost"
- data-testid="data-table-sort-button"
- size="xs"
+ <DropdownMenu modal={false}>
+ <DropdownMenuTrigger asChild={true}>
+ <div
+ className={cn(
+ "group flex items-center w-full select-none space-x-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-2",
+ className,
+ )}
+ data-testid="data-table-sort-button"
+ >
+ <span className="flex-1">{header}</span>
+ <span
className={cn(
- "ml-3 h-5 data-[state=open]:bg-accent m-0 p-1",
+ "ml-3 h-5 m-0 p-1",
!column.getIsSorted() &&
"invisible group-hover:visible data-[state=open]:visible",
)}
@@ -61,28 +64,60 @@ export const DataTableColumnHeader = <TData, TValue>({
) : (
<ChevronsUpDown className="h-3 w-3" />
)}
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start">
- <DropdownMenuItem onClick={() => column.toggleSorting(false)}>
- <AscIcon className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" />
- Asc
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => column.toggleSorting(true)}>
- <DescIcon className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" />
- Desc
- </DropdownMenuItem>
- {column.getIsSorted() && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem onClick={() => column.clearSorting()}>
- <ChevronsUpDown className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" />
- Clear
- </DropdownMenuItem>
- </>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
+ </span>
+ </div>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <DropdownMenuItem onClick={() => column.toggleSorting(false)}>
+ <AscIcon className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" />
+ Asc
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => column.toggleSorting(true)}>
+ <DescIcon className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" />
+ Desc
+ </DropdownMenuItem>
+ {column.getIsSorted() && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={() => column.clearSorting()}>
+ <ChevronsUpDown className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" />
+ Clear
+ </DropdownMenuItem>
+ </>
+ )}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={() => navigator.clipboard.writeText(column.id)}
+ >
+ <CopyIcon className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" />
+ Copy column name
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+};
+
+export const DataTableColumnHeaderWithSummary = <TData, TValue>({
+ column,
+ header,
+ summary,
+ className,
+}: DataTableColumnHeaderProps<TData, TValue> & {
+ summary: React.ReactNode;
+}) => {
+ return (
+ <div
+ className={cn(
+ "flex flex-col h-full py-2 justify-between items-start gap-1",
+ className,
+ )}
+ >
+ <DataTableColumnHeader
+ column={column}
+ header={header}
+ className={className}
+ />
+ {summary}
</div>
);
};
diff --git a/frontend/src/components/data-table/column-summary.tsx b/frontend/src/components/data-table/column-summary.tsx
new file mode 100644
index 0000000000..37ff69e00f
--- /dev/null
+++ b/frontend/src/components/data-table/column-summary.tsx
@@ -0,0 +1,157 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import React, { useContext } from "react";
+import { ColumnChartSpecModel } from "./chart-spec-model";
+import { useTheme } from "@/theme/useTheme";
+import { prettyNumber, prettyScientificNumber } from "@/utils/numbers";
+import { prettyDate } from "@/utils/dates";
+import { DelayMount } from "../utils/delay-mount";
+import { ChartSkeleton } from "../charts/chart-skeleton";
+
+export const ColumnChartContext = React.createContext<
+ ColumnChartSpecModel<unknown>
+>(ColumnChartSpecModel.EMPTY);
+
+interface Props<TData, TValue> {
+ columnId: string;
+}
+
+const LazyVegaLite = React.lazy(() =>
+ import("react-vega").then((m) => ({ default: m.VegaLite })),
+);
+
+export const TableColumnSummary = <TData, TValue>({
+ columnId,
+}: Props<TData, TValue>) => {
+ const chartSpecModel = useContext(ColumnChartContext);
+ const { theme } = useTheme();
+ const { spec, type, summary } = chartSpecModel.getHeaderSummary(columnId);
+
+ let chart: React.ReactNode = null;
+ if (spec) {
+ chart = (
+ <DelayMount
+ milliseconds={200}
+ fallback={<ChartSkeleton seed={columnId} width={130} height={60} />}
+ >
+ <LazyVegaLite
+ spec={spec}
+ width={120}
+ height={50}
+ style={{ minWidth: "unset", maxHeight: "60px" }}
+ actions={false}
+ theme={theme === "dark" ? "dark" : "vox"}
+ />
+ </DelayMount>
+ );
+ }
+
+ const renderStats = () => {
+ if (!summary) {
+ return null;
+ }
+
+ switch (type) {
+ case "date":
+ // Without a chart
+ if (!spec) {
+ return (
+ <div className="flex flex-col whitespace-pre">
+ <span>min: {prettyDate(summary.min)}</span>
+ <span>max: {prettyDate(summary.max)}</span>
+ <span>unique: {prettyNumber(summary.unique)}</span>
+ <span>nulls: {prettyNumber(summary.nulls)}</span>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex justify-between w-full px-2 whitespace-pre">
+ <span>{prettyDate(summary.min)}</span>-
+ <span>{prettyDate(summary.max)}</span>
+ </div>
+ );
+ case "integer":
+ case "number":
+ // Without a chart
+ if (!spec) {
+ return (
+ <div className="flex flex-col whitespace-pre">
+ <span>
+ min:{" "}
+ {typeof summary.min === "number"
+ ? prettyScientificNumber(summary.min)
+ : summary.min}
+ </span>
+ <span>
+ max:{" "}
+ {typeof summary.max === "number"
+ ? prettyScientificNumber(summary.max)
+ : summary.max}
+ </span>
+ <span>unique: {prettyNumber(summary.unique)}</span>
+ <span>nulls: {prettyNumber(summary.nulls)}</span>
+ </div>
+ );
+ }
+
+ if (
+ typeof summary.min === "number" &&
+ typeof summary.max === "number"
+ ) {
+ return (
+ <div className="flex justify-between w-full px-2 whitespace-pre">
+ <span>{prettyScientificNumber(summary.min)}</span>
+ <span>{prettyScientificNumber(summary.max)}</span>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex justify-between w-full px-2 whitespace-pre">
+ <span>{summary.min}</span>
+ <span>{summary.max}</span>
+ </div>
+ );
+ case "boolean":
+ // Without a chart
+ if (!spec) {
+ return (
+ <div className="flex flex-col whitespace-pre">
+ <span>true: {prettyNumber(summary.true)}</span>
+ <span>false: {prettyNumber(summary.false)}</span>
+ </div>
+ );
+ }
+
+ if (summary.nulls == null || summary.nulls === 0) {
+ return null;
+ }
+
+ return (
+ <div className="flex flex-col whitespace-pre">
+ <span>nulls: {prettyNumber(summary.nulls)}</span>
+ </div>
+ );
+ case "string":
+ return (
+ <div className="flex flex-col whitespace-pre">
+ <span>unique: {prettyNumber(summary.unique)}</span>
+ <span>nulls: {prettyNumber(summary.nulls)}</span>
+ </div>
+ );
+ case "unknown":
+ return (
+ <div className="flex flex-col whitespace-pre">
+ <span>nulls: {prettyNumber(summary.nulls)}</span>
+ </div>
+ );
+ }
+ };
+
+ return (
+ <div className="flex flex-col items-center text-xs text-muted-foreground align-end">
+ {chart}
+ {renderStats()}
+ </div>
+ );
+};
diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsx
index 61bc3559df..025f91581f 100644
--- a/frontend/src/components/data-table/columns.tsx
+++ b/frontend/src/components/data-table/columns.tsx
@@ -1,8 +1,12 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { ColumnDef } from "@tanstack/react-table";
-import { DataTableColumnHeader } from "./column-header";
+import {
+ DataTableColumnHeader,
+ DataTableColumnHeaderWithSummary,
+} from "./column-header";
import { Checkbox } from "../ui/checkbox";
import { MimeCell } from "./mime-cell";
+import { TableColumnSummary } from "./column-summary";
interface ColumnInfo {
key: string;
@@ -62,6 +66,7 @@ export function generateColumns<T>(
selection: "single" | "multi" | null,
): Array<ColumnDef<T>> {
const columnInfo = getColumnInfo(items);
+
const columns = columnInfo.map(
(info): ColumnDef<T> => ({
id: info.key,
@@ -73,7 +78,13 @@ export function generateColumns<T>(
return (row as any)[info.key];
},
header: ({ column }) => {
- return <DataTableColumnHeader header={info.key} column={column} />;
+ return (
+ <DataTableColumnHeaderWithSummary
+ header={info.key}
+ column={column}
+ summary={<TableColumnSummary columnId={info.key} />}
+ />
+ );
},
cell: ({ renderValue, getValue }) => {
const value = getValue();
diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsx
index cd12868148..9eae35cc67 100644
--- a/frontend/src/components/data-table/data-table.tsx
+++ b/frontend/src/components/data-table/data-table.tsx
@@ -33,6 +33,7 @@ interface DataTableProps<TData> extends Partial<DownloadActionProps> {
pagination?: boolean;
pageSize?: number;
selection?: "single" | "multi" | null;
+ showColumnSummary?: boolean;
rowSelection?: RowSelectionState;
onRowSelectionChange?: OnChangeFn<RowSelectionState>;
}
@@ -104,7 +105,11 @@ const DataTableInternal = <TData,>({
data-state={row.getIsSelected() && "selected"}
>
{row.getVisibleCells().map((cell) => (
- <TableCell key={cell.id}>
+ <TableCell
+ key={cell.id}
+ className="whitespace-nowrap truncate max-w-[300px]"
+ title={String(cell.getValue())}
+ >
{flexRender(
cell.column.columnDef.cell,
cell.getContext(),
diff --git a/frontend/src/components/data-table/loading-table.tsx b/frontend/src/components/data-table/loading-table.tsx
new file mode 100644
index 0000000000..746747afac
--- /dev/null
+++ b/frontend/src/components/data-table/loading-table.tsx
@@ -0,0 +1,56 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { cn } from "@/utils/cn";
+
+interface Props {
+ wrapperClassName?: string;
+ className?: string;
+ pageSize?: number;
+}
+
+export const LoadingTable = ({
+ wrapperClassName,
+ className,
+ pageSize = 10,
+}: Props) => {
+ const NUM_COLUMNS = 8;
+
+ return (
+ <div className={cn(wrapperClassName, "flex flex-col space-y-2")}>
+ <div className={cn(className || "rounded-md border")}>
+ <Table>
+ <TableHeader>
+ {Array.from({ length: 1 }).map((_, i) => (
+ <TableRow key={i}>
+ {Array.from({ length: NUM_COLUMNS }).map((_, j) => (
+ <TableHead key={j}>
+ <div className="h-4 bg-[var(--slate-5)] animate-pulse rounded-md w-[70%]" />
+ </TableHead>
+ ))}
+ </TableRow>
+ ))}
+ </TableHeader>
+ <TableBody>
+ {Array.from({ length: pageSize }).map((_, i) => (
+ <TableRow key={i}>
+ {Array.from({ length: NUM_COLUMNS }).map((_, j) => (
+ <TableCell key={j}>
+ <div className="h-4 bg-[var(--slate-5)] animate-pulse rounded-md w-[90%]" />
+ </TableCell>
+ ))}
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+ <div className="flex align-items justify-between flex-shrink-0 h-8" />
+ </div>
+ );
+};
diff --git a/frontend/src/components/data-table/pagination.tsx b/frontend/src/components/data-table/pagination.tsx
index 4b4c45119f..d2fcff35ee 100644
--- a/frontend/src/components/data-table/pagination.tsx
+++ b/frontend/src/components/data-table/pagination.tsx
@@ -24,37 +24,39 @@ export const DataTablePagination = <TData,>({
if (isAllPageSelected && !isAllSelected) {
return (
- <span>
- {prettyNumber(selected)} selected
+ <>
+ <span>{prettyNumber(selected)} selected</span>
<Button
size="xs"
data-testid="select-all-button"
variant="link"
+ className="mb-0 h-6"
onClick={() => table.toggleAllRowsSelected(true)}
>
Select all {prettyNumber(count)}
</Button>
- </span>
+ </>
);
}
if (selected) {
return (
- <span>
- {prettyNumber(selected)} selected
+ <>
+ <span>{prettyNumber(selected)} selected</span>
<Button
size="xs"
data-testid="clear-selection-button"
variant="link"
+ className="mb-0 h-6"
onClick={() => table.toggleAllRowsSelected(false)}
>
Clear selection
</Button>
- </span>
+ </>
);
}
- return `${prettyNumber(count)} items`;
+ return <span>{prettyNumber(count)} items</span>;
};
const currentPage = Math.min(
table.getState().pagination.pageIndex + 1,
@@ -64,7 +66,9 @@ export const DataTablePagination = <TData,>({
return (
<div className="flex flex-1 items-center justify-between px-2">
- <div className="text-sm text-muted-foreground">{renderTotal()}</div>
+ <div className="text-sm text-muted-foreground h-6 flex items-baseline">
+ {renderTotal()}
+ </div>
<div className="flex items-center space-x-2">
<Button
size="xs"
diff --git a/frontend/src/components/data-table/types.ts b/frontend/src/components/data-table/types.ts
new file mode 100644
index 0000000000..b18aa50215
--- /dev/null
+++ b/frontend/src/components/data-table/types.ts
@@ -0,0 +1,10 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+export interface ColumnHeaderSummary {
+ column: string | number;
+ min?: number | string | undefined | null;
+ max?: number | string | undefined | null;
+ unique?: number | null;
+ nulls?: number | null;
+ true?: number | null;
+ false?: number | null;
+}
diff --git a/frontend/src/components/editor/actions/useCellActionButton.tsx b/frontend/src/components/editor/actions/useCellActionButton.tsx
index dac451f469..9575736c25 100644
--- a/frontend/src/components/editor/actions/useCellActionButton.tsx
+++ b/frontend/src/components/editor/actions/useCellActionButton.tsx
@@ -7,7 +7,11 @@ import {
getEditorViewMode,
toggleMarkdown,
} from "@/core/codemirror/format";
-import { hasOnlyOneCellAtom, useCellActions } from "@/core/cells/cells";
+import {
+ hasOnlyOneCellAtom,
+ useCellActions,
+ useCellIds,
+} from "@/core/cells/cells";
import {
ImageIcon,
Code2Icon,
@@ -77,10 +81,14 @@ export function useCellActionButtons({ cell }: Props) {
const setAiCompletionCell = useSetAtom(aiCompletionCellAtom);
const aiEnabled = useAtomValue(aiEnabledAtom);
const autoInstantiate = useAtomValue(autoInstantiateAtom);
+ const cellIds = useCellIds();
+
if (!cell) {
return [];
}
+
const { cellId, config, getEditorView, name, hasOutput, status } = cell;
+ const cellIdx = cellIds.indexOf(cellId);
const editorView = getEditorView();
const toggleDisabled = async () => {
@@ -125,7 +133,7 @@ export function useCellActionButtons({ cell }: Props) {
<div className="flex items-center justify-between">
<Label htmlFor="cell-name">Cell name</Label>
<NameCellInput
- placeholder={`cell_${cellId}`}
+ placeholder={`cell_${cellIdx}`}
value={name}
onKeyDown={(e) => {
if (e.key === "Enter") {
@@ -144,7 +152,7 @@ export function useCellActionButtons({ cell }: Props) {
},
rightElement: (
<NameCellInput
- placeholder={`cell_${cellId}`}
+ placeholder={`cell_${cellIdx}`}
value={name}
onChange={(newName) => updateCellName({ cellId, name: newName })}
/>
diff --git a/frontend/src/components/editor/cell/code/ai-completion-editor.tsx b/frontend/src/components/editor/cell/code/ai-completion-editor.tsx
index 52f30a6003..484f6791c5 100644
--- a/frontend/src/components/editor/cell/code/ai-completion-editor.tsx
+++ b/frontend/src/components/editor/cell/code/ai-completion-editor.tsx
@@ -18,6 +18,7 @@ import { useAtom } from "jotai";
import { includeOtherCellsAtom } from "@/core/ai/state";
import { Checkbox } from "@/components/ui/checkbox";
import { getCodes } from "@/core/codemirror/copilot/getCodes";
+import { useTheme } from "@/theme/useTheme";
const Original = CodeMirrorMerge.Original;
const Modified = CodeMirrorMerge.Modified;
@@ -81,6 +82,8 @@ export const AiCompletionEditor: React.FC<Props> = ({
}
}, [enabled]);
+ const { theme } = useTheme();
+
return (
<div className="flex flex-col w-full rounded-[inherit] overflow-hidden">
<div
@@ -170,7 +173,7 @@ export const AiCompletionEditor: React.FC<Props> = ({
</Button>
</div>
{completion && enabled && (
- <CodeMirrorMerge className="cm">
+ <CodeMirrorMerge className="cm" theme={theme}>
<Original
onChange={onChange}
value={currentCode}
diff --git a/frontend/src/components/editor/chrome/panels/datasources-panel.tsx b/frontend/src/components/editor/chrome/panels/datasources-panel.tsx
index 18704acab9..1f61fa5643 100644
--- a/frontend/src/components/editor/chrome/panels/datasources-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/datasources-panel.tsx
@@ -345,9 +345,17 @@ const DatasetColumnPreview: React.FC<{
</div>
);
+ const updateSpec = (spec: TopLevelFacetedUnitSpec) => {
+ return {
+ ...spec,
+ config: { ...spec.config, background: "transparent" },
+ };
+ };
const chart = preview.chart_spec && (
<LazyVegaLite
- spec={JSON.parse(preview.chart_spec) as TopLevelFacetedUnitSpec}
+ spec={updateSpec(
+ JSON.parse(preview.chart_spec) as TopLevelFacetedUnitSpec,
+ )}
width={"container" as unknown as number}
height={100}
actions={false}
diff --git a/frontend/src/components/editor/links/cell-link.tsx b/frontend/src/components/editor/links/cell-link.tsx
index 8361e6b96d..c93202c507 100644
--- a/frontend/src/components/editor/links/cell-link.tsx
+++ b/frontend/src/components/editor/links/cell-link.tsx
@@ -67,13 +67,13 @@ export function scrollAndHighlightCell(
cell.classList.add("error-outline");
setTimeout(() => {
cell.classList.remove("error-outline");
- }, 1500);
+ }, 2000);
}
if (variant === "focus") {
cell.classList.add("focus-outline");
setTimeout(() => {
cell.classList.remove("focus-outline");
- }, 1500);
+ }, 2000);
}
return true;
diff --git a/frontend/src/components/utils/delay-mount.tsx b/frontend/src/components/utils/delay-mount.tsx
new file mode 100644
index 0000000000..76fba8ef9e
--- /dev/null
+++ b/frontend/src/components/utils/delay-mount.tsx
@@ -0,0 +1,24 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import React from "react";
+
+interface Props {
+ milliseconds: number;
+ children: React.ReactNode;
+ fallback?: React.ReactNode;
+}
+
+export const DelayMount = ({ milliseconds, children, fallback }: Props) => {
+ const [mounted, setMounted] = React.useState(false);
+
+ React.useEffect(() => {
+ const timeout = setTimeout(() => {
+ setMounted(true);
+ }, milliseconds);
+
+ return () => {
+ clearTimeout(timeout);
+ };
+ }, [milliseconds]);
+
+ return mounted ? children : fallback;
+};
diff --git a/frontend/src/plugins/core/registerReactComponent.tsx b/frontend/src/plugins/core/registerReactComponent.tsx
index 9bfc08c525..302f9c2e31 100644
--- a/frontend/src/plugins/core/registerReactComponent.tsx
+++ b/frontend/src/plugins/core/registerReactComponent.tsx
@@ -162,7 +162,7 @@ function PluginSlotInternal<T>(
const objectId = getUIElementObjectId(hostElement);
invariant(objectId, "Object ID should exist");
const response = await FUNCTIONS_REGISTRY.request({
- args: input.parse(args[0]),
+ args: prettyParse(input, args[0]),
functionName: key,
namespace: objectId,
});
@@ -170,7 +170,7 @@ function PluginSlotInternal<T>(
Logger.error(response.status);
throw new Error(response.status.message);
}
- return output.parse(response.return_value);
+ return prettyParse(output, response.return_value);
};
}
@@ -470,3 +470,14 @@ export function isCustomMarimoElement(
return "__type__" in element && element.__type__ === customElementLocator;
}
+
+function prettyParse<T>(schema: ZodSchema<T>, data: unknown): T {
+ const result = schema.safeParse(data);
+ if (!result.success) {
+ Logger.log("Failed to parse data", data, result.error);
+ throw new Error(
+ result.error.errors.map((e) => `${e.path}: ${e.message}`).join("\n"),
+ );
+ }
+ return result.data;
+}
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index d0d58b3039..8ced77f53f 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -1,5 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { memo, useMemo } from "react";
+import { memo, useEffect, useMemo } from "react";
import { z } from "zod";
import { DataTable } from "../../components/data-table/data-table";
import {
@@ -17,6 +17,12 @@ import { getVegaFieldTypes } from "./vega/utils";
import { Arrays } from "@/utils/arrays";
import { Banner } from "./common/error-banner";
import { prettyNumber } from "@/utils/numbers";
+import { ColumnChartSpecModel } from "@/components/data-table/chart-spec-model";
+import { ColumnChartContext } from "@/components/data-table/column-summary";
+import { Logger } from "@/utils/Logger";
+import { LoadingTable } from "@/components/data-table/loading-table";
+import { DelayMount } from "@/components/utils/delay-mount";
+import { ColumnHeaderSummary } from "@/components/data-table/types";
/**
* Arguments for a data table
@@ -33,6 +39,7 @@ interface Data<T> {
pageSize: number;
selection: "single" | "multi" | null;
showDownload: boolean;
+ showColumnSummary: boolean;
rowHeaders: Array<[string, string[]]>;
fieldTypes?: Record<string, VegaType> | null;
}
@@ -40,6 +47,9 @@ interface Data<T> {
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
type Functions = {
download_as: (req: { format: "csv" | "json" }) => Promise<string>;
+ get_column_summaries: (opts: {}) => Promise<{
+ summaries: ColumnHeaderSummary[];
+ }>;
};
type S = Array<string | number>;
@@ -56,6 +66,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")
pageSize: z.number().default(10),
selection: z.enum(["single", "multi"]).nullable().default(null),
showDownload: z.boolean().default(false),
+ showColumnSummary: z.boolean().default(true),
rowHeaders: z.array(z.tuple([z.string(), z.array(z.any())])),
fieldTypes: z
.record(
@@ -68,6 +79,21 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")
download_as: rpc
.input(z.object({ format: z.enum(["csv", "json"]) }))
.output(z.string()),
+ get_column_summaries: rpc.input(z.object({}).passthrough()).output(
+ z.object({
+ summaries: z.array(
+ z.object({
+ column: z.union([z.number(), z.string()]),
+ min: z.union([z.number(), z.string()]).nullish(),
+ max: z.union([z.number(), z.string()]).nullish(),
+ unique: z.number().nullish(),
+ nulls: z.number().nullish(),
+ true: z.number().nullish(),
+ false: z.number().nullish(),
+ }),
+ ),
+ }),
+ ),
})
.renderer((props) => {
if (typeof props.data.data === "string") {
@@ -101,7 +127,7 @@ interface DataTableProps extends Data<unknown>, Functions {
export const LoadingDataTableComponent = memo(
(props: DataTableProps & { data: string }) => {
const { data, loading, error } = useAsyncData<unknown[]>(() => {
- if (!props.data) {
+ if (!props.data || props.totalRows === 0) {
return Promise.resolve([]);
}
return vegaLoadData(
@@ -109,10 +135,27 @@ export const LoadingDataTableComponent = memo(
{ type: "csv", parse: getVegaFieldTypes(props.fieldTypes) },
{ handleBigInt: true },
);
- }, [props.data, props.fieldTypes]);
+ }, [props.data, props.fieldTypes, props.totalRows]);
+ const { data: columnSummaries, error: columnSummariesError } =
+ useAsyncData(() => {
+ if (props.totalRows === 0) {
+ return Promise.resolve({ summaries: [] });
+ }
+ return props.get_column_summaries({});
+ }, [props.get_column_summaries, props.totalRows]);
+
+ useEffect(() => {
+ if (columnSummariesError) {
+ Logger.error(columnSummariesError);
+ }
+ }, [columnSummariesError]);
if (loading && !data) {
- return null;
+ return (
+ <DelayMount milliseconds={200}>
+ <LoadingTable pageSize={props.pageSize} />
+ </DelayMount>
+ );
}
if (error) {
@@ -126,7 +169,13 @@ export const LoadingDataTableComponent = memo(
);
}
- return <DataTableComponent {...props} data={data || Arrays.EMPTY} />;
+ return (
+ <DataTableComponent
+ {...props}
+ data={data || Arrays.EMPTY}
+ columnSummaries={columnSummaries?.summaries}
+ />
+ );
},
);
LoadingDataTableComponent.displayName = "LoadingDataTableComponent";
@@ -142,12 +191,26 @@ const DataTableComponent = ({
value,
showDownload,
rowHeaders,
+ showColumnSummary,
+ fieldTypes,
download_as: downloadAs,
+ columnSummaries,
className,
setValue,
}: DataTableProps & {
data: unknown[];
+ columnSummaries?: ColumnHeaderSummary[];
}): JSX.Element => {
+ const resultsAreClipped = hasMore && totalRows > 0;
+
+ const chartSpecModel = useMemo(() => {
+ if (!fieldTypes || !data || !columnSummaries) {
+ return ColumnChartSpecModel.EMPTY;
+ }
+ return new ColumnChartSpecModel(data, fieldTypes, columnSummaries, {
+ includeCharts: !resultsAreClipped,
+ });
+ }, [data, fieldTypes, columnSummaries, resultsAreClipped]);
const columns = useMemo(
() => generateColumns(data, generateIndexColumns(rowHeaders), selection),
[data, selection, rowHeaders],
@@ -162,30 +225,35 @@ const DataTableComponent = ({
Result clipped. Total rows {prettyNumber(totalRows)}.
</Banner>
)}
- <Labeled label={label} align="top" fullWidth={true}>
- <DataTable
- data={data}
- columns={columns}
- className={className}
- pagination={pagination}
- pageSize={pageSize}
- rowSelection={rowSelection}
- downloadAs={showDownload ? downloadAs : undefined}
- onRowSelectionChange={(updater) => {
- if (selection === "single") {
- const nextValue =
- typeof updater === "function" ? updater({}) : updater;
- setValue(Object.keys(nextValue).slice(0, 1));
- }
+ <ColumnChartContext.Provider value={chartSpecModel}>
+ <Labeled label={label} align="top" fullWidth={true}>
+ <DataTable
+ data={data}
+ columns={columns}
+ className={className}
+ pagination={pagination}
+ pageSize={pageSize}
+ rowSelection={rowSelection}
+ downloadAs={showDownload ? downloadAs : undefined}
+ showColumnSummary={showColumnSummary}
+ onRowSelectionChange={(updater) => {
+ if (selection === "single") {
+ const nextValue =
+ typeof updater === "function" ? updater({}) : updater;
+ setValue(Object.keys(nextValue).slice(0, 1));
+ }
- if (selection === "multi") {
- const nextValue =
- typeof updater === "function" ? updater(rowSelection) : updater;
- setValue(Object.keys(nextValue));
- }
- }}
- />
- </Labeled>
+ if (selection === "multi") {
+ const nextValue =
+ typeof updater === "function"
+ ? updater(rowSelection)
+ : updater;
+ setValue(Object.keys(nextValue));
+ }
+ }}
+ />
+ </Labeled>
+ </ColumnChartContext.Provider>
</>
);
};
diff --git a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
index c23997927b..752438e1a2 100644
--- a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
+++ b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
@@ -168,6 +168,8 @@ export const DataFrameComponent = memo(
rowHeaders={row_headers || Arrays.EMPTY}
showDownload={false}
download_as={Functions.THROW}
+ showColumnSummary={false}
+ get_column_summaries={getColumnSummaries}
value={Arrays.EMPTY}
setValue={Functions.NOOP}
selection={null}
@@ -178,6 +180,10 @@ export const DataFrameComponent = memo(
);
DataFrameComponent.displayName = "DataFrameComponent";
+function getColumnSummaries() {
+ return Promise.resolve({ summaries: [] });
+}
+
function prettyNumber(value: number): string {
return new Intl.NumberFormat().format(value);
}
diff --git a/frontend/src/plugins/impl/vega/loader.ts b/frontend/src/plugins/impl/vega/loader.ts
index b2122dd1b1..87049e87d9 100644
--- a/frontend/src/plugins/impl/vega/loader.ts
+++ b/frontend/src/plugins/impl/vega/loader.ts
@@ -23,7 +23,12 @@ const customIntegerParser = (v: string) => {
return v;
}
- if (isNumber(Number.parseInt(v))) {
+ const parsedInt = Number.parseInt(v);
+ if (isNumber(parsedInt)) {
+ const needsBigInt = Math.abs(parsedInt) > Number.MAX_SAFE_INTEGER;
+ if (!needsBigInt) {
+ return previousIntegerParser(v);
+ }
try {
return BigInt(v);
} catch {
diff --git a/frontend/src/utils/dates.ts b/frontend/src/utils/dates.ts
new file mode 100644
index 0000000000..f7930c550c
--- /dev/null
+++ b/frontend/src/utils/dates.ts
@@ -0,0 +1,19 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { Logger } from "./Logger";
+
+export function prettyDate(value: string | number | null | undefined): string {
+ if (value == null) {
+ return "";
+ }
+
+ try {
+ return new Date(value).toLocaleDateString(undefined, {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ });
+ } catch (error) {
+ Logger.warn("Failed to parse date", error);
+ return value.toString();
+ }
+}
diff --git a/frontend/src/utils/numbers.ts b/frontend/src/utils/numbers.ts
index 2bd53c6077..cd52f9eac9 100644
--- a/frontend/src/utils/numbers.ts
+++ b/frontend/src/utils/numbers.ts
@@ -1,6 +1,12 @@
/* Copyright 2024 Marimo. All rights reserved. */
-export function prettyNumber(value: number | string): string {
+export function prettyNumber(
+ value: number | string | undefined | null,
+): string {
+ if (value === undefined || value === null) {
+ return "";
+ }
+
if (typeof value === "string") {
return value;
}
diff --git a/marimo/_data/charts.py b/marimo/_data/charts.py
index 1ff5841a09..5b89a48a15 100644
--- a/marimo/_data/charts.py
+++ b/marimo/_data/charts.py
@@ -256,13 +256,13 @@ class WrapperChartBuilder(ChartBuilder):
def altair(self, data: Any, column: str) -> Any:
return self.delegate.altair(
- data, _escape_special_path_characters(column)
+ data, _escape_special_path_characters(str(column))
)
def altair_code(self, data: str, column: str) -> str:
return dedent(
self.delegate.altair_code(
- data, _escape_special_path_characters(column)
+ data, _escape_special_path_characters(str(column))
)
).strip()
@@ -286,10 +286,13 @@ def get_chart_builder(
return WrapperChartBuilder(UnknownChartBuilder())
-def _escape_special_path_characters(column: str) -> str:
+def _escape_special_path_characters(column: str | int) -> str:
"""
Escape special characters in a column name that is a path.
"""
+ if not isinstance(column, str):
+ return str(column)
+
return (
column.replace(".", "\\.")
.replace("[", "\\[")
diff --git a/marimo/_data/preview_column.py b/marimo/_data/preview_column.py
index 445dd2e567..8afb85c78e 100644
--- a/marimo/_data/preview_column.py
+++ b/marimo/_data/preview_column.py
@@ -30,6 +30,12 @@ def get_column_preview(
table = get_table_manager_or_none(item)
if table is None:
return None
+ if table.get_num_rows() == 0:
+ return DataColumnPreview(
+ table_name=table_name,
+ column_name=column_name,
+ error="Table is empty",
+ )
# Get the summary of the column
try:
@@ -54,7 +60,7 @@ def get_column_preview(
# Check for special characters that can't be escaped easily
# (e.g. backslash, quotes)
for char in ["\\", '"', "'"]:
- if char in column_name:
+ if char in str(column_name):
error = (
f"Column names with `{char}` are not supported "
"in charts. Consider renaming the column."
@@ -72,6 +78,7 @@ def get_column_preview(
_get_altair_chart(request, table, summary)
)
except Exception as e:
+ error = str(e)
LOGGER.warning(
"Failed to get chart for column %s in table %s",
column_name,
diff --git a/marimo/_plugins/core/json_encoder.py b/marimo/_plugins/core/json_encoder.py
index 13999a02a4..0bb521dfb6 100644
--- a/marimo/_plugins/core/json_encoder.py
+++ b/marimo/_plugins/core/json_encoder.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import datetime
import json
from json import JSONEncoder
from typing import Any
@@ -72,5 +73,9 @@ class WebComponentEncoder(JSONEncoder):
if isinstance(obj, set):
return list(obj)
+ # Handle datetime objects
+ if isinstance(obj, datetime.datetime):
+ return obj.isoformat()
+
# Fallthrough to default encoder
return JSONEncoder.default(self, obj)
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index 75535c8e87..afed57d661 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -16,6 +16,7 @@ from typing import (
import marimo._output.data.data as mo_data
from marimo import _loggers
+from marimo._data.models import NonNestedLiteral
from marimo._output.mime import MIME
from marimo._output.rich_help import mddoc
from marimo._plugins.core.web_component import JSONType
@@ -25,7 +26,7 @@ from marimo._plugins.ui._impl.tables.table_manager import (
)
from marimo._plugins.ui._impl.tables.utils import get_table_manager
from marimo._plugins.ui._impl.utils.dataframe import ListOrTuple, TableData
-from marimo._runtime.functions import Function
+from marimo._runtime.functions import EmptyArgs, Function
LOGGER = _loggers.marimo_logger()
@@ -41,6 +42,25 @@ class DownloadAsArgs:
format: Literal["csv", "json"]
+@dataclass
+class ColumnSummary:
+ column: str
+ nulls: Optional[int]
+ # int, float, datetime
+ min: Optional[NonNestedLiteral]
+ max: Optional[NonNestedLiteral]
+ # str
+ unique: Optional[int]
+ # bool
+ true: Optional[NonNestedLiteral] = None
+ false: Optional[NonNestedLiteral] = None
+
+
+@dataclass
+class ColumnSummaries:
+ summaries: List[ColumnSummary]
+
+
@mddoc
class table(
UIElement[List[str], Union[List[JSONType], "pd.DataFrame", "pl.DataFrame"]]
@@ -156,6 +176,7 @@ class table(
) -> None:
self._data = data
self._manager = get_table_manager(data)
+ self._unfiltered_manager = self._manager
self._filtered_manager: Optional[TableManager[Any]] = None
totalRows = self._manager.get_num_rows()
@@ -193,6 +214,11 @@ class table(
arg_cls=DownloadAsArgs,
function=self.download_as,
),
+ Function(
+ name=self.get_column_summaries.__name__,
+ arg_cls=EmptyArgs,
+ function=self.get_column_summaries,
+ ),
),
)
@@ -225,3 +251,22 @@ class table(
return mo_data.json(manager.to_json()).url
else:
raise ValueError("format must be one of 'csv' or 'json'.")
+
+ def get_column_summaries(self, args: EmptyArgs) -> ColumnSummaries:
+ del args
+ summaries: List[ColumnSummary] = []
+ for column in self._unfiltered_manager.get_column_names():
+ summary = self._unfiltered_manager.get_summary(column)
+ summaries.append(
+ ColumnSummary(
+ column=column,
+ nulls=summary.nulls,
+ min=summary.min,
+ max=summary.max,
+ unique=summary.unique,
+ true=summary.true,
+ false=summary.false,
+ )
+ )
+
+ return ColumnSummaries(summaries)
diff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.py
index 702f0aa393..f50a4d32d1 100644
--- a/marimo/_plugins/ui/_impl/tables/default_table.py
+++ b/marimo/_plugins/ui/_impl/tables/default_table.py
@@ -132,6 +132,14 @@ class DefaultTableManager(TableManager[JsonTableData]):
return len(self.data)
return 1
+ def get_column_names(self) -> List[str]:
+ if isinstance(self.data, dict):
+ return list(self.data.keys())
+ first = next(iter(self.data), None)
+ if isinstance(first, dict):
+ return list(first.keys())
+ return ["value"]
+
@staticmethod
def is_type(value: Any) -> bool:
return isinstance(value, (list, tuple, dict))
diff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.py
index 5f2e941559..f413df6851 100644
--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py
+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py
@@ -221,4 +221,7 @@ class PandasTableManagerFactory(TableManagerFactory):
def get_num_columns(self) -> int:
return self.data.shape[1]
+ def get_column_names(self) -> list[str]:
+ return self.data.columns.tolist()
+
return PandasTableManager
diff --git a/marimo/_plugins/ui/_impl/tables/polars_table.py b/marimo/_plugins/ui/_impl/tables/polars_table.py
index 20d86a2c2b..44671599e6 100644
--- a/marimo/_plugins/ui/_impl/tables/polars_table.py
+++ b/marimo/_plugins/ui/_impl/tables/polars_table.py
@@ -115,6 +115,9 @@ class PolarsTableManagerFactory(TableManagerFactory):
def get_num_columns(self) -> int:
return self.data.width
+ def get_column_names(self) -> list[str]:
+ return self.data.columns
+
@staticmethod
def _get_field_type(column: pl.Series) -> FieldType:
if column.is_utf8():
diff --git a/marimo/_plugins/ui/_impl/tables/pyarrow_table.py b/marimo/_plugins/ui/_impl/tables/pyarrow_table.py
index df94d4d09a..d61cbb6d63 100644
--- a/marimo/_plugins/ui/_impl/tables/pyarrow_table.py
+++ b/marimo/_plugins/ui/_impl/tables/pyarrow_table.py
@@ -150,6 +150,9 @@ class PyArrowTableManagerFactory(TableManagerFactory):
def get_num_columns(self) -> int:
return self.data.num_columns
+ def get_column_names(self) -> list[str]:
+ return self.data.schema.names
+
@staticmethod
def _get_field_type(column: pa.Array[Any, Any]) -> FieldType:
if isinstance(column, pa.NullArray):
diff --git a/marimo/_plugins/ui/_impl/tables/table_manager.py b/marimo/_plugins/ui/_impl/tables/table_manager.py
index cfa982c12b..8b83c9d0a5 100644
--- a/marimo/_plugins/ui/_impl/tables/table_manager.py
+++ b/marimo/_plugins/ui/_impl/tables/table_manager.py
@@ -16,7 +16,7 @@ FieldTypes = Dict[str, FieldType]
class TableManager(abc.ABC, Generic[T]):
- DEFAULT_LIMIT = 10_000
+ DEFAULT_LIMIT = 20_000
type: str = ""
def __init__(self, data: T) -> None:
@@ -86,6 +86,10 @@ class TableManager(abc.ABC, Generic[T]):
def get_num_columns(self) -> int:
raise NotImplementedError
+ @abc.abstractmethod
+ def get_column_names(self) -> list[str]:
+ raise NotImplementedError
+
class TableManagerFactory(abc.ABC):
@staticmethod
diff --git a/marimo/_server/api/endpoints/ws.py b/marimo/_server/api/endpoints/ws.py
index 62f5a42927..a206443470 100644
--- a/marimo/_server/api/endpoints/ws.py
+++ b/marimo/_server/api/endpoints/ws.py
@@ -309,15 +309,22 @@ class WebsocketHandler(SessionConsumer):
async def listen_for_messages() -> None:
while True:
(op, data) = await self.message_queue.get()
- await self.websocket.send_text(
- json.dumps(
- {
- "op": op,
- "data": data,
- },
- cls=WebComponentEncoder,
+ try:
+ await self.websocket.send_text(
+ json.dumps(
+ {
+ "op": op,
+ "data": data,
+ },
+ cls=WebComponentEncoder,
+ )
)
- )
+ except TypeError as e:
+ # This is a deserialization error
+ LOGGER.error(
+ "Failed to send message to frontend: %s", str(e)
+ )
+ LOGGER.error("Message: %s", data)
async def listen_for_disconnect() -> None:
try:
diff --git a/marimo/_smoke_tests/datasources.py b/marimo/_smoke_tests/datasources.py
index 8af1d3663a..9015e81580 100644
--- a/marimo/_smoke_tests/datasources.py
+++ b/marimo/_smoke_tests/datasources.py
@@ -57,5 +57,11 @@ def __(df):
return pa, pyarrow_df
+def __(mo, polars_df):
+ mo.ui.table(polars_df)
+ return
+
+
if __name__ == "__main__":
app.run()