| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import logging |
| 4 |
from typing import TYPE_CHECKING, Iterator, TypeVar |
| 5 |
from urllib.parse import urlsplit |
| 6 |
|
| 7 |
from mkdocs.exceptions import BuildError |
| 8 |
from mkdocs.structure import StructureItem |
| 9 |
from mkdocs.structure.files import file_sort_key |
| 10 |
from mkdocs.structure.pages import Page, _AbsoluteLinksValidationValue |
| 11 |
from mkdocs.utils import nest_paths |
| 12 |
|
| 13 |
if TYPE_CHECKING: |
| 14 |
from mkdocs.config.defaults import MkDocsConfig |
| 15 |
from mkdocs.structure.files import Files |
| 16 |
|
| 17 |
|
| 18 |
log = logging.getLogger(__name__) |
| 19 |
|
| 20 |
|
| 21 |
class Navigation: |
| 22 |
def __init__(self, items: list, pages: list[Page]) -> None: |
| 23 |
self.items = items # Nested List with full navigation of Sections, Pages, and Links. |
| 24 |
self.pages = pages # Flat List of subset of Pages in nav, in order. |
| 25 |
|
| 26 |
self.homepage = None |
| 27 |
for page in pages: |
| 28 |
if page.is_homepage: |
| 29 |
self.homepage = page |
| 30 |
break |
| 31 |
|
| 32 |
homepage: Page | None |
| 33 |
"""The [page][mkdocs.structure.pages.Page] object for the homepage of the site.""" |
| 34 |
|
| 35 |
pages: list[Page] |
| 36 |
"""A flat list of all [page][mkdocs.structure.pages.Page] objects contained in the navigation.""" |
| 37 |
|
| 38 |
def __str__(self) -> str: |
| 39 |
return '\n'.join(item._indent_print() for item in self) |
| 40 |
|
| 41 |
def __iter__(self) -> Iterator: |
| 42 |
return iter(self.items) |
| 43 |
|
| 44 |
def __len__(self) -> int: |
| 45 |
return len(self.items) |
| 46 |
|
| 47 |
|
| 48 |
class Section(StructureItem): |
| 49 |
def __init__(self, title: str, children: list[StructureItem]) -> None: |
| 50 |
self.title = title |
| 51 |
self.children = children |
| 52 |
|
| 53 |
self.active = False |
| 54 |
|
| 55 |
def __repr__(self): |
| 56 |
name = self.__class__.__name__ |
| 57 |
return f"{name}(title={self.title!r})" |
| 58 |
|
| 59 |
title: str |
| 60 |
"""The title of the section.""" |
| 61 |
|
| 62 |
children: list[StructureItem] |
| 63 |
"""An iterable of all child navigation objects. Children may include nested sections, pages and links.""" |
| 64 |
|
| 65 |
@property |
| 66 |
def active(self) -> bool: |
| 67 |
""" |
| 68 |
When `True`, indicates that a child page of this section is the current page and |
| 69 |
can be used to highlight the section as the currently viewed section. Defaults |
| 70 |
to `False`. |
| 71 |
""" |
| 72 |
return self.__active |
| 73 |
|
| 74 |
@active.setter |
| 75 |
def active(self, value: bool): |
| 76 |
"""Set active status of section and ancestors.""" |
| 77 |
self.__active = bool(value) |
| 78 |
if self.parent is not None: |
| 79 |
self.parent.active = bool(value) |
| 80 |
|
| 81 |
is_section: bool = True |
| 82 |
"""Indicates that the navigation object is a "section" object. Always `True` for section objects.""" |
| 83 |
|
| 84 |
is_page: bool = False |
| 85 |
"""Indicates that the navigation object is a "page" object. Always `False` for section objects.""" |
| 86 |
|
| 87 |
is_link: bool = False |
| 88 |
"""Indicates that the navigation object is a "link" object. Always `False` for section objects.""" |
| 89 |
|
| 90 |
def _indent_print(self, depth: int = 0) -> str: |
| 91 |
ret = [super()._indent_print(depth)] |
| 92 |
for item in self.children: |
| 93 |
ret.append(item._indent_print(depth + 1)) |
| 94 |
return '\n'.join(ret) |
| 95 |
|
| 96 |
|
| 97 |
class Link(StructureItem): |
| 98 |
def __init__(self, title: str, url: str): |
| 99 |
self.title = title |
| 100 |
self.url = url |
| 101 |
|
| 102 |
def __repr__(self): |
| 103 |
name = self.__class__.__name__ |
| 104 |
title = f"{self.title!r}" if self.title is not None else '[blank]' |
| 105 |
return f"{name}(title={title}, url={self.url!r})" |
| 106 |
|
| 107 |
title: str |
| 108 |
"""The title of the link. This would generally be used as the label of the link.""" |
| 109 |
|
| 110 |
url: str |
| 111 |
"""The URL that the link points to. The URL should always be an absolute URLs and |
| 112 |
should not need to have `base_url` prepended.""" |
| 113 |
|
| 114 |
children: None = None |
| 115 |
"""Links do not contain children and the attribute is always `None`.""" |
| 116 |
|
| 117 |
active: bool = False |
| 118 |
"""External links cannot be "active" and the attribute is always `False`.""" |
| 119 |
|
| 120 |
is_section: bool = False |
| 121 |
"""Indicates that the navigation object is a "section" object. Always `False` for link objects.""" |
| 122 |
|
| 123 |
is_page: bool = False |
| 124 |
"""Indicates that the navigation object is a "page" object. Always `False` for link objects.""" |
| 125 |
|
| 126 |
is_link: bool = True |
| 127 |
"""Indicates that the navigation object is a "link" object. Always `True` for link objects.""" |
| 128 |
|
| 129 |
|
| 130 |
def get_navigation(files: Files, config: MkDocsConfig) -> Navigation: |
| 131 |
"""Build site navigation from config and files.""" |
| 132 |
documentation_pages = files.documentation_pages() |
| 133 |
nav_config = config['nav'] |
| 134 |
if nav_config is None: |
| 135 |
documentation_pages = sorted(documentation_pages, key=file_sort_key) |
| 136 |
nav_config = nest_paths(f.src_uri for f in documentation_pages if f.inclusion.is_in_nav()) |
| 137 |
items = _data_to_navigation(nav_config, files, config) |
| 138 |
if not isinstance(items, list): |
| 139 |
items = [items] |
| 140 |
|
| 141 |
# Get only the pages from the navigation, ignoring any sections and links. |
| 142 |
pages = _get_by_type(items, Page) |
| 143 |
|
| 144 |
# Include next, previous and parent links. |
| 145 |
_add_previous_and_next_links(pages) |
| 146 |
_add_parent_links(items) |
| 147 |
|
| 148 |
missing_from_config = [] |
| 149 |
for file in documentation_pages: |
| 150 |
if file.page is None: |
| 151 |
# Any documentation files not found in the nav should still have an associated page, so we |
| 152 |
# create them here. The Page object will automatically be assigned to `file.page` during |
| 153 |
# its creation (and this is the only way in which these page objects are accessible). |
| 154 |
Page(None, file, config) |
| 155 |
if file.inclusion.is_in_nav(): |
| 156 |
missing_from_config.append(file.src_path) |
| 157 |
if missing_from_config: |
| 158 |
log.log( |
| 159 |
config.validation.nav.omitted_files, |
| 160 |
'The following pages exist in the docs directory, but are not ' |
| 161 |
'included in the "nav" configuration:\n - ' + '\n - '.join(missing_from_config), |
| 162 |
) |
| 163 |
|
| 164 |
links = _get_by_type(items, Link) |
| 165 |
for link in links: |
| 166 |
scheme, netloc, path, query, fragment = urlsplit(link.url) |
| 167 |
if scheme or netloc: |
| 168 |
log.debug(f"An external link to '{link.url}' is included in the 'nav' configuration.") |
| 169 |
elif ( |
| 170 |
link.url.startswith('/') |
| 171 |
and config.validation.nav.absolute_links |
| 172 |
is not _AbsoluteLinksValidationValue.RELATIVE_TO_DOCS |
| 173 |
): |
| 174 |
log.log( |
| 175 |
config.validation.nav.absolute_links, |
| 176 |
f"An absolute path to '{link.url}' is included in the 'nav' " |
| 177 |
"configuration, which presumably points to an external resource.", |
| 178 |
) |
| 179 |
else: |
| 180 |
log.log( |
| 181 |
config.validation.nav.not_found, |
| 182 |
f"A reference to '{link.url}' is included in the 'nav' " |
| 183 |
"configuration, which is not found in the documentation files.", |
| 184 |
) |
| 185 |
return Navigation(items, pages) |
| 186 |
|
| 187 |
|
| 188 |
def _data_to_navigation(data, files: Files, config: MkDocsConfig): |
| 189 |
if isinstance(data, dict): |
| 190 |
return [ |
| 191 |
_data_to_navigation((key, value), files, config) |
| 192 |
if isinstance(value, str) |
| 193 |
else Section(title=key, children=_data_to_navigation(value, files, config)) |
| 194 |
for key, value in data.items() |
| 195 |
] |
| 196 |
elif isinstance(data, list): |
| 197 |
return [ |
| 198 |
_data_to_navigation(item, files, config)[0] |
| 199 |
if isinstance(item, dict) and len(item) == 1 |
| 200 |
else _data_to_navigation(item, files, config) |
| 201 |
for item in data |
| 202 |
] |
| 203 |
title, path = data if isinstance(data, tuple) else (None, data) |
| 204 |
lookup_path = path |
| 205 |
if ( |
| 206 |
lookup_path.startswith('/') |
| 207 |
and config.validation.nav.absolute_links is _AbsoluteLinksValidationValue.RELATIVE_TO_DOCS |
| 208 |
): |
| 209 |
lookup_path = lookup_path.lstrip('/') |
| 210 |
if file := files.get_file_from_path(lookup_path): |
| 211 |
if file.inclusion.is_excluded(): |
| 212 |
log.log( |
| 213 |
min(logging.INFO, config.validation.nav.not_found), |
| 214 |
f"A reference to '{file.src_path}' is included in the 'nav' " |
| 215 |
"configuration, but this file is excluded from the built site.", |
| 216 |
) |
| 217 |
page = file.page |
| 218 |
if page is not None: |
| 219 |
if not isinstance(page, Page): |
| 220 |
raise BuildError("A plugin has set File.page to a type other than Page.") |
| 221 |
return page |
| 222 |
return Page(title, file, config) |
| 223 |
return Link(title, path) |
| 224 |
|
| 225 |
|
| 226 |
T = TypeVar('T') |
| 227 |
|
| 228 |
|
| 229 |
def _get_by_type(nav, t: type[T]) -> list[T]: |
| 230 |
ret = [] |
| 231 |
for item in nav: |
| 232 |
if isinstance(item, t): |
| 233 |
ret.append(item) |
| 234 |
if item.children: |
| 235 |
ret.extend(_get_by_type(item.children, t)) |
| 236 |
return ret |
| 237 |
|
| 238 |
|
| 239 |
def _add_parent_links(nav) -> None: |
| 240 |
for item in nav: |
| 241 |
if item.is_section: |
| 242 |
for child in item.children: |
| 243 |
child.parent = item |
| 244 |
_add_parent_links(item.children) |
| 245 |
|
| 246 |
|
| 247 |
def _add_previous_and_next_links(pages: list[Page]) -> None: |
| 248 |
bookended = [None, *pages, None] |
| 249 |
zipped = zip(bookended[:-2], pages, bookended[2:]) |
| 250 |
for page0, page1, page2 in zipped: |
| 251 |
page1.previous_page, page1.next_page = page0, page2 |