VegaLIte Charts Rendering - Elixir, Phoenix, SurfaceUI

382 Views Asked by At

How VegaLite charts can be rendered in Elixir, Phoenix, SurfaceUI component ?

alias VegaLite, as: Vl

# Initialize the specification, optionally with some top-level properties
Vl.new(width: 400, height: 400)

# Specify data source for the graphic, see the data_from_* functions
|> Vl.data_from_values(iteration: 1..100, score: 1..100)
# |> Vl.data_from_values([%{iteration: 1, score: 1}, ...])
# |> Vl.data_from_url("...")

# Pick a visual mark for the graphic
|> Vl.mark(:line)
# |> Vl.mark(:point, tooltip: true)

# Map data fields to visual properties of the mark, like position or shape
|> Vl.encode_field(:x, "iteration", type: :quantitative)
|> Vl.encode_field(:y, "score", type: :quantitative)

So far, I tried in this way.

defmodule CfiAppWeb.Dashboard do
  @moduledoc """
  LiveView for the dashboard
  """
  use Surface.LiveView
  alias VegaLite, as: Vl

  def render(assigns) do
    ~F"""
      <main class="container mx-auto p-4" >
        <div>
          <h1>This is dashbaord</h1>
          <div>{render_graph()}</div>
        </div>
      </main>
    """
  end

  def render_graph() do
    Vl.new(width: 400, height: 400)
      |> Vl.mark(:line)
      |> Vl.encode_field(:x, "x", type: :quantitative)
      |> Vl.encode_field(:y, "y", type: :quantitative)
  end
end

I also use Surface LiveView Components. Usually we can render this kind charts by id in Javascript but in here I can't find a way to render Vega Charts.

1

There are 1 best solutions below

0
On

According to the error you receive

protocol Phoenix.HTML.Safe not implemented for %VegaLite{…}

you attempt to render a VegaLite struct where HTML is expected.

VegaLite documentation states that one can use to_html/1 to get html back, but I’d better implement a protocol Phoenix.HTML.Safe for %VegaLite{…} myself and provide a PR to VegaLite for everyone to enjoy it.