View Source Kino.SmartCell behaviour (Kino v0.10.0)

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

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

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

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: [attribute: "code", language: "elixir"]}
end

options

Options

  • :attribute - the key to put the source text under in attrs. Required

  • :language - the editor language, used for syntax highlighting. Defaults to nil

  • :placement - editor placement within the smart cell, either :top or :bottom. Defaults to :bottom

  • :default_source - the initial editor source. Defaults to ""

other-options

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 to false

Link to this section Summary

Types

Attributes are an intermediate form of smart cell state, used to persist and restore cells.

Callbacks

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.

Link to this section 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()}

Link to this section Callbacks

Link to this callback

scan_binding(server, binding, t)

View Source (optional)
@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.

Link to this callback

scan_eval_result(server, eval_result)

View Source (optional)
@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.

@callback to_source(attrs()) :: String.t() | [String.t()]

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.

Link to this section Functions

Returns a list of available smart cell definitions.

Link to this function

prefixed_var_name(prefix, var_name)

View Source
@spec prefixed_var_name(String.t(), String.t() | nil) :: String.t()

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.

Link to this function

quoted_to_string(quoted)

View Source
@spec quoted_to_string(Macro.t()) :: String.t()

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

Examples

Kino.SmartCell.register(KinoDocs.CustomCell)
Link to this function

valid_variable_name?(string)

View Source
@spec valid_variable_name?(String.t()) :: boolean()

Checks if the given string is a valid Elixir variable name.