Debian Codegraph @

src/pydata_sphinx_theme/toctree.py

raw
1 """Methods to build the toctree used in the html pages."""
2
3 from dataclasses import dataclass
4 from functools import cache
5 from itertools import count
6 from textwrap import dedent
7 from typing import Iterator, List, Tuple, Union
8 from urllib.parse import urlparse
9
10 import sphinx
11
12 from bs4 import BeautifulSoup
13 from docutils import nodes
14 from docutils.nodes import Node
15 from sphinx.addnodes import toctree as TocTreeNodeClass
16 from sphinx.application import Sphinx
17 from sphinx.environment.adapters.toctree import TocTree
18 from sphinx.locale import _
19
20 from .utils import traverse_or_findall
21
22
23 def add_inline_math(node: Node) -> str:
24 """Render a node with HTML tags that activate MathJax processing.
25
26 This is meant for use with rendering section titles with math in them, because
27 math outputs are ignored by pydata-sphinx-theme's header.
28
29 related to the behaviour of a normal math node from:
30 https://github.com/sphinx-doc/sphinx/blob/master/sphinx/ext/mathjax.py#L28
31 """
32 return (
33 '<span class="math notranslate nohighlight">' rf"\({node.astext()}\)" "</span>"
34 )
35
36
37 def _get_ancestor_pagename(app: Sphinx, pagename: str, startdepth: int) -> str:
38 """
39 Get the name of `pagename`'s ancestor that is rooted `startdepth` levels below the
40 global root.
41 """
42 toctree = TocTree(app.env)
43 if sphinx.version_info[:2] >= (7, 2):
44 from sphinx.environment.adapters.toctree import _get_toctree_ancestors
45
46 ancestors = [*_get_toctree_ancestors(app.env.toctree_includes, pagename)]
47 else:
48 ancestors = toctree.get_toctree_ancestors(pagename)
49 try:
50 out = ancestors[-startdepth]
51 except IndexError:
52 # eg for index.rst, but also special pages such as genindex, py-modindex, search
53 # those pages don't have a "current" element in the toctree, so we can
54 # directly return None instead of using the default sphinx
55 # toctree.get_toctree_for(pagename, app.builder, collapse, **kwargs)
56 out = None
57 return out, toctree
58
59
60 @dataclass
61 class LinkInfo:
62 """Dataclass to generate toctree data."""
63
64 is_current: bool
65 href: str
66 title: str
67 is_external: bool
68
69
70 def add_toctree_functions(
71 app: Sphinx, pagename: str, templatename: str, context, doctree
72 ) -> None:
73 """Add functions so Jinja templates can add toctree objects."""
74
75 def suppress_sidebar_toctree(startdepth: int = 1, **kwargs):
76 """Check if there's a sidebar TocTree that needs to be rendered.
77
78 Parameters:
79 startdepth : The level of the TocTree at which to start. 0 includes the
80 entire TocTree for the site; 1 (default) gets the TocTree for the current
81 top-level section.
82
83 kwargs : passed to the Sphinx `toctree` template function.
84 """
85 ancestorname, toctree_obj = _get_ancestor_pagename(
86 app=app, pagename=pagename, startdepth=startdepth
87 )
88 if ancestorname is None:
89 return True # suppress
90 if kwargs.get("includehidden", False):
91 # if ancestor is found and `includehidden=True` we're guaranteed there's a
92 # TocTree to be shown, so don't suppress
93 return False
94
95 # we've found an ancestor page, but `includehidden=False` so we can't be sure if
96 # there's a TocTree fragment that should be shown on this page; unfortunately we
97 # must resolve the whole TOC subtree to find out
98 toctree = get_nonroot_toctree(
99 app, pagename, ancestorname, toctree_obj, **kwargs
100 )
101 return toctree is None
102
103 @cache
104 def get_or_create_id_generator(base_id: str) -> Iterator[str]:
105 for n in count(start=1):
106 if n == 1:
107 yield base_id
108 else:
109 yield f"{base_id}-{n}"
110
111 def unique_html_id(base_id: str):
112 """
113 Create an id that is unique from other ids created by this function at build
114 time.
115
116 The function works by sequentially returning "<base_id>", "<base_id>-2",
117 "<base_id>-3", etc. each time it is called.
118 """
119 return next(get_or_create_id_generator(base_id))
120
121 @cache
122 def _generate_nav_info() -> List[LinkInfo]:
123 """Generate informations necessary to generate nav.
124
125 Instead of messing with html later, having this as a util function
126 should make it slightly easier to generate different html snippet for
127 sidebar or navbar.
128 """
129 toctree = TocTree(app.env)
130
131 # Find the active header navigation item so we decide whether to highlight
132 # Will be empty if there is no active page (root_doc, or genindex etc)
133 if sphinx.version_info[:2] >= (7, 2):
134 from sphinx.environment.adapters.toctree import _get_toctree_ancestors
135
136 # NOTE: `env.toctree_includes` is a dict mapping pagenames to any (possibly
137 # hidden) TocTree directives on that page (i.e., the "child" pages nested
138 # under `pagename`).
139 header_pages = [*_get_toctree_ancestors(app.env.toctree_includes, pagename)]
140 else:
141 header_pages = toctree.get_toctree_ancestors(pagename)
142 if header_pages:
143 # The final list item will be the top-most ancestor
144 active_header_page = header_pages[-1]
145 else:
146 active_header_page = None
147
148 # NOTE: `env.tocs` is a dict mapping pagenames to hierarchical bullet-lists
149 # ("nodetrees" in Sphinx parlance) of in-page headings (including `toctree::`
150 # directives). Thus the `tocs` of `root_doc` yields the top-level pages that sit
151 # just below the root of our site
152 root_toc = app.env.tocs[app.config.root_doc]
153
154 links_data = []
155
156 # Iterate through each node in the root document toc.
157 # Grab the toctree pages and find the relative link + title.
158 for toc in traverse_or_findall(root_toc, TocTreeNodeClass):
159 # TODO: ↑↑↑ use `root_toc.findall(TocTreeNodeClass)` ↑↑↑
160 # once docutils min version >=0.18.1
161 for title, page in toc.attributes["entries"]:
162 # if the page is using "self" use the correct link
163 page = toc.attributes["parent"] if page == "self" else page
164
165 # If this is the active ancestor page, add a class so we highlight it
166
167 # sanitize page title for use in the html output if needed
168 if title is None:
169 title = ""
170 for node in app.env.titles[page].children:
171 if isinstance(node, nodes.math):
172 title += add_inline_math(node)
173 else:
174 title += node.astext()
175
176 # set up the status of the link and the path
177 # if the path is relative then we use the context for the path
178 # resolution and the internal class.
179 # If it's an absolute one then we use the external class and
180 # the complete url.
181 is_absolute = bool(urlparse(page).netloc)
182 link_href = page if is_absolute else context["pathto"](page)
183
184 links_data.append(
185 LinkInfo(
186 is_current=(page == active_header_page),
187 href=link_href,
188 title=title,
189 is_external=is_absolute,
190 )
191 )
192
193 # Add external links defined in configuration as sibling list items
194 for external_link in context["theme_external_links"]:
195 links_data.append(
196 LinkInfo(
197 is_current=False,
198 href=external_link["url"],
199 title=external_link["name"],
200 is_external=True,
201 )
202 )
203
204 return links_data
205
206 @cache
207 def _generate_header_nav_before_dropdown(
208 n_links_before_dropdown,
209 ) -> Tuple[str, List[str]]:
210 """Return html for navbar and dropdown.
211
212 Given the number of links before the dropdown, return the html for the navbar,
213 as well as the list of links to put in a dropdown.
214
215 Returns:
216 - HTML str for the navbar
217 - list of HTML str for the dropdown
218 """
219 try:
220 n_links_before_dropdown = int(n_links_before_dropdown)
221 except Exception:
222 raise ValueError(
223 f"n_links_before_dropdown is not an int: {n_links_before_dropdown}"
224 )
225 links_data = _generate_nav_info()
226
227 links_html = []
228 links_dropdown = []
229 boilerplate = dedent(
230 """
231 <li class="{nav_item} {active}">
232 <a class="{nav_link} nav-{ext_int}" href="{href}">
233 {title}
234 </a>
235 </li>
236 """
237 )
238 nav_item = "nav-item"
239 nav_link = "nav-link"
240 dropdown_item = "dropdown-item"
241 if len(links_data) <= n_links_before_dropdown + 1:
242 # max items without a dropdown is n + 1,
243 # the cutoff counting the dropdown itself.
244 # avoids having a dropdown with exactly one item
245 dropdown_cutoff = n_links_before_dropdown + 1
246 else:
247 dropdown_cutoff = n_links_before_dropdown
248 for link in links_data[:dropdown_cutoff]:
249 links_html.append(
250 boilerplate.format(
251 active="current active" if link.is_current else "",
252 nav_link=nav_link,
253 nav_item=nav_item,
254 ext_int="external" if link.is_external else "internal",
255 href=link.href,
256 title=link.title,
257 )
258 )
259 for link in links_data[dropdown_cutoff:]:
260 links_dropdown.append(
261 boilerplate.format(
262 active="current active" if link.is_current else "",
263 nav_link=nav_link + " " + dropdown_item,
264 nav_item="",
265 ext_int="external" if link.is_external else "internal",
266 href=link.href,
267 title=link.title,
268 )
269 )
270
271 # The first links will always be visible
272 return "\n".join(links_html), links_dropdown
273
274 def generate_header_nav_html(
275 n_links_before_dropdown: int = 5, dropdown_text: str = "More"
276 ) -> str:
277 """Generate top-level links that are meant for the header navigation.
278
279 We use this function instead of the TocTree-based one used for the
280 sidebar because this one is much faster for generating the links and
281 we don't need the complexity of the full Sphinx TocTree.
282
283 This includes two kinds of links:
284
285 - Links to pages described listed in the root_doc TocTrees
286 - External links defined in theme configuration
287
288 Additionally it will create a dropdown list for several links after
289 a cutoff.
290
291 Parameters:
292 n_links_before_dropdown:The number of links to show before nesting the
293 remaining links in a Dropdown element.
294 dropdown_text:Text of the dropdown element button.
295 """
296 out, links_dropdown = _generate_header_nav_before_dropdown(
297 n_links_before_dropdown
298 )
299
300 if links_dropdown:
301 dropdown_id = unique_html_id("pst-nav-more-links")
302 links_dropdown_html = "\n".join(links_dropdown)
303 out += f"""
304 <li class="nav-item dropdown">
305 <button class="btn dropdown-toggle nav-item" type="button"
306 data-bs-toggle="dropdown" aria-expanded="false"
307 aria-controls="{dropdown_id}">
308 {_(dropdown_text)}
309 </button>
310 <ul id="{dropdown_id}" class="dropdown-menu">
311 {links_dropdown_html}
312 </ul>
313 </li>
314 """
315
316 return out
317
318 # Cache this function because it is expensive to run, and because Sphinx
319 # somehow runs this twice in some circumstances in unpredictable ways.
320 @cache
321 def generate_toctree_html(
322 kind: str, startdepth: int = 1, show_nav_level: int = 1, **kwargs
323 ) -> Union[BeautifulSoup, str]:
324 """Return the navigation link structure in HTML.
325
326 This is similar to Sphinx's own default TocTree generation, but it is modified
327 to generate TocTrees for *second*-level pages and below (not supported
328 by default in Sphinx).
329 This is used for our sidebar, which starts at the second-level page.
330
331 It also modifies the generated TocTree slightly for Bootstrap classes
332 and structure (via BeautifulSoup).
333
334 Arguments are passed to Sphinx "toctree" function (context["toctree"] below).
335
336 ref: https://www.sphinx-doc.org/en/master/templating.html#toctree
337
338 Parameters:
339 kind : "sidebar" or "raw". Whether to generate HTML meant for sidebar
340 navigation ("sidebar") or to return the raw BeautifulSoup object
341 ("raw").
342 startdepth : The level of the toctree at which to start. By default,
343 for the navbar uses the normal toctree (`startdepth=0`), and for the
344 sidebar starts from the second level (`startdepth=1`).
345 show_nav_level : The level of the navigation bar to toggle as visible on
346 page load. By default, this level is 1, and only top-level pages are
347 shown, with drop-boxes to reveal children. Increasing `show_nav_level`
348 will show child levels as well.
349 kwargs : passed to the Sphinx `toctree` template function.
350
351 Returns:
352 HTML string (if kind == "sidebar") OR BeautifulSoup object
353 (if kind == "raw")
354 """
355 if startdepth == 0:
356 html_toctree = context["toctree"](**kwargs)
357 else:
358 # find relevant ancestor page; some pages (search, genindex) won't have one
359 ancestorname, toctree_obj = _get_ancestor_pagename(
360 app=app, pagename=pagename, startdepth=startdepth
361 )
362 if ancestorname is None:
363 raise RuntimeError(
364 "Template requested to generate a TocTree fragment but no suitable "
365 "ancestor found to act as root node. Please report this to theme "
366 "developers."
367 )
368 # select the "active" subset of the navigation tree for the sidebar
369 toctree_element = get_nonroot_toctree(
370 app, pagename, ancestorname, toctree_obj, **kwargs
371 )
372 html_toctree = app.builder.render_partial(toctree_element)["fragment"]
373
374 soup = BeautifulSoup(html_toctree, "html.parser")
375
376 # pair "current" with "active" since that's what we use w/ bootstrap
377 for li in soup("li", {"class": "current"}):
378 li["class"].append("active")
379
380 # Remove sidebar links to sub-headers on the page
381 for li in soup.select("li"):
382 # Remove
383 if li.find("a"):
384 href = li.find("a")["href"]
385 if "#" in href and href != "#":
386 li.decompose()
387
388 if kind == "sidebar":
389 # Add bootstrap classes for first `ul` items
390 for ul in soup("ul", recursive=False):
391 ul.attrs["class"] = [*ul.attrs.get("class", []), "nav", "bd-sidenav"]
392
393 # Add collapse boxes for parts/captions.
394 # Wraps the TOC part in an extra <ul> to behave like chapters with toggles
395 # show_nav_level: 0 means make parts collapsible.
396 if show_nav_level == 0:
397 partcaptions = soup.find_all("p", attrs={"class": "caption"})
398 if len(partcaptions):
399 new_soup = BeautifulSoup(
400 "<ul class='list-caption'></ul>", "html.parser"
401 )
402 for caption in partcaptions:
403 # Assume that the next <ul> element is the TOC list
404 # for this part
405 for sibling in caption.next_siblings:
406 if sibling.name == "ul":
407 toclist = sibling
408 break
409 li = soup.new_tag("li", attrs={"class": "toctree-l0"})
410 li.extend([caption, toclist])
411 new_soup.ul.append(li)
412 soup = new_soup
413
414 # Add icons and labels for collapsible nested sections
415 add_collapse_checkboxes(soup)
416
417 # Open the sidebar navigation to the proper depth
418 for ii in range(int(show_nav_level)):
419 for details in soup.select(f"li.toctree-l{ii} > details"):
420 details["open"] = "open"
421
422 return soup
423
424 @cache
425 def generate_toc_html(kind: str = "html") -> BeautifulSoup:
426 """Return the within-page TOC links in HTML."""
427 if "toc" not in context:
428 return ""
429
430 soup = BeautifulSoup(context["toc"], "html.parser")
431
432 # Add toc-hN + visible classes
433 def add_header_level_recursive(ul, level):
434 if ul is None:
435 return
436 if level <= (context["theme_show_toc_level"] + 1):
437 ul["class"] = [*ul.get("class", []), "pst-show_toc_level"]
438 for li in ul("li", recursive=False):
439 li["class"] = [*li.get("class", []), f"toc-h{level}"]
440 add_header_level_recursive(li.find("ul", recursive=False), level + 1)
441
442 add_header_level_recursive(soup.find("ul"), 1)
443
444 # Add in CSS classes for bootstrap
445 for ul in soup("ul"):
446 ul["class"] = [*ul.get("class", []), "nav", "section-nav", "flex-column"]
447
448 for li in soup("li"):
449 li["class"] = [*li.get("class", []), "nav-item", "toc-entry"]
450 if li.find("a"):
451 a = li.find("a")
452 a["class"] = [*a.get("class", []), "nav-link"]
453
454 # If we only have one h1 header, assume it's a title
455 h1_headers = soup.select(".toc-h1")
456 if len(h1_headers) == 1:
457 title = h1_headers[0]
458 # If we have no sub-headers of a title then we won't have a TOC
459 if not title.select(".toc-h2"):
460 out = ""
461 else:
462 out = title.find("ul")
463 # Else treat the h1 headers as sections
464 else:
465 out = soup
466
467 # Return the toctree object
468 if kind == "html":
469 return out
470 else:
471 return soup
472
473 def navbar_align_class() -> List[str]:
474 """Return the class that aligns the navbar based on config."""
475 align = context.get("theme_navbar_align", "content")
476 align_options = {
477 "content": ("col-lg-3", "col-lg-9", "me-auto"),
478 "left": ("", "", "me-auto"),
479 "right": ("", "", "ms-auto"),
480 }
481 if align not in align_options:
482 raise ValueError(
483 "Theme option navbar_align must be one of"
484 f"{align_options.keys()}, got: {align}"
485 )
486 return align_options[align]
487
488 context["unique_html_id"] = unique_html_id
489 context["generate_header_nav_html"] = generate_header_nav_html
490 context["suppress_sidebar_toctree"] = suppress_sidebar_toctree
491 context["generate_toctree_html"] = generate_toctree_html
492 context["generate_toc_html"] = generate_toc_html
493 context["navbar_align_class"] = navbar_align_class
494
495
496 def add_collapse_checkboxes(soup: BeautifulSoup) -> None:
497 """Add checkboxes to collapse children in a toctree."""
498 # based on https://github.com/pradyunsg/furo
499
500 for element in soup.find_all("li", recursive=True):
501 # We check all "li" elements, to add a "current-page" to the correct li.
502 classes = element.get("class", [])
503
504 # expanding the parent part explicitly, if present
505 if "current" in classes:
506 parentli = element.find_parent("li", class_="toctree-l0")
507 if parentli:
508 parentli.find("details")["open"] = None
509
510 # Nothing more to do, unless this has "children"
511 if not element.find("ul"):
512 continue
513
514 # Add a class to indicate that this has children.
515 element["class"] = [*classes, "has-children"]
516
517 if soup.new_tag is None:
518 continue
519
520 # For table of contents nodes that have subtrees, we modify the HTML so
521 # that the subtree can be expanded or collapsed in the browser.
522 #
523 # The HTML markup tree at the parent node starts with this structure:
524 #
525 # - li.has-children
526 # - a.reference or p.caption
527 # - ul
528 #
529 # Note the first child of li.has-children is p.caption only if this node
530 # is a section heading. (This only happens when show_nav_level is set to
531 # 0.)
532 #
533 # Now we modify the tree structure in one of two ways.
534 #
535 # (1) If the node holds a section heading, the HTML tree will be
536 # modified like so:
537 #
538 # - li.has-children
539 # - details
540 # - summary
541 # - p.caption
542 # - .toctree-toggle
543 # - ul
544 #
545 # (2) Otherwise, if the node holds a link to a page in the docs:
546 #
547 # - li.has-children
548 # - a.reference
549 # - details
550 # - summary
551 # - .toctree-toggle
552 # - ul
553 #
554 # Why the difference? In the first case, the TOC section heading is not
555 # a link, but in the second case it is. So in the first case it makes
556 # sense to put the (non-link) text inside the summary tag so that the
557 # user can click either the text or the .toctree-toggle chevron icon to
558 # expand/collapse the TOC subtree. But in the second case, putting the
559 # link in the summary tag would make it unclear whether clicking on the
560 # link should expand the subtree or take you to the link.
561
562 # Create <details> and put the entire subtree into it
563 details = soup.new_tag("details")
564 details.extend(element.contents)
565 element.append(details)
566
567 # Hoist the link to the top if there is one
568 toc_link = element.select_one("details > a.reference")
569 if toc_link:
570 element.insert(0, toc_link)
571
572 # Create <summary> with chevron icon
573 summary = soup.new_tag("summary")
574 span = soup.new_tag(
575 "span",
576 attrs={
577 "class": "toctree-toggle",
578 # This element and the chevron it contains are purely decorative;
579 # the actual expand/collapse functionality is delegated to the
580 # <summary> tag
581 "role": "presentation",
582 },
583 )
584 span.append(soup.new_tag("i", attrs={"class": "fa-solid fa-chevron-down"}))
585 summary.append(span)
586
587 # Prepend section heading (if there is one) to <summary>
588 collapsible_section_heading = element.select_one("details > p.caption")
589 if collapsible_section_heading:
590 # Put heading inside summary so that the heading text (and chevron) are both
591 # clickable
592 summary.insert(0, collapsible_section_heading)
593
594 # Prepend <summary> to <details>
595 details.insert(0, summary)
596
597 # If this TOC node has a "current" class, be expanded by default
598 # (by opening the details/summary disclosure widget)
599 if "current" in classes:
600 details["open"] = "open"
601
602
603 def get_nonroot_toctree(
604 app: Sphinx, pagename: str, ancestorname: str, toctree, **kwargs
605 ):
606 """Get the partial TocTree (rooted at `ancestorname`) that dominates `pagename`.
607
608 Parameters:
609 app : Sphinx app.
610 pagename : Name of the current page (as Sphinx knows it; i.e., its relative path
611 from the documentation root).
612 ancestorname : Name of a page that dominates `pagename` and that will serve as the
613 root of the TocTree fragment.
614 toctree : A Sphinx TocTree object. Since this is always needed when finding the
615 ancestorname (see _get_ancestor_pagename), it's more efficient to pass it here to
616 re-use it.
617 kwargs : passed to the Sphinx `toctree` template function.
618
619 This is similar to `context["toctree"](**kwargs)` (AKA `toctree(**kwargs)` within a
620 Jinja template), or `TocTree.get_toctree_for()`, which always uses the "root"
621 doctree (i.e., `doctree = self.env.get_doctree(self.env.config.root_doc)`).
622 """
623 kwargs.setdefault("collapse", True)
624 if "maxdepth" not in kwargs or not kwargs["maxdepth"]:
625 kwargs["maxdepth"] = 0
626 kwargs["maxdepth"] = int(kwargs["maxdepth"])
627 # starting from ancestor page, recursively parse `toctree::` elements
628 ancestor_doctree = toctree.env.tocs[ancestorname].deepcopy()
629 toctrees = []
630
631 # for each `toctree::` directive in the ancestor page...
632 for toctree_node in traverse_or_findall(ancestor_doctree, TocTreeNodeClass):
633 # TODO: ↑↑↑↑↑↑ use `ancestor_doctree.findall(TocTreeNodeClass)` ↑↑↑↑↑↑
634 # once docutils min version >=0.18.1
635
636 # ... resolve that `toctree::` (recursively get children, prune, collapse, etc)
637 resolved_toctree = toctree.resolve(
638 docname=pagename,
639 builder=app.builder,
640 toctree=toctree_node,
641 **kwargs,
642 )
643 # ... keep the non-empty ones
644 if resolved_toctree:
645 toctrees.append(resolved_toctree)
646 if not toctrees:
647 return None
648 # ... and merge them into a single entity
649 result = toctrees[0]
650 for resolved_toctree in toctrees[1:]:
651 result.extend(resolved_toctree.children)
652 return result