@material-ui/core#capitalize TypeScript Examples

The following examples show how to use @material-ui/core#capitalize. 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: uuid-generator.ts    From react-spring-messenger-project with MIT License 6 votes vote down vote up
export default function UUIDv4(): string {
    let digitArray: string[] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
    let alphanumericArray = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
    let alphanumericCapArray = alphanumericArray.map(letter => capitalize(letter));
    let rx = "x"
    return "xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xxxx".replaceAll(rx, () => {
        let array = alphanumericArray.concat(alphanumericCapArray);
        array.push(...digitArray);
        return array[Math.floor(Math.random() * array.length)];
    });
}
Example #2
Source File: ChangeNetworkButton.tsx    From homebase-app with MIT License 6 votes vote down vote up
ChangeNetworkButton = () => {
  const { network } = useTezos()
  const { open } = useActionSheet(ActionSheet.Network);

  return (
    <StyledConnectedButton onClick={() => open()}>
      <Grid container style={{ gap: 5 }} alignItems="center" wrap="nowrap">
        <Grid item>
          <ColorDot color={networkDotColorMap[network]} />
        </Grid>
        <Grid item>
          <NetworkText color="textPrimary">{capitalize(network)}</NetworkText>
        </Grid>
      </Grid>
    </StyledConnectedButton>
  );
}
Example #3
Source File: NetworkSheet.tsx    From homebase-app with MIT License 6 votes vote down vote up
NetworkSheet: React.FC<Props> = (props) => {
  const { network, changeNetwork } = useTezos();

  const options = useMemo(
    () => SUPPORTED_NETWORKS.filter((n) => n !== network),
    [network]
  );

  return (
    <ResponsiveDialog open={props.open} onClose={props.onClose} title={"Choose Network"}>
      <Grid container direction={"column"} style={{ gap: 20 }}>
        {options.map((networkOption, i) => (
          <SheetItem item key={`network-${i}`} onClick={() => {
              props.onClose()
              changeNetwork(networkOption)
            }}>
            <Grid container justifyContent="center" alignItems="center" style={{ gap: 8 }}>
              <Grid item>
                <ColorDot color={networkDotColorMap[networkOption]} />
              </Grid>
              <Grid item>
                <Typography variant={"h6"} color="textPrimary">{capitalize(networkOption)}</Typography>
              </Grid>
            </Grid>
          </SheetItem>
        ))}
      </Grid>
    </ResponsiveDialog>
  );
}
Example #4
Source File: CatalogKindHeader.tsx    From backstage with Apache License 2.0 5 votes vote down vote up
/** @public */
export function CatalogKindHeader(props: CatalogKindHeaderProps) {
  const { initialFilter = 'component', allowedKinds } = props;
  const classes = useStyles();
  const catalogApi = useApi(catalogApiRef);
  const { value: allKinds } = useAsync(async () => {
    return await catalogApi
      .getEntityFacets({ facets: ['kind'] })
      .then(response => response.facets.kind?.map(f => f.value).sort() || []);
  });
  const {
    updateFilters,
    queryParameters: { kind: kindParameter },
  } = useEntityList();

  const queryParamKind = useMemo(
    () => [kindParameter].flat()[0]?.toLocaleLowerCase('en-US'),
    [kindParameter],
  );
  const [selectedKind, setSelectedKind] = useState(
    queryParamKind ?? initialFilter,
  );

  useEffect(() => {
    updateFilters({
      kind: selectedKind ? new EntityKindFilter(selectedKind) : undefined,
    });
  }, [selectedKind, updateFilters]);

  // Set selected Kind on query parameter updates; this happens at initial page load and from
  // external updates to the page location.
  useEffect(() => {
    if (queryParamKind) {
      setSelectedKind(queryParamKind);
    }
  }, [queryParamKind]);

  // Before allKinds is loaded, or when a kind is entered manually in the URL, selectedKind may not
  // be present in allKinds. It should still be shown in the dropdown, but may not have the nice
  // enforced casing from the catalog-backend. This makes a key/value record for the Select options,
  // including selectedKind if it's unknown - but allows the selectedKind to get clobbered by the
  // more proper catalog kind if it exists.
  const availableKinds = [capitalize(selectedKind)].concat(
    allKinds?.filter(k =>
      allowedKinds
        ? allowedKinds.some(
            a => a.toLocaleLowerCase('en-US') === k.toLocaleLowerCase('en-US'),
          )
        : true,
    ) ?? [],
  );
  const options = availableKinds.sort().reduce((acc, kind) => {
    acc[kind.toLocaleLowerCase('en-US')] = kind;
    return acc;
  }, {} as Record<string, string>);

  return (
    <Select
      input={<InputBase value={selectedKind} />}
      value={selectedKind}
      onChange={e => setSelectedKind(e.target.value as string)}
      classes={classes}
    >
      {Object.keys(options).map(kind => (
        <MenuItem value={kind} key={kind}>
          {`${options[kind]}s`}
        </MenuItem>
      ))}
    </Select>
  );
}
Example #5
Source File: AlertDialog.test.tsx    From backstage with Apache License 2.0 4 votes vote down vote up
describe('<AlertDialog />', () => {
  describe.each`
    alert              | status                   | action                      | text
    ${acceptableAlert} | ${AlertStatus.Accepted}  | ${['accept', 'accepted']}   | ${'My team can commit to making this change soon, or has already.'}
    ${dimissableAlert} | ${AlertStatus.Dismissed} | ${['dismiss', 'dismissed']} | ${'Reason for dismissing?'}
    ${snoozableAlert}  | ${AlertStatus.Snoozed}   | ${['snooze', 'snoozed']}    | ${'For how long?'}
  `('Default forms', ({ alert, status, action: [action, actioned], text }) => {
    it(`Displays a default ${action} form`, () => {
      const { getByText } = render(
        <AlertDialog
          open
          group="Ramones"
          alert={alert}
          status={status}
          onClose={jest.fn()}
          onSubmit={jest.fn()}
        />,
      );
      expect(getByText(text)).toBeInTheDocument();
      expect(
        getByText(`${capitalize(action)} this action item?`),
      ).toBeInTheDocument();
      expect(
        getByText(`This action item will be ${actioned} for all of Ramones.`),
      ).toBeInTheDocument();
    });
  });

  describe.each`
    alert                 | status                   | action                      | text
    ${customAcceptAlert}  | ${AlertStatus.Accepted}  | ${['accept', 'accepted']}   | ${'My team can commit to making this change soon, or has already.'}
    ${customDismissAlert} | ${AlertStatus.Dismissed} | ${['dismiss', 'dismissed']} | ${'Reason for dismissing?'}
    ${customSnoozeAlert}  | ${AlertStatus.Snoozed}   | ${['snooze', 'snoozed']}    | ${'For how long?'}
  `('Custom forms', ({ alert, status, action: [action, actioned] }) => {
    it(`Displays a custom ${capitalize(action)} form`, () => {
      const { getByText } = render(
        <AlertDialog
          open
          group="Ramones"
          alert={alert}
          status={status}
          onClose={jest.fn()}
          onSubmit={jest.fn()}
        />,
      );
      expect(getByText(`You. ${capitalize(action)}. Me.`)).toBeInTheDocument();
      expect(
        getByText(`${capitalize(action)} this action item?`),
      ).toBeInTheDocument();
      expect(
        getByText(`This action item will be ${actioned} for all of Ramones.`),
      ).toBeInTheDocument();
    });
  });

  describe.each`
    alert               | status                   | action                      | text
    ${nullAcceptAlert}  | ${AlertStatus.Accepted}  | ${['accept', 'accepted']}   | ${'My team can commit to making this change soon, or has already.'}
    ${nullDismissAlert} | ${AlertStatus.Dismissed} | ${['dismiss', 'dismissed']} | ${'Reason for dismissing?'}
    ${nullSnoozeAlert}  | ${AlertStatus.Snoozed}   | ${['snooze', 'snoozed']}    | ${'For how long?'}
  `('Null forms', ({ alert, status, action: [action, actioned], text }) => {
    it(`Does NOT display a ${capitalize(action)} form`, () => {
      const { getByText, getByRole, queryByText } = render(
        <AlertDialog
          open
          group="Ramones"
          alert={alert}
          status={status}
          onClose={jest.fn()}
          onSubmit={jest.fn()}
        />,
      );
      expect(queryByText(text)).not.toBeInTheDocument();
      expect(getByRole('button', { name: action })).toBeInTheDocument();
      expect(
        getByText(`${capitalize(action)} this action item?`),
      ).toBeInTheDocument();
      expect(
        getByText(`This action item will be ${actioned} for all of Ramones.`),
      ).toBeInTheDocument();
    });
  });
});
Example #6
Source File: AlertDialog.tsx    From backstage with Apache License 2.0 4 votes vote down vote up
AlertDialog = ({
  open,
  group,
  alert,
  status,
  onClose,
  onSubmit,
}: AlertDialogProps) => {
  const classes = useStyles();
  const [isSubmitDisabled, setSubmitDisabled] = useState(true);
  const formRef = useRef<Maybe<HTMLFormElement>>(null);

  useEffect(() => {
    setSubmitDisabled(open);
  }, [open]);

  function disableSubmit(isDisabled: boolean) {
    setSubmitDisabled(isDisabled);
  }

  function onDialogClose() {
    onClose();
    setSubmitDisabled(true);
  }

  const [action, actioned] = choose(
    status,
    [
      ['snooze', 'snoozed'],
      ['accept', 'accepted'],
      ['dismiss', 'dismissed'],
    ],
    ['', ''],
  );

  const TransitionProps = {
    mountOnEnter: true,
    unmountOnExit: true,
    onEntered() {
      if (formRef.current) {
        formRef.current.id = DEFAULT_FORM_ID;
      }
    },
  };

  const Form = formOf(alert, status);

  return (
    <Dialog
      open={open}
      onClose={onDialogClose}
      scroll="body"
      maxWidth="lg"
      TransitionProps={TransitionProps}
    >
      <Box display="flex" justifyContent="flex-end">
        <IconButton
          className={classes.icon}
          disableRipple
          aria-label="Close"
          onClick={onDialogClose}
        >
          <CloseIcon />
        </IconButton>
      </Box>
      <DialogContent className={classes.content}>
        <Box mb={1.5}>
          <Typography variant="h5">
            <b>{capitalize(action)} this action item?</b>
          </Typography>
          <Typography variant="h6" color="textSecondary">
            <b>
              This action item will be {actioned} for all of {group}.
            </b>
          </Typography>
        </Box>
        <Box
          display="flex"
          flexDirection="column"
          bgcolor="alertBackground"
          p={2}
          mb={1.5}
          borderRadius={4}
        >
          <Typography>
            <b>{alert?.title}</b>
          </Typography>
          <Typography color="textSecondary">{alert?.subtitle}</Typography>
        </Box>
        {Form && (
          <Form
            ref={formRef}
            alert={alert}
            onSubmit={onSubmit}
            disableSubmit={disableSubmit}
          />
        )}
      </DialogContent>
      <Divider />
      <DialogActions className={classes.actions} disableSpacing>
        {Form ? (
          <Button
            type="submit"
            color="primary"
            variant="contained"
            aria-label={action}
            form={DEFAULT_FORM_ID}
            disabled={isSubmitDisabled}
          >
            {capitalize(action)}
          </Button>
        ) : (
          <Button
            type="button"
            color="primary"
            variant="contained"
            aria-label={action}
            onClick={() => onSubmit(null)}
          >
            {capitalize(action)}
          </Button>
        )}
      </DialogActions>
    </Dialog>
  );
}
Example #7
Source File: CostOverviewCard.tsx    From backstage with Apache License 2.0 4 votes vote down vote up
CostOverviewCard = ({
  dailyCostData,
  metricData,
}: CostOverviewCardProps) => {
  const theme = useTheme<CostInsightsTheme>();
  const styles = useOverviewTabsStyles(theme);
  const config = useConfig();
  const [tabIndex, setTabIndex] = useState(0);
  const { setDuration, setProject, setMetric, ...filters } =
    useFilters(mapFiltersToProps);

  // Reset tabIndex if breakdowns available change
  useEffect(() => {
    // Intentionally off-by-one to account for the overview tab
    const lastIndex = Object.keys(dailyCostData.groupedCosts ?? {}).length;
    if (tabIndex > lastIndex) {
      setTabIndex(0);
    }
  }, [dailyCostData, tabIndex, setTabIndex]);

  const metric = filters.metric
    ? findAlways(config.metrics, m => m.kind === filters.metric)
    : null;

  const breakdownTabs = Object.keys(dailyCostData.groupedCosts ?? {}).map(
    key => ({
      id: key,
      label: `Breakdown by ${key}`,
      title: `Cloud Cost By ${capitalize(key)}`,
    }),
  );
  const tabs = [
    { id: 'overview', label: 'Total cost', title: 'Cloud Cost' },
  ].concat(breakdownTabs);
  // tabIndex can temporarily be invalid while the useEffect above processes
  const safeTabIndex = tabIndex > tabs.length - 1 ? 0 : tabIndex;

  const OverviewTabs = () => {
    return (
      <>
        <Tabs
          indicatorColor="primary"
          onChange={(_, index) => setTabIndex(index)}
          value={safeTabIndex}
        >
          {tabs.map((tab, index) => (
            <Tab
              className={styles.default}
              label={tab.label}
              key={tab.id}
              value={index}
              classes={{ selected: styles.selected }}
            />
          ))}
        </Tabs>
      </>
    );
  };

  // Metrics can only be selected on the total cost graph
  const showMetricSelect = config.metrics.length && safeTabIndex === 0;

  return (
    <Card style={{ position: 'relative', overflow: 'visible' }}>
      <ScrollAnchor id={DefaultNavigation.CostOverviewCard} />
      <CardContent>
        {dailyCostData.groupedCosts && <OverviewTabs />}
        <CostOverviewHeader title={tabs[safeTabIndex].title}>
          <PeriodSelect duration={filters.duration} onSelect={setDuration} />
        </CostOverviewHeader>
        <Divider />
        <Box ml={2} my={1} display="flex" flexDirection="column">
          {safeTabIndex === 0 ? (
            <CostOverviewChart
              dailyCostData={dailyCostData}
              metric={metric}
              metricData={metricData}
            />
          ) : (
            <CostOverviewBreakdownChart
              costBreakdown={dailyCostData.groupedCosts![tabs[safeTabIndex].id]}
            />
          )}
        </Box>
        <Box display="flex" justifyContent="flex-end" alignItems="center">
          {showMetricSelect && (
            <MetricSelect
              metric={filters.metric}
              metrics={config.metrics}
              onSelect={setMetric}
            />
          )}
        </Box>
      </CardContent>
    </Card>
  );
}