FreeTube/src/renderer/components/ft-toast/ft-toast.js

56 lines
1.5 KiB
JavaScript
Raw Normal View History

2020-06-14 23:13:35 +02:00
import Vue from 'vue'
import FtToastEvents from './ft-toast-events.js'
2020-06-14 23:13:35 +02:00
export default Vue.extend({
name: 'FtToast',
data: function () {
return {
2020-06-27 12:41:34 +02:00
toasts: [
],
2020-06-14 23:13:35 +02:00
}
},
mounted: function () {
FtToastEvents.$on('toast.open', this.open)
},
2020-06-27 17:27:03 +02:00
beforeDestroy: function () {
FtToastEvents.$off('toast.open', this.open)
},
2020-06-14 23:13:35 +02:00
methods: {
performAction: function (toast) {
toast.action()
this.close(toast)
2020-06-14 23:13:35 +02:00
},
close: function (toast) {
2020-06-27 17:27:03 +02:00
clearTimeout(toast.timeout)
// Remove toasts when most recent toast has finished to avoid re-render
if (this.toasts.filter(toast => toast.isOpen).length === 1) {
// Wait for fade-out to finish
setTimeout(this.clear, 300)
}
toast.isOpen = false
2020-06-14 23:13:35 +02:00
},
2020-07-04 17:44:35 +02:00
open: function (message, action, time) {
const toast = { message: message, action: action || (() => { }), isOpen: false, timeout: null }
2020-07-04 17:44:35 +02:00
toast.timeout = setTimeout(this.close, time || 3000, toast)
setImmediate(() => toast.isOpen = true)
if (this.toasts.length > 4) {
for (let i = this.toasts.length - 1; i >= 0; i--) {
if (!this.toasts[i].isOpen) {
// Replace the first hidden toast starting from the bottom
return this.toasts.splice(i, 1, toast)
}
2020-06-27 12:41:34 +02:00
}
// Else replace the most recent
return this.toasts.splice(4, 1, toast)
}
this.toasts.push(toast)
2020-06-14 23:13:35 +02:00
},
clear: function () {
if (this.toasts.every(toast => !toast.isOpen)) {
this.toasts = []
}
2020-06-27 12:41:34 +02:00
}
2020-06-14 23:13:35 +02:00
},
})