Skip to content

Commit

Permalink
Merge pull request #3334 from pawamoy/goto-anchor-returns-bool
Browse files Browse the repository at this point in the history
Return a boolean from `Markdown.goto_anchor`
  • Loading branch information
davep authored Sep 21, 2023
2 parents 79e9f3b + 91ab82e commit 0bef8fb
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 3 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 7 additions & 3 deletions src/textual/widgets/_markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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.
Expand Down
15 changes: 15 additions & 0 deletions tests/test_markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 0bef8fb

Please sign in to comment.