larshei

larshei

Cannot figure out why my Vega plot and JS Hook do not work

I was trying to add timeline graphs to my current application.

The application uses Surface UI 0.6.1 and LiveView 0.16.x.

Throughout the application I made use of JS Hooks every now and then, e.g. to draw or update markers on a Leaflet Map and all worked very well so far.

Now I am running into 2 problems:

  1. I cannot figure out how to add vega lite to my phoenix project. I followed the Third-party JS packages
    section from GitHub - phoenixframework/esbuild: An installer for esbuild, as in running npm install in the assets directory. However, I cannot see any files being added anywhere, but the compiler is also not complaining on import vegaEmbed from 'vega-embed' . Where are the packages located? :thinking:
  2. It seems like my Hooks do not work, but I do not see a difference to the Hooks I used before. Here is the code, the console.log statement is not showing in the console output in Chrome (always using “empty cache and hard reload” when reloading the page):

JS

import vegaEmbed from 'vega-embed' 

const XyDiagram = {
  mounted() {
    this.handleEvent("draw", ({spec}) => {
      console.log("XY Diagram Hook")
      vegaEmbed(this.el, spec)
        .then((result) => result.view)
        .catch((error) => console.error(error))
    })
  },
}

export {XyDiagram}

EX

defmodule Components.XyDiagram do
  use Surface.LiveComponent

  require Logger

  prop data, :list, required: true
  prop height, :decimal, default: 200
  prop value_key, :atom, required: true

  @impl true
  def update(assigns, socket) do
    data =
      Enum.map(assigns.data, & %{x: &1.timestamp, y: &1[assigns.value_key]})

    spec =
      VegaLite.new(title: "Title", width: :container, height: :container, padding: 5)
      |> VegaLite.data_from_values(data)
      |> VegaLite.mark(:line)
      |> VegaLite.encode_field(:x, "x", type: :temporal)
      |> VegaLite.encode_field(:y, "y", type: :quantitative)
      |> VegaLite.to_spec()
      |> IO.inspect() # print looks good here :)

    {:ok, push_event(socket, "draw", %{"spec" => spec})}
  end

  @impl true
  def render(assigns) do
    ~H"""
    <div style={"width:100%; height: 300px"} id="graph" :hook="XyDiagram" phx-update="ignore" />
    """
  end
end

I am a bit lost and do not know what else to try or search for.

Can you spot what I am doing wrong here?

Most Liked

milangupta

milangupta

This is how I have mine set up … if it helps you.

assets/vendor/vega_lite.js

/* import vegaEmbed from "vega-embed"; */

/**
 * A hook used to render graphics according to the given
 * Vega-Lite specification.
 *
 * The hook expects a `vega_lite:<id>:init` event with `{ spec }` payload,
 * where `spec` is the graphic definition as an object.
 *
 * Configuration:
 *
 *   * `data-id` - plot id
 * 
 * 
 * OPTIONS : FULL LIST @ https://github.com/vega/vega-embed#options
 * Eg,
 * actions:	Boolean / Object	
 * Determines if action links ("Export as PNG/SVG", "View Source", "View Vega" 
 * (only for Vega-Lite), "Open in Vega Editor") are included with the embedded view. If the value is true, 
 * all action links will be shown and none if the value is false. This property can take a key-value mapping 
 * object that maps keys (export, source, compiled, editor) to boolean values for determining if each action 
 * link should be shown. By default, export, source, and editor are true and compiled is false. These defaults 
 * can be overridden: for example, if actions is {export: false, source: true}, the embedded visualization 
 * will have two links – "View Source" and "Open in Vega Editor". The export property can take a key-value 
 * mapping object that maps keys (svg, png) to boolean values for determining if each export action 
 * link should be shown. By default, svg and png are true.
 */


const VegaLite = {
  mounted() {
    this.id = this.el.getAttribute("data-id");
    this.viewPromise = null;

    const container = document.createElement("div");
    this.el.appendChild(container);

    this.handleEvent(`vega_lite:${this.id}:init`, ({ spec }) => {
      this.viewPromise = vegaEmbed(container, spec, {"actions": false})
        .then((result) => result.view)
        .catch((error) => {
          console.error(
            `Failed to render the given Vega-Lite specification, got the following error:\n\n    ${error.message}\n\nMake sure to check for typos.`
          );
        });
    });
  },

  destroyed() {
    if (this.viewPromise) {
      this.viewPromise.then((view) => view.finalize());
    }
  },
};

export default VegaLite;

assets/js/app.js

import VegaLite from '../vendor/vega_lite';

...

Hooks.VegaLite = VegaLite;

mix.exs

      {:vega_lite, "~> 0.1.2"},

Where Next?

Popular in Questions Top

pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
Phillipp
Hey, I have a NanoPi-M3 and try to install Elixir on their Ubuntu image. I followed the Raspberry Pi installation instructions from the ...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

Other popular topics Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 42633 214
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

We're in Beta

About us Mission Statement