@material-ui/icons#Check JavaScript Examples

The following examples show how to use @material-ui/icons#Check. 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: App.js    From covid-vaccine-notification-system with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
tableIcons = {
  Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
  Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
  Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
  Delete: forwardRef((props, ref) => <Delete {...props} ref={ref} />),
  DetailPanel: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
  Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />),
  Export: forwardRef((props, ref) => <Save {...props} ref={ref} />),
  Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />),
  FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />),
  LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />),
  NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
  PreviousPage: forwardRef((props, ref) => <ChevronLeft {...props} ref={ref} />),
  ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
  Search: forwardRef((props, ref) => <Search {...props} ref={ref} />),
  SortArrow: forwardRef((props, ref) => <ArrowUpward {...props} ref={ref} />),
  ThirdStateCheck: forwardRef((props, ref) => <Remove {...props} ref={ref} />),
  ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />),
}
Example #2
Source File: Users.js    From InstagramClone with Apache License 2.0 5 votes vote down vote up
export default function Users() {
    const [users, setUsers] = useState([])
    useEffect(() => {
        firebase.firestore()
            .collection("users")

            .onSnapshot((snapshot) => {
                let result = snapshot.docs.map(doc => {
                    const data = doc.data();
                    const id = doc.id;
                    return { id, ...data }
                })
                setUsers(result)
            })
    }, [])
    const history = useHistory();

    const columns = [
        { field: 'id', headerName: 'ID', width: 280 },
        { field: 'name', headerName: 'Name', width: 130 },
        { field: 'username', headerName: 'Username', width: 130 },
        {
            field: 'banned', headerName: 'banned', width: 150,
            renderCell: (params) => (
                <div>
                    {params.value ?
                        <Chip
                            icon={<Check />}
                            label="True"
                            color="primary"
                            variant="outlined"
                        />
                        :
                        <Chip
                            icon={<Clear />}
                            label="False"
                            color="secondary"
                            variant="outlined"
                        />


                    }
                </div>

            ),

        },
        {
            field: 'link', headerName: 'Detail', width: 150,
            renderCell: (params) => (

                <div>
                    <Button variant="contained" color="primary" onClick={() => { history.push({pathname: `/user/${params.row.id}`}) }}>
                        View
                    </Button>
                </div>

            ),

        },
    ];



    return (
        <div style={{ height: 400, width: '100%', marginTop: '100px', backgroundColor: 'white' }}>
            <DataGrid rows={users} columns={columns} pageSize={5} columns={columns.map((column) => ({
                ...column,
                disableClickEventBubbling: true,
            }))} />
        </div>
    )
}
Example #3
Source File: QuizzesSection.js    From Quizzie with MIT License 4 votes vote down vote up
function QuizzesSection(props) {
	const [loading, setLoading] = useState(true);
	const [userType, setUserType] = useState(props.type);
	const [profile, setProfile] = useState(props.profile);
	const [quizzes, setQuizzes] = useState([]);
	const [quizzesEnrolled, setQuizzesEnrolled] = useState([]);

	const [joinModal, setJoinModal] = useState(false);
	const [quizCode, setQuizCode] = useState("");
	const [quizCodeError, setQuizCodeError] = useState(false);

	const [enrollModal, setEnrollModal] = useState(false);
	const [enrollQuizName, setEnrollQuiz] = useState("");
	const [enrollQuizId, setEnrollQuizId] = useState("");

	const [enrollSnack, setEnrollSnack] = useState(false);
	const [snackbar, setSnackBar] = useState(false);
	const [errorSnack, setErrorSnack] = useState(false);

	const [infoModal, setInfoModal] = useState(false);
	const [infoLoading, setInfoLoading] = useState(false);
	const [currQuiz, setCurrQuiz] = useState({});
	const [timeRemain, setTimeRemain] = useState("");

	const [startModal, setStartModal] = useState(false);
	const [quizStarted, setQuizStarted] = useState(false);
	const [redirectId, setRedirectId] = useState("");
	const [quizDetails, setQuizDetails] = useState({});

	const [earlyError, setEarlyError] = useState(false);
	const [lateError, setLateError] = useState(false);
	const [givenSnack, setGivenSnack] = useState(false);
	const [privateWrongCode, setPrivateWrongCode] = useState(false);
	const [alreadyEnrolled, setAlreadyEnrolled] = useState(false);

	const setRefresh = props.refresh;

	const { executeRecaptcha } = useGoogleReCaptcha();

	const getCols = () => {
		if (isWidthUp("md", props.width)) {
			return 3;
		}

		return 2;
	};

	const getInfoWidth = () => {
		if (isWidthUp("sm", props.width)) {
			return "45%";
		}

		return "80%";
	};

	const onCloseHandle = () => {
		setJoinModal(false);
		setInfoModal(false);
		setStartModal(false);

		setQuizCode("");
		setQuizCodeError(false);
		setEnrollModal(false);
		setEnrollQuiz("");
		setEnrollQuizId("");
		setTimeRemain("");
		setCurrQuiz({});
	};

	const onJoinClick = () => {
		setJoinModal(true);
	};

	const handleJoinChange = (event) => {
		setQuizCode(event.target.value);
	};

	const handleEnrollButton = (quiz) => {
		setEnrollQuiz(quiz.quizName);
		setEnrollQuizId(quiz._id);
		setEnrollModal(true);
	};

	const handleInfoButton = (quiz) => {
		setInfoModal(true);
		getQuizInfo(quiz.quizId._id);
	};

	const handleStartButton = (quiz) => {
		setEnrollQuiz(quiz.quizId.quizName);
		setEnrollQuizId(quiz.quizId._id);
		setStartModal(true);
	};

	const getQuizInfo = async (id) => {
		setInfoLoading(true);

		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/quiz/${id}`;

		try {
			await axios
				.get(url, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setCurrQuiz(res.data.result);
					setInfoLoading(false);
				});
		} catch (error) {
			console.log(error);
			onCloseHandle();
			setInfoLoading(false);
		}
	};

	const handleJoinSubmit = async () => {
		if (quizCode.trim().length === 0) {
			setQuizCodeError(true);
			return;
		}
		setQuizCodeError(false);
		setEnrollSnack(true);
		let url = "https://quizzie-api.herokuapp.com/quiz/enrollPrivate";
		let token = localStorage.getItem("authToken");

		let captcha = await executeRecaptcha("join_private");

		let data = {
			quizCode: quizCode,
			captcha: captcha,
		};

		try {
			await axios
				.patch(url, data, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setRefresh(true);
					onCloseHandle();
					setSnackBar(true);
				});
		} catch (error) {
			setEnrollSnack(false);
			if (error.response.status === 404) {
				setPrivateWrongCode(true);
			} else if (error.response.status === 409) {
				setAlreadyEnrolled(true);
			} else {
				setErrorSnack(true);
			}
		}
	};

	const handleEnroll = async () => {
		setEnrollSnack(true);
		let token = localStorage.getItem("authToken");
		let url = "https://quizzie-api.herokuapp.com/quiz/enroll";

		let captcha = await executeRecaptcha("quiz_enroll");

		let data = {
			quizId: enrollQuizId,
			captcha: captcha,
		};

		try {
			await axios
				.patch(url, data, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setRefresh(true);
					onCloseHandle();
					setSnackBar(true);
				});
		} catch (error) {
			console.log(error);
			setErrorSnack(true);
		}
	};

	const handleUnenroll = async () => {
		setEnrollSnack(true);
		let token = localStorage.getItem("authToken");
		let url = "https://quizzie-api.herokuapp.com/quiz/unenroll";

		let captcha = await executeRecaptcha("quiz_unenroll");

		let data = {
			quizId: currQuiz._id,
			captcha: captcha,
		};

		try {
			await axios
				.patch(url, data, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setRefresh(true);
				});
		} catch (error) {
			console.log(error);
			setErrorSnack(true);
		}
	};

	const handleQuizStart = async () => {
		setEnrollSnack(true);
		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/quiz/start`;

		let captcha = await executeRecaptcha("quiz_start");

		let data = {
			quizId: enrollQuizId,
			captcha: captcha,
		};

		try {
			await axios
				.patch(url, data, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setRedirectId(data.quizId);
					setQuizDetails(res.data);
					setQuizStarted(true);
				});
		} catch (error) {
			setEnrollSnack(false);
			if (error.response.status === 401) {
				setEarlyError(true);
			} else if (error.response.status === 402) {
				setLateError(true);
			} else if (error.response.status === 405) {
				setGivenSnack(true);
			}
		}
	};

	const setupEnrolled = () => {
		let quizzes = [];

		profile.quizzesEnrolled.map((quiz) => {
			if (
				!profile.quizzesGiven.find((o) => o.quizId === quiz.quizId._id)
			) {
				quizzes.push(quiz);
			}
		});

		setQuizzesEnrolled(quizzes);
	};

	const getQuizzes = async () => {
		setLoading(true);
		let token = localStorage.getItem("authToken");
		let url = "https://quizzie-api.herokuapp.com/quiz/all";

		let quizList = [];

		try {
			await axios
				.get(url, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					res.data.result.map((quiz) => {
						if (quiz.quizType === "public") {
							if (userType === "user") {
								if (
									!profile.quizzesEnrolled.find(
										(o) => o.quizId._id === quiz._id
									)
								)
									quizList.push(quiz);
							} else quizList.push(quiz);
						}
					});

					quizList.sort(function (a, b) {
						return a.scheduledFor - b.scheduledFor;
					});

					setQuizzes(quizList);
					setLoading(false);
				});
		} catch (error) {
			console.log(error);
		}
	};

	useEffect(() => {
		if (infoModal) {
			if (currQuiz.scheduledFor <= Date.now()) {
				setTimeRemain("Already Started!");
			} else {
				setTimeout(() => {
					setTimeRemain(
						countdown(
							new Date(),
							new Date(Number(currQuiz.scheduledFor))
						).toString()
					);
				}, 1000);
			}
		}
	});

	useEffect(() => {
		if (userType === "user") setupEnrolled();
		getQuizzes();
	}, []);

	if (loading) {
		return <QuizLoading />;
	} else if (quizStarted) {
		return (
			<Redirect
				to={{
					pathname: `/quiz`,
					state: {
						questions: quizDetails.data,
						duration: quizDetails.duration,
						start: quizDetails.scheduledFor,
						id: enrollQuizId,
						timeStarted: Date.now(),
						restartStatus: quizDetails.quizRestart,
					},
				}}
			/>
		);
	} else {
		return (
			<div className="quizzes-section">
				<div className="quiz-btn-section">
					{userType === "user" ? (
						<Button className="join-quiz-btn" onClick={onJoinClick}>
							<Check />
							Join a Quiz
						</Button>
					) : null}
					{userType === "admin" ? (
						<Button
							className="create-quiz-btn"
							component={Link}
							to="/createQuiz"
						>
							<Add />
							Create a quiz
						</Button>
					) : null}
				</div>
				{userType === "user" ? (
					<div className="enrolled-list">
						<Typography variant="h5" className="up-quizzes">
							Enrolled Quizzes
						</Typography>
						{quizzesEnrolled.length === 0 ? (
							<p style={{ textAlign: "center" }}>
								Sorry! No quizzes available at the moment!
							</p>
						) : (
							<div className="quiz-list root1">
								<GridList
									cols={getCols()}
									className="grid-list btn-set"
								>
									{quizzesEnrolled.map((quiz) => (
										<GridListTile
											key={quiz._id}
											className="quiz-tile"
										>
											<img src="../CC LOGO-01.svg" />
											<GridListTileBar
												title={quiz.quizId.quizName}
												actionIcon={
													<div className="inline">
														<Tooltip title="Start Quiz">
															<IconButton
																aria-label={`start ${quiz.quizId.quizName}`}
																onClick={() =>
																	handleStartButton(
																		quiz
																	)
																}
															>
																<PlayCircleFilled className="enroll-icon" />
															</IconButton>
														</Tooltip>
														<Tooltip title="Info">
															<IconButton
																aria-label={`info ${quiz.quizId.quizName}`}
																onClick={() =>
																	handleInfoButton(
																		quiz
																	)
																}
															>
																<Info className="enroll-icon" />
															</IconButton>
														</Tooltip>
													</div>
												}
											/>
										</GridListTile>
									))}
								</GridList>
							</div>
						)}
					</div>
				) : null}
				<Typography variant="h5" className="up-quizzes">
					Upcoming Quizzes
				</Typography>
				{quizzes.length === 0 ? (
					<p style={{ textAlign: "center" }}>
						Sorry! No quizzes available at the moment!
					</p>
				) : (
					<div className="quiz-list root1">
						<GridList cols={getCols()} className="grid-list">
							{quizzes.map((quiz) => (
								<GridListTile
									key={quiz._id}
									className="quiz-tile"
								>
									<img src="../CC LOGO-01.svg" />
									<GridListTileBar
										title={quiz.quizName}
										subtitle={`By: ${quiz.adminId.name}`}
										actionIcon={
											userType === "user" ? (
												<Tooltip title="Enroll">
													<IconButton
														aria-label={`enroll ${quiz.quizName}`}
														onClick={() =>
															handleEnrollButton(
																quiz
															)
														}
													>
														<Check className="enroll-icon" />
													</IconButton>
												</Tooltip>
											) : null
										}
									/>
								</GridListTile>
							))}
						</GridList>
					</div>
				)}
				<Dialog
					open={joinModal}
					onClose={onCloseHandle}
					aria-labelledby="join-quiz-modal"
					PaperProps={{
						style: {
							backgroundColor: "white",
							color: "#333",
							minWidth: "30%",
						},
					}}
					style={{ width: "100%" }}
				>
					<div className="modal-info">
						{userType === "admin" ? (
							<Typography
								variant="h6"
								className="type-head join-sub"
							>
								Organizers cannot enroll in quizzes.
							</Typography>
						) : (
							<div
								style={{
									display: "flex",
									flexDirection: "column",
								}}
							>
								<Typography variant="h5" className="type-head">
									JOIN A PRIVATE QUIZ
								</Typography>
								<Typography
									variant="h6"
									className="type-head join-sub"
								>
									Enter the code of the quiz you want to join
								</Typography>
								<TextInput
									error={quizCodeError}
									helperText={
										quizCodeError ? "Required" : null
									}
									label="Quiz Code"
									variant="outlined"
									value={quizCode}
									onChange={handleJoinChange}
									className="quiz-code-field"
								/>
								<Button
									className="join-quiz-btn join-modal-btn"
									onClick={handleJoinSubmit}
								>
									Join!
								</Button>
							</div>
						)}
					</div>
				</Dialog>
				<Dialog
					open={enrollModal}
					onClose={onCloseHandle}
					aria-labelledby="enroll-quiz-modal"
					PaperProps={{
						style: {
							backgroundColor: "white",
							color: "#333",
							minWidth: "30%",
						},
					}}
					style={{ width: "100%" }}
				>
					<div className="modal-info">
						{userType === "admin" ? (
							<Typography
								variant="h6"
								className="type-head join-sub"
							>
								Organizers cannot enroll in quizzes.
							</Typography>
						) : (
							<div>
								<Typography
									variant="h6"
									className="type-head join-sub"
								>{`Are you sure you want to join ${enrollQuizName}?`}</Typography>
								<div className="btn-div m-top">
									{/* classes in Navbar.css */}
									<Button
										className="logout-btn m-right"
										onClick={handleEnroll}
									>
										Yes
									</Button>
									<Button
										className="cancel-btn m-left"
										onClick={onCloseHandle}
									>
										No
									</Button>
								</div>
							</div>
						)}
					</div>
				</Dialog>
				<Dialog
					open={startModal}
					onClose={onCloseHandle}
					aria-labelledby="start-quiz-modal"
					PaperProps={{
						style: {
							backgroundColor: "white",
							color: "#333",
							minWidth: "30%",
						},
					}}
					style={{ width: "100%" }}
				>
					<div className="modal-info">
						<div>
							<Typography
								variant="h6"
								className="type-head join-sub"
							>{`Are you sure you want to start ${enrollQuizName}?`}</Typography>
							<div className="btn-div m-top2 start-div">
								{/* classes in Navbar.css */}
								<Button
									className="logout-btn m-right"
									onClick={handleQuizStart}
								>
									Yes
								</Button>
								<Button
									className="cancel-btn m-left"
									onClick={onCloseHandle}
								>
									No
								</Button>
							</div>
						</div>
					</div>
				</Dialog>
				<Dialog
					open={infoModal}
					onClose={onCloseHandle}
					aria-labelledby="info-quiz-modal"
					PaperProps={{
						style: {
							backgroundColor: "white",
							color: "#333",
							minWidth: getInfoWidth(),
							maxHeight: "45%",
						},
					}}
					style={{ width: "100%" }}
				>
					<DialogTitle
						style={{ textAlign: "center", fontWeight: "bold" }}
					>
						Quiz Info
					</DialogTitle>

					{/* From the profile section */}
					{infoLoading ? (
						<Loading />
					) : (
						<div
							className="modal-info no-p-top"
							style={{ textAlign: "center" }}
						>
							<Typography
								variant="h6"
								className="profile-param info-param"
							>
								Name:{" "}
								<span className="profile-data">
									{currQuiz.quizName}
								</span>
							</Typography>
							<Typography
								variant="h6"
								className="profile-param info-param"
							>
								Date:{" "}
								<span className="profile-data">
									{new Date(
										Number(currQuiz.scheduledFor)
									).toDateString()}
								</span>
							</Typography>
							<Typography
								variant="h6"
								className="profile-param info-param"
							>
								Time:{" "}
								<span className="profile-data">
									{new Date(
										Number(currQuiz.scheduledFor)
									).toLocaleTimeString()}
								</span>
							</Typography>
							<div className="time-sec">
								<Typography
									variant="h6"
									className="profile-param info-param"
								>
									<span className="profile-data time-rem">
										{timeRemain}
									</span>
								</Typography>
							</div>
							<Button
								className="unenroll-btn"
								onClick={handleUnenroll}
							>
								<Block style={{ color: "white" }} />
								Unenroll
							</Button>
						</div>
					)}
				</Dialog>
				<Snackbar
					open={snackbar}
					autoHideDuration={2000}
					onClose={() => setSnackBar(false)}
				>
					<Alert
						variant="filled"
						severity="success"
						onClose={() => setSnackBar(false)}
					>
						Successfully Enrolled!
					</Alert>
				</Snackbar>
				<Snackbar
					open={errorSnack}
					autoHideDuration={2000}
					onClose={() => setErrorSnack(false)}
				>
					<Alert
						variant="filled"
						severity="error"
						onClose={() => setErrorSnack(false)}
					>
						There was some error. Please try again!
					</Alert>
				</Snackbar>
				<Snackbar
					open={enrollSnack}
					autoHideDuration={5000}
					onClose={() => setEnrollSnack(false)}
				>
					<Alert
						variant="filled"
						severity="info"
						onClose={() => setErrorSnack(false)}
					>
						Processing... Please Wait!
					</Alert>
				</Snackbar>
				<Snackbar
					open={earlyError}
					autoHideDuration={5000}
					onClose={() => setEarlyError(false)}
				>
					<Alert
						variant="filled"
						severity="error"
						onClose={() => setEarlyError(false)}
					>
						The quiz has not yet started!
					</Alert>
				</Snackbar>
				<Snackbar
					open={lateError}
					autoHideDuration={5000}
					onClose={() => setLateError(false)}
				>
					<Alert
						variant="filled"
						severity="error"
						onClose={() => setLateError(false)}
					>
						This quiz has ended!
					</Alert>
				</Snackbar>
				<Snackbar
					open={givenSnack}
					autoHideDuration={5000}
					onClose={() => setGivenSnack(false)}
				>
					<Alert
						variant="filled"
						severity="error"
						onClose={() => setGivenSnack(false)}
					>
						Already given this quiz!
					</Alert>
				</Snackbar>
				<Snackbar
					open={privateWrongCode}
					autoHideDuration={5000}
					onClose={() => setPrivateWrongCode(false)}
				>
					<Alert
						variant="filled"
						severity="error"
						onClose={() => setPrivateWrongCode(false)}
					>
						This quiz code does not exists!
					</Alert>
				</Snackbar>
				<Snackbar
					open={alreadyEnrolled}
					autoHideDuration={5000}
					onClose={() => setAlreadyEnrolled(false)}
				>
					<Alert
						variant="filled"
						severity="error"
						onClose={() => setAlreadyEnrolled(false)}
					>
						Already enrolled in this quiz!
					</Alert>
				</Snackbar>
			</div>
		);
	}
}
Example #4
Source File: ResultPage.js    From Quizzie with MIT License 4 votes vote down vote up
function ResultPage(props) {
	const [quizId, setQuizId] = useState(props.match.params.id);
	const [loading, setLoading] = useState(true);

	const [name, setName] = useState("");
	const [marks, setMarks] = useState(null);
	const [responses, setResponses] = useState([]);


	const resIcon = (response) => {
		if(response.selected === response.correctAnswer) {
			return <Check style={{color: 'green', marginLeft: '3px'}} />
		} else if(response.selected === null) {
			return <Warning style={{color: 'goldenrod', marginLeft: '3px'}} />
		} 
		else {
			return <Close style={{color: 'red', marginLeft: '3px'}} />
		}
	}

	const getDetails = async () => {
		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/quiz/${quizId}`;

		try {
			await axios.get(url, {
				headers: {
					"auth-token": token
				}
			}).then(res => {
				setName(res.data.result.quizName);
			})
		} catch (error) {
			console.log(error);
		}
	}

	const getResponses = async () => {
		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/user/studentQuizResult/${quizId}`;

		try {
			await axios.get(url, {
				headers: {
					"auth-token": token
				}
			}).then(res => {
				setMarks(res.data.result.marks);
				setResponses(res.data.result.responses);
				setLoading(false);
			})
		} catch (error) {
			console.log(error);
		}
	}

	useState(() => {
		getDetails();
		getResponses();
	}, [])

	if (loading) {
		return <Loading />
	}

	return (
		<Container className="result-page">
			<div className="result-head">
				<Typography variant="h4" className="result-title">Results</Typography>
			</div>
			<div className="result-quiz-info">
				<Typography variant="h5"><span className="profile-param">Quiz:</span> <strong>{name}</strong></Typography>
				<Typography variant="h5"><span className="profile-param">Scored:</span> <strong>{marks}</strong> out of <strong>{responses.length}</strong></Typography>
			</div>
			<div className="result-responses">
				<div className="result-response-title">
					<Typography variant="h5">Responses</Typography>
				</div>
				<div className="result-responses-list">
					{responses.map((response) => (
						<ExpansionPanel elevation={3} className="expansion" key={response.quesId}>
							<ExpansionPanelSummary
								className="question-response"
								expandIcon={<ExpandMore />}
								aria-controls="question-content"
								aria-label="Expand"
							>
								<Typography className="question-label">{response.description} {resIcon(response)}</Typography>
							</ExpansionPanelSummary>
							<ExpansionPanelDetails>
								<List component="nav" className="options-display">
									{response.options.map((option) => (
										<ListItem button key={option._id}>
											<ListItemIcon><Adjust style={{ color: response.correctAnswer === option.text ? 'green' : (response.selected === option.text? 'red': 'black') }} /></ListItemIcon>
											<ListItemText style={{ color: response.correctAnswer === option.text ? 'green' : (response.selected === option.text? 'red': 'black') }} primary={option.text} />
										</ListItem>
									))}
								</List>
							</ExpansionPanelDetails>
						</ExpansionPanel>
					))}
				</div>
			</div>
		</Container>
	)
}
Example #5
Source File: StudentResponses.js    From Quizzie with MIT License 4 votes vote down vote up
function StudentResponses(props) {
	const [loading, setLoading] = useState(true);

	const [name, setName] = useState("");
	const [marks, setMarks] = useState(null);
	const [responses, setResponses] = useState([]);
	
	const [redirect, setRedirect] = useState(false);

	let state = null;

	const resIcon = (response) => {
		if(response.selected === response.correctAnswer) {
			return <Check style={{color: 'green', marginLeft: '3px'}} />
		} else if(response.selected === null) {
			return <Warning style={{color: 'goldenrod', marginLeft: '3px'}} />
		} 
		else {
			return <Close style={{color: 'red', marginLeft: '3px'}} />
		}
	}

	const setup = () => {
		setName(state.userId.name);
		setMarks(state.marks);
		setResponses(state.responses);
		setLoading(false);
	}

	
	useState(() => {
		if(props.location.state === undefined) {
			setLoading(false);
			setRedirect(true);
			return;
		}

		state = props.location.state.response;
		setup();
	}, [])

	if (loading) {
		return <Loading />
	} else if(redirect) {
		return <Redirect to="/dashboard" />
	}

	return (
		<Container className="result-page">
			<div className="result-head">
				<Typography variant="h4" className="result-title">Results</Typography>
			</div>
			<div className="result-quiz-info">
				<Typography variant="h5"><span className="profile-param">Quiz:</span> <strong>{name}</strong></Typography>
				<Typography variant="h5"><span className="profile-param">Scored:</span> <strong>{marks}</strong> out of <strong>{responses.length}</strong></Typography>
			</div>
			<div className="result-responses">
				<div className="result-response-title">
					<Typography variant="h5">Responses</Typography>
				</div>
				<div className="result-responses-list">
					{responses.map((response) => (
						<ExpansionPanel elevation={3} className="expansion" key={response.quesId}>
							<ExpansionPanelSummary
								className="question-response"
								expandIcon={<ExpandMore />}
								aria-controls="question-content"
								aria-label="Expand"
							>
								<Typography className="question-label">{response.description} {resIcon(response)}</Typography>
							</ExpansionPanelSummary>
							<ExpansionPanelDetails>
								<List component="nav" className="options-display">
									{response.options.map((option) => (
										<ListItem button key={option._id}>
											<ListItemIcon><Adjust style={{ color: response.correctAnswer === option.text ? 'green' : (response.selected === option.text? 'red': 'black') }} /></ListItemIcon>
											<ListItemText style={{ color: response.correctAnswer === option.text ? 'green' : (response.selected === option.text? 'red': 'black') }} primary={option.text} />
										</ListItem>
									))}
								</List>
							</ExpansionPanelDetails>
						</ExpansionPanel>
					))}
				</div>
			</div>
		</Container>
	)
}
Example #6
Source File: AgentsTable.js    From voicemail-for-amazon-connect with Apache License 2.0 4 votes vote down vote up
render() {
        let classes = this.props.classes;
        return (
            <div className={this.props.className}>
                <Paper className={classes.root}>
                    <div className={classes.topBar}>
                        <Grid container justify={"space-between"} alignItems={"flex-end"} direction={"row"}>
                            <Grid item className={classes.searchBox}>
                                <SearchTextField
                                    ref={(c) => this.searchTextField = c }
                                    showClearButton={this.props.searchFilter !== ""}
                                    searchChangeFunc={this.handleSearchChange}/>
                            </Grid>
                            <Grid item>
                                <Button color="secondary" className={classes.syncButton} onClick={() => this.setState({syncOpen: true})}>
                                    Sync Agents
                                </Button>
                                <AsyncButton loading={this.props.loading} color={"primary"} onClick={() => {
                                    this.props.getAgents();
                                    if (this.searchTextField) {
                                        this.searchTextField.updateSearch("")
                                    }
                                }} >Refresh</AsyncButton>
                            </Grid>
                        </Grid>
                    </div>
                    <Dialog
                        open={this.state.syncOpen}
                        onClose={() => this.setState({syncOpen: false})}
                        aria-labelledby="alert-dialog-title"
                        aria-describedby="alert-dialog-description"
                    >
                        <DialogTitle id="alert-dialog-title">Sync Amazon Connect Agents?</DialogTitle>
                        <DialogContent>
                            <DialogContentText id="alert-dialog-description">
                                This process will sync all users in Amazon Connect to the VM portal.
                            </DialogContentText>
                        </DialogContent>
                        <DialogActions>
                            <Button onClick={() => this.setState({syncOpen: false})} color="primary">
                                Cancel
                            </Button>
                            <Button onClick={this.handleSync} color="primary" autoFocus>
                                Sync
                            </Button>
                        </DialogActions>
                    </Dialog>

                    <Table className={classes.table} stickyHeader aria-label="sticky table" size="small">
                        <TableHead>
                            <TableRow>
                                {headerCells.map(headerCell => (
                                    <TableCell className={classes.tableCell}
                                        key={headerCell.id}
                                        align={headerCell.numeric ? 'right' : 'left'}
                                        padding={headerCell.disablePadding ? 'none' : 'default'}>
                                        <TableSortLabel
                                            onClick={() => this.sortBy(headerCell.id)}
                                            key={headerCell.id}
                                            hideSortIcon={!headerCell.sortable}
                                            active={this.props.sortKey === headerCell.id}
                                            direction={this.props.sortOrder}
                                            IconComponent={ArrowDropDown}>
                                            {headerCell.label}
                                        </TableSortLabel>
                                    </TableCell>
                                ))}
                            </TableRow>
                        </TableHead>
                        <TableBody>
                            {this.props.agents.map(agent => (
                                <TableRow key={agent.userId} hover onClick={() => {this.showAgent(agent)}}>
                                    <TableCell align="left">{agent.username}</TableCell>
                                    <TableCell align="left">{agent.extension}</TableCell>
                                    <TableCell align="left">{
                                        this.props.encryptVoicemail ?
                                            <Check fontSize="inherit"/> : 
                                                ( agent.encryptVoicemail ? 
                                                    <Check fontSize="inherit"/> : null ) }
                                    </TableCell>
                                    <TableCell align="left">{
                                        agent.transcribeVoicemail ?
                                            <Check className={this.props.transcribeVoicemail ? null : classes.checkDisable} fontSize="inherit"/> :
                                            null}
                                    </TableCell>
                                    <TableCell align="left">
                                        <span
                                            className={classes.delivery}>{agent.deliverEmail ? "Email" : ""}</span>
                                        <span
                                            className={classes.delivery}>{agent.deliverSMS ? `SMS: ${agent.deliverSMSPhoneNumber}` : ""}</span>
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>

                    <div className={classes.navigationBar}>
                        <Button disabled={this.props.page.prev.length === 0} onClick={() => {
                            this.props.getAgents(this.props.page.prev[this.props.page.prev.length - 1]);
                        }}><KeyboardArrowLeft className={classes.navButton}/></Button>
                        <Button disabled={this.props.page.next.length === 0} onClick={() => {
                            this.props.getAgents(this.props.page.next[0]);
                        }}><KeyboardArrowRight className={classes.navButton}/></Button>
                    </div>
                </Paper>
            </div>
        )
    }
Example #7
Source File: SelectStep.js    From web-wallet with Apache License 2.0 4 votes vote down vote up
function SelectStep ({
  setSelectedUTXO,
  selectedUTXO,
  handleClose,
  setStep,
  gasPrice,
  setGasPrice,
  selectedSpeed,
  setSelectedSpeed
}) {
  const dispatch = useDispatch();

  const [ utxos, setUtxos ] = useState([]);
  const [ searchUTXO, setSearchUTXO ] = useState('');

  const submitLoading = useSelector(selectLoading([
    `QUEUE/GET_${selectedUTXO ? selectedUTXO.currency : ''}`,
    'EXIT/CREATE'
  ]));

  useEffect(() => {
    async function fetchUTXOS () {
      const _utxos = await networkService.getUtxos();
      const utxos = orderBy(_utxos, i => i.currency, 'desc');
      setUtxos(utxos);
    }
    fetchUTXOS();
  }, []);

  async function doCheckExitQueue () {
    const res = await dispatch(checkForExitQueue(selectedUTXO.currency));
    if (!res) {
      return setStep(2);
    }
    return doExit();
  }

  async function doExit () {
    const res = await dispatch(exitUtxo(selectedUTXO, gasPrice));
    if (res) {
      dispatch(openAlert('Exit submitted. You will be blocked from making further transactions until the exit is confirmed.'));
      handleClose();
    }
  }

  const _utxos = useMemo(() => {
    return utxos.filter(i => {
      return i.currency.toLowerCase().includes(searchUTXO.toLowerCase()) ||
        i.tokenInfo.name.toLowerCase().includes(searchUTXO.toLowerCase());
    }).filter(i => !!i);
  }, [ utxos, searchUTXO ]);

  function closeModal () {
    setSearchUTXO('');
    setSelectedSpeed('normal');
    handleClose();
  }

  return (
    <>
      <h2>Start Standard Exit</h2>

      <Input
        label='Select a UTXO to exit from the OMG Network'
        icon
        placeholder='Search by token'
        value={searchUTXO}
        onChange={i => setSearchUTXO(i.target.value)}
      />

      <div className={styles.list}>
        {!utxos.length && (
          <div className={styles.disclaimer}>You do not have any UTXOs on the OMG Network.</div>
        )}
        {_utxos.map((i, index) => {
          return (
            <div
              key={index}
              onClick={() => setSelectedUTXO(i)}
              className={[
                styles.utxo,
                selectedUTXO === i ? styles.selected : ''
              ].join(' ')}
            >
              <div className={styles.title}>
                {i.tokenInfo.name}
              </div>

              <div className={styles.value}>
                <div className={styles.amount}>
                  {logAmount(i.amount.toString(), i.tokenInfo.decimals)}
                </div>

                <div className={styles.check}>
                  {selectedUTXO === i && <Check />}
                </div>
              </div>
            </div>
          );
        })}
      </div>

      <GasPicker
        selectedSpeed={selectedSpeed}
        setSelectedSpeed={setSelectedSpeed}
        setGasPrice={setGasPrice}
      />

      <div className={styles.buttons}>
        <Button
          onClick={closeModal}
          type='outline'
          style={{ flex: 0 }}
        >
          CANCEL
        </Button>
        <Button
          onClick={doCheckExitQueue}
          type='primary'
          style={{ flex: 0 }}
          loading={submitLoading}
          tooltip='Your exit transaction is still pending. Please wait for confirmation.'
          disabled={!selectedUTXO}
        >
          SUBMIT EXIT
        </Button>
      </div>
    </>
  );
}
Example #8
Source File: MergeModal.js    From web-wallet with Apache License 2.0 4 votes vote down vote up
function MergeModal ({ open }) {
  const dispatch = useDispatch();

  const [ selectedUTXOs, setSelectedUTXOs ] = useState([]);
  const [ searchUTXO, setSearchUTXO ] = useState('');
  const [ utxos, setUtxos ] = useState([]);
  const [ ledgerModal, setLedgerModal ] = useState(false);
  const [ typedData, setTypedData ] = useState({});

  const loading = useSelector(selectLoading([ 'TRANSFER/CREATE' ]));
  const ledgerConnect = useSelector(selectLedger);

  useEffect(() => {
    async function fetchUTXOS () {
      const _utxos = await networkService.getUtxos();
      const utxos = orderBy(_utxos, i => i.currency, 'desc');
      setUtxos(utxos);
    }
    if (open) {
      fetchUTXOS();
    }
  }, [ open ]);

  useEffect(() => {
    if (selectedUTXOs.length) {
      setSearchUTXO(selectedUTXOs[0].currency);
      const { typedData } = networkService.getMergeTypedData(selectedUTXOs);
      setTypedData(typedData);
    }
    if (!selectedUTXOs.length) {
      setSearchUTXO('');
    }
  }, [ selectedUTXOs ]);

  async function submit ({ useLedgerSign }) {
    if (selectedUTXOs.length > 1 && selectedUTXOs.length < 5) {
      const res = await dispatch(mergeUtxos(useLedgerSign, selectedUTXOs));
      if (res) {
        dispatch(setActiveHistoryTab('Transactions'));
        dispatch(openAlert('Merge submitted. You will be blocked from making further transactions until the merge is confirmed.'));
        handleClose();
      }
    }
  }

  function handleClose () {
    setSelectedUTXOs([]);
    setSearchUTXO('');
    setLedgerModal(false);
    dispatch(closeModal('mergeModal'));
  }

  function handleUtxoClick (utxo) {
    const isSelected = selectedUTXOs.some(i => i.utxo_pos === utxo.utxo_pos);
    if (isSelected) {
      setSelectedUTXOs(selectedUTXOs.filter(i => i.utxo_pos !== utxo.utxo_pos));
    }
    if (!isSelected && selectedUTXOs.length < 4) {
      setSelectedUTXOs([ ...selectedUTXOs, utxo ]);
    }
  }

  function renderMergeScreen () {
    const _utxos = utxos
      .filter(i => i.currency.includes(searchUTXO))
      .filter(i => i);

    return (
      <>
        <h2>Merge UTXOs</h2>
        <div className={styles.disclaimer}>Select the UTXOs you want to merge</div>

        <div className={styles.list}>
          {!utxos.length && (
            <div className={styles.disclaimer}>You do not have any UTXOs on the OMG Network.</div>
          )}
          {_utxos.map((i, index) => {
            const selected = selectedUTXOs.some(selected => selected.utxo_pos === i.utxo_pos);
            return (
              <div
                key={index}
                onClick={() => handleUtxoClick(i)}
                className={[
                  styles.utxo,
                  selected ? styles.selected : ''
                ].join(' ')}
              >
                <div className={styles.title}>
                  {i.tokenInfo.name}
                </div>

                <div className={styles.value}>
                  <div className={styles.amount}>
                    {logAmount(i.amount.toString(), i.tokenInfo.decimals)}
                  </div>

                  <div className={styles.check}>
                    {selected && <Check />}
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        <div className={styles.disclaimer}>You can select a maximum of 4 UTXOs to merge at once.</div>

        <div className={styles.buttons}>
          <Button
            onClick={handleClose}
            type='outline'
            className={styles.button}
          >
            CANCEL
          </Button>
          {ledgerConnect ? (
            <Button
              onClick={() => setLedgerModal(true)}
              type='primary'
              className={styles.button}
              loading={loading}
              tooltip='Your merge transaction is still pending. Please wait for confirmation.'
              disabled={selectedUTXOs.length <= 1 || selectedUTXOs.length > 4}
            >
            MERGE WITH LEDGER
            </Button>) : (
            <Button
              onClick={submit}
              type='primary'
              className={styles.button}
              loading={loading}
              tooltip='Your merge transaction is still pending. Please wait for confirmation.'
              disabled={selectedUTXOs.length <= 1 || selectedUTXOs.length > 4}
            >
            MERGE
            </Button>)}
        </div>
      </>
    );
  }

  return (
    <Modal open={open}>
      {!ledgerModal && renderMergeScreen()}
      {ledgerModal && (
        <LedgerPrompt
          loading={loading}
          submit={submit}
          handleClose={handleClose}
          typedData={typedData}
        />
      )}
    </Modal>
  );
}
Example #9
Source File: TransferModal.js    From web-wallet with Apache License 2.0 4 votes vote down vote up
function TransferModal ({ open }) {
  const dispatch = useDispatch();

  const [ currency, setCurrency ] = useState('');
  const [ value, setValue ] = useState('');
  const [ feeToken, setFeeToken ] = useState('');
  const [ recipient, setRecipient ] = useState('');
  const [ metadata, setMetadata ] = useState('');
  const [ usableFees, setUsableFees ] = useState([]);
  const [ ledgerModal, setLedgerModal ] = useState(false);
  const [ typedData, setTypedData ] = useState({});

  const [ utxoPicker, setUtxoPicker ] = useState(false);
  const [ utxos, setUtxos ] = useState([]);
  const [ selectedUtxos, setSelectedUtxos ] = useState([]);
  const [ selectedFeeUtxos, setSelectedFeeUtxos ] = useState([]);

  const balances = useSelector(selectChildchainBalance, isEqual);
  const fees = useSelector(selectFees, isEqual);
  const ledgerConnect = useSelector(selectLedger);

  const feesLoading = useSelector(selectLoading([ 'FEE/GET' ]));
  const loading = useSelector(selectLoading([ 'TRANSFER/CREATE' ]));

  useEffect(() => {
    async function fetchUTXOS () {
      const _utxos = await networkService.getUtxos();
      const utxos = orderBy(_utxos, i => i.currency, 'desc');
      setUtxos(utxos);
    }
    if (open) {
      fetchUTXOS();
    }
  }, [ open ]);

  useEffect(() => {
    if (Object.keys(fees).length) {
      const usableFees = balances.filter(balance => {
        const feeObject = fees[balance.currency];
        if (feeObject) {
          if (new BN(balance.amount).gte(new BN(feeObject.amount))) {
            return true;
          }
        }
        return false;
      }).map(i => {
        const feeObject = fees[i.currency];
        const feeAmount = new BN(feeObject.amount).div(new BN(feeObject.subunit_to_unit));
        return {
          title: i.name,
          value: i.currency,
          subTitle: `Fee Amount: ${feeAmount.toFixed()}`
        };
      });
      setUsableFees(usableFees);
    }
  }, [ balances, fees, open ]);

  useEffect(() => {
    if (balances.length && !currency) {
      setCurrency(balances[0].currency);
    }
  }, [ balances, currency, open ]);

  useEffect(() => {
    if (usableFees.length && !feeToken) {
      setFeeToken(usableFees[0].value);
    }
  }, [ usableFees, feeToken ]);

  const selectOptions = balances.map(i => ({
    title: i.name,
    value: i.currency,
    subTitle: `Balance: ${logAmount(i.amount, i.decimals)}`
  }));

  async function submit ({ useLedgerSign }) {
    if (
      value > 0 &&
      currency &&
      feeToken &&
      recipient
    ) {
      try {
        const valueTokenInfo = await getToken(currency);
        const { txBody, typedData } = await dispatch(getTransferTypedData({
          utxos: [ ...selectedUtxos, ...selectedFeeUtxos ],
          recipient,
          value: powAmount(value, valueTokenInfo.decimals),
          currency,
          feeToken,
          metadata
        }));
        setTypedData(typedData);
        const res = await dispatch(transfer({
          useLedgerSign,
          txBody,
          typedData
        }));
        if (res) {
          dispatch(setActiveHistoryTab('Transactions'));
          dispatch(openAlert('Transfer submitted. You will be blocked from making further transactions until the transfer is confirmed.'));
          handleClose();
        }
      } catch (err) {
        //
      }
    }
  }

  function handleClose () {
    setCurrency('');
    setValue('');
    setFeeToken('');
    setRecipient('');
    setSelectedUtxos([]);
    setUtxos([]);
    setUtxoPicker(false);
    setMetadata('');
    setLedgerModal(false);
    dispatch(closeModal('transferModal'));
  }

  const disabledTransfer = value <= 0 ||
    !currency ||
    !feeToken ||
    !recipient ||
    new BN(value).gt(new BN(getMaxTransferValue()));

  function getMaxTransferValue () {
    const transferingBalanceObject = balances.find(i => i.currency.toLowerCase() === currency.toLowerCase());
    if (!transferingBalanceObject) {
      return;
    }
    if (currency.toLowerCase() === feeToken.toLowerCase()) {
      const availableAmount = new BN(transferingBalanceObject.amount).minus(new BN(fees[feeToken.toLowerCase()].amount));
      return logAmount(availableAmount, transferingBalanceObject.decimals);
    }
    return logAmount(transferingBalanceObject.amount, transferingBalanceObject.decimals);
  }

  function handleUtxoClick (utxo) {
    const isSelected = selectedUtxos.some(i => i.utxo_pos === utxo.utxo_pos);
    if (isSelected) {
      return setSelectedUtxos(selectedUtxos.filter(i => i.utxo_pos !== utxo.utxo_pos));
    }
    if ((selectedUtxos.length + selectedFeeUtxos.length) < 4) {
      return setSelectedUtxos([ ...selectedUtxos, utxo ]);
    }
  }

  function handleFeeUtxoClick (utxo) {
    const isSelected = selectedFeeUtxos.some(i => i.utxo_pos === utxo.utxo_pos);
    if (isSelected) {
      return setSelectedFeeUtxos(selectedFeeUtxos.filter(i => i.utxo_pos !== utxo.utxo_pos));
    }
    if ((selectedUtxos.length + selectedFeeUtxos.length) < 4) {
      return setSelectedFeeUtxos([ ...selectedFeeUtxos, utxo ]);
    }
  }

  function handleUtxoPickerBack () {
    setSelectedUtxos([]);
    setSelectedFeeUtxos([]);
    setUtxoPicker(false);
  }

  function renderUtxoPicker () {
    const currencyUtxos = utxos
      .filter(i => i.currency.toLowerCase() === currency.toLowerCase())
      .filter(i => !!i);

    const feeUtxos = utxos
      .filter(i => i.currency.toLowerCase() === feeToken.toLowerCase())
      .filter(i => !!i);

    const selectedCurrencyAmount = selectedUtxos.reduce((acc, cur) => {
      return acc.plus(new BN(cur.amount.toString()));
    }, new BN(0));

    const selectedFeeAmount = selectedFeeUtxos.reduce((acc, cur) => {
      return acc.plus(new BN(cur.amount.toString()));
    }, new BN(0));

    const currencyObject = balances.find(i => i.currency.toLowerCase() === currency.toLowerCase());
    const currencyCoverAmount = new BN(powAmount(value.toString(), currencyObject.decimals));

    const feeObject = fees[feeToken.toLowerCase()];
    const feeCoverAmount = new BN(feeObject.amount.toString());

    const sameCurrency = feeToken.toLowerCase() === currency.toLowerCase();
    const utxoPickerDisabled = sameCurrency
      ? currencyCoverAmount.plus(feeCoverAmount).gt(selectedCurrencyAmount)
      : currencyCoverAmount.gt(selectedCurrencyAmount) || feeCoverAmount.gt(selectedFeeAmount);

    function renderCurrencyPick () {
      const enough = sameCurrency
        ? currencyCoverAmount.plus(feeCoverAmount).lte(selectedCurrencyAmount)
        : currencyCoverAmount.lte(selectedCurrencyAmount);

      return (
        <>
          <div className={styles.description}>
            Transfer amount to cover: {sameCurrency
              ? logAmount(currencyCoverAmount.plus(feeCoverAmount), currencyObject.decimals)
              : logAmount(currencyCoverAmount, currencyObject.decimals)}
          </div>

          <div className={[ styles.list, !sameCurrency ? styles.doubleList : '' ].join(' ')}>
            {!currencyUtxos.length && (
              <div className={styles.disclaimer}>You do not have any UTXOs for this token on the OMG Network.</div>
            )}
            {currencyUtxos.map((i, index) => {
              const selected = selectedUtxos.some(selected => selected.utxo_pos === i.utxo_pos);
              return (
                <div
                  key={index}
                  onClick={() => {
                    if (!enough || selected) {
                      handleUtxoClick(i);
                    }
                  }}
                  className={[
                    styles.utxo,
                    selected ? styles.selected : ''
                  ].join(' ')}
                >
                  <div className={styles.title}>
                    {i.tokenInfo.name}
                  </div>

                  <div className={styles.value}>
                    <div className={styles.amount}>
                      {logAmount(i.amount.toString(), i.tokenInfo.decimals)}
                    </div>

                    <div className={styles.check}>
                      {selected && <Check />}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </>
      );
    }

    function renderFeePick () {
      const logFeeAmount = new BN(feeObject.amount.toString()).div(new BN(feeObject.subunit_to_unit.toString()));
      const enough = selectedFeeAmount.gte(feeCoverAmount);
      return (
        <>
          <div className={styles.description}>
            Fee amount to cover: {logFeeAmount.toFixed()}
          </div>

          <div className={[ styles.list, !sameCurrency ? styles.doubleList : '' ].join(' ')}>
            {!feeUtxos.length && (
              <div className={styles.disclaimer}>You do not have any fee UTXOs on the OMG Network.</div>
            )}
            {feeUtxos.map((i, index) => {
              const selected = selectedFeeUtxos.some(selected => selected.utxo_pos === i.utxo_pos);
              return (
                <div
                  key={index}
                  onClick={() => {
                    if (!enough || selected) {
                      handleFeeUtxoClick(i);
                    }
                  }}
                  className={[
                    styles.utxo,
                    selected ? styles.selected : ''
                  ].join(' ')}
                >
                  <div className={styles.title}>
                    {i.tokenInfo.name}
                  </div>

                  <div className={styles.value}>
                    <div className={styles.amount}>
                      {logAmount(i.amount.toString(), i.tokenInfo.decimals)}
                    </div>

                    <div className={styles.check}>
                      {selected && <Check />}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </>
      );
    }

    return (
      <>
        <h2>Select UTXOs</h2>
        <div className={styles.description}>
          By default, this wallet will automatically pick UTXOs to cover your transaction amount. However, if you are a more advanced user, you can pick the UTXOs you would like to spend in this transaction manually.
        </div>

        {renderCurrencyPick()}
        {!sameCurrency && renderFeePick()}

        <div className={styles.disclaimer}>You can select a maximum of 4 UTXOs.</div>

        <div className={styles.buttons}>
          <Button
            onClick={handleUtxoPickerBack}
            type='outline'
            className={styles.button}
          >
            USE DEFAULT
          </Button>

          <Button
            className={styles.button}
            onClick={() => setUtxoPicker(false)}
            type='primary'
            disabled={utxoPickerDisabled}
          >
            SELECT UTXOS
          </Button>
        </div>
      </>
    );
  }

  function renderTransferScreen () {
    return (
      <>
        <h2>Transfer</h2>
        <div className={styles.address}>
          {`From address : ${networkService.account}`}
        </div>

        <Input
          label='To Address'
          placeholder='Hash or ENS name'
          paste
          value={recipient}
          onChange={i => setRecipient(i.target.value)}
        />

        <InputSelect
          label='Amount to transfer'
          placeholder={0}
          value={value}
          onChange={i => {
            setValue(i.target.value);
            setSelectedUtxos([]);
            setSelectedFeeUtxos([]);
          }}
          selectOptions={selectOptions}
          onSelect={i => {
            setCurrency(i.target.value);
            setSelectedUtxos([]);
            setSelectedFeeUtxos([]);
          }}
          selectValue={currency}
          maxValue={getMaxTransferValue()}
        />

        {value > 0 && (
          <div
            className={styles.utxoPickLink}
            onClick={() => setUtxoPicker(true)}
          >
            {selectedUtxos.length ? 'Change Selected UTXOs' : 'Advanced UTXO Select'}
          </div>
        )}

        <Select
          loading={feesLoading}
          label='Fee'
          value={feeToken}
          options={usableFees}
          onSelect={i => {
            setFeeToken(i.target.value);
            setSelectedUtxos([]);
            setSelectedFeeUtxos([]);
          }}
          error="No balance to pay fees"
        />

        <Input
          label='Message'
          placeholder='-'
          value={metadata}
          onChange={i => setMetadata(i.target.value || '')}
        />

        <div className={styles.buttons}>
          <Button
            onClick={handleClose}
            type='outline'
            className={styles.button}
          >
            CANCEL
          </Button>

          <Button
            className={styles.button}
            onClick={() => {
              ledgerConnect
                ? setLedgerModal(true)
                : submit({ useLedgerSign: false });
            }}
            type='primary'
            loading={loading}
            tooltip='Your transfer transaction is still pending. Please wait for confirmation.'
            disabled={disabledTransfer}
          >
            {ledgerConnect ? 'TRANSFER WITH LEDGER' : 'TRANSFER'}
          </Button>
        </div>
      </>
    );
  }

  return (
    <Modal open={open}>
      {!ledgerModal && !utxoPicker && renderTransferScreen()}
      {!ledgerModal && utxoPicker && renderUtxoPicker()}
      {ledgerModal && (
        <LedgerPrompt
          loading={loading}
          submit={submit}
          handleClose={handleClose}
          typedData={typedData}
        />
      )}
    </Modal>
  );
}
Example #10
Source File: ModalForm.js    From checkmynft with MIT License 4 votes vote down vote up
export default function ModalForm(props) {
  let {
    classes,
    open,
    setOpen,
    nftInfo,
    arweaveMetadataUploadedURL,
    arweaveImageUploadedURL,
  } = props.componentProps;

  return (
    <Modal
      open={open}
      onClose={setOpen}
      BackdropComponent={Backdrop}
      className={classes.modal}
    >
      <Fade in={open}>
        {arweaveImageUploadedURL === "" || arweaveMetadataUploadedURL === "" ? (
          <div className={classes.paper}>
            <div
              style={{
                fontFamily: "Poppins",
                fontSize: "20px",
                fontWeight: 600,
                textAlign: "center",
                marginBottom: "40px",
              }}
            >
              Hang tight!
            </div>
            <div style={{ display: "flex", justifyContent: "center" }}>
              <CircularProgress size={60} style={{ color: "#9856EC" }} />
            </div>
            <div
              style={{
                fontFamily: "Poppins",
                fontSize: "16px",
                fontWeight: 400,
                textAlign: "center",
                maxWidth: "470px",
                marginTop: "40px",
              }}
            >
              Your NFT is being uploaded to the permaweb!
              <div>
                Token metadata:{" "}
                {arweaveMetadataUploadedURL !== "" ? (
                  <Check style={{ color: "green" }} />
                ) : (
                  "Uploading..."
                )}{" "}
              </div>
              <div>
                Token Image:{" "}
                {arweaveImageUploadedURL !== "" ? (
                  <Check style={{ color: "green" }} />
                ) : (
                  "Uploading..."
                )}{" "}
              </div>
              <br />
              Just a few seconds left until immortality ?
            </div>
            <br />
          </div>
        ) : (
          <div className={classes.paper}>
            <div
              style={{
                fontFamily: "Poppins",
                fontSize: "24px",
                fontWeight: 600,
                textAlign: "center",
                marginBottom: "40px",
                color: "#16CA48",
              }}
            >
              Success! ?
            </div>
            <div
              style={{
                fontFamily: "Poppins",
                fontSize: "16px",
                fontWeight: 400,
                textAlign: "center",
                maxWidth: "470px",
                marginTop: "40px",
              }}
            >
              Your NFT has been saved on Arweave! You just ensured the longevity
              of your artwork. Great job!
            </div>
            <div
              style={{
                display: "flex",
                justifyContent: "center",
                marginTop: "20px",
              }}
            >
              <img src={arweaveDeployment} alt="Deployment" />
            </div>
            <div
              style={{
                fontFamily: "Poppins",
                fontSize: "16px",
                fontWeight: 400,
                textAlign: "center",
                maxWidth: "470px",
                marginTop: "40px",
                color: "rgba(0, 0, 0, 0.25)",
              }}
            >
              Arweave Metadata TX ID:{" "}
              <a
                href={arweaveMetadataUploadedURL}
                alt="metadata"
                target="_blank"
                rel="noreferrer"
              >
                {arweaveMetadataUploadedURL === ""
                  ? ""
                  : arweaveMetadataUploadedURL.replace(
                      arweaveEndpoint + "/",
                      ""
                    )}
              </a>
              <br />
              Arweave Image TX ID:{" "}
              <a
                href={arweaveImageUploadedURL}
                alt="Image URL"
                target="_blank"
                rel="noreferrer"
              >
                {arweaveImageUploadedURL === ""
                  ? ""
                  : arweaveImageUploadedURL.replace(arweaveEndpoint + "/", "")}
              </a>
            </div>

            <div
              style={{
                fontFamily: "Poppins",
                fontSize: "16px",
                fontWeight: 400,
                textAlign: "center",
                maxWidth: "470px",
                marginTop: "40px",
              }}
            >
              Share the news to help other artists and collectors learn about
              this service!
            </div>

            <a
              onClick={() => setOpen(false)}
              style={{
                textTransform: "none",
                textDecoration: "none",
              }}
              target="_blank"
              rel="noreferrer"
              href={createTweet(nftInfo.address, nftInfo.tokenID)}
            >
              <Button
                variant="contained"
                className={classes.button}
                fullWidth
                style={{
                  background: "rgba(29, 161, 242, 1)",
                  color: "#FFFFFF",
                  fontFamily: "Helvetica",
                  fontWeight: 700,
                  textTransform: "none",
                  fontSize: "21px",
                  marginTop: "20px",
                  height: "56px",
                }}
              >
                Tweet
              </Button>
            </a>
          </div>
        )}
      </Fade>
    </Modal>
  );
}