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

MAINT: Update CSS for external packages and remove redundant code #478

Merged
merged 13 commits into from
Feb 9, 2022
Merged
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
6 changes: 3 additions & 3 deletions .github/workflows/lighthouserc.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
},
"assert": {
"assertions": {
"categories:performance": ["error", { "minScore": 0.7 }],
"categories:accessibility": ["error", { "minScore": 0.7 }],
"categories:best-practices": ["error", { "minScore": 0.7 }]
"categories:performance": ["error", { "minScore": 0.85 }],
"categories:accessibility": ["error", { "minScore": 0.85 }],
"categories:best-practices": ["error", { "minScore": 0.85 }]
}
}
}
Expand Down
8 changes: 8 additions & 0 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,11 @@ Much of these tests also use `pytest-regressions`, to check whether newly-genera
## `.github/workflows/` - Continuous Integration and Deployment

Contains Continuous-integration (CI) workflows, run on commits/PRs to the GitHub repository.

## Parent theme - `pydata-sphinx-theme`

This theme inherits a lot of functionality and design rules from its parent theme, the [PyData Sphinx Theme](https://github.com/pydata/pydata-sphinx-theme).
This is a theme designed for the PyData community, with a similar look and feel to the book theme.
Over time, we try to upstream any improvements made here into the parent theme, as long as the look and feel is the same between the two.

If you come across something in the codebase and you're not sure where it comes from (an example is the `generate_nav_html` function), you should [check the PyData Theme source files](https://github.com/pydata/pydata-sphinx-theme/tree/master/src/pydata_sphinx_theme) to see if it is defined there.
9 changes: 4 additions & 5 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,18 +118,17 @@
"use_download_button": True,
"logo_only": True,
"show_toc_level": 2,
"announcement": (
"⚠️The latest release refactored our HTML, "
"so double-check your custom CSS rules!⚠️"
),
# For testing
# "use_fullscreen_button": False,
# "home_page_in_toc": True,
# "single_page": True,
# "extra_footer": "<a href='https://google.com'>Test</a>", # DEPRECATED KEY
# "extra_navbar": "<a href='https://google.com'>Test</a>",
# "show_navbar_depth": 2,
"announcement": (
"⚠️The latest release refactored our HTML, "
"so double-check your custom CSS rules!⚠️"
),
"show_toc_level": 2,
}

# -- ABlog config -------------------------------------------------
Expand Down
52 changes: 52 additions & 0 deletions docs/contributing/tests.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,55 @@ To preview the output of these tests:
- Scroll to the "Audit with Lighthouse" section
- If there are errors, you should see them along with the link to preview the report at `report: <URL TO PAGE>`.
- If there are not errors, you can list them by clicking the `uploading` section, which will reveal links to the report for each page


## Test multiple Sphinx versions

This theme is tested against the latest two major versions of Sphinx.
We try to set up our regression tests such that there are no differences between these two Sphinx versions.

### Unit tests

Use the variable `sphinx_build.software_versions` to conditionally run tests based on the version of Sphinx.

For example:

```python
if sphinx_build.software_versions == ".sphinx3":
foo
elif sphinx_build.software_versions == ".sphinx4":
bar
```

### Regression tests

Regression tests are trickier, because updating them generally requires re-running the tests, not hand-editing code.
This is cumbersome for maintenance because we have to run the test suite two times for each regression that is updated.
For this reason, we have a more lightweight approach:

**If a regression test differs between Sphinx versions**, decide if the difference is substantial.
Do we gain something meaningful by testing both major versions of Sphinx, or is the difference unrelated to our theme's functionality?

1. **If not substantial**, then add a conditional and only run the regression test on the latest Sphinx version we support.
Add a note to explain why you're only testing against one version of Sphinx.

For example:

```python
if sphinx_build.software_versions == ".sphinx4":
# Only Sphinx4 because Sphinx3 adds an extra whitespace and isn't important
file_regression.check(...)
```
2. **If it is substantial**, follow these steps:

To support multiple Sphinx versions with regression tests, use the `extension` key to create a different regression file for that version of Sphinx.
For example:

```python
file_regression.check(
html.prettify(),
basename="foo",
extension=f"{sphinx_build.software_versions}.html",
encoding="utf8",
)
```
66 changes: 57 additions & 9 deletions docs/reference/extensions.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,18 +38,66 @@ Here's a sample post list:

## `sphinx-togglebutton` - Toggle content with buttons

An admonition toggle:
A block toggle:

## `sphinx-tabs` - Tabbed content
```{toggle}

::::{tabs}
:::{tab} Apples
Some apples.
:::{note} This note is toggled!
:::
:::{tab} Oranges
Some oranges.

```

A block toggle in the margin:

::::{container} margin

```{toggle}

:::{note} This note is toggled!
:::
:::{tab} Pears
Some pears.

```

::::

An admonition toggle:

:::{note}
:class: dropdown

This note will be toggled!

:::

An admonition toggle in the margin

::::{note}
:class: margin

:::{toggle}

This toggle is in the margin!

:::

::::

## `sphinx-tabs` - Tabbed content

% For some reason sphinx-tabs doesn't work properly with myst markdown
% so using rST here.
````{eval-rst}
.. tabs::

.. tab:: Apples

Apples are green, or sometimes red.

.. tab:: Pears

Pears are green.

.. tab:: Oranges

Oranges are orange.
````
6 changes: 3 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ readme = "README.md"
requires-python = ">=3.7"
dependencies = [
"sphinx>=3,<5",
"beautifulsoup4>=4.6.1,<5",
"pydata-sphinx-theme~=0.7.2",
"pydata-sphinx-theme~=0.8.0",
"pyyaml",
]

Expand Down Expand Up @@ -63,11 +62,12 @@ doc = [
"sphinx-copybutton",
"sphinx_tabs",
"sphinx-togglebutton>=0.2.1",
"sphinx-thebe",
"sphinx-thebe>=0.1.1",
"sphinxcontrib-bibtex~=2.2",
"sphinxext-opengraph",
]
test = [
"beautifulsoup4>=4.6.1,<5",
"coverage",
"myst_nb~=0.13",
"pytest~=6.0.1",
Expand Down
89 changes: 11 additions & 78 deletions src/sphinx_book_theme/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import os
from pathlib import Path

from bs4 import BeautifulSoup as bs
from docutils.parsers.rst.directives.body import Sidebar
from docutils import nodes
from sphinx.application import Sphinx
Expand All @@ -27,65 +26,11 @@ def get_html_theme_path():

def add_to_context(app, pagename, templatename, context, doctree):

# TODO: remove this whenever the nav collapsing functionality is in the PST
def sbt_generate_nav_html(
level=1,
include_item_names=False,
with_home_page=False,
prev_section_numbers=None,
show_depth=1,
):
# Config stuff
config = app.env.config
if isinstance(with_home_page, str):
with_home_page = with_home_page.lower() == "true"

# Convert the pydata toctree html to beautifulsoup
toctree = context["generate_nav_html"](
startdepth=level - 1,
kind="sidebar",
maxdepth=4,
collapse=False,
includehidden=True,
titles_only=True,
)
toctree = bs(toctree, "html.parser")

# Add the master_doc page as the first item if specified
if with_home_page:
# Pull metadata about the master doc
master_doc = config["master_doc"]
master_doctree = app.env.get_doctree(master_doc)
master_url = context["pathto"](master_doc)
master_title = list(master_doctree.traverse(nodes.title))
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 class="nav bd-sidenav">
<li class="{li_class}">
<a href="{master_url}" class="reference internal">{master_title}</a>
</li>
</ul>""",
"html.parser",
)
toctree.insert(0, ul_home("ul")[0])

# Open the navbar to the proper depth
for ii in range(int(show_depth)):
for checkbox in toctree.select(
f"li.toctree-l{ii} > input.toctree-checkbox"
):
checkbox.attrs["checked"] = None

return toctree.prettify()

context["sbt_generate_nav_html"] = sbt_generate_nav_html
# Add the site title to our context so it can be inserted into the navbar
if not context.get("root_doc"):
# TODO: Sphinx renamed master to root in 4.x, deprecate when we drop 3.x
context["root_doc"] = context.get("master_doc")
context["root_title"] = app.env.titles[context["root_doc"]].astext()

# Update the page title because HTML makes it into the page title occasionally
if pagename in app.env.titles:
Expand Down Expand Up @@ -149,11 +94,11 @@ def sbt_generate_nav_html(
)


def update_thebe_config(app, env, docnames):
def update_thebe_config(app):
"""Update thebe configuration with SBT-specific values"""
theme_options = env.config.html_theme_options
theme_options = app.env.config.html_theme_options
if theme_options.get("launch_buttons", {}).get("thebe") is True:
if not hasattr(env.config, "thebe_config"):
if not hasattr(app.env.config, "thebe_config"):
SPHINX_LOGGER.warning(
(
"Thebe is activated but not added to extensions list. "
Expand All @@ -162,7 +107,7 @@ def update_thebe_config(app, env, docnames):
)
return
# Will be empty if it doesn't exist
thebe_config = env.config.thebe_config
thebe_config = app.env.config.thebe_config
else:
return

Expand All @@ -180,19 +125,7 @@ def update_thebe_config(app, env, docnames):
branch = "master"
thebe_config["repository_branch"] = branch

# Update the selectors to find thebe-enabled cells
selector = thebe_config.get("selector", "") + ",.cell"
thebe_config["selector"] = selector.lstrip(",")

selector_input = (
thebe_config.get("selector_input", "") + ",.cell_input div.highlight"
)
thebe_config["selector_input"] = selector_input.lstrip(",")

selector_output = thebe_config.get("selector_output", "") + ",.cell_output"
thebe_config["selector_output"] = selector_output.lstrip(",")

env.config.thebe_config = thebe_config
app.env.config.thebe_config = thebe_config


def _string_or_bool(var):
Expand Down Expand Up @@ -224,7 +157,7 @@ def run(self):


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

# Configuration for Juypter Book
app.connect("html-page-context", add_hub_urls)
Expand Down
24 changes: 16 additions & 8 deletions src/sphinx_book_theme/assets/scripts/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,27 @@ var sbRunWhenDOMLoaded = (cb) => {
};

// Toggle full-screen with button
// Safari requires a `webkit` prefix, so this uses conditionals to check for that
// ref: https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API
var toggleFullScreen = () => {
var navToggler = $("#navbar-toggler");
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen();
if (!navToggler.hasClass("collapsed")) {
navToggler.click();
var isInFullScreen =
(document.fullscreenElement && document.fullscreenElement !== null) ||
(document.webkitFullscreenElement &&
document.webkitFullscreenElement !== null);
let docElm = document.documentElement;
if (!isInFullScreen) {
console.log("[SBT]: Entering full screen");
if (docElm.requestFullscreen) {
docElm.requestFullscreen();
} else if (docElm.webkitRequestFullscreen) {
docElm.webkitRequestFullscreen();
}
} else {
console.log("[SBT]: Exiting full screen");
if (document.exitFullscreen) {
document.exitFullscreen();
if (navToggler.hasClass("collapsed")) {
navToggler.click();
}
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
}
};
Expand Down
6 changes: 3 additions & 3 deletions src/sphinx_book_theme/assets/styles/abstracts/_mixins.scss
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@
*********************************************/
// Scrollbar styles to be re-used in a few spots
@mixin scrollbar-style() {
scrollbar-width: thin;
&::-webkit-scrollbar {
width: 5px;
height: 5px;
width: 0.5em;
height: 0.5em;
}

&::-webkit-scrollbar {
Expand All @@ -15,6 +14,7 @@

&::-webkit-scrollbar-thumb {
background: #c1c1c1;
border-radius: 1em;

&:hover {
background: #a0a0a0;
Expand Down
Loading