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