@mui/material#Checkbox TypeScript Examples

The following examples show how to use @mui/material#Checkbox. 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: OptionsCheck.tsx    From ui-schema with MIT License 6 votes vote down vote up
OptionCheck: React.ComponentType<{
    disabled?: boolean
    checked: boolean
    label: React.ReactNode
    onChange: SwitchBaseProps['onChange']
}> = ({disabled, checked, label, onChange}) => {
    const uid = useUID()

    return <FormControlLabel
        id={'uis-' + uid}
        control={<Checkbox
            id={'uis-' + uid}
            checked={checked}
            onChange={onChange}
            disabled={disabled}
        />}
        disabled={disabled}
        label={label}
    />
}
Example #2
Source File: boolean.tsx    From mui-toolpad with MIT License 6 votes vote down vote up
function BooleanPropEditor({ label, value, onChange, disabled }: EditorProps<boolean>) {
  const handleChange = React.useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      onChange(event.target.checked);
    },
    [onChange],
  );

  return (
    <FormControlLabel
      control={<Checkbox checked={!!value} disabled={disabled} onChange={handleChange} />}
      label={label}
    />
  );
}
Example #3
Source File: CheckBoxFilter.tsx    From Tachidesk-WebUI with Mozilla Public License 2.0 6 votes vote down vote up
export default function CheckBoxFilter(props: Props) {
    const {
        state,
        name,
        position,
        group,
        updateFilterValue,
        update,
    } = props;
    const [val, setval] = React.useState(state);

    const handleChange = (event: { target: { name: any; checked: any; }; }) => {
        setval(event.target.checked);
        const upd = update.filter((e: {
            position: number; group: number | undefined;
        }) => !(position === e.position && group === e.group));
        updateFilterValue([...upd, { position, state: event.target.checked.toString(), group }]);
    };

    if (state !== undefined) {
        return (
            <Box sx={{ display: 'flex', flexDirection: 'column', minWidth: 120 }}>
                <FormControlLabel
                    key={name}
                    control={(
                        <Checkbox
                            name={name}
                            checked={val}
                            onChange={handleChange}
                        />
                    )}
                    label={name}
                />
            </Box>
        );
    }
    return (<></>);
}
Example #4
Source File: Vault.tsx    From NekoMaid with MIT License 6 votes vote down vote up
Groups: React.FC<{ plugin: Plugin, id: string | undefined, onClose: () => void, groups: GroupInfo[] }> =
  ({ plugin, id, onClose, groups }) => {
    const [loading, setLoading] = useState(true)
    const [playerGroups, setPlayerGroups] = useState<Record<string, true>>({ })
    const refresh = () => {
      setLoading(true)
      plugin.emit('vault:playerGroup', (res: string[]) => {
        if (!res) return
        const obj: Record<string, true> = { }
        res.forEach(it => (obj[it] = true))
        setPlayerGroups(obj)
        setLoading(false)
      }, id, null, 0)
    }
    useEffect(() => {
      setPlayerGroups({})
      if (!id) return
      refresh()
    }, [id])
    return <Dialog onClose={onClose} open={!!id}>
      <DialogTitle>{lang.vault.whosPermissionGroup(id!)}</DialogTitle>
      <List sx={{ pt: 0 }}>
        {groups.map(it => <ListItem onClick={() => { }} key={it.id}>
          <ListItemIcon><Checkbox
            tabIndex={-1}
            disabled={loading}
            checked={!!playerGroups[it.id]}
            onChange={e => plugin.emit('vault:playerGroup', (res: boolean) => {
              action(res)
              refresh()
            }, id, it.id, e.target.checked ? 1 : 2)}
          /></ListItemIcon>
          <ListItemText primary={it.id} />
        </ListItem>)}
      </List>
      <DialogActions><Button onClick={onClose}>{minecraft['gui.back']}</Button></DialogActions>
    </Dialog>
  }
Example #5
Source File: ThreeStateCheckbox.tsx    From Tachidesk-WebUI with Mozilla Public License 2.0 6 votes vote down vote up
ThreeStateCheckbox = (props: IThreeStateCheckboxProps) => {
    const {
        name, checked, onChange,
    } = props;
    const [localChecked, setLocalChecked] = useState(checkedToState(checked));
    useEffect(() => setLocalChecked(checkedToState(checked)), [checked]);
    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        setLocalChecked(stateTransition(localChecked));
        if (onChange) {
            onChange(stateToChecked(stateTransition(localChecked)), e.currentTarget.name);
        }
    };
    const CancelBox = createSvgIcon(
        <>
            <path
                d="M 19 6.41 L 13.41 12 L 19 17.59 L 17.59 19 L 12 13.41 L 6.41 19 V 19 H 6.41 L 5 17.59 L 11 12 L 5 6.41 L 6.41 5 L 12 10.59 L 17.59 5 L 19 6.41 M 5 5 m 0 -2 H 5 c -1.1 0 -2 0.9 -2 2 v 14 c 0 1.1 0.9 2 2 2 h 14 c 1.1 0 2 -0.9 2 -2 V 5 c 0 -1.1 -0.9 -2 -2 -2 z "
            />
        </>,
        'CancelBox',
    );

    return (
        <Checkbox
            name={name}
            checked={localChecked === CheckState.SELECTED}
            indeterminate={localChecked === CheckState.INTERMEDIATE}
            indeterminateIcon={<CancelBox />}
            onChange={handleChange}
            className={`${localChecked}`}
        />
    );
}
Example #6
Source File: DeletedCheckbox.tsx    From frontend with MIT License 6 votes vote down vote up
export default function DeletedCheckbox() {
  const name = 'deleted'
  const { t } = useTranslation('expenses')
  const [field, meta] = useField(name)

  return (
    <FormControl
      fullWidth
      size="small"
      variant="outlined"
      error={Boolean(meta.error) && Boolean(meta.touched)}>
      <FormControlLabel
        disabled
        control={<Checkbox {...field} />}
        label={`${t('fields.' + name)}`}
      />
    </FormControl>
  )
}
Example #7
Source File: ColumnConfigureItem.tsx    From Cromwell with MIT License 6 votes vote down vote up
ColumnConfigureItem = (props: {
    data: TColumnConfigureItemData;
}) => {
    const data = props.data;
    const [visible, setVisible] = useState(data.sortedColumns[data.column.name]?.visible ?? data.column.visible);
    const toggleVisibility = () => {
        setVisible(!visible);
        if (!data.sortedColumns[data.column.name]) data.sortedColumns[data.column.name] = {
            name: data.column.name,
        };
        data.sortedColumns[data.column.name].visible = !visible;
    }

    return (
        <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            width: '100%', minWidth: '20px'
        }}>
            <p className={styles.ellipsis} style={{ minWidth: '20px' }}>{props.data.column.label}</p>
            <div className={commonStyles.center}>
                <Checkbox
                    checked={visible}
                    onChange={toggleVisibility}
                />
            </div>
        </div>
    )
}
Example #8
Source File: DisabledTextField.tsx    From abrechnung with GNU Affero General Public License v3.0 5 votes vote down vote up
DisabledCheckbox = styled(Checkbox)(({ theme }: { theme: Theme }) => ({
    "& .Mui-disabled": {
        color: theme.palette.text.primary,
        WebkitTextFillColor: theme.palette.text.primary,
    },
}))
Example #9
Source File: CircleCheckboxField.tsx    From frontend with MIT License 5 votes vote down vote up
export default function CircleCheckboxField({ name, label, labelProps }: CircleCheckboxField) {
  const { t } = useTranslation('one-time-donation')
  const [field, meta] = useField(name)
  const helperText = meta.touched ? translateError(meta.error as TranslatableField, t) : ''
  return (
    <FormControl required component="fieldset" error={Boolean(meta.error) && Boolean(meta.touched)}>
      <FormControlLabel
        sx={
          field.checked
            ? {
                background: lighten(theme.palette.primary.main, 0.8),
                border: `1px solid ${theme.borders.light}`,
              }
            : undefined
        }
        label={<Typography sx={{ fontWeight: 'bold', ml: 1 }}>{label}</Typography>}
        control={
          <Checkbox
            icon={
              <Icon
                sx={(theme) => ({
                  width: 30,
                  height: 30,
                  border: `1px solid ${theme.palette.primary.dark}`,
                  // @ts-expect-error theme doesn't include overrides
                  borderRadius: theme.borders.round,
                })}
              />
            }
            checkedIcon={
              <CheckIcon
                sx={(theme) => ({
                  width: 30,
                  height: 30,
                  border: `1px solid ${theme.palette.primary.main}`,
                  backgroundColor: theme.palette.primary.main,
                  // @ts-expect-error theme doesn't include overrides
                  borderRadius: theme.borders.round,
                  color: '#fff',
                })}
              />
            }
            checked={Boolean(field.value)}
            {...field}
          />
        }
        {...labelProps}
      />
      {Boolean(meta.error) && (
        <FormHelperText error>{helperText ? t(helperText) : 'General Error'}</FormHelperText>
      )}
    </FormControl>
  )
}
Example #10
Source File: PurchaseDebitorShares.tsx    From abrechnung with GNU Affero General Public License v3.0 5 votes vote down vote up
function AccountTableRow({
    transaction,
    account,
    showAdvanced,
    debitorShareValueForAccount,
    showPositions,
    positionValueForAccount,
    debitorValueForAccount,
    updateDebShare,
}) {
    const transactionHasPositions =
        transaction.positions != null && transaction.positions.find((item) => !item.deleted) !== undefined;

    return (
        <TableRow hover>
            <TableCell>
                <Grid container direction="row" alignItems="center">
                    <Grid item>{account.type === "personal" ? <PersonalAccountIcon /> : <ClearingAccountIcon />}</Grid>
                    <Grid item sx={{ ml: 1 }}>
                        <Typography variant="body2" component="span">
                            {account.name}
                        </Typography>
                    </Grid>
                </Grid>
            </TableCell>
            <TableCell width="100px">
                {showAdvanced ? (
                    <ShareInput
                        onChange={(value) => updateDebShare(account.id, value)}
                        value={debitorShareValueForAccount(account.id)}
                    />
                ) : (
                    <Checkbox
                        name={`${account.name}-checked`}
                        checked={transaction.debitor_shares.hasOwnProperty(account.id)}
                        onChange={(event) => updateDebShare(account.id, event.target.checked ? 1.0 : 0)}
                    />
                )}
            </TableCell>
            {showPositions || transactionHasPositions ? (
                <>
                    <TableCell align="right">
                        {positionValueForAccount(account.id).toFixed(2)} {transaction.currency_symbol}
                    </TableCell>
                    <TableCell></TableCell>
                    <TableCell align="right">
                        {debitorValueForAccount(account.id).toFixed(2)} {transaction.currency_symbol}
                    </TableCell>
                    <TableCell></TableCell>
                    <TableCell width="100px" align="right">
                        {(debitorValueForAccount(account.id) + positionValueForAccount(account.id)).toFixed(2)}{" "}
                        {transaction.currency_symbol}
                    </TableCell>
                </>
            ) : (
                <TableCell width="100px" align="right">
                    {(debitorValueForAccount(account.id) + positionValueForAccount(account.id)).toFixed(2)}{" "}
                    {transaction.currency_symbol}
                </TableCell>
            )}
        </TableRow>
    );
}
Example #11
Source File: CheckboxWrapper.tsx    From console with GNU Affero General Public License v3.0 5 votes vote down vote up
CheckboxWrapper = ({
  label,
  onChange,
  value,
  id,
  name,
  checked = false,
  disabled = false,
  noTopMargin = false,
  tooltip = "",
  overrideLabelClasses = "",
  overrideCheckboxStyles,
  classes,
  className,
}: CheckBoxProps) => {
  return (
    <React.Fragment>
      <Grid
        item
        xs={12}
        className={`${classes.fieldContainer} ${
          noTopMargin ? classes.noTopMargin : ""
        } ${className ? className : ""}`}
      >
        <div>
          <Checkbox
            name={name}
            id={id}
            value={value}
            color="primary"
            inputProps={{ "aria-label": "secondary checkbox" }}
            checked={checked}
            onChange={onChange}
            checkedIcon={<span className={classes.checkedIcon} />}
            icon={<span className={classes.unCheckedIcon} />}
            disabled={disabled}
            disableRipple
            disableFocusRipple
            focusRipple={false}
            centerRipple={false}
            disableTouchRipple
            style={overrideCheckboxStyles || {}}
          />
        </div>
        {label !== "" && (
          <InputLabel
            htmlFor={id}
            className={`${classes.noMinWidthLabel} ${overrideLabelClasses}`}
          >
            <span>{label}</span>
            {tooltip !== "" && (
              <div className={classes.tooltipContainer}>
                <Tooltip title={tooltip} placement="top-start">
                  <div className={classes.tooltip}>
                    <HelpIcon />
                  </div>
                </Tooltip>
              </div>
            )}
          </InputLabel>
        )}
      </Grid>
    </React.Fragment>
  );
}
Example #12
Source File: CheckboxElement.tsx    From react-hook-form-mui with MIT License 5 votes vote down vote up
export default function CheckboxElement({
  name,
  validation = {},
  required,
  parseError,
  label,
  control,
  ...rest
}: CheckboxElementProps): JSX.Element {

  if (required) {
    validation.required = 'This field is required'
  }

  return (
    <Controller
      name={name}
      rules={validation}
      control={control}
      render={({ field: { value, onChange }, fieldState: { invalid, error } }) => {
        const helperText = error ? (typeof parseError === 'function' ? parseError(error) : error.message) : rest.helperText
        return (
          <FormControl required={required} error={invalid}>
            <FormGroup row>
              <FormControlLabel
                label={label || ''}
                control={
                  <Checkbox
                    color={'primary'}
                    sx={{
                      color: invalid ? "error.main" : undefined,
                    }}
                    value={value}
                    checked={!!value}
                    onChange={() => {
                      onChange(!value)
                      //setValue(name, !formValue, { shouldValidate: true })
                    }}
                  />
                }
              />
            </FormGroup>
            {helperText && <FormHelperText error={invalid}>{helperText}</FormHelperText>}
          </FormControl>
        )
      }}
    />
  )
}
Example #13
Source File: LibraryOptions.tsx    From Tachidesk-WebUI with Mozilla Public License 2.0 5 votes vote down vote up
function dispalyTab(currentTab: number) {
    const { options, setOptions } = useLibraryOptionsContext();

    function setContextOptions(
        e: React.ChangeEvent<HTMLInputElement>,
        checked: boolean,
    ) {
        setOptions((prev) => ({ ...prev, [e.target.name]: checked }));
    }

    function setGridContextOptions(
        e: React.ChangeEvent<HTMLInputElement>,
        checked: boolean,
    ) {
        if (checked) {
            setOptions((prev) => ({ ...prev, gridLayout: parseInt(e.target.name, 10) }));
        }
    }

    return (
        <TabPanel index={2} currentIndex={currentTab}>
            <Stack direction="column">
                DISPLAY MODE
                <FormControlLabel
                    label="Compact grid"
                    control={(
                        <Radio
                            name="0"
                            checked={options.gridLayout === 0 || options.gridLayout === undefined}
                            onChange={setGridContextOptions}
                        />
                    )}
                />
                <FormControlLabel
                    label="Comfortable grid"
                    control={(
                        <Radio
                            name="1"
                            checked={options.gridLayout === 1}
                            onChange={setGridContextOptions}
                        />
                    )}
                />
                <FormControlLabel
                    label="list"
                    control={(
                        <Radio
                            name="2"
                            checked={options.gridLayout === 2}
                            onChange={setGridContextOptions}
                        />
                    )}
                />
                BADGES
                <FormControlLabel
                    label="Unread Badges"
                    control={(
                        <Checkbox
                            name="showUnreadBadge"
                            checked={options.showUnreadBadge}
                            onChange={setContextOptions}
                        />
                    )}
                />
                <FormControlLabel
                    label="Download Badges"
                    control={(
                        <Checkbox
                            name="showDownloadBadge"
                            checked={options.showDownloadBadge}
                            onChange={setContextOptions}
                        />
                    )}
                />
            </Stack>
        </TabPanel>
    );
}
Example #14
Source File: BooleanFilterField.tsx    From firecms with MIT License 5 votes vote down vote up
export function BooleanFilterField({
                                       name,
                                       title,
                                       value,
                                       setValue
                                   }: BooleanFieldProps) {
    const classes = useStyles();

    function updateFilter(val?: boolean) {
        if (val !== undefined) {
            setValue(
                ["==", val]
            );
        } else {
            setValue(
                undefined
            );
        }
    }

    const valueSetToTrue = value && value[1];
    const valueSet = !!value;

    return (
        <FormControlLabel
            className={classes.formControl}
            labelPlacement={"end"}
            checked={valueSet && valueSetToTrue}
            control={
                <Checkbox
                    key={`filter-${name}`}
                    indeterminate={!valueSet}
                    onChange={(evt) => {
                        if (valueSetToTrue) { updateFilter(false); } else if (!valueSet) { updateFilter(true); } else { updateFilter(undefined); }
                    }}
                />
            }
            label={!valueSet ? "No filter" : (valueSetToTrue ? `${title} is true` : `${title} is false`)}
        />
    );
}
Example #15
Source File: ProductListItem.tsx    From Cromwell with MIT License 5 votes vote down vote up
ProductListItem = (props: TPropsType) => {
    const cstore = getCStore();
    const { data } = props;

    let selected = false;
    if (props.allSelected && !props.selectedItems[data.id]) selected = true;
    if (!props.allSelected && props.selectedItems[data.id]) selected = true;

    return (
        <Grid container className={styles.listItem}>
            {props.data && (
                <>
                    <Grid item xs={8} className={styles.itemMain}>
                        {!props.embedded && (
                            <div className={commonStyles.center}>
                                <Checkbox
                                    checked={selected}
                                    onChange={() => props.listItemProps.toggleSelection(data)} />
                            </div>
                        )}
                        <div
                            style={{ backgroundImage: `url(${props?.data?.mainImage})` }}
                            className={styles.itemImage}
                        ></div>
                        <div className={styles.itemMainInfo}>
                            <p className={styles.itemTitle}>{props.data?.name}</p>
                            <div className={styles.priceBlock}>
                                {(data?.oldPrice !== undefined && data?.oldPrice !== null) && (
                                    <p className={styles.oldPrice}>{cstore.getPriceWithCurrency(data.oldPrice)}</p>
                                )}
                                <p className={styles.price}>{cstore.getPriceWithCurrency(data?.price)}</p>
                            </div>
                        </div>
                    </Grid>
                    <Grid item xs={2}>
                        <p className={styles.itemTitle}>{props.data?.stockStatus ?? 'In stock'}</p>
                        <p style={{ fontSize: '14px' }} className={styles.ellipsis}>{props.data?.sku}</p>
                    </Grid>
                    <Grid item xs={2} className={styles.listItemActions}>
                        <Link to={`${productPageInfo.baseRoute}/${props.data?.id}`}>
                            <IconButton
                                aria-label="edit"
                            >
                                <EditIcon />
                            </IconButton>
                        </Link>
                        {!props.embedded && (
                            <IconButton
                                aria-label="delete"
                                onClick={() => props.listItemProps.handleDeleteProductBtnClick(props.data)}
                            >
                                <DeleteForeverIcon />
                            </IconButton>
                        )}
                    </Grid>
                </>
            )}
        </Grid>
    )
}
Example #16
Source File: form-checkbox.tsx    From example with MIT License 5 votes vote down vote up
export function FormCheckbox({ form, name, options, ...rest }: React.PropsWithChildren<IFormCheckboxProps>) {
	const { register } = form

	return <FormControlLabel
		control={<Checkbox {...register(name, {...options})} />}
		{...rest}
	/>
}
Example #17
Source File: SettingsPage.tsx    From Cromwell with MIT License 5 votes vote down vote up
export function SettingsPage(props: TPluginSettingsProps<TProductFilterSettings>) {
    const onSave = () => {
        getRestApiClient().purgeRendererEntireCache();
    }

    return (
        <PluginSettingsLayout<TProductFilterSettings> {...props} onSave={onSave}>
            {({ pluginSettings, changeSetting }) => {
                const mobileIconPosition = pluginSettings?.mobileIconPosition ?? defaultSettings.mobileIconPosition;
                const collapsedByDefault = pluginSettings?.collapsedByDefault ?? defaultSettings.collapsedByDefault;
                const mobileCollapsedByDefault = pluginSettings?.mobileCollapsedByDefault ?? defaultSettings.mobileCollapsedByDefault;
                return (
                    <div style={{ display: 'flex', flexDirection: 'column' }}>
                        <TextFieldWithTooltip label="List ID"
                            tooltipText="ID of a CList component on the page. See in the source code of a Theme or ask its author"
                            value={pluginSettings?.listId ?? ''}
                            style={{ marginBottom: '15px', marginRight: '15px', maxWidth: '450px' }}
                            onChange={e => changeSetting('listId', e.target.value)}
                        />
                        <TextFieldWithTooltip label="Mobile breakpoint (px)"
                            tooltipText="Width of the browser window in pixels that triggers mobile device mode where will be displayed only small icon that invokes filter modal pop-up"
                            value={(pluginSettings?.mobileBreakpoint ?? 600) + ''}
                            style={{ marginBottom: '15px', marginRight: '15px', maxWidth: '450px' }}
                            onChange={e => {
                                const num = Number(e.target.value);
                                if (!isNaN(num)) changeSetting('mobileBreakpoint', num);
                            }}
                        />
                        <h3 style={{ marginBottom: '15px', marginTop: '20px' }}>Mobile icon position (in pixels):</h3>
                        <TextField label="Top"
                            value={mobileIconPosition.top}
                            style={{ marginBottom: '15px', marginRight: '15px', maxWidth: '150px' }}
                            onChange={e => changeSetting('mobileIconPosition', {
                                ...mobileIconPosition,
                                top: parseInt(e.target.value)
                            })}
                            variant="standard"
                        />
                        <TextField label="Left"
                            value={mobileIconPosition.left}
                            style={{ marginBottom: '15px', maxWidth: '150px' }}
                            onChange={e => changeSetting('mobileIconPosition', {
                                ...mobileIconPosition,
                                left: parseInt(e.target.value)
                            })}
                            variant="standard"
                        />
                        <h3 style={{ marginBottom: '10px', marginTop: '10px' }}>Options visibility</h3>
                        <FormControlLabel
                            control={
                                <Checkbox
                                    checked={collapsedByDefault}
                                    onChange={() => changeSetting('collapsedByDefault', !collapsedByDefault)}
                                    color="primary"
                                />
                            }
                            label="All options collapsed by default at desktop screen"
                        />
                        <FormControlLabel
                            control={
                                <Checkbox
                                    checked={mobileCollapsedByDefault}
                                    onChange={() => changeSetting('mobileCollapsedByDefault', !mobileCollapsedByDefault)}
                                    color="primary"
                                />
                            }
                            label="All options collapsed by default at mobile screen"
                        />
                    </div>
                )
            }}
        </PluginSettingsLayout>
    )
}
Example #18
Source File: History.tsx    From your_spotify with GNU General Public License v3.0 5 votes vote down vote up
export default function History() {
  const { interval } = useSelector(selectRawIntervalDetail);
  const [items, setItems] = useState<TrackInfoWithTrack[]>([]);
  const [hasMore, setHasMore] = useState(true);
  const [followInterval, setFollowInterval] = useState(true);

  const fetch = useCallback(async () => {
    if (!hasMore) return;
    let result: UnboxPromise<ReturnType<typeof api.getTracks>>;
    if (followInterval) {
      result = await api.getTracks(10, items.length, interval.start, interval.end);
    } else {
      result = await api.getTracks(10, items.length);
    }
    setItems([...items, ...result.data]);
    setHasMore(result.data.length === 10);
  }, [hasMore, followInterval, items, interval.start, interval.end]);

  const reset = useCallback(() => {
    setItems([]);
    setHasMore(true);
    fetch();
  }, [fetch]);

  const handleSetFollowInterval = useCallback(
    (ev: React.SyntheticEvent, value: boolean) => {
      setFollowInterval(value);
      reset();
    },
    [reset],
  );

  useEffect(() => {
    reset();
    // initial fetch
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [interval]);

  useEffect(() => {
    fetch();
    // initial fetch
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <TitleCard
      title="Your history"
      right={
        <div className={s.followinterval}>
          <Checkbox checked={followInterval} onChange={handleSetFollowInterval} />
          <Text>Follow interval</Text>
        </div>
      }>
      <Track line playable />
      <InfiniteScroll dataLength={items.length} next={fetch} hasMore={hasMore} loader={<Loader />}>
        {items.map((item) => (
          <Track
            playable
            key={item.played_at}
            listenedAt={new Date(item.played_at)}
            artists={item.track.full_artist}
            album={item.track.full_album}
            track={item.track}
          />
        ))}
      </InfiniteScroll>
    </TitleCard>
  );
}
Example #19
Source File: LoginForm.tsx    From frontend with MIT License 5 votes vote down vote up
function LoginForm() {
  const { t } = useTranslation('one-time-donation')
  const formik = useFormikContext<OneTimeDonation>()
  return (
    <Collapse in={!formik.values.anonymousDonation} timeout="auto">
      <Grid sx={{ marginBottom: theme.spacing(4) }} container rowSpacing={3}>
        <Grid item xs={12}>
          <Typography fontWeight={'bold'} fontSize={16} color="#343434">
            {t('second-step.login')}
          </Typography>
        </Grid>
        <Grid item xs={12}>
          <FormTextField name="personsEmail" type="text" label="Email" fullWidth size="medium" />
        </Grid>
        <Grid item xs={12}>
          <FormTextField
            name="personsPassword"
            type="password"
            label={t('second-step.password')}
            fullWidth
            size="medium"
          />
        </Grid>
        <Box display={'flex'} justifyContent="space-between" width="100%" alignItems="center">
          <FormControlLabel
            control={<Checkbox />}
            label={t('second-step.checkbox-label') as string}
          />
          <Box sx={{ opacity: 0.85 }}>
            <Typography display="inline" color="GrayText">
              Don&apos;t have an account?
            </Typography>{' '}
            <Link color={theme.palette.primary.dark} href="#">
              Sign up
            </Link>
          </Box>
        </Box>
        <Button color="info" variant="contained" fullWidth sx={{ marginTop: theme.spacing(3) }}>
          {t('second-step.btn-login')}
        </Button>
        <Button
          size="large"
          color="primary"
          variant="outlined"
          fullWidth
          sx={{ marginTop: theme.spacing(3) }}>
          <Box display="inline-flex" alignItems="center" marginRight={theme.spacing(2)}>
            <Google />
          </Box>
          Log in with Google
        </Button>
      </Grid>
    </Collapse>
  )
}
Example #20
Source File: CheckboxButtonGroup.tsx    From react-hook-form-mui with MIT License 4 votes vote down vote up
export default function CheckboxButtonGroup({
  helperText,
  options,
  label,
  name,
  parseError,
  required,
  labelKey = 'label',
  valueKey = 'id',
  returnObject,
  disabled,
  row,
  control,
  checkboxColor,
  ...rest
}: CheckboxButtonGroupProps): JSX.Element {
  const theme = useTheme()
  const { field: { value = [], onChange }, fieldState: { invalid, error } } = useController({
    name,
    rules: required ? { required: 'This field is required' } : undefined,
    control
  })

  helperText = error ? (typeof parseError === 'function' ? parseError(error) : error.message) : helperText

  const handleChange = (index: number | string) => {
    const newArray = [...value]
    const exists =
      value.findIndex((i: any) =>
        returnObject ? i[valueKey] === index : i === index
      ) === -1
    if (exists) {
      newArray.push(
        returnObject ? options.find(i => i[valueKey] === index) : index
      )
    } else {
      newArray.splice(
        value.findIndex((i: any) =>
          returnObject ? i[valueKey] === index : i === index
        ),
        1
      )
    }
    // setValue(name, newArray, { shouldValidate: true })
    onChange(newArray)
    if (typeof rest.onChange === 'function') {
      rest.onChange(newArray)
    }
  }

  return (
    <FormControl error={invalid} required={required}>
      {label && <FormLabel error={invalid}>{label}</FormLabel>}
      <FormGroup row={row}>
        {options.map((option: any) => {
          const optionKey = option[valueKey]
          if (!optionKey) {
            console.error(
              `CheckboxButtonGroup: valueKey ${valueKey} does not exist on option`,
              option
            )
          }
          const isChecked =
            value.findIndex((item: any) =>
              returnObject ? item[valueKey] === optionKey : item === optionKey
            ) !== -1
          return (
            <FormControlLabel
              control={
                <Checkbox
                  sx={{
                    color: invalid ? theme.palette.error.main : undefined
                  }}
                  color={checkboxColor || 'primary'}
                  value={optionKey}
                  checked={isChecked}
                  disabled={disabled}
                  onChange={() => handleChange(optionKey)}
                />
              }
              label={option[labelKey]}
              key={optionKey}
            />
          )
        })}
      </FormGroup>
      {helperText && <FormHelperText>{helperText}</FormHelperText>}
    </FormControl>
  )
}
Example #21
Source File: EpisodeListing.tsx    From multi-downloader-nx with MIT License 4 votes vote down vote up
EpisodeListing: React.FC = () => {
  const [store, dispatch] = useStore();

  const [season, setSeason] = React.useState<'all'|string>('all');

  const seasons = React.useMemo(() => {
    const s: string[] = [];
    for (const {season} of store.episodeListing) {
      if (s.includes(season))
        continue;
      s.push(season);
    }
    return s;
  }, [ store.episodeListing ])

  const [selected, setSelected] = React.useState<string[]>([]);

  React.useEffect(() => {
    setSelected(parseSelect(store.downloadOptions.e));
  }, [ store.episodeListing ])

  const close = () => {
    dispatch({
      type: 'episodeListing',
      payload: []
    });
    dispatch({
      type: 'downloadOptions',
      payload: {
        ...store.downloadOptions,
        e: `${([...new Set([...parseSelect(store.downloadOptions.e), ...selected])]).join(',')}`
      }
    })
  }

  return <Dialog open={store.episodeListing.length > 0} onClose={close} scroll='paper' maxWidth='xl' sx={{ p: 2 }}>
      <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 200px 20px' }}>
        <Typography color='text.primary' variant="h5" sx={{ textAlign: 'center', alignItems: 'center', justifyContent: 'center', display: 'flex' }}>
          Episodes
        </Typography>
        <FormControl sx={{ mr: 2, mt: 2 }}>
          <InputLabel id='seasonSelectLabel'>Season</InputLabel>
          <Select labelId="seasonSelectLabel" label='Season' value={season} onChange={(e) => setSeason(e.target.value)}>
            <MenuItem value='all'>Show all Epsiodes</MenuItem>
            {seasons.map((a, index) => {
              return <MenuItem value={a} key={`MenuItem_SeasonSelect_${index}`}>
                {a}
              </MenuItem>
            })}
          </Select>
        </FormControl>
      </Box>
      <List>
        <ListItem sx={{ display: 'grid', gridTemplateColumns: '25px 1fr 5fr' }}>
          <Checkbox
            indeterminate={store.episodeListing.some(a => selected.includes(a.e)) && !store.episodeListing.every(a => selected.includes(a.e))}
            checked={store.episodeListing.every(a => selected.includes(a.e))}
            onChange={() => {
              if (selected.length > 0) {
                setSelected([]);
              } else {
                setSelected(store.episodeListing.map(a => a.e));
              }
            }}
          />
        </ListItem>
        {store.episodeListing.filter((a) => season === 'all' ? true : a.season === season).map((item, index, { length }) => {
          const e = isNaN(parseInt(item.e)) ? item.e : parseInt(item.e);
          const isSelected = selected.includes(e.toString());
          return <Box {...{ mouseData: isSelected }} key={`Episode_List_Item_${index}`} sx={{
              backdropFilter: isSelected ? 'brightness(1.5)' : '',
              '&:hover': {
                backdropFilter: 'brightness(1.5)'
              }
            }}
            onClick={() => {
              let arr: string[] = [];
              if (isSelected) {
                arr = [...selected.filter(a => a !== e.toString())];
              } else {
                arr = [...selected, e.toString()];
              }
              setSelected(arr.filter(a => a.length > 0));
            }}>
            <ListItem sx={{ display: 'grid', gridTemplateColumns: '25px 50px 1fr 5fr' }}>
              { isSelected ? <CheckBox /> : <CheckBoxOutlineBlank /> }
              <Typography color='text.primary' sx={{ textAlign: 'center' }}>
                {e}
              </Typography>
              <img style={{ width: 'inherit', maxHeight: '200px', minWidth: '150px' }} src={item.img}></img>
              <Box sx={{ display: 'flex', flexDirection: 'column', pl: 1 }}>
                <Box sx={{ display: 'grid', gridTemplateColumns: '1fr min-content' }}>
                  <Typography color='text.primary' variant="h5">
                    {item.name}
                  </Typography>
                  <Typography color='text.primary'>
                    {item.time.startsWith('00:') ? item.time.slice(3) : item.time}
                  </Typography>
                </Box>
                <Typography color='text.primary'>
                  {item.description}
                </Typography>
              </Box>
            </ListItem>
            {index < length - 1 && <Divider />}
          </Box>
        })}
      </List>
  </Dialog>
}
Example #22
Source File: Create.tsx    From metaplex with Apache License 2.0 4 votes vote down vote up
Create = () => {
  const connection = useConnection();
  const wallet = useWallet();
  const anchorWallet = useMemo(() => {
    if (
      !wallet ||
      !wallet.publicKey ||
      !wallet.signAllTransactions ||
      !wallet.signTransaction
    ) {
      return;
    }

    return {
      publicKey: wallet.publicKey,
      signAllTransactions: wallet.signAllTransactions,
      signTransaction: wallet.signTransaction,
    } as anchor.Wallet;
  }, [wallet]);

  const [mintA, setMintA] = React.useState(localStorage.getItem('mintA') || '');
  const [mintB, setMintB] = React.useState(localStorage.getItem('mintB') || '');
  const [price, setPrice] = React.useState(localStorage.getItem('price') || '');
  const [paysEveryTime, setPaysEveryTime] = React.useState(false);
  const [authority, setAuthority] = React.useState(
    localStorage.getItem('authority') || '',
  );

  useEffect(() => {
    (async () => {
      if (!anchorWallet) {
        return;
      }
      setAuthority(anchorWallet.publicKey.toString());
    })();
  }, [anchorWallet]);

  const handleSubmit = async (event: React.MouseEvent<HTMLElement>) => {
    event.preventDefault();
    if (!anchorWallet) {
      return;
    }
    const res = await createEntanglement(
      anchorWallet,
      connection,
      null,
      authority,
      paysEveryTime,
      price,
      mintA,
      mintB,
    );
    console.log(res);
  };

  const isEnable = (
    mintA: string,
    mintB: string,
    authority: string,
    price: string,
  ): boolean => {
    return (
      // eslint-disable-next-line no-extra-boolean-cast
      !!mintA && !!mintB && !!price && !!authority
    );
  };

  return (
    <React.Fragment>
      <Typography variant="h4" color="text.primary" gutterBottom>
        Create Entanglement
      </Typography>
      <p>
        Create an entanglement between two NFTs. Using connected wallet as
        entanglement authority.
      </p>

      <Box
        component="form"
        sx={{
          '& .MuiTextField-root': { m: 1, width: '25ch' },
        }}
        noValidate
        autoComplete="off"
      >
        <TextField
          required
          id="mintA-text-field"
          label="MintA"
          helperText="You do not even need to own this token to create this entanglement."
          value={mintA}
          onChange={e => {
            localStorage.setItem('mintA', e.target.value);
            setMintA(e.target.value);
          }}
        />
        <TextField
          required
          id="mintB-text-field"
          label="MintB"
          helperText="This token will be removed from your token account right now."
          value={mintB}
          onChange={e => {
            localStorage.setItem('mintB', e.target.value);
            setMintB(e.target.value);
          }}
        />
        <TextField
          required
          id="authority-text-field"
          label="Authority"
          helperText="Entanglement Authority"
          value={authority}
          onChange={e => {
            localStorage.setItem('authority', e.target.value);
            setAuthority(e.target.value);
          }}
        />
        <TextField
          required
          id="price-text-field"
          helperText="Price for a swap"
          label="Price"
          value={price}
          onChange={e => {
            localStorage.setItem('price', e.target.value);
            setPrice(e.target.value);
          }}
        />
        <FormGroup>
          <FormControlLabel
            control={
              <Checkbox
                checked={paysEveryTime}
                onChange={e => {
                  setPaysEveryTime(e.target.checked);
                }}
              />
            }
            label="Pay the swapping fee each swap"
          />
        </FormGroup>
        <FormGroup>
          <Button
            variant="contained"
            onClick={async e => await handleSubmit(e)}
            endIcon={<SendIcon />}
            disabled={!isEnable(mintA, mintB, price, authority)}
          >
            Entangle
          </Button>
        </FormGroup>
        {!isEnable(mintA, mintB, price, authority) && (
          <Alert severity="warning" style={{ marginTop: '1rem' }}>
            <AlertTitle>Warning</AlertTitle>
            You should fill the four inputs.
          </Alert>
        )}
      </Box>
    </React.Fragment>
  );
}
Example #23
Source File: GroupSettings.tsx    From abrechnung with GNU Affero General Public License v3.0 4 votes vote down vote up
export default function GroupSettings({ group }) {
    const [showLeaveModal, setShowLeaveModal] = useState(false);
    const history = useHistory();

    const userPermissions = useRecoilValue(currUserPermissions(group.id));

    const [isEditing, setIsEditing] = useState(false);

    useTitle(`${group.name} - Settings`);

    const startEdit = () => {
        setIsEditing(true);
    };

    const stopEdit = () => {
        setIsEditing(false);
    };

    const handleSubmit = (values, { setSubmitting }) => {
        updateGroupMetadata({
            groupID: group.id,
            name: values.name,
            description: values.description,
            currencySymbol: values.currencySymbol,
            terms: values.terms,
            addUserAccountOnJoin: values.addUserAccountOnJoin,
        })
            .then((res) => {
                setSubmitting(false);
                setIsEditing(false);
            })
            .catch((err) => {
                setSubmitting(false);
                toast.error(err);
            });
    };

    const confirmLeaveGroup = () => {
        leaveGroup({ groupID: group.id })
            .then((res) => {
                history.push("/");
            })
            .catch((err) => {
                toast.error(err);
            });
    };

    return (
        <MobilePaper>
            {userPermissions.is_owner ? (
                <Alert severity="info">You are an owner of this group</Alert>
            ) : !userPermissions.can_write ? (
                <Alert severity="info">You only have read access to this group</Alert>
            ) : null}

            <Formik
                initialValues={{
                    name: group.name,
                    description: group.description,
                    terms: group.terms,
                    currencySymbol: group.currency_symbol,
                    addUserAccountOnJoin: group.add_user_account_on_join,
                }}
                onSubmit={handleSubmit}
                validationSchema={validationSchema}
                enableReinitialize={true}
            >
                {({ values, handleBlur, handleChange, handleSubmit, isSubmitting }) => (
                    <Form onSubmit={handleSubmit}>
                        <DisabledTextField
                            variant="standard"
                            margin="normal"
                            required
                            fullWidth
                            type="text"
                            label="Name"
                            name="name"
                            disabled={!userPermissions.can_write || !isEditing}
                            onBlur={handleBlur}
                            onChange={handleChange}
                            value={values.name}
                        />

                        <DisabledTextField
                            variant="standard"
                            margin="normal"
                            fullWidth
                            type="text"
                            name="description"
                            label="Description"
                            disabled={!userPermissions.can_write || !isEditing}
                            onBlur={handleBlur}
                            onChange={handleChange}
                            value={values.description}
                        />
                        <DisabledTextField
                            variant="standard"
                            margin="normal"
                            required
                            fullWidth
                            type="text"
                            name="currencySymbol"
                            label="Currency"
                            disabled={!userPermissions.can_write || !isEditing}
                            onBlur={handleBlur}
                            onChange={handleChange}
                            value={values.currencySymbol}
                        />
                        <DisabledTextField
                            variant="standard"
                            multiline={true}
                            margin="normal"
                            fullWidth
                            type="text"
                            name="terms"
                            label="Terms"
                            disabled={!userPermissions.can_write || !isEditing}
                            onBlur={handleBlur}
                            onChange={handleChange}
                            value={values.terms}
                        />
                        <FormGroup>
                            <DisabledFormControlLabel
                                control={
                                    <Checkbox
                                        name="addUserAccountOnJoin"
                                        disabled={!userPermissions.can_write || !isEditing}
                                        onBlur={handleBlur}
                                        onChange={handleChange}
                                        checked={values.addUserAccountOnJoin}
                                    />
                                }
                                label="Automatically add accounts for newly joined group members"
                            />
                        </FormGroup>

                        {isSubmitting && <LinearProgress />}
                        <Grid container justifyContent="space-between" style={{ marginTop: 10 }}>
                            <div>
                                {userPermissions.can_write && isEditing && (
                                    <>
                                        <Button
                                            type="submit"
                                            variant="contained"
                                            color="primary"
                                            disabled={isSubmitting}
                                            startIcon={<Save />}
                                        >
                                            Save
                                        </Button>
                                        <Button
                                            variant="contained"
                                            color="error"
                                            disabled={isSubmitting}
                                            onClick={stopEdit}
                                            startIcon={<Cancel />}
                                            sx={{ ml: 1 }}
                                        >
                                            Cancel
                                        </Button>
                                    </>
                                )}
                                {userPermissions.can_write && !isEditing && (
                                    <Button
                                        variant="contained"
                                        color="primary"
                                        disabled={isSubmitting}
                                        onClick={startEdit}
                                        startIcon={<Edit />}
                                    >
                                        Edit
                                    </Button>
                                )}
                            </div>
                            <Button variant="contained" onClick={() => setShowLeaveModal(true)}>
                                Leave Group
                            </Button>
                        </Grid>
                    </Form>
                )}
            </Formik>

            {/*<List>*/}
            {/*    <ListItem>*/}
            {/*        <ListItemText primary="Created" secondary={group.created}/>*/}
            {/*    </ListItem>*/}
            {/*    <ListItem>*/}
            {/*        <ListItemText primary="Joined" secondary={group.joined}/>*/}
            {/*    </ListItem>*/}
            {/*</List>*/}

            <Dialog open={showLeaveModal} onClose={() => setShowLeaveModal(false)}>
                <DialogTitle>Leave Group</DialogTitle>
                <DialogContent>
                    <DialogContentText>
                        <span>
                            Are you sure you want to leave the group {group.name}. If you are the last member to leave
                            this group it will be deleted and its transaction will be lost forever...
                        </span>
                    </DialogContentText>
                </DialogContent>
                <DialogActions>
                    <Button color="secondary" onClick={confirmLeaveGroup}>
                        Yes pls
                    </Button>
                    <Button color="primary" onClick={() => setShowLeaveModal(false)}>
                        No
                    </Button>
                </DialogActions>
            </Dialog>
        </MobilePaper>
    );
}
Example #24
Source File: TableWrapper.tsx    From console with GNU Affero General Public License v3.0 4 votes vote down vote up
TableWrapper = ({
  itemActions,
  columns,
  onSelect,
  records,
  isLoading,
  loadingMessage = <Typography component="h3">Loading...</Typography>,
  entityName,
  selectedItems,
  idField,
  classes,
  radioSelection = false,
  customEmptyMessage = "",
  customPaperHeight = "",
  noBackground = false,
  columnsSelector = false,
  textSelectable = false,
  columnsShown = [],
  onColumnChange = (column: string, state: boolean) => {},
  infiniteScrollConfig,
  sortConfig,
  autoScrollToBottom = false,
  disabled = false,
  onSelectAll,
  rowStyle,
  parentClassName = "",
}: TableWrapperProps) => {
  const [columnSelectorOpen, setColumnSelectorOpen] = useState<boolean>(false);
  const [anchorEl, setAnchorEl] = React.useState<any>(null);

  const findView = itemActions
    ? itemActions.find((el) => el.type === "view")
    : null;

  const clickAction = (rowItem: any) => {
    if (findView) {
      const valueClick = findView.sendOnlyId ? rowItem[idField] : rowItem;

      let disabled = false;

      if (findView.disableButtonFunction) {
        if (findView.disableButtonFunction(valueClick)) {
          disabled = true;
        }
      }

      if (findView.to && !disabled) {
        history.push(`${findView.to}/${valueClick}`);
        return;
      }

      if (findView.onClick && !disabled) {
        findView.onClick(valueClick);
      }
    }
  };

  const openColumnsSelector = (event: { currentTarget: any }) => {
    setColumnSelectorOpen(!columnSelectorOpen);
    setAnchorEl(event.currentTarget);
  };

  const closeColumnSelector = () => {
    setColumnSelectorOpen(false);
    setAnchorEl(null);
  };

  const columnsSelection = (columns: IColumns[]) => {
    return (
      <Fragment>
        <IconButton
          aria-describedby={"columnsSelector"}
          color="primary"
          onClick={openColumnsSelector}
          size="large"
        >
          <ViewColumnIcon fontSize="inherit" />
        </IconButton>
        <Popover
          anchorEl={anchorEl}
          id={"columnsSelector"}
          open={columnSelectorOpen}
          anchorOrigin={{
            vertical: "bottom",
            horizontal: "left",
          }}
          transformOrigin={{
            vertical: "top",
            horizontal: "left",
          }}
          onClose={closeColumnSelector}
        >
          <div className={classes.shownColumnsLabel}>Shown Columns</div>
          <div className={classes.popoverContent}>
            {columns.map((column: IColumns) => {
              return (
                <CheckboxWrapper
                  key={`tableColumns-${column.label}`}
                  label={column.label}
                  checked={columnsShown.includes(column.elementKey!)}
                  onChange={(e) => {
                    onColumnChange(column.elementKey!, e.target.checked);
                  }}
                  id={`chbox-${column.label}`}
                  name={`chbox-${column.label}`}
                  value={column.label}
                />
              );
            })}
          </div>
        </Popover>
      </Fragment>
    );
  };

  return (
    <Grid item xs={12} className={parentClassName}>
      <Paper
        className={`${classes.paper} ${noBackground ? classes.noBackground : ""}
        ${disabled ? classes.disabled : ""} 
        ${
          customPaperHeight !== ""
            ? customPaperHeight
            : classes.defaultPaperHeight
        }`}
      >
        {isLoading && (
          <Grid container className={classes.loadingBox}>
            <Grid item xs={12} style={{ textAlign: "center" }}>
              {loadingMessage}
            </Grid>
            <Grid item xs={12}>
              <LinearProgress />
            </Grid>
          </Grid>
        )}
        {columnsSelector && !isLoading && records.length > 0 && (
          <div className={classes.overlayColumnSelection}>
            {columnsSelection(columns)}
          </div>
        )}
        {records && !isLoading && records.length > 0 ? (
          // @ts-ignore
          <InfiniteLoader
            isRowLoaded={({ index }) => !!records[index]}
            loadMoreRows={
              infiniteScrollConfig
                ? infiniteScrollConfig.loadMoreRecords
                : () => new Promise(() => true)
            }
            rowCount={
              infiniteScrollConfig
                ? infiniteScrollConfig.recordsCount
                : records.length
            }
          >
            {({ onRowsRendered, registerChild }) => (
              // @ts-ignore
              <AutoSizer>
                {({ width, height }: any) => {
                  const optionsWidth = calculateOptionsSize(
                    width,
                    itemActions
                      ? itemActions.filter((el) => el.type !== "view").length
                      : 0
                  );
                  const hasSelect: boolean = !!(onSelect && selectedItems);
                  const hasOptions: boolean = !!(
                    (itemActions && itemActions.length > 1) ||
                    (itemActions &&
                      itemActions.length === 1 &&
                      itemActions[0].type !== "view")
                  );
                  return (
                    // @ts-ignore
                    <Table
                      ref={registerChild}
                      disableHeader={false}
                      headerClassName={"headerItem"}
                      headerHeight={40}
                      height={height}
                      noRowsRenderer={() => (
                        <Fragment>
                          {customEmptyMessage !== ""
                            ? customEmptyMessage
                            : `There are no ${entityName} yet.`}
                        </Fragment>
                      )}
                      overscanRowCount={10}
                      rowHeight={40}
                      width={width}
                      rowCount={records.length}
                      rowGetter={({ index }) => records[index]}
                      onRowClick={({ rowData }) => {
                        clickAction(rowData);
                      }}
                      rowClassName={`rowLine ${findView ? "canClick" : ""} ${
                        !findView && textSelectable ? "canSelectText" : ""
                      }`}
                      onRowsRendered={onRowsRendered}
                      sort={sortConfig ? sortConfig.triggerSort : undefined}
                      sortBy={sortConfig ? sortConfig.currentSort : undefined}
                      sortDirection={
                        sortConfig ? sortConfig.currentDirection : undefined
                      }
                      scrollToIndex={
                        autoScrollToBottom ? records.length - 1 : -1
                      }
                      rowStyle={(r) => {
                        if (rowStyle) {
                          const returnElement = rowStyle(r);

                          if (typeof returnElement === "string") {
                            return get(TableRowPredefStyles, returnElement, {});
                          }

                          return returnElement;
                        }

                        return {};
                      }}
                    >
                      {hasSelect && (
                        // @ts-ignore
                        <Column
                          headerRenderer={() => (
                            <Fragment>
                              {onSelectAll ? (
                                <div className={classes.checkAllWrapper}>
                                  <CheckboxWrapper
                                    label={""}
                                    onChange={onSelectAll}
                                    value="all"
                                    id={"selectAll"}
                                    name={"selectAll"}
                                    checked={
                                      selectedItems?.length === records.length
                                    }
                                  />
                                </div>
                              ) : (
                                <Fragment>Select</Fragment>
                              )}
                            </Fragment>
                          )}
                          dataKey={`select-${idField}`}
                          width={selectWidth}
                          disableSort
                          cellRenderer={({ rowData }) => {
                            const isSelected = selectedItems
                              ? selectedItems.includes(
                                  isString(rowData) ? rowData : rowData[idField]
                                )
                              : false;

                            return (
                              <Checkbox
                                value={
                                  isString(rowData) ? rowData : rowData[idField]
                                }
                                color="primary"
                                inputProps={{
                                  "aria-label": "secondary checkbox",
                                }}
                                className="TableCheckbox"
                                checked={isSelected}
                                onChange={onSelect}
                                onClick={(e) => {
                                  e.stopPropagation();
                                }}
                                checkedIcon={
                                  <span
                                    className={
                                      radioSelection
                                        ? classes.radioSelectedIcon
                                        : classes.checkedIcon
                                    }
                                  />
                                }
                                icon={
                                  <span
                                    className={
                                      radioSelection
                                        ? classes.radioUnselectedIcon
                                        : classes.unCheckedIcon
                                    }
                                  />
                                }
                              />
                            );
                          }}
                        />
                      )}
                      {generateColumnsMap(
                        columns,
                        width,
                        optionsWidth,
                        hasSelect,
                        hasOptions,
                        selectedItems || [],
                        idField,
                        columnsSelector,
                        columnsShown,
                        sortConfig ? sortConfig.currentSort : "",
                        sortConfig ? sortConfig.currentDirection : undefined
                      )}
                      {hasOptions && (
                        // @ts-ignore
                        <Column
                          dataKey={idField}
                          width={optionsWidth}
                          headerClassName="optionsAlignment"
                          className="optionsAlignment"
                          cellRenderer={({ rowData }) => {
                            const isSelected = selectedItems
                              ? selectedItems.includes(
                                  isString(rowData) ? rowData : rowData[idField]
                                )
                              : false;
                            return elementActions(
                              itemActions || [],
                              rowData,
                              isSelected,
                              idField
                            );
                          }}
                        />
                      )}
                    </Table>
                  );
                }}
              </AutoSizer>
            )}
          </InfiniteLoader>
        ) : (
          <Fragment>
            {!isLoading && (
              <div>
                {customEmptyMessage !== ""
                  ? customEmptyMessage
                  : `There are no ${entityName} yet.`}
              </div>
            )}
          </Fragment>
        )}
      </Paper>
    </Grid>
  );
}
Example #25
Source File: index.tsx    From mui-toolpad with MIT License 4 votes vote down vote up
function ApiEditorContent<Q>({ appId, className, apiNode }: ApiEditorContentProps<Q>) {
  const domApi = useDomApi();
  const dom = useDom();

  const [apiQuery, setApiQuery] = React.useState<Q>(apiNode.attributes.query.value);
  const savedQuery = React.useRef(apiNode.attributes.query.value);

  const [transformEnabled, setTransformEnabled] = React.useState<boolean>(
    apiNode.attributes.transformEnabled?.value ?? false,
  );
  const savedTransformEnabled = React.useRef(apiNode.attributes.transformEnabled?.value);

  const [transform, setTransform] = React.useState<string>(
    apiNode.attributes.transform?.value ?? '(data) => { return data }',
  );
  const savedTransform = React.useRef(apiNode.attributes.transform?.value);

  const conectionId = apiNode.attributes.connectionId.value as NodeId;
  const connection = appDom.getMaybeNode(dom, conectionId, 'connection');
  const dataSourceName = apiNode.attributes.dataSource.value;
  const dataSource = dataSources[dataSourceName] || null;

  const previewApi: appDom.ApiNode<Q> = React.useMemo(() => {
    return {
      ...apiNode,
      attributes: {
        ...apiNode.attributes,
        query: appDom.createConst(apiQuery),
        transformEnabled: appDom.createConst(transformEnabled),
        transform: appDom.createConst(transform),
      },
    };
  }, [apiNode, apiQuery, transformEnabled, transform]);

  const debouncedPreviewApi = useDebounced(previewApi, 250);

  const previewQuery = useQuery(['api', debouncedPreviewApi], async () =>
    client.query.execApi(appId, debouncedPreviewApi, {}),
  );

  const handleConnectionChange = React.useCallback(
    (newConnectionId) => {
      if (apiNode) {
        domApi.setNodeNamespacedProp(
          apiNode,
          'attributes',
          'connectionId',
          appDom.createConst(newConnectionId),
        );
      }
    },
    [apiNode, domApi],
  );

  const handleTransformFnChange = React.useCallback((newValue: string) => {
    setTransform(newValue);
  }, []);

  const handleTransformEnabledChange = React.useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      setTransformEnabled(event.target.checked);
    },
    [],
  );

  const handleSave = React.useCallback(() => {
    (Object.keys(apiQuery) as (keyof Q)[]).forEach((propName) => {
      if (typeof propName !== 'string' || !apiQuery[propName]) {
        return;
      }
      domApi.setNodeNamespacedProp(apiNode, 'attributes', 'query', appDom.createConst(apiQuery));
      domApi.setNodeNamespacedProp(
        apiNode,
        'attributes',
        'transform',
        appDom.createConst(transform),
      );
      domApi.setNodeNamespacedProp(
        apiNode,
        'attributes',
        'transformEnabled',
        appDom.createConst(transformEnabled),
      );
    });
    savedQuery.current = apiQuery;
    savedTransform.current = transform;
    savedTransformEnabled.current = transformEnabled;
  }, [apiNode, apiQuery, domApi, transform, transformEnabled]);

  useShortcut({ code: 'KeyS', metaKey: true }, handleSave);

  const allChangesAreCommitted =
    savedQuery.current === apiQuery &&
    savedTransformEnabled.current === transformEnabled &&
    savedTransform.current === transform;

  usePrompt(
    'Your API has unsaved changes. Are you sure you want to navigate away? All changes will be discarded.',
    !allChangesAreCommitted,
  );

  if (!dataSource) {
    return (
      <NotFoundEditor className={className} message={`DataSource "${dataSourceName}" not found`} />
    );
  }

  const previewIsInvalid: boolean = !connection && !previewQuery.isError;

  return (
    <Box sx={{ width: '100%', height: '100%' }}>
      <SplitPane
        split="horizontal"
        allowResize
        defaultSize="60%"
        paneStyle={{
          width: '100%',
          overflowY: 'auto',
          display: 'block',
        }}
      >
        <Stack sx={{ width: '100%', p: 3 }}>
          <Stack direction="row" gap={2}>
            <NodeNameEditor node={apiNode} />
            <ConnectionSelect
              dataSource={dataSourceName}
              value={connection?.id ?? null}
              onChange={handleConnectionChange}
            />
          </Stack>
          <Toolbar disableGutters>
            <Button onClick={handleSave} disabled={allChangesAreCommitted}>
              Update
            </Button>
          </Toolbar>
          <Stack spacing={2}>
            {connection ? (
              <dataSource.QueryEditor
                appId={appId}
                connectionId={connection.id}
                // TODO: Add disabled mode to QueryEditor
                // disabled={!connection}
                value={apiQuery}
                onChange={(newApiQuery) => setApiQuery(newApiQuery)}
                globalScope={{}}
              />
            ) : null}
            <Stack>
              <FormControlLabel
                label="Transform API response"
                control={
                  <Checkbox
                    checked={transformEnabled}
                    onChange={handleTransformEnabledChange}
                    inputProps={{ 'aria-label': 'controlled' }}
                  />
                }
              />
            </Stack>
            {transformEnabled ? (
              <JsExpressionEditor
                globalScope={{}}
                value={transform}
                onChange={handleTransformFnChange}
              />
            ) : null}
          </Stack>
        </Stack>
        {previewQuery.isLoading || (previewIsInvalid && previewQuery.isFetching) ? (
          <LinearProgress />
        ) : null}
        <Box sx={{ p: 2 }}>
          {previewQuery.isError ? (
            <Alert severity="error">{(previewQuery.error as Error).message}</Alert>
          ) : null}
          {!previewIsInvalid && previewQuery.isSuccess ? (
            <JsonView src={previewQuery.data} />
          ) : null}
        </Box>
      </SplitPane>
    </Box>
  );
}
Example #26
Source File: ItemViewer.tsx    From NekoMaid with MIT License 4 votes vote down vote up
ItemEditor: React.FC = () => {
  const plugin = usePlugin()
  const theme = useTheme()
  const [item, setItem] = useState<Item | undefined>()
  const [types, setTypes] = useState<string[]>([])
  const [tab, setTab] = useState(0)
  const [level, setLevel] = useState(1)
  const [enchantment, setEnchantment] = useState<string | undefined>()
  const [nbtText, setNBTText] = useState('')
  const nbt: NBT = item?.nbt ? parse(item.nbt) : { id: 'minecraft:' + (item?.type || 'air').toLowerCase(), Count: new Byte(1) } as any
  useEffect(() => {
    if (!item || types.length) return
    plugin.emit('item:fetch', (a: string[], b: string[]) => {
      setTypes(a)
      enchantments = b
    })
  }, [item])
  useEffect(() => {
    _setItem = (it: any) => {
      setItem(it)
      setNBTText(it.nbt ? stringify(parse(it.nbt), { pretty: true }) : '')
    }
    return () => { _setItem = null }
  }, [])
  const cancel = () => {
    setItem(undefined)
    if (_resolve) {
      _resolve(false)
      _resolve = null
    }
  }
  const update = () => {
    const newItem: any = { ...item }
    if (nbt) {
      newItem.nbt = stringify(nbt as any)
      setNBTText(stringify(nbt, { pretty: true }))
    }
    setItem(newItem)
  }
  const isAir = item?.type === 'AIR'
  const name = nbt?.tag?.display?.Name
  const enchantmentMap: Record<string, true> = { }
  return <Dialog open={!!item} onClose={cancel}>
    <DialogTitle>{lang.itemEditor.title}</DialogTitle>
    <DialogContent sx={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'center' }}>
      {item && <Box sx={{ display: 'flex', width: '100%', justifyContent: 'center' }}>
        <ItemViewer item={item} />
        <Autocomplete
          options={types}
          sx={{ maxWidth: 300, marginLeft: 1, flexGrow: 1 }}
          value={item?.type}
          onChange={(_, it) => {
            item.type = it || 'AIR'
            if (nbt) nbt.id = 'minecraft:' + (it ? it.toLowerCase() : 'air')
            update()
          }}
          getOptionLabel={it => {
            const locatedName = getName(it.toLowerCase())
            return (locatedName ? locatedName + ' ' : '') + it
          }}
          renderInput={(params) => <TextField {...params} label={lang.itemEditor.itemType} size='small' variant='standard' />}
        />
      </Box>}
      <Tabs centered value={tab} onChange={(_, it) => setTab(it)} sx={{ marginBottom: 2 }}>
        <Tab label={lang.itemEditor.baseAttribute} disabled={isAir} />
        <Tab label={minecraft['container.enchant']} disabled={isAir} />
        <Tab label='NBT' disabled={isAir} />
      </Tabs>
      {nbt && tab === 0 && <Grid container spacing={1} rowSpacing={1}>
        <Grid item xs={12} md={6}><TextField
          fullWidth
          label={lang.itemEditor.count}
          type='number'
          variant='standard'
          value={nbt.Count}
          disabled={isAir}
          onChange={e => {
            nbt.Count = new Byte(item!.amount = parseInt(e.target.value))
            update()
          }}
        /></Grid>
        <Grid item xs={12} md={6}><TextField
          fullWidth
          label={lang.itemEditor.damage}
          type='number'
          variant='standard'
          value={nbt.tag?.Damage}
          disabled={isAir}
          onChange={e => {
            set(nbt, 'tag.Damage', parseInt(e.target.value))
            update()
          }}
        /></Grid>
        <Grid item xs={12} md={6}>
          <TextField
            fullWidth
            label={lang.itemEditor.displayName}
            variant='standard'
            disabled={isAir}
            value={name ? stringifyTextComponent(JSON.parse(name)) : ''}
            onChange={e => {
              set(nbt, 'tag.display.Name', JSON.stringify(item!.name = e.target.value))
              update()
            }}
          />
          <FormControlLabel
            label={minecraft['item.unbreakable']}
            disabled={isAir}
            checked={nbt.tag?.Unbreakable?.value === 1}
            control={<Checkbox
              checked={nbt.tag?.Unbreakable?.value === 1}
              onChange={e => {
                set(nbt, 'tag.Unbreakable', new Byte(+e.target.checked))
                update()
              }} />
            }
          />
        </Grid>
        <Grid item xs={12} md={6}><TextField
          fullWidth
          multiline
          label={lang.itemEditor.lore}
          variant='standard'
          maxRows={5}
          disabled={isAir}
          value={nbt.tag?.display?.Lore?.map(l => stringifyTextComponent(JSON.parse(l)))?.join('\n') || ''}
          onChange={e => {
            set(nbt, 'tag.display.Lore', e.target.value.split('\n').map(text => JSON.stringify(text)))
            update()
          }}
        /></Grid>
      </Grid>}
      {nbt && tab === 1 && <Grid container spacing={1} sx={{ width: '100%' }}>
        {nbt.tag?.Enchantments?.map((it, i) => {
          enchantmentMap[it.id] = true
          return <Grid item key={i}><Chip label={getEnchantmentName(it)} onDelete={() => {
            nbt?.tag?.Enchantments?.splice(i, 1)
            update()
          }} /></Grid>
        })}
        <Grid item><Chip label={lang.itemEditor.newEnchantment} color='primary' onClick={() => {
          setEnchantment('')
          setLevel(1)
        }} /></Grid>
        <Dialog onClose={() => setEnchantment(undefined)} open={enchantment != null}>
          <DialogTitle>{lang.itemEditor.newEnchantmentTitle}</DialogTitle>
          <DialogContent>
            <Box component='form' sx={{ display: 'flex', flexWrap: 'wrap' }}>
              <FormControl variant='standard' sx={{ m: 1, minWidth: 120 }}>
                <InputLabel htmlFor='item-editor-enchantment-selector'>{minecraft['container.enchant']}</InputLabel>
                <Select
                  id='item-editor-enchantment-selector'
                  label={minecraft['container.enchant']}
                  value={enchantment || ''}
                  onChange={e => setEnchantment(e.target.value)}
                >{enchantments
                  .filter(e => !(e in enchantmentMap))
                  .map(it => <MenuItem key={it} value={it}>{getEnchantmentName(it)}</MenuItem>)}
                </Select>
              </FormControl>
              <FormControl sx={{ m: 1, minWidth: 120 }}>
                <TextField
                  label={lang.itemEditor.level}
                  type='number'
                  variant='standard'
                  value={level}
                  onChange={e => setLevel(parseInt(e.target.value))}
                />
              </FormControl>
            </Box>
          </DialogContent>
          <DialogActions>
            <Button onClick={() => setEnchantment(undefined)}>{minecraft['gui.cancel']}</Button>
            <Button disabled={!enchantment || isNaN(level)} onClick={() => {
              if (nbt) {
                if (!nbt.tag) nbt.tag = { Damage: new Int(0) }
                ;(nbt.tag.Enchantments || (nbt.tag.Enchantments = [])).push({ id: enchantment!, lvl: new Short(level) })
              }
              setEnchantment(undefined)
              update()
            }}>{minecraft['gui.ok']}</Button>
          </DialogActions>
        </Dialog>
      </Grid>}
    </DialogContent>
    {nbt && tab === 2 && <Box sx={{
      '& .CodeMirror': { width: '100%' },
      '& .CodeMirror-dialog, .CodeMirror-scrollbar-filler': { backgroundColor: theme.palette.background.paper + '!important' }
    }}>
      <UnControlled
        value={nbtText}
        options={{
          mode: 'javascript',
          phrases: lang.codeMirrorPhrases,
          theme: theme.palette.mode === 'dark' ? 'material' : 'one-light'
        }}
        onChange={(_: any, __: any, nbt: string) => {
          const n = parse(nbt) as any as NBT
          const newItem: any = { ...item, nbt }
          if (n.Count?.value != null) newItem.amount = n.Count.value
          setItem(newItem)
        }}
      />
    </Box>}
    <DialogActions>
      <Button onClick={cancel}>{minecraft['gui.cancel']}</Button>
      <Button onClick={() => {
        setItem(undefined)
        if (_resolve) {
          _resolve(!item || item.type === 'AIR' ? null : item)
          _resolve = null
        }
      }}>{minecraft['gui.ok']}</Button>
    </DialogActions>
  </Dialog>
}
Example #27
Source File: CertificatesTab.tsx    From frontend with MIT License 4 votes vote down vote up
export default function CertificatesTab() {
  const { data = { donations: [], total: 0 } } = useUserDonations()
  const [fromDate, setFromDate] = React.useState(new Date())
  const [toDate, setToDate] = React.useState(new Date())

  return (
    <Root>
      <Box className={classes.boxTitle}>
        <Typography className={classes.h3}>История на сертификати</Typography>
      </Box>
      <ProfileTab name={ProfileTabs.certificates}>
        <Box>
          <Box sx={{ mt: 4 }}>
            <h3 className={classes.thinFont}>Онлайн дарения</h3>
          </Box>
          <Box
            sx={{
              display: 'flex',
              alignItems: 'baseline',
              justifyContent: 'space-between',
              mt: 2,
            }}>
            <span className={classes.smallText}>Покажи:</span>
            <Box>
              <Checkbox defaultChecked />
              <span className={classes.smallText}>еднократни</span>
            </Box>
            <Box>
              <Checkbox defaultChecked />
              <span className={classes.smallText}>месечни</span>
            </Box>
            <LocalizationProvider dateAdapter={AdapterDateFns}>
              <span className={classes.smallText}>от дата</span>
              <DesktopDatePicker
                label="от дата"
                inputFormat="MM/dd/yyyy"
                value={fromDate}
                onChange={(date) => setFromDate(date as Date)}
                renderInput={(params) => <TextField {...params} />}
              />
              <span className={classes.smallText}>до дата</span>
              <DesktopDatePicker
                label="до дата"
                inputFormat="MM/dd/yyyy"
                value={toDate}
                onChange={(date) => setToDate(date as Date)}
                renderInput={(params) => <TextField {...params} />}
              />
            </LocalizationProvider>
          </Box>
          {data.donations.length ? (
            <TableContainer>
              <Table sx={{ minWidth: 650, backgroundColor: 'white' }} aria-label="simple table">
                <TableHead>
                  <TableRow>
                    <TableCell>№</TableCell>
                    <TableCell>Дата</TableCell>
                    <TableCell>Вид</TableCell>
                    <TableCell>Кауза</TableCell>
                    <TableCell>стойност</TableCell>
                    <TableCell>сертификат</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {data.donations.map((donation, index) => (
                    <TableRow
                      key={index}
                      sx={{ '&:last-child td, &:last-child th': { border: 0 } }}>
                      <TableCell component="th" scope="row">
                        {index + 1}
                      </TableCell>
                      <TableCell>{formatDateString(donation.createdAt)}</TableCell>
                      <TableCell>
                        <Avatar sx={{ background: '#F6992B' }}>
                          <StarIcon />
                        </Avatar>
                      </TableCell>
                      <TableCell>{donation.targetVault.campaign.title}</TableCell>
                      <TableCell>
                        {donation.amount} {donation.currency}
                      </TableCell>
                      <TableCell>
                        <Button variant="outlined">
                          Свали <ArrowForwardIcon />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          ) : (
            <Box sx={{ fontSize: 20, mt: 4 }}>Към момента няма направени дарения</Box>
          )}
        </Box>
      </ProfileTab>
    </Root>
  )
}
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: 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>
    );
}