Flash notifications with timeout?

Hi! I’m using put_flash/3 to notify the user when they don’t have enough privileges for the requested action. But in some of those cases, I want to auto-dismiss the message after a given amount of time, especially if the required action is also taken automatically, like for example redirecting to the login page.
Now I’ve searched how to do this using only what Phoenix provides me but all docs and threads I read point toward writing a custom implementation, some of them even going the JS way.
Am I missing something here? Maybe I’m using flash wrong. Is there a similar function that allows for custom timeouts? Is it a good idea to try and rewrite put_flash to include an auto-close functionality?

There is the Flashy library which does this, among other things.

I’ve also had my eye on LiveToast though it doesn’t do this yet. While Flashy is great and I like it a lot, it uses modules to represent notifications instead of functions which I do not love.
I’m not sure what is happening with LiveToast, though, and if it’s even a plan to have them auto-close.

To answer part of your question, Flashy does use LiveView’s built-in flash while LiveToast uses a live component with its own state.

1 Like
Hooks.Flash = {
  mounted(){
    let hide = () => liveSocket.execJS(this.el, this.el.getAttribute("phx-click"))
    this.timer = setTimeout(() => hide(), 8000)
    this.el.addEventListener("phx:hide-start", () => clearTimeout(this.timer))
    this.el.addEventListener("mouseover", () => {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => hide(), 8000)
    })
  },
  destroyed(){ clearTimeout(this.timer) }
}
12 Likes

:exploding_head:

For whatever reason in the back of my head I assumed we couldn’t use JS because of change tracking and didn’t give it another thought but… temporary flash… duh me. Thanks!

Is this what Phoenix uses to show the alert when it can’t see the server? If I remember correctly, it has like a reverse loading bar that goes down to zero and then it gets closed. Or maybe I’m making it up lol but I think I saw it more than once