react#ChangeEvent TypeScript Examples

The following examples show how to use react#ChangeEvent. 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: NativeSelect.stories.tsx    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
Basic = () => {
  const [value, setValue] = useState<string | null>(null);

  return (
    <Layout>
      <NativeSelect
        value={value}
        onChange={({ target }: ChangeEvent<HTMLSelectElement>) =>
          setValue(target.value)
        }
      >
        {createOptions(items)}
      </NativeSelect>
      <NativeSelect
        value={value}
        onChange={({ target }: ChangeEvent<HTMLSelectElement>) =>
          setValue(target.value)
        }
        disabled
      >
        {createOptions(items)}
      </NativeSelect>
    </Layout>
  );
}
Example #2
Source File: AddressInput.tsx    From anthem with Apache License 2.0 6 votes vote down vote up
render(): JSX.Element {
    return (
      <form
        data-cy="dashboard-address-input-form"
        onSubmit={(event: ChangeEvent<HTMLFormElement>) => {
          event.preventDefault();
          this.setAddress();
        }}
      >
        <SearchInput
          onBlur={this.props.onBlur}
          onFocus={this.props.onFocus}
          assignRef={this.props.assignInputRef}
          data-cy="dashboard-address-input"
          value={this.state.value}
          onChange={this.handleEnterAddress}
          placeholder={this.props.tString(
            "Search address or transaction hash...",
          )}
          onSubmit={this.setAddress}
          style={{
            width: this.props.isDesktop
              ? this.props.inputWidth || 375
              : undefined,
          }}
        />
      </form>
    );
  }
Example #3
Source File: validation.ts    From DevC-benin-jobs with GNU General Public License v3.0 6 votes vote down vote up
useFormInput = (
  initialValue: string = '',
): IUseFormInputReturnProps => {
  const [value, setValue] = useState<string>(initialValue);
  const [error, setError] = useState<string>('');
  const [isValid, setIsValid] = useState<boolean>(value.length > 0);
  const handleUserInput = (min?: number, max?: number) => (
    event: ChangeEvent<HTMLInputElement>,
  ): void => {
    const {
      target: { name, value },
    } = event;
    const isValid = validateInput(name, value);
    if (max && value.length > max) return;
    if (
      name.toLowerCase() === inputNames.password ||
      name.toLowerCase() === inputNames.email
    ) {
      setValue(value);
      setIsValid(isValid);
      setError(!isValid ? assignError(name) : '');
      return;
    }
    if (!isValid && value !== '') return;
    setValue(value);
    setIsValid(validateLength(value, min, max));
  };
  return { value, setValue, handleUserInput, error, setError, isValid };
}
Example #4
Source File: index.tsx    From pola-web with MIT License 6 votes vote down vote up
FormInput: React.FC<IFormInput> = ({
  value,
  type = 'text',
  name = `input_${getGuid()}`,
  placeholder,
  onChange,
}) => {
  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    if (onChange) {
      onChange(e.currentTarget.value);
    }
  };

  return (
    <InputContainer>
      <StyledInput
        name={name}
        type={type}
        value={value}
        disabled={!onChange}
        placeholder={placeholder}
        onChange={handleChange}
      />
    </InputContainer>
  );
}
Example #5
Source File: LanguageDropDown.tsx    From crowdsource-dataplatform with MIT License 6 votes vote down vote up
LanguageDropDown = ({ selectedLanguage, updateSelectedLanguage }: LanguageDropDownProps) => {
  const { t } = useTranslation();

  const handleChange = (e: ChangeEvent<HTMLSelectElement>) => {
    const value = e.target.value;
    updateSelectedLanguage(value);
  };

  return (
    <Row>
      <Col data-testid="LanguageDropDown">
        <div className="contributionLanguage">
          <Form.Group
            controlId="languageDropDown"
            className="d-flex flex-column flex-md-row align-items-md-center"
          >
            <Form.Label className={`${styles.label} mb-0 me-md-2`}>
              {t('selectDropDownLanguagePrompt')}:
            </Form.Label>
            <Form.Select
              data-testid="SelectDropDownLanguage"
              value={selectedLanguage}
              aria-label="Your Language"
              className={`${styles.languageDropdown} mt-1 mt-md-0`}
              name="languageDropDown"
              onChange={handleChange as any}
            >
              {CONTRIBUTION_LANGUAGE?.map(locale => (
                <option key={locale} value={RAW_LANGUAGES[locale]}>
                  {DISPLAY_LANGUAGES[locale]}
                </option>
              ))}
            </Form.Select>
          </Form.Group>
        </div>
      </Col>
    </Row>
  );
}
Example #6
Source File: index.tsx    From redux-with-domain with MIT License 6 votes vote down vote up
DatasetField: FC<Props> = props => {
  const fields = useSelector((state: any) =>
    module.selectors.getDatasetFields(state)
  )

  const dispatch = useDispatch()
  const onSearch = useCallback(
    (event: ChangeEvent<HTMLInputElement>) => {
      dispatch(module.actions.updateFilter(event.target.value))
    },
    [module, dispatch]
  )

  return (
    <div className="dataset-field">
      <div className="title">数据集字段</div>
      <div className="list">
        <Input
          className="search"
          size="small"
          placeholder="搜索字段"
          onChange={onSearch}
        />
        {fields.map((field, index: number) => {
          return <FieldItem field={field} key={field.id} />
        })}
      </div>
    </div>
  )
}
Example #7
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 #8
Source File: index.tsx    From dockerstats with Apache License 2.0 6 votes vote down vote up
onChange = (e: ChangeEvent<HTMLInputElement>) => {
    const input = e.target.value
    const parts = this.state.input.split('/')
    let error = true
    if (parts.length === 2) {
      error = false
    }
    this.setState(() => ({ input, error }))
  }
Example #9
Source File: FontSize.tsx    From dnde with GNU General Public License v3.0 6 votes vote down vote up
FontSize = () => {
  const [visible, path] = useVisibility({ attribute: ATTRIBUTE });
  const { mjmlJson, setMjmlJson } = useEditor();
  const { getValue } = useValue({ path, visible, attribute: ATTRIBUTE });

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    let value = e.currentTarget.value;
    if (path && visible) {
      let json = {};
      let element = _.get(mjmlJson, path);
      element.attributes[ATTRIBUTE] = value;
      json = _.set(mjmlJson, path, element);
      setMjmlJson({ ...json });
    }
  };

  return visible ? (
    <Form.Item label="FontSize">
      <Input onChange={handleChange} value={getValue()} />
    </Form.Item>
  ) : null;
}
Example #10
Source File: FloatingLabelInput.tsx    From remix-hexagonal-architecture with MIT License 6 votes vote down vote up
FloatingLabelInput = forwardRef<
  FloatingLabelInputRef,
  FloatingLabelInputProps
>(function FloatingLabelInput(props, ref) {
  const { name, label, errorMessage, inputProps } = props;

  const inputRef = useRef<HTMLInputElement | null>(null);
  const [value, setValue] = useState("");
  const isStickyLabel = value.length > 0;

  useImperativeHandle(ref, () => ({
    focus: () => inputRef.current?.focus(),
    clear: () => setValue(""),
  }));

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    const newValue = e.target.value;
    setValue(newValue);
  };

  return (
    <label className="group">
      <div className="relative">
        <input
          {...inputProps}
          ref={(node) => {
            inputRef.current = node;
            props.inputRef?.(node);
          }}
          name={name}
          value={value}
          onChange={handleChange}
          className={classNames(
            "block w-full rounded border bg-transparent px-4 pt-6 pb-2",
            "border-2 border border-dark focus:border-primary",
            "text-base text-lighter transition-colors",
            {
              "border-danger": !!errorMessage,
            },
            inputProps.className
          )}
        />
        <span
          className={classNames(
            "absolute left-4 -translate-y-1/2 font-bold",
            "transition-all group-focus-within:top-4 group-focus-within:text-xs",
            {
              "top-1/2": !isStickyLabel,
              "top-4 text-xs": isStickyLabel,
              "text-danger": !!errorMessage,
            }
          )}
        >
          {label}
        </span>
      </div>

      {errorMessage && (
        <span className="block px-4 pt-4 text-sm text-danger" role="alert">
          <span aria-hidden className="inline-block w-[2ch]">
            ?
          </span>{" "}
          {errorMessage}
        </span>
      )}
    </label>
  );
})
Example #11
Source File: Checkbox.tsx    From hub with Apache License 2.0 6 votes vote down vote up
CheckBox = (props: Props) => {
  const handleOnChange = (e: ChangeEvent<HTMLInputElement>) => {
    if (props.onChange) {
      props.onChange(e);
    }
  };

  const id = `${props.device}-${props.name}-${props.value}`;

  return (
    <div className={`form-check me-sm-2 mb-2 ${props.className}`}>
      <input
        type="checkbox"
        className={`form-check-input ${styles.input}`}
        name={props.name}
        value={props.value}
        id={id}
        onChange={handleOnChange}
        checked={props.checked}
        aria-checked={props.checked}
        disabled={props.disabled}
        tabIndex={0}
      />
      <label
        className={`form-check-label ${styles.label} ${props.labelClassName}`}
        htmlFor={id}
        data-testid="checkboxLabel"
      >
        <div className="d-flex align-items-baseline mw-100">
          {props.icon && <span className={`me-2 position-relative ${styles.icon}`}>{props.icon}</span>}
          <span className="d-inline-block text-truncate">{props.label}</span>
          {!isUndefined(props.legend) && <small className="ps-1">({props.legend})</small>}
        </div>
      </label>
    </div>
  );
}
Example #12
Source File: AsyncSelect.tsx    From one-platform with MIT License 5 votes vote down vote up
AsyncSelect = ({
  render,
  onSelect,
  customFilter,
  onTypeaheadInputChanged,
  ...selectProps
}: Props): JSX.Element => {
  const [isOpen, setIsOpen] = useToggle();
  const [options, setOptions] = useState<ReactElement<any, string | JSXElementConstructor<any>>[]>(
    []
  );

  const [typeAhead, setTypeAhead] = useState('');

  useEffect(() => {
    if (!isOpen) {
      setTypeAhead('');
      setOptions([]);
      return;
    }

    setOptions(LOADING);
    render(typeAhead)
      .then((loadedOptions) => {
        setOptions(loadedOptions);
      })
      .catch(() => {
        setOptions([
          <SelectOption
            key="option-error"
            value="Failed to fetch request"
            isPlaceholder
            isDisabled
          />,
        ]);
      });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [typeAhead, isOpen]);

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const onPfeSelect = (...args: any) => {
    // eslint-disable-next-line prefer-spread
    onSelect?.apply(null, args);
    setIsOpen.off();
  };

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const onPfeTypeAheadChange = (value: string) => {
    setTypeAhead(value);
    // eslint-disable-next-line prefer-spread
    if (onTypeaheadInputChanged) onTypeaheadInputChanged(value);
  };

  const onFilter = (a: ChangeEvent<HTMLInputElement> | null, value: string) => {
    if (!value) {
      return options;
    }

    if (!customFilter) return options;

    return options.filter((child) => customFilter(child));
  };

  return (
    <PfeSelect
      {...selectProps}
      onSelect={onPfeSelect}
      isOpen={isOpen}
      onToggle={setIsOpen.toggle}
      onTypeaheadInputChanged={onPfeTypeAheadChange}
      onFilter={customFilter && onFilter}
    >
      {options}
    </PfeSelect>
  );
}
Example #13
Source File: NotificationContent.tsx    From anchor-web-app with Apache License 2.0 5 votes vote down vote up
function NotificationContentBase({ className }: NotificationContentProps) {
  const { liquidationAlert, updateLiquidationAlert } = useJobs();

  const { focusVisible, ...switchClasses } = useSwitchStyle();
  const sliderClasses = useSliderStyle();

  const testNotifications = useCallback(() => {
    new Notification('Anchor Borrow Usage Notification', {
      body: 'Notifications have been enabled.',
    });
  }, []);

  return (
    <div className={className}>
      <h2>
        <NotificationsNone />
        <IconSpan>
          Notification{' '}
          <InfoTooltip>
            Currently notifications only support desktop browsers and require
            the webapp to be open in a tab
          </InfoTooltip>
        </IconSpan>
      </h2>

      <div className="switch">
        <p>Anchor Borrow Usage</p>
        <Switch
          focusVisibleClassName={focusVisible}
          classes={switchClasses}
          checked={liquidationAlert.enabled}
          onChange={({ target }: ChangeEvent<HTMLInputElement>) =>
            updateLiquidationAlert({
              ...liquidationAlert,
              enabled: target.checked,
            })
          }
        />
      </div>

      {liquidationAlert.enabled && (
        <Slider
          classes={sliderClasses}
          valueLabelDisplay="on"
          valueLabelFormat={valueLabelFormat}
          marks={sliderMarks}
          value={liquidationAlert.ratio * 100}
          min={notificationMin}
          max={notificationMax}
          onChange={(_: any, newValue: number) => {
            updateLiquidationAlert({
              ...liquidationAlert,
              ratio: newValue / 100,
            });
          }}
        />
      )}

      {liquidationAlert.enabled && (
        <ActionButton
          className="test-notifications"
          onClick={testNotifications}
        >
          Test Notifications
        </ActionButton>
      )}
    </div>
  );
}
Example #14
Source File: ConfigEditor.tsx    From grafana-kdb-datasource-ws with Apache License 2.0 5 votes vote down vote up
onHostChange = (event: ChangeEvent<HTMLInputElement>) => {
    const { onOptionsChange, options } = this.props;
    const jsonData = {
      ...options.jsonData,
      host: event.target.value,
    };
    onOptionsChange({ ...options, jsonData });
  };
Example #15
Source File: Room.tsx    From slate-yjs-example with MIT License 5 votes vote down vote up
Room: React.FC<RoomProps> = ({ slug, removeRoom }) => {
  const [users, setUsers] = useState<User[]>([createUser(), createUser()]);
  const [roomSlug, setRoomSlug] = useState<string>(slug);
  const [isRemounted, setRemountState] = useState(false);

  const remount = debounce(() => {
    setRemountState(true);
    setTimeout(setRemountState, 50, false);
  }, 300);

  const changeSlug = (e: ChangeEvent<HTMLInputElement>) => {
    setRoomSlug(e.target.value);
    remount();
  };

  const addUser = () => setUsers((users) => users.concat(createUser()));

  const removeUser = (userId: string) =>
    setUsers((users) => users.filter((u: User) => u.id !== userId));

  return (
    <RoomWrapper>
      <Title>
        <H4>Document slug:</H4>
        <Input type="text" value={roomSlug} onChange={changeSlug} />
        <Button type="button" onClick={addUser}>
          Add random user
        </Button>
        <Button type="button" onClick={removeRoom}>
          Remove Room
        </Button>
      </Title>
      <Grid>
        {users.map((user: User) =>
          isRemounted ? null : (
            <Client
              {...user}
              slug={roomSlug}
              key={user.id}
              removeUser={removeUser}
            />
          )
        )}
      </Grid>
    </RoomWrapper>
  );
}
Example #16
Source File: Optimize.tsx    From sc2-planner with MIT License 5 votes vote down vote up
onChangeTextArea = (e: ChangeEvent<HTMLTextAreaElement>, itemShortName: string): void => {
        const newValue = e.target.value
        this.props.updateOptimize(itemShortName, newValue)
    }
Example #17
Source File: SharedComponents.tsx    From anthem with Apache License 2.0 5 votes vote down vote up
TextInput = (props: {
  "data-cy": string;
  label?: string;
  autoFocus?: boolean;
  placeholder: string;
  value: string;
  type?: string;
  style?: React.CSSProperties;
  onSubmit?: () => void;
  onFocus?: () => void;
  onBlur?: () => void;
  assignRef?: (ref: HTMLInputElement) => void;
  onChange: (value: string) => void;
}) => (
  <View>
    {props.label && (
      <p
        style={{
          margin: 0,
          fontSize: 10,
          marginBottom: 1,
          marginLeft: 1,
        }}
      >
        {props.label}
      </p>
    )}
    <input
      dir="auto"
      spellCheck={false}
      style={props.style}
      value={props.value}
      data-cy={props["data-cy"]}
      type={props.type || "text"}
      onFocus={props.onFocus}
      onBlur={props.onBlur}
      onSubmit={props.onSubmit}
      autoFocus={props.autoFocus}
      ref={props.assignRef}
      placeholder={props.placeholder}
      onChange={(event: ChangeEvent<HTMLInputElement>) => {
        props.onChange(event.target.value);
      }}
      className={`${Classes.INPUT} .modifier :modifier`}
    />
  </View>
)
Example #18
Source File: NativeList.tsx    From GTAV-NativeDB with MIT License 5 votes vote down vote up
export default function NativeList() {
  const [filter, setFilter] = useState('')
  const namespaces = useNativeSearch(filter)
  const inputRef = useRef<HTMLInputElement>(null)
  const history = useHistory()
  const query = useQuery()

  useEffect(() => {
    const search = query.get('search')
    setFilter(search ?? '')
  }, [query, setFilter])

  const handleSearchKeyDown = useCallback((e: KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      inputRef.current?.blur()
      e.preventDefault()
    }
  }, [inputRef])

  const handleSearchBlur = useCallback(() => {
    if (filter) {
      history.replace(`${history.location.pathname}?search=${encodeURIComponent(filter)}`)
    }
    else {
      history.replace(history.location.pathname)
    }
  }, [history, filter])

  const handleFilterChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {
    setFilter(e.target.value)
  }, [setFilter])

  useSetAppBarSettings('NativeList', {
    search: {
      onChange: handleFilterChange,
      onKeyDown: handleSearchKeyDown,
      onBlur: handleSearchBlur,
      ref: inputRef,
      value: filter
    }
  })

  useHotkeys('ctrl+k', () => {
    inputRef.current?.focus()
  }, {
    filter: (event: globalThis.KeyboardEvent) => {
      event.preventDefault()
      return true
    },
  }, [inputRef])

  return (
    <Fragment>
      <NativeListComponent
        sx={{ height: '100%' }}
        namespaces={namespaces}
      />
    </Fragment>
  )
}
Example #19
Source File: dialog-delete.tsx    From keycaplendar with MIT License 5 votes vote down vote up
DialogDelete = ({
  close,
  folders,
  images,
  open,
  toggleImageChecked,
}: DialogDeleteProps) => {
  const dispatch = useAppDispatch();
  const [deleteAllVersions, setDeleteAllVersions] = useState(false);
  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    setDeleteAllVersions(e.target.checked);
  };
  const createArray = (allVersions = deleteAllVersions) => {
    if (allVersions) {
      const array = images
        .map((image) => folders.map((folder) => `${folder}/${image.name}`))
        .flat(1);
      return array;
    } else {
      const array = images.map((image) => image.fullPath);
      return array;
    }
  };
  const deleteImages = () => {
    const array = createArray();
    dispatch(setLoading(true));
    batchStorageDelete(array)
      .then(() => {
        queue.notify({ title: "Successfully deleted files." });
        close();
        listAll();
      })
      .catch((error) => {
        queue.notify({ title: `Failed to delete files: ${error}` });
        console.log(error);
        dispatch(setLoading(false));
      });
  };
  return (
    <Dialog className="delete-image-dialog" onClose={close} open={open}>
      <DialogTitle>{pluralise`Delete ${[images.length, "image"]}`}</DialogTitle>
      <DialogContent>
        {pluralise`The following ${[images.length, "image"]} will be deleted:`}
        <div className="chips-container">
          <ChipSet>
            {images.map((image) => (
              <Chip
                key={image.fullPath}
                disabled
                label={image.name}
                onTrailingIconInteraction={() => toggleImageChecked(image)}
                trailingIcon="close"
              />
            ))}
          </ChipSet>
        </div>
        {`Are you sure you want to delete ${
          images.length > 1 ? "these" : "this"
        }?`}{" "}
        This cannot be undone.
      </DialogContent>
      <DialogActions>
        <div className="checkbox-container">
          <Checkbox
            checked={deleteAllVersions}
            label="Delete all versions"
            onChange={handleChange}
          />
        </div>
        <DialogButton action="close" label="Close" onClick={close} />
        <DialogButton
          className="delete"
          label="Delete"
          onClick={deleteImages}
        />
      </DialogActions>
    </Dialog>
  );
}
Example #20
Source File: Login.tsx    From jmix-frontend with Apache License 2.0 5 votes vote down vote up
Login = observer(() => {
  const intl = useIntl();

  const mainStore = useMainStore();

  const [login, setLogin] = useState("");
  const [password, setPassword] = useState("");
  const [performingLoginRequest, setPerformingLoginRequest] = useState(false);

  const changeLogin = useCallback((e: ChangeEvent<HTMLInputElement>) => setLogin(e.target.value), [setLogin]);
  const changePassword = useCallback((e: ChangeEvent<HTMLInputElement>) => setPassword(e.target.value), [setPassword]);

  const doLogin = useCallback(() => {
    setPerformingLoginRequest(true);
    mainStore
      .login(login, password)
      .then(action(() => {
        setPerformingLoginRequest(false);
      }))
      .catch(action((error: JmixServerError) => {
        setPerformingLoginRequest(false);

        const loginMessageErrorIntlId = loginMapJmixRestErrorToIntlId(error);
        message.error(intl.formatMessage({id: loginMessageErrorIntlId}));
      }));
  }, [setPerformingLoginRequest, mainStore, intl, login, password]);

  return (
    <Card className={styles.loginForm}>
      <JmixDarkIcon className={styles.logo} />

      <div className={styles.title}>
        <%= title %>
      </div>

      <Form layout='vertical' onFinish={doLogin}>
        <Form.Item>
          <Input id='input_login'
                  placeholder={intl.formatMessage({id: 'login.placeholder.login'})}
                  onChange={changeLogin}
                  value={login}
                  prefix={<UserOutlined style={{ margin: "0 11px 0 0" }}/>}
                  size='large'/>
        </Form.Item>
        <Form.Item>
          <Input id='input_password'
                  placeholder={intl.formatMessage({id: 'login.placeholder.password'})}
                  onChange={changePassword}
                  value={password}
                  type='password'
                  prefix={<LockOutlined style={{ margin: "0 11px 0 0" }}/>}
                  size='large'/>
        </Form.Item>
        <Form.Item>
          <div className={styles.languageSwitcherContainer}>
            <LanguageSwitcher />
          </div>
        </Form.Item>
        <Form.Item>
          <Button type='primary'
                  htmlType='submit'
                  size='large'
                  block={true}
                  loading={performingLoginRequest}>
            <FormattedMessage id='login.loginBtn'/>
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );
})
Example #21
Source File: Input.tsx    From avalon.ist with MIT License 5 votes vote down vote up
changeInput = (event: ChangeEvent<HTMLInputElement>) => {
    this.setState({
      content: event.target.value.slice(0, 250),
    });
  };
Example #22
Source File: TextArea.tsx    From Notepad with MIT License 5 votes vote down vote up
function TextArea() {
  const [linesNum, setLineNum] = useState(1);
  const [columnIndex, setColumnIndex] = useState(0);
  const [textAreaContent, setTextAreaContent] = useState(() => {
    return getFromLocalStorage("notepad_textarea_content") || "";
  });

  function handleTextAreaChange(
    event:
      | ChangeEvent<HTMLTextAreaElement>
      | KeyboardEvent<HTMLTextAreaElement>
      | MouseEvent<HTMLTextAreaElement>
  ) {
    setLineNum(getLineNumber(event.target as HTMLTextAreaElement));
    setColumnIndex(getColumnIndex(event.target as HTMLTextAreaElement));
    setTextAreaContent((event.target as HTMLTextAreaElement).value);
    setToLocalStorage(
      "notepad_textarea_content",
      event.target as HTMLTextAreaElement
    );
  }

  useEffect(() => {
    let textAreaElem: HTMLTextAreaElement = document.getElementById(
      "text-area"
    ) as HTMLTextAreaElement;
    enableTabIndentation(textAreaElem);

    new UserPreference().setFontSettings();
  }, []);

  return (
    <>
      <textarea
        name="text-area"
        id="text-area"
        autoFocus
        spellCheck="false"
        value={textAreaContent}
        onKeyUp={handleTextAreaChange}
        onKeyDown={handleTextAreaChange}
        onKeyPress={handleTextAreaChange}
        onChange={handleTextAreaChange}
        onFocus={handleTextAreaChange}
        onMouseUp={handleTextAreaChange}
        data-testid="text-area"
      />
      <div className="details-tab">
        <div className="line-number">
          <p data-testid="line-index">
            Ln {linesNum}, Col {columnIndex}
          </p>
        </div>
        <div className="extra-details"></div>
      </div>
    </>
  );
}
Example #23
Source File: AmountInput.tsx    From hypertext with GNU General Public License v3.0 5 votes vote down vote up
// match escaped "." characters in a non-capturing group

export default function AmountInput({
  controlled,
  isInvalid,
  isDisabled,
  value,
  onChange,
}: {
  controlled: boolean
  isInvalid: boolean
  isDisabled: boolean
  value: string
  onChange: (value: string) => void
}): JSX.Element {
  const ref = useRef<HTMLInputElement>(null)
  useLayoutEffect(() => {
    if (ref.current) ref.current.size = Math.max(1, value.length)
  })

  return (
    <Input
      ref={ref}
      value={value}
      onChange={(event: ChangeEvent<HTMLInputElement>): void => {
        // if the user is typing, interpret commas as decimal separators and replace them with periods
        const value = event.target.value.replace(/,/g, !controlled ? '' : '.')
        if (value === '' || REGEX.test(escapeRegExp(value))) {
          onChange(value)
        }
      }}
      // chakra options
      isDisabled={isDisabled}
      _disabled={{
        opacity: 0.4,
        cursor: 'not-allowed',
      }}
      isInvalid={isInvalid}
      borderColor={!isInvalid ? 'transparent !important' : undefined}
      isRequired={true}
      variant="flushed"
      fontSize="3xl"
      textAlign="center"
      // universal input options
      inputMode="decimal"
      title="Token Amount"
      autoComplete="off"
      autoCorrect="off"
      // text-specific options
      type="text"
      placeholder="0"
      minLength={1}
      maxLength={79}
      spellCheck="false"
    />
  )
}
Example #24
Source File: LanguageSelector.tsx    From crowdsource-dataplatform with MIT License 5 votes vote down vote up
LanguageSelector = ({
  selectedLanguage,
  updateSelectedLanguage,
}: {
  selectedLanguage: string | undefined;
  updateSelectedLanguage: (language: string | undefined) => void;
}) => {
  const { t } = useTranslation();

  const handleChange = (e: ChangeEvent<HTMLSelectElement>) => {
    const value = e.target.value;

    if (value === 'all') updateSelectedLanguage(undefined);
    else updateSelectedLanguage(value);
  };

  return (
    <Form.Group controlId="language">
      <Form.Label className="mb-2 mb-md-4">{t('selectLanguagePrompt')}:</Form.Label>
      <div className="d-md-flex align-items-md-center">
        <Form.Select
          value={selectedLanguage || 'all'}
          aria-label="Select Language"
          onChange={handleChange as any}
          className={`${styles.dropdown} me-5 mb-3 mb-md-0`}
        >
          <option key="all" value="all">
            {t('allLanguages')}
          </option>
          {CONTRIBUTION_LANGUAGE?.map(locale => (
            <option key={locale} value={RAW_LANGUAGES[locale]}>
              {DISPLAY_LANGUAGES[locale]}
            </option>
          ))}
        </Form.Select>
        <DataLastUpdated />
      </div>
    </Form.Group>
  );
}
Example #25
Source File: InputString.tsx    From hive with MIT License 5 votes vote down vote up
change = (e: ChangeEvent<HTMLInputElement>) => {
        const { value, config } = this.props;

        config.changeValue(value.value_id, e.target.value);
    };
Example #26
Source File: Comments.tsx    From The-TypeScript-Workshop with MIT License 5 votes vote down vote up
Comments = (props: StoryModel) => {
  const { comments, id } = props;
  const [newComment, setNewComment] = useState('');
  const { addComment, fetchStories } = useContext(StoriesContext);
  const user = useContext(UserContext);
  const [showAdd, setShowAdd] = useState(false);
  const handleChange = (event: ChangeEvent<HTMLInputElement>) =>
    setNewComment(event.target.value);
  const handleSave = async () => {
    if (newComment) {
      await addComment!(id, comments, {
        comment: newComment,
        user: user!.email!,
        timestamp: Date.now(),
      });
      fetchStories!();
      handleToggle();
    }
  };
  const handleToggle = () => setShowAdd(!showAdd);
  return (
    <div>
      {comments && comments.map((c) => <Comment key={c.timestamp} {...c} />)}
      {showAdd ? (
        <div>
          <TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            id="comment"
            label="Comment"
            name="comment"
            autoComplete="comment"
            autoFocus
            onChange={handleChange}
          />{' '}
          <Button color="primary" variant="contained" onClick={handleSave}>
            Save
          </Button>
        </div>
      ) : (
        <Button color="primary" variant="contained" onClick={handleToggle}>
          Add a comment
        </Button>
      )}
    </div>
  );
}
Example #27
Source File: FileInput.tsx    From yet-another-generic-startpage with MIT License 5 votes vote down vote up
FileInput = ({ label, id, onChange, valid }: FileInputProps) => {
  const [dragging, setDragging] = useState(false)

  const addDrag = (event: DragEvent<HTMLDivElement>) => {
    event.preventDefault()
    setDragging(true)
  }

  const removeDrag = (event: DragEvent<HTMLDivElement>) => {
    event.preventDefault()
    setDragging(false)
  }

  const handleDrop = (event: DragEvent<HTMLDivElement>) => {
    event.preventDefault()
    setDragging(false)
    const file = event.dataTransfer.items[0].getAsFile()
    if (file) onChange?.(file)
  }

  const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) onChange?.(file)
  }

  return (
    <Wrapper onDrop={handleDrop} onDragOver={addDrag} onDragLeave={removeDrag}>
      <HiddenFileInput as="input" type="file" id={id} onChange={handleChange} />
      <Label htmlFor={id} valid={valid} dragging={dragging}>
        {label} <Upload />
      </Label>
    </Wrapper>
  )
}
Example #28
Source File: Link.tsx    From dnde with GNU General Public License v3.0 5 votes vote down vote up
Link = () => {
  const [visible, path] = useVisibility({ attribute: ATTRIBUTE });
  const { mjmlJson, setMjmlJson } = useEditor();
  const { getValue } = useValue({ path, visible, attribute: ATTRIBUTE });
  const [value, setValue] = useState('');

  useEffect(() => {
    if (visible) {
      setValue(getValue());
    }
  }, [visible, path]);

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    setValue(e.target.value);
    if (path && visible) {
      setValueInState(e.target.value);
    }
  };

  const setValueInState = (userValue: string) => {
    let json = {};
    let element = _.get(mjmlJson, path);
    element.attributes[ATTRIBUTE] = userValue;
    json = _.set(mjmlJson, path, element);
    setMjmlJson({ ...json });
  };

  // if entered url does not contain 'https://' | 'http://' add it on blur event,
  // after the user finises typing.
  const onBlur = (e: any) => {
    if (e && e.target && e.target.value) {
      const url = addHttps(e.target.value);
      setValueInState(url);
      setValue(url);
    }
  };

  return visible ? (
    <FormItem>
      <Row>
        <Col span={24}>
          <Input addonBefore={ATTRIBUTE} onBlur={onBlur} onChange={handleChange} value={value} />
        </Col>
      </Row>
    </FormItem>
  ) : null;
}
Example #29
Source File: MessageInput.tsx    From airmessage-web with Apache License 2.0 5 votes vote down vote up
export default function MessageInput(props: Props) {
	const theme = useTheme();
	const colorBG = theme.palette.messageIncoming.main;
	
	const {
		onMessageChange: propsOnMessageChange,
		onMessageSubmit: propsOnMessageSubmit,
		message: propsMessage,
		attachments: propsAttachments,
		onAttachmentAdd: propsOnAttachmentAdd
	} = props;
	
	const handleChange = useCallback((event: ChangeEvent<HTMLTextAreaElement>) => {
		propsOnMessageChange(event.target.value);
	}, [propsOnMessageChange]);
	
	const submitInput = useCallback(() => {
		propsOnMessageSubmit(propsMessage, propsAttachments);
	}, [propsOnMessageSubmit, propsMessage, propsAttachments]);
	
	const handleKeyPress = useCallback((event: React.KeyboardEvent<HTMLElement>) => {
		if(!event.shiftKey && event.key === "Enter") {
			event.preventDefault();
			submitInput();
		}
	}, [submitInput]);
	
	const handlePaste = useCallback((event: React.ClipboardEvent<HTMLElement>) => {
		propsOnAttachmentAdd(Array.from(event.clipboardData.files));
	}, [propsOnAttachmentAdd]);
	
	return (
		<div className={styles.root} style={{backgroundColor: colorBG}}>
			<Flipper flipKey={props.attachments.map(attachment => attachment.id).join(" ")}>
				{props.attachments.length > 0 &&
					<div className={styles.attachmentqueue}>
						{props.attachments.map((file) => {
							const queueData: QueuedAttachmentProps = {
								file: file.file,
								onRemove: () => props.onAttachmentRemove(file)
							};
							
							let component: React.ReactNode;
							if(file.file.type.startsWith("image/")) component = <QueuedAttachmentImage queueData={queueData} />;
							else component = <QueuedAttachmentGeneric queueData={queueData} />;
							
							return (<Flipped flipId={"attachmentqueue-" + file.id} key={file.id} onAppear={onAttachmentAppear} onExit={onAttachmentExit}>
								{component}
							</Flipped>);
						})}
					</div>
				}
				<div className={styles.control}>
					<InputBase className={styles.textfield} maxRows="5" multiline fullWidth autoFocus placeholder={props.placeholder} value={props.message} onChange={handleChange} onKeyPress={handleKeyPress} onPaste={handlePaste} />
					<IconButton size="small" color="primary" disabled={props.message.trim() === "" && props.attachments.length === 0} onClick={submitInput}><PushIcon /></IconButton>
				</div>
			</Flipper>
		</div>
	);
}