Created
February 21, 2018 02:54
-
-
Save developit/71a459bb7be7019ea92ba4a9eb2c4012 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component } from 'preact'; | |
import Snackbar from 'preact-material-components/Snackbar'; | |
const TIMEOUT = 3; | |
export default class Toaster extends Component { | |
seen = []; | |
queue = []; | |
snackbarRef = c => { | |
this.snackbar = c; | |
}; | |
queueClose() { | |
clearTimeout(this.closeTimer); | |
this.closeTimer = setTimeout(this.hide, (TIMEOUT + 2) * 1000); | |
} | |
hide = () => { | |
clearTimeout(this.closeTimer); | |
this.current = null; | |
this.setState({ visible: false }); | |
}; | |
show = callback => { | |
clearTimeout(this.closeTimer); | |
if (this.state.visible) return callback(); | |
this.setState({ visible: true }, () => { | |
setTimeout(callback, 100); | |
}); | |
}; | |
notify(info) { | |
this.current = info; | |
if (this.seen.indexOf(info)===-1) this.seen.push(info); | |
this.show(() => { | |
if (this.snackbar) { | |
this.snackbar.MDComponent.show({ | |
...info, | |
timeout: TIMEOUT*1000 | |
}); | |
} | |
if (!this.processQueue()) { | |
this.queueClose(); | |
} | |
}); | |
} | |
processQueue = () => { | |
let notif = this.queue.shift(); | |
if (notif) { | |
this.notify(notif); | |
return true; | |
} | |
return false; | |
}; | |
queueNotify(info) { | |
this.seen.push(info); | |
if (this.queue.push(info)===1) { | |
setTimeout(this.processQueue); | |
} | |
} | |
componentWillReceiveProps({ notifications=[] }) { | |
for (let i=0; i<notifications.length; i++) { | |
if (this.seen.indexOf(notifications[i])===-1) { | |
this.queueNotify(notifications[i]); | |
} | |
} | |
} | |
render(props, { visible }) { | |
return ( | |
visible ? <Snackbar style={{ zIndex: 1001 }} ref={this.snackbarRef} /> : null | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Clearly you haven't included a manual on how to actually call this. To save newcomers from wasting more time here is how to use this code
Passing just a string will warn you that there is no message