DEV Community

Mykolas Mankevicius
Mykolas Mankevicius

Posted on • Updated on

Phoenix Liveview - open editor for element

In your dev.exs update the live_reload config and add the web_console_logger: true key

config :no_spark, NoSparkWeb.Endpoint,
  live_reload: [
    web_console_logger: true,
    patterns: [
      ~r"priv/static/(?!uploads/).*(js|css|png|jpeg|jpg|gif|svg)$",
      ~r"priv/gettext/.*(po)$",
      ~r"lib/no_spark_web/(controllers|live|components)/.*(ex|heex)$"
    ]
  ]
Enter fullscreen mode Exit fullscreen mode

Then in your assets/js/app.js add the following!

window.addEventListener("phx:live_reload:attached", ({ detail: reloader }) => {
  // Enable server log streaming to client.
  // Disable with reloader.disableServerLogs()
  reloader.enableServerLogs()
  window.liveReloader = reloader
  let keyDown
  window.addEventListener("keydown", (event) => keyDown = event.key)
  window.addEventListener("keyup", (_) => keyDown = null)
  window.addEventListener("click", (event) => {
    if (keyDown === "c") {
      event.preventDefault()
      event.stopImmediatePropagation()
      reloader.openEditorAtCaller(event.target)
    } else if (keyDown === "d") {
      event.preventDefault()
      event.stopImmediatePropagation()
      reloader.openEditorAtDef(event.target)
    }

  })
})
Enter fullscreen mode Exit fullscreen mode

You also need to export the PLUG_EDITOR env variable:

export PLUG_EDITOR="vscode://file/__FILE__:__LINE__"
Enter fullscreen mode Exit fullscreen mode

You're welcome!!! And have a nice day!!!

Top comments (0)