Tracking inactivity in a Phoenix LiveView app

I find myself doing something very similar to what @sb8244 is describing.

In all of my LV applications so far, I create a generic LV template like:

defmodule AppWeb.LiveTemplate do
  defmacro __using__(_opts) do
    quote do
      use AppWeb, :live_view

      alias AppWeb.Router.Helpers, as: Routes
      alias App.{Contexts..}
      require Logger

      def handle_event(
            "user_inactive",
            target,
            socket
          ) do
          # Do Something
          {:noreply, socket}
        end
      end
    end
  end
end

You can then use this in your live views:

defmodule AppWeb.LivePage do
  use AppWeb.LiveTemplate

  def mount() do
  # etc...
  end
end

I’ve found this pattern to be super useful when defining events that all my live views need to respond to or like @sb8244 said, creating common authentication functionality.

I wouldn’t be surprised if there’s a better way to do this though. One thing that confuses me is having to set up the Routes alias again inside this macro even though it’s also in AppWeb.