-
Notifications
You must be signed in to change notification settings - Fork 32
/
content_tabs.py
179 lines (145 loc) · 5.75 KB
/
content_tabs.py
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
"""
A special theme-specific extension to support "content tabs" from mkdocs-material.
"""
from typing import List
from docutils import nodes
from docutils.parsers.rst import directives
from sphinx.util.docutils import SphinxDirective
from sphinx.application import Sphinx
from sphinx.util.logging import getLogger
from sphinx.writers.html import HTMLTranslator
LOGGER = getLogger(__name__)
def is_md_tab_type(node: nodes.Node, name: str):
"""Check if a node is a certain tabbed component."""
try:
return node.get("type") == name
except AttributeError:
return False
class content_tab_set(nodes.container):
pass
class MaterialTabSetDirective(SphinxDirective):
"""A container for a set of tab items."""
has_content = True
option_spec = {
"name": directives.unchanged,
"class": directives.class_option,
}
def run(self) -> List[nodes.Node]:
"""Run the directive."""
self.assert_has_content()
tab_set = content_tab_set(
"",
is_div=True,
type="md-tab-set",
classes=["tabbed-set", "tabbed-alternate"] + self.options.get("class", []),
)
self.set_source_info(tab_set)
if self.options.get("name", ""):
self.add_name(tab_set)
self.state.nested_parse(self.content, self.content_offset, tab_set)
for item in tab_set.children:
if not is_md_tab_type(item, "md-tab-item"):
LOGGER.warning(
"All children of a 'md-tab-set' should be 'md-tab-item'",
location=item,
)
break
return [tab_set]
class MaterialTabItemDirective(SphinxDirective):
"""A single tab item in a tab set.
Note: This directive generates a single container,
for the label and content::
<container design_component="tab-item" has_title=True>
<rubric>
...title nodes
<container design_component="tab-content">
...content nodes
This allows for a default rendering in non-HTML outputs.
The ``MaterialTabSetHtmlTransform`` then transforms this container
into the HTML specific structure.
"""
required_arguments = 1 # the tab label is the first argument
final_argument_whitespace = True
has_content = True
option_spec = {
"class": directives.class_option,
}
def run(self) -> List[nodes.Node]:
"""Run the directive."""
self.assert_has_content()
if not is_md_tab_type(self.state_machine.node, "md-tab-set"):
LOGGER.warning(
"The parent of a 'md-tab-item' should be a 'md-tab-set'",
location=(self.env.docname, self.lineno),
)
tab_item = nodes.container(
"", is_div=True, type="md-tab-item", classes=["tabbed-block"]
)
# add tab label
textnodes, _ = self.state.inline_text(self.arguments[0], self.lineno)
tab_label = nodes.rubric(
self.arguments[0], *textnodes, classes=["tabbed-label"]
)
self.add_name(tab_label)
tab_item += tab_label
# add tab content
tab_content = nodes.container(
"",
is_div=True,
type="",
classes=["tabbed-block"] + self.options.get("class", []),
)
self.state.nested_parse(self.content, self.content_offset, tab_content)
tab_item += tab_content
return [tab_item]
class content_tab_label(nodes.TextElement, nodes.General):
pass
def visit_tab_label(self, node):
attributes = {"for": node["input_id"]}
self.body.append(self.starttag(node, "label", **attributes))
def depart_tab_label(self, node):
self.body.append("</label>")
def visit_tab_set(self: HTMLTranslator, node: content_tab_set):
# increment tab set counter
self.tab_set_count = getattr(self, "tab_set_count", 0) + 1
# configure tab set's div attributes
tab_set_identity = f"__tabbed_{self.tab_set_count}"
attributes = {"data-tabs": f"{self.tab_set_count}:{len(node.children)}"}
self.body.append(self.starttag(node, "div", **attributes))
# walkabout the children
tab_label_div = nodes.container("", is_div=True, classes=["tabbed-labels"])
tab_content_div = nodes.container("", is_div=True, classes=["tabbed-content"])
for tab_count, tab_item in enumerate(node.children):
try:
tab_label, tab_block = tab_item.children
except ValueError as exc:
raise ValueError(f"md-tab-item has no children:\n{repr(tab_item)}") from exc
tab_item_identity = tab_set_identity + f"_{tab_count + 1}"
# create: <input checked="checked" id="id" type="radio">
self.body.append(
"<input "
+ ("checked " if not tab_count else "")
+ f'type="radio" id="{self.attval(tab_item_identity)}"'
+ f' name="{self.attval(tab_set_identity)}">'
)
# create: <label for="id">...</label>
label_node = content_tab_label(
"",
*tab_label.children,
input_id=tab_item_identity,
classes=tab_label["classes"],
)
label_node.source, label_node.line = tab_item.source, tab_item.line
tab_label_div += label_node
# add content
tab_content_div += tab_block
tab_label_div.walkabout(self)
tab_content_div.walkabout(self)
raise nodes.SkipNode()
def depart_tab_set(self, node):
self.body.append("</div>")
def setup(app: Sphinx) -> None:
app.add_directive("md-tab-set", MaterialTabSetDirective)
app.add_directive("md-tab-item", MaterialTabItemDirective)
app.add_node(content_tab_label, html=(visit_tab_label, depart_tab_label))
app.add_node(content_tab_set, html=(visit_tab_set, depart_tab_set))