@mui/material#TextField TypeScript Examples

The following examples show how to use @mui/material#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: TextFieldWithTooltip.tsx    From Cromwell with MIT License 6 votes vote down vote up
export default function TextFieldWithTooltip(props: TextFieldProps & {
    tooltipText?: string;
    tooltipLink?: string;
}) {
    const history = useHistory();

    const openLink = () => {
        if (props.tooltipLink) {
            if (props.tooltipLink.startsWith('http')) {
                window.open(props.tooltipLink, '_blank');
            } else {
                history.push(props.tooltipLink);
            }
        }
    }

    return (
        <TextField
            InputProps={{
                endAdornment: (
                    <InputAdornment position="end">
                        <Tooltip title={props.tooltipText}>
                            <IconButton onClick={openLink}>
                                <HelpOutlineOutlined />
                            </IconButton>
                        </Tooltip>
                    </InputAdornment>
                ),
            }}
            variant="standard"
            {...props}
        />
    )
}
Example #2
Source File: SolidColoredTextfield.tsx    From genshin-optimizer with MIT License 6 votes vote down vote up
export default function SolidColoredTextField({ hasValue, startAdornment, flattenCorners = false, InputProps, sx, ...props }: SolidColoredTextFieldProps) {
  const theme = useTheme()
  return <TextField
    {...props}
    variant="filled"
    color={hasValue ? "success" : "primary"}
    hiddenLabel={props.label ? false : true}
    type="search"
    InputProps={{
      ...InputProps,
      startAdornment,
    }}
    InputLabelProps={{ style: { color: theme.palette.text.primary } }}
    sx={{
      ...sx,
      "& .MuiFilledInput-root": { backgroundColor: hasValue ? theme.palette.success.main : theme.palette.primary.main, borderRadius: flattenCorners ? 0 : 1, paddingTop: props.label ? undefined : 0, paddingBottom: 0 },
      "& .MuiFilledInput-root:before": { border: "none" },
      "& .MuiFilledInput-root:after": { border: "none" },
      "& .MuiFilledInput-root.Mui-focused": { backgroundColor: hasValue ? theme.palette.success.light : theme.palette.primary.light },
      "& .MuiFilledInput-root:hover": { backgroundColor: hasValue ? theme.palette.success.dark : theme.palette.primary.dark },
      "& .MuiFilledInput-root:hover:not(.Mui-disabled):before": { border: "none" },
      // Remove the x at the end of search input for IE
      "& input[type=search]::-ms-clear": { display: "none", width: 0, height: 0 },
      "& input[type=search]::-ms-reveal": { display: "none", width: 0, height: 0 },

      // Remove the x at the end of search input for Chrome
      "& input[type=search]::-webkit-search-decoration": { display: "none" },
      "& input[type=search]::-webkit-search-cancel-button": { display: "none" },
      "& input[type=search]::-webkit-search-results-button": { display: "none" },
      "& input[type=search]::-webkit-search-results-decoration": { display: "none" },
    }}
  />
}
Example #3
Source File: InputBoxWrapper.tsx    From console with GNU Affero General Public License v3.0 6 votes vote down vote up
function InputField(props: TextFieldProps) {
  const classes = inputStyles();

  return (
    <TextField
      InputProps={{ classes } as Partial<OutlinedInputProps>}
      {...props}
    />
  );
}
Example #4
Source File: NodeNameEditor.tsx    From mui-toolpad with MIT License 6 votes vote down vote up
export default function NodeNameEditor({ node, sx }: NodeNameEditorProps) {
  const domApi = useDomApi();

  const [nameInput, setNameInput] = React.useState(node.name);
  React.useEffect(() => setNameInput(node.name), [node.name]);

  const handleNameInputChange = React.useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => setNameInput(event.target.value),
    [],
  );

  const handleNameCommit = React.useCallback(
    () => domApi.setNodeName(node.id, nameInput),
    [domApi, node.id, nameInput],
  );

  const handleKeyPress = React.useCallback(
    (event: React.KeyboardEvent<HTMLDivElement>) => {
      if (event.key === 'Enter') {
        handleNameCommit();
      }
    },
    [handleNameCommit],
  );

  return (
    <TextField
      sx={sx}
      fullWidth
      label="name"
      value={nameInput}
      onChange={handleNameInputChange}
      onBlur={handleNameCommit}
      onKeyPress={handleKeyPress}
    />
  );
}
Example #5
Source File: BlockEditor.tsx    From NekoMaid with MIT License 6 votes vote down vote up
BlockSelector: React.FC<{ worlds: string[] }> = ({ worlds }) => {
  const his = useHistory()
  const [world, setWorld] = useState(worlds[0])
  const [x, setX] = useState('0')
  const [y, setY] = useState('0')
  const [z, setZ] = useState('0')
  return <Grid container>
    <Grid item xs={6}>
      <FormControl variant='standard' fullWidth>
        <InputLabel id='nekomaid-block-editor-world'>{lang.world}</InputLabel>
        <Select
          labelId='nekomaid-block-editor-world'
          value={world}
          label={lang.world}
          onChange={e => setWorld(e.target.value)}
        >
          {worlds.map(it => <MenuItem key={it} value={it}>{it}</MenuItem>)}
        </Select>
      </FormControl>
    </Grid>
    <Grid item xs={2}><TextField variant='standard' label='X' type='number' fullWidth value={x} onChange={e => setX(e.target.value)} /></Grid>
    <Grid item xs={2}><TextField variant='standard' label='Y' type='number' fullWidth value={y} onChange={e => setY(e.target.value)} /></Grid>
    <Grid item xs={2}><TextField variant='standard' label='Z' type='number' fullWidth value={z} onChange={e => setZ(e.target.value)} /></Grid>
    <Grid item xs={12} sx={{ marginTop: 3, textAlign: 'center' }}>
      <Button
        variant='contained'
        onClick={() => his.push(`/NekoMaid/block/${world}/${parseFloat(x) | 0}/${parseFloat(y) | 0}/${parseFloat(z) | 0}`)}
      >{minecraft['gui.done']}</Button>
    </Grid>
  </Grid>
}
Example #6
Source File: FormSelectField.tsx    From frontend with MIT License 6 votes vote down vote up
export default function FormSelectField({
  label,
  name,
  options,
  ...textFieldProps
}: FormSelectFieldProps) {
  const { t } = useTranslation()
  const [field, meta] = useField(name)
  const helperText = meta.touched ? translateError(meta.error as TranslatableField, t) : ''
  return (
    <TextField
      fullWidth
      select
      label={t(label)}
      size="small"
      variant="outlined"
      error={Boolean(meta.error) && Boolean(meta.touched)}
      helperText={helperText}
      {...textFieldProps}
      {...field}>
      {options.map((o) => {
        return (
          <MenuItem key={o.key} value={o.value}>
            {o.name}
          </MenuItem>
        )
      })}
    </TextField>
  )
}
Example #7
Source File: form-text-input.tsx    From example with MIT License 6 votes vote down vote up
export function FormTextInput({ form, options, name, label, helperText, disabled, ...rest }: IFormTextInputProps) {
	const { register } = form
	const { hasError, message: errorMessage } = useFormInputError(form, name)

	return <TextField
		label={label}
		size="small"
		error={hasError}
		helperText={errorMessage ?? helperText}
		fullWidth
		{...rest}
		{...register(name, { required: true, disabled, ...options })}
	/>
}
Example #8
Source File: SapioCompilerModal.tsx    From sapio-studio with Mozilla Public License 2.0 6 votes vote down vote up
export function SapioCompilerModal(props: { show: boolean }) {
    const dispatch = useDispatch();
    const handleSubmit: FormEventHandler<HTMLFormElement> = (event) => {
        event.preventDefault();
        event.stopPropagation();
        const form = event.currentTarget;
        // triggers reconnect
        dispatch(close_modal());
    };
    return (
        <Dialog open={props.show} onClose={() => dispatch(close_modal())}>
            <DialogTitle>Set Contract Generator URL</DialogTitle>
            <DialogContent>
                <form onSubmit={handleSubmit}>
                    <TextField
                        name="ws"
                        type="text"
                        placeholder="url"
                        label="Websocket"
                    />
                    <Button type="submit">Set</Button>
                </form>
            </DialogContent>
            <DialogActions>
                <Button onClick={() => dispatch(close_modal())}>Close</Button>
            </DialogActions>
        </Dialog>
    );
}
Example #9
Source File: CustomColorTextField.tsx    From firecms with MIT License 5 votes vote down vote up
export default function CustomColorTextField({
                                                 property,
                                                 value,
                                                 setValue,
                                                 customProps,
                                                 touched,
                                                 error,
                                                 isSubmitting,
                                                 context, // the rest of the entity values here
                                                 ...props
                                             }: FieldProps<string, CustomColorTextFieldProps>) {

    const classes = useStyles({ customColor: customProps.color });

    return (
        <>
            <TextField required={property.validation?.required}
                       classes={{
                           root: classes.root
                       }}
                       error={!!error}
                       disabled={isSubmitting}
                       label={property.title}
                       value={value ?? ""}
                       onChange={(evt: any) => {
                           setValue(
                               evt.target.value
                           );
                       }}
                       helperText={error}
                       fullWidth
                       variant={"filled"}/>

            <FieldDescription property={property}/>
        </>

    );

}
Example #10
Source File: SettingsPage.tsx    From Cromwell with MIT License 5 votes vote down vote up
export function SettingsPage(props: TPluginSettingsProps<TProductFilterSettings>) {
    const onSave = () => {
        getRestApiClient().purgeRendererEntireCache();
    }

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

  return (
    <Autocomplete
      options={nativesArray}
      value={natives[value]}
      onChange={(e, native) => native && onChange(native.hash)}
      renderInput={(params) => (
        <TextField 
          {...params} 
          label="Preview Native" 
        />
      )}
      renderOption={(props, option) => (
        <li {...props}>
          <Typography noWrap>{option.name}</Typography>
        </li>
      )}
      ListboxComponent={
        ListboxComponent as React.ComponentType<React.HTMLAttributes<HTMLElement>>
      }
      getOptionLabel={(native) => native.name}
      sx={sx}
      disableClearable
      disableListWrap
      fullWidth
    />
  )
}
Example #12
Source File: GroupMemberSelect.tsx    From abrechnung with GNU Affero General Public License v3.0 5 votes vote down vote up
export default function GroupMemberSelect({
    group,
    onChange,
    value = null,
    disabled = false,
    noDisabledStyling = false,
    className = null,
    ...props
}) {
    const members = useRecoilValue(groupMembers(group.id));
    const memberIDToUsername = useRecoilValue(groupMemberIDsToUsername(group.id));

    return (
        <Autocomplete
            options={members.map((m) => m.user_id)}
            getOptionLabel={(option) => memberIDToUsername[option]}
            value={value}
            disabled={disabled}
            openOnFocus
            fullWidth
            PopperComponent={StyledAutocompletePopper}
            className={className}
            onChange={(event, newValue) => onChange(newValue)}
            renderOption={(props, user_id) => (
                <Box component="li" {...props}>
                    <Typography variant="body2" component="span" sx={{ ml: 1 }}>
                        {memberIDToUsername[user_id]}
                    </Typography>
                </Box>
            )}
            renderInput={
                noDisabledStyling
                    ? (params) => <DisabledTextField variant="standard" {...params} {...props} />
                    : (params) => <TextField variant="standard" {...params} {...props} />
            }
        />
    );
}
Example #13
Source File: DetailError.tsx    From airmessage-web with Apache License 2.0 5 votes vote down vote up
function DetailErrorAuth(props: {resetCallback?: VoidFunction | undefined}) {
	const [password, setPassword] = useState("");
	const updatePassword = useCallback((event: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => setPassword(event.target.value), [setPassword]);
	
	const [isLoading, setIsLoading] = useState(false);
	const confirm = useCallback(() => {
		if(password.trim().length === 0) return;
		
		setIsLoading(true);
		Promise.all([setCryptoPassword(password), setSecureLS(SecureStorageKey.ServerPassword, password)]).then(connect);
	}, [setIsLoading, password]);
	const onKeyDown = useCallback((event: React.KeyboardEvent<HTMLDivElement>) => {
		//Confirm when enter is pressed
		if(event.key === "Enter") {
			confirm();
		}
	}, [confirm]);
	
	return (<>
		<LockRounded className={styles.icon} />
		<div className={styles.split}>
			<Typography variant="h4" gutterBottom>Server is password-protected</Typography>
			<Typography color="textSecondary" gutterBottom>Please enter your server password</Typography>
			<TextField label="Password" variant="filled" type="password" autoComplete="current-password" margin="normal" autoFocus
					   value={password} onChange={updatePassword} onKeyDown={onKeyDown} />
			<div className={`${styles.buttonRow} ${styles.buttonRowReverse}`}>
				<Button variant="contained" disableElevation onClick={confirm} disabled={password.trim().length === 0 || isLoading}>Continue</Button>
				{props.resetCallback && <Button onClick={props.resetCallback}>Reconfigure</Button>}
			</div>
		</div>
	</>);
}
Example #14
Source File: SelectElement.tsx    From react-hook-form-mui with MIT License 5 votes vote down vote up
export default function SelectElement({
  name,
  required,
  valueKey = 'id',
  labelKey = 'title',
  options = [],
  parseError,
  type,
  objectOnChange,
  validation = {},
  control,
  ...rest
}: SelectElementProps): JSX.Element {
  const isNativeSelect = !!rest.SelectProps?.native
  const ChildComponent = isNativeSelect ? 'option' : MenuItem
  if (required) {
    validation.required = 'This field is required'
  }
  return (
    <Controller
      name={name}
      rules={validation}
      control={control}
      render={({ field: { onBlur, onChange, value }, fieldState: { invalid, error } }) => {
        // handle shrink on number input fields
        if (type === 'number' && typeof value !== 'undefined') {
          rest.InputLabelProps = rest.InputLabelProps || {}
          rest.InputLabelProps.shrink = true
        }
        if (typeof value === 'object') {
          value = value[valueKey] // if value is object get key
        }
        return <TextField
          {...rest}
          name={name}
          value={value ?? ''}
          onBlur={onBlur}
          onChange={(event) => {
            let item: number | string = event.target.value
            if (type === 'number') {
              item = Number(item)
            }
            onChange(item)
            if (typeof rest.onChange === 'function') {
              if (objectOnChange) {
                item = options.find(i => i[valueKey] === item)
              }
              rest.onChange(item)
            }
          }}
          select
          required={required}
          error={invalid}
          helperText={error ? (typeof parseError === 'function' ? parseError(error) : error.message) : rest.helperText}
        >{isNativeSelect && <option />}
          {options.map((item: any) =>
            createElement(
              ChildComponent,
              {
                key: `${name}_${item[valueKey]}`,
                value: item[valueKey]
              },
              item[labelKey]
            )
          )}
        </TextField>
      }}
    />
  )
}
Example #15
Source File: CharacterSelectionModal.tsx    From genshin-optimizer with MIT License 5 votes vote down vote up
export function CharacterSelectionModal({ show, onHide, onSelect, filter = () => true, newFirst = false }: CharacterSelectionModalProps) {
  const sortKeys = useMemo(() => newFirst ? ["new", ...defaultSortKeys] : defaultSortKeys, [newFirst])
  const { database } = useContext(DatabaseContext)
  const { t } = useTranslation("page_character")

  const [sortBy, setsortBy] = useState(sortKeys[0])
  const [ascending, setascending] = useState(false)
  const [elementalFilter, setelementalFilter] = useState<ElementKey | "">("")
  const [weaponFilter, setweaponFilter] = useState<WeaponTypeKey | "">("")

  const characterSheets = usePromise(CharacterSheet.getAll, [])

  const [favesDirty, setFavesDirty] = useForceUpdate()
  useEffect(() => database.followAnyChar(setFavesDirty), [database, setFavesDirty])

  const [searchTerm, setSearchTerm] = useState("")
  const deferredSearchTerm = useDeferredValue(searchTerm)

  const sortConfigs = useMemo(() => characterSheets && characterSortConfigs(database, characterSheets), [database, characterSheets])
  const filterConfigs = useMemo(() => characterSheets && favesDirty && characterFilterConfigs(database, characterSheets), [favesDirty, database, characterSheets])
  const ownedCharacterKeyList = useMemo(() => characterSheets ? allCharacterKeys.filter(cKey => filter(database._getChar(cKey), characterSheets[cKey])) : [], [database, characterSheets, filter])
  const characterKeyList = useMemo(() => (characterSheets && sortConfigs && filterConfigs) ?
    ownedCharacterKeyList
      .filter(filterFunction({ element: elementalFilter, weaponType: weaponFilter, favorite: "yes", name: deferredSearchTerm }, filterConfigs))
      .sort(sortFunction(sortBy, ascending, sortConfigs) as (a: CharacterKey, b: CharacterKey) => number)
      .concat(
        ownedCharacterKeyList
          .filter(filterFunction({ element: elementalFilter, weaponType: weaponFilter, favorite: "no", name: deferredSearchTerm }, filterConfigs))
          .sort(sortFunction(sortBy, ascending, sortConfigs) as (a: CharacterKey, b: CharacterKey) => number)
      )
    : [],
    [characterSheets, elementalFilter, weaponFilter, sortBy, ascending, sortConfigs, filterConfigs, ownedCharacterKeyList, deferredSearchTerm])

  if (!characterSheets) return null
  return <ModalWrapper open={show} onClose={onHide} sx={{ "& .MuiContainer-root": { justifyContent: "normal" } }}>
    <CardDark>
      <CardContent sx={{ py: 1 }}>
        <Grid container spacing={1} >
          <Grid item>
            <WeaponToggle sx={{ height: "100%" }} onChange={setweaponFilter} value={weaponFilter} size="small" />
          </Grid>
          <Grid item>
            <ElementToggle sx={{ height: "100%" }} onChange={setelementalFilter} value={elementalFilter} size="small" />
          </Grid>
          <Grid item>
            <TextField
              autoFocus
              value={searchTerm}
              onChange={(e: ChangeEvent<HTMLTextAreaElement>) => setSearchTerm(e.target.value)}
              label={t("characterName")}
            />
          </Grid>

          <Grid item flexGrow={1} />

          <Grid item >
            <SortByButton sx={{ height: "100%" }}
              sortKeys={sortKeys} value={sortBy} onChange={setsortBy as any}
              ascending={ascending} onChangeAsc={setascending} />
          </Grid>
          <Grid item>
            <CloseButton onClick={onHide} />
          </Grid>
        </Grid>
      </CardContent>
      <Divider />
      <CardContent><Grid container spacing={1}>
        {characterKeyList.map(characterKey => <Grid item key={characterKey} xs={6} md={4} lg={3} >
          <CharacterBtn key={characterKey} characterKey={characterKey} characterSheet={characterSheets[characterKey]} onClick={() => { onHide(); onSelect?.(characterKey) }} />
        </Grid>)}
      </Grid></CardContent>
    </CardDark>
  </ModalWrapper>
}
Example #16
Source File: AutocompleteWrapper.tsx    From console with GNU Affero General Public License v3.0 5 votes vote down vote up
function InputField(props: TextFieldProps) {
  const classes = inputStyles();

  return (
    <TextField
      InputProps={{ classes } as Partial<OutlinedInputProps>}
      {...props}
    />
  );
}
Example #17
Source File: CreateApiNodeDialog.tsx    From mui-toolpad with MIT License 5 votes vote down vote up
export function ConnectionSelect({ dataSource, value, onChange }: ConnectionSelectProps) {
  const dom = useDom();

  const app = appDom.getApp(dom);
  const { connections = [] } = appDom.getChildNodes(dom, app);

  const filtered = React.useMemo(() => {
    return dataSource
      ? connections.filter((connection) => connection.attributes.dataSource.value === dataSource)
      : connections;
  }, [connections, dataSource]);

  const handleSelectionChange = React.useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      onChange((event.target.value as NodeId) || null);
    },
    [onChange],
  );

  return (
    <TextField
      select
      fullWidth
      value={value || ''}
      label="Connection"
      onChange={handleSelectionChange}
    >
      {filtered.map((connection) => (
        <MenuItem key={connection.id} value={connection.id}>
          {connection.name} | {connection.attributes.dataSource.value}
        </MenuItem>
      ))}
    </TextField>
  );
}
Example #18
Source File: ServerSwitch.tsx    From NekoMaid with MIT License 5 votes vote down vote up
ServerSwitch: React.FC<DialogProps> = props => {
  const [value, setValue] = useState<string>('')
  let error = false
  // eslint-disable-next-line no-new
  try { if (value) new URL(value.startsWith('http://') ? value : 'http://' + value) } catch { error = true }
  return <Dialog fullWidth maxWidth='xs' {...props}>
    <DialogTitle>{lang.serverSwitch.title}</DialogTitle>
    <DialogContent sx={{ overflow: 'hidden' }}>
      <Autocomplete
        freeSolo
        inputValue={value}
        clearOnBlur={false}
        onInputChange={(_: any, v: string) => setValue(v)}
        noOptionsText={lang.serverSwitch.noServer}
        style={{ width: '100%', maxWidth: 500, marginTop: 10 }}
        options={JSON.parse(localStorage.getItem('NekoMaid:servers') || '[]')}
        getOptionLabel={(option: any) => option.address}
        renderInput={(props: any) => <TextField
          {...props}
          error={error}
          label={minecraft['addServer.enterIp']}
          helperText={error ? lang.serverSwitch.wrongHostname : undefined}
        />}
      />
      <DialogContentText>{lang.serverSwitch.content}</DialogContentText>
    </DialogContent>
    <DialogActions>
      <Button
        color='primary'
        disabled={error}
        onClick={() => (location.search = '?' + encodeURIComponent(value))}
      >{lang.serverSwitch.connect}</Button>
    </DialogActions>
  </Dialog>
}
Example #19
Source File: CampaignSelect.tsx    From frontend with MIT License 5 votes vote down vote up
export default function CampaignSelect({ label, name, campaigns, ...textFieldProps }: Props) {
  const { t } = useTranslation('transfer')

  const [field, meta] = useField(name)
  const { setFieldValue } = useFormikContext()

  const helperText = meta.touched ? translateError(meta.error as TranslatableField, t) : ''

  const handleChange = (event: React.ChangeEvent<{ value: unknown }>) => {
    setFieldValue(name, event.target.value)
  }

  return (
    <TextField
      {...textFieldProps}
      {...field}
      select
      variant="outlined"
      fullWidth
      onChange={handleChange}
      label={t(label)}
      error={Boolean(meta.error) && Boolean(meta.touched)}
      helperText={helperText}>
      {[{ id: '', title: '' }, ...(campaigns || [])].map((p) => {
        return (
          <MenuItem key={p.id} value={p.id}>
            {p.title}
          </MenuItem>
        )
      })}
    </TextField>
  )
}
Example #20
Source File: form-select.tsx    From example with MIT License 5 votes vote down vote up
export function FormSelect({ form, options, name, children, helperText, disabled,  ...rest }: React.PropsWithChildren<IFormSelectProps>) {
	const { register } = form
	const { hasError, message: errorMessage } = useFormInputError(form, name)

	return <TextField
		size="small"
		error={hasError}
		helperText={errorMessage ?? helperText}
		select
		fullWidth
		{...register(name, { required: true, disabled, ...options })}
		{...rest}
	>
		{ children }
	</TextField>
}
Example #21
Source File: NewNickname.tsx    From sapio-studio with Mozilla Public License 2.0 5 votes vote down vote up
export function NewNickname(props: { show: boolean; hide: () => void }) {
    const [value, set_value] = React.useState<null | string>(null);
    const [key_value, set_key_value] = React.useState<null | string>(null);
    return (
        <Dialog onClose={props.hide} open={props.show}>
            <DialogTitle>Create a new User</DialogTitle>
            <DialogContent>
                <DialogContentText>
                    The key and nickname for the new person. Keys must be
                    unique.
                </DialogContentText>
                <TextField
                    onChange={(ev) => set_value(ev.currentTarget.value)}
                    value={value}
                    autoFocus
                    margin="dense"
                    label="Name"
                    name="name"
                    type="text"
                    fullWidth
                    variant="standard"
                />
                <TextField
                    onChange={(ev) => set_key_value(ev.currentTarget.value)}
                    value={key_value}
                    autoFocus
                    margin="dense"
                    label="Key Hash"
                    name="keyhash"
                    type="text"
                    fullWidth
                    variant="standard"
                />
            </DialogContent>
            <DialogActions>
                <Button onClick={props.hide}>Cancel</Button>
                <Button
                    color="success"
                    onClick={async (ev) => {
                        if (value !== null && key_value) {
                            await window.electron.chat.add_user(
                                value,
                                key_value
                            );
                        }
                        props.hide();
                    }}
                >
                    Create
                </Button>
            </DialogActions>
        </Dialog>
    );
}
Example #22
Source File: WidgetDateTimePicker.tsx    From ui-schema with MIT License 5 votes vote down vote up
WidgetDateTimePicker: React.FC<WidgetProps & WithScalarValue & WidgetDateTimePickerProps<any>> = (
    {
        value, storeKeys, onChange, schema, required,
        Picker,
        pickerProps,
    }
) => {
    const adapter = React.useContext(MuiPickersAdapterContext)
    const {utils} = adapter || {}
    const dateFormat = (schema.getIn(['date', 'format']) as string | undefined) || 'yyyy-MM-dd HH:mm'
    const dateFormatData = schema.getIn(['date', 'formatData']) as string || dateFormat
    const dateValue = React.useMemo(
        () =>
            !utils || typeof value === 'undefined' ?
                null : utils.parse(value as string, dateFormatData),
        [value, utils, dateFormatData],
    )

    const viewsList = schema.getIn(['date', 'views'])
    const views = React.useMemo(
        () => List.isList(viewsList) ? viewsList.toArray() as CalendarOrClockPickerView[] : undefined,
        [viewsList],
    )

    const openTo = schema.getIn(['date', 'openTo']) as CalendarOrClockPickerView
    let orientation = schema.getIn(['date', 'orientation']) as 'landscape' | 'portrait' | undefined
    if (!orientation && !views) {
        console.error('WidgetDatePicker invalid, `orientation`=`landscape` requires `views`')
        orientation = undefined
    }

    return <Picker
        label={<TransTitle schema={schema} storeKeys={storeKeys}/>}
        value={dateValue}
        inputFormat={dateFormat}
        orientation={orientation}
        openTo={openTo}
        views={views}
        readOnly={schema.get('readOnly') as boolean}
        onChange={(e) => {
            if (!utils) return
            onChange({
                storeKeys: storeKeys,
                scopes: ['value'],
                type: 'set',
                schema,
                required,
                data: {value: e ? utils.formatByString(e, dateFormatData) : ''},
            } as UIStoreActionSet)
        }}
        renderInput={(params) => <TextField {...params} fullWidth/>}
        {...pickerProps || {}}
    />
}
Example #23
Source File: handleAccountDialog.tsx    From Search-Next with GNU General Public License v3.0 5 votes vote down vote up
HandleAccountDialog: React.FC<HandleAccountDialogProps> = ({
  open,
  title,
  value,
  onOk,
  onCancel,
}) => {
  const { Item } = Form;
  const form = Form.useForm();
  const { handleSubmit, reset, setValue } = form;

  const handleCancel = () => {
    onCancel();
  };

  const handleOk = () => {
    handleSubmit(onOk, (err) => {
      console.log(err);
    })();
  };

  React.useEffect(() => {
    if (open && value) {
      setValue('username', value['username']);
    }
    if (!open) {
      setValue('username', '');
    }
  }, [open]);

  return (
    <Modal
      title={title ? title : '修改账户名称'}
      open={open}
      onCancel={handleCancel}
      onOk={handleOk}
    >
      <Form form={form} size="small">
        <Item
          name="username"
          label="账户名称"
          rules={{ required: { value: true, message: '请输入账户名称' } }}
        >
          <TextField
            fullWidth
            variant="outlined"
            placeholder="请输入账户名称"
          />
        </Item>
      </Form>
    </Modal>
  );
}
Example #24
Source File: index.tsx    From yearn-watch-legacy with GNU Affero General Public License v3.0 5 votes vote down vote up
StyledTextField = styled(TextField)`
    && {
        width: 100%;
        background-color: transparent;
        align-content: center;
        border-color: transparent;
        .MuiOutlinedInput-root {
            fieldset {
                border-color: transparent !important;
            }
            &:hover fieldset {
                border-color: transparent !important;
            }
            &.Mui-focused fieldset {
                border-color: transparent;
            }
            color: ${({ theme }) => theme.text} !important;
        }
    }
`
Example #25
Source File: FirebaseLoginView.tsx    From firecms with MIT License 4 votes vote down vote up
function PhoneLoginForm({
                       onClose,
                       authDelegate
                   }: {
    onClose: () => void,
    authDelegate: FirebaseAuthDelegate,
}) {
    useRecaptcha();

    const [phone, setPhone] = useState<string>();
    const [code, setCode] = useState<string>();
    const [isInvalidCode, setIsInvalidCode] = useState(false);

    const handleSubmit = async (event: any) => {
        event.preventDefault();

        if (code && authDelegate.confirmationResult) {
            setIsInvalidCode(false);

            authDelegate.confirmationResult.confirm(code).catch((e: FirebaseError) => {
                if (e.code === "auth/invalid-verification-code") {
                    setIsInvalidCode(true)
                }
            });
        } else {
            if (phone) {
                authDelegate.phoneLogin(phone, window.recaptchaVerifier);
            }
        }
    }

    return (
        <form onSubmit={handleSubmit}>
            {isInvalidCode &&
            <Box p={2}>
                <ErrorView
                    error={"Invalid confirmation code"}/>
            </Box>}


            <div id={RECAPTCHA_CONTAINER_ID} />
            <Grid container spacing={1}>
                <Grid item xs={12}>
                    <IconButton
                        onClick={onClose}>
                        <ArrowBackIcon sx={{ width: 20, height: 20 }}/>
                    </IconButton>
                </Grid>
                <Grid item xs={12} sx={{
                    p: 1,
                    display: "flex"
                }}>
                    <Typography align={"center"}
                                variant={"subtitle2"}>{"Please enter your phone number"}</Typography>
                </Grid>
                <Grid item xs={12}>
                    <TextField placeholder="" fullWidth
                                value={phone}
                                disabled={Boolean(phone && (authDelegate.authLoading || authDelegate.confirmationResult))}
                                type="phone"
                                required
                                onChange={(event) => setPhone(event.target.value)}/>
                </Grid>
                {Boolean(phone && authDelegate.confirmationResult) &&
                    <>
                        <Grid item xs={12} sx={{
                            mt: 2,
                            p: 1,
                            display: "flex"
                        }}>
                        <Typography align={"center"}
                                    variant={"subtitle2"}>{"Please enter the confirmation code"}</Typography>
                        </Grid>
                        <Grid item xs={12}>
                            <TextField placeholder="" fullWidth
                                value={code}
                                type="text"
                                required
                                onChange={(event) => setCode(event.target.value)}/>
                        </Grid>
                    </>
                }

                <Grid item xs={12}>
                    <Box sx={{
                        display: "flex",
                        justifyContent: "end",
                        alignItems: "center",
                        width: "100%"
                    }}>

                        {authDelegate.authLoading &&
                        <CircularProgress sx={{ p: 1 }} size={16}
                                        thickness={8}/>
                        }

                        <Button type="submit">
                            {"Ok"}
                        </Button>
                    </Box>
                </Grid>

            </Grid>
        </form>
    );
}
Example #26
Source File: MenuItem.tsx    From Cromwell with MIT License 4 votes vote down vote up
Item = (props: {
    data: TMainMenuItem;
    itemProps?: {
        items: TMainMenuItem[];
        canReorder: boolean;
        refreshList: () => void;
    }
}) => {
    const { refreshList, items, canReorder } = props.itemProps ?? {};
    const item = props.data;

    const forceUpdate = useForceUpdate();
    const classes = useStyles();
    const [_expanded, setExpanded] = React.useState(false);
    const expanded = _expanded && !canReorder;

    if (!item) return null;

    const handleExpandClick = () => {
        if (canReorder) return;
        setExpanded(!_expanded);
    };

    const handleChange = (prop: keyof TMainMenuItem, val: string) => {
        (item as any)[prop] = val;
        forceUpdate();
    }

    const handleRemove = (event) => {
        event.stopPropagation();
        if (items) {
            items.splice(items.indexOf(item), 1);
            refreshList?.();
        }
    }

    return (
        <div className={`${classes.card} PluginMainMenu-paper`}>
            <CardActionArea
                className={classes.cardHeader}
                onClick={handleExpandClick}
            >
                <p className={classes.cardTitle}>{item.title}</p>
                <CardActions disableSpacing className={classes.cardActions}>
                    {!canReorder && (
                        <IconButton
                            className={clsx(classes.expand, {
                                [classes.expandOpen]: expanded,
                            })}
                            aria-expanded={expanded}
                            aria-label="show more"
                        >
                            <ExpandMoreIcon />
                        </IconButton>
                    )}
                    <IconButton onClick={handleRemove}>
                        <HighlightOffIcon />
                    </IconButton>
                </CardActions>
            </CardActionArea>
            <Collapse in={expanded} timeout="auto" unmountOnExit>
                <div className={classes.cardContent}>
                    <TextField label="Title" variant="outlined"
                        value={item.title}
                        className={classes.field}
                        onChange={(e) => { handleChange('title', e.target.value) }}
                    />
                    <TextField label="Link" variant="outlined"
                        value={item.href}
                        className={classes.field}
                        onChange={(e) => { handleChange('href', e.target.value) }}
                    />
                    <TextField label="Columns" variant="outlined"
                        value={item.sublinkCols}
                        className={classes.field}
                        onChange={(e) => { handleChange('sublinkCols', e.target.value) }}
                    />
                    <TextField label="Width in px" variant="outlined"
                        value={item.width}
                        className={classes.field}
                        onChange={(e) => { handleChange('width', e.target.value) }}
                    />
                    <TextField
                        value={item.html}
                        label="Custom HTML"
                        multiline
                        rows={4}
                        variant="outlined"
                        className={classes.field}
                        onChange={(e) => { handleChange('html', e.target.value) }}
                    />
                    <div className={classes.sublinksList}>
                        <h3 className={classes.sublinksTitle}>Sublinks</h3>
                        {item.sublinks && item.sublinks.map((sl, slIndex) => {
                            return (
                                <div className={`${classes.sublinkItem} PluginMainMenu-paper`} >
                                    <TextField label="Sublink title" variant="outlined"
                                        value={sl.title}
                                        className={classes.subField}
                                        onChange={(e) => { if (item.sublinks) item.sublinks[slIndex].title = e.target.value; forceUpdate(); }}
                                    />
                                    <TextField label="Sublink href" variant="outlined"
                                        value={sl.href}
                                        className={classes.subField}
                                        onChange={(e) => { if (item.sublinks) item.sublinks[slIndex].href = e.target.value; forceUpdate(); }}
                                    />
                                    <IconButton onClick={(e) => {
                                        e.stopPropagation();
                                        if (item.sublinks) item.sublinks.splice(slIndex, 1);
                                        refreshList?.();
                                    }}>
                                        <HighlightOffIcon />
                                    </IconButton>
                                </div>
                            )
                        })}
                        <div className={`PluginMainMenu-paper ${classes.card}`}>
                            <MenuItem
                                className={classes.addBtn}
                                onClick={() => {
                                    if (!item.sublinks) item.sublinks = [];
                                    item.sublinks.push({});
                                    forceUpdate();
                                }}>
                                <AddIcon />
                            </MenuItem>
                        </div>
                    </div>
                </div>
            </Collapse>
        </div>
    )
}