@material-ui/core#NativeSelect JavaScript Examples

The following examples show how to use @material-ui/core#NativeSelect. 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: CountryPicker.jsx    From ReactJS-Projects with MIT License 6 votes vote down vote up
Countries = ({ handleCountryChange }) => {
  const [countries, setCountries] = useState([]);

  useEffect(() => {
    const fetchAPI = async () => {
      setCountries(await fetchCountries());
    };

    fetchAPI();
  }, []);

  return (
    <FormControl className={styles.formControl}>
      <NativeSelect defaultValue="" onChange={(e) => handleCountryChange(e.target.value)}>
        <option value="">United States</option>
        {countries.map((country, i) => <option key={i} value={country}>{country}</option>)}
      </NativeSelect>
    </FormControl>
  );
}
Example #2
Source File: BooleanSelect.js    From acsys with MIT License 6 votes vote down vote up
export default function NumberEditor(props) {
  return (
    <Grid item xs={props.width}>
      <h3 className="element-header">{props.field_name.toUpperCase()}</h3>
      <NativeSelect
        defaultValue={Boolean(props.defaultValue)}
        onChange={(e) =>
          props.handleChange(props.currentKey, e.target.value == 'true')
        }
        inputProps={{
          name: props.currentKey,
        }}
        style={{ width: '100%' }}
      >
        <option value>True</option>
        <option value={false}>False</option>
      </NativeSelect>
    </Grid>
  );
}
Example #3
Source File: index.js    From Edlib with GNU General Public License v3.0 6 votes vote down vote up
render() {
        const { classes } = this.props;
        return (
            <div className="adapterSelector">
                <FormControl
                    className={classes.formControl}
                >
                    <NativeSelect
                        value={this.props.current}
                        onChange={event => this.handleChange(event.target.value)}
                        name="adapterMode"
                        className={classes.nativeSelect}
                    >
                        {this.props.adapters.map(data => (<option key={data.key} value={data.key}>{data.name}</option>))}
                    </NativeSelect>
                </FormControl>
            </div>
        );
    }
Example #4
Source File: CountryPicker (2).jsx    From CovidIndiaStats with MIT License 6 votes vote down vote up
CountryPicker = ({ handleCountryChange }) => {
  const [fetchedCountries, setFetchedCountries] = useState([]);

  useEffect(() => {
    const fetchAPI = async () => {
      setFetchedCountries(await countries());
    };

    fetchAPI();
  }, [setFetchedCountries]);
  if (fetchedCountries) {
    return (
      <FormControl
        className={`${styles.formControl} fadeInUp`}
        style={{ animationDelay: "1s" }}
      >
        <NativeSelect
          defaultValue=""
          onChange={(e) => handleCountryChange(e.target.value)}
          onClick={ReactGa.event({
            category: "Global options",
            action: "Global options checked",
          })}
        >
          <option value="Global">Global</option>
          {fetchedCountries.map((item, i) => (
            <option value={item.country} key={i}>
              {item.country}
            </option>
          ))}
        </NativeSelect>
      </FormControl>
    );
  } else return null;
}
Example #5
Source File: CountryPicker.jsx    From javascript-mini-projects with The Unlicense 6 votes vote down vote up
CountryPicker = ({ handleCountryChange }) => {
const [fetchedCountries, setFetchedCountries]= useState([]);

    useEffect(() => {
        const fetchAPI = async () => {
            setFetchedCountries(await fetchCountries());
        }
        fetchAPI();
    }, [setFetchedCountries]);

    console.log(fetchedCountries);

    return(
        <FormControl className={styles.formControl}>
            <NativeSelect defaultValue="" onChange={(e) => handleCountryChange (e.target.value)}>
                <option value="">Global</option>
                {fetchedCountries.map((country, i) => <option key={i} value={country}>{country}</option>)}
            </NativeSelect>
        </FormControl>
    )
}
Example #6
Source File: index.jsx    From redive_linebot with MIT License 5 votes vote down vote up
EditForm = ({ onCancel, onSubmit }) => {
  const classes = useStyles();
  const [{ data: bossData = [], loading }] = useAxios("/api/Admin/WorldBoss");
  const bossEl = useRef(null);
  const announceEl = useRef(null);
  const startTimeEl = useRef(null);
  const endTimeEl = useRef(null);

  const handleSubmit = () => {
    const [startAt, endAt] = [startTimeEl.current.value, endTimeEl.current.value];

    if (startAt >= endAt) {
      alert("請確認活動時間");
      return;
    }

    onSubmit({
      world_boss_id: parseInt(bossEl.current.value),
      announcement: announceEl.current.value,
      start_time: startAt,
      end_time: endAt,
    });
  };

  return (
    <Grid container spacing={1} component={Paper} className={classes.form}>
      {loading && <HeartbeatLoading />}
      <Grid item xs={12}>
        <Typography variant="h5">世界王活動管理</Typography>
      </Grid>
      <Grid item xs={12}>
        <FormControl fullWidth>
          <NativeSelect fullWidth inputRef={bossEl}>
            {bossData.map(boss => (
              <option key={boss.id} value={boss.id}>
                {boss.name}
              </option>
            ))}
          </NativeSelect>
          <FormHelperText>請選擇世界王來綁定活動,若無世界王,請先去新增世界王</FormHelperText>
        </FormControl>
      </Grid>
      <Grid item xs={12}>
        <TextField label="活動公告" multiline fullWidth margin="normal" inputRef={announceEl} />
      </Grid>
      <Grid item xs={6}>
        <FormControl fullWidth required margin="normal">
          <FormLabel>開始時間</FormLabel>
          <Input inputProps={{ type: "datetime-local" }} inputRef={startTimeEl} />
        </FormControl>
      </Grid>
      <Grid item xs={6}>
        <FormControl fullWidth required margin="normal">
          <FormLabel>結束時間</FormLabel>
          <Input inputProps={{ type: "datetime-local" }} inputRef={endTimeEl} />
        </FormControl>
      </Grid>
      <Grid item xs={6}>
        <Button variant="contained" color="secondary" fullWidth onClick={onCancel}>
          取消
        </Button>
      </Grid>
      <Grid item xs={6}>
        <Button variant="contained" color="primary" fullWidth onClick={handleSubmit}>
          新增
        </Button>
      </Grid>
    </Grid>
  );
}
Example #7
Source File: NewUserDialog.js    From acsys with MIT License 4 votes vote down vote up
export default function NewUserDialog(props) {
  return (
    <Dialog
      open={props.open}
      onClose={props.closeDialog}
      aria-labelledby="alert-dialog-title"
      aria-describedby="alert-dialog-description"
    >
      <DialogTitle id="alert-dialog-title">{'Add User'}</DialogTitle>
      <DialogContent>
        <Typography variant="p" color="secondary">
          {props.message}
        </Typography>
        <NativeSelect
          onChange={(e) => props.setRole(e.target.value)}
          style={{ width: '97%' }}
        >
          <option value={'Administrator'}>Administrator</option>
          <option value={'Standard User'}>Standard User</option>
          <option value={'Contributor'}>Viewer</option>
        </NativeSelect>

        <input
          id="email"
          name="email"
          placeholder="Email"
          margin="normal"
          color="primary"
          variant="outlined"
          style={{ width: '97%', marginTop: '20px' }}
          value={props.email}
          onChange={(e) => props.setEmail(e.target.value)}
        />

        <input
          id="username"
          name="username"
          placeholder="Username"
          margin="normal"
          color="primary"
          variant="outlined"
          style={{ width: '97%', marginTop: '20px' }}
          value={props.username}
          onChange={(e) => props.setUsername(e.target.value)}
        />

        <input
          id="passwordOne"
          name="passwordOne"
          placeholder="Password"
          margin="normal"
          color="primary"
          variant="outlined"
          type="password"
          style={{ width: '97%', marginTop: '20px' }}
          value={props.passwordOne}
          onChange={(e) => props.setPasswordOne(e.target.value)}
        />

        <input
          id="passwordTwo"
          name="passwordTwo"
          placeholder="Confirm Password"
          margin="normal"
          color="primary"
          variant="outlined"
          type="password"
          style={{ width: '97%', marginTop: '20px' }}
          value={props.passwordTwo}
          onChange={(e) => props.setPasswordTwo(e.target.value)}
        />
      </DialogContent>
      <DialogActions>
        <Button onClick={props.action} color="primary" autoFocus>
          {props.actionProcess && <CircularProgress size={24} />}
          {!props.actionProcess && 'Add'}
        </Button>
        <Button onClick={props.closeDialog} color="primary" autoFocus>
          Cancel
        </Button>
      </DialogActions>
    </Dialog>
  );
}
Example #8
Source File: ViewDialog.js    From acsys with MIT License 4 votes vote down vote up
export default function ViewDialog(props) {
  return (
    <Dialog
      open={props.open}
      onClose={props.closeDialog}
      aria-labelledby="alert-dialog-title"
      aria-describedby="alert-dialog-description"
      maxWidth={'sm'}
    >
      <DialogTitle id="alert-dialog-title">View Settings</DialogTitle>
      <DialogContent>
        <DialogContentText id="alert-dialog-description"></DialogContentText>
        <div>
          <Grid container spacing={0}>
            <Grid item xs={3}>
              <div>
                <Typography>Order By Field</Typography>
              </div>
            </Grid>
            <Grid item xs={3}>
              <div>
                <Typography>Order</Typography>
              </div>
            </Grid>
            <Grid item xs={3}>
              <div>
                <Typography>Entries Per Page</Typography>
              </div>
            </Grid>
            <Grid item xs={3}>
              <div>
                <Typography>Update Mode</Typography>
              </div>
            </Grid>
            <Grid item xs={3}>
              <div>
                <NativeSelect
                  defaultValue={props.viewOrderField}
                  onChange={(e) => props.setOrderField(e.target.value)}
                >
                  <option value="none">none</option>
                  {Object.values(props.docDetails).map((detail) => {
                    return (
                      <option value={detail.field_name}>
                        {detail.field_name}
                      </option>
                    );
                  })}
                </NativeSelect>
              </div>
            </Grid>
            <Grid item xs={3}>
              <div>
                <NativeSelect
                  defaultValue={props.viewOrder}
                  onChange={(e) => props.setOrder(e.target.value)}
                >
                  <option value={'asc'}>asc</option>
                  <option value={'desc'}>desc</option>
                </NativeSelect>
              </div>
            </Grid>
            <Grid item xs={3}>
              <div>
                <NativeSelect
                  defaultValue={props.rowNum}
                  onChange={(e) =>
                    props.setEntriesPerPage(parseInt(e.target.value))
                  }
                >
                  <option value={5}>5</option>
                  <option value={10}>10</option>
                  <option value={15}>15</option>
                  <option value={20}>20</option>
                  <option value={50}>50</option>
                  <option value={100}>100</option>
                </NativeSelect>
              </div>
            </Grid>
            <Grid item xs={3}>
              <div>
                <NativeSelect
                  defaultValue={props.isRemovable}
                  onChange={(e) =>
                    props.setUpdateOnly('true' == e.target.value)
                  }
                  style={{ width: '100%' }}
                >
                  <option value={true}>Add/Remove</option>
                  <option value={false}>Update Only</option>
                </NativeSelect>
              </div>
            </Grid>
            <Grid item xs={12} style={{ marginTop: 20 }}>
              <div>
                <Typography>Status For Table [{props.viewTable}]</Typography>
              </div>
            </Grid>
            <Grid item xs={12}>
              <div>
                <NativeSelect
                  defaultValue={props.locked}
                  onChange={(e) =>
                    props.setLockedValue('true' == e.target.value)
                  }
                  style={{ width: '100%' }}
                >
                  <option value={true}>Locked (No API Access)</option>
                  <option value={false}>Unlocked (API Access)</option>
                </NativeSelect>
              </div>
            </Grid>
          </Grid>
        </div>
      </DialogContent>
      <DialogActions>
        <Button onClick={props.action} color="primary" autoFocus>
          {props.actionProcess && <CircularProgress size={24} />}
          {!props.actionProcess && 'Save'}
        </Button>
        <Button onClick={props.closeDialog} color="primary" autoFocus>
          Cancel
        </Button>
      </DialogActions>
    </Dialog>
  );
}
Example #9
Source File: FieldDefCard.js    From acsys with MIT License 4 votes vote down vote up
Card = memo(({ id, details, moveCard }) => {
  const ref = useRef(null);
  const [{ isDragging }, connectDrag] = useDrag({
    item: { id, type: ItemTypes.CARD },
    collect: (monitor) => {
      const result = {
        isDragging: monitor.isDragging(),
      };
      return result;
    },
  });
  const [, connectDrop] = useDrop({
    accept: ItemTypes.CARD,
    hover({ id: draggedId }) {
      if (draggedId !== id) {
        moveCard(draggedId, id);
      }
    },
  });
  connectDrag(ref);
  connectDrop(ref);
  const opacity = isDragging ? 0 : 1;
  const containerStyle = useMemo(() => ({ ...style, opacity }), [opacity]);
  const data = [];

  data.push(<option value="none">none</option>);

  if (details.type === 'string') {
    data.push(<option value="autoGen">autoGen</option>);
    data.push(<option value="textEditor">textEditor</option>);
    data.push(<option value="richTextEditor">richTextEditor</option>);
    data.push(<option value="dateTimePicker">dateTimePicker</option>);
    data.push(<option value="imageReference">imageReference</option>);
    data.push(<option value="imageURL">imageURL</option>);
    data.push(<option value="videoReference">videoReference</option>);
    data.push(<option value="videoURL">videoURL</option>);
  }

  if (details.type === 'boolean') {
    data.push(<option value="booleanSelect">boolean</option>);
  }

  if (details.type === 'number') {
    data.push(<option value="numberEditor">numberEditor</option>);
    data.push(<option value="booleanSelect">boolean</option>);
  }

  const width = [];

  for (let i = 0; i < 12; i++) {
    width.push(<option value={i + 1}>{i + 1}</option>);
  }

  const setControl = (event) => {
    details.control = event;
  };
  const setKey = (event) => {
    details.is_key = event;
  };
  const showOnTable = (event) => {
    details.is_visible_on_table = event;
  };
  const showOnPage = (event) => {
    details.is_visible_on_page = event;
  };
  const setWidth = (event) => {
    details.width = parseInt(event);
  };

  return (
    <Paper style={{ maxHeight: 160, marginBottom: 30 }}>
      <AppBar
        style={{ height: 30, borderBottom: '1px solid rgba(0, 0, 0, 0.12)' }}
        position="static"
        color="default"
        elevation={0}
      >
        <Typography variant="subtitle1" align="center">
          {details.field_name}
        </Typography>
      </AppBar>
      <div ref={ref} style={containerStyle}>
        <Grid container spacing={2}>
          <Grid item xs={3}>
            <div>
              <Typography>Control</Typography>
            </div>
          </Grid>
          <Grid item xs={2}>
            <div>
              <Typography>Key</Typography>
            </div>
          </Grid>
          <Grid item xs={2}>
            <div>
              <Typography>Show on table</Typography>
            </div>
          </Grid>
          <Grid item xs={2}>
            <div>
              <Typography>Show on page</Typography>
            </div>
          </Grid>
          <Grid item xs={2}>
            <div>
              <Typography>Width on page</Typography>
            </div>
          </Grid>
          <Grid item xs={3}>
            <div>
              <NativeSelect
                defaultValue={details.control}
                onChange={(e) => setControl(e.target.value)}
              >
                {data}
              </NativeSelect>
            </div>
          </Grid>
          <Grid item xs={2}>
            <div>
              <NativeSelect
                defaultValue={Boolean(details.is_key)}
                onChange={(e) => setKey(e.target.value == 'true')}
              >
                <option value={true}>True</option>
                <option value={false}>False</option>
              </NativeSelect>
            </div>
          </Grid>
          <Grid item xs={2}>
            <div>
              <NativeSelect
                defaultValue={Boolean(details.is_visible_on_table)}
                onChange={(e) => showOnTable(e.target.value == 'true')}
              >
                <option value={true}>Show</option>
                <option value={false}>Hide</option>
              </NativeSelect>
            </div>
          </Grid>
          <Grid item xs={2}>
            <div>
              <NativeSelect
                defaultValue={Boolean(details.is_visible_on_page)}
                onChange={(e) => showOnPage(e.target.value == 'true')}
              >
                <option value={true}>Show</option>
                <option value={false}>Hide</option>
              </NativeSelect>
            </div>
          </Grid>
          <Grid item xs={2}>
            <div>
              <NativeSelect
                defaultValue={details.width}
                onChange={(e) => setWidth(e.target.value)}
              >
                {width}
              </NativeSelect>
            </div>
          </Grid>
        </Grid>
      </div>

      {moveCard}
    </Paper>
  );
})
Example #10
Source File: Card.js    From acsys with MIT License 4 votes vote down vote up
Card = memo(({ id, entry, deleteField }) => {
  const ref = useRef(null);
  const containerStyle = useMemo(() => ({ ...style }));
  const data = [];

  data.push(<option value="string">string</option>);
  data.push(<option value="number">number</option>);
  data.push(<option value="boolean">boolean</option>);

  const width = [];

  for (let i = 0; i < 12; i++) {
    width.push(<option value={i + 1}>{i + 1}</option>);
  }

  const setDataType = (event) => {
    entry.dataType = event;
  };
  const setFieldName = (event) => {
    entry.fieldName = event;
  };
  const setValue = (event) => {
    entry.value = event;
  };

  return (
    <Paper style={{ maxHeight: 160, marginBottom: 30 }}>
      <AppBar
        style={{ height: 30, borderBottom: '1px solid rgba(0, 0, 0, 0.12)' }}
        position="static"
        color="default"
        elevation={0}
      >
        <Grid container spacing={1}>
          <Grid item xs />
          <Grid item>
            <IconButton
              edge="start"
              aria-label="remove"
              style={{ padding: 0 }}
              onClick={() => deleteField(entry)}
            >
              <Close />
            </IconButton>
          </Grid>
        </Grid>
      </AppBar>
      <div ref={ref} style={containerStyle}>
        <Grid container spacing={2}>
          <Grid item xs={2}>
            <div>
              <Typography>Data Type</Typography>
            </div>
          </Grid>
          <Grid item xs={5}>
            <div>
              <Typography>Field Name</Typography>
            </div>
          </Grid>
          <Grid item xs={5}>
            <div>
              <Typography>Value</Typography>
            </div>
          </Grid>
          <Grid item xs={2}>
            <div>
              <NativeSelect
                defaultValue={entry.dataType}
                onChange={(e) => setDataType(e.target.value)}
              >
                {data}
              </NativeSelect>
            </div>
          </Grid>
          <Grid item xs={5}>
            <div>
              <input
                placeholder="Enter Field Name"
                defaultValue={entry.fieldName}
                onChange={(e) => setFieldName(e.target.value)}
                type="text"
                style={{ width: '90%' }}
              />
            </div>
          </Grid>
          <Grid item xs={5}>
            <div>
              <input
                placeholder="Enter Value"
                defaultValue={entry.value}
                onChange={(e) => setValue(e.target.value)}
                type="text"
                style={{ width: '90%' }}
              />
            </div>
          </Grid>
        </Grid>
      </div>
    </Paper>
  );
})
Example #11
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 #12
Source File: Configuration.js    From acsys with MIT License 4 votes vote down vote up
Configuration = () => {
  const [databaseType, setdatabaseType] = useState('local');
  const [host, sethost] = useState('');
  const [port, setport] = useState('');
  const [database, setdatabase] = useState('');
  const [username, setusername] = useState('');
  const [password, setpassword] = useState('');
  const [socketPath, setsocketPath] = useState('');
  const [projectName, setprojectName] = useState('');
  const [uploadFile, setuploadFile] = useState('');
  const [fileName, setfileName] = useState('');
  const [loading, setloading] = useState(false);
  const [error, seterror] = useState(null);
  const [message, setmessage] = useState('');

  const setRef = (ref) => {
    setfileName(ref.target.files[0].name);
    setuploadFile(ref.target.files[0]);
  };

  const onKeyDownSI = (event) => {
    if (event.key === 'Enter') {
      event.preventDefault();
      event.stopPropagation();
      onSubmit();
    }
  };

  const onSubmit = async (event) => {
    try {
      setloading(true);

      if (databaseType === 'local' && projectName.length < 1) {
        setloading(false);
        setmessage('Please enter a project name.');
      } else {
        if (databaseType === 'firestore') {
          await Acsys.setInitialFirestoreConfig(uploadFile);
          await sleep(5000);
          window.location.reload();
          setloading(false);
        } else if (databaseType === 'mysql') {
          if (
            host.length > 0 &&
            database.length > 0 &&
            username.length > 0 &&
            password.length > 0 &&
            uploadFile
          ) {
            await Acsys.setInitialMysqlConfig(
              host,
              port,
              database,
              username,
              password,
              socketPath,
              uploadFile
            );
            await sleep(5000);
            window.location.reload();
            setloading(false);
          } else {
            setloading(false);
            setmessage('Please complete necessary fields.');
          }
        } else {
          await Acsys.setInitialLocalDatabaseConfig(projectName);
          await sleep(7500);
          window.location.reload();
          setloading(false);
        }
      }
    } catch (error) {
      await sleep(5000);
      window.location.reload();
      setloading(false);
    }
    event.preventDefault();
  };

  const sleep = (time) => {
    return new Promise((resolve) => setTimeout(resolve, time));
  };

  const onChange = (event) => {
    setState({ [event.target.name]: event.target.value });
  };

  const renderConfig = () => {
    if (databaseType === 'local') {
      return (
        <div>
          <input
            id="projectName"
            name="projectName"
            placeholder="Project Name"
            defaultValue={projectName}
            onKeyDown={onKeyDownSI}
            onChange={(event) => setprojectName(event.target.value)}
            style={{ marginTop: '20px', width: '96%' }}
          />
          <Typography variant="p" color="secondary" style={{ minHeight: 25 }}>
            {message}
          </Typography>
          <p style={{ marginBottom: 0 }}>
            When this option is selected Acsys will use the internal database.
          </p>
        </div>
      );
    } else if (databaseType === 'firestore') {
      return (
        <div>
          <p>
            Upload JSON service account key file. Instructions for creating this
            file can be found{' '}
            <Link
              href="https://cloud.google.com/iam/docs/creating-managing-service-account-keys"
              target="_blank"
              color="primary"
              rel="noreferrer"
            >
              here
            </Link>
            .
          </p>
          <Grid container>
            <Grid item xs={3}>
              <input
                id="contained-button-file"
                type="file"
                style={{ display: 'none' }}
                onChange={setRef}
              />
              <label htmlFor="contained-button-file">
                <Button
                  variant="contained"
                  color="primary"
                  component="span"
                  style={{ height: 28 }}
                >
                  Upload
                </Button>
              </label>
            </Grid>
            <Grid item xs={9}>
              <input defaultValue={fileName} style={{ height: 19 }} />
            </Grid>
          </Grid>
        </div>
      );
    } else if (databaseType === 'mysql') {
      return (
        <div>
          <input
            id="host"
            name="host"
            placeholder="Host"
            defaultValue={host}
            onKeyDown={onKeyDownSI}
            onChange={(event) => sethost(event.target.value)}
            style={{ marginTop: '20px', width: '96%' }}
          />
          <input
            id="port"
            name="port"
            placeholder="Port (Optional)"
            defaultValue={port}
            onKeyDown={onKeyDownSI}
            onChange={(event) => setport(event.target.value)}
            type="number"
            style={{ marginTop: '20px', width: '96%' }}
          />
          <input
            id="database"
            name="database"
            placeholder="Database"
            defaultValue={database}
            onKeyDown={onKeyDownSI}
            onChange={(event) => setdatabase(event.target.value)}
            style={{ marginTop: '20px', width: '96%' }}
          />
          <input
            id="username"
            name="username"
            placeholder="Username"
            defaultValue={username}
            onKeyDown={onKeyDownSI}
            onChange={(event) => setusername(event.target.value)}
            style={{ marginTop: '20px', width: '96%' }}
          />
          <input
            id="password"
            name="password"
            placeholder="Password"
            defaultValue={password}
            onKeyDown={onKeyDownSI}
            onChange={(event) => setpassword(event.target.value)}
            type="password"
            style={{ marginTop: '20px', width: '96%' }}
          />
          <input
            id="socketPath"
            name="socketPath"
            placeholder="Socket Path (Production only)"
            defaultValue={socketPath}
            onKeyDown={onKeyDownSI}
            onChange={(event) => setsocketPath(event.target.value)}
            style={{ marginTop: '20px', width: '96%' }}
          />
          <p>
            Instructions for binding the socket path can be found{' '}
            <Link
              href="https://cloud.google.com/sql/docs/mysql/connect-functions"
              target="_blank"
              color="primary"
              rel="noreferrer"
            >
              here
            </Link>
            . Instructions for creating upload file can be found{' '}
            <Link
              href="https://cloud.google.com/iam/docs/creating-managing-service-account-keys"
              target="_blank"
              color="primary"
              rel="noreferrer"
            >
              here
            </Link>
            .
          </p>
          <Grid container>
            <Grid item xs={3}>
              <input
                id="contained-button-file"
                type="file"
                style={{ display: 'none' }}
                onChange={setRef}
              />
              <label htmlFor="contained-button-file">
                <Button
                  variant="contained"
                  color="primary"
                  component="span"
                  style={{ height: 28 }}
                >
                  Upload
                </Button>
              </label>
            </Grid>
            <Grid item xs={9}>
              <input defaultValue={fileName} style={{ height: 19 }} />
            </Grid>
          </Grid>
          <Typography variant="p" color="secondary" style={{ minHeight: 25 }}>
            {message}
          </Typography>
        </div>
      );
    }
  };

  return (
    <Grid
      className="landing-grid"
      container
      alignItems="center"
      justify="center"
      direction="column"
    >
      <Container maxWidth="sm">
        <Paper style={{ margin: '50px' }}>
          <Box
            margin="auto"
            width="80%"
            display="flex"
            flexDirection="column"
            textAlign="center"
            padding="16px"
          >
            <Typography variant="h4" color="primary">
              Configure Database
            </Typography>
            <NativeSelect
              onChange={(e) => setdatabaseType(e.target.value)}
              style={{ marginTop: '20px' }}
            >
              <option value={'local'}>Local</option>
              <option value={'firestore'}>Firestore</option>
              <option value={'mysql'}>MySQL</option>
            </NativeSelect>
            {renderConfig()}
          </Box>
          <Box
            margin="auto"
            width="50%"
            display="flex"
            flexDirection="column"
            textAlign="center"
            padding="16px"
          >
            <Button
              onClick={onSubmit}
              type="submit"
              variant="contained"
              color="primary"
            >
              {loading && <CircularProgress color="white" size={24} />}
              {!loading && 'Submit'}
            </Button>
            {error && (
              <Typography variant="body1" color="error">
                {error.message}
              </Typography>
            )}
          </Box>
        </Paper>
      </Container>
    </Grid>
  );
}
Example #13
Source File: Settings.js    From acsys with MIT License 4 votes vote down vote up
Settings = (props) => {
  const [host, setHost] = useState('');
  const [port, setPort] = useState('');
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [socketPath, setSocketPath] = useState('');
  const [dhost, setDhost] = useState('');
  const [dport, setDport] = useState('');
  const [ddatabase, setDatabase] = useState('');
  const [dusername, setDusername] = useState('');
  const [dpassword, setDpassword] = useState('');
  const [project_name, setProjectName] = useState('');
  const [databaseType, setDatabaseType] = useState('');
  const [type, setType] = useState('');
  const [project_id, setProjectId] = useState('');
  const [private_key_id, setPrivateKeyId] = useState('');
  const [private_key, setPrivateKey] = useState('');
  const [client_email, setClientEmail] = useState('');
  const [client_id, setClientId] = useState('');
  const [auth_uri, setAuthUri] = useState('');
  const [token_uri, setTokenUri] = useState('');
  const [auth_provider_x509_cert_url, setAuthProviderX509CertUrl] =
    useState('');
  const [client_x509_cert_url, setClientX509CertUrl] = useState('');
  const [bucket, setBucket] = useState('');
  const [buckets, setBuckets] = useState([]);
  const [updateBucket, setUpdateBucket] = useState(false);
  const [updateEmail, setUpdateEmail] = useState(false);
  const [updateDatabase, setUpdateDatabase] = useState(false);
  const [updateStorage, setUpdateStorage] = useState(false);
  const [uploadFile, setUploadFile] = useState();
  const [fileName, setFileName] = useState('');
  const [page, setPage] = useState(0);
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [error, setError] = useState('');
  const [message, setMessage] = useState('');
  const [messageOpen, setMessageOpen] = useState(false);
  const [isStateless, setIsStateless] = useState('');

  const handleClickOpen = () => {
    if (updateDatabase || updateStorage || updateEmail || updateBucket) {
      setOpen(true);
    }
  };

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

  const handleMessageClose = () => {
    setMessageOpen(false);
  };

  const closeDialog = () => {
    setLoading(false);
  };

  useEffect(async () => {
    props.setHeader('Settings');
    const isStateless = await Acsys.isStateless();
    const emailConfig = await Acsys.getEmailConfig();
    if (emailConfig.length > 0) {
      setHost(emailConfig[0].host);
      setPort(emailConfig[0].port);
      setUsername(emailConfig[0].username);
      setPassword(emailConfig[0].password);
    }
    const databaseType = await Acsys.getDatabaseType();
    if (!isStateless) {
      const databaseConfig = await Acsys.getDatabaseConfig();
      if (databaseType === 'local') {
        setProjectName(databaseConfig.project_name);
      } else if (databaseType === 'firestore') {
        const currentBucket = await Acsys.getCurrentBucket();
        const buckets = await Acsys.getStorageBuckets();

        setBucket(currentBucket);
        setBuckets(buckets);
        setType(databaseConfig.type);
        setProjectId(databaseConfig.project_id);
        setPrivateKeyId(databaseConfig.private_key_id);
        setPrivateKey(databaseConfig.private_key);
        setClientEmail(databaseConfig.client_email);
        setClientId(databaseConfig.client_id);
        setAuthUri(databaseConfig.auth_uri);
        setTokenUri(databaseConfig.token_uri);
        setAuthProviderX509CertUrl(databaseConfig.auth_provider_x509_cert_url);
        setClientX509CertUrl(databaseConfig.client_x509_cert_url);
      } else if (databaseType === 'mysql') {
        const currentBucket = await Acsys.getCurrentBucket();
        const buckets = await Acsys.getStorageBuckets();
        setBucket(currentBucket);
        setBuckets(buckets);
        setType(databaseConfig.type);
        setProjectId(databaseConfig.project_id);
        setPrivateKeyId(databaseConfig.private_key_id);
        setPrivateKey(databaseConfig.private_key);
        setClientEmail(databaseConfig.client_email);
        setClientId(databaseConfig.client_id);
        setAuthUri(databaseConfig.auth_uri);
        setTokenUri(databaseConfig.token_uri);
        setAuthProviderX509CertUrl(databaseConfig.auth_provider_x509_cert_url);
        setClientX509CertUrl(databaseConfig.client_x509_cert_url);
      }
    }
    setIsStateless(isStateless);
    setDatabaseType(databaseType);
  }, []);

  // setDatabaseType = (type) => {
  //   setState({
  //     databaseType: type,
  //   });
  // };

  const selectBucket = (bucket) => {
    setBucket(bucket);
  };

  const setEmail = async () => {
    const config = {
      host: host,
      port: port,
      username: username,
      password: password,
    };
    await Acsys.setEmailConfig(config);
  };

  const set_bucket = async () => {
    const config = {
      bucket: bucket,
    };
    await Acsys.setStorageBucket(config);
  };

  const handlesetDatabase = async () => {
    if (databaseType === 'firestore') {
      if (uploadFile === undefined) {
        setMessageOpen(true);
        setOpen(false);
        setMessage('Please select a configuration to upload.');
        setLoading(false);
      } else {
        await Acsys.setFirestoreConfig(uploadFile);
      }
    } else if (databaseType === 'mysql') {
      if (
        dhost < 1 ||
        ddatabase < 1 ||
        dusername < 1 ||
        dpassword < 1 ||
        uploadFile === undefined
      ) {
        setMessageOpen(true);
        setOpen(false);
        setMessage(
          'Please complete all necessary database fields and storage setTings.'
        );
        setLoading(false);
      } else {
        await Acsys.setMysqlConfig(
          dhost,
          dport,
          ddatabase,
          dusername,
          dpassword,
          socketPath,
          uploadFile
        );
      }
    } else if (databaseType === 'local') {
      if (project_name.length < 1) {
        setMessageOpen(true);
        setOpen(false);
        setMessage('Please enter a project name.');
        setLoading(false);
      } else {
        await Acsys.setLocalDatabaseConfig(project_name);
      }
    }
  };

  const setConfig = async () => {
    setOpen(false);
    setLoading(false);
    if (updateEmail) {
      setEmail();
      await sleep(5000);
    }
    if (updateBucket) {
      set_bucket();
      await sleep(5000);
    }
    if (updateDatabase || updateStorage) {
      handlesetDatabase();
      await sleep(5000);
    }
    if ((updateDatabase || updateEmail || updateStorage) && loading) {
      await sleep(7500);
      window.location.reload();
    }
    setLoading(false);
  };

  const setRef = (ref) => {
    const fileReader = new FileReader();
    fileReader.onload = (event) => loadFields(event);
    try {
      fileReader.readAsText(ref.target.files[0]);
    } catch (error) {}
    setFileName(ref.target.files[0].name), setUploadFile(ref.target.files[0]);
  };

  const loadFields = (event) => {
    try {
      const setTings = JSON.parse(event.target.result);
      setType(setTings.type);
      setProjectId(ettings.project_id);
      setPrivateKeyId(setTings.private_key_id);
      setPrivateKey(setTings.private_key);
      setClientEmail(setTings.client_email);
      setClientId(setTings.client_id);
      setAuthUri(setTings.auth_uri);
      setTokenUri(setTings.token_uri);
      setAuthProviderX509CertUrl(setTings.auth_provider_x509_cert_url);
      setClientX509CertUrl(setTings.client_x509_cert_url);
    } catch (error) {}
  };

  const sleep = (time) => {
    return new Promise((resolve) => setTimeout(resolve, time));
  };

  const onChange = (event) => {
    // setState({ [event.target.name]: event.target.value });
  };

  const getBucketPanel = () => {
    console.log('buckerts', buckets);
    return (
      <ExpansionPanel
        style={{ clear: 'both' }}
        onChange={(e) => setUpdateBucket(!updateBucket)}
      >
        <ExpansionPanelSummary
          expandIcon={<KeyboardArrowDown />}
          aria-controls="panel1a-content"
          id="panel1a-header"
        >
          <Typography>Bucket Configuration</Typography>
        </ExpansionPanelSummary>
        <ExpansionPanelDetails>
          <Box
            margin="auto"
            width="90%"
            display="flex"
            flexDirection="column"
            textAlign="center"
            padding="16px"
          >
            <NativeSelect
              value={bucket}
              onChange={(e) => setBucket(e.target.value)}
              style={{ width: '100%', paddingTop: 7 }}
            >
              {buckets.map((bucketName) => (
                <option value={bucketName}>{bucketName}</option>
              ))}
            </NativeSelect>
          </Box>
        </ExpansionPanelDetails>
      </ExpansionPanel>
    );
  };

  const getLocalPanel = () => {
    return (
      <ExpansionPanel
        style={{ clear: 'both' }}
        onChange={(e) => setUpdateDatabase(!updateDatabase)}
      >
        <ExpansionPanelSummary
          expandIcon={<KeyboardArrowDown />}
          aria-controls="panel1a-content"
          id="panel1a-header"
        >
          <Typography>Local Configuration</Typography>
        </ExpansionPanelSummary>
        <ExpansionPanelDetails>
          <Box
            margin="auto"
            width="90%"
            display="flex"
            flexDirection="column"
            textAlign="center"
            padding="16px"
          >
            <input
              id="project_name"
              name="project_name"
              placeholder="Project Name"
              value={project_name}
              onChange={(e) => setProjectName(e.target.value)}
              style={{ marginTop: '20px' }}
            />
          </Box>
        </ExpansionPanelDetails>
      </ExpansionPanel>
    );
  };

  const getFirestorePanel = (name) => {
    return (
      <Grid>
        <Grid item xs={12} style={{ marginBottom: 30 }}>
          {bucket.length > 0 ? getBucketPanel() : null}
        </Grid>
        <Grid item xs={12}>
          <ExpansionPanel
            style={{ clear: 'both' }}
            onChange={(e) => setUpdateStorage(!updateStorage)}
          >
            <ExpansionPanelSummary
              expandIcon={<KeyboardArrowDown />}
              aria-controls="panel1a-content"
              id="panel1a-header"
            >
              <Typography>{name} Configuration</Typography>
            </ExpansionPanelSummary>
            <ExpansionPanelDetails>
              <Box
                margin="auto"
                width="90%"
                display="flex"
                flexDirection="column"
                textAlign="center"
                padding="16px"
              >
                <input
                  id="type"
                  name="type"
                  onChange={(e) => setType(e.target.value)}
                  placeholder="Type"
                  value={type}
                  style={{ marginTop: '20px' }}
                />
                <input
                  id="project_id"
                  name="project_id"
                  onChange={(e) => setProjectId(e.target.value)}
                  placeholder="Project ID"
                  value={project_id}
                  style={{ marginTop: '20px' }}
                />
                <input
                  id="private_key_id"
                  name="private_key_id"
                  onChange={(e) => setPrivateKeyId(e.target.value)}
                  placeholder="Private Key ID"
                  value={private_key_id}
                  style={{ marginTop: '20px' }}
                />
                <input
                  id="private_key"
                  name="private_key"
                  onChange={(e) => setPrivateKeyId(e.target.value)}
                  placeholder="Private Key"
                  value={private_key}
                  style={{ marginTop: '20px' }}
                />
                <input
                  id="client_email"
                  name="client_email"
                  onChange={(e) => setClientEmail(e.target.value)}
                  placeholder="Client Email"
                  value={client_email}
                  style={{ marginTop: '20px' }}
                />
                <input
                  id="client_id"
                  name="client_id"
                  onChange={(e) => setClientId(e.target.value)}
                  placeholder="Client ID"
                  value={client_id}
                  style={{ marginTop: '20px' }}
                />
                <input
                  id="auth_uri"
                  name="auth_uri"
                  onChange={(e) => setAuthUri(e.target.value)}
                  placeholder="Auth URI"
                  value={auth_uri}
                  style={{ marginTop: '20px' }}
                />
                <input
                  id="token_uri"
                  name="token_uri"
                  onChange={(e) => setTokenUri(e.target.value)}
                  placeholder="Token URI"
                  value={token_uri}
                  style={{ marginTop: '20px' }}
                />
                <input
                  id="auth_provider_x509_cert_url"
                  name="auth_provider_x509_cert_url"
                  onChange={(e) => setAuthProviderX509CertUrl(e.target.value)}
                  placeholder="Auth Provider x509 Cert URL"
                  value={auth_provider_x509_cert_url}
                  style={{ marginTop: '20px' }}
                />
                <input
                  id="client_x509_cert_url"
                  name="client_x509_cert_url"
                  onChange={(e) => setClientX509CertUrl(e.target.value)}
                  placeholder="Client x509 Cert URL"
                  value={client_x509_cert_url}
                  style={{ marginTop: '20px' }}
                />
                <Grid container style={{ marginTop: '20px' }}>
                  <Grid item xs>
                    <input defaultValue={fileName} style={{ width: '100%' }} />
                  </Grid>
                  <Grid item>
                    <input
                      id="contained-button-file"
                      type="file"
                      style={{ display: 'none' }}
                      onChange={setRef}
                    />
                    <label htmlFor="contained-button-file">
                      <Button
                        variant="contained"
                        color="primary"
                        component="span"
                        style={{ marginLeft: 28, height: 32 }}
                      >
                        New Config
                      </Button>
                    </label>
                  </Grid>
                </Grid>
              </Box>
            </ExpansionPanelDetails>
          </ExpansionPanel>
        </Grid>
      </Grid>
    );
  };

  const getMysqlPanel = () => {
    return (
      <Grid>
        <Grid item xs={12} style={{ marginBottom: 30 }}>
          <ExpansionPanel
            style={{ clear: 'both' }}
            onChange={(e) => setUpdateDatabase(!updateDatabase)}
          >
            <ExpansionPanelSummary
              expandIcon={<KeyboardArrowDown />}
              aria-controls="panel1a-content"
              id="panel1a-header"
            >
              <Typography>MySQL Configuration</Typography>
            </ExpansionPanelSummary>
            <ExpansionPanelDetails>
              <Box
                margin="auto"
                width="90%"
                display="flex"
                flexDirection="column"
                textAlign="center"
                padding="16px"
              >
                <input
                  id="dhost"
                  name="dhost"
                  placeholder="Host"
                  value={dhost}
                  onChange={(e) => setDhost(e.target.value)}
                  style={{ marginTop: '20px' }}
                />
                <input
                  id="dport"
                  name="dport"
                  placeholder="Port (Can be empty)"
                  value={dport}
                  onChange={(e) => setDport(e.target.value)}
                  type="number"
                  style={{ marginTop: '20px' }}
                />
                <input
                  id="ddatabase"
                  name="ddatabase"
                  placeholder="Database"
                  value={ddatabase}
                  onChange={(e) => setDatabase(e.target.value)}
                  style={{ marginTop: '20px' }}
                />
                <input
                  id="dusername"
                  name="dusername"
                  placeholder="Username"
                  value={dusername}
                  onChange={(e) => setDusername(e.target.value)}
                  style={{ marginTop: '20px' }}
                />
                <input
                  id="dpassword"
                  name="dpassword"
                  placeholder="Password"
                  value={dpassword}
                  onChange={(e) => setDpassword(e.target.value)}
                  type="password"
                  style={{ marginTop: '20px' }}
                />
                <input
                  id="socketPath"
                  name="socketPath"
                  placeholder="Socket Path (May be needed for production environments)"
                  value={socketPath}
                  onChange={(e) => setSocketPath(e.target.value)}
                  style={{ marginTop: '20px' }}
                />
              </Box>
            </ExpansionPanelDetails>
          </ExpansionPanel>
        </Grid>
        <Grid item xs={12}>
          {getFirestorePanel('Storage')}
        </Grid>
      </Grid>
    );
  };

  const getConfigPanel = () => {
    if (databaseType === 'local') {
      return getLocalPanel();
    } else if (databaseType === 'firestore') {
      return getFirestorePanel('Firestore');
    } else if (databaseType === 'mysql') {
      return getMysqlPanel();
    }
  };

  return (
    <div>
      <Tooltip title="Save Server setTings">
        <Button
          style={{ float: 'right', marginBottom: 20, marginLeft: 20 }}
          variant="contained"
          color="primary"
          onClick={handleClickOpen}
        >
          Configure
        </Button>
      </Tooltip>
      <Paper
        style={{
          margin: 'auto',
          overflow: 'hidden',
          clear: 'both',
          marginBottom: 20,
        }}
      >
        <div>
          <div class="element-container">
            <Grid container spacing={3}>
              <Grid item xs={12}>
                <Grid container>
                  <Grid item xs={9}>
                    <h1 class="element-header" style={{ marginTop: 0 }}>
                      Configuration
                    </h1>
                  </Grid>
                  <Grid item xs={3}>
                    <Tooltip title="setS Database Type For Project">
                      <NativeSelect
                        value={databaseType}
                        onChange={(e) => setDatabaseType(e.target.value)}
                        style={{ width: '100%', paddingTop: 7 }}
                      >
                        <option value={'local'}>Local</option>
                        <option value={'firestore'}>Firestore</option>
                        <option value={'mysql'}>MySQL</option>
                      </NativeSelect>
                    </Tooltip>
                  </Grid>
                </Grid>
                <Grid item xs={12} style={{ marginBottom: 30 }}>
                  <ExpansionPanel
                    style={{ clear: 'both' }}
                    onChange={(e) => setUpdateEmail(!updateEmail)}
                  >
                    <ExpansionPanelSummary
                      expandIcon={<KeyboardArrowDown />}
                      aria-controls="panel1a-content"
                      id="panel1a-header"
                    >
                      <Typography>Email Configuration</Typography>
                    </ExpansionPanelSummary>
                    <ExpansionPanelDetails>
                      <Box
                        margin="auto"
                        width="90%"
                        display="flex"
                        flexDirection="column"
                        textAlign="center"
                        padding="16px"
                      >
                        <input
                          id="host"
                          name="host"
                          placeholder="Host"
                          value={host}
                          onChange={(e) => setHost(e.target.value)}
                          style={{ marginTop: '20px' }}
                        />
                        <input
                          id="port"
                          name="port"
                          placeholder="Port"
                          value={port}
                          onChange={(e) => setPort(e.target.value)}
                          style={{ marginTop: '20px' }}
                        />
                        <input
                          id="username"
                          name="username"
                          placeholder="Username"
                          value={username}
                          onChange={(e) => setUsername(e.target.value)}
                          style={{ marginTop: '20px' }}
                        />
                        <input
                          id="password"
                          name="password"
                          placeholder="Password"
                          type="password"
                          value={password}
                          onChange={(e) => setPassword(e.target.value)}
                          style={{ marginTop: '20px' }}
                        />
                      </Box>
                    </ExpansionPanelDetails>
                  </ExpansionPanel>
                </Grid>
                {!isStateless ? (
                  <Grid item xs={12}>
                    {getConfigPanel()}
                  </Grid>
                ) : null}
              </Grid>
            </Grid>
          </div>
          <div class="element-container">
            <div style={{ height: 40 }}></div>
          </div>
        </div>
        <LoadingDialog loading={loading} message={'Saving setTings'} />
        <YesNoDialog
          open={open}
          closeDialog={handleClose}
          title={'Update configuration?'}
          message={
            'Are you sure you want to update the configuration? Doing so will overwrite current setTings.'
          }
          action={setConfig}
          actionProcess={loading}
        />
        <MessageDialog
          open={messageOpen}
          closeDialog={handleMessageClose}
          title={'Error'}
          message={message}
        />
      </Paper>
    </div>
  );
}