@material-ui/core#fade JavaScript Examples
The following examples show how to use
@material-ui/core#fade.
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: WelcomeWindow.js From qasong with ISC License | 6 votes |
export default function TransitionsModal({ showAboutUs, setShowAboutUs }) {
const classes = useStyles();
// const handleOpen = () => {
// setOpen(true);
// };
const handleClose = () => {
setShowAboutUs(false);
};
return (
<Dialog
className={classes.modal}
open={showAboutUs}
onClose={handleClose}
PaperProps={{
classes: {
root: classes.paper,
},
}}
>
<Fade in={showAboutUs}>
<WelcomeWindowContent />
</Fade>
</Dialog>
);
}
Example #2
Source File: Publish.js From Edlib with GNU General Public License v3.0 | 6 votes |
Publish = ({ label, initialPublish = false }) => {
const { dispatch, state: { isPublished = initialPublish } } = useForm();
return (
<div className="publish-box">
<span>{label}</span>
<Fade in={!isPublished}>
<WarningIcon
htmlColor={'#fec63d'}
style={{ fontSize: 25 }}
/>
</Fade>
<Switch
checked={isPublished}
onToggle={() => {
dispatch({ type: FormActions.setPublish, payload: { published: !isPublished } });
}}
color={'tertiary'}
/>
</div>
);
}
Example #3
Source File: Modal.js From web-wallet with Apache License 2.0 | 6 votes |
function _Modal ({
children,
open,
onClose,
light
}) {
const classes = useStyles();
return (
<Modal
aria-labelledby='transition-modal-title'
aria-describedby='transition-modal-description'
className={classes.modal}
open={open}
onClose={onClose}
closeAfterTransition
BackdropComponent={Backdrop}
BackdropProps={{
timeout: 500
}}
>
<Fade in={open}>
<div
className={[
classes.paper,
light ? classes.light : ''
].join(' ')}
>
{children}
</div>
</Fade>
</Modal>
);
}
Example #4
Source File: index.js From AED-Map with MIT License | 6 votes |
ModalWrapper = ({ ButtonOpen, ModalContent }) => {
const classes = useStyles();
const [open, setOpen] = useState(false);
const handleOpen = event => {
event.preventDefault();
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
return (
<>
<ButtonOpen handleOpen={handleOpen} />
<Modal
className={classes.modal}
open={open}
onClose={handleClose}
closeAfterTransition
BackdropComponent={Backdrop}
BackdropProps={{
timeout: 500
}}
>
<Fade in={open}>
<div className={classes.paper}>
<ModalContent handleClose={handleClose} />
</div>
</Fade>
</Modal>
</>
);
}
Example #5
Source File: Agents.js From voicemail-for-amazon-connect with Apache License 2.0 | 5 votes |
render() {
let classes = this.props.classes;
if (this.props.role === "") {
return (
<div>
<NavigationBar/>
<p> The user you logged in with is not in the "Manager" Cognito User Pool group. You must be a member of this group to view this page.</p>
</div>
)
}
return (
<div>
<NavigationBar/>
<AgentsTable className={classes.agentsTable}/>
<Dialog
scroll="paper"
disableAutoFocus={true}
open={this.props.showGlobalSettingsModal}
closeAfterTransition
BackdropComponent={Backdrop}
onClose={() => {
this.props.showSettings(false)
}}>
<Fade in={this.props.showGlobalSettingsModal}>
<DialogContent>
<GlobalSettings/>
</DialogContent>
</Fade>
</Dialog>
<Dialog
scroll="paper"
disableAutoFocus={true}
open={this.props.showAgentSettings}
closeAfterTransition
BackdropComponent={Backdrop}
onClose={() => {
this.props.showAgentModal(false)
}}>
<Fade in={this.props.showAgentSettings}>
<DialogContent>
<AgentSettings/>
</DialogContent>
</Fade>
</Dialog>
<Dialog
scroll="paper"
disableAutoFocus={true}
open={this.props.showContactFlowModal}
closeAfterTransition
BackdropComponent={Backdrop}
onClose={() => {
this.props.showContactFlow(false)
}}>
<Fade in={this.props.showContactFlowModal}>
<DialogContent>
<ContactFlow/>
</DialogContent>
</Fade>
</Dialog>
</div>
)
}
Example #6
Source File: UserFeedback.js From qasong with ISC License | 5 votes |
export default function TransitionsModal({ showFeedback, setShowFeedback }) {
const [message, setMessage] = React.useState("");
const classes = useStyles();
const handleClose = () => {
setShowFeedback(false);
};
const handleChange = (e) => {
setMessage(e.target.value);
};
const handlePost = () => {
postUserFeedback(message);
alert("Thank you for the feedback!");
handleClose();
};
return (
<Dialog
open={showFeedback}
onClose={handleClose}
PaperProps={{
classes: {
root: classes.paper,
},
}}
>
<Fade in={showFeedback}>
<Box px={2} py={4}>
<Box pb={1}>
<Typography gutterBottom variant="h4" align="center">
Send Us Feedback
</Typography>
<Typography>
Suggest a feature, report a bug, or say anything else you want about qasong
</Typography>
</Box>
<Box pb={1}>
<TextField
id="outlined-multiline-static"
label="Feedback"
multiline
rows={4}
color="secondary"
variant="outlined"
fullWidth
onChange={handleChange}
/>
</Box>
<Box pb={1} align="right">
<Button variant="contained" color="secondary" onClick={handlePost}>
send
</Button>
</Box>
</Box>
</Fade>
</Dialog>
);
}
Example #7
Source File: index.js From yi-note with GNU General Public License v3.0 | 5 votes |
SupportExtension = () => {
const { t } = useTranslation('notesView');
const { open } = useStoreState(state => state.videoNotes.support);
const { setOpen } = useStoreActions(actions => actions.videoNotes.support);
const containerRef = useRef(null);
const [message, setMessage] = useState({});
useEffect(() => {
containerRef.current = document.getElementById(APP_ID);
}, []);
const clearState = () => {
setMessage({});
};
const handleClose = () => {
clearState();
setOpen(false);
};
return (
<StyledModal
container={containerRef.current}
open={open}
onClose={handleClose}
closeAfterTransition
BackdropComponent={Backdrop}
BackdropProps={{
timeout: 500
}}
>
<Fade in={open}>
<StyledPaper>
<Grid container direction="column" spacing={3}>
{message.status && (
<Grid item>
<Alert severity={message.status}>{message.message}</Alert>
</Grid>
)}
<Grid item container justify="center">
<Typography>{t('support.text')}</Typography>
</Grid>
<Grid item>
<Sponsor />
</Grid>
<Grid item>
<Star />
</Grid>
<Grid item>
<Share />
</Grid>
</Grid>
</StyledPaper>
</Fade>
</StyledModal>
);
}
Example #8
Source File: Skills.js From Portfolio with MIT License | 5 votes |
export default function Skills() {
const classes = useStyles()
const theme = useTheme()
const mdDown = useMediaQuery(theme.breakpoints.down('md'))
const align = mdDown ? "center" : "flex-end"
const textAlign = mdDown ? "center" : "right"
const animRef = useRef(null)
const animate = useAnimate(animRef)
return (
<Grid container justify="center" alignItems="center" spacing={10} className={classes.cont}>
<Grid item xs={12} lg={6} ref={animRef}>
<Typography variant="h2" gutterBottom align="center">
Skills
</Typography>
<Hidden mdDown>
<Fade in={animate} style={{ transitionDelay: '100ms' }}>
<div>
<Image
alt="Skills"
src="/skill.svg"
width="1139"
height="655"
/>
</div>
</Fade>
</Hidden>
</Grid>
<Grid container item xs={12} lg={6} direction="column" spacing={1} alignItems={align}>
{
Object.getOwnPropertyNames(wrappedSkills).map((title, id) =>
<Grid item key={id} className={classes.skobj}>
<Typography variant="h4" align={textAlign} gutterBottom component="p">
{title}
</Typography>
<Grid container item direction="row" spacing={1} justify="center">
{
wrappedSkills[title].map(({ alt, icon }, i) =>
<Grid item key={i}>
<Zoom in={animate} style={{ transitionDelay: `${150 * i}ms` }}>
<Tooltip title={alt.replace("_", " ")} placement="top">
<Avatar variant="rounded" className={clsx([classes.avatar, classes[alt]])}>
{icon}
</Avatar>
</Tooltip>
</Zoom>
</Grid>
)
}
</Grid>
</Grid>
)
}
</Grid>
</Grid>
)
}
Example #9
Source File: Landing.js From Portfolio with MIT License | 5 votes |
export default function Landing() {
const classes = useStyles();
const theme = useTheme();
const mdDown = useMediaQuery(theme.breakpoints.down('sm'));
return (
<Grid container justify="center" alignItems="center" className={classes.cont}>
<Grid item xs={12} lg={6}>
<Typography variant={mdDown ? "h2" : "h1"}>
{landing.title}
</Typography>
<Typography variant={mdDown ? "h5" : "h4"} component="h2" className={classes.subtitle}>
<ReactTyped
strings={landing.subtitles}
typeSpeed={40}
backSpeed={50}
loop
/>
</Typography>
<Grid container direction="row" spacing={2}>
{
professionalDetails.map(({ alt, icon, link }, i) =>
<Grid item key={i}>
<a href={link} target="_blank" rel="noopener noreferrer">
<Zoom in={true} style={{ transitionDelay: `${100 * i}ms` }}>
<Tooltip title={alt} placement="top">
<Avatar variant="rounded" className={clsx([classes.avatar, classes[alt]])}>
{icon}
</Avatar>
</Tooltip>
</Zoom>
</a>
</Grid>
)
}
</Grid>
</Grid>
<Hidden mdDown>
<Fade in={true} style={{ transitionDelay: '100ms' }}>
<Grid item lg={6}>
<Image
src="/landing.svg"
alt="Landing"
width="900.94"
height="787"
/>
</Grid>
</Fade>
</Hidden>
</Grid>
)
}
Example #10
Source File: Searchbar.js From dscbppimt-official-website with MIT License | 5 votes |
styles = theme => ({
search: {
position: 'relative',
borderRadius: theme.shape.borderRadius,
backgroundColor: fade(theme.palette.common.white,0.3),
'&:hover': {
backgroundColor: fade(theme.palette.common.white,1.5),
},
marginRight: theme.spacing(2),
marginLeft: 0,
width: '100%',
[theme.breakpoints.up('sm')]: {
marginLeft: theme.spacing(3),
width: 'auto',
},
},
searchIcon: {
padding: theme.spacing(0, 2),
height: '100%',
position: 'absolute',
pointerEvents: 'none',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
inputRoot: {
color: 'inherit',
},
inputInput: {
padding: theme.spacing(1, 1, 1, 0),
// vertical padding + font size from searchIcon
paddingLeft: `calc(1em + ${theme.spacing(4)}px)`,
transition: theme.transitions.create('width'),
width: '100%',
[theme.breakpoints.up('md')]: {
width: '20ch',
},
},
grow: {
flexGrow: 1,
},
})
Example #11
Source File: Settings.js From qasong with ISC License | 4 votes |
export default function TransitionsModal({
showSettings,
setShowSettings,
darkMode,
setDarkMode,
playbackRate,
setPlaybackRate,
}) {
const classes = useStyles();
const handleClose = () => {
setShowSettings(false);
};
function handleDarkmodeButtonClick() {
setDarkMode(!darkMode);
}
function handleChangePlaybackRate(e) {
setPlaybackRate(e.target.value);
}
// function handleChangeLanguage(e){
// console.log(e)
// setSelectedLanguage(e.target.value)
// }
return (
<Dialog
className={classes.modal}
open={showSettings}
onClose={handleClose}
PaperProps={{
classes: {
root: classes.paper,
},
}}
>
<Fade in={showSettings}>
<>
<Typography gutterBottom variant="h4" align="center">
Settings
</Typography>
<Grid>
<Grid>
{/* dark mode */}
<FormControlLabel
control={
<Switch onChange={handleDarkmodeButtonClick} checked={darkMode} />
}
label="Dark Mode"
labelPlacement="start"
/>
</Grid>
<Grid>
<FormControlLabel
label="Playback Speed"
labelPlacement="start"
control={
<Select
className={classes.select}
defaultValue={1}
value={playbackRate}
onChange={handleChangePlaybackRate}
>
<MenuItem value={0.25}>0.25</MenuItem>
<MenuItem value={0.5}>0.50</MenuItem>
<MenuItem value={0.75}>0.75</MenuItem>
<MenuItem value={1}>normal</MenuItem>
<MenuItem value={1.25}>1.25</MenuItem>
<MenuItem value={1.5}>1.5</MenuItem>
<MenuItem value={1.75}>1.75</MenuItem>
<MenuItem value={2}>2</MenuItem>
</Select>
}
/>
</Grid>
<Grid>
{/* <FormControlLabel
label="Language"
labelPlacement="start"
control={
<Select
className={classes.select}
defaultValue="en"
value={selectedLanguage}
onChange={handleChangeLanguage}
>
<MenuItem value="en">english</MenuItem>
<MenuItem value="ro">romanian</MenuItem>
</Select>
}
/> */}
</Grid>
</Grid>
</>
</Fade>
</Dialog>
);
}
Example #12
Source File: BlockUser.js From medha-STPC with GNU Affero General Public License v3.0 | 4 votes |
BlockUser = props => {
const [open, setOpen] = React.useState(false);
const [formState, setFormState] = useState({
isDataBlockUnblock: false,
isValid: false,
stateCounter: 0,
values: {}
});
const handleCloseModal = (message = "") => {
setOpen(false);
/** This event handles the scenario when the pop up is closed just by clicking outside the popup
to ensure that only string value is passed to message variable */
if (typeof message !== "string") {
message = "";
}
setFormState(formState => ({
...formState,
values: {},
isDataBlockUnblock: false,
isValid: false,
stateCounter: 0
}));
if (formState.isDataBlockUnblock) {
props.closeModal(true, message);
} else {
props.closeModal(false, message);
}
};
const handleSubmit = event => {
setOpen(true);
/** CALL Put FUNCTION */
blockUser();
props.clearSelectedRow(true);
event.preventDefault();
};
const blockUser = () => {
var body;
if (props.isUnBlocked || props.isMultiUnblock) {
body = {
blocked: false
};
}
if (props.isBlocked || props.isMulBlocked) {
body = {
blocked: true
};
}
if (props.isMulBlocked || props.isMultiUnblock) {
let MultiBlockUnblockUrl;
if (props.isMulBlocked) {
MultiBlockUnblockUrl = USER_URL + strapiConstants.STRAPI_BLOCK_URL;
} else if (props.isMultiUnblock) {
MultiBlockUnblockUrl = USER_URL + strapiConstants.STRAPI_UNBLOCK_URL;
}
let MultiBlockUnblockId = {
ids: props.id
};
serviceProviders
.serviceProviderForPostRequest(
MultiBlockUnblockUrl,
MultiBlockUnblockId
)
.then(res => {
setFormState(formState => ({
...formState,
isValid: true
}));
formState.isDataBlockUnblock = true;
if (props.isMultiUnblock) {
handleCloseModal("Users has been unblocked");
} else {
handleCloseModal("Users has been blocked");
}
})
.catch(error => {
console.log("error");
formState.isDataBlockUnblock = false;
if (props.isMultiUnblock) {
handleCloseModal("Error unblocking selected Users");
} else {
handleCloseModal("Error blocking selected Users");
}
});
} else {
let BLOCK_URL;
if (props.dataToBlockUnblock.isUserBlock === true) {
BLOCK_URL = USER_URL + strapiConstants.STRAPI_BLOCK_URL;
} else if (props.dataToBlockUnblock.isUserBlock === false) {
BLOCK_URL = USER_URL + strapiConstants.STRAPI_UNBLOCK_URL;
}
let BLOCKUNBLOCKID = {
ids: parseInt(props.id)
};
serviceProviders
.serviceProviderForPostRequest(BLOCK_URL, BLOCKUNBLOCKID)
.then(res => {
formState.isDataBlockUnblock = true;
if (props.dataToBlockUnblock["isUserBlock"]) {
handleCloseModal(
"User " + props.dataToBlockUnblock["name"] + " has been blocked"
);
} else {
handleCloseModal(
"User " + props.dataToBlockUnblock["name"] + " has been unblocked"
);
}
})
.catch(error => {
console.log("error", error);
formState.isDataBlockUnblock = false;
handleCloseModal("user unblock successfully");
});
}
};
const handleBlock = async event => {
props.clearSelectedRow(true);
props.closeModal();
};
const classes = useStyles();
return (
<Modal
aria-labelledby="transition-modal-title"
aria-describedby="transition-modal-description"
className={classes.modal}
open={props.getModel}
onClose={handleCloseModal}
closeAfterTransition
BackdropComponent={Backdrop}
BackdropProps={{
timeout: 500
}}
>
<Fade in={props.getModel}>
<div className={classes.paper}>
<div className={classes.blockpanel}>
<Typography variant={"h2"} className={classes.textMargin}>
{props.isUnBlocked || props.isMultiUnblock ? "Unblock" : null}
{props.isBlocked || props.isMulBlocked ? "Block" : null}
</Typography>
<div className={classes.crossbtn}>
<IconButton
aria-label="close"
className={classes.closeButton}
onClick={props.modalClose}
>
<CloseIcon />
</IconButton>
</div>
</div>
<div className={classes.edit_dialog}>
<Grid item xs={12}>
<Grid
container
spacing={2}
alignItems="center"
justifyContent="center"
>
<Grid item lg className={classes.deletemessage}>
{props.isUnBlocked
? "Are you sure you want to unblock user " +
props.dataToBlockUserName
: null}
{props.isMultiUnblock
? "Are you sure you want to unblock the selected users "
: null}
{props.isBlocked
? "Are you sure you want to block user " +
props.dataToBlockUserName
: null}
{props.isMulBlocked
? "Are you sure you want to block the selected users "
: null}
</Grid>
</Grid>
</Grid>
<Grid item xs={12}>
<Grid
container
direction="row"
justify="flex-end"
alignItems="center"
spacing={2}
>
<Grid item>
<YellowButton
type="submit"
color="primary"
variant="contained"
onClick={handleSubmit}
>
OK
</YellowButton>
</Grid>
<Grid item>
<GrayButton
type="submit"
color="primary"
variant="contained"
onClick={handleBlock}
>
Close
</GrayButton>
</Grid>
</Grid>
</Grid>
</div>
<Backdrop className={classes.backdrop} open={open}>
<CircularProgress color="inherit" />
</Backdrop>
</div>
</Fade>
</Modal>
);
}
Example #13
Source File: MarkAttaindance.js From medha-STPC with GNU Affero General Public License v3.0 | 4 votes |
MarkAttaindance = props => {
const [open, setOpen] = React.useState(false);
const [formState, setFormState] = useState({
isAttaindanceMarked: false,
isValid: false,
stateCounter: 0,
values: {}
});
const handleCloseModal = () => {
setOpen(false);
setFormState(formState => ({
...formState,
values: {},
isAttaindanceMarked: false,
isValid: false,
stateCounter: 0
}));
if (formState.isAttaindanceMarked) {
props.closeAttaindanceModal(true);
} else {
props.closeAttaindanceModal(false);
}
};
const handleSubmit = event => {
setOpen(true);
/** CALL Put FUNCTION */
attaindanceHandler();
event.preventDefault();
};
const attaindanceHandler = () => {
var body;
if (props.isPresent) {
body = {
is_attendance_verified: true
};
}
if (props.isAbsent) {
body = {
is_attendance_verified: false
};
}
serviceProviders
.serviceProviderForPutRequest(REGISTRATION_URL, props.id, body)
.then(res => {
formState.isAttaindanceMarked = true;
handleCloseModal();
})
.catch(error => {
console.log("error---", error);
formState.isAttaindanceMarked = false;
handleCloseModal();
});
};
const classes = useStyles();
return (
<Modal
aria-labelledby="transition-modal-title"
aria-describedby="transition-modal-description"
className={classes.modal}
open={props.showModal}
onClose={handleCloseModal}
closeAfterTransition
BackdropComponent={Backdrop}
BackdropProps={{
timeout: 500
}}
>
<Fade in={props.showModal}>
<div className={classes.paper}>
<div className={classes.blockpanel}>
<Typography variant={"h2"} className={classes.textMargin}>
{props.isPresent
? genericConstants.ADD_ATT_BUTTON_TEXT
: genericConstants.REMOVE_ATT_BUTTON_TEXT}
</Typography>
<div className={classes.crossbtn}>
<IconButton
aria-label="close"
className={classes.closeButton}
onClick={props.modalClose}
>
<CloseIcon />
</IconButton>
</div>
</div>
<div className={classes.edit_dialog}>
<Grid item xs={12}>
<Grid container spacing={2} alignItems="center">
<Grid item lg className={classes.deletemessage}>
{props.isPresent ? (
<p>
Are you sure you want to add attendence for{" "}
{props.studentName}?
</p>
) : (
<p>
Are you sure you want to remove attendence for{" "}
{props.studentName}?
</p>
)}
</Grid>
</Grid>
</Grid>
<Grid item xs={12}>
<Grid
container
direction="row"
justify="flex-end"
alignItems="center"
spacing={2}
>
<Grid item>
<YellowButton
type="submit"
color="primary"
variant="contained"
onClick={handleSubmit}
>
Ok
</YellowButton>
</Grid>
<Grid item>
<GrayButton
type="submit"
color="primary"
variant="contained"
onClick={props.modalClose}
>
Close
</GrayButton>
</Grid>
</Grid>
</Grid>
</div>
<Backdrop className={classes.backdrop} open={open}>
<CircularProgress color="inherit" />
</Backdrop>
</div>
</Fade>
</Modal>
);
}
Example #14
Source File: HireStudent.js From medha-STPC with GNU Affero General Public License v3.0 | 4 votes |
HireStudent = props => {
const [open, setOpen] = React.useState(false);
const [formState, setFormState] = useState({
isStudentHired: false,
isValid: false,
stateCounter: 0,
values: {}
});
const handleCloseModal = () => {
setOpen(false);
setFormState(formState => ({
...formState,
values: {},
isStudentHired: false,
isValid: false,
stateCounter: 0
}));
if (formState.isStudentHired) {
props.closeHireModal(true);
} else {
props.closeHireModal(false);
}
};
const handleSubmit = event => {
setOpen(true);
/** CALL Put FUNCTION */
studentHired();
event.preventDefault();
};
const studentHired = () => {
var body;
if (props.isHired) {
body = {
is_hired_at_event: true
};
}
if (props.isUnHired) {
body = {
is_hired_at_event: false
};
}
serviceProviders
.serviceProviderForPutRequest(REGISTRATION_URL, props.id, body)
.then(res => {
formState.isStudentHired = true;
handleCloseModal();
})
.catch(error => {
console.log("error---", error);
formState.isStudentHired = false;
handleCloseModal();
});
};
const classes = useStyles();
return (
<Modal
aria-labelledby="transition-modal-title"
aria-describedby="transition-modal-description"
className={classes.modal}
open={props.showModal}
onClose={handleCloseModal}
closeAfterTransition
BackdropComponent={Backdrop}
BackdropProps={{
timeout: 500
}}
>
<Fade in={props.showModal}>
<div className={classes.paper}>
<div className={classes.blockpanel}>
<Typography variant={"h2"} className={classes.textMargin}>
{props.isHired
? genericConstants.HIRE_BUTTON_TEXT
: genericConstants.DEHIRE_BUTTON_TEXT}
</Typography>
<div className={classes.crossbtn}>
<IconButton
aria-label="close"
className={classes.closeButton}
onClick={props.modalClose}
>
<CloseIcon />
</IconButton>
</div>
</div>
<div className={classes.edit_dialog}>
<Grid item xs={12}>
<Grid container spacing={2} alignItems="center">
<Grid item lg className={classes.deletemessage}>
{props.isHired ? (
<p>Are you sure you want to Hire {props.studentName}?</p>
) : (
<p>Are you sure you want to Dehire {props.studentName}?</p>
)}
</Grid>
</Grid>
</Grid>
<Grid item xs={12}>
<Grid
container
direction="row"
justify="flex-end"
alignItems="center"
spacing={2}
>
<Grid item>
<YellowButton
type="submit"
color="primary"
variant="contained"
onClick={handleSubmit}
>
Ok
</YellowButton>
</Grid>
<Grid item>
<GrayButton
type="submit"
color="primary"
variant="contained"
onClick={props.modalClose}
>
Close
</GrayButton>
</Grid>
</Grid>
</Grid>
</div>
<Backdrop className={classes.backdrop} open={open}>
<CircularProgress color="inherit" />
</Backdrop>
</div>
</Fade>
</Modal>
);
}
Example #15
Source File: DeleteEvent.js From medha-STPC with GNU Affero General Public License v3.0 | 4 votes |
DeleteUser = props => {
const { setLoaderStatus } = useContext(LoaderContext);
const [formState, setFormState] = useState({
isDeleteData: false,
isValid: false,
stateCounter: 0,
values: {},
dataToDelete: {}
});
if (props.showModal && !formState.stateCounter) {
formState.stateCounter = 0;
formState.values[EVENT_ID] = props.id;
formState.isDeleteData = false;
formState.dataToDelete = props.dataToDelete;
}
const handleCloseModal = (message = "") => {
/** This event handles the scenario when the pop up is closed just by clicking outside the popup
to ensure that only string value is passed to message variable */
if (typeof message !== "string") {
message = "";
}
setFormState(formState => ({
...formState,
values: {},
isDeleteData: false,
isValid: false,
stateCounter: 0
}));
if (formState.isDeleteData) {
props.closeModal(true, message);
} else {
props.closeModal(false, message);
}
};
const handleSubmit = event => {
/** CALL Put FUNCTION */
setLoaderStatus(true);
props.clearSelectedRow(true);
deleteData();
event.preventDefault();
};
const deleteData = () => {
if (props.isMultiDelete) {
serviceProviders
.serviceProviderForAllDeleteRequest(EVENT_URL, props.id)
.then(res => {
setLoaderStatus(false);
setFormState(formState => ({
...formState,
isValid: true
}));
formState.isDeleteData = true;
handleCloseModal("Events has been deleted successfully");
})
.catch(error => {
setLoaderStatus(false);
console.log("error", error);
formState.isDeleteData = false;
handleCloseModal(
"An error has occured while deleting events. Kindly, try again"
);
});
} else {
serviceProviders
.serviceProviderForDeleteRequest(EVENT_URL, props.id)
.then(res => {
setLoaderStatus(false);
setFormState(formState => ({
...formState,
isValid: true
}));
formState.isDeleteData = true;
handleCloseModal(
"Event " +
formState.dataToDelete["name"] +
" has been deleted successfully"
);
})
.catch(error => {
setLoaderStatus(false);
console.log("error");
formState.isDeleteData = false;
handleCloseModal(
"An error has occured while deleting event" +
formState.dataToDelete["name"] +
". Kindly, try again"
);
});
}
};
const handleClose = async event => {
props.clearSelectedRow(true);
props.closeModal();
};
const classes = useStyles();
return (
<Modal
aria-labelledby="transition-modal-title"
aria-describedby="transition-modal-description"
className={classes.modal}
open={props.showModal}
onClose={handleCloseModal}
closeAfterTransition
BackdropComponent={Backdrop}
BackdropProps={{
timeout: 500
}}
>
<Fade in={props.showModal}>
<div className={classes.paper}>
<div className={classes.blockpanel}>
<Typography variant={"h2"} className={classes.textMargin}>
{genericConstants.DELETE_TEXT}
</Typography>
<div className={classes.crossbtn}>
<IconButton
aria-label="close"
className={classes.closeButton}
onClick={props.modalClose}
>
<CloseIcon />
</IconButton>
</div>
</div>
<div className={classes.edit_dialog}>
<Grid item xs={12}>
<Grid container spacing={2} alignItems="center">
<Grid item lg className={classes.deletemessage}>
{props.id ? (
props.isMultiDelete ? (
<p>
Are you sure you want to delete "{props.seletedUser}"
Events?
</p>
) : (
<p>
Are you sure you want to delete event "
{props.dataToDelete["name"]}"?
</p>
)
) : null}
</Grid>
</Grid>
</Grid>
<Grid item xs={12}>
<Grid
container
direction="row"
justify="flex-end"
alignItems="center"
spacing={2}
>
<Grid item>
<YellowButton
type="submit"
color="primary"
variant="contained"
onClick={handleSubmit}
>
Ok
</YellowButton>
</Grid>
<Grid item>
<GrayButton
type="submit"
color="primary"
variant="contained"
onClick={handleClose}
>
Close
</GrayButton>
</Grid>
</Grid>
</Grid>
</div>
</div>
</Fade>
</Modal>
);
}
Example #16
Source File: DeleteCollege.js From medha-STPC with GNU Affero General Public License v3.0 | 4 votes |
DeleteZone = props => {
const [open, setOpen] = React.useState(false);
const [formState, setFormState] = useState({
isDeleteData: false,
isValid: false,
stateCounter: 0,
values: {},
dataToDelete: {}
});
if (props.showModal && !formState.stateCounter) {
formState.stateCounter = 0;
formState.values[COLLEGE_ID] = props.id;
formState.isDeleteData = false;
formState.dataToDelete = props.dataToDelete;
}
const handleCloseModal = (message = "") => {
/** This event handles the scenario when the pop up is closed just by clicking outside the popup
to ensure that only string value is passed to message variable */
if (typeof message !== "string") {
message = "";
}
setFormState(formState => ({
...formState,
values: {},
isDeleteData: false,
isValid: false,
stateCounter: 0
}));
if (formState.isDeleteData) {
props.closeModal(true, message);
} else {
props.closeModal(false, message);
}
};
const handleSubmit = async event => {
/** CALL Put FUNCTION */
setOpen(true);
event.preventDefault();
event.persist();
props.clearSelectedRow(true);
let status = {};
/** Calls checkIfStateCanBeDelete function to check whether the state can be deleted
and returns back an opbject with status and message*/
if (props.isMultiDelete) {
status = await checkIfMultiCollegeCanBeDelete();
} else {
status = await checkIfCollegeCanBeDelete(
formState.dataToDelete.organizationId
);
}
setOpen(false);
if (status["status"]) {
deleteData();
} else {
formState.isDeleteData = false;
handleCloseModal(
status["message"]
); /** returns back a message saying state cannot be deleted */
}
};
const handleClose = async event => {
props.clearSelectedRow(true);
props.closeModal();
};
const checkIfMultiCollegeCanBeDelete = async () => {
let dataToSent = {};
let isErrorCounter = 0;
for (let i in props.MultiOrganizationId) {
let status = await checkIfCollegeCanBeDelete(
props.MultiOrganizationId[i]
);
if (!status["status"]) {
isErrorCounter += 1;
break;
}
}
if (isErrorCounter > 0) {
dataToSent = {
status: false,
message: "Error deleting selected Colleges"
};
} else {
dataToSent = { status: true, message: "Success" };
}
return dataToSent;
};
/** This checks if the state can be deleted and returns back an array with status and message*/
const checkIfCollegeCanBeDelete = async id => {
let dataToReturn = {};
let studentsCheckUrl =
strapiConstants.STRAPI_DB_URL +
strapiConstants.STRAPI_COLLEGES +
"/" +
id +
"/" +
strapiConstants.STRAPI_STUDENT;
await serviceProviders
.serviceProviderForGetRequest(studentsCheckUrl)
.then(res => {
if (res.data.result.length > 0) {
dataToReturn = {
status: false,
message:
"Cannot delete College " +
formState.dataToDelete["name"] +
" as it is linked to other Students"
};
} else {
dataToReturn = {
status: true,
message: "Success"
};
}
})
.catch(error => {
console.log("error", error);
/** return error */
dataToReturn = {
status: false,
message: "Error deleting College " + formState.dataToDelete["name"]
};
});
return dataToReturn;
};
const deleteData = () => {
if (props.isMultiDelete) {
let deleteId = {
ids: props.id
};
serviceProviders
.serviceProviderForPostRequest(COLLEGE_URL, deleteId)
.then(res => {
setFormState(formState => ({
...formState,
isValid: true
}));
formState.isDeleteData = true;
handleCloseModal("Colleges have been deleted successfully");
})
.catch(error => {
console.log("error");
formState.isDeleteData = false;
handleCloseModal(
"An error has occured while deleting colleges. Kindly, try again"
);
});
} else {
let idArray = [];
idArray.push(parseInt(props.id));
let deleteId = {
ids: idArray
};
serviceProviders
.serviceProviderForPostRequest(COLLEGE_URL, deleteId)
.then(res => {
setFormState(formState => ({
...formState,
isValid: true
}));
formState.isDeleteData = true;
handleCloseModal(
"College " +
formState.dataToDelete["name"] +
" has been deleted successfully"
);
})
.catch(error => {
console.log("error", error);
formState.isDeleteData = false;
handleCloseModal(
"An error has occured while deleting college" +
formState.dataToDelete["name"] +
". Kindly, try again"
);
});
}
};
const classes = useStyles();
return (
<Modal
aria-labelledby="transition-modal-title"
aria-describedby="transition-modal-description"
className={classes.modal}
open={props.showModal}
onClose={handleCloseModal}
closeAfterTransition
BackdropComponent={Backdrop}
BackdropProps={{
timeout: 500
}}
>
<Fade in={props.showModal}>
<div className={classes.paper}>
<div className={classes.blockpanel}>
<Typography variant={"h2"} className={classes.textMargin}>
{genericConstants.DELETE_TEXT}
</Typography>
<div className={classes.crossbtn}>
<IconButton
aria-label="close"
className={classes.closeButton}
onClick={props.modalClose}
>
<CloseIcon />
</IconButton>
</div>
</div>
<div className={classes.edit_dialog}>
<Grid item xs={12}>
<Grid container spacing={2} alignItems="center">
<Grid item lg className={classes.deletemessage}>
{props.isMultiDelete
? "Are you sure you want to delete the selected Colleges?"
: "Are you sure you want to delete College " +
formState.dataToDelete["name"] +
"?"}
</Grid>
</Grid>
</Grid>
<Grid item xs={12}>
<Grid
container
direction="row"
justify="flex-end"
alignItems="center"
spacing={2}
>
<Grid item>
<YellowButton
type="submit"
color="primary"
variant="contained"
onClick={handleSubmit}
>
Ok
</YellowButton>
</Grid>
<Grid item>
<GrayButton
type="submit"
color="primary"
variant="contained"
onClick={handleClose}
>
Close
</GrayButton>
</Grid>
</Grid>
</Grid>
</div>
<Backdrop className={classes.backdrop} open={open}>
<CircularProgress color="inherit" />
</Backdrop>
</div>
</Fade>
</Modal>
);
}
Example #17
Source File: BlockUnblockCollege.js From medha-STPC with GNU Affero General Public License v3.0 | 4 votes |
BlockUnblockCollege = props => {
const [open, setOpen] = React.useState(false);
const [formState, setFormState] = useState({
isDataBlockUnblock: false,
isValid: false,
stateCounter: 0
});
/** Part for editing college */
if (props.showModal && !formState.stateCounter) {
formState.stateCounter = 0;
formState.isDataBlockUnblock = false;
}
const handleCloseModal = (message = "") => {
setOpen(false);
/** This event handles the scenario when the pop up is closed just by clicking outside the popup
to ensure that only string value is passed to message variable */
if (typeof message !== "string") {
message = "";
}
setFormState(formState => ({
...formState,
values: {},
isDataBlockUnblock: false,
isValid: false,
stateCounter: 0
}));
if (formState.isDataBlockUnblock) {
props.closeModal(true, message);
} else {
props.closeModal(false, message);
}
};
const handleSubmit = async event => {
/** CALL Put FUNCTION */
setOpen(true);
event.preventDefault();
event.persist();
props.clearSelectedRow(true);
/** Calls checkIfStateCanBeDelete function to check whether the state can be deleted
and returns back an opbject with status and message*/
blockUnblockData();
};
const blockUnblockData = () => {
if (props.isMultiBlock || props.isMultiUnblock) {
let COLLEGE_URL = "";
if (props.isMultiUnblock) {
COLLEGE_URL = COLLEGE_UNBLOCK_URL;
} else {
COLLEGE_URL = COLLEGE_BLOCK_URL;
}
let postData = {
ids: props.multiBlockCollegeIds
};
serviceProviders
.serviceProviderForPostRequest(COLLEGE_URL, postData)
.then(res => {
setFormState(formState => ({
...formState,
isValid: true
}));
formState.isDataBlockUnblock = true;
if (props.isMultiUnblock) {
handleCloseModal("Colleges have been unblocked successfully");
} else {
handleCloseModal("Colleges have been blocked successfully");
}
})
.catch(error => {
console.log("error");
formState.isDataBlockUnblock = false;
if (props.isMultiUnblock) {
handleCloseModal(
"An error has occured while unblocking colleges. Kindly, try again."
);
} else {
handleCloseModal(
"An error has occured while blocking colleges. Kindly, try again."
);
}
});
} else {
if (props.dataToBlockUnblock["is_blocked"]) {
let ids = [];
ids.push(props.dataToBlockUnblock["id"]);
let postData = {
ids: ids
};
serviceProviders
.serviceProviderForPostRequest(COLLEGE_UNBLOCK_URL, postData)
.then(res => {
setFormState(formState => ({
...formState,
isValid: true
}));
formState.isDataBlockUnblock = true;
handleCloseModal(
"College " +
props.dataToBlockUnblock["name"] +
" has been unblocked."
);
})
.catch(error => {
console.log("error");
formState.isDataBlockUnblock = false;
handleCloseModal(
"An error has occured while unblocking college" +
props.dataToBlockUnblock["name"] +
". Kindly, try again."
);
});
} else {
let ids = [];
ids.push(props.dataToBlockUnblock["id"]);
let postData = {
ids: ids
};
serviceProviders
.serviceProviderForPostRequest(COLLEGE_BLOCK_URL, postData)
.then(res => {
setFormState(formState => ({
...formState,
isValid: true
}));
formState.isDataBlockUnblock = true;
handleCloseModal(
"College " +
props.dataToBlockUnblock["name"] +
" has been blocked."
);
})
.catch(error => {
console.log("error");
formState.isDataBlockUnblock = false;
handleCloseModal(
"An error has occured while blocking college" +
props.dataToBlockUnblock["name"] +
". Kindly, try again."
);
});
}
}
};
const handleBlock = async event => {
props.clearSelectedRow(true);
props.closeModal();
};
const classes = useStyles();
return (
<React.Fragment>
{!formUtilities.checkEmpty(props.dataToBlockUnblock) ||
props.multiBlockCollegeIds.length ? (
<Modal
aria-labelledby="transition-modal-title"
aria-describedby="transition-modal-description"
className={classes.modal}
open={props.showModal}
onClose={handleCloseModal}
closeAfterTransition
BackdropComponent={Backdrop}
BackdropProps={{
timeout: 500
}}
>
<Fade in={props.showModal}>
<div className={classes.paper}>
<div className={classes.blockpanel}>
<Typography variant={"h2"} className={classes.textMargin}>
{props.isMultiBlock || props.isMultiUnblock
? props.isMultiBlock
? genericConstants.BLOCK_BUTTON_TEXT
: genericConstants.UNBLOCK_BUTTON_TEXT
: null}
{!props.isMultiBlock && !props.isMultiUnblock
? props.dataToBlockUnblock["is_blocked"]
? genericConstants.UNBLOCK_BUTTON_TEXT
: genericConstants.BLOCK_BUTTON_TEXT
: null}
</Typography>
<div className={classes.crossbtn}>
<IconButton
aria-label="close"
className={classes.closeButton}
onClick={props.modalClose}
>
<CloseIcon />
</IconButton>
</div>
</div>
<div className={classes.edit_dialog}>
<Grid item xs={12}>
<Grid container spacing={2} alignItems="center">
<Grid item lg className={classes.deletemessage}>
{props.isMultiBlock || props.isMultiUnblock
? props.isMultiBlock
? "Are you sure you want to block all selected colleges"
: "Are you sure you want to unblock all selected colleges"
: null}
{!props.isMultiBlock && !props.isMultiUnblock
? props.dataToBlockUnblock["is_blocked"]
? "Are you sure you want to unblock college " +
props.dataToBlockUnblock["name"]
: "Are you sure you want to block college " +
props.dataToBlockUnblock["name"]
: null}
</Grid>
</Grid>
</Grid>
<Grid item xs={12}>
<Grid
container
direction="row"
justify="flex-end"
alignItems="center"
spacing={2}
>
<Grid item>
<YellowButton
type="submit"
color="primary"
variant="contained"
onClick={handleSubmit}
>
OK
</YellowButton>
</Grid>
<Grid item>
<GrayButton
type="submit"
color="primary"
variant="contained"
onClick={handleBlock}
>
Close
</GrayButton>
</Grid>
</Grid>
</Grid>
</div>
<Backdrop className={classes.backdrop} open={open}>
<CircularProgress color="inherit" />
</Backdrop>
</div>
</Fade>
</Modal>
) : null}
</React.Fragment>
);
}
Example #18
Source File: index.js From Recess with MIT License | 4 votes |
function LikePanel({ postId, user }) {
const classes = useStyles();
const [like, setLike] = useState(false);
const [usersLiked, setUsersLiked] = useState([]);
const [likeCounter, setLikeCounter] = useState(0);
const [likeModal, setLikeModal] = useState(false);
const onLike = (e) => {
e.preventDefault();
if (user) {
db.collection("posts")
.doc(postId)
.collection("likes")
.doc(user.uid)
.set({
username: user.displayName,
photoURL: user.photoURL,
})
.then(() => {
setLike(true);
setLikeCounter(likeCounter + 1);
})
.catch((err) => console.log(err));
}
};
const onDislike = (e) => {
e.preventDefault();
if (user) {
db.collection("posts")
.doc(postId)
.collection("likes")
.doc(user.uid)
.delete()
.then(() => {
setLike(false);
setLikeCounter(likeCounter - 1);
})
.catch((err) => console.log(err));
}
};
// Getting Post's like data and updating like state
useEffect(() => {
db.collection("posts")
.doc(postId)
.collection("likes")
.onSnapshot((snap) => {
let documents = [];
snap.forEach((doc) => {
documents.push({
userName: doc.data().username,
photoURL: doc.data().photoURL,
userId: doc.id,
});
});
setUsersLiked(documents);
setLikeCounter(documents.length);
if (user) {
documents.map((u) => {
if (u.userId === user.uid) {
setLike(true);
}
});
}
});
}, []);
return (
<>
<div className={classes.likeContainer}>
<Button>
{like ? (
<FavoriteIcon onClick={onDislike} />
) : (
<FavoriteBorderIcon onClick={onLike} />
)}
</Button>
{likeCounter ? (
<Typography>
Liked by{" "}
<b
className={classes.likeCounter}
onClick={() => setLikeModal(true)}
>
{likeCounter} {likeCounter > 1 ? " users." : " user."}
</b>
</Typography>
) : null}
</div>
<Modal
className={classes.modal}
open={likeModal}
onClose={() => setLikeModal(false)}
closeAfterTransition
BackdropComponent={Backdrop}
BackdropProps={{
timeout: 500,
}}
>
<Fade in={likeModal}>
<div className={classes.paper}>
<h2>Users Liked:</h2>
<Divider />
<List className={classes.likelist}>
{usersLiked.map((user) => (
<ListItem button key={user.userId}>
<ListItemAvatar>
<Avatar
className={classes.avatar}
alt={user.userName}
src={user?.photoURL}
/>
</ListItemAvatar>
<ListItemText primary={user.userName} />
</ListItem>
))}
</List>
</div>
</Fade>
</Modal>
</>
);
}
Example #19
Source File: Content.js From hacktoberfest-participants with MIT License | 4 votes |
function Content(props) {
const { edges } = props.data.allContributorsJson;
const participantsPerPage = 6;
const classes = useStyles();
const [modal, setModal] = React.useState(false);
const [filteredParticipants, setFilteredParticipants] = React.useState(edges);
const [searchText, setSearchText] = React.useState('');
const [firstParticipantIndex, setFirstParticipantIndex] = React.useState(0);
const [participantsCount, setParticipantsCount] = React.useState(
edges.length
);
const handleSearch = ({ target: { value } }) => {
setSearchText(value);
setFirstParticipantIndex(0);
};
React.useEffect(() => {
if (searchText) {
const caseFreeSearchText = searchText.trim().toLowerCase();
if (!edges || !edges.length) return;
const filteredResult = edges.filter(({ node: { name, github } }) => {
return (
name.toLowerCase().includes(caseFreeSearchText) ||
getGithubUsernameFromURL(github).includes(caseFreeSearchText)
);
});
setParticipantsCount(filteredResult.length);
setFilteredParticipants(
filteredResult.slice(
firstParticipantIndex,
firstParticipantIndex + participantsPerPage
)
);
} else {
setParticipantsCount(
edges.length
);
setFilteredParticipants(
edges.slice(
firstParticipantIndex,
firstParticipantIndex + participantsPerPage
)
);
}
}, [searchText, firstParticipantIndex, participantsCount]);
const [id, setID] = React.useState(null);
return (
<main>
<div className={classes.heroContent}>
<Container maxWidth='sm'>
<Typography
component='h1'
variant='h3'
align='center'
color='inherit'
gutterBottom
>
Are you participating?{' '}
<span role='img' aria-label='thinking'>
?
</span>
</Typography>
<Typography
variant='h5'
align='center'
color='textSecondary'
paragraph
>
<u>
<a
href='https://hacktoberfest.digitalocean.com/'
style={{ textDecoration: 'none', color: 'inherit' }}
>
Hacktoberfest
</a>
</u>{' '}
is the time to come together and make the open-source world a better
place. ? Go raise a PR and add yourself in the list.
</Typography>
<div className={classes.heroButtons}>
<Grid container spacing={2} justify='center'>
<Grid item>
<AwesomeButtonSocial
className={classes.btn}
type='github'
target='_blank'
href='https://github.com/iamdarshshah/hacktoberfest-participants#steps-to-add-yourself-in-the-list'
>
Create a Pull Request
</AwesomeButtonSocial>
</Grid>
</Grid>
</div>
</Container>
<Container maxWidth='md'>
<Grid container spacing={1} justify='center'>
<Grid item xs={12} sm={8} md={5}>
<SearchTextField
startAdornment={
<InputAdornment position='start'>
<SearchIcon />
</InputAdornment>
}
onChange={handleSearch}
InputLabelProps={{
shrink: true,
}}
style={{ marginTop: 40 }}
fullWidth
margin='normal'
variant='outlined'
placeholder='Search by name or Github username'
id='input-with-icon-grid'
color='secondary'
/>
</Grid>
</Grid>
</Container>
</div>
<Container className={classes.cardGrid} maxWidth='md'>
<Grid container spacing={4}>
{Boolean(filteredParticipants.length) &&
filteredParticipants.map((edge, index) => {
return (
<Grid key={index} item xs={12} sm={6} md={4}>
<Card
className={classes.card}
onClick={() => {
setModal(true);
const githubID = edge.node.github.split('.com/')[1];
setID(githubID);
}}
>
<CardContent className={classes.cardContent}>
<Typography
gutterBottom
variant='h5'
align='center'
component='h2'
>
<b>
<u>
<i>{`${edge.node.name}`}</i>
</u>
</b>
</Typography>
<Typography />
<Typography
gutterBottom
variant='h6'
align='center'
component='h2'
>{`${edge.node.desc}`}</Typography>
</CardContent>
<Divider />
<CardContent>
<Typography className={classes.extraMargin}>
{edge.node.github ? (
<Link
className={classes.iconCls}
href={edge.node.github}
component='a'
target='_blank'
>
<GitHubIcon />
</Link>
) : null}
{edge.node.twitter ? (
<Link
className={classes.iconCls}
href={edge.node.twitter}
component='a'
target='_blank'
>
<TwitterIcon />
</Link>
) : null}
{edge.node.linkedin ? (
<Link
className={classes.iconCls}
href={edge.node.linkedin}
component='a'
target='_blank'
>
<LinkedInIcon />
</Link>
) : null}
</Typography>
</CardContent>
</Card>
</Grid>
);
})}
{!Boolean(filteredParticipants.length) && (
<Grid item xs={12}>
<Typography
component='div'
variant='h5'
align='center'
color='inherit'
gutterBottom
>
{' '}
<span role='img' aria-label='user not found'>
?
</span>{' '}
No participant found
</Typography>
</Grid>
)}
<Modal
disableEnforceFocus
disableAutoFocus
closeAfterTransition
open={modal}
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
}}
onClose={() => setModal(false)}
>
<div className={classes.modalContainer}>
<Fade in={modal}>
<Profile id={id} />
</Fade>
</div>
</Modal>
</Grid>
<Pagination
onPrev={() => {
setFirstParticipantIndex((prev) =>
prev - participantsPerPage >= 0 ? prev - participantsPerPage : 0
);
}}
onNext={() => {
setFirstParticipantIndex((prev) => {
return prev + participantsPerPage >= edges.length
? prev
: prev + participantsPerPage;
});
}}
actualPage={Math.ceil(
(firstParticipantIndex + 1) / participantsPerPage
)}
pagesCount={Math.ceil(participantsCount / participantsPerPage)}
></Pagination>
</Container>
</main>
);
}
Example #20
Source File: H5PEditorContainer.js From Edlib with GNU General Public License v3.0 | 4 votes |
H5PEditorContainer = ({ intl, editorSetup }) => {
const {
state: formState,
state: { parameters: formParameters, max_score: maxScore },
} = useForm();
const [currentView, setCurrentView] = React.useState(views.H5P);
const [parameters, setParameters] = React.useState({
...formState,
maxScore,
parameters: JSON.parse(formParameters),
});
const startupParameters = React.useMemo(() => parameters, []);
const [isSaved, setIsSaved] = React.useState(false);
const [isH5PReady, setIsH5PReady] = React.useState(false);
const h5PRef = React.createRef();
const [fileStatus, setFileStatus] = React.useState({
total: 10,
inProgress: 0,
failed: 0,
done: 0,
});
const [showFileProgress, toggleShowFileProgress] = React.useState(false);
const [librarySelected, setLibrarySelected] = useState(false);
const theme = useTheme();
const onParamsChange = (newParameters) => {
setParameters({
...parameters,
...newParameters,
});
};
const {
init,
reDraw,
getParams,
getMaxScore,
getLibrary,
getTitle,
h5pEditor,
onBeforeUpgrade,
stageUpgrade,
iframeLoading,
setAuthor,
} = useH5PEditor(onParamsChange);
const getCurrentParams = React.useCallback(() => {
return currentView === views.H5P ? getParams() : parameters.parameters;
}, [currentView, parameters, getParams]);
const getLibraryCache = () =>
h5pEditor && !iframeLoading
? h5pEditor.iframeWindow.H5PEditor.libraryCache
: {};
const shouldConfirmClose = React.useCallback(() => {
if (isSaved) {
return false;
}
const currentParams = getCurrentParams();
return (
JSON.stringify(
removeKeys(startupParameters.parameters, ['metadata'])
) !== JSON.stringify(removeKeys(currentParams, ['metadata'])) ||
currentParams.metadata.title !==
startupParameters.parameters.metadata.title
);
}, [getCurrentParams, startupParameters, isSaved]);
useConfirmWindowClose(shouldConfirmClose);
React.useEffect(() => {
const H5PReadyInterval = setInterval(() => {
if (typeof window.H5PEditor !== 'undefined') {
clearInterval(H5PReadyInterval);
setIsH5PReady(true);
}
}, 25);
}, []);
React.useEffect(() => {
if (isH5PReady) {
init(h5PRef.current, parameters);
}
}, [isH5PReady]);
React.useEffect(() => {
if (isH5PReady) {
if (currentView === views.H5P) {
reDraw(parameters.parameters, getLibrary());
} else {
onParamsChange({
parameters: getParams(),
});
}
}
}, [currentView, isH5PReady]);
const getFormState = () => formState;
React.useEffect(() => {
if (h5pEditor) {
const H5PLibraryInterval = setInterval(() => {
try {
const selectedLibrary = getLibrary();
if (
typeof selectedLibrary === 'string' &&
selectedLibrary.length > 0
) {
const { creatorName } = editorSetup;
if (creatorName !== null) {
setAuthor(creatorName, 'Author');
}
clearInterval(H5PLibraryInterval);
setLibrarySelected(true);
}
// eslint-disable-next-line no-empty
} catch (ignore) {}
}, 1000);
}
}, [h5pEditor, getCurrentParams, getFormState]);
const save = (isDraft = false) => {
try {
const params = getCurrentParams();
const { h5pLanguage } = editorSetup;
if (
!(params || params.params) ||
typeof params.params === 'undefined'
) {
return false;
}
//don't need the outcome. Simple test that it's a json object. The try/catch will catch if it fails
JSON.parse(JSON.stringify(params));
if (!getTitle()) {
return false;
}
if (
params.metadata &&
h5pLanguage &&
!params.metadata.defaultLanguage
) {
params.metadata.defaultLanguage = h5pLanguage;
}
const formValues = getFormState();
formValues.title = params.metadata.title || '';
formValues.isDraft = isDraft;
formValues.library = getLibrary();
formValues.parameters = JSON.stringify(params);
formValues.max_score = getMaxScore(params);
setIsSaved(true);
const errorHandler = ({ response }) => {
let responseData;
try {
responseData = JSON.parse(response.data);
} catch (err) {
responseData = [response.request.responseText];
}
setIsSaved(false);
return [responseData];
};
const statusHandler = (status) => {
toggleShowFileProgress(true);
setFileStatus(status);
if (status.total === status.inProgress) {
toggleShowFileProgress(false);
} else if (status.failed > 0) {
toggleShowFileProgress(false);
errorHandler({
responseText: intl.formatMessage({
id: 'H5P_EDITOR.UPLOAD_OF_MEDIAFILE_FAILED',
}),
});
}
};
return {
values: formValues,
statusHandler,
errorHandler,
isValid: true,
};
} catch (error) {
return {
errorMessages: [error],
isValid: false,
};
}
};
const getSidebarComponents = () => {
const {
adapterName = null,
adapterList = [],
showDisplayOptions = false,
} = editorSetup;
const {
frame,
copyright,
download,
language_iso_639_3: languageISO6393,
isNewLanguageVariant,
} = formState;
const components = [];
if (showDisplayOptions === true) {
components.push({
id: 'displayOptions',
title: intl.formatMessage({
id: 'DISPLAYOPTIONS.DISPLAYOPTIONS',
}),
component: (
<DisplayOptions
displayButtons={frame}
displayCopyright={copyright}
displayDownload={download}
/>
),
});
}
if (
editorSetup.libraryUpgradeList &&
editorSetup.libraryUpgradeList.length > 0
) {
components.push({
id: 'upgradeContent',
title: intl.formatMessage({
id: 'H5PCONTENTUPGRADE.UPDATECONTENT',
}),
info: (
<NewReleases
htmlColor={theme.colors.tertiary}
fontSize="large"
/>
),
component: (
<ContentUpgradeContainer
libraries={editorSetup.libraryUpgradeList}
onStageUpgrade={stageUpgrade}
onBeforeUpgrade={() =>
onBeforeUpgrade(getCurrentParams())
}
/>
),
});
}
const languageText = getLanguageStringFromCode(languageISO6393);
components.push({
id: 'language',
title: intl.formatMessage({
id: 'H5P_EDITOR.LANGUAGE_PICKER.LANGUAGE',
}),
info: languageText !== null ? <div>({languageText})</div> : null,
component: (
<LanguagePicker
getParameters={() => getCurrentParams()}
library={parameters.library}
hideNewVariant={editorSetup.hideNewVariant}
isNewLanguageVariant={isNewLanguageVariant}
autoTranslateTo={editorSetup.autoTranslateTo}
value={languageISO6393}
libraryCache={getLibraryCache}
setParams={(newParameters) => {
onParamsChange({ parameters: newParameters });
nextTick(() => {
if (currentView === views.H5P) {
reDraw(newParameters, parameters.library);
} else {
setCurrentView(null);
setCurrentView(views.LIST);
}
});
}}
/>
),
});
if (adapterName !== null) {
components.push({
id: 'adapterSelect',
title: 'Adapter',
info: <div>({adapterName})</div>,
component: (
<AdapterSelector
current={adapterName}
adapters={adapterList}
/>
),
});
}
return components;
};
return (
<EditorContainer
tabs={[
{
label: intl.formatMessage({
id: 'H5P_EDITOR.TAB.H5P_VIEW',
}),
onClick: () => setCurrentView(views.H5P),
selected: currentView === views.H5P,
},
{
label: intl.formatMessage({
id: 'H5P_EDITOR.TAB.LIST_VIEW',
}),
onClick: () => setCurrentView(views.LIST),
selected: currentView === views.LIST,
},
]}
sidebar={
librarySelected === true && (
<Fade in={librarySelected}>
<Sidebar
customComponents={getSidebarComponents()}
onSave={save}
/>
</Fade>
)
}
containerClassname="h5p-container"
>
<div className="h5p-editor-container">
{currentView === views.LIST && (
<List
parameters={parameters}
onUpdate={setParameters}
startupParameters={startupParameters}
libraryCache={getLibraryCache}
/>
)}
<H5P visible={currentView === views.H5P} ref={h5PRef} />
<FileUploadProgress
total={fileStatus.total}
inProgress={fileStatus.inProgress}
done={fileStatus.done}
show={showFileProgress}
/>
</div>
</EditorContainer>
);
}
Example #21
Source File: Login.js From react-code-splitting-2021-04-26 with MIT License | 4 votes |
function Login(props) {
var classes = useStyles();
// global
var userDispatch = useUserDispatch();
// local
var [isLoading, setIsLoading] = useState(false);
var [error, setError] = useState(null);
var [activeTabId, setActiveTabId] = useState(0);
var [nameValue, setNameValue] = useState("");
var [loginValue, setLoginValue] = useState("[email protected]");
var [passwordValue, setPasswordValue] = useState("password");
return (
<Grid container className={classes.container}>
<div className={classes.logotypeContainer}>
<img src={logo} alt="logo" className={classes.logotypeImage} />
<Typography className={classes.logotypeText}>Material Admin</Typography>
</div>
<div className={classes.formContainer}>
<div className={classes.form}>
<Tabs
value={activeTabId}
onChange={(e, id) => setActiveTabId(id)}
indicatorColor="primary"
textColor="primary"
centered
>
<Tab label="Login" classes={{ root: classes.tab }} />
<Tab label="New User" classes={{ root: classes.tab }} />
</Tabs>
{activeTabId === 0 && (
<React.Fragment>
<Typography variant="h1" className={classes.greeting}>
Good Morning, User
</Typography>
<Button size="large" className={classes.googleButton}>
<img src={google} alt="google" className={classes.googleIcon} />
Sign in with Google
</Button>
<div className={classes.formDividerContainer}>
<div className={classes.formDivider} />
<Typography className={classes.formDividerWord}>or</Typography>
<div className={classes.formDivider} />
</div>
<Fade in={error}>
<Typography color="secondary" className={classes.errorMessage}>
Something is wrong with your login or password :(
</Typography>
</Fade>
<TextField
id="email"
InputProps={{
classes: {
underline: classes.textFieldUnderline,
input: classes.textField,
},
}}
value={loginValue}
onChange={e => setLoginValue(e.target.value)}
margin="normal"
placeholder="Email Adress"
type="email"
fullWidth
/>
<TextField
id="password"
InputProps={{
classes: {
underline: classes.textFieldUnderline,
input: classes.textField,
},
}}
value={passwordValue}
onChange={e => setPasswordValue(e.target.value)}
margin="normal"
placeholder="Password"
type="password"
fullWidth
/>
<div className={classes.formButtons}>
{isLoading ? (
<CircularProgress size={26} className={classes.loginLoader} />
) : (
<Button
disabled={
loginValue.length === 0 || passwordValue.length === 0
}
onClick={() =>
loginUser(
userDispatch,
loginValue,
passwordValue,
props.history,
setIsLoading,
setError,
)
}
variant="contained"
color="primary"
size="large"
>
Login
</Button>
)}
<Button
color="primary"
size="large"
className={classes.forgetButton}
>
Forget Password
</Button>
</div>
</React.Fragment>
)}
{activeTabId === 1 && (
<React.Fragment>
<Typography variant="h1" className={classes.greeting}>
Welcome!
</Typography>
<Typography variant="h2" className={classes.subGreeting}>
Create your account
</Typography>
<Fade in={error}>
<Typography color="secondary" className={classes.errorMessage}>
Something is wrong with your login or password :(
</Typography>
</Fade>
<TextField
id="name"
InputProps={{
classes: {
underline: classes.textFieldUnderline,
input: classes.textField,
},
}}
value={nameValue}
onChange={e => setNameValue(e.target.value)}
margin="normal"
placeholder="Full Name"
type="text"
fullWidth
/>
<TextField
id="email"
InputProps={{
classes: {
underline: classes.textFieldUnderline,
input: classes.textField,
},
}}
value={loginValue}
onChange={e => setLoginValue(e.target.value)}
margin="normal"
placeholder="Email Adress"
type="email"
fullWidth
/>
<TextField
id="password"
InputProps={{
classes: {
underline: classes.textFieldUnderline,
input: classes.textField,
},
}}
value={passwordValue}
onChange={e => setPasswordValue(e.target.value)}
margin="normal"
placeholder="Password"
type="password"
fullWidth
/>
<div className={classes.creatingButtonContainer}>
{isLoading ? (
<CircularProgress size={26} />
) : (
<Button
onClick={() =>
loginUser(
userDispatch,
loginValue,
passwordValue,
props.history,
setIsLoading,
setError,
)
}
disabled={
loginValue.length === 0 ||
passwordValue.length === 0 ||
nameValue.length === 0
}
size="large"
variant="contained"
color="primary"
fullWidth
className={classes.createAccountButton}
>
Create your account
</Button>
)}
</div>
<div className={classes.formDividerContainer}>
<div className={classes.formDivider} />
<Typography className={classes.formDividerWord}>or</Typography>
<div className={classes.formDivider} />
</div>
<Button
size="large"
className={classnames(
classes.googleButton,
classes.googleButtonCreating,
)}
>
<img src={google} alt="google" className={classes.googleIcon} />
Sign in with Google
</Button>
</React.Fragment>
)}
</div>
<Typography color="primary" className={classes.copyright}>
© 2014-{new Date().getFullYear()} <a style={{ textDecoration: 'none', color: 'inherit' }} href="https://flatlogic.com" rel="noopener noreferrer" target="_blank">Flatlogic</a>, LLC. All rights reserved.
</Typography>
</div>
</Grid>
);
}
Example #22
Source File: resources.js From covid19Nepal-react with MIT License | 4 votes |
function Resources(props) {
const [data, setData] = useState([]);
const [partData, setPartData] = useState([]);
const [ogData, setOgData] = useState([]);
const [fetched, setFetched] = useState(false);
const [city, setCity] = useState('all');
const [category, setCategory] = useState('all');
const [nepalstate, setNepalState] = useState('all');
const [resourcedict, setResourceDict] = useState({});
const [showTable, setShowTable] = useState(false);
const [isDesktop, setIsDesktop] = useState(false);
const [hasScrolled, setHasScrolled] = useState(false);
const [anchorEl, setAnchorEl] = React.useState(null);
const [searchValue, setSearchValue] = useState('');
useEffect(() => {
if (fetched === false) {
getResources();
}
}, [fetched, data, resourcedict]);
const checkForResizeEvent = useCallback((event) => {
if (window.innerWidth > 639) setIsDesktop(true);
else setIsDesktop(false);
}, []);
useEffect(() => {
if (window.innerWidth > 639) setIsDesktop(true);
else setIsDesktop(false);
window.addEventListener('resize', checkForResizeEvent);
return () => {
window.removeEventListener('resize', checkForResizeEvent);
};
}, [isDesktop, checkForResizeEvent]);
const checkScrollEvent = useCallback((event) => {
window.pageYOffset > 100 ? setHasScrolled(true) : setHasScrolled(false);
}, []);
useEffect(() => {
window.pageYOffset > 100 ? setHasScrolled(true) : setHasScrolled(false);
window.addEventListener('scroll', checkScrollEvent);
return () => {
window.removeEventListener('scroll', checkScrollEvent);
};
}, [hasScrolled, checkScrollEvent]);
const getResources = async () => {
try {
const [response] = await Promise.all([
axios.get('https://api.nepalcovid19.org/resources/resources.json'),
]);
// setData(response.data.resources);
const hashmap = {};
response.data.resources.forEach((x) => {
if (typeof hashmap[x['state']] === 'undefined')
hashmap[x['state']] = {};
if (typeof hashmap[x['state']][x['city']] === 'undefined')
hashmap[x['state']][x['city']] = {};
if (
typeof hashmap[x['state']][x['city']][x['category']] === 'undefined'
)
hashmap[x['state']][x['city']][x['category']] = [];
if (Array.isArray(hashmap[x['state']][x['city']][x['category']]))
hashmap[x['state']][x['city']][x['category']].push(x);
});
setResourceDict(hashmap);
setFetched(true);
} catch (err) {}
};
const handleDisclaimerClick = (event) => {
setAnchorEl(event.currentTarget);
};
const handleDisclaimerClose = () => {
setAnchorEl(null);
};
const isDisclaimerOpen = Boolean(anchorEl);
const id = isDisclaimerOpen ? 'simple-popover' : undefined;
function animateScroll() {
document.body.scrollTo({top: 0, behavior: 'smooth'}); // For Safari
document.documentElement.scrollTo({top: 0, behavior: 'smooth'}); // For Chrome, Firefox, IE and Opera
}
const memocols = React.useMemo(
() => [
{
Header: 'City',
accessor: 'city',
},
{
Header: 'Category',
accessor: 'category',
},
{
Header: 'Organisation',
accessor: 'nameoftheorganisation',
},
{
Header: 'Description',
accessor: 'descriptionandorserviceprovided',
},
{
Header: 'Phone',
accessor: 'phonenumber',
},
{
Header: 'Source',
accessor: 'contact',
isVisible: false,
},
],
[]
);
// const memodata = React.useMemo(() => data, [data])
const getCityOptions = function () {
if (nepalstate) {
if (nepalstate === 'all') return [];
else {
return Object.keys(resourcedict[nepalstate])
.sort()
.map((x, i) => (
<option
key={i}
value={x}
style={{
fontFamily: 'archia',
fontSize: '11px !important',
fontWeight: 600,
textTransform: 'uppercase',
}}
>
{x}
</option>
));
}
} else return [];
// return getCityList().map((x) => <option value={x}>{x}</option>)
};
const getnepalstateOptions = function () {
// let defaultOption = ['Please select']
return Object.keys(resourcedict)
.sort()
.map((x, i) => (
<option
key={i}
value={x}
style={{
fontFamily: 'archia',
fontSize: '11px !important',
fontWeight: 600,
textTransform: 'uppercase',
}}
>
{x}
</option>
));
};
const getCategoryOptions = function () {
if (nepalstate && city) {
if (nepalstate === 'all') {
const array = [];
Object.values(resourcedict).forEach((state) => {
Object.values(state).forEach((citydata) => {
Object.keys(citydata).forEach((x) => {
if (array.indexOf(x) === -1) array.push(x);
});
});
});
return array.sort().map((x, i) => (
<option
key={i}
value={x}
style={{
fontFamily: 'archia',
fontSize: '11px !important',
fontWeight: 600,
textTransform: 'uppercase',
}}
>
{x}
</option>
));
} else {
if (city === 'all') {
const array = [];
Object.values(resourcedict[nepalstate]).forEach((citydata) => {
Object.keys(citydata).forEach((x) => {
if (array.indexOf(x) === -1) array.push(x);
});
});
return array.sort().map((x, i) => (
<option
key={i}
value={x}
style={{
fontFamily: 'archia',
fontSize: '11px !important',
fontWeight: 600,
textTransform: 'uppercase',
}}
>
{x}
</option>
));
} else {
return Object.keys(resourcedict[nepalstate][city])
.sort()
.map((x, i) => (
<option
key={i}
value={x}
style={{
fontFamily: 'archia',
fontSize: '11px !important',
fontWeight: 600,
textTransform: 'uppercase',
}}
>
{x}
</option>
));
}
}
} else return [];
};
const filterTable = function () {
let a = [];
if (category === 'all') {
if (city === 'all') {
if (nepalstate === 'all') {
Object.values(resourcedict).forEach((state) => {
Object.values(state).forEach((citydata) => {
Object.values(citydata).forEach((category) => {
category.forEach((x) => a.push(x));
});
});
});
} else {
Object.values(resourcedict[nepalstate]).forEach((citydata) => {
Object.values(citydata).forEach((category) => {
category.forEach((x) => a.push(x));
});
});
}
} else {
Object.values(resourcedict[nepalstate][city]).forEach((x) => {
x.forEach((y) => a.push(y));
});
}
} else {
if (nepalstate === 'all' && city === 'all') {
Object.values(resourcedict).forEach((state) => {
Object.values(state).forEach((citydata) => {
Object.values(citydata).forEach((categorydata) => {
categorydata.forEach((x) => {
if (x.category === category) a.push(x);
});
});
});
});
} else if (nepalstate !== 'all' && city === 'all') {
Object.values(resourcedict[nepalstate]).forEach((citydata) => {
if (category in citydata) {
citydata[category].forEach((x) => {
a.push(x);
});
}
});
} else {
a = resourcedict[nepalstate][city][category];
}
}
try {
if ('PAN Nepal' in resourcedict) {
resourcedict['PAN Nepal']['Multiple']['CoVID-19 Testing Lab'].forEach(
(element) => {
a.push(element);
}
);
}
} catch (err) {}
setData(a);
setOgData(a);
setPartData(a.slice(0, 30));
setShowTable(true);
try {
document.getElementById('input-field-searchbar').value = '';
} catch {}
setSearchValue('');
};
const changeNepalState = function (changedstateevent) {
setNepalState(changedstateevent.target.value);
// setCity(
// Object.keys(resourcedict[changedstateevent.target.value]).sort()[0]
// );
if (changedstateevent.target.value === '') {
setCity('');
document.getElementById('cityselect1').selectedIndex = 0;
setCategory('');
document.getElementById('categoryselect').selectedIndex = 0;
} else {
setCity('all');
document.getElementById('cityselect1').selectedIndex = 1;
setCategory('all');
document.getElementById('categoryselect').selectedIndex = 1;
}
};
const changeCity = function (changedcityevent) {
setCity(changedcityevent.target.value);
setCategory('all');
document.getElementById('categoryselect').selectedIndex = 1;
};
const changeCategory = function (changedcategoryevent) {
setCategory(changedcategoryevent.target.value);
};
const appendData = function () {
const tempArr = partData.concat(
data.slice(partData.length, partData.length + 30)
);
setPartData(tempArr);
};
const openSharingLink = function (message) {
const shareUri = `https://www.addtoany.com/share#url=${encodeURI(
'https://www.nepalcovid19.org/essentials'
)}&title=${encodeURI(message)}`;
const h = 500;
const w = 500;
const left = window.screen.width / 2 - w / 2;
const top = window.screen.height / 2 - h / 2;
return window.open(
shareUri,
document.title,
'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' +
w +
', height=' +
h +
', top=' +
top +
', left=' +
left
);
};
const openSharingTray = function () {
const message =
'Discover nearest coronavirus support and essential service providers such as testing lab centres, accommodation shelters and vegetable vendors at ';
if (navigator.share !== undefined) {
navigator
.share({
title: document.title,
text: message,
url: 'https://www.nepalcovid19.org/essentials',
})
.then()
.catch((error) => {});
} else {
openSharingLink(message);
}
};
useDebounce(
() => {
const newData = getSuggestions(searchValue, ogData);
setData(newData);
setPartData(newData.slice(0, 30));
},
300,
[searchValue, ogData]
);
return (
<div className="Resources" id="top-elem">
<Helmet>
<title>Essentials - nepalcovid19.org</title>
<meta name="title" content="Essentials - nepalcovid19.org" />
</Helmet>
<div className="filtersection">
<div className="filtertitle">
<h3>Service Before Self</h3>
</div>
{!isDesktop && (
<FiltersMobile
handleDisclaimerClick={handleDisclaimerClick}
popoverid={id}
isDisclaimerOpen={isDisclaimerOpen}
anchorEl={anchorEl}
handleDisclaimerClose={handleDisclaimerClose}
nepalstate={nepalstate}
changeNepalState={changeNepalState}
stateoptions={getnepalstateOptions()}
city={city}
changeCity={changeCity}
cityoptions={getCityOptions()}
category={category}
changeCategory={changeCategory}
servicesoptions={getCategoryOptions()}
filterTable={filterTable}
openSharingTray={openSharingTray}
/>
)}
{isDesktop && (
<FiltersDesktop
handleDisclaimerClick={handleDisclaimerClick}
popoverid={id}
isDisclaimerOpen={isDisclaimerOpen}
anchorEl={anchorEl}
handleDisclaimerClose={handleDisclaimerClose}
nepalstate={nepalstate}
changeNepalState={changeNepalState}
stateoptions={getnepalstateOptions()}
city={city}
changeCity={changeCity}
cityoptions={getCityOptions()}
category={category}
changeCategory={changeCategory}
servicesoptions={getCategoryOptions()}
filterTable={filterTable}
openSharingTray={openSharingTray}
/>
)}
</div>
{showTable && (
<React.Fragment>
<div className="searchbar">
<TextField
id="input-field-searchbar"
label="Search keyword"
fullWidth={true}
InputLabelProps={{
shrink: true,
}}
style={{
width: '100%',
}}
variant="outlined"
InputProps={{
startAdornment: (
<InputAdornment position="start">
<Icon.Search size="0.9em" />
</InputAdornment>
),
}}
onChange={(event) => {
setInterval(setSearchValue(event.target.value));
}}
/>
</div>
<ResourceTable
columns={memocols}
data={partData}
totalCount={data.length}
isDesktop={isDesktop}
onScrollUpdate={appendData}
searchValue={searchValue}
/>
<div>
<Fade in={hasScrolled}>
<Fab
color="inherit"
aria-label="gototop"
id="gototopbtn"
onClick={animateScroll}
size="small"
style={{
position: 'fixed',
bottom: '1rem',
right: '1rem',
zIndex: '1000',
}}
>
<Icon.Navigation2 strokeWidth="2.5" color="#4c75f2" />
</Fab>
</Fade>
</div>
</React.Fragment>
)}
</div>
);
}
Example #23
Source File: Header.js From eSim-Cloud with GNU General Public License v3.0 | 4 votes |
function Header (props) {
const history = useHistory()
const classes = useStyles()
const auth = useSelector(state => state.authReducer)
const schSave = useSelector(state => state.saveSchematicReducer)
const [anchorEl, setAnchorEl] = React.useState(null)
const [loginDialog, setLoginDialog] = React.useState(false)
const [logoutConfirm, setLogoutConfirm] = React.useState(false)
const [reloginMessage, setReloginMessage] = React.useState('')
const dispatch = useDispatch()
const handleClick = (event) => {
setAnchorEl(event.currentTarget)
}
// Checks for localStore changes
useEffect(() => {
function checkUserData () {
const userToken = localStorage.getItem('esim_token')
if (userToken && userToken !== '') {
// esim_token was added by another tab
const newUser = parseInt(localStorage.getItem('user_id'))
if (auth.isAuthenticated === null) {
dispatch(loadMinUser())
} else if (auth.user && auth.user.id === newUser) {
dispatch(loadMinUser())
setLoginDialog(false)
} else {
setReloginMessage('You are logged in but the circuit belongs to a different user! Login again with the same credentials')
}
} else {
/* User logged out and esim_token removed from localstore
But redux store still has it */
if (auth.token && auth.token !== '') {
if (!loginDialog) {
setReloginMessage('You have been logged out of your account. Login again')
setLoginDialog(true)
}
}
}
}
window.addEventListener('storage', checkUserData)
return () => {
window.removeEventListener('storage', checkUserData)
}
})
const handleClose = () => {
setAnchorEl(null)
}
const titleHandler = (e) => {
dispatch(setTitle(`* ${e.target.value}`))
dispatch(setSchTitle(`${e.target.value}`))
}
// handle notification snackbar open and close with message
const [snacOpen, setSnacOpen] = React.useState(false)
const [message, setMessage] = React.useState('')
const handleSnacClick = () => {
setSnacOpen(true)
}
const handleSnacClose = (event, reason) => {
if (reason === 'clickaway') {
return
}
setSnacOpen(false)
}
// handle schematic Share Dialog box
const [openShare, setShareOpen] = React.useState(false)
const handleShareOpen = () => {
setShareOpen(true)
}
const handleShareClose = () => {
setShareOpen(false)
}
// change saved schematic share status
const [shared, setShared] = React.useState(schSave.isShared)
useEffect(() => {
setShared(schSave.isShared)
}, [schSave.isShared])
useEffect(() => {
if (history.location.search === '') {
dispatch(setSchTitle('Untitled_Schematic'))
dispatch(setSchDescription(''))
dispatch({ type: actions.CLEAR_DETAILS })
}
}, [history.location.search, dispatch])
const handleShareChange = (event) => {
setShared(event.target.checked)
dispatch(setSchShared(event.target.checked))
}
const handleShare = () => {
if (auth.isAuthenticated !== true) {
setMessage('You are not Logged In')
handleSnacClick()
} else if (schSave.isSaved !== true) {
setMessage('You have not saved the circuit')
handleSnacClick()
} else {
handleShareOpen()
}
}
// handle display format of last saved status
function getDate (jsonDate) {
const json = jsonDate
const date = new Date(json)
const dateTimeFormat = new Intl.DateTimeFormat('en', { month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' })
const [{ value: month }, , { value: day }, , { value: hour }, , { value: minute }, , { value: second }] = dateTimeFormat.formatToParts(date)
return `${day} ${month} ${hour}:${minute}:${second}`
}
// handle Copy Share Url
const textAreaRef = React.useRef(null)
function copyToClipboard (e) {
textAreaRef.current.select()
document.execCommand('copy')
e.target.focus()
setMessage('Copied Successfully!')
handleSnacClick()
}
return (
<>
<Dialog
open={loginDialog}
BackdropProps={{
classes: {
root: classes.backDrop
}
}}
maxWidth='xs'
disableEscapeKeyDown
disableBackdropClick
>
<DialogTitle id="alert-dialog-title" style={{ textAlign: 'center' }}>
<ErrorOutlineIcon style={{ color: 'red' }} fontSize="large" /><br />
<Typography variant='h5' align='center'>
{'Login to continue working on the circuit'}
</Typography>
</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description">
<Typography variant='p'>
{reloginMessage}
{' to continue working on the circuit, otherwise all unsaved changes will be lost.'}
</Typography>
</DialogContentText>
</DialogContent>
<DialogActions>
<Button
onClick={() => { window.location.reload() }}
color="secondary"
>
Start New Circuit
</Button>
<Button
component={RouterLink}
to="/login?close=close&logout=logout"
color="primary"
target="_blank"
>
Login
</Button>
</DialogActions>
</Dialog>
<Dialog
open={logoutConfirm}
onClose={() => { setLogoutConfirm(false) }}
>
<DialogTitle id="alert-dialog-title" style={{ textAlign: 'center' }}>
<ErrorOutlineIcon style={{ color: 'red' }} fontSize="large" /><br />
<Typography variant='h5' align='center'>
{'Are you sure you want to logout?'}
</Typography>
</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description">
You will lose all unsaved changes if you logout now.
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={() => { setLogoutConfirm(false) }} color="secondary">
Cancel
</Button>
<Button
style={{ color: '#ff1744' }}
onClick={() => {
dispatch(logout(history))
}}
>
Logout
</Button>
</DialogActions>
</Dialog>
<Toolbar variant="dense" color="default">
<SimpleSnackbar open={snacOpen} close={handleSnacClose} message={message} />
{/* Display logo */}
<IconButton edge="start" className={classes.button} color="primary">
<Avatar alt="esim logo" src={logo} className={classes.small} />
</IconButton>
<Typography
variant="h6"
color="inherit"
noWrap
className={classes.toolbarTitle}
>
<Link color="inherit" target='_blank' component={RouterLink} to="/">
eSim
</Link>
</Typography>
{/* Input field for schematic title */}
<Hidden xsDown>
<Input
className={classes.input}
color="secondary"
value={schSave.title === 'Untitled_Schematic' ? 'Untitled_Schematic' : schSave.title}
onChange={titleHandler}
inputProps={{ 'aria-label': 'SchematicTitle' }}
/>
</Hidden>
{/* Display last saved and shared option for saved schematics */}
{auth.isAuthenticated === true
? <>
{(schSave.isSaved === true && schSave.details.save_time !== undefined)
? <Typography
variant="body2"
style={{ margin: '0px 15px 0px auto', paddingTop: '5px', color: '#8c8c8c' }}
>
Last Saved : {getDate(schSave.details.save_time)} {/* Display last saved status for saved schematics */}
</Typography>
: <></>
}
<Button
size="small"
variant={shared !== true ? 'outlined' : 'contained'}
color="primary"
className={schSave.isSaved === true && schSave.details.save_time !== undefined ? classes.button : classes.rightBlock}
startIcon={<ShareIcon />}
onClick={handleShare}
>
<Hidden xsDown>Share</Hidden>
</Button>
</>
: <></>
}
{/* Share dialog box to get share url */}
<Dialog
open={openShare}
onClose={handleShareClose}
aria-labelledby="share-dialog-title"
aria-describedby="share-dialog-description"
>
<DialogTitle id="share-dialog-title">{'Share Your Schematic'}</DialogTitle>
<DialogContent>
<DialogContentText id="share-dialog-description">
<FormControlLabel
control={<Switch checked={shared} onChange={handleShareChange} name="shared" />}
label=": Sharing On"
/>
</DialogContentText>
<DialogContentText id="share-dialog-description">
{shared === true
? <input
ref={textAreaRef}
value={`${window.location.protocol}\\\\${window.location.host}/eda/#/editor?id=${schSave.details.save_id}`}
readOnly
/>
: <> Turn On sharing </>
}
</DialogContentText>
</DialogContent>
<DialogActions>
{shared === true && document.queryCommandSupported('copy')
? <Button onClick={copyToClipboard} color="primary" autoFocus>
Copy url
</Button>
: <></>
}
<Button onClick={handleShareClose} color="primary" autoFocus>
close
</Button>
</DialogActions>
</Dialog>
{/* Display login option or user menu as per authenticated status */}
{
(!auth.isAuthenticated
? <Button
size="small"
component={RouterLink}
to="/login?close=close"
style={{ marginLeft: 'auto' }}
color="primary"
variant="outlined"
target="_blank"
>
Login
</Button>
: (<>
<IconButton
edge="start"
color="primary"
aria-controls="simple-menu"
aria-haspopup="true"
onClick={handleClick}
>
<Avatar className={classes.purple}>
{auth.user.username.charAt(0).toUpperCase()}
</Avatar>
</IconButton>
<Menu
id="simple-menu"
anchorEl={anchorEl}
keepMounted
open={Boolean(anchorEl)}
onClose={handleClose}
TransitionComponent={Fade}
style={{ marginTop: '25px' }}
>
<MenuItem
target='_blank'
component={RouterLink}
to="/dashboard"
onClick={handleClose}
>
<ListItemText primary={auth.user.username} secondary={auth.user.email} />
</MenuItem>
<MenuItem
target='_blank'
component={RouterLink}
to="/dashboard/profile"
onClick={handleClose}
>
My Profile
</MenuItem>
<MenuItem
target='_blank'
component={RouterLink}
to="/dashboard/schematics"
onClick={handleClose}
>
My Schematics
</MenuItem>
<MenuItem
target='_blank'
component={RouterLink}
to="/account/change_password"
onClick={handleClose}
>
Change password
</MenuItem>
<MenuItem onClick={() => {
setLogoutConfirm(true)
}}>
Logout
</MenuItem>
</Menu>
</>
)
)
}
</Toolbar>
</>
)
}
Example #24
Source File: Projects.js From Portfolio with MIT License | 4 votes |
export default function Projects({ data }) {
const classes = useStyles()
const animRef = useRef(null)
const animate = useAnimate(animRef)
return (
<Grid direction="row-reverse" container justify="center" alignItems="center" spacing={10} className={classes.cont}>
<Grid item xs={12} lg={6}>
<Typography variant="h2" gutterBottom align="center" innerRef={animRef}>
Projects
</Typography>
<Hidden mdDown>
<Fade in={animate} style={{ transitionDelay: '250ms' }}>
<div>
<Image
alt="Projects"
src="/projects.svg"
width="1144"
height="617.32"
/>
</div>
</Fade>
</Hidden>
</Grid>
<Grid container item xs={12} lg={6} direction="row" spacing={1}>
{
!!data && data.map((v, i) =>
<Grid item sm={6} xs={12} key={i}>
<Fade in={animate} style={{ transitionDelay: `${200 * i}ms` }}>
<Card key={i} className={classes.card}>
<CardActionArea
className={classes.cardActionArea}
href={v.value.html_url}
target="_blank"
rel="noopener noreferrer"
>
<CardHeader
title={<><RepoIcon verticalAlign='middle' /> {v.value.name}</>}
subheader={
<>
{
!!v.value.stargazers_count &&
<>
<StarIcon verticalAlign='middle' />
{v.value.stargazers_count}
</>
}
{
!!v.value.forks &&
<>
<RepoForkedIcon verticalAlign='middle' />
{v.value.forks}
</>
}
</>
}
/>
<CardContent>
<Typography variant="body2" color="textSecondary" component="p">
{v.value.description}
</Typography>
</CardContent>
<CardActions>
<Grid container direction="row" spacing={1}>
{
!!v.value.languages &&
v.value.languages.map((lang, i) =>
<Grid item key={i}>
<Chip
key={i}
label={lang}
size="small"
/>
</Grid>
)
}
</Grid>
</CardActions>
</CardActionArea>
</Card>
</Fade>
</Grid>
)
}
</Grid>
</Grid>
)
}
Example #25
Source File: Navbar.js From eSim-Cloud with GNU General Public License v3.0 | 4 votes |
// Common navbar for Dashboard, Home, Simulator, Gallery, etc.
export function Header () {
const history = useHistory()
const classes = useStyles()
const [anchorEl, setAnchorEl] = React.useState(null)
const auth = store.getState().authReducer
const dispatch = useDispatch()
const handleClick = (event) => {
setAnchorEl(event.currentTarget)
}
const handleClose = () => {
setAnchorEl(null)
}
useEffect(() => {
function checkUserData () {
const userToken = localStorage.getItem('esim_token')
if (userToken && userToken !== '') {
dispatch(loadUser())
} else {
dispatch(authDefault())
}
}
window.addEventListener('storage', checkUserData)
return () => {
window.removeEventListener('storage', checkUserData)
}
}, [dispatch, history])
return (
<>
{/* Display logo */}
<IconButton edge="start" className={classes.button} color="primary">
<Avatar alt="esim logo" src={logo} className={classes.small} />
</IconButton>
<Typography
variant="h6"
color="inherit"
noWrap
className={classes.toolbarTitle}
>
<Link color="inherit" to="/" component={RouterLink}>
eSim
</Link>
</Typography>
{/* Display relative link to other pages */}
<nav>
{
(auth.isAuthenticated
? (<>
<Link
variant="button"
color="textPrimary"
to="/"
component={RouterLink}
className={classes.link}
>
Home
</Link>
<Link
variant="button"
color="textPrimary"
to="/editor"
component={RouterLink}
className={classes.link}
>
Editor
</Link>
<Link
variant="button"
color="textPrimary"
to="/gallery"
component={RouterLink}
className={classes.link}
>
Gallery
</Link>
<Link
variant="button"
color="textPrimary"
to="/projects"
component={RouterLink}
className={classes.link}
>
Projects
</Link>
<Link
variant="button"
color="textPrimary"
to="/simulator/ngspice"
component={RouterLink}
className={classes.link}
>
Simulator
</Link>
<Link
variant="button"
color="textPrimary"
to="/dashboard"
component={RouterLink}
className={classes.link}
>
Dashboard
</Link>
</>)
: (<>
<Link
variant="button"
color="textPrimary"
to="/editor"
component={RouterLink}
style={{ marginRight: '20px' }}
>
Editor
</Link>
<Link
variant="button"
color="textPrimary"
to="/gallery"
component={RouterLink}
style={{ marginRight: '20px' }}
>
Gallery
</Link>
<Link
variant="button"
color="textPrimary"
to="/projects"
component={RouterLink}
className={classes.link}
style={{ marginRight: '20px' }}
>
Projects
</Link>
<Link
variant="button"
color="textPrimary"
to="/simulator/ngspice"
component={RouterLink}
style={{ marginRight: '20px' }}
>
Simulator
</Link>
</>
)
)
}
</nav>
{/* Display login option or user menu as per authenticated status */}
{
(!auth.isAuthenticated ? (<Button
size="small"
component={RouterLink}
to="/login?close=close"
color="primary"
variant="outlined"
target="_blank"
>
Login
</Button>)
: (<>
<IconButton
edge="start"
style={{ marginLeft: 'auto' }}
color="primary"
aria-controls="simple-menu"
aria-haspopup="true"
onClick={handleClick}
>
<Avatar className={classes.purple}>
{auth.user.username.charAt(0).toUpperCase()}
</Avatar>
</IconButton>
<Menu
id="simple-menu"
anchorEl={anchorEl}
keepMounted
open={Boolean(anchorEl)}
onClose={handleClose}
TransitionComponent={Fade}
style={{ marginTop: '25px' }}
>
<MenuItem
component={RouterLink}
to="/dashboard"
onClick={handleClose}
>
<ListItemText primary={auth.user.username} secondary={auth.user.email} />
</MenuItem>
<MenuItem
component={RouterLink}
to="/dashboard/profile"
onClick={handleClose}
>
My Profile
</MenuItem>
<MenuItem
component={RouterLink}
to="/dashboard/schematics"
onClick={handleClose}
>
My Schematics
</MenuItem>
<MenuItem
component={RouterLink}
to="/account/change_password"
onClick={handleClose}
>
Change password
</MenuItem>
<MenuItem onClick={() => {
store.dispatch(logout(history))
}}>
Logout
</MenuItem>
</Menu>
</>
)
)
}
</>
)
}
Example #26
Source File: Experience.js From Portfolio with MIT License | 4 votes |
export default function Experience() {
const classes = useStyles()
const theme = useTheme()
const mdDown = useMediaQuery(theme.breakpoints.down('md'))
const align = mdDown ? "center" : "flex-end"
const textAlign = mdDown ? "center" : "right"
const animRef = useRef(null)
const animate = useAnimate(animRef)
return (
<Grid direction="row" container justify="center" alignItems="center" spacing={10} className={classes.cont}>
<Grid item xs={12} lg={6}>
<Typography variant="h2" gutterBottom align="center">
Experience
</Typography>
<Hidden mdDown>
<Fade in={animate} style={{ transitionDelay: '250ms' }}>
<div>
<Image
alt="Experience"
src="/experience.svg"
width="996.46"
height="828.18"
/>
</div>
</Fade>
</Hidden>
</Grid>
<Grid container item xs={12} lg={6} direction="column" spacing={1} alignItems={align}>
{
Object.getOwnPropertyNames(experience).map((title, id) =>
<Grid item key={id} className={classes.expObj}>
<Typography variant="h4" align={textAlign} gutterBottom component="p">
{title}
</Typography>
<Grid container item direction="row" spacing={1} justify="center">
{
experience[title].map(({
organization,
role,
type,
startDate,
endDate,
city,
state,
country,
url,
thumbnail
}, i) =>
<Grid item xs={12} sm key={i}>
<Fade in={animate} style={{ transitionDelay: `${200 * i}ms` }}>
<Card className={classes.card}>
<CardActionArea
className={classes.cardActionArea}
href={url}
target="_blank"
rel="noopener noreferrer"
>
<CardHeader
avatar={
<Avatar variant="rounded">
<Image
alt={`${organization} logo`}
src={thumbnail}
layout="fill"
/>
</Avatar>
}
title={organization}
subheader={role + " - " + type}
/>
<CardHeader
avatar={<DateRange />}
title={getHumanDiff(startDate, endDate)}
subheader={`${startDate} - ${endDate}`}
className={classes.cardHeader}
/>
<CardHeader
avatar={<LocationCity />}
subheader={`${city}, ${state}, ${country}`}
className={classes.cardHeader}
/>
</CardActionArea>
</Card>
</Fade>
</Grid>
)
}
</Grid>
</Grid>
)
}
</Grid>
<div ref={animRef}></div>
</Grid>
)
}