import React from 'react'; import type {NotificationProps, NotificationState} from '../hyper'; export default class Notification extends React.PureComponent { dismissTimer!: NodeJS.Timeout; constructor(props: NotificationProps) { super(props); this.state = { dismissing: false }; } componentDidMount() { if (this.props.dismissAfter) { this.setDismissTimer(); } } componentDidUpdate(prevProps: NotificationProps, prevState: NotificationState) { // if we have a timer going and the notification text // changed we reset the timer if (this.props.text !== prevProps.text) { if (prevProps.dismissAfter) { this.resetDismissTimer(); } if (prevState.dismissing) { this.setState({dismissing: false}); } } } handleDismiss = () => { this.setState({dismissing: true}); }; onElement = (el: HTMLDivElement | null) => { if (el) { el.addEventListener('webkitTransitionEnd', () => { if (this.state.dismissing) { this.props.onDismiss(); } }); const {backgroundColor} = this.props; if (backgroundColor) { el.style.setProperty('background-color', backgroundColor, 'important'); } } }; setDismissTimer() { this.dismissTimer = setTimeout(() => { this.handleDismiss(); }, this.props.dismissAfter); } resetDismissTimer() { clearTimeout(this.dismissTimer); this.setDismissTimer(); } componentWillUnmount() { clearTimeout(this.dismissTimer); } render() { const {backgroundColor, color} = this.props; const opacity = this.state.dismissing ? 0 : 1; return (
{this.props.customChildrenBefore} {this.props.children || this.props.text} {this.props.userDismissable ? ( [x] ) : null} {this.props.customChildren}
); } }