@chakra-ui/react#Input TypeScript Examples

The following examples show how to use @chakra-ui/react#Input. 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: TextareaPanel.tsx    From openchakra with MIT License 6 votes vote down vote up
TextareaPanel = () => {
  const { setValueFromEvent } = useForm()

  const placeholder = usePropsSelector('placeholder')
  const size = usePropsSelector('size')
  const resize = usePropsSelector('resize')

  return (
    <>
      <FormControl label="Placeholder">
        <Input
          size="sm"
          value={placeholder || ''}
          type="text"
          name="placeholder"
          onChange={setValueFromEvent}
        />
      </FormControl>
      <SizeControl options={options} name="size" label="Size" value={size} />
      <FormControl label="Resize" htmlFor="resize">
        <Select
          name="resize"
          id="size"
          size="sm"
          value={resize || ''}
          onChange={setValueFromEvent}
        >
          <option>horizontal</option>
          <option>vertical</option>
          <option>none</option>
        </Select>
      </FormControl>
    </>
  )
}
Example #2
Source File: VideosPanel.tsx    From react-design-editor with MIT License 6 votes vote down vote up
function VideosPanel() {
  return (
    <>
      <div style={{ padding: '1rem 2rem' }}>
        <InputGroup>
          <InputLeftElement pointerEvents="none" children={<SearchIcon color="gray.300" />} />
          <Input style={{ background: '#fff' }} type="tel" placeholder="Search videos" />
        </InputGroup>
      </div>
    </>
  )
}
Example #3
Source File: RadioGroupPanel.tsx    From openchakra with MIT License 6 votes vote down vote up
RadioGroupPanel = () => {
  const { setValueFromEvent } = useForm()
  const spacing = usePropsSelector('spacing')

  return (
    <>
      <FormControl label="Spacing">
        <Input
          size="sm"
          value={spacing || ''}
          name="spacing"
          onChange={setValueFromEvent}
        />
      </FormControl>
      <SwitchControl label="Inline" name="isInline" />
    </>
  )
}
Example #4
Source File: AmountSelect.tsx    From rari-dApp with GNU Affero General Public License v3.0 6 votes vote down vote up
AmountInput = ({
  displayAmount,
  updateAmount,
  color,
  disabled = false
}: {
  displayAmount: string;
  updateAmount: (symbol: string) => any;
  color: string;
  disabled?: boolean;
}) => {
  return (
    <Input
      type="number"
      inputMode="decimal"
      fontSize="3xl"
      fontWeight="bold"
      variant="unstyled"
      _placeholder={{ color }}
      placeholder="0.0"
      value={displayAmount}
      color={color}
      onChange={(event) => updateAmount(event.target.value)}
      mr={4}
      disabled={disabled}
    />
  );
}
Example #5
Source File: TextControl.tsx    From openchakra with MIT License 6 votes vote down vote up
TextControl: React.FC<TextControlPropsType> = ({
  name,
  label,
  autoFocus = false,
  hasColumn = false,
  placeholder = '',
}) => {
  const { setValueFromEvent } = useForm()
  const value = usePropsSelector(name)

  return (
    <FormControl hasColumn={hasColumn} htmlFor={name} label={label}>
      <Input
        borderRadius="md"
        autoComplete="off"
        id={name}
        name={name}
        autoFocus={autoFocus}
        size="sm"
        value={value || ''}
        type="text"
        width={hasColumn ? '3rem' : '100%'}
        placeholder={placeholder}
        onChange={setValueFromEvent}
      />
    </FormControl>
  )
}
Example #6
Source File: TemplatesPanel.tsx    From react-design-editor with MIT License 6 votes vote down vote up
function TemplatesPanel() {
  return (
    <>
      <div style={{ padding: '1rem 2rem' }}>
        <InputGroup>
          <InputLeftElement pointerEvents="none" children={<SearchIcon color="gray.300" />} />
          <Input style={{ background: '#fff' }} type="tel" placeholder="Search templates" />
        </InputGroup>
      </div>
    </>
  )
}
Example #7
Source File: RegexInputWidget.tsx    From ke with MIT License 6 votes vote down vote up
RegexInput: React.FC<RegexpInputProps> = ({ onChange, regexp, ...props }) => {
  const handleChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      if ((!e.target.value || regexp.test(e.target.value)) && onChange) {
        onChange(e)
      } else {
        e.preventDefault()
      }
    },
    [onChange, regexp]
  )
  return <Input onChange={handleChange} {...props} />
}
Example #8
Source File: index.tsx    From formik-chakra-ui with MIT License 6 votes vote down vote up
InputControl: FC<InputControlProps> = React.forwardRef(
  (props: InputControlProps, ref: ForwardedRef<HTMLInputElement>) => {
    const { name, label, inputProps, ...rest } = props;
    const [field] = useField(name);

    return (
      <FormControl name={name} label={label} {...rest}>
        <Input {...field} id={name} {...inputProps} ref={ref} />
      </FormControl>
    );
  }
)
Example #9
Source File: ChildrenControl.tsx    From openchakra with MIT License 6 votes vote down vote up
ChildrenControl: React.FC = () => {
  const dispatch = useDispatch()
  const textInput = useRef<HTMLInputElement>(null)
  const focusInput = useSelector(getInputTextFocused)
  const { setValueFromEvent } = useForm()
  const children = usePropsSelector('children')
  const onKeyUp = (event: KeyboardEvent) => {
    if (event.keyCode === 13 && textInput.current) {
      textInput.current.blur()
    }
  }
  useEffect(() => {
    if (focusInput && textInput.current) {
      textInput.current.focus()
    } else if (focusInput === false && textInput.current) {
      textInput.current.blur()
    }
  }, [focusInput])

  return (
    <FormControl htmlFor="children" label="Text">
      <Input
        id="children"
        name="children"
        size="sm"
        value={children}
        type="text"
        onChange={setValueFromEvent}
        ref={textInput}
        onKeyUp={onKeyUp}
        onBlur={() => {
          dispatch.app.toggleInputText(false)
        }}
      />
    </FormControl>
  )
}
Example #10
Source File: UrlField.tsx    From calories-in with MIT License 6 votes vote down vote up
function UrlField({ canEdit, food }: Props) {
  const { register } = useFormContext<FoodForm>()

  return (
    <Flex minHeight={canEdit ? '200px' : undefined} flexDirection="column">
      {canEdit && (
        <Alert status="info" mb={3}>
          <AlertIcon color="teal.400" />
          Add a link will open a web page when the food is clicked. This is
          useful if you want to show a specific product.
        </Alert>
      )}

      <FormControl id="email">
        <Flex alignItems="center">
          <FormLabel mb={0} flexShrink={0}>
            Link:
          </FormLabel>
          {canEdit ? (
            <Input
              {...register('url')}
              placeholder="http://example.com"
              type="email"
            />
          ) : (
            <Link
              href={food?.url}
              target="_blank"
              noOfLines={1}
              color="teal.500"
            >
              {food?.url}
            </Link>
          )}
        </Flex>
      </FormControl>
    </Flex>
  )
}
Example #11
Source File: ChakraDateInput.tsx    From ke with MIT License 6 votes vote down vote up
ChakraDateInput = forwardRef<HTMLInputElement, ChakraDateInputProps>(
  ({ className, inputClassName, ...props }, ref) => (
    <InputGroup className={className}>
      <InputLeftElement
        zIndex="unset"
        fontSize="20px"
        width="44px"
        justifyContent="flex-start"
        pl="16px"
        pointerEvents="none"
      >
        <Icon as={Calendar} />
      </InputLeftElement>
      {/* Это обёртка */}
      {/* eslint-disable-next-line react/jsx-props-no-spreading */}
      <Input paddingStart="44px" className={inputClassName} {...props} ref={ref} />
    </InputGroup>
  )
)
Example #12
Source File: Name.tsx    From calories-in with MIT License 6 votes vote down vote up
function Name({
  variantIndex,
  mealForm,
  index,
  getMealNameInputRefById,
  ...rest
}: Props) {
  const dietFormActions = useDietFormActions()

  function onNameChange(event: ChangeEvent<HTMLInputElement>) {
    const { value } = event.target

    dietFormActions.updateMealForm(variantIndex, index, {
      name: value,
    })
  }

  return (
    <Flex alignItems="center" height="100%">
      <Input
        ref={getMealNameInputRefById(mealForm.fieldId)}
        placeholder="Meal name"
        onChange={onNameChange}
        autoComplete="off"
        width="80%"
        bg="white"
        fontWeight="medium"
        textColor="gray.800"
        size="md"
        value={mealForm.name}
        {...rest}
      />
    </Flex>
  )
}
Example #13
Source File: UserForm.tsx    From next-crud with MIT License 6 votes vote down vote up
UserForm = ({ initialValues, onSubmit }: IProps) => {
  const { register, formState, handleSubmit } = useForm<IFormValues>({
    defaultValues: initialValues,
    resolver: yupResolver(schema),
    mode: 'onChange',
  })

  return (
    <VStack
      as="form"
      onSubmit={handleSubmit(onSubmit)}
      spacing={4}
      width="100%"
    >
      <FormControl
        id="username"
        isInvalid={!!formState.errors.username?.message}
      >
        <FormLabel>Username</FormLabel>
        <Input name="username" ref={register} />
        <FormErrorMessage>
          {formState.errors.username?.message}
        </FormErrorMessage>
      </FormControl>
      <Button
        type="submit"
        colorScheme="blue"
        isLoading={formState.isSubmitting}
        disabled={!formState.isValid}
      >
        Submit
      </Button>
    </VStack>
  )
}
Example #14
Source File: SearchInput.tsx    From ksana.in with Apache License 2.0 6 votes vote down vote up
export function SearchInput({ searchText, onChangeSearch }: ISearchInputProps) {
  return (
    <Box width={{ base: '100%' }}>
      <Stack spacing={4}>
        <InputGroup>
          <Input
            size="lg"
            borderWidth="2px"
            borderColor="orange.400"
            name="searchText"
            placeholder="Cari tautan kamu"
            variant="filled"
            value={searchText}
            onChange={onChangeSearch}
          />
          <InputRightElement
            fontSize="2em"
            color="orange.400"
            mr="2"
            mt="1"
            children={<FiSearch />}
          />
        </InputGroup>
      </Stack>
    </Box>
  )
}
Example #15
Source File: DebounceInput.tsx    From ke with MIT License 6 votes vote down vote up
DebounceInput = forwardRef<HTMLInputElement, DebounceInputProps>(
  ({ value, onChange, debounceTimeout = 1000, element = Input, ...rest }, ref): JSX.Element => {
    const handleChange = useCallback(
      (e: ChangeEvent<HTMLInputElement>): void => {
        onChange(e.target.value)
      },
      [onChange]
    )

    // Это обёртка
    /* eslint-disable react/jsx-props-no-spreading */
    return (
      <BaseDebounceInput
        value={value}
        onChange={handleChange}
        debounceTimeout={debounceTimeout}
        resize="none"
        element={element}
        inputRef={ref}
        {...rest}
      />
    )
  }
) as (props: DebounceInputProps & { ref?: React.ForwardedRef<HTMLInputElement> }) => JSX.Element
Example #16
Source File: ImagesPanel.tsx    From react-design-editor with MIT License 6 votes vote down vote up
function ImagesPanel() {
  return (
    <>
      <div style={{ padding: '1rem 2rem' }}>
        <InputGroup>
          <InputLeftElement pointerEvents="none" children={<SearchIcon color="gray.300" />} />
          <Input style={{ background: '#fff' }} type="tel" placeholder="Search images" />
        </InputGroup>
      </div>
    </>
  )
}
Example #17
Source File: MintTo.tsx    From dope-monorepo with GNU General Public License v3.0 5 votes vote down vote up
MintTo = ({
  mintTo,
  setMintTo,
  mintAddress,
  setMintAddress,
}: {
  mintTo: boolean;
  setMintTo: (shouldMintTo: boolean) => void;
  mintAddress: string | undefined;
  setMintAddress: (value: string) => void;
}) => {
  const { account } = useWeb3React();
  const isContract = useIsContract(account);

  useEffect(() => {
    if (isContract) {
      setMintTo(true);
    }
  }, [isContract, setMintTo]);

  if (!mintTo && !isContract) {
    return <Button onClick={() => setMintTo(true)}>Send to a friend?</Button>;
  }

  return (
    <PanelContainer justifyContent="flex-start" css={css`max-height:180px;`}>
      <PanelTitleBarFlex onClick={() => setMintTo(false)}>
        <span>Send to Different Address</span>
        <Image
          src="/images/icon/circle-clear-input.svg"
          alt="close"
          width="16px"
          marginRight="8px"
          cursor="pointer"
        />
      </PanelTitleBarFlex>
      <PanelBody>
        {!isContract && <p>Send to a friend, or another wallet?</p>}
        {isContract && (
          <p>
            It looks like you are using a contract wallet. Please set the Optimism address you want these items sent to.
          </p>
        )}
        <Input
          placeholder="0x…"
          onChange={(e: React.ChangeEvent<HTMLInputElement>) => setMintAddress(e.target.value)}
          value={mintAddress}
        />
      </PanelBody>
    </PanelContainer>
  );
}
Example #18
Source File: TextPanel.tsx    From react-design-editor with MIT License 5 votes vote down vote up
function TextPanel() {
  const { addObject } = useCoreHandler()
  const addHeading = () => {
    const options = {
      type: 'text',
      text: 'Add a heading',
      fontSize: 32,
      width: 320,
      fontWeight: 700,
      fontFamily: 'Lexend',
      textAlign: 'center',
    }
    addObject(options)
  }

  const addSubheading = () => {
    const options = {
      type: 'text',
      text: 'Add a subheading',
      fontSize: 24,
      width: 320,
      fontWeight: 500,
      fontFamily: 'Lexend',
      textAlign: 'center',
    }
    addObject(options)
  }

  const addTextBody = () => {
    const options = {
      type: 'text',
      text: 'Add a little bit of body text',
      fontSize: 18,
      width: 320,
      fontWeight: 300,
      fontFamily: 'Lexend',
      textAlign: 'center',
    }
    addObject(options)
  }
  return (
    <>
      <div className="panel-text" style={{ padding: '1rem 1.5rem' }}>
        <InputGroup>
          <InputLeftElement pointerEvents="none" children={<SearchIcon color="gray.600" />} />
          <Input style={{ background: '#fff' }} type="tel" placeholder="Search text" />
        </InputGroup>
        <div className="label">Click text to add to page</div>
        <div className="add-text-items">
          <div onClick={addHeading} className="add-text-item add-heading">
            Add a heading
          </div>
          <div onClick={addSubheading} className="add-text-item add-subheading">
            Add a subheading
          </div>
          <div onClick={addTextBody} className="add-text-item add-body-text">
            Add a litle bit of body text
          </div>
        </div>
      </div>
    </>
  )
}
Example #19
Source File: index.tsx    From engine with MIT License 5 votes vote down vote up
Details = () => (
  <AccordionItem>
    <h2>
      <AccordionButton _expanded={{ bg: "gray.300", color: "white" }}>
        <Box flex="1" textAlign="left">
          Details
        </Box>
        <AccordionIcon />
      </AccordionButton>
    </h2>
    <AccordionPanel pb={4}>
      <InputGroup size="sm">
        <InputLeftAddon children="Name" w="24" />
        <Input defaultValue="DoThingsFoo" />
      </InputGroup>
      <InputGroup size="sm">
        <InputLeftAddon children="File path" w="24" />
        <Input defaultValue="src/producers/domain/computation.ts" />
      </InputGroup>
      <InputGroup size="sm">
        <InputLeftAddon children="Author" w="24" />
        <Input defaultValue="John Doe" isReadOnly />
      </InputGroup>
      <InputGroup size="sm">
        <InputLeftAddon children="Created on" w="24" />
        <Input defaultValue="19/02/2022" isReadOnly />
      </InputGroup>
      <InputGroup size="sm">
        <InputLeftAddon children="Version" w="24" />
        <Select placeholder="Select a version">
          <option value="option1" selected>
            V2 22/02/2022 14:23 - John a2a2b227a7 (latest)
          </option>
          <option value="option2">V1 20/02/2022 13:23 Jane 9c32e516af</option>
        </Select>
      </InputGroup>
      <InputGroup size="sm">
        <InputLeftAddon children="Description" w="24" />
        <Textarea defaultValue="Does what it needs to do in terms of computation"></Textarea>
      </InputGroup>
    </AccordionPanel>
  </AccordionItem>
)
Example #20
Source File: ColorPicker.tsx    From dope-monorepo with GNU General Public License v3.0 5 votes vote down vote up
ColorPicker = ({ colors, selectedColor, changeCallback }: ColorPickerProps) => {
  const [color, setColor] = useState(selectedColor ?? colors[0]);

  const handleColorInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    handleColorChange(e.target.value);
  };

  const handleColorChange = (color: string) => {
    setColor(color);
    if (typeof changeCallback === 'function') changeCallback(color);
  };

  return (
    <>
      <Popover variant="picker">
        <PopoverTrigger>
          <Button
            aria-label={color}
            background={color}
            height="64px"
            width="64px"
            padding={0}
            minWidth="unset"
            borderRadius={3}
          ></Button>
        </PopoverTrigger>
        <PopoverContent width="196px">
          <PopoverArrow bg={color} />
          <PopoverCloseButton color="white" />
          <PopoverHeader
            height="100px"
            backgroundColor={color}
            borderTopLeftRadius={5}
            borderTopRightRadius={5}
            color="white"
          >
            <Center height="100%">{color}</Center>
          </PopoverHeader>
          <PopoverBody height="96px">
            <SimpleGrid columns={5} spacing={2}>
              {colors.map(c => (
                <Button
                  key={c}
                  aria-label={c}
                  background={c}
                  height="32px"
                  width="32px"
                  padding={0}
                  minWidth="unset"
                  borderRadius={3}
                  _hover={{ background: c }}
                  onClick={() => {
                    handleColorChange(c);
                  }}
                ></Button>
              ))}
            </SimpleGrid>
            <Input
              borderRadius={3}
              marginTop={3}
              placeholder="red.100"
              size="sm"
              value={color}
              onChange={handleColorInputChange}
            />
          </PopoverBody>
        </PopoverContent>
      </Popover>
    </>
  );
}
Example #21
Source File: ImagePanel.tsx    From openchakra with MIT License 5 votes vote down vote up
ImagePanel = () => {
  const { setValueFromEvent } = useForm()

  const src = usePropsSelector('src')
  const fallbackSrc = usePropsSelector('fallbackSrc')
  const alt = usePropsSelector('alt')
  const htmlHeight = usePropsSelector('htmlHeight')
  const htmlWidth = usePropsSelector('htmlWidth')

  return (
    <>
      <FormControl label="Source" htmlFor="src">
        <Input
          placeholder="Image URL"
          value={src || ''}
          size="sm"
          name="src"
          onChange={setValueFromEvent}
        />
      </FormControl>

      <FormControl label="Fallback Src" htmlFor="fallbackSrc">
        <Input
          placeholder="Image URL"
          value={fallbackSrc || ''}
          size="sm"
          name="fallbackSrc"
          onChange={setValueFromEvent}
        />
      </FormControl>

      <FormControl label="Alt" htmlFor="alt">
        <Input
          value={alt || ''}
          size="sm"
          name="alt"
          onChange={setValueFromEvent}
        />
      </FormControl>

      <FormControl label="Html height" htmlFor="htmlHeight">
        <Input
          value={htmlHeight || ''}
          size="sm"
          name="htmlHeight"
          onChange={setValueFromEvent}
        />
      </FormControl>

      <FormControl label="Html width" htmlFor="htmlWidth">
        <Input
          value={htmlWidth || ''}
          size="sm"
          name="htmlWidth"
          onChange={setValueFromEvent}
        />
      </FormControl>
    </>
  )
}
Example #22
Source File: Content.tsx    From calories-in with MIT License 5 votes vote down vote up
function Content({ title, onClose, initialRef, variantFormIndex }: Props) {
  const { register } = useFormContext()
  const nameRegister = register('name')
  const nameInputRef = useMergeRefs(nameRegister.ref, initialRef)

  const onSubmit = useSubmitVariantNameForm({
    variantFormIndex,
    onComplete: onClose,
  })

  const { errorMessage, isInvalid } = useFormError('name')

  useSelectInputText(initialRef)

  return (
    <form onSubmit={onSubmit}>
      <ModalContent>
        <ModalHeader>{title}</ModalHeader>
        <ModalCloseButton />

        <ModalBody>
          <FormControl isInvalid={isInvalid}>
            <FormLabel>Name</FormLabel>
            <Input
              autoComplete="off"
              {...nameRegister}
              ref={nameInputRef}
              focusBorderColor={isInvalid ? 'red.500' : undefined}
              placeholder="Enter name"
            />
            <Collapse animateOpacity={true} in={Boolean(errorMessage)}>
              <Box minHeight="21px">
                <FormErrorMessage>{errorMessage}</FormErrorMessage>
              </Box>
            </Collapse>
          </FormControl>
        </ModalBody>

        <ModalFooter>
          <Button mr={3} onClick={onClose}>
            Close
          </Button>
          <Button
            type="submit"
            colorScheme="teal"
            variant="solid"
            onClick={onSubmit}
          >
            Rename
          </Button>
        </ModalFooter>
      </ModalContent>
    </form>
  )
}
Example #23
Source File: Profile.tsx    From dope-monorepo with GNU General Public License v3.0 5 votes vote down vote up
Profile = () => {
  const [section, setSection] = useQueryParam('section', SECTIONS[0]);
  const [searchValue, setSearchValue] = useQueryParam('q', '');
  const debouncedSearchValue = useDebounce<string>(searchValue, 250);

  const handleSearchChange = (event: ChangeEvent<HTMLInputElement>) => {
    const value = event.target.value;
    setSearchValue(value);
  };

  return (
    <>
      <Stack
        margin="0"
        spacing="8px"
        width="100%"
        padding="16px"
        background="white"
        borderBottom="2px solid black"
        direction={['column', 'column', 'row']}
      >
        <InputGroup>
          <Input
            className="search"
            placeholder="Search…"
            size="sm"
            border="2px solid black"
            borderRadius="4px"
            onChange={handleSearchChange}
            value={searchValue}
            _focus={{ boxShadow: '0' }}
          />
          {searchValue !== '' && (
            <InputRightElement height="100%">
              <Image
                width="16px"
                src="/images/icon/circle-clear-input.svg"
                alt="Search"
                onClick={() => setSearchValue('')}
                cursor="pointer"
              />
            </InputRightElement>
          )}
        </InputGroup>
      </Stack>
      <Accordion
        allowToggle
        defaultIndex={SECTIONS.findIndex(val => val === section)}
        onChange={idx => {
          if (idx == -1) return;
          const sectionIdx = Array.isArray(idx) ? idx[0] : idx;
          setSection(SECTIONS[sectionIdx]);
        }}
      >
        <Section>
          <Hustlers searchValue={debouncedSearchValue} />
        </Section>
        <Section>
          <Gear searchValue={debouncedSearchValue} />
        </Section>
        <Section>
          <Dopes searchValue={debouncedSearchValue} />
        </Section>
      </Accordion>
    </>
  );
}
Example #24
Source File: InputSuggestion.tsx    From openchakra with MIT License 5 votes vote down vote up
InputSuggestion: React.FC<FormControlPropType> = ({
  handleChange,
  name,
  value,
  children,
}) => {
  const { setValue } = useForm()
  const [isFocus, setIsFocus] = useState(false)

  return (
    <Combobox
      openOnFocus
      onSelect={item => {
        setValue(name, item)
      }}
    >
      <ComboboxInput
        onFocus={() => setIsFocus(true)}
        id={name}
        value={ltrim(value)}
        name={name}
        onChange={handleChange}
        as={Input}
        aria-labelledby={name}
        size="sm"
        autoComplete="off"
      />

      {isFocus && (
        <ComboboxPopover>
          <ComboboxList
            style={{ maxHeight: 200, overflow: 'scroll' }}
            aria-labelledby={name}
          >
            {children}
          </ComboboxList>
        </ComboboxPopover>
      )}
    </Combobox>
  )
}
Example #25
Source File: LocalPortField.tsx    From bluebubbles-server with Apache License 2.0 5 votes vote down vote up
LocalPortField = ({ helpText }: LocalPortFieldProps): JSX.Element => {
    const dispatch = useAppDispatch();

    const port: number = useAppSelector(state => state.config.socket_port) ?? 1234;
    const [newPort, setNewPort] = useState(port);
    const [portError, setPortError] = useState('');
    const hasPortError: boolean = (portError?? '').length > 0;

    useEffect(() => { setNewPort(port); }, [port]);

    /**
     * A handler & validator for saving a new port.
     *
     * @param theNewPort - The new port to save
     */
    const savePort = (theNewPort: number): void => {
        // Validate the port
        if (theNewPort < 1024 || theNewPort > 65635) {
            setPortError('Port must be between 1,024 and 65,635');
            return;
        } else if (theNewPort === port) {
            setPortError('You have not changed the port since your last save!');
            return;
        }

        dispatch(setConfig({ name: 'socket_port', value: theNewPort }));
        if (hasPortError) setPortError('');
        showSuccessToast({
            id: 'settings',
            duration: 4000,
            description: 'Successfully saved new port! Restarting Proxy & HTTP services...'
        });
    };

    return (
        <FormControl isInvalid={hasPortError}>
            <FormLabel htmlFor='socket_port'>Local Port</FormLabel>
            <Flex flexDirection='row' justifyContent='flex-start' alignItems='center'>
                <Input
                    id='socket_port'
                    type='number'
                    maxWidth="5em"
                    value={newPort}
                    onChange={(e) => {
                        if (hasPortError) setPortError('');
                        setNewPort(Number.parseInt(e.target.value));
                    }}
                />
                <IconButton
                    ml={3}
                    verticalAlign='top'
                    aria-label='Save port'
                    icon={<AiOutlineSave />}
                    onClick={() => savePort(newPort)}
                />
            </Flex>
            {!hasPortError ? (
                <FormHelperText>
                    {helpText ?? 'Enter the local port for the socket server to run on'}
                </FormHelperText>
            ) : (
                <FormErrorMessage>{portError}</FormErrorMessage>
            )}
        </FormControl>
    );
}
Example #26
Source File: index.tsx    From dope-monorepo with GNU General Public License v3.0 5 votes vote down vote up
PlayerPanel = (props: {player: Player}) => {
    const player = props.player;

    return (
        <Accordion>
            <AccordionItem>
                <h2>
                    <AccordionButton>
                        <Box flex='1' textAlign='left'>
                        Basic info
                        </Box>
                        <AccordionIcon />
                    </AccordionButton>
                </h2>
                <AccordionPanel pb={4}>
                    <InputGroup size="sm">
                        <InputLeftAddon children='Name' />
                        <Input onChange={(e) => player.name = e.target.value} placeholder={player.name} />
                    </InputGroup>
                    <div>
                        <Position object={player} />
                    </div>
                </AccordionPanel>
            </AccordionItem>
            <AccordionItem>
                <h2>
                    <AccordionButton>
                        <Box flex='1' textAlign='left'>
                        Quests
                        </Box>
                        <AccordionIcon />
                    </AccordionButton>
                </h2>
                <AccordionPanel pb={4}>
                    {player.questManager.quests.map((quest, i) => {
                        <Text>
                            {quest.name}: {quest.description}
                        </Text>
                    })}
                </AccordionPanel>
            </AccordionItem>
        </Accordion>
    )
}
Example #27
Source File: index.tsx    From nextjs-hasura-boilerplate with MIT License 5 votes vote down vote up
MyAccountPageComponent = ({ user }) => {
  const [name, setName] = useState(user.name);
  const [session] = useSession();
  const [updateUser, { loading: updateUserFetching, error: updateUserError }] =
    useUpdateUserMutation();

  const handleSubmit = () => {
    updateUser({
      variables: {
        userId: session.id,
        name,
      },
    });
  };

  const errorNode = () => {
    if (!updateUserError) {
      return false;
    }

    return (
      <Alert status="error">
        <AlertIcon />
        <AlertTitle>{updateUserError}</AlertTitle>
        <CloseButton position="absolute" right="8px" top="8px" />
      </Alert>
    );
  };

  return (
    <Stack spacing={8}>
      <Heading>My Account</Heading>
      {errorNode()}
      <Box shadow="lg" rounded="lg" p={4}>
        <Stack spacing={4}>
          <FormControl isRequired>
            <FormLabel htmlFor="name">Name</FormLabel>
            <Input
              type="text"
              id="name"
              value={name}
              onChange={(e: FormEvent<HTMLInputElement>) =>
                setName(e.currentTarget.value)
              }
              isDisabled={updateUserFetching}
            />
          </FormControl>
          <FormControl>
            <Button
              loadingText="Saving..."
              onClick={handleSubmit}
              isLoading={updateUserFetching}
              isDisabled={!name.trim()}
            >
              Save
            </Button>
          </FormControl>
        </Stack>
      </Box>
    </Stack>
  );
}
Example #28
Source File: AddAppDomain.tsx    From ledokku with MIT License 5 votes vote down vote up
AddAppDomain = ({ appId, appDomainsRefetch }: AddDomainProps) => {
  const toast = useToast();
  const [addDomainMutation] = useAddDomainMutation();
  const [showAddForm, setShowAddForm] = useState(false);

  const formik = useFormik<{ domainName: string }>({
    initialValues: {
      domainName: '',
    },
    validateOnChange: true,
    validationSchema: addAppDomainYupSchema,
    onSubmit: async (values) => {
      try {
        await addDomainMutation({
          variables: {
            input: {
              appId,
              domainName: values.domainName,
            },
          },
        });

        await appDomainsRefetch();
        toast.success('Domain added successfully');

        formik.resetForm();
      } catch (error) {
        toast.error(error.message);
      }
    },
  });

  return (
    <>
      {!showAddForm ? (
        <Button variant="outline" onClick={() => setShowAddForm(true)}>
          Add custom domain
        </Button>
      ) : (
        <form onSubmit={formik.handleSubmit}>
          <FormControl
            id="domainName"
            isInvalid={Boolean(
              formik.errors.domainName && formik.touched.domainName
            )}
          >
            <Input
              placeholder="www.mydomain.com"
              name="domainName"
              value={formik.values.domainName}
              onChange={formik.handleChange}
            />
            <FormErrorMessage>{formik.errors.domainName}</FormErrorMessage>
          </FormControl>

          <ButtonGroup mt="4" spacing="2">
            <Button isLoading={formik.isSubmitting} type="submit">
              Save
            </Button>
            <Button
              variant="outline"
              disabled={formik.isSubmitting}
              onClick={() => setShowAddForm(false)}
            >
              Cancel
            </Button>
          </ButtonGroup>
        </form>
      )}
    </>
  );
}
Example #29
Source File: ui.tsx    From eth-dapps-nextjs-boiletplate with MIT License 5 votes vote down vote up
// REF: https://stackoverflow.com/questions/55757761/handle-an-input-with-react-hooks
export function useInput(isReadOnly: boolean) {
    const [value, setValue] = useState('')
    const input = <Input value={value} isReadOnly={isReadOnly} onChange={e => setValue(e.target.value)} />
    return [value, input]
}