Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH/MAINT: avoid overwriting the HtmlTranslator #1024

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 60 additions & 9 deletions src/pydata_sphinx_theme/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
from docutils import nodes
from sphinx import addnodes
from sphinx.environment.adapters.toctree import TocTree

# from sphinx.ext.autosummary import autosummary_table
from sphinx.addnodes import toctree as toctree_node
from sphinx.transforms.post_transforms import SphinxPostTransform
from sphinx.util.nodes import NodeMatcher
Expand All @@ -21,7 +23,7 @@
from pygments.styles import get_all_styles
import requests

from .bootstrap_html_translator import BootstrapHTML5Translator
# from .bootstrap_html_translator import BootstrapHTML5Translator

__version__ = "0.11.1rc1.dev0"

Expand Down Expand Up @@ -875,7 +877,7 @@ def _overwrite_pygments_css(app, exception=None):


# ------------------------------------------------------------------------------
# customize rendering of the links
# customize rendering of the html elements
# ------------------------------------------------------------------------------


Expand Down Expand Up @@ -960,6 +962,60 @@ def parse_url(self, path):
return text


class BSTableTransform(SphinxPostTransform):
"""
Update the table nodes to remove "docutils" class and replace "align-xxx" by "table-xxx"
Add the "table" class to fit bootsrap
"""

default_priority = 400
formats = ("html",)

def run(self, **kwargs):
matcher = NodeMatcher(nodes.table)
# TODO: just use "findall" once docutils min version >=0.18.1
for node in _traverse_or_findall(self.document, matcher):

# extract the classes as a list
classes = node.attributes["classes"]
classes = classes if len(classes) == 0 else classes[0].split(" ")

# remove docutils
"docutils" not in classes or classes.remove("docutils")

# add the table class
classes.append("table")

# we're looking at the 'real_table', which is wrapped by an autosummary
# it seems it's already done
# if isinstance(node.parent, autosummary_table):
# classes.append("autosummary")

# add specific class if align is set
if "align" in node:
classes.append(f'table-{node["align"]}')

node.attributes["classes"] = [" ".join(classes)]


class HeaderTransform(SphinxPostTransform):
"""
ensure an aria-level is set for any heading role
"""

default_priority = 400
formats = ("html",)

def run(self, **kwargs):
matcher = NodeMatcher(nodes.title)
# TODO: just use "findall" once docutils min version >=0.18.1
for node in _traverse_or_findall(self.document, matcher):
if isinstance(node.parent, addnodes.compact_paragraph) and node.parent.get(
"toctree"
):
pass


# -----------------------------------------------------------------------------


Expand All @@ -970,13 +1026,8 @@ def setup(app):
app.add_html_theme("pydata_sphinx_theme", str(theme_path))

app.add_post_transform(ShortenLinkTransform)

app.set_translator("html", BootstrapHTML5Translator)
# Read the Docs uses ``readthedocs`` as the name of the build, and also
# uses a special "dirhtml" builder so we need to replace these both with
# our custom HTML builder
app.set_translator("readthedocs", BootstrapHTML5Translator, override=True)
app.set_translator("readthedocsdirhtml", BootstrapHTML5Translator, override=True)
app.add_post_transform(BSTableTransform)
# app.add_post_transform(HeaderTransform)

app.connect("env-updated", update_config)
app.connect("html-page-context", setup_edit_url)
Expand Down
44 changes: 0 additions & 44 deletions src/pydata_sphinx_theme/bootstrap_html_translator.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
"""A custom Sphinx HTML Translator for Bootstrap layout
"""
from packaging.version import Version

import sphinx
from sphinx.writers.html5 import HTML5Translator
from sphinx.util import logging
from sphinx.ext.autosummary import autosummary_table

logger = logging.getLogger(__name__)

Expand All @@ -17,48 +13,8 @@ class BootstrapHTML5Translator(HTML5Translator):
directly styled with Bootstrap, and fulfill acessibility best practices.
"""

def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
self.settings.table_style = "table"

def starttag(self, *args, **kwargs):
"""ensure an aria-level is set for any heading role"""
if kwargs.get("ROLE") == "heading" and "ARIA-LEVEL" not in kwargs:
kwargs["ARIA-LEVEL"] = "2"
return super().starttag(*args, **kwargs)

def visit_table(self, node):
"""
copy of sphinx source to *not* add 'docutils' and 'align-default' classes
but add 'table' class
"""

# init the attributes
atts = {}

# generate_targets_for_table is deprecated in 4.0
if Version(sphinx.__version__) < Version("4.0"):
self.generate_targets_for_table(node)

if Version(sphinx.__version__) < Version("4.3"):
self._table_row_index = 0
else:
self._table_row_indices.append(0)

# get the classes
classes = [cls.strip(" \t\n") for cls in self.settings.table_style.split(",")]

# we're looking at the 'real_table', which is wrapped by an autosummary
if isinstance(node.parent, autosummary_table):
classes += ["autosummary"]

# add the width if set in a style attribute
if "width" in node:
atts["style"] = f'width: {node["width"]}'

# add specific class if align is set
if "align" in node:
classes.append(f'table-{node["align"]}')

tag = self.starttag(node, "table", CLASS=" ".join(classes), **atts)
self.body.append(tag)