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