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: Limit maximum selections in mo.ui.multiselect (#996)

Wasim Sandhud12191fc3276
diff --git a/frontend/src/plugins/impl/MultiselectPlugin.tsx b/frontend/src/plugins/impl/MultiselectPlugin.tsx
index 98daa8aa24..657ba59a82 100644
--- a/frontend/src/plugins/impl/MultiselectPlugin.tsx
+++ b/frontend/src/plugins/impl/MultiselectPlugin.tsx
@@ -11,6 +11,7 @@ interface Data {
label: string | null;
options: string[];
fullWidth: boolean;
+ maxSelections?: number | undefined;
}
type T = string[];
@@ -23,6 +24,7 @@ export class MultiselectPlugin implements IPlugin<T, Data> {
label: z.string().nullable(),
options: z.array(z.string()),
fullWidth: z.boolean().default(false),
+ maxSelections: z.number().optional(),
});
render(props: IPluginProps<string[], Data>): JSX.Element {
@@ -52,6 +54,13 @@ interface MultiselectProps extends Data {
const Multiselect = (props: MultiselectProps): JSX.Element => {
const id = useId();
+ function setValue(newValues: T) {
+ if (props.maxSelections != null && newValues.length > props.maxSelections) {
+ return;
+ }
+ props.setValue(newValues);
+ }
+
return (
<Labeled label={props.label} id={id} fullWidth={props.fullWidth}>
<Combobox<string>
@@ -63,7 +72,7 @@ const Multiselect = (props: MultiselectProps): JSX.Element => {
"w-full": props.fullWidth,
})}
value={props.value}
- onValueChange={(newValues) => props.setValue(newValues || [])}
+ onValueChange={(newValues) => setValue(newValues || [])}
>
{props.options.map((option) => (
<ComboboxItem key={option} value={option}>
diff --git a/marimo/_plugins/ui/_impl/input.py b/marimo/_plugins/ui/_impl/input.py
index 4ad781ede3..b3087656c0 100644
--- a/marimo/_plugins/ui/_impl/input.py
+++ b/marimo/_plugins/ui/_impl/input.py
@@ -632,6 +632,7 @@ class multiselect(UIElement[List[str], List[object]]):
- `on_change`: optional callback to run when this element's value changes
- `full_width`: whether the input should take up the full width of its
container
+ - `max_selections`: maximum number of items that can be selected
"""
_name: Final[str] = "marimo-multiselect"
@@ -644,6 +645,7 @@ class multiselect(UIElement[List[str], List[object]]):
label: str = "",
on_change: Optional[Callable[[List[object]], None]] = None,
full_width: bool = False,
+ max_selections: Optional[int] = None,
) -> None:
if not isinstance(options, dict):
options = {option: option for option in options}
@@ -651,6 +653,14 @@ class multiselect(UIElement[List[str], List[object]]):
self.options = options
initial_value = list(value) if value is not None else []
+ if max_selections is not None:
+ if max_selections < 0:
+ raise ValueError("max_selections cannot be less than 0.")
+ if max_selections < len(initial_value):
+ raise ValueError(
+ "Initial value cannot be greater than max_selections."
+ )
+
super().__init__(
component_name=multiselect._name,
initial_value=initial_value,
@@ -658,6 +668,7 @@ class multiselect(UIElement[List[str], List[object]]):
args={
"options": list(self.options.keys()),
"full-width": full_width,
+ "max-selections": max_selections,
},
on_change=on_change,
)
diff --git a/tests/_plugins/ui/_impl/test_input.py b/tests/_plugins/ui/_impl/test_input.py
index d0d66be695..e927210ef6 100644
--- a/tests/_plugins/ui/_impl/test_input.py
+++ b/tests/_plugins/ui/_impl/test_input.py
@@ -126,6 +126,44 @@ def test_dropdown() -> None:
assert dd.value == 2
+def test_multiselect() -> None:
+ options_list = ["Apples", "Oranges", "Bananas"]
+ ms = ui.multiselect(options=options_list)
+ assert ms.value == []
+
+ ms._update(["Apples"])
+ assert ms.value == ["Apples"]
+
+ ms._update(["Apples", "Oranges"])
+ assert ms.value == ["Apples", "Oranges"]
+
+ options_dict = {"Apples": 1, "Oranges": 2, "Bananas": 3}
+ ms = ui.multiselect(options=options_dict, value=["Apples"])
+ assert ms.value == [1]
+
+ ms._update(["Apples", "Oranges", "Bananas"])
+ assert ms.value == [1, 2, 3]
+
+ ms = ui.multiselect(options=options_list, max_selections=2)
+ assert ms.value == []
+
+ ms._update(["Apples"])
+ assert ms.value == ["Apples"]
+
+ with pytest.raises(ValueError):
+ ms = ui.multiselect(
+ options=options_list, value=options_list, max_selections=0
+ )
+
+ with pytest.raises(ValueError):
+ ms = ui.multiselect(
+ options=options_list, value=options_list, max_selections=2
+ )
+
+ with pytest.raises(ValueError):
+ ms = ui.multiselect(options=options_list, max_selections=-10)
+
+
def test_button() -> None:
assert ui.button().value is None
assert ui.button(value=1).value == 1