C2DH / journal-of-digital-history

frontend app for our Digital Journal
GNU General Public License v3.0
20 stars 4 forks source link

Support nx-altair visualization : interactive NetworkX graphs with Altair library for Python, based on Vega and Vega-Lite #341

Closed eliselavy closed 2 years ago

eliselavy commented 2 years ago

One article use the nx-altair library to display network visualisation : https://pypi.org/project/nx-altair/

Example here: https://github.com/jdh-observer/jdh002-VeaK58WBs82C/blob/main/article-notebook_def.ipynb

The output script are available in the: "text/html"

  "outputs": [
    {
     "data": {
      "**text/html"**: [
       "\n",
       "<div id=\"altair-viz-707864a74e7d4537910a874a4e1f0df5\"></div>\n",
       "**<script type=\"text/javascript\">**\n",
       "  (function(spec, embedOpt){\n",
       "    let outputDiv = document.currentScript.previousElementSibling;\n",
       "    if (outputDiv.id !== \"altair-viz-707864a74e7d4537910a874a4e1f0df5\") {\n",
       "      outputDiv = document.getElementById(\"altair-viz-707864a74e7d4537910a874a4e1f0df5\");\n",
       "    }\n",
       "    const paths = {\n",
       "      \"vega\": \"https://cdn.jsdelivr.net/npm//vega@5?noext\",\n",
       "      \"vega-lib\": \"https://cdn.jsdelivr.net/npm//vega-lib?noext\",\n",
       "      \"vega-lite\": \"https://cdn.jsdelivr.net/npm//vega-lite@4.8.1?noext\",\n",
       "      \"vega-embed\": \"https://cdn.jsdelivr.net/npm//vega-embed@6?noext\",\n",
       "    };\n",
       "\n",
       "    function loadScript(lib) {\n",
       "      return new Promise(function(resolve, reject) {\n",
       "        var s = document.createElement('script');\n",
       "        s.src = paths[lib];\n",
       "        s.async = true;\n",
       "        s.onload = () => resolve(paths[lib]);\n",
       "        s.onerror = () => reject(`Error loading script: ${paths[lib]}`);\n",
       "        document.getElementsByTagName(\"head\")[0].appendChild(s);\n",
       "      });\n",
       "    }\n",
       "\n",
danieleguido commented 2 years ago

Fixed on PR #399

In the jupyter notebooks, for security reasons the tag <script is escaped: \x3Cscript. In trusted notebooks, I guess it is replaced. Have a look at the implementation on the ArticleCellOutputs component, where I extracted the javascript code in htmlScript[2]:

if (output.data['text/html'].some(d => d.indexOf('/script>'))) {
     const htmlScript = output.data['text/html'].join('').match(/(?<=(\x3Cscript[^>]*>))([\s\S]*?)\x3C\/script>/m)
     // ...
}