@material-ui/core#useTheme JavaScript Examples

The following examples show how to use @material-ui/core#useTheme. 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: SimpleRandarChart.js    From paper-and-ink with MIT License 6 votes vote down vote up
export default function SimpleRandarChart() {
  const theme = useTheme();
  return (
    <ResponsiveContainer width="100%" minWidth={500} height={350}>
      <RadarChart cx={200} cy={150} outerRadius={150} data={salesByBrand}>
        <PolarGrid />
        <PolarAngleAxis dataKey="brand" tick={{ fill: theme.palette.contrastText, fontSize: 12 }} />
        <PolarRadiusAxis />
        <Radar name="Brand" dataKey="sales" stroke="#8884d8" fill="#8884d8" fillOpacity={0.6} />
      </RadarChart>
    </ResponsiveContainer>
  );
}
Example #2
Source File: Footer.js    From pomodor with MIT License 6 votes vote down vote up
Footer = () => {
  const theme = useTheme()

  return (
    <Container>
      <Text align="center">
        Made with <Heart color="secondary" /> by Sasha Drmic
      </Text>

      <CoffeeLink
        href="https://www.buymeacoffee.com/sashadrmic"
        target="_blank"
        rel="noopener noreferrer"
      >
        <CoffeeImage src={coffee} alt="Buy me a coffee" />
      </CoffeeLink>

      <Box display="flex" justifyContent="space-between" width={60} m="auto">
        <a
          href="https://twitter.com/sasha_drmic"
          target="_blank"
          rel="noopener noreferrer"
        >
          <Twitter theme={theme} />
        </a>
        <a
          href="https://github.com/sasa95/pomodor"
          target="_blank"
          rel="noopener noreferrer"
        >
          <GitHub theme={theme} />
        </a>
      </Box>
    </Container>
  )
}
Example #3
Source File: TodayWidget.js    From module-federation-examples with MIT License 6 votes vote down vote up
export default function TodayWidget() {
  const theme = useTheme();

  return (
    <Box display="flex" flexDirection="column" flex={1}>
      <Typography component="h2" variant="h6" color="primary" gutterBottom>
        Today
      </Typography>
      <ResponsiveContainer>
        <LineChart
          data={data}
          margin={{
            top: 16,
            right: 16,
            bottom: 0,
            left: 24,
          }}
        >
          <XAxis dataKey="time" stroke={theme.palette.text.secondary} />
          <YAxis stroke={theme.palette.text.secondary}>
            <Label
              angle={270}
              position="left"
              style={{ textAnchor: 'middle', fill: theme.palette.text.primary }}
            >
              Sales ($)
            </Label>
          </YAxis>
          <Line type="monotone" dataKey="amount" stroke={theme.palette.primary.main} dot={false} />
        </LineChart>
      </ResponsiveContainer>
    </Box>
  );
}
Example #4
Source File: NoData.js    From pomodor with MIT License 6 votes vote down vote up
NoData = () => {
  const theme = useTheme()

  return (
    <Box
      display="flex"
      flexDirection="column"
      justifyContent="center"
      alignItems="center"
      alignSelf="center"
      width="90%"
      maxWidth="600px"
      m="auto"
    >
      <Illustration src={illustration} alt="Statistics and charts" />
      <Typography align="center">
        Nothing to show here. Come back after you{' '}
        <LinkStyled to="/timer" color={theme.palette.secondary.main}>
          complete a few sessions
        </LinkStyled>
        .
      </Typography>
    </Box>
  )
}
Example #5
Source File: index.js    From Portfolio with MIT License 6 votes vote down vote up
export default function Index({ projects, setTheme }) {

  const classes = useStyles()

  const trigger = useScrollTrigger({ disableHysteresis: true })

  const theme = useTheme()

  const toggleTheme = useCallback(() => {
    setTheme(theme => theme.palette.type === 'dark' ? lightTheme : darkTheme)
  }, [setTheme])

  return (
    <div className={classes.root}>
      <AppBar color={!trigger ? "transparent" : "inherit"} className={classes.appBar} position="fixed">
        <Toolbar>
          <Typography variant="h6" className={classes.root}>
            { name }
          </Typography>
          <IconButton edge="end" color="inherit" onClick={toggleTheme}>
            {theme.palette.type === "dark" ? <Brightness7/> : <Brightness4/>}
          </IconButton>
        </Toolbar>
      </AppBar>
      <Toolbar className={classes.toolbar} />
      <Container>
        <Landing />
        <Skills />
        <Projects data={projects}/>
        <Experience/>
        <About/>
      </Container>
    </div>
  );
}
Example #6
Source File: Timer.js    From pomodor with MIT License 6 votes vote down vote up
Timer = () => {
  const theme = useTheme()

  const isMD = useMediaQuery(theme.breakpoints.up('md'))
  const isLG = useMediaQuery(theme.breakpoints.up('lg'))
  const isXL = useMediaQuery(theme.breakpoints.up('xl'))

  const getCircleSize = () => {
    if (isXL) return 350
    if (isLG) return 300
    if (isMD) return 250

    return 200
  }

  return (
    <Box width={getCircleSize()} m="auto">
      <LabelButton />
      <CountdownCircle />

      <Box display="flex" justifyContent="center" alignItems="center" my={3}>
        <ResetButton />

        <Box display="flex" flexDirection="column" alignItems="center" mx={3}>
          <ToggleButton />
        </Box>

        <SkipButton />
      </Box>

      <Box display="flex" justifyContent="center">
        <RoundsCounter />
      </Box>

      <FullscreenDialog />
      <DesktopDialog />
    </Box>
  )
}
Example #7
Source File: SimpleLineChart.js    From paper-and-ink with MIT License 6 votes vote down vote up
function SimpleLineChart() {
  const theme = useTheme();
  return (
    <ResponsiveContainer width="100%" minWidth={500} height={350}>
      <LineChart
        width={600}
        height={300}
        data={sales}
        margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
      >
        <XAxis dataKey="month" />
        <YAxis />

        <Tooltip />

        <Line
          type="monotone"
          dataKey="orders"
          stroke={theme.palette.primary.dark}
          activeDot={{ r: 8 }}
        />
        <Line type="monotone" dataKey="sales" stroke={theme.palette.success.light} />
      </LineChart>
    </ResponsiveContainer>
  );
}
Example #8
Source File: CitiesSearch.js    From project-s0-t2-env with MIT License 6 votes vote down vote up
export default function CitiesSearch(props) {
  const names = props.names;
  const theme = useTheme();
  const filterOptions = createFilterOptions({
    limit: 5,
  });

  const [value, setValue] = useState(null);

  if (!names) {
    return (
      <div style={{ height: 0 }}>
        Loading Search Bar
        <Spinner animation="border" variant="secondary" size="sm" />
      </div>
    );
  }
  return (
    <div style={{ width: 300 }} data-cy="search">
      <Autocomplete
        filterOptions={filterOptions}
        options={names}
        value={value}
        onChange={props.onChange}
        id="clear-on-escape"
        clearOnEscape
        renderInput={(params) => (
          <TextField
            {...params}
            label="Cities in California"
            margin="normal"
            data-cy="searchfield"
          />
        )}
      />
    </div>
  );
}
Example #9
Source File: VideoPage.js    From youtube-clone with MIT License 6 votes vote down vote up
export default function VideoPage({ location }) {
  const classes = useStyles();
  const { v: id } = queryString.parse(location.search);
  const theme = useTheme();
  const isMaxScreenSm = useMediaQuery(theme.breakpoints.down("sm"));

  return (
    <div className={classes.container}>
      <Grid container spacing={2}>
        <Grid item xs={12} md={8}>
          <VideoContent videoId={id} />

          {isMaxScreenSm ? (
            <SecondaryVidContent />
          ) : (
            <CommentsContent videoId={id} />
          )}
          {isMaxScreenSm && <Divider className={classes.divider} />}
        </Grid>
        <Grid item xs={12} md={4}>
          {isMaxScreenSm ? (
            <CommentsContent videoId={id} />
          ) : (
            <SecondaryVidContent />
          )}
        </Grid>
      </Grid>
    </div>
  );
}
Example #10
Source File: Switch.js    From pomodor with MIT License 5 votes vote down vote up
Switch = ({ name, action, checked }) => {
  const [state, setState] = useState(false)

  const handleChange = (event) => {
    const checked = event.target.checked
    setState(checked)
    dispatch(action(checked))
  }

  const dispatch = useDispatch()

  const theme = useTheme()
  const darkMode = useSelector((state) => +state.settings.darkMode)
  const darkModeCached = +JSON.parse(localStorage.getItem('darkMode'))

  useEffect(() => {
    if (checked !== null && checked !== undefined) {
      setState(checked)
    }
  }, [checked])

  return (
    <Box>
      <Label
        ml={0}
        control={
          <SettingSwitch
            checked={state}
            onChange={handleChange}
            name={name}
            theme={theme}
            color="primary"
            dark={darkMode || darkModeCached}
          />
        }
        label={name}
        labelPlacement="start"
      />
    </Box>
  )
}
Example #11
Source File: EmissionsPie.js    From project-s0-t2-env with MIT License 5 votes vote down vote up
function EmissionsPie(props) {
  const data = props.data;
  const theme = useTheme();
  return (
    <svg viewBox="0 0 500 500" width="500px" height="500px">
      <VictoryPie
        style={{
          labels: { fill: "black", fontSize: 12, fontFamily: "lato" },
        }}
        colorScale={[
          theme.palette.primary.main,
          theme.palette.secondary.main,
          theme.palette.primary.dark,
          theme.palette.secondary.dark,
          theme.palette.primary.light,
          theme.palette.secondary.light,
        ]}
        innerRadius={75}
        standalone={false}
        animate={{ duration: 1000 }}
        width={400}
        height={400}
        origin={{ x: 250, y: 250 }}
        labels={({ datum }) =>
          `${datum.title} (${Math.floor(
            (100 * datum.y) / data.energyShare.total
          )}%)`
        }
        data={[
          { x: 1, y: data.energyShare.transport, title: "Transport" },
          { x: 2, y: data.energyShare.housing, title: "Housing" },
          { x: 3, y: data.energyShare.food, title: "Food" },
          { x: 4, y: data.energyShare.goods, title: "Goods" },
          { x: 5, y: data.energyShare.services, title: "Services" },
        ]}
      />
      <VictoryLabel
        textAnchor="middle"
        style={{
          fontSize: 15,
          backgroundColor: theme.palette.primary.main,
        }}
        x={250}
        y={250}
        text="CO2 Sources"
      />
    </svg>
  );
}
Example #12
Source File: NavList.js    From pomodor with MIT License 5 votes vote down vote up
NavList = () => {
  const theme = useTheme()
  const isTablet = useMediaQuery(theme.breakpoints.up('sm'))
  const sidenav = +useMediaQuery('(min-width:600px) and (min-height:500px)')

  const timerRunning = useSelector(
    (state) => state.timer.status !== STATUSES.onHold
  )

  return (
    <MatNavList
      component="nav"
      className="NavList"
      aria-label="Main navigation"
      theme={theme}
      sidenav={sidenav}
    >
      <Link to="/timer">
        <NavListItem button>
          <NavItemIcon>
            <TimerIcon />
          </NavItemIcon>
          <ListItemText primary="Timer" />
        </NavListItem>
      </Link>

      <Tooltip
        title="Reset timer to access the stats"
        disableHoverListener={!timerRunning}
        disableTouchListener
        disableFocusListener
        placement={isTablet ? 'right' : 'bottom'}
      >
        <Link
          to={timerRunning ? '#' : '/stats'}
          data-disabled={timerRunning && 'true'}
        >
          <NavListItem button disabled={timerRunning}>
            <NavItemIcon>
              <ShowChartIcon />
            </NavItemIcon>
            <ListItemText primary="Stats" />
          </NavListItem>
        </Link>
      </Tooltip>

      <Tooltip
        title="Reset timer to access the settings"
        disableHoverListener={!timerRunning}
        disableTouchListener
        disableFocusListener
        placement={isTablet ? 'right' : 'bottom'}
      >
        <Link
          to={timerRunning ? '#' : '/settings'}
          data-disabled={timerRunning && 'true'}
        >
          <NavListItem button disabled={timerRunning}>
            <NavItemIcon>
              <SettingsIcon />
            </NavItemIcon>
            <ListItemText primary="Settings" />
          </NavListItem>
        </Link>
      </Tooltip>
    </MatNavList>
  )
}
Example #13
Source File: TrendingPage.js    From youtube-clone with MIT License 5 votes vote down vote up
TrendingPage = ({ location }) => {
  const { category: categoryId } = queryString.parse(location.search);
  const trendingVids = useSelector(({ videos }) => videos.trending);
  const isLoading = useSelector(({ videos }) => videos.isLoading);
  const dispatch = useDispatch();
  const theme = useTheme();
  const isMaxScreenSm = useMediaQuery(theme.breakpoints.only("xs"));

  useEffect(() => {
    dispatch(getTrendingVideos(categoryId));
  }, [categoryId]);

  const classes = useStyles();
  return (
    <Container maxWidth="xl" className={classes.root}>
      <Typography variant="h5" className={classes.text}>
        {capitalize(categories[categoryId]) || "Trending"}
      </Typography>
      <HorizontalCategoryMenu />

      <Divider light className={classes.divider} />
      {(() => {
        if (isLoading && isMaxScreenSm) {
          return (
            <VideoList
              type="vertical_2"
              isLoading={isLoading}
              videos={trendingVids}
            />
          );
        } else if (isLoading && !isMaxScreenSm) {
          return (
            <VideoList
              type="horizontal_1"
              isLoading={isLoading}
              videos={trendingVids}
            />
          );
        } else if (!isLoading && !isMaxScreenSm && trendingVids.length) {
          return (
            <VideoList
              type="horizontal_1"
              isLoading={isLoading}
              videos={trendingVids}
            />
          );
        } else {
          return "Nothing Trending";
        }
      })()}
    </Container>
  );
}
Example #14
Source File: Slider.js    From pomodor with MIT License 5 votes vote down vote up
Slider = ({
  name,
  step,
  marks,
  min,
  max,
  unit,
  action,
  value,
}) => {
  const [sliderValue, setSliderValue] = useState(value)

  useEffect(() => {
    setSliderValue(value)
  }, [value])

  const dispatch = useDispatch()

  const handleChangeCommitted = (event, newValue) => {
    if (newValue !== value) {
      dispatch(action(newValue))
    }
  }

  const handleChange = (event, newValue) => {
    setSliderValue(newValue)
  }

  const valueText = (value) => {
    return `${value} ${unit}`
  }

  const theme = useTheme()
  const darkMode = useSelector((state) => +state.settings.darkMode)
  const darkModeCached = +JSON.parse(localStorage.getItem('darkMode'))

  return (
    <Box mt={2}>
      <Typography id={`${name}-slider`} gutterBottom>
        {name}
      </Typography>
      <SettingSlider
        getAriaValueText={valueText}
        aria-labelledby={`${name}-slider`}
        valueLabelDisplay="auto"
        step={step}
        marks={marks}
        min={min}
        max={max}
        onChangeCommitted={handleChangeCommitted}
        onChange={handleChange}
        value={sliderValue}
        theme={theme}
        dark={darkMode || darkModeCached}
        color="primary"
      />
    </Box>
  )
}
Example #15
Source File: MainNavMenu.js    From youtube-clone with MIT License 5 votes vote down vote up
MainNavMenu = () => {
  const theme = useTheme();

  const isMinScreenMd = useMediaQuery(theme.breakpoints.up("md"));
  const dispatch = useDispatch();
  const handleItemClick = () => {
    if (!isMinScreenMd) {
      dispatch(toggleDrawer(isMinScreenMd));
    }
  };

  return (
    <List>
      {[
        {
          title: "Home",
          icon: HomeIcon,
          path: "/",
        },
        {
          title: "Trending",
          icon: TrendingIcon,
          path: "/trending",
        },
        ...menuAuthIcons,
      ].map((item, index) => {
        return (
          <React.Fragment key={index}>
            <NavItem
              to={item.path}
              title={item.title}
              icon={item.icon}
              onClick={handleItemClick}
            />
            {index === 1 && <Divider />}
          </React.Fragment>
        );
      })}
    </List>
  );
}
Example #16
Source File: OverviewSubcard.js    From pomodor with MIT License 5 votes vote down vote up
OverviewSubcard = ({ icon, sum, label, trend = 0 }) => {
  const theme = useTheme()
  const isMediumScreen = +useMediaQuery(theme.breakpoints.up('md'))
  const darkMode = useSelector((state) => +state.settings.darkMode)

  const [trendColor, setTrendColor] = useState('rgba(0,0,0,0)')
  const [trendIconPath, setTrendIconPath] = useState()

  useEffect(() => {
    if (trend === 0) return
    let color, path

    if (trend > 0) {
      if (darkMode) {
        color = trendProps.positive.dark
      } else {
        color = trendProps.positive.light
      }
      path = trendProps.positive.path
    } else {
      if (darkMode) {
        color = trendProps.negative.dark
      } else {
        color = trendProps.negative.light
      }
      path = trendProps.negative.path
    }

    setTrendColor(color)
    setTrendIconPath(path)
  }, [darkMode, trend])

  return (
    <DataCard md={isMediumScreen} dark={darkMode}>
      <CardContent md={isMediumScreen}>
        <MainGrid
          container
          direction={isMediumScreen ? 'column' : 'row'}
          spacing={2}
          alignItems="center"
        >
          <Grid item xs={2} md={5} lg={9}>
            <Icon
              max-width="100%"
              src={icon}
              alt="Today Icon"
              md={isMediumScreen}
            />
          </Grid>
          <Grid item xs={10} md={12}>
            <Sum dark={darkMode} md={isMediumScreen}>
              {sum}
            </Sum>
            <Label color={theme.palette.text.secondary} md={isMediumScreen}>
              {label}
            </Label>

            {trend !== 0 && (
              <Box
                display="flex"
                alignItems="center"
                justifyContent={isMediumScreen ? 'center' : 'flex-start'}
              >
                <TrendIcon fill={trendColor} path={trendIconPath} />
                <Trend md={isMediumScreen} color={trendColor}>
                  {Math.abs(trend)}%
                </Trend>
              </Box>
            )}
          </Grid>
        </MainGrid>
      </CardContent>
    </DataCard>
  )
}
Example #17
Source File: [city].js    From project-s0-t2-env with MIT License 5 votes vote down vote up
function City() {
  const theme = useTheme();
  const router = useRouter();
  const { city } = router.query;
  const { data } = useSWR("/api/cities/" + city, fetch, {
    // By default, useSWR will call the endpoint we specified (in this case, /api/dog) every time we click away from
    // the page. This can be really useful if we want to make sure the web app is always showing the latest data,
    // but in this case, we don't need that behavior. See what happens if you set these options to true or remove them!
    revalidateOnFocus: false,
    revalidateOnReconnect: false,
  });

  if (!data) {
    return <CircularProgress />;
  }

  return (
    <div>
      <title>
        {data.name}, {data.state} | Environmental Impacts Dashboard
      </title>
      <Typography variant="h3" data-cy="location">
        {data.name}, {data.state}
      </Typography>
      {data.population ? (
        <Typography data-cy="population">
          Population: {numberWithCommas(data.population)}
        </Typography>
      ) : (
        <Typography data-cy="population">
          Sorry, we're missing population information for this city!
        </Typography>
      )}
      <CardContent>
        <List>
          <Divider />
          <CarbonEmissions
            data={data}
            CO2={numberWithCommas(data.CO2)}
            trees={numberWithCommas(Math.floor(data.CO2 / 0.06))}
          />
          <Divider />
          <EmissionsPie data={data} />
          <Divider />
          <CityWaterAir data={data} />
        </List>
      </CardContent>
    </div>
  );
}
Example #18
Source File: LabelsMenu.js    From pomodor with MIT License 5 votes vote down vote up
LabelsMenu = ({ anchor }) => {
  const [anchorEl, setAnchorEl] = useState(anchor || null)

  const { data, labelSelected, menuOpened } = useSelector(
    (state) => state.labels
  )
  const dispatch = useDispatch()

  const theme = useTheme()
  const isMediumScreen = useMediaQuery(theme.breakpoints.up('md'))

  useEffect(() => {
    if (anchor) {
      setAnchorEl(anchor)
    }
  }, [anchor])

  const handleClose = (label) => {
    dispatch(setMenuOpened(false))

    if (label && label.id && label.name && label.color) {
      dispatch(setLabelSelected(label))
    }
  }

  const handleAdd = (e) => {
    e.stopPropagation()

    if (isMediumScreen) {
      dispatch(setDesktopDialog(true))
    } else {
      dispatch(setFullscreenDialog(true))
    }
  }

  return (
    <Menu
      id="long-menu"
      anchorEl={anchorEl}
      keepMounted
      open={menuOpened}
      onClose={handleClose}
      margin="dense"
    >
      {data.map((label) => (
        <LabelMenuItem
          key={label.id}
          selected={labelSelected && label.id === labelSelected.id}
          onClick={() => handleClose(label)}
          px={0}
          touchscreen={'ontouchstart' in document.documentElement ? 1 : 0}
        >
          <Label label={label} />
        </LabelMenuItem>
      ))}
      <MenuItem onClick={handleAdd}>
        <AddLabelIcon />
        Add new label
      </MenuItem>
    </Menu>
  )
}
Example #19
Source File: Chart.js    From management-center with Apache License 2.0 5 votes vote down vote up
Chart = ({ className, title, data, labels, dataDescriptions, ...rest }) => {
	const classes = useStyles();
	const theme = useTheme();

	const options = {
		animation: false,
		cutoutPercentage: 80,
		layout: { padding: 0 },
		legend: {
			display: false
		},
		maintainAspectRatio: false,
		responsive: true,
		tooltips: {
			backgroundColor: theme.palette.background.default,
			bodyFontColor: theme.palette.text.secondary,
			borderColor: theme.palette.divider,
			borderWidth: 1,
			enabled: true,
			footerFontColor: theme.palette.text.secondary,
			intersect: false,
			mode: 'index',
			titleFontColor: theme.palette.text.primary
		}
	};

	return (
		<Card className={clsx(classes.root, className)} {...rest}>
			<CardHeader title={title} />
			<Divider />
			<CardContent>
				<Box height={300} position="relative">
					<Doughnut data={data} options={options} />
				</Box>
				<Box display="flex" justifyContent="center" mt={2}>
					{dataDescriptions.map(({ color, icon: Icon, title, value }) => (
						<Box key={title} p={1} textAlign="center">
							<Icon color="action" />
							<Typography color="textPrimary" variant="body1">
								{title}
							</Typography>
							<Typography style={{ color }} variant="h3">
								{value}%
							</Typography>
						</Box>
					))}
				</Box>
			</CardContent>
		</Card>
	);
}
Example #20
Source File: NavBar.js    From inventory-management-web with MIT License 5 votes vote down vote up
NavBar = ({ mobileOpen, setMobileOpen, tabletOpen, setTabletOpen }) => {
  // used to check current url
  const location = useLocation();

  const theme = useTheme();
  // true if in tablet mode
  const tablet = useMediaQuery(theme.breakpoints.only('sm'));
  const mobile = useMediaQuery(theme.breakpoints.only('xs'));
  const isLoggedIn = location.pathname !== '/login';
  const classes = useStyles(isLoggedIn);

  const { expiryListBadge } = useContext(ExpiryListContext);

  // handle opening and closing of drawer
  const handleDrawerToggle = () => {
    if (tablet) {
      setTabletOpen(!tabletOpen);
    } else {
      setMobileOpen(!mobileOpen);
    }
  };

  return (
    <div className={classes.root}>
      <AppBar position='fixed'>
        <Toolbar>
          <Hidden mdUp>
            <IconButton
              edge='start'
              className={classes.menuButton}
              color='inherit'
              onClick={handleDrawerToggle}
            >
              {tabletOpen ? (
                <ChevronLeftIcon />
              ) : (
                <Badge
                  badgeContent={expiryListBadge}
                  color='primary'
                  overlap='circle'
                  className={classes.tabBadge}
                  invisible={!mobile}
                >
                  <MenuIcon />
                </Badge>
              )}
            </IconButton>
          </Hidden>
          <Typography variant='h6' className={classes.title}>
            Inventory Management Web App
          </Typography>

          <AlertDialog />
        </Toolbar>
      </AppBar>
    </div>
  );
}
Example #21
Source File: home.js    From js-miniapp with MIT License 5 votes vote down vote up
Home = (props: any) => {
  const classes = useStyles();
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('xs'));
  const [shrink, setShrink] = useState(false);
  const [showDrawer, setShowDrawer] = useState(!isMobile);
  useEffect(() => {
    setShowDrawer(!isMobile);
  }, [isMobile]);
  const onShrinkToggle = (shrinkState) => {
    setShrink(shrinkState);
  };
  const onDrawerToggle = (show) => {
    setShowDrawer(show);
  };
  return (
    <Router>
      <ToolBar
        showDrawer={showDrawer}
        onDrawerToggle={onDrawerToggle}
        onShrinkToggle={onShrinkToggle}
        navItems={navItems}
      ></ToolBar>
      <main
        data-testid="homepage-main-content"
        className={clsx(classes.mainContent, {
          [classes.mainContentMobile]: isMobile,
          [classes.drawerOpen]: !isMobile && showDrawer,
          [classes.drawerClosed]: !isMobile && !showDrawer,
          [classes.drawerOpenShrink]: !isMobile && shrink,
        })}
      >
        <Container className={classes.wrapperContainer}>
          <Routes>
            {navItems.map((it) => (
              <Route
                key={it.navLink}
                path={it.navLink}
                element={
                  it.element ??
                  (() => (
                    <div
                      data-testid="nav-routes"
                      style={{ fontSize: '32px', textAlign: 'center' }}
                    >
                      {it.label}
                    </div>
                  ))
                }
              ></Route>
            ))}
            <Route path="*" element={navItems[0].element}></Route>
          </Routes>
        </Container>
      </main>
    </Router>
  );
}
Example #22
Source File: PieChart.js    From gitlab-lint-react with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
WalletPieChart = ({ data, outerRadius }) => {
  const theme = useTheme();
  const RADIAN = Math.PI / 180;
  const renderCustomizedLabel = ({
    cx,
    cy,
    midAngle,
    innerRadius,
    outerRadius,
    index,
    name,
  }) => {
    const radius = 25 + innerRadius + (outerRadius - innerRadius);
    const x = cx + radius * Math.cos(-midAngle * RADIAN);
    const y = cy + radius * Math.sin(-midAngle * RADIAN);

    return (
      <text
        x={x}
        y={y}
        textAnchor={x > cx ? "start" : "end"}
        dominantBaseline="central"
        style={{ fill: theme.palette.secondary.main }}
      >
        {name}
      </text>
    );
  };

  return (
    <ResponsiveContainer>
      <PieChart>
        <Pie
          data={data}
          cx="50%"
          cy="50%"
          outerRadius={outerRadius}
          dataKey="value"
          label={renderCustomizedLabel}
        >
          {data.map((entry, index) => (
            <Cell
              key={`cell-${index}`}
              fill={chartColors[index % chartColors.length]}
            />
          ))}
        </Pie>
        <Tooltip content={<ChartTooltip />} />
      </PieChart>
    </ResponsiveContainer>
  );
}
Example #23
Source File: use-bar-data.js    From horondi_admin with MIT License 5 votes vote down vote up
useBarData = () => {
  const theme = useTheme();
  const barData = useSelector(({ Stats }) => Stats.bar);
  const date = useSelector(({ Stats }) => Stats.date);

  const { selectedValue } = barData;
  const { counts, labels } = barData[selectedValue];

  const mainData = {
    datasets: [
      {
        backgroundColor: theme.palette.secondary.main,
        data: counts,
        label: descriptions[selectedValue][days[date]],
        maxBarThickness: 17,
        categoryPercentage: 0.5
      }
    ],
    labels
  };

  const options = {
    animation: false,
    cornerRadius: 20,
    layout: { padding: 0 },
    legend: { display: false },
    maintainAspectRatio: false,
    responsive: true,
    scales: {
      xAxes: [
        {
          ticks: {
            fontColor: theme.palette.text.secondary
          },
          gridLines: {
            display: false,
            drawBorder: false
          }
        }
      ],
      yAxes: [
        {
          ticks: {
            fontColor: theme.palette.text.secondary,
            beginAtZero: true,
            min: 0,
            stepSize: 1,
            callback: (value) => (Number.isInteger(value) ? value : false)
          },
          gridLines: {
            borderDash: [2],
            borderDashOffset: [2],
            color: theme.palette.divider,
            drawBorder: false,
            zeroLineBorderDash: [2],
            zeroLineBorderDashOffset: [2],
            zeroLineColor: theme.palette.divider
          }
        }
      ]
    },
    tooltips: {
      backgroundColor: theme.palette.background.default,
      bodyFontColor: theme.palette.text.secondary,
      borderColor: theme.palette.divider,
      borderWidth: 1,
      enabled: true,
      footerFontColor: theme.palette.text.secondary,
      intersect: false,
      mode: 'index',
      titleFontColor: theme.palette.text.primary
    }
  };

  return { mainData, options };
}
Example #24
Source File: Drawer.js    From covid-trials-dashboard with MIT License 5 votes vote down vote up
CustomDrawer = () => {
  const [open, setOpen] = useState(false)
  const theme = useTheme()
  const classes = useStyles()

  const handleOpen = () => setOpen(true)
  const handleClose = () => setOpen(false)
  return (
    <div>
      <IconButton
        onClick={handleOpen}
        edge='start'
        color='inherit'
        aria-label='menu'
      >
        <MenuIcon />
      </IconButton>
      <Drawer
        open={open}
        onClose={handleClose}
        variant='temporary'
        anchor={theme.direction === 'rtl' ? 'right' : 'left'}
        ModalProps={{
          keepMounted: true, // Better open performance on mobile.
        }}
      >
        <div className={classes.drawer}>
          <List>
            <ThemeToogleListItem />
            <LanguageSelector />
            {drawerLinks.map(({ name, url, Icon }) => (
              <ListItem
                button
                component='a'
                href={url}
                target='__blank'
                key={name}
              >
                {Icon && (
                  <ListItemIcon>
                    <Icon />
                  </ListItemIcon>
                )}
                <ListItemText primary={name} />
              </ListItem>
            ))}
          </List>
          <FilterList />
        </div>
      </Drawer>
    </div>
  )
}
Example #25
Source File: Landing.js    From Portfolio with MIT License 5 votes vote down vote up
export default function Landing() {

    const classes = useStyles();
    const theme = useTheme();
    const mdDown = useMediaQuery(theme.breakpoints.down('sm'));

    return (
        <Grid container justify="center" alignItems="center" className={classes.cont}>
            <Grid item xs={12} lg={6}>
                <Typography variant={mdDown ? "h2" : "h1"}>
                    {landing.title}
                </Typography>
                <Typography variant={mdDown ? "h5" : "h4"} component="h2" className={classes.subtitle}>

                    <ReactTyped
                        strings={landing.subtitles}
                        typeSpeed={40}
                        backSpeed={50}
                        loop
                    />
                </Typography>
                <Grid container direction="row" spacing={2}>
                    {
                        professionalDetails.map(({ alt, icon, link }, i) =>
                            <Grid item key={i}>
                                <a href={link} target="_blank" rel="noopener noreferrer">
                                    <Zoom in={true} style={{ transitionDelay: `${100 * i}ms` }}>
                                        <Tooltip title={alt} placement="top">
                                            <Avatar variant="rounded" className={clsx([classes.avatar, classes[alt]])}>
                                                {icon}
                                            </Avatar>
                                        </Tooltip>
                                    </Zoom>
                                </a>
                            </Grid>
                        )
                    }
                </Grid>
            </Grid>

            <Hidden mdDown>
                <Fade in={true} style={{ transitionDelay: '100ms' }}>
                    <Grid item lg={6}>
                        <Image
                            src="/landing.svg"
                            alt="Landing"
                            width="900.94"
                            height="787"
                        />
                    </Grid>
                </Fade>
            </Hidden>
        </Grid>
    )
}
Example #26
Source File: Legend.jsx    From covid-trials-dashboard with MIT License 5 votes vote down vote up
Legend = props => {
  const { items = legendProps, onChange, selected } = props
  const classes = legendStyles(props)
  const theme = useTheme()
  const selectedStyles = {
    textDecoration: 'underline',
    fontWeight: theme.typography.fontWeightBold,
    color: theme.palette.text.primary,
  }
  return (
    <div className={classes.root}>
      <Breadcrumbs
        itemsBeforeCollapse={Infinity}
        separator='>'
        aria-label='breadcrumb'
      >
        {items.map(item => (
          <BigFontTooltip
            onClick={() => onChange(item)}
            key={item.id}
            title={item.info}
          >
            <div
              className={classes.item}
              style={
                selected && item.id === selected.id ? selectedStyles : null
              }
            >
              <div
                className={classes.square}
                style={{ backgroundColor: item.color }}
              />
              <Typography color='inherit'>{item.label}</Typography>
            </div>
          </BigFontTooltip>
        ))}
      </Breadcrumbs>
    </div>
  )
}
Example #27
Source File: TrafficByDevice.js    From EMP with MIT License 4 votes vote down vote up
TrafficByDevice = () => {
  // const classes = useStyles();
  const theme = useTheme();

  const data = {
    datasets: [
      {
        data: [63, 15, 22],
        backgroundColor: [
          colors.indigo[500],
          colors.red[600],
          colors.orange[600]
        ],
        borderWidth: 8,
        borderColor: colors.common.white,
        hoverBorderColor: colors.common.white
      }
    ],
    labels: ['Desktop', 'Tablet', 'Mobile']
  };

  const options = {
    animation: false,
    cutoutPercentage: 80,
    layout: { padding: 0 },
    legend: {
      display: false
    },
    maintainAspectRatio: false,
    responsive: true,
    tooltips: {
      backgroundColor: theme.palette.background.default,
      bodyFontColor: theme.palette.text.secondary,
      borderColor: theme.palette.divider,
      borderWidth: 1,
      enabled: true,
      footerFontColor: theme.palette.text.secondary,
      intersect: false,
      mode: 'index',
      titleFontColor: theme.palette.text.primary
    }
  };

  const devices = [
    {
      title: 'Desktop',
      value: 63,
      icon: LaptopMacIcon,
      color: colors.indigo[500]
    },
    {
      title: 'Tablet',
      value: 15,
      icon: TabletIcon,
      color: colors.red[600]
    },
    {
      title: 'Mobile',
      value: 23,
      icon: PhoneIcon,
      color: colors.orange[600]
    }
  ];

  return (
    <Card>
      <CardHeader title="Traffic by Device" />
      <Divider />
      <CardContent>
        <Box
          height={300}
          position="relative"
        >
          <Doughnut
            data={data}
            options={options}
          />
        </Box>
        <Box
          display="flex"
          justifyContent="center"
          mt={2}
        >
          {devices.map(({
            color,
            icon: Icon,
            title,
            value
          }) => (
            <Box
              key={title}
              p={1}
              textAlign="center"
            >
              <Icon color="action" />
              <Typography
                color="textPrimary"
                variant="body1"
              >
                {title}
              </Typography>
              <Typography
                style={{ color }}
                variant="h2"
              >
                {value}
                %
              </Typography>
            </Box>
          ))}
        </Box>
      </CardContent>
    </Card>
  );
}
Example #28
Source File: Popup.js    From covid-trials-dashboard with MIT License 4 votes vote down vote up
PopUpDisplay = ({ popupInfo, onClose }) => {
  const [learnMoreOpen, setLearnMoreOpen] = useState(false)
  const theme = useTheme()
  const isPopupAndClicked = popupInfo && popupInfo.clickedLocation.lng
  const handleClick = () => {
    ReactGA.event({
      category: 'volunteer',
      action: 'How to volunteer clicked',
      label: 'Popup button, how to volunteer',
    })
    setLearnMoreOpen(!learnMoreOpen)
  }
  useEffect(() => {
    setLearnMoreOpen(false)
  }, [isPopupAndClicked])
  const { t } = useTranslation('mapPopup')

  if (popupInfo) {
    const {
      clickedLocation,
      phase,
      preferredName,
      registryLink,
      acceptsHealthySubjects,
      contact = [{}],
      sponsors,
    } = popupInfo
    const participation = contact[0]
    const sponsorNames = sponsors.map(sponsor => sponsor.sponsorName).join(', ')
    const sponsorPlural =
      sponsors.length > 1 ? t('sponsorPlural') : t('sponsorPlural')
    const firstSponsor = sponsors[0] && sponsors[0].sponsorName
    const StyledPopup = styled(Popup)`
      .mapboxgl-popup-content {
        padding: 0px;
        user-select: text;
        cursor: text;
      }
      .mapboxgl-popup-close-button {
        color: ${theme.palette.text.primary};
        font-size: ${theme.typography.fontSize};
      }
      .MuiPaper-root {
        min-width: 10rem !important;
      }
      @media only screen and (max-width: 601px) {
        .MuiPaper-root {
          max-width: 15rem !important;
        }
      }
      .MuiCardContent-root:last-child {
        padding-bottom: 2px;
      }
    `
    return (
      <StyledPopup
        tipSize={5}
        anchor='top'
        longitude={clickedLocation.lng}
        latitude={clickedLocation.lat}
        closeOnClick={false}
        onClose={onClose}
      >
        <Card style={{ maxWidth: '26rem', minWidth: '20rem' }}>
          {learnMoreOpen ? (
            <>
              <CardContent>
                {participation.name && (
                  <DisplayField
                    alwaysShow
                    label={t('name')}
                    content={participation.name}
                  />
                )}
                {participation.website && (
                  <DisplayField
                    label={t('website')}
                    alwaysShow
                    content={
                      <Link
                        onClick={() =>
                          ReactGA.event({
                            category: 'volunteer website',
                            action: 'Volunteer website link clicked',
                            label: `${participation.website} clicked`,
                          })
                        }
                        href={participation.website}
                        target='_blank'
                        rel='noopener noreferrer'
                        style={{
                          color: theme.palette.primary.main,
                          textDecoration: 'underline',
                        }}
                      >
                        {participation.website}
                      </Link>
                    }
                  />
                )}
                {participation.email && (
                  <DisplayField
                    alwaysShow
                    label={t('email')}
                    content={
                      <DontBreakOutLink
                        onClick={() =>
                          ReactGA.event({
                            category: 'email link',
                            action: 'Volunteer email link clicked',
                            label: `${participation.email} clicked`,
                          })
                        }
                        href={`mailto:${participation.email}?subject=I am interested in volunteering for your clinical trial&body=Hello,%0d%0dI found your study on www.coviddash.org and I am interested in participating in your clinical trial for a COVID-19 vaccine. I am a healthy subject who has not had COVID-19 and is not experiencing COVID-19 symptoms. I am located in ((ENTER CITY)) and can be reached at this email. Please let me know the next steps for potentially being screened and enrolled in this study.`}
                        target='_blank'
                        rel='noopener noreferrer'
                        style={{
                          color: theme.palette.primary.main,
                          textDecoration: 'underline',
                        }}
                      >
                        {participation.email}
                      </DontBreakOutLink>
                    }
                  />
                )}
                <DisplayField
                  label={t('phoneNumber')}
                  alwaysShow
                  content={participation.phone}
                />
                {participation.notes && (
                  <DisplayField
                    label={t('notes')}
                    content={participation.notes}
                    alwaysShow
                  />
                )}
              </CardContent>
              <CardActions>
                <Button onClick={handleClick} variant='contained'>
                  {t('backToDetails')}
                </Button>
              </CardActions>
            </>
          ) : (
            <CardContent>
              <DisplayField
                // alwaysShow
                label={t('acceptsHealthyVolunteers')}
                content={
                  acceptsHealthySubjects === 'Yes' ? (
                    <Box
                      color='success.main'
                      style={{ display: 'flex', alignItems: 'center' }}
                    >
                      <CheckCircleIcon style={{ paddingRight: '2px' }} />
                      {t('yes')}
                    </Box>
                  ) : (
                    t('no')
                  )
                }
              />
              <DisplayField label={`${sponsorPlural}`} content={sponsorNames} />
              <DisplayField
                onlyMobile
                label={t('trialSponsor')}
                content={firstSponsor}
              />
              <DisplayField label={t('product')} content={preferredName} />
              <DividerWithMargin />
              <DisplayField label={t('phase')} content={phase} alwaysShow />
              {registryLink && (
                <DisplayField
                  label={t('trialRegistryLinks')}
                  alwaysShow
                  content={
                    Array.isArray(registryLink) ? (
                      registryLink.map((link, index) => (
                        <Link
                          key={`${link}${index}`}
                          onClick={() =>
                            ReactGA.event({
                              category: 'Trial Registry Link',
                              action: 'Trial Registry link clicked',
                              label: `Trial Registry ${link} clicked`,
                            })
                          }
                          href={link}
                          target='_blank'
                          rel='noopener noreferrer'
                          style={{
                            color: theme.palette.primary.main,
                            textDecoration: 'underline',
                            marginRight: '5px',
                          }}
                        >
                          {index > 0 ? `Link ${index + 1}` : 'Link'}
                        </Link>
                      ))
                    ) : (
                      <Link
                        onClick={() =>
                          ReactGA.event({
                            category: 'Trial Registry Link',
                            action: 'Trial Registry link clicked',
                            label: `Trial Registry ${registryLink} clicked`,
                          })
                        }
                        href={registryLink}
                        target='_blank'
                        rel='noopener noreferrer'
                        style={{
                          color: theme.palette.primary.main,
                          textDecoration: 'underline',
                        }}
                      >
                        {t('clickHere')}
                      </Link>
                    )
                  }
                />
              )}
              <CardActions>
                <Button
                  onClick={handleClick}
                  variant='contained'
                  color='secondary'
                >
                  {t('howToVolunteer')}
                </Button>
              </CardActions>
            </CardContent>
          )}
        </Card>
      </StyledPopup>
    )
  }
  return null
}
Example #29
Source File: Drawer.js    From inventory-management-web with MIT License 4 votes vote down vote up
function NavDrawer({ mobileOpen, setMobileOpen, tabletOpen }) {
  const classes = useStyles({ tab: tabletOpen });
  const theme = useTheme();
  // true if in tablet mode
  const tablet = useMediaQuery(theme.breakpoints.only('sm'));

  // links and labels for each link in drawer
  const [list, setList] = useState({
    links: ['/', '/inventory', '/transaction'],
    labels: ['Home', 'Inventory', 'Transactions'],
  });

  // function to handle drawer state on mobile
  const handleDrawerToggle = () => {
    setMobileOpen(!mobileOpen);
  };
  // array of drawer icons
  const listIcons = [
    <HomeIcon className={classes.icons} />,
    <ListIcon className={classes.icons} />,
    <PersonIcon className={classes.icons} />,
    <ReceiptIcon className={classes.icons} />,
  ];

  useEffect(() => {
    // Add Admin protected links to the list only if isStaff is true
    const isAdmin = localStorage.getItem('isStaff');
    if (isAdmin === 'true') {
      setList({
        labels: ['Home', 'Inventory', 'Employees', 'Transactions'],
        links: ['/', '/inventory', '/employee', '/transaction'],
      });
    }
  }, []);

  const { expiryListBadge, setExpiryListBadge, update } = useContext(
    ExpiryListContext
  );

  const history = useHistory();

  const apiFetch = async () => {
    try {
      const response = await getEndPoint('/api/explist/', null, history);
      const { data } = response;
      setExpiryListBadge(data.count);
    } catch (e) {
      console.log(e);
    }
  };

  // call API on component load
  useEffect(() => {
    apiFetch();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [update]);

  const drawer = (
    <div>
      <List>
        {list.labels.map((text, index) => (
          <Link
            to={list.links[index]}
            className={classes.link}
            key={text}
            onClick={handleDrawerToggle}
          >
            <ListItem button key={text}>
              <ListItemIcon className={classes.listIcon}>
                <Badge
                  badgeContent={expiryListBadge}
                  color='primary'
                  overlap='circle'
                  className={classes.tabBadge}
                  invisible={!(text === 'Inventory' && !tabletOpen && tablet)}
                >
                  {listIcons[index]}
                </Badge>
              </ListItemIcon>
              <Badge
                badgeContent={expiryListBadge}
                color='primary'
                overlap='circle'
                className={classes.badge}
                invisible={text !== 'Inventory'}
              >
                <ListItemText primary={text} className={classes.listText} />
              </Badge>
            </ListItem>
          </Link>
        ))}
      </List>
    </div>
  );

  return (
    <nav className={classes.drawer}>
      <Hidden smUp>
        <Drawer
          variant='temporary'
          open={mobileOpen}
          onClose={handleDrawerToggle}
          classes={{
            paper: classes.drawerPaper,
          }}
          ModalProps={{
            keepMounted: true, // Better open performance on mobile.
          }}
        >
          <div className={classes.drawerHeader}>
            <IconButton onClick={handleDrawerToggle}>
              <ChevronLeftIcon />
            </IconButton>
          </div>
          {drawer}
        </Drawer>
      </Hidden>
      <Hidden xsDown>
        <Drawer
          classes={{
            paper: classes.drawerPaper,
          }}
          variant='permanent'
          open
        >
          <div className={classes.toolbar} />
          {drawer}
        </Drawer>
      </Hidden>
    </nav>
  );
}