Autocomplete
An autocomplete field suggests completions as you type,
in a list that opens under the field and lays over whatever is there.
The list has to reach past the box the field is in,
which here is a form that scrolls inside a fill(1) panel,
and so clips its children.
The field edits its text with use_text_input,
which makes it focusable and handles typing, moving the cursor, and pasting,
and leaves drawing the text and the list to the field.
It draws the text in a row that scrolls sideways,
with the cursor's cell holding the hook's cursor_cell handle,
so a value wider than the field keeps the cursor in view.
PACKAGES = (
"counterweight",
"hypothesis",
"more-itertools",
"mypy",
"pydantic",
"pydantic-settings",
"pytest",
"pytest-asyncio",
"pytest-xdist",
"ruff",
"waxy",
"wcwidth",
)
GROUPS = ("bench", "dev", "docs", "lint", "test")
PYTHONS = ("3.13", "3.14", "3.15", "3.15t")
INDEXES = ("pypi", "testpypi", "pytorch-cpu", "pytorch-cu128")
RECIPES = ("codegen", "devlog", "docs-build", "docs-serve", "mutate", "pre-commit", "profile", "test", "upgrade")
SHOWN_ROWS = 5
CURSOR = (text_color("slate", 900) | text_bg("sky", 300)).text_style
below = Style(layout=waxy.Style(inset_top=waxy.Percent(1.0)))
above = Style(layout=waxy.Style(inset_bottom=waxy.Percent(1.0)))
@dataclass(frozen=True, slots=True)
class Completion:
text: str
highlight: Highlight
is_dismissed: bool
def edited(self, text: str) -> Completion:
return self if text == self.text else Completion(text=text, highlight=Highlight(), is_dismissed=False)
@component
def autocomplete(candidates: tuple[str, ...], auto_focus: bool = False, list_clip: Style = clip_to_screen) -> Div:
rects = use_rects()
completion, set_completion = use_state(Completion(text="", highlight=Highlight(), is_dismissed=False))
highlighted_match, _ = use_state(ElementHandle)
def edit(edit_text: Callable[[str], str]) -> str:
return set_completion(lambda c: c.edited(edit_text(c.text))).text
field = use_text_input(completion.text, edit, auto_focus=auto_focus)
def matching(text: str) -> tuple[str, ...]:
return subsequence_matches(text, candidates) if text else ()
shown = matching(completion.text)
highlighted = completion.highlight.index_in(shown)
is_open = field.focus.is_focused and not completion.is_dismissed and bool(shown)
def choose(match: str) -> None:
set_completion(Completion(text=match, highlight=Highlight(), is_dismissed=True))
def on_input(event: InputEvent, receiver: Receiver) -> InputResponse:
highlighted_in_view = ScrollIntoView(highlighted_match, block="nearest")
# Keys typed ahead of a render decide from the text they follow, not the one last rendered.
now = get_state(set_completion)
now_shown = matching(now.text)
is_showing = not now.is_dismissed and bool(now_shown)
match event:
case KeyPressed(key=Key.Down | Key.Up as key) if is_showing:
by = 1 if key == Key.Down else -1
set_completion(replace(now, highlight=now.highlight.moved(now_shown, by)))
case KeyPressed(key=Key.Enter | Key.Tab) if (
is_showing and (index := now.highlight.index_in(now_shown)) is not None
):
choose(now_shown[index])
case KeyPressed(key=Key.Escape) if is_showing:
set_completion(replace(now, is_dismissed=True))
case _:
if (edited := response_controls(field.on_input(event, receiver))) is None:
return None
return (*edited, highlighted_in_view)
return highlighted_in_view
room_above = rects.border.top - rects.screen.top
room_below = rects.screen.bottom - rects.border.bottom
suggestions = Div(
style=z(1)
| position_absolute
| (above if room_above > room_below else below)
| inset_x(0)
| list_clip
| col
| border
| border_lightrounded
| border_color("sky", 400)
| max_height(SHOWN_ROWS + 2)
| overflow_y_scroll,
on_input=scroll_on_wheel(1),
children=tuple(
Text(
content=match,
style=pad_x(1) | (text_bg("sky", 800) if index == highlighted else text_bg("slate", 900)),
handle=highlighted_match if index == highlighted else None,
on_input=on_click(partial(choose, match)),
)
for index, match in enumerate(shown)
),
)
return Div(
style=width(24) | (text_bg("slate", 700) if field.focus.is_focused else text_bg("slate", 800)),
on_input=first(on_input, focus_receiver_on_press),
children=(
Div(
style=row | overflow_x_scroll | stick_to_end_x,
on_input=field.on_press,
children=(
Text(content=field.before_cursor, style=text_wrap_none),
Text(
content=field.at_cursor,
style=text_wrap_none | Style(text_style=CURSOR if field.focus.is_focused else CellStyle()),
handle=field.cursor_cell,
),
Text(content=field.after_cursor, style=text_wrap_none),
),
),
*([suggestions] if is_open else []),
),
)
@component
def labelled(label: str, field: Component) -> Div:
return Div(style=row | gap(1), children=(Text(content=f"{label:>7}"), field))
@component
def root(list_clip: Style = clip_to_screen) -> Div:
return Div(
style=full | col,
on_input=first(tab_focus, clear_focus),
children=(
Div(
style=fill(1) | col | border | border_lightrounded | pad_x(1),
children=(
Text(content=" Add a dependency ", style=position_absolute | inset_top(-1) | clip_to_border),
Div(
style=fill(1) | col | gap(1) | overflow_y_scroll,
on_input=scroll_on_wheel(1),
children=(
labelled("Package", autocomplete(PACKAGES, auto_focus=True, list_clip=list_clip)),
labelled("Group", autocomplete(GROUPS, list_clip=list_clip)),
labelled("Python", autocomplete(PYTHONS, list_clip=list_clip)),
labelled("Index", autocomplete(INDEXES, list_clip=list_clip)),
),
),
),
),
Text(
content="Type to see suggestions. Down and Up move through them, "
"Enter or Tab chooses one, and Escape closes them.",
style=fill(1) | pad(1) | text_wrap_pretty | text_color("slate", 400),
),
labelled("just", autocomplete(RECIPES, list_clip=list_clip)),
),
)
Typing py into the package field opens the list,
which reaches past the bottom of the panel and over the text below it:
╭─ Add a dependency ───────────────────╮
│ Package py │
│ ╭──────────────────────╮ │
│ Group │ mypy │ │
│ │ pydantic │ │
│ Python │ pydantic-settings │ │
╰─────────│ pytest │─────╯
│ pytest-asyncio │
Type to s╰──────────────────────╯
Up move through them, Enter or Tab
chooses one, and Escape closes them.
just
Matching
The field matches its candidates with subsequence_matches
and keeps which match is highlighted with a Highlight,
both covered on the Pickers page, with the keys and scrolling a long list.
This page is about where the list goes.
The list
The list is a Div the field renders only while it's focused and has matches,
so it closes when focus moves away:
Tab with the list closed bubbles to the root's tab_focus,
and a press anywhere that doesn't claim it bubbles to the root's clear_focus.
It's absolutely positioned against the field,
so it doesn't push the fields below it down.
inset_top=Percent(1.0) puts its top edge at the bottom of the field,
and inset_x(0) makes it as wide as the field.
It's raised with z(1), so it's drawn over the fields and text that follow it.
It's at most SHOWN_ROWS matches tall, and scrolls the rest.
Choosing a match
Down and Up move the highlight through the list, wrapping at the ends.
The field keeps its text in one state with its Highlight and whether the list is dismissed,
and the setter it passes to use_text_input applies each edit to that state,
resetting the highlight whenever the edit changes the text,
so moving the cursor leaves it where it was.
Each key decides from that state as the keys before it left it, read with get_state,
so keys typed ahead of a render act on the text they follow:
╭─ Add a dependency ───────────────────╮
│ Package py │
│ ╭──────────────────────╮ │
│ Group │ mypy │ │
│ │ pydantic │ │
│ Python │ pydantic-settings │ │
╰─────────│ pytest │─────╯
│ pytest-asyncio │
Type to s╰──────────────────────╯
Up move through them, Enter or Tab
chooses one, and Escape closes them.
just
Enter or Tab replaces the text with the highlighted match, and closes the list:
Escape closes the list too, and it stays closed until the text changes.
Each of these keys is handled only while the list is open.
Every other event goes to use_text_input's handler, which passes on the keys it doesn't edit with,
so with the list closed, Tab moves focus and Enter bubbles to whatever handles it outside the field.
A press on a match chooses it, through on_click.
on_click claims the press, so it never reaches the root's clear_focus, and focus stays in the field.
Escaping the panel
The list sets clip_to_screen, so no ancestor clips it.
With the default, clip_to_padding, the panel would cut the list off at its padding box:
╭─ Add a dependency ───────────────────╮
│ Package py │
│ ╭──────────────────────╮ │
│ Group │ mypy │ │
│ │ pydantic │ │
│ Python │ pydantic-settings │ │
╰──────────────────────────────────────╯
Type to see suggestions. Down and
Up move through them, Enter or Tab
chooses one, and Escape closes them.
just
clip_to_screen changes only what clips the list.
The list is still positioned against the field, and still needs its z to cover what follows it.
Inside a scroll container
The form scrolls, with scroll_on_wheel,
and has its border and title on the panel around it, so they stay put while the fields move.
The open list is positioned against its field, so it moves with the field as the form scrolls.
It's part of the form's content, so it also extends how far the form scrolls:
the four fields and the gaps between them reach two rows past the form,
but with the Python field's list open, the form scrolls three rows down, and further still to show all of it.
Opening upward
A field near the bottom of the screen, below the panel, opens its list above it instead,
with inset_bottom=Percent(1.0), when there's more room above it than below.
The field compares its own border box, from use_rects,
with the screen around it, which the same Rects carry as
screen:
Choosing a package with Down and Enter, then tabbing to the recipe field, whose list opens upward:
Opening a picker with a key
A picker is the same field and list, opened by a key over the corner of the screen, as a command palette or VS Code's quick pick is, to choose one of a few settings and close again. Here F2 picks the Python and F3 the package index:
@component
def settings() -> Div:
python, set_python = use_state("3.15")
index, set_index = use_state("pypi")
nothing_picked: Picking | None = None
picking, set_picking = use_state(nothing_picked)
chosen = {PYTHON: (python, set_python), INDEX: (index, set_index)}
def choose(choice: Choice, name: str) -> None:
chosen[choice][1](choice.option_for(name))
def open_picker(choice: Choice) -> tuple[AnyControl, ...]:
opening = Picking(choice)
set_picking(opening)
return opening.opened()
def on_input(event: InputEvent, _: Receiver) -> InputResponse:
match event:
case KeyPressed(key=Key.F2):
return open_picker(PYTHON)
case KeyPressed(key=Key.F3):
return open_picker(INDEX)
case _:
return None
return Div(
style=full | col | pad_x(1),
on_input=on_input,
children=(
Text(content=f"Python {python}", style=text_color("teal", 300)),
Text(content=f"Index {index}", style=text_color("teal", 300)),
Text(content="F2 picks the Python and F3 the index", style=text_color("slate", 400) | text_wrap_pretty),
*(
()
if picking is None
else (
picker(
picking,
chosen[picking.choice][0],
partial(choose, picking.choice),
partial(set_picking, None),
).with_key(picking.choice.label),
)
),
),
)
The picker draws the same field as above, with use_text_input,
and narrows its list with subsequence_matches, which lists everything while nothing is typed.
It opens with the current choice marked and highlighted, and choosing one, or Escape, closes it.
@component
def picker(picking: Picking, current: str, choose: Callable[[str], None], close: Callable[[], object]) -> Div:
choice = picking.choice
names = choice.names
completion, set_completion = use_state(Completion(text="", highlight=Highlight(key=current)))
def edit(edit_text: Callable[[str], str]) -> str:
return set_completion(lambda c: c.edited(edit_text(c.text))).text
field = use_text_input(completion.text, edit, handle=picking.focus)
shown = subsequence_matches(completion.text, names)
highlighted = completion.highlight.index_in(shown)
def chosen(name: str) -> InputResponse:
choose(name)
close()
return ClearFocus()
def on_input(event: InputEvent, receiver: Receiver) -> InputResponse:
highlighted_in_view = ScrollIntoView(picking.highlighted, block="nearest")
match event:
case KeyPressed(key=Key.Down | Key.Up as key):
by = 1 if key == Key.Down else -1
set_completion(
lambda c: replace(c, highlight=c.highlight.moved(subsequence_matches(c.text, names), by))
)
# Enter typed ahead with the text before it chooses from what that text matches, not what last rendered.
case KeyPressed(key=Key.Enter | Key.Tab):
now = get_state(set_completion)
now_shown = subsequence_matches(now.text, names)
# The picker is modal, so with nothing to choose its keys stay in it, as Tab stays in a web dialog.
if (index := now.highlight.index_in(now_shown)) is None:
return ()
return chosen(now_shown[index])
case KeyPressed(key=Key.Escape):
close()
return ClearFocus()
case _:
if (edited := response_controls(field.on_input(event, receiver))) is None:
return None
return (*edited, highlighted_in_view)
return highlighted_in_view
def option_row(index: int, name: str) -> Text:
marker = "▸" if name == current else " "
is_bar = name in choice.titles
return Text(
content=f"{marker}── {name} ──" if is_bar else f"{marker} {name}",
style=text_wrap_none
| (text_bold if is_bar else text_color("slate", 300))
| (text_bg("sky", 800) if index == highlighted else Style()),
handle=picking.highlighted if index == highlighted else None,
on_input=on_click(partial(chosen, name)),
)
return Div(
style=position_absolute
| inset_right(1)
| inset_top(1)
| z(1)
| width(20)
| col
| border
| border_lightrounded
| border_color("amber", 300)
| pad_x(1)
| content_color("slate", 900)
| padding_color("slate", 900),
on_input=first(on_input, focus_receiver_on_press),
children=(
Text(content=choice.label, style=text_color("slate", 400)),
Div(
style=row | overflow_x_scroll | stick_to_end_x | text_bg("slate", 700),
on_input=field.on_press,
children=(
Text(content="> ", style=text_wrap_none),
Text(content=field.before_cursor, style=text_wrap_none),
Text(
content=field.at_cursor,
style=text_wrap_none | Style(text_style=CURSOR),
handle=field.cursor_cell,
),
Text(content=field.after_cursor, style=text_wrap_none),
),
),
Div(
style=col | max_height(5) | overflow_y_scroll,
on_input=scroll_on_wheel(1),
children=tuple(option_row(index, name) for index, name in enumerate(shown))
or (Text(content="nothing matches", style=text_color("slate", 400)),),
),
),
)
Sections
The options can come in sections, each under a bar naming it.
A bar is listed and chosen as an option is, by its title, so typing narrows to it as well,
and whatever handles the choice decides what choosing it means:
here a bar chooses its section's newest version, as uv python install pypy does.
@dataclass(frozen=True, slots=True)
class Section:
"""A run of a picker's options, under a bar with its `title`, which is chosen as an option is, or under no bar."""
title: str | None
options: tuple[str, ...]
@property
def names(self) -> tuple[str, ...]:
"""What the section lists, in order: its bar's title, if it has one, then its options."""
return (*(() if self.title is None else (self.title,)), *self.options)
@dataclass(frozen=True, slots=True)
class Choice:
label: str
sections: tuple[Section, ...]
@property
def names(self) -> tuple[str, ...]:
return tuple(*section.names for section in self.sections)
@property
def titles(self) -> frozenset[str]:
return frozenset(section.title for section in self.sections if section.title is not None)
def option_for(self, name: str) -> str:
"""The option choosing `name` picks: for a bar, the newest of its section, which it lists last."""
return next((section.options[-1] for section in self.sections if section.title == name), name)
# Choosing a bar chooses the newest of its section, as `uv python install pypy` does.
PYTHON = Choice(
label="Python",
sections=(
Section(title="CPython", options=("3.13", "3.14", "3.15", "3.15t")),
Section(title="PyPy", options=("pypy3.10", "pypy3.11")),
),
)
INDEX = Choice(label="Index", sections=(Section(title=None, options=("pypi", "testpypi", "pytorch-cpu")),))
Focus
Nothing has focus before the picker opens, so use_text_input's auto_focus would take it,
but a picker opened while another is open has to take focus from that one, and auto_focus takes it from nothing.
So the key that opens a picker returns FocusOn for its field's
FocusHandle,
with a ScrollIntoView for the highlighted option,
which can start past the rows the list shows.
Returned with the state change that opens the picker, both apply to the frame it opens in.
Choosing, or Escape, returns ClearFocus,
so the keys go back to the screen behind it.
A handle for each opening
The handles belong to one opening of a picker, a Picking, not to the screen,
and each Picking makes its own:
@dataclass(frozen=True, slots=True, eq=False)
class Picking:
"""One opening of a picker: what it offers, and handles of its own."""
choice: Choice
focus: FocusHandle = field(default_factory=FocusHandle)
highlighted: ElementHandle = field(default_factory=ElementHandle)
def opened(self) -> tuple[AnyControl, ...]:
"""What the key that opens the picker returns, so the frame it opens in focuses it and shows its current option."""
return FocusOn(self.focus), ScrollIntoView(self.highlighted, block="nearest")
Pressing F3 while the Python picker is open opens the index picker in the frame the Python picker closes in.
A FocusOn names its target by handle, and resolves as soon as it's handled, against the frame on screen.
With one handle shared by every opening, that's still the Python picker's field,
so focus would go there, then leave with the field as it unmounts, and the index picker would open without focus.
With a handle of its own, the index picker's field isn't on screen yet, so the FocusOn waits for the render that mounts it:
Choosing a Python version, a bar, then switching pickers with F3: