forked from folio-org/stripes-components
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCallout.js
74 lines (66 loc) · 2.23 KB
/
Callout.js
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
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
import React from 'react';
import ReactDOM from 'react-dom';
import cloneDeep from 'lodash/cloneDeep';
import uniqueId from 'lodash/uniqueId';
import findIndex from 'lodash/findIndex';
import TransitionGroup from 'react-transition-group/TransitionGroup';
import CalloutElement from './CalloutElement';
import css from './Callout.css';
class Callout extends React.Component {
constructor(props) {
super(props);
this.state = {
callouts: [],
};
this.sendCallout = this.sendCallout.bind(this);
this.removeCallout = this.removeCallout.bind(this);
}
updateCalloutContainer() {
this.calloutContainer = document.getElementById('OverlayContainer');
}
sendCallout({ type = 'success', message, timeout = 6000 }) {
this.setState((curState) => {
const newState = cloneDeep(curState);
const newCallout = Object.assign(
{ id: uniqueId('callout-'), onDismiss: this.removeCallout },
{ type, message, timeout }
);
newState.callouts.push(newCallout);
if (timeout !== 0) {
window.setTimeout(() => { this.removeCallout(newCallout.id); }, timeout);
}
return newState;
});
}
removeCallout(id) {
const toHide = findIndex(this.state.callouts, c => c.id === id);
if (toHide === -1) { return; }
this.setState((curState) => {
const newState = cloneDeep(curState);
newState.callouts.splice(toHide, 1);
return newState;
});
}
render() {
// We don't want to try and create a Portal if the callout container hasn't been rendered yet,
// which is the case whenever the Callout Container is going to be put into the DOM at the same
// or later time as this Callout.
if (!this.calloutContainer) {
this.updateCalloutContainer();
if (!this.calloutContainer) {
return null;
}
}
return ReactDOM.createPortal(
<div className={css.callout}>
<TransitionGroup className={css.calloutContainer} aria-live="polite" aria-relevant="additions">
{this.state.callouts.map(calloutProps => (
<CalloutElement key={calloutProps.id} transition="slide" {...calloutProps} />
))}
</TransitionGroup>
</div>,
this.calloutContainer
);
}
}
export default Callout;