diff --git a/lib/plausible_web/live/flash.ex b/lib/plausible_web/live/flash.ex index 384399011..60a0c72a5 100644 --- a/lib/plausible_web/live/flash.ex +++ b/lib/plausible_web/live/flash.ex @@ -2,15 +2,55 @@ defmodule PlausibleWeb.Live.Flash do @moduledoc """ Flash component for LiveViews - works also when embedded within dead views """ - use Phoenix.LiveComponent + + use Phoenix.Component alias Phoenix.LiveView.JS alias Phoenix.Flash - def render(assigns) do + @flash_timer_assigns %{ + success: :clear_flash_success, + error: :clear_flash_error + } + + @flash_timer_timeout_ms 5000 + + defmacro __using__(_opts) do + quote do + import PlausibleWeb.Live.Flash, only: [put_live_flash: 3, flash_messages: 1] + + def handle_info({:clear_live_flash, key}, socket) do + {:noreply, Phoenix.LiveView.clear_flash(socket, key)} + end + end + end + + def put_live_flash(socket, key, message) when key in [:success, :error] do + timer_key = Map.fetch!(@flash_timer_assigns, key) + + if flash_timer = socket.assigns[timer_key] do + Process.cancel_timer(flash_timer) + end + + flash_timer = + Process.send_after( + self(), + {:clear_live_flash, key}, + @flash_timer_timeout_ms + ) + + socket + |> Phoenix.LiveView.put_flash(key, message) + |> assign(timer_key, flash_timer) + end + + def flash_messages(assigns) do ~H"""
-
- <.flash :if={Flash.get(@flash, :success)}> +
+ <.flash :if={Flash.get(@flash, :success)} key="success"> <:icon> <.icon_success /> @@ -21,7 +61,7 @@ defmodule PlausibleWeb.Live.Flash do <%= Flash.get(@flash, :success) %> - <.flash :if={Flash.get(@flash, :error)}> + <.flash :if={Flash.get(@flash, :error)} key="error"> <:icon> <.icon_error /> @@ -32,15 +72,14 @@ defmodule PlausibleWeb.Live.Flash do <%= Flash.get(@flash, :error) %> -
-