Snackbar.tsx 2.31 KB
Newer Older
Matija Obreza's avatar
Matija Obreza committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import * as React from 'react';
import {connect} from 'react-redux';

import Snackbar_ from 'material-ui/Snackbar';

interface ISnacks {
    snack: string;
}

/// Based on example from https://material-ui.com/demos/snackbars/#consecutive-snackbars
class Snackbar extends React.Component<ISnacks, any> {

    private queue = [];

    public constructor(props: any) {
        super(props);
        this.state = {
            open: false,
            messageInfo: {},
        };
    }

    public componentWillMount() {
        const { snack } = this.props;
Matija Obreza's avatar
Cleanup    
Matija Obreza committed
25
        // console.log('Snack willMount', snack);
Matija Obreza's avatar
Matija Obreza committed
26
27
28
29
30
        this.pushSnack(snack);
    }

    public componentWillReceiveProps(nextProps) {
        const { snack } = nextProps;
Matija Obreza's avatar
Cleanup    
Matija Obreza committed
31
        // console.log('Snack willReceive', snack);
Matija Obreza's avatar
Matija Obreza committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
        this.pushSnack(snack);
    }

    private pushSnack(snack) {
        if (! snack || ! snack.message) {
          return;
        }

        this.queue.push({
          message: snack.message,
          key: new Date().getTime(),
        });

        if (this.state.open) {
          // immediately begin dismissing current message to start showing new one
          this.setState({ open: false });
        } else {
          this.processQueue();
        }
    }

    private processQueue() {
        if (this.queue.length > 0) {
          this.setState({
            messageInfo: this.queue.shift(),
            open: true,
          });
        }
    }

    private handleClose = (event, reason) => {
        if (reason === 'clickaway') {
          return;
        }
        this.setState({ open: false });
    }

    private handleExited = () => {
        this.processQueue();
    }

    public render() {
      const { message, key } = this.state.messageInfo;

      return (
          <Snackbar_
              key={ key }
              anchorOrigin={ { vertical: 'bottom', horizontal: 'right' } }
              open={ this.state.open }
              autoHideDuration={ 3000 }
              onClose={ this.handleClose }
              onExited={ this.handleExited }
              SnackbarContentProps={ { 'aria-describedby': 'message-id' } }
              message={ <span id="message-id">{ message }</span> }
          />
      );
    }
}

const mapStateToProps = (state) => ({
    snack: state.snackbar.content,
});

export default connect(mapStateToProps, null)(Snackbar);