I can’t figure this out and hope anyone can help me understand what is (not) happening in my phoenix app.
Versions:
phoenix: 1.7.10
phoenix_html: 3.3
phoenix_live_view: 0.20.1
My core_components.ex
:
@doc """
Renders flash notices.
"""
attr :id, :string, doc: "the optional id of flash container"
attr :flash, :map, default: %{}, doc: "the map of flash messages to display"
attr :title, :string, default: nil
attr :kind, :atom, values: [:info, :error], doc: "used for styling and flash lookup"
attr :rest, :global, doc: "the arbitrary HTML attributes to add to the flash container"
slot :inner_block, doc: "the optional inner block that renders the flash message"
def flash(assigns) do
assigns = assign_new(assigns, :id, fn -> "flash-#{assigns.kind}" end)
~H"""
<div
:if={msg = render_slot(@inner_block) || Phoenix.Flash.get(@flash, @kind)}
id={@id}
phx-click={JS.push("lv:clear-flash", value: %{key: @kind}) |> hide("##{@id}")}
role="alert"
class={["flash", @kind == :info && "flash-info", @kind == :error && "flash-error"]}
phx-mounted={show("##{@id}")}
{@rest}
>
<p :if={@title}>
<span :if={@kind == :info}>(i)</span>
<span :if={@kind == :error}>/!\</span>
<%= @title %>
</p>
<p><%= msg %></p>
<button type="button" aria-label={gettext("close")}>x</button>
</div>
"""
end
## JS Commands
def show(js \\ %JS{}, selector) do
JS.show(js,
to: selector,
time: 300,
transition: {
"transition-all ease-out duration-300",
"opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95",
"opacity-100 translate-y-0 sm:scale-100"
}
)
end
def hide(js \\ %JS{}, selector) do
JS.hide(js,
to: selector,
time: 200,
transition: {
"transition-all ease-in duration-200",
"opacity-100 translate-y-0 sm:scale-100",
"opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
}
)
end
In my recipe_live.ex
:
@impl true
def handle_info({FormComponent, {:saved, recipe}}, socket) do
{:noreply,
socket
|> put_flash(:info, dgettext("notifs", "Autosaved draft"))
|> push_patch(to: ~p"/recipes/#{recipe.id}/edit")}
end
Now my flash is rendered, but I don’t see the classes I thought would be added by the show/2
function. If I close the flash, the classes are set though and I see my flash notification being faded/slided out.
Is phx-mounted={show("##{@id}")}
not working with push_patch
? Should I do this differently? I tried hooks, push_event and listen to it in JS to exec the show command, nothing seems to work.
Can anyone explain to me what is happening?