You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

77 lines
2.5 KiB

import { Controller } from "@hotwired/stimulus"
import Toastify from 'toastify-js'
export default class FlashController extends Controller {
static TOASTIFY_DEFAULTS = {
selector: 'flashbar',
escapeMarkup: false,
close: true,
position: 'center',
offset: { y: 30 },
}
static should_popup = true
static targets = ['flashItem']
connect() {
if (FlashController.should_popup) { this.buildPopupsFromWithin() }
}
enable() { FlashController.should_popup = true }
disable() { FlashController.should_popup = false }
iconNotice() { return this.icon('M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z') }
iconAlert() { return this.icon('M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z') }
className(toastType) { return `alert alert-${toastType} inset-ring-2 shadow-xl/50` }
classNameNotice() { return this.className('success') }
classNameAlert() { return this.className('error') }
textNotice(message) { return `${this.iconNotice()}<div>${message}</div>` }
textAlert(message) { return `${this.iconAlert()}<div>${message}</div>` }
buildPopupsFromWithin() {
FlashController.should_popup = false
this.flashItemTargets.forEach((item) => {
this.onPopupEvent({ detail: { type: item.dataset.type, message: item.textContent.trim() } })
})
}
icon(drawing) {
return `<svg xmlns="http://>']www.w3.org/2000/svg" class="h-6 w-6 shrink-0 stroke-current mx-4" fill="none" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="${drawing}" />
</svg>`
}
onPopupEvent(event) {
const { type, message } = event.detail
switch (type) {
case 'notice': this.notice(message); break
case 'alert': this.alert(message); break
default: console.error(`undefined popup message type: ${type}`)
}
}
log(type, message) {
switch (type) {
case 'notice': console.info(`FLASH:${type} => ${message}`); break
case 'alert': console.warn(`FLASH:${type} => ${message}`); break
}
}
notice(message) {
Toastify({
...FlashController.TOASTIFY_DEFAULTS,
text: this.textNotice(message),
className: this.classNameNotice(),
}).showToast();
this.log('notice', message)
}
alert(message) {
Toastify({
...FlashController.TOASTIFY_DEFAULTS,
text: this.textAlert(message),
className: this.classNameAlert(),
}).showToast();
this.log('alert', message)
}
}