reactstrap#Container TypeScript Examples

The following examples show how to use reactstrap#Container. 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: index.tsx    From resume-nextjs with MIT License 6 votes vote down vote up
function Yosume() {
  return (
    <>
      <NextSeo {...Payload._global.seo} />
      <Head>
        <title>{Payload._global.headTitle}</title>
        <link rel="shortcut icon" href={Payload._global.favicon} />
      </Head>
      <Container style={Style.global}>
        <Profile.Component payload={Payload.profile} />
        <Introduce.Component payload={Payload.introduce} />
        <Skill.Component payload={Payload.skill} />
        <Experience.Component payload={Payload.experience} />
        <Project.Component payload={Payload.project} />
        <OpenSource.Component payload={Payload.openSource} />
        <Presentation.Component payload={Payload.presentation} />
        <Article.Component payload={Payload.article} />
        <Education.Component payload={Payload.education} />
        <Etc.Component payload={Payload.etc} />
        <Footer.Component payload={Payload.footer} />
      </Container>
    </>
  );
}
Example #2
Source File: index.tsx    From atorch-console with MIT License 6 votes vote down vote up
AtorchConsole: React.FC = () => {
  const dispatch = useDispatch();
  const connected = useSelector((state) => state.report.connected);
  const latest = useSelector((state) => state.report.latest);
  const onConnect = () => dispatch(connect());
  return (
    <Container className={locals.container}>
      <Row className='ml-2 justify-content-center'>
        <Button outline onClick={onConnect}>
          {connected ? 'Disconnect' : 'Connect'}
        </Button>
      </Row>
      <PrintReport packet={latest} />
    </Container>
  );
}
Example #3
Source File: app.tsx    From website with Apache License 2.0 5 votes vote down vote up
function App(): JSX.Element {
  const { x, y, place, isLoading } = useContext(Context);
  const showChart = shouldShowChart(x.value, y.value, place.value);
  const showChooseStatVarMessage = shouldShowChooseStatVarMessage(
    x.value,
    y.value,
    place.value
  );
  const showInfo = !showChart && !showChooseStatVarMessage;
  const [isSvModalOpen, updateSvModalOpen] = useState(false);
  const toggleSvModalCallback = () => updateSvModalOpen(!isSvModalOpen);
  return (
    <>
      <StatVarChooser
        openSvHierarchyModal={isSvModalOpen}
        openSvHierarchyModalCallback={toggleSvModalCallback}
      />
      <div id="plot-container">
        <Container fluid={true}>
          {!showChart && (
            <Row>
              <h1 className="mb-4">Scatter Plot Explorer</h1>
            </Row>
          )}
          <Row>
            <PlaceOptions toggleSvHierarchyModal={toggleSvModalCallback} />
          </Row>
          {showChooseStatVarMessage && (
            <Row className="info-message">
              Choose 2 statistical variables from the left pane.
            </Row>
          )}
          {showInfo && (
            <Row>
              <Info />
            </Row>
          )}
          {showChart && (
            <Row id="chart-row">
              <ChartLoader />
            </Row>
          )}
        </Container>
      </div>
      <Spinner isOpen={shouldDisplaySpinner(isLoading)} />
    </>
  );
}
Example #4
Source File: MainInputFormRunStep.tsx    From nextclade with MIT License 5 votes vote down vote up
MainInputFormContainer = styled(Container)`
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
`
Example #5
Source File: DatasetSelector.tsx    From nextclade with MIT License 5 votes vote down vote up
DatasetSelectorContainer = styled(Container)`
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  padding: 0;
`
Example #6
Source File: WhatsNewButton.tsx    From nextclade with MIT License 5 votes vote down vote up
export function WhatsNewButton() {
  const { t } = useTranslation()

  const [showChangelog, setShowChangelog] = useRecoilState(changelogIsShownAtom)
  const [showChangelogOnUpdate, setShowChangelogOnUpdate] = useRecoilState(changelogShouldShowOnUpdatesAtom)

  const toggleOpen = useCallback(() => {
    setShowChangelog((showChangelog) => !showChangelog)
  }, [setShowChangelog])

  const open = useCallback(() => {
    setShowChangelog(true)
  }, [setShowChangelog])

  const close = useCallback(() => {
    setShowChangelog(false)
  }, [setShowChangelog])

  const text = t("What's new")
  const closeText = t('Close this window')

  return (
    <>
      <ButtonWhatsNewBase type="button" onClick={open} title={text}>
        <FaListUl className="mr-xl-2" />
        <span className="d-none d-xl-inline">{text}</span>
      </ButtonWhatsNewBase>

      <Modal centered isOpen={showChangelog} toggle={toggleOpen} fade={false} size="lg">
        <ModalHeader toggle={close} tag="div">
          <H1 className="text-center">{text}</H1>
        </ModalHeader>

        <ModalBody>
          <MDXProvider components={components}>
            <Changelog />
          </MDXProvider>
        </ModalBody>

        <ModalFooter>
          <Container fluid>
            <Row noGutters className="my-2">
              <Col className="d-flex w-100">
                <div className="ml-auto">
                  <Toggle
                    className="m-0"
                    identifier={'show-whatsnew-again-toggle'}
                    checked={showChangelogOnUpdate}
                    onCheckedChanged={setShowChangelogOnUpdate}
                  >
                    {t('Show when a new version is available')}
                  </Toggle>
                </div>
              </Col>
            </Row>

            <Row noGutters className="my-2">
              <Col className="d-flex w-100">
                <ButtonOk className="ml-auto" type="button" color="success" onClick={close} title={closeText}>
                  {t('OK')}
                </ButtonOk>
              </Col>
            </Row>
          </Container>
        </ModalFooter>
      </Modal>
    </>
  )
}
Example #7
Source File: Footer.tsx    From nextclade with MIT License 5 votes vote down vote up
FooterContainer = styled(Container)`
  background-color: #2a2a2a;
  color: #c4cdd5;
  padding: 6px 10px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
`
Example #8
Source File: CitationButton.tsx    From nextclade with MIT License 5 votes vote down vote up
export function CitationButton() {
  const { t } = useTranslation()
  const [showCitation, setShowCitation] = useState(false)
  const toggleOpen = useCallback(() => setShowCitation((showCitation) => !showCitation), [])
  const open = useCallback(() => setShowCitation(true), [])
  const close = useCallback(() => setShowCitation(false), [])
  const text = t('Citation')
  const closeText = t('Close this window')

  return (
    <>
      <ButtonCitationBase type="button" onClick={open} title={text}>
        <HiOutlineAcademicCap className="mr-xl-2" />
        <span className="d-none d-xl-inline">{text}</span>
      </ButtonCitationBase>

      <Modal centered isOpen={showCitation} toggle={toggleOpen} fade={false} size="lg">
        <ModalHeader toggle={close} tag="div">
          <h2 className="text-center">{text}</h2>
        </ModalHeader>

        <ModalBody>
          <Citation />
        </ModalBody>

        <ModalFooter>
          <Container fluid>
            <Row noGutters className="my-2">
              <Col className="d-flex w-100">
                <ButtonOk className="ml-auto" type="button" color="success" onClick={close} title={closeText}>
                  {t('OK')}
                </ButtonOk>
              </Col>
            </Row>
          </Container>
        </ModalFooter>
      </Modal>
    </>
  )
}
Example #9
Source File: Home.tsx    From reference-merchant with Apache License 2.0 5 votes vote down vote up
function Home(props) {
  const { t } = useTranslation("layout");
  const [selectedProduct, setSelectedProduct] = useState<Product>();
  const [products, setProducts] = useState<Product[] | undefined>();
  const [demoMode, setDemoMode] = useState<boolean>(props.demoMode === undefined ? false : true);

  const getProducts = async () => {
    try {
      setProducts(await new BackendClient().getProductsList());
    } catch (e) {
      console.error(e);
    }
  };

  useEffect(() => {
    //noinspection JSIgnoredPromiseFromCall
    getProducts();
  }, []);

  return (
    <>
      <TestnetWarning />
      <Container>
        <h1 className="text-center font-weight-bold mt-5">{t("name")}</h1>

        <section className="mt-5">
          {products && (
            <Row>
              {products.map((product, i) => (
                <Col key={product.gtin} md={6} lg={4}>
                  <Card key={product.gtin} className="mb-4">
                    <CardImg top src={product.image_url} />
                    <CardBody>
                      <CardTitle className="font-weight-bold h5">{product.name}</CardTitle>
                      <CardText>{product.description}</CardText>
                    </CardBody>
                    <CardFooter>
                      <Row>
                        <Col>
                          <div>
                            <strong>Price:</strong> {product.price / 1000000} {product.currency}
                          </div>
                        </Col>
                        <Col lg={4} className="text-right">
                          <Button
                            color="secondary"
                            block
                            className="btn-sm"
                            onClick={() => setSelectedProduct(products[i])}
                          >
                            Buy Now
                          </Button>
                        </Col>
                      </Row>
                    </CardFooter>
                  </Card>
                </Col>
              ))}
            </Row>
          )}
          {!products && <ProductsLoader />}
        </section>
      </Container>
      <Payment
        demoMode={demoMode}
        product={selectedProduct}
        isOpen={!!selectedProduct}
        onClose={() => setSelectedProduct(undefined)}
      />
    </>
  );
}
Example #10
Source File: app.tsx    From website with Apache License 2.0 5 votes vote down vote up
function App(): JSX.Element {
  const { statVar, placeInfo, isLoading } = useContext(Context);
  const showChart =
    !_.isNull(statVar.value.info) &&
    !_.isEmpty(placeInfo.value.enclosingPlace.dcid) &&
    !_.isEmpty(placeInfo.value.enclosedPlaceType);
  const showLoadingSpinner =
    isLoading.value.isDataLoading || isLoading.value.isPlaceInfoLoading;
  const [isSvModalOpen, updateSvModalOpen] = useState(false);
  const toggleSvModalCallback = () => updateSvModalOpen(!isSvModalOpen);

  // Show the BigQuery button when there is a chart
  return (
    <>
      <StatVarChooser
        openSvHierarchyModal={isSvModalOpen}
        openSvHierarchyModalCallback={toggleSvModalCallback}
      />
      <div id="plot-container">
        <Container fluid={true}>
          {!showChart && (
            <Row>
              <h1 className="mb-4">Map Explorer</h1>
            </Row>
          )}
          <Row>
            <PlaceOptions toggleSvHierarchyModal={toggleSvModalCallback} />
          </Row>
          {!showChart && (
            <Row>
              <Info />
            </Row>
          )}
          {showChart && (
            <Row id="chart-row">
              <ChartLoader />
            </Row>
          )}
          <div
            id="screen"
            style={{ display: showLoadingSpinner ? "block" : "none" }}
          >
            <div id="spinner"></div>
          </div>
        </Container>
      </div>
    </>
  );
}
Example #11
Source File: ClientHistory.tsx    From TutorBase with MIT License 5 votes vote down vote up
ClientHistory = () => {
    let clientData = useSelector(selectClientData);
    let [dropDownOpen, setDropdownOpen] = useState<boolean>(false);
    let [dropDownValue, setDropdownValue] = useState<String>("All");
    let [appointments, setAppointments] = useState<Array<Appointment>>([]);
    let dispatch = useDispatch();

    useEffect(() => {
        const getAppointments = async () => {
            return (await api.GetClientAppointments(clientData.clientId)).data.reverse();
        }

        getAppointments().then(value => {
                setAppointments(value);
                dispatch(clientDataActions.setAppointment(value));
            }
        )
    }, [clientData.clientId, dispatch]);

    let filteredAppointments = appointments;
    if (dropDownValue==="Denied"){
        filteredAppointments = appointments.filter((appointment) => !appointment.confirmed);
    } else if (dropDownValue==="Completed"){
        filteredAppointments = appointments.filter((appointment) => appointment.confirmed);
    }

    let meetingCards = filteredAppointments.map(appointment => (
        <MeetingCard appt={appointment} isTutor={false} includePrevious={true}/>
    ));

    return (
        <Container fluid style={{maxWidth:"100vw"}}>
            <Row className="title" style={{ marginTop: '25px'}}>
            <div className="profile-text">History</div>
            </Row>

            <hr></hr>

            <Dropdown isOpen={dropDownOpen} toggle={() => {setDropdownOpen(!dropDownOpen)}}>
                <DropdownToggle caret >
                    {dropDownValue}
                </DropdownToggle>

                <DropdownMenu>
                    <DropdownItem
                        onClick={(event) => {
                            setDropdownValue("All");
                            setDropdownOpen(false);
                        }}>All</DropdownItem>
                    <DropdownItem
                        onClick={(event) => {
                            setDropdownValue("Completed");
                            setDropdownOpen(false);
                        }}>Completed</DropdownItem>
                    <DropdownItem
                        onClick={(event) => {
                            setDropdownValue("Denied");
                            setDropdownOpen(false);
                        }}>Denied</DropdownItem>
                </DropdownMenu>
            </Dropdown>

            {meetingCards}
        </Container>
    );
}
Example #12
Source File: Meetings.tsx    From TutorBase with MIT License 5 votes vote down vote up
Meetings = (params: IParams) => {
    let clientData = useSelector(selectClientData);
    let tutorData = useSelector(selectTutorData);
    let [dropDownOpen, setDropdownOpen] = useState<boolean>(false);
    let [dropDownValue, setDropdownValue] = useState<String>("All");
    let [appointments, setAppointments] = useState<Array<Appointment>>([]);
    let dispatch = useDispatch();

    useEffect(() => {
        const getAppointments = async () => {
            return params.mode === "Tutor" ? (await api.GetTutorAppointments(tutorData.tutorId)).data : 
            (await api.GetClientAppointments(clientData.clientId)).data;
        }

        getAppointments().then(value => {
                
                setAppointments(value);
                if(params.mode === "Tutor")
                    dispatch(tutorDataActions.setAppointment(value));
                else
                    dispatch(clientDataActions.setAppointment(value));
            }
        )
    }, [clientData.clientId, tutorData.tutorId, dispatch]);


    let filteredAppointments = appointments;
    if (dropDownValue==="Pending"){
        filteredAppointments = appointments.filter((appointment) => !appointment.confirmed);
    } else if (dropDownValue==="Upcoming"){
        filteredAppointments = appointments.filter((appointment) => appointment.confirmed);
    }

    let meetingCards = filteredAppointments.map(appointment => (
        <MeetingCard appt={appointment} isTutor={params.mode==="Tutor"} includePrevious={false}/>
    ));


    return (
        <Container fluid>
            <Row className="title" style={{ marginTop: '25px'}}>
            <div className="profile-text">Meetings</div>
            </Row>

            <hr></hr>

            <Dropdown isOpen={dropDownOpen} toggle={() => {setDropdownOpen(!dropDownOpen)}}>
                <DropdownToggle caret >
                    {dropDownValue}
                </DropdownToggle>
                <DropdownMenu>
                    <DropdownItem 
                        onClick={(event) => {
                            setDropdownValue("All");
                            setDropdownOpen(false);
                        }}>All</DropdownItem>
                    <DropdownItem 
                        onClick={(event) => {
                            setDropdownValue("Pending");
                            setDropdownOpen(false);
                        }}>Pending</DropdownItem>
                    <DropdownItem 
                        onClick={(event) => {
                            setDropdownValue("Upcoming");
                            setDropdownOpen(false);
                        }}>Upcoming</DropdownItem>
                </DropdownMenu>
            </Dropdown>

            {meetingCards}
        </Container>
    );
}
Example #13
Source File: TutorHistory.tsx    From TutorBase with MIT License 5 votes vote down vote up
TutorHistory = () => {
    let tutorData = useSelector(selectTutorData);
    let [dropDownOpen, setDropdownOpen] = useState<boolean>(false);
    let [dropDownValue, setDropdownValue] = useState<String>("All");
    let [appointments, setAppointments] = useState<Array<Appointment>>([]);
    let dispatch = useDispatch();

    useEffect(() => {
        const getAppointments = async () => {
            return (await api.GetTutorAppointments(tutorData.tutorId)).data.reverse();
        }

        getAppointments().then(value => {
                setAppointments(value);
                dispatch(tutorDataActions.setAppointment(value));
            }
        )
    }, [tutorData.tutorId, dispatch]);

    let filteredAppointments = appointments;
    if (dropDownValue==="Denied"){
        filteredAppointments = appointments.filter((appointment) => !appointment.confirmed);
    } else if (dropDownValue==="Completed"){
        filteredAppointments = appointments.filter((appointment) => appointment.confirmed);
    }
   
    let meetingCards = filteredAppointments.map(appointment => (
        <MeetingCard appt={appointment} isTutor={true} includePrevious={true}/>
    ));

    return (
        <Container fluid>
            <Row className="title" style={{ marginTop: '25px'}}>
            <div className="profile-text">History</div>
            </Row>

            <hr></hr>

            <Dropdown isOpen={dropDownOpen} toggle={() => {setDropdownOpen(!dropDownOpen)}}>
                <DropdownToggle caret >
                    {dropDownValue}
                </DropdownToggle>
                <DropdownMenu>
                    <DropdownItem 
                        onClick={(event) => {
                            setDropdownValue("All");
                            setDropdownOpen(false);
                        }}>All</DropdownItem>
                    <DropdownItem 
                        onClick={(event) => {
                            setDropdownValue("Completed");
                            setDropdownOpen(false);
                        }}>Completed</DropdownItem>
                    <DropdownItem 
                        onClick={(event) => {
                            setDropdownValue("Denied");
                            setDropdownOpen(false);
                        }}>Denied</DropdownItem>
                </DropdownMenu>
            </Dropdown>

            {meetingCards}
        </Container>
    );
}
Example #14
Source File: app.tsx    From website with Apache License 2.0 5 votes vote down vote up
function App({
  query,
  loading,
  onSearch,
  chartsData,
}: AppPropType): JSX.Element {
  return (
    <>
      <div id="plot-container">
        <Container fluid={true}>
          <Row>
            <Card className="place-options-card">
              <Container className="place-options" fluid={true}>
                <div className="place-options-section">
                  <TextSearchBar
                    onSearch={onSearch}
                    initialValue={query}
                    placeholder='For example "People with Doctorate Degrees in France"'
                  />
                </div>
              </Container>
            </Card>
          </Row>
          {chartsData && !loading && (
            <Row>
              <Card>
                <div id="main" className="col-md-9x col-lg-10">
                  <StatVarResults {...chartsData} />
                </div>
              </Card>
            </Row>
          )}
          <div id="screen" style={{ display: loading ? "block" : "none" }}>
            <div id="spinner"></div>
          </div>
        </Container>
      </div>
    </>
  );
}
Example #15
Source File: OrderDetails.tsx    From reference-merchant with Apache License 2.0 4 votes vote down vote up
function OrderDetails({ orderId }: OrderDetailsProps) {
  const { t } = useTranslation("order");
  const [order, setOrder] = useState<Order | undefined | null>();

  const tx =
    order && order.paymentStatus.blockchainTxs.length > 0
      ? order.paymentStatus.blockchainTxs[0]
      : null;
  const refundTx =
    order &&
    order.paymentStatus.blockchainTxs.length > 1 &&
    order.paymentStatus.blockchainTxs[1].isRefund
      ? order.paymentStatus.blockchainTxs[1]
      : null;

  useEffect(() => {
    let isOutdated = false;

    const fetchOrder = async () => {
      try {
        const fetched = await new BackendClient().getOrderDetails(orderId);

        if (!isOutdated) {
          setOrder(fetched);
        }
      } catch (e) {
        console.error("Unexpected error", e);
      }
    };

    // noinspection JSIgnoredPromiseFromCall
    fetchOrder();

    return () => {
      isOutdated = true;
    };
  }, [orderId]);

  const cashOut = async () => {
    const client = new BackendClient();
    await client.payout(order!.vaspPaymentRef);
    const fetched = await new BackendClient().getOrderDetails(orderId);
    if (fetched) {
      setOrder(fetched);
    }
  };

  const refund = async () => {
    const client = new BackendClient();
    await client.refund(order!.vaspPaymentRef);
    const fetched = await new BackendClient().getOrderDetails(orderId);
    if (fetched) {
      setOrder(fetched);
    }
  };

  // Show spinner if order is undefined - it is being loaded
  let orderInfo = (
    <div className="d-flex justify-content-center">
      <Spinner color="primary" />
    </div>
  );

  if (order !== undefined) {
    if (order === null) {
      // There is no order with this ID
      orderInfo = (
        <Alert color="danger">
          <i className="fa fa-close" /> {t("unknown")}
        </Alert>
      );
    } else {
      orderInfo = (
        <>
          <InfoField caption="Order ID" value={orderId.toUpperCase()} />
          <InfoField caption="Creation time" value={order.createdAt.toLocaleString()} />
          <InfoField caption="Current status" value={t(`status.${order?.paymentStatus.status}`)} />

          <div className="mt-5">
            <OrderProducts
              productOrders={order.products}
              total={order.totalPrice}
              currency={order.currency}
            />
          </div>

          <div className="mt-5">
            <h2 className="h5 font-weight-normal text-body">Payment details</h2>

            <InfoField caption="Payment ID" value={order.vaspPaymentRef.toUpperCase()} />
            <InfoField caption="Payment type" value="Direct" />
            <InfoField
              caption="Merchant Diem address"
              value={order.paymentStatus.merchantAddress}
            />
            <InfoField caption="Payer Diem address" value={tx ? tx.senderAddress : "N/A"} />
            <InfoField caption="Payer wallet type" value="Non-hosted" />
            <InfoField
              caption="Diem amount"
              value={tx ? `${tx.amount / 1000000} ${tx.currency}` : "N/A"}
            />

            <LinkField
              caption="Diem transaction ID"
              text={tx ? `${tx.transactionId}` : undefined}
              url={`https://diemexplorer.com/testnet/version/${tx?.transactionId}`}
              external
            />

            {refundTx && (
              <LinkField
                caption="Diem refund transaction ID"
                text={`${refundTx.transactionId}`}
                url={`https://diemexplorer.com/testnet/version/${refundTx.transactionId}`}
                external
              />
            )}

            <div className="mt-4">Payment events</div>
            <div className="mt-3">
              <PaymentEvents events={order.paymentStatus.events} />
            </div>

            <div className="d-flex justify-content-center m-2">
              <Button
                disabled={!order.paymentStatus.canCashOut}
                onClick={cashOut}
                className="m-2"
                color="primary"
              >
                Cash out
              </Button>
              <Button
                disabled={!order.paymentStatus.canRefund}
                onClick={refund}
                className="m-2"
                color="primary"
              >
                Refund
              </Button>
            </div>

            <div className="d-flex justify-content-center mt-5">
              <a href={`admin/order/${orderId}`} target="_blank" rel="noopener noreferrer">
                #permalink
              </a>
            </div>
          </div>
        </>
      );
    }
  }

  return (
    <Container className="container-narrow pt-5">
      <div className="text-center">
        <div className="h2">{t("title")}</div>
      </div>

      <div className="d-flex flex-column justify-content-center m-5">{orderInfo}</div>
    </Container>
  );
}
Example #16
Source File: SeqViewSettings.tsx    From nextclade with MIT License 4 votes vote down vote up
export function SeqViewSettings() {
  const { t } = useTranslationSafe()

  const [maxNucMarkers, setMaxNucMarkers] = useRecoilStateDeferred(maxNucMarkersAtom)

  const [seqMarkerMissingHeightState, setSeqMarkerMissingHeightState] = useSeqMarkerState(
    seqMarkerMissingHeightStateAtom,
  )

  const [seqMarkerGapHeightState, setSeqMarkerGapHeightState] = useSeqMarkerState(seqMarkerGapHeightStateAtom)

  const [seqMarkerMutationHeightState, setSeqMarkerMutationHeightState] = useSeqMarkerState(
    seqMarkerMutationHeightStateAtom,
  )

  const [seqMarkerUnsequencedHeightState, setSeqMarkerUnsequencedHeightState] = useSeqMarkerState(
    seqMarkerUnsequencedHeightStateAtom,
  )

  return (
    <Container fluid>
      <Row noGutters>
        <Col>
          <Form>
            <NumericField
              identifier="max-nuc-markers"
              label={t('Maximum number of nucleotide sequence view markers')}
              title={t(
                'Sets threshold on maximum number of markers (mutations, deletions etc.) to display in nucleotide views. Reducing this number increases performance. If the threshold is reached, then the nucleotide sequence view will be disabled.',
              )}
              min={0}
              max={1_000_000}
              value={maxNucMarkers}
              onValueChanged={setMaxNucMarkers}
            />

            <FormGroup>
              {t('Missing')}
              <Multitoggle
                values={SEQ_MARKER_HEIGHT_STATES}
                value={seqMarkerMissingHeightState}
                onChange={setSeqMarkerMissingHeightState}
              />
            </FormGroup>

            <FormGroup>
              <Label>
                {t('Gaps')}
                <Multitoggle
                  values={SEQ_MARKER_HEIGHT_STATES}
                  value={seqMarkerGapHeightState}
                  onChange={setSeqMarkerGapHeightState}
                />
              </Label>
            </FormGroup>

            <FormGroup>
              <Label>
                {t('Mutations')}
                <Multitoggle
                  values={SEQ_MARKER_HEIGHT_STATES}
                  value={seqMarkerMutationHeightState}
                  onChange={setSeqMarkerMutationHeightState}
                />
              </Label>
            </FormGroup>

            <FormGroup>
              <Label>
                {t('Unsequenced')}
                <Multitoggle
                  values={SEQ_MARKER_HEIGHT_STATES}
                  value={seqMarkerUnsequencedHeightState}
                  onChange={setSeqMarkerUnsequencedHeightState}
                />
              </Label>
            </FormGroup>
          </Form>
        </Col>
      </Row>
    </Container>
  )
}
Example #17
Source File: ClientSettings.tsx    From TutorBase with MIT License 4 votes vote down vote up
ClientSettings = () => {
    let clientData = useSelector(selectClientData);
    let dispatch = useDispatch();

    let [nameModalOpen, setNameModalOpen] = useState<boolean>(false);
    let [imgModalOpen, setImgModalOpen] = useState<boolean>(false);
    
    let [tempName, setTempName] = useState<Name>({
        first_name: "", 
        last_name: ""
    });
    let [clientName, setClientName] = useState<Name>({
        first_name: "",
        last_name: ""
    }); 
    let [croppedImg, setCroppedImg] = useState<string>("");
    let [clientImg, setClientImg] = useState<string>("");

    const saveNameChange = async () => {
        let name: Name = {first_name: tempName.first_name, last_name: tempName.last_name};
        await api.SetClientName(name, clientData.clientId);
        setClientName(name);
        dispatch(clientDataActions.setFirstName(tempName.first_name));
        dispatch(clientDataActions.setLastName(tempName.last_name));
        setNameModalOpen(false);
    }

    const handleImageSave = async (img: string) => {
        await api.SetClientProfileImage(img, clientData.clientId);
        setClientImg(img);
        dispatch(clientDataActions.setProfileImage(img));
    }

    const saveImgChange = async () => {
        if(croppedImg.toString() !== "") {
            CompressAndSaveImg(croppedImg, clientData.first_name + clientData.last_name + "-photo", handleImageSave);
        } else {
            handleImageSave(croppedImg);
        }

        setImgModalOpen(false);
    }

    const cancelNameChange = () => {
        setNameModalOpen(false); 
        setTempName(clientName);
    }

    const cancelImgChange = () => {
        setCroppedImg("");
        setImgModalOpen(false);
    }

    useEffect(() => {
        const getUser = async () => {
            return (await api.GetUserById(clientData.clientId)).data;
        }
        getUser().then(value => {
            setTempName({first_name: value[0].first_name, last_name: value[0].last_name});
            setClientName({first_name: value[0].first_name, last_name: value[0].last_name});
            setClientImg(value[0].profile_img);
            dispatch(clientDataActions.setFirstName(value[0].first_name));
            dispatch(clientDataActions.setLastName(value[0].last_name));
            dispatch(clientDataActions.setProfileImage(value[0].profile_img));
        });
        
    }, [clientData.clientId, dispatch]);

    return (
        <Container className="settings" fluid>
            <Row className="title" style={{ marginTop: '25px'}}>
            <div className="profile-text">Settings</div>
            </Row>

            <hr></hr>

             <Row>
                <ListGroup>

                    <ListGroupItem className="img-item">
                        <img src={clientImg === ""  ? defaultUser : clientImg} width="200px"/>
                        <a href="#" className="modal-link" onClick={() => setImgModalOpen(true)}>
                            <span className="heading-item"><FontAwesomeIcon icon={faEdit} className="font-adj"/></span>
                        </a>
                        <Modal isOpen={imgModalOpen} fade={false} toggle={() => {setImgModalOpen(!imgModalOpen)}} className="img-modal">
                            <ModalHeader toggle={() => {cancelImgChange()}}>Edit Profile Photo</ModalHeader>
                            <ModalBody>
                                Change your profile photo here.
                                <hr/>
                                <Avatar
                                    width={250}
                                    height={250}
                                    cropColor="#E66064"
                                    closeIconColor="#E66064"
                                    onCrop={(img) => setCroppedImg(img)}
                                    onClose={() => {setCroppedImg("")}}
                                    onBeforeFileLoad={() => {}}
                                    src={clientImg === "" ? defaultUser : clientImg}
                                />
                            </ModalBody>
                            <ModalFooter>
                                <Button className="btn-red" onClick={() => {saveImgChange()}}>Save</Button>
                                <Button color="secondary" onClick={() => {cancelImgChange()}}>Cancel</Button>
                            </ModalFooter>
                        </Modal>
                    </ListGroupItem>

                    <ListGroupItem className="name-item">
                        <span className="heading-item">{clientName.first_name} {clientName.last_name}</span>
                        <a href="#" className="modal-link" onClick={() => {setNameModalOpen(true)}}>
                            <span className="heading-item"><FontAwesomeIcon icon={faEdit} className="font-adj"/></span>
                        </a>
                        <Modal isOpen={nameModalOpen} fade={false} toggle={() => {setNameModalOpen(!nameModalOpen)}} className="name-modal">
                            <ModalHeader toggle={() => {cancelNameChange()}}>Edit Name</ModalHeader>
                            <ModalBody>
                                Change your name here.
                                <hr/>
                                <InputGroup>
                                    First Name:<Input id="first-name" value={tempName.first_name} onChange={(value) => setTempName({first_name: value.target.value, last_name: tempName.last_name})} />
                                </InputGroup>
                                <InputGroup>
                                    Last Name:<Input id="last-name" value={tempName.last_name} onChange={(value) => setTempName({first_name: tempName.first_name, last_name: value.target.value})} />
                                </InputGroup>
                            </ModalBody>
                            <ModalFooter>
                                <Button className="btn-red" onClick={() => {saveNameChange()}}>Save</Button>
                                <Button color="secondary" onClick={() => {cancelNameChange()}}>Cancel</Button>
                            </ModalFooter>
                        </Modal>
                    </ListGroupItem>

                 </ListGroup>
             </Row>
        </Container>
    );
}
Example #18
Source File: SettingsButton.tsx    From nextclade with MIT License 4 votes vote down vote up
export function SettingsButton() {
  const { t } = useTranslationSafe()

  const [isSettingsDialogOpen, setIsSettingsDialogOpen] = useRecoilState(isSettingsDialogOpenAtom)
  const [showWhatsnewOnUpdate, setShowWhatsnewOnUpdate] = useRecoilState(changelogShouldShowOnUpdatesAtom)

  const toggleOpen = useCallback(
    () => setIsSettingsDialogOpen(!isSettingsDialogOpen),
    [setIsSettingsDialogOpen, isSettingsDialogOpen],
  )

  const text = useMemo(() => t('Settings'), [t])
  const closeText = useMemo(() => t('Close this window'), [t])

  return (
    <>
      <ButtonSettingsBase type="button" onClick={toggleOpen} title={text}>
        <IoMdSettings className="mr-xl-2" />
        <span className="d-none d-xl-inline">{text}</span>
      </ButtonSettingsBase>

      <Modal backdrop="static" centered isOpen={isSettingsDialogOpen} toggle={toggleOpen} fade={false}>
        <ModalHeader toggle={toggleOpen} tag="div">
          <h3 className="text-center">{text}</h3>
        </ModalHeader>

        <ModalBody>
          <Container>
            <Row>
              <Col>
                <CardL2>
                  <CardL2Header>{t('System')}</CardL2Header>
                  <CardL2Body>
                    <SystemSettings />
                  </CardL2Body>
                </CardL2>
              </Col>
            </Row>
            <Row noGutters>
              <Col>
                <CardL2>
                  <CardL2Header>{t('Sequence view markers')}</CardL2Header>
                  <CardL2Body>
                    <SeqViewSettings />
                  </CardL2Body>
                </CardL2>
              </Col>
            </Row>
            <Row noGutters>
              <Col>
                <CardL2>
                  <CardL2Header>{t('Other settings')}</CardL2Header>
                  <CardL2Body>
                    <FormGroup>
                      <Toggle
                        identifier={'settings-show-whatsnew-toggle'}
                        checked={showWhatsnewOnUpdate}
                        onCheckedChanged={setShowWhatsnewOnUpdate}
                      >
                        {t(`Show "What's new" dialog after each update`)}
                      </Toggle>
                    </FormGroup>
                  </CardL2Body>
                </CardL2>
              </Col>
            </Row>
          </Container>
        </ModalBody>

        <ModalFooter>
          <Container fluid>
            <Row noGutters className="my-2">
              <Col className="d-flex w-100">
                <ButtonOk className="ml-auto" type="button" color="success" onClick={toggleOpen} title={closeText}>
                  {t('OK')}
                </ButtonOk>
              </Col>
            </Row>
          </Container>
        </ModalFooter>
      </Modal>
    </>
  )
}
Example #19
Source File: TutorOverview.tsx    From TutorBase with MIT License 4 votes vote down vote up
TutorOverview = () => {
    let tutorData = useSelector(selectTutorData);
    let dispatch = useDispatch();

    let [tooltipsOpen, setTooltipsOpen] = useState<Array<boolean>>([false, false, false, false, false, false, false]);
    let [weeklyAppointments, setWeeklyAppointments] = useState<Array<Appointment>>([]);
    let [tutorCourses, setTutorCourses] = useState<Array<Course>>([]);

    let daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    let currDate = useMemo(() => {return new Date()}, [])
    let currWeekMap = GetWeekMap(currDate);

    useEffect(() => {
        const getTutorAppointments = async () => {
            return (await api.GetTutorAppointments(tutorData.tutorId)).data;
        }

        getTutorAppointments().then(value => {
                setWeeklyAppointments(GetWeeklyAppointments(value, currDate));
                dispatch(tutorDataActions.setAppointment(value));
            }
        )
    }, [currDate, tutorData.tutorId, dispatch]);

    useEffect(() => {
        const getTutorCourses = async () => {
            return (await api.GetCoursesByTutorId(tutorData.tutorId)).data;
        }

        getTutorCourses().then(value => {
                setTutorCourses(value);
                dispatch(tutorDataActions.setCourses(value));
            }
        )
    }, [tutorData.tutorId, dispatch]);

    return (
        <Container className="overview" fluid>
            <Row className="title" style={{ marginTop: '25px'}}>
                <div className="profile-text">Overview</div>
            </Row>

            <hr></hr>

            <Row>
                <Col className="courses-col" md={6}>
                    <Row className="title" style={{ marginTop: '25px'}}>
                        <h2>Courses</h2>
                    </Row>
                    <Container className="table-container">
                        <Table className="table-striped">
                            <tbody>
                                {tutorCourses.map((course, i) => {
                                        return (
                                            <tr key={i}>
                                                <td className="td-bold">{course.name}</td>
                                            </tr>
                                        );
                                    }
                                )}
                                {tutorCourses.length > 0 ? <></> :
                                    <tr><td className="td-bold">No courses found!<br/>Change which courses you plan to tutor from the Settings page.</td></tr>
                                }
                            </tbody>
                        </Table>
                    </Container>
                </Col>
                <Col className="weekly-sched-col" md={6}>
                    <Row className="title" style={{ marginTop: '25px'}}>
                        <h2>Weekly Tutoring Schedule</h2>
                    </Row>
                    <Container className="table-container">
                        <Table className="table-striped">
                            <tbody>
                                {Array.from(Array(7).keys()).map(day => {
                                    let date = currWeekMap.get(day);
                                    if(date !== undefined) {
                                        let date_time = BreakDownTime(date.toISOString());
                                        let daily_appointments = GetDailyAppointments(weeklyAppointments, date);
                                        let unconfirmed = UnconfirmedMeetingExists(daily_appointments);
                                        return (
                                            <tr key={day}>
                                                <td className="td-bold">{daysOfWeek[day]}, {date_time[0].split(",")[0]}</td>
                                                <td>
                                                    {daily_appointments.length > 0 ? daily_appointments.length : "No"} Meetings
                                                    {unconfirmed ? 
                                                    <span className="sched-pending">
                                                        <FontAwesomeIcon id={"pending-icon-"+day} icon={faQuestionCircle}/>
                                                        <Tooltip placement="top" isOpen={tooltipsOpen[day]} target={"pending-icon-"+day} toggle={() => {
                                                            let tooltipsOpenCopy = [...tooltipsOpen];
                                                            tooltipsOpenCopy[day] = !tooltipsOpen[day];
                                                            setTooltipsOpen(tooltipsOpenCopy); 
                                                        }}>
                                                            You have one or more unconfirmed meetings on this day.
                                                        </Tooltip>
                                                    </span> : <></>}
                                                </td>
                                            </tr>
                                        );
                                    } else {
                                        return <></>;
                                    }
                                })}
                            </tbody>
                        </Table>
                    </Container>
                </Col>
            </Row>

        </Container>
    );
}
Example #20
Source File: TutorPanelSignup.tsx    From TutorBase with MIT License 4 votes vote down vote up
Panel = (props: IProps) => {
    let dispatch = useDispatch();
    let id = useSelector(selectClientData).clientId;
    const [modalOpen, setModalOpen] = useState(false);
    let params : string = useLocation().pathname;
    const [selectedSubjects, setSelectedSubjects] = useState(new Set<string>());
    const [RIN, setRIN] = useState("");
    const [validRIN, setValidRIN] = useState(false);
    const [cohort, setCohort] = useState("");
    const [comments, setComments] = useState("");
    const [footerMessage, setFooterMessage] = useState("");
    const [rate, setRate] = useState(0);
    let subjects = [];
    let selectedSubjectsOutput = [];
    const [subjectsList, setSubjectsList] = useState(new Array<Subject>());
    function checkRIN(value: string) {
        if (value.length !== 9) {
            setValidRIN(false);
        }
        else {
            setValidRIN(true); 
        }
        setRIN(value);

    }
    function submit() {
        if (!validRIN
            || cohort === ""
            || cohort === "Select"
            || selectedSubjects.size === 0) {
                setFooterMessage("Please complete required fields.");
                return;
        }
        let subs: Array<String> = Array.from(selectedSubjects.keys());
        api.TutorSignup(id, RIN, subs, comments, rate).then(res =>{
            res ?
            setFooterMessage("Application submitted.")
            : setFooterMessage("Error submitting. Please try again.");
            }).catch(err => {
                setFooterMessage("Error submitting. Please try again.")
            });
    }
    
    useEffect(() => {
        // Get all avaliable subjects from API
        const getSubjects = async () => {
            return (await api.GetSubjects()).data;
        }

        getSubjects().then(value => {
                setSubjectsList(value);
            }
        )
    }, []);
    for (let i = 0; i < subjectsList.length; i++) {
        let name: string = subjectsList[i].id;
        let color = SubjectToColor(name);
        subjects.push(
            (<Button
                style={{background: color}}
                onClick={() => setSelectedSubjects(SelectedSubjectsHandler(selectedSubjects, name))}
            >
                {name}
            </Button>
            )
            );
    }
    let selectedSubs:Array<string> = Array.from(selectedSubjects.keys());
    for (let i = 0; i < selectedSubs.length; i++) {
        let name: string = selectedSubs[i];
        let color = SubjectToColor(name);
        selectedSubjectsOutput.push(
            (
               
                    <Badge
                    style={{
                        backgroundColor: color,
                        cursor:'default',
                        color: "black",
                        minWidth: '6em',
                        display: "flex",
                        flexDirection:'row',
                        alignItems: 'center',
                        marginRight: '0.5em'
                    }}
                    pill
                >
                    <div style={{
                        display: "flex",
                        flex: '50%',
                    }}>
                        {name + ' '}
                    </div> 
                    <Button 
                    close 
                    style={{
                        display: "flex",
                        flex: '50%',
                        alignItems: 'center'
                    }}
                    onClick={() => setSelectedSubjects(SelectedSubjectsHandler(selectedSubjects, name))} /> 
                    
                </Badge>
            )
        );
    }
    return (
        <div id="panel-wrapper">
            <Navbar className={classNames("navbar-expand-lg", "navbar-light", "bg-light", "border-bottom", "shadow")}>
                <Button className="btn-red" id="menu-toggle" onClick={() => {
                    dispatch(actions.toggleSidebar());
                }}>☰</Button>
            </Navbar>

            <Container fluid className="background" style={{marginBottom:'10em'}}>
                <hr></hr>
                <Row xs="2" className="parent">

                </Row>
                <div style={{display:'flex', flexDirection:'column', flexWrap:'wrap', alignContent:'center'}}>
                    {props.isLoading ? (
                        <div style={{display:'flex', flexDirection:'row', flex:'1 1 0px', flexWrap:'wrap', justifyContent:'center', marginTop:'10em'}}>
                            <Spinner style={{color:'#E66064'}}></Spinner>
                        </div>) 
                    : (
                    <div>
                        <div style={{display:'flex', flexDirection:'row', flex:'1 1 0px', flexWrap:'wrap', justifyContent:'center', marginTop:'10em'}}>
                            <h5>You are not currently signed up as a tutor. This dashboard is for tutors only. You can apply to be a TutorBase tutor below!
                            </h5></div>
                            
                            <div style={{display:'flex', flexDirection:'row', flex:'1 1 0px', flexWrap:'wrap', justifyContent:'center', marginTop:'1em'}}>
                            <Button 
                                className="btn-red" 
                                style={{height:'4em', width:'10em', borderRadius:'20em'}}
                                onClick={() => setModalOpen(true)}
                            >
                                Sign up as tutor
                            </Button>
                            <Modal
                                centered={true}
                                scrollable={true}
                                isOpen={modalOpen}
                            >
                                <ModalHeader toggle={() => setModalOpen(!modalOpen)}>
                                    Tutor Application Form
                                </ModalHeader>
                                <ModalBody>
                                <h5>RIN</h5>
                                <Input 
                                    defaultValue={RIN}
                                    onChange={(e) => checkRIN(e.target.value)}
                                    valid={validRIN}
                                    invalid={!validRIN}
                                    />
                                <p />
                                <h5>Cohort</h5>
                                <Input 
                                type="select"
                                    onChange={(e) => setCohort(e.target.value)}
                                    initialValue="Select"
                                    invalid={cohort === "" || cohort === "Select"}>
                                        <option>
                                        Select
                                    </option>
                                    <option>
                                        Freshman
                                    </option>
                                    <option>
                                        Sophomore
                                    </option>
                                    <option>
                                        Junior
                                    </option>
                                    <option>
                                        Senior
                                    </option>
                                    <option>
                                        Graduate
                                    </option>
                                    </Input>
                                <p />
                                <h5>Select Subjects to tutor</h5>
                                <ButtonGroup>
                                    {subjects}
                                    
                                </ButtonGroup>
                                <p>
                                    Selected:
                                    <Card
                                    outline={selectedSubjects.size === 0}
                                    color= {selectedSubjects.size === 0 ? "danger" : ""}>
                                <CardBody 
                                    style={{
                                        display: "flex",
                                        background: "lightgray",
                                        minHeight: "4em",
                                        flexWrap: 'wrap'
                                    }}>
                                {selectedSubjectsOutput}


                            </CardBody></Card>
                            </p>
                            <p>
                                <h5>Hourly Rate ($) (optional)</h5>
                                <Input
                                type="number"
                                    onChange={(e) => setRate(+(e.target.value))} />
                                </p>
                                <h5>Comments (optional)</h5>
                                <Input 
                                    type="textarea"
                                    onChange={(e) => setComments(e.target.value)} />

                                </ModalBody>
                                <ModalFooter>
                                <p style={{color: footerMessage === "Application submitted." ? 'green' : 'red'}}>
                                    {footerMessage}
                                </p>

                                <Button
                                    color="primary"
                                    onClick={() => submit()}
                                >
                                    Submit
                                </Button>
                                {' '}
                                <Button onClick={() => setModalOpen(false)}>
                                    Cancel
                                </Button>
                                </ModalFooter>
                            </Modal>
                        </div>
                    </div>
                    )}
                </div>
            </Container>
        </div>
    );
}
Example #21
Source File: SignupPage.tsx    From TutorBase with MIT License 4 votes vote down vote up
export function SignUpPage() {
    const [signUpData, setSignUpData] = useState({
        first_name: "",
        last_name: "",
        email: "",
        password: "",
        phone_number: "",
        visible: false,
        passwordValid: false,
        emailValid: false,
        firstNameValid: false,
        lastNameValid: false,
        phoneValid: false,
        loginValid: true,
        emailTaken: false,
    });

    const history = useHistory();

    const HandleChange = (event: any) => {
        let name = event.target.name;
        let value = event.target.value;

        if (name === "first_name")
            IsFirstNameValid(value)
        else if (name === "last_name")
            IsLastNameValid(value)
        else if (name === "email")
            IsEmailValid(value)
    };

    const IsFirstNameValid = (value: any) => {
        let firstValid = false;
        if (value.length > 0)
            firstValid = true

        setSignUpData({
            ...signUpData,
            first_name: value,
            firstNameValid: firstValid,
        })
    }

    const IsLastNameValid = (value: any) => {
        let lastValid = false;
        if (value.length > 0)
            lastValid = true

        setSignUpData({
            ...signUpData,
            last_name: value,
            lastNameValid: lastValid,
        })
    }

    const IsEmailValid = (value: string) => {
        setSignUpData((signUpData: any) => ({
            ...signUpData,
            email: value,
            emailValid: isEmail.validate(value),
            emailTaken: false,
        }));
    }

    const IsPhoneNumberValid = (value: any) => {
        let phoneValid = false;
        if (value.length === 0 || (value.length === 10 && value.match(/^[0-9]+$/) != null))
            phoneValid = true

        setSignUpData({
            ...signUpData,
            phone_number: value,
            phoneValid: phoneValid,
        })
    }

    const CreateUser = async () => {
        let body = {
            "email": signUpData.email,
            "first_name": signUpData.first_name,
            "last_name": signUpData.last_name,
            "phone": signUpData.phone_number,
        }

        const request = await fetch(ApiBaseAddress + "api/users", {
            method: "post",
            body: JSON.stringify(body),
            headers: {
                "Content-Type": "application/json",
            },
            credentials: 'include',
        });

        if (request.ok) {
            history.push("home");
        } else {
            setSignUpData((signUpData) => ({
                ...signUpData,
                emailTaken: true,
                emailValid: false,
            }));
        }
    }
        
    const SubmitEvent = (event: any) => {
        event.preventDefault();
        if (signUpData.firstNameValid && signUpData.lastNameValid) {
            CreateUser();
        } else {
            setSignUpData({
                ...signUpData,
                loginValid: false
            });
        }
    };

    return (
        <div className="flexBox">

            <Container className="signupContainer" fluid="xs" style={{padding: "3%", margin: "10em"}}>
                <Row>
                    <Col xs="1"/>
                    <Col xs="11">
                        <Form onSubmit={event => SubmitEvent(event)}>
                            <Label className="signupText">Sign Up</Label>
                            <FormGroup row>
                                <Container>
                                    <Row>
                                        <Col xs="auto">
                                            <Input
                                                type="text"
                                                className="form-control"
                                                name="first_name"
                                                placeholder="First Name"
                                                value={signUpData.first_name}
                                                onChange={event => HandleChange(event)}
                                                autoComplete="off"
                                            />
                                        </Col>
                                        <Col xs="auto">
                                            <div>
                                                {signUpData.firstNameValid ?
                                                    <MdCheck size="30px" color="green"></MdCheck> :
                                                    <VscError size="30px" color="red"></VscError>}
                                            </div>
                                        </Col>
                                    </Row>
                                </Container>
                            </FormGroup>
                            <FormGroup row>
                                <Container>
                                    <Row>
                                        <Col xs="auto">
                                            <Input
                                                type="text"
                                                className="form-control"
                                                name="last_name"
                                                placeholder="Last Name"
                                                value={signUpData.last_name}
                                                onChange={event => HandleChange(event)}
                                                autoComplete="off"
                                            />
                                        </Col>
                                        <Col xs="auto">
                                            <div>
                                                {signUpData.lastNameValid ?
                                                    <MdCheck size="30px" color="green"></MdCheck> :
                                                    <VscError size="30px" color="red"></VscError>}
                                            </div>
                                        </Col>
                                    </Row>

                                </Container>
                            </FormGroup>
                            <FormGroup row>
                                <Container>
                                    <Row>
                                        <Col xs="auto">
                                            <Input
                                                type="email"
                                                className="form-control"
                                                name="email"
                                                placeholder="Email"
                                                value={signUpData.email}
                                                onChange={event => HandleChange(event)}
                                                autoComplete="off"
                                            />
                                        </Col>
                                        <Col xs="auto">
                                            <div>
                                                {signUpData.emailValid ?
                                                    <MdCheck size="30px" color="green"></MdCheck> :
                                                    <VscError size="30px" color="red"></VscError>}
                                            </div>
                                        </Col>
                                    </Row>
                                </Container>
                            </FormGroup>
                            <FormGroup row>
                                <Container fluid>
                                    <Row>
                                        <Col xs="auto">
                                            <Input
                                                type="number"
                                                className="form-control"
                                                name="phone"
                                                placeholder="Cell Number (optional)"
                                                value={signUpData.phone_number}
                                                onChange={event => HandleChange(event)}
                                                autoComplete="off"
                                            />
                                        </Col>
                                        <Col xs="auto">
                                            <div>
                                                {signUpData.phoneValid ? (
                                                    <MdCheck size="30px" color="green"></MdCheck>
                                                ) : (
                                                    <VscError size="30px" color="red"></VscError>
                                                )}
                                            </div>
                                        </Col>
                                    </Row>
                                </Container>
                            </FormGroup>
                            <div>
                                {signUpData.loginValid ? '' : 'Invalid Fields'}
                            </div>
                            <div>
                                {signUpData.emailTaken && 'Email already taken'}
                            </div>
                            <Button color="danger" type="submit">
                                Create Account
                            </Button>
                            <div>Already have an account? Click <Link to='/login'>here</Link></div>
                        </Form>

                    </Col>
                </Row>
            </Container>
        </div>
    );
}
Example #22
Source File: ConfirmationDetails.tsx    From reference-merchant with Apache License 2.0 4 votes vote down vote up
function ConfirmationDetails({ orderId }: OrderDetailsProps) {
  const { t } = useTranslation(["order", "layout"]);
  const [order, setOrder] = useState<Order | undefined | null>();

  useEffect(() => {
    let isOutdated = false;

    const fetchOrder = async () => {
      try {
        const fetched = await new BackendClient().getOrderDetails(orderId);

        if (!isOutdated) {
          setOrder(fetched);
        }
      } catch (e) {
        console.error("Unexpected error", e);
      }
    };

    // noinspection JSIgnoredPromiseFromCall
    fetchOrder();

    return () => {
      isOutdated = true;
    };
  }, [orderId]);

  const cashOut = async () => {
    const client = new BackendClient();
    await client.payout(order!.vaspPaymentRef);
    const fetched = await new BackendClient().getOrderDetails(orderId);
    if (fetched) {
      setOrder(fetched);
    }
  };

  // Show spinner if order is undefined - it is being loaded
  let orderInfo = (
    <div className="d-flex justify-content-center">
      <Spinner color="primary" />
    </div>
  );

  if (order !== undefined) {
    if (order === null) {
      // There is no order with this ID
      orderInfo = (
        <Alert color="danger">
          <i className="fa fa-close" /> {t("unknown")}
        </Alert>
      );
    } else {
      orderInfo = (
        <>
          <div style={{ display: "flex", alignItems: "center" }}>
            <i className="fa fa-check-circle fa-4x" style={{ color: "#59a559" }} />
            <div style={{ marginLeft: 20, fontSize: 20, fontWeight: 500, color: "black" }}>
              {t("order_on_the_way")}
            </div>
          </div>
          <div className="h5 mt-4 mb-4 font-weight-normal text-body">
            {t("got_your_order")} <br />
            {t("order_summary")}
          </div>
          <Row style={{ alignItems: "center" }}>
            <Col xs={3}>
              <img
                src={order.products[0].product.image_url}
                width="75"
                height="75"
                alt={"product image"}
              />
            </Col>
            <Col>{order.products[0].product.name}</Col>
            <Col style={{ textAlign: "right" }}>
              {t("qty")}. {order.products[0].quantity}
            </Col>
          </Row>
          <Row className="mt-4">
            <Col xs={8}>{t("items_Total")}</Col>
            <Col xs={4} style={{ textAlign: "right" }}>
              {order.totalPrice / 1000000} XUS
            </Col>
          </Row>
          <Row className="mt-1">
            <Col xs={9}>{t("shipping")}</Col>
            <Col xs={3} className="pl-2">
              {t("free")}
            </Col>
          </Row>
          <Row className="mt-1">
            <Col xs={9}>{t("duties_taxes")}</Col>
            <Col xs={3} className="pl-2">
              {t("free")}
            </Col>
          </Row>
          <Row className="mt-1">
            <Col xs={8} className="font-weight-bold">
              {t("total_order")}
            </Col>
            <Col xs={4} style={{ textAlign: "right" }} className="font-weight-bold">
              {order.totalPrice / 1000000} XUS
            </Col>
          </Row>
        </>
      );
    }
  }

  return (
    <>
      <TestnetWarning />
      <Container className="container-very-narrow pt-5">
        <div className="text-center">
          <div className="h2">{t("layout:name")}</div>
        </div>
        <div className="d-flex flex-column justify-content-center m-3">{orderInfo}</div>
      </Container>
    </>
  );
}
Example #23
Source File: page.tsx    From website with Apache License 2.0 4 votes vote down vote up
render(): JSX.Element {
    const numPlaces = Object.keys(this.state.placeName).length;
    const numStatVarInfo = Object.keys(this.state.statVarInfo).length;
    const namedPlaces: NamedPlace[] = [];
    for (const place in this.state.placeName) {
      namedPlaces.push({ dcid: place, name: this.state.placeName[place] });
    }
    const statVarTokens = Array.from(
      getTokensFromUrl(TIMELINE_URL_PARAM_KEYS.STAT_VAR, statVarSep)
    );
    const statVars = statVarTokens.map((sv) =>
      sv.includes("|") ? sv.split("|")[0] : sv
    );

    const deselectSVs = (svList: string[]) => {
      const availableSVs = statVars.filter((sv) => svList.indexOf(sv) === -1);
      const statVarTokenInfo = {
        name: TIMELINE_URL_PARAM_KEYS.STAT_VAR,
        sep: statVarSep,
        tokens: new Set(availableSVs),
      };
      setTokensToUrl([statVarTokenInfo]);
    };

    const svToSvInfo = {};
    for (const sv of statVars) {
      svToSvInfo[sv] =
        sv in this.state.statVarInfo ? this.state.statVarInfo[sv] : {};
    }

    return (
      <>
        <StatVarWidget
          openSvHierarchyModal={this.state.showSvHierarchyModal}
          openSvHierarchyModalCallback={this.toggleSvHierarchyModal}
          collapsible={true}
          svHierarchyType={StatVarHierarchyType.SCATTER}
          samplePlaces={namedPlaces}
          deselectSVs={deselectSVs}
          selectedSVs={svToSvInfo}
          selectSV={(sv) =>
            addToken(TIMELINE_URL_PARAM_KEYS.STAT_VAR, statVarSep, sv)
          }
        />
        <div id="plot-container">
          <Container fluid={true}>
            {numPlaces === 0 && <h1 className="mb-4">Timelines Explorer</h1>}
            <Card id="place-search">
              <Row>
                <Col sm={12}>
                  <p>Select places:</p>
                </Col>
                <Col sm={12}>
                  <SearchBar
                    places={this.state.placeName}
                    addPlace={(place) =>
                      addToken(TIMELINE_URL_PARAM_KEYS.PLACE, placeSep, place)
                    }
                    removePlace={(place) => {
                      removeToken(
                        TIMELINE_URL_PARAM_KEYS.PLACE,
                        placeSep,
                        place
                      );
                    }}
                  />
                </Col>
              </Row>
              <Row className="d-lg-none">
                <Col>
                  <Button color="primary" onClick={this.toggleSvHierarchyModal}>
                    Select variables
                  </Button>
                </Col>
              </Row>
            </Card>
            {numPlaces === 0 && <Info />}
            {numPlaces !== 0 && numStatVarInfo !== 0 && (
              <div id="chart-region">
                <ChartRegion
                  placeName={this.state.placeName}
                  statVarInfo={this.state.statVarInfo}
                  statVarOrder={statVars}
                ></ChartRegion>
              </div>
            )}
          </Container>
        </div>
      </>
    );
  }
Example #24
Source File: statvar.tsx    From website with Apache License 2.0 4 votes vote down vote up
export function StatVarChooser(props: StatVarChooserProps): JSX.Element {
  const { x, y, place } = useContext(Context);

  // Temporary variable for storing an extra statvar.
  const [thirdStatVar, setThirdStatVar] = useState(emptyStatVar);
  // Records which two of the three statvars are wanted if a third statvar is selected.
  const [modalSelected, setModalSelected] = useState(defaultModalSelected);
  const [modalOpen, setModalOpen] = useState(false);
  const [samplePlaces, setSamplePlaces] = useState(
    getSamplePlaces(
      place.value.enclosingPlace.dcid,
      place.value.enclosedPlaceType,
      place.value.enclosedPlaces
    )
  );
  useEffect(() => {
    const samplePlaces = getSamplePlaces(
      place.value.enclosingPlace.dcid,
      place.value.enclosedPlaceType,
      place.value.enclosedPlaces
    );
    setSamplePlaces(samplePlaces);
  }, [place.value.enclosedPlaces]);
  const closeModal = () => {
    setThirdStatVar(emptyStatVar);
    setModalOpen(false);
  };

  useEffect(() => {
    const statVarsToGetInfo = [];
    if (!_.isEmpty(x.value.statVarDcid) && _.isNull(x.value.statVarInfo)) {
      statVarsToGetInfo.push(x.value.statVarDcid);
    }
    if (!_.isEmpty(y.value.statVarDcid) && _.isNull(y.value.statVarInfo)) {
      statVarsToGetInfo.push(y.value.statVarDcid);
    }
    if (_.isEmpty(statVarsToGetInfo)) {
      return;
    }
    getStatVarInfo(statVarsToGetInfo)
      .then((info) => {
        statVarsToGetInfo.forEach((sv) => {
          const svInfo = sv in info ? info[sv] : {};
          if (sv === x.value.statVarDcid) {
            x.setStatVarInfo(svInfo);
          } else {
            y.setStatVarInfo(svInfo);
          }
        });
      })
      .catch(() => {
        if (statVarsToGetInfo.indexOf(x.value.statVarDcid) > -1) {
          x.setStatVarInfo({});
        }
        if (statVarsToGetInfo.indexOf(y.value.statVarDcid) > -1) {
          y.setStatVarInfo({});
        }
      });
  }, [x.value, y.value]);

  let yTitle = y.value.statVarDcid;
  if (y.value.statVarInfo && y.value.statVarInfo.title) {
    yTitle = y.value.statVarInfo.title;
  }
  let xTitle = x.value.statVarDcid;
  if (x.value.statVarInfo && x.value.statVarInfo.title) {
    xTitle = x.value.statVarInfo.title;
  }

  const selectedSvs = {};
  if (!_.isEmpty(x.value.statVarDcid)) {
    selectedSvs[x.value.statVarDcid] = x.value.statVarInfo;
  }
  if (!_.isEmpty(y.value.statVarDcid)) {
    selectedSvs[y.value.statVarDcid] = y.value.statVarInfo;
  }
  if (!_.isEmpty(thirdStatVar.dcid)) {
    selectedSvs[thirdStatVar.dcid] = thirdStatVar.info;
  }

  return (
    <>
      <StatVarWidget
        openSvHierarchyModal={props.openSvHierarchyModal}
        openSvHierarchyModalCallback={props.openSvHierarchyModalCallback}
        collapsible={true}
        svHierarchyType={StatVarHierarchyType.SCATTER}
        samplePlaces={samplePlaces}
        deselectSVs={(svList: string[]) =>
          svList.forEach((sv) => {
            removeStatVar(x, y, sv);
          })
        }
        selectedSVs={selectedSvs}
        selectSV={(sv) => addStatVar(x, y, sv, setThirdStatVar, setModalOpen)}
      />
      {/* Modal for selecting 2 stat vars when a third is selected */}
      <Modal isOpen={modalOpen} backdrop="static" id="statvar-modal">
        <ModalHeader toggle={closeModal}>
          Only Two Statistical Variables Supported
        </ModalHeader>
        <ModalBody>
          <Container>
            <div>
              You selected:{" "}
              <b>{thirdStatVar.info.title || thirdStatVar.dcid}</b>
            </div>
            <div className="radio-selection-label">
              Please choose 1 more statistical variable to keep:
            </div>
            <div className="radio-selection-section">
              <FormGroup radio="true" row>
                <Label radio="true">
                  <Input
                    id="x-radio-button"
                    type="radio"
                    name="statvar"
                    defaultChecked={modalSelected.x}
                    onClick={() => setModalSelected({ x: true, y: false })}
                  />
                  {xTitle}
                </Label>
              </FormGroup>
              <FormGroup radio="true" row>
                <Label radio="true">
                  <Input
                    id="y-radio-button"
                    type="radio"
                    name="statvar"
                    defaultChecked={modalSelected.y}
                    onClick={() => setModalSelected({ x: false, y: true })}
                  />
                  {yTitle}
                </Label>
              </FormGroup>
            </div>
          </Container>
        </ModalBody>
        <ModalFooter>
          <Button
            color="primary"
            onClick={() =>
              confirmStatVars(
                x,
                y,
                thirdStatVar,
                setThirdStatVar,
                modalSelected,
                setModalSelected,
                setModalOpen
              )
            }
          >
            Confirm
          </Button>
        </ModalFooter>
      </Modal>
    </>
  );
}
Example #25
Source File: plot_options.tsx    From website with Apache License 2.0 4 votes vote down vote up
// TODO: Add a new API that given a statvar, a parent place, and a child type,
// returns the available dates for the statvar. Then, fill the datapicker with
// the dates.
function PlotOptions(): JSX.Element {
  const { place, x, y, display } = useContext(Context);
  const [lowerBound, setLowerBound] = useState(
    place.value.lowerBound.toString()
  );
  const [upperBound, setUpperBound] = useState(
    place.value.upperBound.toString()
  );
  const [xDenomInput, setXDenomInput] = useState(x.value.denom);
  const [yDenomInput, setYDenomInput] = useState(y.value.denom);
  const yAxisLabel =
    display.chartType === ScatterChartType.SCATTER
      ? "Y-axis"
      : y.value.statVarInfo.title || y.value.statVarDcid;
  const xAxisLabel =
    display.chartType === ScatterChartType.SCATTER
      ? "X-axis"
      : x.value.statVarInfo.title || x.value.statVarDcid;
  const axisLabelStyle = {};
  if (
    yAxisLabel.length > MIN_WIDTH_LABEL_LENGTH ||
    xAxisLabel.length > MIN_WIDTH_LABEL_LENGTH
  ) {
    axisLabelStyle["width"] =
      Math.min(
        MAX_WIDTH_LABEL_LENGTH,
        Math.max(xAxisLabel.length, yAxisLabel.length)
      ) /
        2 +
      "rem";
  }

  return (
    <Card id="plot-options">
      <Container fluid={true}>
        <div className="plot-options-row">
          <div className="plot-options-label" style={axisLabelStyle}>
            {yAxisLabel}:
          </div>
          <div className="plot-options-input-section">
            <div className="plot-options-input">
              <FormGroup check>
                <Label check>
                  <Input
                    id="per-capita-y"
                    type="checkbox"
                    checked={y.value.perCapita}
                    onChange={(e) => y.setPerCapita(e.target.checked)}
                  />
                  Per Capita
                </Label>
              </FormGroup>
            </div>
            <div className="plot-options-input">
              <FormGroup check>
                <Input
                  id="log-y"
                  type="checkbox"
                  checked={y.value.log}
                  onChange={(e) => checkLog(y, e)}
                />
                <Label check>Log scale</Label>
              </FormGroup>
            </div>
          </div>
        </div>
        <div className="plot-options-row">
          <div className="plot-options-label" style={axisLabelStyle}>
            {xAxisLabel}:
          </div>
          <div className="plot-options-input-section">
            <div className="plot-options-input">
              <FormGroup check>
                <Label check>
                  <Input
                    id="per-capita-x"
                    type="checkbox"
                    checked={x.value.perCapita}
                    onChange={(e) => x.setPerCapita(e.target.checked)}
                  />
                  Per Capita
                </Label>
              </FormGroup>
            </div>
            <div className="plot-options-input">
              <FormGroup check>
                <Input
                  id="log-x"
                  type="checkbox"
                  checked={x.value.log}
                  onChange={(e) => checkLog(x, e)}
                />
                <Label check>Log scale</Label>
              </FormGroup>
            </div>
          </div>
        </div>
        {display.chartType === ScatterChartType.SCATTER && (
          <>
            <div className="plot-options-row">
              <div className="plot-options-label">Display:</div>
              <div className="plot-options-input-section">
                <div className="plot-options-input">
                  <Button
                    id="swap-axes"
                    size="sm"
                    color="light"
                    onClick={() => swapAxes(x, y)}
                    className="plot-options-swap-button"
                  >
                    Swap X and Y axes
                  </Button>
                </div>
                <div className="plot-options-input">
                  <FormGroup check>
                    <Label check>
                      <Input
                        id="quadrants"
                        type="checkbox"
                        checked={display.showQuadrants}
                        onChange={(e) => checkQuadrants(display, e)}
                      />
                      Show quadrants
                    </Label>
                  </FormGroup>
                </div>
                <div className="plot-options-input">
                  <FormGroup check>
                    <Label check>
                      <Input
                        id="quadrants"
                        type="checkbox"
                        checked={display.showLabels}
                        onChange={(e) => checkLabels(display, e)}
                      />
                      Show labels
                    </Label>
                  </FormGroup>
                </div>
                <div className="plot-options-input">
                  <FormGroup check>
                    <Label check>
                      <Input
                        id="density"
                        type="checkbox"
                        checked={display.showDensity}
                        onChange={(e) => checkDensity(display, e)}
                      />
                      Show density
                    </Label>
                  </FormGroup>
                </div>
              </div>
            </div>
            <div className="plot-options-row">
              <div className="plot-options-label">Filter by population:</div>
              <div className="plot-options-input-section pop-filter">
                <div className="plot-options-input">
                  <FormGroup check>
                    <Input
                      className="pop-filter-input"
                      type="number"
                      onChange={(e) =>
                        selectLowerBound(place, e, setLowerBound)
                      }
                      value={lowerBound}
                      onBlur={() =>
                        setLowerBound(place.value.lowerBound.toString())
                      }
                    />
                  </FormGroup>
                </div>
                <span>to</span>
                <div className="plot-options-input">
                  <FormGroup check>
                    <Input
                      className="pop-filter-input"
                      type="number"
                      onChange={(e) =>
                        selectUpperBound(place, e, setUpperBound)
                      }
                      value={upperBound}
                      onBlur={() =>
                        setUpperBound(place.value.upperBound.toString())
                      }
                    />
                  </FormGroup>
                </div>
              </div>
            </div>
          </>
        )}
      </Container>
    </Card>
  );
}
Example #26
Source File: DataVisualization.tsx    From TutorBase with MIT License 4 votes vote down vote up
DataVisualization = () => {
  
  const [dropdownLabel2, setDropdownLabel2] = useState("All Time");
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const [dropdownOpen2, setDropdownOpen2] = useState(false);
  const [dropdownOpen3, setDropdownOpen3] = useState(false);
  const [dateRange, setDateRange] = useState(new Date(2020,0,0));
  const [course, setCourse] = useState("All Courses");
  const [courses, setCourses] = useState(new Array<string>());
  const [appointments, setAppointments] = useState(0);
  const [hours, setHours] = useState(0);
  const [earnings, setEarnings] = useState(0);
  const [chart, setChart] = useState(0);
  const [meetingsMap, setMeetingsMap] = useState(new Map<number,number>());
  const [earningsMap, setEarningsMap] = useState(new Map<number,number>());
  const toggle = () => setDropdownOpen(prevState => !prevState);
  const toggle2 = () => setDropdownOpen2(prevState => !prevState);
  const toggle3 = () => setDropdownOpen3(prevState => !prevState);
  let tutor = useSelector(selectClientData);
  let tutorID = tutor.clientId;
  useEffect(() => {
    GetTutoringHours(course, tutorID).then( apiResult => {
    setMeetingsMap(apiResult[0]);
    setEarningsMap(apiResult[1]);
    setAppointments(apiResult[3]);
    setHours(apiResult[2]);
    setEarnings(apiResult[4]);
    setCourses(apiResult[5]);
    });
  },[]);



  let coursesDropdowns:Array<ReactElement> = [];
  coursesDropdowns.push(<DropdownItem onClick={() => {
    setCourse("All Courses");
    GetTutoringHours("All Courses", tutorID).then( apiResult => {
      setMeetingsMap(apiResult[0]);
      setEarningsMap(apiResult[1]);
      setAppointments(apiResult[3]);
      setHours(apiResult[2]);
      setEarnings(apiResult[4]);
      setCourses(apiResult[5]);
      });
  }}>
    All Courses
  </DropdownItem>);
  for (let i = 0; i < courses.length; i++) {
    coursesDropdowns.push(<DropdownItem onClick={() => {
      setCourse(courses[i]);
      GetTutoringHours(courses[i], tutorID).then( apiResult => {
        setMeetingsMap(apiResult[0]);
        setEarningsMap(apiResult[1]);
        setAppointments(apiResult[3]);
        setHours(apiResult[2]);
        setEarnings(apiResult[4]);
        setCourses(apiResult[5]);
        });
    }}>
      {courses[i]}
    </DropdownItem>);         
  }
    return (
        <Container fluid className="background" style={{marginBottom:'10em'}}>
        <hr></hr>
        <Row xs="2" className="parent">

        </Row>
        <div style={{display:'flex', flexDirection:'row', flexWrap:'wrap'}}>
                <div style={{display:'flex', flexDirection:'column', flex:'1 1 0px', flexWrap:'wrap'}}>
                    <Card body>
                    <CardTitle tag="h5">Appointments</CardTitle>
                    <CardText>
                        <h1>
                        <CountUp 
                            end={appointments} 
                            useEasing={true}
                            duration={3.5}
                            />
                            </h1>
                        </CardText>
                    
                    </Card>
                </div>
                <div style={{display:'flex', flexDirection:'column', flex:'1 1 0px', flexWrap:'wrap'}}>
                    <Card body>
                    <CardTitle tag="h5">Hours Tutored</CardTitle>
                    <CardText>
                        <h1>
                        <CountUp 
                            end={hours} 
                            useEasing={true}
                            duration={4}
                            />
                            </h1>
                        </CardText>
                    
                    </Card>
                </div>
                <div style={{display:'flex', flexDirection:'column', flex:'1 1 0px', flexWrap:'wrap'}}>
                <Card body>
                    <CardTitle tag="h5">Earnings</CardTitle>
                    <CardText>
                        <h1>
                        <CountUp 
                            decimals={2}
                            prefix="$"
                            end={earnings} 
                            useEasing={true}
                            

                            duration={4}/>
                            </h1>
                        </CardText>
                    
                    </Card>
                </div>
            </div>
        
            <div style={{display:'flex', flexDirection:'row'}}>
            <Card body>
                <CardTitle tag="h5">
                <div style={{display:'flex', flexDirection:'row', flexWrap:'wrap'}}>
                  <div style={{display:'flex', flexDirection:'column', marginRight:'1em', marginTop:'0.25em'}}>
                    <Dropdown isOpen={dropdownOpen} toggle={toggle}>
                      <DropdownToggle caret>
                        {(chart === 0) ? "Calendar" : (chart === 1 ? "Total Hours" : "Total Earnings")}
                        
                        <FontAwesomeIcon icon={faArrowDown} style={{marginLeft:'1em'}}/>
                      </DropdownToggle>
                      <DropdownMenu>
                        <DropdownItem header>Tutor Data</DropdownItem>
                        <DropdownItem onClick={() => setChart(0)}>Calendar</DropdownItem>
                        <DropdownItem onClick={() => setChart(1)}>Total Hours</DropdownItem>
                        <DropdownItem divider />
                        <DropdownItem onClick={() => setChart(2)}>Total Earnings</DropdownItem>
                      </DropdownMenu>
                    </Dropdown>
                  </div>
                    { chart != 0 ?
                    <div style={{display:'flex', flexDirection:'column', marginRight:'1em', marginTop:'0.25em'}}>
                    <Dropdown isOpen={dropdownOpen2} toggle={toggle2} style={{alignSelf:'right'}}>
                      <DropdownToggle caret>
                        {dropdownLabel2}
                        <FontAwesomeIcon icon={faArrowDown} style={{marginLeft:'1em'}}/>
                      </DropdownToggle>
                      <DropdownMenu>
                        <DropdownItem header>Date Range</DropdownItem>
                        <DropdownItem onClick={() => {
                          let date = new Date(getNow());
                          date.setFullYear(2020);
                          date.setMonth(0);
                          date.setDate(0);
                          setDateRange(date);
                          setDropdownLabel2("All Time");
                        }}>
                          All Time
                        </DropdownItem>
                        
                        <DropdownItem onClick={() => {
                              let date = new Date(getNow());
                              date.setFullYear(date.getFullYear() - 1);
                              setDateRange(date);
                              setDropdownLabel2("1Y");

                            }}>1Y
                        </DropdownItem>

                        <DropdownItem onClick={() => { 
                              let date = new Date(getNow()); 
                              date.setMonth(date.getMonth() - 6);
                              setDateRange(date);
                              setDropdownLabel2("6M");
                            }}>6M
                        </DropdownItem>
                        <DropdownItem onClick={() => { 
                              let date = new Date(getNow()); 
                              date.setMonth(date.getMonth() - 1);
                              setDateRange(date);
                              setDropdownLabel2("1M");
                            }}>1M
                        </DropdownItem>
                      </DropdownMenu>
                    </Dropdown>
                    </div>
                    : <div></div>}
                    <div style={{display:'flex', flexDirection:'column', marginTop:'0.25em'}}>
                      <Dropdown isOpen={dropdownOpen3} toggle={toggle3} style={{alignSelf:'right'}}>
                      <DropdownToggle caret>
                        {course}
                        <FontAwesomeIcon icon={faArrowDown} style={{marginLeft:'1em'}}/>
                      </DropdownToggle>
                      <DropdownMenu>
                        <DropdownItem header>Filter by Course</DropdownItem>
                        {coursesDropdowns}
                      </DropdownMenu>
                    </Dropdown>
                    </div>
                    </div>
                    </CardTitle>
                    
                    <CardText>
                      {chart == 0 ?
                        <TutorHeatmap dateMap={meetingsMap} />
                        : (chart == 1 ? <LineGraph dateMap={meetingsMap}
                          fromTime={dateRange}
                          isHours={true}/>
                          :<LineGraph dateMap={earningsMap}
                          fromTime={dateRange}
                          isHours={false}/>
                          )}
                      
                      
                    </CardText>

                    
              </Card>
            </div>
            </Container>
    );
}
Example #27
Source File: chart.tsx    From website with Apache License 2.0 4 votes vote down vote up
export function Chart(props: ChartProps): JSX.Element {
  const statVar = props.statVar.value;
  const [errorMessage, setErrorMessage] = useState("");
  const mainSvInfo: StatVarInfo =
    statVar.dcid in statVar.info ? statVar.info[statVar.dcid] : {};
  const title = getTitle(
    Array.from(props.dates),
    mainSvInfo.title || statVar.dcid,
    statVar.perCapita
  );
  const placeDcid = props.placeInfo.enclosingPlace.dcid;
  const statVarDcid = statVar.dcid;
  const [mapPoints, setMapPoints] = useState(null);
  const [mapPointsFetched, setMapPointsFetched] = useState(false);
  const [zoomTransformation, setZoomTransformation] = useState(
    DEFAULT_ZOOM_TRANSFORMATION
  );
  const chartContainerRef = useRef<HTMLDivElement>();

  // load mapPoints in the background.
  useEffect(() => {
    props.mapPointsPromise
      .then((mapPoints) => {
        setMapPoints(mapPoints);
        setMapPointsFetched(true);
      })
      .catch(() => setMapPointsFetched(true));
  }, []);

  function replot() {
    draw(
      props,
      setErrorMessage,
      mapPoints,
      zoomTransformation,
      setZoomTransformation,
      props.display.value.color,
      props.display.value.domain
    );
  }

  // Replot when data changes.
  useEffect(() => {
    if (props.display.value.showMapPoints && !mapPointsFetched) {
      loadSpinner(SECTION_CONTAINER_ID);
      return;
    } else {
      removeSpinner(SECTION_CONTAINER_ID);
    }
    replot();
  }, [props, mapPointsFetched]);

  // Replot when chart width changes on sv widget toggle.
  useEffect(() => {
    const debouncedHandler = _.debounce(() => {
      if (!props.display.value.showMapPoints || mapPointsFetched) {
        replot();
      }
    }, DEBOUNCE_INTERVAL_MS);
    const resizeObserver = new ResizeObserver(debouncedHandler);
    if (chartContainerRef.current) {
      resizeObserver.observe(chartContainerRef.current);
    }
    return () => {
      resizeObserver.unobserve(chartContainerRef.current);
      debouncedHandler.cancel();
    };
  }, [props, chartContainerRef]);

  return (
    <div className="chart-section-container">
      <Card className="chart-section-card">
        <Container id={SECTION_CONTAINER_ID} fluid={true}>
          <div className="chart-section">
            <div className="map-title">
              <h3>
                {title}
                {props.dates.size > 1 && (
                  <span
                    onMouseOver={onDateRangeMouseOver}
                    onMouseOut={onDateRangeMouseOut}
                    id={DATE_RANGE_INFO_ID}
                  >
                    <i className="material-icons-outlined">info</i>
                  </span>
                )}
              </h3>
              <div id={DATE_RANGE_INFO_TEXT_ID}>
                The date range represents the dates of the data shown in this
                map.
              </div>
            </div>
            {errorMessage ? (
              <div className="error-message">{errorMessage}</div>
            ) : (
              <div className="map-section-container">
                <div id={CHART_CONTAINER_ID} ref={chartContainerRef}>
                  <div id={MAP_CONTAINER_ID}></div>
                  <div id={LEGEND_CONTAINER_ID}></div>
                </div>
                <div className="zoom-button-section">
                  <div id={ZOOM_IN_BUTTON_ID} className="zoom-button">
                    <i className="material-icons">add</i>
                  </div>
                  <div id={ZOOM_OUT_BUTTON_ID} className="zoom-button">
                    <i className="material-icons">remove</i>
                  </div>
                </div>
              </div>
            )}
            {props.display.value.showTimeSlider &&
              props.sampleDates &&
              props.sampleDates.length > 1 && (
                <TimeSlider
                  currentDate={_.max(Array.from(props.dates))}
                  dates={props.sampleDates}
                  metahash={props.metahash}
                  onPlay={props.onPlay}
                  startEnabled={props.dates.size === 1}
                  updateDate={props.updateDate}
                />
              )}
            <div className="map-links">
              {mainSvInfo.ranked && (
                <a className="explore-timeline-link" href={props.rankingLink}>
                  <span className="explore-timeline-text">
                    Explore rankings
                  </span>
                  <i className="material-icons">keyboard_arrow_right</i>
                </a>
              )}
              {!mainSvInfo.ranked &&
                (props.placeInfo.selectedPlace.dcid in props.mapDataValues ||
                  props.placeInfo.selectedPlace.dcid in
                    props.breadcrumbDataValues) && (
                  <a
                    className="explore-timeline-link"
                    href={`/tools/timeline#place=${placeDcid}&statsVar=${statVarDcid}`}
                  >
                    <span className="explore-timeline-text">
                      Explore timeline
                    </span>
                    <i className="material-icons">keyboard_arrow_right</i>
                  </a>
                )}
            </div>
          </div>
        </Container>
      </Card>
      <ToolChartFooter
        chartId="map"
        sources={props.sources}
        mMethods={null}
        sourceSelectorSvInfoList={[props.sourceSelectorSvInfo]}
        onSvMetahashUpdated={(svMetahashMap) =>
          props.statVar.setMetahash(svMetahashMap[props.statVar.value.dcid])
        }
        hideIsRatio={false}
        isPerCapita={props.statVar.value.perCapita}
        onIsPerCapitaUpdated={(isPerCapita: boolean) =>
          props.statVar.setPerCapita(isPerCapita)
        }
      >
        {props.placeInfo.mapPointPlaceType && (
          <div className="chart-option">
            <FormGroup check>
              <Label check>
                <Input
                  id="show-installations"
                  type="checkbox"
                  checked={props.display.value.showMapPoints}
                  onChange={(e) =>
                    props.display.setShowMapPoints(e.target.checked)
                  }
                />
                Show Installations
              </Label>
            </FormGroup>
          </div>
        )}
      </ToolChartFooter>
      <div id="map-chart-screen" className="screen">
        <div id="spinner"></div>
      </div>
    </div>
  );
}
Example #28
Source File: index.tsx    From mops-vida-pm-watchdog with MIT License 4 votes vote down vote up
SensorConsole: React.FC = () => {
  const dispatch = useDispatch();
  const connected = useSelector((state) => state.report.connected);
  const shuttingdown = useSelector((state) => state.report.shuttingdown);
  const latest = useSelector((state) => state.report.latest);
  const onConnect = async () => {
    if (connected) {
      await dispatch(disconnect());
    } else {
      await dispatch(requestDevice());
      await dispatch(connect());
    }
  };
  const onShutdown = () => dispatch(shutdown());
  const onReadHistory = () => dispatch(readHistory());
  return (
    <Container className={locals.container}>
      <Row>
        <ButtonGroup>
          <Button color={connected ? 'success' : 'primary'} onClick={onConnect}>
            {connected ? 'Disconnect' : 'Connect'}
          </Button>
          <Button disabled={!connected} color={connected ? 'danger' : undefined} onClick={onShutdown}>
            {shuttingdown ? 'Shutting down' : 'Shutdown'}
          </Button>
          <Button disabled={!connected} color={connected ? 'info' : undefined} onClick={onReadHistory}>
            Read history (one-time)
          </Button>
        </ButtonGroup>
      </Row>
      <Row>
        <h1>Real-time</h1>
        <Table className={locals.table} responsive borderless>
          <thead>
            <tr>
              <th className={locals.field}>#</th>
              <th>Value</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>
                PM <sub>2.5</sub>
              </td>
              <td className='text-monospace'>
                <FormattedPM25 value={latest.pm25} />
              </td>
            </tr>
            <tr>
              <td>Battery</td>
              <td>
                <Progress value={latest.batteryCapacity ?? 0}>
                  {latest.batteryCapacity ? `${latest.batteryCapacity}%` : 'N/A'} {latest.batteryCharging ? '(Charging)' : '(Discharge)'}
                </Progress>
              </td>
            </tr>
            <tr>
              <td>Record date</td>
              <td className='text-monospace'>
                <RecordDate value={latest.recordDate} />
              </td>
            </tr>
            <tr>
              <td>Runtime</td>
              <td className='text-monospace'>{latest.runTime ? prettyDuration(latest.runTime * 1000) : 'N/A'}</td>
            </tr>
            <tr>
              <td>Boot time</td>
              <td className='text-monospace'>{latest.bootTime ? prettyDuration(latest.bootTime * 1000) : 'N/A'}</td>
            </tr>
            <tr>
              <td>Measurement Interval</td>
              <td className='text-monospace'>
                <MeasurementInterval />
              </td>
            </tr>
            <tr>
              <td>Firmare Version</td>
              <td className='text-monospace'>{latest.version ?? 'N/A'}</td>
            </tr>
          </tbody>
        </Table>
      </Row>
      <History />
    </Container>
  );
}
Example #29
Source File: stat_var_chooser.tsx    From website with Apache License 2.0 4 votes vote down vote up
export function StatVarChooser(props: StatVarChooserProps): JSX.Element {
  const [samplePlaces, setSamplePlaces] = useState([]);
  // extraStatVar holds a stat var that is selected after the max number of
  // selected stat vars has been reached. This stat var will either be removed
  // or used to replace another selected stat var.
  const [extraStatVar, setExtraStatVar] = useState(EMPTY_SV_AND_INFO);
  const [modalSelection, setModalSelection] = useState("");
  const [modalOpen, setModalOpen] = useState(false);
  const modalSvOrder = useRef(Object.keys(props.statVars));

  useEffect(() => {
    modalSvOrder.current = Object.keys(props.statVars);
  }, [props.statVars]);

  useEffect(() => {
    if (!props.placeDcid || !props.enclosedPlaceType) {
      setSamplePlaces([]);
      return;
    }
    getEnclosedPlacesPromise(props.placeDcid, props.enclosedPlaceType)
      .then((enclosedPlaces) => {
        const samplePlaces = getSamplePlaces(
          props.placeDcid,
          props.enclosedPlaceType,
          enclosedPlaces
        );
        setSamplePlaces(samplePlaces);
      })
      .catch(() => {
        setSamplePlaces([]);
      });
  }, [props.placeDcid, props.enclosedPlaceType]);

  const selectedSVs = { ...props.statVars };
  // although we don't propagate the extra stat var selection to the rest of the
  // tool, we do need to pass it to the widget because the StatVarHierarchy has
  // it showing as selected.
  if (!_.isEmpty(extraStatVar.dcid)) {
    selectedSVs[extraStatVar.dcid] = extraStatVar.info;
  }

  return (
    <>
      <StatVarWidget
        openSvHierarchyModal={props.openSvHierarchyModal}
        openSvHierarchyModalCallback={props.openSvHierarchyModalCallback}
        collapsible={false}
        svHierarchyType={StatVarHierarchyType.DOWNLOAD}
        samplePlaces={samplePlaces}
        deselectSVs={(svList: string[]) =>
          svList.forEach((sv) => {
            props.onStatVarRemoved(sv);
          })
        }
        selectedSVs={selectedSVs}
        selectSV={(sv) => selectSV(sv)}
      />
      {/* Modal for selecting stat var to replace when too many are selected */}
      <Modal isOpen={modalOpen} backdrop="static" id="statvar-modal">
        <ModalHeader toggle={closeModal}>
          Only 5 Statistical Variables Supported
        </ModalHeader>
        <ModalBody>
          <Container>
            <div>
              You selected:{" "}
              <b>{extraStatVar.info.title || extraStatVar.dcid}</b>
            </div>
            <div className="radio-selection-label">
              Please choose a statistical variable to replace:
            </div>
            <div className="radio-selection-section">
              {modalSvOrder.current.map((sv, idx) => {
                return (
                  <FormGroup key={sv} radio="true" row>
                    <Label radio="true">
                      <Input
                        type="radio"
                        name="statvar"
                        defaultChecked={
                          (_.isEmpty(modalSelection) && idx === 0) ||
                          modalSelection === sv
                        }
                        onClick={() => setModalSelection(sv)}
                      />
                      {sv in props.statVars
                        ? props.statVars[sv].title || sv
                        : sv}
                    </Label>
                  </FormGroup>
                );
              })}
            </div>
          </Container>
        </ModalBody>
        <ModalFooter>
          <Button color="primary" onClick={() => confirmStatVars()}>
            Confirm
          </Button>
        </ModalFooter>
      </Modal>
    </>
  );

  /**
   * Close the modal
   */
  function closeModal(): void {
    setExtraStatVar(EMPTY_SV_AND_INFO);
    setModalSelection("");
    setModalOpen(false);
  }

  /**
   * Confirms the variable to replace in the modal.
   */
  function confirmStatVars(): void {
    const svToRemove = _.isEmpty(modalSelection)
      ? modalSvOrder.current[0]
      : modalSelection;
    props.onStatVarRemoved(svToRemove);
    props.onStatVarSelected(extraStatVar.dcid, extraStatVar.info);
    closeModal();
  }

  /**
   * Select a variable.
   */
  function selectSV(sv: string): void {
    getStatVarInfo([sv])
      .then((svInfo) => {
        const selectedSVInfo = svInfo[sv] || {};
        if (Object.keys(props.statVars).length >= MAX_SV) {
          setExtraStatVar({ dcid: sv, info: selectedSVInfo });
          setModalOpen(true);
        } else {
          props.onStatVarSelected(sv, selectedSVInfo);
        }
      })
      .catch(() => {
        if (Object.keys(props.statVars).length >= MAX_SV) {
          setExtraStatVar({ dcid: sv, info: {} });
          setModalOpen(true);
        } else {
          props.onStatVarSelected(sv, {});
        }
      });
  }
}