Show a toast

v0.0.12

A toast is a short note at the bottom of the screen that tells the reader something happened, such as "Order refunded." It has a tone, and it can carry an Undo button and a link. This guide puts the toasts of Gervaz on a LiveView page, pushes one from the page and from a component, and answers an Undo. Each toast leaves by itself through a timer message in the page's own process, so none of it is JavaScript.

Before you begin

  • Have a LiveView that mounts a Gervaz table or form. See Mount a table and a form in a LiveView.
  • The default UI adapter, MishkaGervaz.UIAdapters.Tailwind, draws each toast with its toast/1 function. A custom adapter can override it.

Attach the toasts to the page

Call MishkaGervaz.Toast.attach/1 once, in mount/3. It puts the hook that keeps the page's toasts on the socket and starts their list in the :gervaz_toasts assign. Then draw them with toasts/1:

elixir
def mount(_params, _session, socket), do: {:ok, MishkaGervaz.Toast.attach(socket)}

def render(assigns) do
  ~H"""
  ...
  <MishkaGervaz.Toast.toasts toasts={@gervaz_toasts} ui={MyAppWeb.UIAdapter} />
  """
end

The region is a polite live region at the bottom of the screen, at its end side, and above the bottom edge on a phone. ui defaults to MishkaGervaz.UIAdapters.Tailwind, and id defaults to "gervaz-toasts". The page keeps at most four toasts, the newest last.

Push a toast

Call push/4 where something happened. It takes the socket, a tone and the text, and returns the socket with the toast on it:

elixir
socket =
  MishkaGervaz.Toast.push(socket, :ok, "Order refunded.",
    navigate: "/admin/refunds",
    link_label: "See refunds"
  )

socket = MishkaGervaz.Toast.push(socket, :info, "Product deleted.", undo: {:restore, product.id})

The tones are :ok, :info, :warn and :error. These options are read:

OptionMeaning
undoWhat the Undo button stands for, any term. Without it there is no button.
undo_labelThe button's words. The default is "Undo".
navigateA path inside the app that the toast links to.
hrefA plain address it links to instead, such as a file to download.
link_labelThe link's words. The default is "Open".
msHow long it stays, in milliseconds. The default is 5000, and 8000 with an Undo or a link.

Send a toast from a component

A LiveComponent runs in the page's process, so it sends the page a toast with send_toast/3. It takes the same arguments as push/4 without the socket, and the page's hook shows it:

elixir
MishkaGervaz.Toast.send_toast(:ok, "Order refunded.")

Answer an Undo

An Undo takes its toast away and sends the page {:toast_undo, undo}, where undo is the term the push gave. Do what it stands for in handle_info/2:

elixir
def handle_info({:toast_undo, {:restore, product_id}}, socket) do
  # restore the product here
  {:noreply, socket}
end

The Close button takes a toast away. MishkaGervaz.Toast.dismiss/2 takes one away from the server by its id.

Next steps