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.

chore: refactor table to clean it up (#2319)

Myles Scolnick2cc6bb5ca3f3
diff --git a/frontend/src/components/data-table/SearchBar.tsx b/frontend/src/components/data-table/SearchBar.tsx
new file mode 100644
index 0000000000..92eb7543ad
--- /dev/null
+++ b/frontend/src/components/data-table/SearchBar.tsx
@@ -0,0 +1,65 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import React, { useState, useEffect } from "react";
+import { SearchIcon } from "lucide-react";
+import { Spinner } from "../icons/spinner";
+import { cn } from "@/utils/cn";
+import { useDebounce } from "@uidotdev/usehooks";
+import useEvent from "react-use-event-hook";
+
+interface SearchBarProps {
+ hidden: boolean;
+ value: string;
+ handleSearch: (query: string) => void;
+ onHide: () => void;
+ reloading?: boolean;
+}
+
+export const SearchBar = ({
+ hidden,
+ value,
+ handleSearch,
+ onHide,
+ reloading,
+}: SearchBarProps) => {
+ const [internalValue, setInternalValue] = useState(value);
+ const debouncedSearch = useDebounce(internalValue, 500);
+ const onSearch = useEvent(handleSearch);
+ const ref = React.useRef<HTMLInputElement>(null);
+
+ useEffect(() => {
+ onSearch(debouncedSearch);
+ }, [debouncedSearch, onSearch]);
+
+ useEffect(() => {
+ if (hidden) {
+ setInternalValue("");
+ } else {
+ ref.current?.focus();
+ }
+ }, [hidden]);
+
+ return (
+ <div
+ className={cn(
+ "flex items-center space-x-2 h-8 px-2 border-b transition-all overflow-hidden duration-300 opacity-100",
+ hidden && "h-0 border-none opacity-0",
+ )}
+ >
+ <SearchIcon className="w-4 h-4 text-muted-foreground" />
+ <input
+ type="text"
+ ref={ref}
+ className="w-full h-full border-none bg-transparent focus:outline-none text-sm"
+ value={internalValue}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ onHide();
+ }
+ }}
+ onChange={(e) => setInternalValue(e.target.value)}
+ placeholder="Search"
+ />
+ {reloading && <Spinner size="small" />}
+ </div>
+ );
+};
diff --git a/frontend/src/components/data-table/TableActions.tsx b/frontend/src/components/data-table/TableActions.tsx
new file mode 100644
index 0000000000..4cbaf99b0c
--- /dev/null
+++ b/frontend/src/components/data-table/TableActions.tsx
@@ -0,0 +1,73 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import React from "react";
+import { Tooltip } from "../ui/tooltip";
+import { Button } from "../ui/button";
+import { SearchIcon } from "lucide-react";
+import { DataTablePagination } from "./pagination";
+import { DownloadAs, type DownloadActionProps } from "./download-actions";
+import type { Table, RowSelectionState } from "@tanstack/react-table";
+
+interface TableActionsProps<TData> {
+ enableSearch: boolean;
+ onSearchQueryChange?: (query: string) => void;
+ isSearchEnabled: boolean;
+ setIsSearchEnabled: React.Dispatch<React.SetStateAction<boolean>>;
+ pagination: boolean;
+ selection?: "single" | "multi" | null;
+ onRowSelectionChange?: (value: RowSelectionState) => void;
+ table: Table<TData>;
+ downloadAs?: DownloadActionProps["downloadAs"];
+}
+
+export const TableActions = <TData,>({
+ enableSearch,
+ onSearchQueryChange,
+ isSearchEnabled,
+ setIsSearchEnabled,
+ pagination,
+ selection,
+ onRowSelectionChange,
+ table,
+ downloadAs,
+}: TableActionsProps<TData>) => {
+ return (
+ <div className="flex items-center justify-between flex-shrink-0 pt-1">
+ {onSearchQueryChange && enableSearch && (
+ <Tooltip content="Search">
+ <Button
+ variant="text"
+ size="xs"
+ className="mb-0"
+ onClick={() => setIsSearchEnabled(!isSearchEnabled)}
+ >
+ <SearchIcon className="w-4 h-4 text-muted-foreground" />
+ </Button>
+ </Tooltip>
+ )}
+ {pagination ? (
+ <DataTablePagination
+ selection={selection}
+ onSelectAllRowsChange={
+ onRowSelectionChange
+ ? (value: boolean) => {
+ if (value) {
+ const allKeys = Array.from(
+ { length: table.getRowModel().rows.length },
+ (_, i) => [i, true] as const,
+ );
+ onRowSelectionChange(Object.fromEntries(allKeys));
+ } else {
+ onRowSelectionChange({});
+ }
+ }
+ : undefined
+ }
+ table={table}
+ />
+ ) : (
+ <div />
+ )}
+ {downloadAs && <DownloadAs downloadAs={downloadAs} />}
+ </div>
+ );
+};
diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsx
index f011cab1a6..1c0953c6c2 100644
--- a/frontend/src/components/data-table/data-table.tsx
+++ b/frontend/src/components/data-table/data-table.tsx
@@ -1,47 +1,30 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import React, { memo, useEffect, useState } from "react";
+import React, { memo } from "react";
import {
- type Column,
type ColumnDef,
type ColumnFiltersState,
ColumnPinning,
- type ColumnPinningState,
- type OnChangeFn,
- type PaginationState,
- type Row,
- type RowSelectionState,
- type SortingState,
- type Table as TanStackTable,
- flexRender,
getCoreRowModel,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
+ type OnChangeFn,
+ type PaginationState,
+ type RowSelectionState,
+ type SortingState,
useReactTable,
} from "@tanstack/react-table";
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@/components/ui/table";
-import { DataTablePagination } from "./pagination";
-import { type DownloadActionProps, DownloadAs } from "./download-actions";
+import { Table } from "@/components/ui/table";
+import type { DownloadActionProps } from "./download-actions";
import { cn } from "@/utils/cn";
-import { SearchIcon } from "lucide-react";
-import { Button } from "../ui/button";
-import { useDebounce } from "@uidotdev/usehooks";
-import useEvent from "react-use-event-hook";
-import { Tooltip } from "../ui/tooltip";
-import { Spinner } from "../icons/spinner";
import { FilterPills } from "./filter-pills";
-import { ColumnWrappingFeature } from "./column-wrapping/feature";
+import { useColumnPinning } from "./hooks/useColumnPinning";
+import { renderTableHeader, renderTableBody } from "./renderers";
+import { SearchBar } from "./SearchBar";
+import { TableActions } from "./TableActions";
import { ColumnFormattingFeature } from "./column-formatting/feature";
-import { useDeepCompareMemoize } from "@/hooks/useDeepCompareMemoize";
-import { SELECT_COLUMN_ID } from "./types";
+import { ColumnWrappingFeature } from "./column-wrapping/feature";
interface DataTableProps<TData> extends Partial<DownloadActionProps> {
wrapperClassName?: string;
@@ -103,12 +86,11 @@ const DataTableInternal = <TData,>({
freezeColumnsRight,
}: DataTableProps<TData>) => {
const [isSearchEnabled, setIsSearchEnabled] = React.useState<boolean>(false);
- const [columnPinning, setColumnPinning] = React.useState<ColumnPinningState>({
- left: freezeColumnsLeft
- ? [SELECT_COLUMN_ID, ...freezeColumnsLeft]
- : [SELECT_COLUMN_ID],
- right: freezeColumnsRight,
- });
+
+ const { columnPinning, setColumnPinning } = useColumnPinning(
+ freezeColumnsLeft,
+ freezeColumnsRight,
+ );
const table = useReactTable<TData>({
_features: [ColumnPinning, ColumnWrappingFeature, ColumnFormattingFeature],
@@ -162,138 +144,6 @@ const DataTableInternal = <TData,>({
onColumnPinningChange: setColumnPinning,
});
- useEffect(() => {
- setColumnPinning({
- left:
- !freezeColumnsLeft || freezeColumnsLeft?.includes(SELECT_COLUMN_ID)
- ? freezeColumnsLeft
- : [SELECT_COLUMN_ID, ...freezeColumnsLeft],
- right: freezeColumnsRight,
- });
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [useDeepCompareMemoize([freezeColumnsLeft, freezeColumnsRight])]);
-
- const getPinningStyles = (
- column: Column<TData>,
- ): React.HTMLAttributes<HTMLElement> => {
- const isPinned = column.getIsPinned();
- const isLastLeftPinnedColumn =
- isPinned === "left" && column.getIsLastColumn("left");
- const isFirstRightPinnedColumn =
- isPinned === "right" && column.getIsFirstColumn("right");
-
- return {
- className: cn(isPinned && "bg-background", "shadow-r z-10"),
- style: {
- boxShadow:
- isLastLeftPinnedColumn && column.id !== "__select__"
- ? "-4px 0 4px -4px var(--slate-8) inset"
- : isFirstRightPinnedColumn
- ? "4px 0 4px -4px var(--slate-8) inset"
- : undefined,
- left: isPinned === "left" ? `${column.getStart("left")}px` : undefined,
- right:
- isPinned === "right" ? `${column.getAfter("right")}px` : undefined,
- opacity: 1,
- position: isPinned ? "sticky" : "relative",
- zIndex: isPinned ? 1 : 0,
- width: column.getSize(),
- },
- };
- };
-
- // Update column sizes in table state for column pinning offsets
- // https://github.com/TanStack/table/discussions/3947#discussioncomment-9564867
- const columnSizingHandler = (
- thead: HTMLTableCellElement | null,
- table: TanStackTable<TData>,
- column: Column<TData>,
- ) => {
- if (!thead) {
- return;
- }
- if (
- table.getState().columnSizing[column.id] ===
- thead.getBoundingClientRect().width
- ) {
- return;
- }
-
- table.setColumnSizing((prevSizes) => ({
- ...prevSizes,
- [column.id]: thead.getBoundingClientRect().width,
- }));
- };
-
- const renderHeader = (position: "left" | "center" | "right") => {
- // Hide header if no results
- if (!table.getRowModel().rows?.length) {
- return;
- }
-
- const headerGroups =
- position === "left"
- ? table.getLeftHeaderGroups()
- : position === "right"
- ? table.getRightHeaderGroups()
- : table.getCenterHeaderGroups();
-
- // whitespace-pre so that strings with different whitespace look
- // different
- return headerGroups.map((headerGroup) =>
- headerGroup.headers.map((header) => {
- const { className, style } = getPinningStyles(header.column);
- return (
- <TableHead
- key={header.id}
- className={cn(
- "h-auto min-h-10 whitespace-pre align-top",
- className,
- )}
- style={style}
- ref={(thead) => columnSizingHandler(thead, table, header.column)}
- >
- {header.isPlaceholder
- ? null
- : flexRender(header.column.columnDef.header, header.getContext())}
- </TableHead>
- );
- }),
- );
- };
-
- const renderCells = (
- row: Row<TData>,
- position: "left" | "center" | "right",
- ) => {
- const cells =
- position === "left"
- ? row.getLeftVisibleCells()
- : position === "right"
- ? row.getRightVisibleCells()
- : row.getCenterVisibleCells();
-
- return cells.map((cell) => {
- const { className, style } = getPinningStyles(cell.column);
- return (
- <TableCell
- key={cell.id}
- className={cn(
- "whitespace-pre truncate max-w-[300px]",
- cell.column.getColumnWrapping &&
- cell.column.getColumnWrapping() === "wrap" &&
- "whitespace-pre-wrap min-w-[200px]",
- className,
- )}
- style={style}
- title={String(cell.getValue())}
- >
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
- </TableCell>
- );
- });
- };
-
return (
<div className={cn(wrapperClassName, "flex flex-col space-y-1")}>
<FilterPills filters={filters} table={table} />
@@ -308,134 +158,21 @@ const DataTableInternal = <TData,>({
/>
)}
<Table>
- <TableHeader>
- {renderHeader("left")}
- {renderHeader("center")}
- {renderHeader("right")}
- </TableHeader>
- <TableBody>
- {table.getRowModel().rows?.length ? (
- table.getRowModel().rows.map((row) => (
- <TableRow
- key={row.id}
- data-state={row.getIsSelected() && "selected"}
- onClick={() => {
- // If we have any row selected, make the row
- // toggle selection on click
- if (table.getIsSomeRowsSelected()) {
- row.toggleSelected();
- }
- }}
- >
- {renderCells(row, "left")}
- {renderCells(row, "center")}
- {renderCells(row, "right")}
- </TableRow>
- ))
- ) : (
- <TableRow>
- <TableCell
- colSpan={columns.length}
- className="h-24 text-center"
- >
- No results.
- </TableCell>
- </TableRow>
- )}
- </TableBody>
+ {renderTableHeader(table)}
+ {renderTableBody(table, columns)}
</Table>
</div>
- <div className="flex items-center justify-between flex-shrink-0 pt-1">
- {onSearchQueryChange && enableSearch && (
- <Tooltip content="Search">
- <Button
- variant="text"
- size="xs"
- className="mb-0"
- onClick={() => setIsSearchEnabled(!isSearchEnabled)}
- >
- <SearchIcon className="w-4 h-4 text-muted-foreground" />
- </Button>
- </Tooltip>
- )}
- {pagination ? (
- <DataTablePagination
- selection={selection}
- onSelectAllRowsChange={
- onRowSelectionChange
- ? (value) => {
- if (value) {
- const allKeys = Array.from(
- { length: table.getRowCount() },
- (_, i) => [i, true] as const,
- );
- onRowSelectionChange(Object.fromEntries(allKeys));
- } else {
- onRowSelectionChange({});
- }
- }
- : undefined
- }
- table={table}
- />
- ) : (
- <div />
- )}
- {downloadAs && <DownloadAs downloadAs={downloadAs} />}
- </div>
- </div>
- );
-};
-
-const SearchBar = (props: {
- hidden: boolean;
- value: string;
- handleSearch: (query: string) => void;
- onHide: () => void;
- reloading?: boolean;
-}) => {
- const { reloading, value, handleSearch, hidden, onHide } = props;
- const [internalValue, setInternalValue] = useState(value);
- const debouncedSearch = useDebounce(internalValue, 500);
- const onSearch = useEvent(handleSearch);
- const ref = React.useRef<HTMLInputElement>(null);
-
- useEffect(() => {
- onSearch(debouncedSearch);
- }, [debouncedSearch, onSearch]);
-
- useEffect(() => {
- if (hidden) {
- // Closing, reset
- setInternalValue("");
- } else {
- // Opening, focus
- ref.current?.focus();
- }
- }, [hidden]);
-
- return (
- <div
- className={cn(
- "flex items-center space-x-2 h-8 px-2 border-b transition-all overflow-hidden duration-300 opacity-100",
- hidden && "h-0 border-none opacity-0",
- )}
- >
- <SearchIcon className="w-4 h-4 text-muted-foreground" />
- <input
- type="text"
- ref={ref}
- className="w-full h-full border-none bg-transparent focus:outline-none text-sm"
- value={internalValue}
- onKeyDown={(e) => {
- if (e.key === "Escape") {
- onHide();
- }
- }}
- onChange={(e) => setInternalValue(e.target.value)}
- placeholder="Search"
+ <TableActions
+ enableSearch={enableSearch}
+ onSearchQueryChange={onSearchQueryChange}
+ isSearchEnabled={isSearchEnabled}
+ setIsSearchEnabled={setIsSearchEnabled}
+ pagination={pagination}
+ selection={selection}
+ onRowSelectionChange={onRowSelectionChange}
+ table={table}
+ downloadAs={downloadAs}
/>
- {reloading && <Spinner size="small" />}
</div>
);
};
diff --git a/frontend/src/components/data-table/hooks/useColumnPinning.ts b/frontend/src/components/data-table/hooks/useColumnPinning.ts
new file mode 100644
index 0000000000..d7056e7f97
--- /dev/null
+++ b/frontend/src/components/data-table/hooks/useColumnPinning.ts
@@ -0,0 +1,41 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import React from "react";
+import { SELECT_COLUMN_ID } from "../types";
+import type { ColumnPinningState } from "@tanstack/react-table";
+
+interface UseColumnPinningResult {
+ columnPinning: ColumnPinningState;
+ setColumnPinning: React.Dispatch<React.SetStateAction<ColumnPinningState>>;
+}
+
+export function useColumnPinning(
+ freezeColumnsLeft?: string[],
+ freezeColumnsRight?: string[],
+): UseColumnPinningResult {
+ const [columnPinning, setColumnPinning] = React.useState<ColumnPinningState>({
+ left: freezeColumnsLeft
+ ? [SELECT_COLUMN_ID, ...freezeColumnsLeft]
+ : [SELECT_COLUMN_ID],
+ right: freezeColumnsRight,
+ });
+
+ const setColumnPinningWithFreeze = React.useCallback(
+ (newState: React.SetStateAction<ColumnPinningState>) => {
+ setColumnPinning((prevState) => {
+ const updatedState =
+ typeof newState === "function" ? newState(prevState) : newState;
+ return {
+ left:
+ !freezeColumnsLeft || freezeColumnsLeft?.includes(SELECT_COLUMN_ID)
+ ? freezeColumnsLeft
+ : [SELECT_COLUMN_ID, ...(freezeColumnsLeft || [])],
+ right: freezeColumnsRight,
+ ...updatedState,
+ };
+ });
+ },
+ [freezeColumnsLeft, freezeColumnsRight],
+ );
+
+ return { columnPinning, setColumnPinning: setColumnPinningWithFreeze };
+}
diff --git a/frontend/src/components/data-table/renderers.tsx b/frontend/src/components/data-table/renderers.tsx
new file mode 100644
index 0000000000..c889b3efff
--- /dev/null
+++ b/frontend/src/components/data-table/renderers.tsx
@@ -0,0 +1,164 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import {
+ TableHeader,
+ TableHead,
+ TableBody,
+ TableRow,
+ TableCell,
+} from "@/components/ui/table";
+import {
+ flexRender,
+ type Table,
+ type ColumnDef,
+ type Row,
+ type Column,
+ type Table as TanStackTable,
+ type HeaderGroup,
+ type Cell,
+} from "@tanstack/react-table";
+import { cn } from "@/utils/cn";
+
+export function renderTableHeader<TData>(
+ table: Table<TData>,
+): JSX.Element | null {
+ if (!table.getRowModel().rows?.length) {
+ return null;
+ }
+
+ const renderHeaderGroup = (headerGroups: Array<HeaderGroup<TData>>) => {
+ return headerGroups.map((headerGroup) =>
+ headerGroup.headers.map((header) => {
+ const { className, style } = getPinningStyles(header.column);
+ return (
+ <TableHead
+ key={header.id}
+ className={cn(
+ "h-auto min-h-10 whitespace-pre align-top",
+ className,
+ )}
+ style={style}
+ ref={(thead) => columnSizingHandler(thead, table, header.column)}
+ >
+ {header.isPlaceholder
+ ? null
+ : flexRender(header.column.columnDef.header, header.getContext())}
+ </TableHead>
+ );
+ }),
+ );
+ };
+
+ return (
+ <TableHeader>
+ {renderHeaderGroup(table.getLeftHeaderGroups())}
+ {renderHeaderGroup(table.getCenterHeaderGroups())}
+ {renderHeaderGroup(table.getRightHeaderGroups())}
+ </TableHeader>
+ );
+}
+
+export function renderTableBody<TData>(
+ table: Table<TData>,
+ columns: Array<ColumnDef<TData>>,
+): JSX.Element {
+ const renderCells = (row: Row<TData>, cells: Array<Cell<TData, unknown>>) => {
+ return cells.map((cell) => {
+ const { className, style } = getPinningStyles(cell.column);
+ return (
+ <TableCell
+ key={cell.id}
+ className={cn(
+ "whitespace-pre truncate max-w-[300px]",
+ cell.column.getColumnWrapping &&
+ cell.column.getColumnWrapping() === "wrap" &&
+ "whitespace-pre-wrap min-w-[200px]",
+ className,
+ )}
+ style={style}
+ title={String(cell.getValue())}
+ >
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
+ </TableCell>
+ );
+ });
+ };
+
+ return (
+ <TableBody>
+ {table.getRowModel().rows?.length ? (
+ table.getRowModel().rows.map((row) => (
+ <TableRow
+ key={row.id}
+ data-state={row.getIsSelected() && "selected"}
+ onClick={() => {
+ if (table.getIsSomeRowsSelected()) {
+ row.toggleSelected();
+ }
+ }}
+ >
+ {renderCells(row, row.getLeftVisibleCells())}
+ {renderCells(row, row.getCenterVisibleCells())}
+ {renderCells(row, row.getRightVisibleCells())}
+ </TableRow>
+ ))
+ ) : (
+ <TableRow>
+ <TableCell colSpan={columns.length} className="h-24 text-center">
+ No results.
+ </TableCell>
+ </TableRow>
+ )}
+ </TableBody>
+ );
+}
+
+function getPinningStyles<TData>(
+ column: Column<TData>,
+): React.HTMLAttributes<HTMLElement> {
+ const isPinned = column.getIsPinned();
+ const isLastLeftPinnedColumn =
+ isPinned === "left" && column.getIsLastColumn("left");
+ const isFirstRightPinnedColumn =
+ isPinned === "right" && column.getIsFirstColumn("right");
+
+ return {
+ className: cn(isPinned && "bg-background", "shadow-r z-10"),
+ style: {
+ boxShadow:
+ isLastLeftPinnedColumn && column.id !== "__select__"
+ ? "-4px 0 4px -4px var(--slate-8) inset"
+ : isFirstRightPinnedColumn
+ ? "4px 0 4px -4px var(--slate-8) inset"
+ : undefined,
+ left: isPinned === "left" ? `${column.getStart("left")}px` : undefined,
+ right: isPinned === "right" ? `${column.getAfter("right")}px` : undefined,
+ opacity: 1,
+ position: isPinned ? "sticky" : "relative",
+ zIndex: isPinned ? 1 : 0,
+ width: column.getSize(),
+ },
+ };
+}
+
+// Update column sizes in table state for column pinning offsets
+// https://github.com/TanStack/table/discussions/3947#discussioncomment-9564867
+function columnSizingHandler<TData>(
+ thead: HTMLTableCellElement | null,
+ table: TanStackTable<TData>,
+ column: Column<TData>,
+) {
+ if (!thead) {
+ return;
+ }
+ if (
+ table.getState().columnSizing[column.id] ===
+ thead.getBoundingClientRect().width
+ ) {
+ return;
+ }
+
+ table.setColumnSizing((prevSizes) => ({
+ ...prevSizes,
+ [column.id]: thead.getBoundingClientRect().width,
+ }));
+}