@material-ui/core#FormControlLabel TypeScript Examples

The following examples show how to use @material-ui/core#FormControlLabel. 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: Settings.tsx    From firetable with Apache License 2.0 6 votes vote down vote up
Settings = ({ config, handleChange }) => {
  return (
    <>
      <FormControlLabel
        control={
          <Switch
            checked={config.isArray}
            onChange={() => handleChange("isArray")(!Boolean(config.isArray))}
            name="isArray"
          />
        }
        label="Set as an array"
      />
    </>
  );
}
Example #2
Source File: radio_input.tsx    From jupyter-extensions with Apache License 2.0 6 votes vote down vote up
/** Funtional Component for Radio input fields */
export function RadioInput(props: RadioInputProps) {
  const { options, ...groupProps } = props;
  return (
    <ThemeProvider theme={theme}>
      <RadioGroup {...groupProps}>
        {options &&
          options.map((o, i) => (
            <FormControlLabel
              key={i}
              value={o.value}
              control={<Radio />}
              label={o.text}
              className={css.primaryTextColor}
            />
          ))}
      </RadioGroup>
    </ThemeProvider>
  );
}
Example #3
Source File: Settings.tsx    From SpaceEye with MIT License 6 votes vote down vote up
SettingsSwitch: React.FC<SettingsSwitchProps> = props => {
    const { label, isChecked, onChange } = props
    return (
        <FormControl component="fieldset">
            <FormControlLabel
                control={
                    <Switch
                        checked={isChecked}
                        onChange={(_, checked) => onChange(checked)}
                        name={label}
                        color="primary"
                    />
                }
                label={label}
                labelPlacement="top"
            />
        </FormControl>
    )
}
Example #4
Source File: SQFormCheckbox.tsx    From SQForm with MIT License 6 votes vote down vote up
function SQFormCheckbox({
  isDisabled = false,
  label,
  name,
  onChange,
  size = 'auto',
  muiFieldProps = {},
}: SQFormCheckboxProps): JSX.Element {
  const {
    formikField: {field},
    fieldHelpers: {handleChange},
  } = useForm({name, onChange});

  return (
    <Grid item sm={size}>
      <FormControlLabel
        control={
          <Checkbox
            checked={!!field.value}
            color="primary"
            disabled={isDisabled}
            name={name}
            onChange={handleChange}
            {...muiFieldProps}
          />
        }
        label={label}
      />
    </Grid>
  );
}
Example #5
Source File: Input.tsx    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
InputSwitch: FunctionComponent<InputSwitchProps> = ({
  value = false,
  onChange,
  label = null,
  labelPlacement = 'start',
  debounce,
  ...others
}) => {
  const classes = useStyles();
  // Maintains the current state of the switch.
  // If the switch has gone a period without changing,
  // onChange will be called to propage the change to the local storage.
  const [currentValue, setCurrentValue] = useDebouncedState<boolean>(value, onChange, debounce);
  const onValueChange = useCallback(
    (_event, newValue) => setCurrentValue(newValue),
    [setCurrentValue]
  );

  const control = (
    <MaterialSwitch
      checked={currentValue}
      onChange={onValueChange}
      classes={{
        switchBase: classes.inputSwitchBase,
      }}
      {...others}
    />
  );

  return label ? (
    <FormControlLabel label={label} labelPlacement={labelPlacement} control={control} />
  ) : (
    control
  );
}
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: 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 #8
Source File: SwitchFilter.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
SwitchFilter = ({ label, value, onChange }: Props) => {
  const classes = useStyles();

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

  return (
    <Box pb={1} pt={1}>
      <FormControlLabel
        control={
          <Switch
            checked={value}
            onChange={handleChange}
            name={label}
            color="primary"
          />
        }
        label={label}
        className={classes.root}
      />
    </Box>
  );
}
Example #9
Source File: PostCreateForm.tsx    From clearflask with Apache License 2.0 6 votes vote down vote up
renderEditNotify(
    draft: Partial<Admin.IdeaDraftAdmin>,
    selectedCategory?: Client.Category,
    FormControlLabelProps?: Partial<React.ComponentProps<typeof FormControlLabel>>,
    SwitchProps?: Partial<React.ComponentProps<typeof Switch>>,
  ): React.ReactNode | null {
    if (!this.showModOptions()
      || !selectedCategory?.subscription) return null;
    return (
      <FormControlLabel
        disabled={this.state.isSubmitting}
        control={(
          <Switch
            checked={!!draft.notifySubscribers}
            onChange={(e, checked) => this.setState({
              draftFieldNotifySubscribers: !draft.notifySubscribers,
              draftFieldNotifyTitle: undefined,
              draftFieldNotifyBody: undefined,
            })}
            color='primary'
            {...SwitchProps}
          />
        )}
        label='Notify all subscribers'
        {...FormControlLabelProps}
      />
    );
  }
Example #10
Source File: Language.tsx    From back-home-safe with GNU General Public License v3.0 6 votes vote down vote up
Language = () => {
  const { t } = useTranslation("tutorial");
  const { language, setLanguage } = useI18n();

  return (
    <Wrapper>
      <h2>{t("language.name")}</h2>
      <StyledRadioGroup
        aria-label="language"
        name="language"
        value={language}
        onChange={(event) => {
          setLanguage(event.target.value as languageType);
        }}
      >
        <FormControlLabel
          value={languageType["ZH-HK"]}
          control={<Radio />}
          label="繁體中文"
        />
        <FormControlLabel
          value={languageType.EN}
          control={<Radio />}
          label="English"
        />
      </StyledRadioGroup>
    </Wrapper>
  );
}
Example #11
Source File: index.tsx    From frontegg-react with MIT License 6 votes vote down vote up
Checkbox = forwardRef<HTMLInputElement, CheckboxProps>((props, ref) => {
  const components = (
    <FormControlLabel control={<MaterialCheckbox inputRef={ref} {...mapper(props)} />} label={props.label} />
  );

  if (props.fullWidth) {
    return <div>{components}</div>;
  }
  return components;
})
Example #12
Source File: ResetTime.tsx    From multisig-react with MIT License 6 votes vote down vote up
Switch = ({ label, name }: { label: string; name: string }): ReactElement => (
  <FormControlLabel
    label={label}
    control={
      <Field
        name={name}
        type="checkbox"
        render={({ input: { checked, onChange, name, value } }) => (
          <StyledSwitch checked={checked} onChange={onChange} name={name} value={value} />
        )}
      />
    }
  />
)
Example #13
Source File: Settings.tsx    From swap-ui with Apache License 2.0 6 votes vote down vote up
function CloseNewAccountsSwitch() {
  const styles = useStyles();
  const { isClosingNewAccounts, setIsClosingNewAccounts } = useSwapContext();

  return (
    <FormGroup style={{ display: "none" }} row>
      <FormControlLabel
        classes={{ label: styles.closeAccountSwitchLabel }}
        labelPlacement="start"
        style={{
          display: "flex",
          justifyContent: "space-between",
          marginLeft: 0,
          width: "100%",
        }}
        control={
          <Switch
            checked={isClosingNewAccounts}
            onChange={() => setIsClosingNewAccounts(!isClosingNewAccounts)}
            color="primary"
          />
        }
        label="Close new accounts"
      />
    </FormGroup>
  );
}
Example #14
Source File: LabeledRadio.tsx    From UsTaxes with GNU Affero General Public License v3.0 6 votes vote down vote up
export function LabeledRadio<A>(props: LabeledRadioProps<A>): ReactElement {
  const { label, name, values, useGrid = true, sizes = { xs: 12 } } = props

  const classes = useStyles()
  const { control } = useFormContext<A>()

  return (
    <ConditionallyWrap
      condition={useGrid}
      wrapper={(children) => (
        <Grid item {...sizes}>
          {children}
        </Grid>
      )}
    >
      <Controller
        name={name}
        render={({ field: { value, onChange } }) => (
          <div className={classes.root}>
            <FormControl component="fieldset">
              <FormLabel>{label}</FormLabel>
              <RadioGroup name={name} value={value} onChange={onChange}>
                {values.map(([rowLabel, rowValue], i) => (
                  <FormControlLabel
                    key={i}
                    value={rowValue}
                    control={<Radio color="primary" />}
                    label={rowLabel}
                  />
                ))}
              </RadioGroup>
            </FormControl>
          </div>
        )}
        control={control}
      />
    </ConditionallyWrap>
  )
}
Example #15
Source File: SideDrawerField.tsx    From firetable with Apache License 2.0 5 votes vote down vote up
export default function Checkbox({
  column,
  control,
  disabled,
}: ISideDrawerFieldProps) {
  const classes = useStyles();
  const fieldClasses = useFieldStyles();
  const switchClasses = useSwitchStyles();

  return (
    <Controller
      control={control}
      name={column.key}
      render={({ onChange, onBlur, value }) => {
        const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
          onChange(event.target.checked);
        };

        return (
          <ButtonBase
            className={clsx(fieldClasses.root, classes.root)}
            disabled={disabled}
          >
            <FormControlLabel
              control={
                <Switch
                  checked={value}
                  onChange={handleChange}
                  onBlur={onBlur}
                  disabled={disabled}
                  classes={switchClasses}
                />
              }
              label={column.name}
              labelPlacement="start"
              classes={{ root: classes.formControlLabel, label: classes.label }}
            />
          </ButtonBase>
        );
      }}
    />
  );
}
Example #16
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 #17
Source File: checkbox_input.tsx    From jupyter-extensions with Apache License 2.0 5 votes vote down vote up
StyledLabel = withStyles({
  label: {
    ...INPUT_TEXT_STYLE,
    marginRight: '-8px',
    marginLeft: '-2px',
  },
})(FormControlLabel)
Example #18
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 #19
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 #20
Source File: OdiffConfigForm.tsx    From frontend with Apache License 2.0 5 votes vote down vote up
OdiffConfigForm: React.FunctionComponent = () => {
  const [config, updateConfig] = useConfigHook<OdiffConfig>();

  return (
    <React.Fragment>
      <FormControlLabel
        label="Output diff mask"
        control={
          <Switch
            checked={config.outputDiffMask}
            onChange={(event, checked) =>
              updateConfig("outputDiffMask", checked)
            }
            color="primary"
            name="strict"
          />
        }
      />
      <FormControlLabel
        label="Fail on layout diff"
        control={
          <Switch
            checked={config.failOnLayoutDiff}
            onChange={(event, checked) =>
              updateConfig("failOnLayoutDiff", checked)
            }
            color="primary"
            name="strict"
          />
        }
      />
      <FormControlLabel
        label="Ignore anti-alliasing"
        control={
          <Switch
            checked={config.antialiasing}
            onChange={(event, checked) => updateConfig("antialiasing", checked)}
            color="primary"
            name="antialiasing"
          />
        }
      />
      <TextValidator
        name="threshold"
        validators={["minNumber:0", "maxNumber:1"]}
        errorMessages={["Enter greater than 0", "Enter less than 1"]}
        InputProps={{ inputProps: { min: 0, max: 1, step: 0.001 } }}
        margin="dense"
        id="threshold"
        label="Pixel diff threshold"
        type="number"
        fullWidth
        required
        value={config.threshold}
        onChange={(event) => {
          const value = (event.target as HTMLInputElement).value;
          updateConfig("threshold", parseFloat(value));
        }}
      />
    </React.Fragment>
  );
}
Example #21
Source File: exposedPopulationAnalysis.tsx    From prism-frontend with MIT License 5 votes vote down vote up
AnalysisFormControlLabel = withStyles(() => ({
  label: {
    color: 'black',
  },
}))(FormControlLabel)
Example #22
Source File: SelectedKindsFilter.tsx    From backstage with Apache License 2.0 5 votes vote down vote up
SelectedKindsFilter = ({ value, onChange }: Props) => {
  const classes = useStyles();
  const alertApi = useApi(alertApiRef);
  const catalogApi = useApi(catalogApiRef);

  const { error, value: kinds } = useAsync(async () => {
    return await catalogApi
      .getEntityFacets({ facets: ['kind'] })
      .then(response => response.facets.kind?.map(f => f.value).sort() || []);
  });

  useEffect(() => {
    if (error) {
      alertApi.post({
        message: `Failed to load entity kinds`,
        severity: 'error',
      });
    }
  }, [error, alertApi]);

  const normalizedKinds = useMemo(
    () => (kinds ? kinds.map(k => k.toLocaleLowerCase('en-US')) : kinds),
    [kinds],
  );

  const handleChange = useCallback(
    (_: unknown, v: string[]) => {
      onChange(
        normalizedKinds && normalizedKinds.every(r => v.includes(r))
          ? undefined
          : v,
      );
    },
    [normalizedKinds, onChange],
  );

  const handleEmpty = useCallback(() => {
    onChange(value?.length ? value : undefined);
  }, [value, onChange]);

  if (!kinds?.length || !normalizedKinds?.length || error) {
    return <></>;
  }

  return (
    <Box pb={1} pt={1}>
      <Typography variant="button">Kinds</Typography>
      <Autocomplete
        className={classes.formControl}
        multiple
        limitTags={4}
        disableCloseOnSelect
        aria-label="Kinds"
        options={normalizedKinds}
        value={value ?? normalizedKinds}
        getOptionLabel={k => kinds[normalizedKinds.indexOf(k)] ?? k}
        onChange={handleChange}
        onBlur={handleEmpty}
        renderOption={(option, { selected }) => (
          <FormControlLabel
            control={
              <Checkbox
                icon={<CheckBoxOutlineBlankIcon fontSize="small" />}
                checkedIcon={<CheckBoxIcon fontSize="small" />}
                checked={selected}
              />
            }
            label={kinds[normalizedKinds.indexOf(option)] ?? option}
          />
        )}
        size="small"
        popupIcon={<ExpandMoreIcon data-testid="selected-kinds-expand" />}
        renderInput={params => <TextField {...params} variant="outlined" />}
      />
    </Box>
  );
}
Example #23
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 #24
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 #25
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 #26
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 #27
Source File: Checkbox.tsx    From glific-frontend with GNU Affero General Public License v3.0 5 votes vote down vote up
Checkbox: React.SFC<CheckboxProps> = (props) => {
  const {
    field,
    title,
    info = false,
    darkCheckbox,
    disabled = false,
    addLabelStyle = true,
    form,
    handleChange,
    infoType = 'tooltip',
    handleInfoClick = () => {},
  } = props;

  const handleChangeCallback = () => {
    const { name, value } = field;
    form.setFieldValue(name, !value);
    if (handleChange) handleChange(!value);
  };

  return (
    <div className={styles.Checkbox}>
      <FormControlLabel
        control={
          <CheckboxElement
            data-testid="checkboxLabel"
            classes={darkCheckbox ? { colorPrimary: styles.CheckboxColor } : null}
            {...field}
            color="primary"
            checked={field.value ? field.value : false}
            onChange={handleChangeCallback}
            disabled={disabled}
          />
        }
        labelPlacement="end"
        label={title}
        classes={{
          label: addLabelStyle ? styles.Label : styles.LabelNoStyle,
          root: styles.Root,
        }}
      />
      {info && infoType === 'tooltip' && (
        <Tooltip tooltipClass={styles.Tooltip} title={info.title} placement="right">
          <InfoIcon />
        </Tooltip>
      )}
      {info && infoType === 'dialog' && (
        <InfoIcon className={styles.InfoIcon} onClick={() => handleInfoClick()} />
      )}
    </div>
  );
}
Example #28
Source File: RiskCriteria.tsx    From listo with MIT License 5 votes vote down vote up
RiskCriteria = ({
  text,
  options,
  handleRiskOption,
  description,
}: Props) => {
  const classes = useStyles({});

  if (!options) {
    // TODO: this should be moved to pre-validation
    return null;
  }

  const selectedOption = options.find(o => o.selected);
  const value = selectedOption ? selectedOption.text : UNSELECTED_KEY;

  const ExpansionPanelDetails = withStyles(theme => ({
    root: {
      padding: theme.spacing(2),
      backgroundColor: '#f5f9fe',
    },
  }))(MuiExpansionPanelDetails);

  return (
    <React.Fragment>
      <Paper className={classes.root}>
        <Grid container spacing={2}>
          <Grid item xs={12}>
            <ExpansionPanel>
              <ExpansionPanelSummary
                expandIcon={<ExpandMoreIcon />}
                aria-controls="panel1a-content"
              >
                <Typography>{text}</Typography>
              </ExpansionPanelSummary>
              <ExpansionPanelDetails>
                <Typography>{description}</Typography>
              </ExpansionPanelDetails>
            </ExpansionPanel>
          </Grid>
          <Grid item xs={12}>
            <FormControl>
              <RadioGroup onChange={handleRiskOption} value={value}>
                {options.map(option => (
                  <FormControlLabel
                    key={option.text}
                    value={option.text}
                    control={<Radio />}
                    label={option.text}
                  />
                ))}
                <FormControlLabel
                  value={UNSELECTED_KEY}
                  control={<Radio />}
                  style={{ display: 'none' }}
                  label="Hidden"
                />
              </RadioGroup>
            </FormControl>
          </Grid>
        </Grid>
      </Paper>
    </React.Fragment>
  );
}
Example #29
Source File: ExamplesTab.tsx    From prompts-ai with MIT License 5 votes vote down vote up
// cleanExampleList

export default function ExamplesTab() {
    const dispatch = useDispatch();

    const showPreviousOutputs = useSelector(selectExamplePreviousOutputsStatus);
    const handlePreviousOutputsSwitchChange = (event: React.ChangeEvent<{}>, value: boolean) => {
        dispatch(updateExamplePreviousOutputsStatus(value));
    }

    const styles = useStyles();
    useEffect(() => {
        dispatch(cleanExampleList());
    })

    return (
        <Box>
            <Box mb={1}>
                <Card className={styles.instructionCard}>
                    <CardContent>
                        <Typography variant="subtitle1">Multiple Examples</Typography>
                        <Typography variant="body2">This is a tool to quickly run your prompt on multiple examples.
                            You can use it for text transformation and classification tasks. Use "{"{example}"}" key in the prompt and the editor
                            will replace it with each of the following examples. The tool is useful to understand how changing a prompt and parameters
                            will impact generated results.
                        </Typography>
                        <Box mt={1}>
                            <RunExamplesButton/>
                        </Box>
                        <Box mt={1}>
                            <Grid container spacing={1} alignItems="center">
                                <Grid item><FormControlLabel
                                    control={<Switch value={showPreviousOutputs}
                                                     onChange={handlePreviousOutputsSwitchChange}
                                                     name="previous-outputs-switch" color="primary"/>}
                                    label="Show previous outputs"
                                /></Grid>
                            </Grid>
                        </Box>
                    </CardContent>
                </Card>
            </Box>
            <ExampleCollection/>
        </Box>
    );
}