summaryrefslogtreecommitdiff
path: root/frontend/src/flash.js
blob: 44b94797d25cf8c634d002e98ffc51732fe256d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import React from 'react';
import { Container } from 'react-bootstrap';
import Toast from 'react-bootstrap/Toast';

class Flash extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			messages: [],
		}
		this.seq = 0;
	}
	componentDidMount() {
		window.flash = this.flash.bind(this);
	}
	componentWillUnmount() {
		window.flash = null;
	}
	render() {
		if (this.state.messages.length === 0) {
			return '';
		}
		let that = this;
		const messages = this.state.messages.map(function(message, index) {
			return <Toast key={message.seq} onClose={() => that.remove(message.seq)} autohide={true} delay={(index+1)*3000}>
				<Toast.Header><strong className="mr-auto">{message.header || 'Inventory'}</strong></Toast.Header>
				<Toast.Body>{message.text}</Toast.Body>
			</Toast>;
		});
		return <Container style={{position: 'absolute', top: 0, right: 0}}>
			{messages}
		</Container>;
	}
	remove(seq) {
		this.setState(function(state, props) {
			const messages = state.messages.filter((message) => message.seq !== seq);
			return { messages };
		});
	}
	flash(message) {
		message.seq = ++this.seq;
		this.setState(function(state, props) {
			const messages = [...state.messages, message];
			return { messages };
		});
	}
}

export { Flash };