| 1 |
""" |
| 2 |
Deals with generating the per-page table of contents. |
| 3 |
|
| 4 |
For the sake of simplicity we use the Python-Markdown `toc` extension to |
| 5 |
generate a list of dicts for each toc item, and then store it as AnchorLinks to |
| 6 |
maintain compatibility with older versions of MkDocs. |
| 7 |
""" |
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
from typing import Iterable, Iterator, TypedDict |
| 11 |
|
| 12 |
|
| 13 |
class _TocToken(TypedDict): |
| 14 |
level: int |
| 15 |
id: str |
| 16 |
name: str |
| 17 |
children: list[_TocToken] |
| 18 |
|
| 19 |
|
| 20 |
def get_toc(toc_tokens: list[_TocToken]) -> TableOfContents: |
| 21 |
toc = [_parse_toc_token(i) for i in toc_tokens] |
| 22 |
# For the table of contents, always mark the first element as active |
| 23 |
if len(toc): |
| 24 |
toc[0].active = True # type: ignore[attr-defined] |
| 25 |
return TableOfContents(toc) |
| 26 |
|
| 27 |
|
| 28 |
class AnchorLink: |
| 29 |
"""A single entry in the table of contents.""" |
| 30 |
|
| 31 |
def __init__(self, title: str, id: str, level: int) -> None: |
| 32 |
self.title, self.id, self.level = title, id, level |
| 33 |
self.children = [] |
| 34 |
|
| 35 |
title: str |
| 36 |
"""The text of the item, as HTML.""" |
| 37 |
|
| 38 |
@property |
| 39 |
def url(self) -> str: |
| 40 |
"""The hash fragment of a URL pointing to the item.""" |
| 41 |
return '#' + self.id |
| 42 |
|
| 43 |
level: int |
| 44 |
"""The zero-based level of the item.""" |
| 45 |
|
| 46 |
children: list[AnchorLink] |
| 47 |
"""An iterable of any child items.""" |
| 48 |
|
| 49 |
def __str__(self) -> str: |
| 50 |
return self.indent_print() |
| 51 |
|
| 52 |
def indent_print(self, depth: int = 0) -> str: |
| 53 |
indent = ' ' * depth |
| 54 |
ret = f'{indent}{self.title} - {self.url}\n' |
| 55 |
for item in self.children: |
| 56 |
ret += item.indent_print(depth + 1) |
| 57 |
return ret |
| 58 |
|
| 59 |
|
| 60 |
class TableOfContents(Iterable[AnchorLink]): |
| 61 |
"""Represents the table of contents for a given page.""" |
| 62 |
|
| 63 |
def __init__(self, items: list[AnchorLink]) -> None: |
| 64 |
self.items = items |
| 65 |
|
| 66 |
def __iter__(self) -> Iterator[AnchorLink]: |
| 67 |
return iter(self.items) |
| 68 |
|
| 69 |
def __len__(self) -> int: |
| 70 |
return len(self.items) |
| 71 |
|
| 72 |
def __str__(self) -> str: |
| 73 |
return ''.join(str(item) for item in self) |
| 74 |
|
| 75 |
|
| 76 |
def _parse_toc_token(token: _TocToken) -> AnchorLink: |
| 77 |
anchor = AnchorLink(token['name'], token['id'], token['level']) |
| 78 |
for i in token['children']: |
| 79 |
anchor.children.append(_parse_toc_token(i)) |
| 80 |
return anchor |