| 1 |
from contextlib import contextmanager |
| 2 |
from functools import partial |
| 3 |
import hashlib |
| 4 |
from pathlib import Path |
| 5 |
|
| 6 |
from docutils import nodes |
| 7 |
from docutils.parsers.rst import directives |
| 8 |
from sphinx import version_info as sphinx_version |
| 9 |
from sphinx.application import Sphinx |
| 10 |
from sphinx.environment import BuildEnvironment |
| 11 |
from sphinx.transforms import SphinxTransform |
| 12 |
|
| 13 |
from . import compiled as static_module |
| 14 |
from ._compat import findall, read_text |
| 15 |
from .article_info import setup_article_info |
| 16 |
from .badges_buttons import setup_badges_and_buttons |
| 17 |
from .cards import setup_cards |
| 18 |
from .dropdown import setup_dropdown |
| 19 |
from .grids import setup_grids |
| 20 |
from .icons import setup_icons |
| 21 |
from .shared import ( |
| 22 |
PassthroughTextElement, |
| 23 |
SdDirective, |
| 24 |
create_component, |
| 25 |
setup_custom_directives, |
| 26 |
) |
| 27 |
from .tabs import setup_tabs |
| 28 |
|
| 29 |
|
| 30 |
def setup_extension(app: Sphinx) -> None: |
| 31 |
"""Set up the sphinx extension.""" |
| 32 |
app.connect("builder-inited", update_css_js) |
| 33 |
app.connect("env-updated", update_css_links) |
| 34 |
# we override container html visitors, to stop the default behaviour |
| 35 |
# of adding the `container` class to all nodes.container |
| 36 |
app.add_node( |
| 37 |
nodes.container, override=True, html=(visit_container, depart_container) |
| 38 |
) |
| 39 |
app.add_node( |
| 40 |
PassthroughTextElement, |
| 41 |
html=(visit_depart_null, visit_depart_null), |
| 42 |
latex=(visit_depart_null, visit_depart_null), |
| 43 |
text=(visit_depart_null, visit_depart_null), |
| 44 |
man=(visit_depart_null, visit_depart_null), |
| 45 |
texinfo=(visit_depart_null, visit_depart_null), |
| 46 |
) |
| 47 |
with capture_directives(app) as directive_map: |
| 48 |
app.add_directive("div", Div, override=True) |
| 49 |
app.add_transform(AddFirstTitleCss) |
| 50 |
setup_badges_and_buttons(app) |
| 51 |
setup_cards(app) |
| 52 |
setup_grids(app) |
| 53 |
setup_dropdown(app) |
| 54 |
setup_icons(app) |
| 55 |
setup_tabs(app) |
| 56 |
setup_article_info(app) |
| 57 |
|
| 58 |
app.add_config_value("sd_custom_directives", {}, "env") |
| 59 |
app.connect( |
| 60 |
"config-inited", partial(setup_custom_directives, directive_map=directive_map) |
| 61 |
) |
| 62 |
|
| 63 |
|
| 64 |
@contextmanager |
| 65 |
def capture_directives(app: Sphinx): |
| 66 |
"""Capture the directives that are registered by the extension.""" |
| 67 |
directive_map = {} |
| 68 |
add_directive = app.add_directive |
| 69 |
|
| 70 |
def _add_directive(name, directive, **kwargs): |
| 71 |
directive_map[name] = directive |
| 72 |
add_directive(name, directive, **kwargs) |
| 73 |
|
| 74 |
app.add_directive = _add_directive |
| 75 |
yield directive_map |
| 76 |
app.add_directive = add_directive |
| 77 |
|
| 78 |
|
| 79 |
def update_css_js(app: Sphinx): |
| 80 |
"""Copy the CSS to the build directory.""" |
| 81 |
# reset changed identifier |
| 82 |
app.env.sphinx_design_css_changed = False |
| 83 |
# setup up new static path in output dir |
| 84 |
static_path = (Path(app.outdir) / "_sphinx_design_static").absolute() |
| 85 |
static_existed = static_path.exists() |
| 86 |
static_path.mkdir(exist_ok=True) |
| 87 |
app.config.html_static_path.append(str(static_path)) |
| 88 |
# Copy JS to the build directory. |
| 89 |
js_path = static_path / "design-tabs.js" |
| 90 |
app.add_js_file(js_path.name) |
| 91 |
if not js_path.exists(): |
| 92 |
content = read_text(static_module, "sd_tabs.js") |
| 93 |
js_path.write_text(content) |
| 94 |
# Read the css content and hash it |
| 95 |
content = read_text(static_module, "style.min.css") |
| 96 |
# Write the css file |
| 97 |
if sphinx_version < (7, 1): |
| 98 |
hash = hashlib.md5(content.encode("utf8"), usedforsecurity=False).hexdigest() |
| 99 |
css_path = static_path / f"sphinx-design.{hash}.min.css" |
| 100 |
else: |
| 101 |
# since sphinx 7.1 a checksum is added to the css file URL, so there is no need to do it here |
| 102 |
# https://github.com/sphinx-doc/sphinx/pull/11415 |
| 103 |
css_path = static_path / "sphinx-design.min.css" |
| 104 |
app.add_css_file(css_path.name) |
| 105 |
if css_path.exists(): |
| 106 |
return |
| 107 |
if static_existed: |
| 108 |
app.env.sphinx_design_css_changed = True |
| 109 |
for path in static_path.glob("*.css"): |
| 110 |
path.unlink() |
| 111 |
css_path.write_text(content, encoding="utf8") |
| 112 |
|
| 113 |
|
| 114 |
def update_css_links(app: Sphinx, env: BuildEnvironment): |
| 115 |
"""If CSS has changed, all files must be re-written, to include the correct stylesheets.""" |
| 116 |
if env.sphinx_design_css_changed: |
| 117 |
return list(env.all_docs.keys()) |
| 118 |
|
| 119 |
|
| 120 |
def visit_container(self, node: nodes.Node): |
| 121 |
classes = "docutils container" |
| 122 |
attrs = {} |
| 123 |
if node.get("is_div", False): |
| 124 |
# we don't want the CSS for container for these nodes |
| 125 |
classes = "docutils" |
| 126 |
if "style" in node: |
| 127 |
attrs["style"] = node["style"] |
| 128 |
self.body.append(self.starttag(node, "div", CLASS=classes, **attrs)) |
| 129 |
|
| 130 |
|
| 131 |
def depart_container(self, node: nodes.Node): |
| 132 |
self.body.append("</div>\n") |
| 133 |
|
| 134 |
|
| 135 |
def visit_depart_null(self, node: nodes.Element) -> None: |
| 136 |
"""visit/depart passthrough""" |
| 137 |
|
| 138 |
|
| 139 |
class Div(SdDirective): |
| 140 |
"""Same as the ``container`` directive, |
| 141 |
but does not add the ``container`` class in HTML outputs, |
| 142 |
which can interfere with Bootstrap CSS. |
| 143 |
""" |
| 144 |
|
| 145 |
optional_arguments = 1 # css classes |
| 146 |
final_argument_whitespace = True |
| 147 |
option_spec = {"style": directives.unchanged, "name": directives.unchanged} |
| 148 |
has_content = True |
| 149 |
|
| 150 |
def run_with_defaults(self) -> list[nodes.Node]: |
| 151 |
try: |
| 152 |
if self.arguments: |
| 153 |
classes = directives.class_option(self.arguments[0]) |
| 154 |
else: |
| 155 |
classes = [] |
| 156 |
except ValueError as exc: |
| 157 |
raise self.error( |
| 158 |
f'Invalid class attribute value for "{self.name}" directive: "{self.arguments[0]}".' |
| 159 |
) from exc |
| 160 |
node = create_component("div", rawtext="\n".join(self.content), classes=classes) |
| 161 |
if "style" in self.options: |
| 162 |
node["style"] = self.options["style"] |
| 163 |
self.set_source_info(node) |
| 164 |
self.add_name(node) |
| 165 |
if self.content: |
| 166 |
self.state.nested_parse(self.content, self.content_offset, node) |
| 167 |
return [node] |
| 168 |
|
| 169 |
|
| 170 |
class AddFirstTitleCss(SphinxTransform): |
| 171 |
"""Add a CSS class to to the first sections title.""" |
| 172 |
|
| 173 |
default_priority = 699 # priority main |
| 174 |
|
| 175 |
def apply(self): |
| 176 |
hide = False |
| 177 |
for docinfo in findall(self.document)(nodes.docinfo): |
| 178 |
for name in findall(docinfo)(nodes.field_name): |
| 179 |
if name.astext() == "sd_hide_title": |
| 180 |
hide = True |
| 181 |
break |
| 182 |
break |
| 183 |
if not hide: |
| 184 |
return |
| 185 |
for section in findall(self.document)(nodes.section): |
| 186 |
if isinstance(section.children[0], nodes.title): |
| 187 |
if "classes" in section.children[0]: |
| 188 |
section.children[0]["classes"].append("sd-d-none") |
| 189 |
else: |
| 190 |
section.children[0]["classes"] = ["sd-d-none"] |
| 191 |
break |