Skip to content

Commit e3b9563

Browse files
larsonerclaude
andcommitted
refactor: confine embed fix-ups to the scraper
Keep only the minimal sizing fix in basedatatypes (_repr_html_ fallback sizes like the html renderers). The dark-page card and the after-load resize now come from a single idempotent fix-up block the scraper appends to any code block that displayed a figure: repr-captured embeds and the scraper's own embeds both sit in an output_subarea div, so one :has() rule styles both, and one guarded listener resizes every figure. No more per-figure uuid/script plumbing outside scraper code. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
1 parent 9b6cceb commit e3b9563

4 files changed

Lines changed: 52 additions & 76 deletions

File tree

‎plotly/basedatatypes.py‎

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -825,21 +825,14 @@ def _repr_html_(self):
825825
if "text/html" in bundle:
826826
return bundle["text/html"]
827827
else:
828-
import uuid
829-
830-
from plotly.io._utils import embed_in_output_card, resize_after_load_script
831-
832-
div_id = str(uuid.uuid4())
833828
# Size like the html renderers do: "100%" height collapses or
834829
# overflows in plain-HTML consumers such as sphinx-gallery.
835-
html = self.to_html(
830+
return self.to_html(
836831
full_html=False,
837832
include_plotlyjs="cdn",
838833
default_width="100%",
839834
default_height=525,
840-
div_id=div_id,
841835
)
842-
return embed_in_output_card(html + resize_after_load_script(div_id))
843836

844837
def _repr_mimebundle_(self, include=None, exclude=None, validate=True, **kwargs):
845838
"""

‎plotly/io/_sg_scraper.py‎

Lines changed: 34 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,40 @@
66
import logging
77
import os
88
import textwrap
9-
import uuid
109

1110
import plotly
1211
from plotly.basedatatypes import BaseFigure
1312
from plotly.io._base_renderers import sphinx_gallery_figures
14-
from plotly.io._utils import embed_in_output_card, resize_after_load_script
1513

1614
plotly.io.renderers.default = "sphinx_gallery_png"
1715

16+
# Fix-up markup for the figures of a code block, both the ones this scraper
17+
# embeds and the repr-captured ones sphinx-gallery embeds itself (both sit in
18+
# an ``output_subarea`` div). The card keeps the light background baked into
19+
# the figures presentable on dark pages, detected via ``data-theme`` (themes
20+
# with a toggle) or the OS preference (theme-less pages); on light pages it is
21+
# invisible. The resize fixes up figures that drew while the page was still
22+
# laying out and so can be sized to a container whose width then changed.
23+
_CARD = "background:#fff;border-radius:0.25rem;padding:0.5rem"
24+
_SELECTOR = "div.output_subarea:has(.plotly-graph-div)"
25+
_FIXUP_HTML = (
26+
"<style>"
27+
f'html[data-theme="dark"] {_SELECTOR}{{{_CARD}}}'
28+
"@media (prefers-color-scheme: dark){"
29+
f'html:not([data-theme="light"]) {_SELECTOR}{{{_CARD}}}'
30+
"}"
31+
"</style>"
32+
"<script>"
33+
"if (!window.plotlySphinxGalleryResize) {"
34+
"window.plotlySphinxGalleryResize = true;"
35+
'window.addEventListener("load", function () {'
36+
'document.querySelectorAll(".plotly-graph-div").forEach('
37+
"function (gd) { Plotly.Plots.resize(gd); });"
38+
"});"
39+
"}"
40+
"</script>"
41+
)
42+
1843

1944
def plotly_sg_scraper(block, block_vars, gallery_conf, **kwargs):
2045
"""Scrape Plotly figures for galleries of examples using
@@ -86,6 +111,8 @@ def plotly_sg_scraper(block, block_vars, gallery_conf, **kwargs):
86111
# Repr-displayed figures are embedded by sphinx-gallery
87112
# itself; their static image only serves as the thumbnail.
88113
rst += _inline_html(fig_dict)
114+
if figures:
115+
rst += _raw_html_rst(_FIXUP_HTML)
89116
return rst
90117
finally:
91118
# Don't let figures leak into the next block if writing one failed.
@@ -147,26 +174,25 @@ def _inline_html(fig_dict):
147174
"""Embed a figure into the rst directly, rather than via a file.
148175
149176
The figure is wrapped in the same div that sphinx-gallery wraps captured
150-
HTML reprs in, so that themes can style both kinds of embed alike.
177+
HTML reprs in, so that the fix-up markup applies to both kinds of embed.
151178
"""
152-
div_id = str(uuid.uuid4())
153179
html = plotly.io.to_html(
154180
fig_dict,
155181
include_plotlyjs="cdn",
156182
full_html=False,
157183
default_width="100%",
158184
default_height=525,
159185
validate=False,
160-
div_id=div_id,
161186
)
162-
# The figure may draw before the page finishes laying out, ending up
163-
# sized to a container whose width then changes.
164-
html = embed_in_output_card(html + resize_after_load_script(div_id))
165187
html = (
166188
'<div class="output_subarea output_html rendered_html output_result">\n'
167189
f"{html}\n"
168190
"</div>"
169191
)
192+
return _raw_html_rst(html)
193+
194+
195+
def _raw_html_rst(html):
170196
return "\n.. raw:: html\n\n" + textwrap.indent(html, " ") + "\n"
171197

172198

‎plotly/io/_utils.py‎

Lines changed: 0 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -91,43 +91,3 @@ def plotly_cdn_url(cdn_ver=get_plotlyjs_version()):
9191
return "https://cdn.plot.ly/plotly-{cdn_ver}.min.js".format(
9292
cdn_ver=cdn_ver,
9393
)
94-
95-
96-
def resize_after_load_script(div_id):
97-
"""Script that resizes a plotly div once the page finishes loading.
98-
99-
A figure drawn while its page is still loading (e.g. one embedded in a
100-
sphinx-gallery page) can be sized to a container whose width changes by
101-
the time loading finishes, so fix it up once afterwards.
102-
"""
103-
return (
104-
"<script>(function() {"
105-
"function fit() {"
106-
f'var gd = document.getElementById("{div_id}");'
107-
"if (window.Plotly && gd) Plotly.Plots.resize(gd);"
108-
"}"
109-
'if (document.readyState === "complete") fit();'
110-
'else window.addEventListener("load", fit);'
111-
"})();</script>"
112-
)
113-
114-
115-
def embed_in_output_card(html):
116-
"""Wrap embedded-figure HTML in a card that stays legible on dark pages.
117-
118-
The figure keeps the light background baked into it, so on dark pages an
119-
edge-to-edge white slab results; a white padded card reads as intentional
120-
instead. Both dark selectors are needed: ``data-theme`` covers themes
121-
with an explicit toggle, the media query covers theme-less pages under a
122-
dark OS preference. On light pages the white-on-white card is invisible.
123-
"""
124-
card = "background:#fff;border-radius:0.25rem;padding:0.5rem"
125-
return (
126-
"<style>"
127-
f'html[data-theme="dark"] .plotly-output-card{{{card}}}'
128-
"@media (prefers-color-scheme: dark){"
129-
f'html:not([data-theme="light"]) .plotly-output-card{{{card}}}'
130-
"}"
131-
"</style>"
132-
f'<div class="plotly-output-card">{html}</div>'
133-
)

‎tests/test_io/test_sg_scraper.py‎

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -129,18 +129,17 @@ def test_scraper(gallery, image_format):
129129
for path, color in zip(gallery.paths, COLORS):
130130
root = os.path.splitext(path)[0]
131131
assert_image_color(Path(f"{root}.{image_format}"), color, image_format)
132-
# One interactive embed per figure: wrapped like sphinx-gallery wraps HTML
133-
# reprs so themes can style both alike, resized once the page finishes
134-
# laying out, and styled as a card so the light background works on dark
135-
# pages.
136-
for token in (
137-
".. raw:: html",
138-
"plotly-graph-div",
139-
'class="output_subarea',
140-
"Plotly.Plots.resize",
141-
'class="plotly-output-card"',
132+
# One interactive embed per figure, wrapped like sphinx-gallery wraps HTML
133+
# reprs, plus one fix-up block styling the embeds as cards on dark pages
134+
# and resizing them once the page finishes laying out.
135+
for token, count in (
136+
(".. raw:: html", 3),
137+
('class="plotly-graph-div"', 2),
138+
('class="output_subarea', 2),
139+
("div.output_subarea:has(.plotly-graph-div)", 2),
140+
("Plotly.Plots.resize", 1),
142141
):
143-
assert rst.count(token) == 2, token
142+
assert rst.count(token) == count, token
144143

145144
# The thumbnail must be a scraped figure rather than a "no image" default,
146145
# and one image per figure in order is what makes `thumbnail_number` work
@@ -169,7 +168,7 @@ def test_scraper_ignores_other_examples(gallery):
169168
for other in others:
170169
assert other.read_text() == "another example", f"{other.name} was scraped"
171170
assert len(gallery.paths) == 1
172-
assert rst.count(".. raw:: html") == 1
171+
assert rst.count('class="plotly-graph-div"') == 1
173172

174173

175174
def test_scraper_repr_figure(gallery):
@@ -180,7 +179,9 @@ def test_scraper_repr_figure(gallery):
180179
"""
181180
fig = go.Figure()
182181
gallery.globals["___"] = fig # as sphinx-gallery's repr capture leaves it
183-
assert gallery.scrape("fig.update_layout(title='hi')\nfig") == ""
182+
rst = gallery.scrape("fig.update_layout(title='hi')\nfig")
183+
assert 'class="plotly-graph-div"' not in rst # sphinx-gallery embeds it
184+
assert "Plotly.Plots.resize" in rst # but the fix-up block still applies
184185
assert len(gallery.paths) == 1
185186
assert_image_color(Path(gallery.paths[0]), COLORS[0])
186187
assert_image_color(gallery.thumbnail(), COLORS[0])
@@ -193,7 +194,7 @@ def test_scraper_repr_figure(gallery):
193194
# A figure both shown and repr-displayed is scraped once
194195
fig.show()
195196
rst = gallery.scrape("fig.show()\nfig")
196-
assert rst.count(".. raw:: html") == 1
197+
assert rst.count('class="plotly-graph-div"') == 1
197198
assert len(gallery.paths) == 2
198199

199200

@@ -227,14 +228,14 @@ def kaleido_warnings():
227228
rst = gallery.scrape("fig.show()")
228229

229230
# The shown figure is embedded inline instead of via files
230-
assert rst.count("plotly-graph-div") == 1
231+
assert rst.count('class="plotly-graph-div"') == 1
231232
assert gallery.paths == []
232233
(warning,) = kaleido_warnings()
233234
assert "no browser" in warning.getMessage()
234235

235236
# Only one warning per build, however many blocks follow; repr-displayed
236237
# figures are embedded by sphinx-gallery itself so they scrape to nothing
237-
assert gallery.scrape("fig") == ""
238+
assert 'class="plotly-graph-div"' not in gallery.scrape("fig")
238239
assert gallery.paths == []
239240
assert len(kaleido_warnings()) == 1
240241

@@ -249,10 +250,6 @@ def test_repr_html_fallback_size(monkeypatch):
249250
monkeypatch.setattr(pio.renderers, "default", "sphinx_gallery_png")
250251
html = go.Figure()._repr_html_()
251252
assert 'style="height:525px; width:100%;"' in html
252-
# Fixes up figures drawn while the page was still laying out
253-
assert "Plotly.Plots.resize" in html
254-
# Styled as a card so the light-background figure works on dark pages
255-
assert 'class="plotly-output-card"' in html
256253
fig = go.Figure(layout={"height": 400})
257254
assert 'style="height:400px; width:100%;"' in fig._repr_html_()
258255

0 commit comments

Comments
 (0)