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: sortable variable table (#516)

Myles Scolnick0b479c81fe46
diff --git a/frontend/src/components/data-table/column-header.tsx b/frontend/src/components/data-table/column-header.tsx
index 02a9729145..b3c219ad2f 100644
--- a/frontend/src/components/data-table/column-header.tsx
+++ b/frontend/src/components/data-table/column-header.tsx
@@ -21,16 +21,16 @@ import {
interface DataTableColumnHeaderProps<TData, TValue>
extends React.HTMLAttributes<HTMLDivElement> {
column: Column<TData, TValue>;
- title: string;
+ header: React.ReactNode;
}
export const DataTableColumnHeader = <TData, TValue>({
column,
- title,
+ header,
className,
}: DataTableColumnHeaderProps<TData, TValue>) => {
if (!column.getCanSort()) {
- return <div className={cn(className)}>{title}</div>;
+ return <div className={cn(className)}>{header}</div>;
}
const sortFn = column.getSortingFn();
@@ -40,14 +40,18 @@ export const DataTableColumnHeader = <TData, TValue>({
sortFn === sortingFns.basic ? ArrowDown10Icon : ArrowDownWideNarrowIcon;
return (
- <div className={cn("flex items-center space-x-2", className)}>
- <span>{title}</span>
+ <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"
size="xs"
- className="ml-3 h-5 data-[state=open]:bg-accent m-0 p-1"
+ className={cn(
+ "ml-3 h-5 data-[state=open]:bg-accent m-0 p-1",
+ !column.getIsSorted() &&
+ "invisible group-hover:visible data-[state=open]:visible"
+ )}
>
{column.getIsSorted() === "desc" ? (
<DescIcon className="h-3 w-3" />
diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsx
index 9184cc83b8..af17bebc19 100644
--- a/frontend/src/components/data-table/columns.tsx
+++ b/frontend/src/components/data-table/columns.tsx
@@ -70,7 +70,7 @@ export function generateColumns<T>(
return (row as any)[info.key];
},
header: ({ column }) => {
- return <DataTableColumnHeader title={info.key} column={column} />;
+ return <DataTableColumnHeader header={info.key} column={column} />;
},
cell: ({ renderValue, getValue }) => {
const value = getValue();
@@ -130,7 +130,7 @@ export function generateIndexColumns<T>(
return keys[idx];
},
header: ({ column }) => {
- return <DataTableColumnHeader title={title} column={column} />;
+ return <DataTableColumnHeader header={title} column={column} />;
},
cell: ({ renderValue }) => {
return <b>{String(renderValue())}</b>;
diff --git a/frontend/src/components/variables/variables-table.tsx b/frontend/src/components/variables/variables-table.tsx
index 7b4322caf5..374e41ba7d 100644
--- a/frontend/src/components/variables/variables-table.tsx
+++ b/frontend/src/components/variables/variables-table.tsx
@@ -1,5 +1,5 @@
/* Copyright 2023 Marimo. All rights reserved. */
-import React, { memo } from "react";
+import React, { memo, useMemo } from "react";
import {
TableHeader,
TableRow,
@@ -8,13 +8,24 @@ import {
TableCell,
Table,
} from "../ui/table";
-import { Variables } from "@/core/variables/types";
+import { Variable, Variables } from "@/core/variables/types";
import { CellId } from "@/core/cells/ids";
import { CellLink } from "@/components/editor/links/cell-link";
import { cn } from "@/utils/cn";
import { SquareEqualIcon, WorkflowIcon } from "lucide-react";
import { Badge } from "../ui/badge";
import { toast } from "../ui/use-toast";
+import {
+ useReactTable,
+ getCoreRowModel,
+ flexRender,
+ ColumnDef,
+ SortingState,
+ getSortedRowModel,
+ ColumnSort,
+} from "@tanstack/react-table";
+import { DataTableColumnHeader } from "../data-table/column-header";
+import { sortBy } from "lodash-es";
interface Props {
className?: string;
@@ -25,124 +36,226 @@ interface Props {
variables: Variables;
}
+/* Column Definitions */
+
+function columnDefOf<T>(columnDef: ColumnDef<Variable, T>) {
+ return columnDef;
+}
+
+const ColumnIds = {
+ name: "name",
+ type: "type-value",
+ defs: "defs-refs",
+};
+
+const COLUMNS = [
+ columnDefOf({
+ id: ColumnIds.name,
+ accessorFn: (v) => [v.name, v.declaredBy] as const,
+ enableSorting: true,
+ sortingFn: "alphanumeric",
+ header: ({ column }) => (
+ <DataTableColumnHeader header={"Name"} column={column} />
+ ),
+ cell: ({ getValue }) => {
+ const [name, declaredBy] = getValue();
+ return (
+ <div className="max-w-[130px]">
+ <Badge
+ title={name}
+ variant={declaredBy.length > 1 ? "destructive" : "outline"}
+ className="rounded-sm text-ellipsis block overflow-hidden max-w-fit cursor-pointer font-medium"
+ onClick={() => {
+ navigator.clipboard.writeText(name);
+ toast({ title: "Copied to clipboard" });
+ }}
+ >
+ {name}
+ </Badge>
+ </div>
+ );
+ },
+ }),
+ columnDefOf({
+ id: ColumnIds.type,
+ accessorFn: (v) => [v.dataType, v.value] as const,
+ enableSorting: true,
+ sortingFn: "alphanumeric",
+ header: ({ column }) => (
+ <DataTableColumnHeader
+ header={
+ <div className="flex flex-col gap-1">
+ <span>Type</span>
+ <span>Value</span>
+ </div>
+ }
+ column={column}
+ />
+ ),
+ cell: ({ getValue }) => {
+ const [dataType, value] = getValue();
+ return (
+ <div className="max-w-[150px]">
+ <div className="text-ellipsis overflow-hidden whitespace-nowrap text-muted-foreground font-mono text-xs">
+ {dataType}
+ </div>
+ <div
+ className="text-ellipsis overflow-hidden whitespace-nowrap"
+ title={value}
+ >
+ {value}
+ </div>
+ </div>
+ );
+ },
+ }),
+ columnDefOf({
+ id: ColumnIds.defs,
+ accessorFn: (v) => [v.declaredBy, v.usedBy] as const,
+ enableSorting: true,
+ sortingFn: "basic",
+ header: ({ column }) => (
+ <DataTableColumnHeader
+ header={
+ <div className="flex flex-col gap-1">
+ <span>Declared By</span>
+ <span>Used By</span>
+ </div>
+ }
+ column={column}
+ />
+ ),
+ cell: ({ getValue }) => {
+ const [declaredBy, usedBy] = getValue();
+
+ return (
+ <div className="flex flex-col gap-1 py-1">
+ <div className="flex flex-row overflow-auto gap-2 items-center">
+ <span title="Declared by">
+ <SquareEqualIcon className="w-3.5 h-3.5 text-muted-foreground" />
+ </span>
+
+ {declaredBy.length === 1 ? (
+ <CellLink variant="focus" cellId={declaredBy[0]} />
+ ) : (
+ <div className="text-destructive flex flex-row gap-2">
+ {declaredBy.slice(0, 3).map((cellId, idx) => (
+ <span className="flex" key={cellId}>
+ <CellLink
+ variant="focus"
+ key={cellId}
+ cellId={cellId}
+ className="whitespace-nowrap text-destructive"
+ />
+ {idx < declaredBy.length - 1 && ", "}
+ </span>
+ ))}
+ </div>
+ )}
+ </div>
+ <div className="flex flex-row overflow-auto gap-2 items-baseline">
+ <span title="Used by">
+ <WorkflowIcon className="w-3.5 h-3.5 text-muted-foreground" />
+ </span>
+
+ {usedBy.slice(0, 3).map((cellId, idx) => (
+ <span className="flex" key={cellId}>
+ <CellLink
+ variant="focus"
+ key={cellId}
+ cellId={cellId}
+ className="whitespace-nowrap"
+ />
+ {idx < usedBy.length - 1 && ", "}
+ </span>
+ ))}
+ {usedBy.length > 3 && (
+ <div className="whitespace-nowrap text-muted-foreground text-xs">
+ +{usedBy.length - 3} more
+ </div>
+ )}
+ </div>
+ </div>
+ );
+ },
+ }),
+];
+
+/**
+ * Sort the variables by the specified column sort
+ * Defaults to the order they are defined in the notebook
+ */
+function sortData(
+ variables: Variable[],
+ sort: ColumnSort | undefined,
+ cellIdToIndex: Map<CellId, number>
+) {
+ // Default to sort by the cell that defined it
+ if (!sort) {
+ sort = { id: ColumnIds.defs, desc: false };
+ }
+
+ let sortedVariables: Variable[] = [];
+ switch (sort.id) {
+ case ColumnIds.name:
+ sortedVariables = sortBy(variables, (v) => v.name);
+ break;
+ case ColumnIds.type:
+ sortedVariables = sortBy(variables, (v) => v.dataType);
+ break;
+ case ColumnIds.defs:
+ sortedVariables = sortBy(variables, (v) =>
+ cellIdToIndex.get(v.declaredBy[0])
+ );
+ break;
+ }
+
+ return sort.desc ? sortedVariables.reverse() : sortedVariables;
+}
+
export const VariableTable: React.FC<Props> = memo(
({ className, cellIds, variables }) => {
- const cellIdToIndex = new Map<CellId, number>();
- cellIds.forEach((id, index) => cellIdToIndex.set(id, index));
+ const [sorting, setSorting] = React.useState<SortingState>([]);
- const sortedVariables = Object.values(variables).sort((a, b) => {
- const aIndex = cellIdToIndex.get(a.declaredBy[0]);
- const bIndex = cellIdToIndex.get(b.declaredBy[0]);
- if (aIndex === undefined || bIndex === undefined) {
- return 0;
- }
- return aIndex - bIndex;
+ const sortedVariables = useMemo(() => {
+ const cellIdToIndex = new Map<CellId, number>();
+ cellIds.forEach((id, index) => cellIdToIndex.set(id, index));
+ return sortData(Object.values(variables), sorting[0], cellIdToIndex);
+ }, [variables, sorting, cellIds]);
+
+ const table = useReactTable({
+ data: sortedVariables,
+ columns: COLUMNS,
+ getCoreRowModel: getCoreRowModel(),
+ // sorting
+ manualSorting: true,
+ onSortingChange: setSorting,
+ getSortedRowModel: getSortedRowModel(),
+ state: { sorting },
});
return (
<Table className={cn("w-full overflow-hidden text-sm flex-1", className)}>
<TableHeader>
- <TableRow className="whitespace-nowrap text-xs hover:bg-accent">
- <TableHead>Name</TableHead>
- <TableHead>
- <div className="flex flex-col gap-1">
- <span>Type</span>
- <span>Value</span>
- </div>
- </TableHead>
- <TableHead>
- <div className="flex flex-col gap-1">
- <span>Declared By</span>
- <span>Used By</span>
- </div>
- </TableHead>
+ <TableRow className="whitespace-nowrap text-xs">
+ {table.getFlatHeaders().map((header) => (
+ <TableHead key={header.id}>
+ {flexRender(
+ header.column.columnDef.header,
+ header.getContext()
+ )}
+ </TableHead>
+ ))}
</TableRow>
</TableHeader>
<TableBody>
- {sortedVariables.map((variable) => (
- <TableRow key={variable.name} className="hover:bg-accent">
- <TableCell
- className="font-medium max-w-[130px]"
- title={variable.name}
- >
- <div>
- <Badge
- variant={
- variable.declaredBy.length > 1 ? "destructive" : "outline"
- }
- className="rounded-sm text-ellipsis block overflow-hidden max-w-fit cursor-pointer"
- onClick={() => {
- navigator.clipboard.writeText(variable.name);
- toast({ title: "Copied to clipboard" });
- }}
- >
- {variable.name}
- </Badge>
- </div>
- </TableCell>
- <TableCell className="max-w-[150px]">
- <div className="text-ellipsis overflow-hidden whitespace-nowrap text-muted-foreground font-mono text-xs">
- {variable.dataType}
- </div>
- <div
- className="text-ellipsis overflow-hidden whitespace-nowrap"
- title={variable.value}
- >
- {variable.value}
- </div>
- </TableCell>
- <TableCell className="py-1">
- <div className="flex flex-col gap-1">
- <div className="flex flex-row overflow-auto gap-2 items-center">
- <span title="Declared by">
- <SquareEqualIcon className="w-3.5 h-3.5 text-muted-foreground" />
- </span>
-
- {variable.declaredBy.length === 1 ? (
- <CellLink
- variant="focus"
- cellId={variable.declaredBy[0]}
- />
- ) : (
- <div className="text-destructive flex flex-row gap-2">
- {variable.declaredBy.slice(0, 3).map((cellId, idx) => (
- <span className="flex" key={cellId}>
- <CellLink
- variant="focus"
- key={cellId}
- cellId={cellId}
- className="whitespace-nowrap text-destructive"
- />
- {idx < variable.declaredBy.length - 1 && ", "}
- </span>
- ))}
- </div>
- )}
- </div>
- <div className="flex flex-row overflow-auto gap-2 items-baseline">
- <span title="Used by">
- <WorkflowIcon className="w-3.5 h-3.5 text-muted-foreground" />
- </span>
-
- {variable.usedBy.slice(0, 3).map((cellId, idx) => (
- <span className="flex" key={cellId}>
- <CellLink
- variant="focus"
- key={cellId}
- cellId={cellId}
- className="whitespace-nowrap"
- />
- {idx < variable.usedBy.length - 1 && ", "}
- </span>
- ))}
- {variable.usedBy.length > 3 && (
- <div className="whitespace-nowrap text-muted-foreground text-xs">
- +{variable.usedBy.length - 3} more
- </div>
- )}
- </div>
- </div>
- </TableCell>
+ {table.getRowModel().rows.map((row) => (
+ <TableRow key={row.id} className="hover:bg-accent">
+ {row.getVisibleCells().map((cell) => (
+ <TableCell key={cell.id}>
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
+ </TableCell>
+ ))}
</TableRow>
))}
</TableBody>