Debian Codegraph @

sphinx_design/dropdown.py

raw
1 """Originally Adapted from sphinxcontrib.details.directive"""
2
3 from docutils import nodes
4 from docutils.parsers.rst import directives
5 from sphinx.application import Sphinx
6 from sphinx.transforms.post_transforms import SphinxPostTransform
7
8 from sphinx_design.shared import (
9 SEMANTIC_COLORS,
10 SdDirective,
11 create_component,
12 is_component,
13 make_choice,
14 margin_option,
15 )
16
17 from ._compat import findall
18 from .icons import get_octicon, list_octicons
19
20
21 def setup_dropdown(app: Sphinx) -> None:
22 app.add_node(dropdown_main, html=(visit_dropdown_main, depart_dropdown_main))
23 app.add_node(dropdown_title, html=(visit_dropdown_title, depart_dropdown_title))
24 app.add_directive("dropdown", DropdownDirective)
25 app.add_post_transform(DropdownHtmlTransform)
26
27
28 class dropdown_main(nodes.Element, nodes.General): # noqa: N801
29 pass
30
31
32 class dropdown_title(nodes.TextElement, nodes.General): # noqa: N801
33 pass
34
35
36 def visit_dropdown_main(self, node):
37 if node.get("opened"):
38 self.body.append(self.starttag(node, "details", open="open"))
39 else:
40 self.body.append(self.starttag(node, "details"))
41
42
43 def depart_dropdown_main(self, node):
44 self.body.append("</details>")
45
46
47 def visit_dropdown_title(self, node):
48 self.body.append(self.starttag(node, "summary"))
49
50
51 def depart_dropdown_title(self, node):
52 self.body.append("</summary>")
53
54
55 class DropdownDirective(SdDirective):
56 """A directive to generate a collapsible container.
57
58 Note: This directive generates a single container,
59 for the title (optional) and content::
60
61 <container design_component="dropdown" has_title=True>
62 <rubric>
63 ...title nodes
64 ...content nodes
65
66 This allows for a default rendering in non-HTML outputs.
67
68 The ``DropdownHtmlTransform`` then transforms this container
69 into the HTML specific structure.
70 """
71
72 optional_arguments = 1 # title of dropdown
73 final_argument_whitespace = True
74 has_content = True
75 option_spec = {
76 "open": directives.flag, # make open by default
77 "color": make_choice(SEMANTIC_COLORS),
78 "icon": make_choice(list_octicons()),
79 "chevron": make_choice(
80 ["right-down", "down-up"]
81 ), # chevron direction closed-open
82 "animate": make_choice(("fade-in", "fade-in-slide-down")),
83 "margin": margin_option,
84 "name": directives.unchanged,
85 "class-container": directives.class_option,
86 "class-title": directives.class_option,
87 "class-body": directives.class_option,
88 }
89
90 def run_with_defaults(self) -> list[nodes.Node]:
91 # default classes
92 classes = {
93 "container_classes": self.options.get("margin", ["sd-mb-3"])
94 + self.options.get("class-container", []),
95 "title_classes": self.options.get("class-title", []),
96 "body_classes": self.options.get("class-body", []),
97 }
98
99 # add color classes
100 title_color = self.options.get("color")
101 if title_color:
102 classes["title_classes"].extend(
103 [f"sd-bg-{title_color}", f"sd-bg-text-{title_color}"]
104 )
105
106 # add animation classes
107 if (
108 "animate" in self.options
109 and ("sd-" + self.options["animate"]) not in classes["container_classes"]
110 ):
111 classes["container_classes"].append("sd-" + self.options["animate"])
112
113 container = create_component(
114 "dropdown",
115 opened="open" in self.options,
116 type="dropdown",
117 has_title=len(self.arguments) > 0,
118 icon=self.options.get("icon"),
119 chevron=self.options.get("chevron"),
120 **classes,
121 )
122 self.set_source_info(container)
123 if self.arguments:
124 textnodes, messages = self.state.inline_text(self.arguments[0], self.lineno)
125 title_node = nodes.rubric(self.arguments[0], "", *textnodes)
126 container += title_node
127 container += messages
128 # where possible we add the target to the title node,
129 # so that it can be used as the reference text
130 self.add_name(title_node)
131 else:
132 self.add_name(container)
133 self.state.nested_parse(self.content, self.content_offset, container)
134 return [container]
135
136
137 class DropdownHtmlTransform(SphinxPostTransform):
138 """Transform dropdown containers into the HTML specific AST structures::
139
140 <details class="sd-sphinx-override sd-dropdown sd-card">
141 <summary class="sd-summary-title sd-card-header">
142 ...title nodes
143 <div class="sd-summary-content sd-card-body">
144 ...content nodes
145
146 """
147
148 default_priority = 199
149 formats = ("html",)
150
151 def run(self) -> None:
152 """Run the transform"""
153 document: nodes.document = self.document
154 for node in findall(document)(lambda node: is_component(node, "dropdown")):
155 # TODO option to not have card css (but requires more formatting)
156 use_card = True
157
158 marker_type = (
159 "chevron-down" if node["chevron"] == "down-up" else "chevron-right"
160 )
161 state_marker = nodes.inline(
162 "",
163 "",
164 nodes.raw(
165 "",
166 nodes.Text(get_octicon(marker_type, height="1.5em")),
167 format="html",
168 ),
169 classes=["sd-summary-state-marker", f"sd-summary-{marker_type}"],
170 )
171
172 newnode = dropdown_main(
173 opened=node["opened"],
174 classes=["sd-sphinx-override", "sd-dropdown"]
175 + (["sd-card"] if use_card else ["sd-d-flex-column"])
176 + node["container_classes"],
177 )
178
179 if node["has_title"]:
180 title_text_children = node[0].children
181 if node[0].get("ids"):
182 newnode["ids"] += node[0]["ids"]
183 body_children = node[1:]
184 else:
185 title_text_children = [
186 nodes.raw(
187 "...",
188 nodes.Text(
189 get_octicon(
190 "kebab-horizontal", height="1.5em", classes=["no-title"]
191 )
192 ),
193 format="html",
194 )
195 ]
196 body_children = node.children
197 title_text_node = nodes.inline(
198 "",
199 "",
200 *title_text_children,
201 classes=["sd-summary-text"],
202 )
203 title_children = [title_text_node, state_marker]
204 if node["icon"]:
205 title_children.insert(
206 0,
207 nodes.raw(
208 "",
209 get_octicon(node["icon"], height="1em"),
210 classes=["sd-summary-icon"],
211 format="html",
212 ),
213 )
214
215 newnode += dropdown_title(
216 "",
217 "",
218 *title_children,
219 classes=["sd-summary-title"]
220 + (["sd-card-header"] if use_card else [])
221 + node["title_classes"],
222 )
223 body_node = create_component(
224 "dropdown-body",
225 classes=["sd-summary-content"]
226 + (["sd-card-body"] if use_card else [])
227 + node["body_classes"],
228 children=body_children,
229 )
230 if use_card:
231 for para in findall(body_node)(nodes.paragraph):
232 para["classes"] = ([] if "classes" in para else para["classes"]) + [
233 "sd-card-text"
234 ]
235 newnode += body_node
236 # newnode += open_marker
237 node.replace_self(newnode)