@mui/material#FormControl JavaScript Examples

The following examples show how to use @mui/material#FormControl. 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: Roles.js    From admin-web with GNU Affero General Public License v3.0 6 votes vote down vote up
render() {
    const { classes, t, roles, Roles, handleAutocomplete } = this.props;
    return (
      <FormControl className={classes.form}>
        <Typography variant="h6" className={classes.headline}>{t('Roles')}</Typography>
        <FormControl className={classes.input}>
          <MagnitudeAutocomplete
            multiple
            disabled={!this.context.includes(SYSTEM_ADMIN_WRITE)}
            value={roles || []}
            filterAttribute={'name'}
            getOptionLabel={(roleID) => Roles.find(r => r.ID === roleID)?.name || ''}
            onChange={handleAutocomplete('roles')}
            className={classes.input} 
            options={Roles || []}
            label={t('Roles')}
            placeholder={t("Search roles") + "..."}
            renderOption={(props, option) => (
              <li {...props} key={option.ID}>
                {option.name || option || ''}
              </li>
            )}
          />
        </FormControl>
      </FormControl>
    );
  }
Example #2
Source File: FormGroupCheckbox.jsx    From matx-react with MIT License 5 votes vote down vote up
export default function FormGroupCheckbox() {
  const [state, setState] = React.useState({
    gilad: true,
    jason: false,
    antoine: false,
  });

  const handleChange = (name) => (event) => {
    setState({ ...state, [name]: event.target.checked });
  };

  const { gilad, jason, antoine } = state;
  const error = [gilad, jason, antoine].filter((v) => v).length !== 2;

  return (
    <AppButtonRoot>
      <FormControl component="fieldset" className="formControl">
        <FormLabel component="legend">Assign responsibility</FormLabel>
        <FormGroup>
          <FormControlLabel
            control={<Checkbox checked={gilad} onChange={handleChange('gilad')} value="gilad" />}
            label="Gilad Gray"
          />
          <FormControlLabel
            control={<Checkbox checked={jason} onChange={handleChange('jason')} value="jason" />}
            label="Jason Killian"
          />
          <FormControlLabel
            control={
              <Checkbox checked={antoine} onChange={handleChange('antoine')} value="antoine" />
            }
            label="Antoine Llorca"
          />
        </FormGroup>
        <FormHelperText>Be careful</FormHelperText>
      </FormControl>

      <FormControl required error={error} component="fieldset" className="formControl">
        <FormLabel component="legend">Pick two</FormLabel>
        <FormGroup>
          <FormControlLabel
            control={<Checkbox checked={gilad} onChange={handleChange('gilad')} value="gilad" />}
            label="Gilad Gray"
          />
          <FormControlLabel
            control={<Checkbox checked={jason} onChange={handleChange('jason')} value="jason" />}
            label="Jason Killian"
          />
          <FormControlLabel
            control={
              <Checkbox checked={antoine} onChange={handleChange('antoine')} value="antoine" />
            }
            label="Antoine Llorca"
          />
        </FormGroup>

        <FormHelperText>You can display an error</FormHelperText>
      </FormControl>
    </AppButtonRoot>
  );
}
Example #3
Source File: Sync.js    From admin-web with GNU Affero General Public License v3.0 5 votes vote down vote up
render() {
    const { classes, t, sync } = this.props;
    const { sortedDevices, order, orderBy, wipingID, snackbar } = this.state;

    return (
      <FormControl className={classes.form}>
        <Grid container alignItems="center"  className={classes.headline}>
          <Typography variant="h6">{t('Mobile devices')}</Typography>
        </Grid>
        <Table size="small">
          <TableHead>
            <TableRow>
              {this.columns.map((column, key) =>
                <TableCell
                  key={key}
                  padding={column.padding || 'normal'}
                >
                  <TableSortLabel
                    active={orderBy === column.value}
                    align="left" 
                    direction={order}
                    onClick={this.handleSort(column.value, column.type, true)}
                  >
                    {t(column.label)}
                  </TableSortLabel>
                </TableCell>
              )}
              <TableCell padding="checkbox">{t('Actions')}</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {(sortedDevices || sync).map((obj, idx) =>
              <TableRow key={idx}>
                <TableCell>{obj.deviceid || ''}</TableCell>
                <TableCell>{obj.deviceuser || ''}</TableCell>
                <TableCell>{(obj.devicetype || '') + ' / ' + (obj.useragent || '')}</TableCell>
                <TableCell>{obj.firstsynctime ? parseUnixtime(obj.firstsynctime) : ''}</TableCell>
                <TableCell>{obj.lastupdatetime ? parseUnixtime(obj.lastupdatetime) : ''}</TableCell>
                <TableCell>{obj.asversion || ''}</TableCell>
                <TableCell>{(obj.foldersSynced || '') + '/' + (obj.foldersSyncable || '')}</TableCell>
                <TableCell>{this.getWipeStatus(obj.wipeStatus)}</TableCell>
                <TableCell style={{ display: 'flex' }}>
                  {obj.wipeStatus >= 2 && <Tooltip title="Cancel remote wipe" placement="top">
                    <IconButton onClick={this.handleRemoteWipeCancel(obj.deviceid)}>
                      <DoNotDisturbOn color="secondary"/>
                    </IconButton>
                  </Tooltip>}
                  {obj.wipeStatus < 2 && <Tooltip title="Remote wipe" placement="top">
                    <IconButton onClick={this.handlePasswordDialog(obj.deviceid)}>
                      <CleaningServices color="error" />
                    </IconButton>
                  </Tooltip>}
                  <Tooltip title="Resync" placement='top'>
                    <IconButton onClick={this.handleResync(obj.deviceid)}>
                      <SyncIcon color="primary"/>
                    </IconButton>
                  </Tooltip>
                  <Tooltip title="Delete device" placement='top'>
                    <IconButton onClick={this.handleRemoteDelete(obj.deviceid)}>
                      <Delete color="error"/>
                    </IconButton>
                  </Tooltip>
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
        <PasswordSafetyDialog
          open={Boolean(wipingID)}
          deviceID={wipingID}
          onClose={this.handlePasswordDialog('')}
          onConfirm={this.handleRemoteWipeConfirm}
        />
        <Feedback
          snackbar={snackbar || ''}
          onClose={() => this.setState({ snackbar: '' })}
        />
      </FormControl>
    );
  }
Example #4
Source File: Layout1Customizer.jsx    From matx-react with MIT License 4 votes vote down vote up
Layout1Customizer = ({ settings, handleChange, handleControlChange }) => {
  return (
    <Fragment>
      <Box mb="16px" mx="12px">
        <ThemeName>Sidebar theme</ThemeName>
        <ToolbarContainer>
          {mainSidebarThemes.map((color, i) => (
            <Tooltip key={i} title={color} placement="top">
              <ToolbarContent
                color={color}
                onClick={() => handleChange('layout1Settings.leftSidebar.theme', color)}
              >
                {settings.layout1Settings.leftSidebar.theme === color && <Icon>done</Icon>}
                <div className={settings.themes[color].palette.type}></div>
              </ToolbarContent>
            </Tooltip>
          ))}
        </ToolbarContainer>
      </Box>

      <Box mb="32px" mx="12px">
        <ThemeName>Sidebar theme</ThemeName>
        <ToolbarContainer>
          {topbarThemes.map((color, i) => (
            <Tooltip key={i} title={color} placement="top">
              <ToolbarContent
                color={color}
                onClick={() => handleChange('layout1Settings.topbar.theme', color)}
              >
                {settings.layout1Settings.topbar.theme === color && <Icon>done</Icon>}
                <div className={settings.themes[color].palette.type}></div>
              </ToolbarContent>
            </Tooltip>
          ))}
        </ToolbarContainer>
      </Box>

      <Box mb="18px" mx="12px">
        <FormControl component="fieldset">
          <FormLabel component="legend">Sidebar mode</FormLabel>
          <RadioGroup
            aria-label="Sidebar"
            name="leftSidebar"
            value={settings.layout1Settings.leftSidebar.mode}
            onChange={handleControlChange('layout1Settings.leftSidebar.mode')}
          >
            <FormControlLabel value="full" control={<Radio />} label="Full" />
            <FormControlLabel value="close" control={<Radio />} label="Close" />
            <FormControlLabel value="compact" control={<Radio />} label="Compact" />
          </RadioGroup>
        </FormControl>
      </Box>

      <Box mb="32px" mx="12px">
        <ThemeName sx={{ mb: 4 }}>Sidebar background image</ThemeName>
        <div>
          <Grid container spacing={3}>
            {sidebarBG.map((bg, i) => (
              <Grid item xs={4} key={i}>
                <BadgeSelected
                  color="primary"
                  badgeContent={<Icon>done</Icon>}
                  invisible={settings.layout1Settings.leftSidebar.bgImgURL !== bg}
                  sx={{ width: '100%', height: '100%', cursor: 'pointer' }}
                >
                  <Paper onClick={() => handleChange('layout1Settings.leftSidebar.bgImgURL', bg)}>
                    <IMG src={bg} alt="" />
                  </Paper>
                </BadgeSelected>
              </Grid>
            ))}
          </Grid>
        </div>
      </Box>

      <Box mb="24px" mx="12px">
        <FormControl component="fieldset">
          <FormLabel component="legend">Topbar</FormLabel>
          <FormGroup>
            <FormControlLabel
              control={
                <Switch
                  checked={get(settings.layout1Settings.topbar, 'show')}
                  onChange={handleControlChange('layout1Settings.topbar.show')}
                />
              }
              label="Show"
            />

            <FormControlLabel
              control={
                <Switch
                  checked={get(settings.layout1Settings.topbar, 'fixed')}
                  onChange={handleControlChange('layout1Settings.topbar.fixed')}
                />
              }
              label="Fixed"
            />
          </FormGroup>
        </FormControl>
      </Box>
    </Fragment>
  );
}
Example #5
Source File: index.js    From neutron with Mozilla Public License 2.0 4 votes vote down vote up
SectionSavedPassword = () => {
  const [credentials, setCredentials] = useState([]);
  const [revealPasswords, setRevealPasswords] = useState({});

  const reloadCredentials = useCallback(() => {
    getAllCredentialsAsync()
      .then((_credentials) => {
        setCredentials(_credentials);
      })
      .catch((err) => {
        // eslint-disable-next-line no-console
        console.log(err);
      });
  }, [setCredentials]);

  useEffect(() => {
    reloadCredentials();
  }, [reloadCredentials]);

  useEffect(() => {
    ipcRenderer.removeAllListeners('password-credentials-added');
    ipcRenderer.on('password-credentials-added', () => {
      reloadCredentials();
    });
    return () => {
      ipcRenderer.removeAllListeners('password-credentials-added');
    };
  }, [reloadCredentials]);

  return (
    <List disablePadding dense>
      {credentials.length < 1 ? (
        <ListItem disabled>
          <ListItemText primary="Saved passwords will appear here." />
        </ListItem>
      ) : (
        <>
          <ListItem>
            <Table size="small" aria-label="Saved Passwords">
              <TableHead>
                <TableRow>
                  <TableCell>Website</TableCell>
                  <TableCell align="right">Username</TableCell>
                  <TableCell align="right">Password</TableCell>
                  <TableCell align="right" />
                </TableRow>
              </TableHead>
              <TableBody>
                {credentials.map((row) => {
                  const key = `${row.domain}-${row.username}`;
                  return (
                    <TableRow key={key}>
                      <TableCell component="th" scope="row">
                        {row.domain}
                      </TableCell>
                      <TableCell align="right">
                        <TextField
                          value={row.username}
                          margin="dense"
                          fullWidth
                          variant="outlined"
                          inputProps={{ 'aria-label': 'Username' }}
                          disabled
                        />
                      </TableCell>
                      <TableCell align="right">
                        <FormControl variant="outlined">
                          <OutlinedInput
                            id="outlined-adornment-password"
                            type={revealPasswords[key] ? 'text' : 'password'}
                            defaultValue={row.password}
                            margin="dense"
                            endAdornment={(
                              <InputAdornment position="end">
                                <IconButton
                                  aria-label="toggle password visibility"
                                  onClick={() => {
                                    setRevealPasswords({
                                      ...revealPasswords,
                                      [key]: !revealPasswords[key],
                                    });
                                  }}
                                  edge="end"
                                  size="large"
                                >
                                  {revealPasswords[key]
                                    ? <VisibilityIcon /> : <VisibilityOffIcon />}
                                </IconButton>
                              </InputAdornment>
                            )}
                            inputProps={{ 'aria-label': 'Password' }}
                            fullWidth
                            onChange={(e) => {
                              const newPassword = e.target.value;
                              saveCredentialAsync(row.domain, row.username, newPassword, row.id)
                                .then(() => reloadCredentials())
                                .catch((err) => {
                                  // eslint-disable-next-line no-console
                                  console.log(err);
                                });
                            }}
                          />
                        </FormControl>
                      </TableCell>
                      <TableCell align="right">
                        <Tooltip title="Remove">
                          <IconButton
                            aria-label="Remove"
                            size="small"
                            onClick={() => {
                              deleteCredentialAsync(row.id)
                                .then(() => reloadCredentials())
                                .catch((err) => {
                                  // eslint-disable-next-line no-console
                                  console.log(err);
                                });
                            }}
                          >
                            <ClearIcon />
                          </IconButton>
                        </Tooltip>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </ListItem>
          <ListItem disabled>
            <ListItemText primary={`Passwords are stored encrypted locally on disk with the master key stored securely in ${getKeytarVaultName()}.`} />
          </ListItem>
        </>
      )}
    </List>
  );
}
Example #6
Source File: AddFetchmail.js    From admin-web with GNU Affero General Public License v3.0 4 votes vote down vote up
render() {
    const { classes, t, open, onClose, username } = this.props;
    const { active, srcServer, srcUser, srcPassword, srcFolder, srcAuth, fetchall, keep, protocol,
      useSSL, sslCertCheck, sslCertPath, sslFingerprint, extraOptions } = this.state;
    const disabled = [srcServer, srcUser, srcPassword, protocol].includes('');
  
    return (
      <Dialog
        onClose={onClose}
        open={open}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>{t('addEntry', { username: username })}</DialogTitle>
        <DialogContent style={{ minWidth: 400 }}>
          <FormControl className={classes.form} autoComplete="off" noValidate>
            <TextField 
              className={classes.input} 
              label={t("Source server")} 
              fullWidth 
              value={srcServer || ''}
              onChange={this.handleInput('srcServer')}
              autoFocus
              required
            />
            <TextField 
              className={classes.input} 
              label={t("Source user")} 
              fullWidth 
              value={srcUser || ''}
              onChange={this.handleInput('srcUser')}
              required
            />
            <form autoComplete="off" noValidate>
              <TextField 
                className={classes.input} 
                label={t("Source password")} 
                fullWidth 
                value={srcPassword || ''}
                onChange={this.handleInput('srcPassword')}
                type="password"
                required
                id="new-password"
                name='new-password'
                autoComplete="new-password"
              />
            </form>
            <TextField 
              className={classes.input} 
              label={t("Source folder")} 
              fullWidth 
              value={srcFolder || ''}
              onChange={this.handleInput('srcFolder')}
            />
            <TextField 
              className={classes.input} 
              label={t("Source auth")} 
              fullWidth 
              value={srcAuth || ''}
              onChange={this.handleInput('srcAuth')}
              select
            >
              {this.authTypes.map(t =>
                <MenuItem key={t} value={t}>{t}</MenuItem>  
              )}
            </TextField>
            <TextField 
              className={classes.input} 
              label={t("Protocol")} 
              fullWidth 
              value={protocol || ''}
              onChange={this.handleInput('protocol')}
              select
              required
            >
              {this.protocols.map(p =>
                <MenuItem key={p} value={p}>{p}</MenuItem>  
              )}
            </TextField>
            <TextField 
              className={classes.input} 
              label={t("SSL certificate path")} 
              fullWidth 
              value={sslCertPath || ''}
              onChange={this.handleInput('sslCertPath')}
              disabled={!useSSL}
            />
            <TextField 
              className={classes.input} 
              label={t("SSL fingerprint")} 
              fullWidth 
              value={sslFingerprint || ''}
              onChange={this.handleInput('sslFingerprint')}
              disabled={!useSSL}
            />
            <TextField 
              className={classes.input} 
              label={t("Extra options")} 
              fullWidth 
              value={extraOptions || ''}
              onChange={this.handleInput('extraOptions')}
            />
            <Grid container>
              <FormControlLabel
                control={
                  <Checkbox
                    checked={active}
                    onChange={this.handleCheckbox('active')}
                    color="primary"
                  />
                }
                label="Active"
              />
              <FormControlLabel
                control={
                  <Checkbox
                    checked={useSSL}
                    onChange={this.handleCheckbox('useSSL')}
                    color="primary"
                  />
                }
                label="Use SSL"
              />
              <FormControlLabel
                control={
                  <Checkbox
                    checked={fetchall}
                    onChange={this.handleCheckbox('fetchall')}
                    color="primary"
                  />
                }
                label="Fetch all"
              />
              <FormControlLabel
                control={
                  <Checkbox
                    checked={keep}
                    onChange={this.handleCheckbox('keep')}
                    color="primary"
                  />
                }
                label="Keep"
              />
              <FormControlLabel
                control={
                  <Checkbox
                    checked={sslCertCheck}
                    onChange={this.handleCheckbox('sslCertCheck')}
                    color="primary"
                    disabled={!useSSL}
                  />
                }
                label="SSL certificate check"
              />
            </Grid>
          </FormControl>
        </DialogContent>
        <DialogActions>
          <Button
            onClick={onClose}
            color="secondary"
          >
            {t('Cancel')}
          </Button>
          <Button
            onClick={this.handleAdd}
            variant="contained"
            color="primary"
            disabled={disabled}
          >
            {t('Add')}
          </Button>
        </DialogActions>
      </Dialog>
    );
  }
Example #7
Source File: DeleteSavedFilter.jsx    From Edlib with GNU General Public License v3.0 4 votes vote down vote up
DeleteSavedFilter = ({
    show,
    onClose,
    savedFilterData,
    onDeleted,
    filterUtils,
}) => {
    const { classes } = useStyles();
    const { t } = useTranslation();
    const request = useRequestWithToken();
    const { edlibApi } = useConfigurationContext();

    const [selected, setSelected] = React.useState(null);
    const selectedSavedFilter = React.useMemo(() => {
        if (!selected) {
            return null;
        }

        return savedFilterData.find((sfd) => sfd.id === selected);
    }, [selected]);

    return (
        <Dialog open={show} onClose={() => onClose()} maxWidth="sm" fullWidth>
            <DialogTitle>{_.capitalize(t('delete_filter'))}</DialogTitle>
            <DialogContent>
                <Box pt={1}>
                    <FormControl
                        variant="outlined"
                        fullWidth
                        className={classes.formControl}
                    >
                        <InputLabel>
                            {_.capitalize(t('choose_filter'))}
                        </InputLabel>
                        <Select
                            value={selected}
                            onChange={(e) => setSelected(e.target.value)}
                            label={_.capitalize(t('choose_filter'))}
                        >
                            {savedFilterData.map((savedFilter) => (
                                <MenuItem
                                    key={savedFilter.id}
                                    value={savedFilter.id}
                                >
                                    {savedFilter.name}
                                </MenuItem>
                            ))}
                        </Select>
                    </FormControl>
                    <div className={classes.formControl}>
                        <FilterChips
                            chips={filterUtils.getChipsFromChoices(
                                selectedSavedFilter
                                    ? selectedSavedFilter.choices
                                    : []
                            )}
                            color="default"
                        />
                    </div>
                </Box>
            </DialogContent>
            <DialogActions>
                <Button
                    color="primary"
                    variant="outlined"
                    onClick={() => onClose()}
                >
                    {t('cancel')}
                </Button>
                <Button
                    color="primary"
                    variant="contained"
                    style={{ marginLeft: 5 }}
                    disabled={!selected}
                    onClick={() => {
                        if (!selected) {
                            return;
                        }

                        let url = edlibApi(`/common/saved-filters/${selected}`);

                        request(url, 'DELETE', {
                            json: false,
                        }).then(() => onDeleted(selected));
                    }}
                >
                    {t('delete')}
                </Button>
            </DialogActions>
        </Dialog>
    );
}
Example #8
Source File: index.js    From fireact with MIT License 4 votes vote down vote up
AddUser = () => {
    const title = 'Add User';
    const mountedRef = useRef(true);
    const history = useHistory(); 

    const { userData } = useContext(AuthContext);
    const { setBreadcrumb } = useContext(BreadcrumbContext);
    const [emailAddress, setEmailAddress] = useState({
        hasError: false,
        error: null,
        value: null
    });
    const [error, setError] = useState(null);
    const [success, setSuccess] = useState(false);
    const [inSubmit, setInSubmit] = useState(false);
    const [selectedRole, setSelectedRole] = useState('user');
    const [inviteDialog, setInviteDialog] = useState(false);

    useEffect(() => {
        setBreadcrumb([
            {
                to: "/",
                text: "Home",
                active: false
            },
            {
                to: "/account/"+userData.currentAccount.id+"/",
                text: userData.currentAccount.name,
                active: false
            },
            {
                to: "/account/"+userData.currentAccount.id+"/users",
                text: 'Manage Users',
                active: false
            },    
            {
                to: null,
                text: title,
                active: true
            }
        ]);
    }, [userData, setBreadcrumb, title]);

    useEffect(() => {
        return () => { 
            mountedRef.current = false
        }
    },[]);

    return (
        <>
            <Paper>
                <Box p={2}>
                {success?(
                        <>
                            {inviteDialog?(
                                <Alert severity="success">The invite is sent to the email address.</Alert>
                            ):(
                                <Alert severity="success">The user is added to the account.</Alert>
                            )}
                            <Stack direction="row" spacing={1} mt={2}>
                                <Button variant="contained" color="primary" onClick={() => history.push("/account/"+userData.currentAccount.id+"/users")} >Back to User List</Button>
                            </Stack>
                        </>
                    ):(
                        <>
                            {error !== null && 
                                <div style={{marginBottom: '20px'}}><Alert severity="error">{error}</Alert></div>
                            }
                            {inviteDialog?(
                                <>
                                    <Alert severity="info">The email is not registered by any existing user. Do you want to send an invite to the user?</Alert>
                                    <Stack direction="row" spacing={1} mt={2}>
                                        <Button variant="contained" color="primary" disabled={inSubmit} onClick={e => {
                                            e.preventDefault();
                                            setInSubmit(true);
                                            const inviteEmailToAccount = CloudFunctions.httpsCallable('inviteEmailToAccount');
                                            inviteEmailToAccount({
                                                accountId: userData.currentAccount.id,
                                                email: emailAddress.value,
                                                role: selectedRole
                                            }).then(res => {
                                                if (!mountedRef.current) return null
                                                setInSubmit(false);
                                                setSuccess(true);
                                            }).catch(err => {
                                                if (!mountedRef.current) return null
                                                setError(err.message);
                                            });
                                        }}>{inSubmit && <Loader />}
                                            Yes, send an invite</Button>
                                        <Button variant="contained" color="secondary" disabled={inSubmit} onClick={() => {
                                                history.push("/account/"+userData.currentAccount.id+"/users");
                                        }}>No</Button>
                                    </Stack>
                                </>
                            ):(
                                <Form handleSubmit={e => {
                                    e.preventDefault();
                                    setError(null);
                                    setSuccess(false);
                                    setInSubmit(true);
                                    const addUserToAccount = CloudFunctions.httpsCallable('addUserToAccount');
                                    addUserToAccount({
                                        accountId: userData.currentAccount.id,
                                        email: emailAddress.value,
                                        role: selectedRole
                                    }).then(res => {
                                        if (!mountedRef.current) return null
                                        setInSubmit(false);
                                        setSuccess(true);
                                    }).catch(err => {
                                        if (!mountedRef.current) return null
                                        setInSubmit(false);
                                        if(err.details && err.details.code === 'auth/user-not-found'){
                                            setInviteDialog(true);
                                            setInSubmit(false);
                                        }else{
                                            setError(err.message);
                                        }
                                    });
                                }}
                                disabled={emailAddress.hasError || emailAddress.value===null || selectedRole===null || inSubmit}
                                submitBtnStyle={(selectedRole!=='remove')?"primary":"danger"}
                                inSubmit={inSubmit}
                                enableDefaultButtons={true}
                                backToUrl={"/account/"+userData.currentAccount.id+"/users"}
                                >

                                    <Input label="Email Address" type="email" name="email-address" hasError={emailAddress.hasError} error={emailAddress.error} minLen={5} maxLen={50} required={true} validRegex="^[a-zA-Z0-9-_+\.]*@[a-zA-Z0-9-_\.]*\.[a-zA-Z0-9-_\.]*$" changeHandler={setEmailAddress} fullWidth />
                                    <FormControl fullWidth>
                                        <InputLabel>Role</InputLabel>
                                        <Select label="Role" value={selectedRole} onChange={e => {
                                            setSelectedRole(e.target.value);
                                        }}>
                                            <MenuItem value="user">user</MenuItem>
                                            <MenuItem value="admin">admin</MenuItem>
                                        </Select>
                                    </FormControl>
                                </Form>
                            )}
                        </>
                    )}                    
                </Box>
            </Paper>
        </>

    )
}
Example #9
Source File: Settings1.js    From react-saas-template with MIT License 4 votes vote down vote up
function Settings1(props) {
  const { classes, pushMessageToSnackbar } = props;
  const [isSaveLoading, setIsSaveLoading] = useState(false);
  const [isDefaultLoading, setIsDefaultLoading] = useState(false);
  const [option1, setOption1] = useState("None");
  const [option2, setOption2] = useState("None");
  const [option3, setOption3] = useState("None");
  const [option4, setOption4] = useState("None");
  const [option5, setOption5] = useState("2 Days");
  const [option6, setOption6] = useState(7500);

  const handleChange = useCallback(
    (event) => {
      const { name, value } = event.target;
      if (name === "option6") {
        if (value > 7500 || value < 1000) {
          return;
        }
      }
      switch (name) {
        case "option1": {
          setOption1(value);
          break;
        }
        case "option2": {
          setOption2(value);
          break;
        }
        case "option3": {
          setOption3(value);
          break;
        }
        case "option4": {
          setOption4(value);
          break;
        }
        case "option5": {
          setOption5(value);
          break;
        }
        case "option6": {
          setOption6(value);
          break;
        }
        default:
          throw new Error("No branch selected in switch statement.");
      }
    },
    [setOption1, setOption2, setOption3, setOption4, setOption5, setOption6]
  );

  const resetState = useCallback(() => {
    setIsSaveLoading(false);
    setIsDefaultLoading(false);
    setOption1("None");
    setOption2("None");
    setOption3("None");
    setOption4("None");
    setOption5("2 Days");
    setOption6(7500);
  }, [
    setIsSaveLoading,
    setIsDefaultLoading,
    setOption1,
    setOption2,
    setOption3,
    setOption4,
    setOption5,
    setOption6,
  ]);

  const onSetDefault = useCallback(() => {
    setIsDefaultLoading(true);
    setTimeout(() => {
      pushMessageToSnackbar({
        text: "Your settings have been reset to default",
      });
      resetState();
    }, 1500);
  }, [pushMessageToSnackbar, resetState]);

  const onSubmit = useCallback(() => {
    setIsSaveLoading(true);
    setTimeout(() => {
      pushMessageToSnackbar({
        text: "Your settings have been saved",
      });
      setIsSaveLoading(false);
    }, 1500);
  }, [setIsSaveLoading, pushMessageToSnackbar]);

  const inputs = [
    {
      state: option1,
      label: "Option 1",
      stateName: "option1",
    },
    {
      state: option2,
      label: "Option 2",
      stateName: "option2",
    },
    {
      state: option3,
      label: "Option 3",
      stateName: "option3",
    },
    {
      state: option4,
      label: "Option 4",
      stateName: "option4",
    },
  ];

  return (
    <Accordion>
      <AccordionSummary expandIcon={<ExpandMoreIcon />}>
        <Typography>Settings 1</Typography>
      </AccordionSummary>
      <AccordionDetails className={classes.dBlock}>
        <List disablePadding>
          <Bordered disableVerticalPadding disableBorderRadius>
            {inputs.map((element, index) => (
              <ListItem
                className="listItemLeftPadding"
                disableGutters
                divider
                key={index}
              >
                <ListItemText>
                  <Typography variant="body2">{element.label}</Typography>
                </ListItemText>
                <FormControl variant="outlined">
                  <ListItemSecondaryAction
                    className={classes.ListItemSecondaryAction}
                  >
                    <Select
                      value={element.state}
                      onChange={handleChange}
                      input={
                        <OutlinedInput
                          name={element.stateName}
                          labelWidth={0}
                          className={classes.numberInput}
                          classes={{ input: classes.numberInputInput }}
                        />
                      }
                      MenuProps={{ disableScrollLock: true }}
                    >
                      {inputOptions.map((innerElement) => (
                        <MenuItem value={innerElement} key={innerElement}>
                          {innerElement}
                        </MenuItem>
                      ))}
                    </Select>
                  </ListItemSecondaryAction>
                </FormControl>
              </ListItem>
            ))}
            <ListItem className="listItemLeftPadding" disableGutters divider>
              <ListItemText>
                <Typography variant="body2">Option 5</Typography>
              </ListItemText>
              <FormControl variant="outlined">
                <ListItemSecondaryAction
                  className={classes.ListItemSecondaryAction}
                >
                  <Select
                    value={option5}
                    onChange={handleChange}
                    input={
                      <OutlinedInput
                        name="option5"
                        labelWidth={0}
                        className={classes.numberInput}
                        classes={{ input: classes.numberInputInput }}
                      />
                    }
                    MenuProps={{ disableScrollLock: true }}
                  >
                    {[
                      "Always",
                      "6 Hours",
                      "12 Hours",
                      "1 Day",
                      "2 Days",
                      "3 Days",
                      "1 Week",
                    ].map((element) => (
                      <MenuItem value={element} key={element}>
                        {element}
                      </MenuItem>
                    ))}
                  </Select>
                </ListItemSecondaryAction>
              </FormControl>
            </ListItem>
            <ListItem className="listItemLeftPadding" disableGutters>
              <ListItemText>
                <Typography variant="body2">Option 6</Typography>
              </ListItemText>
              <FormControl variant="outlined">
                <ListItemSecondaryAction
                  className={classes.ListItemSecondaryAction}
                >
                  <OutlinedInput
                    labelWidth={0}
                    name="option6"
                    value={option6}
                    type="number"
                    onChange={handleChange}
                    className={classes.numberInput}
                    classes={{ input: classes.numberInputInput }}
                    inputProps={{ step: 20 }}
                  />
                </ListItemSecondaryAction>
              </FormControl>
            </ListItem>
          </Bordered>
        </List>
      </AccordionDetails>
      <AccordionDetails className={classes.accordionDetails}>
        <Box mr={1}>
          <Button
            onClick={onSetDefault}
            disabled={isSaveLoading || isDefaultLoading}
          >
            Default {isDefaultLoading && <ButtonCircularProgress />}
          </Button>
        </Box>
        <Button
          variant="contained"
          color="secondary"
          disabled={isSaveLoading || isDefaultLoading}
          onClick={onSubmit}
        >
          Save {isSaveLoading && <ButtonCircularProgress />}
        </Button>
      </AccordionDetails>
    </Accordion>
  );
}
Example #10
Source File: AddClass.js    From admin-web with GNU Affero General Public License v3.0 4 votes vote down vote up
render() {
    const { classes, t, open, onClose, _classes } = this.props;
    const { classname, parentClasses, members, filters, loading, autocompleteInput } = this.state;

    return (
      <Dialog
        onClose={onClose}
        open={open}
        maxWidth="md"
        fullWidth
        TransitionProps={{
          onEnter: this.handleEnter,
        }}>
        <DialogTitle>{t('addHeadline', { item: 'Group' })}</DialogTitle>
        <DialogContent style={{ minWidth: 400 }}>
          <FormControl className={classes.form}>
            <TextField 
              className={classes.input} 
              label={t("Groupname")} 
              fullWidth 
              value={classname || ''}
              onChange={this.handleInput('classname')}
              autoFocus
              required
            />
            <MagnitudeAutocomplete
              value={parentClasses || []}
              filterAttribute={'classname'}
              inputValue={autocompleteInput}
              onChange={this.handleAuto('parentClasses')}
              className={classes.input} 
              options={_classes}
              onInputChange={this.handleInput('autocompleteInput')}
              label={t("Parent groups")}
              multiple
            />
            <TextField 
              className={classes.input} 
              label={t("Members (separate by comma)")} 
              fullWidth 
              value={members || ''}
              onChange={this.handleMemberInput}
            />
          </FormControl>
          <div>
            <Typography variant="body1">{t('Filters (All must be true)')}</Typography>
            {filters.map((ANDFilter, ANDidx) =>
              <Accordion
                className={classes.panel}
                elevation={2 /* 1 has global overwrite */}
                key={ANDidx}
                defaultExpanded
              >
                <AccordionSummary>
                  <Grid container justifyContent="space-between">
                    <Typography body="body1">{t('Filter (One must be true)')}</Typography>
                    <IconButton onClick={this.handleRemoveAND(ANDidx)} size="large">
                      <Delete fontSize="small" color="error"/>
                    </IconButton>
                  </Grid>
                </AccordionSummary>
                <AccordionDetails>
                  <Grid container>
                    {ANDFilter.map((ORFilter, ORidx) =>  
                      <Grid item xs={12} key={ORidx} className={classes.grid}>
                        <Autocomplete
                          value={ORFilter.prop || ''}
                          inputValue={ORFilter.prop || ''}
                          onChange={this.handleAutocomplete(ANDidx, ORidx, 'prop')}
                          onInputChange={this.handleFilterInput(ANDidx, ORidx, 'prop')}
                          freeSolo
                          className={classes.flexTextfield} 
                          options={this.columns}
                          renderInput={(params) => (
                            <TextField
                              {...params}
                              label={t("Name of property to match")}
                            />
                          )}
                        />
                        <TextField
                          className={classes.flexTextfield} 
                          label={t("Comparison operator")}
                          value={ORFilter.op || ''}
                          onChange={this.handleFilterInput(ANDidx, ORidx, 'op')}
                          select
                        >
                          {this.operators.map(op =>
                            <MenuItem value={op.value} key={op.label}>{op.label}</MenuItem>
                          )}
                        </TextField>
                        <TextField
                          className={classes.flexTextfield} 
                          label={t("Compare value (binary operators)")}
                          value={ORFilter.val || ''}
                          onChange={this.handleFilterInput(ANDidx, ORidx, 'val')}
                        />
                        {filters[ANDidx].length > 1 &&
                        <IconButton onClick={this.handleRemoveOR(ANDidx, ORidx)} size="large">
                          <Delete fontSize="small" color="error"/>
                        </IconButton>}
                      </Grid>
                    )}
                    <Grid container justifyContent="center" className={classes.marginTop}>
                      <Button variant="outlined" onClick={this.handleAddOR(ANDidx)}>{t('Add or-statement')}</Button>
                    </Grid>
                  </Grid>
                </AccordionDetails>
              </Accordion>
            )}
            <Grid container justifyContent="center" className={classes.marginTop}>
              <Button variant="outlined" onClick={this.handleAddAND}>{t('Add and-statement')}</Button>
            </Grid>
          </div>
        </DialogContent>
        <DialogActions>
          <Button
            onClick={onClose}
            color="secondary"
          >
            {t('Cancel')}
          </Button>
          <Button
            onClick={this.handleAdd}
            variant="contained"
            color="primary"
            disabled={loading || !classname}
          >
            {loading ? <CircularProgress size={24}/> : t('Add')}
          </Button>
        </DialogActions>
      </Dialog>
    );
  }
Example #11
Source File: CreateSavedFilter.jsx    From Edlib with GNU General Public License v3.0 4 votes vote down vote up
CreateSavedFilter = ({
    show,
    onClose,
    savedFilterData,
    filters,
    onDone,
    filterUtils,
}) => {
    const { classes } = useStyles();
    const { t } = useTranslation();
    const { edlibApi } = useConfigurationContext();
    const [selected, setSelected] = React.useState('new');
    const [newFilterName, setNewFilterName] = React.useState('My filter');

    const request = useRequestWithToken();

    return (
        <Dialog open={show} onClose={() => onClose()} maxWidth="sm" fullWidth>
            <DialogTitle>{_.capitalize(t('edit_filter'))}</DialogTitle>
            <DialogContent>
                <Box pt={1}>
                    <FormControl
                        variant="outlined"
                        fullWidth
                        className={classes.formControl}
                    >
                        <InputLabel>
                            {_.capitalize(t('choose_filter'))}
                        </InputLabel>
                        <Select
                            value={selected}
                            onChange={(e) => setSelected(e.target.value)}
                            label={_.capitalize(t('choose_filter'))}
                        >
                            <MenuItem value="new">
                                <em>{_.capitalize(t('create_new'))}</em>
                            </MenuItem>
                            {savedFilterData.map((savedFilter) => (
                                <MenuItem
                                    key={savedFilter.id}
                                    value={savedFilter.id}
                                >
                                    {savedFilter.name}
                                </MenuItem>
                            ))}
                        </Select>
                    </FormControl>
                    {selected === 'new' && (
                        <TextField
                            required
                            label={_.capitalize(t('name'))}
                            variant="outlined"
                            className={classes.formControl}
                            fullWidth
                            value={newFilterName}
                            onChange={(e) => setNewFilterName(e.target.value)}
                        />
                    )}
                    <div className={classes.formControl}>
                        <FilterChips
                            chips={filterUtils.getChipsFromFilters(false)}
                        />
                    </div>
                </Box>
            </DialogContent>
            <DialogActions>
                <Button
                    color="primary"
                    variant="outlined"
                    onClick={() => onClose()}
                >
                    {t('cancel')}
                </Button>
                <Button
                    color="primary"
                    variant="contained"
                    style={{ marginLeft: 5 }}
                    onClick={() => {
                        let url = edlibApi(`/common/saved-filters`);

                        if (selected !== 'new') {
                            url += `/` + selected;
                        }

                        request(url, 'POST', {
                            body: {
                                name: newFilterName,
                                choices: [
                                    filters.contentTypes.value.map(
                                        (contentType) => ({
                                            group: 'contentType',
                                            value: contentType.value,
                                        })
                                    ),
                                    filters.licenses.value.map(
                                        (contentType) => ({
                                            group: 'license',
                                            value: contentType.value,
                                        })
                                    ),
                                ].flat(),
                            },
                        }).then((data) => onDone(data));
                    }}
                >
                    {t('save')}
                </Button>
            </DialogActions>
        </Dialog>
    );
}
Example #12
Source File: AddGlobalUser.js    From admin-web with GNU Affero General Public License v3.0 4 votes vote down vote up
render() {
    const { classes, t, open, onClose, Domains, servers } = this.props;
    const { username, loading, properties, password, repeatPw,
      usernameError, domain, autocompleteInput, status, homeserver,
      lang, langs, chat, chatAvailable } = this.state;
    const { displayname, displaytypeex } = properties;
    const addDisabled = !domain || usernameError || !username || loading ||
      ((password !== repeatPw || password.length < 6) && status !== 4);
    
    return (
      <Dialog
        onClose={onClose}
        open={open}
        maxWidth="sm"
        fullWidth
        TransitionProps={{
          onEnter: this.handleEnter,
        }}
      >
        <DialogTitle>{t('addHeadline', { item: 'User' })}</DialogTitle>
        <DialogContent>
          <FormControl className={classes.form}>
            <MagnitudeAutocomplete
              value={domain}
              filterAttribute={'domainname'}
              inputValue={autocompleteInput}
              onChange={this.handleAutocomplete}
              className={classes.input} 
              options={Domains}
              onInputChange={this.handleInput('autocompleteInput')}
              label={t('Domain')}
              placeholder={t("Search domains")  + "..."}
              autoFocus
              autoSelect
            />
            <TextField
              select
              className={classes.input}
              label={t("Mode")}
              fullWidth
              value={status || 0}
              onChange={this.handleInput('status')}
            >
              {this.statuses.map((status, key) => (
                <MenuItem key={key} value={status.ID}>
                  {status.name}
                </MenuItem>
              ))}
            </TextField>
            <TextField 
              label={t("Username")}
              value={username || ''}
              onChange={this.handleUsernameInput}
              fullWidth
              InputProps={{
                endAdornment: <div>@{domain?.domainname || '<select domain>'}</div>,
                className: classes.noWrap,
              }}
              className={classes.input}
              required
              error={!!username && usernameError}
            />
            {status !== 4 && <TextField 
              label={t("Password")}
              value={password || ''}
              onChange={this.handleInput('password')}
              className={classes.input}
              type="password"
              required
              FormHelperTextProps={{
                error: true,
              }}
              helperText={(password && password.length < 6) ? t('Password must be at least 6 characters long') : ''}
              autoComplete="new-password"
            />}
            {status !== 4 && <TextField 
              label={t("Repeat password")}
              value={repeatPw || ''}
              onChange={this.handleInput('repeatPw')}
              className={classes.input}
              type="password"
              required
              FormHelperTextProps={{
                error: true,
              }}
              autoComplete="off"
              helperText={(repeatPw && password !== repeatPw) ? t("Passwords don't match") : ''}
            />}
            <TextField 
              label={t("Display name")}
              value={displayname || ''}
              onChange={this.handlePropertyChange('displayname')}
              className={classes.input}
            />
            <TextField
              select
              className={classes.input}
              label={t("Language")}
              fullWidth
              value={lang || 'en_US'}
              onChange={this.handleInput('lang')}
            >
              {langs.map((l) => (
                <MenuItem key={l.code} value={l.code}>
                  {l.code + ": " + l.name}
                </MenuItem>
              ))}
            </TextField>
            <TextField
              select
              className={classes.input}
              label={t("Type")}
              fullWidth
              value={displaytypeex || 0}
              onChange={this.handlePropertyChange('displaytypeex')}
            >
              {this.types.map((type, key) => (
                <MenuItem key={key} value={type.ID}>
                  {type.name}
                </MenuItem>
              ))}
            </TextField>
            <MagnitudeAutocomplete
              value={homeserver}
              filterAttribute={'hostname'}
              onChange={this.handleServer}
              className={classes.input} 
              options={servers}
              label={t('Homeserver')}
            />
            <FormControlLabel
              control={
                <Checkbox
                  checked={chat || false}
                  onChange={this.handleCheckbox('chat')}
                  color="primary"
                />
              }
              label={t('Create grommunio-chat User')}
              disabled={!chatAvailable}
            />
          </FormControl>
        </DialogContent>
        <DialogActions>
          <Button
            onClick={onClose}
            color="secondary"
          >
            {t('Cancel')}
          </Button>
          <Button
            onClick={this.handleAddAndEdit}
            variant="contained"
            color="primary"
            disabled={addDisabled}
          >
            {loading ? <CircularProgress size={24}/> : t('Add and edit')}
          </Button>
          <Button
            onClick={this.handleAdd}
            variant="contained"
            color="primary"
            disabled={addDisabled}
          >
            {loading ? <CircularProgress size={24}/> : t('Add')}
          </Button>
        </DialogActions>
      </Dialog>
    );
  }