derpycoder

derpycoder

I didn’t think I could do it, but after getting the hang of the Hooks, I have created a tool that I really needed in front-end web development space.

I can barely remember what I worked on today, let alone the file I worked on. So when I get thrown into a project or get asked to work on a web component that was built by my colleagues, I get lost in the labyrinthian code.

Here’s my best attempt at solving that issue:

Source Code Viewer


The tooltip has 2 icons, 1 that leads to the source code, and the other will lead to the Storybook components page. Which I haven’t implemented yet.

Also, this is currently restricted to dev, but I wish to enable it for prod as well. We can enable the inspector like we enable latency sim, and clicking on the show source would open up GitHub/Storybook.

And it works everywhere, see:


P.S. Just stuck figuring out a way to add multiple JS Hook. (I found out a post on Elixir Forum, by someone who figured it out and even did lazy loaded Hook!)

P.P.S. It’s not a library, just changes made across several places. I can paste the whole thing if people want. Took me a while to get the popup to work, but it was worth it.


Inspired by: https://bit.dev (Toggle the inspect button in the top right to hover over each element and see their names and link!)

I suggested this to many people, I really want this to be part of LiveView, or Storybook, or both. (See: Add dev config for injecting HTML comments around function components)


P.S. Here’s the full source code:

Showing Posts 1 to 10

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

This is fantastic. I really really like this.

I do wonder if there is a way to sort of “layer” this on top of LiveView instead of requiring each component to pass this stuff in.

derpycoder

derpycoder OP

Exactly my thought.

That’s why I suggested the same in this Git issue: Add dev config for injecting HTML comments around function components

derpycoder

derpycoder OP

Here’s the code, so others can play around with it, till the Phoenix team adds it to Phoenix 2.0!

defmodule DerpyToolsWeb.Nav do
import Phoenix.LiveView
use Phoenix.Component

def on_mount(:default, _params, _session, socket) do
  {:cont,
   socket
   |> attach_hook(:inspect_source, :handle_event, &handle_event/3)}
end

defp handle_event("inspect-source", %{"file" => file, "line" => line}, socket) do
  System.cmd("code", ["--goto", "#{file}:#{line}"])

  {:halt, socket}
end

defp handle_event(_, _, socket), do: {:cont, socket}
scope "/", DerpyToolsWeb do
  pipe_through :browser

  live_session :no_log_in_required,
    on_mount: [DerpyToolsWeb.Nav] do
    live "/", HomePageLive
    ...
  end
end

Usage

<h2
  id="test-div"
  data-file={__ENV__.file}
  data-line={__ENV__.line}
  phx-hook={Mix.env() == :dev && "SourceInspector"}
  class="..."
>
    Hover over this!
</h2>

JavaScript Side

source_inspector.js

import { computePosition, flip, offset, arrow } from "../vendor/floating-ui";

const SourceInspector = {
  mounted() {
    if (!this.el.dataset) {
      console.log("Please pass in file & line data attributes!");
      return;
    }

    const globalTooltip = document.querySelector("#inspector-tooltip");

    let tooltip = globalTooltip.cloneNode(true);
    tooltip.setAttribute("id", `inspect-${this.el.id}`);
    const inspectSourceBtn = tooltip.querySelector("#source-btn");
    const arrowElement = tooltip.querySelector("#arrow");

    this.el.addEventListener("mouseenter", () => {
      const { file, line } = this.el.dataset;

      this.el.appendChild(tooltip);

      tooltip.classList.remove("hidden");
      tooltip.classList.add("flex");

      placeTooltip(this.el, tooltip, arrowElement);

      this.el.classList.add(
        "rounded-lg",
        "outline",
        "outline-offset-4",
        "outline-pink-500"
      );

      inspectSourceBtn.setAttribute("phx-value-file", file);
      inspectSourceBtn.setAttribute("phx-value-line", line);
    });
    this.el.addEventListener("mouseleave", (e) => {
      handleMouseLeave(this.el, tooltip);
    });
  },
};

function handleMouseLeave(target, tooltip) {
  target.classList.remove(
    "rounded-lg",
    "outline",
    "outline-offset-4",
    "outline-pink-500"
  );

  tooltip.classList.add("hidden");
  tooltip.classList.remove("flex");
}

function placeTooltip(target, tooltip, arrowElement) {
  computePosition(target, tooltip, {
    placement: "top",
    middleware: [
      flip(),
      offset(8),
      arrow({
        element: arrowElement,
      }),
    ],
  }).then(({ x, y, placement, middlewareData }) => {
    Object.assign(tooltip.style, {
      left: `${x}px`,
      top: `${y}px`,
    });

    const { x: arrowX, y: arrowY } = middlewareData.arrow;

    const staticSide = {
      top: "bottom",
      right: "left",
      bottom: "top",
      left: "right",
    }[placement.split("-")[0]];

    Object.assign(arrowElement.style, {
      left: arrowX != null ? `${arrowX}px` : "",
      top: arrowY != null ? `${arrowY}px` : "",
      right: "",
      bottom: "",
      [staticSide]: "-10px",
    });
  });
}

export default SourceInspector;

app.js

import SourceInspector from "./source_inspector";

let liveSocket = new LiveSocket("/live", Socket, {
  params: {
    _csrf_token: csrfToken,
  },
  hooks: {
    SourceInspector,
  },
});

N.B. Don’t forget to add this in the environment variable:
export ELIXIR_EDITOR="code --goto __FILE__:__LINE__"

This way, the Beam instance will know to open the VS Code editor!


P.S. I used float-ui, which is the next iteration of Popper.js, for the tooltip.

Just download the ESM files from JS Delivr, i.e.

D4no0

D4no0

Love the approach! I think that you are into something great, as I think that we failed as developers to find a human-compatible way to build complex systems.

I always loved things like scratch, they present building blocks that are very similar to the way we write code, capable of building complex tings, and it can be operated by a 8 year old kid.

derpycoder

derpycoder OP

That, plus I have a major qualm with the current state of Web Development:

  1. There’s a lack of a tool, as universal and unchanging as a Guitar. (Why does Node.js exist? It’s just a time-sink to debug. :bug:)
  2. The wrapper-around-wrapper approach that’s nuking performance back to the 1980s. (Microsoft Teams and it’s slow as heck next version is being shoved down our throat as fast! :turtle:)
  3. Code rot, in projects built with nearsighted frameworks. (My angular project, which I built 5 years back, doesn’t run anymore. :cross_mark:)
  4. Complexity that has crept into the tooling. (Webpack at work, compiles our project which is written in an Interpreted language, at a snail’s pace. :snail:)

I wanted to quit this field. But decided to stick around because of Elixir, Phoenix & Live View.

Hope it pans out.

linusdm

linusdm

This makes me think of a feature that is also in the Smalltalk webframework seaside.st. There it’s called a halo decoration there. You can see it in action here: https://book.seaside.st/book/fundamentals/rendering-components/fun-with-canvas#scrap2

I can remember it was a really nice workflow to be able to toggle between a render mode and source mode. I think one of the buttons also brought you straight to the implementation of the component (in this case, inside the smalltalk image, which is another beast entirely, but it could also work to bring you to the correct file inside your IDE).
In any case, it also made clear how your components were nested, and what the structure was of your entire page.

D4no0

D4no0

This is something that is present in a lot of google products, one that I closely hate is the native android development.

Sometimes I have a feeling that all the new features and ways to write code are designed in an agile system, kind of a innovation with timelines, witch is not only stupid sounding, but impossible to achieve.

derpycoder

derpycoder OP

That’s awesome.

Being able to toggle the editor view and the rendered view. (Kind of like LiveBook 2.0.)

So, we see the components we build, then inline make the change to the code, and then render and the source code is replaced with the rendered view.

Then all the changes we make in the browser-based IDE are written back to the file. So we won’t even have to jump back to the VS Code or any other external IDE.

Just REPL it directly on the browser.

linusdm

linusdm

It’s closely related to what’s called REPL-driven-development. I don’t know if Elixir is capable of what’s being described in that article (e.g. with the breakloop) and can stand next to Smalltalk and lisp/Clojure in that regard.

derpycoder

derpycoder OP

Actually, Jose Valim intends to build real-time code, REPL-based development. See:

https://github.com/livebook-dev/livebook/issues/1351

Where Next? Top

Trending in Discussions Top

AstonJ
As the title says, please share what you’ve been up to with Elixir. Whether that’s been learning it, looking into it, making stuff with i...
2977 94592 917
New
cblavier
Hey there, It’s been more than a year since we started using LiveView as our main UI library and building a whole library of UI componen...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
heathen
Quite interesting article Google brought me. Didn’t find any mentions about it here. What do you think in general? Would you use togethe...
New
AstonJ
Since we have deprecated our Erlang sections (as we have dedicated Erlang Forums now) let’s add this thread for those who’d like to post ...
New
maennchen
:warning: Security advisory: Decimal DoS vulnerability A vulnerability has been published for decimal where very large exponents can cau...
New
Null-logic-0
What IDE or editor are you using for Elixir development? Personally, I use Zed, and I really like it, but sometimes I wish there were a ...
New

Other Trending Topics Top

marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New
webofbits
Aludel - LLM Evaluation Workbench Aludel is an embeddable Phoenix LiveView dashboard for evaluating and comparing LLM prompts across mult...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews