# All files / components/AttachmentMenu index.js

95.08% Statements 58/61
91.67% Branches 11/12
88.46% Functions 23/26
96.36% Lines 53/55

    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
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250

    6x
    1x
    6x
    6x
    6x
    6x

    1x

    1x
    6x

    6x

    6x

    1x

    6x
    6x
    6x

    6x
    6x

    1x

    6x
    6x
    6x

    1x
    36x

    7x

    7x

    7x

    7x

    7x

    1x

    6x

    6x
    6x
    6x

    6x

    3x
    3x

    3x

    3x

    3x
    3x

    3x
    3x

    9x
    9x
    9x

    9x

    36x

    3x

    8x

    1x

    1x

    1x

    1x

     /* eslint-disable camelcase */
    import React from 'react';
    import PropTypes from 'prop-types';
    import styled from 'styled-components';
    import { rgba } from 'polished';

    import { Flex, Box } from 'grid-styled';
    import { Icon } from 'react-icons-kit';

    import { ic_music_note as MusicNote } from 'react-icons-kit/md/ic_music_note';
    import { ic_attach_file as AttachFile } from 'react-icons-kit/md/ic_attach_file';
    import { ic_image as Image } from 'react-icons-kit/md/ic_image';
    import { ic_insert_drive_file as File } from 'react-icons-kit/md/ic_insert_drive_file';
    import { ic_lock_open as LockOpen } from 'react-icons-kit/md/ic_lock_open';
    import { ic_video_library as VideoLibrary } from 'react-icons-kit/md/ic_video_library';

    import { textColor, themeColor } from '../../utils/style';

    const MdMusicNote = (props) => <Icon icon={MusicNote} {...props} />;
    const MdAttachFile = (props) => <Icon icon={AttachFile} {...props} />;
    const MdImage = (props) => <Icon icon={Image} {...props} />;
    const MdFile = (props) => <Icon icon={File} {...props} />;
    const MdLockOpen = (props) => <Icon icon={LockOpen} {...props} />;
    const MdVideoLibrary = (props) => <Icon icon={VideoLibrary} {...props} />;

    const validFileFormats = [
      'image/jpeg',
      'image/gif',
      'image/png',
      'image/jpg',
      'image/x-tiff',
      'image/tiff',
      'image/bmp',
      'application/pdf',
      'application/geojson',
      'audio/mp3',
      'video/mp4',
      'video/mov',
      'video/quicktime',
      'application/octet-stream',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'application/vnd.ms-excel',
      'text/comma-separated-values',
      'text/csv',
      'application/csv',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'application/vnd.ms-powerpoint',
      'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    ];

    const StyledContainer = styled.div`
      color: ${(props) => textColor(props.theme, 'light', 'secondary')};
      display: block;
      cursor: pointer;
      padding: 0;
      margin: 0;
      box-shadow: ${(props) => props.theme.shadows['4p']};
      border-radius: 5px;
      background-color: ${(props) => props.theme.palette.common.white};
    `;

    const StyledMenuList = styled.ul`
      padding: 0;
      margin: 0;
      font-size: ${(props) => props.theme.typography.classes.caption.fontSize};
      line-height: ${(props) => props.theme.typography.classes.caption.lineHeight};
      font-weight: ${(props) => props.theme.typography.weights.fontWeightMedium};

      li {
        list-style: none;
        padding: 5px;

        &:hover {
          color: ${(props) => themeColor(props.theme, 'accent', 'base')};
          background-color: ${(props) => rgba(themeColor(props.theme, 'accent', 'base'), 0.1)};
        }
      }
    `;

    const StyledMenuTitle = styled.span`
      display: block;
      font-size: ${(props) => props.theme.typography.classes.small.fontSize};
      line-height: ${(props) => props.theme.typography.classes.small.lineHeight};
      font-weight: ${(props) => props.theme.typography.weights.fontWeightNormal};
      padding: 10px 15px;
    `;

    const renderIcon = (type, size) => {
      switch (type) {
        case 'image':
          return <MdImage size={size} />;
        case 'video':
          return <MdVideoLibrary size={size} />;
        case 'audio':
          return <MdMusicNote size={size} />;
        case 'document':
          return <MdFile size={size} />;
        case 'link':
          return <MdLockOpen size={size} />;
        default:
          return <MdAttachFile size={size} />;
      }
    };

    class AttachmentMenu extends React.Component {
      constructor(props) {
        super(props);

        this.handleFileChosen = this.handleFileChosen.bind(this);
        this.handleItemClick = this.handleItemClick.bind(this);
        this.myFileInput = null;

        this.state = {
          currentAcceptedTypes: '*',
        };
      }

      // TODO -> Add a test to simulate user choose the file (hard to do it)
      /* istanbul ignore next  */
      handleFileChosen(file) {
        const { onAttachmentSelected } = this.props;
        if (!file || !validFileFormats.includes(file.type)) { return; }

        const data = {
          content_type: file.type,
          content: 'attachment',
          media: file,
          name: file.name,
        };

        if (typeof onAttachmentSelected === 'function') {
          onAttachmentSelected(data);
        }
      }

      handleItemClick(item) {
        const { acceptedTypes, onItemClick } = this.props;
        const acceptedTypesForItem = acceptedTypes[item.type] || [];

        const updatedAcceptedTypes = acceptedTypesForItem.join(',') || '*';

        this.setState({
          currentAcceptedTypes: updatedAcceptedTypes,
        });

        this.myFileInput.accept = updatedAcceptedTypes;
        this.myFileInput.click();

        Eif (typeof onItemClick === 'function') {
          onItemClick(item);
        }
      }

      render() {
        const {
          className, data, iconSize, title,
        } = this.props;
        const { currentAcceptedTypes } = this.state;
        const { items } = data;

        return (
          <StyledContainer>
            <StyledMenuTitle>{title}</StyledMenuTitle>
            <StyledMenuList className={className}>
              {items.map((item, index) => (
                <li
                  key={item.id}
                >
                  <div
                    role="button"
                    tabIndex={index}
                    htmlFor="fileInput"
                    onClick={() => this.handleItemClick(item)}
                    onKeyUp={() => this.handleItemClick(item)}
                  >
                    <Flex flex="1 1 auto" alignItems="center">
                      <Box p={2}>
                        {renderIcon(item.type, iconSize)}
                      </Box>
                      <Box p={2} ml="auto" width={1}>
                        <span>{item.name}</span>
                      </Box>
                    </Flex>
                  </div>
                </li>
              ))}
            </StyledMenuList>
            <input
              type="file"
              id="fileInput"
              ref={(fileInput) => { this.myFileInput = fileInput; }}
              accept={currentAcceptedTypes}
              onChange={(e) => this.handleFileChosen(e.target.files[0])}
              style={{ display: 'none' }}
            />
          </StyledContainer>
        );
      }
    }

    AttachmentMenu.defaultProps = {
      onItemClick: null,
      className: 'LT-AttachmentMenu-Container',
    };

    AttachmentMenu.propTypes = {
      /**
       * Array of element to display as Action items [{ id: '1', name: 'MyAction'}]
       */
      data: PropTypes.object.isRequired,
      /**
       * Object whose keys are the type of items and values array of valid types
       */
      acceptedTypes: PropTypes.object,
      /**
       * Title to show on the top
       */
      title: PropTypes.string,
      /**
       * Extra className to style the component
       */
      className: PropTypes.string,
      /**
       * Size for the icons
       */
      iconSize: PropTypes.number,
      /**
       * Callback function called when user clicks on an action Item
       * The callback has the following signature:
       * callback (item)
       */
      onItemClick: PropTypes.func,
      /**
       * Callback function called when user selects a file
       * callback (file)
       */
      onAttachmentSelected: PropTypes.func,
    };

    AttachmentMenu.defaultProps = {
      className: 'LT-AttachmentMenu-Wrapper',
      iconSize: 20,
    };

    AttachmentMenu.displayName = 'AttachmentMenu';

    export default AttachmentMenu;