diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f29d01ec1..65b8b69b30 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Fixed the command palette crashing with a `TimeoutError` in any Python before 3.11 https://github.com/Textualize/textual/issues/3320 - Fixed `Input` event leakage from `CommandPalette` to `App`. +### Changed + +- Breaking change: Changed `Markdown.goto_anchor` to return a boolean (if the anchor was found) instead of `None` https://github.com/Textualize/textual/pull/3334 + ## [0.37.0] - 2023-09-15 ### Added diff --git a/src/textual/widgets/_markdown.py b/src/textual/widgets/_markdown.py index af125c4fa3..f3deec3e22 100644 --- a/src/textual/widgets/_markdown.py +++ b/src/textual/widgets/_markdown.py @@ -660,7 +660,7 @@ def sanitize_location(location: str) -> tuple[Path, str]: location, _, anchor = location.partition("#") return Path(location), anchor - def goto_anchor(self, anchor: str) -> None: + def goto_anchor(self, anchor: str) -> bool: """Try and find the given anchor in the current document. Args: @@ -673,14 +673,18 @@ def goto_anchor(self, anchor: str) -> None: Note that the slugging method used is similar to that found on GitHub. + + Returns: + True when the anchor was found in the current document, False otherwise. """ if not self._table_of_contents or not isinstance(self.parent, Widget): - return + return False unique = TrackedSlugs() for _, title, header_id in self._table_of_contents: if unique.slug(title) == anchor: self.parent.scroll_to_widget(self.query_one(f"#{header_id}"), top=True) - return + return True + return False async def load(self, path: Path) -> None: """Load a new Markdown document. diff --git a/tests/test_markdown.py b/tests/test_markdown.py index 5002430d7d..da4c016aab 100644 --- a/tests/test_markdown.py +++ b/tests/test_markdown.py @@ -125,3 +125,18 @@ async def test_load_non_existing_file() -> None: await pilot.app.query_one(Markdown).load( Path("---this-does-not-exist---.it.is.not.a.md") ) + + +@pytest.mark.parametrize( + ("anchor", "found"), + [ + ("hello-world", False), + ("hello-there", True), + ] +) +async def test_goto_anchor(anchor: str, found: bool) -> None: + """Going to anchors should return a boolean: whether the anchor was found.""" + document = "# Hello There\n\nGeneral.\n" + async with MarkdownApp(document).run_test() as pilot: + markdown = pilot.app.query_one(Markdown) + assert markdown.goto_anchor(anchor) is found