Source code for respysive.presentation

"""Presentation generation and HTML output with the respysive runtime."""

import html
import json
import os
from pathlib import Path

from . import themes
from .assets import (
    ASSETS_MARKER,
    LIBRARIES,
    detect_libraries,
    inline_css,
    inline_external_resources,
    library_urls,
    plotly_geo_assets_script,
)
from .container import OVERFLOW_MODES
from .dependencies import CSS_URLS, JS_URLS, LOCAL_CSS_URLS, get_theme_url
from .themes import THEMES
from .utils import _dedupe_svg_ids, _script_json

_STATIC_DIR = Path(__file__).parent / "static"

TRANSITIONS = ("slide", "fade", "none")

# Reveal.js-style background attributes, mapped to CSS on the slide background layer
_BACKGROUND_CSS = {
    "data-background-color": "background-color",
    "data-background-size": "background-size",
    "data-background-position": "background-position",
    "data-background-repeat": "background-repeat",
    "data-background-opacity": "opacity",
}


def _read_static(name):
    """Read a runtime asset shipped in respysive/static."""
    return (_STATIC_DIR / name).read_text(encoding="utf-8")


_GUTTERS = {"0": "0", "1": "0.25rem", "2": "0.5rem", "3": "1rem", "4": "1.5rem", "5": "3rem"}


def _bootstrap_canvas_css():
    """Adapt Bootstrap 4 to fixed-size slides.

    Bootstrap breakpoints follow the browser viewport, while slides have a
    fixed width. Without these rules ``col-md-6`` would stack on a narrow
    window, making slides taller (so more shrunk by overflow fitting) and
    different from the PDF/PPTX output. Breakpoints are listed from sm to xl
    so the widest wins, as on a large screen.

    Also adds the Bootstrap 5 gutter classes (``g-3``…) generated by
    ``Row(gap=…)``, which Bootstrap 4 lacks.

    Returns:
        str: CSS rules.
    """
    rules = []
    for bp in ("sm", "md", "lg", "xl"):
        rules.append(f".reveal .col-{bp}{{flex-basis:0;flex-grow:1;max-width:100%}}")
        rules.append(f".reveal .col-{bp}-auto{{flex:0 0 auto;width:auto;max-width:100%}}")
        for n in range(1, 13):
            pct = f"{n / 12 * 100:.6g}%"
            rules.append(f".reveal .col-{bp}-{n}{{flex:0 0 {pct};max-width:{pct}}}")
        for n in range(12):
            rules.append(f".reveal .offset-{bp}-{n}{{margin-left:{n / 12 * 100:.6g}%}}")
        for n in range(13):
            rules.append(f".reveal .order-{bp}-{n}{{order:{n}}}")
    for n, size in _GUTTERS.items():
        rules.append(
            f".reveal .row.g-{n}{{margin-left:calc(-0.5 * {size});margin-right:calc(-0.5 * {size});row-gap:{size}}}"
        )
        rules.append(
            f".reveal .row.g-{n} > [class*='col']{{padding-left:calc(0.5 * {size});padding-right:calc(0.5 * {size})}}"
        )
    return "\n".join(rules)


def _background_layer(kwargs):
    """Build the background layer of a slide from data-background-* kwargs.

    Args:
        kwargs: Slide kwargs.

    Returns:
        str: ``<div class="rs-bg">`` element, or an empty string.
    """
    style = {}
    images = []
    if kwargs.get("data-background-image"):
        images.append(f"url('{kwargs['data-background-image']}')")
    if kwargs.get("data-background-gradient"):
        images.append(kwargs["data-background-gradient"])
    if images:
        style["background-image"] = ", ".join(images)
    for attr, prop in _BACKGROUND_CSS.items():
        if kwargs.get(attr) is not None:
            style[prop] = kwargs[attr]
    if not style:
        return ""
    style_str = html.escape("; ".join(f"{k}: {v}" for k, v in style.items()), quote=True)
    return f'<div class="rs-bg" style="{style_str}"></div>'


def _is_remote(url):
    return url.startswith(("http://", "https://", "file://"))


def _resolve_url(key, url, offline):
    """Return the URL to emit for a library file.

    Offline exports need something the inliner can read: local paths set with
    set_local_js_urls/set_local_css_urls become file:// URLs, and missing
    local files fall back to the CDN.
    """
    if not offline or _is_remote(url):
        return url
    path = Path(url)
    if path.exists():
        return path.resolve().as_uri()
    return JS_URLS.get(key) or CSS_URLS.get(key) or url


def _css_tag(url, fallback=None):
    if fallback and fallback != url:
        return (
            f"<link type='text/css' href='{url}' rel='stylesheet' "
            f"onerror=\"this.onerror=null;this.href='{fallback}';\">\n"
        )
    return f"<link type='text/css' href='{url}' rel='stylesheet'>\n"


def _js_tag(url, fallback=None):
    if fallback and fallback != url:
        return (
            f"<script src='{url}' type='text/javascript' "
            f"onerror=\"this.onerror=null;this.src='{fallback}';\"></script>\n"
        )
    return f"<script src='{url}' type='text/javascript'></script>\n"


def _slide_contents(slides):
    """Yield the raw contents added to slides (figures, dicts, strings…).

    Walks the records kept for exports: rows, cards, split title pages and
    Row/Column layouts, including vertical stacks.
    """
    from .layout import Column, Row

    def walk(item):
        if isinstance(item, (Row, Column)):
            for child in item.content:
                yield from walk(child)
        else:
            yield item

    for slide in slides:
        if isinstance(slide, list):
            yield from _slide_contents(slide)
            continue
        for record in getattr(slide, "_export_data", []):
            kind = record.get("type")
            if kind == "row":
                for element in record["elements"]:
                    yield element["content"]
            elif kind == "cards":
                yield from (card["graph"] for card in record["cards"] if "graph" in card)
            elif kind == "split_title_page":
                yield record["custom_content"]
            elif kind == "layout":
                yield from walk(record["layout"])


def _flatten(slides):
    """Slides in order, with vertical stacks expanded."""
    for slide in slides:
        if isinstance(slide, list):
            yield from _flatten(slide)
        else:
            yield slide


def _create_slide_html(slide):
    """Create HTML representation of a slide.

    A list of slides becomes a vertical stack. Custom CSS classes from
    ``slide.kwargs['class']`` are merged with the runtime classes, and
    ``data-background-*`` kwargs are rendered as a background layer.

    Args:
        slide: Slide object or list of slides for vertical grouping

    Returns:
        str: HTML section element containing the slide content
    """
    if isinstance(slide, list):
        return "<section class='stack'>" + "\n".join(_create_slide_html(s) for s in slide) + "</section>"

    classes = ["rs-slide"]
    if slide.center:
        classes.append("center")

    custom_class = slide.kwargs.get("class", "")
    if isinstance(custom_class, str) and custom_class:
        classes.append(custom_class)
    elif isinstance(custom_class, list):
        classes.extend(custom_class)

    attrs = {k: v for k, v in slide.kwargs.items() if k != "class" and not k.startswith("data-background")}
    overflow = getattr(slide, "overflow", None)
    if overflow:
        attrs["data-overflow"] = overflow
    attrs_str = " ".join(f'{k}="{html.escape(str(v), quote=True)}"' for k, v in attrs.items())

    shared_data_html = ""
    if hasattr(slide, "content_obj") and slide.content_obj.content:
        shared_data_html = slide.content_obj.content

    return f"""<section class="{" ".join(classes)}" {attrs_str}>
        {_background_layer(slide.kwargs)}
        <div class="container rs-body" style="text-align: left;">
            {shared_data_html}
            {slide.content}
        </div>
    </section>"""


[docs] class Presentation: """Presentation container for creating HTML slideshows. Creates interactive presentations using Bootstrap and the respysive runtime (navigation, fragments, speaker notes, overflow fitting). Supports global data sharing and multiple content types. """ def __init__(self): """Initialize an empty presentation.""" self.slides = [] self._global_geojson = {} self._custom_css = "" self._libraries = [] self._extra_css = [] self._extra_js = [] def __repr__(self): n = len(self.slides) return f"Presentation({n} slide{'s' if n != 1 else ''})" def _check_geojson_refs(self): """Raise if a map refers to GeoJSON that was not added to the deck.""" for slide in _flatten(self.slides): content = getattr(slide, "content_obj", None) missing = sorted(getattr(content, "geojson_refs", set()) - self._global_geojson.keys()) if missing: raise ValueError( f"GeoJSON {', '.join(map(repr, missing))} is used by a map but was never added. " "Call presentation.add_global_geojson() with that id." )
[docs] def add_global_geojson(self, div_id, geojson_data): """Add global GeoJSON data for sharing across slides. Args: div_id: Unique identifier for the GeoJSON data geojson_data: GeoJSON as a dictionary, a JSON string, or the path of a .geojson/.json file Raises: TypeError: If geojson_data is not a dict, a string or a path. FileNotFoundError: If geojson_data is a path to a missing file. """ if isinstance(geojson_data, dict): json_str = json.dumps(geojson_data, separators=(",", ":")) elif isinstance(geojson_data, str) and geojson_data.lstrip().startswith(("{", "[")): json_str = geojson_data elif isinstance(geojson_data, (str, os.PathLike)): with open(geojson_data, encoding="utf-8") as f: json_str = f.read() else: raise TypeError( f"geojson_data must be a dict, a JSON string or a file path, got {type(geojson_data).__name__}" ) self._global_geojson[div_id] = json_str
[docs] def add_custom_css(self, css: str): """Add custom CSS to the presentation. Injects custom CSS into the HTML <head> for styling, overlays, or watermarks. CSS is applied to all slides in the presentation. Args: css: CSS code as string Example: Add a logo overlay to slides with the 'branded' class:: presentation.add_custom_css(''' .slides section.branded::after { content: ''; position: absolute; top: 20px; right: 20px; width: 100px; height: 100px; background-image: url('logo.svg'); background-size: contain; opacity: 0.7; pointer-events: none; z-index: 10; } ''') slide = Slide(**{'class': 'branded'}) """ self._custom_css += css + "\n"
[docs] def add_library(self, name=None, js=None, css=None): """Load an extra library, either built-in or from your own URLs. Built-in libraries are normally detected from the slides; naming one forces it. URLs are loaded in the order given, after built-in libraries, and are embedded like the others by ``offline=True``. Args: name: Built-in library to force ('plotly', 'vega', 'd3', 'mathjax', 'maplibre', 'fontawesome'). js: Script URL(s) or local path(s). css: Stylesheet URL(s) or local path(s). Raises: ValueError: If name is not a built-in library and no URL is given. Example:: presentation.add_library("mathjax") presentation.add_library( js="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js", css=["https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"], ) """ js = [js] if isinstance(js, str) else list(js or []) css = [css] if isinstance(css, str) else list(css or []) if name is not None and not (js or css): if name not in LIBRARIES: raise ValueError( f"Unknown library {name!r}; available: {list(LIBRARIES)}. Pass js=/css= URLs for other libraries." ) if name not in self._libraries: self._libraries.append(name) self._extra_js += [u for u in js if u not in self._extra_js] self._extra_css += [u for u in css if u not in self._extra_css]
[docs] def add_slide(self, slide): """Add slide or slides to the presentation. Args: slide: Slide object or list of Slide objects (a nested list creates a vertical stack) """ if isinstance(slide, list): for sl in slide: self.slides.append(sl) else: self.slides.append(slide)
[docs] def to_html( self, theme="moon", width=1280, height=720, minscale=0.2, maxscale=2.0, margin=0.04, custom_theme=None, center=True, embedded=False, transition="slide", overflow="fit", controls=True, progress=True, slide_number="c/t", libraries="auto", offline=False, ): """Generate the full HTML document for the presentation. Args: theme: 'sober', 'science' or 'corporate' for a respysive theme, which also gives Plotly and Altair charts its colours and font. Otherwise a Reveal.js theme name (e.g. 'moon', 'white', 'black'), of which only the CSS is used. Use 'custom' with custom_theme for external CSS, or None for no theme. width: Slide width in pixels. Default 1280. height: Slide height in pixels. Default 720. minscale: Minimum scaling factor. Default 0.2. maxscale: Maximum scaling factor. Default 2.0. margin: Margin around slides as a fraction of the window (0.0 to 0.5). Default 0.04. custom_theme: URL to custom CSS theme file. Required when theme='custom'. center: Vertically center slide content. Default True. embedded: Size the deck to its parent element instead of the window. Default False. transition: Slide transition: 'slide', 'fade' or 'none'. Default 'slide'. overflow: Default handling of content taller than the slide, overridable per slide: 'fit' shrinks text then scales content to fit, 'warn' logs overflowing slides in the browser console, 'visible' does nothing. controls: Show navigation arrows. Default True. progress: Show the progress bar. Default True. slide_number: Slide number format: 'c/t', 'c', 'h.v', 'h/v', or None to hide it. libraries: Built-in libraries to load: 'auto' (those the slides use, plus add_library() names), 'all', or a list of names. Bootstrap is always loaded. offline: Embed every script, stylesheet and font in the HTML file so it opens without network. Files are cached locally on first download; run respysive.download_libraries() beforehand to work fully offline. Map tiles and remote images still need the network. Returns: str: Complete HTML document as string. Raises: ValueError: If theme is 'custom' but custom_theme is not provided, or if transition / overflow is not a supported value. """ if theme == "custom" and custom_theme is None: raise ValueError("If the theme is set to 'custom', a URL for the custom theme must be provided.") if transition not in TRANSITIONS: raise ValueError(f"transition must be one of {TRANSITIONS}, got {transition!r}") if overflow not in OVERFLOW_MODES: raise ValueError(f"overflow must be one of {OVERFLOW_MODES}, got {overflow!r}") self._check_geojson_refs() slides_html = _dedupe_svg_ids("\n".join([_create_slide_html(slide) for slide in self.slides])) if libraries == "auto": names = detect_libraries(slides_html) names += [n for n in self._libraries if n not in names] elif libraries == "all": names = list(LIBRARIES) else: names = [libraries] if isinstance(libraries, str) else list(libraries) if "bootstrap" not in names: names.insert(0, "bootstrap") # every slide layout relies on it lib_css, lib_js = library_urls(names) css_links_html = "" theme_css = theme_js = "" if theme in THEMES: theme_css = themes.theme_css(theme) theme_js = f"<script>\n{themes.theme_script(theme)}\n</script>" theme = THEMES[theme]["base"] # set_local_css_urls({'theme': ...}) replaces the Reveal.js stylesheet of the theme theme_url = custom_theme or ((LOCAL_CSS_URLS.get("theme") or get_theme_url(theme)) if theme else None) if theme_url and offline and not _is_remote(theme_url) and Path(theme_url).exists(): css_links_html += f"<style>\n{inline_css(theme_url)}\n</style>\n" elif theme_url: css_links_html += _css_tag(_resolve_url("theme", theme_url, offline)) for key, url in lib_css: css_links_html += _css_tag(_resolve_url(key, url, offline), None if offline else CSS_URLS[key]) for url in self._extra_css: css_links_html += _css_tag(_resolve_url(None, url, offline)) js_links_html = "" for key, url in lib_js: js_links_html += _js_tag(_resolve_url(key, url, offline), None if offline else JS_URLS[key]) for url in self._extra_js: js_links_html += _js_tag(_resolve_url(None, url, offline)) global_geojson_html = "" for div_id, json_str in self._global_geojson.items(): # a JSON script keeps the text as written: a <div> would parse "<" and "&" as HTML global_geojson_html += ( f'<script type="application/json" id="{html.escape(str(div_id), quote=True)}">' f"{_script_json(json_str)}</script>\n" ) runtime_config = json.dumps( { "width": width, "height": height, "margin": margin, "minScale": minscale, "maxScale": maxscale, "transition": transition, "overflow": overflow, "controls": controls, "progress": progress, "slideNumber": slide_number, "embedded": embedded, } ) html_class = "rs-center" if center else "" geo_assets_html = plotly_geo_assets_script(_slide_contents(self.slides)) if offline else "" document = f"""<!DOCTYPE html> <html class="{html_class}"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> {css_links_html} <style type='text/css'> {_read_static("respysive.css")} {_bootstrap_canvas_css()} @page {{ size: {width}px {height}px; margin: 0; }} {theme_css} /* Custom user CSS */ {self._custom_css} </style> {theme_js} {js_links_html} </head> <body class="reveal-viewport"> {ASSETS_MARKER} {geo_assets_html} {global_geojson_html} <div class="reveal rs-deck"> <div class="slides rs-canvas" style="--rs-w: {width}px; --rs-h: {height}px;"> {slides_html} </div> </div> <script>window.RESPYSIVE_CONFIG = {runtime_config};</script> <script> {_read_static("respysive.js")} </script> </body> </html>""" return inline_external_resources(document) if offline else document
def save_html(self, file_name, **kwargs): """Save presentation as HTML file. Args: file_name: Output HTML filename **kwargs: Arguments to pass to to_html() """ presentation_html = self.to_html(**kwargs) with open(file_name, "w", encoding="utf-8") as f: f.write(presentation_html) def save_pdf(self, file_name, fragments=False, timeout=60, **kwargs): """Save presentation as a PDF file, one page per slide. The PDF is printed by headless Chromium, so it matches the slides on screen. Requires ``pip install playwright`` and ``python -m playwright install chromium``. Args: file_name: Output PDF filename fragments: One page per fragment step instead of the final state timeout: Seconds allowed for loading charts, equations and maps **kwargs: Arguments to pass to to_html() """ from .exporters import PdfExporter PdfExporter(self, fragments=fragments, timeout=timeout).save(file_name, **kwargs)
[docs] def check(self, min_scale=0.7, timeout=60, **kwargs): """Render the deck in headless Chromium and report how each slide fits. The report lists, for each slide, the scale of its text after fitting, what becomes a picture in a PowerPoint export, and the hosts the deck loads resources from. Printing it gives a table. Requires Playwright and Chromium, like the exports. Args: min_scale: Text scale under which a slide counts as too small. timeout: Seconds allowed for loading charts, equations and maps **kwargs: Arguments to pass to to_html(), as for save_html() Returns: respysive.report.DeckReport Example: >>> report = deck.check(theme="white") # doctest: +SKIP >>> print(report) # doctest: +SKIP >>> slides_to_split = [s.number for s in report.small] # doctest: +SKIP """ from .report import check return check(self, min_scale=min_scale, timeout=timeout, **kwargs)
def save_pptx(self, file_name, timeout=60, **kwargs): """Save presentation as a PowerPoint file. Slides are rebuilt from the layout rendered by headless Chromium: text stays editable, charts, maps and equations become pictures. Requires ``pip install playwright python-pptx`` and ``python -m playwright install chromium``. Args: file_name: Output .pptx filename timeout: Seconds allowed for loading charts, equations and maps **kwargs: Arguments to pass to to_html() """ from .exporters import PptxExporter PptxExporter(self, timeout=timeout).save(file_name, **kwargs)