pax_global_header00006660000000000000000000000064142642540350014517gustar00rootroot0000000000000052 comment=d6bbae620cc4d92220a260fca75da66ed71e4e72 sphinx-togglebutton-0.3.2/000077500000000000000000000000001426425403500155455ustar00rootroot00000000000000sphinx-togglebutton-0.3.2/.github/000077500000000000000000000000001426425403500171055ustar00rootroot00000000000000sphinx-togglebutton-0.3.2/.github/workflows/000077500000000000000000000000001426425403500211425ustar00rootroot00000000000000sphinx-togglebutton-0.3.2/.github/workflows/tests.yml000066400000000000000000000012261426425403500230300ustar00rootroot00000000000000name: continuous-integration on: [push, pull_request] jobs: publish: name: Publish to PyPi if: github.event_name == 'push' && startsWith(github.event.ref, 'refs/tags') runs-on: ubuntu-latest steps: - name: Checkout source uses: actions/checkout@v2 - name: Set up Python 3.8 uses: actions/setup-python@v1 with: python-version: "3.8" - name: Build package run: | pip install build python -m build - name: Publish uses: pypa/gh-action-pypi-publish@v1.1.0 with: user: __token__ password: ${{ secrets.PYPI_KEY }} sphinx-togglebutton-0.3.2/.gitignore000066400000000000000000000034071426425403500175410ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ pip-wheel-metadata/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # PEP 582; used by e.g. github.com/David-OConnor/pyflow __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ sphinx-togglebutton-0.3.2/CHANGELOG.md000066400000000000000000000066001426425403500173600ustar00rootroot00000000000000# Changelog ## v0.3.2 - 2022-07-15 ([full changelog](https://github.com/executablebooks/sphinx-togglebutton/compare/v0.3.1...347b1ad3a093afad0f0d4c0041249f09f39afab2)) ### Enhancements made - Toggle arrow now points to the right, in order to more closely match the styles of other common documentation themes like Quarto and Material for MkDocs [#49](https://github.com/executablebooks/sphinx-togglebutton/pull/49) ([@choldgraf](https://github.com/choldgraf)) - Toggle buttons are now more minimal and take up the full width to be easier to click, style is roughly inspired by JupyterLab [#47](https://github.com/executablebooks/sphinx-togglebutton/pull/47) ([@choldgraf](https://github.com/choldgraf)) ### Bugfixes - Fix insertion of toggle hint into nested spans [#45](https://github.com/executablebooks/sphinx-togglebutton/pull/45) ([@janssenhenning](https://github.com/janssenhenning)) ### Contributors to this release [@Apteryks](https://github.com/search?q=repo%3Aexecutablebooks%2Fsphinx-togglebutton+involves%3AApteryks+updated%3A2022-03-26..2022-07-15&type=Issues) | [@choldgraf](https://github.com/search?q=repo%3Aexecutablebooks%2Fsphinx-togglebutton+involves%3Acholdgraf+updated%3A2022-03-26..2022-07-15&type=Issues) | [@janssenhenning](https://github.com/search?q=repo%3Aexecutablebooks%2Fsphinx-togglebutton+involves%3Ajanssenhenning+updated%3A2022-03-26..2022-07-15&type=Issues) | [@tfiers](https://github.com/search?q=repo%3Aexecutablebooks%2Fsphinx-togglebutton+involves%3Atfiers+updated%3A2022-03-26..2022-07-15&type=Issues) | ## v0.3.1 This is release updates the behavior of the toggle button arrow for admonitions, to point down/up instead of down/right. See [#38](https://github.com/executablebooks/sphinx-togglebutton/issues/38) for details. ## v0.3.0 ([full changelog](https://github.com/executablebooks/sphinx-togglebutton/compare/v0.2.3...9e73e2e1a673d2485dd8c8d56510cdf910531f1a)) ### Enhancements made - ENH: Enhance toggle button design and layout [#32](https://github.com/executablebooks/sphinx-togglebutton/pull/32) ([@choldgraf](https://github.com/choldgraf)) - IMPROVE: Allow clicking on whole admonition title [#29](https://github.com/executablebooks/sphinx-togglebutton/pull/29) ([@rkdarst](https://github.com/rkdarst)) - ENHANCE: Improve hiding behavior for togglebuttons [#33](https://github.com/executablebooks/sphinx-togglebutton/pull/33) ([@choldgraf](https://github.com/choldgraf)) ## v0.2.2 ([full changelog](https://github.com/executablebooks/sphinx-togglebutton/compare/v0.2.0...v0.2.2)) ### Bugs fixed * 🐛 BUG: fixing toggle button text overlap on narrow screens [#17](https://github.com/executablebooks/sphinx-togglebutton/pull/17) ([@choldgraf](https://github.com/choldgraf)) * 🐛 BUG: Fixing overlapping title on hidden admonitions [#15](https://github.com/executablebooks/sphinx-togglebutton/pull/15) ([@choldgraf](https://github.com/choldgraf)) ### Documentation improvements * 📚 DOC: release docs and removing circle [#16](https://github.com/executablebooks/sphinx-togglebutton/pull/16) ([@choldgraf](https://github.com/choldgraf)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/executablebooks/sphinx-togglebutton/graphs/contributors?from=2020-06-09&to=2020-08-08&type=c)) [@choldgraf](https://github.com/search?q=repo%3Aexecutablebooks%2Fsphinx-togglebutton+involves%3Acholdgraf+updated%3A2020-06-09..2020-08-08&type=Issues)sphinx-togglebutton-0.3.2/LICENSE000066400000000000000000000020571426425403500165560ustar00rootroot00000000000000MIT License Copyright (c) 2018 Chris Holdgraf Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. sphinx-togglebutton-0.3.2/MANIFEST.in000066400000000000000000000000131426425403500172750ustar00rootroot00000000000000graft doc/ sphinx-togglebutton-0.3.2/README.md000066400000000000000000000031621426425403500170260ustar00rootroot00000000000000# sphinx-togglebutton A small sphinx extension to make it possible to add a "toggle button" to sections of your page. This allows you to: - Collapse Sphinx admonitions (notes, warnings, etc) so that their content is hidden until users click a toggle button. - Collapse arbitrary chunks of content on your page with a `collapse` directive. ![Demonstration of Sphinx Togglebutton](https://user-images.githubusercontent.com/1839645/152654312-a72a320f-e1e0-40be-95ae-3ed34facc4d3.gif) Installation ============ You can install `sphinx-togglebutton` with `pip`: ```bash pip install sphinx-togglebutton ``` Usage ===== In your `conf.py` configuration file, add `sphinx_togglebutton` to your extensions list. E.g.: ```python extensions = [ ... 'sphinx_togglebutton' ... ] ``` Now, whenever you wish for an admonition to be toggle-able, add the `:class: dropdown` parameter to the admonition directive that you use. For example, this code would create a toggle-able "note" admonition that starts hidden: ```rst .. note:: :class: dropdown This is my note. ``` Clicking on the toggle button will toggle the item's visibility. You may also **show the content by default**. To do so, add the `dropdown` class *as well as* a `toggle-shown` class, like so: ```rst .. note:: :class: dropdown, toggle-shown This is my note. ``` You can also use **containers** to add arbitrary toggle-able code. For example, here's a container with an image inside: ```rst .. container:: toggle, toggle-hidden .. admonition:: Look at that, an image! .. image:: https://media.giphy.com/media/mW05nwEyXLP0Y/giphy.gif ``` sphinx-togglebutton-0.3.2/RELEASES.md000066400000000000000000000005151426425403500172730ustar00rootroot00000000000000# Instructions for creating a new release Spinx-Toggle is [hosted on the pypi repository](https://pypi.org/project/sphinx-togglebutton/). To create a new release of Sphinx-Togglebutton, [follow the ExecutableBooks release instructions](https://github.com/executablebooks/.github/blob/master/CONTRIBUTING.md#releases-and-change-logs)sphinx-togglebutton-0.3.2/docs/000077500000000000000000000000001426425403500164755ustar00rootroot00000000000000sphinx-togglebutton-0.3.2/docs/Makefile000066400000000000000000000011451426425403500201360ustar00rootroot00000000000000# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build SPHINXPROJ = SphinxCopybutton SOURCEDIR = . BUILDDIR = _build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)sphinx-togglebutton-0.3.2/docs/changelog.md000066400000000000000000000000411426425403500207410ustar00rootroot00000000000000```{include} ../CHANGELOG.md ``` sphinx-togglebutton-0.3.2/docs/conf.py000066400000000000000000000023721426425403500200000ustar00rootroot00000000000000# -- Project information ----------------------------------------------------- project = "Sphinx Toggle Button" copyright = "2022, Executable Books Community" author = "Chris Holdgraf" # The short X.Y version version = "" # The full version, including alpha/beta/rc tags release = "" # -- General configuration --------------------------------------------------- extensions = ["myst_nb", "sphinx_examples", "sphinx_design", "sphinx_togglebutton"] templates_path = ["_templates"] source_suffix = ".rst" main_doc = "index" language = None exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] # -- Options for HTML output ------------------------------------------------- html_theme = "sphinx_book_theme" # html_theme = "sphinx_rtd_theme" # These are just for testing # html_theme = "pydata_sphinx_theme" # html_theme = "alabaster" # html_theme = "furo" html_theme_options = { "repository_url": "https://github.com/executablebooks/sphinx-togglebutton", "use_repository_button": True, "use_issues_button": True, "use_edit_page_button": True, "home_page_in_toc": True, } myst_enable_extensions = ["colon_fence"] # To test behavior in JS # togglebutton_hint = "test show" # togglebutton_hint_hide = "test hide" # togglebutton_open_on_print = False sphinx-togglebutton-0.3.2/docs/index.md000066400000000000000000000031661426425403500201340ustar00rootroot00000000000000# `sphinx-togglebutton` A small sphinx extension to add "toggle button" elements to sections of your page. For example: ## Collapse admonitions You can collapse admonitions (notes, warnings, etc) so that their content is hidden until users click the admonition title. ````{example} An example admonition toggle :reverse: :::{admonition} Click the title to toggle :class: dropdown This title was made into a dropdown admonition by adding `:class: dropdown` to it. ::: ```` See {ref}`dropdown-admonitions` for more information. ## Hide any content behind a toggle button You can also hide arbitrary content behind a toggle button. When users press the button, they will see the content. For example: ````{example} An example toggle directive :reverse: ```{toggle} This is a toggled content block! ``` ```` You can either do this with a `{toggle}` directive, or by adding a `toggle` CSS class to any elements you'd like hidden behind a toggle button. See [](use:css-selector) for more details. :::{admonition} Check out sphinx-design as well! :class: tip For a bootstrap-based "dropdown" directive that uses pure CSS, check out [Sphinx Design](https://sphinx-design.readthedocs.io/en/latest/dropdowns.html) ::: ## Installation You can install `sphinx-togglebutton` with `pip`: ```bash pip install sphinx-togglebutton ``` Then, activate it in your `sphinx` build by adding it to your `conf.py` configuration file, like so: E.g.: ```python extensions = [ ... 'sphinx_togglebutton' ... ] ``` See {ref}`usage` for information about how to use `sphinx-togglebutton`. ```{toctree} :maxdepth: 2 use reference/index changelog ```sphinx-togglebutton-0.3.2/docs/reference/000077500000000000000000000000001426425403500204335ustar00rootroot00000000000000sphinx-togglebutton-0.3.2/docs/reference/index.md000066400000000000000000000022671426425403500220730ustar00rootroot00000000000000# Reference examples This page shows the most common ways that `sphinx-togglebutton` is used as a reference. This is a benchmark for styling, and also helps demonstrate the behavior of this extension. ```{toctree} notebooks ``` ## Use amongst text Here's a paragraph, it's just here to provide some text context for the togglebuttons in this section. :::{note} :class: toggle A test toggle admonition. ::: Here's a paragraph, it's just here to provide some text context for the togglebuttons in this section. :::{toggle} A test toggle directive. ::: Here's a paragraph, it's just here to provide some text context for the togglebuttons in this section. ## Sequential toggle buttons Here's how they look right after one another: ### Admonition toggles :::{note} :class: toggle This is my note. ::: :::{note} :class: toggle This is my second. ::: ### Toggle directive :::{toggle} This is my first. ::: :::{toggle} This is my second. ::: ## Long titles :::{admonition} A really long admonition that will take up multiple lines A really long admonition that will take up multiple lines :class: toggle Admonition content. ```{image} https://jupyterbook.org/_static/logo-wide.svg ``` ::: sphinx-togglebutton-0.3.2/docs/reference/notebooks.md000066400000000000000000000046761426425403500227750ustar00rootroot00000000000000--- jupytext: formats: ipynb,md:myst text_representation: extension: .md format_name: myst format_version: 0.12 jupytext_version: 1.8.2 kernelspec: display_name: Python 3 language: python name: python3 --- # Jupyter notebooks Sphinx Togglebutton has support within MyST-NB. This page shows off showing / hiding inputs, outputs, and entire cells. ```{code-cell} ipython3 :tags: [hide-cell] from matplotlib import rcParams, cycler import matplotlib.pyplot as plt import numpy as np ``` ## Hiding the cell ```{code-cell} ipython3 :tags: [hide-cell] # Fixing random state for reproducibility np.random.seed(19680801) N = 10 data = [np.logspace(0, 1, 100) + np.random.randn(100) + ii for ii in range(N)] data = np.array(data).T cmap = plt.cm.coolwarm rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, N))) from matplotlib.lines import Line2D custom_lines = [Line2D([0], [0], color=cmap(0.), lw=4), Line2D([0], [0], color=cmap(.5), lw=4), Line2D([0], [0], color=cmap(1.), lw=4)] fig, ax = plt.subplots(figsize=(10, 5)) lines = ax.plot(data) ax.legend(custom_lines, ['Cold', 'Medium', 'Hot']); ``` ## Hiding input ```{code-cell} ipython3 :tags: [hide-input] # Fixing random state for reproducibility np.random.seed(19680801) N = 10 data = [np.logspace(0, 1, 100) + np.random.randn(100) + ii for ii in range(N)] data = np.array(data).T cmap = plt.cm.coolwarm rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, N))) from matplotlib.lines import Line2D custom_lines = [Line2D([0], [0], color=cmap(0.), lw=4), Line2D([0], [0], color=cmap(.5), lw=4), Line2D([0], [0], color=cmap(1.), lw=4)] fig, ax = plt.subplots(figsize=(10, 5)) lines = ax.plot(data) ax.legend(custom_lines, ['Cold', 'Medium', 'Hot']); ``` ## Hiding output ```{code-cell} ipython3 :tags: [hide-output] # Fixing random state for reproducibility np.random.seed(19680801) N = 10 data = [np.logspace(0, 1, 100) + np.random.randn(100) + ii for ii in range(N)] data = np.array(data).T cmap = plt.cm.coolwarm rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, N))) from matplotlib.lines import Line2D custom_lines = [Line2D([0], [0], color=cmap(0.), lw=4), Line2D([0], [0], color=cmap(.5), lw=4), Line2D([0], [0], color=cmap(1.), lw=4)] fig, ax = plt.subplots(figsize=(10, 5)) lines = ax.plot(data) ax.legend(custom_lines, ['Cold', 'Medium', 'Hot']); ```sphinx-togglebutton-0.3.2/docs/use.md000066400000000000000000000075501426425403500176220ustar00rootroot00000000000000(usage)= # Use and configure This page covers how to use and configure / customize `sphinx-togglebutton`. There are three main ways to use `sphinx-togglebutton`: - Wrap arbitrary objects in a toggle button via a CSS selector - Collapse admonitions with the `dropdown` class - Make arbitrary chunks of content "toggle-able" with the `toggle` directive Each is described below (use:css-selector)= ## Collapse a block of content with a CSS selector You can hide any content and display a toggle button to show it by using certain CSS classes. `sphinx-togglebutton` will wrap elements with these classes in a `
` block like so: ```html
Click to show
``` ````{example} ```{image} https://media.giphy.com/media/FaKV1cVKlVRxC/giphy.gif :class: toggle ``` ```` ### Configure the CSS selector used to insert toggle buttons By default, `sphinx-togglebutton` will use this selector: ``` .toggle, .admonition.dropdown ``` However, you can customize this behavior with the `togglebutton_selector` configuration value. To specify the selector to use, pass a valid CSS selector as a string: :::{admonition} example :class: tip Configure `sphinx-togglebutton` to look for a `.toggle-this-element` class and an element with ID `#my-special-id` **instead of** `.toggle` and `.admonition.dropdown`. ```python sphinx_togglebutton_selector = ".toggle-this-element, #my-special-id" ``` ::: (dropdown-admonitions)= ## Collapse admonitions with the `dropdown` class `sphinx-togglebutton` treats admonitions as a special case if they are selected. If a Sphinx admonition matches the toggle button selector, then its title will be displayed with a button to reveal its content. ````{example} ```{admonition} This will be shown :class: dropdown And this will be hidden! ``` ```` This works for any kind of Sphinx admoniton: :::{note} :class: dropdown A note! ::: :::{warning} :class: dropdown A warning! ::: (toggle-directive)= ## Use the `{toggle}` directive to toggle blocks of content To add toggle-able content, use the **toggle directive**. This directive will wrap its content in a toggle-able container. You can call it like so: :::{tab-set-code} ````markdown ```{toggle} Here is my toggle-able content! ``` ```` ```rst .. toggle:: Here is my toggle-able content! ``` ::: The code above results in: :::{toggle} Here is my toggle-able content! ::: To show the toggle-able content by default, use the `:show:` flag. ````markdown ```{toggle} :show: Here is my toggle-able content! ``` ```` It results in the following: :::{toggle} :show: Here is my toggle-able content! ::: ## Change the button hint text You can control the "hint" text that is displayed next to togglebuttons. To do so, use the following configuration variable in your `conf.py` file: ```python togglebutton_hint = "Displayed when the toggle is closed." togglebutton_hint_hide = "Displayed when the toggle is open." ``` ## Change the toggle icon color You can apply some extra styles to the toggle button to achieve the look you want. This is particularly useful if the color of the toggle button does not contrast with the background of an admonition. To style the toggle button, [add a custom CSS file to your documentation](https://docs.readthedocs.io/en/stable/guides/adding-custom-css.html) and include a custom CSS selector like so: ```scss // Turn the color red... // ...with admonition toggle buttons button.toggle-button { color: red; } // ...with content block toggle buttons .toggle-button summary { color: red; } ``` ## Printing behavior with toggle buttons By default `sphinx-togglebutton` will **open all toggle-able content when you print**. It will close them again when the printing operation is complete. To disable this behavior, use the following configuration in `conf.py`: ```python togglebutton_open_on_print = False ``` sphinx-togglebutton-0.3.2/readthedocs.yml000066400000000000000000000001761426425403500205610ustar00rootroot00000000000000version: 2 python: version: 3 install: - method: pip path: . extra_requirements: - sphinx sphinx-togglebutton-0.3.2/setup.cfg000066400000000000000000000000421426425403500173620ustar00rootroot00000000000000[metadata] license_file = LICENSE sphinx-togglebutton-0.3.2/setup.py000066400000000000000000000021721426425403500172610ustar00rootroot00000000000000import os from pathlib import Path from setuptools import setup, find_packages version = [ line for line in Path("sphinx_togglebutton/__init__.py").read_text().split("\n") if "__version__" in line ] version = version[0].split(" = ")[-1].strip('"') with open("./README.md", "r") as ff: readme_text = ff.read() setup( name="sphinx-togglebutton", version=version, description="Toggle page content and collapse admonitions in Sphinx.", long_description=readme_text, long_description_content_type="text/markdown", author="Chris Holdgraf", author_email="choldgraf@berkeley.edu", url="https://github.com/executablebooks/sphinx-togglebutton", license="MIT License", packages=find_packages(), package_data={ "sphinx_togglebutton": ["_static/togglebutton.css", "_static/togglebutton.js", "_static/togglebutton-chevron.svg"] }, install_requires=["setuptools", "wheel", "sphinx", "docutils"], extras_require={"sphinx": ["matplotlib", "numpy", "myst_nb", "sphinx_book_theme", "sphinx_design", "sphinx_examples"]}, classifiers=["License :: OSI Approved :: MIT License"], ) sphinx-togglebutton-0.3.2/sphinx_togglebutton/000077500000000000000000000000001426425403500216535ustar00rootroot00000000000000sphinx-togglebutton-0.3.2/sphinx_togglebutton/__init__.py000066400000000000000000000051671426425403500237750ustar00rootroot00000000000000"""A small sphinx extension to add "toggle" buttons to items.""" import os from docutils.parsers.rst import Directive, directives from docutils import nodes __version__ = "0.3.2" def st_static_path(app): static_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "_static")) app.config.html_static_path.append(static_path) def initialize_js_assets(app, config): # Update the global context app.add_js_file(None, body=f"let toggleHintShow = '{config.togglebutton_hint}';") app.add_js_file(None, body=f"let toggleHintHide = '{config.togglebutton_hint_hide}';") open_print = str(config.togglebutton_open_on_print).lower() app.add_js_file(None, body=f"let toggleOpenOnPrint = '{open_print}';") app.add_js_file("togglebutton.js") # This function reads in a variable and inserts it into JavaScript def insert_custom_selection_config(app): # This is a configuration that you've specified for users in `conf.py` selector = app.config["togglebutton_selector"] js_text = "var togglebuttonSelector = '%s';" % selector app.add_js_file(None, body=js_text) class Toggle(Directive): """Hide a block of markup text by wrapping it in a container.""" optional_arguments = 1 final_argument_whitespace = True has_content = True option_spec = {"id": directives.unchanged, "show": directives.flag} def run(self): self.assert_has_content() classes = ["toggle"] if "show" in self.options: classes.append("toggle-shown") parent = nodes.container(classes=classes) self.state.nested_parse(self.content, self.content_offset, parent) return [parent] # We connect this function to the step after the builder is initialized def setup(app): # Add our static path app.connect("builder-inited", st_static_path) # Add relevant code to headers app.add_css_file("togglebutton.css") # Add the string we'll use to select items in the JS # Tell Sphinx about this configuration variable app.add_config_value("togglebutton_selector", ".toggle, .admonition.dropdown", "html") app.add_config_value("togglebutton_hint", "Click to show", "html") app.add_config_value("togglebutton_hint_hide", "Click to hide", "html") app.add_config_value("togglebutton_open_on_print", True, "html") # Run the function after the builder is initialized app.connect("builder-inited", insert_custom_selection_config) app.connect("config-inited", initialize_js_assets) app.add_directive("toggle", Toggle) return { "version": __version__, "parallel_read_safe": True, "parallel_write_safe": True, } sphinx-togglebutton-0.3.2/sphinx_togglebutton/_static/000077500000000000000000000000001426425403500233015ustar00rootroot00000000000000sphinx-togglebutton-0.3.2/sphinx_togglebutton/_static/togglebutton.css000066400000000000000000000072211426425403500265320ustar00rootroot00000000000000/** * Admonition-based toggles */ /* Visibility of the target */ .admonition.toggle .admonition-title ~ * { transition: opacity .3s, height .3s; } /* Toggle buttons inside admonitions so we see the title */ .admonition.toggle { position: relative; } /* Titles should cut off earlier to avoid overlapping w/ button */ .admonition.toggle .admonition-title { padding-right: 25%; cursor: pointer; } /* Hovering will cause a slight shift in color to make it feel interactive */ .admonition.toggle .admonition-title:hover { box-shadow: inset 0 0 0px 20px rgb(0 0 0 / 1%); } /* Hovering will cause a slight shift in color to make it feel interactive */ .admonition.toggle .admonition-title:active { box-shadow: inset 0 0 0px 20px rgb(0 0 0 / 3%); } /* Remove extra whitespace below the admonition title when hidden */ .admonition.toggle-hidden { padding-bottom: 0; } .admonition.toggle-hidden .admonition-title { margin-bottom: 0; } /* hides all the content of a page until de-toggled */ .admonition.toggle-hidden .admonition-title ~ * { height: 0; margin: 0; opacity: 0; visibility: hidden; } /* General button style and position*/ button.toggle-button { /** * Background and shape. By default there's no background * but users can style as they wish */ background: none; border: none; outline: none; /* Positioning just inside the admonition title */ position: absolute; right: 0.5em; padding: 0px; border: none; outline: none; } /* Display the toggle hint on wide screens */ @media (min-width: 768px) { button.toggle-button.toggle-button-hidden:before { content: attr(data-toggle-hint); /* This will be filled in by JS */ font-size: .8em; align-self: center; } } /* Icon behavior */ .tb-icon { transition: transform .2s ease-out; height: 1.5em; width: 1.5em; stroke: currentColor; /* So that we inherit the color of other text */ } /* The icon should point right when closed, down when open. */ /* Open */ .admonition.toggle button .tb-icon { transform: rotate(90deg); } /* Closed */ .admonition.toggle button.toggle-button-hidden .tb-icon { transform: rotate(0deg); } /* With details toggles, we don't rotate the icon so it points right */ details.toggle-details .tb-icon { height: 1.4em; width: 1.4em; margin-top: 0.1em; /* To center the button vertically */ } /** * Details-based toggles. * In this case, we wrap elements with `.toggle` in a details block. */ /* Details blocks */ details.toggle-details { margin: 1em 0; } details.toggle-details summary { display: flex; align-items: center; cursor: pointer; list-style: none; border-radius: .2em; border-left: 3px solid #1976d2; background-color: rgb(204 204 204 / 10%); padding: 0.2em 0.7em 0.3em 0.5em; /* Less padding on left because the SVG has left margin */ font-size: 0.9em; } details.toggle-details summary:hover { background-color: rgb(204 204 204 / 20%); } details.toggle-details summary:active { background: rgb(204 204 204 / 28%); } .toggle-details__summary-text { margin-left: 0.2em; } details.toggle-details[open] summary { margin-bottom: .5em; } details.toggle-details[open] summary .tb-icon { transform: rotate(90deg); } details.toggle-details[open] summary ~ * { animation: toggle-fade-in .3s ease-out; } @keyframes toggle-fade-in { from {opacity: 0%;} to {opacity: 100%;} } /* Print rules - we hide all toggle button elements at print */ @media print { /* Always hide the summary so the button doesn't show up */ details.toggle-details summary { display: none; } }sphinx-togglebutton-0.3.2/sphinx_togglebutton/_static/togglebutton.js000066400000000000000000000162621426425403500263630ustar00rootroot00000000000000/** * Add Toggle Buttons to elements */ let toggleChevron = ` `; var initToggleItems = () => { var itemsToToggle = document.querySelectorAll(togglebuttonSelector); console.log(`[togglebutton]: Adding toggle buttons to ${itemsToToggle.length} items`) // Add the button to each admonition and hook up a callback to toggle visibility itemsToToggle.forEach((item, index) => { if (item.classList.contains("admonition")) { // If it's an admonition block, then we'll add a button inside // Generate unique IDs for this item var toggleID = `toggle-${index}`; var buttonID = `button-${toggleID}`; item.setAttribute('id', toggleID); if (!item.classList.contains("toggle")){ item.classList.add("toggle"); } // This is the button that will be added to each item to trigger the toggle var collapseButton = ` `; title = item.querySelector(".admonition-title") title.insertAdjacentHTML("beforeend", collapseButton); thisButton = document.getElementById(buttonID); // Add click handlers for the button + admonition title (if admonition) admonitionTitle = document.querySelector(`#${toggleID} > .admonition-title`) if (admonitionTitle) { // If an admonition, then make the whole title block clickable admonitionTitle.addEventListener('click', toggleClickHandler); admonitionTitle.dataset.target = toggleID admonitionTitle.dataset.button = buttonID } else { // If not an admonition then we'll listen for the button click thisButton.addEventListener('click', toggleClickHandler); } // Now hide the item for this toggle button unless explicitly noted to show if (!item.classList.contains("toggle-shown")) { toggleHidden(thisButton); } } else { // If not an admonition, wrap the block in a
block // Define the structure of the details block and insert it as a sibling var detailsBlock = `
${toggleChevron} ${toggleHintShow}
`; item.insertAdjacentHTML("beforebegin", detailsBlock); // Now move the toggle-able content inside of the details block details = item.previousElementSibling details.appendChild(item) item.classList.add("toggle-details__container") // Set up a click trigger to change the text as needed details.addEventListener('click', (click) => { let parent = click.target.parentElement; if (parent.tagName.toLowerCase() == "details") { summary = parent.querySelector("summary"); details = parent; } else { summary = parent; details = parent.parentElement; } // Update the inner text for the proper hint if (details.open) { summary.querySelector("span.toggle-details__summary-text").innerText = toggleHintShow; } else { summary.querySelector("span.toggle-details__summary-text").innerText = toggleHintHide; } }); // If we have a toggle-shown class, open details block should be open if (item.classList.contains("toggle-shown")) { details.click(); } } }) }; // This should simply add / remove the collapsed class and change the button text var toggleHidden = (button) => { target = button.dataset['target'] var itemToToggle = document.getElementById(target); if (itemToToggle.classList.contains("toggle-hidden")) { itemToToggle.classList.remove("toggle-hidden"); button.classList.remove("toggle-button-hidden"); } else { itemToToggle.classList.add("toggle-hidden"); button.classList.add("toggle-button-hidden"); } } var toggleClickHandler = (click) => { // Be cause the admonition title is clickable and extends to the whole admonition // We only look for a click event on this title to trigger the toggle. if (click.target.classList.contains("admonition-title")) { button = click.target.querySelector(".toggle-button"); } else if (click.target.classList.contains("tb-icon")) { // We've clicked the icon and need to search up one parent for the button button = click.target.parentElement; } else if (click.target.tagName == "polyline") { // We've clicked the SVG elements inside the button, need to up 2 layers button = click.target.parentElement.parentElement; } else if (click.target.classList.contains("toggle-button")) { // We've clicked the button itself and so don't need to do anything button = click.target; } else { console.log(`[togglebutton]: Couldn't find button for ${click.target}`) } target = document.getElementById(button.dataset['button']); toggleHidden(target); } // If we want to blanket-add toggle classes to certain cells var addToggleToSelector = () => { const selector = ""; if (selector.length > 0) { document.querySelectorAll(selector).forEach((item) => { item.classList.add("toggle"); }) } } // Helper function to run when the DOM is finished const sphinxToggleRunWhenDOMLoaded = cb => { if (document.readyState != 'loading') { cb() } else if (document.addEventListener) { document.addEventListener('DOMContentLoaded', cb) } else { document.attachEvent('onreadystatechange', function() { if (document.readyState == 'complete') cb() }) } } sphinxToggleRunWhenDOMLoaded(addToggleToSelector) sphinxToggleRunWhenDOMLoaded(initToggleItems) /** Toggle details blocks to be open when printing */ if (toggleOpenOnPrint == "true") { window.addEventListener("beforeprint", () => { // Open the details document.querySelectorAll("details.toggle-details").forEach((el) => { el.dataset["togglestatus"] = el.open; el.open = true; }); // Open the admonitions document.querySelectorAll(".admonition.toggle.toggle-hidden").forEach((el) => { console.log(el); el.querySelector("button.toggle-button").click(); el.dataset["toggle_after_print"] = "true"; }); }); window.addEventListener("afterprint", () => { // Re-close the details that were closed document.querySelectorAll("details.toggle-details").forEach((el) => { el.open = el.dataset["togglestatus"] == "true"; delete el.dataset["togglestatus"]; }); // Re-close the admonition toggle buttons document.querySelectorAll(".admonition.toggle").forEach((el) => { if (el.dataset["toggle_after_print"] == "true") { el.querySelector("button.toggle-button").click(); delete el.dataset["toggle_after_print"]; } }); }); } sphinx-togglebutton-0.3.2/tox.ini000066400000000000000000000014041426425403500170570ustar00rootroot00000000000000# To use tox, see https://tox.readthedocs.io [tox] envlist = py39-sphinx3 [testenv] # only recreate the environment when we use `tox -r` recreate = false [testenv:docs] description = Build the documentation extras = sphinx deps = -e. sphinx_rtd_theme furo alabaster commands = sphinx-build \ -n -b {posargs:html} docs/ docs/_build/{posargs:html} [testenv:docs-live] description = Auto-build and preview the documentation in the browser deps = -e. sphinx-autobuild sphinx_rtd_theme furo alabaster extras = sphinx commands = sphinx-autobuild \ --re-ignore _build/.* \ --watch sphinx_togglebutton \ --port 0 --open-browser \ -n -b {posargs:html} docs/ docs/_build/{posargs:html}