livebook-dev / kino

Client-driven interactive widgets for Livebook
Apache License 2.0
372 stars 65 forks source link

How do I use the Collaborative Editor in a custom Kino.SmartCell? #169

Closed BrooklinJazz closed 2 years ago

BrooklinJazz commented 2 years ago

Hi there!

I'm attempting to build a Kino.SmartCell that will automatically run tests. It looks there's an awesome option to include a code editor in a smart cell: https://hexdocs.pm/kino/Kino.SmartCell.html#module-collaborative-editor that would be a perfect fit for my use case.

However, I can't seem to make it work. I'd be happy to contribute an example to the documentation once I get this working (if desired).

Here's my stupid simple SmartCell.

defmodule Kino.SmartCell.TestRunner do
  use Kino.JS
  use Kino.JS.Live
  use Kino.SmartCell, name: "Test Runner"

  @impl true
  def init(attrs, ctx) do
    {:ok, assign(ctx, editor: [attribute: "code", language: "elixir"])}
  end

  @impl true
  def handle_connect(ctx) do
    {:ok, %{}, ctx}
  end

  @impl true
  def to_attrs(ctx) do
   %{}
  end

  @impl true
  def to_source(attrs) do
    ""
  end

  asset "main.js" do
    """
    export function init(ctx, payload) {

      ctx.root.innerHTML = `
        Hello
      `;
    }
    """
  end
end

Kino.SmartCell.register(Kino.SmartCell.TestRunner)

This renders the following in LiveBook but there's no code editor. image

I'm sure I'm doing something wrong, and would greatly appreciate your help! 🙏

josevalim commented 2 years ago

Just as a heads up, take a look at kino_db. We have one with editor there!

BrooklinJazz commented 2 years ago

Thank you! I will check that out!

BrooklinJazz commented 2 years ago

Got it working! It was a silly mistake. I put :editor in the assigns 🤦‍♂️Don't think there's any documentation change needed. The issue was between the chair and the keyboard on this one. Thank you @josevalim!

The working module is:

defmodule Kino.SmartCell.TestRunner do
  use Kino.JS
  use Kino.JS.Live
  use Kino.SmartCell, name: "Test Runner"

  @impl true
  def init(attrs, ctx) do
    {:ok, ctx, editor: [attribute: "code", language: "elixir"]}
  end

  @impl true
  def handle_connect(ctx) do
    {:ok, %{}, ctx}
  end

  @impl true
  def to_attrs(ctx) do
    %{}
  end

  @impl true
  def to_source(attrs) do
    ""
  end

  asset "main.js" do
    """
    export function init(ctx, payload) {

      ctx.root.innerHTML = `
        Hello
      `;
    }
    """
  end
end

Kino.SmartCell.register(Kino.SmartCell.TestRunner)

Closing this issue!

jonatanklosko commented 2 years ago

FTR there are some examples with editor in the "Exploring Smart cells" notebook on the explore page :)