Removed queue,

destroy elements once all toasts are hidden
This commit is contained in:
kylejwatson 2020-07-04 16:13:47 +01:00
parent 48deb375cb
commit cc101fd119
1 changed files with 22 additions and 20 deletions

View File

@ -6,13 +6,7 @@ export default Vue.extend({
data: function () { data: function () {
return { return {
toasts: [ toasts: [
{ isOpen: false, message: '', action: null, timeout: null },
{ isOpen: false, message: '', action: null, timeout: null },
{ isOpen: false, message: '', action: null, timeout: null },
{ isOpen: false, message: '', action: null, timeout: null },
{ isOpen: false, message: '', action: null, timeout: null }
], ],
queue: [],
} }
}, },
mounted: function () { mounted: function () {
@ -28,26 +22,34 @@ export default Vue.extend({
}, },
close: function (toast) { close: function (toast) {
clearTimeout(toast.timeout) clearTimeout(toast.timeout)
toast.isOpen = false // Remove toasts when most recent toast has finished to avoid re-render
if (this.queue.length !== 0) { if (this.toasts.filter(toast => toast.isOpen).length === 1) {
const nexToast = this.queue.shift() // Wait for fade-out to finish
this.open(nexToast.message, nexToast.action) setTimeout(this.clear, 300)
} }
toast.isOpen = false
}, },
open: function (message, action) { open: function (message, action) {
const toast = { message: message, action: action || (() => { }), isOpen: false, timeout: null }
toast.timeout = setTimeout(this.close, 5000, toast)
setImmediate(() => toast.isOpen = true)
if (this.toasts.length > 4) {
for (let i = this.toasts.length - 1; i >= 0; i--) { for (let i = this.toasts.length - 1; i >= 0; i--) {
const toast = this.toasts[i] if (!this.toasts[i].isOpen) {
if (!toast.isOpen) { // Replace the first hidden toast starting from the bottom
return this.showToast(message, action, toast) return this.toasts.splice(i, 1, toast)
} }
} }
this.queue.push({ message: message, action: action }) // Else replace the most recent
return this.toasts.splice(4, 1, toast)
}
this.toasts.push(toast)
}, },
showToast: function(message, action, toast) { clear: function () {
toast.message = message if (this.toasts.every(toast => !toast.isOpen)) {
toast.action = action || (() => {}) this.toasts = []
toast.isOpen = true }
toast.timeout = setTimeout(this.close, 2000, toast)
} }
}, },
}) })