Skip to content
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
10 changes: 10 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,13 @@ ultraplot/_version.py

# Nox build directories
.nox/*

# Generated docs and draw.io assets. The edited diagram remains a repository asset.
tools/cheatsheet/assets/
docs/_static/plot_types/
tools/cheatsheet/ultraplot_cheatsheet.png
tools/cheatsheet/ultraplot_cheatsheet-code.png
tools/cheatsheet/ultraplot_cheatsheet-reference.png
tools/cheatsheet/ultraplot_cheatsheet-beginner.png
tools/cheatsheet/ultraplot_cheatsheet-intermediate.png
tools/cheatsheet/ultraplot_cheatsheet-advanced.png
2 changes: 2 additions & 0 deletions .readthedocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ version: 2
# Set the OS and build tools
build:
os: ubuntu-22.04
apt_packages:
- xvfb
tools:
python: "mambaforge-latest"

Expand Down
2 changes: 2 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Cheatsheet sources and exports are repository assets, not pip distribution files.
prune tools/cheatsheet
93 changes: 93 additions & 0 deletions docs/_ext/drawio-lazy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/* Fetch SVG-heavy draw.io pages only when they approach the viewport. */
(() => {
"use strict";
let viewerPromise;
function viewer() {
if (window.GraphViewer && window.DOMPurify && window.pako) return Promise.resolve();
if (!viewerPromise) {
viewerPromise = new Promise((resolve, reject) => {
const script = document.createElement("script");
// The standalone viewer bundles DOMPurify, pako and Spinner as UMD
// libraries but consumes their browser globals. Sphinx's RequireJS
// otherwise captures them as anonymous AMD modules instead.
const define = window.define;
const amd = define && define.amd;
if (amd) define.amd = undefined;
const restoreAMD = () => {
if (amd) define.amd = amd;
};
script.src = "https://viewer.diagrams.net/js/viewer-static.min.js";
script.onload = () => {
restoreAMD();
if (window.GraphViewer && window.DOMPurify && window.pako) resolve();
else reject(new Error("Viewer dependencies unavailable"));
};
script.onerror = () => {
restoreAMD();
script.remove();
reject(new Error("Viewer download failed"));
};
document.head.appendChild(script);
}).catch(error => {
viewerPromise = undefined;
throw error;
});
}
return viewerPromise;
}

async function load(element) {
if (element.dataset.loading) return;
element.dataset.loading = "true";
element.setAttribute("aria-busy", "true");
try {
const [xml] = await Promise.all([
fetch(element.dataset.drawioUrl).then(response => {
if (!response.ok) throw new Error(`Diagram download failed (${response.status})`);
return response.text();
}),
viewer(),
]);
element.setAttribute("data-mxgraph", JSON.stringify({
xml, resize: true, fit: true, nav: false, lightbox: false, toolbar: "",
}));
element.replaceChildren();
window.GraphViewer.createViewerForElement(element);
element.removeAttribute("data-mxgraph");
element.style.minHeight = "";
element.setAttribute("aria-busy", "false");
} catch (error) {
delete element.dataset.loading;
element.setAttribute("aria-busy", "false");
const button = document.createElement("button");
button.type = "button";
button.textContent = "Diagram could not be loaded. Retry";
button.addEventListener("click", () => load(element));
element.replaceChildren(button);
console.warn("Draw.io diagram:", error);
}
}

function init() {
const elements = document.querySelectorAll(".drawio-lazy");
const observer = "IntersectionObserver" in window ? new IntersectionObserver(entries => {
for (const entry of entries) {
if (entry.isIntersecting) {
observer.unobserve(entry.target);
load(entry.target);
}
}
}, { rootMargin: "300px" }) : null;
for (const element of elements) {
element.querySelector("a").addEventListener("click", event => {
event.preventDefault();
if (observer) observer.unobserve(element);
load(element);
});
if (observer) observer.observe(element);
else load(element);
}
}
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init);
else init();
})();
162 changes: 162 additions & 0 deletions docs/_ext/drawio.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
from __future__ import annotations

import base64
import hashlib
import html
from pathlib import Path
import urllib.parse
import xml.etree.ElementTree as ET
import zlib

from docutils import nodes
from docutils.parsers.rst import Directive, directives
from sphinx.util.osutil import relative_uri


def _decode_diagram(diagram: ET.Element) -> str:
"""Return an mxGraphModel XML string from a <diagram> element."""

# Uncompressed draw.io files can contain mxGraphModel directly.
graph = diagram.find("mxGraphModel")
if graph is not None:
return ET.tostring(graph, encoding="unicode")

# Normal compressed draw.io representation:
# base64 -> raw DEFLATE -> URL decode
encoded = (diagram.text or "").strip()

if not encoded:
raise ValueError("Draw.io diagram contains no data")

compressed = base64.b64decode(encoded)
inflated = zlib.decompress(compressed, -15).decode("utf-8")

return urllib.parse.unquote(inflated)


def _get_page(path: Path, selector: str | None) -> str:
root = ET.parse(path).getroot()
diagrams = root.findall("diagram")

if not diagrams:
raise ValueError(f"No diagrams found in {path}")

# Default to first page.
if selector is None:
return _decode_diagram(diagrams[0])

# Numeric selector = page index.
try:
index = int(selector)
except ValueError:
index = None

if index is not None:
try:
return _decode_diagram(diagrams[index])
except IndexError:
raise ValueError(
f"Page index {index} does not exist in {path}"
) from None

# Otherwise treat selector as page name.
for diagram in diagrams:
if diagram.get("name") == selector:
return _decode_diagram(diagram)

names = [d.get("name", "<unnamed>") for d in diagrams]
raise ValueError(
f"Page {selector!r} not found in {path}. "
f"Available pages: {', '.join(names)}"
)


class drawio_node(nodes.General, nodes.Element):
pass


def _visit_drawio_html(self, node):
# Write at HTML translation time so cached doctrees also recreate assets
# when the output directory is cleaned. Content hashes allow browser caching.
xml = node["xml"]
digest = hashlib.sha256(xml.encode("utf-8")).hexdigest()
asset = f"_drawio/{digest}.xml"
path = Path(self.builder.outdir) / asset
path.parent.mkdir(parents=True, exist_ok=True)
if not path.exists():
path.write_text(xml, encoding="utf-8")
url = relative_uri(self.builder.get_target_uri(self.builder.current_docname), asset)
classes = html.escape(" ".join(["drawio-lazy", *node["classes"]]), quote=True)
url = html.escape(url, quote=True)
self.body.append(
f'<div class="{classes}" data-drawio-url="{url}" '
'style="min-height:24rem" aria-busy="true">'
f'<a href="{url}">Load diagram</a>'
'<noscript> (JavaScript is required to view this diagram.)</noscript>'
'</div>'
)
raise nodes.SkipNode


def _skip_drawio(self, node):
raise nodes.SkipNode


class DrawioDirective(Directive):
required_arguments = 1
has_content = False

option_spec = {
"page": directives.unchanged,
"class": directives.class_option,
}

def run(self):
env = self.state.document.settings.env

# Resolve relative to the .rst file containing the directive.
source = Path(env.doc2path(env.docname)).resolve()
path = (source.parent / self.arguments[0]).resolve()

if not path.exists():
raise self.error(f"Draw.io file not found: {path}")

# Tell Sphinx that changes to the .drawio file should rebuild this page.
env.note_dependency(str(path))

try:
xml = _get_page(path, self.options.get("page"))
except (ET.ParseError, ValueError) as exc:
raise self.error(str(exc)) from exc

node = drawio_node()
node["xml"] = xml
node["classes"] = self.options.get("class", [])
return [node]


def _copy_loader(app, exception):
if exception is None and app.builder.format == "html":
target = Path(app.outdir) / "_static" / "drawio-lazy.js"
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(Path(__file__).with_name("drawio-lazy.js").read_bytes())


def setup(app):
app.add_directive("drawio", DrawioDirective)

app.add_node(
drawio_node,
html=(_visit_drawio_html, None),
latex=(_skip_drawio, None),
text=(_skip_drawio, None),
)
# Copy our loader without requiring changes to html_static_path.
app.connect("build-finished", _copy_loader)
app.add_js_file("drawio-lazy.js", loading_method="defer")

return {
"version": "2.0",
"parallel_read_safe": True,
"parallel_write_safe": True,
}
34 changes: 34 additions & 0 deletions docs/_scripts/build_plot_types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#!/usr/bin/env python3
"""
Regenerate the visual plot-type index before a documentation build.

Run from ``conf.py`` the same way ``fetch_releases.py`` is: the page and its
thumbnails are generated artefacts, so a clean checkout builds them rather than
carrying 60-odd PNGs in the repository. Rendering is skipped when the icons are
already present, so a local rebuild costs nothing.
"""

import os
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(os.path.dirname(HERE))
GENERATOR = os.path.join(ROOT, "tools", "cheatsheet")

sys.path.insert(0, GENERATOR)


def main():
try:
import docs_index
except ImportError as error: # the tools folder is not shipped in sdists
print(f"plot-type index skipped: {error}")
return
try:
docs_index.main()
except Exception as error: # never fail the docs build over a thumbnail
print(f"plot-type index skipped: {type(error).__name__}: {error}")


if __name__ == "__main__":
main()
47 changes: 47 additions & 0 deletions docs/cheatsheet.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
Cheat Sheet
===========

They say don't change a winning team. With UltraPlot we use Matplotlib's object orientated syntax, and
add to it essential quality of life improvements to make high quality publication ready plots.
To highlight the capabilities in a bird's eye view, we have included a few Matplotlib style cheat sheets below.


================
General Overview
================

.. drawio:: ../tools/cheatsheet/ultraplot_cheatsheet.drawio
:page: UltraPlot cheatsheet

=================
Every day recipes
=================
.. drawio:: ../tools/cheatsheet/ultraplot_cheatsheet.drawio
:page: UltraPlot code recipes


===============
Quick Reference
===============
.. drawio:: ../tools/cheatsheet/ultraplot_cheatsheet.drawio
:page: UltraPlot quick reference

=========
Beginners
=========
.. drawio:: ../tools/cheatsheet/ultraplot_cheatsheet.drawio
:page: Beginner · start here

============
Intermediate
============
.. drawio:: ../tools/cheatsheet/ultraplot_cheatsheet.drawio
:page: Intermediate · layout & guides


======
Expert
======
.. drawio:: ../tools/cheatsheet/ultraplot_cheatsheet.drawio
:page: Advanced · specialist tools

9 changes: 9 additions & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ def __getattr__(self, name):
}
if not FAST_PREVIEW:
run([sys.executable, "_scripts/fetch_releases.py"], check=False)
# Visual plot-type index: thumbnails plus the page that arranges them.
run([sys.executable, "_scripts/build_plot_types.py"], check=False)

# Docs theme selector. Default to Shibuya, but keep env override for A/B checks.
DOCS_THEME = os.environ.get("UPLT_DOCS_THEME", "shibuya").strip().lower()
Expand Down Expand Up @@ -245,9 +247,16 @@ def _reset_ultraplot(gallery_conf, fname):
"sphinx_automodapi.automodapi", # fork of automodapi
"sphinx_copybutton", # add copy button to code
"_ext.notoc",
"_ext.drawio",
"nbsphinx", # parse rst books
"sphinx_gallery.gen_gallery",
]

drawio_headless = "auto"
drawio_builder_export_format = {
"html": "svg",
}

if not FAST_PREVIEW:
extensions.append("sphinx_sitemap")
if HAVE_ULTRAPLOT_THEME_EXT:
Expand Down
1 change: 0 additions & 1 deletion docs/examples/plot_types/05_box_violin.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,4 @@
axs[1].format(title="Violin plot", xlabel="Distribution", ylabel="Value")

axs.format(suptitle="Statistical distributions")
uplt.show(block=1)
fig.show()
Loading
Loading