@material-ui/core#CardActionArea TypeScript Examples

The following examples show how to use @material-ui/core#CardActionArea. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.tsx    From react-app-architecture with Apache License 2.0 6 votes vote down vote up
export function AuthorPlaceholder({
  width = 40,
  height = 40,
}: {
  width?: number;
  height?: number;
}): ReactElement {
  const classes = useStyles();
  return (
    <div className={classes.author}>
      <CardActionArea>
        <CardHeader
          avatar={<Skeleton variant="circle" width={width} height={height} />}
          title={<Skeleton height={width / 2.5} width="80%" />}
          subheader={<Skeleton height={width / 2.5} width="40%" />}
        />
      </CardActionArea>
    </div>
  );
}
Example #2
Source File: index.tsx    From react-app-architecture with Apache License 2.0 6 votes vote down vote up
ReasourceCard = ({
  href,
  imgUrl,
  title,
  description,
  action,
}: {
  href: string;
  imgUrl: string;
  title: string;
  description: string;
  action: string;
}) => {
  const classes = useStyles();
  return (
    <Card className={classes.card} raised={true} elevation={4}>
      <CardActionArea href={href} target="_blank">
        <CardMedia component="img" alt={title} src={imgUrl} title={title} />
        <CardContent>
          <Typography variant="h6" component="h2">
            {title}
          </Typography>
          <Typography variant="body2" color="textSecondary" component="p">
            {description}
          </Typography>
        </CardContent>
      </CardActionArea>
      <CardActions>
        <Button component="a" size="small" color="primary" href={href} target="_blank">
          {action}
        </Button>
      </CardActions>
    </Card>
  );
}
Example #3
Source File: Card.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
Card: FunctionComponent<Props> = (props: PropsWithChildren<Props>) => {
  const {
    title,
    createdAt,
    updatedAt,
    prUrl,
    authorName,
    authorAvatar,
    repositoryName,
    children,
  } = props;

  return (
    <Box marginBottom={1}>
      <Paper variant="outlined">
        <CardActionArea href={prUrl} target="_blank">
          <Box padding={1}>
            <CardHeader
              title={title}
              createdAt={createdAt}
              updatedAt={updatedAt}
              authorName={authorName}
              authorAvatar={authorAvatar}
              repositoryName={repositoryName}
            />
            {children}
          </Box>
        </CardActionArea>
      </Paper>
    </Box>
  );
}
Example #4
Source File: index.tsx    From react-app-architecture with Apache License 2.0 5 votes vote down vote up
BlogCard = ({
  blog,
  selection,
}: {
  blog: Blog;
  selection?: (blog: Blog) => void;
}): ReactElement => {
  const classes = useStyles();

  const { title, description, author, imgUrl, blogUrl, publishedAt } = blog;

  return (
    <Card
      className={classes.card}
      raised={true}
      onClick={() => {
        selection && selection(blog);
      }}
    >
      <CardActionArea className={classes.cardContent} component={Link} to={'/blog/' + blogUrl}>
        <CardMedia
          className={classes.cardMedia}
          component="img"
          alt={title}
          src={imgUrl}
          title={title}
        />
        <CardContent>
          <Typography variant="h6" component="h2" className={classes.cardTitle}>
            {title}
          </Typography>
          <Typography
            variant="body2"
            color="textSecondary"
            component="p"
            className={classes.cardDescription}
          >
            {description}
          </Typography>
        </CardContent>
        <CardHeader
          className={classes.cardAuthor}
          avatar={
            author.profilePicUrl ? (
              <Avatar aria-label={author.name} src={author.profilePicUrl} />
            ) : (
              <FirstLetter text={author.name} />
            )
          }
          title={author.name}
          subheader={convertToReadableDate(publishedAt)}
        />
      </CardActionArea>
    </Card>
  );
}
Example #5
Source File: index.tsx    From react-app-architecture with Apache License 2.0 5 votes vote down vote up
export default function BlogPage(): ReactElement {
  const classes = useStyles();
  const match = useRouteMatch<{ endpoint: string }>();
  const { data, isFetching, message } = useStateSelector((state) => state.blogState);
  const dispatch = useDispatch();

  useEffect(() => {
    const endpoint = match.params.endpoint;
    if (endpoint)
      if (!data) {
        dispatch(fetchBlogByEndpoint(endpoint));
      } else if (data.blogUrl !== endpoint) {
        dispatch(clearPage.action(endpoint));
        dispatch(fetchBlogByEndpoint(endpoint));
      }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [match.params.endpoint]);

  const authorView = data ? (
    <div className={classes.author}>
      <CardActionArea>
        <CardHeader
          avatar={
            data.author.profilePicUrl ? (
              <Avatar aria-label={data.author.name} src={data.author.profilePicUrl} />
            ) : (
              <FirstLetter text={data.author.name} />
            )
          }
          title={data.author.name}
          subheader={convertToReadableDate(data.publishedAt)}
        />
      </CardActionArea>
    </div>
  ) : null;

  return (
    <div className={classes.root}>
      {isFetching && <LinearProgress />}
      <Grid container justify="center">
        <Grid item xs={12} sm={12} md={8} className={classes.blogContent}>
          {isFetching ? <AuthorPlaceholder /> : authorView}
          {isFetching ? (
            <Skeleton variant="rect" height={600} />
          ) : (
            data && data.text && <Markdown text={data.text} />
          )}
        </Grid>
      </Grid>
      {message && (
        <Snackbar
          message={message.text}
          variant={message.type}
          onClose={() => dispatch(removeMessage.action())}
        />
      )}
    </div>
  );
}
Example #6
Source File: ProjectCard.tsx    From backstage with Apache License 2.0 5 votes vote down vote up
ProjectCard = ({
  project,
  fetchBazaarProjects,
  catalogEntities,
}: Props) => {
  const classes = useStyles();
  const [openCard, setOpenCard] = useState(false);
  const { id, name, status, updatedAt, description, membersCount } = project;

  const handleClose = () => {
    setOpenCard(false);
    fetchBazaarProjects();
  };

  return (
    <div>
      <Dialog fullWidth onClose={handleClose} open={openCard}>
        <HomePageBazaarInfoCard
          initProject={project}
          handleClose={handleClose}
          initEntity={catalogEntities[0] || null}
        />
      </Dialog>

      <Card key={id}>
        <CardActionArea onClick={() => setOpenCard(true)}>
          <ItemCardHeader
            classes={{ root: classes.header }}
            title={
              <Typography noWrap variant="h6" component="h4">
                {name}
              </Typography>
            }
            subtitle={`updated ${DateTime.fromISO(
              new Date(updatedAt!).toISOString(),
            ).toRelative({
              base: DateTime.now(),
            })}`}
          />
          <CardContent className={classes.content}>
            <StatusTag styles={classes.statusTag} status={status} />
            <Typography variant="body2" className={classes.memberCount}>
              {Number(membersCount) === Number(1)
                ? `${membersCount} member`
                : `${membersCount} members`}
            </Typography>
            <Typography variant="body2" className={classes.description}>
              {description}
            </Typography>
          </CardContent>
        </CardActionArea>
      </Card>
    </div>
  );
}
Example #7
Source File: AppDynamicPage.tsx    From clearflask with Apache License 2.0 5 votes vote down vote up
LandingLink = (props: {
  server: Server,
  config?: Client.Config;
  link?: Client.LandingLink;
  openInNew?: boolean;
}) => {
  const classes = useStyles();
  const { t } = useTranslation('app');

  if (!props.link) return null;
  var linkToPage = !props.link.linkToPageId ? undefined
    : props.config?.layout.pages.find(p => p.pageId === props.link?.linkToPageId);
  var linkToSlug = linkToPage?.slug;
  var linkUrl = props.link.url;
  if (linkToSlug !== undefined && props.openInNew && props.config) {
    linkUrl = `${getProjectLink(props.config)}/${linkToSlug}`;
    linkToSlug = undefined;
  }
  var linkProps: object | undefined;
  if (linkToSlug) {
    linkProps = {
      component: Link,
      to: preserveEmbed(`/${linkToSlug}`),
    };
  } else if (linkUrl) {
    linkProps = {
      component: 'a',
      color: 'inherit',
      href: linkUrl,
      underline: 'none',
      rel: 'noreferrer noopener',
      ...(props.openInNew ? { target: '_blank' } : {}),
    };
  } else {
    return null;
  }

  const icon: string | undefined = props.link.icon || linkToPage?.icon;

  return (
    <CardActionArea
      key={`${props.link.linkToPageId || props.link.url}`}
      className={classes.landingPaper}
      {...linkProps}
    >
      {!!icon && (
        <DynamicMuiIcon
          name={icon}
          className={classes.landingLinkIcon}
          color='inherit'
          fontSize='inherit'
        />
      )}
      {!!props.link.title && (
        <Typography variant='h5' component='h2' className={classes.landingLinkTitle}>{t(props.link.title as any)}</Typography>
      )}
      {!!props.link.description && (
        <Typography variant='body1' component='div' className={classes.landingLinkDescription}>{t(props.link.description as any)}</Typography>
      )}
      <GoIcon
        className={classes.landingLinkGo}
        color='inherit'
        fontSize='inherit'
      />
    </CardActionArea>
  );
}
Example #8
Source File: CreatePage.tsx    From clearflask with Apache License 2.0 5 votes vote down vote up
TemplateCard = (props: {
  icon?: OverridableComponent<SvgIconTypeMap>,
  className?: string;
  title: string;
  content: string | React.ReactNode;
  disabled?: boolean;
  onClick: () => void;
}) => {
  const classes = useStyles();
  const Icon = props.icon;
  return (
    <HoverArea>
      {(hoverAreaProps, isHovering, isHoverDisabled) => (
        <Card {...hoverAreaProps} elevation={0} className={classNames(
          props.className,
          classes.box,
          isHovering && classes.boxSelected,
          props.disabled && classes.disabled,
        )}>
          <CardActionArea
            onClick={props.onClick}
            disabled={props.disabled}
            className={classNames(classes.flexGrow)}
          >
            {!!Icon && (
              <Icon fontSize='inherit' color='inherit' className={classNames(
                classes.cardIcon,
                isHovering && classes.cardIconSelected,
              )} />
            )}
            <CardHeader
              title={props.title}
              titleTypographyProps={{ align: 'center' }}
              subheaderTypographyProps={{ align: 'center' }}
            />
            {!!props.content && (
              <CardContent>{props.content}</CardContent>
            )}
          </CardActionArea>
        </Card>
      )}
    </HoverArea>
  );
}
Example #9
Source File: DashboardQuickActions.tsx    From clearflask with Apache License 2.0 5 votes vote down vote up
QuickActionArea = (props: {
  droppableId: string;
  isDragging: boolean;
  feedback?: FeedbackInstance | null;
  enabled?: boolean;
  onClick?: (droppableId: string) => Promise<any>;
  color?: string;
  title?: string;
}) => {
  const { t } = useTranslation('app');
  const theme = useTheme();
  const classes = useStyles();
  const [autoDragging, setAutoDragging] = useState<boolean>(false);
  return (
    <RenderControl freezeInitialRender={props.isDragging}>
      <HoverArea>
        {(hoverAreaProps, isHovering, isHoverDown) => (
          <Droppable
            droppableId={props.droppableId}
            ignoreContainerClipping
            isDropDisabled={!props.enabled || (!isHovering && !autoDragging)}
          >
            {(provided, snapshot) => (
              <CardActionArea
                {...hoverAreaProps}
                ref={provided.innerRef}
                {...provided.droppableProps}
                disabled={!props.enabled}
                className={classNames(
                  classes.postAction,
                  !props.enabled && classes.postActionDisabled,
                )}
                style={!props.enabled ? {
                  color: theme.palette.text.disabled,
                } : {
                  color: props.color,
                  borderColor: props.color || fade(theme.palette.common.black, 0.54),
                  background: !snapshot.isDraggingOver ? undefined : fade(props.color || theme.palette.common.black, 0.1),
                }}
                onClick={async e => {
                  if (!props.enabled || !props.onClick) return;
                  setAutoDragging(true);
                  try {
                    await props.onClick(props.droppableId);
                  } finally {
                    setAutoDragging(false);
                  }
                }}
              >
                {provided.placeholder && (<div style={{ display: 'none' }}>{provided.placeholder}</div>)}
                {props.title && (
                  <Typography>{t(props.title as any)}</Typography>
                )}
              </CardActionArea>
            )}
          </Droppable>
        )}
      </HoverArea>
    </RenderControl>
  );
}
Example #10
Source File: DemoContent.tsx    From mo360-ftk with MIT License 5 votes vote down vote up
public render(): JSX.Element {
    const { classes } = this.props;

    return (
      <Container>
        <Typography variant={'h5'} gutterBottom={true} align="center">
          {this.i18n.translateToString('HeadlineDemoContent')}
        </Typography>
        <Grid container spacing={3}>
          <Grid item xs={12} md={6}>
            <Card className={classes.card}>
              <CardActionArea
                href="https://github.com/Daimler/mo360-ftk/tree/master/docs"
                target="_blank"
                className={classes.cardAction}
              >
                <CardMedia className={classes.media} component="img" image={Logo} />
                <CardContent className={classes.cardContent}>
                  <Typography variant="h6">Documentation</Typography>
                </CardContent>
              </CardActionArea>
            </Card>
          </Grid>
          <Grid item xs={12} md={6}>
            <Card className={classes.card}>
              <CardActionArea
                href="https://github.com/Daimler/mo360-ftk"
                target="_blank"
                className={classes.cardAction}
              >
                <CardMedia className={classes.media} component="img" image={LogoGithub} />
                <CardContent className={classes.cardContent}>
                  <Typography variant="h6">Sources @ GitHub</Typography>
                </CardContent>
              </CardActionArea>
            </Card>
          </Grid>
        </Grid>
        <Box m={3} className={classes.centered}>
          <Button variant="contained" color="secondary" onClick={() => this.router.navigateToHome()}>
            {this.i18n.translateToString('BackToHome')}
          </Button>
        </Box>
      </Container>
    );
  }
Example #11
Source File: index.tsx    From react-app-architecture with Apache License 2.0 4 votes vote down vote up
export default function Header(): ReactElement {
  const classes = useStyles();
  const history = useHistory();
  const { isLoggedIn, data: authData } = useStateSelector(({ authState }) => authState);
  const user = authData?.user;

  const isWriter = checkRole(user, Roles.WRITER);
  const isEditor = checkRole(user, Roles.EDITOR);

  const [openAuthDialog, setOpenAuthDialog] = useState(false);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [popupMoreAnchorEl, setPopupMoreAnchorEl] = useState<HTMLElement | null>(null);
  const isPopupMenuOpen = Boolean(popupMoreAnchorEl);
  const dispatch = useDispatch();

  function handlePopupMenuClose() {
    setPopupMoreAnchorEl(null);
  }

  function handlePopupMenuOpen(event: MouseEvent<HTMLElement>) {
    setPopupMoreAnchorEl(event.currentTarget);
  }

  function toggleDrawer() {
    setDrawerOpen(!drawerOpen);
  }

  const renderProfileView = (onClick: (event: MouseEvent<HTMLButtonElement>) => void) => {
    if (!user) return null;
    return (
      <CardActionArea onClick={onClick}>
        {user.profilePicUrl ? (
          <CardHeader
            title={user.name.split(' ')[0]}
            avatar={
              <Avatar className={classes.avatar} aria-label={user.name} src={user.profilePicUrl} />
            }
          />
        ) : (
          <CardHeader title={user.name.split(' ')[0]} avatar={<FirstLetter text={user.name} />} />
        )}
      </CardActionArea>
    );
  };

  const popupMenuId = 'menu-popup';
  const popupMenu = (
    <Menu
      anchorEl={popupMoreAnchorEl}
      anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
      id={popupMenuId}
      keepMounted
      transformOrigin={{ vertical: 'top', horizontal: 'right' }}
      open={isPopupMenuOpen}
      onClose={handlePopupMenuClose}
      PopoverClasses={{ paper: classes.paper }}
    >
      {isLoggedIn && renderProfileView(handlePopupMenuClose)}
      {isWriter && (
        <MenuItem
          className={classes.menuItem}
          onClick={() => {
            history.push('/write/blog');
            handlePopupMenuClose();
          }}
        >
          <IconButton color="inherit">
            <CreateIcon />
          </IconButton>
          <p>Write Blog</p>
        </MenuItem>
      )}
      {isWriter && (
        <MenuItem
          className={classes.menuItem}
          onClick={() => {
            history.push('/writer/blogs');
            handlePopupMenuClose();
          }}
        >
          <IconButton color="inherit">
            <ListIcon />
          </IconButton>
          <p>My Blogs</p>
        </MenuItem>
      )}
      {isEditor && (
        <MenuItem
          className={classes.menuItem}
          onClick={() => {
            history.push('/editor/blogs');
            handlePopupMenuClose();
          }}
        >
          <IconButton color="inherit">
            <SupervisorAccountIcon />
          </IconButton>
          <p>Blogs Admin</p>
        </MenuItem>
      )}
      {isLoggedIn && (
        <MenuItem
          className={classes.menuItem}
          onClick={() => {
            dispatch(logout());
            handlePopupMenuClose();
          }}
        >
          <IconButton color="inherit">
            <SvgIcon>
              <path d={mdiLogout} />
            </SvgIcon>
          </IconButton>
          <p>Logout</p>
        </MenuItem>
      )}
    </Menu>
  );

  const mobileDrawerMenu = (
    <Drawer anchor="top" open={drawerOpen} onClose={toggleDrawer}>
      {isLoggedIn && renderProfileView(toggleDrawer)}
      <List component="nav">
        {[
          {
            title: 'About Project',
            href: 'https://github.com/afteracademy/react-app-architecture',
            icon: <InfoIcon />,
          },
          {
            title: 'Contact',
            href: 'https://github.com/afteracademy/react-app-architecture/issues',
            icon: <EmailIcon />,
          },
        ].map(({ title, href, icon }, position) => (
          <ListItem
            key={position}
            className={classes.drawerItem}
            button
            href={href}
            target="_blank"
            onClick={toggleDrawer}
            component="a"
          >
            <ListItemIcon className={classes.drawerIcon}>{icon}</ListItemIcon>
            <ListItemText primary={title} />
          </ListItem>
        ))}
        {[{ title: 'Blogs', link: '/blogs', icon: <WebIcon /> }].map(
          ({ title, link, icon }, position) => (
            <ListItem
              key={position}
              className={classes.drawerItem}
              button
              component={Link}
              to={link}
              onClick={toggleDrawer}
            >
              <ListItemIcon className={classes.drawerIcon}>{icon}</ListItemIcon>
              <ListItemText primary={title} />
            </ListItem>
          ),
        )}
        {isWriter && <Divider />}
        {isWriter &&
          [
            { title: 'Write Blog', link: '/write/blog', icon: <CreateIcon /> },
            { title: 'My Blogs', link: '/writer/blogs', icon: <WebIcon /> },
          ].map(({ title, link, icon }, position) => (
            <ListItem
              key={position}
              className={classes.drawerItem}
              button
              component={Link}
              to={link}
              onClick={toggleDrawer}
            >
              <ListItemIcon className={classes.drawerIcon}>{icon}</ListItemIcon>
              <ListItemText primary={title} />
            </ListItem>
          ))}
        <Divider />
        {isEditor && <Divider />}
        {isEditor &&
          [{ title: 'Blog Admin', link: '/editor/blogs', icon: <SupervisorAccountIcon /> }].map(
            ({ title, link, icon }, position) => (
              <ListItem
                key={position}
                className={classes.drawerItem}
                button
                component={Link}
                to={link}
                onClick={toggleDrawer}
              >
                <ListItemIcon className={classes.drawerIcon}>{icon}</ListItemIcon>
                <ListItemText primary={title} />
              </ListItem>
            ),
          )}
        {isLoggedIn && (
          <ListItem
            className={classes.drawerItem}
            onClick={() => {
              dispatch(logout());
              toggleDrawer();
            }}
            button
          >
            <ListItemIcon className={classes.drawerIcon}>
              <SvgIcon>
                <path d={mdiLogout} />
              </SvgIcon>
            </ListItemIcon>
            <ListItemText primary="Logout" />
          </ListItem>
        )}
        {!isLoggedIn && (
          <ListItem
            className={classes.drawerItem}
            onClick={() => {
              setOpenAuthDialog(true);
              toggleDrawer();
            }}
            button
          >
            <ListItemIcon className={classes.drawerIcon}>
              <SvgIcon>
                <path d={mdiLogin} />
              </SvgIcon>
            </ListItemIcon>
            <ListItemText primary="Login" />
          </ListItem>
        )}
      </List>
      <div className={classes.drawerCloseButtonContainer}>
        <IconButton className={classes.drawerCloseButton} onClick={toggleDrawer}>
          <CloseIcon />
        </IconButton>
      </div>
    </Drawer>
  );

  return (
    <div className={classes.root}>
      <AppBar position="fixed" color="secondary" className={classes.appbar}>
        <Toolbar>
          <Avatar
            alt="Logo"
            src={afterAcademyLogo}
            className={classes.logo}
            component={Link}
            to={'/'}
          />
          <Typography variant="h6" className={classes.brandName}>
            AfterAcademy React
          </Typography>
          <div className={classes.sectionDesktop}>
            {[
              {
                title: 'About Project',
                href: 'https://github.com/afteracademy/react-app-architecture',
              },
              {
                title: 'Contact',
                href: 'https://github.com/afteracademy/react-app-architecture/issues',
              },
            ].map(({ title, href }, position) => (
              <Button
                key={position}
                color="inherit"
                className={classes.button}
                href={href}
                target="_blank"
              >
                {title}
              </Button>
            ))}
            {[{ title: 'Blogs', link: '/blogs' }].map(({ title, link }, position) => (
              <Button
                key={position}
                color="inherit"
                className={classes.button}
                component={Link}
                to={link}
              >
                {title}
              </Button>
            ))}
            {user?.profilePicUrl ? (
              <Avatar alt={user.name} src={user.profilePicUrl} className={classes.avatar} />
            ) : (
              user?.name && <FirstLetter text={user.name} />
            )}
            {isLoggedIn ? (
              <IconButton
                aria-label="show more"
                aria-haspopup="true"
                onClick={handlePopupMenuOpen}
                color="primary"
              >
                <MenuIcon />
              </IconButton>
            ) : (
              <Fab
                variant="extended"
                size="medium"
                color="primary"
                aria-label="login"
                className={classes.loginButton}
                onClick={() => setOpenAuthDialog(true)}
              >
                Login
              </Fab>
            )}
          </div>
          <div className={classes.sectionMobile}>
            <IconButton
              aria-label="show more"
              aria-haspopup="true"
              color="inherit"
              onClick={toggleDrawer}
            >
              <MenuIcon />
            </IconButton>
          </div>
        </Toolbar>
      </AppBar>
      {popupMenu}
      {mobileDrawerMenu}
      <AuthDialog open={openAuthDialog} onClose={() => setOpenAuthDialog(false)} />
    </div>
  );
}
Example #12
Source File: ProjectsComponent.tsx    From backstage with Apache License 2.0 4 votes vote down vote up
ProjectsComponent = () => {
  const routeRef = useRouteRef(rootRouteRef);
  const codesceneApi = useApi(codesceneApiRef);

  const classes = useStyles();
  const [searchText, setSearchText] = React.useState('');
  const {
    value: projectsWithAnalyses,
    loading,
    error,
  } = useAsync(async (): Promise<Record<number, ProjectAndAnalysis>> => {
    const projects = (await codesceneApi.fetchProjects()).projects;

    const promises = projects.map(project =>
      codesceneApi.fetchLatestAnalysis(project.id),
    );
    // analyses associates project IDs with their latests analysis
    const analyses: Record<number, Analysis> = await Promise.allSettled(
      promises,
    ).then(results => {
      return results
        .filter(result => result.status === 'fulfilled')
        .map(result => result as PromiseFulfilledResult<Analysis>)
        .map(result => result.value)
        .reduce(
          (acc, analysis) => ({ ...acc, [analysis.project_id]: analysis }),
          {},
        );
    });
    return projects.reduce(
      (acc, project) => ({
        ...acc,
        [project.id]: {
          project: project,
          analysis: analyses[project.id],
        },
      }),
      {},
    );
  }, []);

  if (loading) {
    return <Progress />;
  } else if (error) {
    return <Alert severity="error">{error.message}</Alert>;
  } else if (
    !projectsWithAnalyses ||
    Object.keys(projectsWithAnalyses).length === 0
  ) {
    return <Alert severity="error">No projects found!</Alert>;
  }

  const projects = Object.values(projectsWithAnalyses)
    .map(p => p.project)
    .sort((a, b) => a.name.localeCompare(b.name));

  const cards = projects.filter(matchFilter(searchText)).map(project => {
    const analysis = projectsWithAnalyses[project.id].analysis;
    const subtitle = analysis
      ? `Last analysis: ${analysis.readable_analysis_time} · Score: ${analysis.high_level_metrics.current_score} · Active authors: ${analysis.high_level_metrics.active_developers}`
      : undefined;
    const chips = analysis
      ? topLanguages(analysis, 3).map(lang => (
          <Chip label={lang} key={lang} size="small" />
        ))
      : undefined;
    return (
      <Grid key={project.id} item xs={3}>
        <Card>
          <CardActionArea
            style={{
              height: '100%',
              overflow: 'hidden',
              width: '100%',
            }}
            component={RouterLink}
            to={`${routeRef()}/${project.id}`}
          >
            <ItemCardHeader title={project.name} />
            <CardContent>{subtitle}</CardContent>
            <CardActions disableSpacing>{chips}</CardActions>
          </CardActionArea>
        </Card>
      </Grid>
    );
  });

  return (
    <Content className={classes.overflowXScroll}>
      <ContentHeader title="Projects">
        <Input
          id="projects-filter"
          type="search"
          placeholder="Filter"
          onChange={e => setSearchText(e.target.value)}
        />
      </ContentHeader>
      <Grid container>{cards}</Grid>
    </Content>
  );
}
Example #13
Source File: DashboardQuickActions.tsx    From clearflask with Apache License 2.0 4 votes vote down vote up
SelectableQuickActionPostList = React.memo((props: {
  server: Server;
  title?: {
    name: string;
    helpDescription?: string;
  };
  enabled?: boolean;
  selectedPostIds?: string[];
  onClick?: (postId: string) => void;
  PostListProps?: Partial<React.ComponentProps<typeof PostList>>;
  showSampleItem?: string;
  disabledDuringTour?: boolean;
  FirstTimeNoticeProps?: React.ComponentPropsWithoutRef<typeof FirstTimeNotice>;
}) => {
  const { t } = useTranslation('app');
  const classes = useStyles();
  const theme = useTheme();
  const { enqueueSnackbar } = useSnackbar();
  const noticeRef = useRef<FirstTimeNoticeHandle>(null);

  var content = (
    <PostList
      key={props.server.getProjectId()}
      server={props.server}
      layout='similar-merge-action'
      PanelPostProps={{
        overrideTitle: !props.title ? undefined : (
          <FilterControlTitle name={props.title.name} className={classes.feedbackTitle} help={{
            description: props.title.helpDescription,
          }} />
        ),
        renderPost: (idea, ideaIndex) => {
          const title = truncateWithElipsis(30, idea.title);
          return (
            <HoverArea>
              {(hoverAreaProps, isHovering, isHoverDown) => {
                const isLinked = props.selectedPostIds?.includes(idea.ideaId);
                const color = isLinked
                  ? theme.palette.primary.main
                  : theme.palette.common.black;
                return (
                  <CardActionArea
                    {...hoverAreaProps}
                    disabled={!props.enabled}
                    className={classNames(
                      classes.postAction,
                      !props.enabled && classes.postActionDisabled,
                    )}
                    style={!props.enabled ? {
                      color: theme.palette.text.disabled,
                    } : {
                      color: color,
                      borderColor: color || fade(theme.palette.common.black, 0.54),
                    }}
                    onClick={async e => {
                      if (!props.enabled || !props.onClick) return;

                      if (props.disabledDuringTour) {
                        enqueueSnackbar('Disabled during tutorial', { variant: 'warning', preventDuplicate: true });
                        return;
                      }
                      if (!!noticeRef.current && ! await noticeRef.current.invoke()) return;
                      props.onClick(idea.ideaId);
                    }}
                  >
                    {title && (
                      <Typography>{t(title as any)}</Typography>
                    )}
                  </CardActionArea>
                );
              }}
            </HoverArea>
          );
        },
        renderEmpty: !props.showSampleItem ? undefined : () => (
          <QuickActionArea
            key={`sample-item-${props.showSampleItem}`}
            isDragging={false}
            droppableId='disabled-for-dropping'
            enabled={false}
            title={props.showSampleItem}
          />
        ),
      }}
      hideIfEmpty={!props.showSampleItem}
      {...props.PostListProps}
    />
  );

  if (props.FirstTimeNoticeProps) {
    content = (
      <>
        {content}
        <Provider store={ServerAdmin.get().getStore()}>
          <FirstTimeNotice
            {...props.FirstTimeNoticeProps}
            ref={noticeRef}
          />
        </Provider>
      </>
    );
  }

  return content;
}, customReactMemoEquals({
  nested: new Set(['PostListProps', 'FirstTimeNoticeProps', 'title']),
}))
Example #14
Source File: DSCEditor.tsx    From logo-generator with MIT License 4 votes vote down vote up
DSCEditor = function () {
  const dscLogo = useRef(null);
  const logoCanvas = useRef(null);
  const fullLogoImg = useRef(null)
   const [canvasScale , setScale] = useState<number>(0.5);
   const [logoName, setName] = useState<string>("School Name");
   const [darkMode, setMode] = useState(false);
   const [fullLogoUrl, setFullLogoUrl] = useState();
   const [fullLogoUrlVertical, setFullLogoUrlVertical] = useState();
   const [fullLogoUrlOld, setFullLogoUrlOld] = useState();
   const [fullLogoUrlVerticalOld, setFullLogoUrlVerticalOld] = useState();
   const { currentUser }: any= useAuth();
   const [error, setError] = useState('');

  let LogoScale = 2.35;

  useEffect(() => {
    
    WebFont.load({
          google: {
            families: ["Roboto:400", "Product Sans", "Product Sans:400"]
          },
          fontactive: (familyName, fvd) => {
           bwImageHorizontal();
            colorImage();
            colorImageVertical();
            bwImageVertical();
          }
        });
  },[]);

  useEffect(() => {
    
    setError('')
  }, [currentUser])

  useEffect(() => {
    bwImageHorizontal();
    colorImage();
    bwImageVertical();
    colorImageVertical();
 }, [logoName]);


const handleDarkMode = (mode:any) =>{
  setMode(mode);
};

const bwImageHorizontal =()=> {
  const name = logoName;
  const scale = canvasScale;
  const ctx = logoCanvas.current.getContext("2d");
  ctx.font = `400 96px "Product Sans"`;
  LogoScale = 1.36;

  const canvasWidth = Math.max(ctx.measureText("Developer Student Clubs").width, ctx.measureText(name).width) + dscLogo.current.width * LogoScale + 600;
  const canvasHeight = dscLogo.current.height + 150;

  logoCanvas.current.setAttribute("width", canvasWidth * scale);
  logoCanvas.current.setAttribute("height", canvasHeight * scale);

  ctx.scale(scale, scale);
  ctx.font = `400 96px "Product Sans"`;
  ctx.fillStyle = "#fff";

  ctx.drawImage(dscLogo.current, 20, 0, dscLogo.current.width * LogoScale, dscLogo.current.height* LogoScale);

  ctx.fillText("Developer Student Clubs", dscLogo.current.width + 112, 132);

  ctx.font = `400 66px "Product Sans"`;
  ctx.fillText(name, dscLogo.current.width + 112, 243);

  setFullLogoUrl(logoCanvas.current.toDataURL())
}

const bwImageVertical =()=>{
  const name = logoName;
  const scale = canvasScale;
  const ctx = logoCanvas.current.getContext("2d");
  const ctx2 = logoCanvas.current.getContext("2d");
  ctx.font = `400 91px "Product Sans"`;
  ctx2.font = `400 62px "Product Sans"`;

  LogoScale = 2.35;

  const canvasWidth = (Math.max(ctx.measureText("Developer Student Clubs").width, ctx2.measureText(name).width) + 1200 );
  const canvasHeight = dscLogo.current.height * LogoScale + 100;

  logoCanvas.current.setAttribute("width", canvasWidth * scale);
  logoCanvas.current.setAttribute("height", canvasHeight * scale);

  ctx.scale(scale, scale);
  ctx.font = `400 94px "Product Sans"`;
  ctx.fillStyle = "#fff";

  ctx.drawImage(dscLogo.current, canvasWidth/2 - (dscLogo.current.width * LogoScale)/2, -0.25 * dscLogo.current.height * LogoScale, dscLogo.current.width * LogoScale, dscLogo.current.height* LogoScale);

  ctx.textBaseline = "bottom";
  // ctx.textAlign = "center";
  ctx.fillText(
    "Developer Student Clubs",
    canvasWidth/2 - (ctx.measureText("Developer Student Clubs").width / 2),
    dscLogo.current.height * LogoScale + 10
  );

  ctx.font = `400 62px "Product Sans"`;
  ctx.textBaseline = "bottom";
  // ctx.textAlign = "center";
  ctx.fillText(name, canvasWidth/2 - (ctx.measureText(name).width / 2), dscLogo.current.height * LogoScale + 100);

  setFullLogoUrlVertical(logoCanvas.current.toDataURL())
}

const colorImage =()=>{
  const name = logoName;
  const scale = canvasScale;
  const ctx = logoCanvas.current.getContext("2d");
  const ctx2 = logoCanvas.current.getContext("2d");
  ctx.font = `400 96px "Product Sans"`;
  ctx2.font = `400 66px "Product Sans"`;

  LogoScale = 1.36;

  const canvasWidth = Math.max(ctx.measureText("Developer Student Clubs").width, ctx.measureText(name).width) + dscLogo.current.width * LogoScale + 600;
  const canvasHeight = dscLogo.current.height + 150;

  logoCanvas.current.setAttribute("width", canvasWidth * scale);
  logoCanvas.current.setAttribute("height", canvasHeight * scale);

  ctx.scale(scale, scale);
  ctx.font = `400 96px "Product Sans"`;
  ctx.fillStyle = "rgba(0, 0, 0, 0.54)";

  ctx.drawImage(dscLogo.current, 20, 0, dscLogo.current.width * LogoScale, dscLogo.current.height* LogoScale);

  ctx.fillText("Developer Student Clubs", dscLogo.current.width + 112, 132);

  ctx.font = `400 66px "Product Sans"`;
  ctx.fillText(name, dscLogo.current.width + 112, 243);
  
  setFullLogoUrlOld(logoCanvas.current.toDataURL())
}

const colorImageVertical=()=> {
  const name = logoName;
  const scale = canvasScale;
  const ctx = logoCanvas.current.getContext("2d");
  const ctx2 = logoCanvas.current.getContext("2d");
  ctx.font = `400 91px "Product Sans"`;
  ctx2.font = `400 62px "Product Sans"`;

  LogoScale = 2.35;

  const canvasWidth = (Math.max(ctx.measureText("Developer Student Clubs").width, ctx2.measureText(name).width) + 1200 );
  const canvasHeight = dscLogo.current.height * LogoScale + 100;

  logoCanvas.current.setAttribute("width", canvasWidth * scale);
  logoCanvas.current.setAttribute("height", canvasHeight * scale);

  ctx.scale(scale, scale);
  ctx.font = `400 91px "Product Sans"`;
  ctx.fillStyle = "rgba(0, 0, 0, 0.54)";

  ctx.drawImage(dscLogo.current, canvasWidth/2 - (dscLogo.current.width * LogoScale)/2, -0.25 * dscLogo.current.height * LogoScale, dscLogo.current.width * LogoScale, dscLogo.current.height* LogoScale);

  ctx.textBaseline = "bottom";
  // ctx.textAlign = "center";
  ctx.fillText(
    "Developer Student Clubs",
    canvasWidth/2 - (ctx.measureText("Developer Student Clubs").width / 2),
    dscLogo.current.height * LogoScale + 10
  );

  ctx.font = `400 62px "Product Sans"`;
  ctx.textBaseline = "bottom";
  ctx.fillText(name, canvasWidth/2 - (ctx.measureText(name).width / 2), dscLogo.current.height * LogoScale + 100);

  setFullLogoUrlVerticalOld(logoCanvas.current.toDataURL())
}
  
    return (
      <div className="main">
        <MainToolBar
          toDark={handleDarkMode}
          darkMode={darkMode}
          id="DSCToolbar"
          />
        <div style={hidden}>
          {darkMode ? (
            <img
              ref={dscLogo}
              onLoad={() => {
                bwImageHorizontal();
                bwImageVertical();
              }}
              src="assets/dsc/bw.svg"
              alt={`DSC Icon`}
            />
          ) : (
            <img
              ref={dscLogo}
              onLoad={() => {
                colorImage();
                colorImageVertical();
              }}
              src="assets/dsc/color.svg"
              alt={`DSC Icon`}
            />
          )}
        </div>

        <TextField
          label="School Name"
          margin="normal"
          variant="outlined"
          style={{
              width: "100%"
          }}
          onChange={e => {
            setName(e.target.value)
          }}
        />
        <br />
        <canvas
          style={hidden}
          ref={logoCanvas}
        />

        {darkMode ? (
          <>
            <Card style={{width: "100%"}}>
              <CardActionArea style={{background: "#000"}}>
                <CardContent>
                  <img
                    ref={fullLogoImg}
                    alt={`DSC ${name} Logo`}
                    src={fullLogoUrl}
                    style={{maxWidth: "100%"}}
                  />
                  <Alert severity="info" style={{ padding: "0 1rem", background: "#5c5c5c" }}>The text in the logo is white. Please view downloaded logo against dark backgrounds.</Alert>
                </CardContent>
              </CardActionArea>
              <CardActions>
              { currentUser ?
                <Button
                  variant="contained"
                  color="primary"
                  href={fullLogoUrl}
                  style={{ margin: "5px" }}
                  download={`DSC ${logoName} Dark Horizontal-Logo.png`}
                >
                  DOWNLOAD
                </Button> :
                <Button
                variant="contained"
                color="primary"
                href={fullLogoUrl}
                style={{ margin: "5px" }}
                onClick={(e) => setError('Login to download the logo')}
                >
                DOWNLOAD
                </Button>
              } 
              {error && <Alert severity="error" variant="outlined">{error}</Alert>}
              </CardActions>
            </Card>
            <Card style={{width: "100%", marginTop: "1rem"}}>
              <CardActionArea style={{background: "#000"}}>
                <CardContent>
                  <img
                    ref={fullLogoImg}
                    alt={`DSC ${logoName} Logo`}
                    src={fullLogoUrlVertical}
                    style={{maxWidth: "100%"}}
                  />
                  <Alert severity="info" style={{ padding: "0 1rem", background: "#5c5c5c" }}>The text in the logo is white. Please view downloaded logo against dark backgrounds.</Alert>
                </CardContent>
              </CardActionArea>
              <CardActions>
              { currentUser ?
                <Button
                  variant="contained"
                  color="primary"
                  href={fullLogoUrlVertical}
                  style={{ margin: "5px" }}
                  download={`DSC ${logoName} Dark Vertical-Logo.png`}
                >
                  DOWNLOAD
                </Button> :
                <Button
                variant="contained"
                color="primary"
                href={fullLogoUrlVertical}
                style={{ margin: "5px" }}
                onClick={(e) => setError('Login to download the logo')}
                >
                DOWNLOAD
                </Button>
              } 
              {error && <Alert severity="error" variant="outlined">{error}</Alert>}
              </CardActions>
            </Card>
          </>
        ) : (
          <>
            <Card style={{width: "100%"}}>
              <CardActionArea>
                <CardContent>
                  <img
                    ref={fullLogoImg}
                    alt={`DSC ${logoName} Logo`}
                    src={fullLogoUrlOld}
                    style={{maxWidth: "100%"}}
                  />
                  <Alert severity="info" style={{ padding: "0 1rem", background: "#5c5c5c" }}>The text in the logo is black. Please view downloaded logo against light backgrounds.</Alert>
                </CardContent>
              </CardActionArea>
              <CardActions>
              { currentUser ?
                <Button
                  variant="contained"
                  color="primary"
                  href={fullLogoUrlOld}
                  style={{ margin: "5px" }}
                  download={`DSC ${logoName} Light Horizontal-Logo.png`}
                >
                  DOWNLOAD
                </Button> :
                <Button
                variant="contained"
                color="primary"
                href={fullLogoUrlVerticalOld}
                style={{ margin: "5px" }}
                onClick={(e) => setError('Login to download')}
                >
                DOWNLOAD
                </Button>
              } 
              {error && <Alert severity="error" variant="outlined">{error}</Alert>}
              </CardActions>
            </Card>
            <Card style={{width: "100%", marginTop: "1rem"}}>
              <CardActionArea>
                <CardContent>
                  <img
                    ref={fullLogoImg}
                    alt={`DSC ${logoName} Logo`}
                    src={fullLogoUrlVerticalOld}
                    style={{maxWidth: "100%"}}
                  />
                  <Alert severity="info" style={{ padding: "0 1rem", background: "#5c5c5c" }}>The text in the logo is black. Please view downloaded logo against light backgrounds.</Alert>
                </CardContent>
              </CardActionArea>
              <CardActions>
              { currentUser ?
                <Button
                  variant="contained"
                  color="primary"
                  href={fullLogoUrlVerticalOld}
                  style={{ margin: "5px" }}
                  download={`DSC ${logoName} Light Vertical-Logo.png`}
                >
                  DOWNLOAD
                </Button> :
                <Button
                variant="contained"
                color="primary"
                href={fullLogoUrlVerticalOld}
                style={{ margin: "5px" }}
                onClick={(e) => setError('Login to download')}
                >
                DOWNLOAD
                </Button>
              } 
              {error && <Alert severity="error" variant="outlined">{error}</Alert>}
              </CardActions>
            </Card>
          </>
        )}
      </div>
    );
  


}
Example #15
Source File: GDGEditor.tsx    From logo-generator with MIT License 4 votes vote down vote up
function GDGEditor() {
  const GDGLogo = useRef<HTMLCanvasElement | any>(null);
  const logoCanvas = useRef<HTMLCanvasElement | any>(null);
  const fullLogoImg = useRef<HTMLCanvasElement | any>(null);
  const [Scale, setScale] = useState<number>(0.6);
  const [Name, setName] = useState<string>("City Name");
  const [Mode, setMode] = useState<boolean>(false);
  const [bwImageUrl, setbwImageUrl] = useState<any | null | undefined | string>();
  const [colorImageUrl, setcolorImageUrl] = useState<any | null | string>();
  const { currentUser }:any = useAuth();
  const [error, setError] = useState('');
  

  let LogoScale = 2.35;

  useEffect(() => {
    WebFont.load({
      google: {
        families: ["Roboto:400", "Product Sans", "Product Sans:400"]
      },
      fontactive: (familyName, fvd) => {
        bwImage();
        colorImage();
      }
    });
  },[Name])

  useEffect(() => {
    
    setError('')
  }, [currentUser])


  const handleDarkMode = (mode:boolean) => {
    setMode(mode)
  };

  const bwImage = () => {
    const name = Name;
    const scale = Scale;
    const ctx = logoCanvas.current.getContext("2d");
    ctx.font = `400 96px "Product Sans"`;
    LogoScale = 1.35;

    const canvasWidth = ctx.measureText("GDG").width + ctx.measureText(name).width + GDGLogo.current.width * LogoScale + 80;
    const canvasHeight = GDGLogo.current.height + 80;
    logoCanvas.current.setAttribute("width", canvasWidth * scale);
    logoCanvas.current.setAttribute("height", canvasHeight * scale);

    ctx.scale(scale, scale);
    // ctx.fillStyle = "#000";
    ctx.font = `400 96px "Product Sans"`;
    // ctx.fillRect(0, 0, canvasWidth, canvasHeight);
    ctx.fillStyle = "#fff";

    ctx.drawImage(GDGLogo.current, 20, 0, GDGLogo.current.width * LogoScale, GDGLogo.current.height * LogoScale);

    ctx.fillText("GDG", GDGLogo.current.width * LogoScale + 50, 137);

    ctx.font = `400 96px "Product Sans"`;
    ctx.fillText(name, GDGLogo.current.width * LogoScale + ctx.measureText("GDG").width + 70, 137);

    setbwImageUrl(logoCanvas.current.toDataURL())
  }

  const colorImage = () => {
    const name = Name;
    const scale = Scale;
    const ctx = logoCanvas.current.getContext("2d");
    ctx.font = `400 96px "Product Sans"`;

    LogoScale = 1.35;

    const canvasWidth = ctx.measureText("GDG").width + ctx.measureText(name).width + GDGLogo.current.width * LogoScale + 80;
    const canvasHeight = GDGLogo.current.height + 60;

    logoCanvas.current.setAttribute("width", canvasWidth * scale);
    logoCanvas.current.setAttribute("height", canvasHeight * scale);

    ctx.scale(scale, scale);
    ctx.font = `400 96px "Product Sans"`;
    ctx.fillStyle = "rgba(0, 0, 0, 0.6)";

    ctx.drawImage(GDGLogo.current, 20, 0, GDGLogo.current.width * LogoScale, GDGLogo.current.height * LogoScale);

    ctx.fillText("GDG", GDGLogo.current.width * LogoScale + 50, 137);

    ctx.font = `400 96px "Product Sans"`;
    ctx.fillText(name, GDGLogo.current.width * LogoScale + ctx.measureText("GDG").width + 70, 137);

    setcolorImageUrl(logoCanvas.current.toDataURL())
  }


  return (
    <div className="main">
      <MainToolBar
        toDark={handleDarkMode}
        darkMode={Mode}
        id="GDGToolbar"
      />
      <div style={hidden}>
        {Mode ? (
          <img
            ref={
              GDGLogo
            }
            onLoad={() => {
              bwImage();
            }}
            src="assets/gdg/bw.svg"
            alt={`GDG Icon`}
          />
        ) : (
            <img
              ref={
                GDGLogo
              }
              onLoad={() => {
                colorImage();
              }}
              src="assets/gdg/color.svg"
              alt={`GDG Icon`}
            />
          )}
      </div>

      <TextField
        label="City Name"
        margin="normal"
        variant="outlined"
        style={{
          width: "100%"
        }}
        onChange={(event: any) => (setName(event.target.value))}
      />
      <br />
      <canvas
        style={hidden}
        ref={
          logoCanvas
        }
      />

      {Mode ? (
        <Card style={{ width: "100%" }}>
          <CardActionArea style={{ background: "#000" }}>
            <CardContent>
              <img
                ref={fullLogoImg}
                alt={`GDG ${Name} Logo`}
                src={bwImageUrl}
                style={{ maxWidth: "100%" }}
              />
              <Alert severity="info" style={{ padding: "0 1rem", background: "#5c5c5c" }}>The text in the logo is white. Please view downloaded logo against dark backgrounds.</Alert>
            </CardContent>
          </CardActionArea>
          <CardActions>
          { currentUser ? 
                <Button
                 variant="contained"
                 color="primary"
                 href={bwImageUrl}
                 style={{ margin: "5px" }}
                 download={`GDG ${Name} Dark Horizontal-Logo.png`}
                >
                 DOWNLOAD
                </Button> :
                
                <Button
                  variant="contained"
                  color="primary"
                  href={bwImageUrl}
                  style={{ margin: "5px" }}
                  onClick={(e:any) => setError('Login to download the logo')}
                >
                  DOWNLOAD
                </Button>
          }              
                {error && <Alert severity="error" variant="outlined">{error}</Alert>}
          </CardActions>
        </Card>
      ) : (
          <Card style={{ width: "100%" }}>
            <CardActionArea>
              <CardContent>
                <img
                  ref={
                    fullLogoImg
                  }
                  alt={`GDG ${Name} Logo`}
                  src={colorImageUrl}
                  style={{ maxWidth: "100%" }}
                />
                <Alert severity="info" style={{ padding: "0 1rem", background: "#5c5c5c" }}>The text in the logo is black. Please view downloaded logo against light backgrounds.</Alert>
              </CardContent>
            </CardActionArea>
            <CardActions>
              { currentUser ? 
                <Button
                 variant="contained"
                 color="primary"
                 href={colorImageUrl}
                 style={{ margin: "5px" }}
                 download={`GDG ${Name} Light Horizontal-Logo.png`}
                >
                 DOWNLOAD
                </Button> :
                
                <Button
                  variant="contained"
                  color="primary"
                  href={colorImageUrl}
                  style={{ margin: "5px" }}
                  onClick={(e:any) => setError('Login to download the logo')}
                >
                  DOWNLOAD
                </Button>
              }              
                {error && <Alert severity="error" variant="outlined">{error}</Alert>}

                             
            </CardActions>

          </Card>

        )}
    </div>
  );
}
Example #16
Source File: WTMEditor.tsx    From logo-generator with MIT License 4 votes vote down vote up
function WTMEditor() {

  const wtmLogo = useRef(null);
  const logoCanvas = useRef(null);
  const fullLogoImg = useRef(null);
  const [canvasScale, setScale] = useState<number>(0.5);
  const [cityName, setName] = useState<string>("City Name");
  const [fullLogoUrlOld, setFullLogoUrlOld] = useState();
  const [fullLogoUrlVerticalOld, setFullLogoUrlVerticalOld] = useState();
  const { currentUser }: any= useAuth();
  const [error, setError] = useState('');

  let logoScale= 2.35;

  useEffect(() => {
    
    WebFont.load({
          google: {
            families: ["Roboto:400", "Product Sans", "Product Sans:400"]
          },
          fontactive: (familyName, fvd) => {
            colorImage();
            colorImageVertical();
          }
        });
  },[]);

  useEffect(() => {
    
    setError('')
  }, [currentUser])
  

  useEffect(() => {
    colorImage();
    colorImageVertical();
 }, [cityName]);

  
  const colorImage=()=> {
    const name = cityName;
    const scale = canvasScale;
    const ctx = logoCanvas.current.getContext("2d");
    const ctx2 = logoCanvas.current.getContext("2d");
    ctx.font = `400 84px "Product Sans"`;
    ctx2.font = `400 42px "Product Sans"`;

    logoScale = 0.25;

    const canvasWidth = Math.max(ctx.measureText("Women Techmakers").width, ctx.measureText(name).width) + wtmLogo.current.width * logoScale + 450;
    const canvasHeight = wtmLogo.current.height * logoScale + 50;

    logoCanvas.current.setAttribute("width", canvasWidth * scale);
    logoCanvas.current.setAttribute("height", canvasHeight * scale);

    ctx.scale(scale, scale);
    ctx.font = `400 84px "Product Sans"`;
    ctx.fillStyle = "rgba(0, 0, 0, 0.54)";

    ctx.drawImage(wtmLogo.current, 20, 0, wtmLogo.current.width * logoScale, wtmLogo.current.height* logoScale);

    ctx.fillText("Women Techmakers", wtmLogo.current.width * logoScale + 60, 85);

    ctx.font = `400 42px "Product Sans"`;
    ctx.fillText(name, wtmLogo.current.width * logoScale + 60, wtmLogo.current.height * logoScale + 25);

    // setState({
    //   fullLogoUrlOld: logoCanvas.toDataURL()
    // });
    setFullLogoUrlOld(logoCanvas.current.toDataURL());
  }

  const colorImageVertical=()=> {
    const name = cityName;
    const scale = canvasScale;
    const ctx = logoCanvas.current.getContext("2d");
    const ctx2 = logoCanvas.current.getContext("2d");
    ctx.font = `400 84px "Product Sans"`;
    ctx2.font = `400 42px "Product Sans"`;

    logoScale = 0.5;

    const canvasWidth = (Math.max(ctx.measureText("Women Techmakers").width, ctx2.measureText(name).width) + 1500 );
    const canvasHeight = wtmLogo.current.height * logoScale + 230;

    logoCanvas.current.setAttribute("width", canvasWidth * scale);
    logoCanvas.current.setAttribute("height", canvasHeight * scale);

    ctx.scale(scale, scale);
    ctx.font = `400 84px "Product Sans"`;
    ctx.fillStyle = "rgba(0, 0, 0, 0.54)";

    ctx.drawImage(wtmLogo.current, canvasWidth/2 - (wtmLogo.current.width * logoScale)/2, 20, wtmLogo.current.width * logoScale, wtmLogo.current.height* logoScale);

    ctx.textBaseline = "bottom";
    ctx.fillText(
      "Women Techmakers",
      canvasWidth/2 - (ctx.measureText("Women Techmakers").width / 2),
      wtmLogo.current.height * logoScale + 150
    );

    ctx.font = `400 42px "Product Sans"`;
    ctx.textBaseline = "bottom";
    ctx.fillText(name, canvasWidth/2 - (ctx.measureText(name).width / 2), wtmLogo.current.height * logoScale + 215);

    setFullLogoUrlVerticalOld(logoCanvas.current.toDataURL());
  }



  return (
      <div className="main">
        <div style={hidden}>
          <img
            ref={wtmLogo}
            onLoad={() => {
              colorImage();
              colorImageVertical();
            }}
            src="assets/wtm/color.svg"
            alt={`WTM Icon`}
          />
        </div>

        <TextField
          label="City Name"
          margin="normal"
          variant="outlined"
          style={{
              width: "100%"
          }}
          onChange={e => {
            setName(e.target.value)
          }}
        />
        <br />
        <canvas
          style={hidden}
          ref={logoCanvas}
        />
        <Card style={{width: "100%"}}>
          <CardActionArea>
            <CardContent>
              <img
                ref={fullLogoImg}
                alt={`WTM ${name} Logo`}
                src={fullLogoUrlOld}
                style={{maxWidth: "100%"}}
              />
              <Alert severity="info" style={{ padding: "0 1rem", background: "#5c5c5c" }}>The text in the logo is black. Please view downloaded logo against light backgrounds.</Alert>
            </CardContent>
          </CardActionArea>
          <CardActions>
          { currentUser ? 
              <Button
                variant="contained"
                color="primary"
                href={fullLogoUrlOld}
                style={{ margin: "5px" }}
                download={`WTM ${name} Light Horizontal-Logo.png`}
              >
                DOWNLOAD
              </Button> :
                
                <Button
                  variant="contained"
                  color="primary"
                  href={fullLogoUrlOld}
                  style={{ margin: "5px" }}
                  onClick={(e:any) => setError('Login to download the logo')}
                >
                  DOWNLOAD
                </Button>
          }              
                {error && <Alert severity="error" variant="outlined">{error}</Alert>}
          </CardActions>
        </Card>
        <Card style={{width: "100%", marginTop: "1rem"}}>
          <CardActionArea>
            <CardContent>
              <img
                ref={fullLogoImg}
                alt={`WTM ${name} Logo`}
                src={fullLogoUrlVerticalOld}
                style={{maxWidth: "100%"}}
              />
              <Alert severity="info" style={{ padding: "0 1rem", background: "#5c5c5c" }}>The text in the logo is black. Please view downloaded logo against light backgrounds.</Alert>
            </CardContent>
          </CardActionArea>
          <CardActions>
          { currentUser ? 
              <Button
                variant="contained"
                color="primary"
                href={fullLogoUrlVerticalOld}
                style={{ margin: "5px" }}
                download={`WTM ${name} Light Vertical-Logo.png`}
              >
                DOWNLOAD
              </Button> :
                
                <Button
                  variant="contained"
                  color="primary"
                  href={fullLogoUrlVerticalOld}
                  style={{ margin: "5px" }}
                  onClick={(e:any) => setError('Login to download the logo')}
                >
                  DOWNLOAD
                </Button>
          }              
                {error && <Alert severity="error" variant="outlined">{error}</Alert>}
          </CardActions>
        </Card>

      </div>
  );
  

  
}