Skip to content

Commit f002585

Browse files
committed
Add themed_figure extension and continue next Command Queue chapter
1 parent 0cb0b98 commit f002585

File tree

11 files changed

+16070
-8
lines changed

11 files changed

+16070
-8
lines changed

_extensions/themed_figure.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
from typing import List
2+
3+
from docutils import nodes
4+
from docutils.nodes import Node, Element
5+
from docutils.statemachine import StringList
6+
from docutils.parsers.rst.directives.images import Figure
7+
8+
from sphinx.util.docutils import SphinxDirective
9+
from sphinx.application import Sphinx
10+
11+
from copy import deepcopy
12+
13+
#############################################################
14+
15+
def findNodeWithType(target_type, node_list):
16+
for n in node_list:
17+
if isinstance(n, target_type):
18+
return n
19+
20+
#############################################################
21+
22+
class ThemedFigureDirective(Figure):
23+
"""
24+
A figure that switches depending on the dark/light theme
25+
"""
26+
27+
def run(self) -> List[Node]:
28+
url_template = self.arguments[0]
29+
self.arguments[0] = url_template.replace("{theme}", "light")
30+
31+
node_list = super().run()
32+
33+
figure_node = findNodeWithType(nodes.figure, node_list)
34+
if not figure_node:
35+
print(node_list)
36+
raise Exception("Could not find generated figure in themed-figure")
37+
38+
light_image_node = findNodeWithType(nodes.image, figure_node)
39+
if not light_image_node:
40+
print(figure_node)
41+
raise Exception("Could not find generated image in themed-figure")
42+
43+
# Create dark copy
44+
dark_image_node = deepcopy(light_image_node)
45+
dark_image_node['uri'] = url_template.replace("{theme}", "dark")
46+
47+
# Add class
48+
light_image_node['classes'].append("only-light")
49+
dark_image_node['classes'].append("only-dark")
50+
51+
# Insert dark image after light image
52+
index = figure_node.index(light_image_node)
53+
figure_node.insert(index + 1, dark_image_node)
54+
55+
return node_list
56+
57+
#############################################################
58+
59+
def setup(app: Sphinx) -> None:
60+
app.add_directive("themed-figure", ThemedFigureDirective)
61+
return {
62+
'version': '0.1',
63+
'parallel_read_safe': True,
64+
'parallel_write_safe': True,
65+
}

conf.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,12 @@
3535
"sphinx_copybutton",
3636
"sphinx_favicon",
3737
"sphinx_inline_tabs",
38+
39+
# Internal extensions (see _extensions directory)
3840
"style",
3941
"sphinx_literate",
4042
"translation",
43+
"themed_figure",
4144
]
4245

4346
# Add any paths that contain templates here, relative to this directory.

0 commit comments

Comments
 (0)