react-bootstrap#Spinner JavaScript Examples

The following examples show how to use react-bootstrap#Spinner. 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: Loader.js    From mern_library_nginx with MIT License 6 votes vote down vote up
Loader = () => {
   return (
      <Spinner
         animation="border"
         role="status"
         style={{
            width: "200px",
            height: "200px",
            margin: "auto",
            display: "block",
         }}
      >
         <span className="sr-only">Loading....</span>
      </Spinner>
   );
}
Example #2
Source File: with-loading.js    From what-front with MIT License 6 votes vote down vote up
WithLoading = ({
  isLoading,
  children,
  className,
  animation,
  variant,
}) => (isLoading
  ? (
    <Spinner
      animation={animation}
      variant={variant}
      className={classNames(className, { [styles.default]: !variant })}
    />
  ) : children
)
Example #3
Source File: SpinnerCentered.js    From serverless-media-portal with MIT License 6 votes vote down vote up
export default function SpinnerCentered() {
	return (
		<div style={{display: "flex", justifyContent: "center", alignItems: "center", height: "100vh"}}>
			<Spinner
				animation="border"
				role="status"
			/>
		</div>
	);
}
Example #4
Source File: Spinner.js    From tclone with MIT License 6 votes vote down vote up
export default function (color) {
    return (
        <Col className="d-flex justify-content-center py-5">
            <Spinner variant="primary" animation="border" role="status">
                <span className="sr-only">Loading...</span>
            </Spinner>
        </Col>
    )
}
Example #5
Source File: index.js    From Webiu with MIT License 6 votes vote down vote up
Spinners = ({ spinner, animation, variant, size, image, icon }) => {

  return (
    <div className="spinner-component">
        {image ? 
          <div>
            <img src={image} alt="logo" className="preloader img-fluid" />
          </div>
         : null}
        {icon ? 
           <div className="loader">
             <FontAwesomeIcon className="center" icon={faSpinner} />
           </div>
         : null}
        {spinner ? 
           <Spinner className="bootstrap-spinner" animation={animation} variant={variant} size={size} /> 
        : null}
    </div>
  )
}
Example #6
Source File: show.js    From RC4Community with Apache License 2.0 5 votes vote down vote up
function RCform({ formId, fw }) {
  const { form, isLoading, isError } = getFormData(formId);

  if (isLoading) return <Spinner />;
  if (isError) return <Error />;

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log("form submitted", e);
  };

  return (
    <Card style={{ width: fw }} className={styles.showCard}>
      <Card.Title className={styles.showTitle}>{form.title}</Card.Title>
      <Card.Body>
        <Form onSubmit={handleSubmit}>
          {form.data?.attributes.formQs.map((ele, i) => (
            <Form.Group key={i} className="mb-3" controlId="formBasicEmail">
              <Form.Label>{ele.value}</Form.Label>
              {ele.type == "number" ? (
                <>
                  <Form.Control
                    key={i}
                    type={ele.type}
                    min={ele.min}
                    max={ele.max}
                    placeholder=""
                    required={ele.required}
                  />
                  <Form.Text className="text-muted">
                    * Value must be in range {ele.min} - {ele.max}
                  </Form.Text>
                </>
              ) : (
                <Form.Control
                  key={i}
                  type={ele.type}
                  placeholder=""
                  required={ele.required}
                />
              )}

              {ele.type == "number"}
            </Form.Group>
          ))}
          <Button variant="primary" o type="submit">
            Submit
          </Button>
        </Form>
      </Card.Body>
    </Card>
  );
}
Example #7
Source File: ipfs.js    From RC4Community with Apache License 2.0 5 votes vote down vote up
IpfsAdder = ({ showText }) => {
  const [fileUrl, updateFileUrl] = useState(``);
  const [cid, setCID] = useState("");
  const [adding, setAdding] = useState(false);

  const hiddenInput = useRef(null);

  const getIPFS = async (e) => {
    try {
      setAdding(true);
      const file = e.target.files[0];

      const ipfs = await IPFS.create({ repo: "ok" + Math.random() });

      console.log("ipfs", ipfs);
      const { cid } = await ipfs.add(file);
      const url = `https://ipfs.io/ipfs/${cid.toString()}`;
      updateFileUrl(url);

      setCID(cid.toString());
      setAdding(false);
    } catch (e) {
      setAdding(false);
      console.error("An error occurred while uploading media", e);
    }
  };

  const handleInputClick = (event) => {
    hiddenInput.current.click();
  };

  return (
    <div className="mx-auto">
      <Stack direction="vertical" gap={2}>
        <Stack direction="horizontal" gap={2}>
          <Button disabled={adding} onClick={handleInputClick}>
            {adding ? (
              <Spinner
                as="span"
                animation="border"
                size="sm"
                role="status"
                aria-hidden="true"
              />
            ) : (
              showText
            )}
          </Button>
          <input
            type="file"
            style={{ display: "none" }}
            ref={hiddenInput}
            accept="image/*"
            capture="camera"
            onChange={getIPFS}
          />
          {cid && <Copy cid={cid} />}
        </Stack>

        {fileUrl && <PreviewImage srcUrl={fileUrl} />}
      </Stack>
    </div>
  );
}
Example #8
Source File: AddTagModal.js    From serverless-media-portal with MIT License 5 votes vote down vote up
export function AddTagModal({ isOpen, close }) {
	const [isLoading, setIsLoading] = useState(false);
	const { addToast } = useToasts();

	const onSubmit = async e => {
		e.preventDefault();
		setIsLoading(true);
		const uploadResult = await performFormUpload(e.target);
		setIsLoading(false);

		if (uploadResult.success) {
			addNotification("Tag added", "success");
			close(true);
		} else {
			console.error(uploadResult.message);
			addNotification(uploadResult.message, "error");
		}
	};

	const performFormUpload = async target => {
		const formData = Object.fromEntries(new FormData(target).entries());
		const res = await authPost("http://localhost:3001/dev/addTag", {
			formData: {
				Tag: formData.tag
			}
		});

		return res;
	};

	const addNotification = (msg, type) => {
		addToast(msg, {
			appearance: type,
			autoDismiss: true
		});
	};

	return (
		<Modal show={isOpen} onHide={close} backdrop="static" centered animation={false}>
			<Modal.Header closeButton>
				<Modal.Title>Add Tag</Modal.Title>
			</Modal.Header>
			<Modal.Body>
				<Form onSubmit={onSubmit} id="upload-form" className="w-100">
					<Form.Row>
						<Form.Label column xs={3}>Tag:</Form.Label>
						<Col>
							<Form.Control name="tag" type="text" required />
						</Col>
					</Form.Row>

					<hr />

					<Form.Row style={{ flexWrap: "nowrap" }}>
						<Button variant="success" type="submit" className="w-25">
							{isLoading ? (
								<Spinner animation="border" size="sm" />
							) : (
								"Submit"
							)}
						</Button>
					</Form.Row>
				</Form>
			</Modal.Body>
		</Modal>
	);
}
Example #9
Source File: AuthWrapper.js    From serverless-media-portal with MIT License 5 votes vote down vote up
export function AuthWrapper(props) {
	const [isLoading, setIsLoading] = useState(true);
	const [isAuthorized, setIsAuthorized] = useState(false);
	const [hasFailedLoginAttempts, setHasFailedLoginAttempts] = useState(false);

	useEffect(async () => {
		processLogin(false);
	}, []);

	const processLogin = async (userInitiatedLogin, hash = undefined) => {
		try {
			setIsLoading(true);

			if (await logUserIn(hash)) {
				setIsAuthorized(true);
			} else if (userInitiatedLogin) {
				setHasFailedLoginAttempts(true);
			}

			setIsLoading(false);
		} catch (e) {
			console.error(e);
		}
	};

	const style = {
		centered: {
			position: "absolute",
			left: "50%",
			top: "40%"
		}
	};

	return (
		<div>
			{isLoading ? (
				<Spinner
					animation="border"
					role="status"
					style={style.centered}
				/>
			) : !isAuthorized ? (
				<Login
					processLogin={processLogin}
					hasFailedLoginAttempts={hasFailedLoginAttempts}
				/>
			) : (
				{ ...props.children }
			)}
		</div>
	);
}
Example #10
Source File: CommentPane.js    From serverless-media-portal with MIT License 5 votes vote down vote up
export function CommentPane({ videoHash, isUserAnAdmin }) {
	const [isLoading, setIsLoading] = useState(true);
	const [commentList, setCommentList] = useState([]);
	const { addToast } = useToasts();
	
	const userHash = getSavedHashFromLocalStorage();

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

	const loadComments = async () => {
		setIsLoading(true);
		const res = await authGet(`http://localhost:3001/dev/getCommentsForVideo?videoHash=${videoHash}`);

		if (res && res.success && res.comments) {
			setCommentList(res.comments);
		}
		setIsLoading(false);
	};

	const onCommentAdded = async () => {
		await loadComments();
	};

	const deleteComment = async (commentHash) => {
		const res = await authGet(
			`http://localhost:3001/dev/deleteCommentFromVideo?videoHash=${videoHash}&commentHash=${commentHash}`
		);

		if(res.success) {
			addToast("Comment deleted", {
				appearance: "success",
				autoDismiss: true
			});
		} else {
			setCommentList([]); // Force refresh of comments to remove opacity
			addToast("Error deleting comment", {
				appearance: "error",
				autoDismiss: true
			});
			console.error(res.message);
		}

		await loadComments();
	};

	return (
		<CommentContainer>
			<CommentHeader>{commentList.length} {commentList.length === 1 ? "Comment" : "Comments"}</CommentHeader>
			<CommentForm 
				videoHash={videoHash}
				onCommentAdded={onCommentAdded} 
			/>
			<CommentList>
				{!isLoading || (
					<SpinnerContainer>
						<Spinner animation="border" size="sm" />
					</SpinnerContainer>
				)}
				{commentList.sort(x => x.CreatedOn).reverse().map(c => (
					<Comment
						key={c.CommentHash}
						commentHash={c.CommentHash}
						displayName={c.UserDisplayName}
						commentText={c.CommentText}
						dateCreated={c.CreatedOn}
						onDeleteCommentClicked={deleteComment}
						canUserDeleteComment={c.UserHash === userHash || isUserAnAdmin}
					/>
				))}
			</CommentList>
		</CommentContainer>
	);
}
Example #11
Source File: RelatedVideosPane.js    From serverless-media-portal with MIT License 5 votes vote down vote up
export function RelatedVideosPane() {
	const [isLoading, setIsLoading] = useState(true);
	const [videos, setVideos] = useState([]);

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

	const getVideos = async () => {
		const res = await authGet("http://localhost:3001/dev/listRandomVideos?count=5");

		if (res && res.videos) {
			setVideos(res.videos);
		}
		setIsLoading(false);
	};

	return (
		<>
			<style>{`
				.related-videos-title {
					margin-bottom: 14px;
					color: #8c8fa4;
				}
			`}</style>

			<h5 className="related-videos-title">Related videos</h5>

			{isLoading ? (
				<div className="text-center mt-5">
					<Spinner animation="grow" />
				</div>
			) : (
				videos.map(video => (
					<RelatedVideoThumbnail key={video.VideoHash}
						videoHash={video.VideoHash}
						title={video.Title}
						date={video.VideoDate}
						thumbnailName={video.ThumbnailName}
						duration={video.Duration}
					/>
				))
			)}
		</>
	);
}
Example #12
Source File: Profile.jsx    From ashteki with GNU Affero General Public License v3.0 4 votes vote down vote up
Profile = ({ onSubmit, isLoading }) => {
    const { t } = useTranslation();
    const user = useSelector((state) => state.account.user);
    const [localBackground, setBackground] = useState(user?.settings.background);
    const [localCardSize, setCardSize] = useState(user?.settings.cardSize);
    const [customBg, setCustomBg] = useState(null);
    const topRowRef = useRef(null);
    const [bluffTimer, setBluffTimer] = useState(user?.settings.optionSettings.bluffTimer || 0);

    const backgrounds = [{ name: 'none', label: t('none'), imageUrl: BlankBg }];
    const cardSizes = [
        { name: 'small', label: t('small') },
        { name: 'normal', label: t('normal') },
        { name: 'large', label: t('large') },
        { name: 'x-large', label: t('extra-large') }
    ];

    backgrounds.push({
        name: 'ashesreborn',
        label: t('Ashes Reborn'),
        imageUrl: AshesRebornBg
    });

    if (!user) {
        return <Alert variant='danger'>You need to be logged in to view your profile.</Alert>;
    }

    initialValues.email = user.email;
    initialValues.username = user.username;
    if (user?.settings?.optionSettings) {
        initialValues.gameOptions = user.settings.optionSettings;
    }

    const schema = yup.object({
        avatar: yup
            .mixed()
            .test(
                'fileSize',
                t('Image must be less than 100KB in size'),
                (value) => !value || value.size <= 100 * 1024
            )
            .test(
                'fileType',
                t('Unsupported image format'),
                (value) =>
                    !value ||
                    ['image/jpg', 'image/jpeg', 'image/gif', 'image/png'].includes(value.type)
            ),
        username: yup
            .string()
            .required(t('You must specify a username'))
            .min(3, t('Your username must be at least 3 characters long'))
            .max(15, t('Your username cannot be more than 15 charcters'))
            .matches(
                /^[A-Za-z0-9_-]+$/,
                t('Usernames must only use the characters a-z, 0-9, _ and -')
            ),
        email: yup
            .string()
            .email(t('Please enter a valid email address'))
            .required(t('You must specify an email address')),
        password: yup.string().min(6, t('Password must be at least 6 characters')),
        passwordAgain: yup
            .string()
            .oneOf([yup.ref('password'), null], t('The passwords you have entered do not match'))
    });

    return (
        <Formik
            validationSchema={schema}
            onSubmit={async (values) => {
                /**
                 * @type {ProfileDetails}
                 */
                const submitValues = {
                    avatar: values.avatar ? await toBase64(values.avatar) : null,
                    email: values.email,
                    username: values.username,
                    password: values.password,
                    settings: { optionSettings: values.gameOptions }
                };

                if (localBackground) {
                    submitValues.settings.background = localBackground;
                }

                if (localCardSize) {
                    submitValues.settings.cardSize = localCardSize;
                }

                if (customBg) {
                    submitValues.customBackground = customBg;
                }

                if (bluffTimer) {
                    submitValues.settings.optionSettings.bluffTimer = bluffTimer;
                }

                onSubmit(submitValues);

                topRowRef?.current?.scrollIntoView(false);
            }}
            initialValues={initialValues}
        >
            {(formProps) => (
                <Form
                    className='profile-form'
                    onSubmit={(event) => {
                        event.preventDefault();
                        formProps.handleSubmit(event);
                    }}
                >
                    <Row ref={topRowRef}>
                        <Col sm='12'>
                            <ProfileMain formProps={formProps} user={user} />
                        </Col>
                    </Row>
                    <Row>
                        <Col sm='12'>
                            <ProfileBackground
                                backgrounds={backgrounds}
                                selectedBackground={localBackground || user.settings.background}
                                customBackground={user.settings.customBackground}
                                onBackgroundSelected={async (name, file) => {
                                    if (name === 'custom') {
                                        let base64File = await toBase64(file);

                                        setCustomBg(base64File);
                                    }

                                    setBackground(name);
                                }}
                            />
                        </Col>
                    </Row>
                    <Row>
                        <Col sm='6'>
                            <ProfileCardSize
                                cardSizes={cardSizes}
                                selectedCardSize={localCardSize || user.settings.cardSize}
                                onCardSizeSelected={(name) => setCardSize(name)}
                            />
                        </Col>
                        <Col sm='6'>
                            <InGameSettings formProps={formProps} user={user} />

                            <Panel title='Bluff timer'>
                                <RangeSlider
                                    min='0'
                                    max='10'
                                    tooltip='on'
                                    value={bluffTimer}
                                    onChange={(event) => setBluffTimer(event.target.value)}
                                />
                                <br />
                            </Panel>
                        </Col>
                    </Row>
                    <div className='text-center profile-submit'>
                        <Button variant='primary' type='submit' disabled={isLoading}>
                            {isLoading ? (
                                <Spinner
                                    animation='border'
                                    size='sm'
                                    as={'span'}
                                    role='status'
                                    aria-hidden='true'
                                />
                            ) : null}
                            {t('Save')}
                        </Button>
                    </div>
                </Form>
            )}
        </Formik>
    );
}
Example #13
Source File: UserAdmin.jsx    From ashteki with GNU Affero General Public License v3.0 4 votes vote down vote up
UserAdmin = () => {
    const currentUser = useSelector((state) => state.admin.currentUser);
    const user = useSelector((state) => state.account.user);
    const { t } = useTranslation();
    const apiState = useSelector((state) => {
        const retState = state.api[Admin.FindUser];

        if (retState && retState.status === 404) {
            retState.message = 'User was not found.';
        } else if (retState && retState.success) {
            retState.message = 'User details loaded';

            setTimeout(() => dispatch(clearApiStatus(Admin.FindUser)), 3000);
        }

        return retState;
    });
    const apiSaveState = useSelector((state) => {
        const retState = state.api[Admin.SaveUser];

        if (retState && retState.success) {
            retState.message = 'User details saved.';

            setTimeout(() => dispatch(clearApiStatus(Admin.SaveUser)), 5000);
        }

        return retState;
    });
    const dispatch = useDispatch();
    const [currentPermissions, setCurrentPermissions] = useState(
        currentUser?.permissions || defaultPermissions
    );
    const [userVerified, setUserVerified] = useState(currentUser?.verified);
    const [userDisabled, setUserDisabled] = useState(currentUser?.disabled);
    const [faveColor, setfaveColor] = useState(currentUser?.faveColor);

    useEffect(() => {
        if (currentUser) {
            setCurrentPermissions(currentUser.permissions);
            setUserDisabled(currentUser.disabled);
            setUserVerified(currentUser.verified);
            setfaveColor(currentUser.faveColor);
        }
    }, [currentUser]);

    const initialValues = {
        username: '',
        disabled: currentUser?.disabled,
        verified: currentUser?.verified,
        faveColor: currentUser?.faveColor
    };

    const schema = yup.object({
        username: yup.string().required('Username must be specified')
    });

    let permissionsCheckBoxes;

    if (currentUser) {
        permissionsCheckBoxes = permissions.map((permission) => {
            return (
                <Col key={`permissions.${permission.name}`} md='4'>
                    <Form.Check
                        type='switch'
                        id={`permissions.${permission.name}`}
                        label={permission.label}
                        inline
                        onChange={() => {
                            currentPermissions[permission.name] = !currentPermissions[
                                permission.name
                            ];
                            let newPermissions = Object.assign({}, currentPermissions);
                            setCurrentPermissions(newPermissions);
                        }}
                        value='true'
                        checked={currentPermissions[permission.name]}
                    ></Form.Check>
                </Col>
            );
        });
    }

    return (
        <Col sm={{ span: 8, offset: 2 }}>
            <ApiStatus state={apiState} onClose={() => dispatch(clearApiStatus(Admin.FindUser))} />
            <ApiStatus
                state={apiSaveState}
                onClose={() => dispatch(clearApiStatus(Admin.SaveUser))}
            />
            <Formik
                validationSchema={schema}
                onSubmit={async (values) => {
                    dispatch(findUser(values.username));
                }}
                initialValues={initialValues}
            >
                {(formProps) => (
                    <Form
                        onSubmit={(event) => {
                            event.preventDefault();
                            formProps.handleSubmit(event);
                        }}
                    >
                        <Panel title='User administration'>
                            <Row>
                                <Form.Group as={Col} md='6' controlId='formUsername'>
                                    <Form.Label>{t('Username')}</Form.Label>
                                    <Form.Control
                                        name='username'
                                        type='text'
                                        placeholder={t('Enter a username')}
                                        value={formProps.values.username}
                                        onChange={formProps.handleChange}
                                        onBlur={formProps.handleBlur}
                                        isInvalid={
                                            formProps.touched.username &&
                                            !!formProps.errors.username
                                        }
                                    />
                                    <Form.Control.Feedback type='invalid'>
                                        {formProps.errors.username}
                                    </Form.Control.Feedback>
                                </Form.Group>
                            </Row>
                            <Row>
                                <Col md={6}>
                                    <Button type='submit' variant='primary'>
                                        Submit&nbsp;
                                        {apiState?.loading && (
                                            <Spinner
                                                animation='border'
                                                size='sm'
                                                as={'span'}
                                                role='status'
                                                aria-hidden='true'
                                            />
                                        )}
                                    </Button>
                                </Col>
                            </Row>
                        </Panel>
                        {currentUser && (
                            <div>
                                <Panel title={`${currentUser.username} - User details`}>
                                    <dl>
                                        <Row>
                                            <Col md={3}>
                                                <dt>Username:</dt>
                                            </Col>
                                            <Col md={3}>
                                                <dd>{currentUser.username}</dd>
                                            </Col>
                                        </Row>
                                        <Row>
                                            <Col md={3}>
                                                <dt>Email:</dt>
                                            </Col>
                                            <Col md={3}>
                                                <dd>{currentUser.email}</dd>
                                            </Col>
                                        </Row>
                                        <Row>
                                            <Col md={3}>
                                                <dt>Registered:</dt>
                                            </Col>
                                            <Col md={3}>
                                                <dd>
                                                    {moment(currentUser.registered).format(
                                                        'YYYY-MM-DD HH:MM'
                                                    )}
                                                </dd>
                                            </Col>
                                        </Row>
                                        <Row>
                                            <Col md={3}>
                                                <dt>Favorite Color:</dt>
                                            </Col>
                                            <Col md={3}>
                                                <HexColorPicker
                                                    color={faveColor}
                                                    onChange={setfaveColor}
                                                />
                                                ;
                                                <Form.Control
                                                    name='favecolor'
                                                    type='text'
                                                    value={faveColor}
                                                    style={{ backgroundColor: faveColor }}
                                                    onChange={(event) =>
                                                        setfaveColor(event.target.value)
                                                    }
                                                />
                                                <Button onClick={() => setfaveColor('')}>Clear</Button>
                                            </Col>
                                        </Row>
                                    </dl>

                                    <Form.Check
                                        type='switch'
                                        id='disabled'
                                        label={'Disabled'}
                                        inline
                                        onChange={() => setUserDisabled(!userDisabled)}
                                        value='true'
                                        checked={userDisabled}
                                    ></Form.Check>
                                    <Form.Check
                                        type='switch'
                                        id='verified'
                                        label={'Verified'}
                                        inline
                                        onChange={() => setUserVerified(!userVerified)}
                                        value='true'
                                        checked={userVerified}
                                    ></Form.Check>

                                </Panel>
                                {currentUser.linkedAccounts && (
                                    <Panel title='Possibly linked accounts'>
                                        <ul className='list'>
                                            {currentUser.linkedAccounts.map((name) => {
                                                return (
                                                    <li key={name}>
                                                        <a
                                                            href='javascript:void(0)'
                                                            onClick={() => dispatch(findUser(name))}
                                                        >
                                                            {name}
                                                        </a>
                                                    </li>
                                                );
                                            })}
                                        </ul>
                                    </Panel>
                                )}
                                {currentUser.tokens && (
                                    <Panel title='Sessions'>
                                        <Table striped>
                                            <thead>
                                                <tr>
                                                    <th>IP Address</th>
                                                    <th>Last Used</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {currentUser.tokens.map((token) => {
                                                    return (
                                                        <tr key={token.ip}>
                                                            <td>{token.ip}</td>
                                                            <td>
                                                                {moment(token.lastUsed).format(
                                                                    'YYYY-MM-DD HH:MM'
                                                                )}
                                                            </td>
                                                        </tr>
                                                    );
                                                })}
                                            </tbody>
                                        </Table>
                                    </Panel>
                                )}
                                {user?.permissions.canManagePermissions ? (
                                    <Panel title='Permissions'>
                                        <Form.Group>
                                            <Form.Row>{permissionsCheckBoxes}</Form.Row>
                                        </Form.Group>
                                    </Panel>
                                ) : null}
                                <div className='text-center'>
                                    <Button
                                        type='button'
                                        className='btn btn-primary col-xs-3'
                                        onClick={() =>
                                            dispatch(clearUserSessions(currentUser.username))
                                        }
                                    >
                                        Clear sessions
                                    </Button>
                                    <Button
                                        type='button'
                                        variant='primary'
                                        onClick={() => {
                                            currentUser.permissions = currentPermissions;
                                            currentUser.verified = userVerified;
                                            currentUser.disabled = userDisabled;
                                            currentUser.faveColor = faveColor;
                                            dispatch(saveUser(currentUser));
                                        }}
                                    >
                                        Save&nbsp;
                                        {apiSaveState?.loading && (
                                            <Spinner
                                                animation='border'
                                                size='sm'
                                                as={'span'}
                                                role='status'
                                                aria-hidden='true'
                                            />
                                        )}
                                    </Button>
                                </div>
                            </div>
                        )}
                    </Form>
                )}
            </Formik>
        </Col>
    );
}
Example #14
Source File: index.jsx    From nightfall_3 with Creative Commons Zero v1.0 Universal 4 votes vote down vote up
Transactions = () => {
  const [txs, setTxs] = React.useState([]);
  const [isActive, setActive] = React.useState('all');
  const [showModal, setShowModal] = React.useState({ show: false });
  const [delay, setDelay] = React.useState(50);
  const [etherscan] = React.useState(
    ChainIdMapping[process.env.REACT_APP_MODE].chainName === 'Ethereum Mainnet'
      ? 'etherscan.io'
      : 'goerli.etherscan.io',
  );

  const initialPrices = {};
  supportedTokens.forEach(t => {
    initialPrices[t.id] = 0;
  }, {});

  const [currencyValues, setCurrencyValues] = React.useState({ now: 0, ...initialPrices });

  React.useEffect(async () => {
    if (!getPricing()) await setPricing(supportedTokens.map(t => t.id));
    else if (Date.now() - getPricing().time > 86400)
      await setPricing(supportedTokens.map(t => t.id));
    setCurrencyValues(getPricing());
  }, []);

  useInterval(async () => {
    console.log('currencyVals', currencyValues);
    const transactionsDB = await getAllTransactions();
    const commitmentsDB = await getAllCommitments();
    const commits = commitmentsDB.map(c => c._id);
    const nullifiers = commitmentsDB.map(c => c.nullifier);

    const transactions = Array.from(new Set(transactionsDB)).filter(
      t =>
        t.commitments.some(c => commits.includes(c)) ||
        t.nullifiers.some(n => nullifiers.includes(n)),
    );
    const shieldContractAddress = shieldAddressGet();
    const shieldContractInstance = await getContractInstance(
      SHIELD_CONTRACT_NAME,
      shieldContractAddress,
    );
    setDelay(20000);

    const blocks = await findBlocksFromBlockNumberL2(-1);
    const promisedTxs = transactions.map(async tx => {
      const safeTransactionType = BigInt(tx.transactionType).toString();
      let value = BigInt(tx.value);
      // The value of transfers need to be derived from the components making up the transfer
      // Add sum nullifiers in transactions
      // Subtract sum of commitments we have.
      if (safeTransactionType === '1' || safeTransactionType === '2')
        commitmentsDB.forEach(c => {
          if (tx.nullifiers.includes(c.nullifier)) value -= BigInt(c.preimage.value);
          else if (tx.commitments.includes(c._id)) value += BigInt(c.preimage.value);
        });

      const safeValue = value.toString();
      const { ercAddress } = commitmentsDB.find(c => {
        return tx.commitments.includes(c._id) || tx.nullifiers.includes(c.nullifier);
      })?.preimage ?? {
        ercAddress: '0x00',
      };

      // eslint-disable-next-line no-param-reassign
      if (tx?.blockNumberL2) tx.isOnChain = tx.blockNumberL2; // Temp for handling transfers
      blocks.forEach(b => {
        if (tx.isOnChain >= 0) return;
        if (b.transactionHashes.includes(tx._id)) {
          // eslint-disable-next-line no-param-reassign
          tx.isOnChain = b.blockNumberL2;
        }
        // eslint-disable-next-line no-param-reassign
        else tx.isOnChain = -1;
      });

      let withdrawReady = false;
      if (
        safeTransactionType === '3' &&
        tx.isOnChain > 0 &&
        tx.withdrawState !== 'finalised' &&
        Math.floor(Date.now() / 1000) - tx.createdTime > 3600 * 24 * 7
      ) {
        withdrawReady = await isValidWithdrawal(tx._id, shieldContractAddress);
      }
      if (tx.withdrawState === 'instant') {
        const newOwner = await shieldContractInstance.methods.advancedWithdrawals(tx._id).call();
        const myAddress = await Web3.getAccount();
        if (newOwner.toLowerCase() !== ZERO && newOwner.toLowerCase() !== myAddress.toLowerCase())
          // eslint-disable-next-line no-param-reassign
          tx.withdrawState = 'fulfilled';
      }

      const { logoURI, decimals, id, symbol } = supportedTokens.find(
        t => t.address.toLowerCase() === `0x${ercAddress.slice(-40).toLowerCase()}`,
      ) ?? {
        logoURI: null,
        decimals: 0,
        id: '',
      };
      const currencyValue = id !== '' ? currencyValues[id] : 0;
      return {
        ...tx,
        transactionHash: tx._id,
        txType: safeTransactionType,
        value: safeValue,
        now: Math.floor(Date.now() / 1000),
        logoURI,
        decimals,
        currencyValue,
        symbol,
        withdrawReady,
      };
    });
    const mappedTxs = (await Promise.all(promisedTxs)).sort(
      (a, b) => b.createdTime - a.createdTime,
    );
    console.log('Transactions', transactions);
    setTxs(mappedTxs);
  }, delay);

  function downloadFile(content) {
    const a = document.createElement('a');
    const file = new Blob([content], { type: 'text/plain' });
    a.href = URL.createObjectURL(file);
    a.download = 'pnf_bkp.json';
    a.click();
  }

  const handleExportIndedexDB = async () => {
    const exportedDB = await exportIndexdDB('nightfall_commitments');
    const filteredTables = exportedDB.filter(
      arr => arr.table === 'commitments' || arr.table === 'transactions',
    );
    downloadFile(JSON.stringify(filteredTables));
  };

  return (
    <div className="pagePartition" style={{ width: '100%' }}>
      <TxInfoModal onHide={() => setShowModal(false)} {...showModal} />
      <div className="infoWrapper">
        <div className="wrapperTabList">
          <div className="tab-list">
            <div
              className={`tab-list-item ${isActive === 'all' ? 'active' : ''}`}
              onClick={() => setActive('all')}
            >
              All Transactions
            </div>
            <div
              className={`tab-list-item ${isActive === 'pending' ? 'active' : ''}`}
              onClick={() => setActive('pending')}
            >
              Pending
            </div>
            <div
              className={`tab-list-item ${isActive === 'deposit' ? 'active' : ''}`}
              onClick={() => setActive('deposit')}
            >
              Deposits
            </div>
            <div
              className={`tab-list-item ${isActive === 'transfer' ? 'active' : ''}`}
              onClick={() => setActive('transfer')}
            >
              Transfers
            </div>
            <div
              className={`tab-list-item ${isActive === 'withdraw' ? 'active' : ''}`}
              onClick={() => setActive('withdraw')}
            >
              Withdraws
            </div>
          </div>
          <div>
            <button onClick={() => handleExportIndedexDB()} className="exportTransactionsButton">
              Export transactions
            </button>
          </div>
        </div>
        <div className="separator" />
        <div className="innerWrapper">
          {txs
            .filter(f => {
              switch (isActive) {
                case 'deposit':
                  return f.txType === '0';
                case 'transfer':
                  return f.txType === '1' || f.txType === '2';
                case 'withdraw':
                  return f.txType === '3';
                case 'pending':
                  return f.isOnChain === -1;
                default:
                  return f;
              }
            })
            .map(tx => (
              <Row
                key={tx.transactionHash}
                className="transactionRow"
                onClick={() =>
                  setShowModal({
                    show: true,
                    transactionhash: tx.transactionHash,
                    symbol: tx.symbol,
                    value: new BigFloat(BigInt(tx.value), tx.decimals).toFixed(4),
                    _id: tx._id,
                    recipientaddress: tx.recipientAddress,
                    withdrawready: tx.withdrawReady ? 1 : 0,
                    txtype: tx.txType,
                  })
                }
              >
                <Row>
                  <div className="transactionDetails">
                    <div>
                      {tx.isOnChain >= 0 ? (
                        <Image src={tickBox} />
                      ) : (
                        <Spinner animation="border" variant="warning" />
                      )}
                    </div>
                    <div style={{ marginLeft: '14px' }}>
                      {/* Details */}
                      <div style={{ display: 'flex', fontWeight: '600', fontSize: '14px' }}>
                        {/* tx-type-time */}
                        <div style={{ textTransform: 'capitalize' }}>
                          {txTypeOptions[tx.txType]}
                        </div>
                        {/* tx-type-time-type */}
                        <div style={{ color: '#b0b4bb', paddingLeft: '5px' }}>
                          {/* tx-type-time-time */}
                          {displayTime(tx.createdTime, tx.now)}
                        </div>
                      </div>
                      <div
                        style={{
                          display: 'flex',
                          color: '#52555d',
                          fontWeight: '400',
                          fontSize: '12px',
                          lineHeight: '16px',
                        }}
                      >
                        {/* tx-status-hash */}
                        {/* <div> 1/3 • Action Required • From Mumbai to Goerli</div> */}
                        <div style={{ textTransform: 'capitalize' }}>
                          {tx.isOnChain >= 0 ? 'Success' : 'Pending'} • {txTypeDest[tx.txType]}{' '}
                          {!tx.withdrawState ? '' : `• ${tx.withdrawState}`}
                        </div>
                      </div>
                    </div>
                  </div>
                  <div
                    style={{
                      padding: '20px',
                      width: '42%',
                      alignItems: 'center',
                      display: 'flex',
                    }}
                  >
                    {/* details-section */}
                    <div style={{ display: 'block' }}>
                      {/* token-image */}
                      <img src={tx.logoURI} alt="" height="32" width="32" />
                    </div>
                    <div
                      style={{
                        width: 'calc(50% - 50px)',
                        marginLeft: '8px',
                        flexShrink: '0',
                      }}
                    >
                      {/* amount-details */}
                      <div style={{ fontWeight: '600', fontSize: '14px', lineHeight: '20px' }}>
                        {new BigFloat(BigInt(tx.value), tx.decimals).toFixed(4)} {tx.symbol}
                      </div>
                      <div
                        style={{
                          color: '#52555d',
                          marginTop: '4px',
                          wordBreak: 'break-all',
                          fontWeight: '400',
                          fontSize: '12px',
                          lineHeight: '16px',
                        }}
                      >
                        $
                        {new BigFloat(BigInt(tx.value), tx.decimals)
                          .mul(tx.currencyValue)
                          .toFixed(4)}
                      </div>
                    </div>
                    <div
                      style={{
                        marginLeft: '8px',
                        width: 'calc(50% - 50px)',
                        flexShrink: '0',
                      }}
                    >
                      {/* Transaction Details */}
                      <div style={{ fontWeight: '600', fontSize: '14px', lineHeight: '20px' }}>
                        {/* Transaction Hash label */}
                        Transaction Hash
                      </div>
                      <div
                        style={{
                          color: '#52555d',
                          marginTop: '4px',
                          display: 'flex',
                          alignItems: 'center',
                          cursor: 'pointer',
                          fontWeight: '400',
                          fontSize: '12px',
                          lineHeight: '16px',
                        }}
                      >
                        {/* Tooltip */}
                        <img src={polygonChainImage} alt="Polygon Chain" height="16" width="16" />
                        <div style={{ marginLeft: '4px' }}>{`${tx.transactionHash.slice(
                          0,
                          5,
                        )}...${tx.transactionHash.slice(-5)}`}</div>
                      </div>
                    </div>
                    <a
                      href={`https://${etherscan}/tx/${tx.l1Hash}`}
                      className="etherscanLink"
                      rel="noopener noreferrer"
                      target="_blank"
                      style={{ marginLeft: '20px' }}
                      onClick={e => e.stopPropagation()}
                    >
                      <Image src={etherscanArrow} />
                    </a>
                  </div>
                </Row>
                {tx.txType === '3' && tx.isOnChain > 0 && !tx.withdrawState ? (
                  <WithdrawTransaction
                    withdrawready={tx.withdrawReady}
                    transactionhash={tx.transactionHash}
                  />
                ) : (
                  <></>
                )}
              </Row>
            ))}
        </div>
        <Row>
          <div className="bottomSection">
            <img src={bridgeInfoImage} alt="" height="219" width="326" />
          </div>
        </Row>
      </div>
    </div>
  );
}
Example #15
Source File: IndiAssetNFT.js    From RC4Community with Apache License 2.0 4 votes vote down vote up
NFTCard = ({ show, handleClose }) => {
  const [NFT, setNFT] = useState("");

  const [nform, setNform] = useState({
    nadd: "0xb47e3cd837ddf8e4c57f05d70ab865de6e193bbb",
    token: "1",
  });

  const [proc, setProc] = useState(false);

  const handleFetch = async (a, t) => {
    setProc(true);
    const res = await fetchOpenSea(a, t);
    setProc(false);
    setNFT(res);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    handleFetch(nform.nadd, nform.token);
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    setNform((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  return (
    <Modal show={show} onHide={handleClose}>
      <Modal.Header closeButton>
        <Modal.Title>Retrieve a Single Asset</Modal.Title>
      </Modal.Header>
      <Form onSubmit={handleSubmit}>
        <Modal.Body>
          <Form.Group>
            <Form.Label>Address of the contract for this NFT</Form.Label>
            <Form.Control
              name="nadd"
              type="text"
              onChange={handleChange}
              required
              placeholder={nform.nadd}
            />
          </Form.Group>

          <Form.Group>
            <Form.Label>Token ID for this item</Form.Label>
            <Form.Control
              onChange={handleChange}
              name="token"
              type="text"
              required
              placeholder={nform.token}
            />
          </Form.Group>
          {NFT.image_url ? (
            <Card style={{ width: "10em", marginTop: "1em" }}>
              <Card.Header>Preview Image</Card.Header>
              <Card.Img src={NFT.image_preview_url}></Card.Img>
            </Card>
          ) : null}
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" disabled={proc} onClick={handleClose}>
            Close
          </Button>
          <Button variant="primary" disabled={proc} type="submit">
            {proc ? (
              <Spinner
                as="span"
                animation="border"
                size="sm"
                role="status"
                aria-hidden="true"
              />
            ) : (
              "Submit"
            )}
          </Button>
        </Modal.Footer>
      </Form>
    </Modal>
  );
}
Example #16
Source File: NFTprofile.js    From RC4Community with Apache License 2.0 4 votes vote down vote up
GalleryModal = ({
  handleClose,
  show,
  assets,
  handleImage,
  uid,
  select,
  load,
  setLoad,
  errMess,
  setErrMess,
}) => {
  const [upsertNFT, { data, loading, error, reset }] = useMutation(UPSERT_NFT);
  useEffect(() => {
    if (data) {
      setLoad(false);
    }
  }, [data]);
  if (loading) {
    setLoad(true);
  }
  const handleSubmit = (e) => {
    e.preventDefault();
    const assetSelected = assets[select.split("_")[1]];
    const address = assetSelected.asset_contract.address;
    const token = assetSelected.token_id;
    upsertNFT({ variables: { id: uid, address: address, token: token } });
  };

  if (error) {
    if (error.graphQLErrors[0].extensions.code == "instance not found") {
      setErrMess("User not found");
    }
    if (error.graphQLErrors[0].extensions.code == "instance not unique") {
      setErrMess("NFT is owned by someone else");
    } else {
      setErrMess(error.message);
    }
    setTimeout(() => {
      reset();
      setLoad(false);
    }, 5000);
  }

  return (
    <>
      <Modal show={show} onHide={handleClose}>
        <Modal.Header closeButton>
          <Modal.Title>Select a NFT</Modal.Title>
        </Modal.Header>
        {error && (
          <Alert variant={"danger"}>{errMess} - Please try again!</Alert>
        )}
        <Modal.Body className={styles.selectNFT}>
          {assets
            ? assets.map(
                (a, i) =>
                  a.image_url && (
                    <div key={i} className={styles.asset}>
                      <Image
                        key={i}
                        onClick={handleImage}
                        className={`${styles.assetImage} nim_${i}`}
                        src={a.image_url}
                      />
                    </div>
                  )
              )
            : "No assets available"}
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={handleClose}>
            Close
          </Button>
          <Button variant="primary" disabled={load} onClick={handleSubmit}>
            {!load ? (
              "Save Changes"
            ) : (
              <Spinner
                as="span"
                animation="grow"
                size="sm"
                role="status"
                aria-hidden="true"
              />
            )}
          </Button>
        </Modal.Footer>
      </Modal>
    </>
  );
}
Example #17
Source File: AddOrEditUserModal.js    From serverless-media-portal with MIT License 4 votes vote down vote up
export function AddOrEditUserModal({ user, isOpen, close, editUserMode }) {
	const [isLoadingTags, setIsLoadingTags] = useState(false);
	const [allTags, setAllTags] = useState([]);
	const { addToast } = useToasts();

	useEffect(() => {
		if(isOpen) {
			loadTags();
		}
	}, [isOpen]);

	const loadTags = async () => {
		setIsLoadingTags(true);
		const res = await authGet("http://localhost:3001/dev/listAllTags");

		if(res && res.tags) {
			setAllTags(res.tags.map(x => x.TagName));
		}
		setIsLoadingTags(false);
	};

	const onSubmit = async e => {
		e.preventDefault();

		const formData = getFormData(e.target);
		const uploadResult = await performFormUpload(formData);

		if (uploadResult.success) {
			close(true);

			const msg = editUserMode
				? "User updated"
				: "New user added";
			addNotification(msg, "success");
		} else {
			console.error(uploadResult.message);
			addNotification(uploadResult.message, "error");
		}
	};

	const getFormData = form => {
		const formData = Object.fromEntries(new FormData(form).entries());
		
		const dataObj = {
			UserHash: getUserHash(formData),
			DisplayName: formData.displayName,
			Tags: getSelectedTags(formData)
		};

		return dataObj;
	};

	const performFormUpload = async formData => {
		const url = getUploadUrl();
		const res = await authPost(url, {
			formData: formData
		});

		return res;
	};

	const getUploadUrl = () => {
		return editUserMode
			? "http://localhost:3001/dev/editUser" 
			: "http://localhost:3001/dev/addUser";
	};

	const getSelectedTags = formData => {
		const selectedTags = Object.keys(formData).filter(key => allTags.includes(key));

		return selectedTags;
	};

	const getUserHash = formData => {
		const userHash = editUserMode 
			? formData.userHash
			: generateUserHash(formData.displayName, formData.dateOfBirth, formData.password);

		return userHash;
	};

	const addNotification = (msg, type) => {
		addToast(msg, {
			appearance: type,
			autoDismiss: true
		});
	};

	return (
		<Modal show={isOpen} onHide={close} backdrop="static" centered animation={false}>
			<Modal.Header closeButton>
				<Modal.Title>
					<h5 className="mb-0">
						{editUserMode ? (
							<>Edit User: {user.DisplayName}</>
						) : (
							<>Add New User</>
						)}
					</h5>
				</Modal.Title>
			</Modal.Header>
			<Modal.Body>
				<Form onSubmit={onSubmit} id="upload-form" className="w-100">
					<Form.Control name="userHash" type="hidden" defaultValue={user.UserHash} required />

					<Form.Row>
						<Form.Label column xs={3}>Name:</Form.Label>
						<Col>
							<Form.Control name="displayName" type="text" defaultValue={user.DisplayName} maxLength="75" required />
						</Col>
					</Form.Row>

					<Form.Row>
						<Form.Label column xs={3}>Date of Birth:</Form.Label>
						<Col>
							<Form.Control name="dateOfBirth" type="date" disabled={editUserMode} required={!editUserMode} />
						</Col>
					</Form.Row>

					<Form.Row>
						<Form.Label column xs={3}>Password:</Form.Label>
						<Col>
							<Form.Control name="password" type="password" disabled={editUserMode} required={!editUserMode} />
						</Col>
					</Form.Row>

					<Form.Row>
						<Form.Label column xs={3}>Visible Tags:</Form.Label>
						<Col style={{ paddingTop: "10px" }}>
							{isLoadingTags ? (
								<Spinner animation="grow" size="sm" />
							) : (
								allTags.map(tag => (
									<Form.Check
										key={tag}
										custom
										inline
										label={tag}
										type="checkbox"
										name={tag}
										id={tag}
										value={true}
										defaultChecked={user.Tags ? user.Tags.includes(tag) : false}
									/>
								))
							)}
						</Col>
					</Form.Row>

					<hr />

					<Form.Row style={{ flexWrap: "nowrap" }}>
						<Button variant="success" type="submit" className="w-25">Submit</Button>
					</Form.Row>
				</Form>
			</Modal.Body>
		</Modal>
	);
}
Example #18
Source File: EditVideoModal.js    From serverless-media-portal with MIT License 4 votes vote down vote up
export default function EditVideoModal ({ isOpen, setIsOpen, video, onEditFormSubmitted }) {
	const [isLoadingTags, setIsLoadingTags] = useState(false);
	const [allTags, setAllTags] = useState([]);
	const { addToast } = useToasts();

	useEffect(() => {
		if(isOpen) {
			loadTags();
		}
	}, [isOpen]);

	const loadTags = async () => {
		setIsLoadingTags(true);
		const res = await authGet("http://localhost:3001/dev/listAllTags");

		if(res && res.tags) {
			setAllTags(res.tags.map(x => x.TagName));
		}
		setIsLoadingTags(false);
	};

	const onSubmit = (e) => {
		e.preventDefault();
		const formData = getFormData(e.target);

		const newVideo = { ...video };
		newVideo.Title = formData.title;
		newVideo.VideoDate = formData.videoDate;
		newVideo.ViewCount = formData.viewCount;
		newVideo.Description = formData.description;
		newVideo.Tags = getSelectedTags(formData);

		if(newVideo.Tags.length === 0) {
			addToast("Error: at least one tag must be selected", {
				appearance: "warning",
				autoDismiss: true,
				autoDismissTimeout: 10000
			});
		} else {
			onEditFormSubmitted(newVideo);
			setIsOpen(false);
		}
	};

	const getFormData = form => {
		const formData = new FormData(form);
		const data = Object.fromEntries(formData.entries());

		return data;
	};

	const getSelectedTags = formData => {
		const selectedTags = Object.keys(formData).filter(key => allTags.includes(key));

		return selectedTags;
	};

	return (
		<Modal show={isOpen} onHide={() => setIsOpen(false)} backdrop="static" centered animation={false}>
			<Modal.Header closeButton>
				<Modal.Title>
					<h5 className="mb-0">Edit video</h5>
				</Modal.Title>
			</Modal.Header>
			<Modal.Body className="px-4 py-3">
				<Form onSubmit={onSubmit} id="upload-form" className="w-100">
					<Form.Control name="userHash" type="hidden" defaultValue={video.VideoHash} required />

					<Form.Row>
						<Form.Label column xs={3}>Title:</Form.Label>
						<Col>
							<Form.Control name="title" type="text" defaultValue={video.Title} required />
						</Col>
					</Form.Row>

					<Form.Row>
						<Form.Label column xs={3}>Video date:</Form.Label>
						<Col>
							<Form.Control name="videoDate" type="date" defaultValue={video.VideoDate} required />
						</Col>
					</Form.Row>

					<Form.Row>
						<Form.Label column xs={3}>View count:</Form.Label>
						<Col>
							<Form.Control name="viewCount" type="number" defaultValue={video.ViewCount} required />
						</Col>
					</Form.Row>

					<Form.Row>
						<Form.Label column xs={3}>Description:</Form.Label>
						<Col>
							<Form.Control name="description" type="text" defaultValue={video.Description} />
						</Col>
					</Form.Row>

					<Form.Row>
						<Form.Label column xs={3}>Tags:</Form.Label>
						<Col className="pt-2">
							{isLoadingTags ? (
								<Spinner animation="grow" size="sm" />
							) : (
								allTags.map(tag => (
									<Form.Check
										key={tag}
										custom
										inline
										label={tag}
										type="checkbox"
										name={tag}
										id={tag}
										value={true}
										defaultChecked={video.Tags ? video.Tags.includes(tag) : false}
									/>
								))
							)}
						</Col>
					</Form.Row>

					<hr />

					<Form.Row style={{ flexWrap: "nowrap" }}>
						<Button variant="success" type="submit" className="w-25">Submit</Button>
					</Form.Row>
				</Form>
			</Modal.Body>
		</Modal>
	);
}
Example #19
Source File: ManageTagsTable.js    From serverless-media-portal with MIT License 4 votes vote down vote up
export default function ManageTagsTable() {
	const [isLoading, setIsLoading] = useState(true);
	const [tags, setTags] = useState([]);
	const [modalIsOpen, setModalIsOpen] = useState(false);
	const { addToast } = useToasts();

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

	const loadTags = async () => {
		const res = await authGet("http://localhost:3001/dev/listAllTags");

		if (res && res.tags) {
			setTags(res.tags);
			setIsLoading(false);
		}
	};

	const onDeleteClicked = async tagName => {
		setIsLoading(true);
		const res = await authGet(`http://localhost:3001/dev/deleteTag?tagName=${tagName}`);
		
		if(res && res.success) {
			await loadTags();
			addNotification("Tag deleted", "success");
		} else {
			addNotification("Error deleting tag", "error");
			setIsLoading(false);
		}
	};

	const addTagClicked = () => {
		setModalIsOpen(true);
	};

	const addNotification = (msg, type) => {
		addToast(msg, {
			appearance: type,
			autoDismiss: true
		});
	};

	const onTagModalClosed = performReload => {
		setModalIsOpen(false);

		if(performReload === true) {
			setIsLoading(true);
			loadTags();
		}
	};

	return (
		<>
			<Table striped bordered hover responsive>
				<thead>
					<tr>
						<th colSpan="99" className="text-center bg-white">
							<div className="d-inline-block pt-1">Manage Tags</div>
							<Button
								variant="success"
								size="sm"
								className="float-right"
								onClick={() => addTagClicked()}
							>
								Add Tag
							</Button>
						</th>
					</tr>
					<tr>
						<th>Name</th>
						<th style={{ width: 0 }}></th>
					</tr>
				</thead>
				<tbody>
					{isLoading ? (
						<tr>
							<td colSpan="4" className="text-center">
								<Spinner animation="border" size="sm" />
							</td>
						</tr>
					) : (
						tags.map(tag => (
							<tr key={tag.TagName}>
								<td>{tag.TagName}</td>
								<td className="d-flex w-20">
									<Button
										variant="danger"
										size="sm"
										className="ml-auto"
										onClick={() => { 
											if (window.confirm("Are you sure you wish to delete this tag?")) {
												onDeleteClicked(tag.TagName);
											}
										}}
										disabled={tag.TagName === "Admin"}
									>
										Delete
									</Button>
								</td>
							</tr>
						))
					)}
				</tbody>
			</Table>

			<AddTagModal 
				isOpen={modalIsOpen} 
				close={onTagModalClosed} 
			/>
		</>
	);
}
Example #20
Source File: ManageUsersTable.js    From serverless-media-portal with MIT License 4 votes vote down vote up
export default function ManageUsersTable() {
	const [isLoading, setIsLoading] = useState(true);
	const [users, setUsers] = useState([]);
	const [selectedUser, setSelectedUser] = useState({});
	const [userIsBeingEdited, setUserIsBeingEdited] = useState(false);
	const [modalIsOpen, setModalIsOpen] = useState(false);
	const { addToast } = useToasts();
	const navigate = useNavigate();

	useEffect(() => {
		setIsLoading(true);
		loadUsers();
	}, []);

	const loadUsers = async () => {
		const res = await authGet("http://localhost:3001/dev/listUsers");

		if (res && res.users) {
			setUsers(res.users);
			setIsLoading(false);
		}
	};

	const onEditClicked = userHash => {
		setModalIsOpen(true);
		setUserIsBeingEdited(true);
		setSelectedUser(users.find(x => x.UserHash === userHash));
	};

	const onDeleteClicked = (userToDelete) => {
		const msg = userToDelete.UserHash === "$2a$10$yGsdhh0HUIWMoECia9IcLeY2R8VMPeYLWSskup3bqHdbVAmNnGNRi"
			? "Are you sure you want to delete the temporary admin user? If you haven't created another admin user, you will lose access to this page"
			: `Are you sure you wish to delete ${userToDelete.DisplayName} ?`;

		if (window.confirm(msg)) {
			deleteUser(userToDelete.UserHash);
		}
	};

	const deleteUser = async userHash => {
		setIsLoading(true);
		const res = await authGet(`http://localhost:3001/dev/deleteUser?userHash=${userHash}`);

		if (res && res.success) {
			addNotification("User deleted", "success");

			// When users delete the temporary admin, immediately redirect them to login
			if (userHash === "$2a$10$yGsdhh0HUIWMoECia9IcLeY2R8VMPeYLWSskup3bqHdbVAmNnGNRi") {
				navigate("/");
				window.location.reload("/");
			} else {
				await loadUsers();
			}
		} else {
			addNotification("Error deleting user", "error");
		}
	};

	const onAddUserClicked = () => {
		setModalIsOpen(true);
		setUserIsBeingEdited(false);
	};

	const addNotification = (msg, type) => {
		addToast(msg, {
			appearance: type,
			autoDismiss: true
		});
	};

	const onModalClosed = (performReload) => {
		setModalIsOpen(false);
		setSelectedUser({});

		if (performReload === true) {
			setIsLoading(true);
			loadUsers();
		}
	};

	return (
		<>
			<Table className="mb-5" striped bordered hover responsive>
				<thead>
					<tr>
						<th colSpan="99" className="text-center bg-white">
							<div className="d-inline-block pt-1">Manage Users</div>
							<Button
								variant="success"
								size="sm"
								className="float-right"
								onClick={() => onAddUserClicked()}
							>
								Add User
							</Button>
						</th>
					</tr>
					<tr>
						<th style={{ width: "300px" }}>Name</th>
						<th>Hash</th>
						<th>Tags</th>
						<th style={{ width: "130px" }}></th>
					</tr>
				</thead>
				<tbody>
					{isLoading ? (
						<tr>
							<td colSpan="4" className="text-center">
								<Spinner animation="border" size="sm" />
							</td>
						</tr>
					) : (
						users.map(user => (
							<tr key={user.DisplayName}>
								<td>{user.DisplayName}</td>
								<td style={{ maxWidth: "100px", textOverflow: "ellipsis", overflow: "hidden" }} title={user.UserHash}>{user.UserHash}</td>
								<td>{user.Tags.join(", ")}</td>
								<td>
									<Button
										variant="warning"
										size="sm"
										className="ml-auto mr-1"
										onClick={() => onEditClicked(user.UserHash)}
										disabled={user.UserHash === "$2a$10$yGsdhh0HUIWMoECia9IcLeY2R8VMPeYLWSskup3bqHdbVAmNnGNRi"}
									>
										Edit
									</Button>
									<Button
										variant="danger"
										size="sm"
										className="ml-auto"
										onClick={() => onDeleteClicked(user)}
										disabled={users.length === 1}
									>
										Delete
									</Button>
								</td>
							</tr>
						))
					)}
				</tbody>
			</Table>

			<AddOrEditUserModal
				user={selectedUser}
				isOpen={modalIsOpen}
				close={onModalClosed}
				editUserMode={userIsBeingEdited}
			/>
		</>
	);
}
Example #21
Source File: ThumbnailSelector.js    From serverless-media-portal with MIT License 4 votes vote down vote up
/**
 * This component should be a target for refactoring; it's not the cleanest approach.
 * 
 * This component works by taking a video name and attempting to fetch the 3 thumbnails 
 * that it expects to be generated. It generates the URL of the thumbnail based on the 
 * video name then makes a total of 12 attempts to fetch the file, with a 5 second delay 
 * between each attempt. This assumes that at least one thumbnail will be generated 
 * within a minute it being called (i.e. after the video upload has completed).
 */
export function ThumbnailSelector({ videoName, onThumbnailSelected }) {
	const [thumbnailImageNames, setThumbnailImageNames] = useState([]);
	const thumbnailImageNamesThatExist = useRef([]);
	const [forceRender, setForceRender] = useState(true);
	const [selectedThumbnailUrl, setSelectedThumbnailUrl] = useState();
	const [haveAllImagesBeenLoaded, setHaveAllImagesBeenLoaded] = useState(false);

	const numberOfThumbnailsToFetch = 3;

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

	useEffect(() => {
		loadImages();
	}, [thumbnailImageNames]);

	useEffect(() => {
		setForceRender(!forceRender);
		selectedThumbnail(thumbnailImageNamesThatExist.current[0]);

		if (thumbnailImageNamesThatExist.current.length === numberOfThumbnailsToFetch) {
			setHaveAllImagesBeenLoaded(true);
		}
	}, [thumbnailImageNamesThatExist.current]);

	const buildThumbnailUrlList = async () => {
		const thumbnailImages = [];
		const videoNameWithoutExtension = videoName.replace(".mp4", "");

		for (let x = 0; x < numberOfThumbnailsToFetch; x += 1) {
			thumbnailImages.push(`${videoNameWithoutExtension}-${x}.jpg`);
		}

		setThumbnailImageNames(thumbnailImages);
	};

	const loadImages = async () => {
		for (let x = 0; x < thumbnailImageNames.length; x++) {
			await attemptImageLoad(`${thumbnailImageNames[x]}`, 1);
		}
	};

	const attemptImageLoad = async (imageNameWithExtension, attemptNumber) => {
		try {
			const res = await fetch(`https://${process.env.REACT_APP_imageCloudfrontDomain}/${imageNameWithExtension}`, { method: "HEAD" });

			if (res.ok) {
				const newArr = JSON.parse(JSON.stringify(thumbnailImageNamesThatExist.current));
				newArr.push(imageNameWithExtension);
				thumbnailImageNamesThatExist.current = newArr;
				setForceRender(!forceRender);
			} else {
				throw "Didn't find image";
			}
		} catch (e) {
			if (attemptNumber <= 12) {
				setTimeout(() => {
					attemptImageLoad(imageNameWithExtension, attemptNumber + 1);
				}, 4000);
			} else {
				console.log("All 12 attempts have failed for: " + imageNameWithExtension);
				setHaveAllImagesBeenLoaded(true);
			}
		}
	};

	const selectedThumbnail = url => {
		setSelectedThumbnailUrl(url);
		onThumbnailSelected(url);
	};

	return (
		<div>
			{thumbnailImageNamesThatExist.current.map(name => (
				<ThumbnailImage
					src={`https://${process.env.REACT_APP_imageCloudfrontDomain}/${name}`}
					key={name}
					className={selectedThumbnailUrl === name ? "selected-thumbnail" : ""}
					onClick={() => selectedThumbnail(name)}
				/>
			))}

			{haveAllImagesBeenLoaded || (
				<ThumbnailLoadingPlaceholder>
					<Spinner animation="grow" size="sm" />
					<div>Fetching thumbnails</div>
				</ThumbnailLoadingPlaceholder>
			)}
		</div>
	);
}
Example #22
Source File: Upload.js    From serverless-media-portal with MIT License 4 votes vote down vote up
export default function Upload() {
	const [tags, setTags] = useState([]);
	const [videoDuration, setVideoDuration] = useState(0);
	const [isStatusMessageVisible, setIsStatusMessageVisible] = useState(false);
	const [statusMessage, setStatusMessage] = useState();

	const [videoUploadInProgress, setVideoUploadInProgress] = useState(false);
	const [videoHasBeenUploaded, setVideoHasBeenUploaded] = useState(false);
	const [selectedVideoName, setSelectedVideoName] = useState();
	const [selectedThumbnailName, setSelectedThumbnailName] = useState();
	const { addToast } = useToasts();

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

	const loadTags = async () => {
		const res = await authGet("http://localhost:3001/dev/listAllTags");

		if (res && res.tags) {
			setTags(res.tags);
		}
	};

	const onSubmit = async e => {
		e.preventDefault();
		if (videoUploadInProgress || !videoHasBeenUploaded) { return; }

		const formData = getFormData(e.target);
		setIsStatusMessageVisible(true);
		setStatusMessage("Uploading form");

		const formUploadResult = await performFormUpload(formData);
		if (formUploadResult.success) {
			setStatusMessage("Form and video submission complete");
			addNotification("Form submission complete", "success");
		}
	};

	const getFormData = form => {
		const formData = new FormData(form);
		const data = Object.fromEntries(formData.entries());

		return data;
	};

	const performFormUpload = async formData => {
		const data = {
			VideoFileName: selectedVideoName,
			VideoDate: formData.date,
			Title: formData.title,
			Description: formData.description,
			Duration: formData.duration,
			ThumbnailName: selectedThumbnailName,
			Tags: getSelectedTags(formData)
		};

		const res = await authPost("http://localhost:3001/dev/addVideo", {
			formData: data
		});

		return res;
	};

	const getSelectedTags = formData => {
		const tagNames = tags.map(x => x.TagName);
		const selectedTags = Object.keys(formData).filter(key => tagNames.includes(key));

		return selectedTags;
	};


	const onVideoSelection = async e => {
		setIsStatusMessageVisible(true);
		setVideoUploadInProgress(true);
		const videoFile = e.target.files[0];

		if (isFileValid(videoFile)) {
			getAndSetVideoDuration(videoFile);
			await uploadFile(videoFile);
		}
	};

	const isFileValid = file => {
		const fileSizeInMB = Math.floor(file.size / 1024 / 1024);
		if (fileSizeInMB > 512) {
			setStatusMessage("File exceeds 512MB limit");
		} else if (!file.name.includes(".mp4")) {
			setStatusMessage("Selected file is not an MP4");
		} else {
			return true;
		}
	};

	const uploadFile = async videoFile => {
		setStatusMessage("Getting presigned URL");
		const presignedUrl = await getPresignedUrl(videoFile.name);

		if (presignedUrl) {
			setStatusMessage("Performing file upload");
			if (await sendFileToPresignedUrl(presignedUrl, videoFile)) {
				setStatusMessage("Video uploaded");
				setSelectedVideoName(videoFile.name);
				setVideoUploadInProgress(false);
				setVideoHasBeenUploaded(true);
				addNotification("Video uploaded", "success");
			}
		}

		setVideoUploadInProgress(false);
	};

	const getPresignedUrl = async fileName => {
		const res = await authGet(`http://localhost:3001/dev/getPresignedUrlForVideoUpload?fileName=${fileName}`);

		if (res && res.presignedUrl) {
			return res.presignedUrl;
		} else {
			setStatusMessage("Error in getPresignedUrl()");
			console.error(res);
			return false;
		}
	};

	const sendFileToPresignedUrl = async (presignedUrl, file) => {
		const res = await fetch(presignedUrl, {
			method: "PUT",
			body: file,
			headers: {
				"Content-Type": "video/mp4"
			}
		});

		if (res.status === 200) {
			return true;
		} else {
			setStatusMessage("Error in performFileUpload()");
			console.error(res);
			return false;
		}
	};

	const getAndSetVideoDuration = videoFile => {
		const video = document.createElement("video");
		video.preload = "metadata";

		video.onloadedmetadata = function () {
			window.URL.revokeObjectURL(video.src);
			const duration = Math.floor(video.duration);
			setVideoDuration(duration);
		};

		video.src = URL.createObjectURL(videoFile);
	};

	const clearForm = () => {
		setVideoDuration(0);
		setIsStatusMessageVisible(false);
		setStatusMessage();
		setVideoUploadInProgress(false);
		setVideoHasBeenUploaded(false);
		setSelectedVideoName();
		setSelectedThumbnailName();
		document.getElementById("upload-form").reset();
	};

	const addNotification = (msg, type) => {
		addToast(msg, {
			appearance: type,
			autoDismiss: true
		});
	};

	return (
		<Row style={{ padding: "1.75em" }}>
			<Col lg={7} md={10} sm={12}>
				<div className="d-flex">
					<h5>Upload a new video</h5>
					<Button
						variant="secondary"
						size="sm"
						className="ml-auto"
						onClick={() => clearForm()}
					>
						Clear Form
					</Button>
				</div>

				<hr />

				<Form onSubmit={onSubmit} id="upload-form">
					<Form.Row>
						<Form.Label column lg={3}>Video Title:</Form.Label>
						<Col>
							<Form.Control name="title" type="text" minLength="1" required />
						</Col>
					</Form.Row>

					<Form.Row>
						<Form.Label column lg={3}>Taken on:</Form.Label>
						<Col>
							<Form.Control name="date" type="date" required />
						</Col>
					</Form.Row>

					<Form.Row>
						<Form.Label column lg={3}>Duration:</Form.Label>
						<Col>
							<Form.Control
								name="duration"
								type="text"
								value={videoDuration}
								readOnly
								required
							/>
						</Col>
					</Form.Row>

					<Form.Row>
						<Form.Label column lg={3}>Description:</Form.Label>
						<Col>
							<Form.Control
								name="description"
								as="textarea"
								placeholder="Description is optional"
								rows={3}
							/>
						</Col>
					</Form.Row>

					<Form.Row>
						<Form.Label column lg={3} className="text-nowrap">Select {videoHasBeenUploaded ? "thumbnail" : "video"}:</Form.Label>
						<Col>
							{videoUploadInProgress ? (
								<Spinner animation="grow" size="sm" />
							) : videoHasBeenUploaded ? (
								<ThumbnailSelector
									videoName={selectedVideoName}
									onThumbnailSelected={setSelectedThumbnailName}
								/>
							) : (
								<Form.Control
									name="file"
									id="file-input"
									type="file"
									placeholder="Normal text"
									style={{ paddingTop: "0.5em" }}
									accept=".mp4"
									onChange={async e => await onVideoSelection(e)}
									required
								/>
							)}
						</Col>
					</Form.Row>

					<Form.Row>
						<Form.Label column lg={3}>Select tags:</Form.Label>
						<Col style={{ paddingTop: "10px" }}>
							{tags.length === 0 ? (
								<Spinner animation="grow" size="sm" />
							) : (
								tags.map(tag => (
									<Form.Check
										key={tag.TagName}
										custom
										inline
										label={tag.TagName}
										type="checkbox"
										name={tag.TagName}
										id={tag.TagName}
										value={true}
									/>
								))
							)}
						</Col>
					</Form.Row>

					<hr />

					<Form.Row style={{ flexWrap: "nowrap" }}>
						<Button variant="success" type="submit" className="w-25" disabled={!videoHasBeenUploaded}>
							{videoUploadInProgress ? (
								<Spinner animation="border" size="sm" />
							) : (
								<>Submit</>
							)}
						</Button>

						{!isStatusMessageVisible || (
							<Button variant="secondary" className="w-75 ml-2">
								{statusMessage}
							</Button>
						)}
					</Form.Row>
				</Form>
			</Col>
		</Row>
	);
}
Example #23
Source File: AllFresherJob.js    From easy-job-intern with MIT License 4 votes vote down vote up
AllFreshersJobs = () => {
  const { state, dispatch } = useContext(UserContext);
  const [freshersJobs, setFreshersJobs] = useState([]);
  const [loading, setLoading] = useState(true);




  useEffect(() => {
    axios({
      method: "get",
      url: "http://localhost:5000/user/all-freshersjobs",
      headers: {
        Authorization: "Bearer " + localStorage.getItem("jwt"),
      },
    })
      .then((res) => {
        // console.log(res);
        setLoading(false);
        if (res.data.error) {
          // console.log(res.data.error);
          // alert(res.data.error);
          const notify = () => toast(res.data.error);
          notify();
        } else {
          // console.log(res.data.freshersjobs);
          setFreshersJobs(res.data.freshersjobs);
          // console.log(freshersJobs);
        }
      })
      .catch((err) => {
        setLoading(false);
        console.log("Error: ", err);
      });
  }, [freshersJobs]);

  if (freshersJobs && freshersJobs[4]) {
    console.log(freshersJobs[4]);
    const t = new Date(freshersJobs[4].startDate).toString("YYYY-MM-DD");
    console.log(t);
  }

  

  return (
    <div className="internshipsOuterContainer">
      <Toaster />
      <Row className="justify-content-xl-start justify-content-lg-around justify-content-sm-center">
        {loading ? (
          <div className="h-100 w-100 d-flex justify-content-center align-items-center">
            <Spinner
              animation="border"
              variant="light"
              style={{
                borderColor: "#515b66",
                borderRightColor: "transparent",
              }}
            />
          </div>
        ) : freshersJobs && !freshersJobs.length > 0 ? (
          <Alert
            variant="danger"
            className="w-100"
            style={{
              backgroundColor: "#343A40",
              border: "none",
              color: "#ffc107",
            }}
          >
            No Fresher Jobs available right now
          </Alert>
        ) : (
          freshersJobs &&
          freshersJobs.map((fresher) => {
            return (
              <Col
                key={fresher._id}
                className="col-xl-4 col-lg-5 col-md-6 col-sm-11 col-12 colPost"
              >
                <FresherJobCard
                  fresherjob={fresher}
                  userId={state.user._id}
                />
              </Col>
            );
          })
        )}
      </Row>
    </div>
  );
}
Example #24
Source File: BookmarkFresherJob.js    From easy-job-intern with MIT License 4 votes vote down vote up
BookmarkFreshersJobs = () => {
  const { state, dispatch } = useContext(UserContext);
  const [freshersJobs, setFreshersJobs] = useState([]);
  const [loading, setLoading] = useState(true);
  const deletePost = (postId) => {
    axios({
      method: "delete",
      url: "http://localhost:5000/employer/delete-freshersjob",
      data: {
        postId,
      },
      headers: {
        Authorization: "Bearer " + localStorage.getItem("jwt"),
        "Content-Type": "application/json",
      },
    })
      .then((res) => {
        console.log(res);
        if (res.data.error) {
          console.log(res.data.error);
          // alert(res.data.error);
          const notify = () => toast(res.data.error);
          notify();
        } else {
          // console.log(res.data.jobs);
          // setJobs(res.data.jobs);
          // console.log(jobs);
          const notify = () => toast(res.data.message);
          notify();
        }
      })
      .catch((err) => {
        console.log("Error: ", err);
      });
  };




  useEffect(() => {
    axios({
      method: "post",
      url: "http://localhost:5000/student/getBookmarkedFresherJobs",
      headers: {
        Authorization: "Bearer " + localStorage.getItem("jwt"),
      },
    })
      .then((res) => {
        console.log(res);
        setLoading(false);
        if (res.data.error) {
          // console.log(res.data.error);
          // alert(res.data.error);
          const notify = () => toast(res.data.error);
          notify();
        } else {
          // console.log(res.data.freshersjobs);
          setFreshersJobs(res.data.fresherjobs);
          // console.log(freshersJobs);
        }
      })
      .catch((err) => {
        setLoading(false);
        console.log("Error: ", err);
      });
  }, [freshersJobs]);

  if (freshersJobs && freshersJobs[4]) {
    console.log(freshersJobs[4]);
    const t = new Date(freshersJobs[4].startDate).toString("YYYY-MM-DD");
    console.log(t);
  }

  

  return (
    <div className="internshipsOuterContainer">
      <Toaster />
      <Row className="justify-content-xl-start justify-content-lg-around justify-content-sm-center">
        {loading ? (
          <div className="h-100 w-100 d-flex justify-content-center align-items-center">
            <Spinner
              animation="border"
              variant="light"
              style={{
                borderColor: "#515b66",
                borderRightColor: "transparent",
              }}
            />
          </div>
        ) : freshersJobs && !freshersJobs.length > 0 ? (
          <Alert
            variant="danger"
            className="w-100"
            style={{
              backgroundColor: "#343A40",
              border: "none",
              color: "#ffc107",
            }}
          >
            No Fresher Jobs available right now
          </Alert>
        ) : (
          freshersJobs &&
          freshersJobs.map((fresher) => {
            return (
              <Col
                key={fresher._id}
                className="col-xl-4 col-lg-5 col-md-6 col-sm-11 col-12 colPost"
              >
                <FresherJobCard
                  fresherjob={fresher}
                  deletePost={deletePost}
                  userId={state.user._id}
                />
              </Col>
            );
          })
        )}
      </Row>
    </div>
  );
}
Example #25
Source File: FresherJobsGroupedByIndustry.js    From easy-job-intern with MIT License 4 votes vote down vote up
FresherJobsGroupedByIndustry = () => {
  const { state, dispatch } = useContext(UserContext);
  const [freshersJobs, setFreshersJobs] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    axios({
      method: "get",
      url: "http://localhost:5000/user/freshersjob/industry",
      headers: {
        Authorization: "Bearer " + localStorage.getItem("jwt"),
      },
    })
      .then((res) => {
        // console.log(res);
        setLoading(false);
        if (res.data.error) {
          console.log(res.data.error);
          // alert(res.data.error);
          const notify = () => toast(res.data.error);
          notify();
        } else {
          // console.log(res.data.freshersjobs);
          setFreshersJobs(res.data.freshersjobs);
          // console.log(freshersJobs);
        }
      })
      .catch((err) => {
        setLoading(false);
        console.log("Error: ", err);
      });
  }, []);

  if (freshersJobs && freshersJobs[4]) {
    console.log(freshersJobs[4]);
    const t = new Date(freshersJobs[4].startDate).toString("YYYY-MM-DD");
    console.log(t);
  }

  return (
    <div className="internshipsOuterContainer">
      <Toaster />
      {loading ? (
        <div className="h-100 w-100 d-flex justify-content-center align-items-center">
          <Spinner
            animation="border"
            variant="light"
            style={{
              borderColor: "#515b66",
              borderRightColor: "transparent",
            }}
          />
        </div>
      ) : freshersJobs && !freshersJobs.length > 0 ? (
        <Alert
          variant="danger"
          className="w-100"
          style={{
            backgroundColor: "#343A40",
            border: "none",
            color: "#ffc107",
          }}
        >
          No Fresher Jobs available right now
        </Alert>
      ) : (
        freshersJobs &&
        freshersJobs.map((catefresher) => (
          <div key={catefresher._id}>
            <h1 className="parameter">{catefresher._id}</h1>
            <Row className="justify-content-xl-start justify-content-lg-around justify-content-sm-center">
              {catefresher.freshersjobs &&
                catefresher.freshersjobs.map((fresher) => {
                  // console.log(internship.createdBy._id, state.user._id);
                  return (
                    <Col
                      key={fresher._id}
                      className="col-xl-4 col-lg-5 col-md-6 col-sm-11 col-12 colPost"
                    >
                      <FresherJobCard
                        fresherjob={fresher}
                        userId={state.user._id}
                      />
                    </Col>
                  );
                })}
            </Row>
          </div>
        ))
      )}
    </div>
  );
}
Example #26
Source File: FresherJobsGroupedByLocation.js    From easy-job-intern with MIT License 4 votes vote down vote up
FresherJobsGroupedByLocation = () => {
  const { state, dispatch } = useContext(UserContext);
  const [freshersJobs, setFreshersJobs] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    axios({
      method: "get",
      url: "http://localhost:5000/user/freshersjob/location",
      headers: {
        Authorization: "Bearer " + localStorage.getItem("jwt"),
      },
    })
      .then((res) => {
        // console.log(res);
        setLoading(false);
        if (res.data.error) {
          console.log(res.data.error);
          // alert(res.data.error);
          const notify = () => toast(res.data.error);
          notify();
        } else {
          // console.log(res.data.freshersjobs);
          setFreshersJobs(res.data.freshersJobs);
          // console.log(freshersJobs);
        }
      })
      .catch((err) => {
        setLoading(false);
        console.log("Error: ", err);
      });
  }, []);

  if (freshersJobs && freshersJobs[4]) {
    console.log(freshersJobs[4]);
    const t = new Date(freshersJobs[4].startDate).toString("YYYY-MM-DD");
    console.log(t);
  }

  return (
    <div className="internshipsOuterContainer">
      <Toaster />
      {loading ? (
        <div className="h-100 w-100 d-flex justify-content-center align-items-center">
          <Spinner
            animation="border"
            variant="light"
            style={{
              borderColor: "#515b66",
              borderRightColor: "transparent",
            }}
          />
        </div>
      ) : freshersJobs && !freshersJobs.length > 0 ? (
        <Alert
          variant="danger"
          className="w-100"
          style={{
            backgroundColor: "#343A40",
            border: "none",
            color: "#ffc107",
          }}
        >
          No Fresher Jobs available right now
        </Alert>
      ) : (
        freshersJobs &&
        freshersJobs.map((catefresher) => (
          <div key={catefresher._id}>
            <h1 className="parameter">{catefresher._id}</h1>
            <Row className="justify-content-xl-start justify-content-lg-around justify-content-sm-center">
              {catefresher.freshersJobs &&
                catefresher.freshersJobs.map((fresher) => {
                  // console.log(internship.createdBy._id, state.user._id);
                  return (
                    <Col
                      key={fresher._id}
                      className="col-xl-4 col-lg-5 col-md-6 col-sm-11 col-12 colPost"
                    >
                      <FresherJobCard
                        fresherjob={fresher}
                        userId={state.user._id}
                      />
                    </Col>
                  );
                })}
            </Row>
          </div>
        ))
      )}
    </div>
  );
}
Example #27
Source File: FresherJobsGroupedByStream.js    From easy-job-intern with MIT License 4 votes vote down vote up
FresherJobsGroupedByStream = () => {
  const { state, dispatch } = useContext(UserContext);
  const [freshersJobs, setFreshersJobs] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    axios({
      method: "get",
      url: "http://localhost:5000/user/freshersjob/stream",
      headers: {
        Authorization: "Bearer " + localStorage.getItem("jwt"),
      },
    })
      .then((res) => {
        console.log(res);
        setLoading(false);
        if (res.data.error) {
          console.log(res.data.error);
          // alert(res.data.error);
          const notify = () => toast(res.data.error);
          notify();
        } else {
          // console.log(res.data.freshersjobs);
          setFreshersJobs(res.data.freshersjobs);
          // console.log(freshersJobs);
        }
      })
      .catch((err) => {
        setLoading(false);
        console.log("Error: ", err);
      });
  }, []);

  if (freshersJobs && freshersJobs[4]) {
    console.log(freshersJobs[4]);
    const t = new Date(freshersJobs[4].startDate).toString("YYYY-MM-DD");
    console.log(t);
  }

  return (
    <div className="internshipsOuterContainer">
      <Toaster />
      {loading ? (
        <div className="h-100 w-100 d-flex justify-content-center align-items-center">
          <Spinner
            animation="border"
            variant="light"
            style={{
              borderColor: "#515b66",
              borderRightColor: "transparent",
            }}
          />
        </div>
      ) : freshersJobs && !freshersJobs.length > 0 ? (
        <Alert
          variant="danger"
          className="w-100"
          style={{
            backgroundColor: "#343A40",
            border: "none",
            color: "#ffc107",
          }}
        >
          No Fresher Jobs available right now
        </Alert>
      ) : (
        freshersJobs &&
        freshersJobs.map((catefresher) => (
          <div key={catefresher._id}>
            <h1 className="parameter">{catefresher._id}</h1>
            <Row className="justify-content-xl-start justify-content-lg-around justify-content-sm-center">
              {catefresher.freshersjobs &&
                catefresher.freshersjobs.map((fresher) => {
                  // console.log(internship.createdBy._id, state.user._id);
                  return (
                    <Col
                      key={fresher._id}
                      className="col-xl-4 col-lg-5 col-md-6 col-sm-11 col-12 colPost"
                    >
                      <FresherJobCard
                        fresherjob={fresher}
                        userId={state.user._id}
                      />
                    </Col>
                  );
                })}
            </Row>
          </div>
        ))
      )}
    </div>
  );
}
Example #28
Source File: FreshersJobByCompanyName.js    From easy-job-intern with MIT License 4 votes vote down vote up
FreshersJobByCompanyName = () => {
  const { state, dispatch } = useContext(UserContext);
  const [freshersJobs, setFreshersJobs] = useState([]);
  const [loading, setLoading] = useState(true);
  const { companyName } = useParams();

  useEffect(() => {
    axios({
      method: "get",
      url: `http://localhost:5000/user/freshersJob/companyName/${companyName}`,
      headers: {
        Authorization: "Bearer " + localStorage.getItem("jwt"),
      },
    })
      .then((res) => {
        // console.log(res);
        setLoading(false);
        if (res.data.error) {
          // console.log(res.data.error);
          // alert(res.data.error);
          const notify = () => toast(res.data.error);
          notify();
        } else {
          // console.log(res.data.freshersjobs);
          setFreshersJobs(res.data.FreshersJobs);
          // console.log(freshersJobs);
        }
      })
      .catch((err) => {
        setLoading(false);
        console.log("Error: ", err);
      });
  }, [freshersJobs]);

  if (freshersJobs && freshersJobs[4]) {
    console.log(freshersJobs[4]);
    const t = new Date(freshersJobs[4].startDate).toString("YYYY-MM-DD");
    console.log(t);
  }

  return (
    <div className="internshipsOuterContainer">
      <Toaster />
      <Row className="justify-content-xl-start justify-content-lg-around justify-content-sm-center">
        {loading ? (
          <div className="h-100 w-100 d-flex justify-content-center align-items-center">
            <Spinner
              animation="border"
              variant="light"
              style={{
                borderColor: "#515b66",
                borderRightColor: "transparent",
              }}
            />
          </div>
        ) : freshersJobs && !freshersJobs.length > 0 ? (
          <Alert
            variant="danger"
            className="w-100"
            style={{
              backgroundColor: "#343A40",
              border: "none",
              color: "#ffc107",
            }}
          >
            No Fresher Jobs available right now
          </Alert>
        ) : (
          freshersJobs &&
          freshersJobs.map((fresher) => {
            return (
              <Col
                key={fresher._id}
                className="col-xl-4 col-lg-5 col-md-6 col-sm-11 col-12 colPost"
              >
                <FresherJobCard fresherjob={fresher} userId={state.user._id} />
              </Col>
            );
          })
        )}
      </Row>
    </div>
  );
}
Example #29
Source File: AllInternships.js    From easy-job-intern with MIT License 4 votes vote down vote up
AllInternships = () => {
  const { state, dispatch } = useContext(UserContext);
  const [internships, setInternships] = useState([]);
  const [loading, setLoading] = useState(true);
  // console.log(internships);
  // console.log(state);
  useEffect(() => {
    axios({
      method: "get",
      url: "http://localhost:5000/user/all-internships",
      headers: {
        Authorization: "Bearer " + localStorage.getItem("jwt"),
      },
    })
      .then((res) => {
        console.log(res);
        setLoading(false);
        if (res.data.error) {
          console.log(res.data.error);
          // alert(res.data.error);
          const notify = () => toast(res.data.error);
          notify();
        } else {
          console.log(res.data.internships);
          setInternships(res.data.internships);
          console.log(internships);
        }
      })
      .catch((err) => {
        setLoading(false);
        console.log("Error: ", err);
      });
  }, []);

  if (internships && internships[4]) {
    console.log(internships[4]);
    const t = new Date(internships[4].startDate).toString("YYYY-MM-DD");
    console.log(t);
  }

  const deletePost = (postId) => {
    axios({
      method: "delete",
      url: "http://localhost:5000/employer/delete-internship",
      data: {
        postId,
      },
      headers: {
        Authorization: "Bearer " + localStorage.getItem("jwt"),
        "Content-Type": "application/json",
      },
    })
      .then((res) => {
        console.log(res);
        if (res.data.error) {
          // console.log(res.data.error);
          const notify = () => toast(res.data.error);
          notify();
        } else {
          setInternships(res.data.internships);
          window.location.reload(false);
          const notify = () => toast(res.data.message);
          notify();
        }
      })
      .catch((err) => {
        console.log("Error: ", err);
      });
  };

  return (
    <div className="internshipsOuterContainer">
      <Toaster />
      <Row className="justify-content-xl-start justify-content-lg-around justify-content-sm-center">
        {loading ? (
          <div className="h-100 w-100 d-flex justify-content-center align-items-center">
            <Spinner
              animation="border"
              variant="light"
              style={{
                borderColor: "#515b66",
                borderRightColor: "transparent",
              }}
            />
          </div>
        ) : internships && !internships.length > 0 ? (
          <Alert
            variant="danger"
            className="w-100 "
            style={{
              backgroundColor: "#343A40",
              border: "none",
              color: "#ffc107",
            }}
          >
            No internships available right now
          </Alert>
        ) : (
          internships &&
          internships.map((internship) => {
            // console.log(internship.createdBy._id, state.user._id);
            return (
              <Col
                key={internship._id}
                className="col-xl-4 col-lg-5 col-md-6 col-sm-11 col-12 colPost"
              >
                <InternshipCard
                  internship={internship}
                  userId={state.user._id}
                  deletePost={deletePost}
                />
              </Col>
            );
          })
        )}
      </Row>
    </div>
  );
}