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
115 changes: 88 additions & 27 deletions great_docs/_website/website_overlay.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import copy
import html
from collections.abc import Callable, Iterator, Mapping
from pathlib import PurePosixPath
from typing import TYPE_CHECKING, Any, cast
from urllib.parse import unquote

Expand Down Expand Up @@ -59,9 +60,9 @@ def apply(
"""
Merge the user's `quarto.website` settings over the generated `website` block

Replace a link to an authored page's source, such as `user_guide/01-intro.qmd`, with
the page's published path. Warn when `navbar_order` no longer applies and when a generated navbar link is linked
from neither the navbar nor a sidebar after the merge.
Replace links to authored sources with their published paths. Warn when
`navbar_order` no longer applies or a page or section that had a generated
navbar link becomes unreachable from the new navigation.

Parameters
----------
Expand Down Expand Up @@ -90,7 +91,8 @@ def apply(
generated_navbar = cast("dict[str, Any]", website.get("navbar") or {})
generated_left = cast("list[Any]", generated_navbar.get("left") or [])
generated_right = cast("list[Any]", generated_navbar.get("right") or [])
_warn_unmatched_splices(website.get("sidebar"), overlay.get("sidebar"), report)
generated_sidebars = website.get("sidebar")
_warn_unmatched_splices(generated_sidebars, overlay.get("sidebar"), report)

merged = merge(
website, overlay, attribute=lambda center: footer.with_attribution(center, config)
Expand All @@ -104,7 +106,7 @@ def apply(
f"Warning: navbar_order has no effect because quarto.website.navbar.left "
f'replaces the generated navbar items. Add "{CONTENTS}" to the list to keep them.'
)
_warn_unlinked(generated_left, website, report)
_warn_unlinked(generated_left, generated_sidebars, website, layout.build_dir, pages, report)
_mark_repository_icon(quarto_config, generated_right, overlay)


Expand Down Expand Up @@ -248,10 +250,18 @@ def navbar_sources(config: Config, layout: Layout) -> Iterator[Path]:
yield source


def _linked_source(href: str, layout: Layout) -> tuple[str, Path] | None:
def _local_link(href: str) -> str | None:
"""Read a local link target without its query or fragment"""
target = href.split("#", 1)[0].split("?", 1)[0]
if not target or target.startswith("//") or ":" in target.split("/", 1)[0]:
return None
return target


def _linked_source(href: str, layout: Layout) -> tuple[str, Path] | None:
target = _local_link(href)
if target is None:
return None
return target, (layout.source_dir / unquote(target.lstrip("/"))).resolve()


Expand Down Expand Up @@ -563,39 +573,90 @@ def _warn_unmatched_splices(generated: Any, overlay: Any, report: Callable[[str]
)


def _navigation_target(href: str) -> PurePosixPath | str:
"""
Match source and rendered links by their published page path

Keep links outside the site as literal URLs.
"""
target = _local_link(href)
if target is None:
return href
path = PurePosixPath(unquote(target.lstrip("/")))
if path.is_absolute() or ".." in path.parts:
return href
if target.endswith("/"):
return path / "index.html"
if path.suffix in _PAGE_SUFFIXES:
return path.with_suffix(".html")
return path


def _warn_unlinked(
generated_left: list[Any], website: Mapping[str, Any], report: Callable[[str], None]
generated_left: list[Any],
generated_sidebars: Any,
website: Mapping[str, Any],
build_dir: Path,
pages: PageMap,
report: Callable[[str], None],
) -> None:
"""
Warn about generated navbar links that the merged navigation no longer reaches

Parameters
----------
generated_left
The navbar's left side before the merge.
website
The merged `website` block.
report
Callback for the warnings.
Warn when no page of a generated navigation destination remains linked

Returns
-------
:
Authored sections use their most specific published directory. Generated
sections, such as the reference, use the original sidebar's membership.
Standalone pages require a link to the page itself.
"""
linked = {
href.removeprefix("./").removeprefix("/")
for href in _links([website.get("navbar"), website.get("sidebar")])
_navigation_target(href) for href in _links([website.get("navbar"), website.get("sidebar")])
}
sidebar_targets = [
{_navigation_target(href) for href in _links(sidebar)}
for sidebar in _as_list(generated_sidebars)
]
directories = sorted(
{
PurePosixPath(root.destination.relative_to(build_dir).as_posix())
for root in pages.roots
if root.destination != build_dir
},
key=lambda path: len(path.parts),
reverse=True,
)

def section(target: PurePosixPath | str) -> PurePosixPath | None:
if isinstance(target, PurePosixPath):
return next((root for root in directories if target.is_relative_to(root)), None)
return None

published_pages = {
_navigation_target(path.relative_to(build_dir).as_posix())
for path in pages.sources()
if path.suffix in _PAGE_SUFFIXES
}
linked_sections = {
root for target in linked & published_pages if (root := section(target)) is not None
}
for item in generated_left:
if not isinstance(item, Mapping):
continue
link = cast("Mapping[str, Any]", item)
href = link.get("href")
if isinstance(href, str) and href.removeprefix("./").removeprefix("/") not in linked:
report(
f"Warning: {link.get('text', href)} ({href}) is not linked from the navbar "
"or a sidebar because quarto.website.navbar.left replaces the generated items."
)
if not isinstance(href, str):
continue
target = _navigation_target(href)
if target in linked:
continue
root = section(target)
if root is not None:
if root in linked_sections:
continue
elif any(target in members and linked & members for members in sidebar_targets):
continue
report(
f"Warning: {link.get('text', href)} ({href}) is not linked from the navbar "
"or a sidebar because quarto.website.navbar.left replaces the generated items."
)


def _mark_repository_icon(
Expand Down
80 changes: 80 additions & 0 deletions tests/test_website_overlay.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,86 @@ def test_warns_about_navbar_order_and_dropped_links(self, tmp_path: Path):
assert "navbar_order has no effect" in warnings[0]
assert "Changelog (changelog.qmd) is not linked" in warnings[1]

@pytest.mark.parametrize(
("navbar", "sidebar"),
[
('["tutorials/02-example.qmd?view=brief#setup"]', "null"),
('["/tutorials/example.html?view=brief#setup"]', "null"),
("[]", '{id: manual, contents: ["tutorials/02-example.qmd#setup"]}'),
],
)
def test_other_links_keep_a_section_reachable(
self, tmp_path: Path, navbar: str, sidebar: str
) -> None:
"""Resolve links to any page in a section while retaining unrelated warnings"""
tutorials = tmp_path / "tutorials"
tutorials.mkdir()
for name in ("01-start.qmd", "02-example.qmd"):
(tutorials / name).write_text("# Tutorials\n", encoding="utf-8")
recipes = tmp_path / "recipes"
recipes.mkdir()
(recipes / "index.qmd").write_text("# Recipes\n", encoding="utf-8")
contributions = (
Contribution(
navbar=(
NavbarLink("Tutorials", "tutorials/start.qmd"),
NavbarLink("Recipes", "recipes/index.qmd"),
NavbarLink("Changelog", "changelog.qmd"),
),
sidebars=(
Sidebar("tutorials", None, ("tutorials/start.qmd", "tutorials/example.qmd")),
),
),
)
settings = (
"sections:\n"
" - {title: Tutorials, dir: tutorials}\n"
" - {title: Recipes, dir: recipes}\n"
"quarto:\n"
" website:\n"
f" navbar: {{left: {navbar}}}\n"
f" sidebar: {sidebar}\n"
)

_, messages = _assemble(tmp_path, settings, contributions=contributions)

assert [
message.split(" is not linked", 1)[0]
for message in messages
if " is not linked" in message
] == ["Warning: Recipes (recipes/index.qmd)", "Warning: Changelog (changelog.qmd)"]

def test_nested_sections_use_their_full_published_directory(self, tmp_path: Path) -> None:
"""Keep a parent section warning when navigation reaches only a nested section"""
nested = tmp_path / "topics" / "models"
nested.mkdir(parents=True)
(nested / "02-examples.qmd").write_text("# Examples\n", encoding="utf-8")
settings = (
"sections:\n"
" - {title: Topics, dir: topics}\n"
" - {title: Models, dir: topics/models}\n"
"quarto:\n"
" website:\n"
" navbar: {left: ['topics/models/examples.html']}\n"
" sidebar: null\n"
)
contributions = (
Contribution(
navbar=(
NavbarLink("Topics", "topics/index.qmd"),
NavbarLink("Models", "topics/models/index.qmd"),
),
),
)

_, messages = _assemble(tmp_path, settings, contributions=contributions)

assert [
message.split(" is not linked", 1)[0]
for message in messages
if " is not linked" in message
] == ["Warning: Topics (topics/index.qmd)"]


class TestSourceLinks:
def test_links_to_sources_become_published_paths(self, tmp_path: Path):
Expand Down
Loading