react-bootstrap#Tooltip JavaScript Examples

The following examples show how to use react-bootstrap#Tooltip. 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: 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 #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: 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 #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: 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 #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: 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 #11
Source File: MonitoringStatus.js    From SaraAlert with Apache License 2.0 5 votes vote down vote up
renderPHARefreshTooltip(props) {
    return (
      <Tooltip id="button-tooltip" {...props}>
        {this.state.public_health_action === 'None' && <span>You can&apos;t add an additional &quot;None&quot; public health action.</span>}
        {this.state.public_health_action != 'None' && <span>Add an additional &quot;{this.state.public_health_action}&quot; public health action.</span>}
      </Tooltip>
    );
  }
Example #12
Source File: MainCard.js    From Frontend with Apache License 2.0 5 votes vote down vote up
renderTooltip1 = (props) => (
  <Tooltip id="button-tooltip" {...props}>
    Add to Problem List
  </Tooltip>
)
Example #13
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 #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: MainToolbar.jsx    From mapstore2-cadastrapp with GNU General Public License v3.0 5 votes vote down vote up
export default function MainToolbar(props) {
    // following array values are
    // 0: glyphicon
    // 1: action name
    // 2: tooltip text
    let toolbarOptions = [
        ["resize-full", "zoom", "Zoom to whole selection"],
        ["map-marker", "select-by-point", "Select / Activate / Unselect one plot with a simple click "],
        ["polyline", "select-by-linestring", "Select / Activate / Unselect plots which intersects a line"],
        ["polygon", "select-by-polygon", "Select / Activate / Unselect plots which intersects a polygon"],
        ["th-list", "unit-de-fonc", "Landed property information"],
        ["zoom-to", "search-plots", "Plots Search"],
        ["search", "search-owners", "Owners Search"],
        ["user", "coownership", "Co-ownership data Search"],
        ["features-grid", "request-form", "Request on landholding trust"],
        ["cog", "preferences", "Preferences"],
        ["question-sign", "help", "Help"]
    ];

    let clickHandler = (action) => {
        return () => {
            props.onClick(action);
        };
    };

    let tooltipGenerator = (text) => {
        return <Tooltip id="tooltip">{text}</Tooltip>;
    };

    return (
        <div className="side-bar pull-left">
            {toolbarOptions.map((v) => (
                <OverlayTrigger placement="left" overlay={tooltipGenerator(v[2])}>
                    <Button
                        onClick={clickHandler(v[1])}
                        bsStyle="primary"
                        className={props.selected === v[1] ? "square-button btn-selected" : "square-button"}>
                        <span className={"glyphicon glyphicon-" + v[0]}></span>
                    </Button>
                </OverlayTrigger>
            ))}
        </div>
    );
}
Example #16
Source File: Step1.js    From katanapools with GNU General Public License v2.0 5 votes vote down vote up
render() {
    const {address, weight, idx, addressChanged, weightChanged, poolType, symbol, name} = this.props;
    let removeRow = <FontAwesomeIcon icon={faTimes} className="remove-icon-btn" onClick={()=>this.props.removeTokenRow(idx)}/>;
    if (idx === 0 && poolType === 'any') {
      removeRow = <span/>;
    }
function reserveRatioTooltip(props) {
   return <Tooltip {...props}>
    <div>
    Reserve ratio defines the ratio between the total value of the reserves & the market cap of the pool token.
    </div>
    <div>
    While most pools have a network hub token and a pool token kept in a 50/50 reserve ratio,
    </div>
    <div>
     You can also create pools with an array of reserves in any arbitrary reserve ratio.
    </div>
    <div>
    Provided the sum of all reserves is less than or equal to 100.
    </div>

    </Tooltip>;
}
    let tokenDetails = <span/>;;
    if (symbol && name) {
      tokenDetails = <div>Symbol: {symbol} Name: {name}</div>
    }
    return (
        <Row>
        <Col lg={8}>
        <Form.Group controlId="formBasicEmail">
          <Form.Label>Convertible Reserve Token Address</Form.Label>
          <Form.Control type="text" placeholder="address of the ERC20 token contract" value={address} onChange={this.addressChanged} onBlur={this.addressOrSymbolSet}/>
          <Form.Text className="text-muted">
            {tokenDetails}
          </Form.Text>
        </Form.Group>
        </Col>
        <Col lg={4} className="token-weight-slider-container">
          <div className="slidecontainer">
          <Row>
            <Col lg={8} className="reserve-ratio-field-container">
            Token Reserve Ratio
            </Col>
            <Col lg={4}>
            <Form.Control type="number" value={weight} onChange={this.weightChanged} className="amount-row"/>
            </Col>
            </Row>
            <Row>
            <input type="range" min="0" max="100" value={weight} className="slider"
            id="myRange" onChange={this.weightChanged}/>
            </Row>
          </div>
          {removeRow}
        </Col>
        </Row>
      )
  }
Example #17
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 #18
Source File: BridgeModal.js    From plenty-interface with GNU General Public License v3.0 4 votes vote down vote up
BridgeModal = (props) => {
  const dispatch = useDispatch();
  const [errorMessage, setErrorMessage] = useState(null);
  const [isError, setIsError] = useState(false);
  const [showMetamaskTooltip, setShowMetamaskTooltip] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [show, setShow] = useState(false);
  const [userBalances, setUserBalances] = useState({});
  const [isLoading, SetisLoading] = useState(false);
  const [isTokenInSelected, setIsTokenInSelected] = useState(false);
  const [isBridgeSelected, setIsBridgeSelected] = useState(false);
  const [isTokenSelected, setIsTokenSelected] = useState(false);
  const [isBridgeClicked, setIsBridgeClicked] = useState(false);
  const [pendingTransCount, setPendingTransCount] = useState(0);
  const [animationClass, setAnimationClass] = useState('leftToRightFadeInAnimation-4-bridge');
  const [isHistoryLoading, setIsHistoryLoading] = useState(true);
  const selector = useRef('BRIDGES');
  const delay = useRef(5000);
  const firstTimeLoading = useRef(true);
  const {
    walletAddress,
    transaction,
    setTransaction,
    fromBridge,
    toBridge,
    tokenIn,
    tokenOut,
    firstTokenAmount,
    secondTokenAmount,
    fee,
    operation,
    setFromBridge,
    setToBridge,
    setTokenIn,
    setTokenOut,
    setFirstTokenAmount,
    setSecondTokenAmount,
    setFee,
    setOperation,
    tokenList,
    loadedTokensList,
    theme,
    setOpeningFromHistory,
    metamaskAddress,
    currentChain,
    metamaskChain,
    displayMessage,
    setSwitchButtonPressed,
    connectWalletHandler,
    setIsApproved,
  } = props;

  const [connectBridgeWallet, setConnectBrigeWallet] = useState({
    name: fromBridge.name,
    image: fromBridge.image,
    buttonImage: fromBridge.buttonImage,
  });
  
  useEffect(() => {
    if (currentChain !== metamaskChain && transaction === 1) {
      if (metamaskChain !== null) {
        displayMessage({
          type: 'warning',
          duration: FLASH_MESSAGE_DURATION,
          title: 'Chain mismatch',
          content: `Change wallet chain to ${titleCase(currentChain)}.`,
          isFlashMessageALink: false,
          flashMessageLink: '#',
        });

        setTimeout(async () => {
          try {
            await changeNetwork({ networkName: currentChain });
          } catch (error) {
            displayMessage({
              type: 'error',
              duration: FLASH_MESSAGE_DURATION,
              title: 'Chain change failed',
              content: 'Failed to force change the chain. Please change in wallet.',
              isFlashMessageALink: false,
              flashMessageLink: '#',
            });
          }
        }, CHANGE_NETWORK_PROMPT_DELAY);
      }
    }
  }, [currentChain, metamaskChain]);

  useEffect(() => {
    if (currentChain === metamaskChain && isError) {
      setIsError(false);
    }
  }, [metamaskChain]);

  useEffect(() => {
    setOpeningFromHistory(false);
    setIsApproved(false);
  }, []);

  useEffect(() => {
    if (walletAddress) {
      dispatch(setConnectWalletTooltip(false));
      setIsError(false);
    }
  }, [walletAddress]);

  useEffect(async () => {
    if (metamaskAddress) {
      setShowMetamaskTooltip(false);
      setIsError(false);
    }
    if (firstTimeLoading.current && metamaskAddress && walletAddress) {
      const pendingHistoryCount = await getActionRequiredCount({
        ethereumAddress: metamaskAddress,
        tzAddress: walletAddress,
      });
      setPendingTransCount(pendingHistoryCount.count);
      setIsHistoryLoading(false);
      firstTimeLoading.current = false;
    }
  }, [metamaskAddress]);

  useEffect(async () => {
    setUserBalances((prevState) => ({ ...prevState, [tokenIn.name]: null }));
    if (
      tokenIn.name !== 'Token NA' &&
      walletAddress &&
      metamaskAddress &&
      metamaskChain === currentChain
    ) {
      if (operation === 'BRIDGE') {
        const balanceResult = await getBalance(tokenIn.tokenData.CONTRACT_ADDRESS, metamaskAddress);
        if (balanceResult.success) {
          setUserBalances((prevState) => ({
            ...prevState,
            [tokenIn.name]: new BigNumber(balanceResult.balance).div(new BigNumber(10).pow(tokenIn.tokenData.DECIMALS)).toString(),
          }));
        } else {
          setUserBalances((prevState) => ({ ...prevState, [tokenIn.name]: -1 }));
        }
      } else {
        const tokenInDecimals = BridgeConfiguration.getOutTokenUnbridgingWhole(
          toBridge.name,
          tokenIn.name,
        ).DECIMALS;
        const balanceResult = await getBalanceTez(
          tokenIn.tokenData.CONTRACT_ADDRESS,
          tokenIn.tokenData.TOKEN_ID,
          walletAddress,
          tokenInDecimals,
        );
        if (balanceResult.success) {
          setUserBalances((prevState) => ({
            ...prevState,
            [tokenIn.name]: new BigNumber(balanceResult.balance).toString(),
          }));
        } else {
          setUserBalances((prevState) => ({ ...prevState, [tokenIn.name]: -1 }));
        }
      }
    } else {
      setUserBalances((prevState) => ({ ...prevState, [tokenIn.name]: -1 }));
    }
  }, [tokenIn, walletAddress, metamaskAddress, metamaskChain]);

  useInterval(async () => {
    if (metamaskAddress && walletAddress) {
      const pendingHistoryCount = await getActionRequiredCount({
        ethereumAddress: metamaskAddress,
        tzAddress: walletAddress,
      });
      setPendingTransCount(pendingHistoryCount.count);
      setIsHistoryLoading(false);
    }
  }, delay.current);

  const onClickAmount = () => {
    const value = userBalances[tokenIn.name] ?? 0;
    handleFromTokenInput(value);
  };

  const handleFromTokenInput = (input) => {
    setIsError(false);
    if (!walletAddress && !metamaskAddress) {
      dispatch(setConnectWalletTooltip(true));
      setShowMetamaskTooltip(true);
      displayMessage({
        type: 'info',
        duration: FLASH_MESSAGE_DURATION,
        title: 'Connect wallet',
        content: 'Connect both the wallets and proceed.',
        isFlashMessageALink: false,
        flashMessageLink: '#',
      });
      setErrorMessage('Please connect to both the wallets.');
      setIsError(true);
    } else if (!walletAddress && metamaskAddress) {
      dispatch(setConnectWalletTooltip(true));
      setErrorMessage('Please connect to tezos wallet.');
      setIsError(true);
    } else if (!metamaskAddress && walletAddress) {
      setShowMetamaskTooltip(true);
      setErrorMessage(
        `Please connect to ${
          fromBridge.name === 'TEZOS' ? toBridge.name : fromBridge.name
        } wallet.`,
      );
      setIsError(true);
    } else {
      if (
        input === '' ||
        isNaN(input) ||
        tokenIn.name === 'Token NA' ||
        userBalances[tokenIn.name] === null ||
        userBalances[tokenIn.name] < 0
      ) {
        setFirstTokenAmount('');
        setSecondTokenAmount('');
        setFee(0);
      } else {
        setFirstTokenAmount(input);
        if (new BigNumber(input).gt(new BigNumber(userBalances[tokenIn.name]))) {
          setErrorMessage('Insufficient balance');
          setIsError(true);
        } else {
          if (operation === 'BRIDGE') {
            setFee(
              new BigNumber(input)
                .multipliedBy(BridgeConfiguration.getFeesForChain(fromBridge.name).WRAP_FEES)
                .div(10000)
                .toString(),
            );
            const outputAmount = new BigNumber(input)
              .minus(
                new BigNumber(input)
                  .multipliedBy(BridgeConfiguration.getFeesForChain(fromBridge.name).WRAP_FEES)
                  .div(10000),
              )
              .toString();
            setSecondTokenAmount(outputAmount);
          } else {
            setFee(
              new BigNumber(input)
                .multipliedBy(BridgeConfiguration.getFeesForChain(toBridge.name).UNWRAP_FEES)
                .div(10000)
                .toString(),
            );
            const outputAmount = new BigNumber(input)
              .minus(
                new BigNumber(input)
                  .multipliedBy(BridgeConfiguration.getFeesForChain(toBridge.name).UNWRAP_FEES)
                  .div(10000),
              )
              .toString();
            setSecondTokenAmount(outputAmount);
          }
        }
      }
    }
  };

  const handelClickWithMetaAddedBtn = async () => {
    setIsError(false);
    if (firstTokenAmount === '' || isNaN(firstTokenAmount) || firstTokenAmount === 0) {
      setErrorMessage('Enter an amount to proceed');
      setIsError(true);
    } else if (new BigNumber(firstTokenAmount).gt(new BigNumber(userBalances[tokenIn.name]))) {
      setErrorMessage('Insufficient balance');
      setIsError(true);
    } else {
      if (currentChain !== metamaskChain) {
        displayMessage({
          type: 'warning',
          duration: FLASH_MESSAGE_DURATION,
          title: 'Chain mismatch',
          content: `Change wallet chain to ${titleCase(currentChain)}.`,
          isFlashMessageALink: false,
          flashMessageLink: '#',
        });

        setTimeout(async () => {
          try {
            await changeNetwork({ networkName: currentChain });
          } catch (error) {
            displayMessage({
              type: 'error',
              duration: FLASH_MESSAGE_DURATION,
              title: 'Chain change failed',
              content: 'Failed to force change the chain. Please change in wallet.',
              isFlashMessageALink: false,
              flashMessageLink: '#',
            });
          }
        }, CHANGE_NETWORK_PROMPT_DELAY);
      } else {
        SetisLoading(true);
        if (operation === 'BRIDGE') {
          const allowanceResult = await getAllowance(tokenIn, metamaskAddress, fromBridge.name);
          if (allowanceResult.success) {
            if (new BigNumber(allowanceResult.allowance).gte(new BigNumber(firstTokenAmount))) {
              setIsApproved(true);
            }
            setAnimationClass('rightToLeftFadeOutAnimation-4');
            setTimeout(() => {
              SetisLoading(false);
              setTransaction(3);
            }, 600);
          } else {
            displayMessage({
              type: 'error',
              duration: FLASH_MESSAGE_DURATION,
              title: 'Allowance error',
              content: 'Failed to fetch allowance for user. Please try again.',
              isFlashMessageALink: false,
              flashMessageLink: '#',
            });
            SetisLoading(false);
          }
        } else {
          setAnimationClass('rightToLeftFadeOutAnimation-4');
          setTimeout(() => {
            SetisLoading(false);
            setTransaction(3);
          }, 600);
        }
      }
    }
  };

  const handleClose = () => {
    setShow(false);
    setIsBridgeClicked(false);
    setSearchQuery('');
  };
  
  const handleInputFocus = () => {
    setIsError(false);
    setIsTokenInSelected(true);
    if (walletAddress && metamaskAddress && currentChain !== metamaskChain) {
      setErrorMessage(`Please select ${titleCase(currentChain)} chain in wallet.`);
      setIsError(true);
    }
  };

  const selectBridge = (bridge) => {
    setFirstTokenAmount('');
    setSecondTokenAmount('');
    setFee(0);
    if (bridge.name === 'TEZOS') {
      const currentFrom = {
        name: fromBridge.name,
        image: fromBridge.image,
        buttonImage: fromBridge.buttonImage,
      };
      if (currentFrom.name !== 'TEZOS') {
        setToBridge({
          name: currentFrom.name,
          image: currentFrom.image,
          buttonImage: currentFrom.buttonImage,
        });
      }
      setOperation('UNBRIDGE');
    } else {
      setConnectBrigeWallet({
        name: bridge.name,
        image: bridge.image,
        buttonImage: bridge.buttonImage,
      });
      if (operation === 'UNBRIDGE') {
        setToBridge({ name: 'TEZOS', image: tezos, buttonImage: '' });
        setOperation('BRIDGE');
      }
    }
    setFromBridge({ name: bridge.name, image: bridge.image, buttonImage: bridge.buttonImage });
    setIsBridgeSelected(true);
    handleClose();
  };

  const handleBridgeSelect = () => {
    selector.current = 'BRIDGES';
    setIsBridgeClicked(true);
    setShow(true);
  };

  const selectToken = (token) => {
    setFirstTokenAmount('');
    setSecondTokenAmount('');
    setFee(0);

    setTokenIn({
      name: token.name,
      image: token.image,
      tokenData: token.tokenData,
    });
    if (fromBridge.name === 'TEZOS') {
      const outTokenName = BridgeConfiguration.getOutTokenUnbridging(toBridge.name, token.name);
      setTokenOut({
        name: outTokenName,
        image: Object.prototype.hasOwnProperty.call(allTokens, outTokenName)
          ? allTokens[outTokenName]
          : allTokens.fallback,
      });
    } else {
      const outTokenName = BridgeConfiguration.getOutTokenBridging(fromBridge.name, token.name);
      setTokenOut({
        name: outTokenName,
        image: Object.prototype.hasOwnProperty.call(allTokens, outTokenName)
          ? allTokens[outTokenName]
          : allTokens.fallback,
      });
    }
    setIsTokenSelected(true);
    handleClose();
  };

  const handleTokenSelect = () => {
    selector.current = 'TOKENS';
    setShow(true);
  };

  const switchHandler = () => {
    setSwitchButtonPressed(true);
    setFirstTokenAmount('');
    setSecondTokenAmount('');
    setFee(0);
    const currentFrom = {
      name: fromBridge.name,
      image: fromBridge.image,
      buttonImage: fromBridge.buttonImage,
    };
    const currentTo = {
      name: toBridge.name,
      image: toBridge.image,
      buttonImage: toBridge.buttonImage,
    };
    const currentTokenIn = tokenIn.name;
    const currentTokenOut = tokenOut.name;
    const tokenData =
      operation === 'BRIDGE'
        ? loadedTokensList.TEZOS[currentFrom.name].find((token) => token.name === currentTokenOut)
            .tokenData
        : loadedTokensList[currentTo.name].find((token) => token.name === currentTokenOut)
            .tokenData;

    if(tokenIn.tokenData.deprecated) {
      displayMessage({
        type: 'warning',
        duration: FLASH_MESSAGE_DURATION,
        title: 'Deprecated token selected',
        content: 'Bridging not allowed for deprecated token. Please select non deprecated token to switch.',
        isFlashMessageALink: false,
        flashMessageLink: '#',
      });
      setSwitchButtonPressed(false);
    } else {
      setToBridge({
        name: currentFrom.name,
        image: currentFrom.image,
        buttonImage: currentFrom.buttonImage,
      });
      setFromBridge({
        name: currentTo.name,
        image: currentTo.image,
        buttonImage: currentTo.buttonImage,
      });
      setTokenIn({
        name: currentTokenOut,
        image: Object.prototype.hasOwnProperty.call(allTokens, currentTokenOut)
          ? allTokens[currentTokenOut]
          : allTokens.fallback,
        tokenData,
      });
      setTokenOut({
        name: currentTokenIn,
        image: Object.prototype.hasOwnProperty.call(allTokens, currentTokenIn)
          ? allTokens[currentTokenIn]
          : allTokens.fallback,
      });
      if (operation === 'BRIDGE') {
        setOperation('UNBRIDGE');
      } else {
        setOperation('BRIDGE');
      }
    }
  };

  return (
    <div
      className={`justify-content-center mx-auto col-20 col-md-10 col-lg-12 col-xl-12 mb-3 ${styles.gov} ${animationClass}`}
    >
      <div className={styles.border}>
        <div className={` ${styles.bridgeModal}`}>
          <div>
            <div className={styles.resultsHeader}>
              <p className={styles.heading}>
                Bridge{' '}
                {metamaskAddress && (
                  <OverlayTrigger
                    overlay={(props) => (
                      <Tooltip className="connect-wallet-tooltip wallet-message-tooltip" {...props}>
                        Disconnect Ethereum wallets through wallet.
                      </Tooltip>
                    )}
                    placement="top"
                  >
                    <span className={styles.metamaskAddressText}>{`(${truncateMiddle(
                      metamaskAddress,
                      5,
                      4,
                      '...',
                    )})`}</span>
                  </OverlayTrigger>
                )}
              </p>
              {walletAddress &&
                metamaskAddress &&
                (isHistoryLoading ? (
                  <p className={`${styles.resLoading} shimmer`}>View history</p>
                ) : (
                  <p
                    className={`${styles.res}`}
                    onClick={() => {
                      setAnimationClass('rightToLeftFadeOutAnimation-4');
                      setTimeout(() => {
                        setTransaction(2);
                      }, 600);
                    }}
                    style={{ cursor: 'pointer' }}
                  >
                    View history{' '}
                    {pendingTransCount > 0 && (
                      <span className={styles.actionRequiredCount}>{pendingTransCount}</span>
                    )}
                  </p>
                ))}
            </div>
            <div className={`mb-2 ${styles.lineBottom} `}></div>
            <div className={`mt-4 ${styles.from}`}>From</div>
            <div className={`mt-2 ${styles.fromBridgeSelectBox}`}>
              <div>
                <p className={`mb-1 ${styles.fromLabelTop}`}>Select blockchain </p>
                <p className={`mb-0 ${styles.fromLabelBottom}`}>Start the bridge process</p>
              </div>
              <div
                className={clsx(
                  styles.bridgeSelector,
                  styles.selector,
                  isBridgeClicked && styles.fromBridgeClicked,
                )}
                onClick={handleBridgeSelect}
                style={{ boxShadow: isBridgeSelected && 'none' }}
              >
                <img src={fromBridge.image} className="button-logo" />
                <span>{titleCase(fromBridge.name)} </span>
                <span className="span-themed material-icons-round" style={{ fontSize: '20px' }}>
                  expand_more
                </span>
              </div>
            </div>
            <div className={`my-3 ${styles.lineMid} `}></div>
            <p className={styles.midLabel}>Select your token and enter the amount</p>
            <div
              className={`mt-2 ${styles.tokenSelectBox} ${
                isTokenInSelected && styles.tokenInSelected
              } ${styles.inputSelectBox} ${isError && styles.inputError}`}
            >
              <div
                className={clsx(styles.selector, styles.toTokenSelector)}
                onClick={handleTokenSelect}
                style={{ boxShadow: isTokenSelected && 'none' }}
              >
                <img src={tokenIn.image} className="button-logo" />
                <span>{tokenIn.name} </span>
                <span className="span-themed material-icons-round" style={{ fontSize: '18px' }}>
                  expand_more
                </span>
              </div>
              <div className={clsx(styles.inputWrapper)}>
                <input
                  type="text"
                  className={`text-right ${styles.tokenUserInput}`}
                  placeholder="0.0"
                  value={firstTokenAmount}
                  onChange={(e) => handleFromTokenInput(e.target.value)}
                  onFocus={handleInputFocus}
                  onBlur={() => setIsTokenInSelected(false)}
                />
              </div>
            </div>
            <div
              className="flex justify-between"
              style={{ flex: '0 0 100%', marginBottom: '2vh', height: '24px' }}
            >
              <p className={clsx(styles.errorText)}>{isError ? errorMessage : ' '}</p>
              <p className={clsx('wallet-token-balance', styles.balanceText)}>
                {userBalances[tokenIn.name] >= 0 && userBalances[tokenIn.name] !== null && (
                  <>
                    Balance:{' '}
                    <span className={styles.balanceValue} onClick={onClickAmount}>
                      {fromExponential(userBalances[tokenIn.name])}
                    </span>
                  </>
                )}
                {userBalances[tokenIn.name] === null && (
                  <>
                    Balance: <span className="shimmer">0.0000</span>
                  </>
                )}
              </p>
            </div>
            <OverlayTrigger
              overlay={(props) => (
                <Tooltip id={styles.switchTooltip} className="switchTooltip" {...props}>
                  Switch
                </Tooltip>
              )}
              placement="right"
            >
              <div
                className={`mx-auto flex justify-content-center align-items-center ${styles.arrowSwap}`}
                onClick={switchHandler}
              >
                <img src={theme === 'light' ? switchImg : switchImgDark} alt={'switch-image'} />
              </div>
            </OverlayTrigger>

            <div className={`mt-2 ${styles.to}`}>To</div>
            <div
              className={`mt-2 ${styles.toBridgeSelectBox} ${styles.inputSelectBox} ${
                isTokenInSelected ? styles.toBridgeSelected : null
              }`}
            >
              <div className={clsx(styles.toBridgeWrapper)}>
                <div className={styles.toBridgeSelector}>
                  <img src={toBridge.image} className="button-logo" />
                  <span>{titleCase(toBridge.name)}</span>
                </div>
                <div className={clsx(styles.lineVertical, 'mx-2')}></div>
                <div className={clsx(styles.inputWrapper)}>
                  <p className={styles.toLabel}>You will receive</p>
                  <OverlayTrigger
                    overlay={
                      secondTokenAmount === '' || secondTokenAmount <= 0 ? (
                        <span></span>
                      ) : (
                        (props) => (
                          <Tooltip className="switchTooltip token-output-tooltip" {...props}>
                            {fromExponential(secondTokenAmount)}
                          </Tooltip>
                        )
                      )
                    }
                    placement="top"
                  >
                    <input
                      type="text"
                      className={`text-left ${styles.toTokenOutput}`}
                      placeholder="0.0"
                      value={fromExponential(secondTokenAmount)}
                      disabled
                    />
                  </OverlayTrigger>
                </div>
              </div>
              <span
                className={`flex justify-content-center align-items-center ml-2 ${styles.toTokenLabel}`}
              >
                {tokenOut.name}
              </span>
            </div>
            <p className={clsx('mt-2', styles.feeEstimateText)}>
              Bridge fee:{' '}
              <span style={{ fontWeight: '700' }}>
                {Number(fee) > 0 ? fromExponential(Number(Number(fee).toFixed(16))) : 0}
                {` ${operation === 'BRIDGE' ? tokenOut.name : tokenIn.name}`}
              </span>
            </p>

            {metamaskAddress === null ? (
              <OverlayTrigger
                overlay={(props) => (
                  <Tooltip className="connect-wallet-tooltip metamask-wallet-tooltip" {...props}>
                    Connect wallet
                  </Tooltip>
                )}
                placement="top"
                show={showMetamaskTooltip}
              >
                <Button
                  className={clsx('px-md-3', 'mt-3', 'w-100', 'connect-wallet-btn', 'button-bg')}
                  onClick={connectWalletHandler}
                >
                  <div className={clsx('connect-wallet-btn')}>
                    <div className="flex flex-row align-items-center">
                      <connectBridgeWallet.buttonImage />
                      <span className="ml-2">
                        Connect to {titleCase(connectBridgeWallet.name)} wallet
                      </span>
                    </div>
                  </div>
                </Button>
              </OverlayTrigger>
            ) : (
              <>
                <Button
                  className={clsx(
                    'px-md-3',
                    'mt-3',
                    'w-100',
                    'connect-wallet-btn',
                    'button-bg',
                    firstTokenAmount === '' ? styles.disabledProceedButton : '',
                  )}
                  onClick={handelClickWithMetaAddedBtn}
                  loading={isLoading}
                >
                  <div className={clsx('connect-wallet-btn')}>
                    <div className="flex flex-row align-items-center">
                      <span className="ml-2">Proceed</span>
                    </div>
                  </div>
                </Button>
              </>
            )}
          </div>
        </div>
      </div>
      <SelectorModal
        show={show}
        onHide={handleClose}
        selectToken={selector.current === 'BRIDGES' ? selectBridge : selectToken}
        tokens={
          selector.current === 'BRIDGES'
            ? bridgesList
            : operation === 'UNBRIDGE'
            ? [...tokenList]
                .filter((token) => token.name !== 'WRAP')
                .sort(
                  (a, b) =>
                    a.tokenData.deprecated - b.tokenData.deprecated || a.name.localeCompare(b.name),
                )
            : [...tokenList]
                .filter((token) => !token.tokenData.deprecated)
                .sort((a, b) => a.name.localeCompare(b.name))
        }
        searchQuery={searchQuery}
        setSearchQuery={setSearchQuery}
        title={selector.current === 'BRIDGES' ? 'Select a chain' : 'Select a token'}
        selector={selector.current}
      />
    </div>
  );
}
Example #19
Source File: jitsibroadcaster.js    From RC4Community with Apache License 2.0 4 votes vote down vote up
Jitsibroadcaster = ({ room, disName, rtmpSrc, handleChat }) => {
  const apiRef = useRef();
  const [logItems, updateLog] = useState([]);
  const [knockingParticipants, updateKnockingParticipants] = useState([]);
  const [mute, setMute] = useState(true);
  const [name, setName] = useState(null);
  const dataArr = [
    { speaker: "A", hour: "10" },
    { speaker: "B", hour: "20" },
    { speaker: "C", hour: "30" },
    { speaker: "D", hour: "40" },
    { speaker: "Z", hour: "50" },
  ];

  const handleDisplayName = async (hr) => {
    const tar = dataArr.find((o) => o.hour === hr);
    if (!tar || tar.speaker == name) {
      return;
    }
    setName(tar.speaker);
    await apiRef.current.executeCommand("displayName", tar.speaker);
  };

  useEffect(() => {
    setInterval(() => {
      const tada = new Date();
      handleDisplayName(tada.getHours().toString());
    }, 900000);
  }, []);

  const printEventOutput = (payload) => {
    updateLog((items) => [...items, JSON.stringify(payload)]);
  };

  const handleAudioStatusChange = (payload, feature) => {
    if (payload.muted) {
      updateLog((items) => [...items, `${feature} off`]);
    } else {
      updateLog((items) => [...items, `${feature} on`]);
    }
  };

  const handleChatUpdates = (payload, ref) => {
    if (payload.isOpen || !payload.unreadCount) {
      return;
    }
    ref.current.executeCommand("toggleChat");
    updateLog((items) => [
      ...items,
      `you have ${payload.unreadCount} unread messages`,
    ]);
  };

  const handleKnockingParticipant = (payload) => {
    updateLog((items) => [...items, JSON.stringify(payload)]);
    updateKnockingParticipants((participants) => [
      ...participants,
      payload?.participant,
    ]);
  };

  const resolveKnockingParticipants = (ref, condition) => {
    knockingParticipants.forEach((participant) => {
      ref.current.executeCommand(
        "answerKnockingParticipant",
        participant?.id,
        condition(participant)
      );
      updateKnockingParticipants((participants) =>
        participants.filter((item) => item.id === participant.id)
      );
    });
  };

  const handleJitsiIFrameRef1 = (iframeRef) => {
    iframeRef.style.border = "10px solid cadetblue";
    iframeRef.style.background = "cadetblue";
    iframeRef.style.height = "25em";
    iframeRef.style.width = "75%";
  };

  const showDevices = async (ref) => {
    const videoInputs = [];
    // get all available video input
    const devices = await ref.current.getAvailableDevices();

    for (const [key, value] of Object.entries(devices)) {
      if (key == "videoInput") {
        value.forEach((vid) => {
          videoInputs.push(vid.label);
        });
      }
    }
    // log for debug
    updateLog((items) => [...items, JSON.stringify(videoInputs)]);

    let nextDevice = "";
    let devs = await ref.current.getCurrentDevices();

    for (const [key, value] of Object.entries(devs)) {
      if (key == "videoInput") {
        updateLog((items) => [...items, "found " + JSON.stringify(value)]);
        let devLabel = value.label;
        let idx = 0;
        videoInputs.forEach((vid) => {
          if (devLabel == vid) {
            let cur = idx + 1;
            if (cur >= videoInputs.length) {
              nextDevice = videoInputs[0];
            } else {
              nextDevice = videoInputs[cur];
              updateLog((items) => [...items, "next is " + nextDevice]);
            }
          }
          idx++;
        });
      }
    }
    updateLog((items) => [...items, "switching to " + nextDevice]);

    await ref.current.setVideoInputDevice(nextDevice);
  };

  const showAudioOutDevices = async (ref) => {
    const audioOutputs = [];
    // get all available audio output
    const devices = await ref.current.getAvailableDevices();

    for (const [key, value] of Object.entries(devices)) {
      if (key == "audioOutput") {
        value.forEach((vid) => {
          audioOutputs.push(vid.label);
        });
      }
    }
    // log for debug
    updateLog((items) => [...items, JSON.stringify(audioOutputs)]);

    let nextDevice = "";
    let devs = await ref.current.getCurrentDevices();

    for (const [key, value] of Object.entries(devs)) {
      if (key == "audioOutput") {
        updateLog((items) => [...items, "found " + JSON.stringify(value)]);
        let devLabel = value.label;
        let idx = 0;
        audioOutputs.forEach((vid) => {
          if (devLabel == vid) {
            let cur = idx + 1;
            if (cur >= audioOutputs.length) {
              nextDevice = audioOutputs[0];
            } else {
              nextDevice = audioOutputs[cur];
              updateLog((items) => [...items, "next is " + nextDevice]);
            }
          }
          idx++;
        });
      }
    }
    updateLog((items) => [...items, "switching to " + nextDevice]);

    await ref.current.setAudioOutputDevice(nextDevice);
  };

  const showAudioDevice = async (ref) => {
    const audioInputs = [];
    // get all available audio input
    const devices = await ref.current.getAvailableDevices();

    for (const [key, value] of Object.entries(devices)) {
      if (key == "audioInput") {
        value.forEach((vid) => {
          audioInputs.push(vid.label);
        });
      }
    }
    // log for debug
    updateLog((items) => [...items, JSON.stringify(audioInputs)]);

    let nextDevice = "";
    let devs = await ref.current.getCurrentDevices();

    for (const [key, value] of Object.entries(devs)) {
      if (key == "audioInput") {
        updateLog((items) => [...items, "found " + JSON.stringify(value)]);
        let devLabel = value.label;
        let idx = 0;
        audioInputs.forEach((vid) => {
          if (devLabel == vid) {
            let cur = idx + 1;
            if (cur >= audioInputs.length) {
              nextDevice = audioInputs[0];
            } else {
              nextDevice = audioInputs[cur];
              updateLog((items) => [...items, "next is " + nextDevice]);
            }
          }
          idx++;
        });
      }
    }
    updateLog((items) => [...items, "switching to " + nextDevice]);
    await ref.current.setAudioInputDevice(nextDevice);
  };

  const handleApiReady = async (apiObj, ref) => {
    ref.current = apiObj;
    await ref.current.addEventListeners({
      // Listening to events from the external API
      audioMuteStatusChanged: (payload) =>
        handleAudioStatusChange(payload, "audio"),
      videoMuteStatusChanged: (payload) =>
        handleAudioStatusChange(payload, "video"),
      raiseHandUpdated: printEventOutput,
      tileViewChanged: printEventOutput,
      chatUpdated: (payload) => handleChatUpdates(payload, ref),
      knockingParticipant: handleKnockingParticipant,
    });

    await ref.current.executeCommand("toggleFilmStrip");
  };

  // Multiple instances demo
  const showUsers = async (ref, which) => {
    try {
      const pinfo = await ref.current.getParticipantsInfo();
      updateLog((items) => [
        ...items,
        "participantes " + JSON.stringify(pinfo),
      ]);
      await ref.current.executeCommand("setTileView", false);
      await ref.current.setLargeVideoParticipant(pinfo[which].participantId);
    } catch (e) {
      console.error("Participant not found!");
      return;
    }
  };

  const makeTile = (ref) => {
    ref.current.executeCommand("setTileView", true);
  };

  const renderStream = (key) => (
    <div className={styles.streamButton}>
      <ButtonGroup className="m-auto">
        <Button
          variant="warning"
          title="Click to start streaming"
          onClick={() =>
            apiRef.current.executeCommand("startRecording", {
              mode: "stream",
              rtmpStreamKey: key,
              youtubeStreamKey: "",
            })
          }
        >
          Go live!
        </Button>
      </ButtonGroup>
    </div>
  );

  const toggleDevice = () => (
    <div className={styles.device}>
      <Button disabled variant="light">
        <AiFillSetting size={20} />
      </Button>
      <ButtonGroup vertical className="m-auto">
        <OverlayTrigger
          overlay={<Tooltip id="tooltip-disabled">Microphone Device</Tooltip>}
        >
          <Button
            title="Click to switch audio devices"
            onClick={() => showAudioDevice(apiRef)}
          >
            <RiMic2Line size={20} />
          </Button>
        </OverlayTrigger>
        <OverlayTrigger
          overlay={<Tooltip id="tooltip-disabled">Camera Device</Tooltip>}
        >
          <Button
            title="Click to switch video devices"
            onClick={() => showDevices(apiRef)}
          >
            <MdCameraswitch size={20} />
          </Button>
        </OverlayTrigger>
        <OverlayTrigger
          overlay={<Tooltip id="tooltip-disabled">Audio Device</Tooltip>}
        >
          <Button
            title="Click to switch audio devices"
            onClick={() => showAudioOutDevices(apiRef)}
          >
            <MdHeadset size={20} />
          </Button>
        </OverlayTrigger>
      </ButtonGroup>
    </div>
  );

  const toggleView = () => (
    <div className={styles.view}>
      <Button variant="light" disabled>
        <AiFillEye size={20} />
      </Button>
      <ButtonGroup vertical className="m-auto">
        <OverlayTrigger
          overlay={<Tooltip id="tooltip-disabled">Tile View</Tooltip>}
        >
          <Button
            variant="secondary"
            onClick={() => makeTile(apiRef)}
            title="Click to toggle tile view"
          >
            <HiViewGridAdd size={20} />
          </Button>
        </OverlayTrigger>
        <OverlayTrigger
          overlay={<Tooltip id="tooltip-disabled">First User</Tooltip>}
        >
          <Button onClick={() => showUsers(apiRef, 0)} variant="secondary">
            <BiUserPin size={20} />
          </Button>
        </OverlayTrigger>
        <OverlayTrigger
          overlay={<Tooltip id="tooltip-disabled">Second User</Tooltip>}
        >
          <Button onClick={() => showUsers(apiRef, 1)} variant="secondary">
            <FiUsers size={20} />
          </Button>
        </OverlayTrigger>
      </ButtonGroup>
    </div>
  );

  const toolButton = () => (
    <div className={styles.deviceButton}>
      <ButtonGroup className="m-auto">
        <Button
          variant="success"
          title="Click to toogle audio"
          onClick={() => {
            apiRef.current.executeCommand("toggleAudio");
            setMute(!mute);
          }}
        >
          {mute ? <BiMicrophoneOff /> : <BiMicrophone />}
        </Button>
        <DropdownButton variant="danger" as={ButtonGroup} title="End">
          <Dropdown.Item
            as="button"
            onClick={() => apiRef.current.executeCommand("hangup")}
          >
            Leave Meet
          </Dropdown.Item>
          <Dropdown.Item
            variant="danger"
            as="button"
            onClick={() => apiRef.current.stopRecording("stream")}
          >
            End for everyone!
          </Dropdown.Item>
        </DropdownButton>
        <Button color="#f5455c" onClick={handleChat}>
          <FaRocketchat />
        </Button>
      </ButtonGroup>
    </div>
  );

  const renderLog = () =>
    logItems.map((item, index) => (
      <div
        style={{
          fontFamily: "monospace",
          padding: "5px",
        }}
        key={index}
      >
        {item}
      </div>
    ));

  const renderSpinner = () => (
    <div
      style={{
        fontFamily: "sans-serif",
        textAlign: "center",
      }}
    >
      Loading..
    </div>
  );

  return (
    <>
      {rtmp ? renderStream(rtmp) : rtmpSrc && renderStream(rtmpSrc)}
      <div className={styles.jitsiContainer}>
        {toggleDevice()}

        <JitsiMeeting
          domain="meet.jit.si"
          roomName={room}
          spinner={renderSpinner}
          onApiReady={(externalApi) => handleApiReady(externalApi, apiRef)}
          getIFrameRef={handleJitsiIFrameRef1}
          configOverwrite={{
            startWithAudioMuted: true,
            disableModeratorIndicator: true,
            startScreenSharing: false,
            enableEmailInStats: false,
            toolbarButtons: [],
            enableWelcomePage: false,
            prejoinPageEnabled: false,
            startWithVideoMuted: false,
            liveStreamingEnabled: true,
            disableSelfView: false,
            disableSelfViewSettings: true,
            disableShortcuts: true,
            disable1On1Mode: true,
            p2p: {
              enabled: false,
            },
          }}
          interfaceConfigOverwrite={{
            DISABLE_JOIN_LEAVE_NOTIFICATIONS: true,
            FILM_STRIP_MAX_HEIGHT: 0,
            TILE_VIEW_MAX_COLUMNS: 0,
            VIDEO_QUALITY_LABEL_DISABLED: true,
          }}
          userInfo={{
            displayName: disName,
          }}
        />
        {toggleView()}
      </div>
      {toolButton()}
      <div className={styles.log}>{renderLog()}</div>
    </>
  );
}
Example #20
Source File: IssueCard.js    From portfolio 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></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"
              ></span>
              <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 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="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">
                {/* <p className="additions-files">
									<strong>{pullRequest["additions"]} + </strong>
								</p>
								<p className="deletions-files">
									<strong>{pullRequest["deletions"]} - </strong>
								</p> */}
                {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 #21
Source File: table.jsx    From CovidIndiaStats with MIT License 4 votes vote down vote up
render() {
    const {
      isLoaded,
      data,
      sortConfirmed,
      sortActive,
      sortRecovered,
      sortDeceased,
      sortTested,
      sortVaccinated,
      sortOrder,
      percentageToggleActive,
      allStatesData,
      isDataLoading,
      statewise,
    } = this.state;

    const getActiveNumber = (total) => {
      const confirmed = total?.confirmed;
      const recovered = total?.recovered;
      const deceased = total?.deceased;

      return confirmed - recovered - deceased;
    };

    const totalVaccinated = localStorage.getItem("lastTotalVaccinated");

    const dailyConfirmed = [];
    data.map((item) => dailyConfirmed.push(Number(item.dailyconfirmed)));

    const dailyActive = [];
    data.map((item) =>
      dailyActive.push(
        Number(item.dailyconfirmed) -
          Number(item.dailyrecovered) -
          Number(item.dailydeceased)
      )
    );

    const dailyRecovered = [];
    data.map((item) => dailyRecovered.push(Number(item.dailyrecovered)));

    const dailyDeceased = [];
    data.map((item) => dailyDeceased.push(Number(item.dailydeceased)));

    allStatesData.map((t) => {
      let found = false;
      let stateNotes = "";
      statewise.map((s) => {
        if (t.code === s.statecode && !found) {
          stateNotes = s.statenotes;
          found = true;
        }

        t["stateNotes"] = stateNotes;
      });
    });

    if (sortConfirmed) {
      allStatesData.sort(function (x, y) {
        return sortOrder
          ? Number(y?.data?.total?.confirmed) -
              Number(x?.data?.total?.confirmed)
          : Number(x?.data?.total?.confirmed) -
              Number(y?.data?.total?.confirmed);
      });
    }
    if (sortActive) {
      allStatesData.sort(function (x, y) {
        return !sortOrder
          ? Number(getActiveNumber(y?.data?.total)) -
              Number(getActiveNumber(x?.data?.total))
          : Number(getActiveNumber(x?.data?.total)) -
              Number(getActiveNumber(y?.data?.total));
      });
    }
    if (sortRecovered) {
      allStatesData.sort(function (x, y) {
        return !sortOrder
          ? Number(y?.data?.total?.recovered) -
              Number(x?.data?.total?.recovered)
          : Number(x?.data?.total?.recovered) -
              Number(y?.data?.total?.recovered);
      });
    }
    if (sortDeceased) {
      allStatesData.sort(function (x, y) {
        return !sortOrder
          ? Number(y?.data?.total?.deceased) - Number(x?.data?.total?.deceased)
          : Number(x?.data?.total?.deceased) - Number(y?.data?.total?.deceased);
      });
    }

    if (sortTested) {
      allStatesData.sort(function (x, y) {
        return !sortOrder
          ? Number(y?.data?.total?.tested) - Number(x?.data?.total?.tested)
          : Number(x?.data?.total?.tested) - Number(y?.data?.total?.tested);
      });
    }

    if (sortVaccinated) {
      allStatesData.sort(function (x, y) {
        return !sortOrder
          ? Number(y?.data?.total?.vaccinated) -
              Number(x?.data?.total?.vaccinated)
          : Number(x?.data?.total?.vaccinated) -
              Number(y?.data?.total?.vaccinated);
      });
    }

    const sparklinedata = [];
    const sparklineconfirmed = [];
    const sparklineactive = [];
    const sparklinerecovered = [];
    const sparklinedeceased = [];

    data.slice(data.length - 20, data.length).map((item) => {
      sparklinedata.push({
        confirmed: Number(item.dailyconfirmed),
        active:
          Number(item.dailyconfirmed) -
          Number(item.dailyrecovered) -
          Number(item.dailydeceased),
        recovered: Number(item.dailyrecovered),
        deceased: Number(item.dailydeceased),
        date: item.date,
      });
      sparklineconfirmed.push(Number(item.dailyconfirmed));
      sparklineactive.push(
        Number(item.dailyconfirmed) -
          Number(item.dailyrecovered) -
          Number(item.dailydeceased)
      );
      sparklinerecovered.push(Number(item.dailyrecovered));
      sparklinedeceased.push(Number(item.dailydeceased));
    });

    if (isLoaded && !isDataLoading) {
      return (
        <div className="statsTable">
          <div
            className="topStats fadeInUp"
            style={{
              marginBottom: "8px",
              animationDelay: "0.5s",
              borderRadius: "6px",
            }}
          >
            <table
              className="table table-sm table-borderless"
              style={{ marginBottom: "-1px" }}
            >
              <thead>
                <tr>
                  <th
                    className="span delta graphWidth"
                    style={{
                      color: "rgb(66, 179, 244)",
                      background: "rgba(66, 179, 244, 0.125)",
                    }}
                  >
                    CONFIRMED
                  </th>
                  <th
                    className="delta span graphWidth"
                    style={{
                      background: "rgba(255, 7, 58, 0.125)",
                      color: "rgb(255, 80, 100)",
                    }}
                  >
                    ACTIVE
                  </th>
                  <th
                    className="text-success delta span graphWidth"
                    style={{ background: "rgba(88, 189, 88, 0.2)" }}
                  >
                    RECOVERED
                  </th>
                  <th
                    className="text-secondary delta span graphWidth"
                    style={{
                      background: "rgba(92, 87, 86, 0.25)",
                      fontWeight: 600,
                    }}
                  >
                    DECEASED
                  </th>
                </tr>
              </thead>
              {allStatesData.map(
                (item) =>
                  item.code === "TT" && (
                    <tbody className="tbody">
                      <td>
                        <h6
                          className="delta"
                          style={{ fontSize: 12, color: "rgb(66, 179, 244)" }}
                        >
                          {Number(item?.data?.delta?.confirmed) > 0 ? (
                            ""
                          ) : (
                            <Icon.Meh
                              size={12}
                              strokeWidth={3}
                              fill="rgba(23, 162, 184, 0.2)"
                              style={{ verticalAlign: "-0.2rem" }}
                            />
                          )}

                          {Number(item?.data?.delta?.confirmed) > 0
                            ? "+" + commaSeperated(item?.data?.delta?.confirmed)
                            : ""}
                        </h6>
                        <h6
                          style={{
                            textAlign: "center",
                            color: "rgb(66, 179, 244)",
                          }}
                        >
                          <CountUp
                            start={0}
                            end={Number(item?.data?.total?.confirmed)}
                            duration={2}
                            separator=","
                            formattingFn={(number) => commaSeperated(number)}
                          />
                        </h6>

                        <section
                          style={{
                            justifyContent: "center",
                            paddingBottom: "-10px",
                          }}
                        >
                          <MiniSparkline
                            sparklinedata={sparklinedata}
                            datakey={0}
                            type={sparklineconfirmed}
                            fill="#42b3f4"
                            stroke="rgba(66, 179, 244, 0.7)"
                          />
                        </section>
                      </td>

                      <td>
                        <h6
                          className="delta"
                          style={{ color: "#ff446a", fontSize: 12 }}
                        >
                          <Icon.Heart
                            size={12}
                            strokeWidth={3}
                            fill="#ff446a"
                            style={{ verticalAlign: "-0.2rem" }}
                          />
                        </h6>
                        <h6 style={{ color: "#ff446a", textAlign: "center" }}>
                          {!percentageToggleActive ? (
                            <CountUp
                              start={0}
                              end={Number(getActiveNumber(item?.data?.total))}
                              duration={2}
                              separator=","
                              formattingFn={(number) => commaSeperated(number)}
                            />
                          ) : (
                            (
                              (getActiveNumber(item?.data?.total) /
                                Number(item?.data?.total?.confirmed)) *
                              100
                            ).toFixed(1) + "%"
                          )}
                        </h6>
                        <section
                          style={{
                            justifyContent: "center",
                            paddingBottom: "-10px",
                          }}
                        >
                          <MiniSparkline
                            sparklinedata={sparklinedata}
                            datakey={1}
                            type={sparklineactive}
                            fill="#ff446a"
                            stroke="rgba(255, 68, 106, 0.7)"
                          />
                        </section>
                      </td>

                      <td>
                        <h5
                          className="text-success delta"
                          style={{ fontSize: 12 }}
                        >
                          {Number(item?.data?.delta?.recovered) > 0 ? (
                            ""
                          ) : (
                            <Icon.Smile
                              size={12}
                              strokeWidth={3}
                              fill="rgba(23, 162, 184, 0.2)"
                              style={{ verticalAlign: "-0.2rem" }}
                            />
                          )}
                          {Number(item?.data?.delta?.recovered) > 0
                            ? "+" + commaSeperated(item?.data?.delta?.recovered)
                            : ""}
                        </h5>
                        <h6
                          className="text-success"
                          style={{ textAlign: "center" }}
                        >
                          {!percentageToggleActive ? (
                            <CountUp
                              start={0}
                              end={Number(item?.data?.total?.recovered)}
                              duration={2}
                              separator=","
                              formattingFn={(number) => commaSeperated(number)}
                            />
                          ) : (
                            (
                              (Number(item?.data?.total?.recovered) /
                                Number(item?.data?.total?.confirmed)) *
                              100
                            ).toFixed(1) + "%"
                          )}
                        </h6>
                        <section
                          style={{
                            justifyContent: "center",
                            paddingBottom: "-10px",
                          }}
                        >
                          <MiniSparkline
                            sparklinedata={sparklinedata}
                            datakey={2}
                            type={sparklinerecovered}
                            fill="#58bd58"
                            stroke="rgba(88, 189, 88, 0.7)"
                          />
                        </section>
                      </td>

                      <td>
                        <h6
                          className="text-secondary delta"
                          style={{ fontSize: 12 }}
                        >
                          {Number(item?.data?.delta?.deceased) > 0 ? (
                            ""
                          ) : (
                            <Icon.Meh
                              size={12}
                              strokeWidth={3}
                              fill="rgba(40, 167, 69, 0.2)"
                              style={{ verticalAlign: "-0.2rem" }}
                            />
                          )}
                          {Number(item?.data?.delta?.deceased)
                            ? "+" + commaSeperated(item?.data?.delta?.deceased)
                            : ""}
                        </h6>
                        <h6
                          className="colorChange"
                          style={{ textAlign: "center" }}
                        >
                          {!percentageToggleActive ? (
                            <CountUp
                              start={0}
                              end={Number(item?.data?.total?.deceased)}
                              duration={2}
                              separator=","
                              formattingFn={(number) => commaSeperated(number)}
                            />
                          ) : (
                            (
                              (Number(item?.data?.total?.deceased) /
                                Number(item?.data?.total?.confirmed)) *
                              100
                            ).toFixed(1) + "%"
                          )}
                        </h6>
                        <section
                          style={{
                            justifyContent: "center",
                            paddingBottom: "-10px",
                          }}
                        >
                          <MiniSparkline
                            sparklinedata={sparklinedata}
                            datakey={3}
                            type={sparklinedeceased}
                            fill="#5c5756"
                            stroke="rgba(92, 87, 86, 0.7)"
                          />
                        </section>
                      </td>
                    </tbody>
                  )
              )}
            </table>
            {(totalVaccinated || "") && totalVaccinated !== "-" && (
              <div className="vaccinatedPeople">
                <h6>
                  <img src={shield} className="vaccineShield" />{" "}
                  {commaSeperated(totalVaccinated)} Vaccine doses administered
                </h6>
              </div>
            )}
          </div>

          <div className="w-100"></div>
          <div className="row">
            <Updates />
          </div>
          <div className="w-100"></div>
          <div
            className="indiaStateWiseHead fadeInUp"
            style={{
              textAlign: "center",
              animationDelay: "1.8s",
              marginTop: "-15px",
            }}
          >
            <h3>INDIA - STATEWISE </h3>
            <div style={{ alignItems: "right" }}>
              <div
                className="home-toggle float-left"
                style={{ marginTop: "2.5px" }}
              >
                <Switch
                  className="react-switch"
                  onChange={this.onPercentageToggle}
                  onClick={ReactGa.event({
                    category: "Switch %age",
                    action: "Switch %age clicked",
                  })}
                  checked={percentageToggleActive}
                  onColor="#6b7de4"
                  onHandleColor="#3e4da3"
                  handleDiameter={11}
                  uncheckedIcon={false}
                  checkedIcon={false}
                  boxShadow="0 0 5px rgba(0,0,0,0.2)"
                  activeBoxShadow="0 0 2px rgba(0,0,0,0.25)"
                  height={16}
                  width={35}
                ></Switch>
                <span
                  style={{
                    color: "#3e4da3",
                    fontWeight: "bold",
                    verticalAlign: "0.3rem",
                  }}
                >
                  &nbsp;%
                </span>
              </div>
            </div>
          </div>

          <div
            className="supportUs fadeInUp"
            style={{ animationDelay: "1.9s" }}
          >
            <a
              target="_blank"
              rel="noopener noreferrer"
              className="telegramLink"
              href="https://www.buymeacoffee.com/covidindiastats"
            >
              Covid India Stats needs your help
            </a>
            <a
              target="_blank"
              rel="noopener noreferrer"
              className="supportBtn"
              href="https://www.buymeacoffee.com/covidindiastats"
            >
              <FaHandHoldingHeart className="telegramIcon" />
            </a>
          </div>

          <div className="statewiseTable table-responsive">
            <table
              className="table table-sm fadeInUp table-borderless"
              style={{ animationDelay: "1.9s", fontFamily: "notosans" }}
            >
              <thead className="thead-dark">
                <tr>
                  <th className="th">State/UT</th>
                  <th
                    className="th"
                    onClick={() =>
                      this.setState({
                        sortConfirmed: true,
                        sortActive: false,
                        sortRecovered: false,
                        sortDeceased: false,
                        sortTested: false,
                        sortVaccinated: false,
                        sortOrder: !sortOrder,
                      })
                    }
                    style={{ color: "rgb(66, 179, 244)" }}
                  >
                    Confirmed
                    {sortConfirmed && (
                      <SortRoundedIcon
                        fontSize="inherit"
                        style={{
                          color: "#ffc107",
                          verticalAlign: "-0.1rem",
                        }}
                      />
                    )}
                  </th>
                  <th
                    className="th"
                    style={{ color: "#ff446a" }}
                    onClick={() =>
                      this.setState({
                        sortConfirmed: false,
                        sortActive: true,
                        sortRecovered: false,
                        sortDeceased: false,
                        sortTested: false,
                        sortVaccinated: false,
                        sortOrder: !sortOrder,
                      })
                    }
                  >
                    Active
                    {sortActive && (
                      <SortRoundedIcon
                        fontSize="inherit"
                        style={{
                          color: "#ffc107",
                          verticalAlign: "-0.1rem",
                        }}
                      />
                    )}
                  </th>
                  <th
                    className="th text-success"
                    onClick={() =>
                      this.setState({
                        sortConfirmed: false,
                        sortActive: false,
                        sortRecovered: true,
                        sortDeceased: false,
                        sortTested: false,
                        sortVaccinated: false,
                        sortOrder: !sortOrder,
                      })
                    }
                  >
                    Recovered
                    {sortRecovered && (
                      <SortRoundedIcon
                        fontSize="inherit"
                        style={{
                          color: "#ffc107",
                          verticalAlign: "-0.1rem",
                        }}
                      />
                    )}
                  </th>
                  <th
                    className="th text-secondary"
                    onClick={() =>
                      this.setState({
                        sortConfirmed: false,
                        sortActive: false,
                        sortRecovered: false,
                        sortDeceased: true,
                        sortTested: false,
                        sortVaccinated: false,
                        sortOrder: !sortOrder,
                      })
                    }
                  >
                    Deaths
                    {sortDeceased && (
                      <SortRoundedIcon
                        fontSize="inherit"
                        style={{
                          color: "#ffc107",
                          verticalAlign: "-0.1rem",
                        }}
                      />
                    )}
                  </th>
                  <th
                    className="th"
                    style={{ color: "#5969c2" }}
                    onClick={() =>
                      this.setState({
                        sortConfirmed: false,
                        sortActive: false,
                        sortRecovered: false,
                        sortDeceased: false,
                        sortTested: true,
                        sortVaccinated: false,
                        sortOrder: !sortOrder,
                      })
                    }
                  >
                    Tested
                    {sortTested && (
                      <SortRoundedIcon
                        fontSize="inherit"
                        style={{
                          color: "#ffc107",
                          verticalAlign: "-0.1rem",
                        }}
                      />
                    )}
                  </th>
                  <th
                    className="th"
                    style={{ color: "#f4c430" }}
                    onClick={() =>
                      this.setState({
                        sortConfirmed: false,
                        sortActive: false,
                        sortRecovered: false,
                        sortDeceased: false,
                        sortTested: false,
                        sortVaccinated: true,
                        sortOrder: !sortOrder,
                      })
                    }
                  >
                    Vaccinated
                    {sortVaccinated && (
                      <SortRoundedIcon
                        fontSize="inherit"
                        style={{
                          color: "#ffc107",
                          verticalAlign: "-0.1rem",
                        }}
                      />
                    )}
                  </th>
                </tr>
              </thead>
              <tbody className="tbody">
                {allStatesData.map(
                  (item, i) =>
                    item.code !== "TT" && (
                      <tr
                        className="tr"
                        key={item.code}
                        style={{
                          background:
                            i % 2 === 0 ? "rgba(63, 63, 95, 0.2)" : "",
                        }}
                      >
                        <td className="align-middle">
                          <div className="td-md-left">
                            <Link to={`/${item.code}`}>
                              <h6>{item.name}</h6>
                            </Link>
                            <h6>
                              {item.stateNotes ? (
                                  <OverlayTrigger
                                    key="right"
                                    placement="right"
                                    overlay={
                                      <Tooltip id="tooltip-right">
                                        {parse(item.stateNotes)}
                                      </Tooltip>
                                    }
                                  >
                                    <span>
                                      <InfoOutlined
                                        color="inherit"
                                        fontSize="inherit"
                                        className="infoIcon"
                                      />
                                    </span>
                                  </OverlayTrigger>
                                ) : (
                                  ""
                                )}
                            </h6>
                          </div>
                        </td>
                        <td
                          className="delta td-md align-middle"
                          style={{ textAlign: "right" }}
                        >
                          <h6 className="arrowup">
                            <DeltaArrow
                              deltaType={item?.data?.delta?.confirmed}
                              color={"#42b3f4"}
                            />
                            <DeltaValue
                              deltaType={item?.data?.delta?.confirmed}
                              color={"#42b3f4"}
                            />
                            <h6 className="delta td-md align-middle">
                              {commaSeperated(item?.data?.total?.confirmed)}
                            </h6>
                          </h6>
                        </td>
                        <td className="delta td-md align-middle">
                          <h6 className="arrowup">
                            <h6
                              className="delta td-md align-middle"
                              style={{ textAlign: "right" }}
                            >
                              {percentageToggleActive
                                ? (
                                    (getActiveNumber(item?.data?.total) * 100) /
                                    item?.data?.total?.confirmed
                                  ).toFixed(1) + "%"
                                : commaSeperated(
                                    getActiveNumber(item?.data?.total)
                                  )}
                            </h6>
                          </h6>
                        </td>
                        <td
                          className="delta td-md align-middle"
                          style={{ textAlign: "right" }}
                        >
                          <h6 className="arrowup">
                            <DeltaArrow
                              deltaType={item?.data?.delta?.recovered}
                              color={"#28a745"}
                            />
                            <DeltaValue
                              deltaType={item?.data?.delta?.recovered}
                              color={"#28a745"}
                            />
                            <h6 className="delta td-md align-middle">
                              {percentageToggleActive
                                ? (
                                    (item?.data?.total?.recovered * 100) /
                                    item?.data?.total?.confirmed
                                  ).toFixed(1) + "%"
                                : commaSeperated(item?.data?.total?.recovered)}
                            </h6>
                          </h6>
                        </td>
                        <td
                          className="delta td-md align-middle"
                          style={{ textAlign: "right" }}
                        >
                          <h6 className="arrowup">
                            <DeltaArrow
                              deltaType={item?.data?.delta?.deceased}
                              color={"#6c757d"}
                            />
                            <DeltaValue
                              deltaType={item?.data?.delta?.deceased}
                              color={"#6c757d"}
                            />
                            <h6 className="delta td-md align-middle">
                              {percentageToggleActive
                                ? (
                                    (item?.data?.total?.deceased * 100) /
                                    item?.data?.total?.confirmed
                                  ).toFixed(1) + "%"
                                : commaSeperated(item?.data?.total?.deceased)}
                            </h6>
                          </h6>
                        </td>
                        <td
                          className="delta td-md align-middle"
                          style={{ textAlign: "right" }}
                        >
                          <h6 className="arrowup">
                            <DeltaArrow
                              deltaType={item?.data?.delta?.tested}
                              color={"#5969c2"}
                            />
                            <DeltaValue
                              deltaType={item?.data?.delta?.tested}
                              color={"#5969c2"}
                            />
                            <h6 className="delta td-md align-middle">
                              {commaSeperated(item?.data?.total?.tested)}
                            </h6>
                          </h6>
                        </td>
                        <td
                          className="delta td-md align-middle"
                          style={{ textAlign: "right" }}
                        >
                          <h6 className="arrowup">
                            <DeltaArrow
                              deltaType={item?.data?.delta?.vaccinated}
                              color={"#f4c32f"}
                            />
                            <DeltaValue
                              deltaType={item?.data?.delta?.vaccinated}
                              color={"#f4c32f"}
                            />
                            <h6 className="delta td-md align-middle">
                              {commaSeperated(item?.data?.total?.vaccinated)}
                            </h6>
                          </h6>
                        </td>
                      </tr>
                    )
                )}
                {allStatesData.map(
                  (item, i) =>
                    item.code === "TT" && (
                      <tr
                        className="tr"
                        key={item.code}
                        style={{
                          background:
                            i % 2 === 0 ? "rgba(63, 63, 95, 0.2)" : "",
                        }}
                      >
                        <td className="align-middle">
                          <div className="td-md-left">
                            <h6 style={{paddingTop: "7.5px"}}>{item.name}</h6>
                          </div>
                        </td>
                        <td
                          className="delta td-md align-middle"
                          style={{ textAlign: "right" }}
                        >
                          <h6 className="arrowup">
                            <DeltaArrow
                              deltaType={item?.data?.delta?.confirmed}
                              color={"#42b3f4"}
                            />
                            <DeltaValue
                              deltaType={item?.data?.delta?.confirmed}
                              color={"#42b3f4"}
                            />
                            <h6 className="delta td-md align-middle">
                              {commaSeperated(item?.data?.total?.confirmed)}
                            </h6>
                          </h6>
                        </td>
                        <td className="delta td-md align-middle">
                          <h6 className="arrowup">
                            <h6
                              className="delta td-md align-middle"
                              style={{ textAlign: "right" }}
                            >
                              {percentageToggleActive
                                ? (
                                    (getActiveNumber(item?.data?.total) * 100) /
                                    item?.data?.total?.confirmed
                                  ).toFixed(1) + "%"
                                : commaSeperated(
                                    getActiveNumber(item?.data?.total)
                                  )}
                            </h6>
                          </h6>
                        </td>
                        <td
                          className="delta td-md align-middle"
                          style={{ textAlign: "right" }}
                        >
                          <h6 className="arrowup">
                            <DeltaArrow
                              deltaType={item?.data?.delta?.recovered}
                              color={"#28a745"}
                            />
                            <DeltaValue
                              deltaType={item?.data?.delta?.recovered}
                              color={"#28a745"}
                            />
                            <h6 className="delta td-md align-middle">
                              {percentageToggleActive
                                ? (
                                    (item?.data?.total?.recovered * 100) /
                                    item?.data?.total?.confirmed
                                  ).toFixed(1) + "%"
                                : commaSeperated(item?.data?.total?.recovered)}
                            </h6>
                          </h6>
                        </td>
                        <td
                          className="delta td-md align-middle"
                          style={{ textAlign: "right" }}
                        >
                          <h6 className="arrowup">
                            <DeltaArrow
                              deltaType={item?.data?.delta?.deceased}
                              color={"#6c757d"}
                            />
                            <DeltaValue
                              deltaType={item?.data?.delta?.deceased}
                              color={"#6c757d"}
                            />
                            <h6 className="delta td-md align-middle">
                              {percentageToggleActive
                                ? (
                                    (item?.data?.total?.deceased * 100) /
                                    item?.data?.total?.confirmed
                                  ).toFixed(1) + "%"
                                : commaSeperated(item?.data?.total?.deceased)}
                            </h6>
                          </h6>
                        </td>
                        <td
                          className="delta td-md align-middle"
                          style={{ textAlign: "right" }}
                        >
                          <h6 className="arrowup">
                            <DeltaArrow
                              deltaType={item?.data?.delta?.tested}
                              color={"#5969c2"}
                            />
                            <DeltaValue
                              deltaType={item?.data?.delta?.tested}
                              color={"#5969c2"}
                            />
                            <h6 className="delta td-md align-middle">
                              {commaSeperated(item?.data?.total?.tested)}
                            </h6>
                          </h6>
                        </td>
                        <td
                          className="delta td-md align-middle"
                          style={{ textAlign: "right" }}
                        >
                          <h6 className="arrowup">
                            <DeltaArrow
                              deltaType={item?.data?.delta?.vaccinated}
                              color={"#f4c32f"}
                            />
                            <DeltaValue
                              deltaType={item?.data?.delta?.vaccinated}
                              color={"#f4c32f"}
                            />
                            <h6 className="delta td-md align-middle">
                              {commaSeperated(item?.data?.total?.vaccinated)}
                            </h6>
                          </h6>
                        </td>
                      </tr>
                    )
                )}
              </tbody>
            </table>
          </div>
        </div>
      );
    } else {
      return null;
    }
  }
Example #22
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>
    )
}
Example #23
Source File: KeypadOverlay.jsx    From makerverse with GNU General Public License v3.0 4 votes vote down vote up
keypadTooltip = () => {
    const styles = {
        tooltip: {
            fontFamily: 'Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif',
            padding: 5
        },
        container: {
            padding: 5
        },
        axisDirection: {
            marginRight: 10
        },
        divider: {
            borderTop: '1px solid #ccc',
            marginTop: 5,
            paddingTop: 5
        },
        kbd: {
            border: '1px solid #aaa',
            padding: '1px 4px',
            fontFamily: 'sans-serif',
            whiteSpace: 'nowrap'
        },
        icon: {
            minWidth: 10,
            textAlign: 'center'
        }
    };

    return (
        <Tooltip
            id="widget-axes-keypad-tooltip"
            style={styles.tooltip}
        >
            <div style={styles.container}>
                <div className="row no-gutters text-left">
                    <div className="col-xs-12">
                        <span style={styles.axisDirection}>X+</span>
                        <kbd style={styles.kbd}>
                            <i className="fa fa-angle-right" style={styles.icon} />
                        </kbd>
                        <Space width="8" />
                        {i18n._('Right')}
                    </div>
                    <div className="col-xs-12">
                        <span style={styles.axisDirection}>X-</span>
                        <kbd style={styles.kbd}>
                            <i className="fa fa-angle-left" style={styles.icon} />
                        </kbd>
                        <Space width="8" />
                        {i18n._('Left')}
                    </div>
                    <div className="col-xs-12">
                        <span style={styles.axisDirection}>Y+</span>
                        <kbd style={styles.kbd}>
                            <i className="fa fa-angle-up" style={styles.icon} />
                        </kbd>
                        <Space width="8" />
                        {i18n._('Up')}
                    </div>
                    <div className="col-xs-12">
                        <span style={styles.axisDirection}>Y-</span>
                        <kbd style={styles.kbd}>
                            <i className="fa fa-angle-down" style={styles.icon} />
                        </kbd>
                        <Space width="8" />
                        {i18n._('Down')}
                    </div>
                    <div className="col-xs-12">
                        <span style={styles.axisDirection}>Z+</span>
                        <kbd style={styles.kbd}>
                            <i className="fa fa-long-arrow-up" style={styles.icon} />
                        </kbd>
                        <Space width="8" />
                        {i18n._('Page Up')}
                    </div>
                    <div className="col-xs-12">
                        <span style={styles.axisDirection}>Z-</span>
                        <kbd style={styles.kbd}>
                            <i className="fa fa-long-arrow-down" style={styles.icon} />
                        </kbd>
                        <Space width="8" />
                        {i18n._('Page Down')}
                    </div>
                    <div className="col-xs-12">
                        <span style={styles.axisDirection}>A+</span>
                        <kbd style={styles.kbd}>
                            {' ] '}
                        </kbd>
                        <Space width="8" />
                        {i18n._('Right Square Bracket')}
                    </div>
                    <div className="col-xs-12">
                        <span style={styles.axisDirection}>A-</span>
                        <kbd style={styles.kbd}>
                            {' [ '}
                        </kbd>
                        <Space width="8" />
                        {i18n._('Left Square Bracket')}
                    </div>
                </div>
                <div className="row no-gutters">
                    <div style={styles.divider} />
                </div>
                <div className="row no-gutters">
                    <div className="col-xs-12">
                        <div className="table-form">
                            <div className="table-form-row table-form-row-dense">
                                <div className="table-form-col table-form-col-label">{i18n._('0.1x Move')}</div>
                                <div className="table-form-col">
                                    <kbd style={styles.kbd}>{i18n._('Alt')}</kbd>
                                </div>
                            </div>
                            <div className="table-form-row table-form-row-dense">
                                <div className="table-form-col table-form-col-label">{i18n._('10x Move')}</div>
                                <div className="table-form-col">
                                    <kbd style={styles.kbd}>{i18n._('⇧ Shift')}</kbd>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </Tooltip>
    );
}
Example #24
Source File: Step1.js    From katanapools with GNU General Public License v2.0 4 votes vote down vote up
render() {

    const {baseReserveWeight, tokenArrayList, poolType, poolSymbolDefault, detailsVisible} = this.state;
    const { isError, pool: {relayConverterStatus}} = this.props;
    const {poolName, poolSymbol, poolDecimals} = this.state;

    const self = this;
    let isCreationStepPending = false;
    if (relayConverterStatus && relayConverterStatus.type === 'pending') {
      isCreationStepPending = true;
    }
    let relaySelectButton = '';
    let ercSelectButton = '';

    if (poolType === 'relay') {
      relaySelectButton = 'button-active';
      ercSelectButton = '';
    } else {
      ercSelectButton = 'button-active';
    }

    let tokenArrayListDisplay = tokenArrayList.map(function(item, idx){
      return <TokenFormRow key={`token-form-row-${idx}`} address={item.address}
      symbol={item.symbol} name={item.name}
      weight={item.weight ? item.weight : 0} idx={idx}
      weightChanged={self.weightChanged} addressChanged={self.addressChanged} getTokenDetail={self.getTokenNameAndSymbol}
      removeTokenRow={self.removeTokenRow} poolType={poolType}/>;
    });

    let relayTokenRow = <span/>;
    if (poolType === 'relay') {
      relayTokenRow = (
      <Row>
        <Col lg={8}>
        <Form.Group controlId="formBasicEmail">
         <Form.Label>Select network hub token.
           <OverlayTrigger
              placement="top"
              delay={{ show: 250, hide: 400 }}
              overlay={renderNetworkHubTooltip}>
              <FontAwesomeIcon icon={faQuestionCircle} className="info-tooltip-btn"/>
            </OverlayTrigger>
            </Form.Label>
          <Form.Control as="select" onChange={this.baseReserveChanged} selected={this.baseReserveSelected}>
            <option>BNT</option>
            <option>USDB</option>
          </Form.Control>
        </Form.Group>
        </Col>
        <Col lg={4} className="no-pad-col">
          <div className="slidecontainer">
          <Row>
            <Col lg={8}>
            Token Reserve Ratio
           <OverlayTrigger
              placement="right"
              delay={{ show: 250, hide: 400 }}
              overlay={reserveRatioTooltip}>
              <FontAwesomeIcon icon={faQuestionCircle} className="info-tooltip-btn"/>
            </OverlayTrigger>
            </Col>
            <Col lg={4}>
            <Form.Control type="number" value={baseReserveWeight} onChange={this.baseWeightValueChanged} className="amount-row"/>
            </Col>
            </Row>
            <input type="range" min="0" max="100" value={baseReserveWeight} className="slider"
            id="myRange" onChange={this.baseWeightValueChanged}/>
          </div>
        </Col>
        </Row>
        )
    }

function reserveRatioTooltip(props) {
   return <Tooltip {...props}>
    <div>
    Reserve ratio defines the ratio between the total value of the reserves & the market cap of the pool token.
    </div>
    <div>
    While most pools have a network hub token and a pool token kept in a 50/50 reserve ratio,
    </div>
    <div>
     You can also create pools with an array of reserves in any arbitrary reserve ratio.
    </div>
    <div>
    Provided the sum of all reserves is less than or equal to 100.
    </div>

    </Tooltip>;
}

function renderNameTooltip(props) {
  return <Tooltip {...props} className="wizard-tooltip">
    <div className="wizard-tooltip-text">
    <div>Pool name should be descriptive of the pool reserves to allow for easy searching and indexing.</div>
    <div>For instance, a pool name like Link Bat Smart Relay Token could refer to a pool with LINK, BAT, BNT in a 33/33/33 reserve ratio.</div>
    </div>
    </Tooltip>;
}


function renderSymbolTooltip(props) {
  return <Tooltip {...props} className="wizard-tooltip">
    <div className="wizard-tooltip-text">
    <div>Pool symbol should contain the symbols of pool reserves to allow for easy searching and indexing.</div>
    <div>For instance, a pool symbol like LINKBATBNT could refer to a pool with LINK, BAT, BNT in a 33/33/33 reserve ratio.</div>
    </div>
    </Tooltip>;
}

function renderDecimalTooltip(props) {
  return <Tooltip {...props} className="wizard-tooltip">
    <div className="wizard-tooltip-text">
    <div>Decimal precision of pool token.</div>
    <div>The standard is 18 for most ERC20 tokens.</div>
    <div>If you are unsure of what value to enter leave it at 18.</div>
    </div>
    </Tooltip>;
}

function renderNetworkHubTooltip(props) {
  return <Tooltip {...props}>
    <div>A network hub token is a token which allows interconversion of tokens between pools.</div>
    <div>For instance any token XXX can be converted to token YYY provided pool XXXBNT and YYYBNT exists.</div>
    <div>This is done by following a conversion path as XXX -> XXXBNT -> BNT -> YYYBNT -> YYY</div>
    </Tooltip>;
}
function renderFeeTooltip(props) {
  return <Tooltip {...props}>
    <div>Low fee will encourage more conversions whereas a higher fee will encourage more liquidity to the pool.</div>
    <div>Most pools follow a standard 0.1% conversion fees.</div>
    </Tooltip>;
}

function renderConvertibleTokenTooltip(props) {
  return <Tooltip {...props}>
    <div>Convertible tokens are ERC20 tokens </div>
    <div>which can be converted to other tokens in the pool</div>
    <div>or to other tokens via the intermediary network hub token.</div>
    <div>(provided pool contains at least 1 network hub token)</div>
    </Tooltip>;
}

    let isFormInComplete = true;
    if (poolName.length > 0 && poolSymbol.length > 0) {
      isFormInComplete = false;
    }

    let isSubmitBtnDisabled = isCreationStepPending || isFormInComplete;
    let numTransactions = tokenArrayList.length + 3;
    let transactionDetails = <span/>;
    if (detailsVisible) {
      transactionDetails = (
        <div>
          <div>1 transction for Pool token contract deployment.</div>
          <div>1 transaction for Pool converter deployment.</div>
          <div>1 transaction for setting pool conversion fees.</div>
          <div>{tokenArrayList.length} transactions for adding connectors for each of the ERC20 tokens</div>
        </div>
        )
    }
    return (
        <div className="create-pool-form-container">

        <div className="create-form-container">
          <Container className="add-pool-converter-form">
          <Row className="add-pool-form-header">
          <Col lg={6}>
          <div className="header">
            Pool Reserve Ratio<div className="help-link-text">
            <a href="https://katanapools.com/help/reserveratio" target="_blank">What is reserve ratio</a></div>
          </div>
          </Col>
          <Col lg={6} className="btn-toggle-container no-pad-col">
            <ButtonGroup aria-label="Basic example">
              <Button variant="primary" onClick={()=>this.togglePooltype("relay")} className={`toggle-btn ${relaySelectButton}`}>Require network hub token</Button>
              <Button variant="secondary" onClick={()=>this.togglePooltype("any")} className={`toggle-btn ${ercSelectButton}`}>Any ERC20 token</Button>
            </ButtonGroup>
          </Col>
        </Row>
        </Container>
        <Container className="add-pool-converter-form">
        <Form onSubmit={this.onSubmit}>
        {relayTokenRow}
        <div className="sub-form-header">
            Add convertible tokens
            <OverlayTrigger
              placement="top"
              delay={{ show: 250, hide: 400 }}
              overlay={renderConvertibleTokenTooltip}>
              <FontAwesomeIcon icon={faQuestionCircle} className="info-tooltip-btn"/>
            </OverlayTrigger>
        </div>
        {tokenArrayListDisplay}
        <Button onClick={this.addReserveTokenRow} className="row-add-btn">Add another reserve token <FontAwesomeIcon icon={faPlus} /></Button>
          <Row className="add-pool-form-header pool-detail-header">
            <Col lg={6}>
            <div className="header">
              Pool Details
            </div>
            </Col>
          </Row>
        <Row>
          <Col lg={6}>
          <Form.Group controlId="formBasicEmail">
            <Form.Label>
              Pool Name
              <OverlayTrigger
                placement="top"
                delay={{ show: 250, hide: 400 }}
                overlay={renderNameTooltip}>
                <FontAwesomeIcon icon={faQuestionCircle} className="info-tooltip-btn"/>
              </OverlayTrigger>
            </Form.Label>
            <Form.Control type="text" placeholder="name" onChange={this.formNameChanged} value={poolName}/>
            <Form.Text className="text-muted" >
              Enter the pool name eg. XXX Smart Relay Token
            </Form.Text>
          </Form.Group>
          </Col>
          <Col lg={6}>
          <Form.Group controlId="formBasicPassword">
            <Form.Label>Pool Symbol
                <OverlayTrigger
                placement="top"
                delay={{ show: 250, hide: 400 }}
                overlay={renderSymbolTooltip}>
                <FontAwesomeIcon icon={faQuestionCircle} className="info-tooltip-btn"/>
              </OverlayTrigger>
              </Form.Label>
            <Form.Control type="text" placeholder="symbol" value={poolSymbol} onChange={this.formSymbolChanged} defaultValue={poolSymbolDefault}/>
            <Form.Text className="text-muted" >
              Enter the pool symbol eg. XXXYYY for pool with XXX and YYY.
            </Form.Text>
          </Form.Group>
          </Col>
        </Row>
        <Row>
        <Col lg={6} xs={12}>
        <Form.Group controlId="formBasicPassword">
          <Form.Label>Pool Decimals
            <OverlayTrigger
              placement="top"
              delay={{ show: 250, hide: 400 }}
              overlay={renderDecimalTooltip}>
              <FontAwesomeIcon icon={faQuestionCircle} className="info-tooltip-btn"/>
            </OverlayTrigger>
          </Form.Label>
          <Form.Control type="text" placeholder="decimals" value={poolDecimals} onChange={this.formDecimalsChanged}/>
        </Form.Group>
        </Col>
        </Row>
        <Row>
        <Col lg={4}>
        {isError ?

        <Button className="pool-wizard-submit-btn" type="submit" variant="primary">
          Resume
        </Button>
        :
        <Button variant="primary" disabled={isSubmitBtnDisabled} type="submit" className="pool-wizard-submit-btn">
          Next
        </Button>
        }
        </Col>
        <Col lg={8}>

        </Col>
        </Row>
      </Form>
        </Container>
        </div>
      </div>
    )
  }
Example #25
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 #26
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>
    );
  }