# All files / react/Alerter index.jsx

25.53% Statements 12/47
0% Branches 0/16
4.17% Functions 1/24
26.67% Lines 12/45

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209

    1x

    1x
    1x
    1x

    1x

    1x

    1x

    1x

    1x

    1x

    1x

    1x

     import React, { Component } from 'react'
    import PropTypes from 'prop-types'
    import Portal from 'preact-portal'
    import Button from '../Button'

    import styles from './styles.styl'
    import classNames from 'classnames'

    const MINIMUM_ALERT_DURATION = 2000

    const createStore = () => {
      const notifications = []
      const listeners = []

      const dispatch = notification => {
        notification.id = notifications.length
        notifications.push(notification)
        listeners.forEach(listener => listener(notification))
      }

      const subscribe = listener => {
        listeners.push(listener)
      }

      return { dispatch, subscribe }
    }

    const store = createStore()

    class Alert extends Component {
      state = {
        hidden: true
      }

      computeDuration() {
        const words = this.props.message.split(/\W/).filter(Boolean)
        return Math.max(MINIMUM_ALERT_DURATION, words.length / 3 * 1000)
      }

      componentDidMount() {
        this.closeTimer = setTimeout(() => {
          this.beginClosing()
        }, this.props.duration === 'auto' ? this.computeDuration() : this.props.duration)
        // Delay to trigger CSS transition after the first render.
        // Totally open for a better way to achieve this.
        setTimeout(() => {
          this.setState({ hidden: false })
        }, 20)
      }

      beginClosing() {
        this.base.addEventListener('transitionend', this.notifyClosed, false)
        this.setState({ hidden: true })
      }

      notifyClosed = () => {
        this.props.onClose()
      }

      componentWillUnmount() {
        this.base.removeEventListener('transitionend', this.notifyClosed, false)
        this.setState({ hidden: false })
        if (this.closeTimer) {
          clearTimeout(this.closeTimer)
        }
      }

      render() {
        const { message, type, buttonText, buttonAction } = this.props
        const { hidden } = this.state
        return (
          <div
            className={classNames(
              styles['c-alert'],
              hidden ? styles['c-alert--hidden'] : ''
            )}
          >
            <div
              className={classNames(
                styles['c-alert-wrapper'],
                styles[`c-alert--${type}`]
              )}
            >
              <p>{message}</p>
              {buttonText && (
                <Button
                  onClick={buttonAction}
                  className={styles[`c-btn--alert-${type}`]}
                  label={buttonText}
                  size="tiny"
                />
              )}
            </div>
          </div>
        )
      }
    }

    Alert.propTypes = {
      /** @type string - Controls the style of the error */
      type: PropTypes.oneOf(['success', 'info', 'error']),
      /** @type {string} - Message to display */
      message: PropTypes.string.isRequired,
      /** @type {function} - Callback when is dismissed */
      onClose: PropTypes.func,
      /** @type {function} - Text of the button, if absent, no button is displayed */
      buttonText: PropTypes.string,
      /** @type {function} - Callback when clicking on the button */
      buttonAction: PropTypes.func
    }

    Alert.defaultProps = {
      type: 'info',
      onClose: () => {},
      buttonText: undefined,
      buttonAction: () => {},
      duration: 'auto'
    }

    class Alerter extends Component {
      state = {
        notifications: []
      }

      /**
       * @param {string} message
       * @param {object} options
       * @public
       * @static
       */
      static info(msg, options) {
        store.dispatch({ type: 'info', msg, options })
      }

      /**
       * @param {string} msg
       * @param {object} options
       * @public
       * @static
       */
      static success(msg, options) {
        store.dispatch({ type: 'success', msg, options })
      }

      /**
       * @param {string} msg
       * @param {object} options
       * @public
       * @static
       */
      static error(msg, options) {
        store.dispatch({ type: 'error', msg, options })
      }

      componentDidMount() {
        this.setState({ mounted: true })
        store.subscribe(this.notify)
      }

      notify = notification => {
        this.setState({
          notifications: [...this.state.notifications, notification]
        })
      }

      handleClose = id => {
        let idx = this.state.notifications.findIndex(n => n.id === id)
        this.setState({
          notifications: [
            ...this.state.notifications.slice(0, idx),
            ...this.state.notifications.slice(idx + 1)
          ]
        })
      }

      render() {
        const { t, into } = this.props
        const { notifications } = this.state
        return (
          <Portal into={into}>
            {notifications.map(notif => (
              <Alert
                type={notif.type}
                key={notif.id}
                message={t ? t(notif.msg, notif.options) : notif.msg}
                onClose={() => this.handleClose(notif.id)}
                buttonText={notif.options && notif.options.buttonText}
                buttonAction={notif.options && notif.options.buttonAction}
                duration={notif.options && notif.options.duration}
              />
            ))}
          </Portal>
        )
      }
    }

    Alerter.propTypes = {
      /** A translation function. If ommited, messages are left intact */
      t: PropTypes.func,
      /** A selector to target a DOM node where alerts will be rendered */
      into: PropTypes.string
    }

    Alerter.defaultProps = {
      into: 'body'
    }

    export default Alerter