View Source Kino.SmartCell behaviour (Kino v0.14.1)
An interface for defining custom smart cells.
A smart cell is a UI wizard designed for producing a piece of code that accomplishes a specific task. In other words, a smart cell is like a code template parameterized through UI interactions.
This module builds on top of Kino.JS.Live
, consequently keeping
all of its component and communication mechanics. The additional
callbacks specify how the UI maps to source code.
Usage
Defining a custom cell is similar to writing a regular Kino.JS.Live
component, with a couple specifics.
First, we only need to define callbacks, so there is no need for
using Kino.JS.Live.new/2
. The Kino.JS.Live.init/2
callback
always receives attrs/0
as the first argument.
Second, we add a few new bits, namely use Kino.SmartCell
and the
two corresponding callback definitions.
Here is an outline of a custom module
defmodule KinoDocs.CustomCell do
use Kino.JS
use Kino.JS.Live
use Kino.SmartCell, name: "Our custom wizard"
@impl true
def init(attrs, ctx) do
...
end
# Other Kino.JS.Live callbacks
...
@impl true
def to_attrs(ctx) do
...
end
@impl true
def to_source(attrs) do
...
end
end
Additionally, in order for Livebook to pick up the custom cell, we
need to register our module. This usually happens in application.ex
Kino.SmartCell.register(KinoDocs.CustomCell)
Example
As a minimal example, that's how we can define a cell that allows editing the underlying code directly through a textarea.
defmodule KinoDocs.SmartCell.Plain do
use Kino.JS
use Kino.JS.Live
use Kino.SmartCell, name: "Plain code editor"
@impl true
def init(attrs, ctx) do
source = attrs["source"] || ""
{:ok, assign(ctx, source: source)}
end
@impl true
def handle_connect(ctx) do
{:ok, %{source: ctx.assigns.source}, ctx}
end
@impl true
def handle_event("update", %{"source" => source}, ctx) do
broadcast_event(ctx, "update", %{"source" => source})
{:noreply, assign(ctx, source: source)}
end
@impl true
def to_attrs(ctx) do
%{"source" => ctx.assigns.source}
end
@impl true
def to_source(attrs) do
attrs["source"]
end
asset "main.js" do
"""
export function init(ctx, payload) {
ctx.importCSS("main.css");
ctx.root.innerHTML = `
<textarea id="source"></textarea>
`;
const textarea = ctx.root.querySelector("#source");
textarea.value = payload.source;
textarea.addEventListener("change", (event) => {
ctx.pushEvent("update", { source: event.target.value });
});
ctx.handleEvent("update", ({ source }) => {
textarea.value = source;
});
ctx.handleSync(() => {
// Synchronously invokes change listeners
document.activeElement &&
document.activeElement.dispatchEvent(new Event("change"));
});
}
"""
end
asset "main.css" do
"""
#source {
box-sizing: border-box;
width: 100%;
min-height: 100px;
}
"""
end
end
And then we would register it as
Kino.SmartCell.register(KinoDocs.SmartCell.Plain)
Note that we register a synchronization handler on the client with
ctx.handleSync(() => ...)
. This optional handler is invoked before
evaluation and it should flush any deferred UI changes to the server.
In our example we listen to textarea's "change" event, which is only
triggered on blur, so on synchronization we trigger it programmatically.
Collaborative editor
If a smart cell requires editing some code (like SQL), it may use a dedicated editor instance managed by Livebook. The editor handles syntax highlighting and collaborative editing, similarly to the built-in cells.
To enable the editor, we need to include :editor
configuration in
options returned from the Kino.JS.Live.init/2
callback.
@impl true
def init(attrs, ctx) do
# ...
{:ok, ctx, editor: [source: "", language: "elixir"]}
end
You also need to define handle_editor_change/2
, which usually
simply stores the new source in the context.
Example
Here is a minimal example, similar to the one before, but using the editor feature.
defmodule KinoDocs.SmartCell.Editor do
use Kino.JS
use Kino.JS.Live
use Kino.SmartCell, name: "Built-in code editor"
@impl true
def init(attrs, ctx) do
source = attrs["source"] || ""
{:ok, assign(ctx, source: source), editor: [source: source]}
end
@impl true
def handle_connect(ctx) do
{:ok, %{}, ctx}
end
@impl true
def handle_editor_change(source, ctx) do
{:ok, assign(ctx, source: source)}
end
@impl true
def to_attrs(ctx) do
%{"source" => ctx.assigns.source}
end
@impl true
def to_source(attrs) do
attrs["source"]
end
asset "main.js" do
"""
export function init(ctx, payload) {
ctx.importCSS("main.css");
ctx.root.innerHTML = `Editor:`;
}
"""
end
end
Options
:source
- the initial editor source. Required:language
- the editor language, used for syntax highlighting. Defaults tonil
:placement
- editor placement within the smart cell, either:top
or:bottom
. Defaults to:bottom
:intellisense_node
- a{node, cookie}
atom tuple specifying a remote node that should be introspected for editor intellisense. This is only applicable when:language
is Elixir. Defaults tonil
:visible
- whether the editor is shown. Altering this option withKino.JS.Live.Context.reconfigure_smart_cell/2
allows the editor to be shown or hidden, depending on the smart cell state. Defaults totrue
Note that you can programmatically reconfigure some of these options
later using Kino.JS.Live.Context.reconfigure_smart_cell/2
.
Other options
Other than the editor configuration, the following options are supported:
:reevaluate_on_change
- if the cell should be reevaluated whenever the generated source code changes. This option may be helpful in cases where the cell output is a crucial element of the UI interactions. Defaults tofalse
Summary
Types
Attributes are an intermediate form of smart cell state, used to persist and restore cells.
Callbacks
Invoked when the smart cell editor content changes.
Invoked whenever the base evaluation context changes.
Invoked when the smart cell code is evaluated.
Invoked to compute the smart cell state as serializable attributes.
Invoked to generate source code based on the given attributes.
Functions
Returns a list of available smart cell definitions.
Generates unique variable names with the given prefix.
Converts the given AST to formatted code string.
Registers a new smart cell.
Checks if the given string is a valid Elixir variable name.
Types
@type attrs() :: map()
Attributes are an intermediate form of smart cell state, used to persist and restore cells.
Attributes are computed using to_attrs/1
and used to generate
the source code using to_source/1
.
Note that attributes are serialized and deserialized as JSON for persistence, hence make sure to use JSON-friendly data structures.
Persisted attributes are passed to Kino.JS.Live.init/2
as the
first argument and should be used to restore the relevant state.
@type eval_result() :: {:ok, result :: any()} | {:error, Exception.kind(), error :: any(), Exception.stacktrace()}
Callbacks
@callback handle_editor_change(source :: String.t(), ctx :: Kino.JS.Live.Context.t()) :: {:ok, ctx :: Kino.JS.Live.Context.t()}
Invoked when the smart cell editor content changes.
Usually you just want to put the new source in the corresponding assign.
This callback is required if the smart cell enables editor in the
Kino.JS.Live.init/2
configuration.
@callback scan_binding(server :: pid(), Code.binding(), Macro.Env.t()) :: any()
Invoked whenever the base evaluation context changes.
This callback receives the binding and environment available to the smart cell code.
Note that this callback runs asynchronously and it receives the PID
of the smart cell server, so the result needs to be sent explicitly
and handled using Kino.JS.Live.handle_info/2
.
Important: remember that data sent between processes is copied, so avoid sending large data structures. In particular, when looking at variables, instead of sending their values, extract and send only the relevant metadata.
Important: avoid any heavy work in this callback, as it runs in the same process that evaluates code, so we don't want to block it.
@callback scan_eval_result(server :: pid(), eval_result()) :: any()
Invoked when the smart cell code is evaluated.
This callback receives the result of an evaluation, either the return value or an exception if raised.
This callback runs asynchronously and has the same characteristics
as scan_binding/3
.
@callback to_attrs(ctx :: Kino.JS.Live.Context.t()) :: attrs()
Invoked to compute the smart cell state as serializable attributes.
Invoked to generate source code based on the given attributes.
A list of sources can be returned, in which case the sources are joined into a single source, however converting to a Code cell results in multiple cells.
Functions
Returns a list of available smart cell definitions.
Generates unique variable names with the given prefix.
When var_name
is nil
, allocates and returns the next available
name. Otherwise, marks the given suffix as taken, provided that
var_name
has the given prefix.
This function can be used to generate default variable names during smart cell initialization, so that don't overlap.
Converts the given AST to formatted code string.
@spec register(module()) :: :ok
Registers a new smart cell.
This should usually be called in application.ex
when starting
the application.
Examples
Kino.SmartCell.register(KinoDocs.CustomCell)
Checks if the given string is a valid Elixir variable name.