Debian Codegraph @

sphinx_design/shared.py

raw
1 """Shared constants and functions."""
2
3 from __future__ import annotations
4
5 from collections.abc import Sequence
6 from typing import final
7
8 from docutils import nodes
9 from docutils.parsers.rst import directives
10 from sphinx.application import Sphinx
11 from sphinx.config import Config
12 from sphinx.util.docutils import SphinxDirective
13 from sphinx.util.logging import getLogger
14
15 LOGGER = getLogger(__name__)
16
17 WARNING_TYPE = "design"
18
19 SEMANTIC_COLORS = (
20 "primary",
21 "secondary",
22 "success",
23 "info",
24 "warning",
25 "danger",
26 "light",
27 "muted",
28 "dark",
29 "white",
30 "black",
31 )
32
33
34 def setup_custom_directives(
35 app: Sphinx, config: Config, directive_map: dict[str, SdDirective]
36 ) -> None:
37 conf_value = config.sd_custom_directives
38
39 def _warn(msg):
40 LOGGER.warning(
41 f"sd_custom_directives: {msg}", type=WARNING_TYPE, subtype="config"
42 )
43
44 if not isinstance(conf_value, dict):
45 _warn("must be a dictionary")
46 config.sd_custom_directives = {}
47 return
48 for name, data in conf_value.items():
49 if not isinstance(name, str):
50 _warn(f"key must be a string: {name!r}")
51 continue
52 if not isinstance(data, dict):
53 _warn(f"{name!r} value must be a dictionary")
54 continue
55 if "inherit" not in data:
56 _warn(f"{name!r} value must have an 'inherit' key")
57 continue
58 if data["inherit"] not in directive_map:
59 _warn(f"'{name}.inherit' is an unknown directive key: {data['inherit']}")
60 continue
61 directive_cls = directive_map[data["inherit"]]
62 if "options" in data:
63 if not isinstance(data["options"], dict):
64 _warn(f"'{name}.options' value must be a dictionary")
65 continue
66 if "argument" in data and not isinstance(data["argument"], str):
67 _warn(f"'{name}.argument' value must be a string")
68 continue
69 for key, value in data["options"].items():
70 if key not in directive_cls.option_spec:
71 _warn(f"'{name}.options' unknown key {key!r}")
72 continue
73 if not isinstance(value, str):
74 _warn(f"'{name}.options.{key}' value must be a string")
75 continue
76 app.add_directive(name, directive_cls, override=True)
77
78
79 class SdDirective(SphinxDirective):
80 """Base class for all sphinx-design directives.
81
82 Having a base class allows for shared functionality to be implemented in one place.
83 Namely, we allow for default options to be configured, per directive name.
84
85 This class should be sub-classed by all directives in the sphinx-design extension.
86 """
87
88 # TODO perhaps ideally there would be separate sphinx extension,
89 # that generalises the concept of default directive options (that does not require subclassing)
90 # but for now I couldn't think of a trivial way to achieve this.
91
92 @final
93 def run(self) -> list[nodes.Node]:
94 """Run the directive.
95
96 This method should not be overridden, instead override `run_with_defaults`.
97 """
98 if data := self.config.sd_custom_directives.get(self.name):
99 if (not self.arguments) and (argument := data.get("argument")): # type: ignore[has-type]
100 self.arguments = [str(argument)]
101 for key, value in data.get("options", {}).items():
102 if key not in self.options and key in self.option_spec:
103 try:
104 self.options[key] = self.option_spec[key](str(value))
105 except Exception as exc:
106 LOGGER.warning(
107 f"Invalid default option {key!r} for {self.name!r}: {exc}",
108 type=WARNING_TYPE,
109 subtype="directive",
110 location=(self.env.docname, self.lineno),
111 )
112 return self.run_with_defaults()
113
114 def run_with_defaults(self) -> list[nodes.Node]:
115 """Run the directive, after default options have been set.
116
117 This method should be overridden by subclasses.
118 """
119 raise NotImplementedError
120
121
122 def create_component(
123 name: str,
124 classes: Sequence[str] = (),
125 *,
126 rawtext: str = "",
127 children: Sequence[nodes.Node] = (),
128 **attributes,
129 ) -> nodes.container:
130 """Create a container node for a design component."""
131 node = nodes.container(
132 rawtext, is_div=True, design_component=name, classes=list(classes), **attributes
133 )
134 node.extend(children)
135 return node
136
137
138 def is_component(node: nodes.Node, name: str):
139 """Check if a node is a certain design component."""
140 try:
141 return node.get("design_component") == name
142 except AttributeError:
143 return False
144
145
146 def make_choice(choices: Sequence[str]):
147 """Create a choice validator."""
148 return lambda argument: directives.choice(argument, choices)
149
150
151 def _margin_or_padding_option(
152 argument: str | None,
153 class_prefix: str,
154 allowed: Sequence[str],
155 ) -> list[str]:
156 """Validate the margin/padding is one (all) or four (top bottom left right) integers,
157 between 0 and 5 or 'auto'.
158 """
159 if argument is None:
160 raise ValueError("argument required but none supplied")
161 values = argument.split()
162 for value in values:
163 if value not in allowed:
164 raise ValueError(f"{value} is not in: {allowed}")
165 if len(values) == 1:
166 return [f"{class_prefix}-{values[0]}"]
167 if len(values) == 4:
168 return [
169 f"{class_prefix}{side}-{value}"
170 for side, value in zip(["t", "b", "l", "r"], values, strict=False)
171 ]
172 raise ValueError(
173 "argument must be one (all) or four (top bottom left right) integers"
174 )
175
176
177 def margin_option(argument: str | None) -> list[str]:
178 """Validate the margin is one (all) or four (top bottom left right) integers,
179 between 0 and 5 or 'auto'.
180 """
181 return _margin_or_padding_option(
182 argument, "sd-m", ("auto", "0", "1", "2", "3", "4", "5")
183 )
184
185
186 def padding_option(argument: str | None) -> list[str]:
187 """Validate the padding is one (all) or four (top bottom left right) integers,
188 between 0 and 5.
189 """
190 return _margin_or_padding_option(argument, "sd-p", ("0", "1", "2", "3", "4", "5"))
191
192
193 def text_align(argument: str | None) -> list[str]:
194 """Validate the text align is left, right, center or justify."""
195 value = directives.choice(argument, ["left", "right", "center", "justify"])
196 return [f"sd-text-{value}"]
197
198
199 class PassthroughTextElement(nodes.TextElement):
200 """A text element which will not render anything.
201
202 This is required for reference node to render correctly outside of paragraphs.
203 Since sphinx expects them to be within a ``TextElement``:
204 https://github.com/sphinx-doc/sphinx/blob/068f802df90ea790f89319094e407c4d5f6c26ff/sphinx/writers/html5.py#L224
205 """