| 1 |
"""Bootstrap-based sphinx theme from the PyData community.""" |
| 2 |
|
| 3 |
import json |
| 4 |
|
| 5 |
from functools import partial |
| 6 |
from pathlib import Path |
| 7 |
from typing import Dict |
| 8 |
from urllib.parse import urlparse |
| 9 |
|
| 10 |
import requests |
| 11 |
|
| 12 |
from requests.exceptions import ConnectionError, HTTPError, RetryError |
| 13 |
from sphinx.application import Sphinx |
| 14 |
from sphinx.builders.dirhtml import DirectoryHTMLBuilder |
| 15 |
from sphinx.errors import ExtensionError |
| 16 |
|
| 17 |
from . import edit_this_page, logo, pygments, short_link, toctree, translator, utils |
| 18 |
|
| 19 |
|
| 20 |
__version__ = "0.17.1" |
| 21 |
|
| 22 |
|
| 23 |
def update_config(app): |
| 24 |
"""Update config with new default values and handle deprecated keys.""" |
| 25 |
# By the time `builder-inited` happens, `app.builder.theme_options` already exists. |
| 26 |
# At this point, modifying app.config.html_theme_options will NOT update the |
| 27 |
# page's HTML context (e.g. in jinja, `theme_keyword`). |
| 28 |
# To do this, you must manually modify `app.builder.theme_options`. |
| 29 |
theme_options = utils.get_theme_options_dict(app) |
| 30 |
warning = partial(utils.maybe_warn, app) |
| 31 |
|
| 32 |
# TODO: DEPRECATE after v1.0 |
| 33 |
themes = ["light", "dark"] |
| 34 |
for theme in themes: |
| 35 |
if style := theme_options.get(f"pygment_{theme}_style"): |
| 36 |
theme_options[f"pygments_{theme}_style"] = style |
| 37 |
warning( |
| 38 |
f'The parameter "pygment_{theme}_style" was renamed to ' |
| 39 |
f'"pygments_{theme}_style" (note the "s" on "pygments").' |
| 40 |
) |
| 41 |
|
| 42 |
# Validate icon links |
| 43 |
if not isinstance(theme_options.get("icon_links", []), list): |
| 44 |
raise ExtensionError( |
| 45 |
"`icon_links` must be a list of dictionaries, you provided " |
| 46 |
f"type {type(theme_options.get('icon_links'))}." |
| 47 |
"If you wish to disable this feature, either do not provide " |
| 48 |
"a value (leave undefined), or set to an empty list." |
| 49 |
) |
| 50 |
|
| 51 |
# If the user hasn't explicitly set navbar_persistent, default it based on |
| 52 |
# disable_search: show the search button field unless search is disabled. |
| 53 |
if "navbar_persistent" not in theme_options: |
| 54 |
if theme_options.get("disable_search", False): |
| 55 |
navbar_persistent = [] |
| 56 |
else: |
| 57 |
navbar_persistent = ["search-button-field"] |
| 58 |
theme_options["navbar_persistent"] = navbar_persistent |
| 59 |
|
| 60 |
# Set the anchor link default to be # if the user hasn't provided their own |
| 61 |
if not utils.config_provided_by_user(app, "html_permalinks_icon"): |
| 62 |
app.config.html_permalinks_icon = "#" |
| 63 |
|
| 64 |
# check the validity of the theme switcher file |
| 65 |
is_dict = isinstance(theme_options.get("switcher"), dict) |
| 66 |
should_test = theme_options.get("check_switcher", True) |
| 67 |
if is_dict and should_test: |
| 68 |
theme_switcher = theme_options.get("switcher") |
| 69 |
|
| 70 |
# raise an error if one of these compulsory keys is missing |
| 71 |
json_url = theme_switcher["json_url"] |
| 72 |
theme_switcher["version_match"] |
| 73 |
|
| 74 |
# try to read the json file. If it's a url we use request, |
| 75 |
# else we simply read the local file from the source directory |
| 76 |
# display a log warning if the file cannot be reached |
| 77 |
reading_error = None |
| 78 |
if urlparse(json_url).scheme in ["http", "https"]: |
| 79 |
try: |
| 80 |
request = requests.get(json_url) |
| 81 |
request.raise_for_status() |
| 82 |
content = request.text |
| 83 |
except (ConnectionError, HTTPError, RetryError) as e: |
| 84 |
reading_error = repr(e) |
| 85 |
else: |
| 86 |
try: |
| 87 |
content = Path(app.srcdir, json_url).read_text() |
| 88 |
except FileNotFoundError as e: |
| 89 |
reading_error = repr(e) |
| 90 |
|
| 91 |
if reading_error is not None: |
| 92 |
warning( |
| 93 |
f'The version switcher "{json_url}" file cannot be read due to ' |
| 94 |
f"the following error:\n{reading_error}" |
| 95 |
) |
| 96 |
else: |
| 97 |
# check that the json file is not illformed, |
| 98 |
# throw a warning if the file is ill formed and an error if it's not json |
| 99 |
switcher_content = json.loads(content) |
| 100 |
missing_url = any(["url" not in e for e in switcher_content]) |
| 101 |
missing_version = any(["version" not in e for e in switcher_content]) |
| 102 |
if missing_url or missing_version: |
| 103 |
warning( |
| 104 |
f'The version switcher "{json_url}" file is malformed; ' |
| 105 |
'at least one of the items is missing the "url" or "version" key' |
| 106 |
) |
| 107 |
|
| 108 |
# Add an analytics ID to the site if provided |
| 109 |
analytics = theme_options.get("analytics", {}) |
| 110 |
if analytics: |
| 111 |
# Plausible analytics |
| 112 |
plausible_domain = analytics.get("plausible_analytics_domain") |
| 113 |
plausible_url = analytics.get("plausible_analytics_url") |
| 114 |
|
| 115 |
# Ref: https://plausible.io/docs/plausible-script |
| 116 |
if plausible_domain and plausible_url: |
| 117 |
kwargs = { |
| 118 |
"loading_method": "defer", |
| 119 |
"data-domain": plausible_domain, |
| 120 |
"filename": plausible_url, |
| 121 |
} |
| 122 |
app.add_js_file(**kwargs) |
| 123 |
|
| 124 |
# Google Analytics |
| 125 |
gid = analytics.get("google_analytics_id") |
| 126 |
if gid: |
| 127 |
gid_js_path = f"https://www.googletagmanager.com/gtag/js?id={gid}" |
| 128 |
gid_script = f""" |
| 129 |
window.dataLayer = window.dataLayer || []; |
| 130 |
function gtag(){{ dataLayer.push(arguments); }} |
| 131 |
gtag('consent', 'default', {{ |
| 132 |
'ad_storage': 'denied', |
| 133 |
'ad_user_data': 'denied', |
| 134 |
'ad_personalization': 'denied', |
| 135 |
'analytics_storage': 'denied' |
| 136 |
}}); |
| 137 |
gtag('js', new Date()); |
| 138 |
gtag('config', '{gid}'); |
| 139 |
""" |
| 140 |
|
| 141 |
# Link the JS files |
| 142 |
app.add_js_file(gid_js_path, loading_method="async") |
| 143 |
app.add_js_file(None, body=gid_script) |
| 144 |
|
| 145 |
# Update ABlog configuration default if present |
| 146 |
fa_provided = utils.config_provided_by_user(app, "fontawesome_included") |
| 147 |
if "ablog" in app.config.extensions and not fa_provided: |
| 148 |
app.config.fontawesome_included = True |
| 149 |
|
| 150 |
# Handle icon link shortcuts |
| 151 |
shortcuts = [ |
| 152 |
("twitter_url", "fa-brands fa-square-twitter", "Twitter"), |
| 153 |
("bitbucket_url", "fa-brands fa-bitbucket", "Bitbucket"), |
| 154 |
("gitlab_url", "fa-brands fa-square-gitlab", "GitLab"), |
| 155 |
("github_url", "fa-brands fa-square-github", "GitHub"), |
| 156 |
] |
| 157 |
# Add extra icon links entries if there were shortcuts present |
| 158 |
# TODO: Deprecate this at some point in the future? |
| 159 |
icon_links = theme_options.get("icon_links", []) |
| 160 |
for url, icon, name in shortcuts: |
| 161 |
if theme_options.get(url): |
| 162 |
# This defaults to an empty list so we can always insert |
| 163 |
icon_links.insert( |
| 164 |
0, |
| 165 |
{ |
| 166 |
"url": theme_options.get(url), |
| 167 |
"icon": icon, |
| 168 |
"name": name, |
| 169 |
"type": "fontawesome", |
| 170 |
}, |
| 171 |
) |
| 172 |
theme_options["icon_links"] = icon_links |
| 173 |
|
| 174 |
# Prepare the logo config dictionary |
| 175 |
theme_logo = theme_options.get("logo") |
| 176 |
if not theme_logo: |
| 177 |
# In case theme_logo is an empty string |
| 178 |
theme_logo = {} |
| 179 |
if not isinstance(theme_logo, dict): |
| 180 |
raise ValueError(f"Incorrect logo config type: {type(theme_logo)}") |
| 181 |
theme_logo_link = theme_options.get("theme_logo_link") |
| 182 |
if theme_logo_link: |
| 183 |
theme_logo["link"] = theme_logo_link |
| 184 |
theme_options["logo"] = theme_logo |
| 185 |
|
| 186 |
|
| 187 |
def update_and_remove_templates( |
| 188 |
app: Sphinx, pagename: str, templatename: str, context, doctree |
| 189 |
) -> None: |
| 190 |
"""Update template names and assets for page build.""" |
| 191 |
# Allow for more flexibility in template names |
| 192 |
template_sections = [ |
| 193 |
"theme_navbar_start", |
| 194 |
"theme_navbar_center", |
| 195 |
"theme_navbar_persistent", |
| 196 |
"theme_navbar_end", |
| 197 |
"theme_article_header_start", |
| 198 |
"theme_article_header_end", |
| 199 |
"theme_article_footer_items", |
| 200 |
"theme_content_footer_items", |
| 201 |
"theme_footer_start", |
| 202 |
"theme_footer_center", |
| 203 |
"theme_footer_end", |
| 204 |
"theme_primary_sidebar_end", |
| 205 |
"sidebars", |
| 206 |
] |
| 207 |
for section in template_sections: |
| 208 |
if context.get(section): |
| 209 |
context[section] = utils._update_and_remove_templates( |
| 210 |
app=app, |
| 211 |
context=context, |
| 212 |
templates=context.get(section, []), |
| 213 |
section=section, |
| 214 |
templates_skip_empty_check=["sidebar-nav-bs.html", "navbar-nav.html"], |
| 215 |
) |
| 216 |
|
| 217 |
# Remove a duplicate entry of the theme CSS. This is because it is in both: |
| 218 |
# - theme.conf |
| 219 |
# - manually linked in `webpack-macros.html` |
| 220 |
if "css_files" in context: |
| 221 |
theme_css_name = "_static/styles/pydata-sphinx-theme.css" |
| 222 |
for i in range(len(context["css_files"])): |
| 223 |
asset = context["css_files"][i] |
| 224 |
# TODO: eventually the contents of context['css_files'] etc should probably |
| 225 |
# only be _CascadingStyleSheet etc. For now, assume mixed with strings. |
| 226 |
asset_path = getattr(asset, "filename", str(asset)) |
| 227 |
if asset_path == theme_css_name: |
| 228 |
del context["css_files"][i] |
| 229 |
break |
| 230 |
# Add links for favicons in the topbar |
| 231 |
for favicon in context.get("theme_favicons", []): |
| 232 |
icon_type = Path(favicon["href"]).suffix.strip(".") |
| 233 |
opts = { |
| 234 |
"rel": favicon.get("rel", "icon"), |
| 235 |
"sizes": favicon.get("sizes", "16x16"), |
| 236 |
"type": f"image/{icon_type}", |
| 237 |
} |
| 238 |
if "color" in favicon: |
| 239 |
opts["color"] = favicon["color"] |
| 240 |
# Sphinx will auto-resolve href if it's a local file |
| 241 |
app.add_css_file(favicon["href"], **opts) |
| 242 |
|
| 243 |
# Add metadata to DOCUMENTATION_OPTIONS so that we can re-use later |
| 244 |
# Pagename to current page |
| 245 |
app.add_js_file(None, body=f"DOCUMENTATION_OPTIONS.pagename = '{pagename}';") |
| 246 |
if isinstance(context.get("theme_switcher"), dict): |
| 247 |
theme_switcher = context["theme_switcher"] |
| 248 |
json_url = theme_switcher["json_url"] |
| 249 |
version_match = theme_switcher["version_match"] |
| 250 |
|
| 251 |
# Add variables to our JavaScript for re-use in our main JS script |
| 252 |
js = f""" |
| 253 |
DOCUMENTATION_OPTIONS.theme_version = '{__version__}'; |
| 254 |
DOCUMENTATION_OPTIONS.theme_switcher_json_url = '{json_url}'; |
| 255 |
DOCUMENTATION_OPTIONS.theme_switcher_version_match = '{version_match}'; |
| 256 |
DOCUMENTATION_OPTIONS.show_version_warning_banner = |
| 257 |
{str(context["theme_show_version_warning_banner"]).lower()}; |
| 258 |
""" |
| 259 |
app.add_js_file(None, body=js) |
| 260 |
|
| 261 |
# Specify whether search-as-you-type should be used or not. |
| 262 |
search_as_you_type = str(context["theme_search_as_you_type"]).lower() |
| 263 |
app.add_js_file( |
| 264 |
None, body=f"DOCUMENTATION_OPTIONS.search_as_you_type = {search_as_you_type};" |
| 265 |
) |
| 266 |
|
| 267 |
# Update version number for the "made with version..." component |
| 268 |
context["theme_version"] = __version__ |
| 269 |
|
| 270 |
|
| 271 |
def _fix_canonical_url( |
| 272 |
app: Sphinx, pagename: str, templatename: str, context: dict, doctree |
| 273 |
) -> None: |
| 274 |
"""Fix the canonical URL when using the dirhtml builder. |
| 275 |
|
| 276 |
Sphinx builds a canonical URL if ``html_baseurl`` config is set. However, |
| 277 |
it builds a URL ending with ".html" when using the dirhtml builder, which is |
| 278 |
incorrect. Detect this and generate the correct URL for each page. |
| 279 |
|
| 280 |
Workaround for https://github.com/sphinx-doc/sphinx/issues/9730; can be removed |
| 281 |
when that is fixed, released, and available in our minimum supported Sphinx version. |
| 282 |
""" |
| 283 |
if ( |
| 284 |
not app.config.html_baseurl |
| 285 |
or not isinstance(app.builder, DirectoryHTMLBuilder) |
| 286 |
or not context["pageurl"] |
| 287 |
or not context["pageurl"].endswith(".html") |
| 288 |
): |
| 289 |
return |
| 290 |
|
| 291 |
target = app.builder.get_target_uri(pagename) |
| 292 |
context["pageurl"] = app.config.html_baseurl + target |
| 293 |
|
| 294 |
|
| 295 |
def add_shorten_xform(app: Sphinx) -> None: |
| 296 |
"""Add the link shortening transform.""" |
| 297 |
theme_options = utils.get_theme_options_dict(app) |
| 298 |
theme_conf_options = app.builder.theme.get_options() |
| 299 |
if (theme_conf_options | theme_options).get("shorten_urls"): |
| 300 |
app.add_post_transform(short_link.ShortenLinkTransform) |
| 301 |
|
| 302 |
|
| 303 |
def setup(app: Sphinx) -> Dict[str, str]: |
| 304 |
"""Setup the Sphinx application.""" |
| 305 |
here = Path(__file__).parent.resolve() |
| 306 |
theme_path = here / "theme" / "pydata_sphinx_theme" |
| 307 |
app.add_html_theme("pydata_sphinx_theme", str(theme_path)) |
| 308 |
|
| 309 |
app.connect("builder-inited", add_shorten_xform) |
| 310 |
app.connect("builder-inited", translator.setup_translators) |
| 311 |
app.connect("builder-inited", update_config) |
| 312 |
app.connect("html-page-context", _fix_canonical_url) |
| 313 |
app.connect("html-page-context", edit_this_page.setup_edit_url) |
| 314 |
app.connect("html-page-context", toctree.add_toctree_functions) |
| 315 |
app.connect("html-page-context", update_and_remove_templates) |
| 316 |
app.connect("html-page-context", logo.setup_logo_path) |
| 317 |
app.connect("html-page-context", utils.set_secondary_sidebar_items) |
| 318 |
app.connect("build-finished", pygments.overwrite_pygments_css) |
| 319 |
app.connect("build-finished", logo.copy_logo_images) |
| 320 |
|
| 321 |
# https://www.sphinx-doc.org/en/master/extdev/i18n.html#extension-internationalization-i18n-and-localization-l10n-using-i18n-api |
| 322 |
app.add_message_catalog("sphinx", here / "locale") |
| 323 |
|
| 324 |
# Include component templates |
| 325 |
app.config.templates_path.append(str(theme_path / "components")) |
| 326 |
|
| 327 |
return {"parallel_read_safe": True, "parallel_write_safe": True} |