Skip to content

Instantly share code, notes, and snippets.

@vpmartin
Last active November 4, 2024 03:11
Show Gist options
  • Save vpmartin/a4d2a80aa6e39087d308b7f8a0ffa405 to your computer and use it in GitHub Desktop.
Save vpmartin/a4d2a80aa6e39087d308b7f8a0ffa405 to your computer and use it in GitHub Desktop.
A SearchableSelect widget for Textual, that's composed of an Input and an OptionList, and acts as a regular Select widget. Allows searching for items in the options, which is not possible with the base Select widget.
from typing import Any
from textual.containers import Vertical, VerticalScroll
from textual.widgets import Select, OptionList, Input
from textual.widgets.option_list import Option
from textual.validation import Validator, ValidationResult
class InputInOptions(Validator):
"""An `Input` validator that checks if the input is part of a list."""
def __init__(self, options, *args, **kwargs):
self.options = options
super().__init__(*args, **kwargs)
def validate(self, value: str) -> ValidationResult:
return self.success() if value in self.options else self.failure(f"Value '{value}' is not valid.")
class SearchableSelect(Vertical):
def __init__(self, options: dict[str:Any]|list[Any]|list[tuple], sort: bool = True, *args, **kwargs):
# Handle options
# If it is a dict, create a list of `Option` instances with key as `id` and value as `prompt`
if isinstance(options, dict):
if sort:
options = {k: options[k] for k in sorted(options.keys())} # sort by key
options = [Option(v, id=k) for k,v in options.items()]
# If it is a list...
elif isinstance(options, list):
# ... of tuples, ie. same way of creating a regular `Select`, where `options` is of type list[tuple]
# then, same as for dict: create a list of `Option` instances with key as `id` and value as `prompt`
if isinstance(options[0], tuple):
# Name is index 0, id is index 1 (just as for `Select`)
if sort:
options.sort(key=lambda tup: tup[1]) # Reorder by id, ie. index 1
options = [Option(tup[0], id=tup[1]) for tup in options]
# ... of other elements, create a list of `Option` instances with both prompt and id being the element
else:
if sort:
options.sort()
options = [Option(element, id=element) for element in options]
self.all_options = options
self.option_list = OptionList(*options)
self.input = Input(validators=InputInOptions([option.prompt for option in options]))
self.input.selected_option_id = None
super().__init__(self.input, VerticalScroll(self.option_list), *args, **kwargs)
@property
def value(self):
return self.input.selected_option_id
def on_input_changed(self, event: Input.Changed) -> None:
self.option_list.styles.display = 'block'
options: list[Option]
if event.value:
query = Matcher(event.value)
options = [
option
for option in self.all_options
if query.match(option.prompt) > 0.99 # match by `id` or `prompt` ?
]
else:
options = self.all_options
self.option_list.clear_options()
self.option_list.add_options(options)
def on_option_list_option_selected(self, event: OptionList.OptionSelected) -> None:
with self.input.prevent(Input.Changed):
self.input.value = event.option.prompt
self.input.selected_option_id = event.option_id
self.option_list.styles.display = 'none'
self.post_message(Select.Changed(self, event.option_id))
@CFiggers
Copy link

CFiggers commented Nov 4, 2024

This helped me figure out something similar that was kicking my butt. Thanks for publishing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment