react-responsive#useMediaQuery JavaScript Examples

The following examples show how to use react-responsive#useMediaQuery. 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: FeedContainer.js    From quake-fe with MIT License 6 votes vote down vote up
FeedContainer = () => {
  const isBigScreen = useMediaQuery({
    query: "(min-width: 800px)",
  });

  return (
    <div
      id="feed-container"
      className={`${
        isBigScreen ? "persistant-container" : "main-container"
      } scroll`}
    >
      <Feed />
    </div>
  );
}
Example #2
Source File: header.jsx    From nightfall_3 with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
export default function Header() {
  const isSmallScreen = useMediaQuery({ query: '(max-width: 1000px)' });

  if (!isSmallScreen) {
    return (
      <div className="navHead">
        <Logo />
        <NavItems />

        {/* <SearchBox /> */}
      </div>
    );
  }
  return (
    <div className="navHead">
      <CgMenu />
      <Logo />
      <NavItems />

      {/* <SearchBox /> */}
    </div>
  );
}
Example #3
Source File: menuItem.jsx    From nightfall_3 with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
export default function MenuItem() {
  const isSmallScreen = useMediaQuery({ query: '(max-width: 900px)' });

  return (
    <div className="menuBox">
      <CgMenuGridO />
      {!isSmallScreen && <span>Apps</span>}
    </div>
  );
}
Example #4
Source File: navItems.jsx    From nightfall_3 with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
export default function NavItems() {
  const isSmallScreen = useMediaQuery({ query: '(max-width: 900px)' });
  const [state] = useContext(UserContext);
  return (
    <div className="navItems">
      {/* <MenuItem /> */}
      {!isSmallScreen && (
        <div className="accountBox">
          <img src={polygonNightfall} />
          {state.compressedPkd && (
            <div className="accountAddress">
              {`${state.compressedPkd.slice(0, 6)}...${state.compressedPkd.slice(-6)}`}
            </div>
          )}
          <span>
            <IoIosArrowDown />
          </span>
        </div>
      )}
      {!isSmallScreen && <AccountDetails />}
    </div>
  );
}
Example #5
Source File: index.js    From pollaris with MIT License 6 votes vote down vote up
export default function useBreakpoint(bpMap = {}) {
  const breakpoints = Object.entries(bpMap).sort((a, b) => parseInt(a[1], 10) - parseInt(b[1], 10));
  const current = breakpoints.reduce((bp, [name, value]) => (useMediaQuery({ minWidth: value }) ? name : bp), 'default');
  const currentIndex = breakpoints.findIndex(([name]) => name === current);
  const getBpIndex = (bpName) => breakpoints.findIndex(([name]) => name === bpName);

  const isAbove = (bpName, inclusive = true) => (
    inclusive ? getBpIndex(bpName) <= currentIndex : getBpIndex(bpName) < currentIndex
  );
  const isBelow = (bpName, inclusive = false) => (
    inclusive ? getBpIndex(bpName) >= currentIndex : getBpIndex(bpName) > currentIndex
  );
  return {
    current,
    isAbove,
    isBelow,
  };
}
Example #6
Source File: ResultsContainer.js    From quake-fe with MIT License 6 votes vote down vote up
ResultsContainer = () => {
  const [viewType, setViewType] = useState("combo");

  const isBigScreen = useMediaQuery({
    query: "(min-width: 800px)",
  });

  useEffect(() => {
    const container = document.getElementById("results-container");
    const map = document.getElementById("map-container");

    if (isBigScreen) {
      container.style.height = "100%";
      container.style.transform = "translateY(0)";
      map.style.height = "100%";
    } else {
      for (let i = 0; i < view.length; i++) {
        if (viewType === view[i].view) {
          container.style.height = view[i].cheight;
          container.style.transform = view[i].ctransform;
          map.style.height = view[i].mheight;
        }
      }
    }
  }, [viewType, isBigScreen]);

  return (
    <div id="results-container" className="results-container no-scroll">
      <MediaQuery maxWidth={799}>
        <ViewType viewType={viewType} setViewType={setViewType} />
      </MediaQuery>
      <Sort />
      <div className="earthquake-list-container scroll">
        <List />
      </div>
    </div>
  );
}
Example #7
Source File: utils.js    From frontend-app-course-authoring with GNU Affero General Public License v3.0 6 votes vote down vote up
export function useIsMobile() {
  return useMediaQuery({ query: '(max-width: 767.98px)' });
}
Example #8
Source File: utils.js    From frontend-app-course-authoring with GNU Affero General Public License v3.0 6 votes vote down vote up
export function useIsDesktop() {
  return useMediaQuery({ query: '(min-width: 992px)' });
}
Example #9
Source File: useBreakpoint.js    From os-league-tools with MIT License 6 votes vote down vote up
export default function useBreakpoint(query, mode = MODE.GREATER_OR_EQ) {
    switch (mode) {
        case MODE.LESS:
            return useMediaQuery({ maxWidth: query.minWidth });
        case MODE.GREATER:
            return useMediaQuery({ minWidth: query.maxWidth });
        case MODE.LESS_OR_EQ:
            return useMediaQuery({ maxWidth: query.maxWidth });
        case MODE.GREATER_OR_EQ:
            return useMediaQuery({ minWidth: query.minWidth });
        case MODE.STRICT:
        default:
            return useMediaQuery(query);
    }
}
Example #10
Source File: index.js    From prisma.pan.dev with MIT License 6 votes vote down vote up
function Tool({ imageUrl, title, description, toPage, toSite }) {
  const imgUrl = useBaseUrl(imageUrl);
  const toUrl = toPage ? useBaseUrl(toPage) : toSite;
  const isBreakpoint = useMediaQuery({ query: "(max-width: 1200px)" });
  return (
    <div className={isBreakpoint ? "col col--4" : "col col--2"}>
      <Button
        className={clsx(styles.toolsButton)}
        variant="tool"
        href={toUrl}
        target="_self"
        uppercase={false}
        newTab={false}
      >
        <div className={clsx("card", styles.tools)}>
          <div className="card__header">
            <div className={styles.imageContainer}>
              {imgUrl && <img className={styles.toolsImage} src={imgUrl} />}
              <img className={styles.toolsBorder} src="img/prisma_circle.png" />
            </div>
          </div>
          <div className="card__body">
            <div className={styles.toolsTitle}>{title}</div>
            <div className={styles.toolsSummary}>{description}</div>
          </div>
        </div>
      </Button>
    </div>
  );
}
Example #11
Source File: index.js    From thecrucibletracker with MIT License 5 votes vote down vote up
Component = () => (
  <div>
    <Screen isMobile={useMediaQuery({ maxWidth: 767, })} />
  </div>
)
Example #12
Source File: Heading.js    From tclone with MIT License 5 votes vote down vote up
function Heading(props) {
    let { title, btnLogout, backButton, btnProfile } = props

    let dispatch = useDispatch()
    let history = useHistory()
    const isMobile = useMediaQuery({ query: '(max-width: 576px)' })
    let { user: authUser, isAuthenticated } = useSelector(state => state.auth)
    let [btnTxt, setBtnTxt] = React.useState("Don't click")
    if (backButton)
        backButton = (<button
            onClick={() => { isAuthenticated ? history.goBack() : history.push('/') }}
            className="ml-2 btn btn-naked-primary rounded-circle text-primary">
            <FontAwesomeIcon icon={faArrowLeft} size="lg" />
        </button>)
    if (btnLogout)
        btnLogout = (<button onClick={() => { dispatch(logout()) }}
            onMouseEnter={() => { setBtnTxt("Bola naa yaar") }}
            onMouseLeave={() => { setBtnTxt("Never click it") }}
            className="btn btn-outline-primary rounded-pill px-2 py-1 mr-2 font-weight-bold"
        >{btnTxt}
        </button>)
    if (btnProfile && isAuthenticated)
        btnProfile = (
            <Link
                className="d-flex align-items-end"
                to={`/user/${authUser.screen_name}`}
            >
                <Figure
                    className="bg-border-color rounded-circle overflow-hidden my-auto ml-2"
                    style={{ height: "35px", width: "35px" }}
                >
                    <Figure.Image
                        src={(authUser.default_profile_image) ? '/img/default-profile-vector.svg' : authUser.profile_image_url_https}
                        className="w-100 h-100"
                    />
                </Figure>
            </Link>
        )
    return (
        <div className="d-flex justify-content-between border-bottom sticky-top bg-white align-items-center">
            <Row className="d-flex align-items-center">
                {backButton}
                {isMobile && btnProfile}
                <h5 className="my-3 mx-2 font-weight-bold">{title}</h5>
            </Row>
            {btnLogout}
        </div>
    )
}
Example #13
Source File: device.js    From juken with MIT License 5 votes vote down vote up
media = () => ({
  desktop: useMediaQuery({ minWidth: 1100 }),
  tablet: useMediaQuery({ maxWidth: 1100 }),
  mobile: useMediaQuery({ maxWidth: 600 }),
})
Example #14
Source File: KanjiBox.js    From zero-neko with MIT License 5 votes vote down vote up
KanjiBox = (props) =>{
    const isDesktopOrLaptop = useMediaQuery({ query: '(min-device-width: 1024px)' })
    const [kanji, setKanji] = useState();
    useEffect(() => {
        const fetchData = async () => {
            axios('https://kanjiapi.dev/v1/kanji/'+props.data)
            .then(response => {
                setKanji(response.data);
            })
        }
        fetchData()
    },[props.data]);
    let n = 8;
    if (isDesktopOrLaptop) {
        n = 9
    }
    const loading = (
        <li className="box-border transition-all delay-75 col-span-1 rounded-md bg-gray-50 dark:bg-gray-800 p-2 py-8 shadow-md dark:shadow-mdWhite dark:hover:shadow-none hover:shadow-none">
            <svg className="animate-spin mx-auto p" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M12 4.75V6.25" stroke="currentColor" ></path>
                <path d="M17.1266 6.87347L16.0659 7.93413" stroke="currentColor" ></path>
                <path d="M19.25 12L17.75 12" stroke="currentColor" ></path>
                <path d="M17.1266 17.1265L16.0659 16.0659" stroke="currentColor" ></path>
                <path d="M12 17.75V19.25" stroke="currentColor" ></path>
                <path d="M7.9342 16.0659L6.87354 17.1265" stroke="currentColor" ></path>
                <path d="M6.25 12L4.75 12" stroke="currentColor"></path>
                <path d="M7.9342 7.93413L6.87354 6.87347" stroke="currentColor" ></path>
            </svg>
        </li>
    );
    if (kanji === undefined) {
        return loading;
    } else if (!kanji.meanings[0]) {
        return null;
    }
    return(
        <li className="box-border col-span-1 rounded-md bg-gray-50 dark:bg-gray-800 shadow-md dark:shadow-md dark:hover:bg-opacity-80 hover:shadow-none hover:cursor-pointer">
            <a href={"/kanji/"+(kanji ? kanji.kanji : "")} className="w-full h-full block p-2 lg:py-4" >
                <p className="text-xl lg:text-3xl font-black mb-2">{kanji ? kanji.kanji : ""}</p>
                <p className="font-semibold text-xs lg:text-base text-primary capitalize whitespace-nowrap">{kanji ? (kanji.meanings[0].length >= n ? kanji.meanings[0].substr(0, n-3).trim() + '..' : kanji.meanings[0]) : "X"}</p>
            </a>
        </li>
    )
}
Example #15
Source File: DragBox.js    From zero-neko with MIT License 5 votes vote down vote up
DropBox = (props) =>{
    const [kana, setKana] = useState();
    const [show, setShow] = useState(true);
    const isTabletOrMobile = useMediaQuery({ query: '(max-width: 1224px)' })
    useEffect(() => {
        if (props.category === "Hiragana") {
            setKana(props.kana.hiragana) 
        } else if (props.category === "Katakana") {
            setKana(props.kana.katakana)
        } else if (props.category === "Romaji") {
            setKana(props.kana.romaji)
        }
    }, [kana, props])
    const onDragStart = (e) => {
        props.onSetDragItem(props.kana)
        if (!isTabletOrMobile) {
            setTimeout(() => {
                setShow(false)
                e.dataTransfer.setData(props.kana, e.target.id);
            }, 10);
        }
    }
    const onDragEnd = (e) => {
        setShow(true)
    }
    return(
        <li 
            draggable
            autoscroll="true"
            onClick={() => props.onSetDragItem(props.kana)}
            onDragStart={(e) => onDragStart(e)}
            onDragEnd={(e) => onDragEnd(e)} 
            className="box-border flex text-center text-2xl lg:text-4xl font-bold w-12 lg:w-16 h-12 lg:h-16 hover:text-red-300 cursor-pointer">
            <span id={props.kana}
                className={(props.dragItem === props.kana ? "text-primary" : "")+" border-b-2 border-current m-auto "} >
                {!props.correct ? (show ? kana : "") :""}
            </span>
        </li>

    )
}
Example #16
Source File: index.js    From bank-client with MIT License 5 votes vote down vote up
export default function DashboardPage() {
  const { layout, isOpenedModal, user } = useSelector(stateSelector);
  const dispatch = useDispatch();
  const { ref } = useResizeObserver({ onResize });
  const isMobile = useMediaQuery({ maxWidth: 479 });

  useInjectReducer({ key, reducer });
  useInjectSaga({ key, saga });

  return (
    <>
      <FormattedMessage {...messages.dashboard}>
        {(title) => <Helmet title={`${getAlertCount(user)} ${title}`} />}
      </FormattedMessage>

      <Greeting />

      <StyledGridWrapper ref={ref}>
        <ResponsiveReactGridLayout
          breakpoints={{ lg: 1100, md: 900, sm: 580, xs: 480, xxs: 0 }}
          cols={{ lg: 3, md: 3, sm: 2, xs: 1, xxs: 1 }}
          rowHeight={8}
          margin={[20, 10]}
          isResizable={false}
          isDraggable={!isOpenedModal && !isMobile}
          layouts={layout}
          onLayoutChange={(_, layouts) => dispatch(changeLayoutAction(layouts))}
        >
          <StyledGridItem
            key="1"
            data-grid={{ x: 0, y: 0, w: 1, h: 6, static: true }}
          >
            <AvailableFunds />
          </StyledGridItem>

          <StyledGridItem
            key="2"
            data-grid={{ x: 1, y: 0, w: 1, h: 6, static: true }}
          >
            <Savings />
          </StyledGridItem>

          <StyledGridItem
            key="3"
            data-grid={{ x: 2, y: 0, w: 1, h: 6, static: true }}
          >
            <BankInformation />
          </StyledGridItem>

          <StyledGridItem key="4" data-grid={{ x: 0, y: 2, w: 2, h: 16 }}>
            <Bills />
          </StyledGridItem>

          <StyledGridItem key="5" data-grid={{ x: 2, y: 2, w: 1, h: 16 }}>
            <RecentTransactions />
          </StyledGridItem>

          <StyledGridItem key="6" data-grid={{ x: 0, y: 3, w: 1, h: 16 }}>
            <BankCards />
          </StyledGridItem>

          <StyledGridItem key="7" data-grid={{ x: 1, y: 3, w: 1, h: 16 }}>
            <Credits />
          </StyledGridItem>

          <StyledGridItem key="8" data-grid={{ x: 2, y: 2, w: 1, h: 16 }}>
            <Deposits />
          </StyledGridItem>
        </ResponsiveReactGridLayout>
      </StyledGridWrapper>
    </>
  );
}
Example #17
Source File: index.js    From Codelabz with Apache License 2.0 5 votes vote down vote up
Organizations = () => {
  window.scrollTo(0, 0);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const classes = useStyles();
  const isDesktop = useMediaQuery({
    query: "(min-device-width: 767px)",
  });

  return (
    <Grid
      className="row-footer-below"
      style={{ display: "flex", flexDirection: "row" }}
    >
      {isDesktop && (
        <div className="mini-sidebar-column">
          <OrgSidebar onOrgChange={() => {}} />
        </div>
      )}
      {!isDesktop && (
        <Drawer
          anchor="bottom"
          open={drawerVisible}
          height={"60%"}
          onClose={() => setDrawerVisible(false)}
        >
          <Grid>
            <Grid xs={24} className="col-pad-24-s pt-0">
              <OrgSidebar
                onOrgChange={() => {
                  setDrawerVisible(false);
                }}
              />
            </Grid>
          </Grid>
        </Drawer>
      )}

      <Grid>
        {!isDesktop && (
          <Grid>
            <Grid xs={24} className="col-pad-24-s pb-0">
              <Button
                onClick={() => setDrawerVisible(true)}
                block
                type="primary"
                variant="outlined"
              >
                Switch organization
              </Button>
            </Grid>
          </Grid>
        )}
        <Grid className={classes.cardBody}>
          <Grid xs={24} sm={24} md={14} className="col-pad-24-s pr-12">
            <OrgInfoCard />
          </Grid>
          <Grid xs={24} sm={24} md={10} className="col-pad-24-s pl-12">
            <OrgUsersCard />
          </Grid>
        </Grid>
      </Grid>
    </Grid>
  );
}
Example #18
Source File: NavBar.jsx    From emprezzo with MIT License 5 votes vote down vote up
NavBar = () => {
  const { itemCount } = useContext(CartContext);
  const isMobile = useMediaQuery({ query: '(max-width: 600px)' })

  return (
    <>
      <Headroom calcHeightOnResize disableInlineStyles>
        <StyledLink to="/">
          <img src={logo} className="logo" title="emprezzo - Discover the best independent shopping sites & direct to consumer brands" alt="emprezzo - Discover the best independent shopping sites & direct to consumer brands" />
        </StyledLink>
        <NavWrapper>
          <Nav>
            <div className="dropdown">
              <Link to="">
                {!isMobile &&
                  <span>Discover</span>
                }
                {isMobile &&
                  <Menu width="24px" style={{ marginRight: "0.75rem" }} />
                }
              </Link>
              <div className="dropdown-content">
                <Link key="1" to="/randomshop/">Random shop</Link>
                <Link key="2" to="/gift-cards/">Gift cards</Link>


                <Link key="3" target="_blank" to="https://chrome.google.com/webstore/detail/emprezzo/ojfaaaocbgiojhlapncepdiccfgcjmee">Chrome extension</Link>
              </div>
            </div>
            <SearchWrapper>
              <Search collapse indices={searchIndices} variation={"light"} />
            </SearchWrapper>
            <div>
              <Link to="/cart" style={{ display: "flex", margin: "0.5rem", fontSize: "0.85rem" }}>
                <ShoppingCart width="24px" />{itemCount}
              </Link>
            </div>
          </Nav>
        </NavWrapper>
      </Headroom >
      <Cart />
    </>
  );

}
Example #19
Source File: index.js    From prisma.pan.dev with MIT License 5 votes vote down vote up
function Feature({ imageUrl, title, description, toPage }) {
  const imgUrl = useBaseUrl(imageUrl);
  const toUrl = toPage ? useBaseUrl(toPage) : null;
  const isBreakpoint = useMediaQuery({ query: "(max-width: 1200px)" });
  /*
  if (toUrl) {
    return (
      <div className={isBreakpoint ? 'col col--6 margin-bottom--md' : 'col col--4 margin-bottom--md'}>
        <Button
          className={clsx(styles.featuredButton)}
          variant="plain"
          href={toUrl}
          target="_self"
          uppercase={false}
          newTab={false}
        >
          <div className={clsx('card shadow--lw', styles.featured)}>
            <div className="card__body">
              {imgUrl && <img className={styles.featuredImage} src={imgUrl} />}
              <div className={styles.featuredTitle}>{title}</div>
              <div className={styles.featuredSummary}>{description}</div>
            </div>
          </div>
        </Button>
      </div>
    );
  } 
  */
  return (
    <div
      className={
        isBreakpoint
          ? "col col--6 margin-bottom--md"
          : "col col--4 margin-bottom--md"
      }
    >
      <div className={styles.featuredLinks}>
        <div className={clsx("card shadow--lw", styles.featured)}>
          <div className="card__body">
            {imgUrl && <img className={styles.featuredImage} src={imgUrl} />}
            <div className={styles.featuredTitle}>{title}</div>
            <div className={styles.featuredSummary}>{description}</div>
          </div>
        </div>
      </div>
    </div>
  );
}
Example #20
Source File: index.js    From the-eye-knows-the-garbage with MIT License 5 votes vote down vote up
useMedia = function useMedia() {
  var isMd = useMediaQuery(MediaQueryEnum.md);
  var isLg = useMediaQuery(MediaQueryEnum.lg);
  var isXxl = useMediaQuery(MediaQueryEnum.xxl);
  var isXl = useMediaQuery(MediaQueryEnum.xl);
  var isSm = useMediaQuery(MediaQueryEnum.sm);
  var isXs = useMediaQuery(MediaQueryEnum.xs);

  var _useState = useState(getScreenClassName()),
      _useState2 = _slicedToArray(_useState, 2),
      colSpan = _useState2[0],
      setColSpan = _useState2[1];

  useEffect(function () {
    if (isXxl) {
      setColSpan('xxl');
      return;
    }

    if (isXl) {
      setColSpan('xl');
      return;
    }

    if (isLg) {
      setColSpan('lg');
      return;
    }

    if (isMd) {
      setColSpan('md');
      return;
    }

    if (isSm) {
      setColSpan('sm');
      return;
    }

    if (isXs) {
      setColSpan('xs');
      return;
    }

    setColSpan('md');
  }, [isMd, isLg, isXxl, isXl, isSm, isXs]);
  return colSpan;
}
Example #21
Source File: index.jsx    From nightfall_3 with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
Bridge = () => {
  const [state] = useContext(UserContext);
  const isTabletOrMobile = useMediaQuery({ query: '(min-width: 1000px)' });

  return (
    // containerFluid
    <div>
      {process.env.REACT_APP_MODE === 'local' ? <Header /> : <></>}
      <div className="bridgeComponent">
        {isTabletOrMobile && (
          <div className="bridgeComponent__left">
            <SideBar />
          </div>
        )}
        <div className="bridgeComponent__right">
          <div className="blue_back">
            {/* <WarningBanner className="warning-banner" /> */}

            <div className="page_partition">
              <div>
                <BridgeComponent value={state} />
              </div>
              <div className="info_wrapper">
                <div className="info_painel_title">Nightfall Bridge</div>
                <div className="info_painel_description">
                  The safe, fast and most secure way to bring cross-chain assets to Polygon
                  Nightfall.
                </div>
                {isTabletOrMobile && (
                  <>
                    <div className="img1">
                      <img src={ethIcon} alt="" />
                    </div>
                    <div className="img2">
                      <img src={pgIcon} alt="" />
                    </div>
                  </>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
Example #22
Source File: index.jsx    From nightfall_3 with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
export default function SideBar() {
  const isSmallScreen = useMediaQuery({ query: '(min-width: 768px)' });
  const [state] = useContext(UserContext);
  if (isSmallScreen) {
    return (
      <div className="sideBar">
        <div className="sideItems">
          <SideItem text="Nightfall Assets" link="/" Icon={[WalletImg, WalletImgGrey]} />
          <SideItem
            text="L2 Bridge"
            link="/bridge"
            Icon={[BridgeImg, BridgeImgGrey]}
            SideState=""
          />
          <SideItem
            text="Transactions"
            link="/transactionPage"
            Icon={[TransactionImg, TransactionImgGrey]}
          />
        </div>
        <div>
          <div className="links">
            {/* <GiElectric size={24} /> */}
            {state.circuitSync && state.chainSync ? (
              <>
                <img src={synced} style={{ height: '32px', width: '32px' }} />
                <div className="linkText">Nightfall Synced</div>
              </>
            ) : (
              <>
                <Lottie style={{ height: '32px', width: '32px' }} animationData={syncing} loop />
                <div className="linkText">Syncing Nightfall...</div>
              </>
            )}
          </div>
          {/* <div className="links">
            <MdOutlineSupport size={24} />
            <div className="linkText">Support</div>
          </div> */}
        </div>
      </div>
    );
  }
  return <div />;
}
Example #23
Source File: index.js    From Codelabz with Apache License 2.0 4 votes vote down vote up
Home = () => {
  const authed = useAuthStatus();
  const isDesktop = useMediaQuery({
    query: "(min-device-width: 767px)",
  });

  useEffect(() => {
    if (messaging) {
      if (
        Notification.permission !== "granted" &&
        Notification.permission !== "denied"
      ) {
        Notification.requestPermission().then((permission) => {
          if (permission === "granted") {
            messaging
              .getToken()
              .then((refreshedToken) => {
                console.log(refreshedToken);
              })
              .catch((e) => console.log(e));
          }
        });
      }
    }
  }, []);

  useEffect(() => {
    if (messaging) {
      const unsubscribe = messaging.onMessage(
        (payload) => {
          console.log(payload);
        },
        (error) => console.log(error)
      );

      return () => {
        unsubscribe && unsubscribe();
      };
    }
  }, []);

  useEffect(() => {
    if (messaging) {
      const unsubscribe = messaging.onTokenRefresh(
        () => {
          messaging
            .getToken()
            .then((refreshedToken) => {
              console.log(refreshedToken);
            })
            .catch((e) => {
              console.log(e);
            });
        },
        (error) => console.log(error)
      );

      return () => {
        unsubscribe && unsubscribe();
      };
    }
  }, []);

  return (
    <>
      <Grid
        container
        alignItems="center"
        justify="center"
        className="home-row mobile-top-padding mb-24"
        direction="row-reverse"
      >
        <Grid item xs={12} sm={12} md={6} lg={6} className="home-left-col">
          <Fade right={isDesktop}>
            <h1 className="home-title">Get first hand experience in coding.</h1>
            <h2 className="home-description">
              Choose from hundreds of coding guides, tutorials and examples to
              learn new technology your heart desires.
            </h2>

            <Link to={authed ? "/dashboard" : "/signup"}>
              <Button type="primary" className="mt-24 mb-24 call-to-action-btn">
                {authed ? "Explore" : "Join CodeLabz"}
              </Button>
            </Link>
          </Fade>
        </Grid>
        <Grid item md={6} lg={6} order={1} className="home-right-col">
          <Fade left>
            <img
              src={homeMain1}
              alt="Background for auth"
              className="homepage-image"
            />
          </Fade>
        </Grid>
      </Grid>

      <Grid
        container
        className="light-grey-bg home-row"
        justify="center"
        align="center"
      >
        <Grid item xs={12} className="center pt-40 pb-40">
          <h1 className="home-title pl-24 pr-24 mb-8">
            Step-by-step instructions
          </h1>
          <h2 className="home-description pl-24 pr-24">
            Follow them to the dot and you wouldn't miss anything
          </h2>
          <Fade bottom>
            <img
              src={isDesktop ? homeInterface : homePhone}
              alt="Background for auth"
              className="homepage-interface"
            />
          </Fade>
        </Grid>
      </Grid>

      <Grid
        container
        className="home-row pt-40 pb-40"
        align="middle"
        justify="center"
      >
        <Grid item xs={12} className="center mb-24">
          <h1 className="home-title mb-8">Learning made easier</h1>
          <h2 className="home-description">Features that help you get going</h2>
        </Grid>

        <Grid item md={3} xs={12} className="col-pad-24">
          <Fade left>
            <Card>
              <CardActionArea>
                <CardMedia
                  children={<img alt="example" src={featureOdd} />}
                  title="Contemplative Reptile"
                />
                <CardContent>
                  <Typography gutterBottom variant="h5" component="h2">
                    Feature 1
                  </Typography>
                  <Typography
                    variant="body2"
                    color="textSecondary"
                    component="p"
                  >
                    Lorem ipsum dolor sit amet consectetur, adipisicing elit.
                  </Typography>
                </CardContent>
              </CardActionArea>
              <CardActions>
                <Button size="small" color="primary">
                  Share
                </Button>
                <Button size="small" color="primary">
                  Learn More
                </Button>
              </CardActions>
            </Card>
          </Fade>
        </Grid>

        <Grid item md={3} xs={12} className="col-pad-24">
          <Fade left>
            <Card>
              <CardActionArea>
                <CardMedia
                  children={<img alt="example" src={featureOdd} />}
                  title="Contemplative Reptile"
                />
                <CardContent>
                  <Typography gutterBottom variant="h5" component="h2">
                    Feature 1
                  </Typography>
                  <Typography
                    variant="body2"
                    color="textSecondary"
                    component="p"
                  >
                    Lorem ipsum dolor sit amet consectetur, adipisicing elit.
                  </Typography>
                </CardContent>
              </CardActionArea>
              <CardActions>
                <Button size="small" color="primary">
                  Share
                </Button>
                <Button size="small" color="primary">
                  Learn More
                </Button>
              </CardActions>
            </Card>
          </Fade>
        </Grid>

        <Grid item md={3} xs={12} className="col-pad-24">
          <Fade left>
            <Card>
              <CardActionArea>
                <CardMedia
                  children={<img alt="example" src={featureOdd} />}
                  title="Contemplative Reptile"
                />
                <CardContent>
                  <Typography gutterBottom variant="h5" component="h2">
                    Feature 1
                  </Typography>
                  <Typography
                    variant="body2"
                    color="textSecondary"
                    component="p"
                  >
                    Lorem ipsum dolor sit amet consectetur, adipisicing elit.
                  </Typography>
                </CardContent>
              </CardActionArea>
              <CardActions>
                <Button size="small" color="primary">
                  Share
                </Button>
                <Button size="small" color="primary">
                  Learn More
                </Button>
              </CardActions>
            </Card>
          </Fade>
        </Grid>

        <Grid item md={3} xs={12} className="col-pad-24">
          <Fade left>
            <Card>
              <CardActionArea>
                <CardMedia
                  children={<img alt="example" src={featureOdd} />}
                  title="Contemplative Reptile"
                />
                <CardContent>
                  <Typography gutterBottom variant="h5" component="h2">
                    Feature 1
                  </Typography>
                  <Typography
                    variant="body2"
                    color="textSecondary"
                    component="p"
                  >
                    Lorem ipsum dolor sit amet consectetur, adipisicing elit.
                  </Typography>
                </CardContent>
              </CardActionArea>
              <CardActions>
                <Button size="small" color="primary">
                  Share
                </Button>
                <Button size="small" color="primary">
                  Learn More
                </Button>
              </CardActions>
            </Card>
          </Fade>
        </Grid>
      </Grid>
    </>
  );
}
Example #24
Source File: UserEdit.js    From Kurakoo with MIT License 4 votes vote down vote up
SignUp = () => {
    useEffect(()=>{
        AOS.init({
            duration:2000,
            delay:1000
        })
    },[]);
    const initialState = {
        email: "",
        firstName:"",
        lastName:""
    };
    // eslint-disable-next-line
    const [PasswordInputType, ToggleIcon] = usePasswordToggle();
    
    const getMode = () => {
        return JSON.parse(localStorage.getItem("mode")) || false;
    };
    // eslint-disable-next-line
    const [dark, setmode] = useState(getMode());
    useEffect(() => {
        localStorage.setItem("mode", JSON.stringify(dark));
    }, [dark]);

    //CHECK WHETHER THE SCREEN IS SMALL OR NOT
    // eslint-disable-next-line
    const isSmallScreen = useMediaQuery({
        query: "(max-width: 959.5px)"
    });
    const [firstName, setFirstName] = useState("");
    const [lastName, setLastName] = useState("");
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    

    const auth = useSelector((state) => state.auth);
    const user = useSelector((state) => state.user);
    const [formData, setFormData] = useState(initialState);

    //MAKING CHANGE IN STATE VALUES FROM USER INPUT
    // eslint-disable-next-line
    const handleChange = (e) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
    };

    //TOAST TO DISPLAY FOR INVALID INPUTS WITH CUSTOM MESSAGE PARAMETER
    const errorToast = (message) => {
        toast.error(message, {
            position: "top-center",
            autoClose: 3000,
            closeOnClick: true,
            hideProgressBar: true,
            pauseOnHover: true,
            draggable: true,
            progress: undefined
        });
    };

    //TOAST TO DISPLAY FOR SUCCESSFULL SIGNIN
    const successToast = (message) => {
        toast.success(message, {
            position: "top-right",
            autoClose: 2000,
            hideProgressBar: true,
            closeOnClick: true,
            pauseOnHover: true,
            draggable: true,
            progress: undefined
        });
    };

    const editUser = (e) => {
        //FUNCTION TO DO APPROPRIATE TASK ON CLICKING SUBMIT BUTTON
    // eslint-disable-next-line
        //CONDITIONS TO CHECK VALID INPUT DETAILS
        if (formData.email !== "") {
            // eslint-disable-next-line
            const valid_email = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            if (valid_email.test(formData.email)) {
                if (formData.firstName !== "") {
                    if(formData.lastName!=""){
                    //Code to perform authentication via an api
                    // if user is successfully signed then then we can have a .then() block
                    // in which we will show a toast and redirect the user
                    successToast("Successfully edited");
                } else {
                    errorToast("Please enter Last Name");
                }}
                else {
                    errorToast("Please enter First Name");
                }
            } else {
                errorToast("Please enter a valid email id");
            }}
         else {
            errorToast("Please enter email");
        }
    };
    if (auth.authenticate) {
        return <Redirect to={"/"} />;
    }

    if (user.loading) {
        return <Progress mb='4' w='25%'><Progress.Bar striped animated min='0'max='100' mx='auto' now='50'>Loading....</Progress.Bar></Progress>;
    }
    return (
        <div >
              <Navbar/>
              <Meta title="SignUp ​?​?​​??​| Kurakoo" />
              <div class="container" style={{marginTop:'10%'}}>
              <img  alt= "img"src="https://previews.123rf.com/images/chrisdorney/chrisdorney1602/chrisdorney160200077/51658510-no-questions-asked-red-rubber-stamp-over-a-white-background-.jpg"
    style={{width:"25%", height:"480px", opacity:0.5}}
    data-aos='fade-right'/>
	<section id="content" style={{marginTop:'-40%'}}>
		<form action="" data-aos='fade-in'>
			<h1>Update Profile</h1>
			<div>
				<input type="text" placeholder="First Name"  name="firstName"
                                    value={firstName}
                                    onChange={(e) =>
                                        setFirstName(e.target.value)
                                    }
                                    required/>
			</div>
            <div>
				<input type="text" placeholder="Last Name"
                                    name="lasttName"
                                    value={lastName}
                                    onChange={(e) =>
                                        setLastName(e.target.value)
                                    }
                                    required />
			</div>   
            <div>
				<input  type="email"
                                    placeholder="[email protected]"
                                    name="email"
                                    value={email}
                                    onChange={(e) => setEmail(e.target.value)}
                                    required/>
			</div>
            <div>
				<input name="password"
                                    placeholder="Password"
                                    type={PasswordInputType}
                                    value={password}
                                    onChange={(e) =>
                                        setPassword(e.target.value)
                                    }
                                    required />
			</div>
			<div>
				<input type="submit" value="Update"
                            onClick={editUser} />
			</div>
		</form>
	</section><img alt="preview" src="https://previews.123rf.com/images/lkeskinen/lkeskinen1707/lkeskinen170708972/82453980-no-answer-rubber-stamp.jpg"
    style={{width:"25%", height:"480px", opacity:0.5,marginLeft:'75%',marginTop:'-41%'}}
    data-aos='fade-left'/>
</div></div>
        
    );
                                }
Example #25
Source File: SignUp.js    From Kurakoo with MIT License 4 votes vote down vote up
SignUp = () => {
    const [PasswordInputType, ToggleIcon] = usePasswordToggle();

    const getMode = () => {
        return JSON.parse(localStorage.getItem("mode")) || false;
    };
    const [dark, setmode] = useState(getMode());
    useEffect(() => {
        localStorage.setItem("mode", JSON.stringify(dark));
    }, [dark]);

    //CHECK WHETHER THE SCREEN IS SMALL OR NOT
    const isSmallScreen = useMediaQuery({
        query: "(max-width: 959.5px)"
    });
    const [firstName, setFirstName] = useState("");
    const [lastName, setLastName] = useState("");
    const [userName, setUserName] = useState("");
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [course, setCourse] = useState("");
    const [year, setYear] = useState("");
    const [collegeName, setCollegeName] = useState("");
    const [contactNumber, setContactNumber] = useState("");
    const auth = useSelector((state) => state.auth);
    const user = useSelector((state) => state.user);
    const dispatch = useDispatch();

    const userSignup = (e) => {
        e.preventDefault();

        dispatch(
            signup({
                firstName,
                lastName,
                userName,
                email,
                password,
                course,
                year,
                collegeName,
                contactNumber
            })
        );
    };

    if (auth.authenticate) {
        return <Redirect to={"/"} />;
    }

    if (user.loading) {
        return <Progress mb='4' w='25%'><Progress.Bar striped animated min='0'max='100' mx='auto' now='50'>Loading....</Progress.Bar></Progress>;
    }

    return (
        <div className={dark ? "dark-mode main" : "main"}>
            <Grid container>
                <Meta title="SignUp ​?​?​​??​| Kurakoo" />
                {/* SHOW THE SIDE IMAGE ONLY ON LARGE WIDTH SCREENS */}
                {!isSmallScreen ? (
                    <Grid item md={6} lg={6}>
                        <img
                            draggable={false}
                            className="signup_image"
                            src="./images/Formimage.png"
                            alt="signup_image"
                        ></img>
                    </Grid>
                ) : (
                    <Grid item md={12} lg={12}></Grid>
                )}

                <Grid item xs={12} sm={12} md={6} lg={6}>
                    {/* SHOW KURAKOO LOGO RATHER THAN IMAGE ON SMALL SCREENS */}
                    {isSmallScreen ? (
                        <Link to="/">
                            <img
                                draggable={false}
                                className="mobile_logo_img"
                                src="../images/kurakoo-logo.png"
                                alt="mobile_logo_img"
                            ></img>
                        </Link>
                    ) : (
                        <div></div>
                    )}

                    {/* //INPUT CONTENT */}
                    <label className="switch">
                        <input
                            type="checkbox"
                            checked={dark}
                            onChange={() => {
                                setmode(!dark);
                            }}
                        />
                        <span className="slider round"></span>
                        <h2>{dark ? "Dark" : "Light"}</h2>
                    </label>
                    <input type="checkbox" id="show" className="show" />
                    <label for="show" class="title">
                        sign up<i class="flag left"></i>
                        <i class="flag right"></i>
                    </label>
                    <form className="form">
                        <div className="group">
                            <div className="col-1">
                                <label for="name">FirstName</label>
                            </div>
                            <div class="colm-2">
                                <input
                                    type="text"
                                    placeholder="first name"
                                    name="firstName"
                                    value={firstName}
                                    onChange={(e) =>
                                        setFirstName(e.target.value)
                                    }
                                    required
                                />
                            </div>
                        </div>
                        <div className="group">
                            <div className="col-1">
                                <label for="name">LastName</label>
                            </div>
                            <div class="colm-2">
                                <input
                                    type="text"
                                    placeholder="last name"
                                    name="lasttName"
                                    value={lastName}
                                    onChange={(e) =>
                                        setLastName(e.target.value)
                                    }
                                    required
                                />
                            </div>
                        </div>
                        <div className="group">
                            <div className="col-1">
                                <label for="name">Username</label>
                            </div>
                            <div class="colm-2">
                                <input
                                    type="text"
                                    placeholder="Username"
                                    name="name"
                                    value={userName}
                                    onChange={(e) =>
                                        setUserName(e.target.value)
                                    }
                                    required
                                />
                            </div>
                        </div>

                        <div className="group">
                            <div className="col-1">
                                <label for="email">Email</label>
                            </div>
                            <div className="colm-2">
                                <input
                                    type="email"
                                    placeholder="[email protected]"
                                    name="email"
                                    value={email}
                                    onChange={(e) => setEmail(e.target.value)}
                                    required
                                />
                            </div>
                        </div>
                        <div className="group">
                            <div className="col-1">
                                <label for="password">Password</label>
                            </div>
                            <div className="colm-2">
                                <input
                                    name="password"
                                    placeholder="password"
                                    type={PasswordInputType}
                                    value={password}
                                    onChange={(e) =>
                                        setPassword(e.target.value)
                                    }
                                    required
                                />
                                <span className="password-toggle-icon-signup">
                                    {ToggleIcon}
                                </span>
                            </div>
                        </div>
                        <div className="group">
                            <div className="col-1">
                                <label for="course">Course</label>
                            </div>
                            <div className="colm-2">
                                <input
                                    type="text"
                                    placeholder="course"
                                    name="course"
                                    value={course}
                                    onChange={(e) => setCourse(e.target.value)}
                                    required
                                />
                            </div>
                        </div>
                        <div className="group">
                            <div className="col-1">
                                <label for="year">Year</label>
                            </div>
                            <div className="colm-2">
                                <input
                                    type="number"
                                    placeholder="year"
                                    name="year"
                                    value={year}
                                    onChange={(e) => setYear(e.target.value)}
                                    required
                                />
                            </div>
                        </div>
                        <div className="group">
                            <div className="col-1">
                                <label for="college">College</label>
                            </div>
                            <div className="colm-2">
                                <input
                                    type="text"
                                    placeholder="college name"
                                    name="college"
                                    value={collegeName}
                                    onChange={(e) =>
                                        setCollegeName(e.target.value)
                                    }
                                    required
                                />
                            </div>
                        </div>
                        <div className="group">
                            <div className="col-1">
                                <label for="name">ContactNumber</label>
                            </div>
                            <div class="colm-2">
                                <input
                                    type="number"
                                    placeholder="contact number"
                                    name="contactNumber"
                                    value={contactNumber}
                                    onChange={(e) =>
                                        setContactNumber(e.target.value)
                                    }
                                />
                            </div>
                        </div>
                        <input
                            type="submit"
                            className="submit"
                            value="submit"
                            onClick={userSignup}
                        />
                        <br />
                        <p className="signup_signin_message">
                            Already a user?
                            {/* <a href="/signin" className="signin_link">Sign In</a> */}
                            <Link to="/signin">Sign In</Link>
                        </p>
                    </form>
                </Grid>
            </Grid>
        </div>
    );
}
Example #26
Source File: SignIn.js    From Kurakoo with MIT License 4 votes vote down vote up
SignIn = () => {
    useEffect(()=>{
        AOS.init({
            duration:2000,
            delay:1000
        })
    },[]);
    const [PasswordInputType, ToggleIcon] = usePasswordToggle();
    const getMode = () => {
        return JSON.parse(localStorage.getItem("mode")) || false;
    };
    const [dark, setmode] = useState(getMode());
    useEffect(() => {
        localStorage.setItem("mode", JSON.stringify(dark));
    }, [dark]);

    const history = useHistory();

    //STATE HOOK FOR INPUT DETAILS
    const [formData, setFormData] = useState(initialState);

    //MAKING CHANGE IN STATE VALUES FROM USER INPUT
    // eslint-disable-next-line
    const handleChange = (e) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
    };

    //CHECK WHETHER THE SCREEN IS SMALL OR NOT
    const isSmallScreen = useMediaQuery({
        query: "(max-width: 959.5px)"
    });

    //TOAST TO DISPLAY FOR INVALID INPUTS WITH CUSTOM MESSAGE PARAMETER
    const errorToast = (message) => {
        toast.error(message, {
            position: "top-center",
            autoClose: 3000,
            closeOnClick: true,
            hideProgressBar: true,
            pauseOnHover: true,
            draggable: true,
            progress: undefined
        });
    };

    //TOAST TO DISPLAY FOR SUCCESSFULL SIGNIN
    const successToast = (message) => {
        toast.success(message, {
            position: "top-right",
            autoClose: 2000,
            hideProgressBar: true,
            closeOnClick: true,
            pauseOnHover: true,
            draggable: true,
            progress: undefined
        });
    };

    //FUNCTION TO DO APPROPRIATE TASK ON CLICKING SUBMIT BUTTON
    // eslint-disable-next-line
    const PostData = () => {
        //CONDITIONS TO CHECK VALID INPUT DETAILS
        if (formData.email !== "") {
            // eslint-disable-next-line
            const valid_email = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            if (valid_email.test(formData.email)) {
                if (formData.password !== "") {
                    //Code to perform authentication via an api
                    // if user is successfully signed then then we can have a .then() block
                    // in which we will show a toast and redirect the user
                    successToast("Successfully signed in");
                    history.push("/feed");
                } else {
                    errorToast("Please enter password");
                }
            } else {
                errorToast("Please enter a valid email id");
            }
        } else {
            errorToast("Please enter email");
        }
    };

    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const auth = useSelector((state) => state.auth);

    const dispatch = useDispatch();
    const userLogin = (e) => {
        e.preventDefault();

        dispatch(
            login({
                email,
                password
            })
        );
    };

    if (auth.authenticate) {
        return <Redirect to={"/"} />;
    }

    return (
        <div className={dark ? "dark-mode main" : "main"}>
            <Grid container>
                <Meta title="SignIn ​?​?​?​ | Kurakoo" />
                {/* SHOW THE SIDE IMAGE ONLY ON LARGE WIDTH SCREENS */}
                {!isSmallScreen ? (
                    <Grid item md={6} lg={6}>
                        <img
                            draggable={false}
                            className="signin_image"
                            src="./images/Formimage.png"
                            alt="signin_image"
                        ></img>
                    </Grid>
                ) : (
                    <Grid item md={12} lg={12}></Grid>
                )}

                <Grid item xs={12} sm={12} md={6} lg={6}>
                    {/* SHOW KURAKOO LOGO RATHER THAN IMAGE ON SMALL SCREENS */}
                    {!isSmallScreen ? (
                        <div></div>
                    ) : (
                        <Link to="/">
                            <img
                                draggable={false}
                                className="mobile_logo_img"
                                src="../images/kurakoo-logo.png"
                                alt="mobile_logo_img"
                            ></img>
                        </Link>
                    )}

                    {/* Form to take input */}
                    <label className="switch">
                        <input
                            type="checkbox"
                            checked={dark}
                            onChange={() => {
                                setmode(!dark);
                            }}
                        />
                        <span className="slider round"></span>
                        <h2>{dark ? "Dark" : "Light"}</h2>
                    </label>
                    <div className="app" data-aos='fade-up'>
                        <div className="bg"></div>
                        <form className="form1">
                            <header>
                                <img
                                    src="./images/favicon.png"
                                    className="logo"
                                    alt="preview"
                                />
                            </header>
                            <div className="inputs">
                                <input
                                    type="text"
                                    placeholder="email"
                                    name="email"
                                    value={email}
                                    onChange={(e) => setEmail(e.target.value)}
                                />
                                <input
                                    type={PasswordInputType}
                                    placeholder="password"
                                    name="password"
                                    value={password}
                                    onChange={(e) =>
                                        setPassword(e.target.value)
                                    }
                                />
                                <span className="password-toggle-icon-signin">
                                    {ToggleIcon}
                                </span>
                            </div>
                        </form>
                        <footer>
                            <button type="submit" onClick={userLogin}>
                                Continue
                            </button>
                            <p className="para">
                                Don't have an account?{" "}
                                <Link to="/signup">Sign Up</Link>
                            </p>
                        </footer>
                    </div>
                </Grid>
            </Grid>
            </div>
    );
}
Example #27
Source File: orgSidebar.js    From Codelabz with Apache License 2.0 4 votes vote down vote up
OrgSidebar = ({ onOrgChange }) => {
  const isDesktop = useMediaQuery({
    query: "(min-device-width: 767px)",
  });

  const dispatch = useDispatch();
  const orgs = useSelector(
    ({
      profile: {
        data: { organizations },
      },
    }) => organizations
  );

  const current = useSelector(
    ({
      org: {
        general: { current },
      },
    }) => current
  );

  const [activeOrg, setActiveOrg] = useState(orgs[0]); // set the current active org here
  const [showModal, setShowModal] = useState(false); // set the current active org here

  const handleClickEvent = (data) => {
    onOrgChange();
    let orgDetails = orgs.find((element) => {
      return element.org_handle === data.handle;
    });
    setCurrentOrgUserPermissions(
      orgDetails.org_handle,
      orgDetails.permissions
    )(dispatch);
  };

  useEffect(() => {
    let orgDetails = orgs.find((element) => {
      return element.org_handle === current;
    });
    setActiveOrg(orgDetails);
  }, [current, orgs]);

  const createOrg = () => {
    setShowModal(true);
  };

  const createOrgClose = () => {
    setShowModal(false);
  };

  return (
    <>
      {activeOrg && (
        <>
          <OrgIcons
            border={true}
            borderColor={null}
            text={activeOrg.org_name}
            image={activeOrg.org_image}
            onClick={null}
            data={{ name: activeOrg.org_name + " (selected)" }}
            active={true}
            isDesktop={isDesktop}
          />
        </>
      )}

      <OrgIcons
        border={false}
        borderColor={"#4F6EEE"}
        text="Create New Organization"
        icon={<PlusOutlined />}
        onClick={createOrg}
        style={{ color: "#4F6EEE", backgroundColor: "#F2F7FF" }}
        data={{ name: "Create New Organization" }}
        isDesktop={isDesktop}
      />

      {orgs &&
        orgs.map((org) => (
          <Palette
            data-testId="orgSidebarIcon"
            src={org.org_image}
            crossOrigin="Anonymous"
            key={org.org_handle}
          >
            {({ data, loading }) => {
              if (loading) {
                return (
                  <OrgIcons
                    border={true}
                    borderColor={"#aaaaaa"}
                    text={org.org_name}
                    image={org.org_image}
                    onClick={handleClickEvent}
                    data={{ name: org.org_name, handle: org.org_handle }}
                    active={false}
                    isDesktop={isDesktop}
                  />
                );
              } else {
                return (
                  <OrgIcons
                    border={true}
                    borderColor={data[0]}
                    text={org.org_name}
                    image={org.org_image}
                    onClick={handleClickEvent}
                    data={{
                      name: org.org_name,
                      handle: org.org_handle,
                    }}
                    active={false}
                    isDesktop={isDesktop}
                  />
                );
              }
            }}
          </Palette>
        ))}
      <CreateOrgModal show={showModal} closeCallback={createOrgClose} />
    </>
  );
}
Example #28
Source File: index.js    From bank-client with MIT License 4 votes vote down vote up
function HeaderAction({ intl }) {
  const { messagesData, user } = useSelector(stateSelector);
  const dispatch = useDispatch();
  const isMobile = useMediaQuery({ maxWidth: 479 });

  const onLogout = () => dispatch(logoutAction());
  const onGetMessages = () => dispatch(getMessagesAction());
  const onGetNotifications = () => dispatch(getNotificationsAction());
  const onToggleConfirmModal = () => dispatch(toggleConfirmModalAction());

  return (
    <StyledHeaderAction>
      <StyledHeaderWrapper>
        <Dropdown
          trigger={['click']}
          overlay={<Messages />}
          placement="bottomCenter"
          arrow={!isMobile}
          getPopupContainer={(trigger) => trigger.parentNode}
        >
          <StyledHeaderActionItem
            type="link"
            onClick={!messagesData?.data?.length && onGetMessages}
          >
            <Badge count={user?.userConfig?.messageCount}>
              {user?.userConfig?.messageCount ? (
                <StyledMessageFilled />
              ) : (
                <StyledMessageOutlined />
              )}
            </Badge>
            <StyledHeaderActionItemName>
              <FormattedMessage {...messages.messages} />
            </StyledHeaderActionItemName>
          </StyledHeaderActionItem>
        </Dropdown>

        <Dropdown
          trigger={['click']}
          overlay={<Notifications />}
          placement="bottomCenter"
          arrow={!isMobile}
          getPopupContainer={(trigger) => trigger.parentNode}
        >
          <StyledHeaderActionItem
            type="link"
            onClick={user?.userConfig?.notificationCount && onGetNotifications}
          >
            <Badge count={user?.userConfig?.notificationCount}>
              {user?.userConfig?.notificationCount ? (
                <StyledBellFilled />
              ) : (
                <StyledBellOutlined />
              )}
            </Badge>
            <StyledHeaderActionItemName>
              <FormattedMessage {...messages.notifications} />
            </StyledHeaderActionItemName>
          </StyledHeaderActionItem>
        </Dropdown>

        {isMobile ? (
          <>
            <StyledHeaderActionItem type="link" onClick={onToggleConfirmModal}>
              <StyledPoweroffOutlined />
              <StyledHeaderActionItemName>
                <FormattedMessage {...messages.logout} />
              </StyledHeaderActionItemName>
            </StyledHeaderActionItem>

            <Modal />
          </>
        ) : (
          <Popconfirm
            placement="bottomRight"
            title={intl.formatMessage(messages.popConfirmTitle)}
            onConfirm={onLogout}
            okText={intl.formatMessage(messages.popConfirmOk)}
            cancelText={intl.formatMessage(messages.popConfirmCancel)}
          >
            <StyledHeaderActionItem type="link">
              <StyledPoweroffOutlined />
              <StyledHeaderActionItemName>
                <FormattedMessage {...messages.logout} />
              </StyledHeaderActionItemName>
            </StyledHeaderActionItem>
          </Popconfirm>
        )}
      </StyledHeaderWrapper>
    </StyledHeaderAction>
  );
}
Example #29
Source File: index.js    From Codelabz with Apache License 2.0 4 votes vote down vote up
ViewTutorial = () => {
  const firebase = useFirebase();
  const firestore = useFirestore();
  const dispatch = useDispatch();
  const [currentStep, setCurrentStep] = useState(0);
  const [stepPanelVisible, setStepPanelVisible] = useState(true);
  const [timeRemaining, setTimeRemaining] = useState(0);
  const [mode, setMode] = useState("view");
  const [allowEdit, setAllowEdit] = useState(true);
  const [imageDrawerVisible, setImageDrawerVisible] = useState(false);
  const [addNewStepModalVisible, setAddNewStepModalVisible] = useState(false);
  const [currentStepContent, setCurrentStepContent] = useState(null);
  const [stepsData, setStepData] = useState(null);
  const [tutorialData, setTutorialData] = useState(null);
  const isDesktop = useMediaQuery({
    query: "(min-device-width: 767px)",
  });
  const { owner, tutorial_id } = useParams();

  useEffect(() => {
    getCurrentTutorialData(owner, tutorial_id)(firebase, firestore, dispatch);
  }, [owner, tutorial_id, firebase, firestore, dispatch]);

  const currentStepNo = useSelector(
    ({
      tutorials: {
        editor: { current_step_no },
      },
    }) => current_step_no
  );

  const currentTutorialData = useSelector(
    ({
      tutorials: {
        current: { data },
      },
    }) => data
  );

  useEffect(() => {
    if (currentTutorialData) {
      const { steps } = currentTutorialData;
      setStepData(steps);
      setTutorialData(currentTutorialData);
    }
  }, [currentTutorialData]);

  const editorStepData = useSelector(
    ({
      tutorials: {
        editor: { current_step },
      },
    }) => current_step
  );

  useEffect(() => {
    setCurrentStepContent(editorStepData);
  }, [editorStepData]);

  useEffect(() => {
    setAllowEdit(true); // remove this later
    setStepPanelVisible(isDesktop);
  }, [isDesktop]);

  useEffect(() => {
    if (stepsData) {
      setTimeRemaining(TutorialTimeRemaining(stepsData, currentStep));
      getCurrentStepContentFromRTDB(tutorial_id, stepsData[currentStep].id)(
        firebase,
        dispatch
      );
    }
  }, [tutorial_id, firebase, stepsData, currentStep, dispatch]);

  const onChange = (current) => {
    setCurrentStepNo(current)(dispatch);
    !isDesktop &&
      setTimeout(() => {
        setStepPanelVisible(false);
      }, 300);
  };

  useEffect(() => {
    setCurrentStep(currentStepNo);
  }, [currentStepNo]);

  if (tutorialData) {
    window.scrollTo(0, 0);
    return (
      <Grid className="row-footer-below">
        {allowEdit && (
          <Grid>
            <Grid xs={24} sm={24} md={24}>
              <EditControls
                stepPanelVisible={stepPanelVisible}
                isDesktop={isDesktop}
                noteID={stepsData[currentStep].id}
                setMode={(mode) => setMode(mode)}
                mode={mode}
                toggleImageDrawer={() => setImageDrawerVisible(true)}
                tutorial_id={tutorialData.tutorial_id}
                toggleAddNewStep={() =>
                  setAddNewStepModalVisible(!addNewStepModalVisible)
                }
                visibility={stepsData[currentStep].visibility}
                owner={owner}
                currentStep={currentStep}
                step_length={stepsData.length}
              />
            </Grid>
          </Grid>
        )}

        <Grid>
          <Grid xs={24} sm={24} md={24}>
            <TutorialTitle
              stepPanelVisible={stepPanelVisible}
              isDesktop={isDesktop}
              setStepPanelVisible={setStepPanelVisible}
              tutorialData={tutorialData}
              timeRemaining={timeRemaining}
            />
          </Grid>
        </Grid>
        <Grid style={{ display: "flex", flexDirection: "row" }}>
          <Grid
            width={stepPanelVisible ? (isDesktop ? "55%" : "100%") : "0"}
            theme="light"
            style={{ backgroundColor: "white", padding: "2rem" }}
          >
            <StepsPanel
              currentStep={currentStep}
              onChange={onChange}
              stepsData={stepsData}
              onClick={() => setStepPanelVisible(false)}
              hideButton={isDesktop}
            />
          </Grid>

          <Grid style={{ width: "90%", background: "#f0f0f0" }}>
            <Grid className="tutorial-content" justify="center" container>
              <Grid
                xs={24}
                sm={24}
                md={20}
                lg={18}
                className="col-pad-24-s mt-24-od tutorial-paper"
              >
                {!isDesktop && stepPanelVisible ? null : (
                  <>
                    {mode === "view" && (
                      <ReactMarkdown children={currentStepContent} />
                    )}
                    {mode === "edit" && (
                      <>
                        <StepsTitle
                          currentStepNo={currentStepNo}
                          owner={tutorialData.owner}
                          tutorial_id={tutorialData.tutorial_id}
                          step_id={stepsData[currentStep].id}
                          step_title={stepsData[currentStep].title}
                          step_time={stepsData[currentStep].time}
                        />
                        <Editor
                          data={stepsData[currentStep].content}
                          tutorial_id={tutorialData.tutorial_id}
                          id={stepsData[currentStep].id}
                          key={
                            stepsData[currentStep].title +
                            stepsData[currentStep].id
                          }
                          mode={mode}
                        />
                      </>
                    )}
                  </>
                )}
              </Grid>
              {imageDrawerVisible && (
                <ImageDrawer
                  visible={imageDrawerVisible}
                  onClose={() => setImageDrawerVisible(false)}
                  owner={tutorialData.owner}
                  tutorial_id={tutorialData.tutorial_id}
                  imageURLs={tutorialData.imageURLs}
                />
              )}
              <AddNewStepModal
                viewModal={addNewStepModalVisible}
                viewCallback={() =>
                  setAddNewStepModalVisible(!addNewStepModalVisible)
                }
                tutorial_id={tutorialData.tutorial_id}
                steps_length={stepsData.length}
                owner={tutorialData.owner}
              />
            </Grid>
            <Grid>
              <Grid xs={24} sm={24} md={24} className="col-pad-24-s">
                <ControlButtons
                  currentStep={currentStep}
                  setCurrentStep={setCurrentStep}
                  stepsData={stepsData}
                  hide={!isDesktop && stepPanelVisible}
                />
              </Grid>
            </Grid>
          </Grid>
        </Grid>
      </Grid>
    );
  } else {
    return <Spinner half />;
  }
}