|
| 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 | + } |
0 commit comments