@material-ui/core#Checkbox TypeScript Examples

The following examples show how to use @material-ui/core#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: YourTurnContent.tsx    From fishbowl with MIT License 6 votes vote down vote up
GreenCheckbox = withStyles({
  root: {
    color: grey[600],
    "&$checked": {
      color: green[600],
    },
  },
  checked: {},
})((props: CheckboxProps) => <Checkbox color="default" {...props} />)
Example #2
Source File: Checklists.tsx    From listo with MIT License 6 votes vote down vote up
ListoCheckbox = (props: ChecklistProps) => {
  const classes = useStyles();
  const { handleSelectChecklistItem } = useContext(AppContext);
  if (props.toolsSupported.length) {
    return (
      <div className={classes.checklistQuestion}>
        <CheckCircleOutlineIcon className={classes.questionIcon} />
      </div>
      );
  } else if (!props.readOnlyMode) {
    return (<Checkbox
      checked={Boolean(props.checklistItem.checked)}
      onChange={event => {
        handleSelectChecklistItem(
          props.checklistName,
          props.checklistItemIndex,
          event.target.checked
        );
      }}
      color="primary" className={classes.checkboxIcon} />);
  }
  return (
    <div className={classes.checklistQuestion}>
      <PanoramaFishEyeIcon className={classes.questionIcon} />
    </div>
  );
}
Example #3
Source File: StringFacet.tsx    From cognitive-search-static-web-apps-sample-ui with MIT License 6 votes vote down vote up
render(): JSX.Element {
        const state = this.props.state;
        return (<FacetValuesList component="div" disablePadding>

            <FacetValueListItem key={state.fieldName} dense disableGutters>
                <Checkbox edge="start" disableRipple
                    disabled={this.props.inProgress}
                    checked={state.allSelected}
                    onChange={(evt) => state.allSelected = evt.target.checked}
                />
                <ListItemText primary="[ALL]" />
            </FacetValueListItem>

            {state.values.map(facetValue => {
                return (

                    <FacetValueListItem key={facetValue.value} dense disableGutters>
                        <Checkbox edge="start" disableRipple
                            disabled={this.props.inProgress}
                            checked={facetValue.isSelected}
                            onChange={(evt) => facetValue.isSelected = evt.target.checked}
                        />
                        <ListItemText primary={`${facetValue.value} (${facetValue.count})`} />
                    </FacetValueListItem>

                );
            })}

        </FacetValuesList>);
    }
Example #4
Source File: index.tsx    From aqualink-app with MIT License 6 votes vote down vote up
Agreements = ({
  agreementsChecked,
  handleChange,
  classes,
}: AgreementsProps) => {
  return (
    <div className={classes.agreements}>
      <Typography variant="h5">Agree to:</Typography>
      <FormGroup>
        {agreements.map(({ id, label }) => (
          <FormControlLabel
            key={label}
            className={classes.formControlLabel}
            control={
              <Checkbox
                color="primary"
                checked={agreementsChecked[id]}
                onChange={() => handleChange(id)}
              />
            }
            label={label}
          />
        ))}
      </FormGroup>
    </div>
  );
}
Example #5
Source File: CheckBox.tsx    From back-home-safe with GNU General Public License v3.0 6 votes vote down vote up
StyledCheckbox = styled(Checkbox)`
  display: inline-block;
  vertical-align: top;
  margin: 0 8px !important;
  padding: 0 !important;

  &.MuiCheckbox-colorPrimary {
    color: #fff !important;
  }
`
Example #6
Source File: AdminMenuBar.tsx    From project-tauntaun with GNU Lesser General Public License v3.0 6 votes vote down vote up
export function AdminMenuBar() {
  const { commanderMode, setCommanderMode, setShowLoadMissionForm, setShowSaveAsMissionForm } =
    AppStateContainer.useContainer();
  const { showAllGroups, setShowAllGroups } = MapStateContainer.useContainer();

  const saveOnClick = () => {
    console.log('Saving mission.');
    gameService.sendSaveMission();
  };

  const loadOnClick = () => {
    setShowLoadMissionForm(true);
  };

  const onShowAllGroupsChange = (event: any) => setShowAllGroups(event.target.checked);
  const onCommanderModeChange = (event: any) => setCommanderMode(event.target.checked);

  return (
    <React.Fragment>
      <button onClick={loadOnClick}>Load</button>
      <button onClick={saveOnClick}>Save</button>
      <button onClick={() => setShowSaveAsMissionForm(true)}>Save as</button>
      <FormControlLabel
        value="start"
        control={<Checkbox checked={showAllGroups} color="primary" onChange={onShowAllGroupsChange} />}
        label="Show all groups"
        labelPlacement="end"
      />
      <FormControlLabel
        value="start"
        control={<Checkbox checked={commanderMode} color="secondary" onChange={onCommanderModeChange} />}
        label="Commander Mode"
        labelPlacement="end"
      />
    </React.Fragment>
  );
}
Example #7
Source File: MapLegend.tsx    From metro-fare with MIT License 6 votes vote down vote up
LegendLabel = ({
  line,
  title,
  status,
  onChange,
}: {
  line: string;
  title: string;
  status: boolean;
  onChange: any;
}) => {
  return (
    <div className="legend-key-value">
      <Checkbox
        checked={status}
        onChange={onChange}
        name={`key ${line}`}
        color="primary"
      />
      <div className={`key ${line}`}>
        <div className="line"></div>
        <div className="circle"></div>
      </div>
      <div>{title}</div>
    </div>
  );
}
Example #8
Source File: SQFormInclusionListItem.tsx    From SQForm with MIT License 6 votes vote down vote up
function SQFormInclusionListItem({
  isChecked = false,
  isDisabled = false,
  label,
  name,
  onChange,
  size = 'auto',
}: SQFormInclusionListItemProps): JSX.Element {
  const {
    fieldHelpers: {handleChange},
  } = useForm({
    name,
    onChange,
  });

  return (
    <Grid item sm={size}>
      <FormControlLabel
        control={
          <Checkbox
            checked={isChecked}
            color="primary"
            disabled={isDisabled}
            name={name}
            onChange={handleChange}
          />
        }
        label={label}
      />
    </Grid>
  );
}
Example #9
Source File: AlertAcceptForm.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
AlertAcceptForm = forwardRef<
  HTMLFormElement,
  AlertAcceptFormProps
>(({ onSubmit, disableSubmit }, ref) => {
  const [checked, setChecked] = useState(false);

  const onFormSubmit: FormEventHandler = e => {
    e.preventDefault();
    onSubmit(null);
  };

  const onChecked = (_: ChangeEvent<HTMLInputElement>, isChecked: boolean) => {
    setChecked(isChecked);
    disableSubmit(!isChecked);
  };

  return (
    <form ref={ref} onSubmit={onFormSubmit}>
      <FormControl component="fieldset" fullWidth>
        <FormControlLabel
          label="My team can commit to making this change soon, or has already."
          value={checked}
          control={
            <Checkbox color="primary" checked={checked} onChange={onChecked} />
          }
        />
      </FormControl>
    </form>
  );
})
Example #10
Source File: TableHead.tsx    From frontegg-react with MIT License 5 votes vote down vote up
TableHead: FC<FeTableTHeadProps<any>> = <T extends object>(props: FeTableTHeadProps<T>) => {
  const {
    headerGroups,
    onSortChange,
    onFilterChange,
    toggleAllRowsSelected,
    selectedFlatRows,
    isAllRowsSelected,
  } = props;
  const classes = useStyles();

  return (
    <MaterialTableHead className={classes.head}>
      {headerGroups.map((headerGroup) => (
        <TableRow {...headerGroup.getHeaderGroupProps()}>
          {headerGroup.headers.map((c, index) => {
            const column = c as FeTableColumnProps<T>;
            if (column.id === 'fe-selection') {
              return (
                <TableCell {...column.getHeaderProps()}>
                  <Checkbox
                    className={classes.checkBox}
                    indeterminate={!isAllRowsSelected && (selectedFlatRows ?? []).length > 0}
                    checked={isAllRowsSelected}
                    onChange={() => toggleAllRowsSelected?.(!isAllRowsSelected)}
                  />
                </TableCell>
              );
            }
            const withExpander = headerGroup.headers[0].id === 'fe-expander';
            const tableCellProps = column.getHeaderProps(
              column.getSortByToggleProps((p: Partial<TableSortByToggleProps>) => ({
                ...p,
                onClick: column.canSort ? () => onSortChange?.(column) : undefined,
              }))
            );
            const minWidth = headerGroup.headers[0].minWidth || 0;
            const ownWidth = column.width || 0;
            const width = index === 1 && withExpander ? { width: Number(ownWidth) + minWidth, paddingLeft: 32 } : {};
            const cellStyle = { ...tableCellProps?.style, ...width };
            tableCellProps.className = classNames(tableCellProps.className, {
              [classes.firstHeadCell]: index === 0,
              [classes.expander]: index === 0 && withExpander,
            });
            return (
              <TableCell padding='default' {...tableCellProps} style={cellStyle}>
                <Box display='flex' alignItems='center' justifyContent='space-between' flexWrap='nowrap'>
                  <Box display='flex' flexGrow='1'>
                    {column.canSort ? (
                      <TableSortLabel
                        className='fe-sortLabel'
                        active={column.isSorted}
                        direction={column.isSortedDesc ? 'desc' : 'asc'}
                      >
                        {column.render('Header')}
                      </TableSortLabel>
                    ) : (
                      <>{column.render('Header')}</>
                    )}
                  </Box>
                  {column.canFilter && <TableFilterColumn column={column} onFilterChange={onFilterChange} />}
                </Box>
              </TableCell>
            );
          })}
        </TableRow>
      ))}
    </MaterialTableHead>
  );
}
Example #11
Source File: WarningDialog.tsx    From homebase-app with MIT License 5 votes vote down vote up
WarningDialog: React.FC<{
  open: boolean;
  handleClose: () => void;
}> = ({open, handleClose}) => {
  const [checked, setChecked] = useState(false);

  return (
    <CustomDialog open={open} onClose={handleClose} title={"DISCLAIMER"}>
      <TableHeader container direction="row" alignItems="center">
        <Grid item xs={12}>
          <Typography variant="h4" color="textSecondary">
            Homebase is currently experimental and its underlying smart
            contracts remain in testing.
            <br/>
            <br/>
            Expect breaking changes in coming releases. For more on
            Homebase, read {" "}
            <Link
              href="https://github.com/dOrgTech/homebase-app"
              rel="noreferrer noopener"
              target="_blank"
              color="secondary"
            >here</Link>
          </Typography>
        </Grid>
      </TableHeader>
      <Footer>
        <FormControlLabel
          color="secondary"
          control={
            <Checkbox
              checked={checked}
              onChange={(event) => setChecked(event.target.checked)}
              name="checkedA"
            />
          }
          label="I understand"
        />
      </Footer>
      <SendButton disabled={!checked} onClick={handleClose}>
        CONFIRM
      </SendButton>
    </CustomDialog>
  );
}
Example #12
Source File: EntityTagPicker.tsx    From backstage with Apache License 2.0 5 votes vote down vote up
EntityTagPicker = () => {
  const classes = useStyles();
  const {
    updateFilters,
    filters,
    queryParameters: { tags: tagsParameter },
  } = useEntityList();

  const catalogApi = useApi(catalogApiRef);
  const { value: availableTags } = useAsync(async () => {
    const facet = 'metadata.tags';
    const { facets } = await catalogApi.getEntityFacets({
      facets: [facet],
      filter: filters.kind?.getCatalogFilters(),
    });

    return facets[facet].map(({ value }) => value);
  }, [filters.kind]);

  const queryParamTags = useMemo(
    () => [tagsParameter].flat().filter(Boolean) as string[],
    [tagsParameter],
  );

  const [selectedTags, setSelectedTags] = useState(
    queryParamTags.length ? queryParamTags : filters.tags?.values ?? [],
  );

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

  useEffect(() => {
    updateFilters({
      tags: selectedTags.length ? new EntityTagFilter(selectedTags) : undefined,
    });
  }, [selectedTags, updateFilters]);

  if (!availableTags?.length) return null;

  return (
    <Box pb={1} pt={1}>
      <Typography variant="button" component="label">
        Tags
        <Autocomplete
          multiple
          options={availableTags}
          value={selectedTags}
          onChange={(_: object, value: string[]) => setSelectedTags(value)}
          renderOption={(option, { selected }) => (
            <FormControlLabel
              control={
                <Checkbox
                  icon={icon}
                  checkedIcon={checkedIcon}
                  checked={selected}
                />
              }
              label={option}
            />
          )}
          size="small"
          popupIcon={<ExpandMoreIcon data-testid="tag-picker-expand" />}
          renderInput={params => (
            <TextField
              {...params}
              className={classes.input}
              variant="outlined"
            />
          )}
        />
      </Typography>
    </Box>
  );
}
Example #13
Source File: Pager.tsx    From glific-frontend with GNU Affero General Public License v3.0 5 votes vote down vote up
createRows = (
  data: any,
  columnStyles: any,
  showCheckbox?: boolean,
  collapseRow?: string,
  collapseOpen: boolean = false
) => {
  const createRow = (entry: any) => {
    let stylesIndex = -1;
    return Object.keys(entry).map((item: any) => {
      // let's not display recordId in the UI
      if (item === 'recordId' || item === 'translations' || item === 'id') {
        return null;
      }
      // maintain columnStyles index
      stylesIndex += 1;

      return (
        <TableCell
          key={item + entry.recordId}
          className={`${styles.TableCell} ${columnStyles ? columnStyles[stylesIndex] : null}`}
        >
          <div>{entry[item]}</div>
        </TableCell>
      );
    });
  };

  return data.map((entry: any) => {
    let batchAction = null;
    if (showCheckbox) {
      batchAction = <Checkbox />;
    }

    let dataObj: any;
    if (entry.translations) dataObj = JSON.parse(entry.translations);
    return (
      <React.Fragment key={entry.recordId}>
        <TableRow key={entry.recordId} className={styles.TableRow}>
          {batchAction}
          {createRow(entry)}
        </TableRow>
        {collapseOpen && dataObj && entry.id === collapseRow
          ? collapsedRowData(dataObj, columnStyles, entry.recordId)
          : null}
      </React.Fragment>
    );
  });
}
Example #14
Source File: TemplateTypePicker.tsx    From backstage with Apache License 2.0 5 votes vote down vote up
TemplateTypePicker = () => {
  const alertApi = useApi(alertApiRef);
  const { error, loading, availableTypes, selectedTypes, setSelectedTypes } =
    useEntityTypeFilter();

  if (loading) return <Progress />;

  if (!availableTypes) return null;

  if (error) {
    alertApi.post({
      message: `Failed to load entity types`,
      severity: 'error',
    });
    return null;
  }

  return (
    <Box pb={1} pt={1}>
      <Typography variant="button">Categories</Typography>
      <Autocomplete
        multiple
        aria-label="Categories"
        options={availableTypes}
        value={selectedTypes}
        onChange={(_: object, value: string[]) => setSelectedTypes(value)}
        renderOption={(option, { selected }) => (
          <FormControlLabel
            control={
              <Checkbox
                icon={icon}
                checkedIcon={checkedIcon}
                checked={selected}
              />
            }
            label={capitalize(option)}
          />
        )}
        size="small"
        popupIcon={<ExpandMoreIcon data-testid="categories-picker-expand" />}
        renderInput={params => <TextField {...params} variant="outlined" />}
      />
    </Box>
  );
}
Example #15
Source File: PerfMonitorView.tsx    From react-native-performance with MIT License 5 votes vote down vote up
TimeLimitControl = ({
  timeLimitEnabled,
  toggleTimeLimit,
  setTimeLimit,
  timeLimit,
}: {
  timeLimitEnabled: boolean;
  timeLimit: number | null;
  setTimeLimit: (limit: number | null) => void;
  toggleTimeLimit: (checked: boolean) => void;
}) => (
  <div
    style={{
      marginLeft: 10,
      display: "flex",
      flexDirection: "row",
      alignItems: "center",
    }}
  >
    <FormControlLabel
      control={
        <Checkbox
          inputProps={{
            "aria-label": "Time limit enabled",
          }}
          checked={timeLimitEnabled}
          onChange={(event: { target: { checked: boolean } }) => {
            toggleTimeLimit(event.target.checked);
          }}
        />
      }
      label="Enable time limit of "
    />
    <TextField
      inputProps={{
        "aria-label": "Time limit",
      }}
      type="number"
      onChange={({ target: { value } }) =>
        setTimeLimit(Math.floor(parseInt(value, 10)))
      }
      defaultValue={timeLimit}
    />
    <Typography>ms</Typography>
  </div>
)
Example #16
Source File: FirstTimeNotice.tsx    From clearflask with Apache License 2.0 5 votes vote down vote up
FirstTimeNotice = React.forwardRef((props: {
  id: string;
  title: string;
  description: string;
  confirmButtonTitle?: string;
  confirmButtonRed?: boolean;
}, ref: React.Ref<FirstTimeNoticeHandle>) => {
  const classes = useStyles();
  const dialogId = `notice-${props.id}`;
  const noticeStatus = useSelector<ReduxStateAdmin, string | undefined>(state => state.account.account.account?.attrs?.[dialogId], shallowEqual);
  const [dontShowAgain, setDontShowAgain] = useState(noticeStatus !== ConfirmedButShowAgain);
  const isHidden = noticeStatus === ConfirmedAndDontShowAgain;
  const isHiddenOnFirstRender = useRef(isHidden);
  const [dialogState, setDialogState] = useState<((confirmed: boolean, dontShowAgain: boolean) => void) | undefined>(undefined);
  useImperativeHandle(ref, () => ({
    invoke: isHidden ? () => Promise.resolve(true) : async () => {
      const dialogResult = await new Promise<{ confirmed: boolean, dontShowAgain: boolean }>(resolve =>
        setDialogState(() => (confirmed, dontShowAgain) =>
          resolve({ confirmed, dontShowAgain })));
      if (dialogResult.confirmed) {
        const newNoticeStatus = dialogResult.dontShowAgain ? ConfirmedAndDontShowAgain : ConfirmedButShowAgain;
        if (newNoticeStatus !== noticeStatus)
          // Update in the background
          ServerAdmin.get().dispatchAdmin().then(dispatcher => dispatcher.accountAttrsUpdateAdmin({
            accountAttrsUpdateAdmin: {
              attrs: { [dialogId]: newNoticeStatus },
            }
          }));
      }
      return dialogResult.confirmed;
    }
  }), [isHidden, noticeStatus]); // eslint-disable-line react-hooks/exhaustive-deps

  if (isHiddenOnFirstRender.current) return null;

  const dialogConfirm = (confirmed: boolean) => {
    dialogState?.(confirmed, dontShowAgain);
    setDialogState(undefined);
  };
  return (
    <Dialog
      open={!!dialogState}
      onClose={() => dialogConfirm(false)}
    >
      <DialogTitle>{props.title}</DialogTitle>
      <DialogContent>
        <DialogContentText>{props.description}</DialogContentText>
      </DialogContent>
      <DialogActions>
        <FormControlLabel
          label='Do not show this message again'
          className={classes.dontShowAgainCheckbox}
          control={(
            <Checkbox
              size='small'
              color='default'
              checked={dontShowAgain}
              onChange={e => setDontShowAgain(!dontShowAgain)}
            />
          )}
        />
        <Button onClick={() => dialogConfirm(false)}>Back</Button>
        <Button onClick={() => dialogConfirm(true)}
          color={props.confirmButtonRed ? undefined : 'primary'}
          className={classNames(props.confirmButtonRed && classes.dontShowAgainCheckboxRed)}
        >{props.confirmButtonTitle || 'Continue'}</Button>
      </DialogActions>
    </Dialog>
  );
})
Example #17
Source File: FacetFilter.tsx    From crossfeed with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
FacetFilter: React.FC<Props> = (props) => {
  const classes = useStyles();
  const { options, selected, onSelect, onDeselect } = props;

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement>,
    value: string
  ) => {
    e.persist();
    if (e.target.checked) {
      onSelect(value);
    } else {
      onDeselect(value);
    }
  };

  return (
    <>
      <FormGroup classes={{ root: classes.root }}>
        {/* <input className={classes.inp} placeholder="Filter" /> */}
        {options.map((opt) => (
          <FormControlLabel
            classes={{ label: classes.label, root: classes.formControl }}
            key={opt.value}
            control={
              <Checkbox
                checked={selected.includes(opt.value)}
                onChange={(e) => handleChange(e, opt.value)}
              />
            }
            label={
              <>
                <span>{opt.value}</span>
                <span className={classes.count}>{opt.count}</span>
              </>
            }
          />
        ))}
      </FormGroup>
    </>
  );
}
Example #18
Source File: PostEdit.tsx    From clearflask with Apache License 2.0 5 votes vote down vote up
PostSaveButton = (props: {
  children?: any;
  open?: boolean;
  showNotify?: boolean;
  isSubmitting?: boolean;
  onSave: (doNotify: boolean) => void;
  onCancel?: () => void;
}) => {
  const classes = useStyles();
  const [doNotify, setNotify] = useState<boolean>(!!props.showNotify);
  return (
    <>
      {props.children}
      <Collapse mountOnEnter in={!!props.open}>
        <div className={classes.saveButtonActions}>
          {props.showNotify && (
            <FormControlLabel
              disabled={props.isSubmitting}
              control={(
                <Checkbox
                  checked={doNotify}
                  onChange={(e, checked) => setNotify(!doNotify)}
                  color='default'
                  size='small'
                />
              )}
              label='Notify subscribers'
            />
          )}
          <div className={classes.grow} />
          {!!props.onCancel && (
            <Button
              disabled={props.isSubmitting}
              className={classes.saveButtonAction}
              onClick={() => props.onCancel?.()}
            >Cancel</Button>
          )}
          <SubmitButton
            variant='contained'
            disableElevation
            className={classes.saveButtonAction}
            isSubmitting={props.isSubmitting}
            color='primary'
            onClick={() => props.onSave(doNotify)}
          >Save</SubmitButton>
        </div>
      </Collapse>
    </>
  );
}
Example #19
Source File: Pager.tsx    From glific-frontend with GNU Affero General Public License v3.0 5 votes vote down vote up
tableHeadColumns = (
  columnNames: Array<any>,
  columnStyles: any,
  tableVals: any,
  handleTableChange: Function,
  showCheckbox?: boolean,
  listName?: string,
  removeSortBy?: Array<any>
) => {
  let batchAction = null;
  if (showCheckbox) {
    batchAction = <Checkbox />;
  }
  return (
    <TableRow className={styles.TableHeadRow}>
      {batchAction}
      {columnNames.map((name: string, i: number) => (
        <TableCell
          key={name}
          className={`${styles.TableCell} ${columnStyles ? columnStyles[i] : null}`}
        >
          {i !== columnNames.length - 1 && name !== '' && !removeSortBy?.includes(name) ? (
            <TableSortLabel
              active={setColumnToBackendTerms(listName, name) === tableVals.sortCol}
              direction={tableVals.sortDirection}
              onClick={() => {
                if (setColumnToBackendTerms(listName, name) !== tableVals.sortCol) {
                  handleTableChange('sortCol', name);
                } else {
                  handleTableChange('sortCol', name);
                  handleTableChange(
                    'sortDirection',
                    tableVals.sortDirection === 'asc' ? 'desc' : 'asc'
                  );
                }
              }}
            >
              {name}
            </TableSortLabel>
          ) : (
            name
          )}
        </TableCell>
      ))}
    </TableRow>
  );
}
Example #20
Source File: LabeledCheckbox.tsx    From UsTaxes with GNU Affero General Public License v3.0 5 votes vote down vote up
export function LabeledCheckbox<TFormValues>(
  props: LabeledCheckboxProps<TFormValues>
): ReactElement {
  const { label, name, useGrid = true, sizes = { xs: 12 } } = props
  const { control } = useFormContext<TFormValues>()

  return (
    <ConditionallyWrap
      condition={useGrid}
      wrapper={(children) => (
        <Grid item {...sizes}>
          {children}
        </Grid>
      )}
    >
      <Controller
        name={name}
        render={({ field: { value, onChange } }) => (
          <FormControl component="fieldset">
            <FormGroup>
              <FormControlLabel
                control={
                  <Checkbox
                    name={name}
                    checked={value as boolean}
                    onChange={(_, checked) => onChange(checked)}
                    color="primary"
                  />
                }
                label={label}
                value={value}
              />
            </FormGroup>
          </FormControl>
        )}
        control={control}
      />
    </ConditionallyWrap>
  )
}
Example #21
Source File: Tooling.tsx    From listo with MIT License 5 votes vote down vote up
ToolComponent = ({
  category,
  name,
  description,
  warning,
  response,
}: ToolComponentProps) => {
  const classes = useStyles();
  const { handleSelectTool } = useContext(AppContext);

  return (
    <ExpansionPanel square={true}>
      <ExpansionPanelSummary
        expandIcon={<ExpandMoreIcon color="secondary" />}
        aria-controls="panel1a-content"
        id="panel1a-header"
      >
        <Typography component="div" className={classes.column}>
          <Box className={classes.checklistSummary}>
            <FormControlLabel
              onClick={event => event.stopPropagation()}
              control={
                <Checkbox
                  checked={Boolean(response)}
                  color="primary"
                  onChange={event => {
                    handleSelectTool(name, category, event.target.checked);
                  }}
                />
              }
              label={name}
            />
          </Box>
          <Typography variant="caption" gutterBottom color="error">
            {warning}
          </Typography>
        </Typography>
      </ExpansionPanelSummary>
      <ExpansionPanelDetails>
        <ReactMarkdown source={description} />
      </ExpansionPanelDetails>
    </ExpansionPanel>
  );
}
Example #22
Source File: SQFormCheckboxGroupItem.tsx    From SQForm with MIT License 5 votes vote down vote up
function SQFormCheckboxGroupItem({
  groupName,
  label,
  value,
  onChange,
  isRowDisplay = false,
  isDisabled = false,
  inputProps = {},
}: SQFormCheckboxGroupItemProps): JSX.Element {
  const {
    formikField: {field},
    fieldHelpers: {handleChange},
  } = useForm<
    SQFormOption['value'][] | SQFormOption['value'],
    React.ChangeEvent<HTMLInputElement>
  >({name: groupName, onChange});

  const classes = useStyles();

  const isChecked = React.useMemo(() => {
    if (Array.isArray(field.value)) {
      return field.value.includes(value.toString());
    }

    return !!field.value;
  }, [value, field]);

  return (
    <FormControlLabel
      className={`
        ${classes.checkboxGroupItem}
        ${isRowDisplay ? classes.rowDisplay : ''}
      `}
      label={label}
      control={
        <Checkbox
          name={groupName}
          checked={isChecked}
          value={value}
          color="primary"
          disabled={isDisabled}
          onChange={handleChange}
          {...inputProps}
        />
      }
    />
  );
}
Example #23
Source File: Row.tsx    From postgres-nest-react-typescript-boilerplate with GNU General Public License v3.0 5 votes vote down vote up
Row: FC<{
  data: Todo;
  rowStyle?: RowStyle;
  onCompleteTodo: (
    event: React.ChangeEvent<HTMLInputElement>,
    checked: boolean,
    id: string
  ) => void;
  onDeleteTodo: (
    e: React.MouseEvent<HTMLButtonElement, MouseEvent>,
    id: string
  ) => void;
}> = ({ data, rowStyle = {}, onDeleteTodo, onCompleteTodo }) => {
  const { completed, content, createdOn } = data;
  const classes = useStyles({ completed });

  return (
    <TableRow
      style={rowStyle}
      hover
      tabIndex={-1}
      key={`${data.id}_${content}`}
    >
      <TableCell className={classes.contentTableCell}>
        <div className={classes.content}>{content}</div>
        <div className={classes.deleteButtonWrapper}>
          <DeleteButton onClick={(e) => onDeleteTodo(e, data.id)} />
        </div>
      </TableCell>
      <TableCell>{new Date(createdOn).toLocaleString('eu')}</TableCell>
      <TableCell style={{ textAlign: 'center' }}>
        <Checkbox
          checked={completed}
          onChange={(e, checked) => onCompleteTodo(e, checked, data.id)}
          id="completed"
        />
      </TableCell>
    </TableRow>
  );
}
Example #24
Source File: CreateRoom.tsx    From cards-against-formality-pwa with BSD 2-Clause "Simplified" License 5 votes vote down vote up
function DeckSelector({ decks, onChange }: { decks: any[], onChange: (decks: string[]) => void }) {
  const [deckOptions, setDeckOptions] = useState<{ name: string; _id: string, value?: boolean }[]>([]);
  const [isExpanded, setIsExpanded] = useState(false);
  const [isAllSelected, setIsAllSelected] = useState(false);
  const toggleSelectAll = useCallback(() => {
    setDeckOptions(prevDeck => {
      prevDeck.forEach(deck => deck.value = !isAllSelected);
      return [...prevDeck];
    });

    setIsAllSelected(!isAllSelected);
  }, [isAllSelected])

  useEffect(() => {
    if (decks) {
      setDeckOptions(decks.map(deck => {
        return { value: deck.name.includes('Base'), ...deck }
      }));
    }
  }, [decks]);

  useEffect(() => {
    onChange(deckOptions.filter(deck => deck.value).map(deck => deck._id));
  }, [deckOptions, onChange]);


  function _onChange(e: React.ChangeEvent<HTMLInputElement>) {
    setDeckOptions(prevDeck => {
      const deck = prevDeck.find(deck => deck._id === e.target.name);
      if (deck) {
        deck.value = e.target.checked;
      }
      return [...prevDeck];
    });
  }

  if (!decks?.length) {
    return null;
  }

  return <ExpansionPanel expanded={isExpanded} onChange={() => { setIsExpanded(prev => !prev) }}>
    <ExpansionPanelSummary
      expandIcon={<ExpandMoreIcon />}
      aria-controls="panel1bh-content"
      id="panel1bh-header"
    >
      <Typography>Available Decks!</Typography>
    </ExpansionPanelSummary>
    <ExpansionPanelDetails>
      <FormControl required component="fieldset" error={!deckOptions.some(deck => deck.value)}>
        <FormControlLabel
          control={<Checkbox checked={isAllSelected} onChange={toggleSelectAll} name="Select all" />}
          label="Select all"
        />
        <Divider />
        <FormLabel component="legend">Select which decks you would like to play with</FormLabel>
        <FormGroup className="deck-checkbox-group">
          {deckOptions.map(deck => {
            return <FormControlLabel
              key={deck._id}
              control={<Checkbox checked={deck.value} onChange={_onChange} name={deck._id} />}
              label={deck.name}
            />
          })}
        </FormGroup>
        <FormHelperText>You must select at least one</FormHelperText>
      </FormControl>
    </ExpansionPanelDetails>
  </ExpansionPanel>
}
Example #25
Source File: StringCollectionFacet.tsx    From cognitive-search-static-web-apps-sample-ui with MIT License 5 votes vote down vote up
render(): JSX.Element {
        const state = this.props.state;
        return (<FacetValuesList component="div" disablePadding>

            <FacetValueListItem key={state.fieldName} dense disableGutters>
                <Radio edge="start" disableRipple
                    disabled={this.props.inProgress}
                    checked={state.allSelected}
                    onChange={(evt) => state.allSelected = evt.target.checked}
                />
                <ListItemText primary="[ALL]" />
            </FacetValueListItem>

            <FacetValueListItem key={state.fieldName + "-or-and"} dense disableGutters>
                <Radio edge="start" disableRipple
                    disabled={this.props.inProgress || state.allSelected}
                    checked={!state.allSelected && !state.useAndOperator}
                    onChange={(evt) => state.useAndOperator = false}
                />
                <ListItemText primary="[ANY OF]" />

                <Radio edge="start" disableRipple
                    disabled={this.props.inProgress || state.allSelected}
                    checked={!state.allSelected && state.useAndOperator}
                    onChange={(evt) => state.useAndOperator = true}
                />
                <ListItemText primary="[ALL OF]" />
            </FacetValueListItem>

            {state.values.map(facetValue => {
                return (

                    <FacetValueListItem key={facetValue.value} dense disableGutters>
                        <Checkbox edge="start" disableRipple
                            disabled={this.props.inProgress}
                            checked={facetValue.isSelected}
                            onChange={(evt) => facetValue.isSelected = evt.target.checked}
                        />
                        <ListItemText primary={`${facetValue.value} (${facetValue.count})`} />
                    </FacetValueListItem>

                );
            })}

        </FacetValuesList>);
    }
Example #26
Source File: index.tsx    From Nishan with MIT License 5 votes vote down vote up
export default function FilterGroupItemValue(props: Props) {
  let child: any = null;
  const { filter_item_label, dispatch } = useContext(NotionFilterContext);

  const target_value = (props.filter.filter as any).value,
    value = target_value.value ?? "";

  switch (props.type) {
    case "select":
    case "multi_select":
      child = props.value && <TagsAutocomplete label={""} value={value} onChange={(e, value) => {
        dispatch({ type: "CHANGE_VALUE", filter: target_value, value })
      }} options={props.value as SelectOption[]} />
      break;
    case "date":
    case "last_edited_time":
    case "created_time":
      child = props.value && <BasicSelect label={""} value={value} onChange={(e) => {
        dispatch({ type: "CHANGE_VALUE", filter: target_value, value: e.target.value })
      }} items={props.value as { value: string, label: string }[]} />
      break;
  }

  switch (props.value) {
    case "checkbox":
      child = <Checkbox
        checked={Boolean(value)}
        onChange={(e) => {
          dispatch({ type: "CHANGE_VALUE", filter: target_value, value: e.target.checked })
        }}
      />
      break;
    case "string":
      child = <TextField value={value} onChange={(e) => {
        dispatch({ type: "CHANGE_VALUE", filter: target_value, value: e.target.value })
      }} label={filter_item_label && "Value"} placeholder="Value" variant="outlined" />
      break;
    case "number":
      child = <TextField value={value} onChange={(e) => {
        dispatch({ type: "CHANGE_VALUE", filter: target_value, value: e.target.value })
      }} label={filter_item_label && "Value"} type="number" placeholder="Value" variant="outlined" />
      break;
  }

  return <div className="NotionFilter-Group-Item-Value NotionFilter-Group-Item-item">{child}</div>
}
Example #27
Source File: LoginScreen.tsx    From DamnVulnerableCryptoApp with MIT License 5 votes vote down vote up
LoginScreen = (props: IChallengeProps) => {

  const classes = useStyles();
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [failedLogin, setFailedLogin] = useState(false);
  const layoutContext = useContext(LayoutContext);

  let loginError;
  if (failedLogin)
    loginError = <Alert severity="error" >Failed to login</Alert>;


  const doLogin = (user: string, pass: string) => {
    layoutContext.setLoading(true);

    WeakHashingService.login(user, pass).then((res) => {
      if (res.flag) {
        props.setFlag(res.flag);
        setFailedLogin(false);
        window.scrollTo(0, 200);
      }
      else
        setFailedLogin(true);

      layoutContext.setLoading(false);
    }).catch(() => layoutContext.setLoading(false));
  };

  const onUsernameChange = (e: React.ChangeEvent<HTMLInputElement>) => setUsername(e.target.value);
  const onPasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => setPassword(e.target.value);
  const onLoginButtonPressed = () => doLogin(username, password);

  return (

    <Box className={classes.container} p={10} pt={5}>
      <Typography variant="h4" className={classes.title} gutterBottom>FakeAndInsecureWebsite</Typography>
      <Box pt={2}>
        <Container maxWidth="sm">

          <Card raised={true}>
            <Box p={5}>
              <Box textAlign="center"><PublicIcon className={classes.siteLogo} /></Box>
              <Grid container spacing={8} alignItems="flex-end">
                <Grid item md={true} sm={true} xs={true}>
                  <TextField id="username" label="Username" type="email" variant="filled" fullWidth required value={username} onChange={onUsernameChange} />
                </Grid>
              </Grid>
              <Grid container spacing={8} alignItems="flex-end">
                <Grid item md={true} sm={true} xs={true}>
                  <TextField id="username" label="Password" type="password" variant="filled" fullWidth required value={password} onChange={onPasswordChange} />
                </Grid>
              </Grid>
              <Grid container alignItems="center" justify="space-between">
                <Grid item>
                  <FormControlLabel control={
                    <Checkbox color="primary" />
                  } label="Remember me" />
                </Grid>
              </Grid>
              <Grid container justify="center" style={{ marginTop: '10px' }}>
                <Button className={classes.loginButton} fullWidth onClick={onLoginButtonPressed} variant="outlined" >Login</Button>
              </Grid>

              <Box mt={5}>{loginError}</Box>
            </Box>
          </Card>
        </Container >
      </Box>
    </Box>

  );
}
Example #28
Source File: QueryEntry.tsx    From SeeQR with MIT License 5 votes vote down vote up
CompareCheck = styled(Checkbox)`
  color: ${textColor};
`
Example #29
Source File: index.tsx    From vscode-crossnote with GNU Affero General Public License v3.0 4 votes vote down vote up
function OCRWidget(props: WidgetArgs) {
  const classes = useStyles(props);
  const { t } = useTranslation();
  const [canvas, setCanvas] = useState<HTMLCanvasElement>(null);
  // https://github.com/tesseract-ocr/tesseract/wiki/Data-Files#data-files-for-version-400-november-29-2016
  const [link, setLink] = useState<string>("");
  const [imageDataURL, setImageDataURL] = useState<string>("");
  const [ocrDataURL, setOCRDataURL] = useState<string>("");
  const [imageDropAreaElement, setImageDropAreaElement] = useState<
    HTMLInputElement
  >(null);
  const [isProcessing, setIsProcessing] = useState<boolean>(false);
  const [ocrProgresses, setOCRProgresses] = useState<OCRProgress[]>([]);
  const [selectedLanguages, setSelectedLanguages] = useState<string[]>(
    getInitialLanguages()
  );
  const [grayscaleChecked, setGrayscaleChecked] = useState<boolean>(true);

  useEffect(() => {
    if (canvas && imageDataURL) {
      const imageObject = new Image();
      const context = canvas.getContext("2d");
      imageObject.onload = function () {
        canvas.width = imageObject.width;
        canvas.height = imageObject.height;
        context.clearRect(0, 0, canvas.width, canvas.height);
        if (grayscaleChecked) {
          context.fillStyle = "#FFF";
          context.fillRect(0, 0, canvas.width, canvas.height);
          context.globalCompositeOperation = "luminosity";
        }
        context.drawImage(imageObject, 0, 0);
        setOCRDataURL(canvas.toDataURL());
      };
      imageObject.onerror = (error) => {
        throw error;
      };
      imageObject.setAttribute("crossOrigin", "anonymous");
      imageObject.src = imageDataURL;
    }
  }, [canvas, imageDataURL, grayscaleChecked]);

  function clickDropArea(e: any) {
    e.preventDefault();
    e.stopPropagation();
    if (!imageDropAreaElement || isProcessing) return;
    imageDropAreaElement.onchange = function (event) {
      const target = event.target as any;
      const files = target.files || [];
      if (files.length) {
        try {
          const file = files[0] as File;
          const reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = () => {
            setImageDataURL(reader.result as string);
          };
          reader.onerror = (error) => {
            throw error;
          };
        } catch (error) {}
      }
    };
    imageDropAreaElement.click();
  }

  function startOCRFromLink() {
    try {
      setImageDataURL(link);
    } catch (error) {}
  }

  function ocr(input: File | string | HTMLCanvasElement) {
    const worker = createWorker({
      logger: (m: OCRProgress) => {
        setOCRProgresses((ocrProgresses) => {
          if (
            ocrProgresses.length &&
            ocrProgresses[ocrProgresses.length - 1].status === m.status
          ) {
            return [...ocrProgresses.slice(0, ocrProgresses.length - 1), m];
          } else {
            return [...ocrProgresses, m];
          }
        });
      },
    });

    (async () => {
      setIsProcessing(true);
      let languagesArr = selectedLanguages;
      if (languagesArr.length === 0) {
        languagesArr = ["eng"];
      }

      await worker.load();
      await worker.loadLanguage(languagesArr.join("+"));
      await worker.initialize(languagesArr.join("+"));
      const {
        data: { text },
      } = await worker.recognize(input);
      props.replaceSelf("\n" + text);
      await worker.terminate();
      setIsProcessing(false);
    })();
  }

  function toggleLanguage(lang: string) {
    setSelectedLanguages((selectedLanguages) => {
      const offset = selectedLanguages.indexOf(lang);
      if (offset >= 0) {
        selectedLanguages.splice(offset, 1);
        selectedLanguages = [...selectedLanguages];
      } else {
        selectedLanguages = [...selectedLanguages, lang];
      }
      return selectedLanguages;
    });
  }

  if (props.isPreview) {
    return <span></span>;
  }

  if (isProcessing) {
    return (
      <Card elevation={2} className={clsx(classes.card)}>
        <Typography variant={"h5"}>{t("general/Processing")}</Typography>
        {/*<Typography variant={"body1"}>{t("general/please-wait")}</Typography>*/}
        <List>
          {ocrProgresses.length > 0 && (
            <ListItem>
              <ListItemText>
                {t(
                  "tesseract/" + ocrProgresses[ocrProgresses.length - 1].status
                )}
              </ListItemText>
              <ListItemSecondaryAction>
                {Math.floor(
                  ocrProgresses[ocrProgresses.length - 1].progress * 100
                ).toString() + "%"}
              </ListItemSecondaryAction>
            </ListItem>
          )}
        </List>
      </Card>
    );
  }

  if (imageDataURL) {
    return (
      <Card elevation={2} className={clsx(classes.card)}>
        <Box className={clsx(classes.section)}>
          <Typography variant={"subtitle1"} style={{ marginBottom: "8px" }}>
            {t("widget/crossnote.ocr/recognize-text-in-languages")}
          </Typography>
          <FormGroup>
            <FormControlLabel
              control={
                <Checkbox
                  checked={selectedLanguages.indexOf("eng") >= 0}
                  onChange={() => toggleLanguage("eng")}
                  value="eng"
                />
              }
              label="English"
            />
            <FormControlLabel
              control={
                <Checkbox
                  checked={selectedLanguages.indexOf("chi_sim") >= 0}
                  onChange={() => toggleLanguage("chi_sim")}
                  value="chi_sim"
                />
              }
              label="简体中文"
            />
            <FormControlLabel
              control={
                <Checkbox
                  checked={selectedLanguages.indexOf("chi_tra") >= 0}
                  onChange={() => toggleLanguage("chi_tra")}
                  value="chi_tra"
                />
              }
              label="繁體中文"
            />
            <FormControlLabel
              control={
                <Checkbox
                  checked={selectedLanguages.indexOf("jpn") >= 0}
                  onChange={() => toggleLanguage("jpn")}
                  value="jpn"
                />
              }
              label="日本語"
            />
          </FormGroup>
        </Box>
        <Box className={clsx(classes.section)}>
          <Typography variant={"subtitle1"} style={{ marginBottom: "8px" }}>
            {t("widget/crossnote.ocr/extra-settings")}
          </Typography>
          <FormControlLabel
            control={
              <Switch
                checked={grayscaleChecked}
                onChange={() => {
                  setGrayscaleChecked(!grayscaleChecked);
                }}
                color={"primary"}
              ></Switch>
            }
            label={t("widget/crossnote.ocr/grayscale")}
          ></FormControlLabel>
        </Box>
        <Box className={clsx(classes.canvasWrapper)}>
          <canvas
            className={clsx(classes.canvas)}
            ref={(element) => setCanvas(element)}
          ></canvas>
        </Box>
        <ButtonGroup>
          <Button
            onClick={() => {
              setImageDataURL("");
              setOCRDataURL("");
            }}
          >
            {t("general/go-back")}
          </Button>
          <Button
            color={"primary"}
            onClick={() => ocr(ocrDataURL)}
            disabled={!ocrDataURL}
          >
            {t("widget/crossnote.ocr/start-ocr")}
          </Button>
        </ButtonGroup>
      </Card>
    );
  }

  return (
    <Card elevation={2} className={clsx(classes.card)}>
      <Typography variant={"h5"}>{t("widget/crossnote.ocr/ocr")}</Typography>
      <Box className={clsx(classes.actionButtons)}>
        <Tooltip title={t("general/Delete")}>
          <IconButton onClick={() => props.removeSelf()}>
            <TrashCan></TrashCan>
          </IconButton>
        </Tooltip>
      </Box>
      <Box className={clsx(classes.section)}>
        <Typography variant={"subtitle1"} style={{ marginBottom: "8px" }}>
          {t("general/Link")}
        </Typography>
        <Input
          margin={"dense"}
          placeholder={t("widget/crossnote.image/image-url-placeholder")}
          value={link}
          onChange={(event) => {
            setLink(event.target.value);
          }}
          onKeyDown={(event) => {
            if (event.which === 13) {
              startOCRFromLink();
            }
          }}
          fullWidth={true}
        ></Input>
      </Box>
      <Typography
        variant={"subtitle1"}
        style={{ marginTop: "16px", textAlign: "center" }}
      >
        {t("widget/crossnote.auth/Or")}
      </Typography>
      <Box className={clsx(classes.section)}>
        <Typography variant={"subtitle1"} style={{ marginBottom: "8px" }}>
          {t("widget/crossnote.ocr/local-image")}
        </Typography>
        <Box
          className={clsx(
            classes.dropArea,
            isProcessing ? classes.disabled : null
          )}
          onClick={clickDropArea}
        >
          <Typography>
            {isProcessing
              ? t("utils/uploading-image")
              : t("widget/crossnote.image/click-here-to-browse-image-file")}
          </Typography>
        </Box>
      </Box>
      <input
        type="file"
        // multiple
        style={{ display: "none" }}
        ref={(element: HTMLInputElement) => {
          setImageDropAreaElement(element);
        }}
      ></input>
    </Card>
  );
}