react-bootstrap#InputGroup JavaScript Examples

The following examples show how to use react-bootstrap#InputGroup. 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: SearchTokenInput.js    From plenty-interface with GNU General Public License v3.0 6 votes vote down vote up
SearchTokenInput = ({ value, onChange, inputRef }) => {
  return (
    <div className="mt-1 flex flex-row w-100">
      <InputGroup>
        <InputGroup.Prepend>
          <InputGroup.Text className="search-icon border-right-0">
            <BsSearch />
          </InputGroup.Text>
        </InputGroup.Prepend>
        <FormControl
          ref={inputRef}
          placeholder="Search"
          className={'shadow-none border-left-0 search-box'}
          value={value}
          onChange={onChange}
        />
      </InputGroup>
    </div>
  );
}
Example #2
Source File: Auth.js    From fifa with GNU General Public License v3.0 6 votes vote down vote up
enterUsername() {
    return (
      <div>
        <Form onSubmit={this.handleLogin}>
          <InputGroup>
            <FormControl
              ref={input => {
                this.usernameInput = input;
              }}
              placeholder="Enter your alias here"
              name="username"
              aria-label="username"
              aria-describedby="text"
              onChange={this.handleUsernameChange}
            />
            <InputGroup.Append>
              <Button>Submit</Button>
            </InputGroup.Append>
          </InputGroup>
        </Form>
      </div>
    );
  }
Example #3
Source File: adv-post-form.js    From stacker.news with MIT License 6 votes vote down vote up
export default function AdvPostForm () {
  return (
    <AccordianItem
      header={<div style={{ fontWeight: 'bold', fontSize: '92%' }}>options</div>}
      body={
        <>
          <Input
            label={<>boost</>}
            name='boost'
            hint={<span className='text-muted'>ranks posts higher temporarily based on the amount</span>}
            append={<InputGroup.Text className='text-monospace'>sats</InputGroup.Text>}
          />
          <Input
            label={<>forward sats to</>}
            name='forward'
            hint={<span className='text-muted'>100% of sats will be sent to this user</span>}
            prepend=<InputGroup.Text>@</InputGroup.Text>
            showValid
          />
        </>
      }
    />
  )
}
Example #4
Source File: Export.js    From anutimetable with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
Export = ({ API, year, session }) => {
  const [path, setPath] = useState('')
  const encoded = encodeURIComponent('http://'+path)
  const name = `ANU Timetable ${session} ${year}`

  return <DropdownButton
    style={{flexGrow: 1}}
    as={InputGroup.Append}
    alignRight
    title='Export'
    variant='outline-primary'
    id='export-button'
    onClick={() => setPath(`${API}/GetICS${window.location.search}`)}
  >
    <Dropdown.Item eventKey="web" target={"_blank"} rel={"noreferrer"}
      href={`webcal://${path}`}>
      <SiApple /> WebCal (eg iOS)
    </Dropdown.Item>
    <Dropdown.Item eventKey="gcal" target={"_blank"} rel={"noreferrer"}
      href={`https://www.google.com/calendar/render?cid=${encoded}`}>
      <SiGooglecalendar /> Google Calendar
    </Dropdown.Item>
    <Dropdown.Item eventKey="msol" target={"_blank"} rel={"noreferrer"}
      // undocumented OWA MSOL/AAD deeplinks. removing the 0 is supposed to work and could be necessary for some accounts
      // but in our case it drops all but the first qs param during parsing (maybe need double-encode?) and adds a 10s+ delay
      // source code - /owa/node_modules/calendar-bootstrap-config/src/routing/browseDiscoverCalendarsRouteHandler.ts
      href={`https://outlook.live.com/calendar/0/addfromweb?name=${name}&url=${encoded}`}>
      <SiMicrosoftoutlook /> Outlook.com
    </Dropdown.Item>
    <Dropdown.Item eventKey="aad" target={"_blank"} rel={"noreferrer"}
      href={`https://outlook.office.com/calendar/0/addfromweb?name=${name}&url=${encoded}`}>
      <SiMicrosoftexchange /> Office 365
    </Dropdown.Item>
    <Dropdown.Divider />
    <Dropdown.Item eventKey="ics" download={`${name} as of ${new Date().toLocaleDateString().replace(/(\/|\\)/g,'.')}.ics`} href={`${window.location.protocol}//${path}`}>
      <RiCalendar2Fill /> Download ICS file
    </Dropdown.Item>
  </DropdownButton>
}
Example #5
Source File: index.js    From wedding-planner with MIT License 6 votes vote down vote up
function InputText(props) {
  return (
    <InputGroup className={props.style}>
      <InputGroup.Prepend>
        <InputGroup.Text id={props.id}>{props.name}</InputGroup.Text>
      </InputGroup.Prepend>
      <FormControl
        aria-label="Default"
        aria-describedby="inputGroup-sizing-default"
        placeholder={props.placeholder}
      />
    </InputGroup>
  );
}
Example #6
Source File: SearchBar.js    From tclone with MIT License 6 votes vote down vote up
function SearchBar(props) {
    let history = useHistory()
    let [value, setValue] = useState('')
    let handleChange = ({ target: { value } }) => {
        setValue(value)
    }
    let handleSubmit = (e) => {
        e.preventDefault();
        let value = e.target.search.value;
        value = encodeURIComponent(value);
        history.push(`/search?q=${value}`)
    }
    let { className } = props;
    return (
        <Form className={className} onSubmit={handleSubmit} role="search">
            <Form.Group className="w-100 mb-0 rounded-pill border-0 px-3"
                style={{ backgroundColor: "rgb(233,236,239)" }}>
                <InputGroup className="w-100">
                    <InputGroup.Prepend>
                        <InputGroup.Text>
                            <FontAwesomeIcon icon={faSearch} />
                        </InputGroup.Text>
                    </InputGroup.Prepend>
                    <Form.Control
                        value={value}
                        onChange={handleChange}
                        style={{ backgroundColor: "rgb(233,236,239)" }}
                        size="sm"
                        type="search"
                        placeholder="Search for posts, #hastags or @users"
                        name="search"
                        id="tsearch"
                    />
                </InputGroup>
            </Form.Group>
        </Form>
    )
}
Example #7
Source File: Room.Join.js    From fifa with GNU General Public License v3.0 5 votes vote down vote up
render() {
    return (
      <div>
        <h2>Enter Room ID</h2>
        <div>
          <Form onSubmit={this.handleSubmit}>
            <InputGroup>
              <FormControl
                ref={input => {
                  this.roomIdInput = input;
                }}
                placeholder="Enter the RoomID here"
                aria-label="roomId"
                name="roomId"
                aria-describedby="text"
                onChange={this.handleDataChange}
              />
            </InputGroup>
            <br />
            Leave blank if no password
            <InputGroup>
              <FormControl
                placeholder="Enter room password"
                name="password"
                aria-label="password"
                aria-describedby="password"
                onChange={this.handleDataChange}
              />
            </InputGroup>
            <br />
            <InputGroup>
              <InputGroup.Append>
                <Button variant="light" type="submit">
                  Join
                </Button>
              </InputGroup.Append>
            </InputGroup>
          </Form>
        </div>
      </div>
    );
  }
Example #8
Source File: Room.Create.js    From fifa with GNU General Public License v3.0 5 votes vote down vote up
render() {
    const { roomId } = this.state;

    return (
      <div>
        <h2>Create New Room</h2>
        <Form onSubmit={this.handleSubmit}>
          <InputGroup>
            <FormControl
              readOnly
              name="roomId"
              value={roomId}
              aria-label="roomId"
              aria-describedby="text"
            />
          </InputGroup>
          <br />
          <h6>Add password to keep it exclusive</h6>
          <InputGroup>
            <FormControl
              ref={input => {
                this.roomIdInput = input;
              }}
              placeholder="Optional: Enter room password"
              name="password"
              aria-label="password"
              aria-describedby="password"
              onChange={this.handleDataChange}
            />
          </InputGroup>
          <br />
          <br />
          <h4>Game Settings</h4>
          <br />
          <h6>Max Time per chance </h6>
          <InputGroup>
            <FormControl
              type="number"
              placeholder="Default: 120"
              name="max-timer-limit"
              aria-label="max-timer-limit"
              aria-describedby="max-timer-limit"
              onChange={this.handleDataChange}
            />
            <InputGroup.Append>
              <InputGroup.Text id="time-prefiz">seconds</InputGroup.Text>
            </InputGroup.Append>
          </InputGroup>
          <br />
          <h6>Max Players Per Team</h6>
          <InputGroup>
            <FormControl
              type="number"
              placeholder="Default: 14"
              name="max-players-limit"
              aria-label="max-players-limit"
              aria-describedby="max-players-limit"
              onChange={this.handleDataChange}
            />
            <InputGroup.Append>
              <InputGroup.Text id="players-prefix">players</InputGroup.Text>
            </InputGroup.Append>
          </InputGroup>
          <br />
          <InputGroup>
            <InputGroup.Append>
              <Button variant="light" type="submit">
                Create
              </Button>
            </InputGroup.Append>
          </InputGroup>
        </Form>
      </div>
    );
  }
Example #9
Source File: SocialModal.js    From portfolio-react with MIT License 5 votes vote down vote up
function SocialModal() {
	return (
		<Social>
			<Container>
				<SocialIcons>
					<Icon label='github'>
						<AiOutlineGithub size={35} />
						<CustomLink href='https://github.com/pranjaljain0' target='_blank'>
							@pranjaljain0
						</CustomLink>
					</Icon>
					<Icon label='linkedin'>
						<AiOutlineLinkedin size={35} />
						<CustomLink
							href='https://www.linkedin.com/in/pranjaljain0/'
							target='_blank'>
							@pranjaljain0
						</CustomLink>
					</Icon>
				</SocialIcons>

				<InputGroup className='mb-3'>
					<FormControl
						placeholder='Full name'
						aria-label='Name'
						aria-describedby='basic-addon1'
					/>
				</InputGroup>

				<InputGroup className='mb-3'>
					<FormControl
						placeholder='Email address'
						aria-label='Email'
						aria-describedby='basic-addon1'
					/>
				</InputGroup>

				<InputGroup>
					<FormControl
						as='textarea'
						aria-label='With textarea'
						placeholder='Write some description'
						style={{
							resize: 'none',
							height: 100,
						}}
					/>
				</InputGroup>

				<ButtonForm>
					<Button variant='outline-secondary' className='float-right'>
						Submit
					</Button>
				</ButtonForm>
			</Container>
		</Social>
	)
}
Example #10
Source File: item-act.js    From stacker.news with MIT License 5 votes vote down vote up
export function ItemActModal () {
  const { item, setItem } = useItemAct()
  const inputRef = useRef(null)
  const me = useMe()

  useEffect(() => {
    inputRef.current?.focus()
  }, [item])

  return (
    <Modal
      show={!!item}
      onHide={() => {
        setItem(null)
      }}
    >
      <div className='modal-close' onClick={() => setItem(null)}>X</div>
      <Modal.Body>
        <Form
          initial={{
            amount: me?.tipDefault,
            default: false
          }}
          schema={ActSchema}
          onSubmit={async ({ amount }) => {
            await item.act({
              variables: {
                id: item.itemId,
                sats: Number(amount)
              }
            })
            await item.strike()
            setItem(null)
          }}
        >
          <Input
            label='amount'
            name='amount'
            innerRef={inputRef}
            required
            autoFocus
            append={<InputGroup.Text className='text-monospace'>sats</InputGroup.Text>}
          />
          <div className='d-flex'>
            <SubmitButton variant='success' className='ml-auto mt-1 px-4' value='TIP'>tip</SubmitButton>
          </div>
        </Form>
      </Modal.Body>
    </Modal>
  )
}
Example #11
Source File: SelectedV2Pool.js    From katanapools with GNU General Public License v2.0 5 votes vote down vote up
render() {
    const {pool: {currentSelectedPool}} = this.props;
    const {selectedTokenToAdd, selectedTokenToLiquidate, amountTokenToAdd, amountTokenToLiquidate} = this.state;
    const self = this;
    let reservesList = 
    <div>
    <ButtonGroup aria-label="Add Liquidity Token">{
    currentSelectedPool.reserves.map(function(item, idx){
    let btnIsActive = '';
    
    if (item.address === selectedTokenToAdd.address) {
      btnIsActive = 'active-select-btn';
    }

      return (<Button key={`add-liquidity-token-${idx}`} onClick={()=>self.addLiquidityTokenSelected(item)} className={`${btnIsActive}`}>
      {item.symbol}
      </Button>)
    })}
    </ButtonGroup>
    <InputGroup>
     <FormControl type="text" value={amountTokenToAdd}  onChange={this.addLiquidityAmountChanged}/>
      <InputGroup.Append>
        <InputGroup.Text id="btnGroupAddon2">{selectedTokenToAdd.symbol}</InputGroup.Text>
      </InputGroup.Append>
    </InputGroup>
    <Button onClick={this.addPoolLiquidity}>Add</Button>
    </div>;
    
    let removeLiquidityReserveList = 
    <div>
    <ButtonGroup aria-label="Remove liquidity token">{
    currentSelectedPool.reserves.map(function(item, idx){
    let btnIsActive = '';
    if (item.address === selectedTokenToLiquidate.address) {
      btnIsActive = 'active-select-btn';
    }
      return (<Button key={`remove-liquidity-token-${idx}`} onClick={()=>self.removeLiquidityTokenSelected(item)} className={`${btnIsActive}`}>
      {item.symbol}
      </Button>)
    })}
    </ButtonGroup>
    <InputGroup>
        <FormControl type="text" value={amountTokenToLiquidate} onChange={this.removeLiquidityAmountChanged}/>
        <InputGroup.Append>
        <InputGroup.Text id="btnGroupAddon2">{selectedTokenToLiquidate.symbol}</InputGroup.Text>
      </InputGroup.Append>
    </InputGroup>
    <Button onClick={this.removePoolLiquidity}>Remove</Button>
    </div>;
    
    return (
      <div>
      <Col lg={12}>
      <Row>
      <Col lg={6}>
      <div>
        Select Reserve to stake
        {reservesList}
      </div>
      </Col>
      <Col lg={6}>
        Remove Liquidity
         {removeLiquidityReserveList}
      </Col>
      </Row>
      </Col>
      </div>
      )
  }
Example #12
Source File: index.js    From stacker.news with MIT License 5 votes vote down vote up
function InviteForm () {
  const [createInvite] = useMutation(
    gql`
      ${INVITE_FIELDS}
      mutation createInvite($gift: Int!, $limit: Int) {
        createInvite(gift: $gift, limit: $limit) {
          ...InviteFields
        }
      }`, {
      update (cache, { data: { createInvite } }) {
        cache.modify({
          fields: {
            invites (existingInviteRefs = []) {
              const newInviteRef = cache.writeFragment({
                data: createInvite,
                fragment: INVITE_FIELDS
              })
              return [newInviteRef, ...existingInviteRefs]
            }
          }
        })
      }
    }
  )

  return (
    <Form
      initial={{
        gift: 100,
        limit: undefined
      }}
      schema={InviteSchema}
      onSubmit={async ({ limit, gift }) => {
        const { error } = await createInvite({
          variables: {
            gift: Number(gift), limit: limit ? Number(limit) : limit
          }
        })
        if (error) {
          throw new Error({ message: error.String() })
        }
      }}
    >
      <Input
        label='gift'
        name='gift'
        append={<InputGroup.Text className='text-monospace'>sats</InputGroup.Text>}
        required
      />
      <Input
        label={<>invitee limit <small className='text-muted ml-2'>optional</small></>}
        name='limit'
      />

      <SubmitButton variant='secondary'>create</SubmitButton>
    </Form>
  )
}
Example #13
Source File: CommentForm.js    From serverless-media-portal with MIT License 5 votes vote down vote up
export default function CommentForm({ videoHash, onCommentAdded }) {
	const [commentText, setCommentText] = useState("");
	const [isCommentButtonEnabled, setIsCommentButtonEnabled] = useState(false);
	const { addToast } = useToasts();

	useEffect(() => {
		// This is a cheat but it's a quick fix for removing the red validation error 
		// showing on text field after submitting a comment
		if(!commentText) {
			document.getElementById("comment-form").reset();
			setIsCommentButtonEnabled(false);
		} else {
			setIsCommentButtonEnabled(true);
		}
	}, [commentText]);

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

		setIsCommentButtonEnabled(false);
		const res = await writeCommentToApi();

		if(res.success) {
			setCommentText("");
			onCommentAdded();
			addToast("Comment added", {
				appearance: "success",
				autoDismiss: true
			});
		} else {
			setIsCommentButtonEnabled(true);
			addToast(`Error adding comment: ${e.message}`, {
				appearance: "danger",
				autoDismiss: true
			});
		}
	};

	const writeCommentToApi = async () => {
		const res = await authPost("http://localhost:3001/dev/addCommentToVideo", {
			formData: {
				CommentText: commentText,
				VideoHash: videoHash
			}
		});

		return res;
	};

	return (
		<Form onSubmit={onSubmit} name="" method="get" action="/watch" className="mt-2" id="comment-form">
			<InputGroup>
				<Form.Control
					type="text"
					value={commentText}
					onChange={(e) => setCommentText(e.target.value)}
					required
				/>
				<Form.Control
					type="submit"
					value="COMMENT"
					className="btn btn-success"
					style={{ maxWidth: "110px" }}
					disabled={!isCommentButtonEnabled}
				/>
			</InputGroup>
		</Form>
	);
}
Example #14
Source File: searchbox.js    From RC4Community with Apache License 2.0 5 votes vote down vote up
export default function Searchbox() {
  return (
    <Form
      className={`d-flex flex-column flex-md-row gap-2 align-items-center ${styles.form}`}
    >
      <Dropdown>
        <Dropdown.Toggle className={styles.dropdown} id='searchbox-dropdown-toggle'>
          All Communities
        </Dropdown.Toggle>
        <Dropdown.Menu>
          <Dropdown.Item href='#/action-1'>Rooms</Dropdown.Item>
          <Dropdown.Item href='#/action-2'>Users</Dropdown.Item>
          <Dropdown.Item href='#/action-3'>Messages</Dropdown.Item>
        </Dropdown.Menu>
      </Dropdown>
      <Form.Group
        className=' py-1 align-self-center mx-2 w-100'
        controlId='formBasicEmail'
      >
        <InputGroup>
          <InputGroup.Text className='bg-white '>
            <svg
              width='16'
              height='16'
              viewBox='0 0 16 16'
              fill='none'
              xmlns='http://www.w3.org/2000/svg'
            >
              <g clipPath='url(#clip0_2_49)'>
                <path
                  d='M11.742 10.344C12.7103 9.02269 13.144 7.38449 12.9563 5.75715C12.7686 4.12981 11.9734 2.63334 10.7298 1.56713C9.48611 0.500922 7.88575 -0.0563951 6.24883 0.00667803C4.61192 0.0697512 3.05918 0.748563 1.90127 1.90731C0.743349 3.06605 0.0656481 4.61928 0.00374626 6.25624C-0.0581556 7.89319 0.500307 9.49316 1.56741 10.736C2.6345 11.9789 4.13154 12.7731 5.75902 12.9596C7.38649 13.1461 9.02438 12.7112 10.345 11.742H10.344C10.374 11.782 10.406 11.82 10.442 11.857L14.292 15.707C14.4795 15.8946 14.7339 16.0001 14.9991 16.0002C15.2644 16.0003 15.5189 15.895 15.7065 15.7075C15.8941 15.52 15.9996 15.2656 15.9997 15.0004C15.9998 14.7351 15.8945 14.4806 15.707 14.293L11.857 10.443C11.8212 10.4068 11.7828 10.3734 11.742 10.343V10.344ZM12 6.5C12 7.22227 11.8577 7.93747 11.5813 8.60476C11.3049 9.27205 10.8998 9.87837 10.3891 10.3891C9.87836 10.8998 9.27205 11.3049 8.60476 11.5813C7.93747 11.8577 7.22227 12 6.5 12C5.77773 12 5.06253 11.8577 4.39524 11.5813C3.72795 11.3049 3.12163 10.8998 2.61091 10.3891C2.10019 9.87837 1.69506 9.27205 1.41866 8.60476C1.14226 7.93747 0.999998 7.22227 0.999998 6.5C0.999998 5.04131 1.57946 3.64236 2.61091 2.61091C3.64236 1.57946 5.04131 1 6.5 1C7.95869 1 9.35763 1.57946 10.3891 2.61091C11.4205 3.64236 12 5.04131 12 6.5Z'
                  fill='#030C1A'
                />
              </g>
              <defs>
                <clipPath id='clip0_2_49'>
                  <rect width='16' height='16' fill='white' />
                </clipPath>
              </defs>
            </svg>
          </InputGroup.Text>
          <Form.Control
            type='text'
            placeholder='Search the community'
            className='border-start-0'
          />
        </InputGroup>
      </Form.Group>
    </Form>
  );
}
Example #15
Source File: Login.js    From create-sas-app with Apache License 2.0 5 votes vote down vote up
render() {
		return (
			<div className="login">
				<div className="flex justify-content-center align-items-center">
					<Card className={'w100 mb0'}>
						<Row className="loginForm">
							<Col md={12}>
								<Form noValidate validated={this.state.validated}>
									<h1>Login</h1>
									<p className="text-muted">Sign In to your account</p>
									<FormGroup>
										<InputGroup>
											<InputGroup.Prepend><i className={'fas fa-user'}/></InputGroup.Prepend>
											<Form.Control
												name={'username'}
												className={`textInput`}
												placeholder={'Username'}
												value={this.state.username}
												onChange={this.onInputChange}
												required
											/>
										</InputGroup>
									</FormGroup>
									<FormGroup>
										<InputGroup>
											<InputGroup.Prepend><i className={'fas fa-lock'}/></InputGroup.Prepend>
											<Form.Control
												name={'password'}
												placeholder={'Password'}
												type={'password'}
												value={this.state.password}
												onChange={this.onInputChange}
												required
											/>
										</InputGroup>
									</FormGroup>
									<Row>
										<Col md={12}>
											<Button
												onClick={this.login}
												bsstyle={'primary'}
												disabled={this.validateEmail() === 'error' || this.validatePassword() === 'error' || !this.state.username || !this.state.password}
												className={'pull-right'}
											>Login</Button>
											{this.state.error && <div className={'text-danger'}>{this.state.error}</div>}
										</Col>
									</Row>
								</Form>
							</Col>
						</Row>
					</Card>
				</div>
			</div>
		);
	}
Example #16
Source File: settings.js    From stacker.news with MIT License 4 votes vote down vote up
export default function Settings ({ data: { settings } }) {
  const [success, setSuccess] = useState()
  const [setSettings] = useMutation(
    gql`
      mutation setSettings($tipDefault: Int!, $noteItemSats: Boolean!, $noteEarning: Boolean!,
        $noteAllDescendants: Boolean!, $noteMentions: Boolean!, $noteDeposits: Boolean!,
        $noteInvites: Boolean!, $noteJobIndicator: Boolean!) {
        setSettings(tipDefault: $tipDefault, noteItemSats: $noteItemSats,
          noteEarning: $noteEarning, noteAllDescendants: $noteAllDescendants,
          noteMentions: $noteMentions, noteDeposits: $noteDeposits, noteInvites: $noteInvites,
          noteJobIndicator: $noteJobIndicator)
      }`
  )

  const { data } = useQuery(SETTINGS)
  if (data) {
    ({ settings } = data)
  }

  return (
    <LayoutCenter>
      <div className='py-3 w-100'>
        <h2 className='mb-2 text-left'>settings</h2>
        <Form
          initial={{
            tipDefault: settings?.tipDefault || 21,
            noteItemSats: settings?.noteItemSats,
            noteEarning: settings?.noteEarning,
            noteAllDescendants: settings?.noteAllDescendants,
            noteMentions: settings?.noteMentions,
            noteDeposits: settings?.noteDeposits,
            noteInvites: settings?.noteInvites,
            noteJobIndicator: settings?.noteJobIndicator
          }}
          schema={SettingsSchema}
          onSubmit={async ({ tipDefault, ...values }) => {
            await setSettings({ variables: { tipDefault: Number(tipDefault), ...values } })
            setSuccess('settings saved')
          }}
        >
          {success && <Alert variant='info' onClose={() => setSuccess(undefined)} dismissible>{success}</Alert>}
          <Input
            label='tip default'
            name='tipDefault'
            required
            autoFocus
            append={<InputGroup.Text className='text-monospace'>sats</InputGroup.Text>}
          />
          <div className='form-label'>notify me when ...</div>
          <Checkbox
            label='I stack sats from posts and comments'
            name='noteItemSats'
            groupClassName='mb-0'
          />
          <Checkbox
            label='I get a daily airdrop'
            name='noteEarning'
            groupClassName='mb-0'
          />
          <Checkbox
            label='someone replies to someone who replied to me'
            name='noteAllDescendants'
            groupClassName='mb-0'
          />
          <Checkbox
            label='my invite links are redeemed'
            name='noteInvites'
            groupClassName='mb-0'
          />
          <Checkbox
            label='sats are deposited in my account'
            name='noteDeposits'
            groupClassName='mb-0'
          />
          <Checkbox
            label='someone mentions me'
            name='noteMentions'
            groupClassName='mb-0'
          />
          <Checkbox
            label='there is a new job'
            name='noteJobIndicator'
          />
          <div className='d-flex'>
            <SubmitButton variant='info' className='ml-auto mt-1 px-4'>save</SubmitButton>
          </div>
        </Form>
        <div className='text-left w-100'>
          <div className='form-label'>saturday newsletter</div>
          <Button href='https://mail.stacker.news/subscription/form' target='_blank'>(re)subscribe</Button>
          {settings?.authMethods && <AuthMethods methods={settings.authMethods} />}
        </div>
      </div>
    </LayoutCenter>
  )
}
Example #17
Source File: user-header.js    From stacker.news with MIT License 4 votes vote down vote up
export default function UserHeader ({ user }) {
  const [editting, setEditting] = useState(false)
  const me = useMe()
  const router = useRouter()
  const client = useApolloClient()
  const [setName] = useMutation(NAME_MUTATION)

  const isMe = me?.name === user.name
  const Satistics = () => <div className={`mb-2 ml-0 ml-sm-1 ${styles.username} text-success`}>{isMe ? `${user.sats} sats \\ ` : ''}{user.stacked} stacked</div>

  const UserSchema = Yup.object({
    name: Yup.string()
      .required('required')
      .matches(/^[\w_]+$/, 'only letters, numbers, and _')
      .max(32, 'too long')
      .test({
        name: 'name',
        test: async name => {
          if (!name || !name.length) return false
          const { data } = await client.query({ query: NAME_QUERY, variables: { name }, fetchPolicy: 'network-only' })
          return data.nameAvailable
        },
        message: 'taken'
      })
  })

  const lnurlp = encodeLNUrl(new URL(`https://stacker.news/.well-known/lnurlp/${user.name}`))

  return (
    <>
      <div className='d-flex mt-2 flex-wrap flex-column flex-sm-row'>
        <div className='position-relative' style={{ width: 'fit-content' }}>
          <Image
            src={user.photoId ? `https://${process.env.NEXT_PUBLIC_AWS_UPLOAD_BUCKET}.s3.amazonaws.com/${user.photoId}` : '/dorian400.jpg'} width='135' height='135'
            className={styles.userimg}
          />
          {isMe && <PhotoEditor userId={me.id} />}
        </div>
        <div className='ml-0 ml-sm-1 mt-3 mt-sm-0 justify-content-center align-self-sm-center'>
          {editting
            ? (
              <Form
                schema={UserSchema}
                initial={{
                  name: user.name
                }}
                validateImmediately
                onSubmit={async ({ name }) => {
                  if (name === user.name) {
                    setEditting(false)
                    return
                  }
                  const { error } = await setName({ variables: { name } })
                  if (error) {
                    throw new Error({ message: error.toString() })
                  }
                  router.replace({
                    pathname: router.pathname,
                    query: { ...router.query, name }
                  })

                  client.writeFragment({
                    id: `User:${user.id}`,
                    fragment: gql`
                  fragment CurUser on User {
                    name
                  }
                `,
                    data: {
                      name
                    }
                  })

                  setEditting(false)
                }}
              >
                <div className='d-flex align-items-center mb-2'>
                  <Input
                    prepend=<InputGroup.Text>@</InputGroup.Text>
                    name='name'
                    autoFocus
                    groupClassName={styles.usernameForm}
                    showValid
                  />
                  <SubmitButton variant='link' onClick={() => setEditting(true)}>save</SubmitButton>
                </div>
              </Form>
              )
            : (
              <div className='d-flex align-items-center mb-2'>
                <div className={styles.username}>@{user.name}</div>
                {isMe &&
                  <Button className='py-0' style={{ lineHeight: '1.25' }} variant='link' onClick={() => setEditting(true)}>edit nym</Button>}
              </div>
              )}
          <Satistics user={user} />
          <ModalButton
            clicker={
              <Button className='font-weight-bold ml-0 ml-sm-2'>
                <LightningIcon
                  width={20}
                  height={20}
                  className='mr-1'
                />{user.name}@stacker.news
              </Button>
            }
          >
            <a className='d-flex m-auto p-3' style={{ background: 'white', width: 'fit-content' }} href={`lightning:${lnurlp}`}>
              <QRCode className='d-flex m-auto' value={lnurlp} renderAs='svg' size={300} />
            </a>
            <div className='text-center font-weight-bold text-muted mt-3'>click or scan</div>
          </ModalButton>
        </div>
      </div>
      <Nav
        className={styles.nav}
        activeKey={router.asPath.split('?')[0]}
      >
        <Nav.Item>
          <Link href={'/' + user.name} passHref>
            <Nav.Link>bio</Nav.Link>
          </Link>
        </Nav.Item>
        <Nav.Item>
          <Link href={'/' + user.name + '/posts'} passHref>
            <Nav.Link>{user.nitems} posts</Nav.Link>
          </Link>
        </Nav.Item>
        <Nav.Item>
          <Link href={'/' + user.name + '/comments'} passHref>
            <Nav.Link>{user.ncomments} comments</Nav.Link>
          </Link>
        </Nav.Item>
        {isMe &&
          <Nav.Item>
            <Link href='/satistics?inc=invoice,withdrawal' passHref>
              <Nav.Link eventKey='/satistics'>satistics</Nav.Link>
            </Link>
          </Nav.Item>}
      </Nav>
    </>
  )
}
Example #18
Source File: job-form.js    From stacker.news with MIT License 4 votes vote down vote up
// need to recent list items
export default function JobForm ({ item, sub }) {
  const storageKeyPrefix = item ? undefined : `${sub.name}-job`
  const router = useRouter()
  const [monthly, setMonthly] = useState(satsMin2Mo(item?.maxBid || sub.baseCost))
  const [getAuctionPosition, { data }] = useLazyQuery(gql`
    query AuctionPosition($id: ID, $bid: Int!) {
      auctionPosition(sub: "${sub.name}", id: $id, bid: $bid)
    }`,
  { fetchPolicy: 'network-only' })
  const [upsertJob] = useMutation(gql`
    mutation upsertJob($id: ID, $title: String!, $company: String!, $location: String,
      $remote: Boolean, $text: String!, $url: String!, $maxBid: Int!, $status: String) {
      upsertJob(sub: "${sub.name}", id: $id, title: $title, company: $company,
        location: $location, remote: $remote, text: $text,
        url: $url, maxBid: $maxBid, status: $status) {
        id
      }
    }`
  )

  const JobSchema = Yup.object({
    title: Yup.string().required('required').trim(),
    company: Yup.string().required('required').trim(),
    text: Yup.string().required('required').trim(),
    url: Yup.string()
      .or([Yup.string().email(), Yup.string().url()], 'invalid url or email')
      .required('Required'),
    maxBid: Yup.number('must be number')
      .integer('must be whole').min(sub.baseCost, `must be at least ${sub.baseCost}`)
      .required('required'),
    location: Yup.string().test(
      'no-remote',
      "don't write remote, just check the box",
      v => !v?.match(/\bremote\b/gi))
      .when('remote', {
        is: (value) => !value,
        then: Yup.string().required('required').trim()
      })
  })

  const position = data?.auctionPosition

  useEffect(() => {
    const initialMaxBid = Number(item?.maxBid || localStorage.getItem(storageKeyPrefix + '-maxBid')) || sub.baseCost
    getAuctionPosition({ variables: { id: item?.id, bid: initialMaxBid } })
    setMonthly(satsMin2Mo(initialMaxBid))
  }, [])

  return (
    <>
      <Form
        className='py-5'
        initial={{
          title: item?.title || '',
          company: item?.company || '',
          location: item?.location || '',
          remote: item?.remote || false,
          text: item?.text || '',
          url: item?.url || '',
          maxBid: item?.maxBid || sub.baseCost,
          stop: false,
          start: false
        }}
        schema={JobSchema}
        storageKeyPrefix={storageKeyPrefix}
        onSubmit={(async ({ maxBid, stop, start, ...values }) => {
          let status
          if (start) {
            status = 'ACTIVE'
          } else if (stop) {
            status = 'STOPPED'
          }

          const { error } = await upsertJob({
            variables: {
              id: item?.id,
              sub: sub.name,
              maxBid: Number(maxBid),
              status,
              ...values
            }
          })
          if (error) {
            throw new Error({ message: error.toString() })
          }

          if (item) {
            await router.push(`/items/${item.id}`)
          } else {
            await router.push(`/~${sub.name}/recent`)
          }
        })}
      >
        <Input
          label='job title'
          name='title'
          required
          autoFocus
        />
        <Input
          label='company'
          name='company'
          required
        />
        <BForm.Row className='mr-0'>
          <Col>
            <Input
              label='location'
              name='location'
            />
          </Col>
          <Checkbox
            label={<div className='font-weight-bold'>remote</div>} name='remote' hiddenLabel
            groupClassName={styles.inlineCheckGroup}
          />
        </BForm.Row>
        <MarkdownInput
          label='description'
          name='text'
          as={TextareaAutosize}
          minRows={6}
          required
        />
        <Input
          label={<>how to apply <small className='text-muted ml-2'>url or email address</small></>}
          name='url'
          required
        />
        <Input
          label={
            <div className='d-flex align-items-center'>bid
              <Info>
                <ol className='font-weight-bold'>
                  <li>The higher your bid the higher your job will rank</li>
                  <li>The minimum bid is {sub.baseCost} sats/min</li>
                  <li>You can increase or decrease your bid, and edit or stop your job at anytime</li>
                  <li>Your job will be hidden if your wallet runs out of sats and can be unhidden by filling your wallet again</li>
                </ol>
              </Info>
            </div>
          }
          name='maxBid'
          onChange={async (formik, e) => {
            if (e.target.value >= sub.baseCost && e.target.value <= 100000000) {
              setMonthly(satsMin2Mo(e.target.value))
              getAuctionPosition({ variables: { id: item?.id, bid: Number(e.target.value) } })
            } else {
              setMonthly(satsMin2Mo(sub.baseCost))
            }
          }}
          append={<InputGroup.Text className='text-monospace'>sats/min</InputGroup.Text>}
          hint={<PriceHint monthly={monthly} />}
        />
        <><div className='font-weight-bold text-muted'>This bid puts your job in position: {position}</div></>
        {item && <StatusControl item={item} />}
        <SubmitButton variant='secondary' className='mt-3'>{item ? 'save' : 'post'}</SubmitButton>
      </Form>
    </>
  )
}
Example #19
Source File: index.js    From wedding-planner with MIT License 4 votes vote down vote up
VenuesPageComponent = (props) => {
  const eventId = props.eventId;
  const getAccessToken = props.getAccessToken;
  const [venues, setVenues] = useState([]);
  const [loading, setLoading] = useState(false);
  const [search, setSearch] = useState('Convention');
  const [nextUrl, setNextUrl] = useState('');
  const [venueAdded, setVenueAdded] = useState(false);

  // When user hits enter while still in text input focus, trigger venue search
  const onKeyPress = (event) => {
    if (event.charCode === 13) {
      searchVenues();
    }
  };

  // When user clicks search button, trigger venue search
  const handleFormSubmit = (event) => {
    event.preventDefault();
    searchVenues();
  };

  // Method to call venue search API endpoint
  const searchVenues = async () => {
    // Do not allow the user to search for a venue if the search text input is empty.
    if (!search) {
      alert('Please enter a venue name to search.');
      return;
    }

    setLoading(true);

    const token = await getAccessToken();

    var config = {
      method: 'get',
      url: `/api/venue/search?name=${search}`,
      headers: { Authorization: `Bearer ${token}` },
    };

    await axios(config)
      .then(function (res) {
        setLoading(false);
        setVenues(res.data);
      })
      .catch(function (error) {
        setLoading(false);
        console.log(error);
      });
  };

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

  const saveVenue = async (name, address, url) => {
    // getting access token for the site
    const token = await getAccessToken();

    var data = qs.stringify({
      name: name,
      address: address,
      url: url,
      photo: 'test photo',
      eventId: eventId,
    });
    var config = {
      method: 'post',
      url: '/api/venue',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization: `Bearer ${token}`,
      },
      data: data,
    };

    axios(config)
      .then(function (response) {
        setNextUrl(`/events/`);
        setVenueAdded(true);
      })
      .catch(function (error) {
        console.log(error);
      });
  };

  return (
    // Components venue search functionality
    <Container className="pt-5 mb-5">
      {venueAdded && <Redirect to={nextUrl} />}
      <h3 className="title-style mb-5">Search for Venues</h3>
      <Row className="d-flex flex-column flex-md-row vertical-align">
        <Col className="col-sm-12 col-lg-6">
          <InputGroup className="p5 mb-3 vertical-align">
            <InputGroup.Prepend>
              <InputGroup.Text>Search by venue name</InputGroup.Text>
            </InputGroup.Prepend>
            <FormControl
              aria-label="Default"
              aria-describedby="inputGroup-sizing-default"
              onKeyPress={onKeyPress}
              value={search}
              onChange={(e) => setSearch(e.target.value)}
            />
          </InputGroup>
        </Col>
        <Col className="col-sm-12 col-lg-6 mb-3">
          <BtnComponent name="Search" onClick={handleFormSubmit} />
        </Col>
      </Row>
      <br></br>
      {/* Venue card components */}
      <div className="d-sm-block d-md-flex flex-md-wrap justify-content-start my-3">
        {loading ? (
          <Col className="col-6 mb-3">
            <h4 className="title-style">Loading...</h4>
          </Col>
        ) : (
          venues.map((venue, i) => (
            <Col
              className="col-md-6 col-sm-12 mb-3"
              key={`venue-${i}`}
              id={`venue-${i}`}
            >
              <VenueCard
                img={PlaceholderImage}
                // img={
                //   venue.photo === 'Sorry, no photo available'
                //     ? PlaceholderImage
                //     : venue.photo
                // }
                name={venue.name}
                address={venue.address}
                url={venue.url}
                username={'wedding team'}
                onClick={() => {
                  saveVenue(venue.name, venue.address, venue.url);
                }}
              />
            </Col>
          ))
        )}
      </div>
    </Container>
  );
}
Example #20
Source File: index.js    From wedding-planner with MIT License 4 votes vote down vote up
GuestsPage = (props) => {
  const [addShow, setAddShow] = useState(false);
  const [editShow, setEditShow] = useState(false);
  const [deleteShow, setDeleteShow] = useState(false);
  const [inviteShow, setInviteShow] = useState(false);
  const [guests, setGuests] = useState([]);
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [selectedRow, setSelectedRow] = useState({});
  const [showError, setShowError] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');

  const eventId = props.match.params.eventId;
  const { getAccessTokenSilently } = useAuth0();

  const displayError = (message) => {
    setShowError(true);
    setErrorMessage(message);
    setAddShow(true);
  };

  const loadGuestsFromAPI = async () => {
    const token = await getAccessTokenSilently();

    var config = {
      method: 'get',
      url: `/api/guests?eventid=${eventId}`,
      headers: { Authorization: `Bearer ${token}` },
    };

    axios(config)
      .then(function (response) {
        setGuests(response.data);
      })
      .catch(function (error) {
        console.log(error);
      });
  };

  const handleAddGuest = async (event) => {
    setAddShow(false);

    setShowError(false);

    if (!name) return displayError('Please enter a valid name');
    if (!email) return displayError('Please enter a valid email');
    if (!phone) return displayError('Please enter a valid phone');

    event.preventDefault();

    const token = await getAccessTokenSilently();

    var qs = require('qs');
    var data = qs.stringify({
      name: name,
      email: email,
      phone: phone,
      eventid: eventId,
    });
    var config = {
      method: 'post',
      url: '/api/guests',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization: `Bearer ${token}`,
      },
      data: data,
    };

    axios(config)
      .then(function (response) {
        setName('');
        setPhone('');
        setEmail('');
        loadGuestsFromAPI();
      })
      .catch(function (error) {});
  };

  const handleDeleteGuest = async () => {
    const token = await getAccessTokenSilently();

    setDeleteShow(false);

    let id = selectedRow.id;
    if (!id) return;

    var config = {
      method: 'delete',
      url: `/api/guests/${id}`,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization: `Bearer ${token}`,
      },
    };

    axios(config)
      .then(function (response) {
        setSelectedRow({});
        loadGuestsFromAPI();
      })
      .catch(function (error) {
        console.log(error);
      });
  };

  const handleInviteGuest = async (email) => {
    const token = await getAccessTokenSilently();

    setInviteShow(false);

    if (!email) return false;

    var config = {
      method: 'get',
      url: `/api/invitation/send/${email}`,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization: `Bearer ${token}`,
      },
    };

    axios(config)
      .then(function (response) {
        setSelectedRow({});
        loadGuestsFromAPI();
      })
      .catch(function (error) {
        console.log(error);
      });
  };

  const handleEditGuest = async () => {
    const token = await getAccessTokenSilently();

    setEditShow(false);

    let id = selectedRow.id;
    if (!id) return;

    var qs = require('qs');
    var data = qs.stringify(selectedRow);

    var config = {
      method: 'put',
      url: `/api/guests/${id}`,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization: `Bearer ${token}`,
      },
      data: data,
    };

    axios(config)
      .then(function (response) {
        setSelectedRow({ name: '', email: '', phone: '' });
        loadGuestsFromAPI();
      })
      .catch(function (error) {
        console.log(error);
      });
  };

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

  const selectRow = {
    mode: 'radio', // single row selection
    onSelect: (row, isSelect, rowIndex, e) => {
      setSelectedRow(row);
    },
  };

  const columns = [
    {
      dataField: 'id',
      text: 'Id',
      hidden: true, // set to false only for dev
    },
    {
      dataField: 'name',
      text: 'Name  ',
      filter: textFilter({
        placeholder: 'Search by name',
      }),
      sort: true,
    },
    {
      dataField: 'email',
      text: 'Email  ',
      filter: textFilter({
        placeholder: 'Search by email',
      }),
      sort: true,
    },
    {
      dataField: 'phone',
      text: 'Phone  ',
      sort: true,
    },
  ];

  return (
    <Container className="marginCustom mt-5">
      <Row className="shadow-lg mb-3 card-custom-style d-flex flex-wrap p-lg-5 p-sm-1">
        <Col>
          <h3 className="title-style mb-5">Manage Guests</h3>
        </Col>
        <Col>
          <div className="row m-auto">
            {/* Add Guest Button */}
            <Button
              variant="outline-primary"
              onClick={() => setAddShow(true)}
            >
              ADD
            </Button>{' '}
            {/* Modal alert to add */}
            <Modal show={addShow} onHide={() => setAddShow(false)}>
              <Modal.Header closeButton>
                <Modal.Title>Add New Guest</Modal.Title>
              </Modal.Header>
              <Modal.Body>
                <InputGroup>
                  <InputGroup.Prepend>
                    <InputGroup.Text>Name</InputGroup.Text>
                  </InputGroup.Prepend>
                  <FormControl
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                  />
                </InputGroup>
                <InputGroup>
                  <InputGroup.Prepend>
                    <InputGroup.Text>Email</InputGroup.Text>
                  </InputGroup.Prepend>
                  <FormControl
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                  />
                </InputGroup>
                <InputGroup>
                  <InputGroup.Prepend>
                    <InputGroup.Text>Phone Number</InputGroup.Text>
                  </InputGroup.Prepend>
                  <FormControl
                    value={phone}
                    onChange={(e) => setPhone(e.target.value)}
                  />
                </InputGroup>
              </Modal.Body>
              <Modal.Footer>
                {showError && (
                  <h6 className="text-danger mr-auto">
                    {errorMessage}
                  </h6>
                )}
                <Button
                  variant="secondary"
                  onClick={() => setAddShow(false)}
                >
                  Close
                </Button>
                <Button variant="primary" onClick={handleAddGuest}>
                  Add Guest
                </Button>
              </Modal.Footer>
            </Modal>
            {/* Edit Guest Info Button */}
            <Button
              variant="outline-secondary"
              onClick={() => setEditShow(true)}
            >
              EDIT
            </Button>{' '}
            {/* Modal alert to edit */}
            <Modal show={editShow} onHide={() => setEditShow(false)}>
              <Modal.Header closeButton>
                <Modal.Title>Edit Guest Information</Modal.Title>
              </Modal.Header>
              <Modal.Body>
                <InputGroup>
                  <InputGroup.Prepend>
                    <InputGroup.Text>Name</InputGroup.Text>
                  </InputGroup.Prepend>
                  <FormControl
                    value={selectedRow.name}
                    onChange={(e) =>
                      setSelectedRow({
                        ...selectedRow,
                        name: e.target.value,
                      })
                    }
                  />
                </InputGroup>
                <InputGroup>
                  <InputGroup.Prepend>
                    <InputGroup.Text>Email</InputGroup.Text>
                  </InputGroup.Prepend>
                  <FormControl
                    value={selectedRow.email}
                    onChange={(e) =>
                      setSelectedRow({
                        ...selectedRow,
                        email: e.target.value,
                      })
                    }
                  />
                </InputGroup>
                <InputGroup>
                  <InputGroup.Prepend>
                    <InputGroup.Text>Phone Number</InputGroup.Text>
                  </InputGroup.Prepend>
                  <FormControl
                    value={selectedRow.phone}
                    onChange={(e) =>
                      setSelectedRow({
                        ...selectedRow,
                        phone: e.target.value,
                      })
                    }
                  />
                </InputGroup>
                <h6
                  className="text-danger mt-3 text-center"
                  hidden={selectedRow.id}
                >
                  'Edit failed: Please select a guest (Try again)',
                </h6>
              </Modal.Body>
              <Modal.Footer>
                <Button
                  variant="secondary"
                  onClick={() => setEditShow(false)}
                >
                  Close
                </Button>
                <Button
                  variant="primary"
                  onClick={() => handleEditGuest()}
                >
                  Save Changes
                </Button>
              </Modal.Footer>
            </Modal>
            {/* Invite Guest Button */}
            <Button
              variant="outline-info"
              onClick={() => setInviteShow(true)}
            >
              INVITE
            </Button>{' '}
            {/* Modal alert to invite*/}
            <Modal
              show={inviteShow}
              onHide={() => setInviteShow(false)}
            >
              <Modal.Header closeButton>
                <Modal.Title>Invite Guest</Modal.Title>
              </Modal.Header>
              <Modal.Body>
                Are you sure you want to invite {selectedRow.name}?
              </Modal.Body>
              <Modal.Footer>
                <Button
                  variant="secondary"
                  onClick={() => setInviteShow(false)}
                >
                  Do Not Invite
                </Button>
                <Button
                  variant="primary"
                  onClick={async () => {
                    await handleInviteGuest(selectedRow.email);
                  }}
                >
                  Yes Invite Guest
                </Button>
              </Modal.Footer>
            </Modal>
            {/* Delete Guest Button */}
            <Button
              variant="outline-danger"
              onClick={() => setDeleteShow(true)}
            >
              REMOVE
            </Button>{' '}
            {/* Modal alert to delete*/}
            <Modal
              show={deleteShow}
              onHide={() => setDeleteShow(false)}
            >
              <Modal.Header closeButton>
                <Modal.Title>Delete Guest</Modal.Title>
              </Modal.Header>
              <Modal.Body>
                <h6
                  className="text-danger mt-3 text-center"
                  hidden={selectedRow.id}
                >
                  'Delete failed: Please select a guest to delete (Try
                  again)',
                </h6>
                <h6 hidden={!selectedRow.id}>
                  {' '}
                  Are you sure you want to delete this entry?{' '}
                </h6>
              </Modal.Body>
              <Modal.Footer>
                <Button
                  variant="secondary"
                  onClick={() => setDeleteShow(false)}
                >
                  Do Not Delete
                </Button>
                <Button
                  variant="primary"
                  onClick={() => handleDeleteGuest()}
                >
                  Yes Delete Entry
                </Button>
              </Modal.Footer>
            </Modal>
          </div>
        </Col>
        <Col className="col-sm-12">
          <div>
            <SearchTable
              data={guests}
              keyField="id"
              columns={columns}
              selectRow={selectRow}
            />
          </div>
        </Col>
      </Row>
    </Container>
  );
}
Example #21
Source File: Users.js    From ActiveLearningStudio-react-client with GNU Affero General Public License v3.0 4 votes vote down vote up
function Users() {
  const dispatch = useDispatch();
  // const [allUsersAdded, setAllUsersAdded] = useState([]);
  const allListState = useSelector((state) => state.organization);
  const [users, setUsers] = useState([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [searchAlertToggler, setSearchAlertToggler] = useState(1);
  const [activePage, setActivePage] = useState(1);
  const { activeOrganization, permission } = allListState;
  const searchUsers = async (query, page) => {
    const result = await dispatch(searchUserInOrganization(activeOrganization?.id, query, page));
    if (result.data.length > 0) {
      setUsers(result);
      setSearchAlertToggler(1);
    } else {
      setSearchAlertToggler(0);
    }
  };
  const onChangeHandler = async ({ target }) => {
    if (target.value) {
      setSearchQuery(target.value);
      searchUsers(target.value, activePage);
      setUsers([]);
    } else {
      setSearchQuery('');
      setUsers(allListState?.users);
    }
  };
  useEffect(() => {
    if (permission?.Organization?.includes('organization:view-user')) dispatch(getRoles());
  }, [dispatch]);
  useMemo(async () => {
    if (permission?.Organization?.includes('organization:view-user')) {
      const resultUsers = await dispatch(getOrgUsers(activeOrganization.id, activePage));
      setUsers(resultUsers);
      // resultUsers.data.forEach((data) => {
      //   const allUsers = [];
      //   data.data?.map((adm) => {
      //     if (adm.organization_role !== 'Administrator') {
      //       const result = {
      //         value: {
      //           userInfo: adm,
      //         },
      //         role: {
      //           name: adm.organization_role,
      //           id: adm.organization_role_id,
      //         },
      //       };
      //       allUsers.push(result);
      //     }
      //     return true;
      //   });
      //   setAllUsersAdded(allUsers);
      // });
    }
  }, [activeOrganization.id, dispatch, activePage]);
  return (
    <div>
      {permission?.Organization?.includes('organization:view-user') ? (
        <>
          <div className="create-user-row">
            <h5 className="users-heading">
              Users
            </h5>
            {permission?.Organization?.includes('organization:add-user') && (
              <Dropdown className="create-organizations">
                <Dropdown.Toggle id="dropdown-basic-org" className="newuser-button button-text">
                  New User
                </Dropdown.Toggle>
                <Dropdown.Menu>
                  <div className="data-input">
                    <div className="form-group-create">
                      <InviteUser />
                    </div>
                  </div>
                </Dropdown.Menu>
              </Dropdown>
            )}
          </div>
          <div className="user-top-row">
            <InputGroup className="find-user">
              <input placeholder="Find User" className="input-field" value={searchQuery} onChange={onChangeHandler} />
              <InputGroup.Append>
                <Button variant="outline" onClick={() => searchUsers(searchQuery, activePage)}>
                  <img src={SearchButton} alt="search_button" />
                </Button>
              </InputGroup.Append>
            </InputGroup>
            {/* <div className="filter-sub-organization"> Filter Users by Sub-Organization</div> */}
            {/* <div className="filter-by-role"> Filter Users by Role</div> */}
          </div>
          {/* <div className="flex">
            <h5 className="user-created-me">Users Created by Me</h5>
            <hr />
          </div> */}
          {users?.data?.length > 0 ? users.data.map((user) => (
            <UserRow user={user} />
          )) : searchAlertToggler === 0 ? <Alert variant="warning">No User Found</Alert> : <Alert variant="primary">Loading...</Alert>}
          {users?.data?.length > 0
            ? (
              <Pagination
                activePage={activePage}
                itemsCountPerPage={users?.meta?.per_page}
                totalItemsCount={users?.meta?.total}
                pageRangeDisplayed={5}
                onChange={(e) => {
                  setActivePage(e);
                }}
              />
            )
            : null}
        </>
      ) : <Alert variant="danger">You are not authorized to view all users.</Alert>}
    </div>
  );
}
Example #22
Source File: index.js    From wedding-planner with MIT License 4 votes vote down vote up
NewReservationPage = () => {
  const { getAccessTokenSilently } = useAuth0();

  //added useState hook
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [date, setDate] = useState('');
  const [time, setTime] = useState('');
  // used to send user to next page on create success
  const [eventCreated, setEventCreated] = useState(false);
  const [nextUrl, setNextUrl] = useState('');
  // used to handle errors on the page
  const [showError, setShowError] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');

  const displayError = (message) => {
    setShowError(true);
    setErrorMessage(message);
  };

  const saveNewReservation = async (event) => {
    event.preventDefault();

    const token = await getAccessTokenSilently();

    // set the error back to false when the component refresh
    setShowError(false);

    // validate title
    if (!title) return displayError('Please, enter a valid title');

    // validate description
    if (!description)
      return displayError('Please enter a valid description');

    // validate time
    if (!time) return displayError('Please enter a valid time');

    // validate date
    if (!date) return displayError('Please enter a valid date');

    var data = qs.stringify({
      title: title,
      description: description,
      date: date,
      time: time,
    });
    var config = {
      method: 'post',
      url: '/api/weddings',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization: `Bearer ${token}`,
      },
      data: data,
    };

    axios(config)
      .then(function (response) {
        setNextUrl(`/events/`);
        setEventCreated(true);
      })
      .catch(function (error) {
        setShowError(true);
        setErrorMessage(error);
        console.log(error);
      });
  };

  return (
    <Container className="pt-5 mb-5 fixed-margin">
      {eventCreated && <Redirect to={nextUrl} />}

      <Row className="d-flex flex-wrap flex-column mb-5 p-md-5 shadow-lg mb-3 card-custom-style">
        <h3 className="title-style text-center">
          Create Event Reservation
        </h3>
        <hr></hr>
        <Col className="col-sm-12">
          <InputGroup className="mb-3 vertical-align">
            <InputGroup.Append>
              <InputGroup.Text id="TitleOfWedding">
                Title
              </InputGroup.Text>
            </InputGroup.Append>
            <FormControl
              placeholder="Wedding Title"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
            />
          </InputGroup>
          <InputGroup className="mb-3 vertical-align">
            <InputGroup.Append>
              <InputGroup.Text id="StartTimeOfWedding">
                Start Time
              </InputGroup.Text>
            </InputGroup.Append>
            <FormControl
              placeholder="Wedding Start Time"
              value={time}
              onChange={(e) => setTime(e.target.value)}
            />
          </InputGroup>
          <InputGroup className="mb-3 vertical-align">
            <InputGroup.Append>
              <InputGroup.Text id="DescriptionTimeOfWedding">
                Description
              </InputGroup.Text>
            </InputGroup.Append>
            <FormControl
              placeholder="Wedding Description"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
            />
          </InputGroup>
          <h6 className="title-style text-center ont-weight-bold">
            Select Date for the Event
          </h6>
        </Col>
        <Col className="center col-sm-12">
          <Calendar
            className="calendar"
            onClickDay={(value, event) => setDate(value)}
          />
        </Col>
      </Row>
      <Row className="text-center">
        <Col className="col-sm-12">
          {showError && (
            <h5 className="text-danger">{errorMessage}</h5>
          )}{' '}
        </Col>
      </Row>
      <Row>
        <BtnComponent
          className="create-btn-style"
          name="Make Reservation"
          onClick={saveNewReservation}
        />
      </Row>
    </Container>
  );
}
Example #23
Source File: register.js    From easy-job-intern with MIT License 4 votes vote down vote up
StudentSignup = () => {
  const history = useHistory();
  //creating a dicitionary for every field of the form
  const initialState = {
    personName: {
      //value of the input field
      value: "",
      //rules to check while validating the input
      validation: {
        required: true,
        minLength: 5,
      },
      //error messages to show in case any validation rule is not followed
      errorMessage: "",
      // boolean value to check if the whole input field is valid or not
      valid: false,
      //boolean value to check if the input field is touched or not
      touched: false,
    },
    email: {
      value: "",
      validation: {
        required: true,
        isEmail: true,
      },
      errorMessage: "",
      valid: false,
      touched: false,
    },
    password: {
      value: "",
      validation: {
        required: true,
        minLength: 8,
      },
      errorMessage: "",
      valid: false,
      touched: false,
    },
    passwordConfirmation: {
      value: "",
      validation: {
        required: true,
        minLength: 8,
        checkPassword: true,
      },
      errorMessage: "",
      valid: false,
      touched: false,
    },
    showPassword: false,
    contact: {
      value: "",
      validation: {
        required: true,
        Length: 10,
      },
      errorMessage: "",
      valid: false,
      touched: false,
    },
    degree: {
      value: "",
      validation: {
        required: true,
      },
      errorMessage: "",
      valid: false,
      touched: false,
    },
    institutionName: {
      value: "",
      validation: {
        required: true,
      },
      errorMessage: "",
      valid: false,
      touched: false,
    },
    branch: {
      value: "",
      validation: {
        required: true,
      },
      errorMessage: "",
      valid: false,
      touched: false,
    },
    year: {
      value: "",
      validation: {
        required: true,
      },
      errorMessage: "",
      valid: false,
      touched: false,
    },
  };

  const [formValues, setFormValues] = useState(initialState);
  const [signupError, setSignupError] = useState(null);

  const [formIsValid ,setFormIsValid] = useState(false); //boolean to check that the whole form is valid or not

  const handleChange = (e) => {
    const updatedFormValues = { ...formValues };
    const updatedFormElement = { ...updatedFormValues[e.target.name] };
    updatedFormElement.value = e.target.value;
    let validOutput = checkValidity(
      updatedFormElement.value,
      updatedFormElement.validation,
      updatedFormValues.password.value
    );
    updatedFormElement.valid = validOutput[0];
    updatedFormElement.errorMessage = validOutput[1];
    updatedFormElement.touched = true;
    updatedFormValues[e.target.name] = updatedFormElement;

    let formValid = true;
    for (let inputIdentifiers in updatedFormValues) {
      formValid = updatedFormValues[inputIdentifiers].valid && formValid;
    }
    setFormValues(updatedFormValues);
    setFormIsValid(formValid);
  };

  const passwordIsValidChecker = () => {
    const { password, passwordConfirmation } = formValues;
    return password.value === passwordConfirmation.value;
  };

  const submitSignup = (e) => {
    const {
      personName,
      email,
      password,
      passwordConfirmation,
      contact,
      branch,
      year,
      degree,
      institutionName,
    } = formValues;

    e.preventDefault();
    if (!passwordIsValidChecker()) {
      setSignupError("Passwords do not match");
      return;
    } else {
      axios
        .post("http://localhost:5000/student/signup", {
          personName: personName.value,
          email: email.value,
          password: password.value,
          contact: contact.value,
          passwordConfirmation: passwordConfirmation.value,
          branch: branch.value,
          year: year.value,
          degree: degree.value,
          institutionName: institutionName.value,
        })
        .then((res) => {
          console.log(res.data.user);
          // alert(res.data.message);
          const notify = () => toast(res.data.message);
          notify();
          if(res.data.user){
            history.pushState("/student-login");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    }
    setFormValues(initialState);
  };
  const togglePasswordVisiblity = () => { // to handle visibility of passsword 
    
      setFormValues({...formValues, showPassword: !(formValues.showPassword)});
    
  };

  return (
    <>
      <div style={{ padding: "4vh 0" }}>
      <Toaster />
        <Card
          style={{
            width: "40vw",
            marginLeft: "auto",
            marginRight: "auto",
            marginTop: "4vh",
            marginBottom: "4vh",
            backgroundImage: "linear-gradient(to right, white , #6EE2CD)",
          }}
          className="register_card_custom"
        >
          <Card.Header
            style={{
              backgroundColor: "#6c6c6c",
              color: "#6EE2CD",
              fontFamily: '"Merriweather", serif',
              fontSize: "1.25rem",
            }}
            as="h5"
          >
            Student Signup
          </Card.Header>
          <Card.Body>
            <Form onSubmit={(e) => submitSignup(e)}>
              {/* Name of the student */}
              <Form.Group style={{ textAlign: "left" }}>
                <Form.Label style={{ fontWeight: "bold" }}>Name</Form.Label>
                <Form.Control
                  className={`${
                    !formValues.personName.touched
                      ? "input-error"
                      : ""
                  }`}
                  style={{ borderColor: "#6EE2CD", color: "#000000" }}
                  type="text"
                  placeholder="Enter your name"
                  name="personName"
                  value={formValues.personName.value}
                  onChange={handleChange}
                />
              </Form.Group>

              {/* Email address */}
              <Form.Group
                style={{ textAlign: "left" }}
                controlId="formBasicEmail"
              >
                <Form.Label style={{ fontWeight: "bold" }}>
                  Email address
                </Form.Label>
                <Form.Control
                  className={`${
                    !formValues.email.valid && formValues.email.touched
                      ? "input-error"
                      : ""
                  }`}
                  style={{ borderColor: "#6EE2CD", color: "#000000" }}
                  type="email"
                  placeholder="Enter email"
                  name="email"
                  value={formValues.email.value}
                  onChange={handleChange}
                />
                {formValues.email.errorMessage && (
                  <span className="error">{formValues.email.errorMessage}</span>
                )}
              </Form.Group>

              {/*  Password */}
              <Form.Group
                style={{ textAlign: "left" }}
                controlId="formBasicPassword"
              >
                <Form.Label style={{ fontWeight: "bold" }}>Password</Form.Label>
                <InputGroup>
                <Form.Control
                  className={`${
                    !formValues.password.valid && 
                    formValues.password.touched
                      ? "input-error"
                      : ""
                  }`}
                  style={{ borderColor: "#6EE2CD", color: "#000000" }}
                  type={formValues.showPassword?"text":"password"}
                  placeholder="Password"
                  name="password"
                  value={formValues.password.value}
                  onChange={handleChange}
                />
                {formValues.password.errorMessage && (
                  <span className="error">
                    {formValues.password.errorMessage}
                  </span>
                )}
                <InputGroup.Append>
                      <InputGroup.Text style={{borderColor: "#ffc107", color: "#000000", height: "37px", width: "28px", paddingLeft:"1px",paddingRight:"1px" }}>
                        <IconButton style={{width: "25px"}}
                          onClick={togglePasswordVisiblity}
                        >
                          {formValues.showPassword ? <Visibility /> : <VisibilityOff />}
                        </IconButton> 
                      </InputGroup.Text>
                    </InputGroup.Append>
                </InputGroup>
              </Form.Group>

              {/* Confirm Password */}
              <Form.Group
                style={{ textAlign: "left", marginBottom: "1.6vh" }}
                controlId="formBasicPassword"
              >
                <Form.Label style={{ fontWeight: "bold" }}>
                  Confirm Password
                </Form.Label>
                <InputGroup>
                  <Form.Control
                    className={`${
                      !formValues.passwordConfirmation.valid &&
                      formValues.passwordConfirmation.touched
                        ? "input-error"
                        : ""
                    }`}
                    style={{ borderColor: "#6EE2CD", color: "#000000" }}
                    type="password"
                    placeholder="Re-enter Password"
                    name="passwordConfirmation"
                    value={formValues.passwordConfirmation.value}
                    onChange={handleChange}
                  />
                  {formValues.passwordConfirmation.errorMessage && (
                    <span className="error">
                      {formValues.passwordConfirmation.errorMessage}
                    </span>
                  )}
                  <InputGroup.Append>
                    <InputGroup.Text style={{borderColor: "#ffc107", color: "#000000", height: "37px", width: "28px", paddingLeft:"1px",paddingRight:"1px" }}>
                      <IconButton style={{width: "25px"}}
                          onClick={togglePasswordVisiblity}
                      >
                        {formValues.showPassword ? <Visibility /> : <VisibilityOff />}
                      </IconButton> 
                    </InputGroup.Text>
                  </InputGroup.Append>
                </InputGroup>
              </Form.Group>

              {/* Contact Number */}
              <Form.Group style={{ textAlign: "left" }}>
                <Form.Label style={{ fontWeight: "bold" }}>Contact</Form.Label>
                <Form.Control
                  className={`${
                    !formValues.contact.valid && formValues.contact.touched
                      ? "input-error"
                      : ""
                  }`}
                  style={{ borderColor: "#6EE2CD", color: "#000000" }}
                  type="number"
                  placeholder="Enter your contact number"
                  name="contact"
                  value={formValues.contact.value}
                  onChange={handleChange}
                />
                {formValues.contact.errorMessage && (
                  <span className="error">
                    {formValues.contact.errorMessage}
                  </span>
                )}
              </Form.Group>

              {/* Degree */}
              <Form.Group style={{ textAlign: "left" }}>
                <Form.Label style={{ fontWeight: "bold" }}>
                  Which degree you are pursuing?
                </Form.Label>
                <Form.Control
                  className={`${
                    !formValues.degree.valid && formValues.degree.touched
                      ? "input-error"
                      : ""
                  }`}
                  style={{ borderColor: "#6EE2CD", color: "#000000" }}
                  type="text"
                  placeholder="Enter complete name of your degree"
                  name="degree"
                  value={formValues.degree.value}
                  onChange={handleChange}
                />
                {formValues.degree.errorMessage && (
                  <span className="error">
                    {formValues.degree.errorMessage}
                  </span>
                )}
              </Form.Group>

              {/* College Name */}
              <Form.Group
                style={{ textAlign: "left" }}
                controlId="formBasicName"
              >
                <Form.Label style={{ fontWeight: "bold" }}>
                  College Name
                </Form.Label>
                <Form.Control
                  className={`${
                    !formValues.institutionName.valid &&
                    formValues.institutionName.touched
                      ? "input-error"
                      : ""
                  }`}
                  style={{ borderColor: "#6EE2CD", color: "#000000" }}
                  type="text"
                  placeholder="Your college name"
                  name="institutionName"
                  value={formValues.institutionName.value}
                  onChange={handleChange}
                />
                {formValues.institutionName.errorMessage && (
                  <span className="error">
                    {formValues.institutionName.errorMessage}
                  </span>
                )}
              </Form.Group>

              {/* Branch of study */}
              <Form.Group style={{ textAlign: "left" }}>
                <Form.Label style={{ fontWeight: "bold" }}>
                  Field of study
                </Form.Label>
                <Form.Control
                  className={`${
                    !formValues.branch.valid && formValues.branch.touched
                      ? "input-error"
                      : ""
                  }`}
                  style={{ borderColor: "#6EE2CD", color: "#000000" }}
                  type="text"
                  placeholder="Enter your field of study"
                  name="branch"
                  value={formValues.branch.value}
                  onChange={handleChange}
                />
                {formValues.branch.errorMessage && (
                  <span className="error">
                    {formValues.branch.errorMessage}
                  </span>
                )}
              </Form.Group>

              {/* Year of study */}
              <Form.Group style={{ textAlign: "left" }}>
                <Form.Label style={{ fontWeight: "bold" }}>
                  Which year of college you are in?
                </Form.Label>
                <Form.Control
                  className={`${
                    !formValues.year.valid && formValues.year.touched
                      ? "input-error"
                      : ""
                  }`}
                  style={{ borderColor: "#6EE2CD", color: "#000000" }}
                  type="text"
                  placeholder="Enter your college year"
                  name="year"
                  value={formValues.year.value}
                  onChange={handleChange}
                />
                {formValues.year.errorMessage && (
                  <span className="error">{formValues.year.errorMessage}</span>
                )}
              </Form.Group>

              {/* Already a user? */}
              <Form.Group style={{ textAlign: "left", fontSize: "1.5vh" }}>
                <Link to="/student-login">
                  <a href="/#" style={{ fontWeight: "bold" }}>
                    Already have an account? Sign in
                  </a>
                </Link>
              </Form.Group>

              {signupError ? (
                <Form.Text
                  style={{ paddingBottom: "0.6vh", fontWeight: "bold" }}
                  className="text-danger"
                >
                  {signupError}
                </Form.Text>
              ) : null}
              <Button
                style={{ color: "#6EE2CD", fontWeight: "bold" }}
                variant="secondary"
                type="submit"
              >
                Register
              </Button>
            </Form>
          </Card.Body>
        </Card>
      </div>
    </>
  );
}
Example #24
Source File: login.js    From easy-job-intern with MIT License 4 votes vote down vote up
function LoginForm() {
  const { dispatch } = useContext(UserContext);
  const history = useHistory();

  //creating a dicitionary for every field of the form
  const initialState = {
    email: {
      //value of the input field
      value: "",
      //rules to check while validating the input
      validation: {
        required: true,
        isEmail: true,
      },
      //error messages to show in case any validation rule is not followed
      errorMessage: "",
      // boolean value to check if the whole input field is valid or not
      valid: false,
      //boolean value to check if the input field is touched or not
      touched: false,
    },

    password: {
      value: "",
      validation: {
        required: true,
        minLength: 8,
      },
      errorMessage: "",
      valid: false,
      touched: false,
    },
    showPassword: false,
  };
  const [formValues, setFormValues] = useState(initialState);

  const [formIsValid ,setFormIsValid] = useState(false);

  const handleChange = (e) => {
    const updatedFormValues = { ...formValues };
    const updatedFormElement = { ...updatedFormValues[e.target.name] };
    updatedFormElement.value = e.target.value;
    let validOutput = checkValidity(
      updatedFormElement.value,
      updatedFormElement.validation,
      updatedFormValues.password.value
    );
    updatedFormElement.valid = validOutput[0];
    updatedFormElement.errorMessage = validOutput[1];
    updatedFormElement.touched = true;
    updatedFormValues[e.target.name] = updatedFormElement;

    let formValid = true;
    for (let inputIdentifiers in updatedFormValues) {
      formValid = updatedFormValues[inputIdentifiers].valid && formValid;
    }
    setFormValues(updatedFormValues);
    setFormIsValid(formValid);
  };

  const submitSignin = (e) => {
    e.preventDefault();
    const { email, password } = formValues;
    axios
      .post("http://localhost:5000/student/signin", {
        email: email.value,
        password: password.value,
      })
      .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 {
          localStorage.setItem("jwt", res.data.token);
          localStorage.setItem("user", JSON.stringify(res.data.user));
          localStorage.setItem("type", JSON.stringify("student"));
          dispatch({ type: "USER", payload: { user: res.data.user , userType: "student"} });
          console.log(
            "Token: ",
            res.data.token,
            "User Details: ",
            res.data.user
          );
          // alert("Signin Successfull");
          const notify = () => toast("Signin Successfull");
          notify();
          history.push("/");
        }
      })
      .catch((err) => {
        console.log("Error: ", err);
      });
    setFormValues(initialState);
  };

  const togglePasswordVisiblity = () => {
    // to handle visibility of passsword

    setFormValues({ ...formValues, showPassword: !formValues.showPassword });
  };
  return (
    <>
      <div style={{ padding: "4vh 0" }}>
        <Toaster />
        <Card
          style={{
            width: "40vw",
            marginLeft: "auto",
            marginRight: "auto",
            marginTop: "4vh",
            marginBottom: "4vh",
            backgroundImage: "linear-gradient(to right, white , #ffc107)",
          }}
          className="register_card_custom"
        >
          <Card.Header
            style={{
              backgroundColor: "#6c6c6c",
              color: "#ffc107",
              fontFamily: '"Merriweather", serif',
              fontSize: "1.25rem",
            }}
            as="h5"
          >
            Student Signin
          </Card.Header>
          <Card.Body>
            <Form onSubmit={(e) => submitSignin(e)}>
              <Form.Group
                style={{ textAlign: "left" }}
                controlId="formBasicEmail"
              >
                <Form.Label style={{ fontWeight: "bold" }}>
                  Email address
                </Form.Label>
                <Form.Control
                  style={{ borderColor: "#ffc107", color: "#000000" }}
                  className={`${
                    !formValues.email.valid && formValues.email.touched
                      ? "input-error"
                      : ""
                  }`}

                  type="email"
                  placeholder="Enter email"
                  name="email"
                  value={formValues.email.value}
                  onChange={handleChange}
                />
                {formValues.email.errorMessage && (
                  <span className="error">{formValues.email.errorMessage}</span>
                )}
              </Form.Group>

              <Form.Group
                style={{ textAlign: "left" }}
                controlId="formBasicPassword"
              >
                <Form.Label style={{ fontWeight: "bold" }}>Password</Form.Label>
                <InputGroup>
                  <Form.Control
                    style={{ borderColor: "#ffc107", color: "#000000" }}
                    type={formValues.showPassword ? "text" : "password"}
                    className={`${
                      !formValues.password.valid && formValues.password.touched
                        ? "input-error"
                        : ""
                    }`}
                    placeholder="Password"
                    name="password"
                    value={formValues.password.value}
                    onChange={handleChange}
                  />
                  {formValues.password.errorMessage && (
                    <span className="error">
                      {formValues.password.errorMessage}
                    </span>
                  )}
                  <InputGroup.Append>
                    <InputGroup.Text
                      style={{
                        borderColor: "#ffc107",
                        color: "#000000",
                        height: "37px",
                        width: "28px",
                        paddingLeft: "1px",
                        paddingRight: "1px",
                      }}
                    >
                      <IconButton
                        style={{ width: "25px" }}
                        onClick={togglePasswordVisiblity}
                      >
                        {formValues.showPassword ? (
                          <Visibility />
                        ) : (
                          <VisibilityOff />
                        )}
                      </IconButton>
                    </InputGroup.Text>
                  </InputGroup.Append>
                </InputGroup>
              </Form.Group>
              <Form.Group
                style={{
                  textAlign: "left",
                  fontSize: "1.5vh",
                  marginTop: "10px",
                }}
              >
                <Link to="/student-signup">
                  <a href="/#" style={{ fontWeight: "bold" }}>
                    Don't have an account? Sign up
                  </a>
                </Link>
              </Form.Group>

              <Button
                style={{ color: "#ffc107", fontWeight: "bold" }}
                variant="secondary"
                type="submit"
              >
                Signin
              </Button>
            </Form>
          </Card.Body>
        </Card>
      </div>
    </>
  );
}
Example #25
Source File: employerSignup.js    From easy-job-intern with MIT License 4 votes vote down vote up
EmployerSignup = () => {
  const history = useHistory();
  //listing initial states of the fields present in the form
  const initialState = {
    companyName: {
      value: "",
      validation: {
        required: true,
      },
      errorMessage: "",
      valid: false,
      touched: false,
    },
    email: {
      value: "",
      validation: {
        required: true,
        isEmail: true,
      },
      errorMessage: "",
      valid: false,
      touched: false,
    },
    password: {
      value: "",
      validation: {
        required: true,
        minLength: 8,
      },
      errorMessage: "",
      valid: false,
      touched: false,
    },
    passwordConfirmation: {
      value: "",
      validation: {
        required: true,
        minLength: 8,
        checkPassword: true,
      },
      errorMessage: "",
      valid: false,
      touched: false,
    },
    showPassword: false,

    contact: {
      value: "",
      validation: {
        required: true,
        Length: 10,
      },
      errorMessage: "",
      valid: false,
      touched: false,
    },
    personName: {
      value: "",
      validation: {
        required: true,
        minLength: 5,
      },
      errorMessage: "",
      valid: false,
      touched: false,
    },
  };

  const [formValues, setFormValues] = useState(initialState);
  const [signupError, setSignupError] = useState(null);

  const [formIsValid ,setFormIsValid] = useState(false);

  const handleChange = (e) => {
    const updatedFormValues = { ...formValues };
    const updatedFormElement = { ...updatedFormValues[e.target.name] };
    updatedFormElement.value = e.target.value;
    let validOutput = checkValidity(
      updatedFormElement.value,
      updatedFormElement.validation,
      updatedFormValues.password.value
    );
    updatedFormElement.valid = validOutput[0];
    updatedFormElement.errorMessage = validOutput[1];
    updatedFormElement.touched = true;
    updatedFormValues[e.target.name] = updatedFormElement;

    let formValid = true;
    for (let inputIdentifiers in updatedFormValues) {
      formValid = updatedFormValues[inputIdentifiers].valid && formValid;
    }
    setFormValues(updatedFormValues);
    setFormIsValid(formValid);
  };

  const passwordIsValidChecker = () => {
    const { password, passwordConfirmation } = formValues;
    return password.value === passwordConfirmation.value;
  };

  const submitSignup = (e) => {
    const {
      companyName,
      email,
      password,
      passwordConfirmation,
      personName,
      contact,
    } = formValues;

    e.preventDefault();
    if (!passwordIsValidChecker()) {
      setSignupError("Passwords do not match");
      return;
    } else {
      axios
        .post("http://localhost:5000/employer/signup", {
          personName: personName.value,
          email: email.value,
          password: password.value,
          contact: contact.value,
          passwordConfirmation: passwordConfirmation.value,
          companyName: companyName.value,
        })
        .then((res) => {
          console.log(res.data.user);
          // alert(res.data.message);
          const notify = () => toast(res.data.message);
          notify();
          if(res.data.user){
            history.push("/employer-login");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    }
    setFormValues(initialState);
  };
  const togglePasswordVisiblity = () => {
    setFormValues({ ...formValues, showPassword: !formValues.showPassword });
  };

  return (
    <>
      <div style={{ padding: "4vh 0" }}>
        <Toaster />
        <Card
          style={{
            width: "40vw",
            marginLeft: "auto",
            marginRight: "auto",
            marginTop: "4vh",
            marginBottom: "4vh",
            backgroundImage: "linear-gradient(to right, white , #6EE2CD)",
          }}
          className="employer_form_card_custom"
        >
          <Card.Header
            style={{
              backgroundColor: "#6c6c6c",
              color: "#6EE2CD",
              fontFamily: '"Merriweather", serif',
              fontSize: "1.25rem",
            }}
            as="h5"
          >
            Employer Signup
          </Card.Header>
          <Card.Body>
            <Form onSubmit={(e) => submitSignup(e)}>
              {/* Name of the company */}
              <Form.Group style={{ textAlign: "left" }}>
                <Form.Label style={{ fontWeight: "bold" }}>
                  Company Name
                </Form.Label>
                <Form.Control
                  className={`${
                    !formValues.companyName.valid &&
                    formValues.companyName.touched
                      ? "input-error"
                      : ""
                  }`}
                  style={{ borderColor: "#6EE2CD", color: "#000000" }}
                  type="text"
                  placeholder="Enter the company name"
                  name="companyName"
                  value={formValues.companyName.value}
                  onChange={handleChange}
                />
                {formValues.companyName.errorMessage && (
                  <span className="error">
                    {formValues.companyName.errorMessage}
                  </span>
                )}
              </Form.Group>

              {/*Email  */}
              <Form.Group
                style={{ textAlign: "left" }}
                controlId="formBasicEmail"
              >
                <Form.Label style={{ fontWeight: "bold" }}>
                  Email address
                </Form.Label>
                <Form.Control
                  className={`${
                    !formValues.email.valid && formValues.email.touched
                      ? "input-error"
                      : ""
                  }`}
                  style={{ borderColor: "#6EE2CD", color: "#000000" }}
                  type="email"
                  placeholder="Enter email"
                  name="email"
                  value={formValues.email.value}
                  onChange={handleChange}
                />
                {formValues.email.errorMessage && (
                  <span className="error">{formValues.email.errorMessage}</span>
                )}
              </Form.Group>

              {/* Password */}
              <Form.Group
                style={{ textAlign: "left" }}
                controlId="formBasicPassword"
              >
                <Form.Label style={{ fontWeight: "bold" }}>Password</Form.Label>
                <InputGroup>
                  <Form.Control
                    className={`${
                      !formValues.password.valid && formValues.password.touched
                        ? "input-error"
                        : ""
                    }`}
                    style={{ borderColor: "#6EE2CD", color: "#000000" }}
                    type={formValues.showPassword ? "text" : "password"}
                    placeholder="Password"
                    name="password"
                    value={formValues.password.value}
                    onChange={handleChange}
                  />
                  {formValues.password.errorMessage && (
                    <span className="error">
                      {formValues.password.errorMessage}
                    </span>
                  )}
                  <InputGroup.Append>
                    <InputGroup.Text
                      style={{
                        borderColor: "#6EE2CD",
                        color: "#000000",
                        height: "37px",
                        width: "28px",
                        paddingLeft: "1px",
                        paddingRight: "1px",
                      }}
                    >
                      <IconButton
                        style={{ width: "25px" }}
                        onClick={togglePasswordVisiblity}
                      >
                        {formValues.showPassword ? (
                          <Visibility />
                        ) : (
                          <VisibilityOff />
                        )}
                      </IconButton>
                    </InputGroup.Text>
                  </InputGroup.Append>
                </InputGroup>
              </Form.Group>
              {/* Password Confirmation */}
              <Form.Group
                style={{ textAlign: "left", marginBottom: "1.6vh" }}
                controlId="formBasicPassword"
              >
                <Form.Label style={{ fontWeight: "bold" }}>
                  Confirm Password
                </Form.Label>
                <InputGroup>
                  <Form.Control
                    className={`${
                      !formValues.passwordConfirmation.valid &&
                      formValues.passwordConfirmation.touched
                        ? "input-error"
                        : ""
                    }`}
                    style={{ borderColor: "#6EE2CD", color: "#000000" }}
                    type="password"
                    placeholder="Re-enter Password"
                    name="passwordConfirmation"
                    value={formValues.passwordConfirmation.value}
                    onChange={handleChange}
                  />
                  {formValues.passwordConfirmation.errorMessage && (
                    <span className="error">
                      {formValues.passwordConfirmation.errorMessage}
                    </span>
                  )}
                  <InputGroup.Append>
                    <InputGroup.Text
                      style={{
                        borderColor: "#6EE2CD",
                        color: "#000000",
                        height: "37px",
                        width: "28px",
                        paddingLeft: "1px",
                        paddingRight: "1px",
                      }}
                    >
                      <IconButton
                        style={{ width: "25px" }}
                        onClick={togglePasswordVisiblity}
                      >
                        {formValues.showPassword ? (
                          <Visibility />
                        ) : (
                          <VisibilityOff />
                        )}
                      </IconButton>
                    </InputGroup.Text>
                  </InputGroup.Append>
                </InputGroup>
              </Form.Group>
              {/* Person Name */}
              <Form.Group style={{ textAlign: "left" }}>
                <Form.Label style={{ fontWeight: "bold" }}>Name</Form.Label>
                <Form.Control
                  className={`${
                    !formValues.personName.valid &&
                    formValues.personName.touched
                      ? "input-error"
                      : ""
                  }`}
                  style={{ borderColor: "#6EE2CD", color: "#000000" }}
                  type="text"
                  placeholder="Enter your name"
                  name="personName"
                  value={formValues.personName.value}
                  onChange={handleChange}
                />
                {formValues.personName.errorMessage && (
                  <span className="error">
                    {formValues.personName.errorMessage}
                  </span>
                )}
              </Form.Group>

              {/* contact */}
              <Form.Group style={{ textAlign: "left" }}>
                <Form.Label style={{ fontWeight: "bold" }}>Contact</Form.Label>
                <Form.Control
                  className={`${
                    !formValues.contact.valid && formValues.contact.touched
                      ? "input-error"
                      : ""
                  }`}
                  style={{ borderColor: "#6EE2CD", color: "#000000" }}
                  type="number"
                  placeholder="Enter your contact number"
                  name="contact"
                  value={formValues.contact.value}
                  onChange={handleChange}
                />
                {formValues.contact.errorMessage && (
                  <span className="error">
                    {formValues.contact.errorMessage}
                  </span>
                )}
              </Form.Group>
              {/* For Existing user */}
              <Form.Group style={{ textAlign: "left", fontSize: "1.5vh" }}>
                <Link to="/employer-login">
                  <a href="/#" style={{ fontWeight: "bold" }}>
                    Already have an account? Sign in
                  </a>
                </Link>
              </Form.Group>

              {signupError ? (
                <Form.Text
                  style={{ paddingBottom: "0.6vh", fontWeight: "bold" }}
                  className="text-danger"
                >
                  {signupError}
                </Form.Text>
              ) : null}
              <Button
                style={{ color: "#6EE2CD", fontWeight: "bold" }}
                variant="secondary"
                type="submit"
              >
                Register
              </Button>
            </Form>
          </Card.Body>
        </Card>
      </div>
    </>
  );
}
Example #26
Source File: employerSignin.js    From easy-job-intern with MIT License 4 votes vote down vote up
function EmployerSignin() {
  const { state, dispatch } = useContext(UserContext);
  const history = useHistory();

  const initialState = {
    email: {
      //value of the input field
      value: "",
      //rules to check while validating the input
      validation: {
        required: true,
        isEmail: true,
      },
      //error messages to show in case any validation rule is not followed
      errorMessage: "",
      // boolean value to check if the whole input field is valid or not
      valid: false,
      //boolean value to check if the input field is touched or not
      touched: false,
    },

    password: {
      value: "",
      validation: {
        required: true,
        minLength: 8,
      },
      errorMessage: "",
      valid: false,
      touched: false,
    },
    showPassword: false,
  };
  const [formValues, setFormValues] = useState(initialState);

  const [formIsValid, setFormIsValid] = useState(false);

  const handleChange = (e) => {
    const updatedFormValues = { ...formValues };
    const updatedFormElement = { ...updatedFormValues[e.target.name] };
    updatedFormElement.value = e.target.value;
    let validOutput = checkValidity(
      updatedFormElement.value,
      updatedFormElement.validation,
      updatedFormValues.password.value
    );
    updatedFormElement.valid = validOutput[0];
    updatedFormElement.errorMessage = validOutput[1];
    updatedFormElement.touched = true;
    updatedFormValues[e.target.name] = updatedFormElement;

    let formValid = true;
    for (let inputIdentifiers in updatedFormValues) {
      formValid = updatedFormValues[inputIdentifiers].valid && formValid;
    }
    setFormValues(updatedFormValues);
    setFormIsValid(formValid);
  };

  const submitSignin = (e) => {
    e.preventDefault();
    const { email, password } = formValues;
    axios
      .post("http://localhost:5000/employer/signin", {
        email: email.value,
        password: password.value,
      })
      .then((res) => {
        console.log(res);
        if (res.data.error) {
          console.log(res.data.error);
          // alert(res.data.error);
          // toast(res.data.error);
          console.log(res.data.error);
          const notify = () => toast(res.data.error);
          notify();
        } else {
          localStorage.setItem("jwt", res.data.token);
          localStorage.setItem("user", JSON.stringify(res.data.user));
          localStorage.setItem("type", JSON.stringify("employee"))
          dispatch({ type: "USER", payload: {user: res.data.user , userType: "employee"} });
          console.log(state);
          console.log(
            "Token: ",
            res.data.token,
            "User Details: ",
            res.data.user
          );
          // alert("Signin Successfull");
          // toast("Signin Successfull");
          const notify = () => toast('Signin Successfull');
          notify();
          history.push("/");
        }
      })
      .catch((err) => {
        console.log("Error: ", err);
      });
    setFormValues(initialState);
  };

  const togglePasswordVisiblity = () => {
    // to handle visibility of passsword

    setFormValues({ ...formValues, showPassword: !formValues.showPassword });
  };
  return (
    <>
      <div style={{ padding: "4vh 0" }}>
      <Toaster />
        <Card
          style={{
            width: "40vw",
            marginLeft: "auto",
            marginRight: "auto",
            marginTop: "4vh",
            marginBottom: "4vh",
            backgroundImage: "linear-gradient(to right, white , #ffc107)",
          }}
          className="employer_form_card_custom"
        >
          <Card.Header
            style={{
              backgroundColor: "#6c6c6c",
              color: "#ffc107",
              fontFamily: '"Merriweather", serif',
              fontSize: "1.25rem",
            }}
            as="h5"
          >
            Employer Signin
          </Card.Header>
          <Card.Body>
            <Form onSubmit={(e) => submitSignin(e)}>
              <Form.Group
                style={{ textAlign: "left" }}
                controlId="formBasicEmail"
              >
                <Form.Label style={{ fontWeight: "bold" }}>
                  Email address
                </Form.Label>
                <Form.Control
                  style={{ borderColor: "#ffc107", color: "#000000" }}
                  className={`${
                    !formValues.email.valid && 
                    formValues.email.touched
                      ? "input-error"
                      : ""
                  }`}
                  type="email"
                  placeholder="Enter email"
                  name="email"
                  value={formValues.email.value}
                  onChange={handleChange}
                />
                {formValues.email.errorMessage && (
                  <span className="error">{formValues.email.errorMessage}</span>
                )}
              </Form.Group>

              <Form.Group
                style={{ textAlign: "left" }}
                controlId="formBasicPassword"
              >
                <Form.Label style={{ fontWeight: "bold" }}>Password</Form.Label>

                <InputGroup>
                  <Form.Control
                    style={{ borderColor: "#ffc107", color: "#000000" }}
                    type={formValues.showPassword ? "text" : "password"}
                    className={`${
                      !formValues.password.valid && formValues.password.touched
                        ? "input-error"
                        : ""
                    }`}
                    placeholder="Password"
                    name="password"
                    value={formValues.password.value}
                    onChange={handleChange}
                  />
                  {formValues.password.errorMessage && (
                    <span className="error">
                      {formValues.password.errorMessage}
                    </span>
                  )}
                  <InputGroup.Append>
                    <InputGroup.Text
                      style={{
                        borderColor: "#ffc107",
                        color: "#000000",
                        height: "37px",
                        width: "28px",
                        paddingLeft: "1px",
                        paddingRight: "1px",
                      }}
                    >
                      <IconButton
                        style={{ width: "25px" }}
                        onClick={togglePasswordVisiblity}
                      >
                        {formValues.showPassword ? (
                          <Visibility />
                        ) : (
                          <VisibilityOff />
                        )}
                      </IconButton>
                    </InputGroup.Text>
                  </InputGroup.Append>
                </InputGroup>

                <Form.Group
                  style={{
                    textAlign: "left",
                    fontSize: "1.5vh",
                    marginTop: "10px",
                  }}
                >
                  <Link to="/employer-signup">
                    <a href="/#" style={{ fontWeight: "bold" }}>
                      Don't have an account? Sign up
                    </a>
                  </Link>
                </Form.Group>
              </Form.Group>
              <Button
                style={{ color: "#ffc107", fontWeight: "bold" }}
                variant="secondary"
                type="submit"
              >
                Signin
              </Button>
            </Form>
          </Card.Body>
        </Card>
      </div>
    </>
  );
}
Example #27
Source File: ViewPaths.js    From katanapools with GNU General Public License v2.0 4 votes vote down vote up
render() {
        let {fromToken, toToken, pathList} = this.props;
        const {showMain, transferAmount} = this.state;
        const self = this;

        if (pathList.length === 0) {
            return <span/>;
        }

        if (showMain) {
         let viewAllPaths = <span/>;
         
         if (pathList.length > 2) {
             viewAllPaths = <div className="view-toggle-container" onClick={this.toggleHidePath}>{pathList.length - 2} more paths. View All <FontAwesomeIcon icon={faChevronDown}/></div>;
         }

         return  (<div>
            <div className="h6 conversion-path-header">
            <Row>
            <Col lg={8} xs={6}>
            Conversion paths  from {fromToken.symbol} to {toToken.symbol}
            </Col>
            <Col lg={4} xs={6} className="path-label-container">
               <InputGroup className="mb-3">
                <Form.Control type="text" placeholder="Amount" className="swap-amount-input"
                value={transferAmount} onChange={this.tranferAmountChanged}/>
                <InputGroup.Append>
                  <InputGroup.Text id="basic-addon2">{fromToken.symbol}</InputGroup.Text>
                </InputGroup.Append>
              </InputGroup>
            </Col>
            </Row>
            </div>
            {
          
            
            pathList.slice(0, 2).map(function(item, idx){
                let isBestPath = "";
                if (idx === 0) {
                    isBestPath = "best-path";
                }

                return (<ListGroupItem key={`frompath-${idx}`} className={`path-row ${isBestPath}`}>
                <Row>
                <Col lg={10} className="token-path-display">
                {item.path.map(function(cell, idx){

                
                let pointerArrow = <span/>;
                if (idx < item.path.length - 1) {
                      pointerArrow =
                      <div className="arrow-right-container">
                        <FontAwesomeIcon icon={faArrowRight} />
                      </div>
                }
                return <div className="meta-item-cell-container" key={cell.meta.symbol + "idx"}>
                      <div className="meta-item-cell">
                        <div className="token-label-cell">{cell.meta.symbol}</div>
                        <div className="token-name-cell">{cell.meta.name}</div>
                      </div>
                      {pointerArrow}
                    </div>
                })}
                <div className="path-conversion-price">{transferAmount} {item.path[0].meta.symbol} = {item.price} {item.path[item.path.length - 1].meta.symbol}</div>
                </Col>
                <Col lg={2}>

                <Button className="path-swap-btn" onClick={self.submitSwap.bind(self, idx)}>Swap</Button>
                </Col>
                </Row>
                </ListGroupItem>)
            })}
            {viewAllPaths}
            </div>)
        }
        return (
            <div>
            <div className="h6 conversion-path-header">
            <Row>
            <Col lg={8} xs={6}>
            Conversion paths  from {fromToken.symbol} to {toToken.symbol}
            </Col>
            <Col lg={4} xs={6} className="path-label-container">
               <InputGroup className="mb-3">
                <Form.Control type="text" placeholder="Amount" className="swap-amount-input"
                value={transferAmount} onChange={this.tranferAmountChanged}/>
                <InputGroup.Append>
                  <InputGroup.Text id="basic-addon2">{fromToken.symbol}</InputGroup.Text>
                </InputGroup.Append>
              </InputGroup>
            </Col>
            </Row>
            </div>
            {
            pathList.map(function(item, idx){
                let isBestPath = "";
                if (idx === 0) {
                    isBestPath = "best-path";
                }
                return (<ListGroupItem key={`frompath-${idx}`} className={`path-row ${isBestPath}`}>
                <Row>
                <Col lg={10} className="token-path-display">
                {item.path.map(function(cell, idx){
                let pointerArrow = <span/>;
                if (idx < item.path.length - 1) {
                      pointerArrow =
                      <div className="arrow-right-container">
                        <FontAwesomeIcon icon={faArrowRight} />
                      </div>
                }
                return <div className="meta-item-cell-container" key={cell.meta.symbol + {idx}+"idx"}>
                      <div className="meta-item-cell">
                        <div className="token-label-cell">{cell.meta.symbol}</div>
                        <div className="token-name-cell">{cell.meta.name}</div>
                      </div>
                      {pointerArrow}
                    </div>
                })}
                <div className="path-conversion-price">{transferAmount} {item.path[0].meta.symbol} = {item.price} {item.path[item.path.length - 1].meta.symbol}</div>
                </Col>
                <Col lg={2}>
                <Button className="path-swap-btn" onClick={self.submitSwap.bind(self, idx)}>Swap</Button>
                </Col>
                </Row>
                </ListGroupItem>)
            })}
            <div className="view-toggle-container" onClick={this.toggleShowPath}>View less. <FontAwesomeIcon icon={faChevronUp}/>.</div>
            </div>

            )
    }
Example #28
Source File: tasks.js    From community-forum-frontend with GNU General Public License v3.0 4 votes vote down vote up
render() {
    return (
      <div>
        <Modal show={this.state.showModal} onHide={this.handleClose} centered>
          <div className="modalbody">
            <Modal.Body>
              <Form>
                <div className="formdetails">
                  <div className="forminsides">
                    <Form.Group controlId="Description">
                      <Form.Label>Description</Form.Label>
                      <Form.Control
                        as="textarea"
                        rows="3"
                        placeholder="Description"
                        onChange={(e) => {
                          this.handleChange("description", e);
                        }}
                      />
                    </Form.Group>
                    <Form.Group controlId="TopicList">
                      <Form.Label>Topic</Form.Label>
                      <InputGroup>
                        <FormControl
                          placeholder={this.state.topicName}
                          aria-describedby="basic-addon2"
                          disabled="true"
                        />

                        <DropdownButton
                          as={InputGroup.Append}
                          variant="outline-secondary"
                          title=""
                          id="input-group-dropdown-2"
                        >
                          {this.state.Topics.map((topic) => {
                            return (
                              <Dropdown.Item
                                eventKey={topic.topicName}
                                onSelect={() =>
                                  this.handleSelect(
                                    topic.topicName,
                                    {
                                      topic: topic.topicName,
                                      id: topic._id,
                                    },
                                    "topics"
                                  )
                                }
                              >
                                {topic.topicName}
                              </Dropdown.Item>
                            );
                          })}
                        </DropdownButton>
                      </InputGroup>
                    </Form.Group>
                    <Form.Group controlId="assigned">
                      <Form.Label>Assign To:</Form.Label>
                      <InputGroup>
                        <FormControl
                          placeholder={this.state.username}
                          aria-describedby="basic-addon2"
                          disabled="true"
                        />
                        <DropdownButton
                          as={InputGroup.Append}
                          variant="outline-secondary"
                          title=""
                          id="input-group-dropdown-2"
                        >
                          {this.state.users.map((user) => {
                            return (
                              <Dropdown.Item
                                eventKey={user.username}
                                onSelect={() =>
                                  this.handleSelect(
                                    user.username,
                                    {
                                      username: user.username,
                                      email: user.email,
                                      id: user._id,
                                    },
                                    "users"
                                  )
                                }
                              >
                                {user.username}
                              </Dropdown.Item>
                            );
                          })}
                        </DropdownButton>
                      </InputGroup>
                    </Form.Group>
                    <Form.Group controlId="setDate">
                      <Form.Label>Complete By: </Form.Label>
                      <Form.Control
                        type="date"
                        placeholder="Enter email"
                        onChange={(e) => this.handleChange("date", e)}
                      />
                    </Form.Group>
                  </div>
                </div>
                <div className="cta-register">
                  <Button
                    variant="primary"
                    type="submit"
                    onClick={(e) => this.handleAddTask(e)}
                  >
                    Add Task
                  </Button>
                </div>
              </Form>
            </Modal.Body>
          </div>
        </Modal>
        <div className="ToDosHeading">
          To-Do Tasks
          <Button className="addbutton" onClick={this.handleTasksAdd}>
            Add
          </Button>
        </div>
        <div className="navTabs">
          <Tabs defaultActiveKey="ongoing" id="uncontrolled-tab-example">
            <Tab eventKey="ongoing" title="OnGoing" className="ongoingTab">
              <Form>
                {this.state.tasks.map((task) => {
                  return task.completed ? (
                    ""
                  ) : (
                    <div>
                      <Form.Group
                        controlId="formBasicCheckbox"
                        className="formCheckbox"
                        onChange={(e) =>
                          this.handleChangeTask("completed", e, task._id)
                        }
                        id={task.description}
                      >
                        <Form.Check type="checkbox" />
                        <div className="textTasks">
                          <div className="labelParra">{task.description}</div>
                          <div className="subparra">
                            {task.assignedBy.username}, {task.dueDate}.
                          </div>
                        </div>
                        <div className="icons">
                          <FiMoreVertical
                            size={20}
                            className="FiMoreVertical"
                          />
                          <MdInfoOutline size={20} className="FiMoreVertical" />
                        </div>
                      </Form.Group>
                    </div>
                  );
                })}
              </Form>
            </Tab>

            <Tab
              eventKey="completed"
              title="Completed"
              className="completedTab"
            >
              {this.state.tasks.map((task) => {
                return task.completed ? (
                  <Form.Group
                    controlId="formBasicCheckbox"
                    className="formCheckbox"
                    onChange={(e) =>
                      this.handleChangeTask("notCompleted", e, task._id)
                    }
                  >
                    <Form.Check
                      defaultChecked="true"
                      type="checkbox"
                      label={
                        <div className="textTasks">
                          <div className="labelParra">
                            <s>{task.description}</s>
                          </div>
                          <div className="subparra">
                            {task.assignedBy.username}, {task.dueDate}.
                          </div>
                        </div>
                      }
                    />
                    <div className="icons">
                      <FiMoreVertical size={20} className="FiMoreVertical" />
                      <MdInfoOutline size={20} className="FiMoreVertical" />
                    </div>
                  </Form.Group>
                ) : (
                  ""
                );
              })}
            </Tab>
          </Tabs>
        </div>
      </div>
    );
  }
Example #29
Source File: Toolbar.js    From anutimetable with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
export default function Toolbar({ API, timetableState: {
  timeZone, year, session, sessions, timetableData, modules, selectedModules, darkMode,
  setTimeZone, setYear, setSession, setSessions, setTimetableData, setModules, setSelectedModules,
} }) {
  const theme = theme => ({
    ...theme,
    colors: {
      ...theme.colors,
      neutral0: darkMode ? '#101214' : '#fff',
      neutral10: darkMode ? theme.colors.neutral80 : theme.colors.neutral10,
      neutral80: darkMode ? '#fff' : '#000',
      primary25: darkMode ? '#343A40' : '#deebff',
      primary: '#42A5FF',
      primary50: darkMode ? '#343A40' : '#deebff',
    }
  })

  const MultiValueLabel = props => <components.MultiValueLabel {...props}>
    <a variant="link" size="sm" target="_blank" rel="noreferrer"
      href={`http://programsandcourses.anu.edu.au/${year}/course/${props.data.value}`}
      onMouseDown={e => e.stopPropagation()} // prevent dropdown from opening on href
    >{props.data.value}</a> {/* use value (eg COMP1130) instead of label to save space */}
  </components.MultiValueLabel>

  const options = useMemo(() => {
    return Object.entries(modules).map(([id, { title }]) => ({ label: title, value: id }))
  }, [modules])
  const showExport = selectedModules.length !== 0

  const styles = {
    control: provided => ({
      ...provided,
      margin: '-1px',
      ...(showExport && {
        borderTopRightRadius: 0,
        borderBottomRightRadius: 0
      }),
    }),

    container: provided => ({
      ...provided,
      flexGrow: 10,
    }),

    multiValue: (provided, { data }) => ({
      ...provided,
      backgroundColor: stringToColor(data.value),
    }),

    multiValueLabel: provided => ({
      ...provided,
      a: {
        color: 'white'
      }
    }),

    multiValueRemove: provided => ({
      ...provided,
      color: 'white',
    }),

    option: provided => ({
      ...provided,
      ':hover': {
        transitionDelay: '30ms',
        background: provided[':active'].backgroundColor
      },
    }),
  }

  return <InputGroup /* style={{ maxWidth: 'none !important', /*flexBasis: 'fit-content' }} */>
    <BigSelect
      className="border"
      styles={styles}
      isMulti
      isSearchable

      autoFocus
      // controlShouldRenderValue broken?
      blurInputOnSelect={false}
      closeMenuOnSelect
      // openMenuOnClick={false}
      // captureMenuScroll overriden by BigSelect
      // closeMenuOnScroll broken?
      backspaceRemovesValue
      escapeClearsValue
      tabSelectsValue

      isLoading={Object.keys(modules).length === 0}
      loadingMessage={() => 'Loading courses...'}
      noOptionsMessage={() => 'No matching courses found'}

      theme={theme}
      // formatOptionLabel={({ label, value }, { context }) => context === "value" ? value : label}
      components={{ MultiValueLabel }}

      value={selectedModules.map(({ title, id }) => ({ label: title, value: id }))}
      onChange={n => setSelectedModules(n.map(option => ({ ...option, id: option.value })))}
      options={options}
    />
    {/* somehow there's no NPM module for this. maybe I should write one? */}
    {showExport && <Export API={API} year={year} session={session} />}
  </InputGroup>
}