@material-ui/core#CardActions TypeScript Examples

The following examples show how to use @material-ui/core#CardActions. 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: ProductItem.tsx    From frontend-clean-architecture with MIT License 6 votes vote down vote up
ProductItem: React.FC<ProductListProps> = ({ product }) => {
    const classes = useStyles();
    const bloc = useCartPloc();

    return (
        <Grid item xs={6} sm={4} md={3} lg={2}>
            <Card className={classes.card}>
                <CardMedia
                    className={classes.cardMedia}
                    image={product.image}
                    title="Image title"
                />
                <CardContent className={classes.cardContent}>
                    <Typography className={classes.productTitle} gutterBottom variant="subtitle1">
                        {product.title}
                    </Typography>
                    <Typography variant="h6" className={classes.productPrice}>
                        {product.price.toLocaleString("es-ES", {
                            style: "currency",
                            currency: "EUR",
                        })}
                    </Typography>
                </CardContent>
                <CardActions className={classes.cardActions}>
                    <Button
                        size="small"
                        color="primary"
                        onClick={() => bloc.addProductToCart(product)}>
                        Add to Cart
                    </Button>
                </CardActions>
            </Card>
        </Grid>
    );
}
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: DomainCard.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
DomainCard = ({ entity }: DomainCardProps) => {
  const catalogEntityRoute = useRouteRef(entityRouteRef);

  const ownedByRelations = getEntityRelations(entity, RELATION_OWNED_BY);
  const url = catalogEntityRoute(entityRouteParams(entity));

  const owner = (
    <EntityRefLinks
      entityRefs={ownedByRelations}
      defaultKind="group"
      color="inherit"
    />
  );

  return (
    <Card>
      <CardMedia>
        <ItemCardHeader title={entity.metadata.name} subtitle={owner} />
      </CardMedia>
      <CardContent>
        {entity.metadata.tags?.length ? (
          <Box>
            {entity.metadata.tags.map(tag => (
              <Chip size="small" label={tag} key={tag} />
            ))}
          </Box>
        ) : null}
        {entity.metadata.description}
      </CardContent>
      <CardActions>
        <Button to={url} color="primary">
          Explore
        </Button>
      </CardActions>
    </Card>
  );
}
Example #4
Source File: movie.tsx    From 0Auth with MIT License 6 votes vote down vote up
function Movie({ id, name, age_limit, ticket, bookMovie }: MovieProps) {
  const classes = useStyles();

  return (
    <Card className={classes.root} variant="outlined">
      <CardContent>
        <Typography className={classes.title} color="textSecondary" gutterBottom>
          {name}
        </Typography>
        <Typography className={classes.pos} color="textSecondary">
          age limit: {age_limit}
        </Typography>
      </CardContent>
      {
        ticket !== undefined
          ? (
            <CardActions>
              <Button size="small">Already Book</Button>
            </CardActions>
          )
          : (
            <CardActions onClick={() => bookMovie(id)}>
              <Button size="small">Reservation</Button>
            </CardActions>
          )
      }
    </Card>
  );
}
Example #5
Source File: ProfileCard.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
ProfileCard = (props: Props) => {
  const [selection, setSelection] = useState(false);

  const handleSelect = () => {
    props.onClick(props.index, props.repository);
    setSelection(props.selections.has(props.index));
  };

  const classes = useStyles();

  return (
    <Card className={classes.root}>
      <CardHeader
        avatar={
          <Avatar aria-label="recipe" className={classes.avatar}>
            {props.shortName}
          </Avatar>
        }
        action={<IconButton aria-label="settings" />}
        title={props.title}
        subheader={props.repository.replace('https://github.com/', '')}
      />
      <CardContent>
        <Typography variant="body2" color="textSecondary" component="p">
          {props.description}
        </Typography>
      </CardContent>
      <CardActions disableSpacing>
        <IconButton aria-label="select" onClick={handleSelect}>
          {selection ? (
            <CheckBoxIcon color="primary" />
          ) : (
            <CheckBoxOutlineBlankIcon />
          )}
        </IconButton>
      </CardActions>
    </Card>
  );
}
Example #6
Source File: DocsCardGrid.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
DocsCardGrid = (props: DocsCardGridProps) => {
  const { entities } = props;
  const getRouteToReaderPageFor = useRouteRef(rootDocsRouteRef);
  const config = useApi(configApiRef);
  if (!entities) return null;
  return (
    <ItemCardGrid data-testid="docs-explore">
      {!entities?.length
        ? null
        : entities.map((entity, index: number) => (
            <Card key={index}>
              <CardMedia>
                <ItemCardHeader
                  title={entity.metadata.title ?? entity.metadata.name}
                />
              </CardMedia>
              <CardContent>{entity.metadata.description}</CardContent>
              <CardActions>
                <Button
                  to={getRouteToReaderPageFor({
                    namespace: toLowerMaybe(
                      entity.metadata.namespace ?? 'default',
                      config,
                    ),
                    kind: toLowerMaybe(entity.kind, config),
                    name: toLowerMaybe(entity.metadata.name, config),
                  })}
                  color="primary"
                  data-testid="read_docs"
                >
                  Read Docs
                </Button>
              </CardActions>
            </Card>
          ))}
    </ItemCardGrid>
  );
}
Example #7
Source File: SearchCard.tsx    From covid19testing-map with GNU General Public License v3.0 6 votes vote down vote up
SearchCard = () => {
  const classes = useStyles();

  const details: any = [];
  Object.keys(labelMap).forEach((key: string) => {
    details.push({
      type: 'boolean',
      title: labelMap[key].card,
      key,
      icon: labelMap[key].icon,
    });
  });
  return (
    <div>
      <CardHeader title="Search" />

      <CardContent>
        <Typography color="textPrimary" className={classes.cardMargin}>
          Great! Enter the name of their practice or the address of their clinic
          to get started.
        </Typography>
        <Typography color="textPrimary" className={classes.cardMargin}>
          If you can’t find them in our database, it’s unlikely that they are
          offering COVID-19 testing to their patients at this time.
        </Typography>

        <CardActions />
      </CardContent>
    </div>
  );
}
Example #8
Source File: ListCard.tsx    From glific-frontend with GNU Affero General Public License v3.0 6 votes vote down vote up
ListCard: React.SFC<ListCardProps> = ({ ...props }) => {
  const { data } = props;
  const { t } = useTranslation();

  const link = (id: any) => `/${props.link.start}/${id}/${props.link.end}`;

  const viewDetails = (id: any) => (
    <Link to={link(id)} className={styles.Link}>
      <p>{t('View Details')}</p>
    </Link>
  );
  return (
    <div className={styles.CardContainer}>
      {data.map((dataInfo: any) => (
        <Card variant="outlined" className={styles.Card} key={dataInfo.id}>
          <CardContent className={styles.CardContent}>
            <div data-testid="label">{dataInfo.label}</div>

            <Typography variant="body2" component="div" data-testid="description">
              {dataInfo.description}
            </Typography>
          </CardContent>
          <CardActions className={styles.CardActions}>
            {viewDetails(dataInfo.id)}
            {dataInfo.operations}
          </CardActions>
        </Card>
      ))}
    </div>
  );
}
Example #9
Source File: Variation.tsx    From prompts-ai with MIT License 6 votes vote down vote up
export default function Variation(props: Props) {
    const styles = useStyles();
    const showPromptForVariations = useSelector(selectShowPromptForVariations);

    return <Card className={styles.card}>
        <CardContent>
            { showPromptForVariations && (
                <>
                    <Typography className={styles.prompt}>{props.prompt}</Typography>
                    <span role={"img"} aria-label={"brain"}>?️</span>
                    <Typography className={styles.output} component={'span'}><strong>{props.output}</strong></Typography>
                </>
            )}
            { !showPromptForVariations && (
                <>
                    <span role={"img"} aria-label={"brain"}>?️</span>
                    <Typography className={styles.output} component={'span'}>{props.output}</Typography>
                </>
            )}
        </CardContent>
        { showPromptForVariations && (
            <CardActions>
                <Typography variant="caption">Temperature: {props.temperature}</Typography>
                <Typography variant="caption">Max tokens: {props.maxTokens}</Typography>
                <Typography variant="caption">Top P: {props.topP}</Typography>
                <Typography variant="caption">Frequency penalty: {props.frequencyPenalty}</Typography>
                <Typography variant="caption">Presence penalty: {props.presencePenalty}</Typography>
                <Typography variant="caption">Model: {props.modelName}</Typography>
            </CardActions>
        )
        }
    </Card>;
}
Example #10
Source File: PricingPlan.tsx    From clearflask with Apache License 2.0 5 votes vote down vote up
render() {
    return (
      <Card elevation={0} className={classNames(this.props.className, this.props.classes.box, this.props.selected && this.props.classes.boxSelected)}>
        <CardHeader
          title={(
            <div className={this.props.classes.title}>
              {this.props.plan.title}
              {this.props.plan.beta && (
                <div className={this.props.classes.beta}>
                  EARLY<br />ACCESS
                </div>
              )}
            </div>
          )}
          titleTypographyProps={{ align: 'center' }}
        />
        <CardContent>
          {this.renderPriceTag()}
          {(this.props.overridePerks || this.props.plan.perks).map(perk => (
            <div key={perk.desc} style={{ display: 'flex', alignItems: 'baseline' }}>
              <CheckIcon fontSize='inherit' />
              &nbsp;
              <Typography variant='subtitle1'>
                {perk.desc}
                {!!perk.terms && (<>
                  &nbsp;
                  <HelpPopper description={perk.terms} />
                </>)}
              </Typography>
            </div>
          ))}
        </CardContent>
        {
          !!this.props.actionTitle && (
            <CardActions className={this.props.classes.actions}>
              {this.props.actionType === 'radio' ? (
                <FormControlLabel
                  label={this.props.actionTitle}
                  control={(
                    <Radio
                      checked={this.props.selected}
                      color='primary'
                      onChange={e => this.props.actionOnClick && this.props.actionOnClick()}
                      disabled={!this.props.actionOnClick}
                    />
                  )}
                />
              ) : (
                <Button
                  color='primary'
                  variant='contained'
                  disableElevation
                  style={{ fontWeight: 900 }}
                  onClick={this.props.actionOnClick}
                  disabled={!this.props.actionOnClick}
                  {...(this.props.actionTo ? {
                    component: Link,
                    to: this.props.actionTo,
                  } : {})}
                  {...(this.props.actionToExt ? {
                    component: 'a',
                    href: this.props.actionToExt,
                  } : {})}
                >
                  {this.props.actionTitle}
                </Button>
              )}
            </CardActions>
          )
        }
        {this.props.remark && (
          <div className={this.props.classes.remark}>
            <Typography variant='caption' component='div' color='textSecondary'>{this.props.remark}</Typography>
          </div>
        )}
      </Card >
    );
  }
Example #11
Source File: TemplateCard.tsx    From backstage with Apache License 2.0 5 votes vote down vote up
TemplateCard = (props: TemplateCardProps) => {
  const { template } = props;
  const styles = useStyles();
  const ownedByRelations = getEntityRelations(template, RELATION_OWNED_BY);
  const templateRoute = useRouteRef(selectedTemplateRouteRef);
  const href = templateRoute({ templateName: template.metadata.name });

  return (
    <Card>
      <CardHeader template={template} />
      <CardContent>
        <Box className={styles.box}>
          <MarkdownContent
            content={template.metadata.description ?? 'No description'}
          />
        </Box>
        {(template.metadata.tags?.length ?? 0) > 0 && (
          <>
            <Divider className={styles.margin} />
            <Box>
              {template.metadata.tags?.map(tag => (
                <Chip size="small" label={tag} key={tag} />
              ))}
            </Box>
          </>
        )}
      </CardContent>
      <CardActions>
        <div className={styles.footer}>
          <div className={styles.ownedBy}>
            {ownedByRelations.length > 0 && (
              <>
                <UserIcon />
                <EntityRefLinks
                  entityRefs={ownedByRelations}
                  defaultKind="Group"
                />
              </>
            )}
          </div>
          <Button size="small" variant="outlined" color="primary" to={href}>
            Choose
          </Button>
        </div>
      </CardActions>
    </Card>
  );
}
Example #12
Source File: TemplateCard.tsx    From backstage with Apache License 2.0 5 votes vote down vote up
TemplateCard = ({ template, deprecated }: TemplateCardProps) => {
  const backstageTheme = useTheme<BackstageTheme>();
  const templateRoute = useRouteRef(selectedTemplateRouteRef);
  const templateProps = getTemplateCardProps(template);
  const ownedByRelations = getEntityRelations(
    template as Entity,
    RELATION_OWNED_BY,
  );
  const themeId = backstageTheme.getPageTheme({ themeId: templateProps.type })
    ? templateProps.type
    : 'other';
  const theme = backstageTheme.getPageTheme({ themeId });
  const classes = useStyles({ backgroundImage: theme.backgroundImage });
  const href = templateRoute({ templateName: templateProps.name });

  const scmIntegrationsApi = useApi(scmIntegrationsApiRef);
  const sourceLocation = getEntitySourceLocation(template, scmIntegrationsApi);

  return (
    <Card>
      <CardMedia className={classes.cardHeader}>
        <FavoriteEntity className={classes.starButton} entity={template} />
        {deprecated && <DeprecationWarning />}
        <ItemCardHeader
          title={templateProps.title}
          subtitle={templateProps.type}
          classes={{ root: classes.title }}
        />
      </CardMedia>
      <CardContent style={{ display: 'grid' }}>
        <Box className={classes.box}>
          <Typography variant="body2" className={classes.label}>
            Description
          </Typography>
          <MarkdownContent content={templateProps.description} />
        </Box>
        <Box className={classes.box}>
          <Typography variant="body2" className={classes.label}>
            Owner
          </Typography>
          <EntityRefLinks entityRefs={ownedByRelations} defaultKind="Group" />
        </Box>
        <Box>
          <Typography variant="body2" className={classes.label}>
            Tags
          </Typography>
          {templateProps.tags?.map(tag => (
            <Chip size="small" label={tag} key={tag} />
          ))}
        </Box>
      </CardContent>
      <CardActions>
        {sourceLocation && (
          <IconButton
            className={classes.leftButton}
            href={sourceLocation.locationTargetUrl}
          >
            <ScmIntegrationIcon type={sourceLocation.integrationType} />
          </IconButton>
        )}
        <Button
          color="primary"
          to={href}
          aria-label={`Choose ${templateProps.title}`}
        >
          Choose
        </Button>
      </CardActions>
    </Card>
  );
}
Example #13
Source File: SettingList.tsx    From glific-frontend with GNU Affero General Public License v3.0 5 votes vote down vote up
SettingList: React.SFC = () => {
  const { t } = useTranslation();
  const { data: providerData, loading } = useQuery(GET_PROVIDERS);

  if (loading) return <Loading />;
  const SettingIcon = <Settingicon />;

  const List = [
    {
      name: 'Organisation',
      shortcode: 'organization',
      description: t('Manage organisation name, supported languages, hours of operations.'),
    },
    {
      name: 'Billing',
      shortcode: 'billing',
      description: t('Setup for glific billing account'),
    },
  ];

  const heading = (
    <Typography variant="h5" className={styles.Title}>
      <IconButton disabled className={styles.Icon}>
        {SettingIcon}
      </IconButton>
      {t('Settings')}
    </Typography>
  );

  let CardList: any = [];
  if (providerData) {
    // create setting list of Organisation & providers
    CardList = [...List, ...providerData.providers];
  }

  return (
    <>
      {heading}
      <div className={styles.CardContainer}>
        {CardList.map((data: any) => (
          <Card
            variant="outlined"
            className={styles.Card}
            key={data.shortcode}
            data-testid={data.shortcode}
          >
            <CardContent className={styles.CardContent}>
              <div data-testid="label" className={styles.Label}>
                {data.name}
              </div>
              <Typography
                variant="body2"
                component="div"
                data-testid="description"
                className={styles.Description}
              >
                {data.description}
              </Typography>
            </CardContent>
            <CardActions className={styles.CardActions}>
              <Link
                to={{
                  pathname: `settings/${data.shortcode}`,
                }}
                className={styles.Link}
              >
                <IconButton aria-label="Edit" color="default" data-testid="EditIcon">
                  <EditIcon />
                </IconButton>
              </Link>
            </CardActions>
          </Card>
        ))}
      </div>
    </>
  );
}
Example #14
Source File: Welcome.tsx    From ra-enterprise-demo with MIT License 5 votes vote down vote up
Welcome: FC = () => {
    const translate = useTranslate();
    const classes = useStyles();
    return (
        <Card className={classes.root}>
            <Box display="flex">
                <Box flex="1">
                    <Typography variant="h5" component="h2" gutterBottom>
                        {translate('pos.dashboard.welcome.title')}
                    </Typography>
                    <Box maxWidth="50em">
                        <Typography variant="body1" component="p" gutterBottom>
                            {translate('pos.dashboard.welcome.subtitle')}
                        </Typography>
                    </Box>
                    <CardActions className={classes.actions}>
                        <Button
                            variant="contained"
                            href="#/tours"
                            startIcon={<TourIcon />}
                        >
                            {translate('pos.dashboard.welcome.demo_button')}
                        </Button>
                        <Button
                            variant="contained"
                            href="https://marmelab.com/ra-enterprise/"
                            startIcon={<HomeIcon />}
                        >
                            {translate('pos.dashboard.welcome.ra_button')}
                        </Button>
                        <Button
                            variant="contained"
                            href="https://github.com/marmelab/ra-enterprise-demo"
                            target="demo_source_code"
                            startIcon={<GitHubIcon />}
                        >
                            {translate('pos.dashboard.welcome.github_button')}
                        </Button>
                    </CardActions>
                </Box>

                <Box
                    display={{ xs: 'none', sm: 'none', md: 'block' }}
                    className={classes.media}
                    width="16em"
                    height="9em"
                    overflow="hidden"
                />
            </Box>
        </Card>
    );
}
Example #15
Source File: ActiveRulesList.tsx    From posso-uscire with GNU General Public License v3.0 5 votes vote down vote up
function Rule({ rule }) {
  const [showMoreDetails, setShowMoreDetails] = useState(false);
  const [language] = useLanguage();
  const classes = useStyles();

  const { from, to, details, moreDetails } = rule;

  const dateFromTo = [
    from ? `${i18n.FROM[language]} ${parseDate(from)}` : "",
    to ? `${i18n.TO[language]} ${parseDate(to)}` : "",
  ].join(" ");

  return (
    <Card className={classes.cardRoot} variant="outlined">
      <CardContent>
        {dateFromTo && (
          <Typography
            component={"div"}
            className={classes.dateFromTo}
            color="textPrimary"
            gutterBottom
          >
            ? {dateFromTo}
          </Typography>
        )}
        {rule.name && (
          <Typography variant="h5" component="h2">
            {getLocalizedValue(rule.name)}
          </Typography>
        )}

        {details && (
          <Typography
            component={"div"}
            color="textPrimary"
            className={classes.rulesList}
          >
            <List component="nav" dense={true}>
              {[...details, ...(showMoreDetails ? moreDetails : [])].map(
                (detail, index) => (
                  <ListItem button key={index}>
                    <ListItemText
                      classes={{ primary: classes.rule }}
                      primary={getLocalizedValue(detail)}
                    />
                  </ListItem>
                )
              )}
            </List>
          </Typography>
        )}
      </CardContent>
      {!showMoreDetails && moreDetails && (
        <CardActions classes={{ root: classes.cardActions }}>
          <Button
            size="medium"
            color="primary"
            variant="outlined"
            onClick={() => setShowMoreDetails(true)}
          >
            {i18n.MORE_INFO[language]}
          </Button>
        </CardActions>
      )}
    </Card>
  );
}
Example #16
Source File: ToolCard.tsx    From backstage with Apache License 2.0 5 votes vote down vote up
ToolCard = ({ card, objectFit }: Props) => {
  const classes = useStyles();

  const { title, description, url, image, lifecycle, tags } = card;

  return (
    <Card key={title}>
      <CardMedia
        image={image}
        title={title}
        className={classNames(classes.media, {
          [classes.mediaContain]: objectFit === 'contain',
        })}
      />
      <CardContent>
        <Typography paragraph variant="h5">
          {title}{' '}
          {lifecycle && lifecycle.toLocaleLowerCase('en-US') !== 'ga' && (
            <Chip
              size="small"
              label={lifecycle}
              className={classNames(
                classes.lifecycle,
                classes[lifecycle.toLocaleLowerCase('en-US')],
              )}
            />
          )}
        </Typography>
        <Typography>{description || 'Description missing'}</Typography>
        {tags && (
          <Box marginTop={2}>
            {tags.map((item, idx) => (
              <Chip size="small" key={idx} label={item} />
            ))}
          </Box>
        )}
      </CardContent>
      <CardActions>
        <Button color="primary" to={url} disabled={!url}>
          Explore
        </Button>
      </CardActions>
    </Card>
  );
}
Example #17
Source File: index.tsx    From react-app-architecture with Apache License 2.0 5 votes vote down vote up
InfoCard = ({
  imgUrl,
  href,
  title,
  subtitle,
  description,
  action = 'Learn More',
}: {
  imgUrl: string;
  href: string;
  title: string;
  subtitle: string;
  description: string;
  action?: string;
}) => {
  const classes = useStyles();
  return (
    <Card className={classes.infoCard} raised={true}>
      <CardHeader
        avatar={<Avatar className={classes.avatar} src={imgUrl} />}
        title={title}
        subheader={subtitle}
      />
      <CardContent>
        <Typography variant="subtitle1" component="p">
          {description}
        </Typography>
      </CardContent>
      <CardActions className={classes.cardAction}>
        <Button
          className={classes.button}
          variant="contained"
          component="a"
          size="small"
          color="primary"
          href={href}
          target="_blank"
        >
          {action}
        </Button>
      </CardActions>
    </Card>
  );
}
Example #18
Source File: ValidatorsStats.tsx    From community-repo with GNU General Public License v3.0 5 votes vote down vote up
ValidatorsStats = (props: { stash: String, activeEras: ActiveEra[]; }) => {
  const classes = useStyles();
  let sortedByBlock = props.activeEras
  let noDataLabel = 'No Data Available'
  let firstBlock: ActiveEra | undefined = undefined
  let lastBlock: ActiveEra | undefined = undefined
  let scoringPeriodText = ''

  const copyValidatorStatistics = () => navigator.clipboard.writeText(scoringPeriodText)

  if(props.activeEras.length > 0) {
    sortedByBlock = props.activeEras.sort((e1,e2) => e1.block - e2.block)
    firstBlock = sortedByBlock[0];
    lastBlock = sortedByBlock[sortedByBlock.length - 1];
    scoringPeriodText = `Validator Date: ${new Date(firstBlock!.date).toLocaleDateString()}-${new Date(lastBlock!.date).toLocaleDateString()}\nDescription: I was an active validator from era/block ${firstBlock!.era}/${firstBlock!.block} to era/block ${lastBlock!.era}/${lastBlock!.block}\nwith stash account ${props.stash}. (I was active in all the eras in this range and found a total of ? blocks)`
    return (
        <Card className={classes.root}>
          <CardContent>
            <Typography className={classes.title} color="textPrimary" gutterBottom>
              Scoring period text:
            </Typography>
            { scoringPeriodText.split('\n').map((i, key) => <Typography key={key} className={classes.pos} color="textSecondary">{i}</Typography>) }
          </CardContent>
          <CardActions>
            <Button onClick={copyValidatorStatistics} size="small">Copy to clipboard</Button>
          </CardActions>
        </Card>
    );
  } else {
    return (
      <Card className={classes.root}>
        <CardContent>
        <Typography className={classes.pos} color="textSecondary">
            { noDataLabel }
          </Typography>
        </CardContent>
      </Card>
    )
  }
}
Example #19
Source File: StatsCard.component.tsx    From akashlytics with GNU General Public License v3.0 5 votes vote down vote up
export function StatsCard({
  number,
  text,
  tooltip,
  actionButton,
  graphPath,
  diffNumber,
  diffPercent,
}: IStatsCardProps) {
  const classes = useStyles();
  const mediaQuery = useMediaQueryContext();

  return (
    <Card
      className={clsx(classes.root, { [classes.rootSmall]: mediaQuery.smallScreen })}
      elevation={3}
    >
      <CardHeader
        classes={{ title: classes.number, root: classes.cardHeader, subheader: classes.subHeader }}
        title={number}
        subheader={diffNumber && (
          <>
            <DiffNumber value={diffNumber} />
            &nbsp;
            <DiffPercentageChip value={diffPercent} />
          </>
        )}
      />
      <div className={classes.cardContent}>
        <p className={classes.title}>{text}</p>
      </div>

      <CardActions>
        {tooltip && (
          <CustomTooltip arrow enterTouchDelay={0} leaveTouchDelay={10000} title={tooltip}>
            <HelpIcon className={classes.tooltip} />
          </CustomTooltip>
        )}
        {graphPath && (
          <Button
            aria-label="graph"
            component={RouterLink}
            to={graphPath}
            size="small"
            classes={{ label: classes.actionButtonLabel }}
          >
            <Box component="span" marginRight=".5rem">
              Graph
            </Box>
            <TimelineIcon className={classes.actionIcon} />
          </Button>
        )}

        {actionButton}
      </CardActions>
    </Card>
  );
}
Example #20
Source File: ValidatorReport.tsx    From community-repo with GNU General Public License v3.0 5 votes vote down vote up
ValidatorReportCard = (props: { stash: string, report: Reports }) => {
    const copyValidatorStatistics = () => navigator.clipboard.writeText(scoringPeriodText)
    const [scoringPeriodText, setScoringPeriodText] = useState('')
    const useStyles = makeStyles({
        root: {
            minWidth: '100%',
            textAlign: 'left'
        },
        title: {
            fontSize: 18,
        },
        pos: {
            marginTop: 12,
        },
    });

    const classes = useStyles();

    useEffect(() => {
        updateScoringPeriodText()
    });

    const updateScoringPeriodText = () => {
        if (props.report.report.length > 0) {
            const scoringDateFormat = 'DD-MM-yyyy';
            const report = `Validator Date: ${moment(props.report.startTime).format(scoringDateFormat)} - ${moment(props.report.endTime).format(scoringDateFormat)}\nDescription: I was an active validator from era/block ${props.report.startEra}/${props.report.startBlock} to era/block ${props.report.endEra}/${props.report.endBlock}\nwith stash account ${props.stash}. (I was active in all the eras in this range and found a total of ${props.report.totalBlocks} blocks)`
            setScoringPeriodText(report)
        } else {
            setScoringPeriodText('')
        }
    }

    if (props.report.report.length > 0) {
        return (<Card className={classes.root}>
            <CardContent>
                <Typography className={classes.title} color="textPrimary" gutterBottom>
                    Validator Report:
                </Typography>
                { scoringPeriodText.split('\n').map((i, key) => <Typography key={key} className={classes.pos} color="textSecondary">{i}</Typography>) }
            </CardContent>
            <CardActions>
                <Button onClick={copyValidatorStatistics} size="small">Copy to clipboard</Button>
            </CardActions>
        </Card>)
    }
    return (
        <Card className={classes.root}>
            <CardContent>
                <Typography className={classes.pos} color="textSecondary">
                    No Data Available
                </Typography>
            </CardContent>
        </Card>
    )
}
Example #21
Source File: TestVariationList.tsx    From frontend with Apache License 2.0 5 votes vote down vote up
TestVariationList: React.FunctionComponent<IProps> = ({
  items,
  onDeleteClick,
}) => {
  const classes = useStyles();
  const [selectedItem, setSelectedItem] = React.useState<TestVariation | null>(
    null
  );

  const handleClose = () => {
    setSelectedItem(null);
  };

  return (
    <React.Fragment>
      <Grid container>
        {items.length === 0 && (
          <Typography variant="h5">No variations</Typography>
        )}
        {items.map((t) => (
          <Grid item key={t.id} xs={4}>
            <Card className={classes.card}>
              <CardMedia
                component="img"
                className={classes.media}
                image={staticService.getImage(t.baselineName)}
                title={t.name}
              />
              <CardContent>
                <TestVariationDetails testVariation={t} />
              </CardContent>
              <CardActions>
                <Button
                  color="primary"
                  component={Link}
                  to={`${routes.VARIATION_DETAILS_PAGE}/${t.id}`}
                >
                  History
                </Button>
                <IconButton
                  onClick={(event: React.MouseEvent<HTMLElement>) =>
                    setSelectedItem(t)
                  }
                >
                  <Delete />
                </IconButton>
              </CardActions>
            </Card>
          </Grid>
        ))}
      </Grid>

      {selectedItem && (
        <BaseModal
          open={!!selectedItem}
          title={"Delete TestVariation"}
          submitButtonText={"Delete"}
          onCancel={handleClose}
          content={
            <Typography>{`Are you sure you want to delete: ${selectedItem.name}?`}</Typography>
          }
          onSubmit={() => {
            onDeleteClick(selectedItem.id);
            handleClose();
          }}
        />
      )}
    </React.Fragment>
  );
}
Example #22
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 #23
Source File: ProjectListPage.tsx    From frontend with Apache License 2.0 4 votes vote down vote up
ProjectsListPage = () => {
  const { enqueueSnackbar } = useSnackbar();
  const projectState = useProjectState();
  const projectDispatch = useProjectDispatch();
  const helpDispatch = useHelpDispatch();

  const [createDialogOpen, setCreateDialogOpen] = React.useState(false);
  const [updateDialogOpen, setUpdateDialogOpen] = React.useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = React.useState(false);

  useEffect(() => {
    setHelpSteps(helpDispatch, PROJECT_LIST_PAGE_STEPS);
  });

  const toggleCreateDialogOpen = () => {
    setCreateDialogOpen(!createDialogOpen);
  };

  const toggleUpdateDialogOpen = () => {
    setUpdateDialogOpen(!updateDialogOpen);
  };

  const toggleDeleteDialogOpen = () => {
    setDeleteDialogOpen(!deleteDialogOpen);
  };

  return (
    <Box mt={2}>
      <Grid container spacing={2}>
        <Grid item xs={4}>
          <Box
            height="100%"
            alignItems="center"
            justifyContent="center"
            display="flex"
          >
            <Fab
              color="primary"
              aria-label="add"
              onClick={() => {
                toggleCreateDialogOpen();
                setProjectEditState(projectDispatch);
              }}
            >
              <Add />
            </Fab>
          </Box>

          <BaseModal
            open={createDialogOpen}
            title={"Create Project"}
            submitButtonText={"Create"}
            onCancel={toggleCreateDialogOpen}
            content={<ProjectForm />}
            onSubmit={() =>
              createProject(projectDispatch, projectState.projectEditState)
                .then((project) => {
                  toggleCreateDialogOpen();
                  enqueueSnackbar(`${project.name} created`, {
                    variant: "success",
                  });
                })
                .catch((err) =>
                  enqueueSnackbar(err, {
                    variant: "error",
                  })
                )
            }
          />

          <BaseModal
            open={updateDialogOpen}
            title={"Update Project"}
            submitButtonText={"Update"}
            onCancel={toggleUpdateDialogOpen}
            content={<ProjectForm />}
            onSubmit={() =>
              updateProject(projectDispatch, projectState.projectEditState)
                .then((project) => {
                  toggleUpdateDialogOpen();
                  enqueueSnackbar(`${project.name} updated`, {
                    variant: "success",
                  });
                })
                .catch((err) =>
                  enqueueSnackbar(err, {
                    variant: "error",
                  })
                )
            }
          />

          <BaseModal
            open={deleteDialogOpen}
            title={"Delete Project"}
            submitButtonText={"Delete"}
            onCancel={toggleDeleteDialogOpen}
            content={
              <Typography>{`Are you sure you want to delete: ${projectState.projectEditState.name}?`}</Typography>
            }
            onSubmit={() =>
              deleteProject(projectDispatch, projectState.projectEditState.id)
                .then((project) => {
                  toggleDeleteDialogOpen();
                  enqueueSnackbar(`${project.name} deleted`, {
                    variant: "success",
                  });
                })
                .catch((err) =>
                  enqueueSnackbar(err, {
                    variant: "error",
                  })
                )
            }
          />
        </Grid>
        {projectState.projectList.map((project) => (
          <Grid item xs={4} key={project.id}>
            <Card id={LOCATOR_PROJECT_LIST_PAGE_PROJECT_LIST}>
              <CardContent>
                <Typography>Id: {project.id}</Typography>
                <Typography>Name: {project.name}</Typography>
                <Typography>Main branch: {project.mainBranchName}</Typography>
                <Typography>
                  Created: {formatDateTime(project.createdAt)}
                </Typography>
              </CardContent>
              <CardActions>
                <Button color="primary" href={project.id}>
                  Builds
                </Button>
                <Button
                  color="primary"
                  href={`${routes.VARIATION_LIST_PAGE}/${project.id}`}
                >
                  Variations
                </Button>
                <IconButton
                  onClick={(event: React.MouseEvent<HTMLElement>) => {
                    toggleUpdateDialogOpen();
                    setProjectEditState(projectDispatch, project);
                  }}
                >
                  <Edit />
                </IconButton>
                <IconButton
                  onClick={(event: React.MouseEvent<HTMLElement>) => {
                    toggleDeleteDialogOpen();
                    setProjectEditState(projectDispatch, project);
                  }}
                >
                  <Delete />
                </IconButton>
              </CardActions>
            </Card>
          </Grid>
        ))}
      </Grid>
    </Box>
  );
}
Example #24
Source File: index.tsx    From firetable with Apache License 2.0 4 votes vote down vote up
export default function BasicCard({
  className,
  style,

  overline,
  title,
  imageSource,
  imageShape = "square",
  imageClassName,

  tabs,
  bodyContent,

  primaryButton,
  primaryLink,
  secondaryAction,
}: ICardProps) {
  const classes = useStyles();

  const [tab, setTab] = useState(0);

  const handleChangeTab = (event: React.ChangeEvent<{}>, newValue: number) =>
    setTab(newValue);

  return (
    <Card className={clsx(classes.root, className)} style={style}>
      <Grid
        container
        direction="column"
        wrap="nowrap"
        className={classes.container}
      >
        <Grid item xs className={classes.cardContentContainer}>
          <CardContent className={clsx(classes.container, classes.cardContent)}>
            <Grid
              container
              direction="column"
              wrap="nowrap"
              className={classes.container}
            >
              {(overline || title || imageSource) && (
                <Grid item className={classes.headerContainer}>
                  <Grid container spacing={3}>
                    <Grid item xs>
                      {overline && (
                        <Typography
                          variant="overline"
                          className={classes.overline}
                        >
                          {overline}
                        </Typography>
                      )}
                      {title && (
                        <Typography variant="h5" className={classes.title}>
                          {title}
                        </Typography>
                      )}
                    </Grid>

                    {imageSource && (
                      <Grid item>
                        <CardMedia
                          className={clsx(
                            classes.image,
                            imageShape === "circle" && classes.imageCircle,
                            imageClassName
                          )}
                          image={imageSource}
                          title={typeof title === "string" ? title : ""}
                        />
                      </Grid>
                    )}
                  </Grid>
                </Grid>
              )}

              {tabs && (
                <Grid item className={classes.tabsContainer}>
                  <Tabs
                    className={classes.tabs}
                    value={tab}
                    onChange={handleChangeTab}
                    indicatorColor="primary"
                    textColor="primary"
                    variant="fullWidth"
                    aria-label="full width tabs"
                  >
                    {tabs?.map((tab, index) => (
                      <Tab
                        key={`card-tab-${index}`}
                        className={classes.tab}
                        label={tab.label}
                        disabled={tab.disabled}
                        {...a11yProps(index)}
                      />
                    ))}
                  </Tabs>
                  <Divider className={clsx(classes.tabs, classes.tabDivider)} />
                </Grid>
              )}

              {(tabs || bodyContent) && (
                <Grid item xs className={classes.contentContainer}>
                  {tabs && (
                    <div className={classes.tabSection}>
                      {tabs[tab].content && Array.isArray(tabs[tab].content) ? (
                        <Grid
                          container
                          direction="column"
                          wrap="nowrap"
                          justify="space-between"
                          spacing={3}
                          className={classes.tabContentGrid}
                        >
                          {(tabs[tab].content as React.ReactNode[]).map(
                            (element, index) => (
                              <Grid item key={`tab-content-${index}`}>
                                {element}
                              </Grid>
                            )
                          )}
                        </Grid>
                      ) : (
                        tabs[tab].content
                      )}
                    </div>
                  )}

                  {bodyContent && Array.isArray(bodyContent) ? (
                    <Grid
                      container
                      direction="column"
                      wrap="nowrap"
                      justify="space-between"
                      className={classes.container}
                    >
                      {bodyContent.map((element, i) => (
                        <Grid item key={i}>
                          {element}
                        </Grid>
                      ))}
                    </Grid>
                  ) : (
                    bodyContent
                  )}
                </Grid>
              )}
            </Grid>
          </CardContent>
        </Grid>

        {(primaryButton || primaryLink || secondaryAction) && (
          <Grid item>
            <Divider className={classes.divider} />
            <CardActions className={classes.cardActions}>
              <Grid item>
                {primaryButton && (
                  <Button
                    {...primaryButton}
                    color={primaryButton.color || "primary"}
                    disabled={!!primaryButton.disabled}
                    endIcon={
                      primaryButton.endIcon === undefined ? (
                        <GoIcon />
                      ) : (
                        primaryButton.endIcon
                      )
                    }
                  >
                    {primaryButton.label}
                  </Button>
                )}
                {primaryLink && (
                  <Button
                    classes={{ label: classes.primaryLinkLabel }}
                    {...(primaryLink as any)}
                    color={primaryLink.color || "primary"}
                    component="a"
                    endIcon={
                      primaryLink.endIcon === undefined ? (
                        <GoIcon />
                      ) : (
                        primaryLink.endIcon
                      )
                    }
                  >
                    {primaryLink.label}
                  </Button>
                )}
              </Grid>
              {secondaryAction && <Grid item>{secondaryAction}</Grid>}
            </CardActions>
          </Grid>
        )}
      </Grid>
    </Card>
  );
}
Example #25
Source File: Conversation.tsx    From prompts-ai with MIT License 4 votes vote down vote up
export default function Conversation(props: Props) {
    const styles = useStyles();
    const dispatch = useDispatch();
    const prompt = useSelector(selectPrompt);
    const globalCompletionParameters = useSelector(selectCompletionParameters);
    const conversation = useSelector((state: RootState) => {
        const workspace = state.editor.present.workspaces.find(w => w.id === state.editor.present.currentWorkspaceId)!;
        return workspace.conversations.find(c => c.id === props.id)!;
    });

    const hasStarted = conversation.parts.some(c => c.submitted);

    useEffect(() => {
        conversationBottom.current!.scrollTop = conversationBottom.current!.scrollHeight;
    });

    const conversationBottom = createRef<HTMLDivElement>();

    return <Card className={styles.card}>
        <CardContent>
            <Grid container alignItems={'center'} justify={'space-between'}>
                <Grid item><Typography>
                    {!hasStarted && (
                        "New Conversation"
                    )}
                    {hasStarted && (
                        <Box>
                            <Typography component={'span'}>Conversation #{props.ind}</Typography><br/>
                            <Typography variant={'caption'} component={'span'}>The prompt and parameters are locked.</Typography>
                        </Box>
                    )}
                </Typography></Grid>
                <Grid item>
                    {hasStarted && (
                        <IconButton onClick={() => {
                            dispatch(deleteConversation(props.id));
                        }}>
                            <Delete />
                        </IconButton>
                    )}
                </Grid>
            </Grid>
            <Box mt={1} className={styles.conversationBox}>
                <Paper className={styles.conversationBox} ref={conversationBottom}>
                    <Box ml={1} mt={1}>
                        {hasStarted && (<>
                            <Typography component={'span'} className={styles.promptedText}>{conversation.initialPrompt}</Typography>
                                {conversation.parts.map(part => (<>
                                    {part.source === ConversationPartSource.gpt && <Typography component={'span'} className={styles.generatedText}>{part.text}</Typography>}
                                    {part.source === ConversationPartSource.user && <Typography component={'span'} className={styles.promptedText}>{part.text}</Typography>}
                                </>))}
                        </>)}
                        {!hasStarted && (<>
                            <Typography component={'span'} className={styles.promptedText}>{prompt}</Typography>
                            <Typography component={'span'} className={styles.promptedText}>{conversation.restartSequence}</Typography>
                        </>)}
                        <div />
                    </Box>
                </Paper>
            </Box>
            <Box mt={2} className={styles.responseInput}>
                <Input conversationId={props.id} afterSend={() => {
                    conversationBottom.current!.scrollTop = conversationBottom.current!.scrollHeight;
                }}/>
            </Box>
            <Box mt={1}>
                <Accordion>
                    <AccordionSummary
                        expandIcon={<ExpandMoreIcon />}
                        aria-controls="panel1a-content"
                        id="panel1a-header"
                    >
                        <Typography>Parameters</Typography>
                    </AccordionSummary>
                    <AccordionDetails>
                        <Typography>
                            <Grid container spacing={1}>
                                <Grid item>
                                    <TextField
                                        value={conversation.restartSequence.split('\n').join('\\n')}
                                        onChange={(event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>) => {
                                            dispatch(updateConversationRestartSequence({
                                                conversationId: props.id,
                                                restartSequence: event.currentTarget.value.split('\\n').join('\n')
                                            }));
                                        }}
                                        className={styles.settingField}
                                        label={'Before User Input'}
                                        variant={'outlined'}
                                    />
                                </Grid>
                                <Grid item>
                                    <TextField
                                        value={conversation.startSequence.split('\n').join('\\n')}
                                        onChange={(event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>) => {
                                            dispatch(updateConversationStartSequence({
                                                conversationId: props.id,
                                                startSequence: event.currentTarget.value.split('\\n').join('\n')
                                            }));
                                        }}
                                        className={styles.settingField}
                                        label={'Before GPT-3 Completion'}
                                        variant={'outlined'}
                                    />
                                </Grid>
                            </Grid>
                            <Box mt={1}>
                                {conversation.completionParams === undefined && (
                                    <CompletionParameters parameters={globalCompletionParameters} />
                                )}
                                {conversation.completionParams !== undefined && (
                                    <CompletionParameters parameters={conversation.completionParams} />
                                )}
                            </Box>
                        </Typography>
                    </AccordionDetails>
                </Accordion>
            </Box>

        </CardContent>
        <CardActions>
        </CardActions>
    </Card>;
}
Example #26
Source File: CardViewFooter.tsx    From neodash with Apache License 2.0 4 votes vote down vote up
NeoCardViewFooter = ({ fields, settings, selection, type, showOptionalSelections, onSelectionUpdate }) => {
    /**
     * For each selectable field in the visualization, give the user an option to select them from the query output fields.
    */
    const selectableFields = REPORT_TYPES[type].selection;
    const selectables = (selectableFields) ? Object.keys(selectableFields) : [];
    const nodeColorScheme = settings && settings.nodeColorScheme ? settings.nodeColorScheme : "neodash";
    const hideSelections = settings && settings.hideSelections ? settings.hideSelections : false;

    if (!fields || fields.length == 0 || hideSelections) {
        return <div></div>
    }
    return (
        <CardActions style={{ position: "relative", paddingLeft: "15px", marginTop: "-5px", overflowX: "scroll" }} disableSpacing>
            {selectables.map((selectable, index) => {
                const selectionIsMandatory = (selectableFields[selectable]['optional']) ? false : true;

                // Creates the component for node property selections.
                if (selectableFields[selectable].type == SELECTION_TYPES.NODE_PROPERTIES) {
                    // Only show optional selections if we explicitly allow it.
                    if (showOptionalSelections || selectionIsMandatory) {
                        const fieldSelections = fields.map((field, i) => {
                            const nodeLabel = field[0];
                            const discoveredProperties = field.slice(1);
                            const properties = (discoveredProperties ? [...discoveredProperties].sort() : []).concat(["(label)", "(id)", "(no label)"]);
                            const totalColors = categoricalColorSchemes[nodeColorScheme] ? categoricalColorSchemes[nodeColorScheme].length : 0;
                            const color = totalColors > 0 ? categoricalColorSchemes[nodeColorScheme][i % totalColors] : "grey";
                            return <FormControl key={nodeLabel}>
                                <InputLabel style={{ paddingLeft: "10px" }} id={nodeLabel}>{nodeLabel}</InputLabel>
                                <Select labelId={nodeLabel}
                                    id={nodeLabel}
                                    className={'MuiChip-root'}
                                    style={{ backgroundColor: color, paddingLeft: 10, minWidth: 75, marginRight: 5 }}
                                    onChange={e => onSelectionUpdate(nodeLabel, e.target.value)}
                                    value={(selection && selection[nodeLabel]) ? selection[nodeLabel] : ""}>
                                    {/* Render choices */}
                                    {properties.length && properties.map && properties.map((field, index) => {
                                        return <MenuItem key={field} value={field}>
                                            {field}
                                        </MenuItem>
                                    })}
                                </Select>
                            </FormControl>;
                        });
                        return fieldSelections;
                    }
                }
                // Creates the selection for all other types of components
                if (selectableFields[selectable].type == SELECTION_TYPES.LIST ||
                    selectableFields[selectable].type == SELECTION_TYPES.NUMBER ||
                    selectableFields[selectable].type == SELECTION_TYPES.NUMBER_OR_DATETIME ||
                    selectableFields[selectable].type == SELECTION_TYPES.TEXT) {
                    if (selectionIsMandatory || showOptionalSelections) {
                        const sortedFields = fields ? [...fields].sort() : [];

                        const fieldsToRender = (selectionIsMandatory ? sortedFields : sortedFields.concat(["(none)"]));
                        return <FormControl key={index}>
                            <InputLabel id={selectable}>{selectableFields[selectable].label}</InputLabel>
                            <Select labelId={selectable}
                                id={selectable}
                                multiple={selectableFields[selectable].multiple}
                                style={{ minWidth: 120, marginRight: 20 }}
                                onChange={e => onSelectionUpdate(selectable, e.target.value)}
                                renderValue={(selected) => Array.isArray(selected) ? selected.join(', ') : selected}
                                value={
                                    (selection && selection[selectable]) ?
                                        (selectableFields[selectable].multiple && !Array.isArray(selection[selectable])) ? 
                                        [selection[selectable]] : 
                                        selection[selectable]
                                    : 
                                        (selectableFields[selectable].multiple) ? 
                                            (selection[selectable] && selection[selectable].length > 0 ? 
                                             selection[selectable][0] 
                                            : 
                                            [])
                                        : "(no data)"}>

                                {/* Render choices */}
                                {fieldsToRender.map((field) => {
                                    return <MenuItem key={field} value={field}>
                                        {selectableFields[selectable].multiple && Array.isArray(selection[selectable]) ?
                                            <Checkbox checked={selection[selectable].indexOf(field) > -1} /> :
                                            <></>
                                        }
                                        {field}
                                        {/* <ListItemText primary={field} /> */}
                                    </MenuItem>
                                })}
                            </Select>
                        </FormControl>
                    }
                }

            })
            }
        </CardActions >
    );
}
Example #27
Source File: StyledCard.tsx    From firetable with Apache License 2.0 4 votes vote down vote up
export default function StyledCard({
  className,
  overline,
  title,
  imageSource,
  bodyContent,
  primaryButton,
  primaryLink,
  secondaryAction,
  headerAction,
}: StyledCardProps) {
  const classes = useStyles();

  return (
    <Card className={clsx(className, classes.root)}>
      <Grid
        container
        direction="column"
        wrap="nowrap"
        className={classes.container}
      >
        <Grid item xs>
          <CardContent className={clsx(classes.container, classes.cardContent)}>
            <Grid
              container
              direction="column"
              wrap="nowrap"
              className={classes.container}
            >
              <Grid item>
                <Grid container className={classes.headerSection} spacing={3}>
                  <Grid item xs>
                    {overline && (
                      <Typography
                        variant="overline"
                        className={classes.overline}
                      >
                        {overline}
                      </Typography>
                    )}
                    <Grid container direction="row" justify="space-between">
                      {title && (
                        <Typography variant="h5" className={classes.title}>
                          {title}
                        </Typography>
                      )}
                      {headerAction && headerAction}
                    </Grid>
                  </Grid>

                  {imageSource && (
                    <Grid item>
                      <CardMedia
                        className={classes.image}
                        image={imageSource}
                        title={title}
                      />
                    </Grid>
                  )}
                </Grid>
              </Grid>

              <Grid item xs>
                {bodyContent && Array.isArray(bodyContent) ? (
                  <Grid
                    container
                    direction="column"
                    wrap="nowrap"
                    justify="space-between"
                  >
                    {bodyContent.map((element) => (
                      <Grid item>{element}</Grid>
                    ))}
                  </Grid>
                ) : (
                  <Typography variant="body2" color="textSecondary">
                    {bodyContent}
                  </Typography>
                )}
              </Grid>
            </Grid>
          </CardContent>
        </Grid>

        <Grid item>
          <Divider className={classes.divider} />
          <CardActions className={classes.cardActions}>
            {primaryButton && <Button color="primary" {...primaryButton} />}
            {primaryLink && (
              <Button
                color="primary"
                component={Link as any}
                to={primaryLink.to}
                children={primaryLink.children || primaryLink.label}
                endIcon={<GoIcon />}
              />
            )}

            {secondaryAction}
          </CardActions>
        </Grid>
      </Grid>
    </Card>
  );
}
Example #28
Source File: JoinGame.tsx    From planning-poker with MIT License 4 votes vote down vote up
JoinGame = () => {
  const history = useHistory();
  let { id } = useParams<{ id: string }>();

  const [joinGameId, setJoinGameId] = useState(id);
  const [playerName, setPlayerName] = useState('');
  const [gameFound, setIsGameFound] = useState(true);

  useEffect(() => {
    async function fetchData() {
      if (joinGameId) {
        if (await getGame(joinGameId)) {
          setIsGameFound(true);
          if (isCurrentPlayerInGame(joinGameId)) {
            history.push(`/game/${joinGameId}`);
          }
        }
      }
    }
    fetchData();
  }, [joinGameId, history]);

  const handleSubmit = async (event: FormEvent) => {
    event.preventDefault();
    if (joinGameId) {
      const res = await addPlayerToGame(joinGameId, playerName);

      setIsGameFound(res);
      if (res) {
        history.push(`/game/${joinGameId}`);
      }
    }
  };

  return (
    <Grow in={true} timeout={500}>
      <div>
        <form onSubmit={handleSubmit}>
          <Card variant='outlined' className='JoinGameCard'>
            <CardHeader
              className='JoinGameCardHeader'
              title='Join a Session'
              titleTypographyProps={{ variant: 'h4' }}
            />
            <CardContent className='JoinGameCardContent'>
              <TextField
                error={!gameFound}
                helperText={!gameFound && 'Session not found, check the ID'}
                className='JoinGameTextField'
                required
                id='filled-required'
                label='Session ID'
                placeholder='xyz...'
                defaultValue={joinGameId}
                variant='outlined'
                onChange={(event: ChangeEvent<HTMLInputElement>) =>
                  setJoinGameId(event.target.value)
                }
              />
              <TextField
                className='JoinGameTextField'
                required
                id='filled-required'
                label='Your Name'
                placeholder='Enter your name'
                defaultValue={playerName}
                variant='outlined'
                onChange={(event: ChangeEvent<HTMLInputElement>) =>
                  setPlayerName(event.target.value)
                }
              />
            </CardContent>
            <CardActions className='JoinGameCardAction'>
              <Button
                type='submit'
                variant='contained'
                color='primary'
                className='JoinGameButton'
              >
                Join
              </Button>
            </CardActions>
          </Card>
        </form>
      </div>
    </Grow>
  );
}
Example #29
Source File: CreateGame.tsx    From planning-poker with MIT License 4 votes vote down vote up
CreateGame = () => {
  const history = useHistory();
  const [gameName, setGameName] = useState('Avengers');
  const [createdBy, setCreatedBy] = useState('SuperHero');
  const [gameType, setGameType] = useState(GameType.Fibonacci);

  const handleSubmit = async (event: FormEvent) => {
    event.preventDefault();
    const game: NewGame = {
      name: gameName,
      createdBy: createdBy,
      gameType: gameType,
      createdAt: new Date(),
    };
    const newGameId = await addNewGame(game);
    history.push(`/game/${newGameId}`);
  };

  return (
    <Grow in={true} timeout={1000}>
      <form onSubmit={handleSubmit}>
        <Card variant='outlined' className='CreateGameCard'>
          <CardHeader
            className='CreateGameCardHeader'
            title='Create New Session'
            titleTypographyProps={{ variant: 'h4' }}
          />
          <CardContent className='CreateGameCardContent'>
            <TextField
              className='CreateGameTextField'
              required
              id='filled-required'
              label='Session Name'
              placeholder='Enter a session name'
              defaultValue={gameName}
              variant='outlined'
              onChange={(event: ChangeEvent<HTMLInputElement>) => setGameName(event.target.value)}
            />
            <TextField
              className='CreateGameTextField'
              required
              id='filled-required'
              label='Your Name'
              placeholder='Enter your name'
              defaultValue={createdBy}
              variant='outlined'
              onChange={(event: ChangeEvent<HTMLInputElement>) => setCreatedBy(event.target.value)}
            />
            <RadioGroup
              aria-label='gender'
              name='gender1'
              value={gameType}
              onChange={(
                event: ChangeEvent<{
                  name?: string | undefined;
                  value: any;
                }>
              ) => setGameType(event.target.value)}
            >
              <FormControlLabel
                value={GameType.Fibonacci}
                control={<Radio color='primary' size='small' />}
                label='Fibonacci (0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)'
              />
              <FormControlLabel
                value={GameType.ShortFibonacci}
                control={<Radio color='primary' size='small' />}
                label='Short Fibonacci (0, ½, 1, 2, 3, 5, 8, 13, 20, 40, 100)'
              />
              <FormControlLabel
                value={GameType.TShirt}
                control={<Radio color='primary' size='small' />}
                label='T-Shirt (XXS, XS, S, M, L, XL, XXL)'
              />
            </RadioGroup>
          </CardContent>
          <CardActions className='CreateGameCardAction'>
            <Button type='submit' variant='contained' color='primary' className='CreateGameButton'>
              Create
            </Button>
          </CardActions>
        </Card>
      </form>
    </Grow>
  );
}