File: toc.py

package info (click to toggle)
python-mkdocs 1.6.1%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 7,812 kB
  • sloc: python: 14,346; javascript: 10,535; perl: 143; sh: 57; makefile: 30; xml: 11
file content (80 lines) | stat: -rw-r--r-- 2,248 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""
Deals with generating the per-page table of contents.

For the sake of simplicity we use the Python-Markdown `toc` extension to
generate a list of dicts for each toc item, and then store it as AnchorLinks to
maintain compatibility with older versions of MkDocs.
"""
from __future__ import annotations

from typing import Iterable, Iterator, TypedDict


class _TocToken(TypedDict):
    level: int
    id: str
    name: str
    children: list[_TocToken]


def get_toc(toc_tokens: list[_TocToken]) -> TableOfContents:
    toc = [_parse_toc_token(i) for i in toc_tokens]
    # For the table of contents, always mark the first element as active
    if len(toc):
        toc[0].active = True  # type: ignore[attr-defined]
    return TableOfContents(toc)


class AnchorLink:
    """A single entry in the table of contents."""

    def __init__(self, title: str, id: str, level: int) -> None:
        self.title, self.id, self.level = title, id, level
        self.children = []

    title: str
    """The text of the item, as HTML."""

    @property
    def url(self) -> str:
        """The hash fragment of a URL pointing to the item."""
        return '#' + self.id

    level: int
    """The zero-based level of the item."""

    children: list[AnchorLink]
    """An iterable of any child items."""

    def __str__(self) -> str:
        return self.indent_print()

    def indent_print(self, depth: int = 0) -> str:
        indent = '    ' * depth
        ret = f'{indent}{self.title} - {self.url}\n'
        for item in self.children:
            ret += item.indent_print(depth + 1)
        return ret


class TableOfContents(Iterable[AnchorLink]):
    """Represents the table of contents for a given page."""

    def __init__(self, items: list[AnchorLink]) -> None:
        self.items = items

    def __iter__(self) -> Iterator[AnchorLink]:
        return iter(self.items)

    def __len__(self) -> int:
        return len(self.items)

    def __str__(self) -> str:
        return ''.join(str(item) for item in self)


def _parse_toc_token(token: _TocToken) -> AnchorLink:
    anchor = AnchorLink(token['name'], token['id'], token['level'])
    for i in token['children']:
        anchor.children.append(_parse_toc_token(i))
    return anchor