From 8fdf0680ba5724d1bec2242f1b9b943a42a591f0 Mon Sep 17 00:00:00 2001 From: Jannis Mattheis Date: Sat, 31 Mar 2018 18:55:30 +0200 Subject: [PATCH] Add SnackBarHandler Component --- ui/src/Layout.js | 2 + ui/src/component/SnackBarHandler.js | 68 +++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 ui/src/component/SnackBarHandler.js diff --git a/ui/src/Layout.js b/ui/src/Layout.js index 447ad4e..0a7e1b8 100644 --- a/ui/src/Layout.js +++ b/ui/src/Layout.js @@ -16,6 +16,7 @@ import Clients from './pages/Clients'; import Users from './pages/Users'; import PropTypes from 'prop-types'; import SettingsDialog from './component/SettingsDialog'; +import SnackBarHandler from './component/SnackBarHandler'; const lightTheme = createMuiTheme({ palette: { @@ -115,6 +116,7 @@ class Layout extends Component { {showSettings && } + diff --git a/ui/src/component/SnackBarHandler.js b/ui/src/component/SnackBarHandler.js new file mode 100644 index 0000000..35fc705 --- /dev/null +++ b/ui/src/component/SnackBarHandler.js @@ -0,0 +1,68 @@ +import React, {Component} from 'react'; +import SnackBarStore from '../stores/SnackBarStore'; +import Snackbar from 'material-ui/Snackbar'; +import IconButton from 'material-ui/IconButton'; +import Close from 'material-ui-icons/Close'; + +class SnackBarHandler extends Component { + static MAX_VISIBLE_SNACK_TIME_IN_MS = 6000; + static MIN_VISIBLE_SNACK_TIME_IN_MS = 1000; + + state = { + current: '', + open: false, + openWhen: 0, + }; + + componentWillMount = () => SnackBarStore.on('change', this.onNewSnack); + componentWillUnmount = () => SnackBarStore.removeListener('change', this.onNewSnack); + + onNewSnack = () => { + const {open, openWhen} = this.state; + + if (!open) { + this.openNextSnack(); + return; + } + + const snackOpenSince = Date.now() - openWhen; + if (snackOpenSince > SnackBarHandler.MIN_VISIBLE_SNACK_TIME_IN_MS) { + this.closeCurrentSnack(); + } else { + setTimeout(this.closeCurrentSnack, SnackBarHandler.MIN_VISIBLE_SNACK_TIME_IN_MS - snackOpenSince); + } + }; + + openNextSnack = () => { + if (SnackBarStore.hasNext()) { + this.setState({ + ...this.state, + open: true, + openWhen: Date.now(), + current: SnackBarStore.next(), + }); + } + }; + + closeCurrentSnack = () => this.setState({...this.state, open: false}); + + render() { + const {open, current} = this.state; + + return ( + {current}} + action={[ + + + , + ]} + /> + ); + } +} + +export default SnackBarHandler;