@mui/material#Select TypeScript Examples

The following examples show how to use @mui/material#Select. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.tsx    From yearn-watch-legacy with GNU Affero General Public License v3.0 6 votes vote down vote up
StyledSelect = styled(Select)`
    && {
        color: ${({ theme }) => theme.text} !important;
        margin-left: 44px;
        margin-top: 2px;
        margin-bottom: 2px;
        text-align: right;
        min-width: 88px;
    }
`
Example #2
Source File: BlockEditor.tsx    From NekoMaid with MIT License 6 votes vote down vote up
BlockSelector: React.FC<{ worlds: string[] }> = ({ worlds }) => {
  const his = useHistory()
  const [world, setWorld] = useState(worlds[0])
  const [x, setX] = useState('0')
  const [y, setY] = useState('0')
  const [z, setZ] = useState('0')
  return <Grid container>
    <Grid item xs={6}>
      <FormControl variant='standard' fullWidth>
        <InputLabel id='nekomaid-block-editor-world'>{lang.world}</InputLabel>
        <Select
          labelId='nekomaid-block-editor-world'
          value={world}
          label={lang.world}
          onChange={e => setWorld(e.target.value)}
        >
          {worlds.map(it => <MenuItem key={it} value={it}>{it}</MenuItem>)}
        </Select>
      </FormControl>
    </Grid>
    <Grid item xs={2}><TextField variant='standard' label='X' type='number' fullWidth value={x} onChange={e => setX(e.target.value)} /></Grid>
    <Grid item xs={2}><TextField variant='standard' label='Y' type='number' fullWidth value={y} onChange={e => setY(e.target.value)} /></Grid>
    <Grid item xs={2}><TextField variant='standard' label='Z' type='number' fullWidth value={z} onChange={e => setZ(e.target.value)} /></Grid>
    <Grid item xs={12} sx={{ marginTop: 3, textAlign: 'center' }}>
      <Button
        variant='contained'
        onClick={() => his.push(`/NekoMaid/block/${world}/${parseFloat(x) | 0}/${parseFloat(y) | 0}/${parseFloat(z) | 0}`)}
      >{minecraft['gui.done']}</Button>
    </Grid>
  </Grid>
}
Example #3
Source File: CampaignTypeSelect.tsx    From frontend with MIT License 6 votes vote down vote up
export default function CampaignTypeSelect({ name = 'campaignTypeId' }) {
  const { t } = useTranslation()
  const { data } = useCampaignTypesList()
  const [field, meta] = useField(name)

  const helperText = meta.touched ? translateError(meta.error as TranslatableField, t) : ''
  return (
    <FormControl
      fullWidth
      size="small"
      variant="outlined"
      error={Boolean(meta.error) && Boolean(meta.touched)}>
      <InputLabel>{t('campaigns:campaign.type')}</InputLabel>
      <Select fullWidth defaultValue="" label={t('campaigns:campaign.type')} {...field}>
        <MenuItem value="" disabled>
          {t('campaigns:campaign.type')}
        </MenuItem>
        {data?.map((campaignType, index) => (
          <MenuItem key={index} value={campaignType.id}>
            {campaignType.name}
          </MenuItem>
        ))}
      </Select>
      {helperText && <FormHelperText error>{helperText}</FormHelperText>}
    </FormControl>
  )
}
Example #4
Source File: Footer.tsx    From website with Apache License 2.0 6 votes vote down vote up
StyledSelect = styled(Select)`
  position: absolute;
  left: 45px;
  bottom: 30px;
  height: 40px;

  @media (max-width: 670px) {
    position: unset;
    display: flex;
    width: 100%;
    align-self: center;
  }
  background: ${({ theme }) => theme.background.backgroundColorLight};
  color: ${({ theme }) => theme.text.textColor};
`
Example #5
Source File: BeneficiarySelect.tsx    From frontend with MIT License 6 votes vote down vote up
export default function BeneficiarySelect({ name = 'beneficiaryId' }) {
  const { t } = useTranslation()
  const { data } = useBeneficiariesList()
  const [field, meta] = useField(name)

  const helperText = meta.touched ? translateError(meta.error as TranslatableField, t) : ''
  return (
    <FormControl
      fullWidth
      size="small"
      variant="outlined"
      error={Boolean(meta.error) && Boolean(meta.touched)}>
      <InputLabel>{t('Бенефициент')}</InputLabel>
      <Select fullWidth defaultValue="" label={t('Бенефициент')} {...field}>
        <MenuItem value="" disabled>
          {t('Бенефициент')}
        </MenuItem>
        {data?.map((beneficiary, index) => (
          <MenuItem key={index} value={beneficiary.id}>
            {beneficiary.person
              ? `${beneficiary.person.firstName} ${beneficiary.person.lastName}`
              : `${beneficiary.company?.name}`}
          </MenuItem>
        ))}
      </Select>
      {helperText && <FormHelperText error>{helperText}</FormHelperText>}
    </FormControl>
  )
}
Example #6
Source File: DarkModeSwitch.tsx    From your_spotify with GNU General Public License v3.0 6 votes vote down vote up
export default function DarkModeSwitch() {
  const dispatch = useAppDispatch();
  const dark = useSelector(selectDarkMode);

  const changeDarkMode = useCallback(
    (mode: DarkModeType) => {
      dispatch(setDarkMode(mode));
    },
    [dispatch],
  );

  return (
    <Select
      variant="standard"
      value={dark}
      onChange={(ev) => changeDarkMode(ev.target.value as DarkModeType)}>
      <MenuItem value="follow">Follow system theme</MenuItem>
      <MenuItem value="dark">Use dark theme</MenuItem>
      <MenuItem value="light">Use light theme</MenuItem>
    </Select>
  );
}
Example #7
Source File: SelectCoordinator.tsx    From frontend with MIT License 6 votes vote down vote up
export default function SelectCoordinator({ name = 'coordinatorId' }) {
  const { t } = useTranslation()
  const [field] = useField(name)
  const { data: personList } = usePersonList()
  const { data: coordinatorList } = useCoordinatorsList()

  return (
    <FormControl fullWidth>
      <InputLabel>Избери</InputLabel>
      <Select fullWidth defaultValue="" label={t('campaigns:campaign.type')} {...field}>
        {personList
          ?.filter((person) => {
            return !coordinatorList?.find((c) => c.personId === person.id)
          })
          ?.map((person) => {
            return (
              <MenuItem key={person.id} value={person.id}>
                {person.firstName} {person.lastName}
              </MenuItem>
            )
          })}
      </Select>
    </FormControl>
  )
}
Example #8
Source File: ViewContractModal.tsx    From sapio-studio with Mozilla Public License 2.0 6 votes vote down vote up
export function ViewContractModal(props: {
    show: boolean;
    bitcoin_node_manager: BitcoinNodeManager;
}) {
    const dispatch = useDispatch();
    return (
        <Dialog open={props.show} onClose={() => dispatch(close_modal())}>
            <DialogTitle>View Existing Contract</DialogTitle>
            <DialogContent>
                <form>
                    <Select
                        placeholder="Existing Contract"
                        className=" mr-sm-2"
                    />
                    <Button type="submit">View</Button>
                </form>
            </DialogContent>
            <DialogActions>
                <Button onClick={() => dispatch(close_modal())}>Close</Button>
            </DialogActions>
        </Dialog>
    );
}
Example #9
Source File: CategorySelect.tsx    From mojito_pdm with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
CategorySelect: React.FC = () => {
    const theme = useTheme()
    const [category, setCategory] = useRecoilState(CarState.categorySearch)

    const handleChange = (event: SelectChangeEvent) => {
        setCategory(event.target.value)
    };

    return (
        <>
            <div>
                <FormControl variant="outlined" sx={{margin: theme.spacing(1), minWidth: 240}} color="error">
                    <InputLabel sx={{color: "white"}}>Category</InputLabel>
                    <Select sx={{color: "white"}}
                            labelId="demo-simple-select-outlined-label"
                            id="demo-simple-select-outlined"
                            value={category}
                            onChange={handleChange}
                            label="Category"
                    >
                        <MenuItem value="">
                            <em>All</em>
                        </MenuItem>
                        <MenuItem value={"Sports"}>Sports</MenuItem>
                        <MenuItem value={"Compacts"}>Compacts</MenuItem>
                        <MenuItem value={"Muscle"}>Muscle</MenuItem>
                        <MenuItem value={"Sedan"}>Sedan</MenuItem>
                        <MenuItem value={"Coupe"}>Coupé</MenuItem>
                        <MenuItem value={"Super"}>Super</MenuItem>
                        <MenuItem value={"SUV"}>SUV</MenuItem>
                        <MenuItem value={"Vans"}>Vans</MenuItem>
                        <MenuItem value={"Offroad"}>Offroad</MenuItem>
                        <MenuItem value={"Sports Classics"}>Sports Classics</MenuItem>
                        <MenuItem value={"Motorcycles"}>Motorcycles</MenuItem>
                    </Select>
                </FormControl>
            </div>
        </>
    )
}
Example #10
Source File: FileList.tsx    From frontend with MIT License 5 votes vote down vote up
function FileList({ files, onDelete, onSetFileRole, filesRole = [] }: Props) {
  const setFileRole = (file: File) => {
    return (event: SelectChangeEvent<CampaignFileRole>) => {
      if (Object.values(CampaignFileRole).includes(event.target.value as CampaignFileRole)) {
        onSetFileRole(file, event.target.value as CampaignFileRole)
      }
    }
  }

  return (
    <List dense>
      {files.map((file, key) => (
        <ListItem
          key={key}
          secondaryAction={
            <IconButton edge="end" aria-label="delete" onClick={() => onDelete && onDelete(file)}>
              <Delete />
            </IconButton>
          }>
          <ListItemAvatar>
            <Avatar>
              <UploadFile />
            </Avatar>
          </ListItemAvatar>
          <ListItemText primary={file.type} />
          <ListItemText primary={file.name} />
          <FormControl>
            <InputLabel id="choose-type-label">{'Избери роля'}</InputLabel>
            <Select<CampaignFileRole>
              id="choose-type"
              label="Избери роля"
              labelId="choose-type-label"
              value={
                filesRole.find((f) => f.file === file.name)?.role ?? CampaignFileRole.background
              }
              onChange={setFileRole(file)}>
              {Object.values(CampaignFileRole).map((role) => (
                <MenuItem key={role} value={role}>
                  {role}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
        </ListItem>
      ))}
    </List>
  )
}
Example #11
Source File: BestOfHour.tsx    From your_spotify with GNU General Public License v3.0 5 votes vote down vote up
export default function BestOfHour({ className }: BestOfHourProps) {
  const { interval } = useSelector(selectRawIntervalDetail);
  const [element, setElement] = useState<Element>(Element.ARTIST);
  const result = useAPI(elementToCall[element], interval.start, interval.end);

  const data = useMemo(() => {
    if (!result) {
      return [];
    }
    return Array.from(Array(24).keys()).map((index) => getElementData(result, index));
  }, [result]);

  const labelFormatter = useCallback(
    (label: string) => {
      return `20 most listened ${element} at ${label}:00`;
    },
    [element],
  );

  const valueFormatter = useCallback(
    (value: number, elementId: string, { payload }: any) => {
      const foundIndex = result?.findIndex((r) => r._id === payload.x);
      if (result && foundIndex !== undefined && foundIndex !== -1) {
        const found = result[foundIndex];
        return [`${value}% of ${getElementName(found, elementId)}`];
      }
      return [];
    },
    [result],
  );

  if (!result) {
    return (
      <LoadingImplementedChart title={`Best ${element} for hour of day`} className={className} />
    );
  }

  return (
    <ChartCard
      title={`Best ${element} for hour of day`}
      right={
        <Select
          value={element}
          onChange={(ev) => setElement(ev.target.value as Element)}
          variant="standard">
          {Object.values(Element).map((elem) => (
            <MenuItem key={elem} value={elem}>
              {elem}
            </MenuItem>
          ))}
        </Select>
      }
      className={className}>
      <StackedBar
        data={data}
        xFormat={formatX}
        tooltipLabelFormatter={labelFormatter}
        tooltipValueFormatter={valueFormatter}
        tooltipItemSorter={itemSorter as any}
      />
    </ChartCard>
  );
}
Example #12
Source File: SelectWrapper.tsx    From console with GNU Affero General Public License v3.0 5 votes vote down vote up
SelectWrapper = ({
  classes,
  id,
  name,
  onChange,
  options,
  label,
  tooltip = "",
  value,
  disabled = false,
}: SelectProps) => {
  return (
    <React.Fragment>
      <Grid item xs={12} className={classes.fieldContainer}>
        {label !== "" && (
          <InputLabel htmlFor={id} className={classes.inputLabel}>
            <span>{label}</span>
            {tooltip !== "" && (
              <div className={classes.tooltipContainer}>
                <Tooltip title={tooltip} placement="top-start">
                  <div className={classes.tooltip}>
                    <HelpIcon />
                  </div>
                </Tooltip>
              </div>
            )}
          </InputLabel>
        )}
        <FormControl fullWidth>
          <Select
            id={id}
            name={name}
            value={value}
            onChange={onChange}
            input={<SelectStyled />}
            disabled={disabled}
          >
            {options.map((option) => (
              <MenuItem
                value={option.value}
                key={`select-${name}-${option.label}`}
              >
                {option.label}
              </MenuItem>
            ))}
          </Select>
        </FormControl>
      </Grid>
    </React.Fragment>
  );
}
Example #13
Source File: Importer.tsx    From your_spotify with GNU General Public License v3.0 5 votes vote down vote up
export default function Importer() {
  const dispatch = useAppDispatch();
  const imports = useSelector(selectImportStates);
  const [importType, setImportType] = useState<ImporterStateTypes>(ImporterStateTypes.privacy);

  const fetch = useCallback(
    async (force = false) => {
      dispatch(getImports(force));
    },
    [dispatch],
  );

  useEffect(() => {
    fetch();
  }, [fetch]);

  const running = useMemo(() => imports?.find((st) => st.status === 'progress'), [imports]);
  const Component = useMemo(
    () => (importType ? ImportTypeToComponent[importType] : null),
    [importType],
  );

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

  return (
    <div>
      <div>
        {running && (
          <div>
            <Text>Importing...</Text>
            <div className={s.progress}>
              <Text>
                {running.current} / {running.total}
              </Text>
            </div>
            <LinearProgress
              style={{ width: '100%' }}
              variant="determinate"
              value={(running.current / running.total) * 100}
            />
          </div>
        )}
      </div>
      {!running && (
        <div>
          <FormControl className={s.selectimport}>
            <InputLabel id="import-type-select">Import type</InputLabel>
            <Select
              labelId="import-type-select"
              value={importType}
              label="Import type"
              onChange={(ev) => setImportType(ev.target.value as ImporterStateTypes)}>
              {Object.values(ImporterStateTypes).map((typ) => (
                <MenuItem value={typ} key={typ}>
                  {typ}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
          {Component && <Component />}
        </div>
      )}
      {imports.length > 0 && <ImportHistory />}
    </div>
  );
}
Example #14
Source File: MultiSelect.tsx    From multi-downloader-nx with MIT License 5 votes vote down vote up
MultiSelect: React.FC<MultiSelectProps> = (props) => {
  const theme = useTheme();

  return <div>
    <FormControl sx={{ m: 1, width: 300 }}>
      <InputLabel id="multi-select-label">{props.title}</InputLabel>
      <Select
        labelId="multi-select-label"
        id="multi-select"
        multiple
        value={(props.selected ?? [])}
        onChange={e => {
          const val = typeof e.target.value === "string" ? e.target.value.split(",") : e.target.value;
          if (props.allOption && val.includes('all')) {
            if (props.values.length === val.length - 1)
              props.onChange([]);
            else 
              props.onChange(props.values);
          } else {
            props.onChange(val);
          }
        }}
        input={<OutlinedInput id="select-multiple-chip" label={props.title} />}
        renderValue={(selected) => (
          selected.join(', ')
        )}
        MenuProps={MenuProps}
      >
        {props.values.concat(props.allOption ? 'all' : []).map((name) => (
          <MenuItem
            key={`${props.title}_${name}`}
            value={name}
            style={getStyles(name, props.selected, theme)}
          >
            {name}
          </MenuItem>
        ))}
      </Select>
    </FormControl>
  </div>
}
Example #15
Source File: StyleField.tsx    From Cromwell with MIT License 5 votes vote down vote up
export function StyleField(props: {
    dataType: 'px' | 'string' | 'color' | 'select';
    handleStyleChange: (name: keyof React.CSSProperties, value: any) => void;
    data: TCromwellBlockData;
    name: keyof React.CSSProperties;
    label: string;
    className?: string;
    style?: React.CSSProperties;
    options?: string[];
}) {
    let val = props.data?.style?.[props.name];
    if (props.dataType === 'px') {
        if (val) val = parseFloat(val);
        if (isNaN(val)) val = undefined;
    }

    let noWrapper = true;
    let Field: React.ComponentType<any> = TextField;
    if (props.dataType === 'color') {
        Field = ColorPicker;
    }
    if (props.dataType === 'select') {
        Field = Select;
        noWrapper = false;
    }

    let content = (
        <Field
            onChange={e => {
                let value: any = e?.target?.value ?? e;
                if (props.dataType === 'px') {
                    if (value) value = parseFloat(value);
                    if (isNaN(value) || value === '' || value === null) value = undefined;
                    if (value !== undefined) value += 'px';
                }
                props.handleStyleChange(props.name, value);
            }}
            variant="standard"
            value={val ?? ''}
            type={props.dataType === 'px' ? 'number' : 'string'}
            label={noWrapper ? props.label : undefined}
            className={noWrapper ? props.className : undefined}
            style={noWrapper ? props.style : undefined}
        >{props.options?.map(opt => <MenuItem value={opt} key={opt}>{opt}</MenuItem>)}</Field>
    );

    if (props.dataType === 'select') {
        content = (
            <FormControl
                className={props.className}
                style={props.style}
            >
                <InputLabel>{props.label}</InputLabel>
                {content}
            </FormControl>
        )
    }

    return content;
}
Example #16
Source File: Sort.tsx    From cli with Apache License 2.0 5 votes vote down vote up
SortRenderer: FunctionComponent<SortProps> = (props) => {
  const {controller, criteria} = props;
  const [state, setState] = React.useState(controller.state);

  useEffect(
    () => controller.subscribe(() => setState(controller.state)),
    [controller]
  );

  const getCurrentCriterion = () =>
    criteria.find(
      ([, criterion]) =>
        state.sortCriteria === buildCriterionExpression(criterion)
    )!;

  const getCriterionFromName = (name: string) =>
    criteria.find(([criterionName]) => criterionName === name)!;

  return (
    <Box>
      <FormControl>
        <InputLabel id="sort-by-label">Sort by</InputLabel>
        <Select
          labelId="sort-by-label"
          label="Sort by"
          id="sort-by"
          onChange={(e) =>
            controller.sortBy(getCriterionFromName(e.target.value as string)[1])
          }
          defaultValue={getCurrentCriterion()[0]}
        >
          {criteria.map(([criterionName]) => (
            <MenuItem key={criterionName} value={criterionName}>
              {criterionName}
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </Box>
  );
}
Example #17
Source File: Sort.tsx    From Cromwell with MIT License 5 votes vote down vote up
export default function Sort<TEntity>(props: {
    options: TSortOption<TEntity>[];
    onChange: (key: keyof TEntity, order: 'ASC' | 'DESC') => any;
}) {
    const [orderByKey, setOrderByKey] = useState<keyof TEntity | null>(null);
    const [order, setOrder] = useState<'ASC' | 'DESC'>('DESC');

    const handleChangeOrderByKey = (key: keyof TEntity) => {
        setOrderByKey(key);
        props.onChange(key, order);
    }
    const toggleOrder = () => {
        setOrder(prev => {
            const newOrder = prev === 'ASC' ? 'DESC' : 'ASC';
            props.onChange(orderByKey, newOrder);
            return newOrder;
        });
    }
    return (
        <FormControl className={styles.wrapper}>
            <InputLabel>Sort</InputLabel>
            <Select
                style={{ minWidth: '60px', maxWidth: '100px' }}
                size="small"
                value={orderByKey ?? 'id'}
                label="Sort"
                onChange={event => handleChangeOrderByKey(event.target.value as any)}
                classes={{
                    icon: styles.selectIcon,
                    select: styles.muiSelect,
                }}
            >
                {props.options.map(sort => (
                    <MenuItem key={sort.key + ''} value={sort.key + ''}>{sort.label}</MenuItem>
                ))}
            </Select>
            <div onClick={toggleOrder} className={styles.orderButton}>
                <ArrowDropDownIcon
                    style={{
                        transform: order === 'ASC' ? 'rotate(180deg)' : undefined,
                        transition: '0.3s',
                    }}
                />
            </div>
        </FormControl>
    )
}
Example #18
Source File: index.tsx    From metaplex with Apache License 2.0 4 votes vote down vote up
Settings = ({ narrow }: { narrow: boolean }) => {
  const { disconnect, publicKey } = useWallet();
  const { setEndpoint, env, endpoint } = useConnectionConfig();
  const { setVisible } = useWalletModal();
  const open = React.useCallback(() => setVisible(true), [setVisible]);
  const { setModal } = useModal();
  const theme = useTheme();
  const colorModeCtx = useColorMode();

  const handleConnect = React.useCallback(() => {
    setModal(ModalEnum.WALLET);
    setVisible(true);
  }, [setModal, setVisible]);

  const connectedActions = [
    {
      click: async () => {
        if (publicKey) {
          await navigator.clipboard.writeText(publicKey.toBase58());
          notify({
            message: 'Wallet update',
            description: 'Address copied to clipboard',
          });
        }
      },
      innerNarrow: () =>
        `Copy Address (${publicKey && shortenAddress(publicKey.toBase58())})`,
      inner: function ConnectedWalletCopyC() {
        return (
          <React.Fragment>
            <CopyOutlined />
            {publicKey && shortenAddress(publicKey.toBase58())}
          </React.Fragment>
        );
      },
    },
    {
      click: open,
      inner: () => 'Change\u00A0Wallet',
    },
    {
      click: () => disconnect().catch(),
      inner: () => `Disconnect\u00A0(${env})`,
      expandedExtra: {
        // these are interepreted as props. TODO: specific types
        color: 'error' as any,
        variant: 'contained' as any,
      },
    },
  ];

  const [drawerOpen, setDrawerOpen] = React.useState(false);
  const [envCollapseOpen, setEnvCollapseOpen] = React.useState(false);

  const hackySkipSet = 'hackySkipSet';
  const toggleDrawer = open => event => {
    if (
      event.type === 'keydown' &&
      (event.key === 'Tab' || event.key === 'Shift')
    ) {
      return;
    }

    if (event.target.classList.contains(hackySkipSet)) {
      return;
    }

    setDrawerOpen(open);
  };

  const drawerC = inner => {
    return (
      <React.Fragment>
        <Button onClick={toggleDrawer(true)}>
          <AccountBalanceWalletIcon />
        </Button>
        <Drawer anchor="right" open={drawerOpen} onClose={toggleDrawer(false)}>
          <Box
            sx={{ width: 250 }}
            role="presentation"
            onClick={toggleDrawer(false)}
            onKeyDown={toggleDrawer(false)}
          >
            {inner}
          </Box>
        </Drawer>
      </React.Fragment>
    );
  };

  const themeSwitch = (
    <Button
      sx={{ ml: 1 }}
      onClick={colorModeCtx.toggleColorMode}
      color="inherit"
    >
      {theme.palette.mode === 'dark' ? (
        <Brightness7Icon />
      ) : (
        <Brightness4Icon />
      )}
    </Button>
  );

  if (narrow) {
    const listHead = (
      <ListItem>
        <ListItemText
          primary="Wallet"
          primaryTypographyProps={{
            fontSize: '1.2rem',
            fontWeight: 'medium',
            letterSpacing: 0,
          }}
        />
      </ListItem>
    );
    return (
      <React.Fragment>
        {!publicKey &&
          drawerC(
            <List>
              {listHead}
              <Divider />
              <ListItemButton
                onClick={() => setEnvCollapseOpen(!envCollapseOpen)}
                className={hackySkipSet}
              >
                Change Network
                {envCollapseOpen ? <ExpandLess /> : <ExpandMore />}
              </ListItemButton>
              <Collapse in={envCollapseOpen} timeout="auto" unmountOnExit>
                <List component="div" disablePadding>
                  {ENDPOINTS.map(p => (
                    <ListItemButton
                      selected={endpoint === p.endpoint}
                      onClick={() => setEndpoint(p.endpoint)}
                      key={p.name}
                      sx={{ pl: 4 }}
                      className={hackySkipSet}
                    >
                      {p.name}
                    </ListItemButton>
                  ))}
                </List>
              </Collapse>
              <ListItemButton onClick={handleConnect}>Connect</ListItemButton>
            </List>,
          )}
        {publicKey &&
          drawerC(
            <List>
              {listHead}
              <Divider />
              {connectedActions.map((a, idx) => {
                return (
                  <ListItemButton onClick={a.click} key={idx}>
                    {(a.innerNarrow && a.innerNarrow()) || a.inner()}
                  </ListItemButton>
                );
              })}
            </List>,
          )}
        {themeSwitch}
      </React.Fragment>
    );
  } else {
    return (
      <Stack
        direction="row"
        spacing={2}
        sx={{
          display: 'flex',
          justifyContent: 'flex-end',
          alignItems: 'center',
          marginRight: '36px',
        }}
      >
        {!publicKey && (
          <React.Fragment>
            <FormControl variant="standard" style={{ minWidth: '10ch' }}>
              <Select
                id="connected-env-select"
                onChange={e => {
                  setEndpoint(e.target.value);
                }}
                value={endpoint}
              >
                {ENDPOINTS.map(({ name, endpoint }) => (
                  <MenuItem key={name} value={endpoint}>
                    {name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
            <Link underline="none">
              <Button variant="contained" onClick={handleConnect}>
                Connect
              </Button>
            </Link>
          </React.Fragment>
        )}
        {publicKey &&
          connectedActions.map((a, idx) => {
            return (
              <Button
                key={idx}
                variant="outlined"
                onClick={a.click}
                {...a.expandedExtra}
              >
                {a.inner()}
              </Button>
            );
          })}
        {themeSwitch}
      </Stack>
    );
  }
}
Example #19
Source File: EditForm.tsx    From frontend with MIT License 4 votes vote down vote up
export default function EditForm() {
  const queryClient = useQueryClient()
  const router = useRouter()
  const id = router.query.id
  const { data }: UseQueryResult<WithdrawalEditResponse> = useWithdrawal(String(id))
  const { data: bankAccounts } = useBankAccountsList()
  const { data: campaigns } = useCampaignList()
  const { data: personList } = usePersonList()
  const { data: vaults } = useVaultsList()

  const [bankAccountId, setBankAccountId] = useState(data?.bankAccountId)
  const [vaultId, setVaultId] = useState(data?.sourceVaultId)
  const [campaignId, setCampaignId] = useState(data?.sourceCampaignId)
  const [approvedById, setApprovedById] = useState(data?.approvedById)

  const { t } = useTranslation()

  const mutationFn = useEditWithdrawal(String(id))

  const initialValues: WithdrawalInput = {
    status: WithdrawalStatus.initial,
    currency: data?.currency,
    amount: data?.amount,
    reason: data?.reason,
    sourceVaultId: vaultId,
    sourceCampaignId: campaignId,
    bankAccountId: bankAccountId,
    documentId: '',
    approvedById: approvedById,
  }

  const mutation = useMutation<
    AxiosResponse<WithdrawalResponse>,
    AxiosError<ApiErrors>,
    WithdrawalInput
  >({
    mutationFn,
    onError: () => AlertStore.show(t('withdrawals:alerts:error'), 'error'),
    onSuccess: () => {
      queryClient.invalidateQueries(endpoints.withdrawals.getWithdrawal(String(id)).url)
      AlertStore.show(t('withdrawals:alerts:edit'), 'success')
      router.push(routes.admin.withdrawals.index)
    },
  })

  function handleSubmit(values: WithdrawalInput) {
    const data: WithdrawalInput = {
      status: WithdrawalStatus.initial,
      currency: values.currency,
      amount: values.amount,
      reason: values.reason,
      sourceVaultId: vaultId,
      sourceCampaignId: campaignId,
      bankAccountId: bankAccountId,
      documentId: 'ff89a831-34da-4b2d-91bc-742247efd9b8',
      approvedById: approvedById,
    }
    mutation.mutate(data)
  }

  return (
    <GenericForm
      onSubmit={handleSubmit}
      initialValues={initialValues}
      validationSchema={validationSchema}>
      <Box>
        <Typography variant="h5" component="h2" sx={{ marginBottom: 2, textAlign: 'center' }}>
          {t('withdrawals:form-heading')}
        </Typography>
        <Grid container spacing={2} sx={{ width: 600, margin: '0 auto' }}>
          <Grid item xs={12}>
            <FormTextField
              type="number"
              label="wihdrawals:Сума"
              name="amount"
              autoComplete="amount"
            />
          </Grid>
          <Grid item xs={12}>
            <FormTextField
              type="string"
              label="wihdrawals:Причина"
              name="reason"
              autoComplete="reason"
            />
          </Grid>
          <Grid item xs={12}>
            <CurrencySelect />
          </Grid>
          <Grid item xs={12}>
            <InputLabel htmlFor="my-input">Банков акаунт</InputLabel>
            <Select
              fullWidth
              id="bankAccountId"
              name="bankAccountId"
              value={bankAccountId}
              onChange={(event) => setBankAccountId(event.target.value)}>
              {bankAccounts?.map((acc) => {
                return (
                  <MenuItem key={acc.id} value={acc.id}>
                    {acc.accountHolderName}
                  </MenuItem>
                )
              })}
            </Select>
          </Grid>
          <Grid item xs={12}>
            <InputLabel htmlFor="my-input">Кампании</InputLabel>
            <Select
              fullWidth
              id="campaignId"
              name="campaignId"
              value={campaignId}
              onChange={(event) => setCampaignId(event.target.value)}>
              {campaigns?.map((camp) => {
                return (
                  <MenuItem key={camp.id} value={camp.id}>
                    {camp.title}
                  </MenuItem>
                )
              })}
            </Select>
          </Grid>
          <Grid item xs={12}>
            <InputLabel htmlFor="my-input">Трезор</InputLabel>
            <Select
              fullWidth
              id="vaultId"
              name="vaultId"
              value={vaultId}
              onChange={(event) => setVaultId(event.target.value)}>
              {vaults?.map((acc) => {
                return (
                  <MenuItem key={acc.id} value={acc.id}>
                    {acc.name}
                  </MenuItem>
                )
              })}
            </Select>
          </Grid>
          <Grid item xs={12}>
            <InputLabel htmlFor="my-input">Одобрен от</InputLabel>
            <Select
              fullWidth
              id="approvedById"
              name="approvedById"
              value={approvedById}
              onChange={(event) => setApprovedById(event.target.value)}>
              {personList?.map((acc) => {
                return (
                  <MenuItem key={acc.id} value={acc.id}>
                    {acc.firstName} {acc.lastName}
                  </MenuItem>
                )
              })}
            </Select>
          </Grid>
          <Grid item xs={6}>
            <SubmitButton fullWidth label={t('withdrawals:cta:submit')} />
          </Grid>
          <Grid item xs={6}>
            <Link href={routes.admin.withdrawals.index} passHref>
              <Button fullWidth={true}>{t('withdrawals:cta:cancel')}</Button>
            </Link>
          </Grid>
        </Grid>
      </Box>
    </GenericForm>
  )
}
Example #20
Source File: SettingsView.tsx    From react-flight-tracker with MIT License 4 votes vote down vote up
SettingsView: React.FC<Props> = (props) => {

  // Fields
  const contextName: string = ViewKeys.SettingsView;

  // Contexts
  const systemContext = useContext(SystemContext);
  const appContext = useContext(AppContext);

  const getSetting = (key: string, type: string) => {

    const value = systemContext.getSetting(key)
    if (typeof (value) === type)
      return value;

    return false;
  };

  const handleChange = (e: SelectChangeEvent) => {
    appContext.changeTheme(e.target.value);
  };

  const handleSettingsChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    systemContext.storeSetting(e.target.name, e.target.checked);
  };

  const renderAppSettings = () => {

    return (
      <Card>

        <CardContent>

          <Typography
            variant={'h6'}
            gutterBottom={true}>
            {'App settings'}
          </Typography>

          <FormGroup>
            <FormControl
              color='secondary'
              variant="filled"
              sx={{ m: 1, minWidth: 120 }}>

              <InputLabel
                id="demo-simple-select-filled-label">
                Theme change
              </InputLabel>
              <Select
                labelId="demo-simple-select-filled-label"
                id="demo-simple-select-filled"
                value={appContext.activeThemeName}
                onChange={handleChange}>

                <MenuItem
                  value={ThemeKeys.DarkTheme}>
                  {ThemeKeys.DarkTheme}
                </MenuItem>
                <MenuItem
                  value={ThemeKeys.LightTheme}>
                  {ThemeKeys.LightTheme}
                </MenuItem>
                <MenuItem
                  value={ThemeKeys.PineappleTheme}>
                  {ThemeKeys.PineappleTheme}
                </MenuItem>
              </Select>
            </FormControl>

          </FormGroup>
        </CardContent>
      </Card>
    );
  };

  const renderMapSettings = () => {

    return (
      <Card>

        <CardContent>

          <Typography
            variant={'h6'}
            gutterBottom={true}>
            {'Map settings'}
          </Typography>

          <FormGroup>
            <FormControlLabel
              control={
                <Switch
                  color='secondary'
                  name={SettingKeys.ShowDataOverlayOnMap}
                  checked={getSetting(SettingKeys.ShowDataOverlayOnMap, 'boolean')}
                  onChange={handleSettingsChange} />
              }
              label="Show data overlay on map"
            />
            <FormControlLabel
              control={
                <Switch
                  color='secondary'
                  name={SettingKeys.ShowLogOverlayOnMap}
                  checked={getSetting(SettingKeys.ShowLogOverlayOnMap, 'boolean')}
                  onChange={handleSettingsChange} />
              }
              label="Show log overlay on map"
            />
          </FormGroup>
        </CardContent>
      </Card>
    );
  };

  return (

    <ViewContainer
      isScrollLocked={true}>

      {renderAppSettings()}

      <Box sx={{ height: (theme) => theme.spacing(1) }} />

      {renderMapSettings()}
    </ViewContainer>
  );
}
Example #21
Source File: Form.tsx    From frontend with MIT License 4 votes vote down vote up
export default function Form() {
  const router = useRouter()
  const { t } = useTranslation()
  let id = router.query.id
  const [beneficiaryType, setBeneficiaryType] = useState<string>('')
  const [personId, setPersonId] = useState<string>('')
  const [companyId, setCompanyId] = useState<string>('')
  const [coordinatorId, setCoordinatorId] = useState<string>('')
  const [cityId, setCityId] = useState<string>('')
  const [countryCode, setCountryCode] = useState<string>('')
  const people = usePeopleList().data
  const companies = useCompaniesList().data
  const coordinators = useCoordinatorsList().data
  const coordinatorRelations = Object.values(PersonRelation)
  const cities = useCitiesList().data
  const countries = useCountriesList().data

  let initialValues: BeneficiaryFormData = {
    type: beneficiaryType,
    personId: personId,
    companyId: companyId,
    coordinatorId: coordinatorId,
    countryCode: countryCode,
    cityId: cityId,
    description: '',
    publicData: '',
    privateData: '',
    coordinatorRelation: 'none',
    campaigns: [],
  }

  if (id) {
    id = String(id)
    const { data }: UseQueryResult<BeneficiaryListResponse> = useViewBeneficiary(id)
    initialValues = {
      type: data?.type,
      cityId: data?.cityId || '',
      companyId: data?.companyId || '',
      coordinatorId: data?.coordinatorId || '',
      countryCode: data?.countryCode || '',
      description: data?.description || '',
      personId: data?.personId || '',
      privateData: data?.privateData || '',
      publicData: data?.publicData || '',
      coordinatorRelation: data?.coordinatorRelation || '',
      campaigns: data?.campaigns || [],
    }
  }
  const mutationFn = id ? useEditBeneficiary(id) : useCreateBeneficiary()

  const mutation = useMutation<
    AxiosResponse<BeneficiaryListResponse>,
    AxiosError<ApiErrors>,
    BeneficiaryFormData
  >({
    mutationFn,
    onError: () => AlertStore.show(t('documents:alerts:error'), 'error'),
    onSuccess: () => {
      AlertStore.show(id ? t('documents:alerts:edit') : t('documents:alerts:create'), 'success')
      router.push(routes.admin.beneficiary.index)
    },
  })

  async function onSubmit(data: BeneficiaryFormData) {
    mutation.mutateAsync(data)
  }

  return (
    <GenericForm
      onSubmit={onSubmit}
      initialValues={initialValues}
      validationSchema={validationSchema}>
      <Box sx={{ height: '62.6vh', marginBottom: '9%' }}>
        <Typography variant="h5" component="h2" sx={{ textAlign: 'center' }}>
          {id ? t('beneficiary:forms:edit-heading') : t('beneficiary:forms:add-heading')}
        </Typography>
        <Grid container spacing={2}>
          <Grid item xs={12}>
            <InputLabel>{t('beneficiary:grid:type')}</InputLabel>
            <Select
              fullWidth
              sx={{ height: '55%' }}
              name="type"
              defaultValue={initialValues.type}
              onChange={(e: SelectChangeEvent) => {
                setBeneficiaryType(e.target.value)
              }}>
              <MenuItem value="">
                <em>None</em>
              </MenuItem>
              {Object.values(LegalEntityType)?.map((type) => {
                return (
                  <MenuItem key={type} value={type}>
                    {t('beneficiary:grid:' + type)}
                  </MenuItem>
                )
              })}
            </Select>
          </Grid>
          <Grid item xs={6}>
            <InputLabel>{t('beneficiary:grid:individual')}</InputLabel>
            <Select
              fullWidth
              sx={{ height: '55%' }}
              name="personId"
              defaultValue={initialValues.personId}
              onChange={(e: SelectChangeEvent) => {
                setPersonId(e.target.value)
              }}>
              <MenuItem value="">
                <em>None</em>
              </MenuItem>
              {people?.map((person) => {
                return (
                  <MenuItem key={person.id} value={person.id}>
                    {person.firstName + ' ' + person.lastName}
                  </MenuItem>
                )
              })}
            </Select>
          </Grid>
          <Grid item xs={6}>
            <InputLabel>{t('beneficiary:grid:company')}</InputLabel>
            <Select
              fullWidth
              sx={{ height: '55%' }}
              name="companyId"
              defaultValue={initialValues.personId}
              onChange={(e: SelectChangeEvent) => {
                setCompanyId(e.target.value)
              }}>
              <MenuItem value="">
                <em>None</em>
              </MenuItem>
              {companies?.map((company) => {
                return (
                  <MenuItem key={company.id} value={company.id}>
                    {company.companyName}
                  </MenuItem>
                )
              })}
            </Select>
          </Grid>
          <Grid item xs={6}>
            <InputLabel>{t('beneficiary:grid:coordinatorRelation')}</InputLabel>
            <Select
              fullWidth
              sx={{ height: '55%' }}
              name="coordinatorRelation"
              defaultValue={initialValues.coordinatorRelation}
              onChange={(e: SelectChangeEvent) => {
                setPersonId(e.target.value)
              }}>
              <MenuItem value="">
                <em>None</em>
              </MenuItem>
              {coordinatorRelations?.map((relation) => {
                return (
                  <MenuItem key={relation} value={relation}>
                    {relation}
                  </MenuItem>
                )
              })}
            </Select>
          </Grid>
          <Grid item xs={6}>
            <InputLabel>{t('beneficiary:grid:coordinator')}</InputLabel>
            <Select
              fullWidth
              sx={{ height: '55%' }}
              name="coordinatorId"
              defaultValue={initialValues.coordinatorId}
              onChange={(e: SelectChangeEvent) => {
                setCoordinatorId(e.target.value)
              }}>
              <MenuItem value="">
                <em>None</em>
              </MenuItem>
              {coordinators?.map((coordinator) => {
                return (
                  <MenuItem key={coordinator.id} value={coordinator.id}>
                    {coordinator.person.firstName} {coordinator.person.lastName}
                  </MenuItem>
                )
              })}
            </Select>
          </Grid>
          <Grid item xs={6}>
            <InputLabel>{t('beneficiary:grid:countryCode')}</InputLabel>
            <Select
              fullWidth
              sx={{ height: '55%' }}
              name="countryCode"
              defaultValue={initialValues.countryCode}
              onChange={(e: SelectChangeEvent) => {
                setCountryCode(e.target.value)
              }}>
              <MenuItem value="">
                <em>None</em>
              </MenuItem>
              {countries?.map((country) => {
                return (
                  <MenuItem key={country.id} value={country.countryCode}>
                    {country.countryCode} - {country.name}
                  </MenuItem>
                )
              })}
            </Select>
          </Grid>
          <Grid item xs={6}>
            <InputLabel>{t('beneficiary:grid:city')}</InputLabel>
            <Select
              fullWidth
              sx={{ height: '55%' }}
              name="cityId"
              defaultValue={initialValues.cityId}
              onChange={(e: SelectChangeEvent) => {
                setCityId(e.target.value)
              }}>
              <MenuItem value="">
                <em>None</em>
              </MenuItem>
              {cities?.map((city) => {
                return (
                  <MenuItem key={city.id} value={city.id}>
                    {city.name}
                  </MenuItem>
                )
              })}
            </Select>
          </Grid>
          <Grid item xs={6}>
            <FormTextField
              type="text"
              name="description"
              autoComplete="target-amount"
              label={t('beneficiary:grid:description')}
              multiline
              rows={1.5}
              defaultValue={initialValues.description}
            />
          </Grid>
          <Grid item xs={6}>
            <SubmitButton fullWidth label={t('documents:cta:submit')} />
          </Grid>
          <Grid item xs={6}>
            <Link href={routes.admin.beneficiary.index} passHref>
              <Button>{t('documents:cta:cancel')}</Button>
            </Link>
          </Grid>
        </Grid>
      </Box>
    </GenericForm>
  )
}
Example #22
Source File: Withdraw.tsx    From wrap.scrt.network with MIT License 4 votes vote down vote up
export default function Withdraw({
  token,
  secretjs,
  secretAddress,
  balances,
  onSuccess,
  onFailure,
}: {
  token: Token;
  secretjs: SecretNetworkClient | null;
  secretAddress: string;
  balances: Map<string, string>;
  onSuccess: (txhash: string) => any;
  onFailure: (error: any) => any;
}) {
  const [targetAddress, setTargetAddress] = useState<string>("");
  const [loadingTx, setLoading] = useState<boolean>(false);
  const [selectedChainIndex, setSelectedChainIndex] = useState<number>(0);
  const inputRef = useRef<any>();
  const maxButtonRef = useRef<any>();

  const sourceChain = chains["Secret Network"];
  const targetChain =
    chains[token.withdrawals[selectedChainIndex].target_chain_name];

  const availableBalance =
    balances.get(token.withdrawals[selectedChainIndex].from_denom) || "";

  useEffect(() => {
    (async () => {
      while (!window.keplr || !window.getOfflineSignerOnlyAmino) {
        await sleep(100);
      }

      // Find address on target chain
      const { chain_id: targetChainId } =
        chains[token.withdrawals[selectedChainIndex].target_chain_name];
      if (token.withdrawals[selectedChainIndex].target_chain_name === "Terra") {
        await suggestTerraToKeplr(window.keplr);
      }
      await window.keplr.enable(targetChainId);
      const targetOfflineSigner =
        window.getOfflineSignerOnlyAmino(targetChainId);
      const targetFromAccounts = await targetOfflineSigner.getAccounts();
      setTargetAddress(targetFromAccounts[0].address);
    })();
  }, [selectedChainIndex]);

  return (
    <>
      <div style={{ padding: "1.5em" }}>
        <div
          style={{
            display: "flex",
            placeItems: "center",
            gap: "0.5em",
          }}
        >
          <Typography>
            Withdraw <strong>{token.name}</strong> from{" "}
            <strong>Secret Network</strong> to
          </Typography>
          <If condition={token.withdrawals.length === 1}>
            <Then>
              <Typography sx={{ marginLeft: "-0.2em" }}>
                <strong>
                  {token.withdrawals[selectedChainIndex].target_chain_name}
                </strong>
              </Typography>
            </Then>
            <Else>
              <FormControl>
                <Select
                  value={selectedChainIndex}
                  onChange={(e) =>
                    setSelectedChainIndex(Number(e.target.value))
                  }
                >
                  {token.withdrawals.map((chain, index) => (
                    <MenuItem value={index} key={index}>
                      <div
                        style={{
                          display: "flex",
                          gap: "0.5em",
                          placeItems: "center",
                        }}
                      >
                        <Avatar
                          src={chains[chain.target_chain_name].chain_image}
                          sx={{
                            marginLeft: "0.3em",
                            width: "1em",
                            height: "1em",
                            boxShadow: "rgba(0, 0, 0, 0.15) 0px 6px 10px",
                          }}
                        />
                        <strong>{chain.target_chain_name}</strong>
                      </div>
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Else>
          </If>
        </div>
        <br />
        <div
          style={{
            display: "flex",
            placeContent: "space-between",
            placeItems: "center",
            gap: "1em",
          }}
        >
          <Typography sx={{ fontWeight: "bold" }}>From:</Typography>
          <CopyableAddress
            address={secretAddress}
            explorerPrefix={sourceChain.explorer_account}
          />
        </div>
        <div
          style={{
            display: "flex",
            placeContent: "space-between",
            placeItems: "center",
            gap: "1em",
          }}
        >
          <Typography sx={{ fontWeight: "bold" }}>To:</Typography>
          <CopyableAddress
            address={targetAddress}
            explorerPrefix={targetChain.explorer_account}
          />
        </div>
        <br />
        <div
          style={{
            display: "flex",
            placeItems: "center",
            gap: "0.3em",
            marginBottom: "0.8em",
          }}
        >
          <Typography sx={{ fontSize: "0.8em", fontWeight: "bold" }}>
            Available to Withdraw:
          </Typography>
          <Typography
            sx={{
              fontSize: "0.8em",
              opacity: 0.8,
              cursor: "pointer",
            }}
            onClick={() => {
              maxButtonRef.current.click();
            }}
          >
            {(() => {
              if (availableBalance === "") {
                return <CircularProgress size="0.6em" />;
              }

              const prettyBalance = new BigNumber(availableBalance)
                .dividedBy(`1e${token.decimals}`)
                .toFormat();

              if (prettyBalance === "NaN") {
                return "Error";
              }

              return `${prettyBalance} ${token.name}`;
            })()}
          </Typography>
        </div>
        <FormControl sx={{ width: "100%" }} variant="standard">
          <InputLabel htmlFor="Amount to Withdraw">
            Amount to Withdraw
          </InputLabel>
          <Input
            autoFocus
            id="Amount to Withdraw"
            fullWidth
            type="text"
            inputRef={inputRef}
            startAdornment={
              <InputAdornment position="start">
                <Avatar
                  src={token.image}
                  sx={{
                    width: "1em",
                    height: "1em",
                    boxShadow: "rgba(0, 0, 0, 0.15) 0px 6px 10px",
                  }}
                />
              </InputAdornment>
            }
            endAdornment={
              <InputAdornment position="end">
                <Button
                  ref={maxButtonRef}
                  style={{
                    padding: "0.1em 0.5em",
                    minWidth: 0,
                  }}
                  onClick={() => {
                    if (availableBalance === "") {
                      return;
                    }

                    const prettyBalance = new BigNumber(availableBalance)
                      .dividedBy(`1e${token.decimals}`)
                      .toFormat();

                    if (prettyBalance === "NaN") {
                      return;
                    }

                    inputRef.current.value = prettyBalance;
                  }}
                >
                  MAX
                </Button>
              </InputAdornment>
            }
          />
        </FormControl>
      </div>
      <div
        style={{
          display: "flex",
          placeContent: "center",
          marginBottom: "0.4em",
        }}
      >
        <LoadingButton
          variant="contained"
          sx={{
            padding: "0.5em 0",
            width: "10em",
            fontWeight: "bold",
            fontSize: "1.2em",
          }}
          loading={loadingTx}
          onClick={async () => {
            if (!secretjs) {
              console.error("No secretjs");
              return;
            }

            if (!inputRef?.current?.value) {
              console.error("Empty withdraw");
              return;
            }

            const normalizedAmount = (inputRef.current.value as string).replace(
              /,/g,
              ""
            );

            if (!(Number(normalizedAmount) > 0)) {
              console.error(`${normalizedAmount} not bigger than 0`);
              return;
            }

            setLoading(true);

            const amount = new BigNumber(normalizedAmount)
              .multipliedBy(`1e${token.decimals}`)
              .toFixed(0, BigNumber.ROUND_DOWN);

            const { withdraw_channel_id, withdraw_gas } =
              chains[token.withdrawals[selectedChainIndex].target_chain_name];
            try {
              const tx = await secretjs.tx.broadcast(
                [
                  new MsgTransfer({
                    sender: secretAddress,
                    receiver: targetAddress,
                    sourceChannel: withdraw_channel_id,
                    sourcePort: "transfer",
                    token: {
                      amount,
                      denom: token.withdrawals[selectedChainIndex].from_denom,
                    },
                    timeoutTimestampSec: String(
                      Math.floor(Date.now() / 1000) + 15 * 60
                    ), // 15 minute timeout
                  }),
                ],
                {
                  gasLimit: withdraw_gas,
                  gasPriceInFeeDenom: 0.25,
                  feeDenom: "uscrt",
                }
              );

              if (tx.code === 0) {
                inputRef.current.value = "";
                onSuccess(tx.transactionHash);
              } else {
                onFailure(tx.rawLog);
              }
            } catch (e) {
              onFailure(e);
            } finally {
              setLoading(false);
            }
          }}
        >
          Withdraw
        </LoadingButton>
      </div>
    </>
  );
}
Example #23
Source File: PSBTDetail.tsx    From sapio-studio with Mozilla Public License 2.0 4 votes vote down vote up
export function PSBTDetail(props: IProps) {
    const psbt_selection_form = React.useRef<HTMLSelectElement>(null);
    const [psbt, setPSBT] = React.useState<Bitcoin.Psbt>(props.psbts[0]!);
    const [flash, setFlash] = React.useState<JSX.Element | null>(null);
    if (props.psbts.length === 0) return null;
    function show_flash(
        msg: string | JSX.Element,
        color: string,
        onclick?: () => void
    ) {
        const click = onclick ?? (() => null);
        const elt = (
            <h3 style={{ color: color }} onClick={click}>
                {msg}
            </h3>
        );
        setFlash(elt);
        setTimeout(() => setFlash(<div></div>), 2000);
    }
    const psbt_handler = new PSBTHandler(show_flash);

    const selectable_psbts = props.psbts.map((w, i) => (
        <MenuItem key={i} value={i}>
            {i} -- {w.toBase64().substr(0, 16)}...
        </MenuItem>
    ));
    const [idx, set_idx] = React.useState(0);
    React.useEffect(() => {
        if (idx < props.psbts.length && idx >= 0) {
            setPSBT(props.psbts[idx]!);
        }
    }, [idx, props.psbts]);
    // missing horizontal
    return (
        <div className="PSBTDetail">
            <InputLabel id="label-select-psbt">PSBT Selection</InputLabel>
            <Select
                labelId="label-select-psbt"
                label="PSBT Selection"
                variant="outlined"
                ref={psbt_selection_form}
                onChange={() => {
                    const idx: number =
                        parseInt(psbt_selection_form.current?.value ?? '0') ??
                        0;
                    set_idx(idx);
                }}
            >
                {selectable_psbts}
            </Select>
            {flash}
            <Hex
                className="txhex"
                value={psbt.toBase64()}
                label="Selected PSBT"
            ></Hex>
            <div className="PSBTActions">
                <Tooltip title="Save PSBT to Disk">
                    <IconButton
                        aria-label="save-psbt-disk"
                        onClick={() => psbt_handler.save_psbt(psbt.toBase64())}
                    >
                        <SaveIcon style={{ color: red[500] }} />
                    </IconButton>
                </Tooltip>
                <Tooltip title="Sign PSBT using Node">
                    <IconButton
                        aria-label="sign-psbt-node"
                        onClick={async () => {
                            const new_psbt = await psbt_handler.sign_psbt(
                                psbt.toBase64()
                            );
                            // TODO: Confirm this saves to model?
                            psbt.combine(new_psbt);
                            setPSBT(psbt);
                        }}
                    >
                        <VpnKeyIcon style={{ color: yellow[500] }} />
                    </IconButton>
                </Tooltip>
                <Tooltip title="Combine PSBT from File">
                    <IconButton
                        aria-label="combine-psbt-file"
                        onClick={async () => {
                            // TODO: Confirm this saves to model?
                            await psbt_handler.combine_psbt(psbt);
                            setPSBT(psbt);
                        }}
                    >
                        <MergeTypeIcon style={{ color: purple[500] }} />
                    </IconButton>
                </Tooltip>
                <Tooltip title="Finalize and Broadcast PSBT with Node">
                    <IconButton
                        aria-label="combine-psbt-file"
                        onClick={async () => {
                            await psbt_handler.finalize_psbt(psbt.toBase64());
                            setPSBT(psbt);
                        }}
                    >
                        <SendIcon style={{ color: orange[500] }} />
                    </IconButton>
                </Tooltip>
                <div></div>
            </div>
        </div>
    );
}
Example #24
Source File: Form.tsx    From frontend with MIT License 4 votes vote down vote up
export default function EditForm() {
  const [type, setType] = useState('donation')
  const [status, setStatus] = useState('initial')
  const [provider, setProvider] = useState('none')
  const [currency, setCurrency] = useState('')
  const [vault, setVault] = useState('')
  const router = useRouter()
  const { t } = useTranslation()

  let id = router.query.id

  const vaults = useVaultsList().data

  let initialValues: DonationInput = {
    type: 'donation',
    status: 'initial',
    provider: 'none',
    currency: '',
    amount: 0,
    targetVaultId: '',
    extCustomerId: '',
    extPaymentIntentId: '',
    extPaymentMethodId: '',
  }

  if (id) {
    id = String(id)
    const { data }: UseQueryResult<DonationResponse> = useDonation(id)

    if (data) {
      initialValues = {
        type: data?.type.toString(),
        status: data?.status.toString(),
        provider: data?.provider.toString(),
        currency: data?.currency.toString(),
        amount: data?.amount,
        targetVaultId: data?.targetVaultId,
        extCustomerId: data?.extCustomerId,
        extPaymentIntentId: data?.extPaymentIntentId,
        extPaymentMethodId: data?.extPaymentMethodId,
      }
    }
  }

  const mutationFn = id ? useEditDonation(id) : useCreateDonation()

  const mutation = useMutation<
    AxiosResponse<DonationResponse>,
    AxiosError<ApiErrors>,
    DonationInput
  >({
    mutationFn,
    onError: () => AlertStore.show(t('donations:alerts:error'), 'error'),
    onSuccess: () => {
      AlertStore.show(id ? t('donations:alerts:edit') : t('donations:alerts:create'), 'success')
      router.push(routes.admin.donations.index)
    },
  })

  async function onSubmit(data: DonationInput) {
    type ? (data.type = type) : ''
    status ? (data.status = status) : ''
    provider ? (data.provider = provider) : ''
    currency ? (data.currency = currency) : ''
    vault ? (data.targetVaultId = vault) : ''

    mutation.mutate(data)
  }

  return (
    <GenericForm
      onSubmit={onSubmit}
      initialValues={initialValues}
      validationSchema={validationSchema}>
      <Box sx={{ marginTop: '5%', height: '62.6vh' }}>
        <Typography variant="h5" component="h2" sx={{ marginBottom: 2, textAlign: 'center' }}>
          {id ? t('donations:edit-form-heading') : t('donations:form-heading')}
        </Typography>
        <Grid container spacing={2} sx={{ width: 600, margin: '0 auto' }}>
          <Grid item xs={6}>
            <FormControl fullWidth size="small">
              <InputLabel id="labelType">{t('donations:type')}</InputLabel>
              <Select
                labelId="labelType"
                label={t('donations:type')}
                id="type"
                name="type"
                value={initialValues.type}
                onChange={(e) => setType(e.target.value)}
                disabled={id ? true : false}>
                {validDonationTypes.map((type) => {
                  return (
                    <MenuItem key={type} value={type}>
                      {type}
                    </MenuItem>
                  )
                })}
              </Select>
            </FormControl>
          </Grid>
          <Grid item xs={6}>
            <FormControl fullWidth size="small">
              <InputLabel id="labelStatus">{t('donations:status')}</InputLabel>
              <Select
                labelId="labelStatus"
                label={t('donations:status')}
                id="status"
                name="status"
                value={initialValues.status}
                onChange={(e) => {
                  setStatus(e.target.value)
                  console.log(e.target.value)
                }}>
                {validDonationStatuses.map((stat) => {
                  return (
                    <MenuItem key={stat} value={stat}>
                      {stat}
                    </MenuItem>
                  )
                })}
              </Select>
            </FormControl>
          </Grid>
          <Grid item xs={6}>
            <FormControl fullWidth size="small">
              <InputLabel id="labelProvider">{t('donations:provider')}</InputLabel>
              <Select
                labelId="labelProvider"
                label={t('donations:provider')}
                id="provider"
                name="provider"
                value={initialValues.provider}
                onChange={(e) => setProvider(e.target.value)}
                disabled={id ? true : false}>
                {validProviders.map((prov) => {
                  return (
                    <MenuItem key={prov} value={prov}>
                      {prov}
                    </MenuItem>
                  )
                })}
              </Select>
            </FormControl>
          </Grid>
          <Grid item xs={6}>
            <FormControl fullWidth size="small">
              <InputLabel id="labelVault">{t('donations:vault')}</InputLabel>
              <Select
                labelId="labelVault"
                label={t('donations:vault')}
                id="targetVaultId"
                name="targetVaultId"
                value={initialValues.targetVaultId}
                onChange={(e) => setVault(e.target.value)}
                disabled={id ? true : false}>
                {vaults?.map((vault) => {
                  return (
                    <MenuItem key={vault.id} value={vault.id}>
                      {vault.name}
                    </MenuItem>
                  )
                })}
              </Select>
            </FormControl>
          </Grid>
          <Grid item xs={12}>
            <FormTextField
              type="text"
              label={t('donations:ext-customer-id')}
              name="extCustomerId"
              disabled={id ? true : false}
            />
          </Grid>
          <Grid item xs={6}>
            <FormTextField
              type="text"
              label={t('donations:ext-payment-intent-id')}
              name="extPaymentIntentId"
              disabled={id ? true : false}
            />
          </Grid>
          <Grid item xs={6}>
            <FormTextField
              type="text"
              label={t('donations:ext-payment-method-id')}
              name="extPaymentMethodId"
              disabled={id ? true : false}
            />
          </Grid>
          <Grid item xs={6}>
            <FormTextField
              type="number"
              label={t('donations:amount')}
              name="amount"
              disabled={id ? true : false}
            />
          </Grid>
          <Grid item xs={6}>
            <FormControl fullWidth size="small">
              <InputLabel id="labelCurrency">{t('donations:currency')}</InputLabel>
              <Select
                labelId="labelCurrency"
                label={t('donations:currency')}
                id="currency"
                name="currency"
                value={initialValues.currency}
                onChange={(e) => setCurrency(e.target.value)}
                disabled={id ? true : false}>
                {validCurrencies.map((currency) => {
                  return (
                    <MenuItem key={currency} value={currency}>
                      {currency}
                    </MenuItem>
                  )
                })}
              </Select>
            </FormControl>
          </Grid>
          <Grid item xs={6}>
            <SubmitButton fullWidth label={t('donations:cta:submit')} />
          </Grid>
          <Grid item xs={6}>
            <Link passHref href={routes.admin.donations.index}>
              <Button>{t('donations:cta:cancel')}</Button>
            </Link>
          </Grid>
        </Grid>
      </Box>
    </GenericForm>
  )
}
Example #25
Source File: Settings.tsx    From abrechnung with GNU Affero General Public License v3.0 4 votes vote down vote up
export default function Settings() {
    const [theme, setTheme] = useRecoilState(themeSettings);

    useTitle("Abrechnung - Settings");

    const [confirmClearCacheOpen, setConfirmClearCacheOpen] = useState(false);

    const handleConfirmClearCacheOpen = () => {
        setConfirmClearCacheOpen(true);
    };

    const handleConfirmClearCacheClose = () => {
        setConfirmClearCacheOpen(false);
    };

    const handleConfirmClearCache = () => {
        clearCache();
        setConfirmClearCacheOpen(false);
        window.location.reload();
    };

    const handleDarkModeChange = (event) => {
        const val = event.target.value;
        setTheme({
            ...theme,
            darkMode: val,
        });
    };

    return (
        <MobilePaper>
            <Typography component="h3" variant="h5">
                Settings
            </Typography>
            <Alert sx={{ mt: 1 }} severity="info">
                These settings are stored locally on your device. Clearing your Browser's local storage will reset them.
            </Alert>
            <Box sx={{ mt: 2 }}>
                <FormControl sx={{ width: 200 }}>
                    <FormGroup>
                        <FormLabel component="legend">Theme</FormLabel>
                        <Select
                            id="dark-mode-select"
                            labelId="dark-mode-select-label"
                            value={theme.darkMode}
                            label="Dark Mode"
                            variant="standard"
                            onChange={handleDarkModeChange}
                        >
                            <MenuItem value="browser">System Default</MenuItem>
                            <MenuItem value="dark">Dark Mode</MenuItem>
                            <MenuItem value="light">Light Mode</MenuItem>
                        </Select>
                    </FormGroup>
                </FormControl>
            </Box>
            <Divider sx={{ mt: 1 }} />
            <Box sx={{ mt: 1 }}>
                <FormControl component="fieldset" variant="standard">
                    <FormLabel component="legend">Clear Cache</FormLabel>
                    <FormGroup>
                        <Button variant="contained" color="error" onClick={handleConfirmClearCacheOpen}>
                            Clear
                        </Button>
                    </FormGroup>
                    {/*<FormHelperText>ACHTUNG!</FormHelperText>*/}
                </FormControl>
            </Box>

            <Dialog
                open={confirmClearCacheOpen}
                onClose={handleConfirmClearCacheClose}
                aria-labelledby="dialog-confirm-clear-cache"
                aria-describedby="dialog-confirm-clear-cache-description"
            >
                <DialogTitle id="dialog-confirm-clear-cache">{"Clear Cache?"}</DialogTitle>
                <DialogContent>
                    <DialogContentText id="dialog-confirm-clear-cache-description">
                        This action will clear your local cache. All your settings (this page) will not be reset.
                    </DialogContentText>
                </DialogContent>
                <DialogActions>
                    <Button onClick={handleConfirmClearCache} autoFocus>
                        Yes
                    </Button>
                    <Button onClick={handleConfirmClearCacheClose}>Cancel</Button>
                </DialogActions>
            </Dialog>
        </MobilePaper>
    );
}
Example #26
Source File: TableSelect.tsx    From firecms with MIT License 4 votes vote down vote up
export function TableSelect(props: {
    name: string;
    enumValues: EnumValues;
    error: Error | undefined;
    multiple: boolean;
    disabled: boolean;
    small: boolean;
    internalValue: string | number | string[] | number[] | undefined;
    valueType: "string" | "number";
    updateValue: (newValue: (string | number | string[] | number[] | null)) => void;
    focused: boolean;
    onBlur?: React.FocusEventHandler<HTMLInputElement | HTMLTextAreaElement>;
    setPreventOutsideClick: (value: any) => void;
}) {

    const {
        name,
        enumValues,
        error,
        internalValue,
        disabled,
        small,
        focused,
        updateValue,
        multiple,
        setPreventOutsideClick,
        valueType
    } = props;

    const [open, setOpen] = useState<boolean>(false);
    const handleOpen = () => {
        setPreventOutsideClick(true);
        setOpen(true);
    };

    const handleClose = () => {
        setPreventOutsideClick(false);
        setOpen(false);
    };

    const classes = useInputStyles();

    const validValue = (Array.isArray(internalValue) && multiple) ||
        (!Array.isArray(internalValue) && !multiple);

    const ref = React.createRef<HTMLInputElement>();
    useEffect(() => {
        if (ref.current && focused) {
            ref.current?.focus({ preventScroll: true });
        }
    }, [focused, ref]);

    return (
        <Select
            variant={"standard"}
            key={`table_select_${name}`}
            inputRef={ref}
            className={classes.select}
            classes={{ select: classes.selectRoot }}
            open={open}
            disabled={disabled}
            multiple={multiple}
            onClose={handleClose}
            onOpen={handleOpen}
            fullWidth
            inputProps={{
                style: {
                    height: "100%"
                }
            }}
            disableUnderline
            error={!!error}
            value={validValue
                ? (multiple ? (internalValue as any[]).map(v => v.toString()) : internalValue)
                : (multiple ? [] : "")}
            onChange={(evt) => {
                if (valueType === "number") {
                    if (multiple) {
                        const newValue = (evt.target.value as string[]).map((v) => parseFloat(v));
                        updateValue(newValue);
                    } else {
                        updateValue(parseFloat(evt.target.value as string));
                    }
                } else if (valueType === "string") {
                    if (!evt.target.value)
                        updateValue(null)
                    else
                        updateValue(evt.target.value);
                } else {
                    throw Error("Missing mapping in TableSelect");
                }
            }}
            renderValue={(enumKey: any) => {
                if (multiple && Array.isArray(enumKey)) {
                    return <ArrayEnumPreview value={enumKey}
                                             name={name}
                                             enumValues={enumValues}
                                             size={small ? "small" : "regular"}/>;
                } else {
                    return <EnumValuesChip
                        enumKey={enumKey}
                        enumValues={enumValues}
                        small={small}/>;
                }
            }
            }>

            {enumToObjectEntries(enumValues).map(([key, labelOrConfig]) => {

                const chip = <EnumValuesChip
                    enumKey={key}
                    enumValues={enumValues}
                    small={true}/>;
                if (multiple) {
                    return (
                        <MenuItem key={`select-${name}-${key}`}
                                  value={key}
                                  disabled={isEnumValueDisabled(labelOrConfig)}
                                  dense={true}>
                            <Checkbox
                                checked={Array.isArray(internalValue) && (internalValue as any[]).map(v => v.toString()).includes(key.toString())}/>
                            <ListItemText primary={chip}/>
                        </MenuItem>
                    );
                } else {
                    return (
                        <MenuItem key={`select-${name}-${key}`} value={key}
                                  disabled={isEnumValueDisabled(labelOrConfig)}
                                  dense={true}>
                            {chip}
                        </MenuItem>
                    );
                }
            })}
        </Select>
    );
}
Example #27
Source File: search.tsx    From Cromwell with MIT License 4 votes vote down vote up
SearchPage: TPageWithLayout<SearchPageProps> = (props) => {
    const filterInput = useRef<TPostFilter>({});
    const listId = 'Blog_list_01';
    const publishSort = useRef<"ASC" | "DESC">('DESC');
    const forceUpdate = useForceUpdate();
    const titleSearchId = "post-filter-search";

    const updateList = () => {
        const list = getBlockInstance<TCList>(listId)?.getContentInstance();
        list?.clearState();
        list?.init();
        list?.updateData();
    }

    const handleChangeTags = (event: any, newValue?: (TTag | undefined | string)[]) => {
        filterInput.current.tagIds = newValue?.map(tag => (tag as TTag)?.id);
        forceUpdate();
        updateList();
    }

    const handleGetPosts = (params: TPagedParams<TPost>) => {
        params.orderBy = 'publishDate';
        params.order = publishSort.current;
        return handleGetFilteredPosts(params, filterInput.current);
    }

    const handleChangeSort = (event: SelectChangeEvent<unknown>) => {
        if (event.target.value === 'Newest') publishSort.current = 'DESC';
        if (event.target.value === 'Oldest') publishSort.current = 'ASC';
        updateList();
    }

    const handleTagClick = (tag?: TTag) => {
        if (!tag) return;
        if (filterInput.current.tagIds?.length === 1 &&
            filterInput.current.tagIds[0] === tag.id) return;
        handleChangeTags(null, [tag]);
        forceUpdate();
    }

    const handleTitleInput = debounce(400, () => {
        filterInput.current.titleSearch = (document.getElementById(titleSearchId) as HTMLInputElement)?.value ?? undefined;
        updateList();
    });

    return (
        <CContainer className={commonStyles.content} id="search_01">
            <CContainer className={styles.filter} id="search_02">
                <div className={styles.filterLeft}>
                    <TextField
                        className={styles.filterItem}
                        placeholder="Search by title"
                        id={titleSearchId}
                        variant="standard"
                        onChange={handleTitleInput}
                    />
                    <Autocomplete
                        multiple
                        freeSolo
                        value={filterInput.current.tagIds?.map(id => props.tags?.find(tag => tag.id === id)) ?? []}
                        className={styles.filterItem}
                        options={props.tags ?? []}
                        getOptionLabel={(option: any) => option?.name ?? ''}
                        style={{ width: 300 }}
                        onChange={handleChangeTags}
                        renderInput={(params) => (
                            <TextField
                                {...params}
                                variant="standard"
                                placeholder="Tags"
                            />
                        )}
                    />
                </div>
                <FormControl className={styles.filterItem}>
                    <InputLabel className={styles.sortLabel}>Sort</InputLabel>
                    <Select
                        style={{ width: '100px' }}
                        onChange={handleChangeSort}
                        variant="standard"
                        defaultValue='Newest'
                    >
                        {['Newest', 'Oldest'].map(sort => (
                            <MenuItem value={sort} key={sort}>{sort}</MenuItem>
                        ))}
                    </Select>
                </FormControl>
            </CContainer>
            <CContainer style={{ marginBottom: '20px' }} id="search_03">
                <CList<TPost>
                    id={listId}
                    ListItem={(props) => (
                        <div className={styles.postWrapper}>
                            <PostCard onTagClick={handleTagClick} data={props.data} key={props.data?.id} />
                        </div>
                    )}
                    usePagination
                    useShowMoreButton
                    useQueryPagination
                    disableCaching
                    pageSize={20}
                    scrollContainerSelector={`.${layoutStyles.Layout}`}
                    firstBatch={props.posts}
                    loader={handleGetPosts}
                    cssClasses={{
                        page: styles.postList
                    }}
                    elements={{
                        pagination: Pagination
                    }}
                />
            </CContainer>
        </CContainer>
    );
}
Example #28
Source File: Language.tsx    From GTAV-NativeDB with MIT License 4 votes vote down vote up
export function CodeGenOptionComponent<TSettings>(props:CodeGenOptionComponentProps<TSettings>) {
  const { type, label, prop, value, onChange } = props

  switch (type) {
    case 'boolean':
      return (
        <FormControlLabel
          control={
            <Checkbox
              name={prop}
              checked={value}
              onChange={onChange}
            />
          }
          sx={{ userSelect: 'none' }}
          label={label}
        />
      )
    case 'combo':
      const options = props.options
      return (
        <FormControl fullWidth>
          <InputLabel id={`${prop}-label`}>{label}</InputLabel>
          <Select
            id={`${prop}-select`}
            labelId={`${prop}-label`}
            name={prop}
            value={value}
            onChange={onChange}
            label={label}
          >
            {options.map(({ label, value }) => (
              <MenuItem key={value} value={value}>
                {label}
              </MenuItem>
            ))}
          </Select>
        </FormControl>
      )
    case 'string':
      return (
        <TextField
          label={label}
          name={prop}
          onChange={(onChange as unknown as ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement>)}
          value={value}
        />
      )
  }
}
Example #29
Source File: TransactionCreateModal.tsx    From abrechnung with GNU Affero General Public License v3.0 4 votes vote down vote up
export default function TransactionCreateModal({ group, show, onClose }) {
    const setTransactions = useSetRecoilState(groupTransactions(group.id));

    const handleSubmit = (values, { setSubmitting }) => {
        createTransaction({
            groupID: group.id,
            type: values.type,
            description: values.description,
            value: parseFloat(values.value),
            billedAt: values.billedAt.toISODate(),
            currencySymbol: "€",
            currencyConversionRate: 1.0,
        })
            .then((t) => {
                addTransactionInState(t, setTransactions);
                setSubmitting(false);
                onClose();
            })
            .catch((err) => {
                toast.error(err);
                setSubmitting(false);
            });
    };

    const validate = (values) => {
        let errors = { value: undefined, description: undefined, billedAt: undefined };
        const floatValue = parseFloat(values.value);
        if (isNaN(floatValue) || floatValue <= 0) {
            errors.value = "please input a valid decimal number";
        }
        if (values.description === null || values.description === undefined || values.description === "") {
            errors.description = "please input a description";
        }
        if (values.billedAt === null || values.billedAt === undefined || values.billedAt === "") {
            errors.billedAt = "please input valid billed at time";
        }
        return errors;
    };

    return (
        <Dialog open={show} onClose={onClose}>
            <DialogTitle>Create Transaction</DialogTitle>
            <DialogContent>
                <Formik
                    validate={validate}
                    initialValues={{
                        type: "purchase",
                        description: "",
                        value: "0.0",
                        billedAt: DateTime.now(),
                    }}
                    onSubmit={handleSubmit}
                >
                    {({ values, setFieldValue, handleChange, handleBlur, handleSubmit, isSubmitting }) => (
                        <Form>
                            <Select
                                required
                                value={values.type}
                                onChange={handleChange}
                                onBlur={handleBlur}
                                variant="standard"
                                name="type"
                            >
                                <MenuItem value="purchase">Purchase</MenuItem>
                                <MenuItem value="transfer">Transfer</MenuItem>
                                {/*<MenuItem value="mimo">MIMO</MenuItem>*/}
                            </Select>
                            <TextField
                                margin="normal"
                                required
                                fullWidth
                                variant="standard"
                                name="description"
                                label="Description"
                                autoFocus
                                value={values.description}
                                onChange={handleChange}
                                onBlur={handleBlur}
                            />
                            <DatePicker
                                inputFormat="yyyy-MM-dd"
                                renderInput={(params) => (
                                    <TextField
                                        name="billedAt"
                                        required
                                        variant="standard"
                                        fullWidth
                                        {...params}
                                        helperText={null}
                                    />
                                )}
                                label="Billed at"
                                value={values.billedAt}
                                onChange={(val) => setFieldValue("billedAt", val, true)}
                            />
                            <TextField
                                margin="normal"
                                required
                                fullWidth
                                type="number"
                                variant="standard"
                                name="value"
                                label="Value"
                                value={values.value}
                                onChange={handleChange}
                                onBlur={handleBlur}
                            />
                            {isSubmitting && <LinearProgress />}
                            <DialogActions>
                                <Button type="submit" color="primary" disabled={isSubmitting}>
                                    Save
                                </Button>
                                <Button color="error" onClick={onClose}>
                                    Cancel
                                </Button>
                            </DialogActions>
                        </Form>
                    )}
                </Formik>
            </DialogContent>
        </Dialog>
    );
}