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: add col filtering (#4531)

Shahmir Varqha9c072b7d64a4
diff --git a/frontend/src/components/data-table/column-header.tsx b/frontend/src/components/data-table/column-header.tsx
index 42afa0994f..0e600458b9 100644
--- a/frontend/src/components/data-table/column-header.tsx
+++ b/frontend/src/components/data-table/column-header.tsx
@@ -2,7 +2,7 @@
"use no memo";
import type { Column } from "@tanstack/react-table";
-import { FilterIcon, FilterX, MinusIcon, SearchIcon } from "lucide-react";
+import { FilterIcon, MinusIcon, SearchIcon, XIcon } from "lucide-react";
import { cn } from "@/utils/cn";
import {
@@ -17,7 +17,7 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "../ui/button";
-import { useRef, useState } from "react";
+import { useMemo, useRef, useState } from "react";
import { NumberField } from "../ui/number-field";
import { Input } from "../ui/input";
import { type ColumnFilterForType, Filter } from "./filters";
@@ -28,21 +28,45 @@ import {
renderCopyColumn,
renderDataType,
renderFormatOptions,
- renderSortIcon,
+ renderSortFilterIcon,
renderSorts,
+ FilterButtons,
+ ClearFilterMenuItem,
+ renderFilterByValues,
} from "./header-items";
+import type { CalculateTopKRows } from "@/plugins/impl/DataTablePlugin";
+import { useAsyncData } from "@/hooks/useAsyncData";
+import { ErrorBanner } from "@/plugins/impl/common/error-banner";
+import { Spinner } from "../icons/spinner";
+import { PopoverClose } from "../ui/popover";
+import { Logger } from "@/utils/Logger";
+import { Checkbox } from "../ui/checkbox";
+import {
+ Command,
+ CommandEmpty,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from "../ui/command";
+import { DraggablePopover } from "../ui/draggable-popover";
+
+const TOP_K_ROWS = 30;
interface DataTableColumnHeaderProps<TData, TValue>
extends React.HTMLAttributes<HTMLDivElement> {
column: Column<TData, TValue>;
header: React.ReactNode;
+ calculateTopKRows?: CalculateTopKRows;
}
export const DataTableColumnHeader = <TData, TValue>({
column,
header,
className,
+ calculateTopKRows,
}: DataTableColumnHeaderProps<TData, TValue>) => {
+ const [isFilterValueOpen, setIsFilterValueOpen] = useState(false);
+
// No header
if (!header) {
return null;
@@ -53,38 +77,53 @@ export const DataTableColumnHeader = <TData, TValue>({
return <div className={cn(className)}>{header}</div>;
}
+ const hasFilter = column.getFilterValue() !== undefined;
+ const hideIcon = !column.getIsSorted() && !hasFilter;
+
return (
- <DropdownMenu modal={false}>
- <DropdownMenuTrigger asChild={true}>
- <div
- className={cn(
- "group flex items-center my-1 space-between w-full select-none gap-2 border hover:border-border border-transparent hover:bg-[var(--slate-3)] data-[state=open]:bg-[var(--slate-3)] data-[state=open]:border-border rounded px-1 -mx-1",
- className,
- )}
- data-testid="data-table-sort-button"
- >
- <span className="flex-1">{header}</span>
- <span
+ <>
+ <DropdownMenu modal={false}>
+ <DropdownMenuTrigger asChild={true}>
+ <div
className={cn(
- "h-5 py-1 px-1",
- !column.getIsSorted() &&
- "invisible group-hover:visible data-[state=open]:visible",
+ "group flex items-center my-1 space-between w-full select-none gap-2 border hover:border-border border-transparent hover:bg-[var(--slate-3)] data-[state=open]:bg-[var(--slate-3)] data-[state=open]:border-border rounded px-1 -mx-1",
+ className,
)}
+ data-testid="data-table-sort-button"
>
- {renderSortIcon(column)}
- </span>
- </div>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start">
- {renderDataType(column)}
- {renderSorts(column)}
- {renderCopyColumn(column)}
- {renderColumnPinning(column)}
- {renderColumnWrapping(column)}
- {renderFormatOptions(column)}
- <DropdownMenuItemFilter column={column} />
- </DropdownMenuContent>
- </DropdownMenu>
+ <span className="flex-1">{header}</span>
+ <span
+ className={cn(
+ "h-5 py-1 px-1",
+ hideIcon &&
+ "invisible group-hover:visible data-[state=open]:visible",
+ )}
+ >
+ {renderSortFilterIcon(column)}
+ </span>
+ </div>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ {renderDataType(column)}
+ {renderSorts(column)}
+ {renderCopyColumn(column)}
+ {renderColumnPinning(column)}
+ {renderColumnWrapping(column)}
+ {renderFormatOptions(column)}
+ <DropdownMenuSeparator />
+ {renderMenuItemFilter(column)}
+ {renderFilterByValues(column, setIsFilterValueOpen)}
+ {hasFilter && <ClearFilterMenuItem column={column} />}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {isFilterValueOpen && (
+ <PopoverFilterByValues
+ setIsFilterValueOpen={setIsFilterValueOpen}
+ calculateTopKRows={calculateTopKRows}
+ column={column}
+ />
+ )}
+ </>
);
};
@@ -113,11 +152,9 @@ export const DataTableColumnHeaderWithSummary = <TData, TValue>({
);
};
-export const DropdownMenuItemFilter = <TData, TValue>({
- column,
-}: React.PropsWithChildren<{
- column: Column<TData, TValue>;
-}>) => {
+export function renderMenuItemFilter<TData, TValue>(
+ column: Column<TData, TValue>,
+) {
const canFilter = column.getCanFilter();
if (!canFilter) {
return null;
@@ -128,8 +165,6 @@ export const DropdownMenuItemFilter = <TData, TValue>({
return null;
}
- const hasFilter = column.getFilterValue() !== undefined;
-
const filterMenuItem = (
<DropdownMenuSubTrigger>
<FilterIcon className="mo-dropdown-icon" />
@@ -137,70 +172,51 @@ export const DropdownMenuItemFilter = <TData, TValue>({
</DropdownMenuSubTrigger>
);
- const clearFilterMenuItem = (
- <DropdownMenuItem onClick={() => column.setFilterValue(undefined)}>
- <FilterX className="mo-dropdown-icon" />
- Clear filter
- </DropdownMenuItem>
- );
-
if (filterType === "boolean") {
return (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuSub>
- {filterMenuItem}
- <DropdownMenuPortal>
- <DropdownMenuSubContent>
- <DropdownMenuItem
- onClick={() => column.setFilterValue(Filter.boolean(true))}
- >
- True
- </DropdownMenuItem>
- <DropdownMenuItem
- onClick={() => column.setFilterValue(Filter.boolean(false))}
- >
- False
- </DropdownMenuItem>
- </DropdownMenuSubContent>
- </DropdownMenuPortal>
- </DropdownMenuSub>
- {hasFilter && clearFilterMenuItem}
- </>
+ <DropdownMenuSub>
+ {filterMenuItem}
+ <DropdownMenuPortal>
+ <DropdownMenuSubContent>
+ <DropdownMenuItem
+ onClick={() => column.setFilterValue(Filter.boolean(true))}
+ >
+ True
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => column.setFilterValue(Filter.boolean(false))}
+ >
+ False
+ </DropdownMenuItem>
+ </DropdownMenuSubContent>
+ </DropdownMenuPortal>
+ </DropdownMenuSub>
);
}
if (filterType === "text") {
return (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuSub>
- {filterMenuItem}
- <DropdownMenuPortal>
- <DropdownMenuSubContent>
- <TextFilter column={column} />
- </DropdownMenuSubContent>
- </DropdownMenuPortal>
- </DropdownMenuSub>
- {hasFilter && clearFilterMenuItem}
- </>
+ <DropdownMenuSub>
+ {filterMenuItem}
+ <DropdownMenuPortal>
+ <DropdownMenuSubContent>
+ <TextFilter column={column} />
+ </DropdownMenuSubContent>
+ </DropdownMenuPortal>
+ </DropdownMenuSub>
);
}
if (filterType === "number") {
return (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuSub>
- {filterMenuItem}
- <DropdownMenuPortal>
- <DropdownMenuSubContent>
- <NumberRangeFilter column={column} />
- </DropdownMenuSubContent>
- </DropdownMenuPortal>
- </DropdownMenuSub>
- {hasFilter && clearFilterMenuItem}
- </>
+ <DropdownMenuSub>
+ {filterMenuItem}
+ <DropdownMenuPortal>
+ <DropdownMenuSubContent>
+ <NumberRangeFilter column={column} />
+ </DropdownMenuSubContent>
+ </DropdownMenuPortal>
+ </DropdownMenuSub>
);
}
@@ -226,7 +242,7 @@ export const DropdownMenuItemFilter = <TData, TValue>({
logNever(filterType);
return null;
-};
+}
const NumberRangeFilter = <TData, TValue>({
column,
@@ -259,6 +275,7 @@ const NumberRangeFilter = <TData, TValue>({
ref={minRef}
value={min}
onChange={(value) => setMin(value)}
+ aria-label="min"
placeholder="min"
onKeyDown={(e) => {
if (e.key === "Enter") {
@@ -275,6 +292,7 @@ const NumberRangeFilter = <TData, TValue>({
ref={maxRef}
value={max}
onChange={(value) => setMax(value)}
+ aria-label="max"
onKeyDown={(e) => {
if (e.key === "Enter") {
handleApply({ max: Number.parseFloat(e.currentTarget.value) });
@@ -287,24 +305,15 @@ const NumberRangeFilter = <TData, TValue>({
className="shadow-none! border-border hover:shadow-none!"
/>
</div>
- <div className="flex gap-2 px-2 justify-between">
- <Button variant="link" size="sm" onClick={() => handleApply()}>
- Apply
- </Button>
- <Button
- variant="linkDestructive"
- size="sm"
- disabled={!hasFilter}
- className=""
- onClick={() => {
- setMin(undefined);
- setMax(undefined);
- column.setFilterValue(undefined);
- }}
- >
- Clear
- </Button>
- </div>
+ <FilterButtons
+ onApply={handleApply}
+ onClear={() => {
+ setMin(undefined);
+ setMax(undefined);
+ column.setFilterValue(undefined);
+ }}
+ clearButtonDisabled={!hasFilter}
+ />
</div>
);
};
@@ -343,23 +352,177 @@ const TextFilter = <TData, TValue>({
}}
className="shadow-none! border-border hover:shadow-none!"
/>
- <div className="flex gap-2 px-2 justify-between">
- <Button variant="link" size="sm" onClick={() => handleApply()}>
- Apply
- </Button>
+ <FilterButtons
+ onApply={handleApply}
+ onClear={() => {
+ setValue("");
+ column.setFilterValue(undefined);
+ }}
+ clearButtonDisabled={!hasFilter}
+ />
+ </div>
+ );
+};
+
+const PopoverFilterByValues = <TData, TValue>({
+ setIsFilterValueOpen,
+ calculateTopKRows,
+ column,
+}: {
+ setIsFilterValueOpen: (open: boolean) => void;
+ calculateTopKRows?: CalculateTopKRows;
+ column: Column<TData, TValue>;
+}) => {
+ const [chosenValues, setChosenValues] = useState<unknown[]>([]);
+ const [query, setQuery] = useState<string>("");
+
+ const { data, loading, error } = useAsyncData(async () => {
+ if (!calculateTopKRows) {
+ return null;
+ }
+ const res = await calculateTopKRows({ column: column.id, k: TOP_K_ROWS });
+ return res.data;
+ }, []);
+
+ const filteredData = useMemo(() => {
+ if (!data) {
+ return [];
+ }
+
+ try {
+ return data.filter(([value, count]) => {
+ // Check if value exists and can be converted to string
+ // Keep null values for filtering
+ return value === undefined
+ ? false
+ : String(value).toLowerCase().includes(query.toLowerCase());
+ });
+ } catch (error_) {
+ Logger.error("Error filtering data", error_);
+ return [];
+ }
+ }, [data, query]);
+
+ let dataTable: React.ReactNode;
+
+ if (loading) {
+ dataTable = <Spinner size="medium" className="mx-auto mt-4" />;
+ }
+
+ if (error) {
+ dataTable = <ErrorBanner error={error} className="mt-4" />;
+ }
+
+ const handleCheckboxClick = (checked: boolean, value: unknown) => {
+ if (!checked) {
+ setChosenValues(chosenValues.filter((v) => v !== value));
+ return;
+ }
+ setChosenValues([...chosenValues, value]);
+ };
+
+ const toggleAllCheckbox = (checked: boolean) => {
+ if (!data) {
+ return;
+ }
+ if (checked) {
+ setChosenValues(filteredData.map(([value]) => value));
+ } else {
+ setChosenValues([]);
+ }
+ };
+
+ const handleApply = () => {
+ if (chosenValues.length === 0) {
+ column.setFilterValue(undefined);
+ return;
+ }
+ column.setFilterValue(Filter.select(chosenValues));
+ };
+
+ if (data) {
+ dataTable = (
+ <>
+ <Command className="text-sm" shouldFilter={false}>
+ <CommandInput
+ placeholder="Search"
+ autoFocus={true}
+ onValueChange={(value) => setQuery(value.trim())}
+ />
+ <CommandEmpty>No results found.</CommandEmpty>
+ <CommandList>
+ <CommandItem className="border-b">
+ <Checkbox
+ checked={chosenValues.length === filteredData.length}
+ onCheckedChange={(checked) => {
+ if (typeof checked === "string") {
+ return;
+ }
+ toggleAllCheckbox(checked);
+ }}
+ aria-label="Select all"
+ className="mr-3 h-3.5 w-3.5"
+ />
+ <span className="font-bold flex-1">{column.id}</span>
+ <span className="font-bold">count</span>
+ </CommandItem>
+ {filteredData.map((row, rowIndex) => {
+ const value = row[0];
+ const count = row[1];
+ return (
+ <CommandItem key={rowIndex} className="border-b">
+ <Checkbox
+ checked={chosenValues.includes(value)}
+ onCheckedChange={(checked) => {
+ if (typeof checked === "string") {
+ return;
+ }
+ handleCheckboxClick(checked, value);
+ }}
+ aria-label="Select row"
+ className="mr-3 h-3.5 w-3.5"
+ />
+ <span className="flex-1 overflow-hidden max-h-20 line-clamp-3">
+ {String(value)}
+ </span>
+ <span className="ml-3">{count}</span>
+ </CommandItem>
+ );
+ })}
+ </CommandList>
+ {filteredData.length === TOP_K_ROWS && (
+ <span className="text-xs text-muted-foreground mt-1.5 text-center">
+ Only showing top {TOP_K_ROWS} rows
+ </span>
+ )}
+ </Command>
+ <FilterButtons
+ onApply={handleApply}
+ onClear={() => {
+ setChosenValues([]);
+ }}
+ clearButtonDisabled={chosenValues.length === 0}
+ />
+ </>
+ );
+ }
+
+ return (
+ <DraggablePopover
+ open={true}
+ onOpenChange={(open) => !open && setIsFilterValueOpen(false)}
+ className="w-80 p-0"
+ >
+ <PopoverClose className="absolute top-2 right-2">
<Button
- variant="linkDestructive"
+ variant="link"
size="sm"
- disabled={!hasFilter}
- className=""
- onClick={() => {
- setValue("");
- column.setFilterValue(undefined);
- }}
+ onClick={() => setIsFilterValueOpen(false)}
>
- Clear
+ <XIcon className="h-4 w-4" />
</Button>
- </div>
- </div>
+ </PopoverClose>
+ <div className="flex flex-col gap-1.5 p-4">{dataTable}</div>
+ </DraggablePopover>
);
};
diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsx
index fbb8d04098..448b115711 100644
--- a/frontend/src/components/data-table/columns.tsx
+++ b/frontend/src/components/data-table/columns.tsx
@@ -2,10 +2,7 @@
"use no memo";
import type { ColumnDef } from "@tanstack/react-table";
-import {
- DataTableColumnHeader,
- DataTableColumnHeaderWithSummary,
-} from "./column-header";
+import { DataTableColumnHeader } from "./column-header";
import { Checkbox } from "../ui/checkbox";
import { getMimeValues, MimeCell } from "./mime-cell";
import type { DataType } from "@/core/kernel/messages";
@@ -30,6 +27,7 @@ import { EmotionCacheProvider } from "../editor/output/EmotionCacheProvider";
import { PopoverClose } from "@radix-ui/react-popover";
import { Button } from "../ui/button";
import type { ColumnChartSpecModel } from "./chart-spec-model";
+import type { CalculateTopKRows } from "@/plugins/impl/DataTablePlugin";
// Artificial limit to display long strings
const MAX_STRING_LENGTH = 50;
@@ -102,6 +100,7 @@ export function generateColumns<T>({
textJustifyColumns,
wrappedColumns,
showDataTypes,
+ calculateTopKRows,
}: {
rowHeaders: string[];
selection: DataTableSelection;
@@ -110,6 +109,7 @@ export function generateColumns<T>({
textJustifyColumns?: Record<string, "left" | "center" | "right">;
wrappedColumns?: string[];
showDataTypes?: boolean;
+ calculateTopKRows?: CalculateTopKRows;
}): Array<ColumnDef<T>> {
const rowHeadersSet = new Set(rowHeaders);
@@ -179,20 +179,24 @@ export function generateColumns<T>({
</div>
);
+ const dataTableColumnHeader = (
+ <DataTableColumnHeader
+ header={headerWithType}
+ column={column}
+ calculateTopKRows={calculateTopKRows}
+ />
+ );
+
// Row headers have no summaries
if (rowHeadersSet.has(key)) {
- return (
- <DataTableColumnHeader header={headerWithType} column={column} />
- );
+ return dataTableColumnHeader;
}
return (
- <DataTableColumnHeaderWithSummary
- key={key}
- header={headerWithType}
- column={column}
- summary={<TableColumnSummary columnId={key} />}
- />
+ <div className="flex flex-col h-full pt-0.5 pb-3 justify-between items-start">
+ {dataTableColumnHeader}
+ <TableColumnSummary columnId={key} />
+ </div>
);
},
diff --git a/frontend/src/components/data-table/filter-pills.tsx b/frontend/src/components/data-table/filter-pills.tsx
index 82330a656c..80ab6b91c5 100644
--- a/frontend/src/components/data-table/filter-pills.tsx
+++ b/frontend/src/components/data-table/filter-pills.tsx
@@ -28,7 +28,7 @@ export const FilterPills = <TData,>({ filters, table }: Props<TData>) => {
}
return (
- <Badge key={filter.id} variant="secondary">
+ <Badge key={filter.id} variant="secondary" className="dark:invert">
{filter.id} {formattedValue}{" "}
<span
className="cursor-pointer opacity-60 hover:opacity-100 pl-1 py-[2px]"
diff --git a/frontend/src/components/data-table/filters.ts b/frontend/src/components/data-table/filters.ts
index ca0d058f9c..d9930ecc43 100644
--- a/frontend/src/components/data-table/filters.ts
+++ b/frontend/src/components/data-table/filters.ts
@@ -64,7 +64,7 @@ export const Filter = {
value,
} as const;
},
- select(options: string[]) {
+ select(options: unknown[]) {
return {
type: "select",
options,
diff --git a/frontend/src/components/data-table/header-items.tsx b/frontend/src/components/data-table/header-items.tsx
index 2bb15cfc70..caec5f0dd1 100644
--- a/frontend/src/components/data-table/header-items.tsx
+++ b/frontend/src/components/data-table/header-items.tsx
@@ -20,11 +20,16 @@ import {
PinOffIcon,
CopyIcon,
ChevronsUpDown,
- ArrowDownNarrowWideIcon,
ArrowDownWideNarrowIcon,
+ BlendIcon,
+ FilterX,
+ ArrowUpNarrowWideIcon,
+ ListFilterPlusIcon,
+ FunnelPlusIcon,
} from "lucide-react";
import { copyToClipboard } from "@/utils/copy";
import { NAMELESS_COLUMN_PREFIX } from "./columns";
+import { Button } from "../ui/button";
export function renderFormatOptions<TData, TValue>(
column: Column<TData, TValue>,
@@ -150,7 +155,7 @@ export function renderCopyColumn<TData, TValue>(column: Column<TData, TValue>) {
);
}
-const AscIcon = ArrowDownNarrowWideIcon;
+const AscIcon = ArrowUpNarrowWideIcon;
const DescIcon = ArrowDownWideNarrowIcon;
export function renderSorts<TData, TValue>(column: Column<TData, TValue>) {
@@ -179,20 +184,28 @@ export function renderSorts<TData, TValue>(column: Column<TData, TValue>) {
);
}
-export function renderSortIcon<TData, TValue>(column: Column<TData, TValue>) {
+export function renderSortFilterIcon<TData, TValue>(
+ column: Column<TData, TValue>,
+) {
if (!column.getCanSort()) {
return null;
}
const isSorted = column.getIsSorted();
+ const isFiltered = column.getFilterValue() !== undefined;
- return isSorted === "desc" ? (
- <DescIcon className="h-3 w-3" />
- ) : isSorted === "asc" ? (
- <AscIcon className="h-3 w-3" />
- ) : (
- <ChevronsUpDown className="h-3 w-3" />
- );
+ let Icon: React.FC<React.SVGProps<SVGSVGElement>>;
+ if (isFiltered && isSorted) {
+ Icon = ListFilterPlusIcon;
+ } else if (isFiltered) {
+ Icon = FunnelPlusIcon;
+ } else if (isSorted) {
+ Icon = isSorted === "desc" ? DescIcon : AscIcon;
+ } else {
+ Icon = ChevronsUpDown;
+ }
+
+ return <Icon className="h-3 w-3" />;
}
export function renderDataType<TData, TValue>(column: Column<TData, TValue>) {
@@ -210,3 +223,72 @@ export function renderDataType<TData, TValue>(column: Column<TData, TValue>) {
</>
);
}
+
+export const ClearFilterMenuItem = <TData, TValue>({
+ column,
+}: {
+ column: Column<TData, TValue>;
+}) => (
+ <DropdownMenuItem onClick={() => column.setFilterValue(undefined)}>
+ <FilterX className="mo-dropdown-icon" />
+ Clear filter
+ </DropdownMenuItem>
+);
+
+export function renderFilterByValues<TData, TValue>(
+ column: Column<TData, TValue>,
+ setIsFilterValueOpen: (open: boolean) => void,
+) {
+ const canFilter = column.getCanFilter();
+ if (!canFilter) {
+ return null;
+ }
+
+ const columnType = column.columnDef.meta?.dataType;
+ // skip boolean as this can be easily filtered through normal filters
+ if (columnType === "boolean") {
+ return null;
+ }
+
+ // there is not yet good support for filtering on lists, dicts, etc.
+ const filterType = column.columnDef.meta?.filterType;
+ if (!filterType) {
+ return null;
+ }
+
+ return (
+ <DropdownMenuSub>
+ <DropdownMenuItem onClick={() => setIsFilterValueOpen(true)}>
+ <BlendIcon className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" />
+ Filter by values
+ </DropdownMenuItem>
+ </DropdownMenuSub>
+ );
+}
+
+export const FilterButtons = ({
+ onApply,
+ onClear,
+ clearButtonDisabled,
+}: {
+ onApply: () => void;
+ onClear: () => void;
+ clearButtonDisabled?: boolean;
+}) => {
+ return (
+ <div className="flex gap-2 px-2 justify-between">
+ <Button variant="link" size="sm" onClick={onApply}>
+ Apply
+ </Button>
+ <Button
+ variant="linkDestructive"
+ size="sm"
+ className=""
+ onClick={onClear}
+ disabled={clearButtonDisabled}
+ >
+ Clear
+ </Button>
+ </div>
+ );
+};
diff --git a/frontend/src/components/ui/draggable-popover.tsx b/frontend/src/components/ui/draggable-popover.tsx
new file mode 100644
index 0000000000..ad91f51749
--- /dev/null
+++ b/frontend/src/components/ui/draggable-popover.tsx
@@ -0,0 +1,68 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { useRef, useState } from "react";
+import { Popover, PopoverContent, PopoverTrigger } from "./popover";
+import { GripHorizontalIcon } from "lucide-react";
+import type * as PopoverPrimitive from "@radix-ui/react-popover";
+
+interface DraggablePopoverProps extends PopoverPrimitive.PopoverProps {
+ children: React.ReactNode;
+ className?: string;
+}
+
+export const DraggablePopover = ({
+ children,
+ className,
+ ...props
+}: DraggablePopoverProps) => {
+ const [position, setPosition] = useState({ x: 0, y: 0 });
+ const dragStartPos = useRef({ x: 0, y: 0 });
+ const [isDragging, setIsDragging] = useState(false);
+
+ const handleMouseDown = (e: React.MouseEvent) => {
+ dragStartPos.current = {
+ x: e.clientX - position.x,
+ y: e.clientY - position.y,
+ };
+ setIsDragging(true);
+ document.addEventListener("mousemove", handleMouseMove);
+ document.addEventListener("mouseup", handleMouseUp);
+ };
+
+ const handleMouseMove = (e: MouseEvent) => {
+ setPosition({
+ x: e.clientX - dragStartPos.current.x,
+ y: e.clientY - dragStartPos.current.y,
+ });
+ };
+
+ const handleMouseUp = () => {
+ setIsDragging(false);
+ document.removeEventListener("mousemove", handleMouseMove);
+ document.removeEventListener("mouseup", handleMouseUp);
+ };
+
+ return (
+ <Popover {...props}>
+ <PopoverTrigger />
+ <PopoverContent
+ className={className}
+ style={{
+ position: "fixed",
+ left: position.x,
+ top: position.y,
+ }}
+ >
+ <div
+ onMouseDown={handleMouseDown}
+ className={`flex items-center justify-center absolute top-0 left-1/2 -translate-x-1/2 ${
+ isDragging ? "cursor-grabbing" : "cursor-grab"
+ }`}
+ >
+ <GripHorizontalIcon className="h-5 w-5 mt-1 text-muted-foreground/40" />
+ </div>
+ {children}
+ </PopoverContent>
+ </Popover>
+ );
+};
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index c8fdc22a80..6570db3edb 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -50,8 +50,8 @@ import {
filterToFilterCondition,
type ColumnFilterValue,
} from "@/components/data-table/filters";
-import { vegaLoadData } from "./vega/loader";
import { isStaticNotebook } from "@/core/static/static-state";
+import { vegaLoadData } from "./vega/loader";
type CsvURL = string;
type TableData<T> = T[] | CsvURL;
@@ -72,6 +72,13 @@ export type GetDataUrl = (opts: {}) => Promise<{
format: "csv" | "json" | "arrow";
}>;
+export type CalculateTopKRows = <T>(req: {
+ column: string;
+ k: number;
+}) => Promise<{
+ data: Array<[unknown, number]>;
+}>;
+
/**
* Arguments for a data table
*
@@ -119,6 +126,7 @@ type DataTableFunctions = {
}>;
get_data_url?: GetDataUrl;
get_row_ids?: GetRowIds;
+ calculate_top_k_rows?: CalculateTopKRows;
};
type S = Array<number | string | { rowId: string; columnName?: string }>;
@@ -226,6 +234,13 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")
format: z.enum(["csv", "json", "arrow"]),
}),
),
+ calculate_top_k_rows: rpc
+ .input(z.object({ column: z.string(), k: z.number() }))
+ .output(
+ z.object({
+ data: z.array(z.tuple([z.any(), z.number()])),
+ }),
+ ),
})
.renderer((props) => {
return (
@@ -287,6 +302,8 @@ interface DataTableProps<T> extends Data<T>, DataTableFunctions {
chartsFeatureEnabled?: boolean;
}
+export type SetFilters = OnChangeFn<ColumnFiltersState>;
+
interface DataTableSearchProps {
// Pagination
paginationState: PaginationState;
@@ -300,7 +317,7 @@ interface DataTableSearchProps {
reloading: boolean;
// Filters
filters?: ColumnFiltersState;
- setFilters?: OnChangeFn<ColumnFiltersState>;
+ setFilters?: SetFilters;
hasStableRowId: boolean;
}
@@ -403,7 +420,6 @@ 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 {
@@ -575,6 +591,7 @@ const DataTableComponent = ({
cellStyles,
toggleDisplayHeader,
chartsFeatureEnabled,
+ calculate_top_k_rows,
}: DataTableProps<unknown> &
DataTableSearchProps & {
data: unknown[];
@@ -618,6 +635,7 @@ const DataTableComponent = ({
wrappedColumns: memoizedWrappedColumns,
// Only show data types if they are explicitly set
showDataTypes: showDataTypes,
+ calculateTopKRows: calculate_top_k_rows,
}),
[
selection,
@@ -627,6 +645,7 @@ const DataTableComponent = ({
memoizedFieldTypes,
memoizedTextJustifyColumns,
memoizedWrappedColumns,
+ calculate_top_k_rows,
],
);
diff --git a/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.py b/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.py
index 7b1f2e61be..45ac51967a 100644
--- a/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.py
+++ b/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.py
@@ -321,7 +321,11 @@ class PolarsTransformHandler(TransformHandler["pl.DataFrame"]):
elif condition.operator == "ends_with":
condition_expr = column.str.ends_with(value_str)
elif condition.operator == "in":
- condition_expr = column.is_in(value or [])
+ # is_in doesn't support None values, so we need to handle them separately
+ if value is not None and None in value:
+ condition_expr = column.is_in(value) | column.is_null()
+ else:
+ condition_expr = column.is_in(value or [])
else:
assert_never(condition.operator)
@@ -551,7 +555,13 @@ class IbisTransformHandler(TransformHandler["ibis.Table"]):
elif condition.operator == "ends_with":
filter_conditions.append(column.endswith(value))
elif condition.operator == "in":
- filter_conditions.append(column.isin(value))
+ # is_in doesn't support None values, so we need to handle them separately
+ if value is not None and None in value:
+ filter_conditions.append(
+ column.isnull() | column.isin(value)
+ )
+ else:
+ filter_conditions.append(column.isin(value))
else:
assert_never(condition.operator)
diff --git a/marimo/_plugins/ui/_impl/dataframes/transforms/types.py b/marimo/_plugins/ui/_impl/dataframes/transforms/types.py
index d2b6164e96..7fbbe1e59a 100644
--- a/marimo/_plugins/ui/_impl/dataframes/transforms/types.py
+++ b/marimo/_plugins/ui/_impl/dataframes/transforms/types.py
@@ -74,9 +74,16 @@ class Condition:
def __post_init__(self) -> None:
if self.operator == "in":
- assert isinstance(self.value, list), (
- "value must be a list for 'in' operator"
- )
+ if isinstance(self.value, list):
+ # Hack to convert to tuple for frozen dataclass
+ # Only tuples can be hashed
+ object.__setattr__(self, "value", tuple(self.value))
+ elif isinstance(self.value, tuple):
+ pass
+ else:
+ raise ValueError(
+ "value must be a list or tuple for 'in' operator"
+ )
@dataclass
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index 9e79041421..f4d8690622 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -136,6 +136,17 @@ class GetDataUrlResponse:
format: Literal["csv", "json", "arrow"]
+@dataclass
+class CalculateTopKRowsArgs:
+ column: ColumnName
+ k: int
+
+
+@dataclass
+class CalculateTopKRowsResponse:
+ data: list[tuple[str, int]]
+
+
def get_default_table_page_size() -> int:
"""Get the default number of rows to display in a table."""
try:
@@ -626,6 +637,11 @@ class table(
arg_cls=EmptyArgs,
function=self._get_data_url,
),
+ Function(
+ name="calculate_top_k_rows",
+ arg_cls=CalculateTopKRowsArgs,
+ function=self._calculate_top_k_rows,
+ ),
),
)
@@ -849,6 +865,21 @@ class table(
return result
+ def _calculate_top_k_rows(
+ self, args: CalculateTopKRowsArgs
+ ) -> CalculateTopKRowsResponse:
+ """Calculate the top k rows in the table, grouped by column.
+ Returns a table of the top k rows, grouped by column with the count.
+ """
+ column, k = args.column, args.k
+ try:
+ data = self._searched_manager.calculate_top_k_rows(column, k)
+ return CalculateTopKRowsResponse(data=data)
+ # Some libs will panic like Polars, which are only caught with BaseException
+ except BaseException as e:
+ LOGGER.error("Failed to calculate top k rows: %s", e)
+ return CalculateTopKRowsResponse(data=[])
+
def _style_cells(self, skip: int, take: int) -> Optional[CellStyles]:
"""Calculate the styling of the cells in the table."""
if self._style_cell is None:
diff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.py
index a62e11a4e6..737929dcad 100644
--- a/marimo/_plugins/ui/_impl/tables/default_table.py
+++ b/marimo/_plugins/ui/_impl/tables/default_table.py
@@ -1,6 +1,8 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import functools
+from collections import defaultdict
from collections.abc import Sequence
from typing import Any, Optional, Union, cast
@@ -261,6 +263,51 @@ class DefaultTableManager(TableManager[JsonTableData]):
def get_row_headers(self) -> list[str]:
return []
+ @functools.lru_cache(maxsize=5) # noqa: B019
+ def calculate_top_k_rows(
+ self, column: ColumnName, k: int
+ ) -> list[tuple[Any, int]]:
+ column_names = self.get_column_names()
+ if column not in column_names:
+ raise ValueError(f"Column {column} not found in table.")
+
+ grouped: dict[str, int] = defaultdict(int)
+ if isinstance(self.data, dict):
+ if self.is_column_oriented:
+ # Handle column-oriented data
+ for value in cast(list[Any], self.data[column]):
+ grouped[value] += 1
+ else:
+ # In this case, the data is a dict of key-value pairs
+ # where the key is the row identifier and the value is the data
+ for key, value in self.data.items():
+ if column == KEY:
+ grouped[key] += 1
+ elif column == VALUE:
+ grouped[value] += 1
+ else:
+ # Handle row-oriented data
+ for row in self.data:
+ if isinstance(row, dict) and column in row:
+ grouped[row[column]] += 1
+
+ sorted_grouped = sorted(
+ grouped.items(), key=lambda x: x[1], reverse=True
+ )
+ top_k = sorted_grouped[:k]
+
+ chosen_column_name = None
+ for column_name in ["count", "number of rows", "count of rows"]:
+ if column_name not in column_names:
+ chosen_column_name = column_name
+ break
+ if chosen_column_name is None:
+ raise ValueError(
+ "Cannot specify a count column name, please rename your column"
+ )
+
+ return [(value, count) for value, count in top_k]
+
def get_field_type(
self, column_name: str
) -> tuple[FieldType, ExternalDataType]:
diff --git a/marimo/_plugins/ui/_impl/tables/ibis_table.py b/marimo/_plugins/ui/_impl/tables/ibis_table.py
index 718517e92e..b1e859005b 100644
--- a/marimo/_plugins/ui/_impl/tables/ibis_table.py
+++ b/marimo/_plugins/ui/_impl/tables/ibis_table.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import functools
from typing import Any, Optional
from marimo._data.models import (
@@ -194,6 +195,24 @@ class IbisTableManagerFactory(TableManagerFactory):
)
return IbisTableManager(sorted_data)
+ @functools.lru_cache(maxsize=5) # noqa: B019
+ def calculate_top_k_rows(
+ self, column: ColumnName, k: int
+ ) -> list[tuple[Any, int]]:
+ count_col_name = f"{column}_count"
+ result = (
+ self.data[[column]]
+ .value_counts(name=count_col_name)
+ .order_by(ibis.desc(count_col_name))
+ .limit(k)
+ .execute()
+ )
+
+ return [
+ (row[0], int(row[1]))
+ for row in result.itertuples(index=False)
+ ]
+
def get_field_type(
self, column_name: str
) -> tuple[FieldType, ExternalDataType]:
diff --git a/marimo/_plugins/ui/_impl/tables/narwhals_table.py b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
index 9855d377d0..8e5041f59a 100644
--- a/marimo/_plugins/ui/_impl/tables/narwhals_table.py
+++ b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import functools
import io
from functools import cached_property
from typing import Any, Optional, Union, cast
@@ -159,6 +160,49 @@ class NarwhalsTableManager(
) -> list[str]:
return []
+ @functools.lru_cache(maxsize=5) # noqa: B019
+ def calculate_top_k_rows(
+ self, column: ColumnName, k: int
+ ) -> list[tuple[Any, int]]:
+ if isinstance(self.data, nw.LazyFrame):
+ raise ValueError(
+ "Cannot calculate top k rows for lazy frames, please collect the data first"
+ )
+
+ columns = self.get_column_names()
+
+ if column not in columns:
+ raise ValueError(f"Column {column} not found in table.")
+
+ # Find a column name for the count that doesn't conflict with existing columns
+ chosen_column_name: str | None = None
+ for col in ["count", f"count of {column}", "num_rows"]:
+ if col not in columns:
+ chosen_column_name = col
+ break
+ if chosen_column_name is None:
+ raise ValueError(
+ "Cannot specify a count column name, please rename your column"
+ )
+
+ # column is also sorted to ensure nulls are last
+ result = (
+ self.data.group_by(column)
+ .agg(nw.len().alias(chosen_column_name))
+ .sort(
+ [chosen_column_name, column], descending=True, nulls_last=True
+ )
+ .head(k)
+ )
+
+ return [
+ (
+ unwrap_py_scalar(row[column]),
+ int(unwrap_py_scalar(row[chosen_column_name])),
+ )
+ for row in result.iter_rows(named=True)
+ ]
+
@staticmethod
def is_type(value: Any) -> bool:
return can_narwhalify(value)
diff --git a/marimo/_plugins/ui/_impl/tables/table_manager.py b/marimo/_plugins/ui/_impl/tables/table_manager.py
index 858d74ce18..92e6b3603f 100644
--- a/marimo/_plugins/ui/_impl/tables/table_manager.py
+++ b/marimo/_plugins/ui/_impl/tables/table_manager.py
@@ -193,6 +193,12 @@ class TableManager(abc.ABC, Generic[T]):
def get_sample_values(self, column: str) -> list[Any]:
pass
+ @abc.abstractmethod
+ def calculate_top_k_rows(
+ self, column: ColumnName, k: int
+ ) -> list[tuple[Any, int]]:
+ pass
+
def __repr__(self) -> str:
rows = self.get_num_rows(force=False)
columns = self.get_num_columns()
diff --git a/tests/_plugins/ui/_impl/dataframes/test_handlers.py b/tests/_plugins/ui/_impl/dataframes/test_handlers.py
index b88ebb2cd6..c5c69a4e03 100644
--- a/tests/_plugins/ui/_impl/dataframes/test_handlers.py
+++ b/tests/_plugins/ui/_impl/dataframes/test_handlers.py
@@ -443,6 +443,72 @@ class TestTransformHandler:
result = apply(df, transform)
assert_frame_equal(result, expected)
+ @staticmethod
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
+ pd.DataFrame({"A": [1, 2], "B": [4, 5]}),
+ ),
+ (
+ pl.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
+ pl.DataFrame({"A": [1, 2], "B": [4, 5]}),
+ ),
+ (
+ ibis.memtable({"A": [1, 2, 3], "B": [4, 5, 6]}),
+ ibis.memtable({"A": [1, 2], "B": [4, 5]}),
+ ),
+ ],
+ )
+ def test_filter_rows_in_operator(
+ df: DataFrameType, expected: DataFrameType
+ ) -> None:
+ transform = FilterRowsTransform(
+ type=TransformType.FILTER_ROWS,
+ operation="keep_rows",
+ where=[Condition(column_id="A", operator="in", value=[1, 2])],
+ )
+ result = apply(df, transform)
+ assert_frame_equal(result, expected)
+
+ @staticmethod
+ @pytest.mark.parametrize(
+ ("df", "expected"),
+ [
+ (
+ pd.DataFrame({"A": [1, 2, None], "B": [4, 5, 6]}),
+ pd.DataFrame({"A": [np.nan], "B": [6]}),
+ ),
+ (
+ pl.DataFrame({"A": [1, 2, None], "B": [4, 5, 6]}),
+ pl.DataFrame({"A": [None], "B": [6]}).with_columns(
+ pl.col("A").cast(pl.Int64)
+ ),
+ ),
+ (
+ ibis.memtable(
+ {"A": [1, 2, None], "B": [4, 5, 6]},
+ schema={"A": "int64", "B": "int64"},
+ ),
+ ibis.memtable(
+ {"A": [None], "B": [6]},
+ schema={"A": "int64", "B": "int64"},
+ ),
+ ),
+ ],
+ )
+ def test_filter_rows_in_operator_null_rows(
+ df: DataFrameType, expected: DataFrameType
+ ) -> None:
+ transform = FilterRowsTransform(
+ type=TransformType.FILTER_ROWS,
+ operation="keep_rows",
+ where=[Condition(column_id="A", operator="in", value=[None])],
+ )
+ result = apply(df, transform)
+ assert_frame_equal(result, expected)
+
@staticmethod
@pytest.mark.parametrize(
("df", "expected"),
diff --git a/tests/_plugins/ui/_impl/tables/test_default_table.py b/tests/_plugins/ui/_impl/tables/test_default_table.py
index b2a802286c..2d73a88671 100644
--- a/tests/_plugins/ui/_impl/tables/test_default_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_default_table.py
@@ -347,6 +347,37 @@ class TestDefaultTable(unittest.TestCase):
]
assert formatted_manager == expected_data
+ def test_calculate_top_k_rows(self) -> None:
+ data = [
+ {"name": "Alice", "score": 46, "grade": "A"},
+ {"name": "Bob", "score": 85, "grade": "A"},
+ {"name": "Charlie", "score": 32, "grade": None},
+ ]
+ manager = DefaultTableManager(data)
+ result = manager.calculate_top_k_rows("grade", 10)
+ expected_data = [("A", 2), (None, 1)]
+ assert result == expected_data
+
+ # test with single value and conflicting column name
+ data = [{"name": "Alice", "age": 31, "count": date(1994, 5, 24)}]
+ manager = DefaultTableManager(data)
+ result = manager.calculate_top_k_rows("count", 10)
+ expected_data = [(date(1994, 5, 24), 1)]
+ assert result == expected_data
+
+ def test_calculate_top_k_rows_nulls(self) -> None:
+ data = [
+ {"name": "Alice", "age": 31, "birth_year": date(1994, 5, 24)},
+ {"name": "Bob", "age": 25, "birth_year": None},
+ {"name": "Charlie", "age": 35, "birth_year": None},
+ {"name": "Dave", "age": 28, "birth_year": date(1994, 5, 24)},
+ ]
+ manager = DefaultTableManager(data)
+ result = manager.calculate_top_k_rows("birth_year", 10)
+ # Nulls should be sorted to the end
+ expected_data = [(date(1994, 5, 24), 2), (None, 2)]
+ assert result == expected_data
+
class TestColumnarDefaultTable(unittest.TestCase):
def setUp(self) -> None:
@@ -662,6 +693,36 @@ class TestColumnarDefaultTable(unittest.TestCase):
}
assert formatted_manager == expected_data
+ def test_calculate_top_k_rows(self) -> None:
+ data = {
+ "grade": ["A", "A", None],
+ "name": ["Alice", "Bob", "Charlie"],
+ }
+ manager = DefaultTableManager(data)
+ result = manager.calculate_top_k_rows("grade", 10)
+ expected_data = [
+ ("A", 2),
+ (None, 1),
+ ]
+ assert result == expected_data
+
+ # Single value
+ data = {"grade": ["A", "A", "A"]}
+ manager = DefaultTableManager(data)
+ result = manager.calculate_top_k_rows("grade", 10)
+ expected_data = [("A", 3)]
+ assert result == expected_data
+
+ def test_calculate_top_k_rows_nulls(self) -> None:
+ data = {"grade": ["A", "A", None, None]}
+ manager = DefaultTableManager(data)
+ result = manager.calculate_top_k_rows("grade", 10)
+ expected_data = [
+ ("A", 2),
+ (None, 2),
+ ]
+ assert result == expected_data
+
@pytest.mark.skipif(
not HAS_DEPS, reason="optional dependencies not installed"
)
@@ -869,6 +930,24 @@ class TestDictionaryDefaultTable(unittest.TestCase):
]
assert formatted_data == expected_data
+ def test_calculate_top_k_rows(self) -> None:
+ data = {"grade": "A", "name": "Alice", "another_grade": "A"}
+ manager = DefaultTableManager(data)
+ result = manager.calculate_top_k_rows("value", 10)
+ expected_data = [("A", 2), ("Alice", 1)]
+ assert result == expected_data
+
+ result = manager.calculate_top_k_rows("key", 10)
+ expected_data = [("grade", 1), ("name", 1), ("another_grade", 1)]
+ assert result == expected_data
+
+ def test_calculate_top_k_rows_nulls(self) -> None:
+ data = {"grade": "A", "name": None, "another_grade": None}
+ manager = DefaultTableManager(data)
+ result = manager.calculate_top_k_rows("value", 10)
+ expected_data = [(None, 2), ("A", 1)]
+ assert result == expected_data
+
@pytest.mark.skipif(
not HAS_DEPS, reason="optional dependencies not installed"
)
diff --git a/tests/_plugins/ui/_impl/tables/test_ibis_table.py b/tests/_plugins/ui/_impl/tables/test_ibis_table.py
index c2e1153393..cf024964a6 100644
--- a/tests/_plugins/ui/_impl/tables/test_ibis_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_ibis_table.py
@@ -336,3 +336,49 @@ class TestIbisTableManagerFactory(unittest.TestCase):
3.0,
]
assert np.isnan(sorted_data[3])
+
+ def test_calculate_top_k_rows(self) -> None:
+ import ibis
+
+ table = ibis.memtable({"A": [2, 3, 3], "B": ["a", "b", "c"]})
+ manager = self.factory.create()(table)
+ result = manager.calculate_top_k_rows("A", 10)
+ assert result == [(3, 2), (2, 1)]
+
+ # Test equal counts with k limit
+ table = ibis.memtable({"A": [1, 1, 2, 2, 3]})
+ manager = self.factory.create()(table)
+ result = manager.calculate_top_k_rows("A", 2)
+ assert len(result) == 2
+ assert {(1, 2), (2, 2)} == set(result)
+ assert all(count == 2 for _, count in result)
+
+ def test_calculate_top_k_rows_nulls(self) -> None:
+ import ibis
+ import pandas as pd
+
+ # Test single null value
+ table = ibis.memtable({"A": [3, None, None]})
+ manager = self.factory.create()(table)
+ result = manager.calculate_top_k_rows("A", 10)
+ assert len(result) == 2
+ assert result[1] == (3, 1)
+ assert pd.isna(result[0][0])
+ assert result[0][1] == 2
+
+ # Test all null values
+ table = ibis.memtable({"A": [None, None, None]})
+ manager = self.factory.create()(table)
+ result = manager.calculate_top_k_rows("A", 10)
+ assert len(result) == 1
+ assert pd.isna(result[0][0])
+ assert result[0][1] == 3
+
+ # Test mixed values with nulls
+ table = ibis.memtable({"A": [1, None, 2, None, 3, None]})
+ manager = self.factory.create()(table)
+ result = manager.calculate_top_k_rows("A", 10)
+ assert len(result) == 4
+ assert pd.isna(result[0][0])
+ assert result[0][1] == 3
+ assert set(result[1:]) == {(1, 1), (2, 1), (3, 1)}
diff --git a/tests/_plugins/ui/_impl/tables/test_narwhals.py b/tests/_plugins/ui/_impl/tables/test_narwhals.py
index fac64ab6f0..3ff7ab49bc 100644
--- a/tests/_plugins/ui/_impl/tables/test_narwhals.py
+++ b/tests/_plugins/ui/_impl/tables/test_narwhals.py
@@ -995,6 +995,79 @@ def test_get_sample_values(df: Any) -> None:
assert sample_values == ["b'bytes1'", "b'bytes2'", "b'bytes3'"]
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+ "df",
+ create_dataframes(
+ {
+ "A": [1, 2, 3, 3, None, None],
+ "B": [4, 5, 6, 6, None, None],
+ },
+ include=["pandas", "polars"],
+ ),
+)
+def test_calculate_top_k_rows(df: Any) -> None:
+ manager = NarwhalsTableManager.from_dataframe(df)
+ result = manager.calculate_top_k_rows("A", 10)
+ normalized_result = _normalize_result(result)
+ assert normalized_result == [(3, 2), (None, 2), (2, 1), (1, 1)]
+
+ # Test with limit
+ result = manager.calculate_top_k_rows("A", 2)
+ normalized_result = _normalize_result(result)
+ assert normalized_result == [(3, 2), (None, 2)]
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+ "df",
+ create_dataframes(
+ {"count": [1, 2, 3, 3, None, None]},
+ include=["pandas", "polars"],
+ ),
+)
+def test_calculate_top_k_rows_conflicting_colname(df: Any) -> None:
+ manager = NarwhalsTableManager.from_dataframe(df)
+
+ # Test original column A
+ result_a = manager.calculate_top_k_rows("count", 10)
+ normalized_result_a = _normalize_result(result_a)
+ assert normalized_result_a == [(3, 2), (None, 2), (2, 1), (1, 1)]
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_calculate_top_k_rows_lazy_frame() -> None:
+ import polars as pl
+
+ df = pl.DataFrame({"A": [1, 2, 3, 3, None, None]}).lazy()
+ manager = NarwhalsTableManager.from_dataframe(df)
+ with pytest.raises(
+ ValueError, match="Cannot calculate top k rows for lazy frames"
+ ):
+ manager.calculate_top_k_rows("A", 10)
+
+
+ reason="Narwhals doesn't support group_by for metadata-only frames"
+)
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_calculate_top_k_rows_metadata_only_frame() -> None:
+ import ibis
+
+ df = ibis.memtable({"A": [1, 2, 3, 3, None, None]})
+ manager = NarwhalsTableManager.from_dataframe(df)
+ result = manager.calculate_top_k_rows("A", 10)
+ assert result == [(3, 2), (None, 2), (2, 1), (1, 1)]
+
+
+def _normalize_result(result: list[tuple[Any, int]]) -> list[tuple[Any, int]]:
+ """Normalize None and NaN values for comparison."""
+ return [
+ (None if val is None or isnan(val) else val, count)
+ for val, count in result
+ ]
+
+
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
@pytest.mark.parametrize(
"df",
@@ -1109,3 +1182,55 @@ def test_get_field_types_with_many_columns_is_performant(df: Any) -> None:
assert total_ms < 500, (
f"Total time: {total_ms}ms for {df.shape[1]} columns with {type(df)}"
)
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+class TestCalculateTopKRowsCaching(unittest.TestCase):
+ def setUp(self) -> None:
+ import polars as pl
+
+ self.data = pl.DataFrame(
+ {"name": ["Alice", "Eve", None], "age": [25, 35, None]}
+ )
+ self.manager = NarwhalsTableManager.from_dataframe(self.data)
+
+ def test_calculate_top_k_rows_caching(self) -> None:
+ """Test that calculate_top_k_rows caching works correctly."""
+ # First call should compute the result
+ result1 = self.manager.calculate_top_k_rows("name", 10)
+
+ # Second call with same args should use cache and return same object
+ result2 = self.manager.calculate_top_k_rows("name", 10)
+ assert result1 is result2
+
+ # Different k value should compute new result
+ result3 = self.manager.calculate_top_k_rows("name", 5)
+ assert result3 is not result1
+
+ # Different column name should compute new result
+ result4 = self.manager.calculate_top_k_rows("age", 10)
+ assert result4 is not result1
+
+ def test_calculate_top_k_rows_cache_invalidation(self) -> None:
+ """Test that cache is properly invalidated when data changes."""
+ # Initial calculation
+ result1 = self.manager.calculate_top_k_rows("name", 2)
+
+ # Modify the data
+ import polars as pl
+
+ new_data = pl.DataFrame(
+ {
+ "name": ["Alice", "Eve", "Bob", None],
+ }
+ )
+
+ # Create a new manager with the new data
+ self.manager = NarwhalsTableManager.from_dataframe(new_data)
+
+ # New calculation should be performed and return different result
+ result2 = self.manager.calculate_top_k_rows("name", 2)
+ assert result2 is not result1 # Different result due to data change
+
+ # Verify the actual results are different
+ assert result1 != result2
diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.py
index 3fa1ee6bac..b4e86c8401 100644
--- a/tests/_plugins/ui/_impl/test_table.py
+++ b/tests/_plugins/ui/_impl/test_table.py
@@ -11,6 +11,8 @@ from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins import ui
from marimo._plugins.ui._impl.dataframes.transforms.types import Condition
from marimo._plugins.ui._impl.table import (
+ CalculateTopKRowsArgs,
+ CalculateTopKRowsResponse,
DownloadAsArgs,
SearchTableArgs,
SortArgs,
@@ -1638,6 +1640,16 @@ def test_default_table_page_size():
assert get_default_table_page_size() == 10
+def test_calculate_top_k_rows():
+ table = ui.table({"A": [1, 3, 3, None, None]})
+ result = table._calculate_top_k_rows(
+ CalculateTopKRowsArgs(column="A", k=10)
+ )
+ assert result == CalculateTopKRowsResponse(
+ data=[(3, 2), (None, 2), (1, 1)],
+ )
+
+
def _convert_data_bytes_to_pandas_df(
data: str, data_format: str
) -> pd.DataFrame: