notebook.js
repository·master·Indexed 43 days ago
https://github.com/jsvine/notebookjsA parser and renderer for Jupyter/IPython notebooks that converts .ipynb files into HTML. It works in both Node.js and browser environments, supporting custom Markdown engines, ANSI-coloring, HTML sanitization via DOMPurify, and custom code highlighters. Version 0.8.3.
What's inside notebookjs
- The HTML output from notebook.js does not include any default styling. To style the output, you must provide your own CSS. Each key element in the rendered notebook has specific CSS classes that can be targeted.
Install and use notebook.js in the Browser
masterTo use notebook.js in the browser, include the script via a
<script>tag. You can then parse a raw.ipynbJSON string, render it, and append the resulting DOM element to your document.<script src="notebook.js"></script> <script> var notebook = nb.parse(JSON.parse(raw_ipynb_json_string)); var rendered = notebook.render(); document.body.appendChild(rendered); </script>Install and use notebook.js in Node.js
masterTo use notebook.js in a Node.js environment, install the package via npm and use the
parsemethod on the imported module. Therender()method returns an object containing the rendered HTML (accessible via.outerHTML).var fs = require("fs"); var nb = require("notebookjs"); var ipynb = JSON.parse(fs.readFileSync("path/to/notebook.ipynb")); var notebook = nb.parse(ipynb); console.log(notebook.render().outerHTML);Enable MathJax / LaTeX / KaTeX support
masterTo support LaTeX rendering in the browser, you must manually load the KaTeX JavaScript and CSS libraries (and fonts) on your webpage. Notebook.js supports a significant subset of LaTeX via KaTeX.How notebook.js abstractions work together
masterThe library follows a hierarchical structure that mirrors the notebook format:
nb.Notebook: The top-level container. It holds metadata and one or moreWorksheetobjects.nb.Worksheet: A collection ofCellobjects.nb.Cell: The fundamental unit of content. Cells can be of typecode,markdown,heading, orraw.- Code Cells contain an
nb.Input(the source code) and one or morenb.Outputobjects. nb.Input: Handles rendering the source code, applying syntax highlighting, and setting the language viadata-languageattributes.nb.Output: Handles rendering results. It uses a priority-based system (nb.display_priority) to select the best renderer for the available data formats (e.g., preferringimage/pngovertext/plain).
- Code Cells contain an
To render a full notebook, you call
.render()on theNotebookinstance, which recursively calls.render()on its worksheets, cells, inputs, and outputs.Configure HTML and Markdown sanitization
masterOn Node.js,
DOMPurifyis used by default. In the browser, you must provideDOMPurifyyourself to enable default behavior. You can provide a custom sanitizer by settingnb.sanitizerto a function that accepts a raw HTML string and returns a sanitized version. To disable sanitization entirely, setnb.sanitizerto an identity function.// To disable sanitization nb.sanitizer = function (x) { return x; };Enable JavaScript execution in notebooks
masterJavaScript in notebooks is disabled by default to prevent XSS attacks. To enable execution for trusted notebooks, set the
nb.executeJavaScriptoption totruebefore callingnb.parse().var nb = require("notebookjs"); // Run the JavaScript in notebook. Ensure you only use this for trusted notebooks nb.executeJavaScript = true; var notebook = nb.parse(ipynb);Implement a custom code highlighter
masterYou can inject custom syntax highlighting by assigning a function to
nb.highlighter. This function is called during the rendering process and receives up to four arguments:text: The text of the cell to highlight.pre: The DOM<pre>node that holds the cell.code: The DOM<code>node that holds the cell (ifundefined, the text is not code).lang: The language of the code in the cell (ifundefined, the text is not code).
The function must return at least the original
textvalue if highlighting fails.var Prism = require('prismjs'); // Example implementation using Prismjs var highlighter = function(code, lang) { if (typeof lang === 'undefined') lang = 'markup'; if (!Prism.languages.hasOwnProperty(lang)) { try { require('prismjs/components/prism-' + lang + '.js'); } catch (e) { console.warn('** failed to load Prism lang: ' + lang); Prism.languages[lang] = false; } } return Prism.languages[lang] ? Prism.highlight(code, Prism.languages[lang]) : code; }; var nb = require("notebookjs"); nb.highlighter = function(text, pre, code, lang) { var language = lang || 'text'; pre.className = 'language-' + language; if (typeof code != 'undefined') { code.className = 'language-' + language; } return highlighter(text, language); };Configure Markdown and ANSI-coloring engines
masterBy default, Node.js usesmarkedfor Markdown andansi_upfor ANSI-coloring. The browser version does not include these. To use custom engines or enable them in the browser, assign a function that accepts raw text and returns rendered text tonb.markdownandnb.ansirespectively.Configure notebook.js engines and behavior
masterThe
nbnamespace allows you to configure the underlying engines used for rendering and customize behavior:nb.prefix: A string prefix applied to all CSS classes generated by the library (default:"nb-").nb.markdown: A function used to parse markdown. Defaults to an identity function ifmarkedis not available.nb.ansi: A function used to convert ANSI escape codes to HTML. Defaults to an identity function ifansi_upis not available.nb.sanitizer: A function used to sanitize HTML. Defaults to an identity function ifDOMPurifyis not available.nb.highlighter: A function used for code syntax highlighting. Defaults to an identity function.nb.executeJavaScript: A boolean flag. Iftrue,application/javascriptoutputs will be rendered as<script>elements. Iffalse(default), they are rendered as<pre>blocks with a warning.
nb.prefix = 'custom-prefix-'; nb.executeJavaScript = true; // You can also provide custom engines nb.highlighter = (code, pre, codeEl, lang) => { /* custom logic */ };Parse and render a notebook with nb.parse()
masterUse
nb.parse(nbjson, config)to create aNotebookinstance from a JSON representation of a notebook (nbformat). Once parsed, you can call.render()on the notebook instance to generate the DOM elements representing the notebook.// Assuming 'nbjson' is your notebook data const notebook = nb.parse(nbjson); const notebookElement = notebook.render(); document.body.appendChild(notebookElement);Reference: nb.display functions
masterThe
nb.displayobject contains the core rendering logic for different MIME types. These are used bynb.Outputto transform raw data into DOM elements:nb.display.text(text): Renders text in a<pre>block with ANSI support.nb.display.html(html): Renders HTML after sanitization.nb.display.marked(md): Renders Markdown using the configurednb.markdownengine.nb.display.svg(svg): Renders SVG content.nb.display.latex(latex): Renders LaTeX. Ifroot.renderMathInElement(e.g., KaTeX) is present in the global scope, it will attempt to render the math.nb.display.javascript(js): Renders JS as a<script>(ifnb.executeJavaScriptis true) or a<pre>block.nb.display.png(data)/nb.display.jpeg(data): Renders base64 encoded images.