notebook.js

repository·master·Indexed 43 days ago

https://github.com/jsvine/notebookjs

A 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.

Tokens
2.4K
Snippets
8
Records
14
Agent score
55%

What's inside notebookjs

  1. Style rendered notebooks with CSS

    master
    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.
  2. Install and use notebook.js in the Browser

    master

    To use notebook.js in the browser, include the script via a <script> tag. You can then parse a raw .ipynb JSON 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>
  3. Install and use notebook.js in Node.js

    master

    To use notebook.js in a Node.js environment, install the package via npm and use the parse method on the imported module. The render() 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);
  4. Enable MathJax / LaTeX / KaTeX support

    master
    To 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.
  5. How notebook.js abstractions work together

    master

    The library follows a hierarchical structure that mirrors the notebook format:

    1. nb.Notebook: The top-level container. It holds metadata and one or more Worksheet objects.
    2. nb.Worksheet: A collection of Cell objects.
    3. nb.Cell: The fundamental unit of content. Cells can be of type code, markdown, heading, or raw.
      • Code Cells contain an nb.Input (the source code) and one or more nb.Output objects.
      • nb.Input: Handles rendering the source code, applying syntax highlighting, and setting the language via data-language attributes.
      • 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., preferring image/png over text/plain).

    To render a full notebook, you call .render() on the Notebook instance, which recursively calls .render() on its worksheets, cells, inputs, and outputs.

  6. Configure HTML and Markdown sanitization

    master

    On Node.js, DOMPurify is used by default. In the browser, you must provide DOMPurify yourself to enable default behavior. You can provide a custom sanitizer by setting nb.sanitizer to a function that accepts a raw HTML string and returns a sanitized version. To disable sanitization entirely, set nb.sanitizer to an identity function.

    // To disable sanitization
    nb.sanitizer = function (x) { return x; };
  7. Enable JavaScript execution in notebooks

    master

    JavaScript in notebooks is disabled by default to prevent XSS attacks. To enable execution for trusted notebooks, set the nb.executeJavaScript option to true before calling nb.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);
  8. Implement a custom code highlighter

    master

    You 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 (if undefined, the text is not code).
    • lang: The language of the code in the cell (if undefined, the text is not code).

    The function must return at least the original text value 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);
        };
  9. Configure Markdown and ANSI-coloring engines

    master
    By default, Node.js uses marked for Markdown and ansi_up for 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 to nb.markdown and nb.ansi respectively.
  10. Configure notebook.js engines and behavior

    master

    The nb namespace 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 if marked is not available.
    • nb.ansi: A function used to convert ANSI escape codes to HTML. Defaults to an identity function if ansi_up is not available.
    • nb.sanitizer: A function used to sanitize HTML. Defaults to an identity function if DOMPurify is not available.
    • nb.highlighter: A function used for code syntax highlighting. Defaults to an identity function.
    • nb.executeJavaScript: A boolean flag. If true, application/javascript outputs will be rendered as <script> elements. If false (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 */ };
  11. Parse and render a notebook with nb.parse()

    master

    Use nb.parse(nbjson, config) to create a Notebook instance 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);
  12. Reference: nb.display functions

    master

    The nb.display object contains the core rendering logic for different MIME types. These are used by nb.Output to 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 configured nb.markdown engine.
    • nb.display.svg(svg): Renders SVG content.
    • nb.display.latex(latex): Renders LaTeX. If root.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> (if nb.executeJavaScript is true) or a <pre> block.
    • nb.display.png(data) / nb.display.jpeg(data): Renders base64 encoded images.