@material-ui/core#TextField TypeScript Examples

The following examples show how to use @material-ui/core#TextField. 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: register.tsx    From 0Auth with MIT License 7 votes vote down vote up
function Register({ submit }: UserProps) {
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [age, setAge] = useState('');
  const [address, setAddress] = useState('');
  const submitInfo = () => submit(name, phone, age, address);

  return (
    <div className="User">
      <h2>Register Info</h2>
      <form noValidate>
        <TextField required id="name" value={name} onChange={e => setName(e.target.value)} label="Name"/><br/>
        <TextField required id="phone" value={phone} onChange={e => setPhone(e.target.value)} label="Phone"/><br/>
        <TextField required id="age" value={age} onChange={e => setAge(e.target.value)} label="Age"/><br/>
        <TextField required id="address" value={address} onChange={e => setAddress(e.target.value)} label="Address"/><br/><br/>
        <Button variant="contained" color="primary" onClick={submitInfo}>
          Submit
        </Button>
      </form>
    </div>
  );
}
Example #2
Source File: SideDrawerField.tsx    From firetable with Apache License 2.0 7 votes vote down vote up
export default function Email({
  control,
  column,
  disabled,
}: ISideDrawerFieldProps) {
  return (
    <Controller
      control={control}
      name={column.key}
      render={({ onChange, onBlur, value }) => {
        return (
          <TextField
            variant="filled"
            fullWidth
            margin="none"
            placeholder={column.name}
            onChange={onChange}
            onBlur={onBlur}
            value={value}
            id={`sidedrawer-field-${column.key}`}
            label=""
            hiddenLabel
            disabled={disabled}
            inputProps={{
              autoComplete: "email",
              maxLength: column.config?.maxLength,
            }}
          />
        );
      }}
    />
  );
}
Example #3
Source File: SearchBox.tsx    From posso-uscire with GNU General Public License v3.0 7 votes vote down vote up
export default function SearchBox() {
  const [language] = useLanguage();
  const router = useRouter();
  return (
    <Box display="flex" justifyContent="center">
      <Autocomplete
        id="province"
        onChange={(_, value) => router.push("/" + (value as Province).urlName)}
        options={regions}
        getOptionLabel={(option) => option.nome}
        style={{ width: "80%", marginTop: 20 }}
        renderInput={(params) => (
          <TextField
            {...params}
            label={i18n.CITY[language]}
            variant="outlined"
          />
        )}
      />
    </Box>
  );
}
Example #4
Source File: CountrySelect.tsx    From storefront with MIT License 7 votes vote down vote up
CountrySelect = React.forwardRef<HTMLDivElement, CountrySelectProps>((props, ref) => (
  <TextField
    ref={ref}
    {...props}
    select
    SelectProps={{
      native: true,
    }}
  >
    {countries.map((country) => (
      <option key={country.code} value={country.code}>
        {country.label} {countryToFlag(country.code)}
      </option>
    ))}
  </TextField>
))
Example #5
Source File: with-subheader.tsx    From react-component-library with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
filter = (
    <TextField
        id="outlined-basic"
        label="filter"
        variant="outlined"
        fullWidth
        InputProps={{
            endAdornment: (
                <InputAdornment position="end">
                    <IconButton aria-label="filter button" edge={'end'}>
                        <Search />
                    </IconButton>
                </InputAdornment>
            ),
        }}
    />
)
Example #6
Source File: Forms.tsx    From signer with Apache License 2.0 7 votes vote down vote up
TextFieldWithFormState = observer(
  (props: TextFieldWithFormStateProps) => {
    const { fieldState, ...otherProps } = props;
    return (
      <TextField
        value={fieldState?.value}
        onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
          fieldState?.onChange(e.target.value);
        }}
        error={fieldState?.hasError}
        helperText={fieldState?.error}
        {...otherProps}
      />
    );
  }
)
Example #7
Source File: index.tsx    From vscode-crossnote with GNU Affero General Public License v3.0 6 votes vote down vote up
function GitHubGistWidget(props: WidgetArgs) {
  const classes = useStyles(props);
  const { t } = useTranslation();
  const [url, setURL] = useState<string>("");

  const setGistURL = useCallback(
    (url: string) => {
      try {
        const location = new URL(url);
        if (location.host !== "gist.github.com") {
          return;
        } else {
          props.setAttributes({
            url: location.origin + location.pathname,
          });
        }
      } catch (error) {}
    },
    [props]
  );

  if (props.attributes["url"]) {
    return (
      <Box className={"preview github-gist"} style={{ whiteSpace: "normal" }}>
        <Gist url={props.attributes["url"]}></Gist>
        {!props.isPreview && (
          <Box className={clsx(classes.actionButtonsGroup)}>
            <IconButton onClick={() => props.removeSelf()}>
              <TrashCanOutline></TrashCanOutline>
            </IconButton>
          </Box>
        )}
      </Box>
    );
  }

  if (props.isPreview) {
    return null;
  }

  return (
    <Card elevation={2} className={clsx(classes.card)}>
      <Typography variant={"h5"}>
        {t("widget/crossnote.github_gist/title")}
      </Typography>
      <TextField
        label={t("widget/crossnote/github_gist/enter-github-gist-url")}
        placeholder={"https://gist.github.com/..."}
        value={url}
        onChange={(event) => setURL(event.target.value)}
        fullWidth={true}
        onKeyUp={(event) => {
          if (event.which === 13) {
            setGistURL(url);
          }
        }}
      ></TextField>
      <Box className={clsx(classes.actionButtonsGroup)}>
        <Tooltip title={t("general/Delete")}>
          <IconButton onClick={() => props.removeSelf()}>
            <TrashCan></TrashCan>
          </IconButton>
        </Tooltip>
      </Box>
    </Card>
  );
}
Example #8
Source File: TextInput.tsx    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
function TextInputBase({ disableBorder, ...props }: TextInputProps) {
  return <TextField {...props} />;
}
Example #9
Source File: index.tsx    From firetable with Apache License 2.0 6 votes vote down vote up
export default function ConnectServiceSelect({
  value = [],
  className,
  TextFieldProps = {},
  ...props
}: IConnectServiceSelectProps) {
  const classes = useStyles();

  const sanitisedValue = Array.isArray(value) ? value : [];

  return (
    <TextField
      label=""
      hiddenLabel
      variant={"filled" as any}
      select
      value={sanitisedValue}
      className={clsx(classes.root, className)}
      {...TextFieldProps}
      SelectProps={{
        renderValue: (value) => `${(value as any[]).length} selected`,
        displayEmpty: true,
        classes: { root: classes.selectRoot },
        ...TextFieldProps.SelectProps,
        // Must have this set to prevent MUI transforming `value`
        // prop for this component to a comma-separated string
        MenuProps: {
          classes: { paper: classes.paper, list: classes.menuChild },
          MenuListProps: { disablePadding: true },
          getContentAnchorEl: null,
          anchorOrigin: { vertical: "bottom", horizontal: "center" },
          transformOrigin: { vertical: "top", horizontal: "center" },
          ...TextFieldProps.SelectProps?.MenuProps,
        },
      }}
    >
      <ErrorBoundary>
        <Suspense fallback={<Loading />}>
          <PopupContents value={sanitisedValue} {...props} />
        </Suspense>
      </ErrorBoundary>
    </TextField>
  );
}
Example #10
Source File: MetricAutocomplete.tsx    From abacus with GNU General Public License v2.0 6 votes vote down vote up
/**
 * An Autocomplete just for Metrics
 */
export default function MetricAutocomplete<
  Multiple extends boolean | undefined = undefined,
  DisableClearable extends boolean | undefined = undefined,
  FreeSolo extends boolean | undefined = undefined,
>(
  props: Omit<AutocompleteProps<Metric, Multiple, DisableClearable, FreeSolo>, 'renderInput'> & {
    error?: string | false
  },
): ReturnType<typeof Autocomplete> {
  const processedOptions = props.options
    .filter((a) => !a.name.startsWith('archived_'))
    .sort((a, b) => a.name.localeCompare(b.name, 'en'))
  return (
    <Autocomplete<Metric, Multiple, DisableClearable, FreeSolo>
      aria-label='Select a metric'
      fullWidth
      options={processedOptions}
      noOptionsText='No metrics found'
      getOptionLabel={(metric: Metric) => metric.name}
      getOptionSelected={(metricA: Metric, metricB: Metric) => metricA.metricId === metricB.metricId}
      renderOption={(option: Metric) => (
        <div>
          <Typography variant='body1'>
            <strong>{option.name}</strong>
          </Typography>
          <Typography variant='body1'>
            <small>{option.description}</small>
          </Typography>
        </div>
      )}
      renderInput={(params: AutocompleteRenderInputParams) => (
        <TextField
          {...params}
          placeholder='Select a metric'
          error={!!props.error}
          helperText={_.isString(props.error) ? props.error : undefined}
          required
          InputProps={{
            ...autocompleteInputProps(params, false),
          }}
          InputLabelProps={{
            shrink: true,
          }}
        />
      )}
      {..._.omit(props, ['options', 'error'])}
    />
  )
}
Example #11
Source File: ConfirmPasswordTextField.tsx    From firebase-react-typescript-project-template with MIT License 6 votes vote down vote up
ConfirmPasswordTextField = ({
  valid,
  onChangeValid,
  showPassword,
  primaryPassword,
  className,
}: Props) => {
  return (
    <TextField
      color="secondary"
      margin="normal"
      error={!valid}
      helperText={!valid && "Password does not match"}
      required
      label="Confirm password"
      autoComplete="password"
      name="confirmPassword"
      id="confirmPassword"
      type={showPassword ? "text" : "password"}
      variant="outlined"
      className={className}
      size="small"
      onChange={(e) => {
        onChangeValid(e.target.value === primaryPassword);
      }}
    />
  );
}
Example #12
Source File: PDF.tsx    From binaural-meet with GNU General Public License v3.0 6 votes vote down vote up
PDF: React.FC<ContentProps> = (props:ContentProps) => {
  assert(props.content.type === 'pdf')
  const memberRef = useRef<Member>(new Member())
  const member = memberRef.current
  member.newProps = props
  const refCanvas = useRef<HTMLCanvasElement>(null)
  const refTextDiv = useRef<HTMLDivElement>(null)
  const refAnnotationDiv = useRef<HTMLDivElement>(null)
  const editing = useObserver(() => props.stores.contents.editing === props.content.id)

  useEffect(()=>{
    member.canvas = refCanvas.current
    member.textDiv = refTextDiv.current
    member.annotationDiv = refAnnotationDiv.current
  // eslint-disable-next-line  react-hooks/exhaustive-deps
  }, [refCanvas.current])

  useEffect(()=>{
    member.updateProps()
  })

  return <div style={{overflow: 'hidden', pointerEvents: 'auto', userSelect: editing? 'text':'none'}}
    onDoubleClick = {(ev) => { if (!editing) {
      ev.stopPropagation()
      ev.preventDefault()
      props.stores.contents.setEditing(props.content.id)
    } }} >
    <canvas style={{ width:`${CANVAS_SCALE*100}%`, height:`${CANVAS_SCALE*100}%`,
      transformOrigin:'top left', transform:`scale(${1/CANVAS_SCALE})`}} ref={refCanvas} />
    <div ref={refTextDiv} style={{position:'absolute', left:0, top:0,
      width:`${CANVAS_SCALE*100}%`, height:`${CANVAS_SCALE*100}%`,
      transformOrigin:'top left', transform:`scale(${1/CANVAS_SCALE})`, lineHeight: 1,
      overflow:'hidden'}} />
    <div ref={refAnnotationDiv} />
    <div style={{position:'absolute', top:0, left:0, width:'100%', height:40}}
      onPointerEnter={()=>{member.showTop = true}} onPointerLeave={()=>{member.showTop = false}}>
      <Observer>{()=>
        <Collapse in={member.showTop} style={{position:'absolute', top:0, left:0, width:'100%'}}>
          <Grid container alignItems="center">
            <Grid item >
              <IconButton size="small" color={member.pageNum>0?'primary':'default'} {...stopper}
                onClick={(ev) => { ev.stopPropagation(); member.updateUrl(member.pageNum - 1) }}
                onDoubleClick={(ev) => {ev.stopPropagation() }} >
              <NavigateBeforeIcon />
              </IconButton>
            </Grid>
            <Grid item xs={1}>
              <TextField value={member.pageText} {...stopper}
                inputProps={{min: 0, style: { textAlign: 'center' }}}
                onChange={(ev)=> { member.pageText = ev.target.value}}
                onBlur={(ev) => {
                  const num = Number(member.pageText)
                  if (num > 0) { member.updateUrl(num-1) }
                }}
                onKeyPress={(ev)=>{
                  if (ev.key === 'Enter'){
                    const num = Number(member.pageText)
                    if (num > 0) { member.updateUrl(num-1) }
                  }
                }}
              />
            </Grid>
            <Grid item style={{fontSize:15}}>/ {member.numPages}</Grid>
            <Grid item >
              <IconButton size="small" color={member.pageNum<member.numPages-1?'primary':'default'} {...stopper}
                onClick={(ev) => { ev.stopPropagation(); member.updateUrl(member.pageNum + 1) }}
                onDoubleClick={(ev) => {ev.stopPropagation() }} >
              <NavigateNextIcon />
              </IconButton>
            </Grid>
          </Grid>
        </Collapse>
      }</Observer>
    </div>
  </div>
}
Example #13
Source File: Forms.tsx    From clarity with Apache License 2.0 6 votes vote down vote up
TextFieldWithFormState = observer(
  (props: TextFieldWithFormStateProps) => {
    const { fieldState, ...otherProps } = props;
    return (
      <TextField
        value={fieldState?.value}
        onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
          fieldState?.onChange(e.target.value);
        }}
        error={fieldState?.hasError}
        helperText={fieldState?.error}
        {...otherProps}
      />
    );
  }
)
Example #14
Source File: ForgotPasswordModal.tsx    From DamnVulnerableCryptoApp with MIT License 6 votes vote down vote up
ForgotPasswordModal = (props: IModalProps) => {

  const [username, setUsername] = useState("");
  const onUsernameChange = (e: React.ChangeEvent<HTMLInputElement>) => setUsername(e.target.value);
  const { isOpen, setIsOpen, setFlag } = props;


  const onModalClose = () => setIsOpen(false);

  const onSubmit = (e: React.SyntheticEvent) => {
    e.preventDefault();

    TimingAttackService.forgotPassword(username).then(res => setFlag(res.flag));
    onModalClose();
  };


  return (
    <Dialog open={isOpen} container={getContainer} style={{ position: 'absolute' }} onClose={onModalClose} BackdropProps={{ style: { position: 'absolute' } }}>
      <DialogTitle >Forgot Password</DialogTitle>
      <DialogContent>
        <form noValidate autoComplete="off" onSubmit={onSubmit}>
          <Alert severity="info">
            Type your username here. If the username is valid an email will be sent to it. No other feedback will be given
          </Alert>

          <TextField fullWidth label="Username" value={username} onChange={onUsernameChange} autoFocus />

          <Box mt={3} textAlign="right">
            <Button variant="contained" color="primary" type="submit">Submit</Button>
          </Box>
        </form>
      </DialogContent>
    </Dialog>
  );
}
Example #15
Source File: TextInput.tsx    From ow-mod-manager with MIT License 6 votes vote down vote up
TextInput: FunctionComponent<Props> = ({
  value,
  onChange,
  label,
  disabled,
  tooltip = '',
}) => {
  const styles = useStyles();
  const [text, setText] = useState('');
  const handleChange = useCallback(
    (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) =>
      setText(event.target.value),
    []
  );
  const handleSaveClick = () => {
    onChange(text);
  };

  useEffect(() => {
    debugConsole.log('useEffect: TextInput setText');
    setText(value);
  }, [value]);

  return (
    <ListItem>
      <Typography>{label}</Typography>
      <Tooltip title={tooltip} placement="bottom">
        <TextField
          className={styles.textField}
          variant="outlined"
          margin="dense"
          fullWidth
          value={text}
          onChange={handleChange}
          color="secondary"
          disabled={disabled}
        />
      </Tooltip>
      {value !== text && (
        <Button variant="contained" color="secondary" onClick={handleSaveClick}>
          {settingsText.textFieldSave}
        </Button>
      )}
    </ListItem>
  );
}
Example #16
Source File: SQFormReadOnlyField.tsx    From SQForm with MIT License 6 votes vote down vote up
function SQFormReadOnlyField({
  label,
  name,
  size = 'auto',
  InputProps = {},
  inputProps = {},
  muiFieldProps = {},
}: SQFormReadOnlyFieldProps): React.ReactElement {
  const {
    formikField: {field},
  } = useForm({name});

  return (
    <Grid item sm={size}>
      <TextField
        id={toKebabCase(name)}
        label={label}
        name={name}
        value={field.value || '- -'}
        fullWidth={true}
        InputLabelProps={{shrink: true}}
        InputProps={{
          ...InputProps,
          readOnly: true,
          disableUnderline: true,
        }}
        inputProps={inputProps}
        style={{marginBottom: 21}}
        {...muiFieldProps}
      />
    </Grid>
  );
}
Example #17
Source File: field.tsx    From Figurify with Apache License 2.0 6 votes vote down vote up
export function Field(props: {
    default: string, label: string,
    onChange: (string) => void,
    number: boolean
}) {
    const [name, setName] = useState(props.default);
    const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
        setName(event.target.value);
        props.onChange(event.target.value);
    };

    return (
        <TextField
            label={props.label}
            value={name}
            type={props.number ? "number" : "text"}
            onChange={handleChange}
            variant="filled"
            style={{width: "11vw"}}
        />
    );
}
Example #18
Source File: CopyTextArea.tsx    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
CopyTextArea: FunctionComponent<CopyTextAreaProps> = ({ text, rows = 5, ...others }) => {
  const onClick = useCallback((event) => {
    (event.target as HTMLInputElement).select();
    document.execCommand('copy');
  }, []);
  return (
    <>
      <Tooltip />
      <TextField
        fullWidth
        data-tip={t('map-ui:popup-click-to-copy')}
        multiline
        InputProps={{
          readOnly: true,
        }}
        inputProps={{ style: { cursor: 'pointer' } }}
        onClick={onClick}
        rows={rows}
        value={text}
        {...others}
      />
    </>
  );
}
Example #19
Source File: TextField.tsx    From aqualink-app with MIT License 6 votes vote down vote up
CustomTextfield = ({
  formField,
  label,
  placeholder,
  name,
  isNumeric,
  step,
  fullWidth,
  size,
  onChange,
  classes,
}: CustomTextfieldProps) => {
  return (
    <TextField
      className={classes.textField}
      variant="outlined"
      inputProps={{ className: classes.textField, step: step || undefined }}
      fullWidth={fullWidth}
      type={isNumeric ? "number" : "text"}
      value={formField.value}
      onChange={onChange}
      label={label}
      placeholder={placeholder}
      name={name}
      error={Boolean(formField.error)}
      helperText={formField.error}
      size={size}
    />
  );
}
Example #20
Source File: customScaffolderExtensions.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
TextValuePicker = (props: FieldExtensionComponentProps<string>) => {
  const {
    onChange,
    required,
    schema: { title, description },
    rawErrors,
    formData,
    uiSchema: { 'ui:autofocus': autoFocus },
    idSchema,
    placeholder,
  } = props;

  return (
    <TextField
      id={idSchema?.$id}
      label={title}
      placeholder={placeholder}
      helperText={description}
      required={required}
      value={formData ?? ''}
      onChange={({ target: { value } }) => onChange(value)}
      margin="normal"
      error={rawErrors?.length > 0 && !formData}
      inputProps={{ autoFocus }}
    />
  );
}
Example #21
Source File: PostCreateForm.tsx    From clearflask with Apache License 2.0 6 votes vote down vote up
renderEditNotifyTitle(
    draft: Partial<Admin.IdeaDraftAdmin>,
    selectedCategory?: Client.Category,
    TextFieldProps?: Partial<React.ComponentProps<typeof TextField>>,
    TextFieldComponent?: React.ElementType<React.ComponentProps<typeof TextField>>,
  ): React.ReactNode {
    if (!this.showModOptions()
      || !selectedCategory?.subscription
      || !draft.notifySubscribers) return null;
    const TextFieldCmpt = TextFieldComponent || TextField;
    return (
      <TextFieldCmpt
        variant='outlined'
        size={this.props.type === 'large' ? 'medium' : 'small'}
        disabled={this.state.isSubmitting}
        label='Notification Title'
        value={draft.notifySubscribers.title || ''}
        onChange={e => this.setState({ draftFieldNotifyTitle: e.target.value })}
        autoFocus
        {...TextFieldProps}
        inputProps={{
          maxLength: PostTitleMaxLength,
          ...TextFieldProps?.inputProps,
        }}
      />
    );
  }
Example #22
Source File: SetupPassword.tsx    From back-home-safe with GNU General Public License v3.0 6 votes vote down vote up
SetupPassword = ({ value, onChange }: Props) => {
  const { t } = useTranslation("tutorial");

  return (
    <Wrapper>
      <h2>
        {t("setup_password.name")}({t("global:form.optional")})
      </h2>
      <p>{t("setup_password.message.password_usage")}</p>
      <TextField
        type="password"
        autoComplete="new-password"
        value={value}
        onChange={(e) => {
          onChange(e.target.value);
        }}
      />
    </Wrapper>
  );
}
Example #23
Source File: index.tsx    From vscode-crossnote with GNU Affero General Public License v3.0 5 votes vote down vote up
function KanbanColumnHeaderDisplay(props: KanbanColumnHeaderProps) {
  const classes = useStyles(props);
  const { t } = useTranslation();
  const column = props.column;
  const board = props.board;
  const isPreview = props.isPreview;
  const refreshBoard = props.refreshBoard;
  const [clickedTitle, setClickedTitle] = useState<boolean>(false);
  const [titleValue, setTitleValue] = useState<string>(column.title);

  useEffect(() => {
    if (!clickedTitle && titleValue !== column.title) {
      column.title = titleValue || t("general/Untitled");
      setTitleValue(column.title);
      refreshBoard(board);
    }
  }, [clickedTitle, board, column.title, titleValue, t, refreshBoard]);

  return (
    <Box className={clsx(classes.columnHeader)}>
      <Box>
        {clickedTitle ? (
          <TextField
            value={titleValue}
            onChange={(event) => {
              setTitleValue(event.target.value);
            }}
            onBlur={() => {
              setClickedTitle(false);
            }}
            onKeyUp={(event) => {
              if (event.which === 13) {
                setClickedTitle(false);
              }
            }}
          ></TextField>
        ) : (
          <Typography
            variant={"body1"}
            style={{ cursor: "text" }}
            onClick={() => {
              if (!isPreview) {
                setClickedTitle(true);
              }
            }}
          >
            {titleValue}
          </Typography>
        )}
      </Box>
      {!isPreview && (
        <Box>
          <IconButton
            onClick={() => {
              const card: KanbanCard = {
                id: Date.now(),
                title: "", //"Card " + column.cards.length,
                description: t("general/empty"),
              };
              if (column) {
                column.cards.push(card);
              }
              props.refreshBoard(board);
            }}
          >
            <CardPlus></CardPlus>
          </IconButton>
          <IconButton
            onClick={() => {
              board.columns = board.columns.filter((l) => column.id !== l.id);
              props.refreshBoard(board);
            }}
          >
            <Close></Close>
          </IconButton>
        </Box>
      )}
    </Box>
  );
}
Example #24
Source File: FieldsDropdown.tsx    From firetable with Apache License 2.0 5 votes vote down vote up
/**
 * Returns dropdown component of all available types
 */
export default function FieldsDropdown({
  value,
  onChange,
  className,
  hideLabel = false,
  options: optionsProp,
}: IFieldsDropdownProps) {
  const classes = useStyles();

  const options = optionsProp
    ? Object.values(FieldType).filter(
        (fieldType) => optionsProp.indexOf(fieldType) > -1
      )
    : Object.values(FieldType);

  return (
    <TextField
      fullWidth
      select
      value={value ? value : ""}
      onChange={onChange}
      inputProps={{ name: "type", id: "type" }}
      label={!hideLabel ? "Field Type" : ""}
      aria-label="Field Type"
      hiddenLabel={hideLabel}
      helperText={value && getFieldProp("description", value)}
      FormHelperTextProps={{ classes: { root: classes.helperText } }}
      className={className}
    >
      {options.map((fieldType) => (
        <MenuItem
          key={`select-field-${getFieldProp("name", fieldType)}`}
          id={`select-field-${fieldType}`}
          value={fieldType}
        >
          <ListItemIcon className={classes.listItemIcon}>
            {getFieldProp("icon", fieldType)}
          </ListItemIcon>
          {getFieldProp("name", fieldType)}
        </MenuItem>
      ))}
    </TextField>
  );
}
Example #25
Source File: KeyModal.tsx    From DamnVulnerableCryptoApp with MIT License 5 votes vote down vote up
KeyModal = (props: IModalProps) => {

  const layoutContext = useContext(LayoutContext);
  const classes = useStyles();

  const onLoginClicked = () => {
    layoutContext.setLoading(true);

    KeyDisclosureService.unlockMailbox(props.mailboxKey).then(res => {
      layoutContext.setLoading(false);
      if (res.success) {
        props.setFlag(res.flag);
        props.setInboxUnlocked(true);
        props.setEmails(res.emails);
        props.setSelectedEmail(res.emails[0]);
      }
    }).catch(() => layoutContext.setLoading(false));
  };

  const onMailboxChange = (e: React.ChangeEvent<HTMLInputElement>) => props.setMailboxKey(e.target.value);
  const getContainer = () => document.getElementById('key-disclosure-container');



  return (
    <Dialog open={!props.inboxUnlocked} container={getContainer} style={{ position: 'absolute' }} BackdropProps={{ style: { position: 'absolute' } }}>
      <DialogTitle id="simple-dialog-title">Unlock [email protected] mailbox</DialogTitle>
      <DialogContent>
        <Box display={props.inboxUnlocked ? "none" : "block"}>
          <Typography>Add your private key to decrypt your inbox</Typography>

          <Box mt={2} mb={3}>
            <TextField placeholder="Private Key" fullWidth multiline rows={8} variant="outlined" onChange={onMailboxChange} />
          </Box>

          <Box textAlign="right">
            <Button variant="contained" className={classes.btn} onClick={onLoginClicked}>Decrypt</Button>
          </Box>
        </Box>
      </DialogContent>
    </Dialog >
  );
}
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: new_comment_dialog.tsx    From jupyter-extensions with Apache License 2.0 5 votes vote down vote up
function NewCommentDialog(props) {
  const [open, setOpen] = useState(true);
  const [comment, setComment] = useState('');

  const handleCloseCancel = () => {
    setOpen(false);
  };

  const handleCloseSend = () => {
    setOpen(false);
    const lineNumber = props.selection.start.line;
    newDetachedCommentThread(
      props.currFilePath,
      props.serverRoot,
      comment,
      lineNumber
    );
  };

  return (
    <div>
      <Dialog
        open={open}
        onClose={handleCloseCancel}
        aria-labelledby="form-dialog-title"
      >
        <DialogTitle id="form-dialog-title">Add a comment</DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            multiline
            margin="dense"
            rows={3}
            value={comment}
            variant="outlined"
            size="medium"
            label="Start a new comment thread"
            onChange={e => setComment(e.target.value)}
            style={style.textField}
            fullWidth
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseCancel} color="primary">
            Cancel
          </Button>
          <Button onClick={handleCloseSend} color="primary">
            Send
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  );
}
Example #28
Source File: OnCallList.tsx    From backstage-plugin-opsgenie with MIT License 5 votes vote down vote up
SchedulesGrid = ({ schedules, cardsPerPage }: { schedules: Schedule[], cardsPerPage: number }) => {
    const classes = useStyles();
    const [results, setResults] = React.useState(schedules);
    const [search, setSearch] = React.useState("");
    const [page, setPage] = React.useState(1);
    const [offset, setOffset] = React.useState(0);
    const handleChange = (_: React.ChangeEvent<unknown>, value: number) => {
        setOffset((value - 1) * cardsPerPage);
        setPage(value);
    };
    const debouncedSearch = useDebounce(search, 300);

    // debounced search
    useEffect(
        () => {
            if (!debouncedSearch) {
                setResults(schedules);
                return;
            }

            const filtered = schedules.filter(schedule => {
                return schedule.name.toLowerCase().includes(debouncedSearch.toLowerCase());
            });
            setResults(filtered);
        },
        [debouncedSearch, schedules]
    );

    return (
        <div>
            <TextField
                fullWidth
                variant="outlined"
                className={classes.search}
                placeholder="Team…"
                InputProps={{
                    startAdornment: (
                        <InputAdornment position="start">
                            <SearchIcon />
                        </InputAdornment>
                    )
                }}
                onChange={e => setSearch(e.target.value)}
            />

            <ItemCardGrid classes={{ root: classes.onCallItemGrid }}>
                {results.filter((_, i) => i >= offset && i < offset + cardsPerPage).map(schedule => <OnCallForScheduleCard key={schedule.id} schedule={schedule} />)}
            </ItemCardGrid>

            <Pagination
                className={classes.pagination}
                count={Math.ceil(results.length / cardsPerPage)}
                page={page}
                onChange={handleChange}
                showFirstButton
                showLastButton
            />
        </div>
    );
}
Example #29
Source File: index.tsx    From GroupChat with MIT License 5 votes vote down vote up
Modal: React.FC<Props> = props => {
  const dispatch = useDispatch();

  const [isValid, setIsValid] = useState(true);
  const [title, setTitle] = useState('');
  const [titleError, setTitleEror] = useState(false);
  const [titleHelper, setTitleHelper] = useState('');
  const [description, setDescription] = useState('');

  const createHandler = (title: string, description: string) => {
    if (titleError) {
      setIsValid(false);
      return;
    }

    props.onCreate(title, description);
  };

  const titleHandler = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    if (e.target.value.length <= 2 || e.target.value.length > 12) {
      setTitleEror(true);
      setTitleHelper('Title should contain 3 to 12 characters.');
    } else {
      setTitleEror(false);
      setTitleHelper('');
      setIsValid(true);
    }

    setTitle(e.target.value);
  };

  return (
    <>
      <div className={styles.backdrop} onClick={() => dispatch({ type: 'MODAL', payload: { modal: null } })}></div>
      <div className={styles.modal}>
        <h2>{props.title}</h2>
        <ThemeProvider theme={darkTheme}>
          <form className={styles.form} onSubmit={e => e.preventDefault()}>
            <TextField
              className={styles.input}
              id="title"
              label="Title"
              variant="outlined"
              onChange={e => titleHandler(e)}
              helperText={titleHelper}
              error={titleError}
              value={title}
            />
            <TextField
              className={styles.input}
              id="description"
              rows={3}
              label="Description"
              variant="outlined"
              multiline
              value={description}
              onChange={e => setDescription(e.target.value)}
            />
            <CustomButton onClick={() => createHandler(title, description)} isPurple title="Create" small />
            {!isValid && <p className={styles.error}>Invalid entries.</p>}
          </form>
        </ThemeProvider>
      </div>
    </>
  );
}