diff --git a/src/textual/widgets/_directory_tree.py b/src/textual/widgets/_directory_tree.py index 5879855c8a..efc56d8613 100644 --- a/src/textual/widgets/_directory_tree.py +++ b/src/textual/widgets/_directory_tree.py @@ -362,11 +362,12 @@ async def watch_path(self) -> None: If the path is changed the directory tree will be repopulated using the new value as the root. """ + has_cursor = self.cursor_node is not None self.reset_node(self.root, str(self.path), DirEntry(self.PATH(self.path))) await self.reload() - if self.cursor_node is not None: + if has_cursor: self.cursor_line = 0 - self.move_cursor(self.cursor_node, animate=False) + self.scroll_to(0, 0, animate=False) def process_label(self, label: TextType) -> Text: """Process a str or Text into a label. May be overridden in a subclass to modify how labels are rendered. diff --git a/src/textual/widgets/_tree.py b/src/textual/widgets/_tree.py index 2b0651a9d5..f73dd8515c 100644 --- a/src/textual/widgets/_tree.py +++ b/src/textual/widgets/_tree.py @@ -935,17 +935,17 @@ def move_cursor_to_line(self, line: int, animate=False) -> None: Args: line: The line number (negative indexes are offsets from the last line). - animate: Enable animation. + animate: Enable scrolling animation. Raises: IndexError: If the line doesn't exist. """ - if line < 0: - line = len(self._tree_lines) + line + if self.cursor_line == line: + return try: node = self._tree_lines[line].node except IndexError: - raise IndexError("No line no. {line} in the tree") + raise IndexError(f"No line no. {line} in the tree") self.move_cursor(node, animate=animate) def select_node(self, node: TreeNode[TreeDataType] | None) -> None: