KevinConti

KevinConti

I’m working with LiveView.JS for the first time. It’s one of the features that’s brought me back to LiveView on the frontend, and I feel like it was a critical piece that was missing for the community in earlier versions of the websocket-based paradigm.

By default, Phoenix comes installed with TailwindCSS. In Tailwind, transitions often occur via CSS classes. Take the following example:

<!-- When a menu is 'opened', it should receive the "block" class. When 'closed', it should receive the "hidden" class -->
<div id="mobile-menu" class="block sm:hidden">...</div>
<div id="desktop-menu" class="hidden sm:block">...</div>

This is a very common occurrence in Tailwind - transitions are almost exclusively driven via class addition and subtraction. When I went to try and apply this pattern with LiveView.JS, I was surprised to not see an obvious way to approach this.

The challenge with JS.toggle() is that the display property is directly applied via the style=display: attribute, where tailwind classes are invalid. This causes problems in the reactive example above, because the mobile menu could be toggled to be in the open state (style= display:block), and if the window is resized, this style will override the existing reactive behavior defined in tailwind (sm:hidden), causing both menus to be shown at once!

Of course, you could avoid this by using the JS.addClass and JS.removeClass functions, but that requires you to know the current state of the element to determine which function to call… meaning we’d need to keep state on the server, exactly what we are trying to avoid for something like a menu’s visibility!

I looked over the other functions available in LiveView.JS, but none seem to handle what I imagine must be an incredibly common use-case.

So, please help me out LiveView devs - am I missing something obvious? All I want is the ability to toggle two sets of arbitrary tailwind classes and let the state be contained entirely on the client via JavaScript. If I can do that, Tailwind will take care of everything else.

Thanks for your suggestions!

Showing Posts 1 to 10

JohnnyCurran

JohnnyCurran

Your example seems to be empty - was it a copy/paste that didn’t get into the post?

Also, have you seen JS.transition? It supports tailwind classes Phoenix.LiveView.JS — Phoenix LiveView v1.2.5

al2o3cr

al2o3cr

The post originally tried to use single backquotes on separate lines to quote a whole block of code, which resulted in the code not getting quoted. I’ve replaced them with triple-backquotes ``` which work as the author intended.

chrismccord

chrismccord

Creator of Phoenix

LiveBeats uses tailwind and toggles menu and such just fine from TailwindUI. Have you looked there?:

check the <.dropdown> in core components and the show_dropdown and hide_dropdown functions:
https://github.com/fly-apps/live_beats/blob/master/lib/live_beats_web/components/core_components.ex#L318-L336

KevinConti

KevinConti OP

Thanks, it was in the mod queue so I didn’t get a chance to review for formatting beforehand :slight_smile:

KevinConti

KevinConti OP

Hey Chris, thanks a bunch for the reply (and for your work)!

I took a brief look, it seems to me like your approach to this problem is as follows:

  1. Create a button that shows the mobile menu (sidebar) on click.
<button
      type="button"
      id="show-mobile-sidebar"
      aria-expanded="false"
      aria-controls="mobile-sidebar"
      class="px-4 border-r border-gray-200 text-gray-500 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-purple-500 lg:hidden"
      phx-click={show_mobile_sidebar()}
    >
      <span class="sr-only">Open sidebar</span>
      <svg
        class="h-6 w-6"
        xmlns="http://www.w3.org/2000/svg"
        fill="none"
        viewBox="0 0 24 24"
        stroke="currentColor"
        aria-hidden="true"
      >
        <path
          stroke-linecap="round"
          stroke-linejoin="round"
          stroke-width="2"
          d="M4 6h16M4 12h8m-8 6h16"
        >
        </path>
      </svg>
    </button>
  1. Inside the mobile menu, have a nested component that is capable of hiding the mobile sidebar:
<div
  id="mobile-sidebar-container"
  class="fixed inset-0 flex z-40 lg:hidden"
  aria-modal="true"
  style="display: none;"
  role="region"
>
  <div class="fixed inset-0 bg-gray-600 bg-opacity-75" phx-click={hide_mobile_sidebar()}></div>

  <div
    id="mobile-sidebar"
    class="relative flex-1 flex flex-col max-w-xs w-full pt-5 pb-4 bg-white hidden min-h-screen"
  >
  ...
  1. Implement the “show” method called by the button in #1 to hide itself.
def show_mobile_sidebar(js \\ %JS{}) do
    js
    |> JS.show(to: "#mobile-sidebar-container", transition: "fade-in")
    |> JS.show(
      to: "#mobile-sidebar",
      display: "flex",
      time: 300,
      transition:
        {"transition ease-in-out duration-300 transform", "-translate-x-full", "translate-x-0"}
    )
    |> JS.hide(to: "#show-mobile-sidebar", transition: "fade-out")
    |> JS.dispatch("js:exec", to: "#hide-mobile-sidebar", detail: %{call: "focus", args: []})
  end

This is clever and seems like a viable approach, but where I think it gets a bit ugly is when you have the desire for a single button to control both the “show” and “hide” behavior of a component. In that case, you’d need to end up having two buttons with most things duplicated, and two methods - something like this:

<button id="show-menu-button" class="block <%= @duplicated_classes %>" phx-click={show_menu("#menu")}>Show Menu</button>
<button id="hide-menu-button" class="hidden <%= @duplicated_classes %>" phx-click={hide_menu("#menu")}>Hide Menu</button>

def show_menu(menu) do
  hide_button("#show-menu-button")
  show_button("#hide-menu-button")
  JS.show(to: menu)
  # transitions omitted for brevity
end 

def hide_menu(menu) do
  hide_button("#hide-menu-button")
  show_button("#show-menu-button")
  JS.hide(to:menu)
  # transitions omitted
end

But I do feel that a more smooth developer experience would be something like this:

<button phx-click={toggle_menu("#menu")}>Menu</button>

def toggle_menu(to) do
  JS.toggleClasses(to: to, in: "block", out: "hidden")
  JS.toggleClasses(to: "#menu-button--icon", in: "block", out: hidden")
end

I’m very open to being wrong about this, because what I’m suggesting is that LiveView.JS should manage the state of the classes for a component. But that said, JS.toggle is already managing this state to determine if it should apply display: none or display: block, so I imagine the implementation would be similar.

What I’m trying to get at is this - as it stands, it looks like JS.toggle is quite limited in use - it requires you to be okay with your component having its display overridden with display: block | flex | inline. In most cases with Tailwind, you really want a specific tailwind class to be applied, and you definitely don’t want your reactive modifiers (sm:, md:, etc) to be overridden.

Very curious as to your thoughts! Thanks again.

chrismccord

chrismccord

Creator of Phoenix

that’s what my linked dropdown component does:
2023-07-13 14-04-52.2023-07-13 14_05_10

The phx-click-away does the hide which you’ll need for a menu anyway, and the same button acts as show and hide because of that.

chrismccord

chrismccord

Creator of Phoenix
sezaru

sezaru

Note sure if you meant the PR on itself or the workaround proposed in the comments. If the latter, that works for classes, but fails if what you are trying to toggle is something else (like attributes for example).

codeanpeace

codeanpeace

For attributes, try swapping JS.add_class and JS.remove_class into @Nik’s workaround re-posted below.

def toggle_expanded(js \\ %JS{}) do
  js
  |> JS.remove_class(
    "expanded",
    to: "#outer-menu.expanded"
  )
  |> JS.add_class(
    "expanded",
    to: "#outer-menu:not(.expanded)"
  )
end
sezaru

sezaru

I tried that, couldn’t make it work, did it work for you? If so I will try to revisit it and see if it was something that I messed up

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
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
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
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
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

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews