react#BaseSyntheticEvent TypeScript Examples

The following examples show how to use react#BaseSyntheticEvent. 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: Avatar.tsx    From docs-components with MIT License 6 votes vote down vote up
function preventDefaultByComponent(
    event: BaseSyntheticEvent,
    inDetails: boolean,
    isRedirect: boolean,
): void {
    if (inDetails || isRedirect) {
        return;
    }

    event.preventDefault();
}
Example #2
Source File: HiddenAvatars.tsx    From docs-components with MIT License 6 votes vote down vote up
HiddenAvatars: React.FC<HiddenAvatarsProps> = (props) => {
    const {contributors, avatarsSize} = props;
    const contributorsCount = contributors.length;

    const controlRef = useRef<HTMLImageElement | null>(null);
    const [isVisiblePopup, setIsVisiblePopup] = useState(false);

    if (contributorsCount === 0) {
        return null;
    }

    const popupData: PopupData = {
        ref: controlRef,
        isVisiblePopup,
        changeVisiblilityPopup: () => setIsVisiblePopup(false),
    };

    const contributorsCountString =
        contributorsCount > LOWER_BOUND_MORE_CONTRIBUTORS
            ? `${LOWER_BOUND_MORE_CONTRIBUTORS}+`
            : `+${contributorsCount}`;

    return (
        <Fragment>
            <div
                className={b('avatar', {size: avatarsSize})}
                ref={controlRef}
                onClick={(event: BaseSyntheticEvent) => {
                    setIsVisiblePopup(!isVisiblePopup);
                    event.preventDefault();
                }}
            >
                {contributorsCountString}
            </div>
            <Details contributors={contributors} popupData={popupData} />
        </Fragment>
    );
}
Example #3
Source File: Avatar.tsx    From docs-components with MIT License 5 votes vote down vote up
Avatar: React.FC<AvatarProps> = (props) => {
    const {avatarData, popupData, isRedirect = false} = props;
    const {contributor, size = AvatarSizes.SMALL, inDetails = false} = avatarData;
    const {changeVisiblilityPopup = () => {}, ref} = popupData || {};
    const {avatar, email, login} = contributor;

    const key = `avatar-${login || email}`;

    if (avatar) {
        return (
            <img
                key={key}
                className={b('avatar', {size})}
                src={avatar}
                ref={ref}
                onMouseOver={() => changeVisiblilityPopup(true)}
                onMouseLeave={() => changeVisiblilityPopup(false)}
                onTouchStart={() => changeVisiblilityPopup()}
                onTouchEnd={(event: BaseSyntheticEvent) =>
                    preventDefaultByComponent(event, inDetails, isRedirect)
                }
            />
        );
    }

    const initials = getInitials(contributor);

    return (
        <div
            key={key}
            className={b('avatar', {size, default: true})}
            ref={ref}
            onMouseOver={() => changeVisiblilityPopup(true)}
            onMouseLeave={() => changeVisiblilityPopup(false)}
            onTouchStart={() => changeVisiblilityPopup()}
            onTouchEnd={(event: BaseSyntheticEvent) =>
                preventDefaultByComponent(event, inDetails, isRedirect)
            }
        >
            {initials}
        </div>
    );
}
Example #4
Source File: index.tsx    From aqualink-app with MIT License 4 votes vote down vote up
RegisterDialog = ({
  open,
  handleRegisterOpen,
  handleSignInOpen,
  classes,
}: RegisterDialogProps) => {
  const dispatch = useDispatch();
  const user = useSelector(userInfoSelector);
  const loading = useSelector(userLoadingSelector);
  const error = useSelector(userErrorSelector);
  const [errorAlertOpen, setErrorAlertOpen] = useState<boolean>(false);
  const [readTerms, setReadTerms] = useState<boolean>(false);

  const { register, errors, handleSubmit } = useForm<RegisterFormFields>({
    reValidateMode: "onSubmit",
  });

  const onSubmit = (
    data: RegisterFormFields,
    event?: BaseSyntheticEvent<object, HTMLElement, HTMLElement>
  ) => {
    if (event) {
      event.preventDefault();
    }
    const registerInfo: UserRegisterParams = {
      fullName: `${data.firstName} ${data.lastName}`,
      organization: data.organization,
      email: data.emailAddress.toLowerCase(),
      password: data.password,
    };
    dispatch(createUser(registerInfo));
  };

  const clearUserError = () => dispatch(clearError());

  useEffect(() => {
    if (user) {
      handleRegisterOpen(false);
    }
    if (error) {
      setErrorAlertOpen(true);
    }
  }, [user, handleRegisterOpen, error]);

  return (
    <Dialog
      onEnter={() => {
        clearUserError();
        setReadTerms(false);
      }}
      scroll="body"
      open={open}
      maxWidth="xs"
    >
      <Card>
        <CardHeader
          className={classes.dialogHeader}
          title={
            <Grid container alignItems="center" justify="space-between">
              <Grid item>
                <Grid container>
                  <Typography variant="h4">Aqua</Typography>
                  <Typography
                    className={classes.dialogHeaderSecondPart}
                    variant="h4"
                  >
                    link
                  </Typography>
                </Grid>
              </Grid>
              <Grid item>
                <IconButton
                  className={classes.closeButton}
                  size="small"
                  onClick={() => {
                    handleRegisterOpen(false);
                  }}
                >
                  <CloseIcon />
                </IconButton>
              </Grid>
            </Grid>
          }
        />
        {loading && <LinearProgress />}
        {error && (
          <Collapse in={errorAlertOpen}>
            <Alert
              severity="error"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setErrorAlertOpen(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              {error}
            </Alert>
          </Collapse>
        )}
        <CardContent>
          <Grid container justify="center" item xs={12}>
            <Grid className={classes.dialogContentTitle} container item xs={10}>
              <Grid item>
                <Typography variant="h5" color="textSecondary">
                  Create an account
                </Typography>
              </Grid>
            </Grid>
            <Grid container item xs={10}>
              <form className={classes.form} onSubmit={handleSubmit(onSubmit)}>
                <Grid className={classes.textFieldWrapper} item xs={12}>
                  <TextField
                    id="firstName"
                    name="firstName"
                    placeholder="First Name"
                    helperText={
                      errors.firstName ? errors.firstName.message : ""
                    }
                    label="First Name"
                    inputRef={register({
                      required: "This is a required field",
                    })}
                    error={!!errors.firstName}
                    inputProps={{ className: classes.textField }}
                    fullWidth
                    variant="outlined"
                  />
                </Grid>
                <Grid className={classes.textFieldWrapper} item xs={12}>
                  <TextField
                    id="lastName"
                    name="lastName"
                    placeholder="Last Name"
                    helperText={errors.lastName ? errors.lastName.message : ""}
                    label="Last Name"
                    inputRef={register({
                      required: "This is a required field",
                    })}
                    error={!!errors.lastName}
                    inputProps={{ className: classes.textField }}
                    fullWidth
                    variant="outlined"
                  />
                </Grid>
                <Grid className={classes.textFieldWrapper} item xs={12}>
                  <TextField
                    id="organization"
                    name="organization"
                    placeholder="Organization"
                    helperText={
                      errors.organization ? errors.organization.message : ""
                    }
                    label="Organization"
                    inputRef={register({
                      required: "This is a required field",
                    })}
                    error={!!errors.organization}
                    inputProps={{ className: classes.textField }}
                    fullWidth
                    variant="outlined"
                  />
                </Grid>
                <Grid className={classes.textFieldWrapper} item xs={12}>
                  <TextField
                    id="emailAddress"
                    name="emailAddress"
                    placeholder="Email Address"
                    helperText={
                      (errors.emailAddress &&
                        (errors.emailAddress.type === "validate"
                          ? "Invalid email address"
                          : errors.emailAddress.message)) ||
                      ""
                    }
                    label="Email Address"
                    inputRef={register({
                      required: "This is a required field",
                      validate: (value) => isEmail(value),
                    })}
                    error={!!errors.emailAddress}
                    inputProps={{ className: classes.textField }}
                    fullWidth
                    variant="outlined"
                  />
                </Grid>
                <Grid className={classes.textFieldWrapper} item xs={12}>
                  <TextField
                    id="password"
                    name="password"
                    type="password"
                    placeholder="Password"
                    helperText={errors.password ? errors.password.message : ""}
                    label="Password"
                    inputRef={register({
                      required: "This is a required field",
                      minLength: {
                        value: 8,
                        message: "Password must be at least 8 characters",
                      },
                    })}
                    error={!!errors.password}
                    inputProps={{ className: classes.textField }}
                    fullWidth
                    variant="outlined"
                  />
                </Grid>
                <Grid
                  container
                  justify="space-between"
                  alignItems="center"
                  item
                  xs={12}
                >
                  <Grid item xs={1}>
                    <Checkbox
                      className={classes.termsCheckbox}
                      checked={readTerms}
                      onChange={() => setReadTerms(!readTerms)}
                      color="primary"
                    />
                  </Grid>
                  <Grid item xs={10} sm={11}>
                    <Box>
                      <Typography
                        className={classes.formText}
                        variant="subtitle1"
                        color="textSecondary"
                      >
                        I have read the{" "}
                        <Link className={classes.termsLink} to="/terms">
                          Terms and Conditions
                        </Link>
                      </Typography>
                    </Box>
                  </Grid>
                </Grid>
                <Grid className={classes.button} item xs={12}>
                  <Button
                    fullWidth
                    type="submit"
                    color="primary"
                    variant="contained"
                    size="large"
                    disabled={!readTerms}
                  >
                    CREATE ACCOUNT
                  </Button>
                </Grid>
                <Grid container item xs={12}>
                  <Typography
                    className={classes.formText}
                    variant="subtitle1"
                    color="textSecondary"
                  >
                    Have an account?{" "}
                    <Button
                      onClick={() => {
                        handleRegisterOpen(false);
                        handleSignInOpen(true);
                      }}
                      color="primary"
                    >
                      SIGN IN
                    </Button>
                  </Typography>
                </Grid>
              </form>
            </Grid>
          </Grid>
        </CardContent>
      </Card>
    </Dialog>
  );
}
Example #5
Source File: index.tsx    From aqualink-app with MIT License 4 votes vote down vote up
SignInDialog = ({
  open,
  handleRegisterOpen,
  handleSignInOpen,
  classes,
}: SignInDialogProps) => {
  const dispatch = useDispatch();
  const user = useSelector(userInfoSelector);
  const loading = useSelector(userLoadingSelector);
  const error = useSelector(userErrorSelector);
  const [errorAlertOpen, setErrorAlertOpen] = useState<boolean>(false);
  const [passwordResetEmail, setPasswordResetEmail] = useState<string>("");
  const { register, errors, handleSubmit } = useForm<SignInFormFields>({
    reValidateMode: "onSubmit",
  });

  useEffect(() => {
    if (user) {
      handleSignInOpen(false);
    }
    if (error) {
      setErrorAlertOpen(true);
    }
  }, [user, handleSignInOpen, error]);

  const onSubmit = (
    data: SignInFormFields,
    event?: BaseSyntheticEvent<object, HTMLElement, HTMLElement>
  ) => {
    if (event) {
      event.preventDefault();
    }
    const registerInfo: UserSignInParams = {
      email: data.emailAddress.toLowerCase(),
      password: data.password,
    };
    dispatch(signInUser(registerInfo));
  };

  const onResetPassword = (
    { emailAddress }: SignInFormFields,
    event?: BaseSyntheticEvent<object, HTMLElement, HTMLElement>
  ) => {
    if (event) {
      event.preventDefault();
    }
    dispatch(resetPassword({ email: emailAddress.toLowerCase() }));
    setPasswordResetEmail(emailAddress.toLowerCase());
  };

  const clearUserError = () => dispatch(clearError());

  return (
    <Dialog
      onEnter={() => {
        clearUserError();
        setPasswordResetEmail("");
      }}
      open={open}
      maxWidth="xs"
    >
      <Card elevation={0}>
        <CardHeader
          className={classes.dialogHeader}
          title={
            <Grid container alignItems="center" justify="space-between">
              <Grid item>
                <Grid container>
                  <Typography variant="h4">Aqua</Typography>
                  <Typography
                    className={classes.dialogHeaderSecondPart}
                    variant="h4"
                  >
                    link
                  </Typography>
                </Grid>
              </Grid>
              <Grid item>
                <IconButton
                  className={classes.closeButton}
                  size="small"
                  onClick={() => handleSignInOpen(false)}
                >
                  <CloseIcon />
                </IconButton>
              </Grid>
            </Grid>
          }
        />
        {loading && <LinearProgress />}
        {error && (
          <Collapse in={errorAlertOpen}>
            <Alert
              severity="error"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setErrorAlertOpen(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              {error}
            </Alert>
          </Collapse>
        )}
        <Collapse in={passwordResetEmail !== ""}>
          <Alert
            severity="success"
            action={
              <IconButton
                aria-label="close"
                color="inherit"
                size="small"
                onClick={() => {
                  setPasswordResetEmail("");
                }}
              >
                <CloseIcon fontSize="inherit" />
              </IconButton>
            }
          >
            {`Password reset email sent to ${passwordResetEmail}.`}
          </Alert>
        </Collapse>
        <CardContent>
          <Grid container justify="center" item xs={12}>
            <Grid className={classes.dialogContentTitle} container item xs={10}>
              <Grid item>
                <Typography variant="h5" color="textSecondary">
                  Sign In
                </Typography>
              </Grid>
            </Grid>
            <Grid container item xs={10}>
              <form className={classes.form} onSubmit={handleSubmit(onSubmit)}>
                <Grid className={classes.textFieldWrapper} item xs={12}>
                  {/* TODO: ADD THIS WHEN WE ENABLE GOOGLE LOGIN */}
                  {/* <Typography className={classes.formText} variant="subtitle2">
                    or login with email address
                  </Typography> */}
                  <TextField
                    id="emailAddress"
                    name="emailAddress"
                    placeholder="Email Address"
                    helperText={
                      (errors.emailAddress &&
                        (errors.emailAddress.type === "validate"
                          ? "Invalid email address"
                          : errors.emailAddress.message)) ||
                      ""
                    }
                    label="Email Address"
                    inputRef={register({
                      required: "This is a required field",
                      validate: (value) => isEmail(value),
                    })}
                    error={!!errors.emailAddress}
                    inputProps={{ className: classes.textField }}
                    fullWidth
                    variant="outlined"
                  />
                </Grid>
                <Grid className={classes.textFieldWrapper} item xs={12}>
                  <TextField
                    id="password"
                    name="password"
                    type="password"
                    placeholder="Password"
                    helperText={errors.password ? errors.password.message : ""}
                    label="Password"
                    inputRef={register({
                      required: "This is a required field",
                    })}
                    error={!!errors.password}
                    inputProps={{ className: classes.textField }}
                    fullWidth
                    variant="outlined"
                  />
                </Grid>
                <Grid container item xs={12}>
                  <Button
                    className={classes.forgotPasswordButton}
                    onClick={handleSubmit(onResetPassword)}
                  >
                    <Typography variant="subtitle2" color="textSecondary">
                      Forgot your password?
                    </Typography>
                  </Button>
                </Grid>
                <Grid className={classes.button} item xs={12}>
                  <Button
                    fullWidth
                    type="submit"
                    color="primary"
                    variant="contained"
                    size="large"
                  >
                    SIGN IN
                  </Button>
                </Grid>
                <Grid container item xs={12}>
                  <Typography
                    className={classes.formText}
                    variant="subtitle1"
                    color="textSecondary"
                  >
                    Don&#39;t have an account?{" "}
                    <Button
                      onClick={() => {
                        handleRegisterOpen(true);
                        handleSignInOpen(false);
                      }}
                      color="primary"
                    >
                      SIGN UP
                    </Button>
                  </Typography>
                </Grid>
              </form>
            </Grid>
          </Grid>
        </CardContent>
      </Card>
    </Dialog>
  );
}
Example #6
Source File: select-account-section.component.tsx    From hive-keychain-extension with MIT License 4 votes vote down vote up
SelectAccountSection = ({
  accounts,
  activeAccount,
  loadActiveAccount,
  setInfoMessage,
}: PropsFromRedux) => {
  const defaultOptions: LocalAccountListItem[] = [];

  useEffect(() => {
    setOptions(
      accounts.map((account: LocalAccount) => {
        return { label: account.name, value: account.name };
      }),
    );
    setSelectedLocalAccount(activeAccount.name);
  }, [accounts, activeAccount]);

  const [options, setOptions] = useState(defaultOptions);
  const [selectedLocalAccount, setSelectedLocalAccount] = useState(
    accounts[0].name,
  );

  const handleItemClicked = (accountName: string) => {
    const itemClicked = accounts.find(
      (account: LocalAccount) => account.name === accountName,
    );
    loadActiveAccount(itemClicked);
  };

  const customLabelRender = (
    selectProps: SelectRenderer<LocalAccountListItem>,
  ) => {
    return (
      <div
        className="selected-account-panel"
        onClick={() => {
          selectProps.methods.dropDown('close');
        }}>
        <img
          src={`https://images.hive.blog/u/${selectedLocalAccount}/avatar`}
          onError={(e: any) => {
            e.target.onError = null;
            e.target.src = '/assets/images/accounts.png';
          }}
        />
        <div className="selected-account-name">{selectedLocalAccount}</div>
      </div>
    );
  };
  const customItemRender = (
    selectProps: SelectItemRenderer<LocalAccountListItem>,
  ) => {
    return (
      <div
        className={`select-account-item ${
          selectedLocalAccount === selectProps.item.value ? 'selected' : ''
        }`}
        onClick={() => {
          handleItemClicked(selectProps.item.value);
          selectProps.methods.dropDown('close');
        }}>
        <img
          src={`https://images.hive.blog/u/${selectProps.item.label}/avatar`}
          onError={(e: any) => {
            e.target.onError = null;
            e.target.src = '/assets/images/accounts.png';
          }}
        />
        <div className="account-name">{selectProps.item.label}</div>
        <Icon
          additionalClassName="copy-username-button"
          name={Icons.COPY}
          type={IconType.OUTLINED}
          onClick={($event) => {
            copyUsernameToClipboard($event, selectProps.item.label);
            selectProps.methods.dropDown('close');
          }}
        />
      </div>
    );
  };
  const copyUsernameToClipboard = (
    event: BaseSyntheticEvent,
    username: string,
  ) => {
    event.preventDefault();
    event.stopPropagation();
    navigator.clipboard.writeText(username);
    setInfoMessage('popup_html_text_copied', [username]);
  };

  return (
    <div>
      {selectedLocalAccount && options && (
        <div className="select-account-section">
          <Select
            values={[selectedLocalAccount]}
            options={options}
            onChange={() => undefined}
            contentRenderer={customLabelRender}
            itemRenderer={customItemRender}
            className="select-account-select"
          />
        </div>
      )}
    </div>
  );
}
Example #7
Source File: generic-transaction.component.tsx    From hive-keychain-extension with MIT License 4 votes vote down vote up
GenericTransaction = ({
  transaction,
  expandableContent,
  detail,
}: PropsFromRedux) => {
  const [isExpandablePanelOpened, setExpandablePanelOpened] = useState(false);

  const toggleExpandableContent = () => {
    if (expandableContent) {
      setExpandablePanelOpened(!isExpandablePanelOpened);
    }
  };

  const getIcon = () => {
    switch (transaction.type) {
      case 'transfer':
      case 'recurrent_transfer':
      case 'fill_recurrent_transfer':
        return Icons.SEND;
      case 'claim_reward_balance':
        return Icons.CLAIM;
      case 'savings':
        return Icons.SAVINGS;
      case 'power_up_down': {
        switch (transaction.subType) {
          case 'transfer_to_vesting':
            return Icons.ARROW_UPWARDS;
          case 'withdraw_vesting':
            return Icons.ARROW_DOWNWARDS;
        }
      }
      case 'delegate_vesting_shares':
        return Icons.DELEGATIONS;
      case 'claim_account':
        return Icons.ACCOUNT;
      case 'convert':
        return Icons.CONVERT;
      default:
        return Icons.LINK;
    }
  };

  const openTransactionOnHiveblocks = (event: BaseSyntheticEvent) => {
    event.stopPropagation();
    chrome.windows.create({
      url: transaction.url,
    });
  };

  return (
    <div
      className={`transaction ${
        expandableContent ? 'has-expandable-content' : ''
      }`}
      key={transaction.key}
      onClick={toggleExpandableContent}>
      <div className="information-panel">
        <div className="top-row">
          <Icon
            name={getIcon()}
            type={IconType.OUTLINED}
            onClick={openTransactionOnHiveblocks}></Icon>
          <CustomTooltip
            message={moment(transaction.timestamp).format(
              'YYYY/MM/DD , hh:mm:ss a',
            )}
            skipTranslation>
            <div className="date">
              {moment(transaction.timestamp).format('L')}
            </div>
          </CustomTooltip>
          <div className="divider"></div>
          {expandableContent && (
            <Icon
              name={Icons.EXPAND_MORE}
              onClick={() => setExpandablePanelOpened(!isExpandablePanelOpened)}
              additionalClassName={`more ${
                isExpandablePanelOpened ? 'opened' : 'closed'
              }`}
              type={IconType.OUTLINED}></Icon>
          )}
        </div>
        <div className="bottom-row">{detail}</div>
      </div>
      {expandableContent && isExpandablePanelOpened && (
        <div
          className={
            isExpandablePanelOpened
              ? 'expandable-panel opened'
              : 'expandable-panel closed'
          }>
          {expandableContent}
        </div>
      )}
    </div>
  );
}
Example #8
Source File: rpc-nodes.component.tsx    From hive-keychain-extension with MIT License 4 votes vote down vote up
RpcNodes = ({
  activeRpc,
  setActiveRpc,
  setErrorMessage,
  setTitleContainerProperties,
}: PropsFromRedux) => {
  const allRpc = RpcUtils.getFullList();
  let displayedRpcs = allRpc;
  const [customRpcs, setCustomRpcs] = useState([] as Rpc[]);

  const [isAddRpcPanelDisplayed, setIsAddRpcPanelDisplayed] = useState(false);
  const [addRpcNodeUri, setAddRpcNodeUri] = useState('');
  const [addRpcNodeChainId, setAddRpcNodeChainId] = useState('');
  const [addRpcNodeTestnet, setAddRpcNodeTestnet] = useState(false);

  const [setNewRpcAsActive, setSetNewRpcAsActive] = useState(false);
  const [switchAuto, setSwitchAuto] = useState(true);

  const [options, setOptions] = useState(
    allRpc.map((rpc) => {
      return {
        label: rpc.uri,
        value: rpc.uri,
        rpc: rpc,
      };
    }),
  );

  useEffect(() => {
    displayedRpcs = [...allRpc, ...customRpcs];
    setOptions(
      displayedRpcs.map((rpc) => {
        return {
          label: rpc.uri,
          value: rpc.uri,
          rpc: rpc,
        };
      }),
    );
  }, [customRpcs]);

  useEffect(() => {
    setTitleContainerProperties({
      title: 'popup_html_rpc_node',
      isBackButtonEnabled: true,
    });
    initCustomRpcList();
    initSwitchAuto();
  }, []);

  useEffect(() => {
    LocalStorageUtils.saveValueInLocalStorage(
      LocalStorageKeyEnum.SWITCH_RPC_AUTO,
      switchAuto,
    );
  }, [switchAuto]);

  const initSwitchAuto = async () => {
    setSwitchAuto(
      await LocalStorageUtils.getValueFromLocalStorage(
        LocalStorageKeyEnum.SWITCH_RPC_AUTO,
      ),
    );
  };

  const initCustomRpcList = async () => {
    setCustomRpcs(await RpcUtils.getCustomRpcs());
  };

  const handleItemClicked = (rpc: Rpc) => {
    setActiveRpc(rpc);
  };

  const deleteCustomRPC = (item: Rpc, event: BaseSyntheticEvent) => {
    event.preventDefault();
    event.stopPropagation();
    const newRpcs = setCustomRpcs(RpcUtils.deleteCustomRpc(customRpcs, item));
    if (activeRpc?.uri === item.uri) {
      setActiveRpc(allRpc[0]);
    }

    return newRpcs;
  };

  const handleSaveNewRpcClicked = () => {
    if (
      !addRpcNodeUri.length ||
      (addRpcNodeTestnet && !addRpcNodeChainId.length)
    ) {
      setErrorMessage('popup_html_rpc_missing_fields');
      return;
    }
    if (displayedRpcs.find((rpc) => rpc.uri === addRpcNodeUri)) {
      setErrorMessage('popup_html_rpc_uri_already_existing');
      return;
    }

    const newCustomRpc = {
      uri: addRpcNodeUri,
      testnet: addRpcNodeTestnet,
      chainId: addRpcNodeChainId.length ? addRpcNodeChainId : undefined,
    };
    setIsAddRpcPanelDisplayed(false);
    RpcUtils.addCustomRpc(newCustomRpc);
    setCustomRpcs([...customRpcs, newCustomRpc]);
    if (setNewRpcAsActive) {
      setSwitchAuto(false);
      setActiveRpc(newCustomRpc);
    }
  };

  const customLabelRender = (selectProps: SelectRenderer<RpcListItem>) => {
    return (
      <div
        className="selected-rpc-node-panel"
        onClick={() => {
          selectProps.methods.dropDown('close');
        }}>
        <div className="selected-rpc-node">
          {activeRpc && activeRpc?.uri && activeRpc.uri}
          {activeRpc?.testnet && <div>- TESTNET</div>}
        </div>
      </div>
    );
  };
  const customItemRender = (selectProps: SelectItemRenderer<RpcListItem>) => {
    return (
      <div
        className={`select-rpc-item ${
          activeRpc?.uri === selectProps.item.rpc.uri ? 'selected' : ''
        }`}
        onClick={() => {
          handleItemClicked(selectProps.item.rpc);
          selectProps.methods.dropDown('close');
        }}>
        <div className="rpc-name">
          {selectProps.item.label}{' '}
          {selectProps.item.rpc.testnet && <div>TESTNET</div>}
        </div>
        {!RpcUtils.isDefault(selectProps.item.rpc) && (
          <img
            src="/assets/images/clear.png"
            className="erase-button"
            onClick={($event) => {
              deleteCustomRPC(selectProps.item.rpc, $event);
              selectProps.methods.dropDown('close');
            }}
          />
        )}
      </div>
    );
  };

  return (
    <div className="rpc-nodes-page">
      <p
        className="introduction"
        dangerouslySetInnerHTML={{
          __html: chrome.i18n.getMessage('popup_html_rpc_node_text'),
        }}></p>

      <CheckboxComponent
        title="popup_html_rpc_automatic_mode"
        hint="popup_html_rpc_automatic_mode_hint"
        checked={switchAuto}
        onChange={setSwitchAuto}></CheckboxComponent>

      {activeRpc && !switchAuto && options && (
        <div className="select-account-section">
          <Select
            values={[]}
            options={options}
            onChange={() => undefined}
            contentRenderer={customLabelRender}
            itemRenderer={customItemRender}
            className="select-rpc-node-select"
          />
        </div>
      )}

      {!switchAuto && !isAddRpcPanelDisplayed && (
        <ButtonComponent
          label={'popup_html_add_rpc'}
          onClick={() => setIsAddRpcPanelDisplayed(true)}
        />
      )}

      {!switchAuto && isAddRpcPanelDisplayed && (
        <div className="add-rpc-panel">
          <div className="add-rpc-caption">
            {chrome.i18n.getMessage('popup_html_add_rpc_text')}
          </div>
          <InputComponent
            type={InputType.TEXT}
            value={addRpcNodeUri}
            onChange={setAddRpcNodeUri}
            placeholder={'popup_html_rpc_node'}
            onEnterPress={handleSaveNewRpcClicked}
          />
          <CheckboxComponent
            title="TESTNET"
            checked={addRpcNodeTestnet}
            onChange={setAddRpcNodeTestnet}
            skipTranslation={true}></CheckboxComponent>
          {addRpcNodeTestnet && (
            <InputComponent
              type={InputType.TEXT}
              value={addRpcNodeChainId}
              onChange={setAddRpcNodeChainId}
              placeholder="Chain Id"
              skipPlaceholderTranslation={true}
              onEnterPress={handleSaveNewRpcClicked}
            />
          )}

          <CheckboxComponent
            title="popup_html_set_new_rpc_as_active"
            checked={setNewRpcAsActive}
            onChange={setSetNewRpcAsActive}></CheckboxComponent>

          <ButtonComponent
            label={'popup_html_save'}
            onClick={() => handleSaveNewRpcClicked()}
            fixToBottom
          />
        </div>
      )}
    </div>
  );
}