View Source Kino.JS (Kino v0.14.0)
Allows for defining custom JavaScript powered kinos.
Example
Here's how we could define a minimal kino that embeds the given HTML directly into the page.
defmodule KinoDocs.HTML do
use Kino.JS
def new(html) do
Kino.JS.new(__MODULE__, html)
end
asset "main.js" do
"""
export function init(ctx, html) {
ctx.root.innerHTML = html;
}
"""
end
end
Let's break down the API.
To define a custom kino we need to create a new module. In this
case we go with KinoDocs.HTML
.
We start by adding use Kino.JS
, which makes our module
asset-aware. In particular, it allows us to use the asset/2
macro to define arbitrary files directly in the module source.
All kinos require a main.js
file that defines a JavaScript
module and becomes the entrypoint on the client side. The
JavaScript module is expected to export the init(ctx, data)
function, where ctx
is a special object (discussed in
detail later) and data
is the kino data passed from the
Elixir side. In our example the init
function accesses the
root element with ctx.root
and overrides its content with
the given HTML string.
Finally, we define the new(html)
function that creates kinos
with the given HTML. Underneath we call Kino.JS.new/2
specifying our module as the kino type and passing the data
(available in the JavaScript init
function later). Again,
it's a convention for each kino module to define a new
function to provide uniform experience for the end user.
Assets
We already saw how to define a JavaScript (or any other) file
using the asset/2
macro, however in most cases it's preferable
to put assets in a dedicated directory to benefit from syntax
highlighting and other editor features. To do that, we just need
to specify where the corresponding directory is located:
use Kino.JS, assets_path: "lib/assets/html"
The default entrypoint file is main.js
, however you can override
it by setting the :entrypoint
option. The entrypoint must be a
path relative to the assets path.
Stylesheets
The ctx.importCSS(url)
function allows us to load CSS from the given
URL into the page. The stylesheet can be an external resource, such as
a font from Google Fonts or a custom asset (as outlined above). Here's
an example of both:
defmodule KinoDocs.HTML do
use Kino.JS
def new(html) do
Kino.JS.new(__MODULE__, html)
end
asset "main.js" do
"""
export function init(ctx, html) {
ctx.importCSS("https://fonts.googleapis.com/css?family=Sofia")
ctx.importCSS("main.css")
ctx.root.innerHTML = html;
}
"""
end
asset "main.css" do
"""
body {
font-family: "Sofia", sans-serif;
}
"""
end
end
URLs
When using multiple asset files, make sure to use relative URLs. For example, when adding an image to the page, instead of:
<img src="/images/cat.jpeg" />
Do:
<img src="./images/cat.jpeg" />
This will correctly point to the images/cat.jpeg
file in your
assets.
Security
Note that all assets are assumed public and Livebook doesn't enforce authentication when loading them. Therefore, never include any sensitive credentials in the assets source, instead pass them as arguments from your Elixir code.
JavaScript API
In the example we briefly introduced the ctx
(context) object
that is made available in the init(ctx, data)
function. This
object encapsulates all of the Livebook-specific API that we can
call on the JavaScript side.
Properties
ctx.root
- the root element controlled by the kino
Functions
ctx.importCSS(url)
- loads CSS from the given URL into the page. Returns aPromise
that resolves once the CSS is loadedctx.importJS(url)
- loads JS from the given URL into the page using a regular<script>
tag. Returns aPromise
that resolves once the JS is loadedctx.handleEvent(event, callback)
- registers an event handler. Onceevent
is broadcasted,callback
is executed with the event payload. This applies toKino.JS.Live
kinosctx.pushEvent(event, payload)
- sends an event to the kino server, where it is handled withKino.JS.Live.handle_event/3
. This applies toKino.JS.Live
kinosctx.handleSync(callback)
- registers a synchronization handler, it should flush any deferred UI changes to the server. This applies toKino.SmartCell
cellsctx.selectSecret(callback, preselectName)
- asks the user to select a Livebook secret. SuggestspreselectName
as the default choice. When the user selects a secret,callback
is called with the secret name
Dependencies
On the JavaScript side you are free to use any external packages and
bundling tooling, as long as you provide the main.js
file with the
init(ctx, data)
entrypoing. Kino itself defines a couple components
using Kino.JS
and we use esbuild to
bundle their assets, but it's entirely up to you.
For simple components that don't require additional dependencies, it may be totally fine to write a single JS/CSS file without any bundling. Theoretically, you could even import dependencies from a CDN, however, we do recommend bundling dependencies with your assets because: (a) occasionally content from CDNs may get blocked; (b) most users run Livebook locally, so fetching assets from the local server is actually faster than fetching from a CDN; (c) nowadays many packages actually assume their end users use a bundler.
To give a concrete example, let's say we want to render a graph using
mermaid
. We would define an NPM project at assets/mermaid
, with
regular package.json
and the following main.js
file:
import mermaid from "mermaid";
mermaid.initialize({ startOnLoad: false });
export function init(ctx, graph) {
mermaid.render("graph1", graph, (svgSource, bindListeners) => {
ctx.root.innerHTML = svgSource;
bindListeners && bindListeners(ctx.root);
});
}
Next, we would bundle the file into lib/assets/mermaid/build/main.js
,
and reference in our Elixir module:
defmodule KinoDocs.Mermaid do
use Kino.JS
use Kino.JS, assets_path: "lib/assets/mermaid/build"
def new(graph) do
Kino.JS.new(__MODULE__, graph)
end
end
With all that, we would use the component like so:
KinoDocs.Mermaid.new("""
graph TD;
A-->B;
A-->C;
B-->D;
C-->D;
""")
Directory structure
Note that we intentionally suggest keeping the NPM project in the
assets/
directory, but placing the bundle output inlib/assets/
. This convention ensures that you do not include the assets source (includingnode_modules/
) in the Hex package, but you do include the bundled assets. While it is possible to specify which directories are published to Hex, following the convention makes everything work as expected by default.
Live kinos
So far we covered the API for defining static kinos, where the
JavaScript side only receives the initial data and there is no
further interaction with the Elixir side. To introduce such
interaction, see Kino.JS.Live
as a next step in our discussion.
Summary
Types
@opaque t()
Functions
Defines an asset file.
This serves as a convenience when prototyping or building simple kinos, otherwise you most likely want to put assets in separate files. See the Assets for more details.
Examples
asset "main.js" do
"""
export function init(ctx, data) {
...
}
"""
end
asset "main.css" do
"""
.box {
...
}
"""
end
Instantiates a static JavaScript kino defined by module
.
The given data
is passed directly to the JavaScript side during
initialization.
Options
:export
- a function called to export the given kino to Markdown. See the "Export" section below
Export
The output can optionally be exported in notebook source by specifying
an :export
function. The function receives data
as an argument
and should return a tuple {info_string, payload}
. info_string
is used to annotate the Markdown code block where the output is
persisted. payload
is the value persisted in the code block. The
value is automatically serialized to JSON, unless it is already a
string.
For example:
data = "graph TD;A-->B;"
Kino.JS.new(__MODULE__, data, export: fn data -> {"mermaid", data} end)
Would be rendered as the following Live Markdown:
```mermaid
graph TD;A-->B;
```
Export function
You should prefer to use the
data
argument for computing the export payload. However, if it cannot be inferred fromdata
, you should just reference the original value. Do not put additional fields indata
, just to use it for export.