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.

refactor(select): shared select-core for multiselect, dropdown, and filter picker (#9849)

Kiran Gadhave9f902f31d1f4
diff --git a/frontend/src/components/data-table/filter-by-values-picker.tsx b/frontend/src/components/data-table/filter-by-values-picker.tsx
index 44390ed8bd..0b21a8bce0 100644
--- a/frontend/src/components/data-table/filter-by-values-picker.tsx
+++ b/frontend/src/components/data-table/filter-by-values-picker.tsx
@@ -7,6 +7,8 @@ import { useMemo, useState } from "react";
import { useAsyncData } from "@/hooks/useAsyncData";
import { ErrorBanner } from "@/plugins/impl/common/error-banner";
import type { CalculateTopKRows } from "@/plugins/impl/DataTablePlugin";
+import type { Option } from "@/components/ui/select-core";
+import { useSelectList } from "@/components/ui/select-core";
import { Logger } from "@/utils/Logger";
import { Sets } from "@/utils/sets";
import { smartMatch } from "@/utils/smartMatch";
@@ -23,7 +25,7 @@ import {
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
import { SentinelCell } from "./sentinel-cell";
import { detectSentinel, stringifyUnknownValue } from "./utils";
-import { CompactChipRow } from "./value-chips";
+import { CompactChipRow } from "@/components/ui/value-chips";
const TOP_K_ROWS = 30;
@@ -101,8 +103,6 @@ export const FilterByValuesList = <TData, TValue>({
onChange,
creatable = false,
}: FilterByValuesListProps<TData, TValue>) => {
- const [query, setQuery] = useState<string>("");
-
const { data, isPending, error } = useAsyncData(async () => {
if (!calculateTopKRows) {
return null;
@@ -111,27 +111,49 @@ export const FilterByValuesList = <TData, TValue>({
return res.data;
}, [calculateTopKRows, column.id]);
- const filteredData = useMemo(() => {
+ const options = useMemo<Array<Option<unknown>>>(() => {
if (!data) {
return [];
}
try {
- // try to do includes and also smart match for prefixes
- return data.filter(([value, _count]) => {
- if (value === undefined) {
- return false;
- }
- const str = String(value);
- return (
- smartMatch(query, str) ||
- str.toLowerCase().includes(query.toLowerCase())
- );
- });
+ return data
+ .filter(([value]) => value !== undefined)
+ .map(([value, count]) => ({
+ value,
+ label: String(value),
+ data: { count },
+ }));
} catch (error_) {
- Logger.error("Error filtering data", error_);
+ Logger.error("Error building filter options", error_);
return [];
}
- }, [data, query]);
+ }, [data]);
+
+ const list = useSelectList<unknown>({
+ options,
+ value: [...chosenValues],
+ onChange: (next) => onChange(next as unknown[]),
+ multiple: true,
+ filterFn: (label, q) =>
+ smartMatch(q, label) || label.toLowerCase().includes(q.toLowerCase())
+ ? 1
+ : 0,
+ });
+
+ const query = list.searchQuery;
+ const setQuery = list.setSearchQuery;
+
+ const filteredData = useMemo<Array<[unknown, number | undefined]>>(
+ () =>
+ list.visibleOptions.map(
+ (o) =>
+ [o.value, (o.data as { count: number }).count] as [
+ unknown,
+ number | undefined,
+ ],
+ ),
+ [list.visibleOptions],
+ );
// Surface chosen values that aren't in the top-K so they stay visible/uncheckable.
// Count is undefined for these rows; the cell renders an em-dash.
diff --git a/frontend/src/components/data-table/filter-pills.tsx b/frontend/src/components/data-table/filter-pills.tsx
index 487a7b8e5f..365af7f8bc 100644
--- a/frontend/src/components/data-table/filter-pills.tsx
+++ b/frontend/src/components/data-table/filter-pills.tsx
@@ -21,7 +21,7 @@ import { AddFilterButton } from "./add-filter-button";
import { FilterPillEditor } from "./filter-pill-editor";
import { type ColumnFilterValue, formatValue, type Snapshot } from "./filters";
import { extractTimezone } from "./types";
-import { ChipWithComma, CompactChipRow } from "./value-chips";
+import { ChipWithComma, CompactChipRow } from "@/components/ui/value-chips";
interface Props<TData> {
filters: ColumnFiltersState | undefined;
diff --git a/frontend/src/components/ui/combobox.tsx b/frontend/src/components/ui/combobox.tsx
index 738c38e501..61e8773889 100644
--- a/frontend/src/components/ui/combobox.tsx
+++ b/frontend/src/components/ui/combobox.tsx
@@ -2,7 +2,7 @@
import { useControllableState } from "@radix-ui/react-use-controllable-state";
import { Check, ChevronDownIcon, XCircle } from "lucide-react";
-import React, { createContext } from "react";
+import React, { createContext, useCallback, useMemo } from "react";
import { cn } from "../../utils/cn";
import { Functions } from "../../utils/functions";
import { Badge } from "./badge";
@@ -40,6 +40,8 @@ interface ComboboxCommonProps<TValue> {
id?: string;
keepPopoverOpenOnSelect?: boolean;
disabled?: boolean;
+ /** Override the trigger contents with a node (e.g. a compact chip summary). */
+ renderValue?: (value: TValue[] | TValue | null) => React.ReactNode;
}
type ComboboxFilterProps =
@@ -97,6 +99,7 @@ export const Combobox = <TValue,>({
keepPopoverOpenOnSelect,
id,
disabled = false,
+ renderValue,
...rest
}: ComboboxProps<TValue>) => {
const [open = false, setOpen] = useControllableState({
@@ -112,39 +115,45 @@ export const Combobox = <TValue,>({
},
});
- const isSelected = (selectedValue: unknown) => {
- if (Array.isArray(value)) {
- return value.includes(selectedValue as TValue);
- }
- return value === selectedValue;
- };
+ const isSelected = useCallback(
+ (selectedValue: unknown) => {
+ if (Array.isArray(value)) {
+ return value.includes(selectedValue as TValue);
+ }
+ return value === selectedValue;
+ },
+ [value],
+ );
- const handleSelect = (selectedValue: unknown) => {
- let newValue: TValue | TValue[] | null = selectedValue as TValue;
+ const handleSelect = useCallback(
+ (selectedValue: unknown) => {
+ let newValue: TValue | TValue[] | null = selectedValue as TValue;
- if (multiple) {
- if (Array.isArray(value)) {
- if (value.includes(newValue)) {
- const newArr = value.filter((val) => val !== selectedValue);
- newValue = newArr.length > 0 ? newArr : [];
+ if (multiple) {
+ if (Array.isArray(value)) {
+ if (value.includes(newValue)) {
+ const newArr = value.filter((val) => val !== selectedValue);
+ newValue = newArr.length > 0 ? newArr : [];
+ } else {
+ newValue = [...value, newValue];
+ }
} else {
- newValue = [...value, newValue];
+ newValue = [newValue];
}
- } else {
- newValue = [newValue];
+ } else if (value === selectedValue) {
+ newValue = null;
}
- } else if (value === selectedValue) {
- newValue = null;
- }
- setValue(newValue);
- const keepOpen = keepPopoverOpenOnSelect ?? multiple;
- if (!keepOpen) {
- setOpen(false);
- }
- };
+ setValue(newValue);
+ const keepOpen = keepPopoverOpenOnSelect ?? multiple;
+ if (!keepOpen) {
+ setOpen(false);
+ }
+ },
+ [keepPopoverOpenOnSelect, multiple, value, setValue, setOpen],
+ );
- const renderValue = (): string => {
+ const renderValueLabel = (): string => {
// If we show chips, we don't want to change the placeholder
if (multiple && chips && placeholder) {
return placeholder;
@@ -168,6 +177,14 @@ export const Combobox = <TValue,>({
return placeholder ?? "--";
};
+ const comboboxContextValue: ComboboxContextValue = useMemo(
+ () => ({
+ isSelected,
+ onSelect: handleSelect,
+ }),
+ [isSelected, handleSelect],
+ );
+
return (
<div className={cn("relative")} {...rest}>
<Popover
@@ -191,7 +208,9 @@ export const Combobox = <TValue,>({
aria-expanded={open}
aria-disabled={disabled}
>
- <span className="truncate flex-1 min-w-0">{renderValue()}</span>
+ <span className="truncate flex-1 min-w-0">
+ {renderValue ? renderValue(value ?? null) : renderValueLabel()}
+ </span>
<ChevronDownIcon className="ml-3 w-4 h-4 opacity-50 shrink-0" />
</button>
</PopoverTrigger>
@@ -209,7 +228,7 @@ export const Combobox = <TValue,>({
/>
<CommandList className="max-h-60 py-.5">
<CommandEmpty>{emptyState}</CommandEmpty>
- <ComboboxContext value={{ isSelected, onSelect: handleSelect }}>
+ <ComboboxContext value={comboboxContextValue}>
{children}
</ComboboxContext>
</CommandList>
@@ -277,12 +296,14 @@ export const ComboboxItem = React.forwardRef(
? value.value
: String(value);
const context = React.use(ComboboxContext);
+ const isOptionSelected = context.isSelected(value);
return (
<CommandItem
ref={ref}
className={cn("pl-6 m-1 py-1", className)}
role="option"
+ aria-selected={isOptionSelected}
value={valueAsString}
disabled={disabled}
onSelect={() => {
@@ -290,9 +311,7 @@ export const ComboboxItem = React.forwardRef(
onSelect?.(value);
}}
>
- {context.isSelected(value) && (
- <Check className="absolute left-1 h-4 w-4" />
- )}
+ {isOptionSelected && <Check className="absolute left-1 h-4 w-4" />}
{children}
</CommandItem>
);
diff --git a/frontend/src/components/ui/select-core/__tests__/use-select-list.test.ts b/frontend/src/components/ui/select-core/__tests__/use-select-list.test.ts
new file mode 100644
index 0000000000..f5568bce02
--- /dev/null
+++ b/frontend/src/components/ui/select-core/__tests__/use-select-list.test.ts
@@ -0,0 +1,294 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import { act, renderHook } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import type { BulkAction, Option } from "../types";
+import { useSelectList } from "../use-select-list";
+
+const opts: Array<Option<string>> = [
+ { value: "a", label: "apple" },
+ { value: "b", label: "banana" },
+ { value: "c", label: "cherry" },
+];
+
+describe("useSelectList - search", () => {
+ it("filters visibleOptions by label using the strict word match", () => {
+ const { result } = renderHook(() =>
+ useSelectList({
+ options: opts,
+ value: [],
+ onChange: vi.fn(),
+ multiple: true,
+ }),
+ );
+ act(() => result.current.setSearchQuery("ban"));
+ expect(result.current.visibleOptions.map((o) => o.value)).toEqual(["b"]);
+ });
+
+ it("returns all options when the query is empty", () => {
+ const { result } = renderHook(() =>
+ useSelectList({
+ options: opts,
+ value: [],
+ onChange: vi.fn(),
+ multiple: true,
+ }),
+ );
+ expect(result.current.visibleOptions).toHaveLength(3);
+ });
+
+ it("keeps options for any positive filter score, not just 1", () => {
+ const { result } = renderHook(() =>
+ useSelectList({
+ options: opts,
+ value: [],
+ onChange: vi.fn(),
+ multiple: true,
+ filterFn: (label) => (label === "apple" ? 0.5 : 0),
+ }),
+ );
+ act(() => result.current.setSearchQuery("anything"));
+ expect(result.current.visibleOptions.map((o) => o.value)).toEqual(["a"]);
+ });
+});
+
+describe("useSelectList - multi toggle", () => {
+ it("adds an unselected value", () => {
+ const onChange = vi.fn();
+ const { result } = renderHook(() =>
+ useSelectList({ options: opts, value: ["a"], onChange, multiple: true }),
+ );
+ act(() => result.current.toggle("b"));
+ expect(onChange).toHaveBeenCalledWith(["a", "b"]);
+ });
+
+ it("removes a selected value", () => {
+ const onChange = vi.fn();
+ const { result } = renderHook(() =>
+ useSelectList({
+ options: opts,
+ value: ["a", "b"],
+ onChange,
+ multiple: true,
+ }),
+ );
+ act(() => result.current.toggle("a"));
+ expect(onChange).toHaveBeenCalledWith(["b"]);
+ });
+
+ it("drops the oldest selection when maxSelections is exceeded", () => {
+ const onChange = vi.fn();
+ const { result } = renderHook(() =>
+ useSelectList({
+ options: opts,
+ value: ["a", "b"],
+ onChange,
+ multiple: true,
+ maxSelections: 2,
+ }),
+ );
+ act(() => result.current.toggle("c"));
+ expect(onChange).toHaveBeenCalledWith(["b", "c"]);
+ });
+
+ it("isChecked reflects membership", () => {
+ const { result } = renderHook(() =>
+ useSelectList({
+ options: opts,
+ value: ["a"],
+ onChange: vi.fn(),
+ multiple: true,
+ }),
+ );
+ expect(result.current.isChecked("a")).toBe(true);
+ expect(result.current.isChecked("b")).toBe(false);
+ });
+});
+
+describe("useSelectList - single toggle", () => {
+ it("replaces the value", () => {
+ const onChange = vi.fn();
+ const { result } = renderHook(() =>
+ useSelectList({ options: opts, value: "a", onChange, multiple: false }),
+ );
+ act(() => result.current.toggle("b"));
+ expect(onChange).toHaveBeenCalledWith("b");
+ });
+
+ it("clears to null when allowSelectNone and the value is re-toggled", () => {
+ const onChange = vi.fn();
+ const { result } = renderHook(() =>
+ useSelectList({
+ options: opts,
+ value: "a",
+ onChange,
+ multiple: false,
+ allowSelectNone: true,
+ }),
+ );
+ act(() => result.current.toggle("a"));
+ expect(onChange).toHaveBeenCalledWith(null);
+ });
+});
+
+describe("useSelectList - pinning + freeze", () => {
+ it("pins selected to the top of visibleOptions when open and idle", () => {
+ const { result } = renderHook(() =>
+ useSelectList({
+ options: opts,
+ value: ["c"],
+ onChange: vi.fn(),
+ multiple: true,
+ pinSelected: true,
+ }),
+ );
+ act(() => result.current.setOpen(true));
+ expect(result.current.visibleOptions.map((o) => o.value)).toEqual([
+ "c",
+ "a",
+ "b",
+ ]);
+ expect(result.current.pinnedCount).toBe(1);
+ });
+
+ it("freezes pinned order while open: a newly toggled item does not re-pin", () => {
+ const onChange = vi.fn();
+ const { result, rerender } = renderHook(
+ ({ value }) =>
+ useSelectList({
+ options: opts,
+ value,
+ onChange,
+ multiple: true,
+ pinSelected: true,
+ }),
+ { initialProps: { value: ["c"] as string[] } },
+ );
+ act(() => result.current.setOpen(true));
+ rerender({ value: ["c", "a"] });
+ expect(result.current.visibleOptions.map((o) => o.value)).toEqual([
+ "c",
+ "a",
+ "b",
+ ]);
+ expect(result.current.isChecked("a")).toBe(true);
+ });
+
+ it("re-pins when the search clears", () => {
+ const { result, rerender } = renderHook(
+ ({ value }) =>
+ useSelectList({
+ options: opts,
+ value,
+ onChange: vi.fn(),
+ multiple: true,
+ pinSelected: true,
+ }),
+ { initialProps: { value: ["b"] as string[] } },
+ );
+ act(() => result.current.setOpen(true));
+ act(() => result.current.setSearchQuery("a"));
+ rerender({ value: ["b", "a"] });
+ act(() => result.current.setSearchQuery(""));
+ expect(result.current.visibleOptions.map((o) => o.value)).toEqual([
+ "b",
+ "a",
+ "c",
+ ]);
+ });
+
+ it("does not pin when pinSelected is false", () => {
+ const { result } = renderHook(() =>
+ useSelectList({
+ options: opts,
+ value: ["c"],
+ onChange: vi.fn(),
+ multiple: true,
+ }),
+ );
+ act(() => result.current.setOpen(true));
+ expect(result.current.visibleOptions.map((o) => o.value)).toEqual([
+ "a",
+ "b",
+ "c",
+ ]);
+ expect(result.current.pinnedCount).toBe(0);
+ });
+});
+
+describe("useSelectList - bulk", () => {
+ const findAction = <K extends BulkAction<string>["kind"]>(
+ actions: ReadonlyArray<BulkAction<string>>,
+ kind: K,
+ ): Extract<BulkAction<string>, { kind: K }> | undefined =>
+ actions.find(
+ (a): a is Extract<BulkAction<string>, { kind: K }> => a.kind === kind,
+ );
+
+ it("idle: select-all picks every option; deselect-all clears", () => {
+ const onChange = vi.fn();
+ const { result } = renderHook(() =>
+ useSelectList({ options: opts, value: ["a"], onChange, multiple: true }),
+ );
+ act(() => findAction(result.current.bulkActions, "select-all")?.run());
+ expect(onChange).toHaveBeenCalledWith(["a", "b", "c"]);
+ onChange.mockClear();
+ act(() => findAction(result.current.bulkActions, "deselect-all")?.run());
+ expect(onChange).toHaveBeenCalledWith([]);
+ });
+
+ it("idle: select-all skips disabled options and keeps the existing selection", () => {
+ const onChange = vi.fn();
+ const withDisabled: Array<Option<string>> = [
+ { value: "a", label: "apple" },
+ { value: "b", label: "banana", disabled: true },
+ { value: "c", label: "cherry" },
+ ];
+ const { result } = renderHook(() =>
+ useSelectList({
+ options: withDisabled,
+ value: ["c"],
+ onChange,
+ multiple: true,
+ }),
+ );
+ act(() => findAction(result.current.bulkActions, "select-all")?.run());
+ expect(onChange).toHaveBeenCalledWith(["c", "a"]);
+ });
+
+ it("searching: select-matching acts only on the matches (additive)", () => {
+ const onChange = vi.fn();
+ const { result } = renderHook(() =>
+ useSelectList({ options: opts, value: ["a"], onChange, multiple: true }),
+ );
+ act(() => result.current.setSearchQuery("b"));
+ act(() => findAction(result.current.bulkActions, "select-matching")?.run());
+ expect(onChange).toHaveBeenCalledWith(["a", "b"]);
+ });
+
+ it("exposes idle bulkActions in select-then-deselect order", () => {
+ const { result } = renderHook(() =>
+ useSelectList({
+ options: opts,
+ value: ["a"],
+ onChange: vi.fn(),
+ multiple: true,
+ }),
+ );
+ const kinds = result.current.bulkActions.map((a) => a.kind);
+ expect(kinds).toEqual(["select-all", "deselect-all"]);
+ const selectAll = findAction(result.current.bulkActions, "select-all");
+ expect(selectAll && "enabled" in selectAll && selectAll.enabled).toBe(true);
+ });
+
+ it("bulkActions is empty for single-select", () => {
+ const { result } = renderHook(() =>
+ useSelectList({
+ options: opts,
+ value: "a",
+ onChange: vi.fn(),
+ multiple: false,
+ }),
+ );
+ expect(result.current.bulkActions).toEqual([]);
+ });
+});
diff --git a/frontend/src/components/ui/select-core/__tests__/utils.test.ts b/frontend/src/components/ui/select-core/__tests__/utils.test.ts
new file mode 100644
index 0000000000..cd0285ee7e
--- /dev/null
+++ b/frontend/src/components/ui/select-core/__tests__/utils.test.ts
@@ -0,0 +1,222 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import { describe, expect, it } from "vitest";
+import type { Option } from "../types";
+import {
+ deselectMatching,
+ getBulkActions,
+ getVisibleOptions,
+ multiselectFilterFn,
+ selectMatching,
+} from "../utils";
+
+describe("multiselectFilterFn", () => {
+ it("matches when all query words appear in the option (any order)", () => {
+ expect(multiselectFilterFn("foo bar", "bar foo")).toBe(1);
+ });
+
+ it("does not match a partial word", () => {
+ expect(multiselectFilterFn("foo bar", "foob")).toBe(0);
+ });
+});
+
+describe("selectMatching", () => {
+ it("adds only unselected matches, existing first then additions", () => {
+ expect(selectMatching(["a"], ["a", "b", "c"])).toEqual(["a", "b", "c"]);
+ });
+
+ it("keeps selections outside the filter untouched", () => {
+ expect(selectMatching(["x", "y"], ["a", "b"])).toEqual([
+ "x",
+ "y",
+ "a",
+ "b",
+ ]);
+ });
+
+ it("is generic over the value type", () => {
+ expect(selectMatching<number>([1], [1, 2])).toEqual([1, 2]);
+ });
+});
+
+describe("deselectMatching", () => {
+ it("removes only the matching items", () => {
+ expect(deselectMatching(["a", "b", "c"], ["a", "c"])).toEqual(["b"]);
+ });
+
+ it("leaves out-of-filter selections intact", () => {
+ expect(deselectMatching(["x", "a"], ["a", "b"])).toEqual(["x"]);
+ });
+});
+
+const opt = (value: string): Option<string> => ({ value, label: value });
+
+describe("getVisibleOptions", () => {
+ it("pins selected options first, both groups in option order", () => {
+ const options = ["a", "b", "c", "d"].map(opt);
+ const { visibleOptions, pinnedCount } = getVisibleOptions(
+ options,
+ new Set(["b", "d"]),
+ );
+ expect(visibleOptions.map((o) => o.value)).toEqual(["b", "d", "a", "c"]);
+ expect(pinnedCount).toBe(2);
+ });
+
+ it("returns options unchanged when nothing is pinned", () => {
+ const options = ["a", "b", "c"].map(opt);
+ const { visibleOptions, pinnedCount } = getVisibleOptions(
+ options,
+ new Set(),
+ );
+ expect(visibleOptions.map((o) => o.value)).toEqual(["a", "b", "c"]);
+ expect(pinnedCount).toBe(0);
+ });
+
+ it("ignores pinned values that are not in options", () => {
+ const options = ["a", "b"].map(opt);
+ const { visibleOptions, pinnedCount } = getVisibleOptions(
+ options,
+ new Set(["b", "ghost"]),
+ );
+ expect(visibleOptions.map((o) => o.value)).toEqual(["b", "a"]);
+ expect(pinnedCount).toBe(1);
+ });
+});
+
+const bulkBase = {
+ options: ["a", "b", "c", "d"].map(opt),
+ value: [] as string[],
+ searchQuery: "",
+ maxSelections: undefined as number | undefined,
+};
+
+describe("getBulkActions", () => {
+ it("returns no specs for 2 or fewer options", () => {
+ expect(
+ getBulkActions({
+ ...bulkBase,
+ options: ["a", "b"].map(opt),
+ filteredOptions: ["a", "b"].map(opt),
+ }),
+ ).toEqual([]);
+ });
+
+ it("returns no specs when maxSelections is 1", () => {
+ expect(
+ getBulkActions({
+ ...bulkBase,
+ filteredOptions: bulkBase.options,
+ maxSelections: 1,
+ }),
+ ).toEqual([]);
+ });
+
+ it("idle: select-all then deselect-all, both enabled", () => {
+ expect(
+ getBulkActions({
+ ...bulkBase,
+ value: ["a"],
+ filteredOptions: bulkBase.options,
+ }),
+ ).toEqual([
+ { kind: "select-all", enabled: true },
+ { kind: "deselect-all", enabled: true },
+ ]);
+ });
+
+ it("idle: select-all disabled when everything is selected", () => {
+ expect(
+ getBulkActions({
+ ...bulkBase,
+ value: ["a", "b", "c", "d"],
+ filteredOptions: bulkBase.options,
+ }),
+ ).toEqual([
+ { kind: "select-all", enabled: false },
+ { kind: "deselect-all", enabled: true },
+ ]);
+ });
+
+ it("searching: items reflect unselected vs selected matches", () => {
+ expect(
+ getBulkActions({
+ ...bulkBase,
+ value: ["a"],
+ searchQuery: "x",
+ filteredOptions: ["a", "b", "c"].map(opt),
+ }),
+ ).toEqual([
+ { kind: "select-matching", items: ["b", "c"].map(opt) },
+ { kind: "deselect-matching", items: ["a"].map(opt) },
+ ]);
+ });
+
+ it("searching with no matches: no specs", () => {
+ expect(
+ getBulkActions({ ...bulkBase, searchQuery: "zzz", filteredOptions: [] }),
+ ).toEqual([]);
+ });
+
+ it("searching: omits select-matching when all matches are already selected", () => {
+ expect(
+ getBulkActions({
+ ...bulkBase,
+ value: ["a", "b"],
+ searchQuery: "x",
+ filteredOptions: ["a", "b"].map(opt),
+ }),
+ ).toEqual([{ kind: "deselect-matching", items: ["a", "b"].map(opt) }]);
+ });
+
+ it("maxSelections > 1: deselect-side only, idle and searching", () => {
+ expect(
+ getBulkActions({
+ ...bulkBase,
+ value: ["a"],
+ filteredOptions: bulkBase.options,
+ maxSelections: 3,
+ }),
+ ).toEqual([{ kind: "deselect-all", enabled: true }]);
+
+ expect(
+ getBulkActions({
+ ...bulkBase,
+ value: ["a"],
+ searchQuery: "x",
+ filteredOptions: ["a", "b"].map(opt),
+ maxSelections: 3,
+ }),
+ ).toEqual([{ kind: "deselect-matching", items: ["a"].map(opt) }]);
+ });
+
+ it("idle: select-all is disabled when only disabled options remain unselected", () => {
+ const options = [opt("a"), { value: "b", label: "b", disabled: true }];
+ expect(
+ getBulkActions({
+ ...bulkBase,
+ options: [...options, opt("c")],
+ value: ["a", "c"],
+ filteredOptions: [...options, opt("c")],
+ }),
+ ).toEqual([
+ { kind: "select-all", enabled: false },
+ { kind: "deselect-all", enabled: true },
+ ]);
+ });
+
+ it("searching: select-matching omits disabled matches", () => {
+ const filteredOptions = [
+ opt("a"),
+ { value: "b", label: "b", disabled: true },
+ opt("c"),
+ ];
+ expect(
+ getBulkActions({
+ ...bulkBase,
+ options: filteredOptions,
+ value: [],
+ searchQuery: "x",
+ filteredOptions,
+ }),
+ ).toEqual([{ kind: "select-matching", items: ["a", "c"].map(opt) }]);
+ });
+});
diff --git a/frontend/src/components/ui/select-core/index.ts b/frontend/src/components/ui/select-core/index.ts
new file mode 100644
index 0000000000..124254a137
--- /dev/null
+++ b/frontend/src/components/ui/select-core/index.ts
@@ -0,0 +1,16 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+export {
+ SelectList,
+ VIRTUALIZE_THRESHOLD,
+ VIRTUALIZED_LIST_HEIGHT,
+} from "./select-list";
+export { useSelectList } from "./use-select-list";
+export { renderSlot, type Slot } from "./render-slot";
+export type { BulkAction, BulkActionSpec, Option, OptionState } from "./types";
+export {
+ deselectMatching,
+ getBulkActions,
+ getVisibleOptions,
+ multiselectFilterFn,
+ selectMatching,
+} from "./utils";
diff --git a/frontend/src/components/ui/select-core/option-row.tsx b/frontend/src/components/ui/select-core/option-row.tsx
new file mode 100644
index 0000000000..7dd0247f73
--- /dev/null
+++ b/frontend/src/components/ui/select-core/option-row.tsx
@@ -0,0 +1,33 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import * as React from "react";
+import { ComboboxItem } from "../combobox";
+import type { Option, OptionState } from "./types";
+
+interface OptionRowProps<V> {
+ option: Option<V>;
+ checked: boolean;
+ renderOption?: (option: Option<V>, state: OptionState) => React.ReactNode;
+}
+
+function OptionRowImpl<V>({
+ option,
+ checked,
+ renderOption,
+}: OptionRowProps<V>): React.JSX.Element {
+ return (
+ <ComboboxItem
+ data-slot="select-option"
+ data-checked={checked || undefined}
+ // Selection identity, not the display string: the Combobox tracks
+ // `isSelected`/`onSelect` by this value and echoes it back through
+ // `onValueChange`. The cast bridges the unconstrained option type to
+ // ComboboxItem's stringifiable-value bound.
+ value={option.value as string | number}
+ disabled={option.disabled}
+ >
+ {renderOption ? renderOption(option, { checked }) : option.label}
+ </ComboboxItem>
+ );
+}
+
+export const OptionRow = React.memo(OptionRowImpl) as typeof OptionRowImpl;
diff --git a/frontend/src/components/ui/select-core/render-slot.ts b/frontend/src/components/ui/select-core/render-slot.ts
new file mode 100644
index 0000000000..ec2612689a
--- /dev/null
+++ b/frontend/src/components/ui/select-core/render-slot.ts
@@ -0,0 +1,20 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import type React from "react";
+
+/**
+ * A customizable piece of UI: either fixed content, or a function that builds it
+ * from `A`. The thunk form lets callers defer work (or read render-time args)
+ * until the slot is actually shown.
+ */
+export type Slot<A extends unknown[] = []> =
+ | React.ReactNode
+ | ((...args: A) => React.ReactNode);
+
+/** Resolve a {@link Slot} to its node, calling the thunk form with `args`. */
+export function renderSlot<A extends unknown[]>(
+ slot: Slot<A>,
+ ...args: A
+): React.ReactNode {
+ return typeof slot === "function" ? slot(...args) : slot;
+}
diff --git a/frontend/src/components/ui/select-core/select-list.tsx b/frontend/src/components/ui/select-core/select-list.tsx
new file mode 100644
index 0000000000..9853835003
--- /dev/null
+++ b/frontend/src/components/ui/select-core/select-list.tsx
@@ -0,0 +1,248 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import type * as React from "react";
+import { Virtuoso } from "react-virtuoso";
+import { CompactChipRow } from "@/components/ui/value-chips";
+import { cn } from "@/utils/cn";
+import { Combobox } from "../combobox";
+import { CommandItem, CommandSeparator } from "../command";
+import { OptionRow } from "./option-row";
+import { renderSlot, type Slot } from "./render-slot";
+import type { BulkAction, Option, OptionState } from "./types";
+import { useSelectList } from "./use-select-list";
+
+/** Above this many options the list virtualizes. */
+export const VIRTUALIZE_THRESHOLD = 200;
+
+/** Fixed pixel height of the virtualized viewport (Virtuoso requires one). */
+export const VIRTUALIZED_LIST_HEIGHT = 200;
+
+function bulkActionLabel<V>(action: BulkAction<V>): string {
+ switch (action.kind) {
+ case "select-all":
+ return "Select all";
+ case "deselect-all":
+ return "Deselect all";
+ case "select-matching":
+ return `Select ${action.items.length} matching`;
+ case "deselect-matching":
+ return `Deselect ${action.items.length} matching`;
+ }
+}
+
+interface SelectListProps<V> {
+ options: Array<Option<V>>;
+ /** Current selection: an array when `multiple`, otherwise a single value or null. */
+ value: V[] | V | null;
+ onChange: (next: V[] | V | null) => void;
+ /** Multi-select when true; single-select (replace-on-pick) when false. */
+ multiple: boolean;
+ /** Cap on multi-select size. At the cap, picking another drops the oldest. */
+ maxSelections?: number;
+ /** Single-select only: re-picking the current value clears it to null. */
+ allowSelectNone?: boolean;
+ /** Float the (frozen) selection to the top of the idle menu, with a separator. */
+ pinSelected?: boolean;
+ /** Summarize the selection in the trigger as a compact chip row instead of "N selected". */
+ compactChipTrigger?: boolean;
+ placeholder?: string;
+ disabled?: boolean;
+ fullWidth?: boolean;
+ className?: string;
+ id?: string;
+ "data-testid"?: string;
+ /** Renders the row content; the core owns the interactive container. */
+ renderOption?: (option: Option<V>, state: OptionState) => React.ReactNode;
+ /** Shown when no option matches the current query. */
+ renderEmpty?: Slot;
+ /**
+ * Virtualize once the visible option count exceeds this. Lower it when
+ * `renderOption` produces expensive rows so they virtualize sooner.
+ */
+ virtualizeThreshold?: number;
+ /** Fixed pixel height of the virtualized viewport. */
+ virtualizedHeight?: number;
+}
+
+export function SelectList<V>(props: SelectListProps<V>): React.JSX.Element {
+ const {
+ options,
+ value,
+ onChange,
+ multiple,
+ maxSelections,
+ allowSelectNone,
+ pinSelected = false,
+ compactChipTrigger = false,
+ placeholder = "Select...",
+ disabled = false,
+ fullWidth = false,
+ className,
+ id,
+ renderOption,
+ renderEmpty = "Nothing found.",
+ virtualizeThreshold = VIRTUALIZE_THRESHOLD,
+ virtualizedHeight = VIRTUALIZED_LIST_HEIGHT,
+ } = props;
+
+ const list = useSelectList<V>({
+ options,
+ value,
+ onChange,
+ multiple,
+ maxSelections,
+ allowSelectNone,
+ pinSelected,
+ });
+
+ const handleComboChange = (next: V[] | V | null): void => {
+ if (!multiple) {
+ if (next == null && !allowSelectNone) {
+ return;
+ }
+ onChange(next);
+ return;
+ }
+ let arr = Array.isArray(next) ? next : [];
+ if (maxSelections != null && arr.length > maxSelections) {
+ arr = arr.slice(-maxSelections);
+ }
+ onChange(arr);
+ };
+
+ // Bulk rows render as raw CommandItem (not ComboboxItem) so Combobox's per-item
+ // toggle doesn't intercept them — only the action's own `run` fires on select.
+ const bulkRows: React.ReactNode[] = list.bulkActions.map((action) => {
+ const disabled =
+ "enabled" in action ? !action.enabled : action.items.length === 0;
+ return (
+ <CommandItem
+ key={action.kind}
+ data-slot="select-bulk"
+ className="pl-6 m-1 py-1"
+ value={`__bulk_${action.kind}`}
+ disabled={disabled}
+ onSelect={() => {
+ if (!disabled) {
+ action.run();
+ }
+ }}
+ >
+ {bulkActionLabel(action)}
+ </CommandItem>
+ );
+ });
+ if (bulkRows.length > 0) {
+ bulkRows.push(
+ <CommandSeparator key="_bulk_separator" data-slot="select-separator" />,
+ );
+ }
+
+ // Rendered at the start of the first unpinned row, not after the last pinned row,
+ // so the menu-separator's `last:hidden` Tailwind variant doesn't hide it inside
+ // Virtuoso's per-item wrapper.
+ const pinnedSeparator = (index: number): React.ReactNode =>
+ list.pinnedCount > 0 &&
+ index === list.pinnedCount &&
+ list.pinnedCount < list.visibleOptions.length ? (
+ <CommandSeparator key="_pinned_separator" data-slot="select-separator" />
+ ) : null;
+
+ const renderItems = () => {
+ if (list.visibleOptions.length > virtualizeThreshold) {
+ return (
+ <Virtuoso
+ data-slot="select-list"
+ style={{ height: virtualizedHeight }}
+ totalCount={list.visibleOptions.length}
+ overscan={50}
+ itemContent={(i: number) => {
+ const option = list.visibleOptions[i];
+ return (
+ <>
+ {i === 0 && bulkRows}
+ {pinnedSeparator(i)}
+ <OptionRow
+ option={option}
+ checked={list.isChecked(option.value)}
+ renderOption={renderOption}
+ />
+ </>
+ );
+ }}
+ />
+ );
+ }
+
+ const rows = list.visibleOptions.flatMap((option, i) => {
+ const separator = pinnedSeparator(i);
+ const row = (
+ <OptionRow
+ key={String(option.value)}
+ option={option}
+ checked={list.isChecked(option.value)}
+ renderOption={renderOption}
+ />
+ );
+ return separator ? [separator, row] : [row];
+ });
+
+ return (
+ <>
+ {bulkRows}
+ {rows}
+ </>
+ );
+ };
+
+ const renderTriggerValue = (current: V[] | V | null): React.ReactNode => {
+ const items = Array.isArray(current)
+ ? current
+ : current != null
+ ? [current]
+ : [];
+ if (items.length === 0) {
+ return <span className="text-muted-foreground">{placeholder}</span>;
+ }
+ return <CompactChipRow items={items.map(list.labelOf)} max={3} />;
+ };
+
+ // Props shared by both branches. `multiple`/`value`/`onValueChange` are the
+ // Combobox's discriminant trio, so they're set per-branch below with the
+ // literal `multiple` that matches each value/handler shape.
+ const comboboxProps = {
+ "data-slot": "select-root",
+ "data-testid": props["data-testid"],
+ displayValue: (option: V) => list.labelOf(option),
+ renderValue: compactChipTrigger ? renderTriggerValue : undefined,
+ placeholder,
+ className: cn({ "w-full": fullWidth }, className),
+ shouldFilter: false as const,
+ search: list.searchQuery,
+ onSearchChange: list.setSearchQuery,
+ open: list.open,
+ onOpenChange: list.setOpen,
+ emptyState: renderSlot(renderEmpty),
+ disabled,
+ id,
+ };
+
+ return multiple ? (
+ <Combobox<V>
+ {...comboboxProps}
+ multiple={true}
+ value={value as V[] | null}
+ onValueChange={handleComboChange}
+ >
+ {renderItems()}
+ </Combobox>
+ ) : (
+ <Combobox<V>
+ {...comboboxProps}
+ multiple={false}
+ value={value as V | null}
+ onValueChange={handleComboChange}
+ >
+ {renderItems()}
+ </Combobox>
+ );
+}
diff --git a/frontend/src/components/ui/select-core/types.ts b/frontend/src/components/ui/select-core/types.ts
new file mode 100644
index 0000000000..df9fa36c9f
--- /dev/null
+++ b/frontend/src/components/ui/select-core/types.ts
@@ -0,0 +1,44 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+/** A single selectable item. */
+export interface Option<V = string> {
+ /** Selection identity; what the adapter serializes. */
+ value: V;
+ /** Human-readable string used for display, filtering, and chip text. */
+ label: string;
+ /** Whether the option can be selected. */
+ disabled?: boolean;
+ /** Arbitrary per-row payload (e.g. `{ count }`) read by render slots. */
+ data?: unknown;
+}
+
+/**
+ * Live state of an option, passed to `renderOption` so custom rows can reflect
+ * selection. Keyboard highlight is exposed on the row element as
+ * `aria-selected` / `data-selected`, so custom rows style it via CSS.
+ */
+export interface OptionState {
+ /** Whether the option is currently selected. */
+ checked: boolean;
+}
+
+/**
+ * Pure-data description of one bulk row to render above the option list. The
+ * hook decides which specs exist for the current search/cap state; the facade
+ * decides labels and markup.
+ *
+ * - `select-all` / `deselect-all` act on the whole option list — the facade
+ * already has it as a prop, so the spec just carries `enabled` for the
+ * disabled-but-visible state (e.g. everything already picked).
+ * - `select-matching` / `deselect-matching` act on the search-filtered subset,
+ * which the facade can't see; `items` carries that subset so the facade can
+ * label the row ("Select N matching") and the slot is omitted when empty.
+ */
+export type BulkActionSpec<V> =
+ | { kind: "select-all"; enabled: boolean }
+ | { kind: "deselect-all"; enabled: boolean }
+ | { kind: "select-matching"; items: Array<Option<V>> }
+ | { kind: "deselect-matching"; items: Array<Option<V>> };
+
+/** A renderable bulk action: spec + the closure that applies it on click. */
+export type BulkAction<V> = BulkActionSpec<V> & { run: () => void };
diff --git a/frontend/src/components/ui/select-core/use-select-list.ts b/frontend/src/components/ui/select-core/use-select-list.ts
new file mode 100644
index 0000000000..f80031e609
--- /dev/null
+++ b/frontend/src/components/ui/select-core/use-select-list.ts
@@ -0,0 +1,347 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import { useMemo, useState } from "react";
+import { assertNever } from "@/utils/assertNever";
+import type { BulkAction, Option } from "./types";
+import {
+ deselectMatching,
+ getBulkActions,
+ getVisibleOptions,
+ multiselectFilterFn,
+ selectMatching,
+} from "./utils";
+
+/** cmdk-style relevance score for `(label, query)`; any positive score matches. */
+type FilterFn = (label: string, query: string) => number;
+
+interface UseSelectListParams<V> {
+ options: Array<Option<V>>;
+ /** Current selection: an array when `multiple`, otherwise a single value or null. */
+ value: V[] | V | null;
+ onChange: (next: V[] | V | null) => void;
+ /** Multi-select when true; single-select (replace-on-pick) when false. */
+ multiple: boolean;
+ /** Cap on multi-select size. At the cap, picking another drops the oldest. */
+ maxSelections?: number;
+ /** Single-select only: re-picking the current value clears it to null. */
+ allowSelectNone?: boolean;
+ /** Match predicate over `(label, query)`; defaults to the strict word match. */
+ filterFn?: FilterFn;
+ /** Float the (frozen) selection to the top of the idle menu. */
+ pinSelected?: boolean;
+}
+
+interface UseSelectListResult<V> {
+ searchQuery: string;
+ setSearchQuery: (query: string) => void;
+ open: boolean;
+ setOpen: (open: boolean) => void;
+ /** Filtered, and (when `pinSelected` and idle) selected-first ordered. */
+ visibleOptions: Array<Option<V>>;
+ /** Count of pinned options at the head of `visibleOptions` (0 unless pinned + idle). */
+ pinnedCount: number;
+ isChecked: (value: V) => boolean;
+ toggle: (value: V) => void;
+ /**
+ * Renderable bulk rows for the current search/cap state, in display order.
+ * Empty for single-select. Each entry carries its data (`enabled` or `items`)
+ * and a `run` closure that applies it.
+ */
+ bulkActions: Array<BulkAction<V>>;
+ /** Map a value back to its option label; falls back to `String(value)`. */
+ labelOf: (value: V) => string;
+}
+
+function asArray<V>(value: V[] | V | null): V[] {
+ if (value == null) {
+ return [];
+ }
+ return Array.isArray(value) ? value : [value];
+}
+
+interface SearchParams<V> {
+ options: Array<Option<V>>;
+ filterFn: FilterFn;
+}
+
+/** Search query and the options that currently match it. */
+function useSearch<V>({ options, filterFn }: SearchParams<V>): {
+ searchQuery: string;
+ setSearchQuery: (query: string) => void;
+ filteredOptions: Array<Option<V>>;
+} {
+ const [searchQuery, setSearchQuery] = useState("");
+ const filteredOptions = useMemo(() => {
+ if (!searchQuery) {
+ return options;
+ }
+ return options.filter((o) => filterFn(o.label, searchQuery) > 0);
+ }, [options, searchQuery, filterFn]);
+ return { searchQuery, setSearchQuery, filteredOptions };
+}
+
+interface PinningParams<V> {
+ value: V[] | V | null;
+ pinSelected: boolean;
+ options: Array<Option<V>>;
+ searchQuery: string;
+ filteredOptions: Array<Option<V>>;
+}
+
+/**
+ * Open state plus the frozen selection snapshot that orders the idle menu. The
+ * snapshot is retaken (`repin`) when the menu opens or the search clears, so a row
+ * toggled mid-session keeps its place instead of jumping to the top under the cursor.
+ */
+function usePinning<V>({
+ value,
+ pinSelected,
+ options,
+ searchQuery,
+ filteredOptions,
+}: PinningParams<V>): {
+ open: boolean;
+ setOpen: (open: boolean) => void;
+ repin: () => void;
+ visibleOptions: Array<Option<V>>;
+ pinnedCount: number;
+} {
+ const [open, setOpenState] = useState(false);
+ const [pinnedSelection, setPinnedSelection] = useState<Set<V>>(
+ () => new Set(asArray(value)),
+ );
+
+ const repin = (): void => setPinnedSelection(new Set(asArray(value)));
+
+ const setOpen = (nextOpen: boolean): void => {
+ setOpenState(nextOpen);
+ if (nextOpen) {
+ repin();
+ }
+ };
+
+ const { visibleOptions, pinnedCount } = useMemo(() => {
+ if (searchQuery || !pinSelected) {
+ return { visibleOptions: filteredOptions, pinnedCount: 0 };
+ }
+ return getVisibleOptions(options, pinnedSelection);
+ }, [searchQuery, pinSelected, filteredOptions, options, pinnedSelection]);
+
+ return { open, setOpen, repin, visibleOptions, pinnedCount };
+}
+
+interface ToggleParams<V> {
+ value: V[] | V | null;
+ onChange: (next: V[] | V | null) => void;
+ multiple: boolean;
+ maxSelections: number | undefined;
+ allowSelectNone: boolean | undefined;
+ selected: ReadonlySet<V>;
+}
+
+/** Membership test and the cap/cardinality-aware single-item toggle. */
+function useToggle<V>({
+ value,
+ onChange,
+ multiple,
+ maxSelections,
+ allowSelectNone,
+ selected,
+}: ToggleParams<V>): {
+ isChecked: (value: V) => boolean;
+ toggle: (value: V) => void;
+} {
+ const isChecked = (candidate: V): boolean => selected.has(candidate);
+
+ const toggle = (candidate: V): void => {
+ if (!multiple) {
+ if (allowSelectNone && value === candidate) {
+ onChange(null);
+ return;
+ }
+ onChange(candidate);
+ return;
+ }
+
+ const current = asArray(value);
+ if (selected.has(candidate)) {
+ onChange(current.filter((v) => v !== candidate));
+ return;
+ }
+
+ let next = [...current, candidate];
+ if (maxSelections != null && next.length > maxSelections) {
+ next = next.slice(-maxSelections);
+ }
+ onChange(next);
+ };
+
+ return { isChecked, toggle };
+}
+
+interface BulkParams<V> {
+ value: V[] | V | null;
+ onChange: (next: V[] | V | null) => void;
+ multiple: boolean;
+ options: Array<Option<V>>;
+ filteredOptions: Array<Option<V>>;
+ searchQuery: string;
+ maxSelections: number | undefined;
+}
+
+/** Bulk-row specs paired with run closures; inert for single-select. */
+function useBulk<V>({
+ value,
+ onChange,
+ multiple,
+ options,
+ filteredOptions,
+ searchQuery,
+ maxSelections,
+}: BulkParams<V>): { bulkActions: Array<BulkAction<V>> } {
+ const bulkActions = useMemo<Array<BulkAction<V>>>(() => {
+ if (!multiple) {
+ return [];
+ }
+ const specs = getBulkActions({
+ options,
+ filteredOptions,
+ value: asArray(value),
+ searchQuery,
+ maxSelections,
+ });
+ return specs.map((spec): BulkAction<V> => {
+ switch (spec.kind) {
+ case "select-all":
+ return {
+ ...spec,
+ run: () =>
+ onChange(
+ selectMatching(
+ asArray(value),
+ options.filter((o) => !o.disabled).map((o) => o.value),
+ ),
+ ),
+ };
+ case "deselect-all":
+ return { ...spec, run: () => onChange([]) };
+ case "select-matching":
+ return {
+ ...spec,
+ run: () =>
+ onChange(
+ selectMatching(
+ asArray(value),
+ spec.items.map((o) => o.value),
+ ),
+ ),
+ };
+ case "deselect-matching":
+ return {
+ ...spec,
+ run: () =>
+ onChange(
+ deselectMatching(
+ asArray(value),
+ spec.items.map((o) => o.value),
+ ),
+ ),
+ };
+ default:
+ return assertNever(spec);
+ }
+ });
+ }, [
+ multiple,
+ options,
+ filteredOptions,
+ value,
+ searchQuery,
+ maxSelections,
+ onChange,
+ ]);
+
+ return { bulkActions };
+}
+
+/**
+ * Headless state for a searchable select list, shared across the multiselect,
+ * dropdown, and top-K filter facades. Composes four focused concerns — search,
+ * pinning/freeze, membership/toggle, and bulk actions — behind one entry point.
+ * Pinning and bulk rows are opt-in so the single-select and top-K facades share
+ * only what they need.
+ */
+export function useSelectList<V>({
+ options,
+ value,
+ onChange,
+ multiple,
+ maxSelections,
+ allowSelectNone,
+ filterFn = multiselectFilterFn,
+ pinSelected = false,
+}: UseSelectListParams<V>): UseSelectListResult<V> {
+ const selected = useMemo(() => new Set(asArray(value)), [value]);
+
+ const labelByValue = useMemo(() => {
+ const map = new Map<V, string>();
+ for (const option of options) {
+ map.set(option.value, option.label);
+ }
+ return map;
+ }, [options]);
+ const labelOf = (candidate: V): string =>
+ labelByValue.get(candidate) ?? String(candidate);
+
+ const {
+ searchQuery,
+ setSearchQuery: setSearchQueryState,
+ filteredOptions,
+ } = useSearch({ options, filterFn });
+
+ const { open, setOpen, repin, visibleOptions, pinnedCount } = usePinning({
+ value,
+ pinSelected,
+ options,
+ searchQuery,
+ filteredOptions,
+ });
+
+ const { isChecked, toggle } = useToggle({
+ value,
+ onChange,
+ multiple,
+ maxSelections,
+ allowSelectNone,
+ selected,
+ });
+
+ const { bulkActions } = useBulk({
+ value,
+ onChange,
+ multiple,
+ options,
+ filteredOptions,
+ searchQuery,
+ maxSelections,
+ });
+
+ const setSearchQuery = (query: string): void => {
+ setSearchQueryState(query);
+ if (query === "") {
+ repin();
+ }
+ };
+
+ return {
+ searchQuery,
+ setSearchQuery,
+ open,
+ setOpen,
+ visibleOptions,
+ pinnedCount,
+ isChecked,
+ toggle,
+ bulkActions,
+ labelOf,
+ };
+}
diff --git a/frontend/src/components/ui/select-core/utils.ts b/frontend/src/components/ui/select-core/utils.ts
new file mode 100644
index 0000000000..b62d0a38b4
--- /dev/null
+++ b/frontend/src/components/ui/select-core/utils.ts
@@ -0,0 +1,121 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import type { BulkActionSpec, Option } from "./types";
+
+/**
+ * Override cmdk's relevance-sorting filter with a stricter membership test: an
+ * option matches only when every whitespace-separated query word appears in it
+ * (case-insensitive), in any order. More lenient than exact match, stricter than
+ * fuzzy.
+ *
+ * Examples:
+ * - "foo bar" matches "foo bar"
+ * - "bar foo" matches "foo bar"
+ * - "foob" does not match "foo bar"
+ */
+export function multiselectFilterFn(option: string, value: string): number {
+ const words = value.split(/\s+/);
+ const match = words.every((word) =>
+ option.toLowerCase().includes(word.toLowerCase()),
+ );
+ return match ? 1 : 0;
+}
+
+/** Union: append the not-yet-selected members of `toAdd`, preserving order. */
+export function selectMatching<V>(selected: V[], toAdd: V[]): V[] {
+ const set = new Set(selected);
+ return [...set, ...toAdd.filter((v) => !set.has(v))];
+}
+
+/** Difference: drop every member of `toRemove` from `selected`. */
+export function deselectMatching<V>(selected: V[], toRemove: V[]): V[] {
+ const set = new Set(toRemove);
+ return selected.filter((v) => !set.has(v));
+}
+
+/**
+ * Order options for the idle (no active search) menu: pinned selections first in
+ * pin insertion order (so a freshly added selection appears after earlier ones),
+ * then everything else in option order. `pinnedSelection` is a frozen snapshot
+ * taken when the menu opens, so toggling an item does not reorder the list under
+ * the cursor. Returns the count of pinned options alongside the list so callers
+ * don't have to re-scan to find where the pinned block ends.
+ */
+export function getVisibleOptions<V>(
+ options: Array<Option<V>>,
+ pinnedSelection: ReadonlySet<V>,
+): { visibleOptions: Array<Option<V>>; pinnedCount: number } {
+ const byValue = new Map(options.map((o) => [o.value, o] as const));
+ const pinned: Array<Option<V>> = [];
+ for (const value of pinnedSelection) {
+ const option = byValue.get(value);
+ if (option) {
+ pinned.push(option);
+ }
+ }
+ const rest = options.filter((o) => !pinnedSelection.has(o.value));
+ return { visibleOptions: [...pinned, ...rest], pinnedCount: pinned.length };
+}
+
+/**
+ * Decide which bulk rows the menu shows for the current search/cap state.
+ *
+ * When searching, the select-side spec carries the unselected matches and the
+ * deselect-side spec carries the selected matches (each omitted when empty).
+ * When idle, the spec is just `select-all` / `deselect-all` with an `enabled`
+ * flag for the disabled-but-visible state. `maxSelections` hides the select-
+ * side everywhere (a bulk select could exceed the cap); `maxSelections === 1`
+ * suppresses bulk rows entirely. Returns `[]` when bulk rows shouldn't show.
+ *
+ * Specs come in select-then-deselect order so the facade can render them as-is.
+ */
+export function getBulkActions<V>(params: {
+ options: Array<Option<V>>;
+ filteredOptions: Array<Option<V>>;
+ value: V[];
+ searchQuery: string;
+ maxSelections: number | undefined;
+}): Array<BulkActionSpec<V>> {
+ const { options, filteredOptions, value, searchQuery, maxSelections } =
+ params;
+
+ if (options.length <= 2 || maxSelections === 1) {
+ return [];
+ }
+
+ const capped = maxSelections != null;
+ const specs: Array<BulkActionSpec<V>> = [];
+
+ if (searchQuery !== "") {
+ if (filteredOptions.length === 0) {
+ return [];
+ }
+ const selected = new Set(value);
+ const selectedMatches: Array<Option<V>> = [];
+ const unselectedMatches: Array<Option<V>> = [];
+ for (const option of filteredOptions) {
+ if (selected.has(option.value)) {
+ selectedMatches.push(option);
+ } else if (!option.disabled) {
+ // Disabled rows can't be picked individually, so bulk select skips them too.
+ unselectedMatches.push(option);
+ }
+ }
+ if (!capped && unselectedMatches.length > 0) {
+ specs.push({ kind: "select-matching", items: unselectedMatches });
+ }
+ if (selectedMatches.length > 0) {
+ specs.push({ kind: "deselect-matching", items: selectedMatches });
+ }
+ return specs;
+ }
+
+ if (!capped) {
+ const selected = new Set(value);
+ specs.push({
+ kind: "select-all",
+ enabled: options.some((o) => !o.disabled && !selected.has(o.value)),
+ });
+ }
+ specs.push({ kind: "deselect-all", enabled: value.length > 0 });
+ return specs;
+}
diff --git a/frontend/src/components/data-table/value-chips.tsx b/frontend/src/components/ui/value-chips.tsx
similarity index 100%
rename from frontend/src/components/data-table/value-chips.tsx
rename to frontend/src/components/ui/value-chips.tsx
diff --git a/frontend/src/plugins/impl/MultiselectPlugin.tsx b/frontend/src/plugins/impl/MultiselectPlugin.tsx
index 46f6736a53..6328fea884 100644
--- a/frontend/src/plugins/impl/MultiselectPlugin.tsx
+++ b/frontend/src/plugins/impl/MultiselectPlugin.tsx
@@ -1,13 +1,10 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { type JSX, useId, useMemo, useState } from "react";
-import { Virtuoso } from "react-virtuoso";
+import { type JSX, useId, useMemo } from "react";
import { z } from "zod";
-import { cn } from "@/utils/cn";
-import { Combobox, ComboboxItem } from "../../components/ui/combobox";
-import { CommandSeparator } from "../../components/ui/command";
+import type { Option } from "@/components/ui/select-core";
+import { SelectList } from "@/components/ui/select-core";
import type { IPlugin, IPluginProps, Setter } from "../types";
import { Labeled } from "./common/labeled";
-import { multiselectFilterFn } from "./multiselectFilterFn";
interface Data {
label: string | null;
@@ -55,9 +52,6 @@ interface MultiselectProps extends Data {
setValue: Setter<T>;
}
-const SELECT_ALL_KEY = "__select_all__";
-const DESELECT_ALL_KEY = "__deselect_all__";
-
export const Multiselect = ({
options,
label,
@@ -68,144 +62,27 @@ export const Multiselect = ({
disabled,
}: MultiselectProps): JSX.Element => {
const id = useId();
- const [searchQuery, setSearchQuery] = useState<string>("");
-
- const filteredOptions = useMemo(() => {
- if (!searchQuery) {
- return options;
- }
- return options.filter(
- (option) => multiselectFilterFn(option, searchQuery) === 1,
- );
- }, [options, searchQuery]);
-
- const handleValueChange = (newValues: string[] | null) => {
- if (!newValues || newValues.length === 0) {
- setValue([]);
- return;
- }
-
- // Remove select all and deselect all from the new values
- newValues = newValues.filter(
- (value) => value !== SELECT_ALL_KEY && value !== DESELECT_ALL_KEY,
- );
-
- if (maxSelections === 1) {
- // For single selection, just take the last selected value
- setValue([newValues[newValues.length - 1]]);
- return;
- }
-
- if (maxSelections != null && newValues.length > maxSelections) {
- // When over max selections, remove oldest selections
- newValues = newValues.slice(-maxSelections);
- }
- setValue(newValues);
- };
-
- const handleSelectAll = () => {
- setValue(options);
- };
-
- const handleDeselectAll = () => {
- setValue([]);
- };
-
- const extraOptions: React.ReactNode[] = [];
- const selectAllEnabled = options.length > 0 && value.length < options.length;
- const deselectAllEnabled = options.length > 0 && value.length > 0;
-
- // Only show when more than 2 options
- // Only show select all when maxSelections is not set
- if (options.length > 2 && maxSelections == null) {
- extraOptions.push(
- <ComboboxItem
- key={SELECT_ALL_KEY}
- value={SELECT_ALL_KEY}
- onSelect={handleSelectAll}
- disabled={!selectAllEnabled}
- >
- Select all
- </ComboboxItem>,
- );
- }
-
- if (options.length > 2) {
- extraOptions.push(
- <ComboboxItem
- key={DESELECT_ALL_KEY}
- value={DESELECT_ALL_KEY}
- onSelect={handleDeselectAll}
- disabled={!deselectAllEnabled}
- >
- {maxSelections === 1 ? "Deselect" : "Deselect all"}
- </ComboboxItem>,
- <CommandSeparator key="_separator" />,
- );
- }
-
- const renderList = () => {
- // List virtualization
- if (filteredOptions.length > 200) {
- return (
- <Virtuoso
- style={{ height: "200px" }}
- totalCount={filteredOptions.length}
- overscan={50}
- itemContent={(i: number) => {
- const comboboxItem = (
- <ComboboxItem key={filteredOptions[i]} value={filteredOptions[i]}>
- {filteredOptions[i]}
- </ComboboxItem>
- );
-
- if (i === 0) {
- return (
- <>
- {extraOptions}
- {comboboxItem}
- </>
- );
- }
-
- return comboboxItem;
- }}
- />
- );
- }
-
- const list = filteredOptions.map((option) => (
- <ComboboxItem key={option} value={option}>
- {option}
- </ComboboxItem>
- ));
-
- return (
- <>
- {extraOptions}
- {list}
- </>
- );
- };
+ const items = useMemo<Array<Option<string>>>(
+ () => options.map((option) => ({ value: option, label: option })),
+ [options],
+ );
return (
<Labeled label={label} id={id} fullWidth={fullWidth}>
- <Combobox<string>
- displayValue={(option) => option}
- placeholder="Select..."
- multiple={true}
- className={cn({
- "w-full": fullWidth,
- })}
+ <SelectList<string>
+ id={id}
+ options={items}
value={value}
- onValueChange={handleValueChange}
- shouldFilter={false}
- search={searchQuery}
- onSearchChange={setSearchQuery}
+ onChange={(next: string[] | string | null) =>
+ setValue((next as string[] | null) ?? [])
+ }
+ multiple={true}
+ maxSelections={maxSelections}
+ pinSelected={true}
+ compactChipTrigger={true}
+ fullWidth={fullWidth}
disabled={disabled}
- >
- {renderList()}
- </Combobox>
+ />
</Labeled>
);
};
diff --git a/frontend/src/plugins/impl/SearchableSelect.tsx b/frontend/src/plugins/impl/SearchableSelect.tsx
index b7bee98352..471103e6e2 100644
--- a/frontend/src/plugins/impl/SearchableSelect.tsx
+++ b/frontend/src/plugins/impl/SearchableSelect.tsx
@@ -1,10 +1,9 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { type JSX, useId, useMemo, useState } from "react";
-import { Virtuoso } from "react-virtuoso";
-import { Combobox, ComboboxItem } from "../../components/ui/combobox";
+import { type JSX, useId, useMemo } from "react";
+import type { Option } from "@/components/ui/select-core";
+import { SelectList } from "@/components/ui/select-core";
import { cn } from "../../utils/cn";
import { Labeled } from "./common/labeled";
-import { multiselectFilterFn } from "./multiselectFilterFn";
interface SearchableSelectProps {
options: string[];
@@ -16,8 +15,6 @@ interface SearchableSelectProps {
disabled: boolean;
}
-const NONE_KEY = "__none__";
-
export const SearchableSelect = (props: SearchableSelectProps): JSX.Element => {
const {
options,
@@ -29,104 +26,26 @@ export const SearchableSelect = (props: SearchableSelectProps): JSX.Element => {
disabled,
} = props;
const id = useId();
- const [searchQuery, setSearchQuery] = useState<string>("");
-
- const filteredOptions = useMemo(() => {
- if (!searchQuery) {
- return options;
- }
- return options.filter(
- (option) => multiselectFilterFn(option, searchQuery) === 1,
- );
- }, [options, searchQuery]);
-
- const handleValueChange = (newValue: string | null) => {
- if (newValue == null) {
- return;
- }
-
- if (newValue === NONE_KEY) {
- setValue(null);
- } else {
- setValue(newValue);
- }
- };
-
- const renderList = () => {
- const extraOptions = allowSelectNone ? (
- <ComboboxItem key={NONE_KEY} value={NONE_KEY}>
- --
- </ComboboxItem>
- ) : null;
-
- if (filteredOptions.length > 200) {
- return (
- <Virtuoso
- style={{ height: "200px" }}
- totalCount={filteredOptions.length}
- overscan={50}
- itemContent={(i: number) => {
- const option = filteredOptions[i];
- const comboboxItem = (
- <ComboboxItem key={option} value={option}>
- {option}
- </ComboboxItem>
- );
-
- if (i === 0) {
- return (
- <>
- {extraOptions}
- {comboboxItem}
- </>
- );
- }
-
- return comboboxItem;
- }}
- />
- );
- }
-
- const list = filteredOptions.map((option) => (
- <ComboboxItem key={option} value={option}>
- {option}
- </ComboboxItem>
- ));
-
- return (
- <>
- {extraOptions}
- {list}
- </>
- );
- };
+ const items = useMemo<Array<Option<string>>>(
+ () => options.map((option) => ({ value: option, label: option })),
+ [options],
+ );
return (
<Labeled label={label} id={id} fullWidth={fullWidth}>
- <Combobox<string>
- displayValue={(option) => {
- if (option === NONE_KEY) {
- return "--";
- }
- return option;
- }}
- placeholder="Select..."
+ <SelectList<string>
+ id={id}
+ options={items}
+ value={value}
+ onChange={(next) => setValue((next as string | null) ?? null)}
multiple={false}
- className={cn({
- "w-full": fullWidth,
- })}
- value={value ?? NONE_KEY}
- onValueChange={handleValueChange}
- shouldFilter={false}
- search={searchQuery}
- onSearchChange={setSearchQuery}
+ allowSelectNone={allowSelectNone}
+ fullWidth={fullWidth}
disabled={disabled}
+ className={cn({ "w-full": fullWidth })}
data-testid="marimo-plugin-searchable-dropdown"
- >
- {renderList()}
- </Combobox>
+ />
</Labeled>
);
};
diff --git a/frontend/src/plugins/impl/__tests__/DropdownPlugin.test.tsx b/frontend/src/plugins/impl/__tests__/DropdownPlugin.test.tsx
index f285e85f08..d0b3fb8404 100644
--- a/frontend/src/plugins/impl/__tests__/DropdownPlugin.test.tsx
+++ b/frontend/src/plugins/impl/__tests__/DropdownPlugin.test.tsx
@@ -225,8 +225,11 @@ describe("DropdownPlugin", () => {
screen.getByTestId("marimo-plugin-searchable-dropdown").firstChild!,
);
- // Select none should clear value
- fireEvent.click(screen.getByText("--"));
+ // Re-picking the current value clears it when allowSelectNone
+ const bananaOption = screen
+ .getAllByRole("option")
+ .find((el) => el.textContent === "Banana");
+ fireEvent.click(bananaOption!);
expect(setValue).toHaveBeenCalledWith([]);
});
});
diff --git a/frontend/src/plugins/impl/__tests__/MultiSelectPlugin.test.ts b/frontend/src/plugins/impl/__tests__/MultiSelectPlugin.test.ts
index fb99eb73f2..68fbc5aaa0 100644
--- a/frontend/src/plugins/impl/__tests__/MultiSelectPlugin.test.ts
+++ b/frontend/src/plugins/impl/__tests__/MultiSelectPlugin.test.ts
@@ -2,7 +2,7 @@
import { beforeEach, expect, it, vi } from "vitest";
import { initialModeAtom } from "@/core/mode";
import { store } from "@/core/state/jotai";
-import { multiselectFilterFn } from "../multiselectFilterFn";
+import { multiselectFilterFn } from "@/components/ui/select-core";
function filterOptions(filter: string, items: string[]) {
return items.filter((option) => multiselectFilterFn(option, filter));
diff --git a/frontend/src/plugins/impl/multiselectFilterFn.tsx b/frontend/src/plugins/impl/multiselectFilterFn.tsx
deleted file mode 100644
index f41380d598..0000000000
--- a/frontend/src/plugins/impl/multiselectFilterFn.tsx
+++ /dev/null
@@ -1,22 +0,0 @@
-/* Copyright 2026 Marimo. All rights reserved. */
-
-/**
- * We override the default filter function which focuses on sorting by relevance with a fuzzy-match,
- * instead of filtering out.
- * The default filter function is `command-score`.
- *
- * Our filter function only matches if all words in the value are present in the option.
- * This is more strict than the default, but more lenient than an exact match.
- *
- * Examples:
- * - "foo bar" matches "foo bar"
- * - "bar foo" matches "foo bar"
- * - "foob" does not matches "foo bar"
- */
-export function multiselectFilterFn(option: string, value: string): number {
- const words = value.split(/\s+/);
- const match = words.every((word) =>
- option.toLowerCase().includes(word.toLowerCase()),
- );
- return match ? 1 : 0;
-}