@material-ui/lab#Alert JavaScript Examples
The following examples show how to use
@material-ui/lab#Alert.
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: Announcement.jsx From redive_linebot with MIT License | 6 votes |
TopNews = props => {
const { breakingNews } = props;
const levels = ["success", "info", "warning", "error"];
if (Object.keys(breakingNews).length === 0) {
breakingNews.level = "success";
breakingNews.title = "乾淨無比";
breakingNews.content = "這個作者很懶,什麼話都沒說~";
breakingNews.create_time = new Date().toString();
}
return (
<Alert severity={levels.indexOf(breakingNews.level) === -1 ? "warning" : breakingNews.level}>
<AlertTitle>{breakingNews.title}</AlertTitle>
{breakingNews.content} <br />
<Typography variant="caption" color="textSecondary">
{new Date(breakingNews.create_time).toLocaleString()}
</Typography>
</Alert>
);
}
Example #2
Source File: ImageErrorAlert.js From treetracker-admin-client with GNU Affero General Public License v3.0 | 6 votes |
function ImageErrorAlert({
alertHeight,
alertWidth,
alertPadding,
alertPosition,
alertTextSize,
alertTitleSize,
}) {
return (
<Alert
severity="error"
style={{
flexDirection: 'column',
position: alertPosition,
width: alertWidth,
height: alertHeight,
padding: alertPadding,
}}
>
<AlertTitle style={{ fontSize: alertTitleSize, whiteSpace: 'nowrap' }}>
Failed to load image
</AlertTitle>
<div>
<p style={{ fontSize: alertTextSize }}>
please try — <strong>reloading the page</strong>
</p>
<p style={{ fontSize: alertTextSize }}>
or — <strong>report the issue to an admin</strong>
</p>
</div>
</Alert>
);
}
Example #3
Source File: metrics.js From graphql-sample-apps with Apache License 2.0 | 6 votes |
Metrics = () => {
const {loading, error, data} = useQuery(query);
const [newMetricName, setNewMetricName] = useState("");
const [addMetric, { loading: mutationLoading }] = useMutation(addMetricMutation, {
awaitRefetchQueries: true,
refetchQueries: [{query}],
});
const metrics = data?.queryMetric || []
return <>
<Navbar title="Metrics" color="primary" />
<Content>
{loading && <Backdrop open={loading || mutationLoading} >
<CircularProgress />
</Backdrop>}
{error && <Alert severity="error">Something Went Horribly Wrong</Alert>}
<Card style={{ padding: 30 }}>
<Typography>Here are the metrics currently configured:</Typography>
<List>
{metrics.map(({ name }, index) => <ListItem item key={index} sm={12} md={6} lg={3}>
<Typography>{name}</Typography>
</ListItem>)}
</List>
<TextField
label="Add Metric"
defaultValue={newMetricName}
onChange={e => setNewMetricName(e.target.value)}
/>
<UglyButton onClick={() => addMetric({ variables: { newMetricName } })} disabled={newMetricName === ""}>
Add Metric
</UglyButton>
</Card>
</Content>
</>
}
Example #4
Source File: AlertMessage.js From reddish with MIT License | 6 votes |
AlertMessage = ({ severity, error, clearError }) => {
const classes = useAlertStyles();
if (!error) {
return null;
}
return (
<div className={classes.root}>
<Alert severity={severity} onClose={clearError}>
<AlertTitle>Error</AlertTitle>
{error}
</Alert>
</div>
);
}
Example #5
Source File: ErrorMessage.js From stack-underflow with MIT License | 6 votes |
AlertMessage = ({ errorMsg, clearErrorMsg }) => {
const classes = useAlertStyles();
if (!errorMsg) {
return null;
}
return (
<div className={classes.root}>
<Alert severity="error" onClose={clearErrorMsg}>
<AlertTitle>Error</AlertTitle>
{errorMsg}
</Alert>
</div>
);
}
Example #6
Source File: AlertBox.js From to-view-list with MIT License | 6 votes |
AlertBox = ({ severity, message, clearError, title }) => {
const classes = useAlertStyles();
return (
<div className={classes.root}>
<Alert severity={severity} onClose={clearError}>
<AlertTitle>{title || 'Error'}</AlertTitle>
{message}
</Alert>
</div>
);
}
Example #7
Source File: index.jsx From redive_linebot with MIT License | 6 votes |
WorldBossMessage = () => {
const { liff } = window;
useEffect(() => {
window.document.title = "管理員用-世界王訊息管理";
}, []);
if (!liff.isLoggedIn()) {
return <Alert severity="error">請先登入</Alert>;
}
return (
<Grid container direction="column" spacing={1}>
<Grid item>
<Alert severity="warning">所有紀錄都會記錄作者資訊,請謹慎操作</Alert>
</Grid>
<Grid item>
<DataList />
</Grid>
<Fab color="primary" aria-label="add" component={Link} to={"/Admin/WorldbossMessage/Create"}>
<AddIcon />
</Fab>
</Grid>
);
}
Example #8
Source File: addPool.jsx From crv.finance with MIT License | 6 votes |
render() {
const { classes } = this.props;
const {
loading,
account,
} = this.state
if(!account || !account.address) {
return (<div></div>)
}
return (
<div className={ classes.root }>
<div className={ classes.inputContainer }>
<Typography variant='h2' align='center' className={ classes.poolInfoHeader }>Setup</Typography>
<Alert icon={false} className={classes.infoAlert}>
Note: The factory does not support tokens with transfer fees.<br /><a href="https://curve.readthedocs.io/factory-deployer.html#limitations" target="_blank" rel="noopener noreferrer">Read all expected behaviors and limitations</a>
</Alert>
{ this.renderInput('name') }
{ this.renderInput('symbol') }
{ this.renderAddressInput() }
{ this.renderBasePoolSelect() }
{ this.renderAssetInfo() }
<Button
className={ classes.actionButton }
variant="outlined"
color="primary"
disabled={ loading }
onClick={ this.onAddPool }
fullWidth
>
<Typography className={ classes.buttonText } variant={ 'h4'} color='secondary'>Create Pool</Typography>
</Button>
</div>
{ loading && <Loader /> }
</div>
)
}
Example #9
Source File: Notification.js From scholar-front-end with MIT License | 6 votes |
function Notification() {
const [open, setOpen] = React.useState(true);
const classes = useStyles();
return (
<div className={classes.root}>
<Collapse in={open}>
<Alert severity="info" action={
<IconButton aria-label="close" size="small" onClick={()=>{
setOpen(false);
}}>
<CloseIcon fontSize="inherit"/>
</IconButton>
}>
<AlertTitle>Price Drop</AlertTitle>
<p className={classes.inform}>All Courses At <strong> 399 </strong>/-</p>
</Alert>
</Collapse>
</div>
)
}
Example #10
Source File: LogoutCallback.jsx From Edlib with GNU General Public License v3.0 | 6 votes |
LogoutCallback = ({ loading, error }) => {
return (
<div className="pt-5">
<Container>
<Grid container justify="center">
<Grid item md={6}>
<Paper>
<h2>Logg ut</h2>
{loading && (
<Box display="flex" justifyContent="center">
<CircularProgress />
</Box>
)}
{error ? (
<Alert color="danger" className="mt-3">
{error.message}
</Alert>
) : (
''
)}
</Paper>
</Grid>
</Grid>
</Container>
</div>
);
}
Example #11
Source File: ErrorFallback.js From akashlytics-deploy with GNU General Public License v3.0 | 6 votes |
export function ErrorFallback({ error, resetErrorBoundary }) {
const classes = useStyles();
return (
<div className={classes.root} role="alert">
<Typography variant="h4" className={classes.heading}>
Something went wrong:
</Typography>
<Alert severity="error" className={classes.alert}>
<AlertTitle>Error</AlertTitle>
{error.message}
</Alert>
<Button variant="contained" color="primary" onClick={resetErrorBoundary}>
Try again
</Button>
</div>
);
}
Example #12
Source File: FailureBox.jsx From pwa with MIT License | 6 votes |
export default function FailureBox() {
return (
<Box m={3}>
<Alert severity="error">
<Typography>{'دریافت اطلاعات با خطا مواجه شد'}</Typography>
</Alert>
</Box>
);
}
Example #13
Source File: LoginCallback.jsx From Edlib with GNU General Public License v3.0 | 6 votes |
LoginCallback = ({ loading, error }) => {
return (
<div className={cn(styles.login)}>
<Container>
<Grid container justify="center">
<Grid item md={6}>
<Paper>
<h2>Logg inn</h2>
{loading && (
<Box justifyContent="center" display="flex">
<CircularProgress />
</Box>
)}
{error ? (
<Alert color="danger" className="mt-3">
{error.message}
</Alert>
) : (
''
)}
</Paper>
</Grid>
</Grid>
</Container>
</div>
);
}
Example #14
Source File: SelectNetworkModal.js From akashlytics-deploy with GNU General Public License v3.0 | 5 votes |
SelectNetworkModal = ({ onClose }) => {
const classes = useStyles();
const { selectedNetworkId } = useSettings();
const [localSelectedNetworkId, setLocalSelectedNetworkId] = useState(selectedNetworkId);
const handleSelectNetwork = (network) => {
setLocalSelectedNetworkId(network.id);
};
const handleSaveChanges = () => {
if (selectedNetworkId !== localSelectedNetworkId) {
// Set in the settings and local storage
localStorage.setItem("selectedNetworkId", localSelectedNetworkId);
// Reset the ui to reload the settings for the currently selected network
ipcApi.send("relaunch");
} else {
onClose();
}
};
return (
<Dialog open={true} onClose={onClose} maxWidth="xs" fullWidth>
<DialogTitle>Select Network</DialogTitle>
<DialogContent dividers className={classes.dialogContent}>
<List className={classes.list}>
{networks.map((network) => {
return (
<ListItem key={network.id} dense button onClick={() => handleSelectNetwork(network)}>
<ListItemIcon>
<Radio checked={localSelectedNetworkId === network.id} value={network.id} />
</ListItemIcon>
<ListItemText
classes={{ secondary: classes.secondaryText }}
primary={
<Box display="flex" alignItems="center" justifyContent="space-between" fontSize="1rem">
<span>
{network.title}
{" - "}
<Typography variant="caption" className={classes.version}>
{network.version}
</Typography>
</span>
{network.id !== mainnetId && <Chip label="Experimental" size="small" color="secondary" className={classes.experimentalChip} />}
</Box>
}
secondary={network.description}
/>
</ListItem>
);
})}
</List>
{localSelectedNetworkId !== mainnetId && (
<Alert variant="outlined" severity="warning" className={classes.alert}>
<Typography variant="body1">
<strong>Warning</strong>
</Typography>
<Typography variant="body2">Changing networks will restart the app and some features are experimental.</Typography>
</Alert>
)}
</DialogContent>
<DialogActions className={classes.dialogActions}>
<Button onClick={onClose} type="button" autoFocus>
Close
</Button>
<Button variant="contained" onClick={handleSaveChanges} color="primary" type="button">
Save
</Button>
</DialogActions>
</Dialog>
);
}
Example #15
Source File: add-data.js From graphql-sample-apps with Apache License 2.0 | 5 votes |
AddData = ({currentTime = new Date()}) => {
const {loading, error, data} = useQuery(query);
const [date, setDate] = useState(currentTime.toISOString().substr(0, 10))
const [values, setValues] = useState({})
const [addCollectionMutation] = useMutation(addCollection);
const metrics = data?.queryMetric || []
const submitMetrics = async () => {
const readings = Object.entries(values).map(([name, value]) => ({ value, metric: { name } }))
await addCollectionMutation({ variables: {readings, date} })
history.push("/");
}
return <>
<Navbar title="Home" color="primary" />
<Content>
{loading && <Backdrop open={loading} >
<CircularProgress />
</Backdrop>}
{error && <Alert severity="error">Something Went Horribly Wrong</Alert>}
<Grid container spacing={3}>
<Grid item sm={12}>
<Card style={{ padding: 30 }}>
<TextField
label="Date"
type="date"
defaultValue={date}
InputLabelProps={{
shrink: true,
}}
style={{ marginRight: 20 }}
onChange={e => setDate(e.target.value)}
/>
</Card>
</Grid>
{metrics.map(({ name }, index) => <Grid item key={index} sm={12} md={6} lg={3}>
<Card style={{ textAlign: "center" }}>
<CardContent>
<TextField
label={name}
type="number"
defaultValue={0}
InputLabelProps={{
shrink: true,
}}
style={{ marginRight: 20 }}
onChange={e => setValues({...values, [name]: e.target.value})}
/>
</CardContent>
</Card>
</Grid>)}
<Grid item sm={12} style={{textAlign: "right"}}>
<UglyButton onClick={submitMetrics}>Add Readings</UglyButton>
</Grid>
</Grid>
</Content>
</>
}
Example #16
Source File: InspectClients.js From management-center with Apache License 2.0 | 5 votes |
Clients = (props) => {
const classes = useStyles();
const context = useContext(WebSocketContext);
const dispatch = useDispatch();
const history = useHistory();
const confirm = useConfirm();
const { enqueueSnackbar } = useSnackbar();
const { client: brokerClient } = context;
const { inspectFeature, userProfile, roles = [], clients = [], onSort, sortBy, sortDirection } = props;
const onUpdateUserRoles = async (user, roles = []) => {
if (!roles) {
roles = [];
}
const rolenames = roles.map((role) => role.value);
await brokerClient.updateUserRoles(user, rolenames);
const clients = await brokerClient.inspectListClients();
dispatch(updateInspectClients(clients));
};
const onSelectClient = async (username) => {
const client = await brokerClient.inspectGetClient(username);
dispatch(updateInspectClient(client));
history.push(`/admin/inspect/clients/detail/${username}`);
};
return (
<div>
<Breadcrumbs aria-label="breadcrumb">
<RouterLink className={classes.breadcrumbLink} to="/home">
Home
</RouterLink>
<RouterLink className={classes.breadcrumbLink} color="inherit" to="/admin">
Admin
</RouterLink>
<Typography className={classes.breadcrumbItem} color="textPrimary">
Inspect
</Typography>
</Breadcrumbs>
{/* TODO: Quick hack to detect whether feature is supported */}
{inspectFeature?.error ? <><br/><Alert severity="warning">
<AlertTitle>{inspectFeature.error.title}</AlertTitle>
{inspectFeature.error.message}
</Alert></> : null}
{!inspectFeature?.error && inspectFeature?.supported === false ? <><br/><Alert severity="warning">
<AlertTitle>Feature not available</AlertTitle>
Make sure that this feature is included in your MMC license.
</Alert></> : null}
<br />
<br />
{ createClientsTable(clients, classes, props, onUpdateUserRoles, onSelectClient) }
</div>
);
}
Example #17
Source File: Job.jsx From Edlib with GNU General Public License v3.0 | 5 votes |
Job = ({
start,
status,
name,
onStop,
showKillButton,
showResumeButton,
showInput,
onResume,
data,
setData,
}) => {
return (
<>
<h2>{name}</h2>
{showInput && (
<Box>
<TextareaAutosize
value={data}
onChange={(e) => setData(e.target.value)}
/>
</Box>
)}
{status.loading && (
<>
<div>
<CircularProgress />
</div>
<div>
<LinearProgress
variant="determinate"
value={status.percentDone || 0}
/>
</div>
<div>{status.message}</div>
{!status.killingStarted && showKillButton && (
<div>
<Button variant="contained" onClick={onStop}>
Stop
</Button>
</div>
)}
</>
)}
{status.done && <Alert severity="success">{status.message}</Alert>}
{status.error && <Alert severity="error">{status.message}</Alert>}
{!status.loading && (
<Button
onClick={start}
disabled={showInput && data === ''}
variant="contained"
color="primary"
>
Start
</Button>
)}
{!status.loading &&
!status.done &&
!status.error &&
showResumeButton && <Button onClick={onResume}>Resume</Button>}
</>
);
}
Example #18
Source File: generate-data.js From graphql-sample-apps with Apache License 2.0 | 5 votes |
Home = ({currentTime = new Date()}) => {
const [endDate, setEndDate] = useState(currentTime.toISOString().substr(0, 10))
const [startDate, setStartDate] = useState(new Date(currentTime.getTime() - 28 * 3600 * 1000 * 24).toISOString().substr(0, 10))
const {loading, error, data} = useQuery(query);
const results = [];
for (let date = Date.parse(startDate); date <= Date.parse(endDate); date = date + 3600 * 1000 * 24) {
results.push({
timestamp: new Date(date).toISOString().substr(0, 10),
readings: (data?.queryMetric || []).map(({name}) => ({
value: ((date - Date.parse(startDate)) / (3600 * 1000 * 24)) + Math.random() * 4,
name
}))
})
}
return <>
<Navbar title="Home" color="primary" />
<Content>
{loading && <Backdrop open={loading} >
<CircularProgress />
</Backdrop>}
{error && <Alert severity="error">Something Went Horribly Wrong</Alert>}
<Grid container spacing={3}>
<Grid item sm={12}>
<Card style={{ padding: 30 }}>
<TextField
label="From"
type="date"
defaultValue={startDate}
InputLabelProps={{
shrink: true,
}}
style={{marginRight: 20}}
onChange={e => setStartDate(e.target.value)}
/>
<TextField
label="To"
type="date"
defaultValue={endDate}
InputLabelProps={{
shrink: true,
}}
onChange={e => setEndDate(e.target.value)}
/>
</Card>
</Grid>
<Grid item sm={12}>
<Card style={{ padding: 30 }}>
<pre>{`mutation {
addCollection(input: [
${results.map(({timestamp, readings}) => `{
timestamp: "${timestamp}",
readings: [
${readings.map(({value, name}) => `{value: ${value}, metric: { name: "${name}" } }`).join(",\n ")}
]
}`).join(",\n ")}
]) {
collection {
readings {
value
metric { name }
}
}
}
}`}</pre>
</Card>
</Grid>
</Grid>
</Content>
</>
}
Example #19
Source File: GenerateCSVWithResourceUrls.jsx From Edlib with GNU General Public License v3.0 | 5 votes |
GenerateCsvWithResourceUrls = () => {
const request = useRequestWithToken();
const [{ loading, error, success }, setStatus] = React.useState({
loading: false,
error: false,
});
const onClick = React.useCallback(() => {
setStatus({
loading: true,
error: false,
});
request('/resources/admin/resources', 'GET', { json: true })
.then(({ resources }) => {
const link = document.createElement('a');
const rows = resources.map((r) => [
r.id,
`${apiConfig.wwwUrl}/s/resources/${r.id}`,
]);
rows.unshift(['id', 'url']);
link.setAttribute('href', encodeURI(listToCSVContent(rows)));
link.setAttribute('download', 'edlib_resources.csv');
document.body.appendChild(link); // Required for FF
link.click();
setStatus({
loading: false,
error: false,
success: true,
});
})
.catch((error) => {
console.error(error);
setStatus({
loading: false,
error: true,
});
});
}, []);
return (
<>
{error && <Alert color="danger">Noe skjedde</Alert>}
{success && <Alert color="success">Vellykket!</Alert>}
<Button color="primary" onClick={onClick} disabled={loading}>
{loading && <CircularProgress />}
{!loading && 'Lag CSV med alle ressurser'}
</Button>
</>
);
}
Example #20
Source File: index.js From flame-coach-web with MIT License | 5 votes |
Notification = ({
open,
openHandler,
message,
level,
collapse,
className
}) => {
const classes = useStyles();
let internalLevel;
switch (level) {
case INFO:
internalLevel = "info";
break;
case WARNING:
internalLevel = "warning";
break;
case ERROR:
internalLevel = "error";
break;
case SUCCESS:
internalLevel = "success";
break;
default:
internalLevel = "info";
break;
}
return (
<Box className={clsx(className, classes.notificationBar)}>
{collapse
? (
<Collapse in={open}>
<Alert
variant="filled"
severity={internalLevel}
action={(
<IconButton
aria-label="close"
color="inherit"
size="small"
onClick={() => {
openHandler(false);
}}
>
<CloseIcon fontSize="inherit" />
</IconButton>
)}
>
{message}
</Alert>
</Collapse>
) : (
<Alert
itemID="notification"
variant="filled"
severity={internalLevel}
>
{message}
</Alert>
)}
</Box>
);
}
Example #21
Source File: NewMeta.js From Designer-Client with GNU General Public License v3.0 | 5 votes |
export function NewMetaDialog(props) {
const open = props.open;
const api = props.api;
const dataType = props.dataType;
const [alertMessage, setAlert] = useState();
const handleClose = (e) => {
props.setOpen(false);
setAlert();
}
return (
<Dialog
open={open}
onClose={handleClose}
scroll='paper'
aria-labelledby="scroll-dialog-title"
aria-describedby="scroll-dialog-description"
maxWidth={'sm'}
disableBackdropClick={true}
fullWidth={true}
>
<Container maxWidth="lg">
{ alertMessage &&
<Box mt={2}>
<Alert severity="error">{alertMessage}</Alert>
</Box>
}
{ dataType === 'upload' &&
<FileUploadForm api={api} handleClose={handleClose} setAlert={setAlert}/>
}
{ dataType === 'url' &&
<FileUrlForm api={api} handleClose={handleClose} setAlert={setAlert}/>
}
{ dataType === 'dbms' &&
<DbmsForm api={api} handleClose={handleClose} setAlert={setAlert}/>
}
</Container>
</Dialog>
);
}
Example #22
Source File: home.js From graphql-sample-apps with Apache License 2.0 | 5 votes |
Home = ({currentTime = new Date()}) => {
const [endTime] = useState(currentTime)
const oneMonthAgo = new Date(endTime.getTime() - 28 * 3600 * 1000 * 24);
const startDate = oneMonthAgo.toISOString().substr(0, 10)
const endDate = endTime.toISOString().substr(0, 10)
const {loading, error, data, refetch} = useQuery(query, {
variables: {
timestampGE: startDate,
timestampLT: endDate,
}
});
const graphData = useMemo(() => {
if(!data) { return [] }
return (data.queryMetric || []).map(({name, readings}) => ({
name,
data: [
["Timestamp", name],
...readings.map(({ value, collection }) => [new Date(collection.timestamp), value]).sort(([k1], [k2]) => k1 < k2 ? -1 : 1)
]
}));
}, [data])
return <>
<Navbar title="Home" color="primary" />
<Content>
{loading && <Backdrop open={loading} >
<CircularProgress />
</Backdrop>}
{error && <Alert severity="error">Something Went Horribly Wrong</Alert>}
<Grid container spacing={3}>
<Grid item sm={12}>
<Card style={{ padding: 30 }}>
<TextField
label="From"
type="date"
defaultValue={startDate}
InputLabelProps={{
shrink: true,
}}
style={{marginRight: 20}}
onChange={e => refetch({ timestampGE: e.target.value })}
/>
<TextField
label="To"
type="date"
defaultValue={endDate }
InputLabelProps={{
shrink: true,
}}
onChange={e => refetch({ timestampLT: e.target.value })}
/>
</Card>
</Grid>
{graphData.map(({name, data}, index) => <Grid item key={index} sm={12} lg={6}>
<Card style={{textAlign: "center"}}>
<CardContent>
<h3>{name}</h3>
{data.length > 1
? <Chart
chartType="LineChart"
width="100%"
loader={<CircularProgress />}
data={data}
options={{
pointSize: 5,
curveType: "function",
legend: { position: "none" }
}} />
: <Typography>Not enough Data to show this chart</Typography>}
</CardContent>
</Card>
</Grid>)}
</Grid>
</Content>
</>
}
Example #23
Source File: create.jsx From redive_linebot with MIT License | 5 votes |
WorldbossMessageCreate = () => {
const [{ data, loading, error }, sendRequest] = useAxios(
{
url: "/api/Game/World/Boss/Feature/Message",
method: "POST",
},
{ manual: true }
);
const [errorControl, setError] = useState({ show: false, message: "" });
const onSubmit = formData => {
const { data = {}, isValidImage = false, isValidTemplate = false } = formData;
const { template, imageUrl } = data;
if (isValidImage && isValidTemplate) {
const payload = { template };
if (imageUrl) {
payload.icon_url = imageUrl;
}
sendRequest({
data: payload,
});
} else {
setError({ show: true, message: "Invalid form data" });
}
};
useEffect(() => {
if (error) {
setError({ show: true, message: error.message });
}
}, [error]);
// 如果成功,就導回列表頁
if (data && data.message === "success") {
return <Redirect to="/Admin/WorldbossMessage" />;
}
return (
<Grid container direction="column" spacing={1}>
<Grid item>
<Alert severity="warning">
請注意,此訊息建立後,將立即生效,所有玩家將會馬上注意到此訊息的內容。
</Alert>
</Grid>
<Grid item>
<MessageForm onSubmit={onSubmit} loading={loading} />
</Grid>
<Snackbar
open={errorControl.show}
autoHideDuration={6000}
onClose={() => setError({ ...errorControl, show: false })}
>
<Alert elevation={6} variant="filled" severity="error" style={{ width: "100%" }}>
{errorControl.message}
</Alert>
</Snackbar>
</Grid>
);
}
Example #24
Source File: WelcomeModal.js From akashlytics-deploy with GNU General Public License v3.0 | 5 votes |
WelcomeModal = ({ open, onClose }) => {
const classes = useStyles();
const { address } = useWallet();
return (
<Dialog open={open} maxWidth="xs" fullWidth>
<DialogContent className={classes.dialogContent}>
<Typography variant="h3">
<strong>Welcome!</strong>
</Typography>
<Typography variant="h6" className={classes.subTitle} color="textSecondary">
You need to get some <LinkTo onClick={() => window.electron.openUrl("https://coinmarketcap.com/currencies/akash-network/")}>$AKT</LinkTo> in order to
deploy the Akash Network.
</Typography>
<Typography variant="caption">Here are some places to acquire some:</Typography>
<ul className={classes.ul}>
<li>
<LinkTo onClick={() => window.electron.openUrl("https://docs.akash.network/token/buy")}>Buy tokens</LinkTo>
</li>
<Box marginTop="1rem">
<hr />
</Box>
<Typography variant="caption">
<strong>Exchanges</strong>
</Typography>
<li>
<LinkTo onClick={() => window.electron.openUrl("https://app.osmosis.zone/")}>Osmosis (DEX)</LinkTo>
</li>
<li>
<LinkTo onClick={() => window.electron.openUrl("https://emeris.com/")}>Emeris (DEX)</LinkTo>
</li>
<li>
<LinkTo onClick={() => window.electron.openUrl("https://dex.sifchain.finance/")}>Sifchain (DEX)</LinkTo>
</li>
<li>
<LinkTo onClick={() => window.electron.openUrl("https://www.kraken.com/")}>Kraken (CEX)</LinkTo>
</li>
<li>
<LinkTo onClick={() => window.electron.openUrl("https://ascendex.com/")}>Ascendex (CEX)</LinkTo>
</li>
<li>
<LinkTo onClick={() => window.electron.openUrl("https://global.bittrex.com/")}>Bittrex (CEX)</LinkTo>
</li>
<li>
<LinkTo onClick={() => window.electron.openUrl("https://www.bitmart.com/")}>Bitmart (CEX)</LinkTo>
</li>
<li>
<LinkTo onClick={() => window.electron.openUrl("https://www.digifinex.com/")}>Digifinex (CEX)</LinkTo>
</li>
<li>
<LinkTo onClick={() => window.electron.openUrl("https://www.bitglobal.com/")}>Bitglobal (CEX)</LinkTo>
</li>
</ul>
<Box marginBottom=".5rem">
<Typography variant="caption">Once you have $AKT, you can send it to your address:</Typography>
</Box>
<Alert icon={false} variant="outlined">
<Address address={address} isCopyable />
</Alert>
</DialogContent>
<DialogActions>
<Button variant="contained" onClick={onClose} type="button" color="primary">
Got it!
</Button>
</DialogActions>
</Dialog>
);
}
Example #25
Source File: Streams.js From management-center with Apache License 2.0 | 4 votes |
Streams = (props) => {
const classes = useStyles();
const context = useContext(WebSocketContext);
const dispatch = useDispatch();
const history = useHistory();
const confirm = useConfirm();
const { enqueueSnackbar } = useSnackbar();
const { client: brokerClient } = context;
const { streamprocessingFeature, connectionID, streams = [], onSort, sortBy, sortDirection } = props;
const [replayStreamEditorOpen, setReplayStreamEditorOpen] = React.useState(false);
const [replayStream, setReplayStream] = React.useState({});
const handleClickReplayStreamEditorOpen = () => {
setReplayStreamEditorOpen(true);
};
const handleReplayStreamEditorClose = () => {
setReplayStreamEditorOpen(false);
};
const handleReplay = async (stream, { replayTopic, gte, lte, reverse, limit, speed }) => {
try {
await brokerClient.replayStream({
streamname: stream.streamname,
replayTopic,
gte,
lte,
reverse,
limit,
speed
});
const streams = await brokerClient.listStreams();
dispatch(updateStreams(streams));
enqueueSnackbar(`Successfully started replay of stream "${stream.streamname}"`, {
variant: 'success'
});
setReplayStreamEditorOpen(false);
} catch (error) {
enqueueSnackbar(`Error starting replay of stream "${stream.streamname}". Reason: ${error}`, {
variant: 'error'
});
setReplayStreamEditorOpen(false);
}
}
const onNewStream = () => {
history.push('/streams/new');
};
const onReload = async () => {
const streams = await brokerClient.listStreams();
dispatch(updateStreams(streams));
}
const onDisableStream = async (streamname) => {
await confirm({
title: 'Confirm stream disable',
description: `Do you really want to disable stream "${streamname}"?`,
cancellationButtonProps: {
variant: 'contained'
},
confirmationButtonProps: {
color: 'primary',
variant: 'contained'
}
});
await brokerClient.disableStream(streamname);
const streams = await brokerClient.listStreams();
enqueueSnackbar('Stream successfully disabled', {
variant: 'success'
});
dispatch(updateStreams(streams));
};
const onEnableStream = async (streamname) => {
await brokerClient.enableStream(streamname);
const streams = await brokerClient.listStreams();
enqueueSnackbar('Stream successfully enabled', {
variant: 'success'
});
dispatch(updateStreams(streams));
};
const onEnableProcessStream = async (streamname) => {
await brokerClient.processStream(streamname, true);
const streams = await brokerClient.listStreams();
enqueueSnackbar('Stream processing successfully enabled', {
variant: 'success'
});
dispatch(updateStreams(streams));
};
const onDisableProcessStream = async (streamname) => {
await brokerClient.processStream(streamname, false);
const streams = await brokerClient.listStreams();
enqueueSnackbar('Stream processing successfully disabled', {
variant: 'success'
});
dispatch(updateStreams(streams));
};
const onEnablePersistStream = async (streamname) => {
await brokerClient.persistStream(streamname, true);
const streams = await brokerClient.listStreams();
enqueueSnackbar('Stream persistence successfully enabled', {
variant: 'success'
});
dispatch(updateStreams(streams));
};
const onDisablePersistStream = async (streamname) => {
await brokerClient.persistStream(streamname, false);
const streams = await brokerClient.listStreams();
enqueueSnackbar('Stream persistence successfully disabled', {
variant: 'success'
});
dispatch(updateStreams(streams));
};
const onSelectStream = async (streamname) => {
const stream = await brokerClient.getStream(streamname);
dispatch(updateStream(stream));
history.push(`/streams/detail/${streamname}`);
};
const onClearStreamMessages = async (streamname) => {
await confirm({
title: 'Confirm clear all stream messages',
description: `Do you really want to clear all messages in the stream "${streamname}"?`,
cancellationButtonProps: {
variant: 'contained'
},
confirmationButtonProps: {
color: 'primary',
variant: 'contained'
}
});
try {
await brokerClient.clearStreamMessages(streamname);
enqueueSnackbar(`Messages from stream "${streamname}" successfully cleared.`, {
variant: 'success'
});
} catch(error) {
enqueueSnackbar(`Error clearing messages from "${streamname}". Reason: ${error}`, {
variant: 'error'
});
}
};
const onReplayStream = async (stream) => {
setReplayStream(stream);
setReplayStreamEditorOpen(true);
};
const onDeleteStream = async (streamname) => {
await confirm({
title: 'Confirm stream deletion',
description: `Do you really want to delete stream "${streamname}"?`,
cancellationButtonProps: {
variant: 'contained'
},
confirmationButtonProps: {
color: 'primary',
variant: 'contained'
}
});
await brokerClient.deleteStream(streamname);
enqueueSnackbar(`Stream "${streamname}" successfully deleted`, {
variant: 'success'
});
const streams = await brokerClient.listStreams();
dispatch(updateStreams(streams));
};
return (
<div>
<ReplayStreamDialog
stream={replayStream}
open={replayStreamEditorOpen}
handleReplay={handleReplay}
handleClose={handleReplayStreamEditorClose}
/>
<Breadcrumbs aria-label="breadcrumb">
<RouterLink className={classes.breadcrumbLink} to="/home">
Home
</RouterLink>
<Typography className={classes.breadcrumbItem} color="textPrimary">
Streams
</Typography>
</Breadcrumbs>
{/* TODO: Quick hack to detect whether feature is supported */}
{streamprocessingFeature?.supported === false ? <><br/><Alert severity="warning">
<AlertTitle>Enterprise Solution feature</AlertTitle>
Streams are a premium feature. For more information visit <a className={classes.link} href="https://www.cedalo.com">cedalo.com</a> or contact us at <a className={classes.link} href="mailto:[email protected]">[email protected]</a>.
</Alert></> : null}
{streamprocessingFeature?.supported !== false && <Grid container spacing={1} alignItems="flex-end">
<Grid item xs={6}>
<Button
variant="outlined"
color="default"
size="small"
className={classes.button}
startIcon={<AddIcon />}
onClick={(event) => {
event.stopPropagation();
onNewStream();
}}
>
New Stream
</Button>
</Grid>
<Grid item xs={6}>
<Box display="flex" flexDirection="row-reverse">
<Tooltip title="Reload streams">
<IconButton
color="secondary"
aria-label="Reload streams"
component="span"
onClick={(event) => {
event.stopPropagation();
onReload();
}}
>
<ReloadIcon />
</IconButton>
</Tooltip>
</Box>
</Grid>
</Grid>}
<br />
{streamprocessingFeature?.supported !== false && streams && streams.length > 0 ? (
<div>
<Hidden xsDown implementation="css">
<TableContainer component={Paper} className={classes.tableContainer}>
<Table size="medium">
<TableHead>
<TableRow>
{STREAM_TABLE_COLUMNS.map((column) => (
<TableCell
key={column.id}
sortDirection={sortBy === column.id ? sortDirection : false}
>
{/* <TableSortLabel
active={sortBy === column.id}
direction={sortDirection}
onClick={() => onSort(column.id)}
> */}
{column.key}
{/* </TableSortLabel> */}
</TableCell>
))}
<TableCell />
</TableRow>
</TableHead>
<TableBody>
{streams &&
streams.map((stream) => (
<StyledTableRow
hover
key={stream.streamname}
onClick={(event) => {
if (
event.target.nodeName?.toLowerCase() === 'td'
) {
onSelectStream(stream.streamname);
}
}}
>
<TableCell>{stream.streamname}</TableCell>
<TableCell>{stream.textdescription}</TableCell>
<TableCell>{stream.sourcetopic}</TableCell>
<TableCell>{stream.targettopic}</TableCell>
<TableCell>{stream.targetqos}</TableCell>
<TableCell>{stream.ttl}</TableCell>
{/* <TableCell>{stream.replaying ? "replaying" : "stopped"}</TableCell> */}
<TableCell>
<Tooltip title="Process stream">
<Switch
checked={
typeof stream.process === 'undefined' ||
stream.process === true
}
onClick={(event) => {
event.stopPropagation();
if (event.target.checked) {
onEnableProcessStream(stream.streamname);
} else {
onDisableProcessStream(stream.streamname);
}
}}
/>
</Tooltip>
</TableCell>
<TableCell>
<Tooltip title="Persist stream">
<Switch
checked={
typeof stream.persist === 'undefined' ||
stream.persist === true
}
onClick={(event) => {
event.stopPropagation();
if (event.target.checked) {
onEnablePersistStream(stream.streamname);
} else {
onDisablePersistStream(stream.streamname);
}
}}
/>
</Tooltip>
</TableCell>
<TableCell>
<Tooltip title="Activate / Deactivate stream">
<Switch
checked={
typeof stream.active === 'undefined' ||
stream.active === true
}
onClick={(event) => {
event.stopPropagation();
if (event.target.checked) {
onEnableStream(stream.streamname);
} else {
onDisableStream(stream.streamname);
}
}}
/>
</Tooltip>
</TableCell>
<TableCell align="right">
<Tooltip title="Clear stream messages">
<IconButton
disabled={!stream.persist}
size="small"
onClick={(event) => {
event.stopPropagation();
onClearStreamMessages(stream.streamname);
}}
>
<ClearStreamIcon fontSize="small" />
</IconButton>
</Tooltip>
<Tooltip title="Replay stream">
<IconButton
disabled={!stream.persist}
size="small"
onClick={(event) => {
event.stopPropagation();
onReplayStream(stream);
}}
>
<ReplayIcon fontSize="small" />
</IconButton>
</Tooltip>
<Tooltip title="Delete stream">
<IconButton
size="small"
onClick={(event) => {
event.stopPropagation();
onDeleteStream(stream.streamname);
}}
>
<DeleteIcon fontSize="small" />
</IconButton>
</Tooltip>
</TableCell>
</StyledTableRow>
))}
</TableBody>
</Table>
</TableContainer>
</Hidden>
<Hidden smUp implementation="css">
<Paper>
<List className={classes.root}>
{streams.map((stream) => (
<React.Fragment>
<ListItem
alignItems="flex-start"
onClick={(event) => onSelectStream(stream.streamname)}
>
<ListItemText
primary={<span>{stream.streamname}</span>}
secondary={
<React.Fragment>
<Typography
component="span"
variant="body2"
className={classes.inline}
color="textPrimary"
>
{stream.streamname}
</Typography>
</React.Fragment>
}
/>
<ListItemSecondaryAction>
<IconButton
edge="end"
size="small"
onClick={(event) => {
event.stopPropagation();
onSelectStream(stream.streamname);
}}
aria-label="edit"
>
<EditIcon fontSize="small" />
</IconButton>
<IconButton
edge="end"
size="small"
onClick={(event) => {
event.stopPropagation();
onDeleteStream(stream.streamname);
}}
aria-label="delete"
>
<DeleteIcon fontSize="small" />
</IconButton>
</ListItemSecondaryAction>
</ListItem>
<Divider />
</React.Fragment>
))}
</List>
</Paper>
</Hidden>
</div>
) : (
<div>No streams found</div>
)}
</div>
);
}
Example #26
Source File: Map.js From pwa with MIT License | 4 votes |
function Map() {
// FIXME you are using leaflet but you haven't imported it in this component because you have put it in index.html
// try to use react leaflet and help encapsulation components (and Separation of concerns)
const [chosenMap, setChosenMap] = useState(null);
const [map, setMap] = useState(null);
const [data, setData] = useState([]);
const [label, setLabel] = useState([]);
const [zoom, setZoom] = useState(0);
const [anchorEl, setAnchorEl] = useState(null);
const [isDataFetching, setIsDataFetching] = useState(false);
const [isDataProcessing, setisDataProcessing] = useState(false);
const [vpnAlert, setVpnAlert] = useState(true);
const {user, token} = useSelector((state) => state.MyActivities);
const {
isMapFetching,
isPrivateMapFetching,
mapList,
serverError,
} = useSelector((state) => state.Map);
const dispatch = useDispatch();
const drawPolygon = useCallback(
(color, polygons) => {
if (map && polygons) {
for (let polygon of polygons) {
let tooltip = null;
let width = null;
if (isNaN(polygon[polygon.length - 1][0])) {
tooltip = polygon[polygon.length - 1][0];
width = polygon[polygon.length - 1][1];
polygon = polygon.slice(0, polygon.length - 1);
}
window.L.polygon([polygon], {
fillColor: `#${(Number(color) % 0x1000000).toString(16)}`,
fill: true,
stroke: false,
fillOpacity: Number(color) / 0x1000000 / 255.0,
}).on('click', function (e) {
showTooltip(tooltip, width, e)
}).addTo(map);
}
}
},
[map]
);
var popup = map && window.L.popup();
function showTooltip(tooltip, width, e) {
if (tooltip !== null) {
let url = `${process.env.REACT_APP_MAP_IMAGE_CDN}${tooltip}`;
popup
.setLatLng(e.latlng)
.setContent("<div>" +
"<img style=\"max-width: 1000px; width: " + width + "px;\" alt=\"stats\" src=" + url + " /> </div>")
.openOn(map);
}
}
const clearPolygon = useCallback(() => {
if (map) {
d3.selectAll('.leaflet-interactive').remove();
}
}, [map]);
const clearLabel = useCallback(() => {
if (map) {
d3.selectAll('.leaflet-tooltip').remove();
}
}, [map]);
const getData = (url, result, cached = false) => {
setIsDataFetching(false);
if (!result) return undefined;
// Add to cache if map does not exist
!cached &&
db.set({
data: result,
fileName: url,
mapName: chosenMap.id,
});
setisDataProcessing(true);
const line = result;
const lineNumber = line.length;
let zzoom = null;
let polygons = [];
let sPolygons = [];
let labels = [];
for (let i = 0; i <= lineNumber; i++) {
if (i === lineNumber || line[i].length === 1) {
if (i > 0) {
let sameColor = {};
polygons.push(...sPolygons);
for (let j = 0; j < polygons.length; j++) {
let color = polygons[j][0];
let points = [];
for (let k = 1; k < polygons[j].length; k += 2)
points.push([polygons[j][k], polygons[j][k + 1]]);
if (color in sameColor)
sameColor[color].push(points);
else
sameColor[color] = [points];
}
setData((prevData) => [...prevData, [zzoom, sameColor]]);
setLabel((prevLabel) => [...prevLabel, [zzoom, labels]]);
polygons = [];
sPolygons = [];
labels = [];
}
if (i < lineNumber)
zzoom = Number(line[i][0]);
continue;
}
if (line[i][0] === 'P') {
polygons.push(line[i].slice(1));
}
if (line[i][0] === 'S') {
sPolygons.push(line[i].slice(1));
}
if (line[i][0] === 'L') {
labels.push({
text: line[i][1],
point: [line[i][2], line[i][3]],
size: line[i][4],
color: `#${(Number(line[i][5]) % 0x1000000).toString(16)}`,
opacity: Number(line[i][5]) / 0x1000000 / 255.0,
})
}
}
setisDataProcessing(false);
setData((prevData) => [...prevData]);
setLabel((prevData) => [...prevData]);
};
const parseFile = async (url, key) => {
setData([]);
setLabel([]);
setIsDataFetching(true);
const _cached = await db.get(url);
if (_cached.length) {
getData(url, _cached[0].data, true);
} else {
if (key) {
const response = await axios({
url,
method: 'GET',
responseType: 'blob',
});
const decrypted = decryptPrivateMap(response.data, key);
decrypted &&
Papa.parse(decrypted, {
complete: (result) => getData(url, result.data, false),
});
} else {
Papa.parse(url, {
download: true,
complete: (result) => getData(url, result.data, false),
});
}
}
};
const findZoomLevels = useCallback(() => {
const result = [];
data.map((element) => result.push(element[0]));
return result;
}, [data]);
const findZoom = useCallback(() => {
const inverseZoomLevel = 10 * Math.pow(2, -(map && map.getZoom()));
const zoomLevels = data && findZoomLevels();
for (let i = 0; i < zoomLevels.length - 1; i++) {
if (inverseZoomLevel <= zoomLevels[i]) {
setZoom(i);
break;
} else if (
inverseZoomLevel > zoomLevels[i] &&
inverseZoomLevel <= zoomLevels[i + 1]
) {
setZoom(i + 1);
break;
} else {
setZoom(zoomLevels.length - 1)
}
}
}, [map, data, findZoomLevels]);
useEffect(() => {
findZoom();
}, [findZoom, data]);
useEffect(() => {
map &&
map.on('zoom', function () {
findZoom();
});
});
const hasPrivateAccess = () => {
return (
user &&
user.permissions.filter((perm) => perm === 'webmap').length &&
user.permissions.some((perm) => {
return perm.includes('maps_');
})
);
};
useEffect(() => {
dispatch(fetchMaps());
hasPrivateAccess() && dispatch(fetchPrivateMaps(token));
setMap(
new window.L.Map('map', {
key: process.env.REACT_APP_MAP_TOKEN,
maptype: 'dreamy',
poi: true,
traffic: false,
zoomControl: false,
center: [32.4279, 53.688],
zoom: 4.2,
})
);
}, [dispatch]);
useEffect(() => {
mapList && setChosenMap(mapList[0]);
}, [mapList]);
useEffect(() => {
chosenMap &&
parseFile(
`${process.env.REACT_APP_MAP_CDN}${chosenMap.id}.${chosenMap.version}.csv`,
chosenMap.key
);
}, [chosenMap]);
useEffect(() => {
if (isDataProcessing)
return;
clearPolygon();
if (!((data || {})[zoom] || [])[1]) {
return;
}
console.log("drawpolygon")
for (let key in data[zoom][1]) {
if (Object.prototype.hasOwnProperty.call(data[zoom][1], key))
drawPolygon(key, data[zoom][1][key]);
}
}, [map, zoom, data, clearPolygon, drawPolygon]);
useEffect(() => {
if (isDataProcessing)
return;
clearLabel();
if (!((label || {})[zoom] || [])[1]) {
return;
}
// TODO clean this shit
let root = document.documentElement;
root.style.setProperty('--label-color', '#000000');
root.style.setProperty('--label-size', 10);
for (let entry of label[zoom][1]) {
window.L.marker(entry.point, {
opacity: 0,
}).bindTooltip(entry.text, {
permanent: true,
className: 'map-label',
direction: 'top',
}).addTo(map);
}
}, [map, label, zoom, clearLabel]);
const handleLocate = async () => {
const myLatLngLocation = await utility.getCurrentPosition();
map.flyTo(myLatLngLocation, 15);
};
const clickMenu = (event) => {
setAnchorEl(event.currentTarget);
};
const closeMenu = (value) => {
value && setChosenMap(value);
setAnchorEl(null);
};
const renderMenu = () => {
return (
<Menu
classes={{
paper: 'map-menu',
}}
anchorEl={anchorEl}
keepMounted
open={Boolean(anchorEl)}
onClose={() => closeMenu()}
>
{mapList &&
mapList.map((item) => {
return (
<MenuItem
key={item.id}
classes={{root: 'map-menu-item'}}
onClick={() => closeMenu(item)}
>
{item.name}
</MenuItem>
);
})}
</Menu>
);
};
return (
<div className={`contentWrapper MapWrapper`}>
<div className="alerts">
<Collapse
className="map-alert-wrapper"
in={isDataFetching || isMapFetching || isPrivateMapFetching}
addEndListener={null}
>
<Alert
severity="info"
action={
<IconButton
color="inherit"
size="small"
onClick={() => {
setIsDataFetching(false);
}}
>
<CloseIcon fontSize="inherit"/>
</IconButton>
}
>
تا دریافت اطلاعات منتظر بمانید.
</Alert>
</Collapse>
{serverError && (
<Collapse
className="map-alert-wrapper"
in={vpnAlert}
addEndListener={null}
>
<Alert
severity="warning"
action={
<IconButton
color="inherit"
size="small"
onClick={() => {
setVpnAlert(false);
}}
>
<CloseIcon fontSize="inherit"/>
</IconButton>
}
>
در صورت اتصال، vpn دستگاه را قطع کنید.
</Alert>
</Collapse>
)}
</div>
<div className="map-button-wrapper">
<button
type="button"
className="map-button"
onClick={() => handleLocate()}
>
<MyLocationIcon/>
</button>
<button
type="button"
name="chosenMap"
className="map-button type"
onClick={(e) => clickMenu(e)}
>
<div>{(chosenMap || {}).name}</div>
<ExpandMoreIcon/>
</button>
</div>
<div
id="map"
style={{
position: 'fixed',
top: 0,
right: 0,
width: '100vw',
height: '100vh',
zIndex: 0,
}}
/>
<div className="comment-wrapper">
<div className="map-comment">{(chosenMap || {}).comment || 'ــ'}</div>
</div>
<div className="logo-wrapper right">
<img src={logo} alt=""/>
</div>
<div className="logo-wrapper left">
<img src={neshanLogo} alt=""/>
</div>
{renderMenu()}
</div>
);
}
Example #27
Source File: index.js From News24x7-Client with MIT License | 4 votes |
render() {
const {
ui: { loading },
} = this.props;
const { dberrors } = this.state;
return (
<Formik
initialValues={{
email: "",
userName: "",
password: "",
passwordConfirmation: "",
}}
validate={validate(getValidationSchema)}
onSubmit={(values, { setSubmitting, setErrors }) => {
setTimeout(() => {
const newUserData = {
email: values.email,
password: values.password,
confirmPassword: values.passwordConfirmation,
handle: values.userName,
};
console.log("User has been sucessfully saved!", newUserData);
this.props.signupUser(newUserData, this.props.history);
setSubmitting(false);
}, 500);
}}
>
{({ touched, errors, handleChange, handleBlur, handleSubmit }) => (
<div className="SignUpContainer">
<div className="SignUpBox">
<div className="SignUpHeader">
<h1 className="SignUpHeading">SIGN UP</h1>
<div className="SignUpHeaderImg">
<img alt="monkey img"
src={
this.state.avatar
? this.state.avatarPassword
? defaultPicPassword
: defaultPicLook
: defaultPic
}
></img>
</div>
</div>
<Grid container spacing={2}>
<Grid item xs={12}>
{!loading
? (dberrors.email && (
<Alert
severity="error"
style={{ textTransform: "capitalize" }}
>
{dberrors.email}
</Alert>
)) ||
(dberrors.error && (
<Alert
severity="error"
style={{ textTransform: "capitalize" }}
>
{dberrors.error}
</Alert>
))
: null}
</Grid>
<Grid item xs={12}>
<TextField
error={errors.name && touched.name ? true : false}
fullWidth
helperText={errors.name && touched.name && errors.name}
id="userName"
label="Username"
name="userName"
className="SignUpUserName"
onBlur={handleBlur}
onChange={handleChange}
required
variant="outlined"
onClick={this.changeAvatar}
/>
</Grid>
<Grid item xs={12}>
<TextField
error={errors.email && touched.email ? true : false}
fullWidth
helperText={errors.email && touched.email && errors.email}
id="email"
label="Email"
name="email"
onBlur={handleBlur}
onChange={handleChange}
required
type="email"
variant="outlined"
onClick={this.changeAvatarOriginal}
/>
</Grid>
<Grid item xs={12}>
<TextField
error={errors.password && touched.password ? true : false}
fullWidth
helperText={
errors.password && touched.password && errors.password
}
id="password"
label="Password"
name="password"
onBlur={handleBlur}
onChange={handleChange}
required
type="password"
variant="outlined"
onClick={this.changeAvatarPassword}
/>
</Grid>
<Grid item xs={12}>
<TextField
error={
errors.passwordConfirmation &&
touched.passwordConfirmation
? true
: false
}
fullWidth
helperText={
errors.passwordConfirmation &&
touched.passwordConfirmation &&
errors.passwordConfirmation
}
id="passwordConfirmation"
label="Confirm Password"
name="passwordConfirmation"
onBlur={handleBlur}
onChange={handleChange}
required
type="password"
variant="outlined"
onClick={this.changeAvatarPassword}
/>
</Grid>
<div className="SignUpSubmit">
<button
type="submit"
onClick={handleSubmit}
style={{ margin: "5px" }}
disabled={loading}
>
Sign Up{" "}
{loading ? (
<CircularProgress size={17} thickness={6} />
) : null}
</button>
<div className="SignUpLink">
<Link to="/login">
Already have an Account ? Log In here
</Link>
</div>
</div>
</Grid>
</div>
</div>
)}
</Formik>
);
}
Example #28
Source File: ExternalApplicationDetails.jsx From Edlib with GNU General Public License v3.0 | 4 votes |
ExternalApplicationDetails = ({
applicationTokensFetchData,
onCreate,
createStatus,
token,
application,
onDeleteRequest,
}) => {
return (
<Container maxWidth={false}>
<Grid component={Box} container paddingY={2}>
<Grid item>
<Breadcrumbs aria-label="breadcrumb">
<Link to="/">Edlib admin</Link>
<Link to="/settings">Settings</Link>
<Link to="/settings/external-applications">
External applications
</Link>
<Typography color="textPrimary">
{application.name}
</Typography>
</Breadcrumbs>
</Grid>
</Grid>
<Grid container component={Box} paddingBottom={2}>
<Grid item md={12}>
<Typography variant="h2">{application.name}</Typography>
</Grid>
</Grid>
<Grid container>
<Grid item md={6}>
<Paper>
<Box padding={2}>
<strong>Application ID: </strong> {application.id}
</Box>
<Box padding={2}>
<Button
variant="contained"
color="primary"
onClick={() => onCreate()}
disabled={createStatus.loading}
>
Create new
</Button>
</Box>
{token && (
<Alert>Created new access token: {token}</Alert>
)}
<DefaultHookQuery
fetchData={applicationTokensFetchData}
>
{({ response: accessTokens }) => (
<Table>
<TableHead>
<TableRow>
<TableCell>Id</TableCell>
<TableCell>Name</TableCell>
<TableCell>Delete</TableCell>
</TableRow>
</TableHead>
<TableBody>
{accessTokens.map(({ id, name }) => (
<TableRow key={id}>
<TableCell width={260}>
{id}
</TableCell>
<TableCell>{name}</TableCell>
<TableCell>
<Button
startIcon={<Delete />}
color="error"
onClick={() =>
onDeleteRequest(id)
}
>
Delete
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</DefaultHookQuery>
</Paper>
</Grid>
</Grid>
</Container>
);
}
Example #29
Source File: withAuthWrapper.js From nextjs-todo-list with MIT License | 4 votes |
withAuthWrapper = (Component) => (props) => {
const [loading, setLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState('');
const { activateAuth } = useContext(AuthContext);
const firebase = useContext(FirebaseContext);
useEffect(() => {
redirectIfAuthenticated();
}, []);
if (errorMessage) {
setTimeout(() => {
setErrorMessage('');
}, 5000);
}
const saveAuthAndRedirect = (data) => {
try {
const { user } = data;
let { idToken = null } = data;
if (!idToken) idToken = user.uid;
activateAuth(user, idToken);
setLoading(false);
Router.push('/');
} catch (error) {
console.log({ error });
}
};
const onGoogleSignIn = async () => {
setLoading(true);
firebase
.doAuthWithGoogle()
.then((resp) => {
saveAuthAndRedirect(resp);
})
.catch((error) => {
const { message } = error;
setLoading(false);
setErrorMessage(message);
});
};
const onGithubSignIn = async () => {
setLoading(true);
await firebase
.doAuthWithGithub()
.then((resp) => saveAuthAndRedirect(resp))
.catch((error) => {
setLoading(false);
const { message } = error;
setErrorMessage(message);
});
};
return (
<MainLayout>
<div className="container">
<div className="main">
{errorMessage && (
<Alert severity="error">
<AlertTitle>Error</AlertTitle>
{errorMessage}
</Alert>
)}
<Component
{...props}
loading={loading}
onGoogleSignIn={onGoogleSignIn}
onGithubSignIn={onGithubSignIn}
/>
</div>
</div>
<style jsx>
{`
.container {
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
`}
</style>
</MainLayout>
);
}