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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
|
#!/usr/bin/env python3
#
# collapse.py
r"""
Adds a collapsible section to an HTML page using a details_ element.
.. _details: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details
.. versionadded:: 2.5.0
.. extensions:: sphinx_toolbox.collapse
Usage
------
.. rst:directive:: .. collapse:: [label]
Adds a collapsible section to an HTML page using a details_ element.
.. _details: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details
With non-HTML builders, the content will be added as-is.
.. rest-example::
.. collapse:: Details
Something small enough to escape casual notice.
.. collapse:: A Different Label
:class: custom-summary
:name: summary0
Something else that might escape notice.
.. collapse:: A long code block
.. code-block:: python
print("Not really")
.. rst:directive:option:: open
:type: flag
The ``:open:`` option can be used to have the section open by default.
.. versionadded:: 3.0.0
.. rest-example::
.. collapse:: Open
:open:
This section is open by default.
API Reference
----------------
"""
#
# Copyright © 2021 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
# OR OTHER DEALINGS IN THE SOFTWARE.
#
# stdlib
from typing import Optional, Sequence
# 3rd party
from docutils import nodes
from docutils.parsers.rst import directives
from docutils.parsers.rst.roles import set_classes
from domdf_python_tools.stringlist import DelimitedList
from sphinx.application import Sphinx
from sphinx.util.docutils import SphinxDirective
from sphinx.writers.html5 import HTML5Translator
# this package
from sphinx_toolbox.utils import SphinxExtMetadata, flag, metadata_add_version
__all__ = ("CollapseDirective", "CollapseNode", "visit_collapse_node", "depart_collapse_node", "setup")
class CollapseDirective(SphinxDirective):
r"""
A Sphinx directive to add a collapsible section to an HTML page using a details_ element.
.. _details: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details
"""
final_argument_whitespace: bool = True
has_content: bool = True
# The label
required_arguments: int = 1
option_spec = {
"class": directives.class_option,
"name": directives.unchanged,
"open": flag,
}
def run(self) -> Sequence[nodes.Node]: # type: ignore[override]
"""
Process the content of the directive.
"""
set_classes(self.options)
self.assert_has_content()
text = '\n'.join(self.content)
label = self.arguments[0]
collapse_node = CollapseNode(text, label, **self.options)
self.add_name(collapse_node)
collapse_node["classes"].append(f"summary-{nodes.make_id(label)}")
self.state.nested_parse(self.content, self.content_offset, collapse_node)
return [collapse_node]
class CollapseNode(nodes.Body, nodes.Element):
"""
Node that represents a collapsible section.
:param rawsource:
:param label:
"""
def __init__(self, rawsource: str = '', label: Optional[str] = None, *children, **attributes):
super().__init__(rawsource, *children, **attributes)
self["label"] = label
def visit_collapse_node(translator: HTML5Translator, node: CollapseNode) -> None:
"""
Visit a :class:`~.CollapseNode`.
:param translator:
:param node: The node being visited.
"""
tag_parts = DelimitedList(["details"])
if node.get("names", None):
names = DelimitedList(node["names"])
tag_parts.append(f'name="{names: }"')
if node.get("classes", None):
classes = DelimitedList(node["classes"])
tag_parts.append(f'class="{classes: }"')
if node.attributes.get("open", False):
tag_parts.append("open")
translator.body.append(f"<{tag_parts: }>\n<summary>{node['label']}</summary>")
translator.context.append("</details>")
def depart_collapse_node(translator: HTML5Translator, node: CollapseNode) -> None:
"""
Depart a :class:`~.CollapseNode`.
:param translator:
:param node: The node being visited.
"""
translator.body.append(translator.context.pop())
@metadata_add_version
def setup(app: Sphinx) -> SphinxExtMetadata:
"""
Setup :mod:`sphinx_toolbox.collapse`.
:param app: The Sphinx application.
"""
app.add_directive("collapse", CollapseDirective)
app.add_node(
CollapseNode,
html=(visit_collapse_node, depart_collapse_node),
latex=(lambda *args, **kwargs: None, lambda *args, **kwargs: None)
)
return {
"parallel_read_safe": True,
}
|