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

budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
juhalehtonen
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New
axelson
Hi there! :wave: @frigidcode and I (but mostly him) have been running an Elixir Book club, we’re almost done with Designing Elixir Syste...
New
achempion
I’ve been using Emacs as my main code editor for more than a two years. It’s a custom build version although I’ve tried doom emacs and sp...
New
budgie
I love Elixir. It’s one of 2 programming languages I’ve ever fallen in love with. But I don’t use it anymore. Serverless was the promis...
New
jtormey
Lately I’ve been thinking about how to organize components as a LiveView application grows. One of the pain points I’ve found (for myself...
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

KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
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
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
kip
In 2021 I started a new library called Tempo with the objective of modelling time as a set of intervals - not as instants. In 2022 I gave...
New
OndrejValenta
(I just needed to vent somewhere and LinkedIn is full of hope, or hype, I’m not sure which exactly) AI dream has many faces, but general...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews