react-bootstrap#OverlayTrigger JavaScript Examples

The following examples show how to use react-bootstrap#OverlayTrigger. 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: action-tooltip.js    From stacker.news with MIT License 6 votes vote down vote up
export default function ActionTooltip ({ children, notForm, disable, overlayText }) {
  // if we're in a form, we want to hide tooltip on submit
  let formik
  if (!notForm) {
    formik = useFormikContext()
  }
  if (disable) {
    return children
  }
  return (
    <OverlayTrigger
      placement='bottom'
      overlay={
        <Tooltip>
          {overlayText || '1 sat'}
        </Tooltip>
      }
      trigger={['hover', 'focus']}
      show={formik?.isSubmitting ? false : undefined}
    >
      {children}
    </OverlayTrigger>
  )
}
Example #2
Source File: CompetitiveSites.js    From portfolio with MIT License 6 votes vote down vote up
render() {
    return (
      <div className="competitive-sites-main-div">
        <ul className="dev-icons">
          {this.props.logos.map((logo) => {
            return (
              <OverlayTrigger
                key={logo.siteName}
                placement={"top"}
                style={{ marginBottom: "5px" }}
                overlay={
                  <Tooltip id={`tooltip-top`}>
                    <strong>{logo.siteName}</strong>
                  </Tooltip>
                }
              >
                <li className="competitive-sites-inline" name={logo.siteName}>
                  <a
                    href={logo.profileLink}
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    <span
                      className="iconify"
                      data-icon={logo.iconifyClassname}
                      style={logo.style}
                      data-inline="false"
                    ></span>
                  </a>
                </li>
              </OverlayTrigger>
            );
          })}
        </ul>
      </div>
    );
  }
Example #3
Source File: Tooltip.js    From Edlib with GNU General Public License v3.0 6 votes vote down vote up
render() {
        let message = '';

        if (this.props.message) {
            message = this.props.message;
        } else if (this.props.messageId) {
            message = <FormattedHTMLMessage id={this.props.messageId}/>;
        }

        return (
            <OverlayTrigger
                placement="bottom"
                overlay={
                    <ToolTip id="tooltip">
                        {message}
                    </ToolTip>
                }
            >
                {this.props.children}
            </OverlayTrigger>
        );
    }
Example #4
Source File: ChartContainer.jsx    From cosmoscan-front with Apache License 2.0 6 votes vote down vote up
ChartContainer = ({ title, chart, select, titleTooltip }) => (
  <Card>
    <ChartHeader>
      <TitleChart>
        <span>
          {title}
          {titleTooltip && (
            <OverlayTrigger
              // placement="right"
              delay={{ show: 250, hide: 400 }}
              overlay={<Tooltip id="button-tooltip">{titleTooltip}</Tooltip>}
            >
              <Icon icon="question-circle" style={{ marginLeft: '5px' }} />
            </OverlayTrigger>
          )}
        </span>
      </TitleChart>
      {select}
    </ChartHeader>

    <Card.Body>{chart}</Card.Body>
  </Card>
)
Example #5
Source File: PlotSelection.jsx    From mapstore2-cadastrapp with GNU General Public License v3.0 6 votes vote down vote up
function PlotSelectionTabActionButtons({onNewTab = () => {}, onTabDelete = () => {}}) {
    return (
        <ButtonGroup className="pull-right">
            <OverlayTrigger placement="bottom" overlay={<Tooltip><Message msgId={'cadastrapp.search.addTab'}/></Tooltip>}>
                <Button
                    className="pull-right"
                    onClick={onNewTab}
                ><span className="glyphicon glyphicon-plus"></span>
                </Button>
            </OverlayTrigger>
            <OverlayTrigger placement="bottom" overlay={<Tooltip><Message msgId={'cadastrapp.search.deleteTab'}/></Tooltip>}>
                <ConfirmButton
                    className="pull-right"
                    confirmContent={<Message msgId={'cadastrapp.search.confirmDeleteTab'}/>}
                    onClick={onTabDelete}>
                    <Glyphicon glyph="trash" />
                </ConfirmButton>
            </OverlayTrigger>
        </ButtonGroup>
    );
}
Example #6
Source File: Participant.js    From talk4free with MIT License 6 votes vote down vote up
// class Participant extends React.Component {
//   render() {
//     const { participant } = this.props;
//     const style = {
//       backgroundImage: `url(${participant.img})`
//     };
//     // console.log("EN participants", participant);
//     return <div className="participant" style={style}></div>;
//     // return <p>hello</p>;
//   }
// }

// export default Participant;

function Participant(props) {
  const { participant } = props;
  // const style = {
  //   backgroundImage: `url(${participant.img})`
  // };
  return (
    <OverlayTrigger
      placement="top"
      overlay={
        <Tooltip id={`tooltip-top`}>
          <strong>{participant.username}</strong>
        </Tooltip>
      }
    >
      <div
        className="participant"
        style={{ backgroundImage: `url(${participant.img})` }}
      ></div>
    </OverlayTrigger>
  );
}
Example #7
Source File: ThemeToggle.react.js    From dash_trich_components with MIT License 6 votes vote down vote up
render() {
        const {
            bg_color_dark,
            icon_color_dark,
            bg_color_light,
            icon_color_light,
            tooltip_text,
            className,
            id,
            style
        } = this.props

        const { checked } = this.state

        let background = checked ? bg_color_dark : bg_color_light
        let color = checked ? icon_color_dark : icon_color_light

        const Label = styled.label`
            background: ${background};
            color: ${color};
        `

        return (
            <div className={`${className} themeToggle`} id={id} style={style}>
                <OverlayTrigger placement='bottom' delay={{ show: 1000 }} overlay={
                    <Tooltip id="tooltip-bottom">
                        {tooltip_text}
                    </Tooltip>
                }>
                    <form>
                        <input type="checkbox" id="theme_toggle" onChange={this.onChange} />
                        <Label htmlFor="theme_toggle"></Label>
                    </form>
                </OverlayTrigger>
            </div>

        );
    }
Example #8
Source File: FABAction.js    From anutimetable with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
FABAction = ({ title, content, onClick, ...props }) => {
  const overlay = <Tooltip>{title}</Tooltip>
  
  return <OverlayTrigger placement='left' overlay={overlay} trigger={['hover', 'click']} {...props}>
    <Button className='fab-action' variant='primary' onClick={onClick} >
      {content}
    </Button>
  </OverlayTrigger>
}
Example #9
Source File: CompetitiveSites.js    From developerPortfolio with MIT License 6 votes vote down vote up
render() {
    return (
      <div className="competitive-sites-main-div">
        <ul className="dev-icons">
          {this.props.logos.map((logo) => {
            return (
              <OverlayTrigger
                key={logo.siteName}
                placement={"top"}
                style={{ marginBottom: "5px" }}
                overlay={
                  <Tooltip id={`tooltip-top`}>
                    <strong>{logo.siteName}</strong>
                  </Tooltip>
                }
              >
                <li className="competitive-sites-inline" name={logo.siteName}>
                  <a
                    href={logo.profileLink}
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    <img
                      className="badge-logo"
                      src={require(`../../assets/images/${logo.logo_path}`)}
                      alt={logo.alt_name}
                    />
                  </a>
                </li>
              </OverlayTrigger>
            );
          })}
        </ul>
      </div>
    );
  }
Example #10
Source File: Tooltip.jsx    From awesome-react-starter with MIT License 6 votes vote down vote up
Tooltip = ({ icon = 'fas fa-question-circle', placement = 'top', children }) => {
  return (
    <OverlayTrigger
      placement={placement}
      overlay={<Popover className="tooltip">{children}</Popover>}
    >
      <div className="h-8 w-8 text-accent flex justify-center items-center">
        <i className={icon}></i>
      </div>
    </OverlayTrigger>
  );
}
Example #11
Source File: index.js    From wedding-planner with MIT License 6 votes vote down vote up
LoginLink = () => {
  const { loginWithRedirect } = useAuth0();
  return (
    <OverlayTrigger
      placement="bottom"
      overlay={<Tooltip id="tooltip-login">Log In</Tooltip>}
    >
      <Nav.Link onClick={() => loginWithRedirect()}>
        <FontAwesomeIcon icon={faSignInAlt} size="lg" />
      </Nav.Link>
    </OverlayTrigger>
  );
}
Example #12
Source File: connectMeta.js    From RC4Community with Apache License 2.0 6 votes vote down vote up
ShowBalance = ({ balance, account }) => {
  return (
    <div>
      <div className={styles.account}>
        {WeiToEth(parseInt(balance, 16))} ETH
        <OverlayTrigger
          overlay={
            <Tooltip placement="right" id="tooltip-disabled">
              Account Id!
            </Tooltip>
          }
        >
          <Badge className={styles.pill} pill>
            {`${account.substr(0, 4)}...${account.substr(
              account.length - 4,
              account.length
            )}`}
          </Badge>
        </OverlayTrigger>
      </div>
    </div>
  );
}
Example #13
Source File: BuildingButtons.jsx    From mapstore2-cadastrapp with GNU General Public License v3.0 5 votes vote down vote up
export default function BuildingsButtons({
    setShowDescription = () => {},
    selected = [],
    data = [],
    dnubat,
    parcelle

}) {
    let [propertiesSelected, setPropertiesSelected] = useState(false);
    let [bundleSelected, setBundleSelected] = useState(false);

    const onPropertiesClick = () => {
        setBundleSelected(false);
        setPropertiesSelected(!propertiesSelected);
    };

    const onBundleClick = () => {
        setPropertiesSelected(false);
        setBundleSelected(!bundleSelected);
    };
    // auto close panel if no row has been selected
    useEffect(() => {
        if (selected.length === 0) {
            setPropertiesSelected(false);
        }
    }, [selected]);

    return (<>
        <ButtonGroup className="pull-right">
            <OverlayTrigger placement="bottom" overlay={<Tooltip><Message msgId={'cadastrapp.duc.releve.depropriete'}/></Tooltip>}>
                <Button
                    disabled={selected.length === 0}
                    bsStyle={propertiesSelected ? "primary" : "default"}
                    onClick={onPropertiesClick}>
                    <Glyphicon glyph="th-list" />
                </Button>
            </OverlayTrigger>
            <OverlayTrigger placement="bottom" overlay={<Tooltip><Message msgId={'cadastrapp.duc.batiment_descriptif'}/></Tooltip>}>
                <Button
                    onClick={() => setShowDescription(true)}
                    disabled={selected.length === 0}>
                    <Glyphicon glyph="info-sign" />
                </Button>
            </OverlayTrigger>
            <OverlayTrigger placement="bottom" overlay={<Tooltip><Message msgId={'cadastrapp.duc.batiment_bundle'}/></Tooltip>}>
                <Button
                    bsStyle={bundleSelected ? "primary" : "default"}
                    onClick={onBundleClick}>
                    <Glyphicon glyph="compressed" /></Button>
            </OverlayTrigger>
        </ButtonGroup>
        <PropertiesRadio parcelle={parcelle} expanded={propertiesSelected} data={data} selected={selected} />
        <BundleRadio
            dnubat={dnubat}
            parcelle={parcelle}
            show={bundleSelected} />
    </>);
}
Example #14
Source File: WidgetStats.jsx    From cosmoscan-front with Apache License 2.0 5 votes vote down vote up
WidgetStats = ({
  title,
  mainInfo,
  sparklineData,
  extraInfo,
  isVertical,
  tooltip,
}) => {
  const theme = useContext(ThemeContext);

  return (
    <Card modifiers="height100">
      <CardBodyWidget>
        <WidgetItem isVertical={isVertical}>
          {tooltip ? (
            <OverlayTrigger
              delay={{ show: 250, hide: 400 }}
              overlay={<Tooltip id="title-tooltip">{tooltip}</Tooltip>}
            >
              <TitleMinor>{title}</TitleMinor>
            </OverlayTrigger>
          ) : (
            <TitleMinor>{title}</TitleMinor>
          )}
          <div>
            {sparklineData && sparklineData.length > 1 && (
              <div>
                <Sparkline
                  data={sparklineData}
                  color={
                    sparklineData[sparklineData.length - 1].y >
                    sparklineData[0].y
                      ? theme.success
                      : theme.danger
                  }
                />
              </div>
            )}
          </div>
        </WidgetItem>
        <WidgetItem>
          <div>{mainInfo}</div>
          <div>
            {sparklineData && sparklineData.length && (
              <Percent
                prevVal={sparklineData[0].y}
                currVal={sparklineData[sparklineData.length - 1].y}
              />
            )}
            {extraInfo}
          </div>
        </WidgetItem>
      </CardBodyWidget>
    </Card>
  );
}
Example #15
Source File: SimpleModal.js    From plenty-interface with GNU General Public License v3.0 5 votes vote down vote up
SimpleModal = (props) => {
  return (
    <Modal
      show={props.open}
      onHide={props.onClose}
      backdrop="static"
      keyboard={false}
      dialogClassName={clsx(
        styles.simpleModal,
        props.className,
        props.isConfirmSwap && styles.confirmSwap,
        props.title === 'Transaction Submitted' && 'centerAlign',
        props.isConfirmTransaction && 'removeCloseIcon',
      )}
      centered={true}
    >
      {/* * Header */}
      <div
        className={clsx('d-flex', props.isConfirmSwap ? styles.confirmSwapHeader : styles.header, {
          [styles.noTitle]: !props.title,
        })}
      >
        <div className={clsx(styles.title, 'flex-grow-1')}>
          {props.title}
          {props.title === 'Transaction Submitted' && (
            <OverlayTrigger
              placement="right"
              overlay={
                <Tooltip id="button-tooltip-ts" {...props}>
                  Your transaction has been added to the mempool. It can take up to 30 seconds
                  before your transaction is confirmed.
                </Tooltip>
              }
            >
              <span
                style={{ cursor: 'pointer' }}
                className="material-icons-round ml-1  info-transaction-submitted"
              >
                help_outline
              </span>
            </OverlayTrigger>
          )}
        </div>
        {!props.isConfirmTransaction && (
          <div className={styles.closeBtn} onClick={props.onClose}>
            <span className="material-icons-round">close</span>
          </div>
        )}
      </div>
      {/* * Header */}

      {/* * Body */}
      <div
        className={clsx(props.isConfirmSwap ? styles.confirmSwapContent : styles.content, {
          [styles.noTopPadding]: !props.title,
        })}
      >
        {props.children}
      </div>
      {/* * Body */}
    </Modal>
  );
}
Example #16
Source File: IssueCard.js    From developerPortfolio with MIT License 4 votes vote down vote up
render() {
    const issue = this.props.issue;
    var iconPR;
    var bgColor;
    if (issue["closed"] === false) {
      iconPR = {
        iconifyClass: "octicon:issue-opened",
        style: { color: "#28a745" }
      };
      bgColor = "#dcffe4";
    } else {
      iconPR = {
        iconifyClass: "octicon:issue-closed",
        style: { color: "#d73a49" }
      };
      bgColor = "#ffdce0";
    }

    var subtitleString =
      "#" + issue["number"] + " opened on " + issue["createdAt"].split("T")[0];
    var assignee;
    if (issue["assignees"]["nodes"].length > 0) {
      const name = issue["assignees"]["nodes"][0]["name"];
      assignee = (
        <OverlayTrigger
          key={name}
          placement={"top"}
          style={{ marginBottom: "5px" }}
          overlay={
            <Tooltip id={`tooltip-top`}>
              <strong>{`Assigned to ${name}`}</strong>
            </Tooltip>
          }
        >
          <a
            href={issue["assignees"]["nodes"][0]["url"]}
            target="_blank"
            rel="noopener noreferrer"
          >
            <img
              className="assigned-to-img"
              src={issue["assignees"]["nodes"][0]["avatarUrl"]}
              alt=""
            />
          </a>
        </OverlayTrigger>
      );
    } else {
      assignee = <noscript />;
    }

    return (
      <Fade bottom duration={2000} distance="40px">
        <div
          className="issue-card"
          style={{
            backgroundColor: bgColor,
            border: `1px solid ${iconPR.style.color}`
          }}
        >
          <div className="issue-top">
            <div className="issue-header">
              <span
                className="iconify issue-icons"
                data-icon={iconPR.iconifyClass}
                style={iconPR.style}
                data-inline="false"
              />
              <div className="issue-title-header">
                <p className="issue-title">
                  <a
                    href={issue["url"]}
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    {issue["title"]}
                  </a>
                </p>
                <p className="issue-subtitle">{subtitleString}</p>
              </div>
            </div>
          </div>
          <div className="issue-down">
            <div className="assignee-repo">
              <p className="parent-repo">
                Repository:{" "}
                <a
                  style={{ color: iconPR.style.color }}
                  href={issue["repository"]["url"]}
                >
                  {issue["repository"]["owner"]["login"]}/
                  {issue["repository"]["name"]}
                </a>
              </p>
              <div className="assignee-info">
                {assignee}
              </div>
            </div>
            <div className="owner-img-div">
              <a
                href={issue["repository"]["owner"]["url"]}
                target="_blank"
                rel="noopener noreferrer"
              >
                <img
                  className="owner-img"
                  src={issue["repository"]["owner"]["avatarUrl"]}
                  alt=""
                />
              </a>
            </div>
          </div>
        </div>
      </Fade>
    );
  }
Example #17
Source File: LiquidityInfo.js    From plenty-interface with GNU General Public License v3.0 4 votes vote down vote up
LiquidityInfo = (props) => {
  const isMobile = useMediaQuery('(max-width: 991px)');

  return (
    <div className="lq-details d-flex flex-wrap justify-content-start align-items-center">
      <div className={clsx(isMobile && 'order-1')}>
        <OverlayTrigger
          placement="top"
          overlay={
            <Tooltip id="button-tooltip" {...props}>
              {config.AMM[config.NETWORK][props.tokenIn.name].DEX_PAIRS[props.tokenOut.name]
                ?.type === 'xtz'
                ? props.cteztoxtz
                : config.AMM[config.NETWORK][props.tokenIn.name].DEX_PAIRS[props.tokenOut.name]
                    ?.type === 'veStableAMM'
                ? props.tokenBrate
                : 1 / props.swapData.tokenOutPerTokenIn}
            </Tooltip>
          }
        >
          <div className="details">
            {(props.isStable ? !isNaN(props.cteztoxtz) : 1 / props.swapData.tokenOutPerTokenIn) ? (
              config.AMM[config.NETWORK][props.tokenIn.name].DEX_PAIRS[props.tokenOut.name]
                ?.type === 'xtz' ? (
                props.cteztoxtz
              ) : config.AMM[config.NETWORK][props.tokenIn.name].DEX_PAIRS[props.tokenOut.name]
                  ?.type === 'veStableAMM' ? (
                Number(props.tokenBrate).toFixed(4)
              ) : (
                (1 / props.swapData.tokenOutPerTokenIn).toFixed(4)
              )
            ) : (
              <span className="shimmer">99999</span>
            )}{' '}
            <span className="content">
              {props.tokenIn.name === 'tez'
                ? 'TEZ'
                : props.tokenIn.name === 'ctez'
                ? 'CTEZ'
                : props.tokenIn.name}{' '}
              per{' '}
              {props.tokenOut.name === 'tez'
                ? 'TEZ'
                : props.tokenOut.name === 'ctez'
                ? 'CTEZ'
                : props.tokenOut.name}
            </span>
          </div>
        </OverlayTrigger>
      </div>
      <div className={clsx(isMobile && 'order-3', isMobile && 'mt-2 ', !isMobile && 'ml-2')}>
        <OverlayTrigger
          placement="top"
          overlay={
            <Tooltip id="button-tooltip" {...props}>
              {config.AMM[config.NETWORK][props.tokenIn.name].DEX_PAIRS[props.tokenOut.name]
                ?.type === 'xtz'
                ? props.xtztoctez
                : config.AMM[config.NETWORK][props.tokenIn.name].DEX_PAIRS[props.tokenOut.name]
                    ?.type === 'veStableAMM'
                ? props.tokenArate
                : props.swapData.tokenOutPerTokenIn}
            </Tooltip>
          }
        >
          <div className="details">
            {(props.isStable ? !isNaN(props.xtztoctez) : props.swapData.tokenOutPerTokenIn) ? (
              config.AMM[config.NETWORK][props.tokenIn.name].DEX_PAIRS[props.tokenOut.name]
                ?.type === 'xtz' ? (
                props.xtztoctez
              ) : config.AMM[config.NETWORK][props.tokenIn.name].DEX_PAIRS[props.tokenOut.name]
                  ?.type === 'veStableAMM' ? (
                Number(props.tokenArate).toFixed(4)
              ) : (
                props.swapData.tokenOutPerTokenIn.toFixed(4)
              )
            ) : (
              <span className="shimmer">99999</span>
            )}{' '}
            <span className="content">
              {props.tokenOut.name === 'tez'
                ? 'TEZ'
                : props.tokenOut.name === 'ctez'
                ? 'CTEZ'
                : props.tokenOut.name}{' '}
              per{' '}
              {props.tokenIn.name === 'tez'
                ? 'TEZ'
                : props.tokenIn.name === 'ctez'
                ? 'CTEZ'
                : props.tokenIn.name}
            </span>
          </div>
        </OverlayTrigger>
      </div>
      <div className={clsx(isMobile && 'order-2', 'ml-2')}>
        {(props.tokenIn.name === 'tez' ? props.poolShare : props.lpTokenAmount.estimatedLpOutput) >
        0 ? (
          <OverlayTrigger
            placement="top"
            overlay={
              <Tooltip id="button-tooltip" {...props}>
                {props.tokenIn.name === 'tez'
                  ? props.poolShare
                  : props.lpTokenAmount.estimatedLpOutput
                  ? (props.lpTokenAmount.estimatedLpOutput /
                      (props.swapData.lpTokenSupply + props.lpTokenAmount.estimatedLpOutput)) *
                    100
                  : '0'}
              </Tooltip>
            }
          >
            <div className="details">
              <span className="content">Share of pool:</span>{' '}
              {props.tokenIn.name === 'tez'
                ? Number(props.poolShare) > 0
                  ? Number(props.poolShare).toFixed(4)
                  : '0'
                : props.lpTokenAmount.estimatedLpOutput
                ? (
                    (props.lpTokenAmount.estimatedLpOutput /
                      (props.swapData.lpTokenSupply + props.lpTokenAmount.estimatedLpOutput)) *
                    100
                  ).toFixed(4)
                : '0'}{' '}
              %
            </div>
          </OverlayTrigger>
        ) : (
          <div className="details">
            <span className="content">Share of pool:</span>{' '}
            {props.tokenIn.name === 'tez'
              ? Number(props.poolShare) > 0
                ? Number(props.poolShare).toFixed(4)
                : '0'
              : props.lpTokenAmount.estimatedLpOutput
              ? (
                  (props.lpTokenAmount.estimatedLpOutput /
                    (props.swapData.lpTokenSupply + props.lpTokenAmount.estimatedLpOutput)) *
                  100
                ).toFixed(4)
              : '0'}{' '}
            %
          </div>
        )}
      </div>
      <OverlayTrigger
        placement="top"
        overlay={
          <Tooltip id="button-tooltip" {...props}>
            <>
              <span className="fee-tooltip-heading">Stable pair</span>
              <div>
                <span className="material-icons-round">expand_less</span>
              </div>
              <img
                className="fee-tooltip-bracket"
                src={props.theme === 'light' ? Feetooltip : FeetooltipDark}
              />
              <div className="flex flex-row fee-tooltip-center">
                0.10 % <span className="content ml-1"> LP fee</span>
                <span className="divider-lq-tooltip mx-2"></span>
                <img src={props.theme === 'light' ? Stableswapwhite : StableSwap} />
              </div>
            </>
          </Tooltip>
        }
      >
        <div className={clsx(isMobile && 'order-4', 'details', isMobile && 'mt-2', 'ml-2')}>
          {config.AMM[config.NETWORK][props.tokenIn.name].DEX_PAIRS[props.tokenOut.name]?.type ===
            'xtz' ||
          config.AMM[config.NETWORK][props.tokenIn.name].DEX_PAIRS[props.tokenOut.name]?.type ===
            'veStableAMM'
            ? '0.10'
            : '0.25'}
          % <span className="content">LP fee</span>
          {(config.AMM[config.NETWORK][props.tokenIn.name].DEX_PAIRS[props.tokenOut.name]?.type ===
            'xtz' ||
            config.AMM[config.NETWORK][props.tokenIn.name].DEX_PAIRS[props.tokenOut.name]?.type ===
              'veStableAMM') && (
            <>
              <span className="divider-lq mx-2"></span>
              <img src={props.theme === 'light' ? StableSwap : StableSwapDark} />
            </>
          )}
        </div>
      </OverlayTrigger>
    </div>
  );
}
Example #18
Source File: EmojiRating.jsx    From doc2pen with Creative Commons Zero v1.0 Universal 4 votes vote down vote up
function EmojiRating() {
	return (
		<div className={styles.emojis}>
			{/*MODIFIED the emojis in the experience form*/}

			{/*Triggers Tooltips on hover*/}
			<OverlayTrigger
				placement="top"
				delay={{ show: 200, hide: 200 }}
				overlay={<Tooltip>Liked it</Tooltip>}
			>
				<label>
					<input
						className={styles.radio}
						type="radio"
						value="1"
						name="feedback"
					/>
					<span className={styles.emoji}>&#128077;</span>
				</label>
			</OverlayTrigger>

			<OverlayTrigger
				placement="top"
				delay={{ show: 200, hide: 200 }}
				overlay={<Tooltip>Dislike</Tooltip>}
			>
				<label>
					<input
						className={styles.radio}
						type="radio"
						value="2"
						name="feedback"
					/>
					<span className={styles.emoji}>&#128078;</span>
				</label>
			</OverlayTrigger>

			<OverlayTrigger
				placement="top"
				delay={{ show: 200, hide: 200 }}
				overlay={<Tooltip>Appreciate</Tooltip>}
			>
				<label>
					<input
						className={styles.radio}
						type="radio"
						value="3"
						name="feedback"
						defaultChecked
					/>
					<span className={styles.emoji}>&#128079;</span>
				</label>
			</OverlayTrigger>

			<OverlayTrigger
				placement="top"
				delay={{ show: 200, hide: 200 }}
				overlay={<Tooltip>Loved it</Tooltip>}
			>
				<label>
					<input
						className={styles.radio}
						type="radio"
						value="4"
						name="feedback"
					/>
					<span className={styles.emoji}>&#128147;</span>
				</label>
			</OverlayTrigger>

			<OverlayTrigger
				placement="top"
				delay={{ show: 200, hide: 200 }}
				overlay={<Tooltip>Mind blowing</Tooltip>}
			>
				<label>
					<input
						className={styles.radio}
						type="radio"
						value="5"
						name="feedback"
					/>
					<span className={styles.emoji}>&#129327;</span>
				</label>
			</OverlayTrigger>
		</div>
	);
}
Example #19
Source File: ConfirmRemoveLiquidity.js    From plenty-interface with GNU General Public License v3.0 4 votes vote down vote up
ConfirmRemoveLiquidity = (props) => {
  return (
    <Modal
      show={props.showConfirmRemoveSupply}
      onHide={props.onHide}
      className="confirm-swap-modal confirm-add-liquidity-modal"
    >
      <Modal.Header>
        <Modal.Title>You will receive</Modal.Title>
        <Modal.Title className={'float-right'}>
          <span
            onClick={props.onHide}
            style={{ cursor: 'pointer' }}
            className="material-icons-round"
          >
            close
          </span>
        </Modal.Title>
      </Modal.Header>
      <Modal.Body>
        <>
          <div className="swap-content-box-wrapper pb-0">
            <div className="header-line"></div>
            <div className="swap-content-box">
              <div className=" removing-padding-confirm-supply">
                <div className="confirm-supply-remove">
                  <button className="token-left">
                    <img src={props.tokenIn.image} className="button-logo" />
                    {props.tokenIn.name === 'tez'
                      ? 'TEZ'
                      : props.tokenIn.name === 'ctez'
                      ? 'CTEZ'
                      : props.tokenIn.name}{' '}
                  </button>
                </div>
                <OverlayTrigger
                  placement="top"
                  overlay={
                    <Tooltip id="button-tooltip" {...props}>
                      {fromExponential(props.removableTokens.tokenFirst_Out)}
                    </Tooltip>
                  }
                >
                  <div className="token-user-input-wrapper add-padding">
                    {props.removableTokens.tokenFirst_Out
                      ? props.removableTokens.tokenFirst_Out.toFixed(6)
                      : '0.00'}
                  </div>
                </OverlayTrigger>
              </div>
            </div>

            <div className="arrow-center-remove-lq">
              <span className="material-icons-round">add</span>
            </div>

            <div className="swap-content-box add-margin-b">
              <div className="removing-padding-confirm-supply">
                <div className="confirm-supply-remove">
                  <button className="token-left">
                    <img src={props.tokenOut.image} className="button-logo" />
                    {props.tokenOut.name === 'tez'
                      ? 'TEZ'
                      : props.tokenOut.name === 'ctez'
                      ? 'CTEZ'
                      : props.tokenOut.name}{' '}
                  </button>
                </div>
                <OverlayTrigger
                  placement="top"
                  overlay={
                    <Tooltip id="button-tooltip" {...props}>
                      {fromExponential(props.removableTokens.tokenSecond_Out)}
                    </Tooltip>
                  }
                >
                  <div className="token-user-input-wrapper add-padding">
                    {props.removableTokens.tokenSecond_Out
                      ? props.removableTokens.tokenSecond_Out.toFixed(6)
                      : '0.00'}
                  </div>
                </OverlayTrigger>
              </div>
            </div>
          </div>
          <div className="slippage-info">
            Output is estimated. If the price changes by more than {props.slippage}% your
            transaction will revert.
          </div>
          <div className="rates-confirm-supply-remove flex justify-between ">
            <p className="rates-label">Rates</p>
            <div className="">
              {props.swapData ? (
                <p className="confirm-supply-amt-details">
                  1{' '}
                  {props.tokenIn.name === 'tez'
                    ? 'TEZ'
                    : props.tokenIn.name === 'ctez'
                    ? 'CTEZ'
                    : props.tokenIn.name}{' '}
                  ={' '}
                  <span className="rates-value">
                    {props.isStableSwap
                      ? props.xtztoctez
                      : props.swapData.tokenOutPerTokenIn?.toFixed(10)}{' '}
                    {props.tokenOut.name === 'tez'
                      ? 'TEZ'
                      : props.tokenOut.name === 'ctez'
                      ? 'CTEZ'
                      : props.tokenOut.name}
                  </span>
                </p>
              ) : null}

              {props.swapData ? (
                <p className="mt-1 confirm-supply-amt-details">
                  1{' '}
                  {props.tokenOut.name === 'tez'
                    ? 'TEZ'
                    : props.tokenOut.name === 'ctez'
                    ? 'CTEZ'
                    : props.tokenOut.name}{' '}
                  ={' '}
                  <span className="rates-value">
                    {props.isStableSwap
                      ? props.cteztoxtz
                      : (1 / props.swapData.tokenOutPerTokenIn).toFixed(10)}{' '}
                    {props.tokenIn.name === 'tez'
                      ? 'TEZ'
                      : props.tokenIn.name === 'ctez'
                      ? 'CTEZ'
                      : props.tokenIn.name}
                  </span>
                </p>
              ) : null}
            </div>
          </div>

          <div className="divider-confirm-supply-remove"></div>
          <div className="flex justify-content-between remove-footer">
            <div className="lp-pair-remove">
              {props.tokenIn.name === 'tez'
                ? 'TEZ'
                : props.tokenIn.name === 'ctez'
                ? 'CTEZ'
                : props.tokenIn.name}{' '}
              /{' '}
              {props.tokenOut.name === 'tez'
                ? 'TEZ'
                : props.tokenOut.name === 'ctez'
                ? 'CTEZ'
                : props.tokenOut.name}{' '}
              Burned LP
            </div>
            <OverlayTrigger
              placement="top"
              overlay={
                <Tooltip id="button-tooltip" {...props}>
                  {fromExponential(props.firstTokenAmount)}
                </Tooltip>
              }
            >
              <div className="lp-pair-value">{Number(props.firstTokenAmount).toFixed(10)}</div>
            </OverlayTrigger>
          </div>
          <div className="confirm-supply-button">
            <Button
              onClick={props.confirmRemoveLiquidity}
              color={'primary'}
              className={'mt-4 w-100 '}
              loading={props.loading}
            >
              Confirm
            </Button>
          </div>
        </>
      </Modal.Body>
    </Modal>
  );
}
Example #20
Source File: footer.js    From stacker.news with MIT License 4 votes vote down vote up
export default function Footer ({ noLinks }) {
  const query = gql`
    {
      connectAddress
    }
  `

  const { data } = useQuery(query, { fetchPolicy: 'cache-first' })

  const darkMode = useDarkMode(false, {
    // set this so it doesn't try to use classes
    onChange: handleThemeChange
  })

  const [mounted, setMounted] = useState()

  useEffect(() => {
    setMounted(true)
  })

  return (
    <footer>
      <Container className='mb-3 mt-4'>
        {!noLinks &&
          <div className='mb-2' style={{ fontWeight: 500 }}>
            {mounted &&
              <div className='mb-2'>
                {darkMode.value
                  ? <Sun onClick={() => darkMode.toggle()} className='fill-grey theme' />
                  : <Moon onClick={() => darkMode.toggle()} className='fill-grey theme' />}
              </div>}
            <Link href='/faq' passHref>
              <a className='nav-link p-0 d-inline-flex'>
                faq
              </a>
            </Link>
            <span className='mx-2 text-muted'> \ </span>
            <Link href='/story' passHref>
              <a className='nav-link p-0 d-inline-flex'>
                story
              </a>
            </Link>
            <span className='mx-2 text-muted'> \ </span>
            <OverlayTrigger trigger='click' placement='top' overlay={AnalyticsPopover} rootClose>
              <div className='nav-link p-0 d-inline-flex' style={{ cursor: 'pointer' }}>
                analytics
              </div>
            </OverlayTrigger>
            <span className='mx-2 text-muted'> \ </span>
            <OverlayTrigger trigger='click' placement='top' overlay={ChatPopover} rootClose>
              <div className='nav-link p-0 d-inline-flex' style={{ cursor: 'pointer' }}>
                chat
              </div>
            </OverlayTrigger>
            <span className='mx-2 text-muted'> \ </span>
            <a href='/rss' className='nav-link p-0 d-inline-flex' target='_blank'>
              rss
            </a>
          </div>}
        {data &&
          <div
            className={`text-small mx-auto mb-1 ${styles.connect}`}
          >
            <span className='nav-item text-muted mr-2'>connect:</span>
            <CopyInput
              size='sm'
              groupClassName='mb-0 w-100'
              readOnly
              placeholder={data.connectAddress}
            />
          </div>}
        <small>
          <a className={`d-inline-block ${styles.contrastLink}`} href='https://github.com/stackernews/stacker.news' target='_blank' rel='noreferrer'>
            This is free open source software<Github width={20} height={20} className='mx-1' />
          </a>
          <span className='d-inline-block text-muted'>
            made with sound love in Austin<Texas className='mx-1' width={20} height={20} />
            by<a href='https://twitter.com/k00bideh' target='_blank' rel='noreferrer' className='text-twitter d-inline-block'><Twitter width={20} height={20} className='ml-1' />@k00bideh</a>
          </span>
        </small>
      </Container>
    </footer>
  )
}
Example #21
Source File: SwapDetails.js    From plenty-interface with GNU General Public License v3.0 4 votes vote down vote up
SwapDetails = (props) => {
  const [isOpen, setOpen] = useState(false);
  const [isConvert, setConvert] = useState(false);

  const swapRoute = useMemo(() => {
    if (props.routePath?.length > 2) {
      return props.routePath.map((tokenName) => tokens.find((token) => token.name === tokenName));
    }

    return null;
  }, [props.routePath]);

  if (!props.firstTokenAmount && !swapRoute) {
    return null;
  }
  const ratesConvert = (e) => {
    e.stopPropagation();
    setConvert(!isConvert);
  };

  return (
    <>
      <div
        className={clsx(
          'swap-detail-wrapper',
          !isOpen && 'closedbg',
          isOpen && 'open-swap-detail-wrapper-first',
        )}
        onClick={() => setOpen(!isOpen)}
        id="topdiv"
      >
        <div className="space-between justify-content-between" style={{ cursor: 'pointer' }}>
          <div className="flex">
            <p className="price-formula whitespace-prewrap  flex flex-row">
              1{' '}
              {isConvert
                ? props.tokenOut.name === 'tez'
                  ? 'TEZ'
                  : props.tokenOut.name === 'ctez'
                  ? 'CTEZ'
                  : props.tokenOut.name
                : props.tokenIn.name === 'tez'
                ? 'TEZ'
                : props.tokenIn.name === 'ctez'
                ? 'CTEZ'
                : props.tokenIn.name}{' '}
              ={' '}
              <OverlayTrigger
                placement="top"
                overlay={
                  <Tooltip id="button-tooltip" {...props}>
                    {props.isStableSwap
                      ? fromExponential(Number(props.computedOutDetails.data.exchangeRate))
                      : fromExponential(
                          Number(props.routeData.bestRouteUntilNoInput.tokenOutPerTokenIn),
                        )}
                  </Tooltip>
                }
              >
                <div>
                  {props.isStableSwap
                    ? isConvert
                      ? Number(1 / props.computedOutDetails.data.exchangeRate).toFixed(3)
                      : Number(props.computedOutDetails.data.exchangeRate).toFixed(3)
                    : props.routeData.bestRouteUntilNoInput.tokenOutPerTokenIn
                    ? isConvert
                      ? Number(
                          1 / props.routeData.bestRouteUntilNoInput.tokenOutPerTokenIn,
                        ).toFixed(3)
                      : Number(props.routeData.bestRouteUntilNoInput.tokenOutPerTokenIn).toFixed(3)
                    : 0}{' '}
                  {isConvert
                    ? props.tokenIn.name === 'tez'
                      ? 'TEZ'
                      : props.tokenIn.name === 'ctez'
                      ? 'CTEZ'
                      : props.tokenIn.name
                    : props.tokenOut.name === 'tez'
                    ? 'TEZ'
                    : props.tokenOut.name === 'ctez'
                    ? 'CTEZ'
                    : props.tokenOut.name}
                </div>
              </OverlayTrigger>
              <span
                className="material-icons-round convert ml-1"
                onClick={(e) => ratesConvert(e)}
                style={{ cursor: 'pointer' }}
              >
                cached
              </span>
            </p>
          </div>
          <span
            className={`material-icons-round buttonanim button--trigger open ${
              props.firstTokenAmount > 0 && isOpen ? 'dropdown-open' : 'dropdown-close'
            }`}
            style={{ cursor: 'pointer' }}
          >
            expand_more
          </span>
          {/* {props.firstTokenAmount > 0 && isOpen ? (
            <span
              className="material-icons-round buttonanim button--trigger-todisappear flex open"
              style={{ cursor: 'pointer' }}
            >
              keyboard_arrow_up
            </span>
          ) : (
            <span
              className="material-icons-round buttonanim button--trigger flex open"
              style={{ cursor: 'pointer' }}
            >
              keyboard_arrow_down
            </span>
          )} */}
        </div>
      </div>
      {props.firstTokenAmount > 0}
      {isOpen && (
        <div className={clsx('swap-detail-wrapper-open', 'buttonanim button--disapear')}>
          <div className="scale-in-animation">
            {/* {isOpen ? ( */}
            <>
              <div className="flex flex-row  align-items-center swap-sub-details">
                {' '}
                <p className="swap-detail-amt-details">Minimum received </p>
                <OverlayTrigger
                  placement="top"
                  key="top"
                  overlay={
                    <Tooltip id="button-tooltip-swap-details-minimum-received" {...props}>
                      Your transaction will revert if there is a large, unfavorable price movement
                      before it is confirmed.
                    </Tooltip>
                  }
                >
                  <span
                    style={{ cursor: 'pointer' }}
                    className="material-icons-round ml-1 swap-detail-amt-details"
                  >
                    help_outline
                  </span>
                </OverlayTrigger>
                <p className="swap-detail-amt-details-value ml-auto">
                  {props.computedOutDetails.data.finalMinimumOut
                    ? props.computedOutDetails.data.finalMinimumOut
                    : '0.00'}{' '}
                  {props.tokenOut.name === 'tez'
                    ? 'TEZ'
                    : props.tokenOut.name === 'ctez'
                    ? 'CTEZ'
                    : props.tokenOut.name}
                </p>
              </div>
              <div className="flex flex-row align-items-center swap-sub-details">
                <p className="swap-detail-amt-details">Price Impact </p>
                <OverlayTrigger
                  key="top"
                  placement="top"
                  overlay={
                    <Tooltip id="button-tooltip-swap-details" {...props}>
                      The difference between the market price and estimated price due to trade size.
                    </Tooltip>
                  }
                >
                  <span
                    style={{ cursor: 'pointer' }}
                    className="material-icons-round ml-1 swap-detail-amt-details"
                  >
                    help_outline
                  </span>
                </OverlayTrigger>
                <p
                  className={clsx(
                    'swap-detail-amt-details-value ml-auto',
                    props.computedOutDetails.data?.priceImpact > 3 && 'error-text-color',
                  )}
                >
                  {props.computedOutDetails.data.priceImpact
                    ? props.computedOutDetails.data.priceImpact
                    : '0.00'}{' '}
                  %
                </p>
              </div>
              <div className="flex flex-row align-items-center  swap-sub-details-padding">
                <p className="swap-detail-amt-details">Fee </p>
                <OverlayTrigger
                  placement="top"
                  key="top"
                  overlay={
                    <Tooltip id="button-tooltip-swap-details" {...props}>
                      Fees are 0.35% for each volatile swap and 0.10% for each stable swap.
                    </Tooltip>
                  }
                >
                  <span
                    style={{ cursor: 'pointer' }}
                    className="material-icons-round ml-1 swap-detail-amt-details"
                  >
                    help_outline
                  </span>
                </OverlayTrigger>
                <p className="swap-detail-amt-details-value ml-auto">
                  {props.isStableSwap ? '0.10' : props.computedOutDetails.data.maxfee} %
                </p>
              </div>
              {props.isConfirmSwap && !props.isStableSwap && (
                <div className="flex flex-row align-items-center">
                  <p className="swap-detail-amt-details">xPlenty Fee </p>
                  <OverlayTrigger
                    placement="top"
                    key="top"
                    overlay={
                      <Tooltip
                        id="button-tooltip-swap-details"
                        arrowProps={{ styles: { display: 'none' } }}
                      >
                        A portion of each trade (0.09%) goes to xPLENTY holders as a protocol
                        incentive.
                      </Tooltip>
                    }
                  >
                    <span
                      style={{ cursor: 'pointer' }}
                      className="material-icons-round ml-1 swap-detail-amt-details"
                    >
                      help_outline
                    </span>
                  </OverlayTrigger>
                  <p className="swap-detail-amt-details-value ml-auto">
                    {props.firstTokenAmount / 1000}{' '}
                    {props.tokenIn.name === 'tez'
                      ? 'TEZ'
                      : props.tokenIn.name === 'ctez'
                      ? 'CTEZ'
                      : props.tokenIn.name}
                  </p>
                </div>
              )}
              {props.isConfirmSwap ? (
                <div className="flex flex-row align-items-center">
                  <p className="swap-detail-amt-details">Slippage tolerance </p>
                  <OverlayTrigger
                    placement="top"
                    key="top"
                    overlay={
                      <Tooltip
                        id="button-tooltip-swap-details"
                        arrowProps={{ styles: { display: 'none' } }}
                      >
                        Change the slippage tolerance in the transaction settings.
                      </Tooltip>
                    }
                  >
                    <span
                      style={{ cursor: 'pointer' }}
                      className="material-icons-round ml-1 swap-detail-amt-details"
                    >
                      help_outline
                    </span>
                  </OverlayTrigger>
                  <p className="swap-detail-amt-details ml-auto">{props.slippage} %</p>
                </div>
              ) : null}
            </>
            {/* ) : null} */}
            {props.firstTokenAmount && swapRoute && <hr className="swap-details-divider" />}
            {props.firstTokenAmount && swapRoute && (
              <>
                <div className="flex flex-row">
                  <p className="swap-detail-amt-details route-heading">Route </p>
                  <OverlayTrigger
                    placement="top"
                    key="top"
                    overlay={
                      <Tooltip id="button-tooltip-swap-details-router" {...props}>
                        Routing through these tokens results in the best price for your trade.
                        <div className="flex flex-row">
                          {props.theme === 'light' ? <Router /> : <RouterDark />}
                          {props.theme === 'light' ? (
                            <Bracket className="router-bracket" />
                          ) : (
                            <BracketDark className="router-bracket" />
                          )}
                          <MdChevronRight className={clsx('router-arrow', 'ml-1')} fontSize={20} />
                          <span className="router-text">Stable pair</span>
                        </div>
                      </Tooltip>
                    }
                  >
                    <span
                      style={{ cursor: 'pointer' }}
                      className="material-icons-round ml-1 swap-detail-amt-details"
                    >
                      help_outline
                    </span>
                  </OverlayTrigger>
                </div>

                <div className="swap-detail-route-container mt-3">
                  {swapRoute.map((token, idx) => (
                    <div key={token.name} className="d-flex my-2 align-self-center">
                      <div
                        className={clsx(
                          idx !== 0 &&
                            props.stableList[idx - 1] === true &&
                            'outer-border-stableswap d-flex',
                        )}
                      >
                        {idx !== 0 && props.stableList[idx - 1] === true && (
                          <div>
                            <span className="stableswap-img">
                              {props.theme === 'light' ? <Stableswap /> : <StableswapDark />}
                            </span>
                          </div>
                        )}
                        <div
                          className={clsx(
                            idx !== 0 && props.stableList[idx - 1] === true
                              ? 'stablepair-outline'
                              : 'route-Outline',
                          )}
                        >
                          <Image src={token.image} height={18} width={18} alt={''} />
                          <span className="ml-1 my-auto token-name-route">
                            {token.name === 'tez'
                              ? 'TEZ'
                              : token.name === 'ctez'
                              ? 'CTEZ'
                              : token.name}
                          </span>
                        </div>
                      </div>
                      {swapRoute[idx + 1] && (
                        <MdChevronRight
                          className={clsx(
                            idx !== 0 && props.stableList[idx - 1] === true
                              ? 'route-arrow-stable'
                              : 'route-arrow',
                          )}
                          fontSize={20}
                        />
                      )}
                    </div>
                  ))}
                </div>
              </>
            )}
          </div>
        </div>
      )}
    </>
  );
}
Example #22
Source File: PullRequestCard.js    From developerPortfolio with MIT License 4 votes vote down vote up
render() {
    const pullRequest = this.props.pullRequest;
    var iconPR;
    var bgColor;
    if (pullRequest["state"] === "OPEN") {
      iconPR = {
        iconifyClass: "octicon:git-pull-request",
        style: { color: "#4CAF50" }
      };
      bgColor = "#dcffe4";
    } else if (pullRequest["state"] === "MERGED") {
      iconPR = {
        iconifyClass: "octicon:git-merge",
        style: { color: "#512DA8" }
      };
      bgColor = "#f5f0ff";
    } else {
      iconPR = {
        iconifyClass: "octicon:git-pull-request",
        style: { color: "#D32F2F" }
      };
      bgColor = "#ffdce0";
    }

    var subtitleString =
      "#" +
      pullRequest["number"] +
      " opened on " +
      pullRequest["createdAt"].split("T")[0];
    var mergedBy;
    if (pullRequest["mergedBy"] !== null) {
      const name = pullRequest["mergedBy"]["login"];
      mergedBy = (
        <OverlayTrigger
          key={name}
          placement={"top"}
          style={{ marginBottom: "5px" }}
          overlay={
            <Tooltip id={`tooltip-top`}>
              <strong>{`Merged by ${name}`}</strong>
            </Tooltip>
          }
        >
          <a
            href={pullRequest["mergedBy"]["url"]}
            target="_blank"
            rel="noopener noreferrer"
          >
            <img
              className="merge-by-img"
              src={pullRequest["mergedBy"]["avatarUrl"]}
              alt=""
            />
          </a>
        </OverlayTrigger>
      );
    } else {
      mergedBy = <noscript></noscript>;
    }

    return (
      <Fade bottom duration={2000} distance="40px">
        <div
          className="pull-request-card"
          style={{
            backgroundColor: bgColor,
            border: `1px solid ${iconPR.style.color}`
          }}
        >
          <div className="pr-top">
            <div className="pr-header">
              <span
                className="iconify pr-icons"
                data-icon={iconPR.iconifyClass}
                style={iconPR.style}
                data-inline="false"
              />
              <div className="pr-title-header">
                <p className="pr-title">
                  <a
                    href={pullRequest["url"]}
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    {pullRequest["title"]}
                  </a>
                </p>
                <p className="pr-subtitle">{subtitleString}</p>
              </div>
            </div>
            <div className="files-changed-header">
              <p
                className="files-changed-text"
                style={{ backgroundColor: iconPR.style.color }}
              >
                {pullRequest["changedFiles"]}
              </p>
              <p className="files-changed-text-2">Files Changed</p>
            </div>
          </div>
          <div className="pr-down">
            <div className="changes-repo">
              <p className="parent-repo">
                Repository:{" "}
                <a
                  style={{ color: iconPR.style.color }}
                  href={pullRequest["baseRepository"]["url"]}
                >
                  {pullRequest["baseRepository"]["owner"]["login"]}/
                  {pullRequest["baseRepository"]["name"]}
                </a>
              </p>
              <div className="changes-files">
                <p className="additions-files">
                  <strong>{pullRequest["additions"]} + </strong>
                </p>
                <p className="deletions-files">
                  <strong>{pullRequest["deletions"]} - </strong>
                </p>
                {mergedBy}
              </div>
            </div>
            <div className="owner-img-div">
              <a
                href={pullRequest["baseRepository"]["owner"]["url"]}
                target="_blank"
                rel="noopener noreferrer"
              >
                <img
                  className="owner-img"
                  src={pullRequest["baseRepository"]["owner"]["avatarUrl"]}
                  alt=""
                />
              </a>
            </div>
          </div>
        </div>
      </Fade>
    );
  }
Example #23
Source File: FarmCardBottom.js    From plenty-interface with GNU General Public License v3.0 4 votes vote down vote up
FarmCardBottom = (props) => {
  const dispatch = useDispatch();
  const { properties, farmData, values } = props.farmCardData;
  const [isExpanded, toggleExpand] = useState(false);
  const target = useRef(null);

  const onWithdrawalFeeClick = () => {
    dispatch(
      openCloseFarmsModal({
        open: FARM_PAGE_MODAL.WITHDRAWAL,
        contractAddress: farmData.CONTRACT,
        withdrawalFeeType: farmData.withdrawalFeeType,
      }),
    );
  };

  const stakedAmount = useMemo(() => {
    return Object.prototype.hasOwnProperty.call(props.userStakes, farmData.CONTRACT)
      ? props.userStakes[farmData.CONTRACT].stakedAmount
      : 0;
  }, [farmData.CONTRACT, props.userStakes, props.userAddress]);

  return (
    <>
      <div
        className={clsx(styles.plentyCardContent, {
          'mt-4': isExpanded,
          'pt-0': !isExpanded,
          [styles.topBorder]: isExpanded,
          [styles.bottomBorder]: isExpanded,
        })}
      >
        {(stakedAmount > 0 || isExpanded) && (
          <div className="d-flex">
            {properties.isDualFarm ? (
              <div
                className={`${styles.harvestStakeAmt} mr-2 d-flex justify-content-between align-center`}
                style={{ paddingRight: '8px' }}
              >
                <div
                  style={{
                    borderRight: '1px solid rgba(0, 0, 0, 0.04)',
                    paddingRight: '16%',
                  }}
                >
                  <Image
                    height={17}
                    src={properties.harvestImg}
                    fuild
                    className="mt-auto mb-auto ml-2"
                  />
                  <span style={{ fontSize: '10px', marginLeft: '6px' }}>
                    {values &&
                    props.userAddress !== null &&
                    Object.prototype.hasOwnProperty.call(
                      props.harvestValueOnFarms,
                      props.isActiveOpen,
                    ) &&
                    Object.prototype.hasOwnProperty.call(
                      props.harvestValueOnFarms[props.isActiveOpen],
                      farmData.CONTRACT,
                    ) &&
                    props.harvestValueOnFarms[props.isActiveOpen][farmData.CONTRACT]
                      .totalRewards[0] > 0 ? (
                      props.harvestValueOnFarms[props.isActiveOpen][
                        farmData.CONTRACT
                      ].totalRewards[0].toFixed(4)
                    ) : (
                      <span className="shimmer">99999</span>
                    )}
                  </span>
                </div>

                <div>
                  <Image
                    height={17}
                    src={properties.harvestImg1}
                    fuild
                    className="mt-auto mb-auto ml-2"
                  />
                  <span style={{ fontSize: '10px', marginLeft: '6px' }}>
                    {values &&
                    props.userAddress !== null &&
                    Object.prototype.hasOwnProperty.call(
                      props.harvestValueOnFarms,
                      props.isActiveOpen,
                    ) &&
                    Object.prototype.hasOwnProperty.call(
                      props.harvestValueOnFarms[props.isActiveOpen],
                      farmData.CONTRACT,
                    ) &&
                    props.harvestValueOnFarms[props.isActiveOpen][farmData.CONTRACT]
                      .totalRewards[1] > 0
                      ? props.harvestValueOnFarms[props.isActiveOpen][
                          farmData.CONTRACT
                        ].totalRewards[1].toFixed(4)
                      : 0}
                  </span>
                </div>
              </div>
            ) : (
              <div className={clsx(styles.harvestStakeAmt, 'mr-2 justify-content-between')}>
                <Image
                  height={31}
                  src={properties.harvestImg}
                  fuild
                  className="mt-auto mb-auto ml-2"
                />
                <span>
                  {values &&
                  props.userAddress !== null &&
                  Object.prototype.hasOwnProperty.call(
                    props.harvestValueOnFarms,
                    props.isActiveOpen,
                  ) &&
                  Object.prototype.hasOwnProperty.call(
                    props.harvestValueOnFarms[props.isActiveOpen],
                    farmData.CONTRACT,
                  ) &&
                  props.harvestValueOnFarms[props.isActiveOpen][farmData.CONTRACT].totalRewards >
                    0 ? (
                    props.harvestValueOnFarms[props.isActiveOpen][
                      farmData.CONTRACT
                    ].totalRewards.toFixed(6)
                  ) : (
                    <span className="shimmer">99999999</span>
                  )}
                </span>
              </div>
            )}

            <Button
              onClick={() => {
                props.setShowConfirmTransaction(true);
                props.setLoader(true);
                localStorage.setItem('stakePair', properties.source);
                props.setFloaterValue({
                  value: properties.isDualFarm
                    ? props.harvestValueOnFarms[props.isActiveOpen][farmData.CONTRACT]
                        .totalRewards[0] > 0
                      ? props.harvestValueOnFarms[props.isActiveOpen][
                          farmData.CONTRACT
                        ].totalRewards[0].toFixed(4)
                      : null
                    : props.harvestValueOnFarms[props.isActiveOpen][farmData.CONTRACT]
                        .totalRewards > 0
                    ? props.harvestValueOnFarms[props.isActiveOpen][
                        farmData.CONTRACT
                      ].totalRewards.toFixed(6)
                    : null,
                  pair: localStorage.getItem('stakePair'),
                  type: 'Harvest',
                });
                props.harvestOnFarm(
                  props.farmCardData.identifier,
                  props.isActiveOpen,
                  props.farmCardData.position,
                  props.setShowConfirmTransaction,
                  props.setLoader,
                );
              }}
              color={stakedAmount > 0 ? 'primary' : 'default'}
              loading={
                props.harvestOperation.tokenPair === props.identifier &&
                props.harvestOperation.isLoading
              }
            >
              Harvest
            </Button>
          </div>
        )}

        {isExpanded && (
          <>
            <div className="mt-3 mb-2">{props.title}</div>

            <div className="d-flex">
              <div
                className={clsx(styles.harvestStakeAmt, 'mr-2 justify-content-end', {
                  [styles.empty]: !stakedAmount,
                })}
              >
                <span>{stakedAmount?.toFixed(5)}</span>
              </div>
              <span />
              {stakedAmount > 0 || !props.isActiveOpen ? (
                <QuantityButton
                  onAddDisabled={!props.isActiveOpen}
                  onRemoveDisabled={stakedAmount <= 0}
                  onAdd={() =>
                    props.openFarmsStakeModal(
                      props.farmCardData.identifier,
                      properties.title,
                      farmData.CONTRACT,
                      props.farmCardData.position,
                    )
                  }
                  onRemove={() =>
                    props.openFarmsUnstakeModal(
                      props.farmCardData.identifier,
                      farmData.CONTRACT,
                      properties.title,
                      farmData.withdrawalFeeType,
                      props.farmCardData.position,
                    )
                  }
                />
              ) : (
                props.isActiveOpen && (
                  <Button
                    onClick={() =>
                      props.openFarmsStakeModal(
                        props.farmCardData.identifier,
                        properties.title,
                        farmData.CONTRACT,
                        props.farmCardData.position,
                      )
                    }
                    color={'default'}
                  >
                    Stake
                  </Button>
                )
              )}
            </div>
          </>
        )}
      </div>

      {isExpanded && (
        <>
          <div className={clsx(styles.plentyCardContent, styles.bottomBorder, 'd-flex')}>
            <div className={clsx(styles.rightBorder, 'w-50 text-center')}>
              <div>Deposit Fee</div>
              <OverlayTrigger
                key="top"
                placement="top"
                overlay={
                  <Tooltip id={'deposit-fee-tooltip'} arrowProps={{ styles: { display: 'none' } }}>
                    No deposit fee
                  </Tooltip>
                }
              >
                <Button
                  id={'deposit-fee'}
                  ref={target}
                  size="small"
                  color="mute"
                  startIcon="help_outline"
                  className="mt-1 ml-auto mr-auto"
                  rounded={false}
                  onClick={undefined}
                >
                  0%
                </Button>
              </OverlayTrigger>
            </div>

            <div className={'w-50 text-center'}>
              <div>Withdrawal Fee</div>
              {props.farmCardData.identifier === 'CTEZ - TEZ' ? (
                <OverlayTrigger
                  key="top"
                  placement="top"
                  overlay={
                    <Tooltip
                      id={'deposit-fee-tooltip'}
                      arrowProps={{ styles: { display: 'none' } }}
                    >
                      No Withdrawal Fee
                    </Tooltip>
                  }
                >
                  <Button
                    size="small"
                    color="mute"
                    startIcon="help_outline"
                    className="mt-1 ml-auto mr-auto"
                    rounded={false}
                  >
                    0 %{' '}
                  </Button>
                </OverlayTrigger>
              ) : (
                <Button
                  size="small"
                  color="mute"
                  startIcon="help_outline"
                  className="mt-1 ml-auto mr-auto"
                  rounded={false}
                  onClick={onWithdrawalFeeClick}
                >
                  Variable
                </Button>
              )}
            </div>
          </div>

          <div className={styles.plentyCardContent}>
            <Button
              className="w-100"
              color={'default'}
              onClick={() =>
                window.open(
                  `https://better-call.dev/mainnet/${farmData.CONTRACT}/operations`,
                  '_blank',
                )
              }
            >
              View On Tezos
            </Button>
          </div>
        </>
      )}
      <div className="d-flex justify-content-center">
        <Button
          onClick={() => toggleExpand(!isExpanded)}
          isIconBtn={true}
          startIcon={isExpanded ? 'expand_less' : 'expand_more'}
          color={'mute'}
        />
      </div>
    </>
  );
}
Example #24
Source File: LaddersQuestionPage.js    From Frontend with Apache License 2.0 4 votes vote down vote up
function LaddersQuestionPage(props) {
  // console.log(props);
  const [type1, setType1] = useState(
    props.type === 'list' ? 'practice' : 'ladder'
  )
  const [problems, setProblems] = useState(null)
  const [show, setShow] = useState(true)
  const creds = JSON.parse(localStorage.getItem('creds'))
  const [prevPage, setPrevPage] = useState('')
  const [firstPage, setFirstPage] = useState(
    '/' + props.wise + '/' + type1 + '/' + props.slug + '?page=1'
  )
  const [nextPage, setNextPage] = useState('')
  const [lastPage, setLastPage] = useState('')
  const [locked, setlocked] = useState(false)

  //for reload button after doing the question
  const updateReload = () => {
    window.location.reload()
  }

  useEffect(() => {
    if (problems != null) {
      //URLs for related pages
      setPrevPage(
        '/' +
          props.wise +
          '/' +
          type1 +
          '/' +
          props.slug +
          '?page=' +
          (problems.meta.current_page - 1)
      )
      setNextPage(
        '/' +
          props.wise +
          '/' +
          type1 +
          '/' +
          props.slug +
          '?page=' +
          (problems.meta.current_page + 1)
      )
      setLastPage(
        '/' +
          props.wise +
          '/' +
          type1 +
          '/' +
          props.slug +
          '?page=' +
          problems.meta.last_page
      )

      //if the last unsolved question is not at this page
      if (problems.meta.curr_unsolved_page != problems.meta.current_page) {
        setlocked(true)
      }
    }
  })

  useEffect(() => {
    if (creds) {
      async function fetchData() {
        const res = await fetch(
          `https://api.codedigger.tech/lists/${props.wise}/${props.type}/${props.slug}${props.pageNo}`,
          {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
              Authorization: `Bearer ${creds.access}`,
            },
          }
        )
        res
          .json()
          .then((res) => setProblems(res))
          .then((show) => setShow(false))
      }
      fetchData()
    } else {
      async function fetchData() {
        const res = await fetch(
          `https://api.codedigger.tech/lists/${props.wise}/${props.type}/${props.slug}${props.pageNo}`,
          {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
            },
          }
        )
        res
          .json()
          .then((res) => setProblems(res))
          .then((show) => setShow(false))
      }
      fetchData()
    }
  }, [])

  var count = 0
  var solvedBtn = -1
  var button = false

  return show == true ? (
    <Loading />
  ) : (
    <div>
      <Navbar />
      <h2 style={{ textAlign: 'center', marginTop: '120px', fontSize: '45px' }}>
        {problems.meta.name}
      </h2>

      {/* Button to reload the page whenever the user solves a question */}
      <Button variant="success" className="updateBtn" onClick={updateReload}>
        Update
      </Button>
      <div
        className="container-fluid"
        style={{
          display: 'flex',
          flexDirection: 'row',
          alignItems: 'center',
          padding: '0rem 0rem',
        }}
      >
        {/* if it is first page dont display prev and first page pointers */}
        {problems.meta.current_page != 1 ? (
          <>
            <OverlayTrigger placement="top" overlay={renderTooltip1}>
              <a href={firstPage}>
                <FontAwesomeIcon
                  className="pageNavIcons"
                  icon={faAngleDoubleLeft}
                />
              </a>
            </OverlayTrigger>

            <OverlayTrigger placement="top" overlay={renderTooltip2}>
              <a href={prevPage}>
                <FontAwesomeIcon
                  className="pageNavIcons"
                  icon={faAngleLeft}
                  style={{ marginLeft: '13px' }}
                />
              </a>
            </OverlayTrigger>
          </>
        ) : (
          <></>
        )}

        {problems.meta.current_page === 1 ? (
          <div
            className="container-card marginLeftOfCards"
            style={{ marginTop: '75px' }}
          >
            {problems.result.map((ProblemData) => {
              count++
              if (ProblemData.solved === false && solvedBtn === -1) {
                solvedBtn = count
              }
              return (
                <>
                  {locked ? (
                    <MainCard
                      type={props.type}
                      count={20}
                      ProblemData={ProblemData}
                      solvedBtn={10}
                    />
                  ) : (
                    <MainCard
                      type={props.type}
                      count={count}
                      ProblemData={ProblemData}
                      solvedBtn={solvedBtn}
                    />
                  )}
                </>
              )
            })}
          </div>
        ) : problems.meta.current_page == problems.meta.last_page ? (
          <div className="container-card" style={{ marginTop: '75px' }}>
            {problems.result.map((ProblemData) => {
              count++
              if (ProblemData.solved === false && solvedBtn === -1) {
                solvedBtn = count
              }
              return (
                <>
                  {locked ? (
                    <MainCard
                      type={props.type}
                      count={20}
                      ProblemData={ProblemData}
                      solvedBtn={10}
                      last={'true'}
                    />
                  ) : (
                    <MainCard
                      type={props.type}
                      count={count}
                      ProblemData={ProblemData}
                      solvedBtn={solvedBtn}
                      last={'true'}
                    />
                  )}
                </>
              )
            })}
          </div>
        ) : (
          <div className="container-card" style={{ marginTop: '75px' }}>
            {problems.result.map((ProblemData) => {
              count++
              if (ProblemData.solved === false && solvedBtn === -1) {
                solvedBtn = count
              }
              return (
                <>
                  {locked ? (
                    <MainCard
                      type={props.type}
                      count={20}
                      ProblemData={ProblemData}
                      solvedBtn={10}
                    />
                  ) : (
                    <MainCard
                      type={props.type}
                      count={count}
                      ProblemData={ProblemData}
                      solvedBtn={solvedBtn}
                    />
                  )}
                </>
              )
            })}
          </div>
        )}

        {/* if it is last page, dont display last and next pointers */}
        {problems.meta.current_page != problems.meta.last_page ? (
          <>
            <OverlayTrigger placement="top" overlay={renderTooltip3}>
              <a href={nextPage} style={{ position: 'absolute', right: '7%' }}>
                <FontAwesomeIcon className="pageNavIcons" icon={faAngleRight} />
              </a>
            </OverlayTrigger>

            <OverlayTrigger placement="top" overlay={renderTooltip4}>
              <a href={lastPage} style={{ position: 'absolute', right: '2%' }}>
                <FontAwesomeIcon
                  className="pageNavIcons"
                  icon={faAngleDoubleRight}
                />
              </a>
            </OverlayTrigger>
          </>
        ) : (
          <></>
        )}
      </div>

      <FooterSmall />
    </div>
  )
}
Example #25
Source File: instructorForm.js    From front-end with MIT License 4 votes vote down vote up
export default function InstructorForm(){

    let textField = {height:'3rem', fontSize:'x-large'};
    let textFieldGroup = {width:'70%', margin:'3rem auto'};

    const [formState, setFormState] = useState({
        name:'',
        email:'',
        code:'',
        website:''
    })

    const changeHandeler = (event) => {
        setFormState({
                ...formState,
                [event.target.name]: event.target.value
        })
    }

    const submitHandeler = (event) => {
        event.preventDefault();
        console.log(`Name: ${formState.name}, Email: ${formState.email}, Authentication Code: ${formState.code}, Website: ${formState.website}`)
        setFormState({
            name:'',
            email:'',
            code:'',
            website:''
        })

        
    }

    const buttonColor = () => {
        if(formState.name.length >= 1 && formState.email.length>=1 && formState.code.length>=1 && formState.website.length>=1 ){
            const filledText = '#FF6900'
            return filledText 
        }
        else{
            return '#BDBDBD'
        }
    }


    return (
        <div style={{width:'100%', height:'100%'}}>
            
            <div className='header'>
                <Navbar expand="lg" variant="light" bg="#FF6900" style={{backgroundColor:'#FF6900', padding:'1rem'}}>
                    <Link to="/Dashboard" style={{width:'100%', color:'black', margin:'.5rem auto'}}>Anywhere Fitness</Link>
                </Navbar>
            </div>
            <div>
                <img style=
                    {{width:'50%',
                    margin:'0',
                    display:'inline',
                    float:'left',
                    height:'55rem',
                    // backgroundSize:'cover'
                    }}
                    src={img}/>

                <form style={{display:'inline', float:'right', width:'50%'}} onSubmit={submitHandeler}>
                    
                    <h1 style={{paddingTop:'10rem', fontSize:'4.5rem'}}>Instructor Sign Up</h1>
                    
                    <Form.Group style={textFieldGroup} controlId="name">
                        <Form.Control onChange={changeHandeler} name='name' value={formState.name} type="name" placeholder="Name" style={textField} />
                    </Form.Group>

                    <Form.Group style={textFieldGroup} controlId="email">
                        <Form.Control onChange={changeHandeler} name='email' value={formState.email} type="email" placeholder="Email" style={textField} />
                    </Form.Group>

                    <Form.Group style={textFieldGroup} controlId="code">
                        {['bottom'].map((placement) => (
                            <OverlayTrigger
                            placement={placement}
                            delay={{hide: 4500}}
                            overlay={
                                <Tooltip>
                                Recieved from invite email. For more information and to request an authentication code, please visit our <a href='/'>help</a> page.
                                </Tooltip>
                            }
                            >
                            <img  className='codeInfo' src={icon} style={{marginLeft:'100%'}} />
                            </OverlayTrigger>
                        ))}
                        <Form.Control onChange={changeHandeler} name='code' value={formState.code} type="text" placeholder="Authentication Code" style={textField} />
                    </Form.Group>

                    <Form.Group style={textFieldGroup} controlId="website">
                        <Form.Control onChange={changeHandeler} name='website' value={formState.website} type="text" placeholder="Website" style={textField} />
                    </Form.Group>
                    
                    <Button
                        style=
                            {{width:'70%',
                            height:'3rem',
                            fontSize:'x-large',
                            margin:'auto',
                            backgroundColor: buttonColor()
                            }}
                        type ='submit'
                        >
                        Confirm
                    </Button>
                </form> 
            </div>
        </div>
    )
}
Example #26
Source File: SelectedPool.js    From katanapools with GNU General Public License v2.0 4 votes vote down vote up
render() {
    const {pool: {currentSelectedPool, currentSelectedPoolError}} = this.props;

    const {reservesNeeded, reservesAdded, fundAllReservesActive, fundOneReserveActive, singleTokenFundConversionPaths,
      withdrawAllReservesActive, withdrawOneReserveActive, singleTokenWithdrawReserveSelection, singleTokenFundReserveSelection,
      singleTokenWithdrawConversionPaths, calculatingFunding, calculatingWithdraw, submitFundingEnabled, fundingCalculateInit, withdrawCalculateInit,
      calculatingAllInputFunding, calculatingAllInputWithdraw,
      
      fundReserveSelection, withdrawSelection
    } = this.state;
    
    const self = this;
    
    let isPurchaseBtnDisabled = false;

    
    let isFundingLoading = <span/>;
    let isWithdrawLoading = <span/>;
    if (calculatingFunding && !fundingCalculateInit) {
      isFundingLoading = <FontAwesomeIcon icon={faSpinner} size="lg" rotation={270} pulse/>;
    }
    
    if (calculatingWithdraw && !withdrawCalculateInit) {
      isWithdrawLoading = <FontAwesomeIcon icon={faSpinner} size="lg" rotation={270} pulse/>;
    }

    let isWithdrawBtnDisabled = false;
    
    if (calculatingFunding) {
     // isPurchaseBtnDisabled = true;
    }

    if (calculatingWithdraw) {
      isWithdrawBtnDisabled = true;
    }
    
    let reserveRatio = '';

    reserveRatio = currentSelectedPool.reserves && currentSelectedPool.reserves.length > 0 ?currentSelectedPool.reserves.map(function(item){
      if (item) {
      return parseInt(item.reserveRatio) / 10000;
      } else {
        return null;
      }
    }).filter(Boolean).join("/") : '';


    if (currentSelectedPoolError) {
      return (<div>
      <div>Could not fetch pool details.</div>
      <div>Currently only pool contracts which expose reserveTokenCount() and reserveTokens() methods are supported.</div>
      </div>)
    }
    const { fundAmount, liquidateAmount } = this.state;

    let minTotalSupply = currentSelectedPool.totalSupply ? 
                          parseFloat(fromDecimals(currentSelectedPool.totalSupply, currentSelectedPool.decimals)).toFixed(4) : "";
    let reserveTokenList = currentSelectedPool.reserves && currentSelectedPool.reserves.length > 0 ? currentSelectedPool.reserves.map(function(item, idx){
      return <div key={`token-${idx}`}>
        <div className="holdings-label">{item.name}</div>
        <div className="holdings-data">&nbsp;{parseFloat(fromDecimals(item.reserveBalance, item.decimals)).toFixed(4)}</div>
      </div>
    }) : <span/>;

    let userHoldingsList = currentSelectedPool.reserves && currentSelectedPool.reserves.length > 0 ? currentSelectedPool.reserves.map(function(item, idx){
      let userBalanceItem = parseFloat(item.userBalance);
      let userBalanceDisplay = "-";
      if (!isNaN(userBalanceItem)) {
        userBalanceDisplay = userBalanceItem.toFixed(4);
      }
      return (<div key={`token-${idx}`}>
        <div className="holdings-label">{item.name}</div>
        <div className="holdings-data">&nbsp;{userBalanceDisplay}</div>
      </div>)
    }) : <span/>;

    let poolHoldings = "";
    if (currentSelectedPool.senderBalance ) {
      poolHoldings = parseFloat(fromDecimals(currentSelectedPool.senderBalance, currentSelectedPool.decimals)).toFixed(4) + " " + currentSelectedPool.symbol;
    }
    let liquidateInfo = <span/>;
    if (liquidateAmount && liquidateAmount > 0 && reservesAdded && reservesAdded.length > 0) {
      liquidateInfo = (
        <div>
          <div>You will receive</div>
            {reservesAdded.map(function(item, idx){
              return <div key={`reserve-added-${idx}`}>{item.addedDisplay} {item.symbol}</div>
            })}
        </div>
        )
    }
    let fundInfo = <span/>;

    if (fundAmount && fundAmount > 0 && reservesNeeded && reservesNeeded.length > 0) {
      fundInfo = (
        <div>
            <div>You will needs to stake</div>
            {reservesNeeded.map(function(item, idx){
              return <div key={`reserve-needed-${idx}`}>{item.neededDisplay} {item.symbol}</div>
            })}
        </div>
        )
    }
    let conversionFee = "";
    if (currentSelectedPool && currentSelectedPool.conversionFee) {
       conversionFee = currentSelectedPool.conversionFee + "%";
    }

    let poolLiquidateAction = <span/>;
    let poolFundAction = <span/>;
    let tokenAllowances = <span/>;
    
    let tokenAllowanceRowVisible = "row-hidden";
    if (this.state.approvalDisplay) {
      tokenAllowanceRowVisible = "row-visible"; 
    }
    
    if (currentSelectedPool.reserves && currentSelectedPool.reserves.length > 0){
      
      if (withdrawAllReservesActive === 'reserve-active') {
      poolLiquidateAction = (
        <div>
          <div className="select-reserve-container">
            <Form.Control type="number" placeholder="Enter amount to liquidate" onChange={this.onLiquidateInputChanged}/>
            <Button className="calculate-btn" disabled={isPurchaseBtnDisabled} onClick={this.calculateAllInputWithdraw}>Calculate</Button>            
          </div>
          <div className="action-info-col">
          {liquidateInfo}
          <Button onClick={this.submitSellPoolToken}  className="pool-action-btn">Sell</Button>
          </div>
        </div>
        )
      } else if (withdrawOneReserveActive === 'reserve-active') {
          let reserveOptions = currentSelectedPool.reserves.map(function(item, key){
            return <Dropdown.Item eventKey={item.symbol} key={`${item.symbol}-${key}`}>{item.symbol}</Dropdown.Item>
          });
          let withdrawActiveAmount = <span/>;
          if (singleTokenWithdrawConversionPaths && singleTokenWithdrawConversionPaths.length > 0) {
            let totalReserveAmount  = 0;
            singleTokenWithdrawConversionPaths.forEach(function(item){
              totalReserveAmount += parseFloat(item.quantity);
            });
            totalReserveAmount = totalReserveAmount.toFixed(4);
            withdrawActiveAmount = <div>{isWithdrawLoading} You will receive {totalReserveAmount} {singleTokenWithdrawReserveSelection.symbol}</div>
          }
        poolLiquidateAction = (
            <div>
            <div className="select-reserve-container">
              <div>
              <label>
                Reserve token in which to withdraw
              </label>
              <DropdownButton id="dropdown-basic-button" title={singleTokenWithdrawReserveSelection.symbol} onSelect={this.withdrawSingleBaseChanged}>
                {reserveOptions}
              </DropdownButton>
              </div>
              <div>
                 <label>Amount of pool tokens to withdraw</label>
                 <div>
                  <Form.Control type="number" placeholder="Pool tokens to withdraw" onChange={this.onSingleReserveLiquidateFundChanged}/>
                  <Button className="calculate-btn" onClick={this.calculateSingleInputWithdraw}>Calculate</Button>
                </div>
              </div>
            </div>
                <div className="action-info-col">
                {withdrawActiveAmount}
                <Button onClick={this.submitSellPoolTokenWithSingleReserve} disabled={isWithdrawBtnDisabled} className="pool-action-btn">Withdraw</Button>
                </div>
            </div>
            )
      }

      if (fundAllReservesActive === 'reserve-active' && fundReserveSelection.length > 0) {
          poolFundAction = (
            <div className="select-reserve-container">
                <div>
                  {
                    fundReserveSelection.map(function(item, idx){
                      return <Form.Control type="number" placeholder={`Enter amount of ${item.symbol} to fund`} value={item.value}
                      onChange={self.fundInputAmountChange.bind(self, idx)}/>
                    })
                  }
                  <div> 
                  <Button className="calculate-btn" disabled={isPurchaseBtnDisabled} onClick={this.calculateAllInputFund}>Calculate</Button>
                  </div>
                </div>
                
                <div className="action-info-col">
                {fundInfo}
                <Button onClick={this.submitBuyPoolToken} className="pool-action-btn">Purchase</Button>
                </div>
            </div>
            )
        } else if (fundOneReserveActive === 'reserve-active') {
          let reserveOptions = currentSelectedPool.reserves.map(function(item, key){
            return <Dropdown.Item eventKey={item.symbol} key={`${item.symbol}-${key}`} >{item.symbol}</Dropdown.Item>
          });
          let fundActiveAmount = <span/>;
          if (singleTokenFundConversionPaths) {
            let totalReserveAmount  = 0;
            singleTokenFundConversionPaths.forEach(function(item){
              totalReserveAmount += parseFloat(item.quantity);
            });
            totalReserveAmount = totalReserveAmount.toFixed(4);
            fundActiveAmount = <div>{isFundingLoading} You will need to stake {totalReserveAmount} {singleTokenFundReserveSelection.symbol}</div>
          }

          poolFundAction = (
            <div>
            <div className="select-reserve-container">
            <div>
              <label>
                Reserve token with which to fund.
              </label>
              <DropdownButton id="dropdown-basic-button" title={singleTokenFundReserveSelection.symbol} onSelect={this.fundSingleBaseChanged}>
                {reserveOptions}
              </DropdownButton>
            </div>
            <div>
              <label>Amount of {singleTokenFundReserveSelection.symbol} to fund</label>
              <div>
                <Form.Control type="number" placeholder={`Enter amount of ${singleTokenFundReserveSelection.symbol} to fund`} onChange={this.onSingleReserveFundInputChanged} className="single-reserve-amount-text"/>
                <Button className="calculate-btn" disabled={isPurchaseBtnDisabled} onClick={this.calculateSingleInputFund}>Calculate</Button>
              </div>
            </div>
            </div>
                <div className="action-info-col">
                {fundActiveAmount}
                <Button onClick={this.submitBuyPoolTokenWithSingleReserve} className="pool-action-btn">Purchase</Button>
                </div>
            </div>
            )
        }
        
    let tokenAllowanceReserves = currentSelectedPool.reserves.map(function(item, idx){
      return <div key={`allowance-${idx}`} className="selected-pool-balance">
      {item.symbol} {item.userAllowance ? parseFloat(item.userAllowance).toFixed(5) : '-'}
      </div>
    });
    
    let tokenSwapAllowanceReserves = currentSelectedPool.reserves.map(function(item, idx){
      return <div key={`allowance-${idx}`} className="selected-pool-balance">
      {item.symbol} {item.swapAllowance ? parseFloat(item.swapAllowance).toFixed(5) : '-'}
      </div>
    });
    
    tokenAllowances = 
    <div className={`${tokenAllowanceRowVisible}`}>
    <div className="approval-type-label">
     Approvals for pool converter contract.
    </div>
    <Row className={`token-allowances-display-row`}>
    <Col lg={8}>
      {tokenAllowanceReserves}
      </Col>
      <Col lg={4}>
      <Button onClick={()=>this.showApprovalDialog("pool")}>Approve reserves </Button>
      <Button onClick={()=>this.showRevokeDialog("pool")} className="revoke-approval-btn">Revoke approval </Button>
      </Col>
    </Row>
    <div className="approval-type-label">
     Approvals for Bancor Network contract.
    </div>
    <Row className="single-token-description">
     <Col lg={12}>
       If you using single token funding, it is also recommended that you approve BancorNetwork contract for swaps.
     </Col>
     </Row>
    <Row>
      <Col lg={8}>
      {tokenSwapAllowanceReserves}
      </Col>
      <Col lg={4}>
      <Button onClick={()=>this.showApprovalDialog("swap")}>Approve reserves </Button>
      <Button onClick={()=>this.showRevokeDialog("swap")} className="revoke-approval-btn">Revoke approval </Button>
      </Col>
    </Row>
    </div>
    }
    
    function allowanceToolTip(props) {
       return <Tooltip {...props}>
        <div>Token allowances refer to amount you have approved the converter contract to spend.</div>
        <div>Set allowances for BancorConverter for faster pool funding and liquidation and save on Gas costs</div>
        </Tooltip>;
    }
    
    let currentPoolTransactions = <span/>;

    if (currentSelectedPool.poolVersion === '1') {
      currentPoolTransactions = (
          <div>
          <Col lg={6}>
            <div className="allowance-label">Fund Pool Holdings</div>
            {poolFundAction}
          </Col>
          <Col lg={6}>
            <div className="allowance-label">Liquitate Pool Holdings</div>
            {poolLiquidateAction}
          </Col>
          </div>
        )
    } else {
      currentPoolTransactions = (
        <div>
          <SelectedV2PoolContainer pool={this.props.pool}/>
        </div>
        )
    }

    return (
      <div>
        <Row className="select-pool-row-1">
          <Col lg={1} className="pool-logo-container">
            <img src={currentSelectedPool.imageURI} className="selected-pool-image" alt="pool-token-img"/>
          </Col>
          <Col lg={2}>
            <div className="cell-label">{currentSelectedPool.symbol}</div>
            <div className="cell-data">{currentSelectedPool.name}</div>
          </Col>
          <Col lg={2}>
           <div className="cell-label">Address</div>
           <div className="cell-data"><AddressDisplay address={currentSelectedPool.address}/></div>
          </Col>
          <Col lg={2}>
            <div className="cell-label">Pool Supply</div>
            <div className="cell-data">{minTotalSupply}</div>
          </Col>
          <Col lg={3}>
            <div>
              <div className="cell-label">Reserves</div>
              <div className="cell-data">{reserveTokenList}</div>
            </div>
          </Col>
          <Col lg={2}>
            <div className="cell-label">Reserve Ratio</div>
            <div className="cell-data">{reserveRatio}</div>
          </Col>
        </Row>
        <Row className="selected-pool-meta-row">
          <Col lg={3}>
            <div className="cell-label">Conversion fee generated</div>
            <div className="cell-data">{conversionFee}</div>
          </Col>
          <Col lg={3}>
            <div className="cell-label">Your pool token holdings</div>
            <div className="cell-data">{poolHoldings}</div>
          </Col>
          <Col lg={4}>
            <div className="cell-label">Your reserve token holdings</div>
            <div className="cell-data">{userHoldingsList}</div>
          </Col>
        </Row>
        
       <div className="pool-action-container pool-allowance-container">

        <Row>
         <Col lg={12}>
          <div className="pool-approval-container">
           <div className="allowance-label">
           Your pool allowances 
           <OverlayTrigger
              placement="right"
              delay={{ show: 250, hide: 400 }}
              overlay={allowanceToolTip}>
              <FontAwesomeIcon icon={faQuestionCircle} className="info-tooltip-btn"/>
            </OverlayTrigger>
           </div>
           <FontAwesomeIcon icon={faChevronDown} className="show-approval-toggle" onClick={this.toggleApprovalDisplay}/>
           {tokenAllowances}
           </div>
         </Col>
        </Row>
        
        <Row className="selected-pool-buy-sell-row">
          <Col lg={12}>
          {currentPoolTransactions}
          </Col>
        </Row>
        
        </div>  
      </div>
      )
  }
Example #27
Source File: Webcam.jsx    From makerverse with GNU General Public License v3.0 4 votes vote down vote up
render() {
        const { state, actions } = this.props;
        const {
            disabled,
            mediaSource,
            deviceId,
            url,
            scale,
            rotation,
            flipHorizontally,
            flipVertically,
            crosshair,
            muted
        } = state;

        if (disabled) {
            return (
                <div className={styles['webcam-off-container']}>
                    <h4><i className={styles['icon-webcam']} /></h4>
                    <h5>{i18n._('Webcam is off')}</h5>
                </div>
            );
        }

        const transformStyle = [
            'translate(-50%, -50%)',
            `rotateX(${flipVertically ? 180 : 0}deg)`,
            `rotateY(${flipHorizontally ? 180 : 0}deg)`,
            `rotate(${(rotation % 4) * 90}deg)`
        ].join(' ');

        return (
            <div className={styles['webcam-on-container']}>
                {mediaSource === MEDIA_SOURCE_LOCAL && (
                    <div style={{ width: '100%' }}>
                        <WebcamComponent
                            className={styles.center}
                            style={{ transform: transformStyle }}
                            width={(100 * scale).toFixed(0) + '%'}
                            height="auto"
                            muted={muted}
                            video={!!deviceId ? deviceId : true}
                        />
                    </div>
                )}
                {mediaSource === MEDIA_SOURCE_MJPEG && (
                    <Image
                        ref={node => {
                            this.imageSource = node;
                        }}
                        src={mapMetaAddressToHostname(url)}
                        style={{
                            width: (100 * scale).toFixed(0) + '%',
                            transform: transformStyle
                        }}
                        className={styles.center}
                    />
                )}
                {crosshair && (
                    <div>
                        <Line
                            className={classNames(
                                styles.center,
                                styles['line-shadow']
                            )}
                            length="100%"
                        />
                        <Line
                            className={classNames(
                                styles.center,
                                styles['line-shadow']
                            )}
                            length="100%"
                            vertical
                        />
                        <Circle
                            className={classNames(
                                styles.center,
                                styles['line-shadow']
                            )}
                            diameter={20}
                        />
                        <Circle
                            className={classNames(
                                styles.center,
                                styles['line-shadow']
                            )}
                            diameter={40}
                        />
                    </div>
                )}
                <div className={styles.toolbar}>
                    <div className={styles.scaleText}>{scale}x</div>
                    <div className="pull-right">
                        {mediaSource === MEDIA_SOURCE_LOCAL && (
                            <Anchor
                                className={styles.btnIcon}
                                onClick={actions.toggleMute}
                            >
                                <i
                                    className={classNames(
                                        styles.icon,
                                        styles.inverted,
                                        { [styles.iconUnmute]: !muted },
                                        { [styles.iconMute]: muted }
                                    )}
                                />
                            </Anchor>
                        )}
                        <OverlayTrigger
                            overlay={<Tooltip id="rotate-left">{i18n._('Rotate Left')}</Tooltip>}
                            placement="top"
                        >
                            <Anchor
                                className={styles.btnIcon}
                                onClick={actions.rotateLeft}
                            >
                                <i
                                    className={classNames(
                                        styles.icon,
                                        styles.inverted,
                                        styles.iconRotateLeft
                                    )}
                                />
                            </Anchor>
                        </OverlayTrigger>
                        <OverlayTrigger
                            overlay={<Tooltip id="rotate-right">{i18n._('Rotate Right')}</Tooltip>}
                            placement="top"
                        >
                            <Anchor
                                className={styles.btnIcon}
                                onClick={actions.rotateRight}
                            >
                                <i
                                    className={classNames(
                                        styles.icon,
                                        styles.inverted,
                                        styles.iconRotateRight
                                    )}
                                />
                            </Anchor>
                        </OverlayTrigger>
                        <OverlayTrigger
                            overlay={<Tooltip id="flip-horizontally">{i18n._('Flip Horizontally')}</Tooltip>}
                            placement="top"
                        >
                            <Anchor
                                className={styles.btnIcon}
                                onClick={actions.toggleFlipHorizontally}
                            >
                                <i
                                    className={classNames(
                                        styles.icon,
                                        styles.inverted,
                                        styles.iconFlipHorizontally
                                    )}
                                />
                            </Anchor>
                        </OverlayTrigger>
                        <OverlayTrigger
                            overlay={<Tooltip id="flip-vertically">{i18n._('Flip Vertically')}</Tooltip>}
                            placement="top"
                        >
                            <Anchor
                                className={styles.btnIcon}
                                onClick={actions.toggleFlipVertically}
                            >
                                <i
                                    className={classNames(
                                        styles.icon,
                                        styles.inverted,
                                        styles.iconFlipVertically
                                    )}
                                />
                            </Anchor>
                        </OverlayTrigger>
                        <OverlayTrigger
                            overlay={<Tooltip id="crosshair">{i18n._('Crosshair')}</Tooltip>}
                            placement="top"
                        >
                            <Anchor
                                className={styles.btnIcon}
                                onClick={actions.toggleCrosshair}
                            >
                                <i
                                    className={classNames(
                                        styles.icon,
                                        styles.inverted,
                                        styles.iconCrosshair
                                    )}
                                />
                            </Anchor>
                        </OverlayTrigger>
                    </div>
                </div>
                <div className={styles['image-scale-slider']}>
                    <Slider
                        defaultValue={scale}
                        min={0.1}
                        max={10}
                        step={0.1}
                        tipFormatter={null}
                        onChange={actions.changeImageScale}
                    />
                </div>
            </div>
        );
    }
Example #28
Source File: SwapTab.js    From plenty-interface with GNU General Public License v3.0 4 votes vote down vote up
SwapTab = (props) => {
  const [firstTokenAmount, setFirstTokenAmount] = useState();
  const [secondTokenAmount, setSecondTokenAmount] = useState();
  const [routeDataCopy, setRouteDataCopy] = useState(false);
  const [firstAmount, setFirstAmount] = useState(0);
  const [secondAmount, setSecondAmount] = useState(0);
  const [routePath, setRoutePath] = useState([]);
  const [errorMessage, setErrorMessage] = useState(false);
  const [message, setMessage] = useState('');
  const [stableList, setStableList] = useState([]);
  const [dolar, setDolar] = useState('0.0');
  const [computedData, setComputedData] = useState({
    success: false,
    data: {
      tokenOutAmount: 0,
      fees: [],
      totalFees: 0,
      minimumOut: [],
      finalMinimumOut: 0,
      priceImpact: 0,
    },
  });
  const [swapData, setSwapData] = useState({
    success: false,
    tezPool: 0,
    ctezPool: 0,
    tokenIn: props.tokenIn.name,
    tokenOut: props.tokenOut.name,
    lpTokenSupply: 0,
    target: 0,
    lpToken: null,
    dexContractInstance: null,
  });
  const isStableSwap = useRef(false);
  const getSwapData = async () => {
    const res = await loadSwapDataStable(props.tokenIn.name, props.tokenOut.name);

    setSwapData(res);
  };
  const getSwapDataGeneralStableswap = async () => {
    const res = await loadSwapDataGeneralStableWithoutDecimal(
      props.tokenIn.name,
      props.tokenOut.name,
    );

    setSwapData(res);
  };
  useEffect(() => {
    // if (props.isStablePair) {
    if (
      config.AMM[config.NETWORK][props.tokenIn.name].DEX_PAIRS[props.tokenOut.name]?.type === 'xtz'
    ) {
      getSwapData();
    } else if (
      config.AMM[config.NETWORK][props.tokenIn.name].DEX_PAIRS[props.tokenOut.name]?.type ===
      'veStableAMM'
    ) {
      getSwapDataGeneralStableswap();
    }
    // }
  }, [props.tokenIn, props.tokenOut]);

  useEffect(() => {
    setRouteDataCopy(false);
    isStableSwap.current =
      config.AMM[config.NETWORK][props.tokenIn.name].DEX_PAIRS[props.tokenOut.name]?.type ===
        'veStableAMM' ||
      config.AMM[config.NETWORK][props.tokenIn.name].DEX_PAIRS[props.tokenOut.name]?.type === 'xtz';

    setRoutePath([]);
    setFirstTokenAmount('');
    setSecondTokenAmount('');
  }, [props.tokenIn, props.tokenOut]);

  useEffect(() => {
    if (props.routeData.success) {
      setRouteDataCopy(true);
    }
  }, [props.routeData]);

  useEffect(() => {
    firstTokenAmount && setFirstAmount(firstTokenAmount);
    secondTokenAmount && setSecondAmount(secondTokenAmount);
    if (props.walletAddress) {
      if (Object.keys(props.tokenOut).length !== 0) {
        if (
          (props.tokenIn.name === 'EURL' && props.tokenOut.name !== 'agEUR.e') ||
          (props.tokenOut.name === 'EURL' && props.tokenIn.name !== 'agEUR.e') ||
          (props.tokenIn.name === 'agEUR.e' && props.tokenOut.name !== 'EURL') ||
          (props.tokenOut.name === 'agEUR.e' && props.tokenIn.name !== 'EURL')
        ) {
          setErrorMessageOnUI(ERRORMESSAGESWAP);
        } else if (
          (props.tokenIn.name === 'EURL' || props.tokenIn.name === 'agEUR.e') &&
          (props.tokenOut.name === 'EURL' || props.tokenOut.name === 'agEUR.e')
        ) {
          setErrorMessage(false);
          setMessage('');
        }
      } else if (firstTokenAmount > props.userBalances[props.tokenIn.name]) {
        setErrorMessageOnUI('Insufficient balance');
      } else {
        setErrorMessage(false);
      }
    }
  }, [
    firstTokenAmount,
    secondTokenAmount,
    props.changeTokenLocation,
    props.tokenIn,
    props.tokenOut,
  ]);

  const [showTransactionSubmitModal, setShowTransactionSubmitModal] = useState(false);
  const [transactionId, setTransactionId] = useState('');

  const transactionSubmitModal = (id) => {
    setTransactionId(id);
    setShowTransactionSubmitModal(true);
  };
  const handleCloseModal = () => {
    props.setShowConfirmSwap(false);
    props.setShowConfirmTransaction(false);

    props.setLoader(false);
    resetVal();
    props.resetAllValues();
    props.setLoading(false);
  };

  const fetchSwapData = async (input) => {
    const tokenOutResponse = await calculateTokensOutStable(
      swapData.tezPool,
      swapData.ctezPool,
      Number(input),
      1000,
      props.slippage,
      swapData.target,
      props.tokenIn.name,
    );

    return tokenOutResponse;
  };

  const fetchSwapDataForGeneralStableSwap = async (input) => {
    const tokenOutResponse = await calculateTokensOutGeneralStable(
      swapData.tokenIn_supply,
      swapData.tokenOut_supply,
      Number(input),
      swapData.exchangeFee,
      props.slippage,
      props.tokenIn.name,
      props.tokenOut.name,
      swapData.tokenIn_precision,
      swapData.tokenOut_precision,
    );

    return tokenOutResponse;
  };

  useEffect(() => {
    getXtzDollarPrice().then((res) => {
      setDolar(res);
    });
  }, []);

  const handleSwapTokenInput = async (input, tokenType) => {
    if (input === '' || isNaN(input)) {
      setFirstTokenAmount('');
      setSecondTokenAmount('');
      props.setComputedOutDetails({});
    } else {
      if (tokenType === 'tokenIn') {
        if (props.isStablePair) {
          if (
            config.AMM[config.NETWORK][props.tokenIn.name].DEX_PAIRS[props.tokenOut.name]?.type ===
            'xtz'
          ) {
            setFirstTokenAmount(input);
            const res = await fetchSwapData(input);

            setSecondTokenAmount(res.tokenOut.toFixed(6));
            setComputedData({
              success: true,
              data: {
                tokenOutAmount: res.tokenOut.toFixed(6),
                fees: res.fee,
                totalFees: res.fee,
                minimumOut: res.minimumOut.toFixed(6),
                finalMinimumOut: res.minimumOut.toFixed(6),
                priceImpact: res.priceImpact,
                exchangeRate: res.exchangeRate,
              },
            });
          } else if (
            config.AMM[config.NETWORK][props.tokenIn.name].DEX_PAIRS[props.tokenOut.name]?.type ===
            'veStableAMM'
          ) {
            setFirstTokenAmount(input);
            const res = await fetchSwapDataForGeneralStableSwap(input);

            setSecondTokenAmount(res.tokenOut_amount);

            setComputedData({
              success: true,
              data: {
                tokenOutAmount: res.tokenOut_amount,
                fees: res.fees,
                totalFees: res.fees,
                minimumOut: res.minimum_Out,
                finalMinimumOut: res.minimum_Out,
                priceImpact: res.priceImpact,
                exchangeRate: res.exchangeRate,
              },
            });
          }
        } else {
          setFirstTokenAmount(input);

          const res = computeTokenOutForRouteBaseV2(
            input,
            props.routeData.allRoutes,
            props.slippage,
          );

          setComputedData(res);

          setComputedData({
            success: true,
            data: {
              tokenOutAmount: res.bestRoute.computations.tokenOutAmount,
              fees: res.bestRoute.computations.fees,
              totalFees:
                res.bestRoute.computations.fees[res.bestRoute.computations.fees.length - 1],
              minimumOut: res.bestRoute.computations.minimumOut,
              finalMinimumOut:
                res.bestRoute.computations.minimumOut[
                  res.bestRoute.computations.minimumOut.length - 1
                ],
              priceImpact: res.bestRoute.computations.priceImpact,
              maxfee: res.bestRoute.maxFee,
            },
          });
          setRoutePath(res.bestRoute.path);
          setStableList(res.bestRoute.isStableList);
          setSecondTokenAmount(res.bestRoute.computations.tokenOutAmount);
        }
      } else if (tokenType === 'tokenOut') {
        if (props.isStablePair) {
          setSecondTokenAmount(input);
          const res = await fetchSwapData(input);

          setFirstTokenAmount(res.tokenOut.toFixed(6));

          setComputedData({
            success: true,
            data: {
              tokenOutAmount: res.tokenOut.toFixed(6),
              fees: res.fee,
              totalFees: res.fee,
              minimumOut: res.minimumOut.toFixed(6),
              finalMinimumOut: res.minimumOut.toFixed(6),
              priceImpact: res.priceImpact,
              exchangeRate: res.exchangeRate,
            },
          });
        } else {
          setSecondTokenAmount(input);

          const res = computeTokenOutForRouteBaseByOutAmountV2(
            Number(input),
            props.routeData.allRoutes,
            props.slippage,
          );
          setComputedData({
            success: true,
            data: {
              tokenOutAmount: res.bestRoute.computations.tokenOutAmount,
              fees: res.bestRoute.computations.fees,
              totalFees:
                res.bestRoute.computations.fees[res.bestRoute.computations.fees.length - 1],
              minimumOut: res.bestRoute.computations.minimumOut,
              finalMinimumOut:
                res.bestRoute.computations.minimumOut[
                  res.bestRoute.computations.minimumOut.length - 1
                ],
              priceImpact: res.bestRoute.computations.priceImpact,
              maxfee: res.bestRoute.maxFee,
            },
          });
          setRoutePath(res.bestRoute.path);
          setStableList(res.bestRoute.isStableList);
          setFirstTokenAmount(res.bestRoute.computations.tokenInAmount);
        }
      }
    }
  };
  const onClickAmount = () => {
    setSecondTokenAmount('');
    // const value =
    //   props.userBalances[props.tokenIn.name].toLocaleString('en-US', {
    //     maximumFractionDigits: 20,
    //     useGrouping: false,
    //   }) ?? 0;
    props.tokenIn.name === 'tez'
      ? handleSwapTokenInput(props.userBalances[props.tokenIn.name] - 0.02, 'tokenIn')
      : handleSwapTokenInput(props.userBalances[props.tokenIn.name], 'tokenIn');
  };
  useEffect(() => {
    handleSwapTokenInput(firstTokenAmount, 'tokenIn');
  }, [routeDataCopy]);
  useEffect(() => {
    setErrorMessage(false);
  }, [props.tokenOut.name]);

  const callSwapToken = () => {
    props.setShowConfirmSwap(true);
  };

  const resetVal = () => {
    props.resetAllValues();
    setFirstTokenAmount('');
    props.setSecondTokenAmount('');
    setSecondTokenAmount('');
  };
  const getDollarValue = (amount, price) => {
    const calculatedValue = amount * price;
    if (calculatedValue < 100) {
      return calculatedValue.toFixed(2);
    }
    return Math.floor(calculatedValue);
  };

  const handleSwapResponse = (status) => {
    if (status) {
      props.setLoading(false);
      setShowTransactionSubmitModal(false);
      props.handleLoaderMessage('success', 'Transaction confirmed');
      props.setBalanceUpdate(true);
      props.setLoader(false);
      props.setShowConfirmSwap(false);
      props.setShowConfirmTransaction(false);
      props.setSecondTokenAmount('');
      props.resetAllValues();
      props.setLoaderInButton(false);
      setFirstTokenAmount('');
      setSecondTokenAmount('');
    } else {
      props.setLoading(false);
      setShowTransactionSubmitModal(false);
      props.handleLoaderMessage('error', 'Transaction failed');
      props.setBalanceUpdate(true);
      props.setLoader(false);
      props.setShowConfirmSwap(false);
      props.setShowConfirmTransaction(false);
      props.resetAllValues();
      props.setSecondTokenAmount('');
      props.setLoaderInButton(false);
    }
  };

  const confirmSwapToken = async () => {
    props.setLoading(true);
    props.setLoader(true);
    props.setLoaderInButton(true);
    props.setShowConfirmSwap(false);
    props.setShowConfirmTransaction(true);
    localStorage.setItem('wrapped', firstTokenAmount);
    localStorage.setItem(
      'token',
      props.tokenIn.name === 'tez'
        ? 'TEZ'
        : props.tokenIn.name === 'ctez'
        ? 'CTEZ'
        : props.tokenIn.name,
    );
    const recepientAddress = props.recepient ? props.recepient : props.walletAddress;
    if (props.tokenIn.name === 'ctez' && props.tokenOut.name === 'tez') {
      ctez_to_tez(
        props.tokenIn.name,
        props.tokenOut.name,
        computedData.data.minimumOut,
        recepientAddress,
        Number(firstTokenAmount),
        transactionSubmitModal,
        props.setShowConfirmSwap,
        resetVal,
        props.setShowConfirmTransaction,
      ).then((response) => {
        handleSwapResponse(response.success);
        props.setShowConfirmTransaction(false);
        props.setLoader(false);
        setTimeout(() => {
          props.setLoaderMessage({});
        }, 5000);
      });
    } else if (props.tokenIn.name === 'tez' && props.tokenOut.name === 'ctez') {
      tez_to_ctez(
        props.tokenIn.name,
        props.tokenOut.name,
        computedData.data.minimumOut,
        recepientAddress,
        Number(firstTokenAmount),
        transactionSubmitModal,
        props.setShowConfirmSwap,
        resetVal,
        props.setShowConfirmTransaction,
      ).then((response) => {
        props.setShowConfirmSwap(false);
        props.setShowConfirmTransaction(false);
        props.setLoader(false);
        handleSwapResponse(response.success);
        setTimeout(() => {
          props.setLoaderMessage({});
        }, 5000);
      });
    } else if (
      config.AMM[config.NETWORK][props.tokenIn.name].DEX_PAIRS[props.tokenOut.name]?.type ===
      'veStableAMM'
    ) {
      //call api for new stableswap
      swapTokens(
        props.tokenIn.name,
        props.tokenOut.name,
        computedData.data.minimumOut,
        recepientAddress,
        Number(firstTokenAmount),
        props.walletAddress,
        transactionSubmitModal,
        props.setShowConfirmSwap,
        resetVal,
        props.setShowConfirmTransaction,
      ).then((response) => {
        props.setShowConfirmSwap(false);
        props.setShowConfirmTransaction(false);
        props.setLoader(false);
        handleSwapResponse(response.success);
        setTimeout(() => {
          props.setLoaderMessage({});
        }, 5000);
      });
    } else {
      if (routePath.length <= 2) {
        swapTokens(
          routePath[0],
          routePath[1],
          computedData.data.finalMinimumOut,
          recepientAddress,
          firstTokenAmount,
          props.walletAddress,
          transactionSubmitModal,
          props.setShowConfirmSwap,
          resetVal,
          props.setShowConfirmTransaction,
        ).then((swapResp) => {
          props.setShowConfirmSwap(false);
          props.setLoader(false);
          props.setShowConfirmTransaction(false);
          handleSwapResponse(swapResp.success);
          setTimeout(() => {
            props.setLoaderMessage({});
          }, 5000);
        });
      } else {
        swapTokenUsingRouteV3(
          routePath,
          computedData.data.minimumOut,
          props.walletAddress,
          firstTokenAmount,
          transactionSubmitModal,
          props.setShowConfirmSwap,
          resetVal,
          props.setShowConfirmTransaction,
        ).then((swapResp) => {
          props.setShowConfirmSwap(false);
          props.setLoader(false);
          props.setShowConfirmTransaction(false);
          handleSwapResponse(swapResp.success);
          setTimeout(() => {
            props.setLoaderMessage({});
          }, 5000);
        });
      }
    }
  };
  const switchTokens = () => {
    props.changeTokenLocation();
    setFirstTokenAmount('');
    setSecondTokenAmount('');
  };

  const setErrorMessageOnUI = (value) => {
    setMessage(value);
    setErrorMessage(true);
  };

  const swapContentButton = useMemo(() => {
    if (props.walletAddress) {
      if (props.tokenOut.name && message === ERRORMESSAGESWAP) {
        return (
          <Button
            onClick={() => setErrorMessageOnUI(ERRORMESSAGESWAP)}
            color={'disabled'}
            className={
              'mt-4 w-100 flex align-items-center justify-content-center disable-button-swap'
            }
          >
            Swap
          </Button>
        );
      }
      if (props.tokenOut.name && firstTokenAmount) {
        if (Number(firstTokenAmount) === 0 || Number(secondTokenAmount) === 0) {
          return (
            <Button
              onClick={() => setErrorMessageOnUI('Enter an amount to swap')}
              color={'disabled'}
              className={
                ' mt-4 w-100 flex align-items-center justify-content-center disable-button-swap'
              }
            >
              Swap
            </Button>
          );
        } else if (firstTokenAmount > props.userBalances[props.tokenIn.name]) {
          return (
            <Button
              onClick={() => setErrorMessageOnUI('Insufficient balance')}
              color={'disabled'}
              className={
                'mt-4 w-100 flex align-items-center justify-content-center disable-button-swap'
              }
            >
              Swap
            </Button>
          );
        } else {
          return (
            <Button
              onClick={callSwapToken}
              color={'primary'}
              className={'mt-4 w-100 flex align-items-center justify-content-center'}
            >
              Swap
            </Button>
          );
        }
      }

      if (!props.tokenOut.name) {
        return (
          <Button
            onClick={() => setErrorMessageOnUI('Please select a token and then enter the amount')}
            color={'disabled'}
            className={
              ' mt-4 w-100 flex align-items-center justify-content-center disable-button-swap'
            }
          >
            Swap
          </Button>
        );
      }

      return (
        <Button
          onClick={() => setErrorMessageOnUI('Enter an amount to swap')}
          color={'disabled'}
          className={
            ' mt-4 w-100 flex align-items-center justify-content-center disable-button-swap'
          }
        >
          Swap
        </Button>
      );
    }

    return (
      <Button
        onClick={props.connecthWallet}
        color={'primary'}
        startIcon={'add'}
        className={'mt-4 w-100 flex align-items-center justify-content-center'}
      >
        Connect Wallet
      </Button>
    );
  }, [
    callSwapToken,
    props.routeData,
    props.connecthWallet,
    firstTokenAmount,
    props.loaderInButton,
    props.tokenOut.name,
    props.walletAddress,
  ]);

  return (
    <>
      <div className="swap-content-box-wrapper">
        <div className="swap-content-box swap-left-right-padding">
          <div
            className={clsx(
              !errorMessage && 'swap-token-select-box',

              errorMessage && 'errorBorder',
              firstTokenAmount > 0 && (errorMessage ? 'errorBorder' : 'typing-border'),
            )}
          >
            <div className="token-selector-balance-wrapper-swap">
              <button
                className="token-selector  token-selector-height"
                onClick={() => props.handleTokenType('tokenIn')}
              >
                <img src={props.tokenIn.image} className="button-logo logo-size" />
                <span className="span-themed">
                  {props.tokenIn.name === 'tez'
                    ? 'TEZ'
                    : props.tokenIn.name === 'ctez'
                    ? 'CTEZ'
                    : props.tokenIn.name}{' '}
                </span>
                <span className="span-themed material-icons-round">expand_more</span>
              </button>
            </div>

            <div className="token-user-input-wrapper">
              <div className="input-heading">YOU PAY</div>
              {props.tokenOut.name && props.userBalances[props.tokenIn.name] >= 0 ? (
                <input
                  type="text"
                  className={clsx(
                    'token-user-input',
                    errorMessage ? 'error-text-color' : 'typing-input-color',
                  )}
                  placeholder="0.0"
                  value={fromExponential(firstTokenAmount)}
                  onChange={(e) => handleSwapTokenInput(e.target.value, 'tokenIn')}
                  disabled={message === ERRORMESSAGESWAP}
                />
              ) : (
                <input type="text" className="token-user-input" placeholder="--" disabled />
              )}
            </div>
            {props.walletAddress ? (
              <div className="flex justify-between" style={{ flex: '0 0 100%' }}>
                {props.tokenOut.name ? (
                  <p
                    className="wallet-token-balance balance-revamp"
                    onClick={onClickAmount}
                    style={{ cursor: 'pointer' }}
                  >
                    Balance:{' '}
                    {props.userBalances[props.tokenIn.name] > 0 ? (
                      <OverlayTrigger
                        placement="top"
                        overlay={
                          <Tooltip id="tooltip-e" {...props}>
                            {fromExponential(props.userBalances[props.tokenIn.name])}
                          </Tooltip>
                        }
                      >
                        <span
                          className={clsx(
                            'balance-tokenin',
                            errorMessage &&
                              message === 'Insufficient balance' &&
                              'error-text-color',
                          )}
                        >
                          {props.userBalances[props.tokenIn.name] >= 0 ? (
                            props.userBalances[props.tokenIn.name].toFixed(4)
                          ) : (
                            <div className="shimmer">0.0000</div>
                          )}{' '}
                        </span>
                      </OverlayTrigger>
                    ) : (
                      <span
                        className={clsx(
                          'balance-tokenin',
                          errorMessage && message === 'Insufficient balance' && 'error-text-color',
                        )}
                      >
                        {props.userBalances[props.tokenIn.name] >= 0 ? (
                          props.userBalances[props.tokenIn.name].toFixed(4)
                        ) : (
                          <div className="shimmer">0.0000</div>
                        )}{' '}
                      </span>
                    )}
                  </p>
                ) : (
                  <p className="wallet-token-balance balance-revamp">
                    Balance: {props.userBalances[props.tokenIn.name]?.toFixed(4)}
                  </p>
                )}

                <p className="wallet-token-balance balance-revamp">
                  ~$
                  {props.tokenIn.name === 'tez' ? (
                    dolar * firstTokenAmount == null ? (
                      <span className="shimmer">99999999</span>
                    ) : firstTokenAmount ? (
                      (dolar * firstTokenAmount).toFixed(2)
                    ) : (
                      '0.00'
                    )
                  ) : props.getTokenPrice.success && firstTokenAmount ? (
                    getDollarValue(
                      firstTokenAmount,
                      props.getTokenPrice.tokenPrice[props.tokenIn.name],
                    )
                  ) : (
                    '0.00'
                  )}
                </p>
              </div>
            ) : null}
          </div>
          {errorMessage && <span className="error-message">{message}</span>}
        </div>

        <div className={clsx('switch-img-background', errorMessage && 'alignment-switch')}>
          <div className="switch-img">
            <div className="swap-arrow-center-revamp  icon-animated" onClick={switchTokens}>
              <img src={props.theme === 'light' ? switchImg : switchImgDark} />
            </div>
          </div>
        </div>

        <div className="second-token-bg">
          <div className="swap-content-box ">
            <div
              className={clsx(
                !errorMessage && 'swap-token-select-box',
                'second-token-input-swap',
                errorMessage && 'errorBorder',
                secondTokenAmount > 0 && (errorMessage ? 'errorBorder' : 'second-input-typing'),
              )}
            >
              <div className="token-selector-balance-wrapper-swap">
                {props.tokenOut.name ? (
                  <button
                    className="token-selector token-selector-height"
                    onClick={() => props.handleTokenType('tokenOut')}
                  >
                    <img src={props.tokenOut.image} className="button-logo logo-size" />
                    <span className="span-themed">
                      {props.tokenOut.name === 'tez'
                        ? 'TEZ'
                        : props.tokenOut.name === 'ctez'
                        ? 'CTEZ'
                        : props.tokenOut.name}{' '}
                    </span>
                    <span className="span-themed material-icons-round">expand_more</span>
                  </button>
                ) : (
                  <button
                    className="token-selector token-selector-height not-selected"
                    onClick={() => props.handleTokenType('tokenOut')}
                  >
                    Select a token <span className="material-icons-round">expand_more</span>
                  </button>
                )}
              </div>

              <div className="token-user-input-wrapper">
                <div className="input-heading receive-heading">YOU RECEIVE</div>
                {props.tokenOut.name ? (
                  props.userBalances[props.tokenOut.name] >= 0 && routeDataCopy ? (
                    <input
                      type="text"
                      className={clsx(
                        'token-user-input',
                        secondTokenAmount && 'second-input-color',
                      )}
                      value={secondTokenAmount && fromExponential(secondTokenAmount)}
                      placeholder="0.0"
                      disabled
                      onChange={(e) => handleSwapTokenInput(e.target.value, 'tokenOut')}
                    />
                  ) : (
                    <span className="shimmer-text ml-auto">
                      <span className="shimmer shimmer-input">0.0000</span>
                    </span>
                  )
                ) : (
                  <input
                    type="text"
                    className="token-user-input"
                    disabled
                    placeholder="--"
                    value="--"
                  />
                )}
              </div>
              {props.walletAddress ? (
                <div className="flex justify-between" style={{ flex: '0 0 100%' }}>
                  <p className="wallet-token-balance balance-revamp">
                    Balance:{' '}
                    {props.tokenOut.name ? (
                      props.userBalances[props.tokenOut.name] >= 0 ? (
                        fromExponential(props.userBalances[props.tokenOut.name])
                      ) : (
                        <div className="shimmer">0.0000</div>
                      )
                    ) : (
                      '--'
                    )}
                  </p>
                  <p className="wallet-token-balance balance-revamp">
                    ~$
                    {props.tokenOut.name === 'tez' ? (
                      dolar * secondTokenAmount == null ? (
                        <span className="shimmer">99999999</span>
                      ) : secondTokenAmount ? (
                        (dolar * secondTokenAmount).toFixed(2)
                      ) : (
                        '0.00'
                      )
                    ) : props.getTokenPrice.success && secondTokenAmount ? (
                      getDollarValue(
                        secondTokenAmount,
                        props.getTokenPrice.tokenPrice[props.tokenOut.name],
                      )
                    ) : (
                      '0.00'
                    )}
                  </p>
                </div>
              ) : null}
            </div>
          </div>
          {props.showRecepient ? (
            <>
              <div className="send-heading">Send to</div>
              <input
                type="text"
                className="receiptant"
                placeholder="Recipient address"
                onChange={(e) => props.setRecepient(e.target.value)}
                value={props.recepient}
              />
            </>
          ) : (
            ''
          )}
          {props.walletAddress &&
          props.tokenIn.name &&
          props.tokenOut.name &&
          Number(firstTokenAmount) > 0 &&
          routeDataCopy ? (
            <SwapDetails
              routePath={routePath}
              theme={props.theme}
              computedOutDetails={computedData}
              tokenIn={props.tokenIn}
              tokenOut={props.tokenOut}
              routeData={props.routeData}
              firstTokenAmount={firstTokenAmount}
              stableList={stableList}
              isStableSwap={isStableSwap.current}
            />
          ) : null}
          {swapContentButton}
        </div>
      </div>

      <ConfirmSwap
        show={props.showConfirmSwap}
        computedData={computedData}
        tokenIn={props.tokenIn}
        firstTokenAmount={firstTokenAmount}
        tokenOut={props.tokenOut}
        slippage={props.slippage}
        confirmSwapToken={confirmSwapToken}
        onHide={props.handleClose}
        routeData={props.routeData}
        loading={props.loading}
        isStableSwap={false}
        theme={props.theme}
      />
      <ConfirmTransaction
        show={props.showConfirmTransaction}
        content={`Swap ${Number(localStorage.getItem('wrapped')).toFixed(6)} ${localStorage.getItem(
          'token',
        )} `}
        theme={props.theme}
        onHide={handleCloseModal}
      />
      <InfoModal
        open={showTransactionSubmitModal}
        InfoMessage={`Swap ${Number(localStorage.getItem('wrapped')).toFixed(
          6,
        )} ${localStorage.getItem('token')} `}
        theme={props.theme}
        onClose={() => setShowTransactionSubmitModal(false)}
        message={'Transaction submitted'}
        buttonText={'View on Block Explorer'}
        onBtnClick={
          transactionId ? () => window.open(`https://tzkt.io/${transactionId}`, '_blank') : null
        }
      />
      <Loader
        loading={props.loading}
        content={`Swap ${Number(localStorage.getItem('wrapped')).toFixed(6)} ${localStorage.getItem(
          'token',
        )} `}
        loaderMessage={props.loaderMessage}
        tokenIn={props.tokenIn.name}
        firstTokenAmount={firstAmount}
        tokenOut={props.tokenOut.name}
        secondTokenAmount={secondAmount}
        setLoaderMessage={props.setLoaderMessage}
        onBtnClick={
          transactionId ? () => window.open(`https://tzkt.io/${transactionId}`, '_blank') : null
        }
      />
    </>
  );
}
Example #29
Source File: translateCard.js    From masakhane-web with MIT License 4 votes vote down vote up
export default function TranslateCard() {
    const [input, setText] = useState("");
    const [translation, setTranslation] = useState('...');
    const [srcLanguages, setSrcLanguages] = useState([]);
    const [tgtLanguages, setTgtLanguages] = useState([]);
    const [show, setShow] = useState(false);
    const [src_lang, setSrc_Lang] = useState('English');
    const [tgt_lang, setTgt_Lang] = useState('Swahili');
    const [feedBackForm, setFeedBackForm] = useState({});
    const textareaRef = useRef(null);
    const textareaRef2= useRef(null);
    const [feedbackToken, setFeedbackToken] = useState(
        localStorage.getItem('feedbackToken') || ''
    );

    const [copySuccess, setCopySuccess] = useState('');
    const [showToast, setShowToast] = useState('');

    const handleClose = () => setShow(false);
    const handleShow = () => setShow(true);

    const copyToClipboard = () => {
        setCopySuccess('Translation Copied!');
        setShowToast(true);
    };

    const handleChangeSrc_Lang= (e) => {
        //localstorage
        const name = e.target.value
        localStorage.setItem('src_lang', name);

        //set state
        setSrc_Lang(name);
        //get target languages
        const target = srcLanguages.filter(x => x.name === name)
        const target_languages = target[0].targets 
        setTgtLanguages(target_languages)
        setTgt_Lang(target_languages[0].name)       
    };

    const handleChangeTgt_Lang = (e) => {
        //localstorage
        localStorage.setItem('tgt_lang', e.target.value);

        //set state
        setTgt_Lang(e.target.value);

        // console.log(e.target.value)
        
    };

    const handleTranslate = (e) => {
        console.log('translating ..')
        console.log(src_lang)
        console.log(tgt_lang)
        e.preventDefault()
    
        fetch( 
            '/translate', 
            {
                method: 'post', 
                // mode: 'no-cors',
                body: JSON.stringify({input, src_lang, tgt_lang}),
                headers: {
                    'Content-Type': 'application/json'
                  },
                // credentials: 'same-origin',
            })
          .then(res => res.json())
          .then(data => {
            //   console.log({ data })
            // do something here
            setTranslation(data.output)
          })
    };

    const submitFeedBack = (formData) => {
        // first set state of feedback Form
        setFeedBackForm({...formData});
        // then submit feedback form to db here
        // here's where you write the function to push feedback to backend

        console.log({formData})

        fetch( 
            '/save', 
            {
                method: 'post', 
                // mode: 'no-cors',
                body: JSON.stringify({
                    src_lang: formData.src_lang,
                    tgt_lang: formData.tgt_lang,
                    accurate_translation:  formData.accurate_translation,
                    know_src_lang: formData.know_src_lang,
                    know_tgt_lang:  formData.know_tgt_lang,
                    own_translation: formData.own_translation,
                    text:  formData.text,
                    translation: formData.translation,
                    understand_translation: formData.understand_translation,
                    feedbackToken: formData.feedbackToken
            }),
                headers: {
                    'Content-Type': 'application/json'
                  },
                // credentials: 'same-origin',
            })
          .then(res => res.json())
          .then(data => {
            //console.log({data})
            // do something here
            handleClear()
          })

    }


    const handleClear = () => {
        // clears text part
        setText('');
        // clear translation
        setTranslation('...');
    }

    useLayoutEffect(() => {
        // Reset height - important to shrink on delete
        textareaRef.current.style.height = "inherit";
        // Set height
        textareaRef.current.style.height = `${Math.max(
          textareaRef.current.scrollHeight,
          MIN_TEXTAREA_HEIGHT
        )}px`;
      }, [input]);

    useLayoutEffect(() => {
        // Reset height - important to shrink on delete
        textareaRef2.current.style.height = "inherit";
        // Set height
        textareaRef2.current.style.height = `${Math.max(
          textareaRef2.current.scrollHeight,
          MIN_TEXTAREA_HEIGHT
        )}px`;
      }, [input]);

    //   console.log({feedbackToken});
    //   console.log({tgt_lang});

    // console.log({feedbackToken});

    let srcLang = [];
    let tgtLang = [];

    useEffect(()=> {
        // define fetch function 
        let src = [];
        let tgt = [];
        const fetchLanguages = async ()=> {
        await fetch( 
            '/translate', 
            {
                method: 'get', 
                headers: {
                    'Content-Type': 'application/json'
                  },
                // credentials: 'same-origin',
            })
          .then(res => res.json())
          .then(data => {
              console.log({ data})
            // do something here
            setSrcLanguages(data)
            setTgtLanguages(data[0].targets)
        
          })
        

        }
        // call fetch function
        fetchLanguages()

    }, [])
    // console.log(srcLanguages)
    // console.log(tgtLanguages)
    // console.log(tgt_lang)

    return (
        <Container className="border">
            
            <Modal 
                scrollable={true} 
                show={show} 
                onHide={handleClose} 
                centered 
                size="lg"
            >
                <Modal.Header closeButton style={{backgroundColor:'#F2F0E9'}}>
                    <Col style={{textAlign: 'center'}}>
                        <h4 style={{ fontSize: 14, color: '#717171' }}>GIVE FEEDBACK</h4>
                        <p style={{ fontSize: 11, color: 'gray' }}>We appreciate your feedback and your contribution will help make our translation better.</p>
                    </Col>
                </Modal.Header>
                <Modal.Body>
                    <MultiStepForm 
                        src_lang={src_lang} 
                        tgt_lang={tgt_lang} 
                        text={input} 
                        translation={translation} 
                        setShow={setShow}
                        submitFeedBack={submitFeedBack}
                        setFeedbackToken={setFeedbackToken}
                        feedbackToken={feedbackToken}
                    />
                </Modal.Body>
            </Modal>

            <Row className="header" style={{ backgroundColor: 'aliceblue', height: 60, fontSize: '1rem', padding: '0.5rem 0.5rem' }}>
                <Col className="border-right" style={{marginBottom: 10}}>
                    <Row>
                        <Col md={6} xs={12}>
                            <Form inline>
                                <Form.Group controlId="fromform">
                                    <Form.Label>From: </Form.Label>
                                    <Form.Control value={src_lang} style={{ border: 0, marginLeft: 10 }} as="select" size="sm" custom onChange={handleChangeSrc_Lang}>
                                    {
                                        srcLanguages && srcLanguages.map((option, index) => {
                                        return (<option key={index} value={option.name}>{option.name}</option>)
                                        })
                                    }
                                    </Form.Control>
                                </Form.Group>
                            </Form>
                        </Col>
                        {/* <Col className="d-none d-sm-block">
                             <Row>
                            {
                                srcLanguages.length > 1 && srcLanguages
                                .filter(x => x.value !== src_lang)
                                .slice(0, 2)
                                .map((option, index) => {
                                return (
                                    <Button key={option.id} variant="light" size="sm" onClick={() => setSrc_Lang(option.name)}>{option.name}</Button>                                   )
                                })
                            }
                            </Row>
                        </Col> */}
                    </Row>
                </Col>
                <Col style={{ marginLeft: '15px' }}>
                    <Row>
                        <Col md={6} xs={12}>
                            <Form inline>
                                <Form.Group controlId="fromform" as={Row}>
                                <Form.Label>To: </Form.Label>
                                    <Form.Control md={6} xs={12} value={tgt_lang} style={{ border: 0, marginLeft: 10 }} as="select" size="sm" custom onChange={handleChangeTgt_Lang}>
                        
                                    {
                                        tgtLanguages.map((option, index) => {
                                        return (<option key={index} value={option.name}>{option.name}</option>)
                                        })
                                    }

                                    </Form.Control>
                                </Form.Group>
                            </Form>
                        </Col>
                        {/* <Col className="d-none d-sm-block">
                            <Row>
                            {
                                tgtLanguages.length > 1 && tgtLanguages
                                .filter(x => x.value !== tgt_lang)
                                .slice(0, 2)
                                .map((option, index) => {
                                return (
                                    <Button key={option.id} variant="light" size="sm" onClick={() => setTgt_Lang(option.name)}>{option.name}</Button>                                   )
                                })
                            }
                            </Row>
                        </Col> */}
                    </Row>
                </Col>
            </Row>
            <Row style={{ minHeight: '250px', marginTop: '20px' }}>
                <Col md={6} xs={12} className="ml-1" style={{ paddingTop: '20px', paddingBottom: '20px', marginLeft: '10px' }}>
                    <Form>
                        <Form.Group controlId="Form.ControlTextarea">
                            <Form.Control 
                                as="textarea"
                                placeholder="Enter Text" 
                                rows="3" 
                                name="text"
                                ref={textareaRef}
                                style={{ fontSize: 24, minHeight: MIN_TEXTAREA_HEIGHT, resize: 'none' }} 
                                value={input}
                                onChange={e => setText(e.target.value)}
                            />
                        </Form.Group>
                    </Form>
                    
                    <Row>
                        <Col md={10} xs={10}>
                            <Button variant="primary" style={{ marginBottom: 10 }} onClick={handleTranslate}>Translate</Button>
                        </Col>
                        <Col md={2} xs={2} lg="2">
                            <Button style = {{color:'grey'}} variant = 'link' size="sm" onClick={handleClear}><i className="fas fa-times"></i></Button>{' '}
                        </Col>
                    </Row>
                </Col>
                <Col style={{ paddingTop: '20px', paddingBottom: '20px' }}>
                    <Form>
                        <Form.Group controlId="Form.ControlTextarea2">
                            <Form.Control 
                                controlid="translation"
                                as="textarea"
                                placeholder="..." 
                                rows="3" 
                                name="text"
                                ref={textareaRef2}
                                style={{ fontSize: 24, minHeight: MIN_TEXTAREA_HEIGHT, resize: 'none' }} 
                                value={translation}
                                readOnly
                                isInvalid={!translation}
                                // onChange={e => setText(e.target.value)}
                                // autoFocus={showToast}
                            />
                            {!translation && (
                                <Form.Control.Feedback type="invalid">
                                    Sorry, there’s no translation for that phrase.
                                </Form.Control.Feedback>
                            )}
                        </Form.Group>
                    </Form>
                    
                    <Row>
                        <Col md={10} xs={10}>
                            {/* <Button variant="light" size = 'sm' style={{ bottom: '10px' }} onClick={handleShow}>Give Feedback on Translation</Button> */}
                        </Col>
                        <Col md={2} xs={2} lg="2">
                            <OverlayTrigger
                                placement='top'
                                overlay={
                                <Tooltip id={'tooltip-top'}>
                                    Copy <strong>Translation</strong>.
                                </Tooltip>
                                }
                            >
                                <CopyToClipboard text={translation} onCopy={copyToClipboard}>
                                    <Button variant="light" size="sm"><i className="fa fa-copy"></i></Button>
                                </CopyToClipboard>
                            </OverlayTrigger>
                        </Col>
                    </Row>
                </Col>
            </Row>

            <div aria-live="polite" aria-atomic="true" style={{ position: 'relative' }}>
                <Toast
                    onClose={() => setShowToast(false)} 
                    show={showToast} 
                    delay={3000} 
                    autohide
                    style={{
                        position: 'absolute',
                        bottom: 0,
                        left: 0
                    }}
                >
                    <Toast.Body style={{color: 'black'}}>{copySuccess}</Toast.Body>
                </Toast>
            </div>
        </Container>
    )
}