|
| 1 | +"""Base class for widgets and the docutils node that wraps rendered output.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import abc |
| 6 | +import collections.abc |
| 7 | +import pathlib |
| 8 | +import typing as t |
| 9 | + |
| 10 | +import jinja2 |
| 11 | +from docutils import nodes |
| 12 | + |
| 13 | +if t.TYPE_CHECKING: |
| 14 | + from sphinx.environment import BuildEnvironment |
| 15 | + from sphinx.writers.html5 import HTML5Translator |
| 16 | + |
| 17 | + |
| 18 | +class widget_container(nodes.container): # type: ignore[misc] # docutils nodes are untyped |
| 19 | + """Wraps a widget's rendered HTML; visit/depart emit the outer div.""" |
| 20 | + |
| 21 | + |
| 22 | +def visit_widget_container( |
| 23 | + translator: HTML5Translator, |
| 24 | + node: widget_container, |
| 25 | +) -> None: |
| 26 | + """Open ``<div class="lm-widget lm-widget-{name}">`` for the widget.""" |
| 27 | + name = node["widget_name"] |
| 28 | + translator.body.append( |
| 29 | + f'<div class="lm-widget lm-widget-{name}" data-widget="{name}">' |
| 30 | + ) |
| 31 | + |
| 32 | + |
| 33 | +def depart_widget_container( |
| 34 | + translator: HTML5Translator, |
| 35 | + node: widget_container, |
| 36 | +) -> None: |
| 37 | + """Close the widget wrapper div.""" |
| 38 | + translator.body.append("</div>") |
| 39 | + |
| 40 | + |
| 41 | +ASSET_FILES: tuple[str, ...] = ("widget.html", "widget.js", "widget.css") |
| 42 | + |
| 43 | + |
| 44 | +class BaseWidget(abc.ABC): |
| 45 | + """Base class every concrete widget subclasses. |
| 46 | +
|
| 47 | + Subclasses declare ``name`` plus optional ``option_spec`` / ``default_options`` |
| 48 | + and may override ``context(env)`` to feed data into the Jinja template. |
| 49 | + Assets (``widget.html``, ``widget.js``, ``widget.css``) live at |
| 50 | + ``<srcdir>/_widgets/<name>/``; only ``widget.html`` is required. |
| 51 | + """ |
| 52 | + |
| 53 | + name: t.ClassVar[str] |
| 54 | + option_spec: t.ClassVar[ |
| 55 | + collections.abc.Mapping[str, collections.abc.Callable[[str], t.Any]] |
| 56 | + ] = {} |
| 57 | + default_options: t.ClassVar[collections.abc.Mapping[str, t.Any]] = {} |
| 58 | + |
| 59 | + @classmethod |
| 60 | + def assets_dir(cls, srcdir: pathlib.Path) -> pathlib.Path: |
| 61 | + return srcdir / "_widgets" / cls.name |
| 62 | + |
| 63 | + @classmethod |
| 64 | + def template_path(cls, srcdir: pathlib.Path) -> pathlib.Path: |
| 65 | + return cls.assets_dir(srcdir) / "widget.html" |
| 66 | + |
| 67 | + @classmethod |
| 68 | + def has_asset(cls, srcdir: pathlib.Path, filename: str) -> bool: |
| 69 | + return (cls.assets_dir(srcdir) / filename).is_file() |
| 70 | + |
| 71 | + @classmethod |
| 72 | + def context(cls, env: BuildEnvironment) -> collections.abc.Mapping[str, t.Any]: |
| 73 | + """Return extra Jinja context. Override in subclasses for widget data.""" |
| 74 | + return {} |
| 75 | + |
| 76 | + @classmethod |
| 77 | + def render( |
| 78 | + cls, |
| 79 | + *, |
| 80 | + options: collections.abc.Mapping[str, t.Any], |
| 81 | + env: BuildEnvironment, |
| 82 | + ) -> str: |
| 83 | + """Render the Jinja template with merged context, return HTML.""" |
| 84 | + template_path = cls.template_path(pathlib.Path(env.srcdir)) |
| 85 | + source = template_path.read_text(encoding="utf-8") |
| 86 | + jenv = jinja2.Environment( |
| 87 | + undefined=jinja2.StrictUndefined, |
| 88 | + autoescape=jinja2.select_autoescape(["html"]), |
| 89 | + keep_trailing_newline=False, |
| 90 | + trim_blocks=True, |
| 91 | + lstrip_blocks=True, |
| 92 | + ) |
| 93 | + template = jenv.from_string(source) |
| 94 | + context: dict[str, t.Any] = { |
| 95 | + **cls.default_options, |
| 96 | + **options, |
| 97 | + **cls.context(env), |
| 98 | + "widget_name": cls.name, |
| 99 | + } |
| 100 | + return template.render(**context) |
0 commit comments