From 327d7fa2d9a44c090963dd7598a24cf3043a31e5 Mon Sep 17 00:00:00 2001 From: Bart Broere Date: Sat, 9 Mar 2024 00:37:03 +0100 Subject: [PATCH] Evaluate all script (grand)children of HTML output to render output of 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 --- packages/starboard-python/src/global.ts | 2 +- packages/starboard-python/src/run.ts | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/packages/starboard-python/src/global.ts b/packages/starboard-python/src/global.ts index 59face4d..fc53fb32 100644 --- a/packages/starboard-python/src/global.ts +++ b/packages/starboard-python/src/global.ts @@ -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); diff --git a/packages/starboard-python/src/run.ts b/packages/starboard-python/src/run.ts index a7a70594..f63064da 100644 --- a/packages/starboard-python/src/run.ts +++ b/packages/starboard-python/src/run.ts @@ -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({ @@ -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)