All files / src/components/DatatableHeader/Widgets DownloadData.js

100% Statements 53/53
100% Branches 14/14
100% Functions 18/18
100% Lines 53/53

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 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233                                                              5x       11x 11x             11x             5x 5x   5x 5x   2x 2x   1x 1x     2x 2x     5x   5x 3x 3x 3x 3x 3x   2x     2x 2x     5x 5x 5x 2x       11x 12x     11x 1x     11x 2x       31x 31x 31x 31x                         10x                   1x                   1x                             1x 8x           2x                 2x                   1x                 1x                           5x                 5x 9x 1x       5x 9x                          
import React, { Component, Fragment } from "react";
import { connect } from "react-redux";
import {
  IconButton,
  Tooltip,
  Zoom,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Button,
  Select,
  MenuItem,
  Input
} from "@material-ui/core";
import {
  CloudDownload as CloudDownloadIcon,
  Close as CloseIcon
} from "@material-ui/icons";
import {
  rowsPropType,
  columnsPropType,
  rowsCurrentPagePropType,
  rowsSelectedPropType,
  isRefreshingPropType,
  setRowsSelectedPropType
} from "../../../proptypes";
import { setRowsSelected as setRowsSelectedAction } from "../../../redux/actions/datatableActions";
import Transition from "./Transition";
 
const Json2csvParser = require("json2csv").Parser;
 
export class DownloadData extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dialogOpen: false,
      fileType: "csv",
      fileName: "my-data"
    };
  }
 
  download = type => {
    const {
      rows,
      columns,
      rowsCurrentPage,
      rowsSelected,
      setRowsSelected
    } = this.props;
    const { fileType, fileName } = this.state;
 
    let data = null;
    switch (type) {
      case "selected":
        data = rowsSelected;
        break;
      case "current":
        data = rowsCurrentPage;
        break;
      default:
      case "all":
        data = rows;
        break;
    }
 
    const hiddenElement = document.createElement("a");
 
    if (fileType === "csv") {
      const json2csvParser = new Json2csvParser({ columns });
      const csv = json2csvParser.parse(data);
      hiddenElement.href = `data:text/csv;charset=utf-8,${encodeURI(csv)}`;
      hiddenElement.target = "_blank";
      hiddenElement.download = `${fileName}.csv`;
    } else {
      hiddenElement.href = `data:text/json;charset=utf-8,${encodeURIComponent(
        JSON.stringify(data)
      )}`;
      hiddenElement.target = "_blank";
      hiddenElement.download = `${fileName}.json`;
    }
 
    hiddenElement.click();
    this.setState({ dialogOpen: false });
    if (type === "selected") {
      setRowsSelected();
    }
  };
 
  toggleDialog = bool => {
    this.setState({ dialogOpen: bool });
  };
 
  setFileName = e => {
    this.setState({ fileName: e.target.value });
  };
 
  setFileType = e => {
    this.setState({ fileType: e.target.value });
  };
 
  render() {
    const { rowsSelected, rows, isRefreshing } = this.props;
    const { dialogOpen, fileType, fileName } = this.state;
    const disabled = rows.length === 0 || isRefreshing;
    return (
      <Fragment>
        <Tooltip
          TransitionComponent={Zoom}
          title={disabled ? "No data to download" : "Download data"}
        >
          <span>
            <IconButton
              className={
                disabled
                  ? "disabled-icon download-data-icon"
                  : "download-data-icon"
              }
              onClick={() => this.toggleDialog(true)}
              disabled={disabled}
            >
              <CloudDownloadIcon color="primary" />
            </IconButton>
          </span>
        </Tooltip>
 
        <Dialog
          open={dialogOpen}
          onClose={() => this.toggleDialog(false)}
          TransitionComponent={Transition}
          fullWidth
          maxWidth="sm"
        >
          <DialogTitle id="alert-dialog-slide-title">
            Download Data
            <IconButton
              aria-label="Close"
              className="close-icon"
              onClick={() => this.toggleDialog(false)}
            >
              <CloseIcon />
            </IconButton>
          </DialogTitle>
          <DialogContent>
            <DialogContentText id="alert-dialog-slide-description">
              Data will be exported in {fileType} file
            </DialogContentText>
            <br />
            <Input
              inputProps={{ className: "input-fileName" }}
              label={fileName}
              value={fileName}
              error={!(fileName.split(" ").join("").length > 0)}
              onChange={e => this.setFileName(e)}
              onFocus={e => e.target.select()}
              autoFocus
            />
            <Select
              position="end"
              value={fileType}
              onChange={e => this.setFileType(e)}
            >
              <MenuItem value="csv">.csv</MenuItem>
              <MenuItem value="json">.json</MenuItem>
            </Select>
          </DialogContent>
          <DialogActions>
            <Button
              className="rows-selected"
              onClick={() => this.download("selected")}
              variant="contained"
              size="small"
              color="primary"
              disabled={rowsSelected.length === 0}
            >
              Rows selected
            </Button>
            <Button
              className="rows-current-page"
              onClick={() => this.download("current")}
              variant="contained"
              size="small"
              color="primary"
            >
              Rows of current page
            </Button>
            <Button
              className="all-rows"
              onClick={() => this.download("all")}
              variant="contained"
              size="small"
              color="primary"
            >
              All rows
            </Button>
          </DialogActions>
        </Dialog>
      </Fragment>
    );
  }
}
 
DownloadData.propTypes = {
  rows: rowsPropType.isRequired,
  columns: columnsPropType.isRequired,
  rowsCurrentPage: rowsCurrentPagePropType.isRequired,
  rowsSelected: rowsSelectedPropType.isRequired,
  isRefreshing: isRefreshingPropType.isRequired,
  setRowsSelected: setRowsSelectedPropType
};
 
const mapDispatchToProps = dispatch => {
  return {
    setRowsSelected: () => dispatch(setRowsSelectedAction([]))
  };
};
 
const mapStateToProps = state => {
  return {
    rowsSelected: state.datatableReducer.rowsSelected,
    isRefreshing: state.datatableReducer.isRefreshing,
    columns: state.datatableReducer.data.columns,
    rows: state.datatableReducer.data.rows,
    rowsCurrentPage: state.datatableReducer.pagination.rowsCurrentPage
  };
};
 
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(DownloadData);