Debian Codegraph @

sphinx_design/tabs.py

raw
1 from docutils import nodes
2 from docutils.parsers.rst import directives
3 from sphinx.application import Sphinx
4 from sphinx.transforms.post_transforms import SphinxPostTransform
5 from sphinx.util.logging import getLogger
6
7 from ._compat import findall
8 from .shared import WARNING_TYPE, SdDirective, create_component, is_component
9
10 LOGGER = getLogger(__name__)
11
12
13 def setup_tabs(app: Sphinx) -> None:
14 app.add_directive("tab-set", TabSetDirective)
15 app.add_directive("tab-item", TabItemDirective)
16 app.add_directive("tab-set-code", TabSetCodeDirective)
17 app.add_post_transform(TabSetHtmlTransform)
18 app.add_node(sd_tab_input, html=(visit_tab_input, depart_tab_input))
19 app.add_node(sd_tab_label, html=(visit_tab_label, depart_tab_label))
20
21
22 class TabSetDirective(SdDirective):
23 """A container for a set of tab items."""
24
25 has_content = True
26 option_spec = {
27 "sync-group": directives.unchanged_required,
28 "class": directives.class_option,
29 }
30
31 def run_with_defaults(self) -> list[nodes.Node]:
32 self.assert_has_content()
33 tab_set = create_component(
34 "tab-set", classes=["sd-tab-set", *self.options.get("class", [])]
35 )
36 self.set_source_info(tab_set)
37 self.state.nested_parse(self.content, self.content_offset, tab_set)
38 for item in tab_set.children:
39 if not is_component(item, "tab-item"):
40 LOGGER.warning(
41 f"All children of a 'tab-set' "
42 f"should be 'tab-item' [{WARNING_TYPE}.tab]",
43 location=item,
44 type=WARNING_TYPE,
45 subtype="tab",
46 )
47 break
48 if "sync_id" in item.children[0]:
49 item.children[0]["sync_group"] = self.options.get("sync-group", "tab")
50 return [tab_set]
51
52
53 class TabItemDirective(SdDirective):
54 """A single tab item in a tab set.
55
56 Note: This directive generates a single container,
57 for the label and content::
58
59 <container design_component="tab-item" has_title=True>
60 <rubric>
61 ...title nodes
62 <container design_component="tab-content">
63 ...content nodes
64
65 This allows for a default rendering in non-HTML outputs.
66
67 The ``TabHtmlTransform`` then transforms this container
68 into the HTML specific structure.
69 """
70
71 required_arguments = 1 # the tab label is the first argument
72 final_argument_whitespace = True
73 has_content = True
74 option_spec = {
75 "selected": directives.flag,
76 "sync": directives.unchanged_required,
77 "name": directives.unchanged,
78 "class-container": directives.class_option,
79 "class-label": directives.class_option,
80 "class-content": directives.class_option,
81 }
82
83 def run_with_defaults(self) -> list[nodes.Node]:
84 self.assert_has_content()
85 if not is_component(self.state_machine.node, "tab-set"):
86 LOGGER.warning(
87 f"The parent of a 'tab-item' should be a 'tab-set' [{WARNING_TYPE}.tab]",
88 location=(self.env.docname, self.lineno),
89 type=WARNING_TYPE,
90 subtype="tab",
91 )
92 tab_item = create_component(
93 "tab-item",
94 classes=["sd-tab-item", *self.options.get("class-container", [])],
95 selected=("selected" in self.options),
96 )
97
98 # add tab label
99 textnodes, _ = self.state.inline_text(self.arguments[0], self.lineno)
100 tab_label = nodes.rubric(
101 self.arguments[0],
102 "",
103 *textnodes,
104 classes=["sd-tab-label", *self.options.get("class-label", [])],
105 )
106 if "sync" in self.options:
107 tab_label["sync_id"] = self.options["sync"]
108 self.add_name(tab_label)
109 tab_item += tab_label
110
111 # add tab content
112 tab_content = create_component(
113 "tab-content",
114 classes=["sd-tab-content", *self.options.get("class-content", [])],
115 )
116 self.state.nested_parse(self.content, self.content_offset, tab_content)
117 tab_item += tab_content
118
119 return [tab_item]
120
121
122 class TabSetCodeDirective(SdDirective):
123 """A container for a set of tab items, generated from code blocks."""
124
125 has_content = True
126 option_spec = {
127 "no-sync": directives.flag,
128 "sync-group": directives.unchanged_required,
129 "class-set": directives.class_option,
130 "class-item": directives.class_option,
131 }
132
133 def run_with_defaults(self) -> list[nodes.Node]:
134 self.assert_has_content()
135 tab_set = create_component(
136 "tab-set", classes=["sd-tab-set", *self.options.get("class-set", [])]
137 )
138 self.set_source_info(tab_set)
139 self.state.nested_parse(self.content, self.content_offset, tab_set)
140 new_children = []
141 for item in tab_set.children:
142 if not isinstance(item, nodes.literal_block):
143 LOGGER.warning(
144 f"All children of a 'tab-code-set' "
145 f"should be a 'literal_block' [{WARNING_TYPE}.tab_code]",
146 location=tab_set,
147 type=WARNING_TYPE,
148 subtype="tab_code",
149 )
150 continue
151 language = item.get("language", "unknown")
152 tab_label = nodes.rubric(
153 language.upper(),
154 nodes.Text(language.upper()),
155 classes=["sd-tab-label", *self.options.get("class-label", [])],
156 )
157 if "no-sync" not in self.options:
158 tab_label["sync_group"] = self.options.get("sync-group", "code")
159 tab_label["sync_id"] = language
160 tab_content = create_component(
161 "tab-content",
162 children=[item],
163 classes=["sd-tab-content", *self.options.get("class-content", [])],
164 )
165 tab_item = create_component(
166 "tab-item",
167 children=[tab_label, tab_content],
168 classes=["sd-tab-item", *self.options.get("class-item", [])],
169 )
170 new_children.append(tab_item)
171 tab_set.children = new_children
172 return [tab_set]
173
174
175 class sd_tab_input(nodes.Element, nodes.General): # noqa: N801
176 pass
177
178
179 class sd_tab_label(nodes.TextElement, nodes.General): # noqa: N801
180 pass
181
182
183 def visit_tab_input(self, node):
184 attributes = {"ids": [node["id"]], "type": node["type"], "name": node["set_id"]}
185 if node["checked"]:
186 attributes["checked"] = "checked"
187 self.body.append(self.starttag(node, "input", **attributes))
188
189
190 def depart_tab_input(self, node):
191 # note do not add a closing tag, since this is a void element:
192 # https://developer.mozilla.org/en-US/docs/Glossary/Void_element
193 pass
194
195
196 def visit_tab_label(self, node):
197 attributes = {"for": node["input_id"]}
198 if "sync_id" in node and "sync_group" in node:
199 attributes["data-sync-id"] = node["sync_id"]
200 attributes["data-sync-group"] = node["sync_group"]
201 self.body.append(self.starttag(node, "label", **attributes))
202
203
204 def depart_tab_label(self, node):
205 self.body.append("</label>")
206
207
208 class TabSetHtmlTransform(SphinxPostTransform):
209 """Transform tab-set to HTML specific AST structure."""
210
211 default_priority = 200
212 formats = ("html",)
213
214 def run(self) -> None:
215 """Run the transform."""
216
217 # setup id generators
218 tab_set_id_base = "sd-tab-set-"
219 tab_item_id_base = "sd-tab-item-"
220 tab_item_id_num = 0
221
222 for tab_set_id_num, tab_set in enumerate(
223 findall(self.document)(lambda node: is_component(node, "tab-set"))
224 ):
225 tab_set_identity = tab_set_id_base + str(tab_set_id_num)
226 children = []
227 # get the first selected node
228 selected_idx = None
229 for idx, tab_item in enumerate(tab_set.children):
230 if tab_item.get("selected", False):
231 if selected_idx is None:
232 selected_idx = idx
233 else:
234 LOGGER.warning(
235 f"Multiple selected 'tab-item' directives [{WARNING_TYPE}.tab]",
236 location=tab_item,
237 type=WARNING_TYPE,
238 subtype="tab",
239 )
240 selected_idx = 0 if selected_idx is None else selected_idx
241
242 for idx, tab_item in enumerate(tab_set.children):
243 try:
244 tab_label, tab_content = tab_item.children
245 except ValueError:
246 raise
247 tab_item_identity = tab_item_id_base + str(tab_item_id_num)
248 tab_item_id_num += 1
249
250 # create: <input checked="checked" id="id" type="radio">
251 input_node = sd_tab_input(
252 "",
253 id=tab_item_identity,
254 set_id=tab_set_identity,
255 type="radio",
256 checked=(idx == selected_idx),
257 )
258 input_node.source, input_node.line = tab_item.source, tab_item.line
259 children.append(input_node)
260
261 # create: <label for="id">...</label>
262 label_node = sd_tab_label(
263 "",
264 "",
265 *tab_label.children,
266 input_id=tab_item_identity,
267 classes=tab_label["classes"],
268 )
269 if tab_label.get("ids"):
270 label_node["ids"] += tab_label["ids"]
271 if "sync_group" in tab_label and "sync_id" in tab_label:
272 label_node["sync_group"] = tab_label["sync_group"]
273 label_node["sync_id"] = tab_label["sync_id"]
274 label_node.source, label_node.line = tab_item.source, tab_item.line
275 children.append(label_node)
276
277 # add content
278 children.append(tab_content)
279
280 tab_set.children = children