holoviz / panel

Panel: The powerful data exploration & web app framework for Python
https://panel.holoviz.org
BSD 3-Clause "New" or "Revised" License
4.76k stars 517 forks source link

Make it easy to use Panel with Sphinx-Gallery #5519

Open MarcSkovMadsen opened 1 year ago

MarcSkovMadsen commented 1 year ago

In https://discourse.holoviz.org/t/how-to-use-sphinx-gallery-with-panel/6035 pkrull asks for help using Panel with sphinx-gallery.

I think it could be quite powerful to support. It could even be used for the Panel or awesome-panel sites? It builds much faster than the notebooks in Panel !

All it takes to support sphinx-gallery is really a _repr_html_ method on Panel objects. For example something that returns an iframe.

Proof of concept

For example by adding the below to the sphinx conf.py file you will get it working

# Configure sphinx-gallery for panel

import panel as pn
from uuid import uuid4
from io import StringIO
from html import escape
import param

class PanelReprHTML(param.Parameterized):
    max_height=param.Integer(1000, bounds=(0,None))
    embed = param.Boolean(True)

    def __init__(self, object):
        self._object = object

    def _get_html(self):
        out = StringIO()
        self._object.save(out, embed=self.embed)
        out.seek(0)
        return escape(out.read())

    def _repr_html_(self):
        html = self._get_html()    
        uid = str(uuid4())       
        return f"""
<script>
function resizeIframe(){{
    setTimeout(() => {{
        var iframe = document.getElementById("{uid}");
        iframe.width = iframe.contentWindow.document.body.scrollWidth + 25;
        iframe.height = Math.min(iframe.contentWindow.document.body.scrollHeight + 10, {self.max_height});
        console.log(iframe.height)
    }}, "100");

}}
</script>        
<iframe id="{uid}" srcdoc='{html}' frameBorder='0' onload='resizeIframe(this)'></iframe>
"""

def _repr_html_(self):
    return PanelReprHTML(self)._repr_html_()

def add_repr_html():
    pn.viewable.Viewable._repr_html_=_repr_html_

PanelReprHTML.max_height=600
add_repr_html()

This is how it looks

sphinx-gallery

Repository

A working repository is here https://github.com/MarcSkovMadsen/sphinx-gallery-panel-example

Todo

Some things that could be done to improve things

Question

How should we support it

larsoner commented 1 year ago

Just popping in to say that at the SG end I think https://github.com/sphinx-gallery/sphinx-gallery/pull/1138 was close to being complete so @MarcSkovMadsen you could probably take it over and push it over the finish line if you want. I could fix the merge conflicts quickly if it would help.