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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: add searchable dropdown functionality (#3723)
devin-ai-integration[bot]ce90ae8434bc
diff --git a/frontend/src/components/ui/combobox.tsx b/frontend/src/components/ui/combobox.tsxindex 871193baa1..ef79a58e15 100644--- a/frontend/src/components/ui/combobox.tsx+++ b/frontend/src/components/ui/combobox.tsx@@ -92,6 +92,7 @@ export const Combobox = <TValue,>({chips = false,chipsClassName,keepPopoverOpenOnSelect,+ ...rest}: ComboboxProps<TValue>) => {const [open = false, setOpen] = useControllableState({prop: openProp,@@ -163,7 +164,7 @@ export const Combobox = <TValue,>({};return (- <div className={cn("relative")}>+ <div className={cn("relative")} {...rest}><Popover open={open} onOpenChange={setOpen}><PopoverTrigger asChild={true}><divdiff --git a/frontend/src/plugins/impl/DropdownPlugin.tsx b/frontend/src/plugins/impl/DropdownPlugin.tsxindex 4a1386e070..22ee94c12e 100644--- a/frontend/src/plugins/impl/DropdownPlugin.tsx+++ b/frontend/src/plugins/impl/DropdownPlugin.tsx@@ -5,13 +5,15 @@ import { z } from "zod";import type { IPlugin, IPluginProps } from "../types";import { NativeSelect } from "../../components/ui/native-select";import { Labeled } from "./common/labeled";-import { cn } from "@/utils/cn";+import { cn } from "../../utils/cn";+import { SearchableSelect } from "./SearchableSelect";interface Data {label: string | null;options: string[];allowSelectNone: boolean;fullWidth: boolean;+ searchable: boolean;}export class DropdownPlugin implements IPlugin<string[], Data> {@@ -23,9 +25,18 @@ export class DropdownPlugin implements IPlugin<string[], Data> {options: z.array(z.string()),allowSelectNone: z.boolean(),fullWidth: z.boolean().default(false),+ searchable: z.boolean().default(false),});render(props: IPluginProps<string[], Data>): JSX.Element {+ if (props.data.searchable) {+ const value = props.value.length > 0 ? props.value[0] : null;+ const setValue = (newValue: string | null) =>+ props.setValue(newValue ? [newValue] : []);+ return (+ <SearchableSelect {...props.data} value={value} setValue={setValue} />+ );+ }return (<Dropdown {...props.data} value={props.value} setValue={props.setValue} />);diff --git a/frontend/src/plugins/impl/MultiselectPlugin.tsx b/frontend/src/plugins/impl/MultiselectPlugin.tsxindex 1feaf3af3e..814c8d7016 100644--- a/frontend/src/plugins/impl/MultiselectPlugin.tsx+++ b/frontend/src/plugins/impl/MultiselectPlugin.tsx@@ -8,6 +8,7 @@ import { Labeled } from "./common/labeled";import { cn } from "@/utils/cn";import { Virtuoso } from "react-virtuoso";import { CommandSeparator } from "../../components/ui/command";+import { multiselectFilterFn } from "./multiselectFilterFn";interface Data {label: string | null;@@ -81,13 +82,22 @@ const Multiselect = ({setValue([]);return;}- if (maxSelections != null && newValues.length > maxSelections) {- return;- }+// Remove select all and deselect all from the new valuesnewValues = 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);};@@ -99,32 +109,38 @@ const Multiselect = ({setValue([]);};- const shouldShowSelectAll =- options.length > 0 && value.length < options.length;- const shouldShowDeselectAll = options.length > 0 && value.length > 0;+ 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- const extraOptions = options.length > 2 && (- <>+ // Only show select all when maxSelections is not set+ if (options.length > 2 && maxSelections == null) {+ extraOptions.push(<ComboboxItemkey={SELECT_ALL_KEY}value={SELECT_ALL_KEY}onSelect={handleSelectAll}- disabled={!shouldShowSelectAll}+ disabled={!selectAllEnabled}>Select all- </ComboboxItem>+ </ComboboxItem>,+ );+ }++ if (options.length > 2) {+ extraOptions.push(<ComboboxItemkey={DESELECT_ALL_KEY}value={DESELECT_ALL_KEY}onSelect={handleDeselectAll}- disabled={!shouldShowDeselectAll}+ disabled={!deselectAllEnabled}>- Deselect all- </ComboboxItem>- <CommandSeparator />- </>- );+ {maxSelections === 1 ? "Deselect" : "Deselect all"}+ </ComboboxItem>,+ <CommandSeparator key="_separator" />,+ );+ }const renderList = () => {// List virtualization@@ -190,28 +206,3 @@ const Multiselect = ({</Labeled>);};--/**- * 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"- */-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;-}--export const exportedForTesting = {- multiselectFilterFn,-};diff --git a/frontend/src/plugins/impl/SearchableSelect.tsx b/frontend/src/plugins/impl/SearchableSelect.tsxnew file mode 100644index 0000000000..a20f58f28d--- /dev/null+++ b/frontend/src/plugins/impl/SearchableSelect.tsx@@ -0,0 +1,120 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { useId, useMemo, useState } from "react";+import { Combobox, ComboboxItem } from "../../components/ui/combobox";+import { Labeled } from "./common/labeled";+import { cn } from "../../utils/cn";+import { multiselectFilterFn } from "./multiselectFilterFn";+import { Virtuoso } from "react-virtuoso";++interface SearchableSelectProps {+ options: string[];+ value: string | null;+ setValue: (value: string | null) => void;+ label: string | null;+ allowSelectNone: boolean;+ fullWidth: boolean;+}++const NONE_KEY = "__none__";++export const SearchableSelect = (props: SearchableSelectProps): JSX.Element => {+ const { options, value, setValue, label, allowSelectNone, fullWidth } = 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}+ </>+ );+ };++ return (+ <Labeled label={label} id={id} fullWidth={fullWidth}>+ <Combobox<string>+ displayValue={(option) => {+ if (option === NONE_KEY) {+ return "--";+ }+ return option;+ }}+ placeholder="Select..."+ multiple={false}+ className={cn("w-full", { "w-full": fullWidth })}+ value={value ?? NONE_KEY}+ onValueChange={handleValueChange}+ shouldFilter={false}+ search={searchQuery}+ onSearchChange={setSearchQuery}+ 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.tsxnew file mode 100644index 0000000000..37323cd7c8--- /dev/null+++ b/frontend/src/plugins/impl/__tests__/DropdownPlugin.test.tsx@@ -0,0 +1,178 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { render, screen, fireEvent } from "@testing-library/react";+import { describe, it, vi, expect, beforeAll } from "vitest";+import { DropdownPlugin } from "../DropdownPlugin";+import type { IPluginProps } from "../../types";++beforeAll(() => {+ global.ResizeObserver = class ResizeObserver {+ observe() {+ // do nothing+ }+ unobserve() {+ // do nothing+ }+ disconnect() {+ // do nothing+ }+ };+ global.HTMLDivElement.prototype.scrollIntoView = () => {+ // do nothing+ };+});++describe("DropdownPlugin", () => {+ describe("searchable dropdown", () => {+ it("renders SearchableSelect when searchable is true", () => {+ const plugin = new DropdownPlugin();+ const host = document.createElement("div");+ const props: IPluginProps<+ string[],+ (typeof plugin)["validator"]["_type"]+ > = {+ data: {+ label: "Test Label",+ options: ["Option 1", "Option 2"],+ allowSelectNone: false,+ fullWidth: false,+ searchable: true,+ initialValue: [],+ },+ value: [],+ setValue: vi.fn(),+ host,+ functions: {},+ };+ render(plugin.render(props));+ expect(+ screen.getByTestId("marimo-plugin-searchable-dropdown"),+ ).toBeInTheDocument();+ });++ it("renders default dropdown when searchable is false", () => {+ const plugin = new DropdownPlugin();+ const host = document.createElement("div");+ const props: IPluginProps<+ string[],+ (typeof plugin)["validator"]["_type"]+ > = {+ data: {+ label: "Test Label",+ options: ["Option 1", "Option 2"],+ allowSelectNone: false,+ fullWidth: false,+ searchable: false,+ initialValue: [],+ },+ value: [],+ setValue: vi.fn(),+ host,+ functions: {},+ };+ render(plugin.render(props));+ expect(screen.getByTestId("marimo-plugin-dropdown")).toBeInTheDocument();+ });++ it("filters options based on search input and handles selection", async () => {+ const plugin = new DropdownPlugin();+ const host = document.createElement("div");+ const setValue = vi.fn();+ const props: IPluginProps<+ string[],+ (typeof plugin)["validator"]["_type"]+ > = {+ data: {+ label: "Test Label",+ options: ["Apple", "Banana", "Orange"],+ allowSelectNone: true,+ fullWidth: false,+ searchable: true,+ initialValue: [],+ },+ value: [],+ setValue,+ host,+ functions: {},+ };+ render(plugin.render(props));++ // Open dropdown+ fireEvent.click(+ screen.getByTestId("marimo-plugin-searchable-dropdown").firstChild!,+ );++ // Initial empty state+ const input = screen.getByRole("combobox");+ expect(input).toHaveValue("");++ // Search functionality+ fireEvent.change(input, { target: { value: "app" } });+ expect(screen.getByText("Apple")).toBeInTheDocument();+ expect(screen.queryByText("Banana")).not.toBeInTheDocument();++ // Selection after search+ fireEvent.click(screen.getByText("Apple"));+ expect(setValue).toHaveBeenCalledWith(["Apple"]);+ });++ it("supports single selection only", async () => {+ const plugin = new DropdownPlugin();+ const host = document.createElement("div");+ const setValue = vi.fn();+ const props: IPluginProps<+ string[],+ (typeof plugin)["validator"]["_type"]+ > = {+ data: {+ label: "Test Label",+ options: ["Apple", "Banana", "Orange"],+ allowSelectNone: true,+ fullWidth: false,+ searchable: true,+ initialValue: [],+ },+ value: ["Apple"],+ setValue,+ host,+ functions: {},+ };+ const { rerender } = render(plugin.render(props));++ // Initial value should be displayed+ expect(+ screen.getByTestId("marimo-plugin-searchable-dropdown").firstChild+ ?.textContent,+ ).toContain("Apple");++ // Open dropdown+ fireEvent.click(+ screen.getByTestId("marimo-plugin-searchable-dropdown").firstChild!,+ );++ // Select second option - should replace first+ fireEvent.click(screen.getByText("Banana"));+ expect(setValue).toHaveBeenCalledWith(["Banana"]);++ // Re-render+ rerender(+ plugin.render({+ ...props,+ value: ["Banana"],+ }),+ );+ expect(+ screen.getByTestId("marimo-plugin-searchable-dropdown").firstChild+ ?.textContent,+ ).toContain("Banana");++ // Open dropdown+ fireEvent.click(+ screen.getByTestId("marimo-plugin-searchable-dropdown").firstChild!,+ );++ // Select none should clear value+ fireEvent.click(screen.getByText("--"));+ expect(setValue).toHaveBeenCalledWith([]);+ });+ });+});diff --git a/frontend/src/plugins/impl/__tests__/MultiSelectPlugin.test.ts b/frontend/src/plugins/impl/__tests__/MultiSelectPlugin.test.tsindex 72eef52274..da34742231 100644--- a/frontend/src/plugins/impl/__tests__/MultiSelectPlugin.test.ts+++ b/frontend/src/plugins/impl/__tests__/MultiSelectPlugin.test.ts@@ -1,10 +1,9 @@/* Copyright 2024 Marimo. All rights reserved. */import { expect, it } from "vitest";-import { exportedForTesting } from "../MultiselectPlugin";+import { multiselectFilterFn } from "../multiselectFilterFn";-const filterFn = exportedForTesting.multiselectFilterFn;function filterOptions(filter: string, items: string[]) {- return items.filter((option) => filterFn(option, filter));+ return items.filter((option) => multiselectFilterFn(option, filter));}it("can filter to relevant words", () => {diff --git a/frontend/src/plugins/impl/data-frames/forms/__tests__/__snapshots__/form.test.tsx.snap b/frontend/src/plugins/impl/data-frames/forms/__tests__/__snapshots__/form.test.tsx.snapindex 66b28647c4..5c04f58cd1 100644--- a/frontend/src/plugins/impl/data-frames/forms/__tests__/__snapshots__/form.test.tsx.snap+++ b/frontend/src/plugins/impl/data-frames/forms/__tests__/__snapshots__/form.test.tsx.snap@@ -148,7 +148,10 @@ exports[`renderZodSchema > should render a form 2`] = `Columns</label><div+ aria-describedby=":r3:-form-item-description"+ aria-invalid="false"class="relative"+ id=":r3:-form-item"><divaria-controls="radix-:r4:"@@ -629,7 +632,10 @@ exports[`renderZodSchema > should render a form 6`] = `Columns</label><div+ aria-describedby=":r1q:-form-item-description"+ aria-invalid="false"class="relative"+ id=":r1q:-form-item"><divaria-controls="radix-:r1r:"@@ -768,7 +774,10 @@ exports[`renderZodSchema > should render a form 7`] = `Columns</label><div+ aria-describedby=":r26:-form-item-description"+ aria-invalid="false"class="relative"+ id=":r26:-form-item"><divaria-controls="radix-:r27:"@@ -815,7 +824,10 @@ exports[`renderZodSchema > should render a form 7`] = `Aggregations</label><div+ aria-describedby=":r28:-form-item-description"+ aria-invalid="false"class="relative"+ id=":r28:-form-item"><divaria-controls="radix-:r29:"@@ -1109,7 +1121,10 @@ exports[`renderZodSchema > should render a form 10`] = `Columns</label><div+ aria-describedby=":r2o:-form-item-description"+ aria-invalid="false"class="relative"+ id=":r2o:-form-item"><divaria-controls="radix-:r2p:"diff --git a/frontend/src/plugins/impl/multiselectFilterFn.tsx b/frontend/src/plugins/impl/multiselectFilterFn.tsxnew file mode 100644index 0000000000..e03a312624--- /dev/null+++ b/frontend/src/plugins/impl/multiselectFilterFn.tsx@@ -0,0 +1,20 @@+/**+ * 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;+}diff --git a/frontend/src/setupTests.ts b/frontend/src/setupTests.tsnew file mode 100644index 0000000000..15af1ce042--- /dev/null+++ b/frontend/src/setupTests.ts@@ -0,0 +1,9 @@+/* Copyright 2024 Marimo. All rights reserved. */+import "@testing-library/jest-dom";++declare module "vitest" {+ interface Assertion {+ toBeInTheDocument(): void;+ toHaveValue(value: string | string[]): void;+ }+}diff --git a/marimo/_plugins/ui/_impl/input.py b/marimo/_plugins/ui/_impl/input.pyindex e839b872bc..7dbb91f32f 100644--- a/marimo/_plugins/ui/_impl/input.py+++ b/marimo/_plugins/ui/_impl/input.py@@ -895,6 +895,14 @@ class dropdown(UIElement[List[str], Any]):dropdown = mo.ui.dropdown(options=["a", "b", "c"], value="a", label="choose one")++ # With search functionality+ dropdown = mo.ui.dropdown(+ options=["a", "b", "c"],+ value="a",+ label="choose one",+ searchable=True,+ )``````python@@ -922,6 +930,8 @@ class dropdown(UIElement[List[str], Any]):allow_select_none (bool, optional): Whether to include special option ("--")for a None value; when None, defaults to True when value is None.Defaults to None.+ searchable (bool, optional): Whether to enable search functionality.+ Defaults to False.label (str, optional): Markdown label for the element. Defaults to "".on_change (Callable[[Any], None], optional): Optional callback to run whenthis element's value changes. Defaults to None.@@ -938,6 +948,7 @@ class dropdown(UIElement[List[str], Any]):options: Sequence[str] | dict[str, Any],value: Optional[str] = None,allow_select_none: Optional[bool] = None,+ searchable: bool = False,*,label: str = "",on_change: Optional[Callable[[Any], None]] = None,@@ -980,6 +991,7 @@ class dropdown(UIElement[List[str], Any]):args={"options": list(self.options.keys()),"allow-select-none": allow_select_none,+ "searchable": searchable,"full-width": full_width,},on_change=on_change,diff --git a/marimo/_smoke_tests/dropdowns.py b/marimo/_smoke_tests/dropdowns.pynew file mode 100644index 0000000000..b44dd2d99d--- /dev/null+++ b/marimo/_smoke_tests/dropdowns.py@@ -0,0 +1,113 @@+import marimo++__generated_with = "0.11.0"+app = marimo.App(width="medium")++[email protected](hide_code=True)+def _(mo):+ mo.md(r"""# dropdown""")+ return+++def _():+ import marimo as mo+ return (mo,)+++def _(mo):+ # Single selection dropdown+ dropdown1 = mo.ui.dropdown(+ options=["Option 1", "Option 2", "Option 3"], value="Option 1"+ )++ # Searchable dropdown+ dropdown2 = mo.ui.dropdown(+ options=["Red", "Blue", "Green", "Yellow"],+ value="Yellow",+ searchable=True,+ )++ # Searchable dropdown, with deselect+ dropdown3 = mo.ui.dropdown(+ options=["Red", "Blue", "Green", "Yellow"],+ value="Yellow",+ searchable=True,+ allow_select_none=True,+ )++ # Dropdown with dictionary+ dropdown4 = mo.ui.dropdown(+ options={"A": 1, "B": 2, "C": 3}, value="A", allow_select_none=True+ )+ return dropdown1, dropdown2, dropdown3, dropdown4+++def _(dropdown1, dropdown2, dropdown3, dropdown4):+ [+ dropdown1,+ dropdown2,+ dropdown3,+ dropdown4,+ ]+ return+++def _(mo):+ # Virtualized+ mo.ui.dropdown(+ options=[str(i) for i in range(1000)],+ value=None,+ searchable=True,+ allow_select_none=True,+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(r"""# multiselect""")+ return+++def _(mo):+ # multiselect+ multiselect1 = mo.ui.multiselect(+ options=["Option 1", "Option 2", "Option 3"], value=["Option 1"]+ )+++ # mutliselect of 1+ multiselect2 = mo.ui.multiselect(+ options=["Red", "Blue", "Green", "Yellow"],+ max_selections=1,+ )++ # multiselect with dictionary+ multiselect3 = mo.ui.multiselect(options={"A": 1, "B": 2, "C": 3}, value=["A"])++ # multiselec with max 2+ multiselect4 = mo.ui.multiselect(+ options=["Cat", "Dog", "Bird"], value=None, max_selections=2+ )+ return multiselect1, multiselect2, multiselect3, multiselect4+++def _(multiselect1, multiselect2, multiselect3, multiselect4):+ [+ multiselect1,+ multiselect2,+ multiselect3,+ multiselect4,+ ]+ return+++if __name__ == "__main__":+ app.run()