MkAnnotations

github Show source on GitHub

Node containing a list of MkAnnotations.

class MkAnnotations(mkcontainer.MkContainer)

Name

Children

Inherits

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

graph TD
  3461153190["mkannotations.MkAnnotations"]
  835538629["mkcontainer.MkContainer"]
  1956333208["mkcontainer.MkContainerBase"]
  1359323199["mknode.MkNode"]
  2751680898["builtins.object"]
  835538629 --> 3461153190
  1956333208 --> 835538629
  1359323199 --> 1956333208
  2751680898 --> 1359323199
/home/runner/work/mknodes/mknodes/src/mknodes/basenodes/mkannotations/metadata.toml
[metadata]
name = "MkAnnotations"
icon = "mdi:alert-box"

[requirements.extension."pymdownx.superfences"]

[examples.python]
python = """
import mknodes as mk

page += mk.MkCode.for_object(mk.MkCode.for_object, extract_body=True)
node = MkAnnotations()
page += node
text = mk.MkText("The MkAnnotations node aggregates annotations(1).")
page += text
info = r"Annotations are numbered and can be set via \\__setitem__."
node[1] = info  # (1)
admonition = mk.MkAdmonition("They can also contain other Markdown.")
node[2] = admonition  # (2)
text.annotations[1] = "Every MkNode can annotate via the 'annotations' attribute"
page += mk.MkCode(str(node), language="markdown", header="Markdown")
"""

[fragments.annotation]
template = """
{{ node.num }}.{{ 3 - self.num | string | length }}{{ node.get_items() | join("\n\n") | indent }}
"""

[output.markdown]
template = """
{{ node.get_items() | sort(attribute="num") | join }}
"""
mknodes.basenodes.mkannotations.MkAnnotations
 62class MkAnnotations(mkcontainer.MkContainer):
 63    """Node containing a list of MkAnnotations."""
 64
 65    REQUIRED_EXTENSIONS = [resources.Extension("pymdownx.superfences")]
 66    ICON = "material/alert-box"
 67
 68    def __init__(
 69        self,
 70        annotations: Mapping[int, str | mk.MkNode] | list[mk.MkNode | str] | None = None,
 71        **kwargs: Any,
 72    ) -> None:
 73        """Constructor.
 74
 75        Args:
 76            annotations: Annotations data (Can be given in different shapes)
 77            kwargs: Keyword arguments passed to parent
 78        """
 79        match annotations:
 80            case None:
 81                items = []
 82            case list():
 83                items = [
 84                    (ann if isinstance(ann, MkAnnotation) else MkAnnotation(i, ann))
 85                    for i, ann in enumerate(annotations, start=1)
 86                ]
 87            case Mapping():
 88                items = [MkAnnotation(k, content=v) for k, v in annotations.items()]
 89            case _:  # pyright: ignore[reportUnnecessaryComparison]
 90                raise TypeError(annotations)
 91        super().__init__(content=items, **kwargs)
 92
 93    def get_items(self) -> list[MkAnnotation]:  # type: ignore[override]
 94        """Return the list of annotations."""
 95        return self._items  # type: ignore[return-value]
 96
 97    def __getitem__(self, item: int) -> MkAnnotation:
 98        for node in self.get_items():
 99            if node.num == item:
100                return node
101        raise IndexError(item)
102
103    def __contains__(self, item: int | MkAnnotation) -> bool:
104        match item:
105            case MkAnnotation():
106                return item in self.get_items()
107            case int():
108                return any(i.num == item for i in self.get_items())
109            case _:
110                raise TypeError(item)
111
112    def __repr__(self) -> str:
113        notes: list[str | MkAnnotation] = []
114        for item in self.get_items():
115            item_children = item.get_items()
116            if len(item_children) == 1:
117                string = reprhelpers.to_str_if_textnode(item_children[0])
118                notes.append(string)
119            else:
120                notes.append(item)
121        return reprhelpers.get_repr(self, annotations=notes)
122
123    def _get_item_pos(self, num: int) -> int:
124        items = self.get_items()
125        item = next(i for i in items if i.num == num)
126        return items.index(item)
127
128    def __setitem__(self, index: int, value: mk.MkNode | str) -> None:
129        import mknodes as mk
130
131        match value:
132            case str():
133                item = mk.MkText(value)
134                node = MkAnnotation(index, content=item, parent=self)
135            case MkAnnotation():
136                node = value
137            case mk.MkNode():
138                node = MkAnnotation(index, content=value, parent=self)
139        items = self.get_items()
140        if index in self:
141            pos = self._get_item_pos(index)
142            items[pos] = node
143        else:
144            items.append(node)
145
146    def get_content(self) -> resources.NodeContent:
147        """Single-pass: get content from sorted annotations and resources."""
148        items = self.get_items()
149        if not items:
150            return resources.NodeContent(
151                markdown="",
152                resources=self._build_node_resources(),
153            )
154
155        items = sorted(items, key=lambda x: x.num)
156
157        # Collect content from children
158        renderer = rendering.current()
159        child_contents = [renderer.render_child(item) for item in items]
160        child_markdowns = [content.markdown for content in child_contents]
161
162        md = "".join(child_markdowns)
163
164        # Aggregate resources
165        aggregated = self._build_node_resources()
166        for child_content in child_contents:
167            aggregated.merge(child_content.resources)
168
169        return resources.NodeContent(markdown=md, resources=aggregated)
170
171    def to_md_unprocessed(self) -> str:
172        content = self.get_content()
173        return content.markdown
174
175    def annotate_text(self, markdown: str) -> str:
176        if not self.get_items():
177            return markdown
178        return f'<div class="annotate" markdown>\n{markdown}\n</div>\n\n{self}'
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: material/alert-box
title: MkAnnotations