|
1 | 1 | import xml.etree.ElementTree as ET |
2 | | - |
3 | | -from docutils.parsers.rst import directives |
4 | | -from docutils.parsers.rst.directives.images import Image |
5 | | -from docutils.nodes import image, paragraph |
| 2 | +from docutils.parsers.rst import Directive, directives |
| 3 | +from docutils import nodes |
6 | 4 | from pathlib import Path |
7 | 5 |
|
8 | 6 | SPHINX_IMAGE_PATH = "blockimg" |
9 | 7 |
|
10 | | -SVG_SCALE = 0.9 |
11 | | - |
12 | | - |
13 | | -def get_svg_size(file_path): |
14 | | - tree = ET.parse(file_path) |
15 | | - root = tree.getroot() |
16 | | - |
17 | | - width = root.attrib.get("width") |
18 | | - height = root.attrib.get("height") |
19 | 8 |
|
20 | | - return float(width), float(height) |
| 9 | +def get_svg_content(file_path): |
| 10 | + with open(file_path, "r", encoding="utf-8") as file: |
| 11 | + return file.read() |
21 | 12 |
|
22 | 13 |
|
23 | 14 | # Global variable to store the app object |
24 | 15 | app = None |
25 | 16 |
|
26 | 17 |
|
27 | | -class BlockImageDirective(Image): |
28 | | - option_spec = Image.option_spec.copy() |
29 | | - option_spec["stack"] = directives.flag |
| 18 | +class BlockImageDirective(Directive): |
| 19 | + has_content = False |
| 20 | + required_arguments = 1 |
| 21 | + optional_arguments = 0 |
30 | 22 |
|
31 | 23 | def run(self): |
32 | 24 | # Adjust the image path |
33 | 25 | file_name = self.arguments[0] + ".svg" |
34 | | - self.arguments[0] = "/" + SPHINX_IMAGE_PATH + "/" + file_name |
35 | | - path = Path(app.srcdir) / SPHINX_IMAGE_PATH / file_name |
36 | | - |
37 | | - # Set it to the scaled SVG size unless width explicitly set. |
38 | | - if self.options.get("width") is None: |
39 | | - width, height = get_svg_size(path) |
40 | | - self.options["width"] = str(round(width * SVG_SCALE)) + "px" |
41 | | - self.options["height"] = str(round(height * SVG_SCALE)) + "px" |
42 | | - |
43 | | - # Call the parent class's run method |
44 | | - nodes = super().run() |
45 | | - |
46 | | - # Wrap each image node in a paragraph node |
47 | | - for i, node in enumerate(nodes): |
48 | | - if isinstance(node, image): |
49 | | - if "stack" not in self.options: |
50 | | - node["classes"].append("block-image") |
51 | | - nodes[i] = paragraph("", "", node) |
52 | | - |
53 | | - return nodes |
| 26 | + file_path = Path(app.srcdir) / SPHINX_IMAGE_PATH / file_name |
| 27 | + |
| 28 | + # Read the SVG content |
| 29 | + svg_content = get_svg_content(file_path) |
| 30 | + |
| 31 | + # Create a raw HTML node with the SVG content |
| 32 | + raw_html = f'<div class="svg-container">{svg_content}</div>' |
| 33 | + raw_node = nodes.raw("", raw_html, format="html") |
| 34 | + |
| 35 | + return [raw_node] |
54 | 36 |
|
55 | 37 |
|
56 | 38 | def setup(apparg): |
|
0 commit comments