allow to clear toasts
This commit is contained in:
parent
de08ab6736
commit
dc62f87b74
|
|
@ -2,6 +2,14 @@ import { showModal } from './modal'
|
|||
import { Toast } from './toast'
|
||||
|
||||
export const toast = new Toast()
|
||||
|
||||
/* istanbul ignore next */
|
||||
if (process.env.NODE_ENV === 'test') {
|
||||
afterEach(() => {
|
||||
toast.clear()
|
||||
})
|
||||
}
|
||||
|
||||
Object.assign(blessing, { notify: { showModal, toast } })
|
||||
|
||||
export { showModal } from './modal'
|
||||
|
|
|
|||
|
|
@ -8,19 +8,24 @@ type QueueElement = { id: string; type: ToastType; message: string }
|
|||
type ToastQueue = QueueElement[]
|
||||
|
||||
const TOAST_EVENT = Symbol('toast')
|
||||
const CLEAR_EVENT = Symbol('clear')
|
||||
|
||||
export const ToastContainer: React.FC = () => {
|
||||
const [queue, setQueue] = useState<ToastQueue>([])
|
||||
|
||||
useEffect(() => {
|
||||
const off = emitter.on(TOAST_EVENT, (toast: QueueElement) => {
|
||||
const off1 = emitter.on(TOAST_EVENT, (toast: QueueElement) => {
|
||||
setQueue(queue => {
|
||||
queue.push(toast)
|
||||
return queue.slice()
|
||||
})
|
||||
})
|
||||
const off2 = emitter.on(CLEAR_EVENT, () => setQueue([]))
|
||||
|
||||
return off
|
||||
return () => {
|
||||
off1()
|
||||
off2()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleClose = (id: string) => {
|
||||
|
|
@ -66,4 +71,8 @@ export class Toast {
|
|||
error(message: string) {
|
||||
emitter.emit(TOAST_EVENT, { id: nanoid(4), type: 'error', message })
|
||||
}
|
||||
|
||||
clear() {
|
||||
emitter.emit(CLEAR_EVENT)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,3 +26,14 @@ test('"Toast" class', () => {
|
|||
|
||||
jest.runAllTimers()
|
||||
})
|
||||
|
||||
test('clear toasts', () => {
|
||||
render(<ToastContainer />)
|
||||
const toast = new Toast()
|
||||
|
||||
toast.success('success')
|
||||
toast.info('info')
|
||||
|
||||
toast.clear()
|
||||
expect(document.querySelectorAll('.alert')).toHaveLength(0)
|
||||
})
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user