@mui/material#TextField JavaScript Examples
The following examples show how to use
@mui/material#TextField.
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: LdapTextfield.js From admin-web with GNU Affero General Public License v3.0 | 6 votes |
render() {
const { classes, children, value, label, desc, flex, ...rest } = this.props;
return (
<TextField
{...rest}
label={label}
helperText={desc || ''}
className={flex ? classes.flexTextfield : classes.textfield}
color="primary"
value={value || ''}
>
{children}
</TextField>
);
}
Example #2
Source File: CustomInputs.jsx From CRM with Apache License 2.0 | 6 votes |
CustomAuthInput = (props) => {
const CssTextField = styled(TextField)({
"& label.Mui-focused": {
color: "#e14eca",
},
"& .MuiInput-underline:after": {
borderBottomColor: "#e14eca",
},
"& .MuiOutlinedInput-root": {
"& fieldset": {
borderColor: "rgba(34,42,66,.2)",
},
"&:hover fieldset": {
borderColor: "rgba(34,42,66,.5)",
},
"&.Mui-focused fieldset": {
borderColor: "#e14eca",
},
},
});
return <CssTextField {...props} fullWidth className="mb-2" />;
}
Example #3
Source File: VisibilityPasswordTextField.js From react-saas-template with MIT License | 6 votes |
function VisibilityPasswordTextField(props) {
const { isVisible, onVisibilityChange, ...rest } = props;
return (
<TextField
{...rest}
type={isVisible ? "text" : "password"}
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton
aria-label="Toggle password visibility"
onClick={() => {
onVisibilityChange(!isVisible);
}}
onMouseDown={(event) => {
event.preventDefault();
}}
size="large">
{isVisible ? <VisibilityIcon /> : <VisibilityOffIcon />}
</IconButton>
</InputAdornment>
),
}}
></TextField>
);
}
Example #4
Source File: MagnitudeAutocomplete.js From admin-web with GNU Affero General Public License v3.0 | 6 votes |
MagnitudeAutocomplete = props => {
const { t, className, value, filterAttribute, onChange, options, label, getOptionLabel,
inputValue, onInputChange, freeSolo, multiple, calculateMagnitude, placeholder, renderOption,
autoFocus, autoSelect, variant, fullWidth, disabled } = props;
const magnitude = calculateMagnitude === false ? 0 : Math.round(Math.log10(options.length) - 2);
return <Autocomplete
className={className}
inputValue={inputValue}
value={value}
onChange={onChange}
options={options || []}
getOptionLabel={getOptionLabel || (o => o[filterAttribute] || '')}
filterOptions={inputValue ? getAutocompleteOptions(filterAttribute, magnitude) : undefined}
noOptionsText={inputValue && inputValue.length < magnitude ?
t('Filter more precisely') + '...' : t('No options')}
renderInput={(params) => (
<TextField
{...params}
label={label || ''}
placeholder={placeholder}
autoFocus={autoFocus}
onChange={onInputChange}
variant={variant || 'outlined'}
/>
)}
renderOption={renderOption}
freeSolo={freeSolo || false}
multiple={multiple || false}
autoSelect={autoSelect}
fullWidth={fullWidth || false}
autoHighlight
disabled={disabled || false}
/>;
}
Example #5
Source File: index.js From zoomkoding-gatsby-blog with BSD Zero Clause License | 6 votes |
function PostSearch({ posts }) {
return (
<Autocomplete
disableClearable
options={posts}
onInputChange={(event, value, reason) => {
if (reason === 'reset' && value) {
const item = posts.find((item) => item.title === value);
if (!item) return;
navigate(item.slug);
}
}}
filterOptions={(options, { inputValue }) =>
options.filter(
({ title, categories }) => title.includes(inputValue) || categories.includes(inputValue),
)
}
getOptionLabel={(option) => option.title}
renderInput={(params) => (
<div className="search-input-wrapper">
<TextField
{...params}
className="search-input"
variant="standard"
size="medium"
InputProps={{
...params.InputProps,
endAdornment: <SearchIcon className="search-icon" />,
}}
/>
</div>
)}
noOptionsText="해당하는 글이 없습니다."
/>
);
}
Example #6
Source File: Settings.js From admin-web with GNU Affero General Public License v3.0 | 5 votes |
render() {
const { classes, t, settings } = this.props;
const { snackbar } = this.state;
return (
<TableViewContainer
headline={t("Settings")}
subtitle={t('settings_sub')}
href="https://docs.grommunio.com/admin/administration.html#settings"
snackbar={snackbar}
onSnackbarClose={() => this.setState({ snackbar: '' })}
>
<Paper className={classes.paper} elevation={1}>
<FormControl className={classes.form}>
<TextField
select
className={classes.input}
label={t("Language")}
fullWidth
value={settings.language || 'en-US'}
onChange={this.handleLangChange}
>
{this.langs.map((lang, key) => (
<MenuItem key={key} value={lang.ID}>
{lang.name}
</MenuItem>
))}
</TextField>
<FormControl className={classes.formControl}>
<FormLabel component="legend">{t('Darkmode')}</FormLabel>
<Switch
checked={(window.localStorage.getItem('darkMode') === 'true')}
onChange={this.handleDarkModeChange}
color="primary"
/>
</FormControl>
</FormControl>
</Paper>
</TableViewContainer>
);
}
Example #7
Source File: DateFacet.js From sampo-ui with MIT License | 5 votes |
render () {
const { from, to, fromError, toError } = this.state
const { min, max } = this.props.facet
const { someFacetIsFetching } = this.props
return (
<Box
sx={{
height: '100%',
display: 'flex'
}}
>
<Box sx={{ width: '160px' }}>
<DatePicker
label={intl.get('facets.dateFacet.fromLabel')}
renderInput={params =>
<TextField
error={fromError}
helperText={fromError ? intl.get('facets.dateFacet.invalidDate') : ' '}
{...params}
/>}
placeholder={moment(min).format('DD.MM.YYYY')}
mask='__.__.____'
value={from}
onChange={date => this.handleFromChange(date)}
inputFormat='DD.MM.YYYY'
minDate={moment(min)}
maxDate={moment(max)}
disabled={someFacetIsFetching}
/>
<Box
sx={theme => ({
marginTop: theme.spacing(1.5)
})}
>
<DatePicker
label={intl.get('facets.dateFacet.toLabel')}
renderInput={params =>
<TextField
error={toError}
helperText={toError ? intl.get('facets.dateFacet.invalidDate') : ' '}
{...params}
/>}
placeholder={moment(max).format('DD.MM.YYYY')}
mask='__.__.____'
value={to}
onChange={date => this.handleToChange(date)}
inputFormat='DD.MM.YYYY'
minDate={moment(min)}
maxDate={moment(max)}
disabled={someFacetIsFetching}
/>
</Box>
</Box>
<Box sx={theme => ({
marginLeft: theme.spacing(1.5),
paddingTop: '55px'
})}
>
<Button
variant='contained'
color='primary'
onClick={this.handleApplyOnClick}
disabled={someFacetIsFetching || fromError || toError}
>
{intl.get('facetBar.applyFacetSelection')}
</Button>
</Box>
</Box>
)
}
Example #8
Source File: PasswordSafetyDialog.js From admin-web with GNU Affero General Public License v3.0 | 5 votes |
render() {
const { classes, t, deviceID, open } = this.props;
const { password } = this.state;
return (
<Dialog
open={open}
onClose={this.handleCancel}
>
<DialogTitle className={classes.iconContainer}>
<Warning
color="warning"
fontSize="large"
/>
</DialogTitle>
<DialogContent className={classes.content}>
<Typography variant="h6" align="center" style={{ marginBottom: 8 }}>
Remote wipe of device {deviceID || '<unknown>'} engaged
</Typography>
<Typography variant="body1">
{t('RemoteWipeExplanation')}
</Typography>
<TextField
style={{ marginTop: 16 }}
label={t('Enter password to confirm')}
value={password}
onChange={this.handleInput}
fullWidth
type="password"
autoComplete="new-password"
/>
</DialogContent>
<DialogActions>
<Button variant="contained" onClick={this.handleCancel}>
{t('Cancel')}
</Button>
<Button
color="error"
onClick={this.handleConfirm(password)}
disabled={!password}
variant="contained"
>
{t('Confirm')}
</Button>
</DialogActions>
</Dialog>
);
}
Example #9
Source File: AutocompleteCombo.jsx From matx-react with MIT License | 5 votes |
AutocompleteCombo = () => {
const [value, setValue] = React.useState(null);
const handleChange = (_, newValue) => {
if (newValue && newValue.inputValue) {
setValue({ label: newValue.inputValue });
return;
}
setValue(newValue);
};
const filterOptions = (options, params) => {
const filtered = filter(options, params);
if (params.inputValue !== '') {
filtered.push({ inputValue: params.inputValue, label: `Add "${params.inputValue}"` });
}
return filtered;
};
return (
<Fragment>
<AutoComplete
options={suggestions}
getOptionLabel={(option) => option.label}
renderInput={(params) => (
<TextField {...params} label="Combo box" variant="outlined" fullWidth />
)}
/>
<AutoComplete
value={value}
options={suggestions}
onChange={handleChange}
filterOptions={filterOptions}
getOptionLabel={(option) => {
// e.g value selected with enter, right from the input
if (typeof option === 'string') {
return option;
}
if (option.inputValue) {
return option.inputValue;
}
return option.label;
}}
renderOption={(option) => option.label}
style={{ width: 300 }}
freeSolo
renderInput={(params) => (
<TextField {...params} label="Free solo with text demo" variant="outlined" fullWidth />
)}
/>
<AutoComplete
options={suggestions}
getOptionLabel={(option) => option.label}
getOptionDisabled={(option) => option === suggestions[0] || option === suggestions[2]}
renderInput={(params) => (
<TextField {...params} label="Disabled option" variant="outlined" fullWidth />
)}
/>
</Fragment>
);
}
Example #10
Source File: Input.js From fireact with MIT License | 5 votes |
Input = (props) => {
const {
hasError,
validRegex,
minLen,
maxLen,
required,
error,
changeHandler,
...others
} = props;
const [hasErrorState, setHasErrorState] = useState(hasError);
const [errorMessage, setErrorMessage] = useState(error);
useEffect(() => {
setHasErrorState(hasError);
setErrorMessage(error);
}, [hasError, error]);
return (
<div style={{marginTop:'20px',marginBottom:'20px'}}>
<TextField error={hasErrorState} helperText={hasErrorState && errorMessage} {...others} onChange={e => {
let foundError = false;
let foundErrorMessage = '';
// validae required
if(typeof(required) !== 'undefined' && required){
if(e.target.value.trim().length === 0){
foundErrorMessage = 'This is a required field.';
foundError = true;
}
}
// validate length
if(!foundError && typeof(minLen) !== 'undefined' && minLen !== 0){
if(e.target.value.length < minLen){
foundErrorMessage = 'The input must be at least '+minLen+' characters.';
foundError = true;
}
}
if(!foundError && typeof(maxLen) !== 'undefined' && maxLen !== 0){
if(e.target.value.length > maxLen){
foundErrorMessage = 'The input must be no more than '+maxLen+' characters.';
foundError = true;
}
}
// validate the value against validation regex
if(!foundError && typeof(validRegex) !=='undefined' && validRegex !== ''){
if(!RegExp(validRegex).test(e.target.value)){
foundErrorMessage = 'The input format is invalid.';
foundError = true;
}
}
if(foundError){
setHasErrorState(true);
setErrorMessage(foundErrorMessage);
}else{
setHasErrorState(false);
}
changeHandler({
hasError: foundError,
error: foundErrorMessage,
value: e.target.value
});
}} />
</div>
)
}
Example #11
Source File: StripeCardForm.js From react-saas-template with MIT License | 5 votes |
function StripeCardForm(props) {
const {
stripeError,
setStripeError,
amount,
amountError,
onAmountChange,
name,
setName
} = props;
return (
<Grid container spacing={2} justifyContent="space-between">
<Grid item xs={8}>
<TextField
variant="outlined"
margin="none"
required
label="Your Name"
value={name}
onChange={event => {
setName(event.target.value);
}}
fullWidth
autoFocus
autoComplete="off"
type="text"
/>
</Grid>
<Grid item xs={4}>
<TextField
required
value={amount}
onChange={event => {
onAmountChange(parseInt(event.target.value));
}}
error={amountError ? true : false}
helperText={amountError}
variant="outlined"
fullWidth
type="number"
margin="none"
label="Amount"
InputProps={{
startAdornment: <InputAdornment position="start">$</InputAdornment>
}}
/>
</Grid>
<Grid item xs={12}>
<StripeTextField
margin="none"
fullWidth
label="Credit Card"
error={stripeError ? true : false}
helperText={stripeError}
variant="outlined"
required
StripeElement={CardElement}
onChange={() => {
if (stripeError) {
setStripeError("");
}
}}
></StripeTextField>
</Grid>
</Grid>
);
}
Example #12
Source File: BadgeAutocomplete.jsx From matx-react with MIT License | 5 votes |
BadgeAutocomplete = () => {
const theme = useTheme();
return (
<Box
sx={{
width: 500,
'& > * + *': {
marginTop: theme.spacing(3),
},
}}
>
<Autocomplete
multiple
id="tags-standard"
options={top100Films}
getOptionLabel={(option) => option.title}
defaultValue={[top100Films[13]]}
renderInput={(params) => (
<TextField
{...params}
variant="standard"
label="Multiple values"
placeholder="Favorites"
fullWidth
/>
)}
/>
<Autocomplete
multiple
id="tags-outlined"
options={top100Films}
getOptionLabel={(option) => option.title}
defaultValue={[top100Films[13]]}
filterSelectedOptions
renderInput={(params) => (
<TextField
{...params}
variant="outlined"
label="filterSelectedOptions"
placeholder="Favorites"
fullWidth
/>
)}
/>
<Autocomplete
multiple
id="tags-filled"
options={top100Films.map((option) => option.title)}
defaultValue={[top100Films[13].title]}
freeSolo
renderTags={(value, getTagProps) =>
value.map((option, index) => (
<Chip variant="outlined" label={option} {...getTagProps({ index })} />
))
}
renderInput={(params) => (
<TextField
{...params}
variant="filled"
label="freeSolo"
placeholder="Favorites"
fullWidth
/>
)}
/>
</Box>
);
}
Example #13
Source File: ChangePasswordDialog.js From react-saas-template with MIT License | 5 votes |
function ChangePassword(props) {
const { onClose, classes, setLoginStatus } = props;
const [isLoading, setIsLoading] = useState(false);
const sendPasswordEmail = useCallback(() => {
setIsLoading(true);
setTimeout(() => {
setLoginStatus("verificationEmailSend");
setIsLoading(false);
onClose();
}, 1500);
}, [setIsLoading, setLoginStatus, onClose]);
return (
<Dialog
open
hideBackdrop
onClose={onClose}
disableEscapeKeyDown={isLoading}
maxWidth="xs">
<form
onSubmit={(e) => {
e.preventDefault();
sendPasswordEmail();
}}
>
<DialogContent className={classes.dialogContent}>
<Typography paragraph>
Enter your email address below and we will send you instructions on
how to reset your password.
</Typography>
<TextField
variant="outlined"
margin="dense"
required
fullWidth
label="Email Address"
autoFocus
type="email"
autoComplete="off"
/>
</DialogContent>
<DialogActions className={classes.dialogActions}>
<Button onClick={onClose} disabled={isLoading}>
Cancel
</Button>
<Button
type="submit"
variant="contained"
color="secondary"
disabled={isLoading}
>
Reset password
{isLoading && <ButtonCircularProgress />}
</Button>
</DialogActions>
</form>
</Dialog>
);
}
Example #14
Source File: AsyncAutocomplete.jsx From matx-react with MIT License | 5 votes |
export default function AsyncAutocomplete() {
const [open, setOpen] = React.useState(false);
const [options, setOptions] = React.useState([]);
const loading = open && options.length === 0;
React.useEffect(() => {
let active = true;
if (!loading) {
return undefined;
}
(async () => {
const response = await fetch('https://country.register.gov.uk/records.json?page-size=5000');
await sleep(3000); // For demo purposes.
const countries = await response.json();
if (active) {
setOptions(Object.keys(countries).map((key) => countries[key].item[0]));
}
})();
return () => {
active = false;
};
}, [loading]);
React.useEffect(() => {
if (!open) {
setOptions([]);
}
}, [open]);
return (
<AutoComplete
open={open}
options={options}
loading={loading}
id="asynchronous-demo"
onOpen={() => setOpen(true)}
onClose={() => setOpen(false)}
getOptionLabel={(option) => option.name}
renderInput={(params) => (
<TextField
{...params}
fullWidth
variant="outlined"
label="Asynchronous"
InputProps={{
...params.InputProps,
endAdornment: (
<React.Fragment>
{loading ? <CircularProgress color="inherit" size={20} /> : null}
{params.InputProps.endAdornment}
</React.Fragment>
),
}}
/>
)}
/>
);
}
Example #15
Source File: search.js From react-table-library with MIT License | 5 votes |
Component = () => {
let data = { nodes };
const materialTheme = getTheme(DEFAULT_OPTIONS);
const theme = useTheme(materialTheme);
const [search, setSearch] = React.useState('');
const handleSearch = (event) => {
setSearch(event.target.value);
};
data = {
nodes: data.nodes.filter((item) => item.name.toLowerCase().includes(search.toLowerCase())),
};
const COLUMNS = [
{ label: 'Task', renderCell: (item) => item.name },
{
label: 'Deadline',
renderCell: (item) =>
item.deadline.toLocaleDateString('en-US', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
}),
},
{ label: 'Type', renderCell: (item) => item.type },
{
label: 'Complete',
renderCell: (item) => item.isComplete.toString(),
},
{ label: 'Tasks', renderCell: (item) => item.nodes?.length },
];
return (
<>
<Stack spacing={10}>
<TextField label="Search Task" value={search} icon={<FaSearch />} onChange={handleSearch} />
</Stack>
<br />
<CompactTable columns={COLUMNS} data={data} theme={theme} />
<br />
<DocumentationSee anchor={'Features/' + key} />
</>
);
}
Example #16
Source File: LanguageDropdown.jsx From Edlib with GNU General Public License v3.0 | 5 votes |
LanguageDropdown = ({ language, setLanguage }) => {
const { t } = useTranslation();
const { edlibApi } = useConfigurationContext();
const [open, setOpen] = React.useState(false);
const { error, loading, response } = useFetchWithToken(
edlibApi('/resources/v1/languages'),
'GET',
React.useMemo(() => ({}), []),
true,
true
);
return (
<Autocomplete
open={open}
onOpen={() => {
setOpen(true);
}}
onClose={() => {
setOpen(false);
}}
isOptionEqualToValue={(option, value) => option === value}
getOptionLabel={(option) => iso6393ToString(option)}
options={response ? response.data : []}
loading={loading}
onChange={(e, v) => {
setLanguage(v);
}}
value={language}
renderInput={(params) => (
<TextField
{...params}
fullWidth
label={_.capitalize(t('language'))}
variant="outlined"
InputProps={{
...params.InputProps,
endAdornment: (
<>
{loading ? (
<CircularProgress
color="inherit"
size={20}
/>
) : null}
{params.InputProps.endAdornment}
</>
),
}}
/>
)}
/>
);
}
Example #17
Source File: AddFolder.js From admin-web with GNU Affero General Public License v3.0 | 5 votes |
render() {
const { classes, t, open, onClose, Users } = this.props;
const { displayname, owners, container, comment, loading, autocompleteInput } = this.state;
return (
<Dialog
onClose={onClose}
open={open}
maxWidth="sm"
fullWidth
>
<DialogTitle>{t('addHeadline', { item: 'Folder' })}</DialogTitle>
<DialogContent style={{ minWidth: 400 }}>
<FormControl className={classes.form}>
<TextField
label={t("Folder name")}
value={displayname}
onChange={this.handleInput('displayname')}
className={classes.input}
autoFocus
required
/>
<TextField
select
className={classes.input}
label={t("Container")}
fullWidth
value={container || ''}
onChange={this.handleInput('container')}
>
{this.types.map((type, key) => (
<MenuItem key={key} value={type.ID}>
{type.name}
</MenuItem>
))}
</TextField>
<TextField
className={classes.input}
label={t("Comment")}
fullWidth
multiline
rows={4}
value={comment}
variant="outlined"
onChange={this.handleInput('comment')}
/>
<MagnitudeAutocomplete
multiple
value={owners || []}
filterAttribute={'username'}
inputValue={autocompleteInput}
onChange={this.handleAutocomplete('owners')}
className={classes.input}
options={Users || []}
onInputChange={this.handleInput('autocompleteInput')}
label={t('Owners')}
placeholder={t("Search domains") + "..."}
/>
</FormControl>
</DialogContent>
<DialogActions>
<Button
onClick={onClose}
color="secondary"
>
Cancel
</Button>
<Button
onClick={this.handleAdd}
variant="contained"
color="primary"
disabled={!displayname || loading}
>
{loading ? <CircularProgress size={24}/> : 'Add'}
</Button>
</DialogActions>
</Dialog>
);
}
Example #18
Source File: index.js From redis-examples with MIT License | 4 votes |
export default function Home() {
const [accountAddress, setAccountAddress] = useState(null)
const [themePreference, setThemePreference] = useState("light")
const [greetingMessage, setGreetingMessage] = useState("Anonymous Person")
const [userSettings, setUserSettings] = useState(null)
useEffect(() => {
checkConnection()
getPreferences()
}, [accountAddress])
async function checkConnection() {
const provider = await detectEthereumProvider()
if (provider) {
provider
.request({ method: 'eth_accounts' })
.then(accounts => {
setAccountAddress(accounts[0])
})
.catch(console.log)
} else {
console.log("Not connected, window.ethereum not found")
}
}
async function connect() {
const provider = await detectEthereumProvider()
console.log("provider:", provider)
if (provider) {
console.log('Ethereum successfully detected!')
provider.request({ method: "eth_requestAccounts" }).then((accounts) => {
if (!accountAddress) {
setAccountAddress(accounts[0])
}
}).catch((err) => console.log(err))
// : alert("Please install MetaMask")
console.log("window.ethereum:", window.ethereum)
getPreferences()
} else {
alert('Please install MetaMask!')
}
}
async function setPreferences(themePreference, greetingMessage) {
if (accountAddress) {
const res = await fetch(`/api/store`, {
method: "POST",
body: JSON.stringify({
accountID: accountAddress,
themePreference: themePreference,
greetingMessage: greetingMessage,
})
})
const data = await res.json()
}
else {
alert("No account address detected")
}
}
async function getPreferences(e) {
if (accountAddress) {
console.log("Fetching user preferences...")
const res = await fetch(`/api/${accountAddress}`, { method: "GET" })
const data = await res.json()
setUserSettings(data.result)
if (data.result) {
setThemePreference(data.result.themePreference)
setGreetingMessage(data.result.greetingMessage)
}
}
else {
console.log("No account connected yet!")
}
}
async function handleDarkMode(e) {
console.log("themePreference:", themePreference)
const newPreference = themePreference == "light" ? "dark" : "light"
setThemePreference(newPreference)
await setPreferences(newPreference, greetingMessage)
await getPreferences()
}
async function takeGreetingMessage(e) {
if (e.keyCode == 13) {
const message = e.target.value
setGreetingMessage(message)
console.log(message)
await setPreferences(themePreference, message)
await getPreferences()
e.target.value = ""
}
}
return (
<div className={styles.container}>
<h2>Web3 Preferences Holder</h2>
<Button variant="contained" onClick={connect}>Connect Metamask</Button>
<p>
Lets you keep user preferences on cross-websites
</p>
<br />
<p>For example, take a greeter message from user.</p>
<TextField label="Call me..." variant="outlined" size="small" onKeyDown={takeGreetingMessage} />
<br />
<br />
<Button onClick={handleDarkMode} variant="contained" size="small" style={{ backgroundColor: "#3D3B3B" }} > Switch Dark Mode </Button>
<p>Sample Component/Page:</p>
<Showcase userSettings={userSettings} />
</div>
)
}
Example #19
Source File: index.js From neutron with Mozilla Public License 2.0 | 4 votes |
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 #20
Source File: Folders.js From admin-web with GNU Affero General Public License v3.0 | 4 votes |
render() {
const { classes, t, folders, domain, tableState, handleMatch,
handleAdd, handleAddingSuccess, handleAddingClose, handleAddingError,
clearSnackbar, handleDelete, handleDeleteClose, handleDeleteError,
handleDeleteSuccess, handleEdit } = this.props;
const { Folders, moreDataAvailable } = folders;
const writable = this.context.includes(DOMAIN_ADMIN_WRITE);
const { match, snackbar, adding, deleting } = tableState;
const { hierarchy } = this.state;
return (
<TableViewContainer
handleScroll={this.handleScroll}
headline={t("Folders")}
subtitle={t('folders_sub')}
href="https://docs.grommunio.com/admin/administration.html#folders"
snackbar={snackbar}
onSnackbarClose={clearSnackbar}
>
<Grid container alignItems="flex-end" className={classes.buttonGrid}>
<Button
variant="contained"
color="primary"
onClick={handleAdd}
disabled={!writable}
>
{t('New folder')}
</Button>
<div className={classes.actions}>
<TextField
value={match}
onChange={handleMatch}
placeholder={t("Search")}
variant="outlined"
className={classes.textfield}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<Search color="secondary" />
</InputAdornment>
),
}}
color="primary"
/>
</div>
</Grid>
<Typography className={classes.count} color="textPrimary">
{t("showingFolders", { count: Folders.length + (hierarchy.length === 1 ? 1 : 0) })}
</Typography>
<Breadcrumbs aria-label="breadcrumb" className={classes.breadcumbs}>
{hierarchy.map((folder, idx) =>
<Link
key={folder.folderid}
underline="hover"
color="primary"
onClick={this.handleBreadcrumb(folder, idx)}
className={classes.link}
>
{folder.displayname}
</Link>
)}
</Breadcrumbs>
<Paper className={classes.tablePaper} elevation={1}>
<Table size="small">
<TableHead>
<TableRow>
{['Folder name', 'Comment', 'Creation time', ''].map(headerName =>
<TableCell key={headerName}>{t(headerName)}</TableCell>
)}
</TableRow>
</TableHead>
<TableBody>
{hierarchy.length === 1 && <TableRow>
<TableCell>{IPM_SUBTREE_OBJECT.displayname}</TableCell>
<TableCell>{t(IPM_SUBTREE_OBJECT.comment)}</TableCell>
<TableCell></TableCell>
<TableCell align="right">
<IconButton onClick={handleEdit('/' + domain.ID + '/folders/' + IPM_SUBTREE_ID)} size="large">
<Edit color="primary"/>
</IconButton>
</TableCell>
</TableRow>}
{Folders.map((obj, idx) =>
<TableRow hover onClick={this.handleFetchChildren(obj)} key={idx}>
<TableCell>{obj.displayname}</TableCell>
<TableCell>{obj.comment}</TableCell>
<TableCell>{obj.creationtime}</TableCell>
<TableCell align="right">
<IconButton onClick={handleEdit('/' + domain.ID + '/folders/' + obj.folderid)} size="large">
<Edit color="primary"/>
</IconButton>
{writable && <IconButton onClick={handleDelete(obj)} size="large">
<Delete color="error"/>
</IconButton>}
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
{(moreDataAvailable) && <Grid container justifyContent="center">
<CircularProgress color="primary" className={classes.circularProgress}/>
</Grid>}
</Paper>
<AddFolder
open={adding}
onClose={handleAddingClose}
onSuccess={handleAddingSuccess}
onError={handleAddingError}
domain={domain}
parentID={hierarchy[hierarchy.length - 1].folderid}
/>
<DeleteFolder
open={!!deleting}
delete={this.props.delete}
onSuccess={handleDeleteSuccess}
onError={handleDeleteError}
onClose={handleDeleteClose}
item={deleting.displayname}
id={deleting.folderid}
domainID={domain.ID}
/>
</TableViewContainer>
);
}
Example #21
Source File: JwtRegister.jsx From matx-react with MIT License | 4 votes |
JwtRegister = () => {
const theme = useTheme();
const { register } = useAuth();
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
const handleFormSubmit = (values) => {
setLoading(true);
try {
register(values.email, values.username, values.password);
navigate('/');
setLoading(false);
} catch (e) {
console.log(e);
setLoading(false);
}
};
return (
<JWTRegister>
<Card className="card">
<Grid container>
<Grid item sm={6} xs={12}>
<ContentBox>
<img
width="100%"
alt="Register"
src="/assets/images/illustrations/posting_photo.svg"
/>
</ContentBox>
</Grid>
<Grid item sm={6} xs={12}>
<Box p={4} height="100%">
<Formik
onSubmit={handleFormSubmit}
initialValues={initialValues}
validationSchema={validationSchema}
>
{({ values, errors, touched, handleChange, handleBlur, handleSubmit }) => (
<form onSubmit={handleSubmit}>
<TextField
fullWidth
size="small"
type="text"
name="username"
label="Username"
variant="outlined"
onBlur={handleBlur}
value={values.username}
onChange={handleChange}
helperText={touched.username && errors.username}
error={Boolean(errors.username && touched.username)}
sx={{ mb: 3 }}
/>
<TextField
fullWidth
size="small"
type="email"
name="email"
label="Email"
variant="outlined"
onBlur={handleBlur}
value={values.email}
onChange={handleChange}
helperText={touched.email && errors.email}
error={Boolean(errors.email && touched.email)}
sx={{ mb: 3 }}
/>
<TextField
fullWidth
size="small"
name="password"
type="password"
label="Password"
variant="outlined"
onBlur={handleBlur}
value={values.password}
onChange={handleChange}
helperText={touched.password && errors.password}
error={Boolean(errors.password && touched.password)}
sx={{ mb: 2 }}
/>
<FlexBox gap={1} alignItems="center">
<Checkbox
size="small"
name="remember"
onChange={handleChange}
checked={values.remember}
sx={{ padding: 0 }}
/>
<Paragraph fontSize={13}>
I have read and agree to the terms of service.
</Paragraph>
</FlexBox>
<LoadingButton
type="submit"
color="primary"
loading={loading}
variant="contained"
sx={{ mb: 2, mt: 3 }}
>
Regiser
</LoadingButton>
<Paragraph>
Already have an account?
<NavLink
to="/session/signin"
style={{ color: theme.palette.primary.main, marginLeft: 5 }}
>
Login
</NavLink>
</Paragraph>
</form>
)}
</Formik>
</Box>
</Grid>
</Grid>
</Card>
</JWTRegister>
);
}
Example #22
Source File: Orgs.js From admin-web with GNU Affero General Public License v3.0 | 4 votes |
render() {
const { classes, t, orgs, tableState, handleMatch, handleRequestSort,
handleAdd, handleAddingSuccess, handleAddingClose, handleAddingError,
clearSnackbar, handleDelete, handleDeleteClose, handleDeleteError,
handleDeleteSuccess, handleEdit } = this.props;
const { order, orderBy, match, snackbar, adding, deleting } = tableState;
const writable = this.context.includes(SYSTEM_ADMIN_WRITE);
return (
<TableViewContainer
handleScroll={this.handleScroll}
headline={t("Organizations")}
href="https://docs.grommunio.com/admin/administration.html#organizations"
subtitle={t("orgs_sub")}
snackbar={snackbar}
onSnackbarClose={clearSnackbar}
>
<Grid container alignItems="flex-end" className={classes.buttonGrid}>
<Button
variant="contained"
color="primary"
onClick={handleAdd}
disabled={!writable}
>
{t("New organization")}
</Button>
<div className={classes.actions}>
<TextField
value={match}
onChange={handleMatch}
placeholder={t("Search organizations")}
variant={"outlined"}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<Search color="secondary" />
</InputAdornment>
),
}}
color="primary"
/>
</div>
</Grid>
<Typography className={classes.count} color="textPrimary">
{t("showingOrgs", { count: orgs.Orgs.length })}
</Typography>
<Paper elevation={1}>
<Table size="small">
<TableHead>
<TableRow>
{this.columns.map((column) => (
<TableCell key={column.value}>
<TableSortLabel
active={orderBy === column.value}
align="left"
direction={orderBy === column.value ? order : "asc"}
onClick={handleRequestSort(column.value)}
>
{t(column.label)}
</TableSortLabel>
</TableCell>
))}
<TableCell padding="checkbox" />
</TableRow>
</TableHead>
<TableBody>
{orgs.Orgs.map((obj, idx) =>
<TableRow key={idx} hover onClick={handleEdit('/orgs/' + obj.ID)}>
<TableCell>{obj.name}</TableCell>
<TableCell>{obj.description}</TableCell>
<TableCell align="right">
{writable && <IconButton onClick={handleDelete(obj)} size="large">
<Delete color="error" />
</IconButton>}
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
{orgs.Orgs.length < orgs.count && (
<Grid container justifyContent="center">
<CircularProgress
color="primary"
className={classes.circularProgress}
/>
</Grid>
)}
</Paper>
<AddOrg
open={adding}
onSuccess={handleAddingSuccess}
onError={handleAddingError}
onClose={handleAddingClose}
/>
<GeneralDelete
open={!!deleting}
delete={this.props.delete}
onSuccess={handleDeleteSuccess}
onError={handleDeleteError}
onClose={handleDeleteClose}
item={deleting.name}
id={deleting.ID}
/>
</TableViewContainer>
);
}
Example #23
Source File: LocationAutocomplete.jsx From matx-react with MIT License | 4 votes |
export default function LocationAutocomplete() {
const theme = useTheme();
const [inputValue, setInputValue] = React.useState('');
const [options, setOptions] = React.useState([]);
const loaded = React.useRef(false);
if (typeof window !== 'undefined' && !loaded.current) {
if (!document.querySelector('#google-maps')) {
loadScript(
'https://maps.googleapis.com/maps/api/js?key=AIzaSyBwRp1e12ec1vOTtGiA4fcCt2sCUS78UYc&libraries=places',
document.querySelector('head'),
'google-maps'
);
}
loaded.current = true;
}
const handleChange = (event) => {
setInputValue(event.target.value);
};
const fetch = React.useMemo(
() =>
throttle((input, callback) => {
autocompleteService.current.getPlacePredictions(input, callback);
}, 200),
[]
);
React.useEffect(() => {
let active = true;
if (!autocompleteService.current && window.google) {
autocompleteService.current = new window.google.maps.places.AutocompleteService();
}
if (!autocompleteService.current) {
return undefined;
}
if (inputValue === '') {
setOptions([]);
return undefined;
}
fetch({ input: inputValue }, (results) => {
if (active) {
setOptions(results || []);
}
});
return () => {
active = false;
};
}, [inputValue, fetch]);
return (
<Autocomplete
id="google-map-demo"
style={{ width: 300 }}
getOptionLabel={(option) => (typeof option === 'string' ? option : option.description)}
filterOptions={(x) => x}
options={options}
autoComplete
includeInputInList
freeSolo
disableOpenOnFocus
renderInput={(params) => (
<TextField
{...params}
label="Add a location"
variant="outlined"
fullWidth
onChange={handleChange}
/>
)}
renderOption={(option) => {
const matches = option.structured_formatting.main_text_matched_substrings;
const parts = parse(
option.structured_formatting.main_text,
matches.map((match) => [match.offset, match.offset + match.length])
);
return (
<Grid container alignItems="center">
<Grid item>
<LocationOnIcon
sx={{
color: theme.palette.text.secondary,
marginRight: theme.spacing(2),
}}
/>
</Grid>
<Grid item xs>
{parts.map((part, index) => (
<span
key={index}
style={{
fontWeight: part.highlight ? 700 : 400,
}}
>
{part.text}
</span>
))}
<Typography variant="body2" color="textSecondary">
{option.structured_formatting.secondary_text}
</Typography>
</Grid>
</Grid>
);
}}
/>
);
}
Example #24
Source File: showreel.js From react-table-library with MIT License | 4 votes |
Component = () => {
const [data, setData] = React.useState({ nodes });
//* Theme *//
const materialTheme = getTheme({
...DEFAULT_OPTIONS,
striped: true,
highlightOnHover: true,
});
const customTheme = {
Table: `
--data-table-library_grid-template-columns: 70px repeat(5, minmax(0, 1fr));
margin: 16px 0px;
`,
};
const theme = useTheme([materialTheme, customTheme]);
//* Resize *//
const resize = { resizerHighlight: '#dee2e6' };
//* Pagination *//
const pagination = usePagination(data, {
state: {
page: 0,
size: 2,
},
onChange: onPaginationChange,
});
function onPaginationChange(action, state) {
console.log(action, state);
}
//* Search *//
const [search, setSearch] = React.useState('');
useCustom('search', data, {
state: { search },
onChange: onSearchChange,
});
function onSearchChange(action, state) {
console.log(action, state);
pagination.fns.onSetPage(0);
}
//* Filter *//
const [isHide, setHide] = React.useState(false);
useCustom('filter', data, {
state: { isHide },
onChange: onFilterChange,
});
function onFilterChange(action, state) {
console.log(action, state);
pagination.fns.onSetPage(0);
}
//* Select *//
const select = useRowSelect(data, {
onChange: onSelectChange,
});
function onSelectChange(action, state) {
console.log(action, state);
}
//* Tree *//
const tree = useTree(
data,
{
onChange: onTreeChange,
},
{
clickType: TreeExpandClickTypes.ButtonClick,
treeYLevel: 1,
treeIcon: {
margin: '4px',
iconDefault: null,
iconRight: <FaChevronRight />,
iconDown: <FaChevronDown />,
},
},
);
function onTreeChange(action, state) {
console.log(action, state);
}
//* Sort *//
const sort = useSort(
data,
{
onChange: onSortChange,
},
{
sortIcon: {
iconDefault: null,
iconUp: <FaChevronUp />,
iconDown: <FaChevronDown />,
},
sortFns: {
TASK: (array) => array.sort((a, b) => a.name.localeCompare(b.name)),
DEADLINE: (array) => array.sort((a, b) => a.deadline - b.deadline),
TYPE: (array) => array.sort((a, b) => a.type.localeCompare(b.type)),
COMPLETE: (array) => array.sort((a, b) => a.isComplete - b.isComplete),
TASKS: (array) => array.sort((a, b) => (a.nodes || []).length - (b.nodes || []).length),
},
},
);
function onSortChange(action, state) {
console.log(action, state);
}
//* Drawer *//
const [drawerId, setDrawerId] = React.useState(null);
const [edited, setEdited] = React.useState('');
const handleEdit = (event) => {
setEdited(event.target.value);
};
const handleCancel = () => {
setEdited('');
setDrawerId(null);
};
const handleSave = () => {
const node = findNodeById(data.nodes, drawerId);
const editedNode = { ...node, name: edited };
const nodes = insertNode(data.nodes, editedNode);
setData({
nodes,
});
setEdited('');
setDrawerId(null);
};
//* Modal *//
const [modalOpened, setModalOpened] = React.useState(false);
//* Custom Modifiers *//
let modifiedNodes = data.nodes;
// search
modifiedNodes = modifiedNodes.filter((node) =>
node.name.toLowerCase().includes(search.toLowerCase()),
);
// filter
modifiedNodes = isHide ? modifiedNodes.filter((node) => !node.isComplete) : modifiedNodes;
//* Columns *//
const COLUMNS = [
{
label: 'Task',
renderCell: (item) => item.name,
resize,
sort: { sortKey: 'TASK' },
select: {
renderHeaderCellSelect: () => (
<Checkbox
size="small"
checked={select.state.all}
indeterminate={!select.state.all && !select.state.none}
onChange={select.fns.onToggleAll}
/>
),
renderCellSelect: (item) => (
<Checkbox
size="small"
checked={select.state.ids.includes(item.id)}
onChange={() => select.fns.onToggleById(item.id)}
/>
),
},
tree: true,
},
{
label: 'Deadline',
renderCell: (item) =>
item.deadline.toLocaleDateString('en-US', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
}),
resize,
sort: { sortKey: 'DEADLINE' },
},
{ label: 'Type', renderCell: (item) => item.type, resize, sort: { sortKey: 'TYPE' } },
{
label: 'Complete',
renderCell: (item) => item.isComplete.toString(),
resize,
sort: { sortKey: 'COMPLETE' },
},
{
label: 'Tasks',
renderCell: (item) => (
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<span>{item.nodes?.length}</span>
<IconButton onClick={() => setDrawerId(item.id)}>
<FaPen size={14} />
</IconButton>
</div>
),
resize,
sort: { sortKey: 'TASKS' },
},
];
return (
<>
<Modal open={modalOpened} onClose={() => setModalOpened(false)}>
<Box
style={{
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: 500,
backgroundColor: '#ffffff',
border: '1px solid #e0e0e0',
borderRadius: '4px',
padding: '10px',
}}
>
<Typography variant="h6" component="h2">
"Not all features included here, but we got ..."
</Typography>
<FormGroup>
<FormControlLabel control={<Checkbox checked />} label="Resize" />
<FormControlLabel control={<Checkbox checked />} label="Sort" />
<FormControlLabel control={<Checkbox checked />} label="Search" />
<FormControlLabel control={<Checkbox checked />} label="Filter" />
<FormControlLabel control={<Checkbox checked />} label="Select" />
<FormControlLabel control={<Checkbox checked />} label="Tree" />
<FormControlLabel control={<Checkbox checked />} label="Drawer on Edit" />
<FormControlLabel control={<Checkbox checked />} label="Pagination" />
</FormGroup>
</Box>
</Modal>
{/* Form */}
<Stack spacing={1} direction="row">
<Button variant="contained" onClick={() => setModalOpened(true)}>
Features?
</Button>
<TextField
label="Search Task"
value={search}
onChange={(event) => setSearch(event.target.value)}
/>
<FormControlLabel
control={
<Checkbox checked={isHide} onChange={(event) => setHide(event.target.checked)} />
}
label="Hide Complete"
/>
</Stack>
{/* Table */}
<CompactTable
columns={COLUMNS}
data={{ ...data, nodes: modifiedNodes }}
theme={theme}
layout={{ custom: true }}
select={select}
tree={tree}
sort={sort}
pagination={pagination}
/>
<br />
<Stack spacing={10}>
<TablePagination
count={modifiedNodes.length}
page={pagination.state.page}
rowsPerPage={pagination.state.size}
rowsPerPageOptions={[1, 2, 5]}
onRowsPerPageChange={(event) =>
pagination.fns.onSetSize(parseInt(event.target.value, 10))
}
onPageChange={(event, page) => pagination.fns.onSetPage(page)}
/>
</Stack>
<Drawer
open={drawerId}
onClose={handleCancel}
title="Edit"
anchor="right"
PaperProps={{
sx: { width: '50%', padding: '20px' },
}}
>
<Stack spacing={1}>
<TextField
label="Name"
value={edited || fromTreeToList(data.nodes).find((node) => node.id === drawerId)?.name}
onChange={handleEdit}
autoFocus
/>
<Button variant="outlined" onClick={handleCancel}>
Cancel
</Button>
<Button variant="contained" onClick={handleSave}>
Save
</Button>
</Stack>
</Drawer>
</>
);
}
Example #25
Source File: Sync.js From admin-web with GNU Affero General Public License v3.0 | 4 votes |
render() {
const { classes, t, sync } = this.props;
const { snackbar, sortedDevices, order, orderBy, match, showPush, onlyActive,
filterEnded, filterUpdated } = this.state;
return (
<TableViewContainer
handleScroll={this.handleScroll}
headline={<>
{t("Mobile devices")}
<IconButton
size="small"
href="https://docs.grommunio.com/admin/administration.html#mobile-devices"
target="_blank"
>
<HelpOutline fontSize="small"/>
</IconButton>
</>
}
subtitle={t('sync_sub')}
snackbar={snackbar}
onSnackbarClose={() => this.setState({ snackbar: '' })}
>
<Grid container alignItems="flex-end" className={classes.buttonGrid}>
<FormControlLabel
control={
<Checkbox
checked={showPush}
onChange={this.handleCheckbox('showPush')}
color="primary"
/>
}
label={t('Show push connections')}
/>
<FormControlLabel
control={
<Checkbox
checked={onlyActive}
onChange={this.handleCheckbox('onlyActive')}
color="primary"
/>
}
label={t('Only show active connections')}
/>
<TextField
value={filterUpdated}
onChange={this.handleInput('filterUpdated')}
label={t("Last updated (seconds)")}
className={classes.select}
select
color="primary"
fullWidth
>
<MenuItem value={60}>10</MenuItem>
<MenuItem value={60}>30</MenuItem>
<MenuItem value={60}>60</MenuItem>
<MenuItem value={120}>120</MenuItem>
</TextField>
<TextField
value={filterEnded}
onChange={this.handleInput('filterEnded')}
label={t("Last ended (seconds)")}
className={classes.select}
select
color="primary"
fullWidth
>
<MenuItem value={20}>3</MenuItem>
<MenuItem value={20}>5</MenuItem>
<MenuItem value={20}>10</MenuItem>
<MenuItem value={20}>20</MenuItem>
</TextField>
<div className={classes.actions}>
<TextField
value={match}
onChange={this.handleInput('match')}
placeholder={t("Filter")}
variant="outlined"
className={classes.textfield}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<Search color="secondary" />
</InputAdornment>
),
}}
color="primary"
/>
</div>
</Grid>
<SyncStatistics data={sync}/>
<Paper elevation={1}>
<Table size="small">
<TableHead>
<TableRow>
{this.columns.map((column) => (
<TableCell
key={column.value}
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('Push')}
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{(sortedDevices || sync).map((obj, idx) => {
const timePast = getTimePast(obj.diff);
const matches = this.getMatch(obj);
return matches ? (
<Tooltip key={idx} placement="top" title={obj.devtype + ' / ' + obj.devagent}>
<TableRow hover className={this.getRowClass(obj, obj.diff)}>
<TableCell className={classes.cell} padding="checkbox">{obj.pid || ''}</TableCell>
<TableCell className={classes.cell} padding="checkbox">{obj.ip || ''}</TableCell>
<TableCell className={classes.cell}>{obj.user || ''}</TableCell>
<TableCell className={classes.cell}>{getStringFromCommand(obj.command)}</TableCell>
<TableCell className={classes.cell}>{timePast}</TableCell>
<TableCell className={classes.cell}>{obj.devid || ''}</TableCell>
<TableCell className={classes.cell}>{obj.addinfo || ''}</TableCell>
<TableCell className={classes.cell} padding="checkbox">
{obj.push ? <CheckCircleOutlined /> : <HighlightOffOutlined />}
</TableCell>
</TableRow>
</Tooltip>
) : null;
})}
</TableBody>
</Table>
</Paper>
</TableViewContainer>
);
}
Example #26
Source File: LoginDialog.js From react-saas-template with MIT License | 4 votes |
function LoginDialog(props) {
const {
setStatus,
history,
classes,
onClose,
openChangePasswordDialog,
status,
} = props;
const [isLoading, setIsLoading] = useState(false);
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
const loginEmail = useRef();
const loginPassword = useRef();
const login = useCallback(() => {
setIsLoading(true);
setStatus(null);
if (loginEmail.current.value !== "[email protected]") {
setTimeout(() => {
setStatus("invalidEmail");
setIsLoading(false);
}, 1500);
} else if (loginPassword.current.value !== "HaRzwc") {
setTimeout(() => {
setStatus("invalidPassword");
setIsLoading(false);
}, 1500);
} else {
setTimeout(() => {
history.push("/c/dashboard");
}, 150);
}
}, [setIsLoading, loginEmail, loginPassword, history, setStatus]);
return (
<Fragment>
<FormDialog
open
onClose={onClose}
loading={isLoading}
onFormSubmit={(e) => {
e.preventDefault();
login();
}}
hideBackdrop
headline="Login"
content={
<Fragment>
<TextField
variant="outlined"
margin="normal"
error={status === "invalidEmail"}
required
fullWidth
label="Email Address"
inputRef={loginEmail}
autoFocus
autoComplete="off"
type="email"
onChange={() => {
if (status === "invalidEmail") {
setStatus(null);
}
}}
helperText={
status === "invalidEmail" &&
"This email address isn't associated with an account."
}
FormHelperTextProps={{ error: true }}
/>
<VisibilityPasswordTextField
variant="outlined"
margin="normal"
required
fullWidth
error={status === "invalidPassword"}
label="Password"
inputRef={loginPassword}
autoComplete="off"
onChange={() => {
if (status === "invalidPassword") {
setStatus(null);
}
}}
helperText={
status === "invalidPassword" ? (
<span>
Incorrect password. Try again, or click on{" "}
<b>"Forgot Password?"</b> to reset it.
</span>
) : (
""
)
}
FormHelperTextProps={{ error: true }}
onVisibilityChange={setIsPasswordVisible}
isVisible={isPasswordVisible}
/>
<FormControlLabel
className={classes.formControlLabel}
control={<Checkbox color="primary" />}
label={<Typography variant="body1">Remember me</Typography>}
/>
{status === "verificationEmailSend" ? (
<HighlightedInformation>
We have send instructions on how to reset your password to your
email address
</HighlightedInformation>
) : (
<HighlightedInformation>
Email is: <b>[email protected]</b>
<br />
Password is: <b>HaRzwc</b>
</HighlightedInformation>
)}
</Fragment>
}
actions={
<Fragment>
<Button
type="submit"
fullWidth
variant="contained"
color="secondary"
disabled={isLoading}
size="large"
>
Login
{isLoading && <ButtonCircularProgress />}
</Button>
<Typography
align="center"
className={classNames(
classes.forgotPassword,
isLoading ? classes.disabledText : null
)}
color="primary"
onClick={isLoading ? null : openChangePasswordDialog}
tabIndex={0}
role="button"
onKeyDown={(event) => {
// For screenreaders listen to space and enter events
if (
(!isLoading && event.keyCode === 13) ||
event.keyCode === 32
) {
openChangePasswordDialog();
}
}}
>
Forgot Password?
</Typography>
</Fragment>
}
/>
</Fragment>
);
}
Example #27
Source File: AddGlobalUser.js From admin-web with GNU Affero General Public License v3.0 | 4 votes |
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>
);
}
Example #28
Source File: RegisterForm.js From Django-REST-Framework-React-BoilerPlate with MIT License | 4 votes |
// ----------------------------------------------------------------------
export default function RegisterForm() {
const dispatch = useDispatch();
const navigate = useNavigate();
const userLogin = useSelector((state) => state.userLogin);
const { userInfo } = userLogin;
const userRgister = useSelector((state) => state.userRgister);
const { error: registerError, loading: registerLoading } = userRgister;
const [showPassword, setShowPassword] = useState(false);
const RegisterSchema = Yup.object().shape({
firstName: Yup.string().min(2, 'Too Short!').max(50, 'Too Long!').required('First name required'),
lastName: Yup.string().min(2, 'Too Short!').max(50, 'Too Long!').required('Last name required'),
email: Yup.string().email('Email must be a valid email address').required('Email is required'),
password: Yup.string().required('Password is required'),
});
const formik = useFormik({
initialValues: {
firstName: '',
lastName: '',
email: '',
password: '',
},
validationSchema: RegisterSchema,
onSubmit: () => {
dispatch(register(values.firstName, values.lastName, values.email, values.password));
},
});
const { errors, touched, values, handleSubmit, isSubmitting, getFieldProps } = formik;
useEffect(() => {
if (userInfo) {
navigate('/dashboard/app', { replace: true });
}
}, [navigate, userInfo]);
return (
<FormikProvider value={formik}>
<Form autoComplete="off" noValidate onSubmit={handleSubmit}>
<Stack spacing={3}>
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
<TextField
fullWidth
label="First name"
{...getFieldProps('firstName')}
error={Boolean(touched.firstName && errors.firstName)}
helperText={touched.firstName && errors.firstName}
/>
<TextField
fullWidth
label="Last name"
{...getFieldProps('lastName')}
error={Boolean(touched.lastName && errors.lastName)}
helperText={touched.lastName && errors.lastName}
/>
</Stack>
<TextField
fullWidth
autoComplete="username"
type="email"
label="Email address"
{...getFieldProps('email')}
error={Boolean(touched.email && errors.email)}
helperText={touched.email && errors.email}
/>
<TextField
fullWidth
autoComplete="current-password"
type={showPassword ? 'text' : 'password'}
label="Password"
{...getFieldProps('password')}
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton edge="end" onClick={() => setShowPassword((prev) => !prev)}>
<Iconify icon={showPassword ? 'eva:eye-fill' : 'eva:eye-off-fill'} />
</IconButton>
</InputAdornment>
),
}}
error={Boolean(touched.password && errors.password)}
helperText={touched.password && errors.password}
/>
{registerError ? (
<Alert severity="error">
<AlertTitle>Register Error</AlertTitle>
{registerError}
</Alert>
) : null}
<LoadingButton
fullWidth
size="large"
type="submit"
variant="contained"
loading={registerLoading ? isSubmitting : null}
>
Register
</LoadingButton>
</Stack>
</Form>
</FormikProvider>
);
}
Example #29
Source File: EmojiTextArea.js From react-saas-template with MIT License | 4 votes |
function EmojiTextarea(props) {
const {
theme,
classes,
rightContent,
placeholder,
maxCharacters,
emojiSet,
inputClassName,
onChange
} = props;
const [open, setOpen] = useState(false);
const [value, setValue] = useState("");
const [characters, setCharacters] = useState(0);
const onSelectEmoji = useCallback(
emoji => {
let _characters;
let _value = value + emoji.native;
if (maxCharacters) {
_characters = countWithEmojis(_value);
if (_characters > maxCharacters) {
return;
}
}
if (onChange) {
onChange(_value, _characters);
}
setValue(_value);
setCharacters(_characters);
},
[value, setValue, setCharacters, maxCharacters, onChange]
);
const handleTextFieldChange = useCallback(
event => {
const { target } = event;
const { value } = target;
let characters;
if (maxCharacters) {
characters = countWithEmojis(value);
if (characters > maxCharacters) {
return;
}
}
if (onChange) {
onChange(value, characters);
}
setValue(value);
setCharacters(characters);
},
[maxCharacters, onChange, setValue, setCharacters]
);
const toggleOpen = useCallback(() => {
setOpen(!open);
}, [open, setOpen]);
return (
<Fragment>
<Grid spacing={0} container>
<Grid
item
xs={rightContent ? 8 : 12}
sm={rightContent ? 9 : 12}
lg={rightContent ? 10 : 12}
className={classes.relative}
>
<TextField
fullWidth
multiline
variant="outlined"
rows={6}
onInput={handleTextFieldChange}
value={value}
placeholder={placeholder}
InputProps={{
classes: {
notchedOutline: inputClassName ? inputClassName : null
}
}}
/>
<div className={classes.floatButtonWrapper}>
<IconButton onClick={toggleOpen} size="large">
{open ? (
<CloseIcon color="primary" />
) : (
<EmojiEmotionsIcon color="primary" />
)}
</IconButton>
</div>
</Grid>
{rightContent && (
<Grid item xs={4} sm={3} lg={2}>
{rightContent}
</Grid>
)}
</Grid>
{maxCharacters && (
<FormHelperText error={characters >= maxCharacters}>
{`${characters}/${maxCharacters} characters`}
</FormHelperText>
)}
<Collapse in={open}>
<Box mt={1}>
<Picker
set={emojiSet}
color={theme.palette.primary.main}
style={{ width: "100%" }}
onSelect={onSelectEmoji}
emojisToShowFilter={emojisToShowFilter}
/>
</Box>
</Collapse>
</Fragment>
);
}