@material-ui/icons#KeyboardArrowLeft JavaScript Examples

The following examples show how to use @material-ui/icons#KeyboardArrowLeft. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ContributorsTable.js    From git-insights with MIT License 5 votes vote down vote up
function TablePaginationActions(props) {
  const classes = useStyles1();
  const theme = useTheme();
  const { count, page, rowsPerPage, onChangePage } = props;

  const handleFirstPageButtonClick = event => {
    onChangePage(event, 0);
  };

  const handleBackButtonClick = event => {
    onChangePage(event, page - 1);
  };

  const handleNextButtonClick = event => {
    onChangePage(event, page + 1);
  };

  const handleLastPageButtonClick = event => {
    onChangePage(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1));
  };

  return (
    <div className={classes.root}>
      <IconButton
        onClick={handleFirstPageButtonClick}
        disabled={page === 0}
        aria-label="first page"
      >
        {theme.direction === 'rtl' ? <LastPageIcon /> : <FirstPageIcon />}
      </IconButton>
      <IconButton onClick={handleBackButtonClick} disabled={page === 0} aria-label="previous page">
        {theme.direction === 'rtl' ? <KeyboardArrowRight /> : <KeyboardArrowLeft />}
      </IconButton>
      <IconButton
        onClick={handleNextButtonClick}
        disabled={page >= Math.ceil(count / rowsPerPage) - 1}
        aria-label="next page"
      >
        {theme.direction === 'rtl' ? <KeyboardArrowLeft /> : <KeyboardArrowRight />}
      </IconButton>
      <IconButton
        onClick={handleLastPageButtonClick}
        disabled={page >= Math.ceil(count / rowsPerPage) - 1}
        aria-label="last page"
      >
        {theme.direction === 'rtl' ? <FirstPageIcon /> : <LastPageIcon />}
      </IconButton>
    </div>
  );
}
Example #2
Source File: CollectionView.js    From acsys with MIT License 4 votes vote down vote up
CollectionView = (props) => {
  const context = useContext(AcsysContext);
  const [content_id, setContentId] = useState('');
  const [viewId, setViewId] = useState(0);
  const [initialViews, setInitialViews] = useState([]);
  const [documentDetails, setDocumentDetails] = useState([]);
  const [acsysView, setAcsysView] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [apiCall, setApiCall] = useState('');
  const [totalRows, setTotalRows] = useState(0);
  const [page, setPage] = useState(1);
  const [orderDir, setOrderDir] = useState('');
  const [locked, setLocked] = useState(true);
  const [reset, setReset] = useState(false);
  const [view, setView] = useState(false);
  const [loading, setLoading] = useState(false);
  const [openKeyMessage, setOpenKeyMessage] = useState(false);
  const [setOpen, setSetOpen] = useState(false);
  const [setDetailOpen, setSetDetailOpen] = useState(false);
  const [setViewOpen, setSetViewOpen] = useState(false);
  const [filterLoading, setFilterLoading] = useState(false);
  const [view_order, setViewOrder] = useState(false);
  const [messageTitle, setMessageTitle] = useState('');
  const [message, setMessage] = useState('');
  const [deleteLoading, setDeleteLoading] = useState(false);

  const copy = () => {
    const el = document.createElement('textarea');
    el.value = apiCall;
    document.body.appendChild(el);
    el.select();
    document.execCommand('copy');
    document.body.removeChild(el);
  };

  const openKeyMessageFunc = () => {
    setOpenKeyMessage(true);
    setMessageTitle('Error');
    setMessage('No keys set Please setUnique key for data.');
  };

  const closeKeyMessage = () => {
    setOpenKeyMessage(false);
  };

  const handleViewChange = (value) => {
    published = value;
    let acsys_id = '';
    if (published) {
      acsys_id = props.match.params.acsys_id;
    } else {
      acsys_id = 'acsys_' + props.match.params.acsys_id;
    }
    context.setPageData(
      acsys_id,
      context.getKeys(),
      row_num,
      view_order,
      orderDir
    );
    context.setPage(1);
    mount();
  };

  const handleClickOpen = (id) => {
    setViewId(id);
    setSetOpen(true);
  };

  const handleClose = () => {
    setSetOpen(false);
  };

  const handleViewOpen = () => {
    setSetViewOpen(true);
  };

  const handleViewClose = () => {
    setSetViewOpen(false);
  };

  const handleDetailOpen = () => {
    setSetDetailOpen(true);
  };

  const handleDetailClose = () => {
    setSetDetailOpen(false);
  };

  const toggleTable = async (value) => {
    if (!value) {
      await Acsys.unlockTable(documentDetails[0].collection);
      setLocked(false);
    } else {
      Acsys.lockTable(documentDetails[0].collection);
      setLocked(true);
    }
  };

  const setLockedValue = (value) => {
    lockedValue = value;
  };

  const setOrderField = (field) => {
    view_orderField = field;
  };

  const setOrder = (order) => {
    view_order = order;
  };

  const setEntriesPerPage = (value) => {
    row_num = value;
  };

  const setUpdateOnly = (value) => {
    is_removable = value;
  };

  const saveViewsetTings = async () => {
    setLoading(true);
    let tempView = acsysView;
    if (view_orderField === 'none') {
      tempView['order_by'] = '';
      tempView['view_order'] = '';
    } else {
      tempView['order_by'] = view_orderField;
      tempView['view_order'] = view_order;
    }
    tempView['is_removable'] = is_removable;
    tempView['row_num'] = row_num;
    toggleTable(lockedValue);
    context.setHeld(false);
    await Acsys.updateData('acsys_views', tempView, [
      ['acsys_id', '=', tempView.acsys_id],
    ]);
    setSetViewOpen(false);
    setReset(True);
    setTotalRows(0);
    setPage(1);
    table_keys = [];
    mount();
  };

  const showPopUp = () => {
    return <div>{Object.values(tableData).map((value, index) => {})}</div>;
  };

  const deleteView = async () => {
    setDeleteLoading(true);

    if (table_keys[viewId]) {
      let keys = [];
      for (let i = 0; i < table_keys[viewId].length; i++) {
        let tKeys = [
          table_keys[viewId][i].field,
          '=',
          table_keys[viewId][i].value,
        ];
        keys.push(tKeys);
      }

      await Acsys.getData(documentDetails[0].collection, keys)
        .then(async (result) => {
          if (result.length < 1) {
            await Acsys.deleteData(
              'acsys_' + documentDetails[0].collection,
              keys
            );
          } else {
            await Acsys.deleteData(documentDetails[0].collection, keys);
          }
        })
        .catch(async () => {});
    } else {
      openKeyMessageFunc();
    }

    handleClose();
    setReset(True);
    table_keys = [];
    mount();
    setDeleteLoading(false);
  };

  const handleChangePrevPage = async () => {
    setLoading(true);
    let keys = [];
    for (let i = 0; i < table_keys[table_keys.length - 1].length; i++) {
      keys.push([table_keys[0][i].field, '=', table_keys[0][i].value]);
    }
    const currentData = await Acsys.getPage(
      tempDetails[0].collection,
      keys,
      row_num,
      view_order,
      orderDir,
      'prev',
      page
    );
    const apiCall = await Acsys.getOpenPageUrl(
      tempDetails[0].collection,
      keys,
      row_num,
      view_order,
      orderDir,
      'prev',
      page
    );
    setLoading(false);
    setTableData(currentData);
    setApiCall(apiCall);
    setPage(page - 1);
    context.setHeld(true);
    context.setPage(page);
    context.setPageData(
      tempDetails[0].collection,
      keys,
      row_num,
      view_order,
      orderDir
    );
    context.setPageDirection('prev');
    window.scrollTo(0, 0);
  };

  const handleChangeNextPage = async () => {
    setLoading(true);
    let keys = [];
    for (let i = 0; i < table_keys[table_keys.length - 1].length; i++) {
      keys.push([
        table_keys[table_keys.length - 1][i].field,
        '=',
        table_keys[table_keys.length - 1][i].value,
      ]);
    }
    const currentData = await Acsys.getPage(
      tempDetails[0].collection,
      keys,
      row_num,
      view_order,
      orderDir,
      'next',
      page
    );
    const apiCall = await Acsys.getOpenPageUrl(
      tempDetails[0].collection,
      keys,
      row_num,
      view_order,
      orderDir,
      'next',
      page
    );
    setLoading(false);
    setTableData(currentData);
    setApiCall(apiCall);
    setPage(page + 1);
    context.setHeld(true);
    context.setPage(page);
    context.setPageData(
      tempDetails[0].collection,
      keys,
      row_num,
      view_order,
      orderDir
    );
    context.setPageDirection('next');
    window.scrollTo(0, 0);
  };

  const savesetTings = async () => {
    setFilterLoading(true);
    table_keys = [];
    for (var i = 0; i < tempDetails.length; i++) {
      tempDetails[i].view_order = i;
      await Acsys.updateData('acsys_document_details', tempDetails[i], [
        ['acsys_id', '=', tempDetails[i].acsys_id],
      ]);
    }
    setFilterLoading(false);
    handleDetailClose();
  };

  const scan = async () => {
    setLoading(true);
    Acsys.deleteData('acsys_document_details', [
      ['content_id', '=', content_id],
    ])
      .then(async () => {
        mount();
      })
      .catch(() => {
        setLoading(false);
      });
  };

  useEffect(() => {
    if (content_id !== props.match.params.content_id && !loading) {
      mount();
    }
  }, [content_id, props.match.params.content_id, loading]);

  useEffect(() => {
    props.setHeader('Content');
    published = true;
    table_keys = [];
    setLoading(true);
    mount();
  }, []);

  const mount = async () => {
    let acsysView;
    let locked = true;
    let details = [];
    let currentData;
    let apiCall;
    let order = [];
    let orderDir = 'asc';
    lockedValue = true;
    is_removable = true;
    view_orderField = 'none';
    // view_order = 'asc';
    row_num = 10;
    if (!reset) {
      table_keys = props.location.state.table_keys;
    }
    let acsys_id = '';
    if (published) {
      acsys_id = props.match.params.acsys_id;
    } else {
      acsys_id = 'acsys_' + props.match.params.acsys_id;
    }

    const content_id = props.match.params.content_id;

    const totalRows = await Acsys.getTableSize(acsys_id);

    try {
      acsysView = await Acsys.getData('acsys_views', [
        ['acsys_id', '=', content_id],
      ]);
      is_removable = acsysView[0].is_removable;
      row_num = acsysView[0].row_num;
      if (acsysView[0].order_by.length > 0) {
        view_orderField = acsysView[0].order_by;
        view_order = acsysView[0].view_order;
      }

      let keys = [];

      try {
        for (let i = 0; i < table_keys.length; i++) {
          keys.push([table_keys[i].field, '=', table_keys[i].value]);
        }
      } catch (error) {}

      details = await Acsys.getData('acsys_document_details', [
        ['content_id', '=', content_id],
      ]);

      await Acsys.getData('acsys_open_tables', [['table_name', '=', acsys_id]])
        .then((result) => {
          if (result[0].table_name === acsys_id) {
            locked = false;
            lockedValue = false;
          }
        })
        .catch(() => {});

      if (details.length > 0) {
        details.sort((a, b) => (a.view_order > b.view_order ? 1 : -1));
        if (acsysView[0].order_by.length > 0) {
          order.push(acsysView[0].order_by);
          orderDir = acsysView[0].view_order;
        }
        for (let i = 0; i < details.length; i++) {
          if (Boolean(details[i].is_key)) {
            order.push(details[i].field_name);
          }
        }
        if (context.isHeld()) {
          let direction = 'none';
          const dbType = await Acsys.getDatabaseType();
          if (dbType === 'firestore') {
            direction = context.getPageDirection();
          }
          currentData = await Acsys.getPage(
            context.getTable(),
            context.getKeys(),
            context.getRowsPerPage(),
            context.getOrder(),
            context.getDirection(),
            direction,
            context.getPage()
          );
          setPage(context.getPage());
        } else {
          currentData = await Acsys.getData(
            acsys_id,
            [],
            row_num,
            order,
            orderDir
          );
          apiCall = await Acsys.getOpenUrl(
            acsys_id,
            [],
            row_num,
            order,
            orderDir
          );
        }
      } else {
        currentData = await Acsys.getData(acsys_id, keys, row_num);
        apiCall = await Acsys.getOpenUrl(acsys_id, keys, row_num);
        await Promise.all(
          Object.keys(currentData[0]).map(async (value, index) => {
            let collectionDetails = {
              acsys_id: uniqid(),
              content_id: content_id,
              collection: acsys_id,
              control: 'none',
              field_name: value,
              is_visible_on_page: true,
              is_visible_on_table: true,
              type: typeof currentData[0][value],
              is_key: false,
              view_order: index,
              width: 12,
            };
            await Acsys.insertData(
              'acsys_document_details',
              collectionDetails
            ).then(() => {
              details.push(collectionDetails);
            });
          })
        ).then(() => {
          details.sort((a, b) => (a.view_order > b.view_order ? 1 : -1));
        });
      }
    } catch (error) {
      console.log(error);
    }

    setReset(false);
    setView(props.location.state.view);
    setLoading(false);
    setLocked(locked);
    setContentId(content_id);
    setInitialViews(currentData);
    setTableData(currentData);
    setApiCall(apiCall);
    setAcsysView(acsysView[0]);
    setPage(page);
    setDocumentDetails(details);
    setTotalRows(totalRows);
    setViewOrder(order);
    setOrderDir(orderDir);
  };

  const renderHeader = () => {
    const details = documentDetails;
    if (details.length > 0) {
      return (
        <TableRow>
          {Object.values(details).map((value) => {
            if (value.is_visible_on_table) {
              return (
                <TableCell
                  style={{
                    paddingLeft: 16,
                    paddingRight: 16,
                    paddingTop: 5,
                    paddingBottom: 5,
                  }}
                >
                  {value.field_name.toUpperCase()}
                </TableCell>
              );
            }
          })}
          <TableCell
            style={{
              paddingLeft: 16,
              paddingRight: 16,
              paddingTop: 5,
              paddingBottom: 5,
            }}
            align="right"
          >
            ACTIONS
          </TableCell>
        </TableRow>
      );
    }
  };

  const renderCellData = (rowData) => {
    return rowData.map((column) => {
      return <TableCell>{column}</TableCell>;
    });
  };
  const renderTableData = () => {
    return tableData.map((tableData, rowIndex) => {
      let tempKey = [];
      return (
        <TableRow>
          {Object.values(documentDetails).map((details) => {
            let returnValue = '';
            Object.values(tableData).map((value, index) => {
              if (Object.keys(tableData)[index] == details.field_name) {
                if (Boolean(details.is_key) && value !== undefined) {
                  let tempObj = {
                    field: details.field_name,
                    value: value,
                  };
                  tempKey.push(tempObj);
                  table_keys[rowIndex] = tempKey;
                }
                if (details.is_visible_on_table) {
                  if (details.control == 'dateTimePicker') {
                    const date = new Date(value);
                    const printDate =
                      ('0' + (date.getMonth() + 1)).slice(-2) +
                      '/' +
                      ('0' + date.getDate()).slice(-2) +
                      '/' +
                      date.getFullYear();
                    returnValue = printDate;
                  } else if (details.control == 'booleanSelect') {
                    const tmpElement = document.createElement('DIV');
                    tmpElement.innerHTML = Boolean(value);
                    const stringLimit = 100;
                    let valueString = tmpElement.innerText;
                    if (valueString.length >= stringLimit) {
                      valueString = valueString.substr(0, stringLimit) + '...';
                    }
                    returnValue = valueString;
                  } else {
                    const tmpElement = document.createElement('DIV');
                    tmpElement.innerHTML = value;
                    const stringLimit = 100;
                    let valueString = tmpElement.innerText;
                    if (valueString.length >= stringLimit) {
                      valueString = valueString.substr(0, stringLimit) + '...';
                    }
                    returnValue = valueString;
                  }
                }
              }
            });
            if (details.is_visible_on_table) {
              return acsysView.link_view_id.length > 0 ? (
                <TableCell
                  to={{
                    pathname:
                      '/CollectionView/' +
                      acsysView.link_table +
                      '/' +
                      acsysView.link_view_id,
                    state: {
                      table_keys: table_keys[rowIndex],
                    },
                  }}
                  component={Link}
                  style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}
                >
                  {returnValue}
                </TableCell>
              ) : (
                <TableCell
                  style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}
                >
                  {returnValue}
                </TableCell>
              );
            }
          })}
          <TableCell align="right" style={{ minWidth: 100 }}>
            {table_keys.length > 0 ? (
              <Tooltip title="Edit Entry">
                <IconButton
                  edge="start"
                  color="inherit"
                  aria-label="edit"
                  to={{
                    pathname: '/DocumentView',
                    state: {
                      mode: 'update',
                      is_removable: is_removable,
                      table_keys: table_keys[rowIndex],
                      routed: false,
                      viewId: documentDetails[0].content_id,
                    },
                  }}
                  component={Link}
                  style={{ marginRight: 10 }}
                >
                  <CreateIcon />
                </IconButton>
              </Tooltip>
            ) : (
              <Tooltip title="Edit Entry">
                <IconButton
                  edge="start"
                  color="inherit"
                  aria-label="edit"
                  onClick={() => openKeyMessageFunc()}
                  style={{ marginRight: 10 }}
                >
                  <CreateIcon />
                </IconButton>
              </Tooltip>
            )}
            {Acsys.getMode() !== 'Viewer' && is_removable ? (
              <Tooltip title="Delete Entry">
                <IconButton
                  edge="start"
                  color="inherit"
                  aria-label="delete"
                  onClick={(event) => {
                    event.stopPropagation();
                    handleClickOpen(rowIndex);
                  }}
                >
                  <DeleteIcon />
                </IconButton>
              </Tooltip>
            ) : (
              <div />
            )}
          </TableCell>
        </TableRow>
      );
    });
  };
  const renderPagination = (paginate) => {
    let startingElement = 0;
    if (totalRows > 0) {
      startingElement = page * row_num - row_num + 1;
    }
    const endingElement = page * row_num - row_num + 1 + tableData.length - 1;
    return paginate ? (
      <Grid style={{ width: 190, float: 'right' }} container>
        <Grid style={{ float: 'right' }} item xs>
          <Typography variant={'body2'} style={{ margin: '10px auto' }}>
            {startingElement}-{endingElement} of {totalRows}
          </Typography>
        </Grid>
        <Grid item xs={6}>
          {page > 1 ? (
            <IconButton onClick={() => handleChangePrevPage()}>
              <KeyboardArrowLeft color="inherit" />
            </IconButton>
          ) : (
            <IconButton>
              <KeyboardArrowLeft
                color="disabled"
                style={{ cursor: 'default' }}
              />
            </IconButton>
          )}
          {page * row_num < totalRows ? (
            <IconButton onClick={() => handleChangeNextPage()}>
              <KeyboardArrowRight color="inherit" />
            </IconButton>
          ) : (
            <IconButton>
              <KeyboardArrowRight
                color="disabled"
                style={{ cursor: 'default' }}
              />
            </IconButton>
          )}
        </Grid>
      </Grid>
    ) : (
      <div>
        <Typography style={{ height: 30, marginTop: 8 }}>
          Please setKeys for pagination.
        </Typography>
      </div>
    );
  };
  const renderTable = (paginate) => {
    let tableDetails = '';
    try {
      tableDetails = tableData.details;
    } catch (error) {}
    if (tableDetails) {
      return <div style={{ margin: 30, overflow: 'auto' }}>{tableDetails}</div>;
    } else {
      try {
        return (
          <div>
            <div style={{ margin: 'auto', overflow: 'auto' }}>
              <Table>
                <TableHead style={{ backgroundColor: '#fafafa' }}>
                  {renderHeader()}
                </TableHead>
                <TableBody>{renderTableData()}</TableBody>
              </Table>
            </div>
            {renderPagination(paginate)}
          </div>
        );
      } catch (error) {}
    }
  };
  tempDetails = documentDetails;
  let projectId = '';
  let viewTable = '';
  let tempKey = [];
  let tempKeys = [];
  let paginate = false;

  try {
    projectId = acsysView.acsys_id;
  } catch (error) {}

  try {
    viewTable = tempDetails[0].collection;
  } catch (error) {}

  for (let i = 0; i < documentDetails.length; i++) {
    if (Boolean(documentDetails[i].is_key)) {
      let tempObj = {
        field: documentDetails[i].field_name,
      };
      tempKey.push(tempObj);
      paginate = true;
    }
  }
  tempKeys[0] = tempKey;
  return (
    <div>
      <Paper
        style={{
          margin: 'auto',
          overflow: 'hidden',
          clear: 'both',
          marginBottom: 20,
        }}
      >
        <AppBar
          position="static"
          elevation={0}
          style={{
            backgroundColor: '#fafafa',
            borderBottom: '1px solid #dcdcdc',
          }}
        >
          <Toolbar style={{ margin: 4, paddingLeft: 12, paddingRight: 12 }}>
            <Grid container spacing={2}>
              <Grid item xs style={{ overflow: 'hidden' }}>
                <Typography
                  align="left"
                  variant="subtitle2"
                  noWrap
                  style={{ marginTop: 10, color: '#000000' }}
                >
                  View: {view}
                </Typography>
              </Grid>
              <Grid item>
                <Tooltip title="Choose Between Published Or Draft Rows">
                  <NativeSelect
                    onChange={(e) => handleViewChange('true' == e.target.value)}
                  >
                    <option value={true}>Published</option>
                    <option value={false}>Draft</option>
                  </NativeSelect>
                </Tooltip>
              </Grid>

              {Acsys.getMode() === 'Administrator' ? (
                <Grid item>
                  <Tooltip title="Change How Data Is Presented">
                    <Button
                      onClick={handleDetailOpen}
                      variant="contained"
                      color="primary"
                    >
                      Field Controls
                    </Button>
                  </Tooltip>
                </Grid>
              ) : (
                <div />
              )}
              {Acsys.getMode() === 'Administrator' ? (
                <Grid item>
                  <Tooltip title="Change How Data Is Organized">
                    <Button
                      onClick={handleViewOpen}
                      variant="contained"
                      color="primary"
                    >
                      View setTings
                    </Button>
                  </Tooltip>
                </Grid>
              ) : (
                <div />
              )}
              <Grid item>
                {Acsys.getMode() !== 'Viewer' && is_removable ? (
                  <Tooltip title="Add New Entry To Table">
                    <Button
                      to={{
                        pathname: '/DocumentView',
                        state: {
                          mode: 'add',
                          table_keys: tempKeys[0],
                          routed: false,
                          viewId: projectId,
                        },
                      }}
                      component={Link}
                      variant="contained"
                      color="primary"
                    >
                      New Entry
                    </Button>
                  </Tooltip>
                ) : (
                  <div />
                )}
              </Grid>
            </Grid>
          </Toolbar>
        </AppBar>
        {renderTable(paginate)}
        <LoadingDialog loading={loading} message={'Loading'} />
        <MessageDialog
          open={openKeyMessage}
          closeDialog={closeKeyMessage}
          title={messageTitle}
          message={message}
        />
        <YesNoDialog
          open={setOpen}
          closeDialog={handleClose}
          title={'Delete data?'}
          message={'Are you sure you want to delete this data?'}
          action={deleteView}
          actionProcess={deleteLoading}
        />
        <FieldControlDialog
          open={setDetailOpen}
          closeDialog={handleDetailClose}
          title={'Field Controls'}
          backend={HTML5Backend}
          component={
            <FieldDef docDetails={tempDetails} handleClick={savesetTings} />
          }
          action={savesetTings}
          actionProcess={filterLoading}
        />
        <ViewDialog
          open={setViewOpen}
          closeDialog={handleViewClose}
          viewOrderField={view_orderField}
          setOrderField={setOrderField}
          docDetails={tempDetails}
          viewOrder={view_order}
          setOrder={setOrder}
          rowNum={row_num}
          setEntriesPerPage={setEntriesPerPage}
          isRemovable={is_removable}
          setUpdateOnly={setUpdateOnly}
          viewTable={viewTable}
          locked={locked}
          setLockedValue={setLockedValue}
          action={saveViewsetTings}
          actionProcess={filterLoading}
        />
      </Paper>
      <Hidden smDown implementation="css">
        {!locked ? (
          <div style={{ clear: 'both' }}>
            API Call:{' '}
            <a className="api-url" href={apiCall} target="_blank">
              {apiCall}
            </a>
            <Tooltip title="Copy To Clipboard">
              <IconButton
                edge="start"
                color="inherit"
                aria-label="edit"
                onClick={copy}
                style={{ marginLeft: 5 }}
              >
                <CopyIcon style={{ height: 15 }} />
              </IconButton>
            </Tooltip>
          </div>
        ) : (
          <div />
        )}
      </Hidden>
    </div>
  );
}
Example #3
Source File: Storage.js    From acsys with MIT License 4 votes vote down vote up
Storage = (props) => {
  const [locked, setLocked] = useState(true);
  const [isDialog, setIsDialog] = useState(false);
  const [mode, setMode] = useState('');
  const [imgUrl, setImgUrl] = useState(undefined);
  const [con, setCon] = useState(true);
  const [fileName, setFileName] = useState('');
  const [currentDir, setCurrentDir] = useState('');
  const [newFolderName, setNewFolderName] = useState('');
  const [files, setFiles] = useState([]);
  const [uploadFile, setUploadFile] = useState('');
  const [page, setPage] = useState(0);
  const [rowsPerPage] = useState(15);
  const [openMessage, setOpenMessage] = useState(false);
  const [loading, setLoading] = useState(false);
  const [syncing, setSyncing] = useState(false);
  const [newFolder, setNewFolder] = useState(false);
  const [isOpenImage, setIsOpenImage] = useState(false);
  const [messageTitle, setMessageTitle] = useState('');
  const [message, setMessage] = useState('');
  const [setError] = useState('');
  const [deleteLoading, setDeleteLoading] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [previousDir, setPreviousDir] = useState('');

  const set = (name, ref) => {
    try {
      props.setFile(name, ref);
    } catch (error) {}
  };

  const closeMessage = () => {
    setOpenMessage(false);
  };

  const openDir = async (dir) => {
    setLoading(true);
    const parentDir = files[0].parent;
    const filesTemp = await Acsys.getData('acsys_storage_items', [
      ['parent', '=', dir],
    ]);
    for (var i = 0; i < filesTemp.length; i++) {
      await Acsys.getStorageURL(filesTemp[i].acsys_id)
        .then((result) => {
          filesTemp[i]['url'] = result;
        })
        .catch((error) => console.log(error));
    }
    filesTemp.sort((a, b) => (a.file_order > b.file_order ? 1 : -1));
    setLoading(false);
    setPreviousDir(parentDir);
    setCurrentDir('/' + dir);
    setFiles(filesTemp);
  };

  const openDirPage = async (dir) => {
    props.history.push('/Storage?' + dir);
    setLocked(false);
  };

  const previousDirFunc = async () => {
    setLoading(true);
    let parentFile = '/';
    let currentDir;
    let files;
    if (previousDir !== '/') {
      const parent = await Acsys.getData(
        'acsys_storage_items',
        [['acsys_id', '=', previousDir]],
        1
      );
      parentFile = parent[0].parent;
      currentDir = '/' + previousDir;
      files = await Acsys.getData('acsys_storage_items', [
        ['parent', '=', previousDir],
      ]);
    } else {
      currentDir = previousDir;
      files = await Acsys.getData('acsys_storage_items', [
        ['parent', '=', '/'],
      ]);
    }
    for (var i = 0; i < files.length; i++) {
      await Acsys.getStorageURL(files[i].acsys_id)
        .then((result) => {
          files[i]['url'] = result;
        })
        .catch((error) => console.log(error));
    }
    files.sort((a, b) => (a.file_order > b.file_order ? 1 : -1));

    setLoading(false);
    setPreviousDir(parentFile);
    setCurrentDir(currentDir);
    setFiles(files);
  };

  const setRef = (ref) => {
    setUploadFile(ref);
  };

  const uploadFileFunc = async () => {
    try {
      setLoading(true);
      await Acsys.uploadFile(uploadFile.files[0], currentDir).then(async () => {
        await loadFiles();
      });
      setLoading(false);
    } catch (error) {}
  };

  const syncFiles = async () => {
    handleSyncClose();
    setLoading(true);
    await Acsys.syncFiles();
    let files = await Acsys.getData('acsys_storage_items', [
      ['parent', '=', '/'],
    ]);
    for (var i = 0; i < files.length; i++) {
      await Acsys.getStorageURL(files[i].acsys_id)
        .then((result) => {
          files[i]['url'] = result;
        })
        .catch((error) => console.log(error));
    }
    files.sort((a, b) => (a.file_order > b.file_order ? 1 : -1));
    setLoading(false);
    setFiles(files);
  };

  const handleSyncOpen = () => {
    setSyncing(true);
  };

  const handleSyncClose = () => {
    setSyncing(false);
  };

  const openImg = (url) => {
    setIsOpenImage(true);
    setImgUrl(url);
  };

  const handleImgClose = () => {
    setIsOpenImage(false);
  };

  const handleChange = (event) => {
    setNewFolderName(event);
  };

  const newFolderOpen = () => {
    setNewFolder(true);
  };

  const newFolderClose = () => {
    setNewFolder(false);
  };

  const createNewFolder = async () => {
    if (newFolderName.indexOf(' ') >= 0) {
      setNewFolder(false);
      setOpenMessage(true);
      setMessageTitle('Error');
      setMessage('Folder name cannot contain spaces.');
    } else {
      setLoading(true);
      setNewFolder(false);
      await Acsys.createNewFolder(newFolderName, currentDir);
      await loadFiles();
      setLoading(false);
    }
  };

  const makeFilePublic = async (fileName) => {
    setLoading(true);
    await Acsys.makeFilePublic(fileName)
      .then(async () => {
        await loadFiles();
      })
      .catch((error) => setError(error));
    setLoading(false);
  };

  const makeFilePrivate = async (fileName) => {
    setLoading(true);
    await Acsys.makeFilePrivate(fileName)
      .then(async () => {
        await loadFiles();
      })
      .catch((error) => setError(error));
    setLoading(false);
  };

  const deleteFile = async () => {
    setDeleteLoading(true);
    await Acsys.deleteFile(fileName)
      .then(async () => {
        await loadFiles();
      })
      .catch((error) => setError(error));
    handleDeleteClose();
  };

  const handleDeleteOpen = async (fileName) => {
    setDeleting(true);
    setFileName(fileName);
  };

  const handleDeleteClose = () => {
    setDeleting(false);
    setDeleteLoading(false);
  };

  const loadFiles = async () => {
    setTimeout(() => {}, 1000);
    let dir = currentDir;
    if (dir !== '/') {
      dir = dir.substring(1, dir.length);
    }
    const files = await Acsys.getData('acsys_storage_items', [
      ['parent', '=', dir],
    ]);
    for (var i = 0; i < files.length; i++) {
      await Acsys.getStorageURL(files[i].acsys_id)
        .then((result) => {
          files[i]['url'] = result;
        })
        .catch((error) => console.log(error));
    }
    files.sort((a, b) => (a.file_order > b.file_order ? 1 : -1));
    setFiles(files);
  };

  const handleChangePage = (event, page) => {
    setPage(page);
  };

  useEffect(async () => {
    try {
      if (
        props.location.search.substring(1) !== currentDir.substring(1) &&
        !locked
      ) {
        let newDir = props.location.search.substring(1);
        if (newDir.length < 1) {
          newDir = '/';
        }
        setLocked(true);
        setLoading(true);
        setIsOpenImage(false);
        const files = await Acsys.getData('acsys_storage_items', [
          ['parent', '=', newDir],
        ]).catch();
        for (var i = 0; i < files.length; i++) {
          await Acsys.getStorageURL(files[i].acsys_id)
            .then((result) => {
              files[i]['url'] = result;
            })
            .catch((error) => console.log(error));
        }
        files.sort((a, b) => (a.file_order > b.file_order ? 1 : -1));
        let currentDir = '/';
        if (newDir !== '/') {
          currentDir += newDir;
        }
        setLocked(false);
        setLoading(false);
        setCurrentDir(currentDir);
        setFiles(files);
      }
    } catch (error) {}
  }, [locked, currentDir, props.location]);

  useEffect(async () => {
    setLoading(true);
    let parent = '/';
    let mode = 'standard';

    try {
      if (props.mode.length > 0) {
        mode = props.mode;
      }
    } catch (error) {
      props.setHeader('Storage');
    }
    let con;
    let files;
    try {
      con = await Acsys.isStorageConnected();
      if (!con) {
        setLoading(false);
        setCon(con);
      }
      files = await Acsys.getData('acsys_storage_items', [
        ['parent', '=', parent],
      ]);
      for (var i = 0; i < files.length; i++) {
        await Acsys.getStorageURL(files[i].acsys_id)
          .then((result) => {
            files[i]['url'] = result;
          })
          .catch((error) => console.log(error));
      }
      files.sort((a, b) => (a.file_order > b.file_order ? 1 : -1));
    } catch (error) {}
    setLoading(false);
    setIsDialog(isDialog);
    setMode(mode);
    setCon(con);
    setFiles(files);
  }, []);

  const getPrevButton = () => {
    return mode !== 'standard' ? (
      <Grid item>
        <Tooltip title="Back">
          <IconButton onClick={() => previousDirFunc()}>
            <KeyboardArrowLeft color="inherit" />
          </IconButton>
        </Tooltip>
      </Grid>
    ) : (
      <div></div>
    );
  };
  const renderIcon = (content_type, url) => {
    if (content_type === 'Folder') {
      return (
        <TableCell style={{ width: 40, paddingRight: 0 }}>
          <FolderOpen />
        </TableCell>
      );
    } else if (content_type.includes('image')) {
      return (
        <TableCell style={{ width: 40, paddingRight: 0 }}>
          <img
            src={url}
            style={{ cursor: 'pointer', height: 40, width: 40, margin: 0 }}
            onClick={() => openImg(url)}
          />
        </TableCell>
      );
    } else {
      return (
        <TableCell style={{ width: 40, paddingRight: 0 }}>
          <Description
            style={{ cursor: 'pointer', height: 40, width: 40, margin: 0 }}
            onClick={() => window.open(url, '_blank')}
          />
        </TableCell>
      );
    }
  };
  const renderName = (id, content_type, name) => {
    if (content_type === 'Folder') {
      if (mode === 'standard') {
        return (
          <TableCell>
            <a onClick={() => openDirPage(id)} style={{ cursor: 'pointer' }}>
              {name}
            </a>
          </TableCell>
        );
      } else {
        return (
          <TableCell>
            <a onClick={() => openDir(id)} style={{ cursor: 'pointer' }}>
              {name}
            </a>
          </TableCell>
        );
      }
    } else {
      if (mode === 'standard') {
        return (
          <TableCell>
            <a>{name}</a>
          </TableCell>
        );
      } else {
        return (
          <TableCell>
            <a onClick={() => set(name, id)} style={{ cursor: 'pointer' }}>
              {name}
            </a>
          </TableCell>
        );
      }
    }
  };
  const renderTableData = () => {
    return files
      .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
      .map((file, index) => {
        const { acsys_id, name, content_type, updated, is_public, url } = file;
        if (name.length > 0) {
          return (
            <TableRow key={index}>
              {renderIcon(content_type, url, name)}
              {renderName(acsys_id, content_type, name)}
              <TableCell>{content_type}</TableCell>
              <TableCell>{updated}</TableCell>
              {Acsys.getMode() !== 'Viewer' ? (
                <TableCell style={{ minWidth: 100 }} align="right">
                  {is_public ? (
                    <Tooltip title="Public To Internet">
                      <IconButton
                        edge="start"
                        color="inherit"
                        aria-label="make private"
                        onClick={() => makeFilePrivate(acsys_id)}
                        style={{ marginRight: 10 }}
                      >
                        <LockOpen />
                      </IconButton>
                    </Tooltip>
                  ) : (
                    <Tooltip title="Not Public">
                      <IconButton
                        edge="start"
                        color="inherit"
                        aria-label="make public"
                        onClick={() => makeFilePublic(acsys_id)}
                        style={{ marginRight: 10 }}
                      >
                        <Lock />
                      </IconButton>
                    </Tooltip>
                  )}
                  <Tooltip title="Delete File">
                    <IconButton
                      edge="start"
                      color="inherit"
                      aria-label="delete"
                      onClick={() => handleDeleteOpen(acsys_id)}
                    >
                      <Delete />
                    </IconButton>
                  </Tooltip>
                </TableCell>
              ) : (
                <div />
              )}
            </TableRow>
          );
        } else {
          return <div />;
        }
      });
  };

  if (con) {
    try {
      return (
        <div>
          <Paper style={{ margin: 'auto', overflow: 'hidden', clear: 'both' }}>
            <AppBar
              position="static"
              elevation={0}
              style={{
                backgroundColor: '#fafafa',
                borderBottom: '1px solid #dcdcdc',
              }}
            >
              <Toolbar style={{ margin: 4, paddingLeft: 12, paddingRight: 12 }}>
                {Acsys.getMode() !== 'Viewer' ? (
                  <Grid container spacing={1}>
                    <Grid item xs style={{ overflow: 'hidden' }}>
                      <Typography
                        align="left"
                        variant="subtitle2"
                        noWrap
                        style={{ marginTop: 10, color: '#000000' }}
                      >
                        {currentDir}
                      </Typography>
                    </Grid>
                    {getPrevButton()}
                    <Grid item style={{ minWidth: 20 }}>
                      <Tooltip title="Scan For File Updates">
                        <Button
                          variant="contained"
                          color="primary"
                          onClick={handleSyncOpen}
                        >
                          Scan
                        </Button>
                      </Tooltip>
                    </Grid>
                    <Grid item style={{ minWidth: 20 }}>
                      <input
                        id="contained-button-file"
                        type="file"
                        style={{ display: 'none' }}
                        ref={setRef}
                        onChange={uploadFileFunc}
                      />
                      <label htmlFor="contained-button-file">
                        <Tooltip title="Upload File">
                          <Button
                            variant="contained"
                            color="primary"
                            component="span"
                          >
                            Upload
                          </Button>
                        </Tooltip>
                      </label>
                    </Grid>
                    <Grid item style={{ minWidth: 20 }}>
                      <Tooltip title="New Folder">
                        <Button
                          variant="contained"
                          color="primary"
                          onClick={newFolderOpen}
                        >
                          New Folder
                        </Button>
                      </Tooltip>
                    </Grid>
                  </Grid>
                ) : (
                  <Grid container spacing={1}>
                    <Grid item xs style={{ overflow: 'hidden' }}>
                      <Typography
                        align="left"
                        variant="subtitle2"
                        noWrap
                        style={{ marginTop: 10, color: '#000000' }}
                      >
                        {currentDir}
                      </Typography>
                    </Grid>
                    {getPrevButton()}
                  </Grid>
                )}
              </Toolbar>
            </AppBar>
            <div style={{ margin: 'auto', overflow: 'auto' }}>
              <Table>
                <TableHead style={{ backgroundColor: '#fafafa' }}>
                  <TableRow>
                    <TableCell
                      colSpan={2}
                      style={{
                        paddingLeft: 16,
                        paddingRight: 16,
                        paddingTop: 5,
                        paddingBottom: 5,
                      }}
                    >
                      NAME
                    </TableCell>
                    <TableCell
                      style={{
                        paddingLeft: 16,
                        paddingRight: 16,
                        paddingTop: 5,
                        paddingBottom: 5,
                        width: 100,
                      }}
                    >
                      TYPE
                    </TableCell>
                    <TableCell
                      style={{
                        paddingLeft: 16,
                        paddingRight: 16,
                        paddingTop: 5,
                        paddingBottom: 5,
                        width: 110,
                      }}
                    >
                      LAST MODIFIED
                    </TableCell>
                    {Acsys.getMode() !== 'Viewer' ? (
                      <TableCell
                        style={{
                          paddingLeft: 16,
                          paddingRight: 16,
                          paddingTop: 5,
                          paddingBottom: 5,
                          width: 100,
                        }}
                        align="right"
                      >
                        ACTIONS
                      </TableCell>
                    ) : (
                      <div />
                    )}
                  </TableRow>
                </TableHead>
                <TableBody>{renderTableData()}</TableBody>
              </Table>
            </div>
            <TablePagination
              rowsPerPageOptions={[25]}
              component="div"
              count={files.length}
              rowsPerPage={rowsPerPage}
              page={page}
              backIconButtonProps={{
                'aria-label': 'previous page',
              }}
              nextIconButtonProps={{
                'aria-label': 'next page',
              }}
              onChangePage={handleChangePage}
              // onChangeRowsPerPage={handleChangeRowsPerPage}
            />
            <LoadingDialog loading={loading} message={'Loading'} />
            <MessageDialog
              open={openMessage}
              closeDialog={closeMessage}
              title={messageTitle}
              message={message}
            />
            <YesNoDialog
              open={syncing}
              closeDialog={handleSyncClose}
              title={'Sync files?'}
              message={
                'Are you sure you want to resync files? This operation can require multiple writes.'
              }
              action={syncFiles}
            />
            <ImageDialog
              open={isOpenImage}
              closeDialog={handleImgClose}
              imgUrl={imgUrl}
            />
            <NewFolderDialog
              open={newFolder}
              closeDialog={newFolderClose}
              handleChange={handleChange}
              createNewFolder={createNewFolder}
            />
            <YesNoDialog
              open={deleting}
              closeDialog={handleDeleteClose}
              title={'Delete file?'}
              message={'Are you sure you want to delete this file?'}
              action={deleteFile}
              actionProcess={deleteLoading}
            />
          </Paper>
        </div>
      );
    } catch (error) {
      console.log('error', error);
      return (
        <div style={{ maxWidth: 1236, margin: 'auto' }}>
          <Paper style={{ height: 40 }}>
            <div style={{ padding: 10, margin: 'auto' }}>
              Please make sure database has been created.
            </div>
          </Paper>
        </div>
      );
    }
  } else {
    return (
      <div style={{ maxWidth: 1236, margin: 'auto' }}>
        <Paper style={{ height: 40 }}>
          <div style={{ padding: 10, margin: 'auto' }}>
            Please configure storage.
          </div>
        </Paper>
      </div>
    );
  }
}
Example #4
Source File: AgentsTable.js    From voicemail-for-amazon-connect with Apache License 2.0 4 votes vote down vote up
render() {
        let classes = this.props.classes;
        return (
            <div className={this.props.className}>
                <Paper className={classes.root}>
                    <div className={classes.topBar}>
                        <Grid container justify={"space-between"} alignItems={"flex-end"} direction={"row"}>
                            <Grid item className={classes.searchBox}>
                                <SearchTextField
                                    ref={(c) => this.searchTextField = c }
                                    showClearButton={this.props.searchFilter !== ""}
                                    searchChangeFunc={this.handleSearchChange}/>
                            </Grid>
                            <Grid item>
                                <Button color="secondary" className={classes.syncButton} onClick={() => this.setState({syncOpen: true})}>
                                    Sync Agents
                                </Button>
                                <AsyncButton loading={this.props.loading} color={"primary"} onClick={() => {
                                    this.props.getAgents();
                                    if (this.searchTextField) {
                                        this.searchTextField.updateSearch("")
                                    }
                                }} >Refresh</AsyncButton>
                            </Grid>
                        </Grid>
                    </div>
                    <Dialog
                        open={this.state.syncOpen}
                        onClose={() => this.setState({syncOpen: false})}
                        aria-labelledby="alert-dialog-title"
                        aria-describedby="alert-dialog-description"
                    >
                        <DialogTitle id="alert-dialog-title">Sync Amazon Connect Agents?</DialogTitle>
                        <DialogContent>
                            <DialogContentText id="alert-dialog-description">
                                This process will sync all users in Amazon Connect to the VM portal.
                            </DialogContentText>
                        </DialogContent>
                        <DialogActions>
                            <Button onClick={() => this.setState({syncOpen: false})} color="primary">
                                Cancel
                            </Button>
                            <Button onClick={this.handleSync} color="primary" autoFocus>
                                Sync
                            </Button>
                        </DialogActions>
                    </Dialog>

                    <Table className={classes.table} stickyHeader aria-label="sticky table" size="small">
                        <TableHead>
                            <TableRow>
                                {headerCells.map(headerCell => (
                                    <TableCell className={classes.tableCell}
                                        key={headerCell.id}
                                        align={headerCell.numeric ? 'right' : 'left'}
                                        padding={headerCell.disablePadding ? 'none' : 'default'}>
                                        <TableSortLabel
                                            onClick={() => this.sortBy(headerCell.id)}
                                            key={headerCell.id}
                                            hideSortIcon={!headerCell.sortable}
                                            active={this.props.sortKey === headerCell.id}
                                            direction={this.props.sortOrder}
                                            IconComponent={ArrowDropDown}>
                                            {headerCell.label}
                                        </TableSortLabel>
                                    </TableCell>
                                ))}
                            </TableRow>
                        </TableHead>
                        <TableBody>
                            {this.props.agents.map(agent => (
                                <TableRow key={agent.userId} hover onClick={() => {this.showAgent(agent)}}>
                                    <TableCell align="left">{agent.username}</TableCell>
                                    <TableCell align="left">{agent.extension}</TableCell>
                                    <TableCell align="left">{
                                        this.props.encryptVoicemail ?
                                            <Check fontSize="inherit"/> : 
                                                ( agent.encryptVoicemail ? 
                                                    <Check fontSize="inherit"/> : null ) }
                                    </TableCell>
                                    <TableCell align="left">{
                                        agent.transcribeVoicemail ?
                                            <Check className={this.props.transcribeVoicemail ? null : classes.checkDisable} fontSize="inherit"/> :
                                            null}
                                    </TableCell>
                                    <TableCell align="left">
                                        <span
                                            className={classes.delivery}>{agent.deliverEmail ? "Email" : ""}</span>
                                        <span
                                            className={classes.delivery}>{agent.deliverSMS ? `SMS: ${agent.deliverSMSPhoneNumber}` : ""}</span>
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>

                    <div className={classes.navigationBar}>
                        <Button disabled={this.props.page.prev.length === 0} onClick={() => {
                            this.props.getAgents(this.props.page.prev[this.props.page.prev.length - 1]);
                        }}><KeyboardArrowLeft className={classes.navButton}/></Button>
                        <Button disabled={this.props.page.next.length === 0} onClick={() => {
                            this.props.getAgents(this.props.page.next[0]);
                        }}><KeyboardArrowRight className={classes.navButton}/></Button>
                    </div>
                </Paper>
            </div>
        )
    }