react-jam-ui
Version:
React JAM UI components
142 lines (119 loc) • 3.19 kB
JavaScript
import React from 'react'
import classNames from 'classnames'
import '../Animate'
import './styles.styl'
const Store = function () {
const store = {
data: []
}
const defaultTimer = 3000;
store.create = function(data) {
const id = Math.random();
data.id = id;
store.data.push(data);
setTimeout(() => {
store.data = store.data.filter(toast => toast.id !== id)
store.changed()
}, data.timer);
store.changed()
}
store.changed = function() {
if (store.cb) store.cb(store.data)
}
store.watch = function(fn) {
store.cb = fn;
}
store.success = function (message, timer=defaultTimer) {
const data = {
status: 'success',
message,
timer
};
store.create(data)
};
store.info = function (message, timer=defaultTimer) {
const data = {
status: 'info',
message,
timer
};
store.create(data)
};
store.warning = function (message, timer=defaultTimer) {
const data = {
status: 'warning',
message,
timer
};
store.create(data)
};
store.error = function (message, timer=defaultTimer) {
const data = {
status: 'error',
message,
timer
};
store.create(data)
};
return store;
};
export const Toast = Store();
export class ToastContainer extends React.Component {
constructor(props) {
super();
const styles = {};
switch (props.style) {
case 'top left':
styles.top = 10;
styles.left = 10;
break;
case 'top right':
styles.top = 10;
styles.right = 10;
break;
case 'bottom left':
styles.bottom = 10;
styles.left = 10;
break;
case 'bottom right':
styles.bottom = 10;
styles.right = 10;
break;
default:
styles.top = 10;
styles.right = 10;
break;
}
this.state = {
styles: styles
}
}
componentWillMount() {
let store = this.props.store;
store.watch(data => {
setTimeout(()=>this.forceUpdate(), 0)
})
}
render() {
const toasts = this.props.store.data;
return <div className='react-toasts-container' style={ this.state.styles } >
{ toasts.map(toast => <div key={`toast-${toast.id}`}>
<div className={`react-toasts ${toast.status} react-toasts-animation`}>
{ toast.message }
</div>
</div>)}
</div>
}
}
/*
<ToastContainer store={ Toast }/>
Toast.success('Success')
Toast.info('info')
Toast.warning('warning')
Toast.error('error')
Toast.create({
status: 'any_other_type',
message: 'Any message',
timer: 2000 (3000 default)
})
*/