@material-ui/core#Checkbox JavaScript 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: form-util.js    From surveillance-forms with MIT License 7 votes vote down vote up
StatefulCheckbox = ({ field }) => {
  const { label, onChange } = field;

  const [value, setValue] = useState(field.value || false);

  const handleChange = () => {
    const newValue = !value;
    setValue(newValue);

    if (onChange) {
      onChange(newValue);
    }
  };

  return (
    <Box display="flex" alignItems="center">
      <Checkbox
        checked={value}
        onChange={handleChange}
        inputProps={{ "aria-label": "primary checkbox" }}
      />
      <div
        style={{ width: "maxContent", cursor: "pointer" }}
        onClick={handleChange}
      >
        <Typography>{label}</Typography>
      </div>
    </Box>
  );
}
Example #2
Source File: ODCheckbox.js    From course-manager with MIT License 6 votes vote down vote up
ODCheckbox = withStyles({
  root: {
    color: '#ffb347',
    '&$checked': {
      color: '#ffb347'
    }
  },
  checked: {}
})((props) => <Checkbox color="default" {...props} />)
Example #3
Source File: checkbox-options.js    From horondi_admin with MIT License 6 votes vote down vote up
CheckboxOptions = ({ options }) => {
  const mappedCheckboxes = options.map(
    ({ color, checked, label, value, handler, dataCy }) => (
      <FormControlLabel
        data-cy={dataCy}
        key={label}
        value={value}
        checked={checked}
        control={<Checkbox color={color} />}
        label={label}
        labelPlacement='end'
        onChange={handler}
      />
    )
  );
  return <>{mappedCheckboxes}</>;
}
Example #4
Source File: Filter.jsx    From covid-trials-dashboard with MIT License 6 votes vote down vote up
Filter = ({ name, options, selected, onSelect }) => {
  const [open, setOpen] = useState(false)
  const classes = useStyles()
  const handleClick = useCallback(() => setOpen(!open), [open])
  return (
    <>
      <ListItem button onClick={handleClick}>
        <ListItemText primary={name} />
        {open ? <ExpandLess /> : <ExpandMore />}
      </ListItem>
      <Collapse in={open} timeout={300} unmountOnExit>
        <List component='div' disablePadding>
          {options.map(opt => (
            <ListItem
              key={opt}
              button
              className={classes.nested}
              onClick={() => onSelect(opt)}
            >
              <ListItemIcon>
                <Checkbox
                  edge='start'
                  checked={selected.includes(opt)}
                  tabIndex={-1}
                />
              </ListItemIcon>
              <ListItemText primary={opt} />
            </ListItem>
          ))}
        </List>
      </Collapse>
    </>
  )
}
Example #5
Source File: AgentSettings.js    From voicemail-for-amazon-connect with Apache License 2.0 6 votes vote down vote up
FormControlCheckBox = ({label, checked, onChange, name, id, color = "primary"}) => {
    return (
        <FormControlLabel
            control={
                <Checkbox
                    name={name}
                    id={id}
                    onChange={onChange}
                    checked={checked}
                    color="primary"/>
            }
            label={label}/>
    )
}
Example #6
Source File: VoteButtons.js    From stack-underflow with MIT License 6 votes vote down vote up
DownvoteButton = ({ checked, handleDownvote }) => {
  const classes = useVoteBtnsStyles();

  return (
    <Checkbox
      checked={checked}
      icon={
        <SvgIcon className={classes.icon}>
          <DownvoteIcon />
        </SvgIcon>
      }
      checkedIcon={
        <SvgIcon className={classes.checkedIcon}>
          <DownvoteIcon />
        </SvgIcon>
      }
      onChange={handleDownvote}
    />
  );
}
Example #7
Source File: VoteButtons.js    From reddish with MIT License 6 votes vote down vote up
DownvoteButton = ({ user, body, handleDownvote, size }) => {
  return user ? (
    <Checkbox
      checked={body.downvotedBy.includes(user.id)}
      icon={<ArrowDownwardIcon style={{ color: '#b2b2b2' }} />}
      checkedIcon={<ArrowDownwardIcon style={{ color: '#9494FF' }} />}
      onChange={handleDownvote}
      size={size || 'small'}
    />
  ) : (
    <AuthFormModal type="downvote" />
  );
}
Example #8
Source File: AppTasks.js    From course-manager with MIT License 6 votes vote down vote up
function TaskItem({ task, checked, formik, ...other }) {
  const { getFieldProps } = formik;

  return (
    <Stack direction="row" justifyContent="space-between" sx={{ py: 0.75 }}>
      <FormControlLabel
        control={
          <Checkbox {...getFieldProps('checked')} value={task} checked={checked} {...other} />
        }
        label={
          <Typography
            variant="body2"
            sx={{
              ...(checked && {
                color: 'text.disabled',
                textDecoration: 'line-through'
              })
            }}
          >
            {task}
          </Typography>
        }
      />
    </Stack>
  );
}
Example #9
Source File: CalendarListView.js    From Doto with MIT License 6 votes vote down vote up
CalendarListView = props => {
    return (
        <div className="list-view">
            <div className="md:ml-3 md:mb-5 text-4xl font-bold">Tasks for Today</div>

            {props.tasks.filter(isToday).map(task => (
                <div key={task.taskId} className="list-view-components">
                    <Checkbox
                        checked={task.isComplete}
                        color="primary"
                        onChange={() => props.onTaskStatusUpdated(task.taskId)}
                    />
                    <div className={task.isComplete ? "isComplete" : ""}>
                        <Typography>{task.title}</Typography>
                        {!task.isComplete && (
                            <Typography color="primary">{moment(task.startDate).fromNow()}</Typography>
                        )}
                    </div>
                </div>
            ))}
        </div>
    );
}
Example #10
Source File: CardMembers.js    From TrelloClone with MIT License 6 votes vote down vote up
CardMembers = ({ card }) => {
  const classes = useStyles();
  const boardMembers = useSelector((state) => state.board.board.members);
  const members = card.members.map((member) => member.user);
  const dispatch = useDispatch();

  return (
    <div>
      <h3 className={classes.membersTitle}>Members</h3>
      <FormControl component='fieldset'>
        <FormGroup>
          {boardMembers.map((member) => (
            <FormControlLabel
              key={member.user}
              control={
                <Checkbox
                  checked={members.indexOf(member.user) !== -1}
                  onChange={async (e) =>
                    dispatch(
                      addCardMember({
                        add: e.target.checked,
                        cardId: card._id,
                        userId: e.target.name,
                      })
                    )
                  }
                  name={member.user}
                />
              }
              label={member.name}
            />
          ))}
        </FormGroup>
      </FormControl>
    </div>
  );
}
Example #11
Source File: CreateGameDialog.js    From dipact with GNU General Public License v3.0 6 votes vote down vote up
checkboxField(name, opts = {}) {
		return (
			<FormControlLabel
				control={
					<Checkbox
						checked={
							opts.invert
								? !this.state.newGameProperties[name]
								: this.state.newGameProperties[name]
						}
						onChange={this.newGamePropertyUpdater(name, opts)}
					/>
				}
				label={opts.label || name}
			/>
		);
	}
Example #12
Source File: general.js    From horondi_admin with MIT License 5 votes vote down vote up
General = ({ data, handleChange }) => {
  const classes = useStyles();
  const { status, isPaid, paymentMethod } = data;
  const { generalLabels } = labels;
  const { deliveryStatusLabel, isPaidLabel, paymentMethodLabel } =
    generalLabels;
  const { statusOptions, paymentOptions } = orders;

  const statusOptionElements = statusOptions.map(({ label, value }, index) => (
    <MenuItem key={label} value={value} disabled={index === 0}>
      {label}
    </MenuItem>
  ));

  const paymentOptionsElements = paymentOptions.map(
    ({ label, value }, index) => (
      <MenuItem key={label} value={value} disabled={index === 0}>
        {label}
      </MenuItem>
    )
  );

  return (
    <div className={classes.general}>
      <div>
        <label htmlFor={inputName.status}>{deliveryStatusLabel}</label>
        <Select
          fullWidth
          id={inputName.status}
          name={inputName.status}
          value={status}
          onChange={handleChange}
          variant={materialUiConstants.outlined}
          defaultValue={statusOptions[0].value}
        >
          {statusOptionElements}
        </Select>
      </div>
      <div>
        <label htmlFor={inputName.paymentMethod}>{paymentMethodLabel}</label>
        <Select
          fullWidth
          id={inputName.paymentMethod}
          name={inputName.paymentMethod}
          value={paymentMethod}
          onChange={handleChange}
          variant={materialUiConstants.outlined}
          defaultValue={paymentOptions[0].value}
        >
          {paymentOptionsElements}
        </Select>
      </div>
      <div className={classes.isPaid}>
        <label htmlFor={inputName.paymentMethod}>{isPaidLabel}</label>
        <Checkbox
          checked={isPaid}
          name={inputName.isPaidInput}
          onChange={handleChange}
        />
      </div>
    </div>
  );
}
Example #13
Source File: DeleteWalletConfirm.js    From akashlytics-deploy with GNU General Public License v3.0 5 votes vote down vote up
DeleteWalletConfirm = ({ isOpen, address, balance, handleCancel, handleConfirmDelete }) => {
  const classes = useStyles();
  const [isConfirmationChecked, setIsConfirmationChecked] = useState(false);
  const [deleteDeployments, setDeleteDeployments] = useState(false);

  return (
    <Dialog
      disableBackdropClick
      disableEscapeKeyDown
      maxWidth="sm"
      aria-labelledby="confirmation-dialog-title"
      open={isOpen}
      onExit={() => setIsConfirmationChecked(false)}
    >
      <DialogTitle id="confirmation-dialog-title">Delete Wallet</DialogTitle>
      <DialogContent dividers className={classes.dialogContent}>
        Are you sure you want to delete this wallet?
        <p>
          Address: <strong>{address}</strong>
          <br />
          {!!balance && (
            <>
              Balance: <strong>{uaktToAKT(balance)} AKT</strong>
            </>
          )}
        </p>
        <Alert severity="warning">
          This wallet will be completely removed from Akashlytics Deploy along with your local certificate and deployments data. If you want to keep access to
          this wallet, make sure you have a backup of the seed phrase or private key.
        </Alert>
        <br />
        <FormControlLabel
          control={<Checkbox checked={deleteDeployments} onChange={(ev, value) => setDeleteDeployments(value)} />}
          label="Delete local deployment data."
        />
        <FormControlLabel
          control={<Checkbox checked={isConfirmationChecked} onChange={(ev, value) => setIsConfirmationChecked(value)} />}
          label="I understand the wallet will be completely removed and I have all the backups I need."
        />
      </DialogContent>
      <DialogActions className={classes.dialogActions}>
        <Button autoFocus onClick={handleCancel} color="primary">
          Cancel
        </Button>
        <Button onClick={() => handleConfirmDelete(deleteDeployments)} disabled={!isConfirmationChecked} variant="contained" color="secondary">
          Delete Wallet
        </Button>
      </DialogActions>
    </Dialog>
  );
}
Example #14
Source File: search-checkboxes.jsx    From amadeus-airport-city-search-mern with MIT License 5 votes vote down vote up
SearchCheckboxes = (props) => {
  const { city, airport } = props.search

  // Handle change event on clicking checkboxes
  const onCheckboxChange = (e) => {
    e.persist();
    if (e.target.checked && (city || airport)) {
      props.setSearch(p => ({ ...p, [e.target.value]: e.target.checked }));
      return;
    }
    if (!e.target.checked && !(!city || !airport)) {
      props.setSearch(p => ({ ...p, [e.target.value]: e.target.checked }));
      return;
    }
  };


  return (
    <div>
      <FormControlLabel
        control={
          <Checkbox
            checked={city}
            onChange={onCheckboxChange}
            value={"city"}
          />
        }
        label="City"
      />
      <FormControlLabel
        control={
          <Checkbox
            checked={airport}
            onChange={onCheckboxChange}
            value={"airport"}
          />
        }
        label="Airport"
      />
    </div>
  )
}
Example #15
Source File: AuthFields.js    From neighborhood-chef-fe with MIT License 5 votes vote down vote up
AuthFields = (props) => {
  const buttonClass = buttonStyles();
  const dispatch = useDispatch();
  const [buttonDisable, setButtonDisable] = useState(true);

  const checkValues = (e) => {
    const email = document.querySelector("input[name='email']").value;
    const terms = document.querySelector("input[type='checkbox']").checked;
    if (
      /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(email) &&
      terms === true
    ) {
      setButtonDisable(false);
    } else {
      setButtonDisable(true);
    }
  };

  return (
    <>
      <Field
        style={{ marginTop: "10%" }}
        component={TextField}
        type="email"
        name="email"
        className="email"
        InputProps={{ onKeyUp: checkValues }}
        label="Email"
        required
      />
      <label style={{ marginTop: "10%" }} className="terms">
        <Field
          component={Checkbox}
          type="checkbox"
          name="terms"
          onChange={checkValues}
        />
        I accept the terms and conditions.
      </label>
      <Button
        style={{ marginTop: "10%" }}
        className={`${buttonClass.root} ${buttonClass.active}`}
        onClick={() => {
          dispatch(changePage(2));
        }}
        disabled={buttonDisable}
      >
        <Typography variant="h5">Continue registering</Typography>
      </Button>
    </>
  );
}
Example #16
Source File: products-filters-container.js    From horondi_client_fe with MIT License 5 votes vote down vote up
ProductsFiltersContainer = ({
  productFilter,
  list,
  categories,
  filterHandler,
  filterName
}) => {
  const styles = useStyles();
  const { i18n } = useTranslation();

  const checkCategory = (category) => {
    const categoryName = categories.filter(
      (element) => element.name[i18n.language === 'ua' ? 0 : 1].value === category
    );
    if (categoryName.length && productFilter.find((filter) => filter === categoryName[0]._id)) {
      return true;
    }
  };

  return (
    <Grid className={styles.container}>
      <li className={styles.mainItem}>
        <ListItemText button='true' primary={filterName} />
      </li>
      <List className={styles.nestedBox}>
        {list.map((listItem) => (
          <label key={listItem}>
            {' '}
            <ListItem
              selected={
                productFilter
                  ? productFilter.find((filter) => filter === listItem) || checkCategory(listItem)
                  : false
              }
              button
              className={styles.nested}
              key={listItem}
            >
              <Checkbox
                name={listItem}
                onChange={filterHandler}
                size='small'
                color='default'
                checked={checkCategory(listItem) || false}
              />
              <ListItemText primary={listItem} />
            </ListItem>{' '}
          </label>
        ))}
      </List>
    </Grid>
  );
}
Example #17
Source File: UserListHead.js    From course-manager with MIT License 5 votes vote down vote up
export default function UserListHead({
  order,
  orderBy,
  rowCount,
  headLabel,
  numSelected,
  onRequestSort,
  onSelectAllClick
}) {
  const createSortHandler = (property) => (event) => {
    onRequestSort(event, property);
  };

  return (
    <TableHead>
      <TableRow>
        <TableCell padding="checkbox">
          <Checkbox
            indeterminate={numSelected > 0 && numSelected < rowCount}
            checked={rowCount > 0 && numSelected === rowCount}
            onChange={onSelectAllClick}
          />
        </TableCell>
        {headLabel.map((headCell) => (
          <TableCell
            key={headCell.id}
            align={headCell.alignRight ? 'right' : 'left'}
            sortDirection={orderBy === headCell.id ? order : false}
          >
            <TableSortLabel
              hideSortIcon
              active={orderBy === headCell.id}
              direction={orderBy === headCell.id ? order : 'asc'}
              onClick={createSortHandler(headCell.id)}
            >
              {headCell.label}
              {orderBy === headCell.id ? (
                <Box sx={{ ...visuallyHidden }}>
                  {order === 'desc' ? 'sorted descending' : 'sorted ascending'}
                </Box>
              ) : null}
            </TableSortLabel>
          </TableCell>
        ))}
      </TableRow>
    </TableHead>
  );
}
Example #18
Source File: GlobalSettings.js    From voicemail-for-amazon-connect with Apache License 2.0 5 votes vote down vote up
render() {

        let classes = this.props.classes;

        let transcribe = this.state.transcribeEnabled;
        if (this.state.transcribeEnabled === null) {
            transcribe = this.props.transcribeVoicemail
        }

        let encrypt = this.state.encryptionEnabled;
        if (this.state.encryptionEnabled === null) {
            encrypt = this.props.encryptVoicemail
        }

        return (
            <div className={classes.root}>
                <h6 className={classes.title}>Global Configurations</h6>
                <div className={classes.checkBox}>
                    <FormControlLabel
                        control={
                            <Checkbox
                                name="transcribeEnabled"
                                id="transcribe"
                                disabled={this.props.loading || this.props.saving}
                                onChange={this.handleEventInputChange}
                                checked={transcribe}
                                color="primary"/>
                        }
                        label="Allow Voicemail Transcriptions"/>
                    <FormControlLabel
                        control={
                            <Checkbox
                                name="encryptionEnabled"
                                id="encrypt"
                                disabled={this.props.loading || this.props.saving}
                                onChange={this.handleEventInputChange}
                                checked={encrypt}
                                color="primary"/>
                        }
                        label="Enforce Voicemail Encryption"/>
                    <TextField
                        name="deliveryEmail"
                        disabled={this.props.loading || this.props.saving}
                        className={classes.deliveryEmail}
                        fullWidth={true}
                        placeholder={this.props.deliveryEmail}
                        onChange={this.handleEventInputChange}
                        value={this.state.deliveryEmail || this.props.deliveryEmail}
                        label={"Delivery Email"}
                    />
                    <p className={classes.infoCaption}>Important: Delivery Email must be verified via Amazon Simple
                        Email Service before emails can be delivered</p>
                </div>
                <Grid container spacing={5} direction="row">
                    <Grid item>
                        <Button color="secondary" onClick={() => {
                            this.props.showModal(false)
                        }}>Cancel</Button>
                    </Grid>
                    <Grid item>
                        <AsyncButton loading={this.props.saving} color="primary" variant="contained" disabled={this.props.userRole != "Administrator"} onClick={this.handleSave}>Save</AsyncButton>
                    </Grid>
                </Grid>
                <div className={classes.spacer}></div>
                <ContactFlow/>
            </div>
        )
    }
Example #19
Source File: checkBoxes.js    From horondi_admin with MIT License 5 votes vote down vote up
CheckBoxes = ({ options, handler }) => {
  const styles = useStyles();

  const updateCheckBoxCheck = (index) => (e) => {
    const newArr = [...options];
    newArr[index].checked = e.target.checked;
    handler(newArr);
  };

  const incrementQuantity = (index) => {
    const newArr = [...options];
    newArr[index].quantity += 1;
    handler(newArr);
  };

  const decrementQuantity = (index) => {
    const newArr = [...options];
    newArr[index].quantity -= 1;
    handler(newArr);
  };

  return (
    <Grid container spacing={5}>
      {options.map((checkbox, index) => (
        <Grid item xs={4} key={checkbox.name} className={styles.gridItem}>
          <div className={styles.item}>
            <Checkbox
              className={styles.checkbox}
              checked={checkbox.checked}
              name={checkbox.name}
              onChange={updateCheckBoxCheck(index)}
            />
            <label className={styles.label} htmlFor={checkbox.name}>
              {checkbox.name}
            </label>
          </div>
          {checkbox.checked && (
            <div className={styles.quantity}>
              <Button
                data-testid='decrement'
                onClick={() => decrementQuantity(index)}
                disabled={checkbox.quantity <= 1}
              >
                <RemoveIcon />
              </Button>
              <h5 className={styles.H5} data-testid='quantity'>
                {checkbox.quantity}
              </h5>
              <Button
                onClick={() => incrementQuantity(index)}
                data-testid='increment'
                disabled={checkbox.quantity >= 10}
              >
                <AddIcon />
              </Button>
            </div>
          )}
        </Grid>
      ))}
    </Grid>
  );
}
Example #20
Source File: ColorManyPicker.js    From course-manager with MIT License 5 votes vote down vote up
export default function ColorManyPicker({ colors, onChecked, sx, ...other }) {
  return (
    <Box sx={sx}>
      {colors.map((color) => {
        const isWhite = color === '#FFFFFF' || color === 'white';

        return (
          <Checkbox
            key={color}
            size="small"
            value={color}
            color="default"
            checked={onChecked(color)}
            icon={
              <IconColor
                sx={{
                  ...(isWhite && {
                    border: (theme) => `solid 1px ${theme.palette.divider}`
                  })
                }}
              />
            }
            checkedIcon={
              <IconColor
                sx={{
                  transform: 'scale(1.4)',
                  '&:before': {
                    opacity: 0.48,
                    width: '100%',
                    content: "''",
                    height: '100%',
                    borderRadius: '50%',
                    position: 'absolute',
                    boxShadow: '4px 4px 8px 0 currentColor'
                  },
                  '& svg': { width: 12, height: 12, color: 'common.white' },
                  ...(isWhite && {
                    border: (theme) => `solid 1px ${theme.palette.divider}`,
                    boxShadow: (theme) => `4px 4px 8px 0 ${theme.palette.grey[500_24]}`,
                    '& svg': { width: 12, height: 12, color: 'common.black' }
                  })
                }}
              />
            }
            sx={{
              color,
              '&:hover': { opacity: 0.72 }
            }}
            {...other}
          />
        );
      })}
    </Box>
  );
}
Example #21
Source File: index.js    From whaticket with MIT License 5 votes vote down vote up
TicketsQueueSelect = ({
	userQueues,
	selectedQueueIds = [],
	onChange,
}) => {
	const handleChange = e => {
		onChange(e.target.value);
	};

	return (
		<div style={{ width: 120, marginTop: -4 }}>
			<FormControl fullWidth margin="dense">
				<Select
					multiple
					displayEmpty
					variant="outlined"
					value={selectedQueueIds}
					onChange={handleChange}
					MenuProps={{
						anchorOrigin: {
							vertical: "bottom",
							horizontal: "left",
						},
						transformOrigin: {
							vertical: "top",
							horizontal: "left",
						},
						getContentAnchorEl: null,
					}}
					renderValue={() => i18n.t("ticketsQueueSelect.placeholder")}
				>
					{userQueues?.length > 0 &&
						userQueues.map(queue => (
							<MenuItem dense key={queue.id} value={queue.id}>
								<Checkbox
									style={{
										color: queue.color,
									}}
									size="small"
									color="primary"
									checked={selectedQueueIds.indexOf(queue.id) > -1}
								/>
								<ListItemText primary={queue.name} />
							</MenuItem>
						))}
				</Select>
			</FormControl>
		</div>
	);
}
Example #22
Source File: CheckboxFacet.js    From azure-search-react-template with MIT License 5 votes vote down vote up
export default function CheckboxFacet(props) {

    let [isExpanded, setIsExpanded] = useState(false);

    const checkboxes = props.values.map(facetValue => {

        let isSelected = props.selectedFacets.some(facet => facet.value === facetValue.value);
        
        return (
            <FacetValueListItem dense disableGutters id={facetValue.value}>
                <Checkbox 
                    edge="start" 
                    disableRipple 
                    checked={isSelected}
                    onClick= {
                        isSelected ? 
                        () => props.removeFilter({field: props.name, value: facetValue.value}) :
                        () => props.addFilter(props.name, facetValue.value)
                    }
                />
                <ListItemText primary={facetValue.value + " (" + facetValue.count + ")"}/>
            </FacetValueListItem>
        );
    });


    return (
        <div>
            <FacetListItem disableRipple={true} button onClick={() => setIsExpanded(!isExpanded)}>
                <ListItemText 
                    primary={props.mapFacetName(props.name)}
                />
                {isExpanded ? <ExpandLess /> : <ExpandMore />}
            </FacetListItem>
            <Collapse in={isExpanded} component="div">
                <FacetValuesList>
                    {checkboxes}
                </FacetValuesList>
            </Collapse>
        </div>
    );
}
Example #23
Source File: Filter.jsx    From Gameplayer with MIT License 5 votes vote down vote up
Filter = ({
  classes,
  onToggleWithName,
  onToggleWithImage,
  onOrderBy,
  withName,
  withImage,
  orderBy,
}) => (
  <Grid item>
    <Grid container direction="row">
      <FormControlLabel
        control={
          <Checkbox
            checked={withName}
            onChange={event => onToggleWithName && onToggleWithName()}
          />
        }
        label="With names"
      />
      <FormControlLabel
        control={
          <Checkbox
            checked={withImage}
            onChange={event => onToggleWithImage && onToggleWithImage()}
          />
        }
        label="With images"
      />
      <FormControlLabel
        control={
          <Select
            className={classes.orderBySelect}
            value={orderBy}
            onChange={event => onOrderBy && onOrderBy(event.target.value)}
          >
            <MenuItem value="id">ID</MenuItem>
            <MenuItem value="imageUrl">Image</MenuItem>
            <MenuItem value="displayName">Name</MenuItem>
            <MenuItem value="owner">Owner</MenuItem>
          </Select>
        }
        label="Order By:"
        labelPlacement="start"
      />
    </Grid>
  </Grid>
)
Example #24
Source File: colors-autocomplete.js    From horondi_admin with MIT License 5 votes vote down vote up
ColorsAutocomplete = ({
  colorsSet,
  selectedColors,
  handleChange,
  handleBlur,
  deleteHandler,
  name,
  id
}) => {
  const styles = useStyles();

  return (
    <Autocomplete
      className={styles.root}
      multiple
      id={id || 'tags-filled'}
      name={name}
      onBlur={handleBlur}
      options={colorsSet}
      value={selectedColors}
      disableCloseOnSelect
      getOptionLabel={(option) => option.name[0].value}
      renderTags={(value, getTagProps) =>
        value.map((option, index) => (
          <div key={option._id} className={styles.colorCircleInTextfield}>
            <ColorCircle
              color={option.colorHex}
              colorName={option.name[0].value}
              size={SMALL_CIRCLE}
              {...getTagProps({ index })}
            />
          </div>
        ))
      }
      getOptionSelected={(option, value) => option._id === value._id}
      renderOption={(option, { selected }) => (
        <div className={styles.selectOptionRow}>
          <div>
            <Checkbox
              icon={icon}
              checkedIcon={checkedIcon}
              className={styles.checkbox}
              checked={selected}
            />
            <ColorCircle color={option.colorHex} size={SMALL_CIRCLE} />
            {option.name[0].value}
          </div>
          {deleteHandler && (
            <CustomizedDeleteIcon
              size={SMALL_SIZE}
              onClickHandler={(e) => {
                e.stopPropagation();
                deleteHandler(option._id);
              }}
            />
          )}
        </div>
      )}
      renderInput={(params) => (
        <TextField
          {...params}
          variant='outlined'
          label={mainLabel}
          placeholder={mainLabel}
        />
      )}
      onChange={(e, value) => {
        handleChange(value);
      }}
    />
  );
}
Example #25
Source File: DailyQuest.jsx    From archeage-tools with The Unlicense 5 votes vote down vote up
render() {
    const { id, name, completed, hidden, rewards, region, rewardTypes, instance } = this.props;
    const { setQuestStatus, setQuestHide } = this.props;

    const typeItem = pathOr(null, ['id'])(rewardTypes.find(t => t.name === REWARD_ITEM));
    const typeXp = pathOr(null, ['id'])(rewardTypes.find(t => t.name === REWARD_XP));
    const typeCoin = pathOr(null, ['id'])(rewardTypes.find(t => t.name === REWARD_COINS));
    const typeProf = pathOr(null, ['id'])(rewardTypes.find(t => t.name === REWARD_PROFICIENCY));

    const itemRewards = rewards
      ? rewards.filter(r => r.typeId === typeItem && (r.region === region || !r.region) && !r.optional) : [];
    const currencyRewards = rewards
      ? rewards.filter(r => ![typeItem, typeXp, typeCoin, typeProf].includes(r.typeId) &&
        (r.region === region || !r.region))
      : [];

    const maxRewards = instance ? 3 : 2;

    return (
      <Paper className="quest">
        <Checkbox
          color="primary"
          checked={completed}
          onChange={(_, checked) => setQuestStatus(id, checked)}
        />
        <QuestTooltip questId={id} disabled={instance}>
          <Typography variant="body2">
            {name}
          </Typography>
        </QuestTooltip>
        <div className="rewards">
          {itemRewards.slice(0, maxRewards).map(item => (
            <Item
              id={item.refId}
              count={item.quantity}
              showCount
              inline
              key={`qr-${id}-${item.refId}`}
            />))}
          {currencyRewards.slice(0, 2).map(currency => (
            <Currency
              key={`qr-${id}-${currency.typeId}`}
              type={rewardTypes.find(r => r.id === currency.typeId).name}
              count={currency.quantity}
              inline
              tooltip
            />))}
          <Tooltip title={`${hidden ? 'Show' : 'Hide'} ${instance ? 'Instance' : 'Quest'}`}>
            <IconButton onClick={() => setQuestHide(id, !hidden)} size="small" color="inherit">
              {hidden
                ? <VisibilityIcon />
                : <VisibilityOffIcon />}
            </IconButton>
          </Tooltip>
        </div>
      </Paper>
    );
  }
Example #26
Source File: images-preview-container.spec.js    From horondi_admin with MIT License 5 votes vote down vote up
describe('Product-form tests', () => {
  let component;
  const imageHandler = jest.fn();

  beforeEach(() => {
    component = mount(
      <ImagesPreviewContainer
        src={mockSrc}
        labels={{}}
        imageHandler={imageHandler}
        multiple
      />
    );
  });

  afterEach(() => {
    component.unmount();
  });

  it('#1 Render the component', () => {
    expect(component).toBeDefined();
  });

  it('#2 Render component with empty src', () => {
    component = shallow(
      <ImagesPreviewContainer
        src={[]}
        labels={{}}
        imageHandler={imageHandler}
        multiple
      />
    );

    expect(component).toBeDefined();
  });

  it('#3 Should call handlers', () => {
    const formLabel = component.find(FormControlLabel);

    const deleteButton = formLabel.at(0).props();
    deleteButton.onClick();

    const checkbox = component.find(Checkbox);
    checkbox
      .at(0)
      .props()
      .onChange({
        target: {
          name: 1,
          checked: true
        }
      });

    checkbox.at(2).simulate('change');

    const primary = formLabel.at(1).props().control;
    primary.props.onChange();

    expect(imageHandler).toHaveBeenCalledTimes(2);
  });
});
Example #27
Source File: index.js    From yi-note with GNU General Public License v3.0 5 votes vote down vote up
BookmarkItem = ({ id, title, description, url, image, selected }) => {
  const { t } = useTranslation(['bookmark', 'options']);
  const history = useHistory();
  const { exporting } = useStoreState(state => state.bookmarks.toolbar);
  const {
    bookmarks: { setBookmark, removeBookmark },
    alerts: { show: showAlerts }
  } = useStoreActions(actions => actions);

  const setSelect = () => {
    setBookmark({ id, selected: !selected });
  };

  const handleOpenPageDetail = () => {
    if (exporting) {
      setSelect();
      return;
    }
    history.push(`/pages/${id}`);
  };

  const handleOpenPageInNewTab = e => {
    e.stopPropagation();
    window.open(url, '_blank');
  };

  const handleDelete = e => {
    e.stopPropagation();
    showAlerts({
      content: t('remove.alert'),
      onConfirm: removeBookmark.bind(null, id)
    });
  };

  return (
    <StyledContainer
      container
      direction="row"
      spacing={1}
      onClick={handleOpenPageDetail}
    >
      <Grid item md={2} sm={12}>
        <Grid container justify="center" alignItems="center">
          <StyledImgContainer src={image}>
            {image ? <img src={image} /> : <div>{t('options:appName')}</div>}
          </StyledImgContainer>
        </Grid>
      </Grid>
      <Grid item md={8} sm={12} container spacing={2} direction="column">
        <Grid item>
          <StyledTitle>{title}</StyledTitle>
        </Grid>
        <Grid item>
          <StyledDescription>{description}</StyledDescription>
        </Grid>
      </Grid>
      <Grid item md={2} sm={12}>
        {exporting ? (
          <Checkbox checked={!!selected} onChange={setSelect} />
        ) : (
          <>
            <Tooltip title={t('open.tooltip')}>
              <IconButton onClick={handleOpenPageInNewTab}>
                <OpenInNewIcon />
              </IconButton>
            </Tooltip>
            <Tooltip title={t('remove.tooltip')}>
              <IconButton onClick={handleDelete}>
                <DeleteIcon />
              </IconButton>
            </Tooltip>
          </>
        )}
      </Grid>
    </StyledContainer>
  );
}
Example #28
Source File: TransactionList.js    From A2 with GNU General Public License v3.0 5 votes vote down vote up
populateBills(bills) {
    const transaction = bills.map(bill => (
      <ExpansionPanel className={styles.bills}>
        <ExpansionPanelSummary>
          <div className={styles.billSummary}>
            <div className={styles.billTitle}>{bill.title}</div>
            <div className={styles.billAmount}>
              ${Number(bill.total).toFixed(2)}
            </div>
          </div>
        </ExpansionPanelSummary>
        <ExpansionPanelDetails className={styles.payments}>
          <div className={styles.paymentsTitle}>
            <div className={styles.paymentHeaders}>
              <Link
                to={{
                  pathname: "split",
                  bill
                }}
              >
                <EditIcon />
              </Link>
              <PaymentIcon />
            </div>
            <div className={styles.runningTotal}>
              <div className={`${styles.billTitle} ${styles.percentage}`}>
                (
                {Math.round(
                  (calculateTotalPaid(bill) / calculateTotalOutstanding(bill)) *
                    100
                )}
                %){" "}
              </div>
              <div className={styles.billTitle}>
                ${calculateTotalPaid(bill).toFixed(2)}/$
                {calculateTotalOutstanding(bill).toFixed(2)}
              </div>
            </div>
          </div>
          {bill.payments.map(payment => {
            const label = `${payment.from} owes ${payment.to} $${Number(
              payment.amount
            ).toFixed(2)}`;
            return (
              <div key={payment.id}>
                <FormControlLabel
                  aria-label="Acknowledge"
                  onClick={() =>
                    this.markPaid({
                      payment_id: payment.payment_id,
                      is_paid: !payment.is_paid
                    })
                  }
                  onFocus={event => event.stopPropagation()}
                  control={<Checkbox checked={payment.is_paid} />}
                  label={label}
                />
              </div>
            );
          })}
        </ExpansionPanelDetails>
      </ExpansionPanel>
    ));

    if (transaction.length === 0) {
      return (
        <div className={styles.noTransactions}>
          You have no outstanding transactions.
        </div>
      );
    }
    return transaction;
  }
Example #29
Source File: table-container-collapsable-row.js    From horondi_admin with MIT License 4 votes vote down vote up
TableContainerCollapsableRow = ({
  id,
  image,
  editHandler,
  showAvatar,
  showCollapse,
  showEdit,
  showDelete,
  showCheckbox,
  deleteHandler,
  setAnswerValue,
  answerValue,
  checkboxChangeHandler,
  onAnswer,
  shouldValidate,
  answer,
  question,
  collapsable = false,
  ...rest
}) => {
  const { SMALL_SIZE, DEFAULT_SIZE } = config.iconSizes;
  const classes = useStyles();
  const [open, setOpen] = useState(false);

  const dense = useSelector(({ Table }) => Table.dense);

  const properties = { ...rest };

  const tableCells = Object.keys(properties).map((property) => (
    <TableCell key={property} data-cy='table-cell'>
      <Typography className={classes.pageTruncateTableControl}>
        {properties[property]}
      </Typography>
    </TableCell>
  ));

  const handleSaveButtonAction = () => {
    onAnswer(id);
    setAnswerValue('');
  };

  const iconSize = dense ? SMALL_SIZE : DEFAULT_SIZE;
  const avatarSize = dense ? classes.small : classes.medium;
  return (
    <>
      <TableRow
        className={classes.tableRowCursor}
        key={id}
        onClick={() => setOpen(!open)}
        hover
      >
        {showCheckbox && (
          <TableCell>
            <Checkbox
              color='default'
              inputProps={{
                'aria-label': materialUiConstants.checkboxDefaultColor
              }}
              onClick={(e) => checkboxChangeHandler(e, id)}
            />
          </TableCell>
        )}
        {showAvatar && (
          <TableCell>
            <Avatar className={avatarSize} src={image}>
              <ImageIcon />
            </Avatar>
          </TableCell>
        )}
        {tableCells}
        {(showEdit || showDelete || showCollapse) && (
          <TableCell>
            {showEdit && (
              <CustomizedEditIcon
                size={iconSize}
                onClickHandler={editHandler}
                data-cy='edit-btn'
              />
            )}
            {showDelete && (
              <CustomizedDeleteIcon
                size={iconSize}
                onClickHandler={deleteHandler}
              />
            )}
            {showCollapse && (
              <IconButton onClick={() => setOpen(!open)}>
                {open ? (
                  <KeyboardArrowUpIcon fontSize={iconSize} />
                ) : (
                  <KeyboardArrowDownIcon fontSize={iconSize} />
                )}
              </IconButton>
            )}
          </TableCell>
        )}
      </TableRow>
      <TableRow className={classes.collapseRowCursor}>
        <TableCell className={classes.tableCell} colSpan={7}>
          <Collapse in={open} timeout='auto'>
            <Box margin={1}>
              <Typography variant='h5' gutterBottom display='inline'>
                {labels.emailQuestionsLabels.questionFrom +
                  properties.senderName}
                :
              </Typography>
              <Typography
                variant='caption'
                component='div'
                style={{ marginBottom: '10px' }}
              >{`${properties.email}`}</Typography>
              <Typography
                style={{ maxWidth: '100%' }}
                gutterBottom
                component='span'
                align='justify'
                variant='h6'
              >
                {question}
              </Typography>
              {answer && (
                <>
                  <Typography
                    style={{ margin: '20px 0 5px' }}
                    variant='h5'
                    gutterBottom
                    component='div'
                  >
                    {labels.emailQuestionsLabels.rowPlaceholder.answer}:
                  </Typography>
                  <Typography gutterBottom component='div'>
                    {answer}
                  </Typography>
                </>
              )}
              <Box
                display='flex'
                flexDirection='column'
                justifyContent='space-between'
              >
                {!answer && (
                  <TextField
                    id='filled-full-width'
                    className={classes.textField}
                    multiline
                    rows={6}
                    margin='normal'
                    placeholder={labels.emailQuestionsLabels.placeholder}
                    InputLabelProps={{ shrink: true }}
                    label={labels.emailQuestionsLabels.textFieldPlaceholder}
                    value={answerValue}
                    variant={formConstants.textFieldFilled}
                    error={!answerValue && shouldValidate}
                    onChange={(e) => setAnswerValue(e.target.value)}
                    helperText={handleHelperText(answerValue, shouldValidate)}
                  />
                )}
                {!answer && (
                  <Box>
                    <Button
                      variant='contained'
                      color='primary'
                      onClick={handleSaveButtonAction}
                    >
                      {labels.emailQuestionsLabels.answer}
                    </Button>
                  </Box>
                )}
              </Box>
            </Box>
          </Collapse>
        </TableCell>
      </TableRow>
    </>
  );
}