Skip to content

Commit

Permalink
Evaluate all script (grand)children of HTML output to render output o…
Browse files Browse the repository at this point in the history
…f Bokeh and Plotly (#138)

* [WIP] Evaluate all script (grand)children of HTML output

* Improvements

* Remove TODO since it's probably resolved

* Update run.ts

* Update run.ts

* Also do this for plain HTML elements, not just for Python objects with _repr_html_

* Move line comment up and refer to it

* Fix typo
  • Loading branch information
bartbroere committed Mar 8, 2024
1 parent 4127a59 commit 327d7fa
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/starboard-python/src/global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ function drawCanvas(pixels: number[], width: number, height: number) {
canvas.height = height;
const ctx = canvas.getContext("2d");
if (!ctx) {
console.warn("Failed to aquire canvas context");
console.warn("Failed to acquire canvas context");
return;
}
ctx.putImageData(image, 0, 0);
Expand Down
17 changes: 17 additions & 0 deletions packages/starboard-python/src/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,15 @@ export async function runStarboardPython(

if (val instanceof HTMLElement) { // A plain HTML element
htmlOutput.appendChild(val);
// Just putting HTML with script tags on the DOM will not get them evaluated
// Using this hack we execute them anyway
val.querySelectorAll('script[type|="text/javascript"]').forEach(
function(e) {
if (e.textContent !== null) {
eval(e.textContent);
}
}
)
} else if (typeof val === "object" && val.name === "PythonError" && val.__error_address) { // A python error
error = val;
outputElement.addEntry({
Expand All @@ -69,6 +78,14 @@ export async function runStarboardPython(
div.className = "rendered_html cell-output-html";
div.appendChild(new DOMParser().parseFromString(result, "text/html").body.firstChild as any);
htmlOutput.appendChild(div);
// Evaluate all script tags manually, see previous comment
div.querySelectorAll('script[type|="text/javascript"]').forEach(
function(e) {
if (e.textContent !== null) {
eval(e.textContent);
}
}
)
hadHTMLOutput = true;
}
} else if (val._repr_latex_ !== undefined) { // It has a LateX representation (e.g. Sympy output)
Expand Down

0 comments on commit 327d7fa

Please sign in to comment.