ijs

Simple library to support working within the iJavaScript kernel within Jupyter

Note that this is available as ijs from within the jupyter-ijavascript-utils module

  • Asynchronous Methods
    • ijs.await - Helper function to support Await / Async functions in iJavaScript
    • ijs.asyncConsole - Utility function for consoling a value in a .then() clause
    • ijs.asyncWait - Utility function for waiting x seconds between promise resolutions
  • iJavaScript Context Detection
  • Introspection
  • Rendering

For example:

//-- get the data
//-- fetch the data
//-- and do not execute the next cell until received.
utils.ijs.await(async ($$, console) => {
 barley = await utils.datasets.fetch('barley.json');
})
//-- use the data as though it was synchronously received

//-- get the min max of the types of barley
barleyByVarietySite = d3.group(barley, d => d.variety, d => d.site)
//-- now group by variety and year
barleyByVarietyYear = d3.group(barley, d => d.variety, d => d.year)

then later

utils.ijs.listGlobals();
// ['barley','d3','barleyByVariety','barleyByVarietySite',...]

Or passing NodeJS variables to JavaScript

(See ijs.htmlScript for more)

utils.ijs.htmlScript({
    scripts: ['https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js'],
    height: '100%',
    onReady: ({rootEl}) => {
        new QRCode(rootEl, "https://jupyter-ijavascript-utils.onrender.com/");
    }
});

Screenshot of QR Code

Methods

(static) asyncConsole(message) → {function}

Simple promise chain for sending a console message

Example
Promise.resolve(200)
 .then(utils.ijs.asyncWait(2))
 .then(utils.ijs.asyncConsole('after waiting for 2 seconds'))
 .then((results) => console.log('results passed through: ${results}`));

//--
after waiting for 2 seconds
results passed through: 200
Parameters:
Name Type Description
message String

the message to be sent to console

Returns:
  • (results) => results passthrough
Type
function

(static) asyncWait(seconds) → {function}

Simple promise chain for waiting N seconds.

Example
Promise.resolve(200)
 .then(utils.ijs.asyncConsole('before waiting for 2 seconds'))
 .then(utils.ijs.asyncWait(2))
 .then(utils.ijs.asyncConsole('after waiting for 2 seconds'))
 .then((results) => console.log('results passed through: ${results}`));

//--
before waiting for 2 seconds
after waiting for 2 seconds
results passed through: 200
Parameters:
Name Type Description
seconds Number

the number of seconds to wait

Returns:
  • (results) => results passthrough
Type
function

(static) await()

Allow for asynchronous programming within iJavaScript nodes.

Screenshot

Example
utils.ijs.await(async ($$, console) => {
   //-- $$ is the display for the current cell
   //-- console is the console for the current cell
   
   barley = await utils.datasets.fetch('barley.json');
   
   console.log(`retrieved:${barley.length} nodes`);

   // return will be the value sent to $$.sendResults()
   // and shown alongside console
   return barley.slice(0,1)
})

//-- outputs

retrieved:120 nodes

[
 {
   yield: 27,
   variety: 'Manchuria',
   year: 1931,
   site: 'University Farm'
 }
]

(static) detectContext() → {IJavaScriptContext}

Determines the current global display and console from iJavaScript (or null if not within iJavaScript)

Returns:
  • ({ display, console }) or null if not within iJavaScript
Type
IJavaScriptContext

(static) detectIJS() → {Boolean}

Determines if we are currently within the iJavaScript context

Returns:
  • true if the code is running within an iJavaScript kernel
Type
Boolean

(static) htmlScript(options)

Generates and renders an html block that loads external css and javascript.

For example, allows running browser side d3js in a Jupyter cell, Leaflet, etc.

Remember, your cells in Jupyter are running in NodeJS.

Once all the files have loaded, then onReady will execute in JavaScript.

Note that only the function in onReady is executed in JavaScript (i.e. Data from other cells in Jupyter would normally not be available).

If data is needed from jupyter, pass them through options.data. (ex: airportData example below)

For More - See the htmlScript tutorial.

Example

For example using a cdn library for qr codes

utils.ijs.htmlScript({
    scripts: ['https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js'],
    height: '100%',
    onReady: ({rootEl}) => {
        new QRCode(rootEl, "https://jupyter-ijavascript-utils.onrender.com/");
    }
});

Screenshot of QR Code

Or working with Leaflet - to show maps

//-- nodeJS Variable
airportData = { ohareORD: { lat: 41.975813, lon: -87.909428, title: "O'Hare Intl Airport" } };
//-- render out html
utils.ijs.htmlScript({
    scripts: ['https://unpkg.com/leaflet@1.6.0/dist/leaflet.js',
              'https://unpkg.com/leaflet-providers@1.13.0/leaflet-providers.js'],
    css: ['https://unpkg.com/leaflet@1.6.0/dist/leaflet.css'],
    data: airportData,
    height: 150,
    //-- function will be executed in javaScript
    onReady: ({rootEl, data}) => {
        // L is globally available from the leaflet.js script.
        
        //-- capture the nodeJS data and use in JavaScript. Neat!
        ohareORD = data.ohareORD;

        map = L.map(rootEl);
        map.setView([ohareORD.lat, ohareORD.lon], 14);
        
        new L.marker([ohareORD.lat, ohareORD.lon]).bindPopup(ohareORD.title).addTo(map);
        
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
           attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        }).addTo(map);
    }
});

Screenshot of Leaflet

Parameters:
Name Type Description
options Object

additional options available during rendering

Properties
Name Type Attributes Default Description
onReady String | function

JavaScript to run once all files have loaded

Properties
Name Type Attributes Description
rootEl Element

results div container

data any <optional>

the options.data parameter

utilityFunctions Object

the options.utilityFunctions object

options Object

the options object passed

animate Object

alias to requestAnimationFrame with additional checks to avoid leaks

scripts Array.<String> <optional>
[]

Array of JavaScript file addresses to load

css Array.<String> <optional>
[]

Array of CSS file addresses to load

data any <optional>

any nodejs data you would like available in javaScript

html String <optional>
''

html elements to include within the result

width String | Number <optional>
'100%'

width of the div container (ex: 400 or '400px')

height String | Number <optional>
'200px'

height of the div container (ex: 200 or '200px')

debug Boolean <optional>
false

whether to incude a debugger breakpoint (once scripts are loaded)

console Boolean <optional>
true

whether to include console statements

(static) listGlobals() → {Array.<String>}

See:

List the globals currently defined.

This can be very useful when keeping track of values after a few cells.

For example:

cars = utils.datasets.fetch('cars.json').then(data => global.cars = data);

then later

utils.ijs.listGlobals();
// cars
Returns:
  • list of the global variables
Type
Array.<String>

(static) listStatic(target) → {Array.<StaticMember>}

See:

List the static members and functions of a class.

Example
utils.ijs.listStatic(utils.ijs)
// [{type:'function', constructor:'Function', isMethod:true, name:'listStatic'}, ...]
Parameters:
Name Type Description
target class

the target class

Returns:
Type
Array.<StaticMember>

(static) markdown(markdownText)

Prints markdown if in the context of iJavaScript.

This can be deceptively helpful, as it allows your text to be data driven:

Screenshot of markdown

Example
utils.ijs.markdown(`# Overview
This is markdown rendered in a cell.`);
Parameters:
Name Type Description
markdownText String

The markdown to be rendered