MkFootNotes

github Show source on GitHub

Node containing a list of MkFootNotes.

class MkFootNotes(mkcontainer.MkContainer)

Name

Children

Inherits

MkContainer
mknodes.basenodes.mkcontainer
A node containing other MkNodes.

graph TD
  3964180375["mkfootnotes.MkFootNotes"]
  835538629["mkcontainer.MkContainer"]
  1956333208["mkcontainer.MkContainerBase"]
  1359323199["mknode.MkNode"]
  2751680898["builtins.object"]
  835538629 --> 3964180375
  1956333208 --> 835538629
  1359323199 --> 1956333208
  2751680898 --> 1359323199
/home/runner/work/mknodes/mknodes/src/mknodes/basenodes/mkfootnotes/metadata.toml
[metadata]
icon = "octicon:list-ordered-16"
name = "MkFootNotes"

[requirements.extension.footnotes]

[examples.regular]
title = "Regular"
python = """
node = MkFootNotes()
page += "The MkFootNotes node aggregates footnotes[^1]."
node[1] = r"Footnotes are numbered, can be set via `__setitem__`."
node[2] = r"They can also get nested[^3]."
node[3] = mk.MkAdmonition("And they can also contain other Markdown.")
node
"""

[fragments.footnote]
template = """
[^{{ footnote.num }}]
{{ node.get_items() | join("\n") | indent(first=True) }}
"""

[output.markdown]
template = """
{{ node.get_items() | sort(attribute="num") | join }}
"""

[output.rst]
template = """
.. rubric:: Footnotes

{% for item in node.get_items() | sort(attribute="num") %}
.. {{ item }}
"""
mknodes.basenodes.mkfootnotes.MkFootNotes
 66class MkFootNotes(mkcontainer.MkContainer):
 67    """Node containing a list of MkFootNotes."""
 68
 69    ICON = "octicons/list-ordered-16"
 70    REQUIRED_EXTENSIONS = [resources.Extension("footnotes")]
 71
 72    def __init__(
 73        self,
 74        footnotes: (Mapping[int, str | mk.MkNode] | list[MkFootNote] | list[str] | None) = None,
 75        **kwargs: Any,
 76    ) -> None:
 77        """Constructor.
 78
 79        Args:
 80            footnotes: Footnotes data (Can be given in different shapes)
 81            kwargs: Keyword arguments passed to parent
 82        """
 83        match footnotes:
 84            case None:
 85                items = []
 86            case list():
 87                items = [
 88                    (
 89                        ann if isinstance(ann, MkFootNote) else MkFootNote(i, ann)  # type: ignore
 90                    )
 91                    for i, ann in enumerate(footnotes, start=1)
 92                ]
 93            case Mapping():
 94                items = [MkFootNote(k, content=v) for k, v in footnotes.items()]
 95            case _:
 96                raise TypeError(footnotes)
 97        super().__init__(content=items, **kwargs)
 98
 99    def get_items(self) -> list[MkFootNote]:  # type: ignore[override]
100        """Return the list of footnotes."""
101        return self._items  # type: ignore[return-value]
102
103    def __repr__(self) -> str:
104        notes: list[mk.MkNode | str] = []
105        for item in self.get_items():
106            item_children = item.get_items()
107            if len(item_children) == 1 and isinstance(item_children[0], mktext.MkText):
108                notes.append(str(item_children[0]))
109            elif len(item_children) == 1:
110                notes.append(item_children[0])
111            else:
112                notes.append(item)
113        return reprhelpers.get_repr(self, footnotes=notes)
114
115    def __getitem__(self, index: int) -> MkFootNote:
116        for node in self.get_items():
117            if node.num == index:
118                return node
119        raise IndexError(index)
120
121    def __contains__(self, item: int | MkFootNote) -> bool:
122        match item:
123            case MkFootNote():
124                return item in self.get_items()
125            case int():
126                return any(i.num == item for i in self.get_items())
127            case _:
128                raise TypeError(item)
129
130    def _get_item_pos(self, num: int) -> int:
131        items = self.get_items()
132        item = next(i for i in items if i.num == num)
133        return items.index(item)
134
135    def __setitem__(self, index: int, value: mk.MkNode | str) -> None:
136        match value:
137            case MkFootNote():
138                node = value
139            case _:
140                node = MkFootNote(index, content=value, parent=self)
141        items = self.get_items()
142        if index in self:
143            pos = self._get_item_pos(index)
144            items[pos] = node
145        else:
146            items.append(node)
147
148    def get_content(self) -> resources.NodeContent:
149        """Single-pass: get content from sorted footnotes and resources."""
150        items = self.get_items()
151        if not items:
152            return resources.NodeContent(
153                markdown="",
154                resources=self._build_node_resources(),
155            )
156
157        items = sorted(items, key=lambda x: x.num)
158
159        # Collect content from children
160        renderer = rendering.current()
161        child_contents = [renderer.render_child(item) for item in items]
162        child_markdowns = [content.markdown for content in child_contents]
163
164        md = "".join(child_markdowns)
165
166        # Aggregate resources
167        aggregated = self._build_node_resources()
168        for child_content in child_contents:
169            aggregated.merge(child_content.resources)
170
171        return resources.NodeContent(markdown=md, resources=aggregated)
172
173    def to_md_unprocessed(self) -> str:
174        content = self.get_content()
175        return content.markdown
Page info
Code for this page
mknodes.manual.nodes_section.create_section_for_nodes
 93def create_section_for_nodes(
 94    nav: mk.MkNav,
 95    klasses: Sequence[type[mk.MkNode]],
 96) -> mk.MkTable:
 97    table = mk.MkTable(columns=["Node", "Docstrings", "Markdown extensions"])
 98    for kls in klasses:
 99        tpl = "classpage_custom.jinja"
100        page = mk.MkClassPage(kls, icon=kls.ICON, template_path=tpl, parent=nav, hide="toc")
101        nav += page
102        if kls.STATUS:
103            page.metadata.status = kls.STATUS
104        elif kls.JS_FILES:
105            page.metadata.status = "js"
106        elif kls.CSS:
107            page.metadata.status = "css"
108        page.created_by = create_section_for_nodes
109        link = mk.MkLink(page, kls.__name__, icon=kls.ICON)
110        extensions = ", ".join(f"`{i}`" for i in kls.REQUIRED_EXTENSIONS)
111        table.add_row((link, kls.__doc__, extensions))
112    return table
Resources
Resources(css=[],
          markdown_extensions={'pymdownx.highlight': {'anchor_linenums': True,
                                                      'line_spans': '__span',
                                                      'pygments_lang_class': True},
                               'pymdownx.superfences': {'custom_fences': [{'class': 'mermaid',
                                                                           'format': <function fence_code_format at 0x7ff77e88b060>,
                                                                           'name': 'mermaid'}]},
                               'tables': {}},
          plugins=[Plugin('mkdocstrings')],
          js=[],
          assets=[],
          packages=[])
Metadata
created:
  source_filename: /home/runner/work/mknodes/mknodes/src/mknodes/manual/nodes_section.py
  source_function: create_section_for_nodes
  source_line_no: 93
hide:
- toc
icon: octicons/list-ordered-16
title: MkFootNotes