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