Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 37 additions & 29 deletions sqlit/domains/explorer/ui/mixins/tree_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from sqlit.shared.ui.protocols import TreeFilterMixinHost

if TYPE_CHECKING:
pass
from collections.abc import Callable


@dataclass
Expand Down Expand Up @@ -57,6 +57,23 @@ def _restore_node_under(parent: Any, snap: _NodeSnapshot) -> None:
_restore_node_under(child, grandchild)


def _call_after_refresh(host: TreeFilterMixinHost, callback: Callable[[], None]) -> None:
"""Run `callback` after the next refresh, once nodes added by a snapshot
restore have been laid out.

Textual's Tree.move_cursor reads `node._line`, which is set during the
next layout pass — not when the node is `add()`-ed. Calling move_cursor
right after a snapshot restore sees stale `_line` values and parks the
cursor on the wrong row.
"""
call_after = getattr(host, "call_after_refresh", None)
if callable(call_after):
call_after(callback)
else:
# Synchronous fallback (used in unit tests with a mock host).
callback()


class TreeFilterMixin:
"""Mixin providing tree filter functionality."""

Expand Down Expand Up @@ -109,21 +126,18 @@ def action_tree_filter_close(self: TreeFilterMixinHost) -> None:

def action_tree_filter_accept(self: TreeFilterMixinHost) -> None:
"""Accept current filter selection, close filter, and activate the node."""
# Remember the match's *data* (not the node reference) before closing.
# Closing the filter rebuilds the tree from the snapshot taken at
# filter-open time, which replaces every node object — so the
# reference we captured here would be stale after close. The data
# payload, however, is the same object on both old and new nodes
# (we pass it through unchanged in _restore_node_under), so we can
# re-locate the match by identity.
# Remember the highlighted node's *data* (not the node reference)
# before closing. Closing the filter rebuilds the tree from the
# snapshot taken at filter-open time, which replaces every node
# object, so the reference we captured here would be stale after
# close. The data payload, however, is the same object on both old
# and new nodes (we pass it through unchanged in _restore_node_under),
# so we can re-locate the node by identity.
matched_data: Any = None
if (
self._tree_filter_matches
and self._tree_filter_match_index < len(self._tree_filter_matches)
):
current_node = self._tree_filter_matches[self._tree_filter_match_index]
if current_node and current_node.data:
matched_data = current_node.data
if self._tree_filter_matches:
cursor_node = self.object_tree.cursor_node
if cursor_node is not None and cursor_node.data:
matched_data = cursor_node.data

# Close the filter
self.action_tree_filter_close()
Expand All @@ -135,22 +149,16 @@ def action_tree_filter_accept(self: TreeFilterMixinHost) -> None:
if fresh_node is None:
return

# Textual's Tree.move_cursor reads `node._line`, which is set during
# the next layout pass — not when the node is `add()`-ed. Since the
# snapshot restore that just ran in action_tree_filter_close added
# all fresh nodes synchronously, calling move_cursor right now sees
# stale `_line` values and parks the cursor on the wrong row.
# Defer the move (and the activation) until after the next refresh.
call_after = getattr(self, "call_after_refresh", None)
if callable(call_after):
call_after(lambda: self._select_and_activate_after_refresh(fresh_node))
else:
# Synchronous fallback (used in unit tests with a mock host).
self._select_and_activate_after_refresh(fresh_node)
_call_after_refresh(self, lambda: self._select_and_activate_after_refresh(fresh_node))

def _select_and_activate_after_refresh(self: TreeFilterMixinHost, node: Any) -> None:
tree = self.object_tree
try:
self.object_tree.move_cursor(node)
tree.move_cursor(node)
tree.scroll_to(
y=node.line - tree.scrollable_content_region.height // 2,
animate=False,
)
except Exception:
pass
self._activate_tree_node(node)
Expand Down Expand Up @@ -191,7 +199,7 @@ def _jump_to_current_match(self: TreeFilterMixinHost) -> None:
# Expand ancestors to make node visible
self._expand_ancestors(node)
# Move cursor to node
self.object_tree.move_cursor(node)
_call_after_refresh(self, lambda: self.object_tree.move_cursor(node))

def _expand_ancestors(self: TreeFilterMixinHost, node: Any) -> None:
"""Expand all ancestor nodes to make a node visible."""
Expand Down
128 changes: 128 additions & 0 deletions tests/ui/explorer/test_filter_accept_cursor_pilot.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import pytest

from sqlit.domains.explorer.domain.tree_nodes import FolderNode, TableNode
from sqlit.domains.shell.app.main import SSMSTUI

from ..mocks import (
Expand Down Expand Up @@ -78,3 +79,130 @@ async def test_filter_accept_lands_cursor_on_matched_connection():
f"match. Expected 'test-server', got node with connection "
f"name={name!r} (cursor.label={getattr(cursor, 'label', None)!r})."
)


@pytest.mark.asyncio
async def test_filter_accept_activates_arrow_highlighted_match():
"""Arrowing to a later match and pressing Enter selects that match, not the first one."""
connections = [
create_test_connection("warehouse-a", "sqlite"),
create_test_connection("warehouse-b", "sqlite"),
create_test_connection("warehouse-c", "sqlite"),
create_test_connection("other", "sqlite"),
]
services = build_test_services(
connection_store=MockConnectionStore(connections),
settings_store=MockSettingsStore({"theme": "tokyo-night"}),
)
app = SSMSTUI(services=services)

async with app.run_test(size=(120, 40)) as pilot:
await pilot.pause()
app.action_focus_explorer()
await pilot.pause()

await pilot.press("slash")
await pilot.pause()
for ch in "warehouse":
await pilot.press(ch)
await pilot.pause()
assert len(app._tree_filter_matches) == 3

await pilot.press("down", "down")
await pilot.pause()
assert _connection_name_of(app.object_tree.cursor_node) == "warehouse-c"

await pilot.press("enter")
await pilot.pause()

assert _connection_name_of(app.object_tree.cursor_node) == "warehouse-c"


@pytest.mark.asyncio
async def test_filter_accept_centers_selected_node():
connections = [create_test_connection(f"conn-{i:02d}", "sqlite") for i in range(80)]
services = build_test_services(
connection_store=MockConnectionStore(connections),
settings_store=MockSettingsStore({"theme": "tokyo-night"}),
)
app = SSMSTUI(services=services)

async with app.run_test(size=(120, 40)) as pilot:
await pilot.pause()
app.action_focus_explorer()
await pilot.pause()

await pilot.press("slash")
await pilot.pause()
for ch in "conn-60":
await pilot.press(ch)
await pilot.pause()

await pilot.press("enter")
await pilot.pause()

tree = app.object_tree
cursor = tree.cursor_node
assert _connection_name_of(cursor) == "conn-60"
height = tree.scrollable_content_region.height
assert tree.max_scroll_y > 0
assert abs((cursor.line - tree.scroll_offset.y) - height // 2) <= 1


def _add_tables_under_first_connection(app: SSMSTUI, names: list[str]) -> None:
"""Hang a Tables folder with the given tables under the first connection,
as if they had been lazy-loaded, so the matches sit below line 0."""
connection = app.object_tree.root.children[0]
tables = connection.add("Tables", data=FolderNode(folder_type="tables"), expand=True)
for name in names:
tables.add_leaf(name, data=TableNode(database=None, schema="main", name=name))
connection.expand()


def _nested_table_services():
return build_test_services(
connection_store=MockConnectionStore([create_test_connection("warehouse", "sqlite")]),
settings_store=MockSettingsStore({"theme": "tokyo-night"}),
)


@pytest.mark.asyncio
async def test_filter_moves_cursor_to_first_nested_match():
"""Typing a filter puts the cursor on the first match even when it is
nested, so Enter without arrowing selects that match."""
app = SSMSTUI(services=_nested_table_services())

async with app.run_test(size=(120, 40)) as pilot:
await pilot.pause()
app.action_focus_explorer()
_add_tables_under_first_connection(app, ["customers", "orders_2023", "orders_2024"])
await pilot.pause()

await pilot.press("slash", *"orders")
await pilot.pause()
assert app.object_tree.cursor_node.label.plain == "orders_2023"

await pilot.press("enter")
await pilot.pause()
assert app.object_tree.cursor_node.label.plain == "orders_2023"


@pytest.mark.asyncio
async def test_filter_accept_activates_arrow_highlighted_nested_match():
app = SSMSTUI(services=_nested_table_services())

async with app.run_test(size=(120, 40)) as pilot:
await pilot.pause()
app.action_focus_explorer()
_add_tables_under_first_connection(app, ["customers", "orders_2023", "orders_2024", "orders_2025"])
await pilot.pause()

await pilot.press("slash", *"orders")
await pilot.pause()
await pilot.press("down", "down")
await pilot.pause()
assert app.object_tree.cursor_node.label.plain == "orders_2025"

await pilot.press("enter")
await pilot.pause()
assert app.object_tree.cursor_node.label.plain == "orders_2025"
4 changes: 4 additions & 0 deletions tests/ui/explorer/test_tree_filter_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ def select_node(self, node: MockTreeNode) -> None:
def move_cursor(self, node: MockTreeNode) -> None:
self.selected_node = node

@property
def cursor_node(self) -> MockTreeNode | None:
return self.selected_node

def focus(self) -> None:
self.has_focus = True

Expand Down
Loading