Skip to content

Commit

Permalink
some edits
Browse files Browse the repository at this point in the history
  • Loading branch information
AakashGfude committed Apr 28, 2021
1 parent cf817ed commit 1e9430d
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 17 deletions.
90 changes: 81 additions & 9 deletions quantecon_book_theme/__init__.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,29 @@
"""A lightweight book theme based on the pydata sphinx theme."""
from pathlib import Path

try:
import importlib.resources as resources
except ImportError:
# python < 3.7
import importlib_resources as resources

from docutils.parsers.rst import directives
from docutils import nodes
from sphinx.util import logging
from sphinx.util.fileutil import copy_asset
from sphinx.util.osutil import ensuredir
from bs4 import BeautifulSoup as bs
from sass import compile as sass_compile
import os

from . import static as theme_static
from .launch import add_hub_urls

__version__ = "0.1.5"
"""quantecon-book-theme version"""

SPHINX_LOGGER = logging.getLogger(__name__)
MESSAGE_CATALOG_NAME = "booktheme"


def get_html_theme_path():
Expand All @@ -22,7 +32,54 @@ def get_html_theme_path():
return theme_path


def add_static_paths(app):
"""Ensure CSS/JS is loaded."""
app.env.book_theme_resources_changed = False

output_static_folder = Path(app.outdir) / "_static"
theme_static_files = resources.contents(theme_static)

if (
app.config.html_theme_options.get("theme_dev_mode", False)
and output_static_folder.exists()
):
# during development, the JS/CSS may change, if this is the case,
# we want to remove the old files and ensure that the new files are loaded
for path in output_static_folder.glob("quantecon-book-theme*"):
if path.name not in theme_static_files:
app.env.book_theme_resources_changed = True
path.unlink()
# note sphinx treats theme css different to regular css
# (it is specified in theme.conf), so we don't directly use app.add_css_file
for fname in resources.contents(theme_static):
if fname.endswith(".css"):
if not (output_static_folder / fname).exists():
(output_static_folder / fname).write_bytes(
resources.read_binary(theme_static, fname)
)
app.env.book_theme_resources_changed = True

# add javascript
for fname in resources.contents(theme_static):
if fname.endswith(".js"):
app.add_js_file(fname)


def update_all(app, env):
"""During development, if CSS/JS has changed, all files should be re-written,
to load the correct resources.
"""
if (
app.config.html_theme_options.get("theme_dev_mode", False)
and env.book_theme_resources_changed
):
return list(env.all_docs.keys())


def add_static_path(app):
"""Ensure CSS/JS is loaded."""
app.env.book_theme_resources_changed = False

static_path = Path(__file__).parent.joinpath("static").absolute()
app.config.html_static_path.append(str(static_path))

Expand Down Expand Up @@ -67,10 +124,13 @@ def find_url_relative_to_root(pagename, relative_page, path_docs_source):

def add_to_context(app, pagename, templatename, context, doctree):
def generate_nav_html(
level=1,
include_item_names=False,
startdepth=1,
kind="sidebar",
maxdepth=4,
collapse=False,
includehidden=True,
titles_only=True,
with_home_page=False,
prev_section_numbers=None,
):
# Config stuff
config = app.env.config
Expand All @@ -94,12 +154,17 @@ def generate_nav_html(
master_doctree = app.env.get_doctree(master_doc)
master_url = context["pathto"](master_doc)
master_title = list(master_doctree.traverse(nodes.title))[0].astext()

if len(master_title) == 0:
raise ValueError(f"Landing page missing a title: {master_doc}")
master_title = master_title[0].astext()
li_class = "toctree-l1"
if context["pagename"] == master_doc:
li_class += " current"
# Insert it into our toctree
ul_home = bs(
f"""
<ul>
<li class="toctree-l1">
<ul class="nav bd-sidenav">
<li class="{li_class}">
<a href="{master_url}" class="reference internal">{master_title}</a>
</li>
</ul>""",
Expand Down Expand Up @@ -327,15 +392,22 @@ def run(self):


def setup(app):
app.connect("env-before-read-docs", update_thebe_config)

# Configuration for Juypter Book
app.connect("html-page-context", add_hub_urls)
app.connect("env-updated", update_all)

app.connect("builder-inited", add_static_path)
# add translations
package_dir = os.path.abspath(os.path.dirname(__file__))
locale_dir = os.path.join(package_dir, "translations", "locales")
app.add_message_catalog(MESSAGE_CATALOG_NAME, locale_dir)

app.add_html_theme("quantecon_book_theme", get_html_theme_path())
app.connect("html-page-context", add_to_context)

app.add_js_file("quantecon-book-theme.js")
app.add_directive("margin", Margin, override=True)

return {
"parallel_read_safe": True,
"parallel_write_safe": True,
}
8 changes: 5 additions & 3 deletions quantecon_book_theme/layout.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{%- extends "basic/layout.html" %}
{%- extends "pydata_sphinx_theme/layout.html" %}

{% block extrahead %}

Expand Down Expand Up @@ -156,7 +156,7 @@
</div>

<nav class="sidebar__nav" id="sidebar-nav" aria-label="Main navigation">
{{ generate_nav_html(include_item_names=True, with_home_page=theme_home_page_in_toc) }}
{{ generate_nav_html(include_item_names=True, with_home_page=theme_home_page_in_toc, kind="sidebar") }}
</nav>

<div class="sidebar__footer">
Expand Down Expand Up @@ -217,7 +217,9 @@
feather.replace()
tippy('[data-tippy-content]');
</script>

<script type="text/javascript" id="MathJax-script" async
src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js">
</script>
{% if theme_google_analytics_id %}
<script>
window.ga = function () {
Expand Down
11 changes: 6 additions & 5 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,23 +27,24 @@
"click",
"setuptools",
"libsass",
"pydata-sphinx-theme~=0.4.1",
"beautifulsoup4",
"pydata-sphinx-theme~=0.6.0",
"beautifulsoup4>=4.6.1,<5",
'importlib-resources>=3.0,<3.5; python_version < "3.7"',
],
extras_require={
"code_style": ["flake8<3.8.0,>=3.7.0", "black", "pre-commit==1.17.0"],
"code_style": ["flake8<3.8.0,>=3.7.0", "black", "pre-commit~=2.7.0"],
"sphinx": [
"folium",
"numpy",
"matplotlib",
"ipywidgets",
"pandas",
"nbclient",
"myst-nb~=0.10.1",
"myst-nb~=0.11.1",
"sphinx-togglebutton>=0.2.1",
"sphinx-copybutton",
"plotly",
"sphinxcontrib-bibtex",
"sphinxcontrib-bibtex~=2.2",
"sphinx-thebe",
],
"testing": [
Expand Down

0 comments on commit 1e9430d

Please sign in to comment.