Debian Codegraph @

docs/_extension/gallery_directive.py

raw
1 """A directive to generate a gallery of images from structured data.
2
3 Generating a gallery of images that are all the same size is a common
4 pattern in documentation, and this can be cumbersome if the gallery is
5 generated programmatically. This directive wraps this particular use-case
6 in a helper-directive to generate it with a single YAML configuration file.
7
8 It currently exists for maintainers of the pydata-sphinx-theme,
9 but might be abstracted into a standalone package if it proves useful.
10 """
11
12 from pathlib import Path
13 from typing import Any, ClassVar, Dict, List
14
15 from docutils import nodes
16 from docutils.parsers.rst import directives
17 from sphinx.application import Sphinx
18 from sphinx.util import logging
19 from sphinx.util.docutils import SphinxDirective
20 from yaml import safe_load
21
22
23 logger = logging.getLogger(__name__)
24
25
26 TEMPLATE_GRID = """
27 `````{{grid}} {columns}
28 {options}
29
30 {content}
31
32 `````
33 """
34
35 GRID_CARD = """
36 ````{{grid-item-card}} {title}
37 {options}
38
39 {content}
40 ````
41 """
42
43
44 class GalleryGridDirective(SphinxDirective):
45 """A directive to show a gallery of images and links in a Bootstrap grid.
46
47 The grid can be generated from a YAML file that contains a list of items, or
48 from the content of the directive (also formatted in YAML). Use the parameter
49 "class-card" to add an additional CSS class to all cards. When specifying the grid
50 items, you can use all parameters from "grid-item-card" directive to customize
51 individual cards + ["image", "header", "content", "title"].
52
53 Danger:
54 This directive can only be used in the context of a Myst documentation page as
55 the templates use Markdown flavored formatting.
56 """
57
58 name = "gallery-grid"
59 has_content = True
60 required_arguments = 0
61 optional_arguments = 1
62 final_argument_whitespace = True
63 option_spec: ClassVar[dict[str, Any]] = {
64 # A class to be added to the resulting container
65 "grid-columns": directives.unchanged,
66 "class-container": directives.unchanged,
67 "class-card": directives.unchanged,
68 }
69
70 def run(self) -> List[nodes.Node]:
71 """Create the gallery grid."""
72 if self.arguments:
73 # If an argument is given, assume it's a path to a YAML file
74 # Parse it and load it into the directive content
75 path_data_rel = Path(self.arguments[0])
76 path_doc, _ = self.get_source_info()
77 path_doc = Path(path_doc).parent
78 path_data = (path_doc / path_data_rel).resolve()
79 if not path_data.exists():
80 logger.info("Could not find grid data at %s.", path_data)
81 nodes.text("No grid data found at {path_data}.")
82 return
83 yaml_string = path_data.read_text()
84 else:
85 yaml_string = "\n".join(self.content)
86
87 # Use all the element with an img-bottom key as sites to show
88 # and generate a card item for each of them
89 grid_items = []
90 for item in safe_load(yaml_string):
91 # remove parameters that are not needed for the card options
92 title = item.pop("title", "")
93
94 # build the content of the card using some extra parameters
95 header = f"{item.pop('header')} \n^^^ \n" if "header" in item else ""
96 image = f"![image]({item.pop('image')}) \n" if "image" in item else ""
97 content = f"{item.pop('content')} \n" if "content" in item else ""
98
99 # optional parameter that influence all cards
100 if "class-card" in self.options:
101 item["class-card"] = self.options["class-card"]
102
103 loc_options_str = "\n".join(f":{k}: {v}" for k, v in item.items()) + " \n"
104
105 card = GRID_CARD.format(
106 options=loc_options_str, content=header + image + content, title=title
107 )
108 grid_items.append(card)
109
110 # Parse the template with Sphinx Design to create an output container
111 # Prep the options for the template grid
112 class_ = "gallery-directive" + f" {self.options.get('class-container', '')}"
113 options = {"gutter": 2, "class-container": class_}
114 options_str = "\n".join(f":{k}: {v}" for k, v in options.items())
115
116 # Create the directive string for the grid
117 grid_directive = TEMPLATE_GRID.format(
118 columns=self.options.get("grid-columns", "1 2 3 4"),
119 options=options_str,
120 content="\n".join(grid_items),
121 )
122
123 # Parse content as a directive so Sphinx Design processes it
124 container = nodes.container()
125 self.state.nested_parse([grid_directive], 0, container)
126
127 # Sphinx Design outputs a container too, so just use that
128 return [container.children[0]]
129
130
131 def setup(app: Sphinx) -> Dict[str, Any]:
132 """Add custom configuration to sphinx app.
133
134 Args:
135 app: the Sphinx application
136
137 Returns:
138 the 2 parallel parameters set to ``True``.
139 """
140 app.add_directive("gallery-grid", GalleryGridDirective)
141
142 return {
143 "parallel_read_safe": True,
144 "parallel_write_safe": True,
145 }