Debian Codegraph @

sphinx_design/icons.py

raw
1 from collections.abc import Sequence
2 from functools import lru_cache
3 import json
4 import re
5 from typing import Any
6
7 from docutils import nodes
8 from docutils.parsers.rst import directives
9 from sphinx.application import Sphinx
10 from sphinx.util import logging
11 from sphinx.util.docutils import SphinxRole
12
13 from . import compiled
14 from ._compat import read_text
15 from .shared import WARNING_TYPE, SdDirective
16
17 logger = logging.getLogger(__name__)
18
19 OCTICON_VERSION = "v19.8.0"
20
21 OCTICON_CSS = """\
22 .octicon {
23 display: inline-block;
24 vertical-align: text-top;
25 fill: currentColor;
26 }"""
27
28
29 def setup_icons(app: Sphinx) -> None:
30 app.add_role("octicon", OcticonRole())
31 app.add_directive("_all-octicon", AllOcticons)
32 for style in ["fa", "fas", "fab", "far"]:
33 # note: fa is deprecated in v5, fas is the default and fab is the other free option
34 app.add_role(style, FontawesomeRole(style))
35 for style in ["regular", "outlined", "round", "sharp", "twotone"]:
36 app.add_role("material-" + style, MaterialRole(style))
37 app.add_config_value("sd_fontawesome_latex", False, "env")
38 app.connect("config-inited", add_fontawesome_pkg)
39 app.add_node(
40 fontawesome,
41 html=(visit_fontawesome_html, depart_fontawesome_html),
42 latex=(visit_fontawesome_latex, None),
43 man=(visit_fontawesome_warning, None),
44 text=(visit_fontawesome_warning, None),
45 texinfo=(visit_fontawesome_warning, None),
46 )
47
48
49 @lru_cache(1)
50 def get_octicon_data() -> dict[str, Any]:
51 """Load all octicon data."""
52 content = read_text(compiled, "octicons.json")
53 return json.loads(content)
54
55
56 def list_octicons() -> list[str]:
57 """List available octicon names."""
58 return list(get_octicon_data().keys())
59
60
61 HEIGHT_REGEX = re.compile(r"^(?P<value>\d+(\.\d+)?)(?P<unit>px|em|rem)$")
62
63
64 def get_octicon(
65 name: str,
66 height: str = "1em",
67 classes: Sequence[str] = (),
68 aria_label: str | None = None,
69 ) -> str:
70 """Return the HTML for an GitHub octicon SVG icon.
71
72 :height: the height of the octicon, with suffix unit 'px', 'em' or 'rem'.
73 """
74 try:
75 data = get_octicon_data()[name]
76 except KeyError as exc:
77 raise KeyError(f"Unrecognised octicon: {name}") from exc
78
79 match = HEIGHT_REGEX.match(height)
80 if not match:
81 raise ValueError(
82 f"Invalid height: '{height}', must be format <integer><px|em|rem>"
83 )
84 height_value = round(float(match.group("value")), 3)
85 height_unit = match.group("unit")
86
87 original_height = 16
88 if "16" not in data["heights"]:
89 original_height = int(next(iter(data["heights"].keys())))
90 elif "24" in data["heights"]:
91 if height_unit == "px":
92 if height_value >= 24:
93 original_height = 24
94 elif height_value >= 1.5:
95 original_height = 24
96 original_width = data["heights"][str(original_height)]["width"]
97 width_value = round(original_width * height_value / original_height, 3)
98 content = data["heights"][str(original_height)]["path"]
99 options = {
100 "version": "1.1",
101 "width": f"{width_value}{height_unit}",
102 "height": f"{height_value}{height_unit}",
103 "class": " ".join(("sd-octicon", f"sd-octicon-{name}", *classes)),
104 }
105
106 options["viewBox"] = f"0 0 {original_width} {original_height}"
107
108 if aria_label is not None:
109 options["aria-label"] = aria_label
110 options["role"] = "img"
111 else:
112 options["aria-hidden"] = "true"
113
114 opt_string = " ".join(f'{k}="{v}"' for k, v in options.items())
115 return f"<svg {opt_string}>{content}</svg>"
116
117
118 class OcticonRole(SphinxRole):
119 """Role to display a GitHub octicon SVG.
120
121 Additional classes can be added to the element after a semicolon.
122 """
123
124 def run(self) -> tuple[list[nodes.Node], list[nodes.system_message]]:
125 """Run the role."""
126 values = self.text.split(";") if ";" in self.text else [self.text]
127 icon = values[0]
128 height = "1em" if len(values) < 2 else values[1]
129 classes = "" if len(values) < 3 else values[2]
130 icon = icon.strip()
131 try:
132 svg = get_octicon(icon, height=height, classes=classes.split())
133 except Exception as exc:
134 msg = self.inliner.reporter.error(
135 f"Invalid octicon content: {exc}",
136 line=self.lineno,
137 )
138 prb = self.inliner.problematic(self.rawtext, self.rawtext, msg)
139 return [prb], [msg]
140 node = nodes.raw("", nodes.Text(svg), format="html")
141 self.set_source_info(node)
142 return [node], []
143
144
145 class AllOcticons(SdDirective):
146 """Directive to generate all octicon icons.
147
148 Primarily for self documentation.
149 """
150
151 option_spec = {
152 "class": directives.class_option,
153 }
154
155 def run_with_defaults(self) -> list[nodes.Node]:
156 classes = self.options.get("class", [])
157 table = nodes.table()
158 group = nodes.tgroup(cols=2)
159 table += group
160 group.extend(
161 (
162 nodes.colspec(colwidth=1),
163 nodes.colspec(colwidth=1),
164 )
165 )
166 body = nodes.tbody()
167 group += body
168 for icon in list_octicons():
169 row = nodes.row()
170 body += row
171 cell = nodes.entry()
172 row += cell
173 cell += nodes.literal(icon, icon)
174 cell = nodes.entry()
175 row += cell
176 cell += nodes.raw(
177 "",
178 get_octicon(icon, classes=classes),
179 format="html",
180 )
181 return [table]
182
183
184 class fontawesome(nodes.Element, nodes.General): # noqa: N801
185 """Node for rendering fontawesome icon."""
186
187
188 class FontawesomeRole(SphinxRole):
189 """Role to display a Fontawesome icon.
190
191 Additional classes can be added to the element after a semicolon.
192 """
193
194 def __init__(self, style: str) -> None:
195 super().__init__()
196 self.style = style
197
198 def run(self) -> tuple[list[nodes.Node], list[nodes.system_message]]:
199 """Run the role."""
200 icon, classes = self.text.split(";", 1) if ";" in self.text else [self.text, ""]
201 icon = icon.strip()
202 node = fontawesome(
203 icon=icon, classes=[self.style, f"fa-{icon}", *classes.split()]
204 )
205 self.set_source_info(node)
206 return [node], []
207
208
209 def visit_fontawesome_html(self, node):
210 self.body.append(self.starttag(node, "span", ""))
211
212
213 def depart_fontawesome_html(self, node):
214 self.body.append("</span>")
215
216
217 def add_fontawesome_pkg(app, config):
218 if app.config.sd_fontawesome_latex:
219 app.add_latex_package("fontawesome")
220
221
222 def visit_fontawesome_latex(self, node):
223 """Add latex fonteawesome icon, if configured, else warn."""
224 if self.config.sd_fontawesome_latex:
225 self.body.append(f"\\faicon{{{node['icon']}}}")
226 else:
227 logger.warning(
228 "Fontawesome icons not included in LaTeX output, "
229 f"consider 'sd_fontawesome_latex=True' [{WARNING_TYPE}.fa-build]",
230 location=node,
231 type=WARNING_TYPE,
232 subtype="fa-build",
233 )
234 raise nodes.SkipNode
235
236
237 def visit_fontawesome_warning(self, node: nodes.Element) -> None:
238 """Warn that fontawesome is not supported for this builder."""
239 logger.warning(
240 "Fontawesome icons not supported for builder: "
241 f"{self.builder.name} [{WARNING_TYPE}.fa-build]",
242 location=node,
243 type=WARNING_TYPE,
244 subtype="fa-build",
245 )
246 raise nodes.SkipNode
247
248
249 @lru_cache(1)
250 def get_material_icon_data(style: str) -> dict[str, Any]:
251 """Load all octicon data."""
252 content = read_text(compiled, f"material_{style}.json")
253 return json.loads(content)
254
255
256 def get_material_icon(
257 style: str,
258 name: str,
259 height: str = "1em",
260 classes: Sequence[str] = (),
261 aria_label: str | None = None,
262 ) -> str:
263 """Return the HTML for an Google material icon SVG icon.
264
265 :height: the height of the material icon, with suffix unit 'px', 'em' or 'rem'.
266 """
267 try:
268 data = get_material_icon_data(style)[name]
269 except KeyError as exc:
270 raise KeyError(f"Unrecognised material-{style} icon: {name}") from exc
271
272 match = HEIGHT_REGEX.match(height)
273 if not match:
274 raise ValueError(
275 f"Invalid height: '{height}', must be format <integer><px|em|rem>"
276 )
277 height_value = round(float(match.group("value")), 3)
278 height_unit = match.group("unit")
279
280 original_height = 20
281 if "20" not in data["heights"]:
282 original_height = int(next(iter(data["heights"].keys())))
283 elif "24" in data["heights"]:
284 if height_unit == "px":
285 if height_value >= 24:
286 original_height = 24
287 elif height_value >= 1.5:
288 original_height = 24
289 original_width = data["heights"][str(original_height)]["width"]
290 width_value = round(original_width * height_value / original_height, 3)
291 content = data["heights"][str(original_height)]["path"]
292 options = {
293 "version": "4.0.0.63c5cb3",
294 "width": f"{width_value}{height_unit}",
295 "height": f"{height_value}{height_unit}",
296 "class": " ".join(("sd-material-icon", f"sd-material-icon-{name}", *classes)),
297 }
298
299 options["viewBox"] = f"0 0 {original_width} {original_height}"
300
301 if aria_label is not None:
302 options["aria-label"] = aria_label
303 options["role"] = "img"
304 else:
305 options["aria-hidden"] = "true"
306
307 opt_string = " ".join(f'{k}="{v}"' for k, v in options.items())
308 return f"<svg {opt_string}>{content}</svg>"
309
310
311 class MaterialRole(SphinxRole):
312 """Role to display a Material-* icon.
313
314 Additional classes can be added to the element after a semicolon.
315 """
316
317 def __init__(self, style: str) -> None:
318 super().__init__()
319 self.style = style
320
321 def run(self) -> tuple[list[nodes.Node], list[nodes.system_message]]:
322 """Run the role."""
323 values = self.text.split(";") if ";" in self.text else [self.text]
324 icon = values[0]
325 height = "1em" if len(values) < 2 else values[1]
326 classes = "" if len(values) < 3 else values[2]
327 icon = icon.strip()
328 try:
329 svg = get_material_icon(
330 self.style, icon, height=height, classes=classes.split()
331 )
332 except Exception as exc:
333 msg = self.inliner.reporter.error(
334 f"Invalid material-{self.style} icon content: {type(exc)} {exc}",
335 line=self.lineno,
336 )
337 prb = self.inliner.problematic(self.rawtext, self.rawtext, msg)
338 return [prb], [msg]
339 node = nodes.raw("", nodes.Text(svg), format="html")
340 self.set_source_info(node)
341 return [node], []