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: row expanded view for table data (#4787)

Shahmir Varqha40014339393f
diff --git a/frontend/src/components/data-table/TableActions.tsx b/frontend/src/components/data-table/TableActions.tsx
index 859ff4b3e4..74c774970c 100644
--- a/frontend/src/components/data-table/TableActions.tsx
+++ b/frontend/src/components/data-table/TableActions.tsx
@@ -4,13 +4,14 @@
import React from "react";
import { Tooltip } from "../ui/tooltip";
import { Button } from "../ui/button";
-import { SearchIcon, ChartBarIcon } from "lucide-react";
+import { SearchIcon, ChartBarIcon, PanelRightIcon } from "lucide-react";
import { DataTablePagination } from "./pagination";
import { DownloadAs, type DownloadActionProps } from "./download-actions";
import type { Table, RowSelectionState } from "@tanstack/react-table";
import type { DataTableSelection } from "./types";
import type { GetRowIds } from "@/plugins/impl/DataTablePlugin";
import { toast } from "../ui/use-toast";
+import { cn } from "@/utils/cn";
interface TableActionsProps<TData> {
enableSearch: boolean;
@@ -26,6 +27,8 @@ interface TableActionsProps<TData> {
getRowIds?: GetRowIds;
toggleDisplayHeader?: () => void;
chartsFeatureEnabled?: boolean;
+ toggleSelectionPanel?: () => void;
+ isSelectionPanelOpen?: boolean;
}
export const TableActions = <TData,>({
@@ -42,6 +45,8 @@ export const TableActions = <TData,>({
getRowIds,
toggleDisplayHeader,
chartsFeatureEnabled,
+ toggleSelectionPanel,
+ isSelectionPanelOpen,
}: TableActionsProps<TData>) => {
const handleSelectAllRows = (value: boolean) => {
if (!onRowSelectionChange) {
@@ -88,7 +93,7 @@ export const TableActions = <TData,>({
};
return (
- <div className="flex items-center justify-between flex-shrink-0 pt-1">
+ <div className="flex items-center flex-shrink-0 pt-1">
{onSearchQueryChange && enableSearch && (
<Tooltip content="Search">
<Button
@@ -106,24 +111,36 @@ export const TableActions = <TData,>({
<Button
variant="text"
size="xs"
- className="mb-0 mr-auto"
+ className="mb-0"
onClick={toggleDisplayHeader}
>
<ChartBarIcon className="w-4 h-4 text-muted-foreground" />
</Button>
</Tooltip>
)}
- {pagination ? (
+ {toggleSelectionPanel && (
+ <Tooltip content="Toggle selection panel">
+ <Button variant="text" size="xs" onClick={toggleSelectionPanel}>
+ <PanelRightIcon
+ className={cn(
+ "w-4 h-4 text-muted-foreground",
+ isSelectionPanelOpen && "text-primary",
+ )}
+ />
+ </Button>
+ </Tooltip>
+ )}
+ {pagination && (
<DataTablePagination
totalColumns={totalColumns}
selection={selection}
onSelectAllRowsChange={handleSelectAllRows}
table={table}
/>
- ) : (
- <div />
)}
- {downloadAs && <DownloadAs downloadAs={downloadAs} />}
+ <div className="ml-auto">
+ {downloadAs && <DownloadAs downloadAs={downloadAs} />}
+ </div>
</div>
);
};
diff --git a/frontend/src/components/data-table/__tests__/data-table.test.tsx b/frontend/src/components/data-table/__tests__/data-table.test.tsx
index 0a21eb0208..8e7e3afa56 100644
--- a/frontend/src/components/data-table/__tests__/data-table.test.tsx
+++ b/frontend/src/components/data-table/__tests__/data-table.test.tsx
@@ -5,6 +5,7 @@ import { describe, expect, it } from "vitest";
import { vi } from "vitest";
import type { ColumnDef } from "@tanstack/react-table";
import type { RowSelectionState } from "@tanstack/react-table";
+import { TooltipProvider } from "@/components/ui/tooltip";
interface TestData {
id: number;
@@ -36,13 +37,21 @@ describe("DataTable", () => {
onRowSelectionChange: mockOnRowSelectionChange,
};
- const { rerender } = render(<DataTable {...commonProps} />);
+ const { rerender } = render(
+ <TooltipProvider>
+ <DataTable {...commonProps} />
+ </TooltipProvider>,
+ );
// Verify initial selection is not cleared
expect(mockOnRowSelectionChange).not.toHaveBeenCalledWith({});
// Simulate remount (as would happen in accordion toggle)
- rerender(<DataTable {...commonProps} />);
+ rerender(
+ <TooltipProvider>
+ <DataTable {...commonProps} />
+ </TooltipProvider>,
+ );
// Verify selection is still not cleared after remount
expect(mockOnRowSelectionChange).not.toHaveBeenCalledWith({});
diff --git a/frontend/src/components/data-table/cell-selection/feature.ts b/frontend/src/components/data-table/cell-selection/feature.ts
index 3ba1e412b5..e95d8b0ae9 100644
--- a/frontend/src/components/data-table/cell-selection/feature.ts
+++ b/frontend/src/components/data-table/cell-selection/feature.ts
@@ -19,13 +19,10 @@ import type {
CellSelectionState,
CellSelectionTableState,
} from "./types";
-import { INDEX_COLUMN_NAME } from "../types";
+import { getStableRowId } from "../utils";
function getRowId<TData>(row: Row<TData>): string {
- if (row && typeof row === "object" && INDEX_COLUMN_NAME in row) {
- return String(row[INDEX_COLUMN_NAME]);
- }
- return row.id;
+ return getStableRowId(row) ?? row.id;
}
export const CellSelectionFeature: TableFeature = {
diff --git a/frontend/src/components/data-table/cell-styling/feature.ts b/frontend/src/components/data-table/cell-styling/feature.ts
index 6ac3272cc5..c4f0aed729 100644
--- a/frontend/src/components/data-table/cell-styling/feature.ts
+++ b/frontend/src/components/data-table/cell-styling/feature.ts
@@ -12,13 +12,10 @@ import type {
} from "@tanstack/react-table";
import type { CellStyleState, CellStylingTableState } from "./types";
-import { INDEX_COLUMN_NAME } from "../types";
+import { getStableRowId } from "../utils";
function getRowId<TData>(row: Row<TData>): string {
- if (row && typeof row === "object" && INDEX_COLUMN_NAME in row) {
- return String(row[INDEX_COLUMN_NAME]);
- }
- return row.id;
+ return getStableRowId(row) ?? row.id;
}
export const CellStylingFeature: TableFeature = {
diff --git a/frontend/src/components/data-table/chart-transforms/chart-transforms.tsx b/frontend/src/components/data-table/chart-transforms/chart-transforms.tsx
index 83c3e98173..ec1bf14f0e 100644
--- a/frontend/src/components/data-table/chart-transforms/chart-transforms.tsx
+++ b/frontend/src/components/data-table/chart-transforms/chart-transforms.tsx
@@ -1,6 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import React, { useState, useMemo, useRef, useEffect } from "react";
+import React, { useState, useMemo } from "react";
import { Button } from "@/components/ui/button";
import {
TableIcon,
@@ -17,7 +17,7 @@ import { ChartSchema } from "./chart-schemas";
import { Form } from "@/components/ui/form";
import { getDefaults } from "@/components/forms/form-utils";
import { useAtom } from "jotai";
-import { type CellId, HTMLCellId } from "@/core/cells/ids";
+import type { CellId } from "@/core/cells/ids";
import { capitalize } from "lodash-es";
import { type TabName, tabsStorageAtom, tabNumberAtom } from "./storage";
import type { FieldTypesWithExternalType } from "../types";
@@ -66,6 +66,7 @@ const DEFAULT_TAB_NAME = "table" as TabName;
const CHART_HEIGHT = 300;
export interface TablePanelProps {
+ cellId: CellId | null;
dataTable: JSX.Element;
displayHeader: boolean;
getDataUrl?: GetDataUrl;
@@ -73,36 +74,18 @@ export interface TablePanelProps {
}
export const TablePanel: React.FC<TablePanelProps> = ({
+ cellId,
dataTable,
getDataUrl,
fieldTypes,
displayHeader,
}) => {
- const containerRef = useRef<HTMLDivElement>(null);
- const [cellId, setCellId] = useState<CellId | null>(null);
-
const [tabsMap, saveTabsMap] = useAtom(tabsStorageAtom);
const tabs = cellId ? (tabsMap.get(cellId) ?? []) : [];
const [tabNum, setTabNum] = useAtom(tabNumberAtom);
const [selectedTab, setSelectedTab] = useState(DEFAULT_TAB_NAME);
- // Finds cellId in shadow / light DOM
- useEffect(() => {
- if (!containerRef.current) {
- return;
- }
-
- // If the element is in the light DOM, we can find it directly
- // Otherwise, we need to traverse up through shadow DOM boundaries
- const cellElement = HTMLCellId.findElementThroughShadowDOMs(
- containerRef.current,
- );
- if (cellElement) {
- setCellId(HTMLCellId.parse(cellElement.id));
- }
- }, [containerRef, displayHeader]);
-
if (!displayHeader || (tabs.length === 0 && !displayHeader)) {
return dataTable;
}
@@ -180,7 +163,7 @@ export const TablePanel: React.FC<TablePanelProps> = ({
};
return (
- <Tabs value={selectedTab} ref={containerRef} className="-mt-1">
+ <Tabs value={selectedTab} className="-mt-1">
<TabsList>
<TabsTrigger
className="text-xs"
diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsx
index 448b115711..31a8606084 100644
--- a/frontend/src/components/data-table/columns.tsx
+++ b/frontend/src/components/data-table/columns.tsx
@@ -1,7 +1,7 @@
/* Copyright 2024 Marimo. All rights reserved. */
"use no memo";
-import type { ColumnDef } from "@tanstack/react-table";
+import type { Column, ColumnDef } from "@tanstack/react-table";
import { DataTableColumnHeader } from "./column-header";
import { Checkbox } from "../ui/checkbox";
import { getMimeValues, MimeCell } from "./mime-cell";
@@ -206,8 +206,6 @@ export function generateColumns<T>({
return <b>{String(renderValue())}</b>;
}
- const value = getValue();
-
function selectCell() {
if (selection !== "single-cell" && selection !== "multi-cell") {
return;
@@ -230,95 +228,12 @@ export function generateColumns<T>({
isCellSelected,
);
- const format = column.getColumnFormatting?.();
-
- if (typeof value === "string") {
- const stringValue = format
- ? String(column.applyColumnFormatting(value))
- : String(renderValue());
-
- const parts = parseContent(stringValue);
- const hasMarkup = parts.some((part) => part.type !== "text");
- if (hasMarkup || stringValue.length < MAX_STRING_LENGTH) {
- return (
- <div onClick={selectCell} className={cellStyles}>
- <UrlDetector parts={parts} />
- </div>
- );
- }
-
- return (
- <PopoutColumn
- cellStyles={cellStyles}
- selectCell={selectCell}
- rawStringValue={stringValue}
- contentClassName="max-h-64 overflow-auto whitespace-pre-wrap break-words text-sm"
- buttonText="X"
- >
- <UrlDetector parts={parts} />
- </PopoutColumn>
- );
- }
-
- if (format) {
- return (
- <div onClick={selectCell} className={cellStyles}>
- {column.applyColumnFormatting(value)}
- </div>
- );
- }
-
- if (isPrimitiveOrNullish(value)) {
- const rendered = renderValue();
- return (
- <div onClick={selectCell} className={cellStyles}>
- {rendered == null ? "" : String(rendered)}
- </div>
- );
- }
-
- if (value instanceof Date) {
- // e.g. 2010-10-07 17:15:00
- const type =
- column.columnDef.meta?.dataType === "date" ? "date" : "datetime";
- const timezone = extractTimezone(column.columnDef.meta?.dtype);
- return (
- <div onClick={selectCell} className={cellStyles}>
- <DatePopover date={value} type={type}>
- {exactDateTime(value, timezone)}
- </DatePopover>
- </div>
- );
- }
-
- const mimeValues = getMimeValues(value);
- if (mimeValues) {
- return (
- <div onClick={selectCell} className={cellStyles}>
- {mimeValues.map((mimeValue, idx) => (
- <MimeCell key={idx} value={mimeValue} />
- ))}
- </div>
- );
- }
-
- if (Array.isArray(value) || typeof value === "object") {
- const rawStringValue = renderAny(value);
- return (
- <PopoutColumn
- cellStyles={cellStyles}
- selectCell={selectCell}
- rawStringValue={rawStringValue}
- >
- <JsonOutput data={value} format="tree" className="max-h-64" />
- </PopoutColumn>
- );
- }
-
- return (
- <div onClick={selectCell} className={cellStyles}>
- {renderAny(getValue())}
- </div>
+ return renderCellValue(
+ column,
+ renderValue,
+ getValue,
+ selectCell,
+ cellStyles,
);
},
// Remove any default filtering
@@ -371,8 +286,8 @@ const PopoutColumn = ({
buttonText,
children,
}: {
- cellStyles: string;
- selectCell: () => void;
+ cellStyles?: string;
+ selectCell?: () => void;
rawStringValue: string;
contentClassName?: string;
buttonText?: string;
@@ -466,3 +381,103 @@ function renderAny(value: unknown): string {
return String(value);
}
}
+
+export function renderCellValue<TData, TValue>(
+ column: Column<TData, TValue>,
+ renderValue: () => TValue | null,
+ getValue: () => TValue,
+ selectCell?: () => void,
+ cellStyles?: string,
+) {
+ const value = getValue();
+ const format = column.getColumnFormatting?.();
+
+ if (typeof value === "string") {
+ const stringValue = format
+ ? String(column.applyColumnFormatting(value))
+ : String(renderValue());
+
+ const parts = parseContent(stringValue);
+ const hasMarkup = parts.some((part) => part.type !== "text");
+ if (hasMarkup || stringValue.length < MAX_STRING_LENGTH) {
+ return (
+ <div onClick={selectCell} className={cellStyles}>
+ <UrlDetector parts={parts} />
+ </div>
+ );
+ }
+
+ return (
+ <PopoutColumn
+ cellStyles={cellStyles}
+ selectCell={selectCell}
+ rawStringValue={stringValue}
+ contentClassName="max-h-64 overflow-auto whitespace-pre-wrap break-words text-sm"
+ buttonText="X"
+ >
+ <UrlDetector parts={parts} />
+ </PopoutColumn>
+ );
+ }
+
+ if (format) {
+ return (
+ <div onClick={selectCell} className={cellStyles}>
+ {column.applyColumnFormatting(value)}
+ </div>
+ );
+ }
+
+ if (isPrimitiveOrNullish(value)) {
+ const rendered = renderValue();
+ return (
+ <div onClick={selectCell} className={cellStyles}>
+ {rendered == null ? "" : String(rendered)}
+ </div>
+ );
+ }
+
+ if (value instanceof Date) {
+ // e.g. 2010-10-07 17:15:00
+ const type =
+ column.columnDef.meta?.dataType === "date" ? "date" : "datetime";
+ const timezone = extractTimezone(column.columnDef.meta?.dtype);
+ return (
+ <div onClick={selectCell} className={cellStyles}>
+ <DatePopover date={value} type={type}>
+ {exactDateTime(value, timezone)}
+ </DatePopover>
+ </div>
+ );
+ }
+
+ const mimeValues = getMimeValues(value);
+ if (mimeValues) {
+ return (
+ <div onClick={selectCell} className={cellStyles}>
+ {mimeValues.map((mimeValue, idx) => (
+ <MimeCell key={idx} value={mimeValue} />
+ ))}
+ </div>
+ );
+ }
+
+ if (Array.isArray(value) || typeof value === "object") {
+ const rawStringValue = renderAny(value);
+ return (
+ <PopoutColumn
+ cellStyles={cellStyles}
+ selectCell={selectCell}
+ rawStringValue={rawStringValue}
+ >
+ <JsonOutput data={value} format="tree" className="max-h-64" />
+ </PopoutColumn>
+ );
+ }
+
+ return (
+ <div onClick={selectCell} className={cellStyles}>
+ {renderAny(value)}
+ </div>
+ );
+}
diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsx
index 06ac111bc5..9950dab3ab 100644
--- a/frontend/src/components/data-table/data-table.tsx
+++ b/frontend/src/components/data-table/data-table.tsx
@@ -30,13 +30,14 @@ import { TableActions } from "./TableActions";
import { ColumnFormattingFeature } from "./column-formatting/feature";
import { ColumnWrappingFeature } from "./column-wrapping/feature";
import type { DataTableSelection } from "./types";
-import { INDEX_COLUMN_NAME } from "./types";
import { CellSelectionFeature } from "./cell-selection/feature";
import type { CellSelectionState } from "./cell-selection/types";
import type { GetRowIds } from "@/plugins/impl/DataTablePlugin";
import { CellStylingFeature } from "./cell-styling/feature";
import type { CellStyleState } from "./cell-styling/types";
import { CopyColumnFeature } from "./copy-column/feature";
+import { FocusRowFeature } from "./focus-row/feature";
+import { getStableRowId } from "./utils";
interface DataTableProps<TData> extends Partial<DownloadActionProps> {
wrapperClassName?: string;
@@ -74,7 +75,12 @@ interface DataTableProps<TData> extends Partial<DownloadActionProps> {
freezeColumnsLeft?: string[];
freezeColumnsRight?: string[];
toggleDisplayHeader?: () => void;
+ // Focus row
+ onFocusRowChange?: OnChangeFn<number>;
+ // Others
chartsFeatureEnabled?: boolean;
+ toggleSelectionPanel?: () => void;
+ isSelectionPanelOpen?: boolean;
}
const DataTableInternal = <TData,>({
@@ -110,6 +116,9 @@ const DataTableInternal = <TData,>({
freezeColumnsRight,
toggleDisplayHeader,
chartsFeatureEnabled,
+ toggleSelectionPanel,
+ isSelectionPanelOpen,
+ onFocusRowChange,
}: DataTableProps<TData>) => {
const [isSearchEnabled, setIsSearchEnabled] = React.useState<boolean>(false);
@@ -118,6 +127,19 @@ const DataTableInternal = <TData,>({
freezeColumnsRight,
);
+ // Returns the row index, accounting for pagination
+ function getPaginatedRowIndex(row: TData, idx: number): number {
+ if (!paginationState) {
+ return idx;
+ }
+
+ // Add offset if manualPagination is enabled
+ const offset = manualPagination
+ ? paginationState.pageIndex * paginationState.pageSize
+ : 0;
+ return idx + offset;
+ }
+
const table = useReactTable<TData>({
_features: [
ColumnPinning,
@@ -126,6 +148,7 @@ const DataTableInternal = <TData,>({
CellSelectionFeature,
CellStylingFeature,
CopyColumnFeature,
+ FocusRowFeature,
],
data,
columns,
@@ -137,19 +160,13 @@ const DataTableInternal = <TData,>({
onPaginationChange: setPaginationState,
getRowId: (row, idx) => {
// Prefer stable row ID if it exists
- if (row && typeof row === "object" && INDEX_COLUMN_NAME in row) {
- return String(row[INDEX_COLUMN_NAME]);
- }
-
- if (!paginationState) {
- return String(idx);
+ const stableRowId = getStableRowId(row);
+ if (stableRowId) {
+ return stableRowId;
}
- // Add offset if manualPagination is enabled
- const offset = manualPagination
- ? paginationState.pageIndex * paginationState.pageSize
- : 0;
- return String(idx + offset);
+ const paginatedRowIndex = getPaginatedRowIndex(row, idx);
+ return String(paginatedRowIndex);
},
}
: {}),
@@ -172,6 +189,9 @@ const DataTableInternal = <TData,>({
enableMultiCellSelection: selection === "multi-cell",
// pinning
onColumnPinningChange: setColumnPinning,
+ // focus row
+ enableFocusRow: true,
+ onFocusRowChange: onFocusRowChange,
// state
state: {
...(sorting ? { sorting } : {}),
@@ -206,7 +226,12 @@ const DataTableInternal = <TData,>({
)}
<Table>
{renderTableHeader(table)}
- {renderTableBody(table, columns)}
+ {renderTableBody(
+ table,
+ columns,
+ isSelectionPanelOpen,
+ getPaginatedRowIndex,
+ )}
</Table>
</div>
<TableActions
@@ -223,6 +248,8 @@ const DataTableInternal = <TData,>({
getRowIds={getRowIds}
toggleDisplayHeader={toggleDisplayHeader}
chartsFeatureEnabled={chartsFeatureEnabled}
+ toggleSelectionPanel={toggleSelectionPanel}
+ isSelectionPanelOpen={isSelectionPanelOpen}
/>
</div>
);
diff --git a/frontend/src/components/data-table/focus-row/feature.ts b/frontend/src/components/data-table/focus-row/feature.ts
new file mode 100644
index 0000000000..a5594ee65f
--- /dev/null
+++ b/frontend/src/components/data-table/focus-row/feature.ts
@@ -0,0 +1,41 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import {
+ type Table,
+ type RowData,
+ type TableFeature,
+ makeStateUpdater,
+ type Row,
+} from "@tanstack/react-table";
+import type { FocusRowOptions, FocusRowTableState } from "./types";
+
+export const FocusRowFeature: TableFeature = {
+ getInitialState: (state): FocusRowTableState => {
+ return {
+ ...state,
+ focusedRowIdx: -1,
+ };
+ },
+
+ getDefaultOptions: <TData extends RowData>(
+ table: Table<TData>,
+ ): FocusRowOptions => {
+ return {
+ enableFocusRow: true,
+ onFocusRowChange: makeStateUpdater("focusedRowIdx", table),
+ };
+ },
+
+ createRow: <TData extends RowData>(
+ row: Row<TData>,
+ table: Table<TData>,
+ ): void => {
+ row.focusRow = (updater) => {
+ table.options.onFocusRowChange?.(updater);
+ };
+
+ row.getFocusedRowIdx = () => {
+ return table.getState().focusedRowIdx;
+ };
+ },
+};
diff --git a/frontend/src/components/data-table/focus-row/types.ts b/frontend/src/components/data-table/focus-row/types.ts
new file mode 100644
index 0000000000..606e906f18
--- /dev/null
+++ b/frontend/src/components/data-table/focus-row/types.ts
@@ -0,0 +1,32 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+/* eslint-disable @typescript-eslint/no-empty-interface */
+
+import type { OnChangeFn, RowData } from "@tanstack/react-table";
+
+// define types for feature's custom state
+export type FocusRowState = number;
+export interface FocusRowTableState {
+ focusedRowIdx: FocusRowState;
+}
+
+// define types for feature's table options
+export interface FocusRowOptions {
+ enableFocusRow?: boolean;
+ onFocusRowChange?: OnChangeFn<FocusRowState>;
+}
+
+// Define types for feature's table APIs
+export interface FocusRowInstance {
+ focusRow?: (rowIdx: FocusRowState) => void;
+ getFocusedRowIdx?: () => FocusRowState;
+}
+
+// Use declaration merging to add feature APIs to TanStack Table's existing types
+declare module "@tanstack/react-table" {
+ interface TableState extends FocusRowTableState {}
+
+ interface TableOptionsResolved<TData extends RowData>
+ extends FocusRowOptions {}
+
+ interface Row<TData extends RowData> extends FocusRowInstance {}
+}
diff --git a/frontend/src/components/data-table/pagination.tsx b/frontend/src/components/data-table/pagination.tsx
index 2a6c2ed1fd..237ff906ba 100644
--- a/frontend/src/components/data-table/pagination.tsx
+++ b/frontend/src/components/data-table/pagination.tsx
@@ -92,7 +92,7 @@ export const DataTablePagination = <TData,>({
);
}
- const rowsLabel = `${prettyNumber(numRows)} ${new PluralWord("row").pluralize(numRows)}`;
+ const rowsLabel = prettifyRowCount(numRows);
const columnsLabel = `${prettyNumber(totalColumns)} ${new PluralWord("column").pluralize(totalColumns)}`;
return <span>{[rowsLabel, columnsLabel].join(", ")}</span>;
@@ -245,3 +245,7 @@ export const PageSelector = ({
</select>
);
};
+
+export function prettifyRowCount(rowCount: number): string {
+ return `${prettyNumber(rowCount)} ${new PluralWord("row").pluralize(rowCount)}`;
+}
diff --git a/frontend/src/components/data-table/renderers.tsx b/frontend/src/components/data-table/renderers.tsx
index aa979c762c..de88cb5393 100644
--- a/frontend/src/components/data-table/renderers.tsx
+++ b/frontend/src/components/data-table/renderers.tsx
@@ -62,6 +62,8 @@ export function renderTableHeader<TData>(
export function renderTableBody<TData>(
table: Table<TData>,
columns: Array<ColumnDef<TData>>,
+ isSelectionPanelOpen?: boolean,
+ getRowIndex?: (row: TData, idx: number) => number,
): JSX.Element {
const renderCells = (row: Row<TData>, cells: Array<Cell<TData, unknown>>) => {
return cells.map((cell) => {
@@ -91,6 +93,11 @@ export function renderTableBody<TData>(
});
};
+ const handleRowClick = (row: Row<TData>) => {
+ const rowIndex = getRowIndex?.(row.original, row.index) ?? row.index;
+ row.focusRow?.(rowIndex);
+ };
+
return (
<TableBody>
{table.getRowModel().rows?.length ? (
@@ -99,7 +106,11 @@ export function renderTableBody<TData>(
key={row.id}
data-state={row.getIsSelected() && "selected"}
// These classes ensure that empty rows (nulls) still render
- className="border-t h-6"
+ className={cn(
+ "border-t h-6",
+ isSelectionPanelOpen && "cursor-pointer",
+ )}
+ onClick={() => handleRowClick(row)}
>
{renderCells(row, row.getLeftVisibleCells())}
{renderCells(row, row.getCenterVisibleCells())}
diff --git a/frontend/src/components/data-table/selection-panel/__tests__/data-selection.test.tsx b/frontend/src/components/data-table/selection-panel/__tests__/data-selection.test.tsx
new file mode 100644
index 0000000000..edbc4372d4
--- /dev/null
+++ b/frontend/src/components/data-table/selection-panel/__tests__/data-selection.test.tsx
@@ -0,0 +1,53 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { describe, expect, it, vi } from "vitest";
+import { render, screen } from "@testing-library/react";
+import { DataSelectionPanel } from "../data-selection";
+import { Provider } from "jotai";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import type { GetRowResult } from "@/plugins/impl/DataTablePlugin";
+import type { FieldTypesWithExternalType } from "../../types";
+
+const renderWithProviders = (component: React.ReactNode) => {
+ return render(
+ <TooltipProvider>
+ <Provider>{component}</Provider>
+ </TooltipProvider>,
+ );
+};
+
+describe("DataSelectionPanel", () => {
+ const mockFieldTypes: FieldTypesWithExternalType = [
+ ["name", ["string", "string"]],
+ ["age", ["number", "number"]],
+ ];
+
+ const mockGetRow = vi
+ .fn()
+ .mockImplementation((rowIdx: number): Promise<GetRowResult> => {
+ const mockData = [
+ { name: "John", age: 30 },
+ { name: "Jane", age: 25 },
+ { name: "Alice", age: 35 },
+ ];
+ return Promise.resolve({ rows: [mockData[rowIdx]] });
+ });
+
+ const mockSetRowIdx = vi.fn();
+
+ it("renders data in selection panel", async () => {
+ renderWithProviders(
+ <DataSelectionPanel
+ rowIdx={0}
+ setRowIdx={mockSetRowIdx}
+ totalRows={3}
+ fieldTypes={mockFieldTypes}
+ getRow={mockGetRow}
+ />,
+ );
+
+ // Wait for the data to load
+ expect(await screen.findByText("John")).toBeInTheDocument();
+ expect(await screen.findByText("30")).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/components/data-table/selection-panel/__tests__/filter-rows.test.ts b/frontend/src/components/data-table/selection-panel/__tests__/filter-rows.test.ts
new file mode 100644
index 0000000000..1f06e01eda
--- /dev/null
+++ b/frontend/src/components/data-table/selection-panel/__tests__/filter-rows.test.ts
@@ -0,0 +1,76 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { describe, expect, it } from "vitest";
+import { filterRows } from "../data-selection";
+
+describe("filterRows", () => {
+ const defaultRowValues = {
+ name: "John",
+ age: 30,
+ };
+
+ it("should filter rows based on column name", () => {
+ const result = filterRows(defaultRowValues, "name");
+ expect(result).toHaveLength(1);
+ expect(result[0][0]).toBe("name");
+ });
+
+ it("should filter rows based on cell value", () => {
+ const result = filterRows(defaultRowValues, "john");
+ expect(result).toHaveLength(1);
+ expect(result[0][0]).toBe("name");
+ });
+
+ it("should handle object values by converting them to strings", () => {
+ const rowValues = {
+ data: { key: "value" },
+ };
+
+ const result = filterRows(rowValues, "value");
+ expect(result).toHaveLength(1);
+ expect(result[0][0]).toBe("data");
+ });
+
+ it("should be case insensitive", () => {
+ const rowValues = {
+ Name: "John",
+ AGE: 30,
+ };
+
+ const result = filterRows(rowValues, "name");
+ expect(result).toHaveLength(1);
+ expect(result[0][0]).toBe("Name");
+ });
+
+ it("should handle partial matches", () => {
+ const rowValues = {
+ firstName: "John",
+ lastName: "Doe",
+ };
+
+ const result = filterRows(rowValues, "name");
+ expect(result).toHaveLength(2);
+ expect(result.map(([name]) => name)).toEqual(["firstName", "lastName"]);
+ });
+
+ it("should return empty array when no matches found", () => {
+ const result = filterRows(defaultRowValues, "xyz");
+ expect(result).toHaveLength(0);
+ });
+
+ it("should handle empty search query", () => {
+ const result = filterRows(defaultRowValues, "");
+ expect(result).toHaveLength(2);
+ });
+
+ it("should handle null values", () => {
+ const rowValues = {
+ name: null,
+ age: 30,
+ };
+
+ const result = filterRows(rowValues, "null");
+ expect(result).toHaveLength(1);
+ expect(result[0][0]).toBe("name");
+ });
+});
diff --git a/frontend/src/components/data-table/selection-panel/data-selection.tsx b/frontend/src/components/data-table/selection-panel/data-selection.tsx
new file mode 100644
index 0000000000..0c8ca2a415
--- /dev/null
+++ b/frontend/src/components/data-table/selection-panel/data-selection.tsx
@@ -0,0 +1,284 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import {
+ ChevronLeft,
+ ChevronRight,
+ SearchIcon,
+ ChevronsLeft,
+ ChevronsRight,
+ AlertTriangle,
+ Info,
+} from "lucide-react";
+import { Button } from "@/components/ui/button";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { DATA_TYPE_ICON } from "@/components/datasets/icons";
+import { Input } from "@/components/ui/input";
+import { CopyClipboardIcon } from "@/components/icons/copy-icon";
+import { useState } from "react";
+import { useAsyncData } from "@/hooks/useAsyncData";
+import {
+ INDEX_COLUMN_NAME,
+ SELECT_COLUMN_ID,
+ type FieldTypesWithExternalType,
+} from "../types";
+import { prettifyRowCount } from "../pagination";
+import type { GetRowResult } from "@/plugins/impl/DataTablePlugin";
+import { NAMELESS_COLUMN_PREFIX } from "../columns";
+import { Banner, ErrorBanner } from "@/plugins/impl/common/error-banner";
+import type { Column } from "@tanstack/react-table";
+import { renderCellValue } from "../columns";
+
+export interface DataSelectionPanelProps {
+ rowIdx: number;
+ setRowIdx: (rowIdx: number) => void;
+ totalRows: number;
+ fieldTypes: FieldTypesWithExternalType | undefined | null;
+ getRow: (rowIdx: number) => Promise<GetRowResult>;
+}
+
+export const DataSelectionPanel: React.FC<DataSelectionPanelProps> = ({
+ rowIdx,
+ setRowIdx,
+ totalRows,
+ fieldTypes,
+ getRow,
+}: DataSelectionPanelProps) => {
+ const [searchQuery, setSearchQuery] = useState("");
+
+ const { data: rows, error } = useAsyncData(async () => {
+ const data = await getRow(rowIdx);
+ return data.rows;
+ }, [getRow, rowIdx, totalRows]);
+
+ const handleSelectRow = (rowIdx: number) => {
+ if (rowIdx < 0 || rowIdx >= totalRows) {
+ return;
+ }
+ setRowIdx(rowIdx);
+ };
+
+ const buttonStyles = "h-6 w-6 p-0.5";
+
+ const renderTable = () => {
+ if (error) {
+ return <ErrorBanner error={error} className="p-4 mx-3 mt-5" />;
+ }
+
+ if (totalRows === 0) {
+ return (
+ <SimpleBanner kind="info" Icon={Info} message="No rows selected" />
+ );
+ }
+
+ if (!rows) {
+ return (
+ <SimpleBanner
+ kind="warn"
+ Icon={AlertTriangle}
+ message="No data available. Please report the issue."
+ />
+ );
+ }
+
+ if (rows.length !== 1) {
+ return (
+ <SimpleBanner
+ kind="warn"
+ Icon={AlertTriangle}
+ message={`Expected 1 row, got ${rows.length} rows. Please report the issue.`}
+ />
+ );
+ }
+
+ const currentRow = rows[0];
+ if (typeof currentRow !== "object" || currentRow === null) {
+ return (
+ <SimpleBanner
+ kind="warn"
+ Icon={AlertTriangle}
+ message="Row is not an object. Please report the issue."
+ />
+ );
+ }
+
+ const rowValues: Record<string, unknown> = {};
+ for (const [columnName, columnValue] of Object.entries(currentRow)) {
+ if (columnName === SELECT_COLUMN_ID || columnName === INDEX_COLUMN_NAME) {
+ continue;
+ }
+ if (columnName.startsWith(NAMELESS_COLUMN_PREFIX)) {
+ // Remove the prefix
+ rowValues[columnName.slice(NAMELESS_COLUMN_PREFIX.length)] =
+ columnValue;
+ } else {
+ rowValues[columnName] = columnValue;
+ }
+ }
+
+ const filteredRows = filterRows(rowValues, searchQuery);
+
+ return (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-1/4">Column</TableHead>
+ <TableHead className="w-3/4">Value</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {filteredRows.map(([columnName, columnValue]) => {
+ const dataType = fieldTypes?.find(
+ ([name]) => name === columnName,
+ )?.[1][0];
+
+ const Icon = dataType ? DATA_TYPE_ICON[dataType] : null;
+ const mockColumn = {
+ id: columnName,
+ columnDef: {
+ meta: {
+ dataType,
+ },
+ },
+ getColumnFormatting: () => undefined,
+ applyColumnFormatting: (value) => value,
+ } as Column<unknown>;
+
+ const cellContent = renderCellValue(
+ mockColumn,
+ () => columnValue,
+ () => columnValue,
+ undefined,
+ "text-left break-all",
+ );
+ const copyValue =
+ typeof columnValue === "object"
+ ? JSON.stringify(columnValue)
+ : String(columnValue);
+
+ return (
+ <TableRow key={columnName} className="group">
+ <TableCell className="flex flex-row items-center gap-1.5">
+ {Icon && (
+ <Icon className="w-4 h-4 p-0.5 rounded-sm bg-muted" />
+ )}
+ {columnName}
+ </TableCell>
+ <TableCell>
+ <div className="flex flex-row items-center justify-between gap-1">
+ {cellContent}
+ <CopyClipboardIcon
+ value={copyValue}
+ className="w-3 h-3 mr-1 text-muted-foreground cursor-pointer opacity-0 group-hover:opacity-100"
+ />
+ </div>
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ );
+ };
+
+ return (
+ <div className="flex flex-col gap-3 mt-4">
+ <div className="flex flex-row gap-2 justify-end items-center mr-2">
+ <Button
+ variant="outline"
+ size="xs"
+ className={buttonStyles}
+ onClick={() => handleSelectRow(0)}
+ disabled={rowIdx === 0}
+ aria-label="Go to first row"
+ >
+ <ChevronsLeft />
+ </Button>
+ <Button
+ variant="outline"
+ size="xs"
+ className={buttonStyles}
+ onClick={() => handleSelectRow(rowIdx - 1)}
+ disabled={rowIdx === 0}
+ aria-label="Previous row"
+ >
+ <ChevronLeft />
+ </Button>
+ <span className="text-xs">
+ Row {rowIdx + 1} of {prettifyRowCount(totalRows)}
+ </span>
+ <Button
+ variant="outline"
+ size="xs"
+ className={buttonStyles}
+ onClick={() => handleSelectRow(rowIdx + 1)}
+ disabled={rowIdx === totalRows - 1}
+ aria-label="Next row"
+ >
+ <ChevronRight />
+ </Button>
+ <Button
+ variant="outline"
+ size="xs"
+ className={buttonStyles}
+ onClick={() => handleSelectRow(totalRows - 1)}
+ aria-label="Go to last row"
+ >
+ <ChevronsRight />
+ </Button>
+ </div>
+
+ <div className="mx-2 -mb-1">
+ <Input
+ type="text"
+ placeholder="Search"
+ onChange={(e) => setSearchQuery(e.target.value)}
+ icon={<SearchIcon className="w-4 h-4" />}
+ className="mb-0 border-border"
+ data-testid="selection-panel-search-input"
+ />
+ </div>
+ {renderTable()}
+ </div>
+ );
+};
+
+export function filterRows(rowValues: object, searchQuery: string) {
+ return Object.entries(rowValues).filter(([columnName, columnValue]) => {
+ const colName = columnName.toLowerCase();
+
+ let columnValueString =
+ typeof columnValue === "object"
+ ? JSON.stringify(columnValue)
+ : String(columnValue);
+ columnValueString = columnValueString.toLowerCase();
+ const searchQueryLower = searchQuery.toLowerCase();
+
+ return (
+ colName.includes(searchQueryLower) ||
+ columnValueString.includes(searchQueryLower)
+ );
+ });
+}
+
+const SimpleBanner: React.FC<{
+ kind: "info" | "warn" | "danger";
+ Icon: React.FC<React.SVGProps<SVGSVGElement>>;
+ message: string;
+}> = ({ kind, Icon, message }) => {
+ return (
+ <Banner
+ kind={kind}
+ className="p-4 mx-3 mt-3 flex flex-row items-center gap-2"
+ >
+ <Icon className="w-5 h-5" />
+ <span>{message}</span>
+ </Banner>
+ );
+};
diff --git a/frontend/src/components/data-table/utils.ts b/frontend/src/components/data-table/utils.ts
new file mode 100644
index 0000000000..71caf11cd0
--- /dev/null
+++ b/frontend/src/components/data-table/utils.ts
@@ -0,0 +1,46 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import type { TableData } from "@/plugins/impl/DataTablePlugin";
+import { vegaLoadData } from "@/plugins/impl/vega/loader";
+import { jsonParseWithSpecialChar } from "@/utils/json/json-parser";
+import { INDEX_COLUMN_NAME } from "./types";
+
+/**
+ * Convenience function to load table data.
+ *
+ * This resolves to an array of objects, where each object represents a row.
+ */
+export async function loadTableData<T = object>(
+ tableData: TableData<T>,
+): Promise<T[]> {
+ // If we already have the data, return it
+ if (Array.isArray(tableData)) {
+ return tableData;
+ }
+
+ // If it looks like json, parse it
+ if (tableData.startsWith("{") || tableData.startsWith("[")) {
+ return jsonParseWithSpecialChar(tableData);
+ }
+
+ // Otherwise, load the data from the URL
+ tableData = await vegaLoadData(
+ tableData,
+ { type: "json" },
+ { handleBigIntAndNumberLike: true },
+ );
+ return tableData;
+}
+
+/**
+ * Get the stable row ID for a row.
+ *
+ * This is the row ID that is used to identify a row in the table.
+ * It is stable across renders and pagination. It may not exist.
+ *
+ */
+export function getStableRowId<TData>(row: TData): string | undefined {
+ if (row && typeof row === "object" && INDEX_COLUMN_NAME in row) {
+ return String(row[INDEX_COLUMN_NAME]);
+ }
+}
diff --git a/frontend/src/components/editor/chrome/panels/context-aware-panel.tsx b/frontend/src/components/editor/chrome/panels/context-aware-panel.tsx
new file mode 100644
index 0000000000..6b8868ad2d
--- /dev/null
+++ b/frontend/src/components/editor/chrome/panels/context-aware-panel.tsx
@@ -0,0 +1,124 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { SlotNames } from "@/core/slots/slots";
+import { Fill, Slot, useSlot } from "@marimo-team/react-slotz";
+import { useAtom } from "jotai";
+import type { PropsWithChildren } from "react";
+import { PanelResizeHandle, Panel } from "react-resizable-panels";
+import {
+ contextAwarePanelOwner,
+ isContextAwarePanelPinnedAtom,
+} from "../state";
+import { handleDragging } from "../wrapper/utils";
+import { useResizeHandle } from "@/hooks/useResizeHandle";
+
+import { PinIcon, PinOffIcon, XIcon } from "lucide-react";
+import { Tooltip } from "@/components/ui/tooltip";
+import { Button } from "@/components/ui/button";
+import { Toggle } from "@/components/ui/toggle";
+import { ErrorBoundary } from "../../boundary/ErrorBoundary";
+
+export const ContextAwarePanel: React.FC = () => {
+ const [owner, setOwner] = useAtom(contextAwarePanelOwner);
+ const [isPinned, setIsPinned] = useAtom(isContextAwarePanelPinnedAtom);
+ const closePanel = () => setOwner(null);
+
+ const slots = useSlot(SlotNames.CONTEXT_AWARE_PANEL);
+
+ if (slots.length === 0 || !owner) {
+ return null;
+ }
+
+ const renderModeToggle = () => {
+ return (
+ <div className="flex flex-row items-center gap-1">
+ <Tooltip content={isPinned ? "Unpin" : "Pin panel"}>
+ <Toggle
+ size="xs"
+ onPressedChange={() => setIsPinned(!isPinned)}
+ pressed={isPinned}
+ aria-label={isPinned ? "Unpin" : "Pin panel"}
+ >
+ {isPinned ? (
+ <PinIcon className="w-4 h-4" />
+ ) : (
+ <PinOffIcon className="w-4 h-4" />
+ )}
+ </Toggle>
+ </Tooltip>
+ </div>
+ );
+ };
+
+ const renderBody = () => {
+ return (
+ <div className="mt-2 pb-7 mb-4 h-full overflow-auto">
+ <div className="flex flex-row justify-between items-center mx-2">
+ {renderModeToggle()}
+ <Button
+ variant="linkDestructive"
+ size="icon"
+ onClick={closePanel}
+ aria-label="Close selection panel"
+ >
+ <XIcon className="w-4 h-4" />
+ </Button>
+ </div>
+
+ {/* TODO: This usually doesn't trigger, and the whole panel closes */}
+ <ErrorBoundary>
+ <Slot name={SlotNames.CONTEXT_AWARE_PANEL} />
+ </ErrorBoundary>
+ </div>
+ );
+ };
+
+ if (!isPinned) {
+ return <ResizableComponent>{renderBody()}</ResizableComponent>;
+ }
+
+ return (
+ <>
+ <PanelResizeHandle
+ onDragging={handleDragging}
+ className="resize-handle border-border z-20 no-print border-l"
+ />
+ <Panel defaultSize={25} minSize={15}>
+ {renderBody()}
+ </Panel>
+ </>
+ );
+};
+
+export const ContextAwarePanelItem: React.FC<PropsWithChildren> = ({
+ children,
+}) => {
+ return (
+ <ErrorBoundary>
+ <Fill name={SlotNames.CONTEXT_AWARE_PANEL}>{children}</Fill>
+ </ErrorBoundary>
+ );
+};
+
+interface ResizableComponentProps {
+ children: React.ReactNode;
+}
+
+const ResizableComponent = ({ children }: ResizableComponentProps) => {
+ const { resizableDivRef, handleRefs, style } = useResizeHandle({
+ startingWidth: 400,
+ minWidth: 300,
+ });
+
+ return (
+ <div className="absolute z-40 right-0 h-full bg-background flex flex-row">
+ <div
+ ref={handleRefs.left}
+ className="w-1 h-full cursor-col-resize border-l"
+ />
+ <div ref={resizableDivRef} style={style}>
+ {children}
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/components/editor/chrome/state.ts b/frontend/src/components/editor/chrome/state.ts
index a6f9569ebe..982c99486d 100644
--- a/frontend/src/components/editor/chrome/state.ts
+++ b/frontend/src/components/editor/chrome/state.ts
@@ -1,6 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { createReducerAndAtoms } from "@/utils/createReducer";
-import { useAtomValue } from "jotai";
+import { atom, useAtomValue } from "jotai";
import type { PanelType } from "./types";
import { ZodLocalStorage } from "@/utils/localStorage";
import { z } from "zod";
@@ -99,3 +99,17 @@ export const exportedForTesting = {
createActions,
initialState,
};
+
+// Context-aware panel
+
+/**
+ * Unique ID of the owner rendering the context-aware panel.
+ * If null, the panel is not open.
+ */
+export const contextAwarePanelOwner = atom<string | null>(null);
+
+/**
+ * If true, the panel is treated as part of the editor.
+ * When false, the panel overlays the editor content.
+ */
+export const isContextAwarePanelPinnedAtom = atom<boolean>(false);
diff --git a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
index d5f5c49933..9b1c42a1ed 100644
--- a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
@@ -32,6 +32,8 @@ import { ChatPanel } from "@/components/chat/chat-panel";
import { TooltipProvider } from "@radix-ui/react-tooltip";
import { TracingPanel } from "../panels/tracing-panel";
import { SecretsPanel } from "../panels/secrets-panel";
+import { ContextAwarePanel } from "../panels/context-aware-panel";
+import { handleDragging } from "./utils";
const LazyTerminal = React.lazy(() => import("@/components/terminal/terminal"));
@@ -95,13 +97,6 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
</Panel>
);
- const handleDragging = (isDragging: boolean) => {
- if (!isDragging) {
- // Once the user is done dragging, dispatch a resize event
- window.dispatchEvent(new Event("resize"));
- }
- };
-
const helperResizeHandle = (
<PanelResizeHandle
onDragging={handleDragging}
@@ -244,6 +239,7 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
<IfCapability capability="terminal">{terminalPanel}</IfCapability>
</PanelGroup>
</Panel>
+ <ContextAwarePanel />
</PanelGroup>
<ErrorBoundary>
<TooltipProvider>
diff --git a/frontend/src/components/editor/chrome/wrapper/utils.ts b/frontend/src/components/editor/chrome/wrapper/utils.ts
new file mode 100644
index 0000000000..fbea88725d
--- /dev/null
+++ b/frontend/src/components/editor/chrome/wrapper/utils.ts
@@ -0,0 +1,8 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+export function handleDragging(isDragging: boolean) {
+ if (!isDragging) {
+ // Once the user is done dragging, dispatch a resize event
+ window.dispatchEvent(new Event("resize"));
+ }
+}
diff --git a/frontend/src/components/icons/copy-icon.tsx b/frontend/src/components/icons/copy-icon.tsx
index 679d9f9512..90b9138767 100644
--- a/frontend/src/components/icons/copy-icon.tsx
+++ b/frontend/src/components/icons/copy-icon.tsx
@@ -35,13 +35,13 @@ export const CopyClipboardIcon: React.FC<Props> = ({
});
const button = (
- <span onClick={handleCopy}>
+ <button type="button" onClick={handleCopy} aria-label="Copy to clipboard">
{isCopied ? (
<CheckIcon className={cn(className, "text-[var(--grass-11)]")} />
) : (
<Copy className={className} />
)}
- </span>
+ </button>
);
if (tooltip === false) {
diff --git a/frontend/src/core/cells/__tests__/ids.test.ts b/frontend/src/core/cells/__tests__/ids.test.ts
index 26b3c8c8f7..f5d50534dd 100644
--- a/frontend/src/core/cells/__tests__/ids.test.ts
+++ b/frontend/src/core/cells/__tests__/ids.test.ts
@@ -1,10 +1,9 @@
/* Copyright 2024 Marimo. All rights reserved. */
-/* eslint-disable @typescript-eslint/no-non-null-assertion */
-import { expect, describe, test } from "vitest";
-import { CellId, CellOutputId, HTMLCellId } from "../ids";
+import { expect, describe, it } from "vitest";
+import { CellId, CellOutputId, HTMLCellId, findCellId } from "../ids";
describe("CellId", () => {
- test("create", () => {
+ it("create", () => {
const cellId = CellId.create();
expect(typeof cellId).toBe("string");
expect(cellId.length).toBeGreaterThan(0);
@@ -12,20 +11,20 @@ describe("CellId", () => {
});
describe("HTMLCellId", () => {
- test("create", () => {
+ it("create", () => {
const cellId = CellId.create();
const htmlCellId = HTMLCellId.create(cellId);
expect(htmlCellId).toBe(`cell-${cellId}`);
});
- test("parse", () => {
+ it("parse", () => {
const cellId = CellId.create();
const htmlCellId = HTMLCellId.create(cellId);
const parsedCellId = HTMLCellId.parse(htmlCellId);
expect(parsedCellId).toBe(cellId);
});
- test("findElement", () => {
+ it("findElement", () => {
document.body.innerHTML = `
<div id="not-a-cell"></div>
<div id="cell-${CellId.create()}">
@@ -41,9 +40,41 @@ describe("HTMLCellId", () => {
});
describe("CellOutputId", () => {
- test("create", () => {
+ it("create", () => {
const cellId = CellId.create();
const cellOutputId = CellOutputId.create(cellId);
expect(cellOutputId).toBe(`output-${cellId}`);
});
});
+
+describe("findCellId", () => {
+ it("should find cell ID when element is inside a cell container", () => {
+ // Create a cell container with a known ID
+ const cellId = CellId.create();
+ const container = document.createElement("div");
+ container.id = HTMLCellId.create(cellId);
+
+ // Create a child element inside the container
+ const child = document.createElement("div");
+ container.append(child);
+
+ // Test finding the cell ID from the child element
+ expect(findCellId(child)).toBe(cellId);
+ });
+
+ it("should find cell ID when element is the cell container itself", () => {
+ // Create a cell container with a known ID
+ const cellId = CellId.create();
+ const container = document.createElement("div");
+ container.id = HTMLCellId.create(cellId);
+
+ // Test finding the cell ID from the container itself
+ expect(findCellId(container)).toBe(cellId);
+ });
+
+ it("should return null when element is not inside a cell container", () => {
+ // Create an element that's not inside any cell container
+ const element = document.createElement("div");
+ expect(findCellId(element)).toBeNull();
+ });
+});
diff --git a/frontend/src/core/cells/ids.ts b/frontend/src/core/cells/ids.ts
index 2bd1653f63..1ebd74bf1d 100644
--- a/frontend/src/core/cells/ids.ts
+++ b/frontend/src/core/cells/ids.ts
@@ -75,6 +75,18 @@ export const HTMLCellId = {
},
};
+/**
+ * Find the cellId of an element
+ */
+export function findCellId(element: HTMLElement): CellId | null {
+ let cellId: CellId | null = null;
+ const cellContainer = HTMLCellId.findElement(element);
+ if (cellContainer) {
+ cellId = HTMLCellId.parse(cellContainer.id);
+ }
+ return cellId;
+}
+
/**
* A typed UIElementId
*/
diff --git a/frontend/src/core/slots/slots.ts b/frontend/src/core/slots/slots.ts
index 32a1543289..84be76dcfe 100644
--- a/frontend/src/core/slots/slots.ts
+++ b/frontend/src/core/slots/slots.ts
@@ -5,4 +5,5 @@ export const slotsController = new SlotzController();
export const SlotNames = {
SIDEBAR: "sidebar",
+ CONTEXT_AWARE_PANEL: "context-aware-panel",
};
diff --git a/frontend/src/hooks/__tests__/useResizeHandle.test.tsx b/frontend/src/hooks/__tests__/useResizeHandle.test.tsx
index e427884444..f35a3c7923 100644
--- a/frontend/src/hooks/__tests__/useResizeHandle.test.tsx
+++ b/frontend/src/hooks/__tests__/useResizeHandle.test.tsx
@@ -178,4 +178,63 @@ describe("useResizeHandle", () => {
expect(resizableDiv.style.width).toBe("600px"); // 500px + 100px movement
expect(onResize).toHaveBeenCalledWith(600);
});
+
+ it("should handle min and max width", () => {
+ const onResize = vi.fn();
+
+ // Create a test component that uses the hook
+ const TestComponent = () => {
+ const { resizableDivRef, handleRefs } = useResizeHandle({
+ startingWidth: 500,
+ minWidth: 400,
+ maxWidth: 600,
+ onResize,
+ });
+
+ return (
+ <div>
+ <div
+ ref={resizableDivRef}
+ style={{ width: "500px" }}
+ data-testid="resizable-div"
+ />
+ <div ref={handleRefs.right} data-testid="right-handle" />
+ </div>
+ );
+ };
+
+ const { getByTestId } = render(<TestComponent />);
+ const resizableDiv = getByTestId("resizable-div") as HTMLDivElement;
+ const rightHandle = getByTestId("right-handle") as HTMLDivElement;
+
+ // Test min width
+ act(() => {
+ const mousedownEvent = new MouseEvent("mousedown", { clientX: 0 });
+ rightHandle.dispatchEvent(mousedownEvent);
+
+ const mousemoveEvent = new MouseEvent("mousemove", { clientX: -200 }); // Try to resize below min
+ document.dispatchEvent(mousemoveEvent);
+
+ const mouseupEvent = new MouseEvent("mouseup");
+ document.dispatchEvent(mouseupEvent);
+ });
+
+ expect(resizableDiv.style.width).toBe("400px"); // Should be clamped to min width
+ expect(onResize).toHaveBeenCalledWith(400);
+
+ // Test max width
+ act(() => {
+ const mousedownEvent = new MouseEvent("mousedown", { clientX: 0 });
+ rightHandle.dispatchEvent(mousedownEvent);
+
+ const mousemoveEvent = new MouseEvent("mousemove", { clientX: 200 }); // Try to resize above max
+ document.dispatchEvent(mousemoveEvent);
+
+ const mouseupEvent = new MouseEvent("mouseup");
+ document.dispatchEvent(mouseupEvent);
+ });
+
+ expect(resizableDiv.style.width).toBe("600px"); // Should be clamped to max width
+ expect(onResize).toHaveBeenCalledWith(600);
+ });
});
diff --git a/frontend/src/hooks/useResizeHandle.ts b/frontend/src/hooks/useResizeHandle.ts
index e9cd56c5d3..639d6f6874 100644
--- a/frontend/src/hooks/useResizeHandle.ts
+++ b/frontend/src/hooks/useResizeHandle.ts
@@ -3,6 +3,8 @@ import { useEffect, useRef } from "react";
interface UseResizeHandleProps {
onResize?: (width: number) => void;
+ minWidth?: number;
+ maxWidth?: number;
startingWidth: number | "contentWidth";
}
@@ -10,6 +12,8 @@ interface UseResizeHandleProps {
export const useResizeHandle = ({
onResize,
startingWidth,
+ minWidth,
+ maxWidth,
}: UseResizeHandleProps) => {
const resizableDivRef = useRef<HTMLDivElement>(null);
const leftRef = useRef<HTMLDivElement>(null);
@@ -37,7 +41,14 @@ export const useResizeHandle = ({
const dx = e.clientX - lastX;
lastX = e.clientX;
+ // dx is negative when moving left
width = activeDirection === "left" ? width - dx : width + dx;
+ if (minWidth) {
+ width = Math.max(minWidth, width);
+ }
+ if (maxWidth) {
+ width = Math.min(maxWidth, width);
+ }
resizableDiv.style.width = `${width}px`;
};
@@ -80,7 +91,7 @@ export const useResizeHandle = ({
document.removeEventListener("mousemove", handleMouseMove);
document.removeEventListener("mouseup", handleMouseUp);
};
- }, [onResize]);
+ }, [minWidth, maxWidth, onResize]);
return {
resizableDivRef,
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index b19888c734..0368899624 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, useEffect, useMemo, useState } from "react";
+import { memo, useCallback, useEffect, useId, useMemo, useState } from "react";
import { z } from "zod";
import { DataTable } from "../../components/data-table/data-table";
import {
@@ -51,11 +51,17 @@ import {
type ColumnFilterValue,
} from "@/components/data-table/filters";
import { isStaticNotebook } from "@/core/static/static-state";
-import { vegaLoadData } from "./vega/loader";
-import { jsonParseWithSpecialChar } from "@/utils/json/json-parser";
-
+import { Provider as SlotzProvider } from "@marimo-team/react-slotz";
+import { findCellId } from "@/core/cells/ids";
+import { slotsController } from "@/core/slots/slots";
+import { ContextAwarePanelItem } from "@/components/editor/chrome/panels/context-aware-panel";
+import { DataSelectionPanel } from "@/components/data-table/selection-panel/data-selection";
+import { Provider, useAtom } from "jotai";
+import { contextAwarePanelOwner } from "@/components/editor/chrome/state";
+import { store } from "@/core/state/jotai";
+import { loadTableData } from "@/components/data-table/utils";
type CsvURL = string;
-type TableData<T> = T[] | CsvURL;
+export type TableData<T> = T[] | CsvURL;
interface ColumnSummaries<T = unknown> {
data: TableData<T> | null | undefined;
summaries: ColumnHeaderSummary[];
@@ -80,6 +86,10 @@ export type CalculateTopKRows = <T>(req: {
data: Array<[unknown, number]>;
}>;
+export interface GetRowResult {
+ rows: unknown[];
+}
+
/**
* Arguments for a data table
*
@@ -245,22 +255,27 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")
})
.renderer((props) => {
return (
- <TooltipProvider>
- <LazyDataTableComponent
- isLazy={props.data.lazy}
- preload={props.data.preload}
- >
- <LoadingDataTableComponent
- {...props.data}
- {...props.functions}
- enableSearch={true}
- data={props.data.data}
- value={props.value}
- setValue={props.setValue}
- experimentalChartsEnabled={true}
- />
- </LazyDataTableComponent>
- </TooltipProvider>
+ <Provider store={store}>
+ <SlotzProvider controller={slotsController}>
+ <TooltipProvider>
+ <LazyDataTableComponent
+ isLazy={props.data.lazy}
+ preload={props.data.preload}
+ >
+ <LoadingDataTableComponent
+ {...props.data}
+ {...props.functions}
+ host={props.host}
+ enableSearch={true}
+ data={props.data.data}
+ value={props.value}
+ setValue={props.setValue}
+ experimentalChartsEnabled={true}
+ />
+ </LazyDataTableComponent>
+ </TooltipProvider>
+ </SlotzProvider>
+ </Provider>
);
});
@@ -301,6 +316,7 @@ interface DataTableProps<T> extends Data<T>, DataTableFunctions {
experimentalChartsEnabled?: boolean;
toggleDisplayHeader?: () => void;
chartsFeatureEnabled?: boolean;
+ host: HTMLElement;
}
export type SetFilters = OnChangeFn<ColumnFiltersState>;
@@ -358,6 +374,8 @@ export const LoadingDataTableComponent = memo(
}
}, [props.pageSize, paginationState.pageSize]);
+ const cellId = findCellId(props.host);
+
// Data loading
const { data, loading, error } = useAsyncData<{
rows: T[];
@@ -421,31 +439,7 @@ export const LoadingDataTableComponent = memo(
totalRows = searchResults.total_rows;
cellStyles = searchResults.cell_styles || {};
}
- // If we already have the data, return it
- if (Array.isArray(tableData)) {
- return {
- rows: tableData,
- totalRows: totalRows,
- cellStyles,
- };
- }
-
- // If it looks like json, parse it
- if (tableData.startsWith("{") || tableData.startsWith("[")) {
- return {
- rows: jsonParseWithSpecialChar(tableData),
- totalRows: totalRows,
- cellStyles,
- };
- }
-
- // Otherwise, load the data from the URL
- tableData = await vegaLoadData(
- tableData,
- { type: "json" },
- { handleBigIntAndNumberLike: true },
- );
-
+ tableData = await loadTableData(tableData);
return {
rows: tableData,
totalRows: totalRows,
@@ -463,6 +457,34 @@ export const LoadingDataTableComponent = memo(
paginationState.pageIndex,
]);
+ const getRow = useCallback(
+ async (rowId: number) => {
+ const result = await search<T>({
+ page_number: rowId,
+ page_size: 1,
+ sort:
+ sorting.length > 0
+ ? {
+ by: sorting[0].id,
+ descending: sorting[0].desc,
+ }
+ : undefined,
+ query: searchQuery,
+ filters: filters.flatMap((filter) => {
+ return filterToFilterCondition(
+ filter.id,
+ filter.value as ColumnFilterValue,
+ );
+ }),
+ });
+ const loadedData = await loadTableData(result.data);
+ return {
+ rows: loadedData,
+ };
+ },
+ [search, sorting, filters, searchQuery],
+ );
+
// If total rows change, reset pageIndex
useEffect(() => {
setPaginationState((state) =>
@@ -545,6 +567,7 @@ export const LoadingDataTableComponent = memo(
cellStyles={data?.cellStyles ?? props.cellStyles}
toggleDisplayHeader={toggleDisplayHeader}
chartsFeatureEnabled={chartsFeatureEnabled}
+ getRow={getRow}
/>
);
@@ -557,6 +580,7 @@ export const LoadingDataTableComponent = memo(
dataTable={dataTable}
getDataUrl={props.get_data_url}
fieldTypes={props.fieldTypes}
+ cellId={cellId}
/>
) : (
dataTable
@@ -602,11 +626,15 @@ const DataTableComponent = ({
toggleDisplayHeader,
chartsFeatureEnabled,
calculate_top_k_rows,
+ getRow,
}: DataTableProps<unknown> &
DataTableSearchProps & {
data: unknown[];
columnSummaries?: ColumnSummaries;
+ getRow: (rowIdx: number) => Promise<GetRowResult>;
}): JSX.Element => {
+ const id = useId();
+ const [focusedRowIdx, setFocusedRowIdx] = useState(0);
const chartSpecModel = useMemo(() => {
if (!columnSummaries) {
return ColumnChartSpecModel.EMPTY;
@@ -664,6 +692,21 @@ const DataTableComponent = ({
[value],
);
+ const [selectionPanelOwner, setSelectionPanelOwner] = useAtom(
+ contextAwarePanelOwner,
+ );
+ const isSelectionPanelOpen = selectionPanelOwner === id;
+
+ function toggleSelectionPanel() {
+ if (isSelectionPanelOpen) {
+ // Close if panel is open
+ setSelectionPanelOwner(null);
+ } else {
+ // Set the owner to current id, which will cause the panel to open
+ setSelectionPanelOwner(id);
+ }
+ }
+
const handleRowSelectionChange: OnChangeFn<RowSelectionState> = useEvent(
(updater) => {
if (selection === "single") {
@@ -720,6 +763,17 @@ const DataTableComponent = ({
1,000,000 rows.
</Banner>
)}
+ {isSelectionPanelOpen && (
+ <ContextAwarePanelItem>
+ <DataSelectionPanel
+ getRow={getRow}
+ fieldTypes={memoizedFieldTypes}
+ totalRows={totalRows === "too_many" ? 100 : totalRows}
+ rowIdx={focusedRowIdx}
+ setRowIdx={setFocusedRowIdx}
+ />
+ </ContextAwarePanelItem>
+ )}
<ColumnChartContext.Provider value={chartSpecModel}>
<Labeled label={label} align="top" fullWidth={true}>
<DataTable
@@ -754,6 +808,9 @@ const DataTableComponent = ({
getRowIds={get_row_ids}
toggleDisplayHeader={toggleDisplayHeader}
chartsFeatureEnabled={chartsFeatureEnabled}
+ toggleSelectionPanel={toggleSelectionPanel}
+ isSelectionPanelOpen={isSelectionPanelOpen}
+ onFocusRowChange={(rowIdx) => setFocusedRowIdx(rowIdx)}
/>
</Labeled>
</ColumnChartContext.Provider>
diff --git a/frontend/src/plugins/impl/common/error-banner.tsx b/frontend/src/plugins/impl/common/error-banner.tsx
index 8c60002b1e..53f476516f 100644
--- a/frontend/src/plugins/impl/common/error-banner.tsx
+++ b/frontend/src/plugins/impl/common/error-banner.tsx
@@ -66,7 +66,7 @@ const bannerStyle = cva(
danger:
"text-error border-[var(--red-6)] shadow-mdSolid shadow-error bg-[var(--red-1)]",
info: "text-primary border-[var(--blue-6)] shadow-mdSolid shadow-accent bg-[var(--blue-1)]",
- warn: "text-warning border-[var(--yellow-6)] bg-[var(--yellow-2)]",
+ warn: "border-[var(--yellow-6)] bg-[var(--yellow-2)] dark:bg-[var(--yellow-4)] text-[var(--yellow-11)] dark:text-[var(--yellow-12)]",
},
clickable: {
true: "cursor-pointer",
diff --git a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
index 6f8c97500b..55d3780b3d 100644
--- a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
+++ b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
@@ -135,6 +135,7 @@ export const DataFramePlugin = createPlugin<S>("marimo-dataframe")
{...props.functions}
value={props.value}
setValue={props.setValue}
+ host={props.host}
/>
</TooltipProvider>
));
@@ -142,6 +143,7 @@ export const DataFramePlugin = createPlugin<S>("marimo-dataframe")
interface DataTableProps extends Data, PluginFunctions {
value: S;
setValue: (value: S) => void;
+ host: HTMLElement;
}
const EMPTY: Transformations = {
@@ -157,6 +159,7 @@ export const DataFrameComponent = memo(
get_dataframe,
get_column_values,
search,
+ host,
}: DataTableProps): JSX.Element => {
const { data, error, loading } = useAsyncData(
() => get_dataframe({}),
@@ -280,6 +283,7 @@ export const DataFrameComponent = memo(
setValue={Functions.NOOP}
selection={null}
lazy={false}
+ host={host}
/>
</div>
);
diff --git a/frontend/src/stories/dataframe.stories.tsx b/frontend/src/stories/dataframe.stories.tsx
index c963c4293d..6934d75067 100644
--- a/frontend/src/stories/dataframe.stories.tsx
+++ b/frontend/src/stories/dataframe.stories.tsx
@@ -39,6 +39,7 @@ export const DataFrame: StoryObj = {
}}
get_dataframe={() => Promise.reject(new Error("not implemented"))}
search={Functions.THROW}
+ host={document.body}
/>
);
},