react-share#FacebookIcon JavaScript Examples

The following examples show how to use react-share#FacebookIcon. 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: share.js    From blog with Apache License 2.0 8 votes vote down vote up
ShareButton = (props) => {
  const { location, siteMetadata, post } = props;
  const twitter = [ siteMetadata.social.twitter ];
  const url = siteMetadata.siteUrl + location.pathname;

  const iconSize = 30;
  const iconStyle = {
    paddingRight: "0.3em",
    marginBottom: "0.2em"
  };

  return (
    <>
      <TwitterShareButton url={url} quote={url} title={post.title} hashtags={post.tags} related={twitter} style={iconStyle}>
        <TwitterIcon size={iconSize}/>
      </TwitterShareButton>

      <LinkedinShareButton url={url} title={post.title} quote={url} source={siteMetadata.siteUrl} style={iconStyle}>
        <LinkedinIcon size={iconSize}/>
      </LinkedinShareButton>

      <FacebookShareButton url={url} quote={url} style={iconStyle}>
        <FacebookIcon size={iconSize}/>
      </FacebookShareButton>

      <RedditShareButton url={url} quote={url} title={post.title} style={iconStyle}>
        <RedditIcon size={iconSize}/>
      </RedditShareButton>

      <EmailShareButton url={url} quote={url} subject={post.title} style={iconStyle}>
        <EmailIcon size={iconSize}/>
      </EmailShareButton>
    </>
  );
}
Example #2
Source File: request_utils.js    From covidsos with MIT License 7 votes vote down vote up
getShareButtons = (accept_link = 'https://wa.me/918618948661/', helpText) => {
  return (
      <>
          <span className='share-icon'>
                <WhatsappShareButton
                    url={accept_link}
                    title={helpText}>
                  <WhatsappIcon size={32} round/>
                </WhatsappShareButton>
              </span>
        <span className='share-icon'>
                <FacebookShareButton
                    url={accept_link}
                    quote={helpText}>
                  <FacebookIcon size={32} round/>
                </FacebookShareButton>
              </span>
        <span className=''>
                <TwitterShareButton
                    url={accept_link}
                    title={helpText}>
                  <TwitterIcon size={32} round/>
                </TwitterShareButton>
              </span>
      </>
  );
}
Example #3
Source File: SocialMediaButtons.js    From covid-19 with MIT License 6 votes vote down vote up
SocialMediaButtons = (props) => {
  const location = useLocation();

  let url;
  if (props.url) {
    url = props.url;
  } else {
    url = 'https://covid-19.direct' + location.pathname;
  }

  const bgStyle = {};
  if (props.backgroundColor) {
    bgStyle.fill = props.backgroundColor;
  }

  return (
    <div className={props.className}>
      {[
        [FacebookShareButton, FacebookIcon],
        [TwitterShareButton, TwitterIcon],
        [RedditShareButton, RedditIcon],
        [WhatsappShareButton, WhatsappIcon],
        [EmailShareButton, EmailIcon],
      ].map(([Button, Icon], i) => (
        <Button className={props.buttonClassName} url={url} quote={QUOTE} key={i}>
          <Icon
              size={props.size || '1em'}
              round={true}
              bgStyle={bgStyle}
              iconFillColor={props.iconColor}
          />
        </Button>
      ))}
    </div>
  );
}
Example #4
Source File: ShareButtons.jsx    From koronawirus.lol with GNU Affero General Public License v3.0 6 votes vote down vote up
ShareButtons = ({ }) => (
    <>
        <ShareButtonContainer>
            <FacebookShareButton url={url}>
                <FacebookIcon size={32} round />
            </FacebookShareButton>
            <button className="react-share__ShareButton" style={{ background: 'white', border: 0, margin: 0, paddingLeft: 0 }} onClick={() => {
                window.location.href = `fb-messenger://share?link=${url}`
            }}>
                <FacebookMessengerIcon size={32} round />
            </button>
            <TwitterShareButton url={url}>
                <TwitterIcon size={32} round />
            </TwitterShareButton>
            <TelegramShareButton url={url}>
                <TelegramIcon size={32} round />
            </TelegramShareButton>
            <LinkedinShareButton url={url}>
                <LinkedinIcon size={32} round />
            </LinkedinShareButton>
        </ShareButtonContainer>
    </>
)
Example #5
Source File: social-share.js    From taskforce-fe-components with Mozilla Public License 2.0 6 votes vote down vote up
SocialsShare = ({ currentPage }) => {
  return (
    <div className="__social-share-container">
      <span>Distribuie pe</span>

      <FacebookShareButton url={currentPage}>
        <FacebookIcon round={true} size={30}></FacebookIcon>
      </FacebookShareButton>
      <LinkedinShareButton url={currentPage}>
        <LinkedinIcon round={true} size={30}></LinkedinIcon>
      </LinkedinShareButton>
      <TwitterShareButton url={currentPage}>
        <TwitterIcon round={true} size={30}></TwitterIcon>
      </TwitterShareButton>
    </div>
  );
}
Example #6
Source File: Share.js    From agility-website-gatsby with MIT License 6 votes vote down vote up
render() {

		if (typeof window === 'undefined') {
			return <div className="share"></div>
		}

		const item = this.props.item.customFields;

		return (
            <div className="share">
                <label>{item.shareLabel}</label>
                {item.facebook &&
                <FacebookShareButton quote={document.title} url={window.location.href} className="SocialMediaShareButton">
                    <FacebookIcon size={36} round />
                </FacebookShareButton>
                }
                {item.twitter &&
                <TwitterShareButton quote={document.title}  url={window.location.href} className="SocialMediaShareButton">
                    <TwitterIcon size={36} round />
                </TwitterShareButton>
                }
                {item.linkedIn &&
                <LinkedinShareButton quote={document.title}  url={window.location.href} className="SocialMediaShareButton">
                    <LinkedinIcon size={36} round />
                </LinkedinShareButton>
                }
            </div>

        );
	}
Example #7
Source File: TokenShareModal.js    From paras-landing with GNU General Public License v3.0 6 votes vote down vote up
Share = ({ show, onClose, tokenData }) => {
	const ShareList = [
		{
			name: (
				<FacebookShareButton url={window.location.href} className="flex text-white">
					<FacebookIcon size={24} round />
					<p className="ml-3">Facebook</p>
				</FacebookShareButton>
			),
			onClick: () => {},
		},
		{
			name: (
				<TwitterShareButton
					title={`Checkout ${tokenData.metadata.title} from collection ${tokenData.metadata.collection} on @ParasHQ\n\n#paras #cryptoart #digitalart #tradingcards`}
					url={window.location.href}
					className="flex text-white"
				>
					<TwitterIcon size={24} round />
					<p className="ml-3">Twitter</p>
				</TwitterShareButton>
			),
			onClick: () => {},
		},
		{
			name: (
				<TelegramShareButton url={window.location.href} className="flex text-white">
					<TelegramIcon size={24} round />
					<p className="ml-3">Telegram</p>
				</TelegramShareButton>
			),
			onClick: () => {},
		},
	]

	return <ListModal show={show} onClose={onClose} list={ShareList} />
}
Example #8
Source File: ShareComponent.js    From paras-landing with GNU General Public License v3.0 6 votes vote down vote up
ShareComponent = ({ title, shareUrl }) => {
	const { localeLn } = useIntl()
	return (
		<div className="flex items-center space-x-2 justify-between">
			<div className="text-white text-sm opacity-80 pr-4">{localeLn('ShareNow')}</div>
			<div className="flex space-x-3">
				<FacebookShareButton
					url={shareUrl}
					quote={title}
					className="Demo__some-network__share-button"
				>
					<FacebookIcon size={24} round />
				</FacebookShareButton>

				<TwitterShareButton
					url={shareUrl}
					title={title}
					className="Demo__some-network__share-button"
				>
					<TwitterIcon size={24} round />
				</TwitterShareButton>
				<TelegramShareButton
					url={shareUrl}
					title={title}
					className="Demo__some-network__share-button"
				>
					<TelegramIcon size={24} round />
				</TelegramShareButton>
			</div>
		</div>
	)
}
Example #9
Source File: ShareButtons.jsx    From Corona-tracker with MIT License 6 votes vote down vote up
ShareButtons = () => {
  const url = 'https://coronatracker.squarespace.com';

  return (
    <>
      <FacebookShareButton url={url}>
        <FacebookIcon size={32} round />
      </FacebookShareButton>
      <LinkedinShareButton url={url}>
        <LinkedinIcon size={32} round />
      </LinkedinShareButton>
      <TwitterShareButton url={url}>
        <TwitterIcon size={32} round />
      </TwitterShareButton>
      <RedditShareButton url={url}>
        <RedditIcon size={32} round />
      </RedditShareButton>
      <TelegramShareButton url={url}>
        <TelegramIcon size={32} round />
      </TelegramShareButton>
    </>
  );
}
Example #10
Source File: index.js    From gatsby-blog-mdx with MIT License 6 votes vote down vote up
ShareButtons = ({ location }) => {
  return (
    <div className="share-buttons-wrap">
      {config.shareButtons.email && (
        <EmailShareButton url={location}>
          <EmailIcon round size={32} />
        </EmailShareButton>
      )}
      {config.shareButtons.facebook && (
        <FacebookShareButton url={location}>
          <FacebookIcon round size={32} />
        </FacebookShareButton>
      )}
      {config.shareButtons.twitter && (
        <TwitterShareButton url={location}>
          <TwitterIcon round size={32} />
        </TwitterShareButton>
      )}
      {config.shareButtons.reddit && (
        <RedditShareButton url={location}>
          <RedditIcon round size={32} />
        </RedditShareButton>
      )}
      {config.shareButtons.linkedIn && (
        <LinkedinShareButton url={location}>
          <LinkedinIcon round size={32} />
        </LinkedinShareButton>
      )}
    </div>
  )
}
Example #11
Source File: Dashboard.js    From shopping-cart-fe with MIT License 5 votes vote down vote up
Dashboard = () => {
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(creators.getCurrentUser());
  }, [dispatch]);
  const user = useSelector((state) => state.user.user);
  const url = `${window.location.origin.toString()}/store/${
    user && user.storeName && user.storeName.toLowerCase().split(' ').join('-')
  }-${user && user._id}`;
  const storeLogo = user.imageUrl ? user.imageUrl : NoLogo;
  const copied = () => {
    message.success('url copied successfully');
  };
  return (
    <div className='mainDiv' data-testid='dashboardMainDiv'>
      <div className='dashboardHeader'>
        <div className='welcomeHeader'>
          Welcome, <br />
          <span className='name'>
            {user.ownerName ? user.ownerName : 'Seller'}!
          </span>
        </div>
        <div className='dashboardLogo'>
          <img src={storeLogo} alt='Store Logo' />
        </div>
      </div>
      <div className='storeUrl'>
        <p id='storeUrl' style={{ marginBottom: '1.3rem' }}>
          {user && url}
        </p>
        <CopyToClipboard text={url}>
          <span>
            <Button ghost onClick={copied}>
              Copy URL
            </Button>
          </span>
        </CopyToClipboard>
        <div className='share'>
          <FacebookShareButton url={user && url}>
            <FacebookIcon size={32} round />
          </FacebookShareButton>
          <TwitterShareButton url={user && url}>
            <TwitterIcon size={32} round />
          </TwitterShareButton>
          <LinkedinShareButton url={user && url}>
            <LinkedinIcon size={32} round />
          </LinkedinShareButton>
          <WhatsappShareButton url={user && url}>
            <WhatsappIcon size={32} round />
          </WhatsappShareButton>
          <EmailShareButton url={user && url}>
            <EmailIcon size={32} round />
          </EmailShareButton>
        </div>
      </div>
      <div className='dashDiv'>
        <Content storeId={user._id} currency={user.currency} />
      </div>
    </div>
  );
}
Example #12
Source File: ShareModal.js    From mern-social-media with MIT License 5 votes vote down vote up
ShareModal = ({ url, theme, setIsShare }) => {
  return (
    <div className="share_modal">
      <div className="share_modal-container">
        <div className="share_modal-header">
          <span>Share to...</span>
          <span onClick={() => setIsShare(false)}>&times;</span>
        </div>
        <div
          className=" share_modal-body"
          style={{ filter: theme ? "invert(1)" : "invert(0)" }}
        >
          <FacebookShareButton url={url}>
            <FacebookIcon round={true} size={32} />
          </FacebookShareButton>

          <TwitterShareButton url={url}>
            <TwitterIcon round={true} size={32} />
          </TwitterShareButton>

          <EmailShareButton url={url}>
            <EmailIcon round={true} size={32} />
          </EmailShareButton>

          <TelegramShareButton url={url}>
            <TelegramIcon round={true} size={32} />
          </TelegramShareButton>

          <WhatsappShareButton url={url}>
            <WhatsappIcon round={true} size={32} />
          </WhatsappShareButton>

          <PinterestShareButton url={url}>
            <PinterestIcon round={true} size={32} />
          </PinterestShareButton>

          <RedditShareButton url={url}>
            <RedditIcon round={true} size={32} />
          </RedditShareButton>

          <LinkedinShareButton url={url}>
            <LineIcon round={true} size={32} />
          </LinkedinShareButton>
        </div>
      </div>
    </div>
  );
}
Example #13
Source File: Person.js    From covid19-brazil-api with MIT License 5 votes vote down vote up
Person = ({ person }) => (
  <Card className="person">
    <div className="person">
      <a href="https://github.com/devarthurribeiro">
        <img src={person.img} alt="Arthur Ribeiro" />
      </a>
      <h3>{person.name}</h3>
      <span>{person.role}</span>
      <p>
        {person.description}
      </p>
      <div className="flex-center">
        <a href={`https://wa.me/${person.whatsapp}`}>
          <WhatsappIcon
            size={40}
            round
          />
        </a>
        <a href={`https://fb.com/${person.facebook}`}>
          <FacebookIcon size={40} round />
        </a>
        <a href={`https://twitter.com/${person.twitter}`}>
          <TwitterIcon size={40} round />
        </a>
      </div>
    </div>
    <style jsx>
      {`
      .person h3, p {
        margin: 8px
      }

      .person span {
        margin-bottom: 6px;
        color: #818181;
      }

      .person img {
        width: 160px;
        heigth: auto;
        border-radius: 50%;
      }

      .person {
        display: flex;
        flex-direction: column;
        align-items: center;
      }
  `}
    </style>
  </Card>
)
Example #14
Source File: sharebuttons.js    From staticwebsitehosting with MIT License 5 votes vote down vote up
buttonConfigs = {
  twitter: { Button: TwitterShareButton, Icon: TwitterIcon },
  facebook: { Button: FacebookShareButton, Icon: FacebookIcon },
  reddit: { Button: RedditShareButton, Icon: RedditIcon },
}
Example #15
Source File: ShareModal.js    From gophie-web with MIT License 4 votes vote down vote up
ShareModal = (props) => {
  const [btnCopyText, setBtnCopyText] = useState(copy.defaultText);
  const [isUrlCopied, setUrlCopied] = useState(false);

  const copyURLToClipboard = () => {
    setUrlCopied(true);
  };

  useEffect(() => {
    if (isUrlCopied === true) {
      setBtnCopyText(copy.copiedText);

      setTimeout(() => {
        setBtnCopyText(copy.defaultText);
        setUrlCopied(false);
      }, 2000);
    }
  }, [isUrlCopied])

  const { movie } = props;
  let url = "";
  // console.log(movie.referral_id);
  if (window.location.hostname === "localhost") {
    url = `localhost:${window.location.port}/shared/${movie.referral_id}`;
  } else {
    url = `https://gophie.cam/shared/${movie.referral_id}`;
  }

  return (
    <>
      <Modal
        show={props.display}
        onHide={props.onHide}
        className="share-card"
        centered
        aria-labelledby="contained-modal-title-vcenter"
      >
        <Modal.Header closeButton>
          <Modal.Title>Share Movie</Modal.Title>
        </Modal.Header>
        <Modal.Body className="show-grid mt-5">
          <Container>
            <Row className="justify-content-between">
              <FacebookShareButton
                url={url}
                quote={movie.name}
                className="mb-2 mr-3"
              >
                <FacebookIcon size={50} round={true} />
              </FacebookShareButton>

              <TwitterShareButton
                url={url}
                title={movie.name}
                className="mb-2 mr-3"
              >
                <TwitterIcon size={50} round={true} />
              </TwitterShareButton>

              <WhatsappShareButton
                url={url}
                title={movie.name}
                className="mb-2 mr-3"
              >
                <WhatsappIcon size={50} round={true} />
              </WhatsappShareButton>

              <TelegramShareButton
                url={url}
                title={movie.name}
                className="mb-2 mr-3"
              >
                <TelegramIcon size={50} round={true} />
              </TelegramShareButton>

              <RedditShareButton url={url} title={movie.name} className="mb-2">
                <RedditIcon size={50} round={true} />
              </RedditShareButton>
            </Row>
            <Row className="justify-content-center mt-3 eoErth">
              <CopyToClipboard text={url}
                onCopy={() => copyURLToClipboard(true)}>
                <button
                  className={isUrlCopied ? copy.copiedClass : copy.defaultClass}
                  onClick={copyURLToClipboard}
                  type="button"
                >
                  {btnCopyText}
                </button>
              </CopyToClipboard>
            </Row>
          </Container>
        </Modal.Body>
      </Modal>
    </>
  );
}
Example #16
Source File: ClubEvent.jsx    From club-connect with GNU General Public License v3.0 4 votes vote down vote up
ShareModal = (props) => {
  const { onRequestClose, shareModalIsOpen, shareData } = props;

  Modal.setAppElement('#__next');

  return (
    <Modal
      className={clubEventStyles.ShareModal}
      isOpen={shareModalIsOpen}
      onRequestClose={onRequestClose}
      shouldCloseOnOverlayClick={true}
      closeTimeoutMS={200}
    >
      <h2>Share This Event</h2>
      <input type="text" value={shareData.eventUrl} readOnly />
      <div className={clubEventStyles.sharePlatforms}>
        <FacebookShareButton
          url={shareData.eventUrl}
          quote={shareData.shareDescription}
          hashtag={'#bccompsciclub'}
          disabled
        >
          <FacebookIcon size={32} round />
        </FacebookShareButton>

        <TwitterShareButton
          url={shareData.eventUrl}
          title={shareData.shareDescription}
          hashtags={['bccompsciclub']}
        >
          <TwitterIcon size={32} round />
        </TwitterShareButton>

        <LinkedinShareButton
          url={shareData.eventUrl}
          title={shareData.shareTitle}
          summary={shareData.shareDescription}
        >
          <LinkedinIcon size={32} round />
        </LinkedinShareButton>

        <FacebookMessengerShareButton url={shareData.eventUrl} disabled>
          <FacebookMessengerIcon size={32} round />
        </FacebookMessengerShareButton>

        <WhatsappShareButton
          url={shareData.eventUrl}
          title={shareData.shareDescription}
        >
          <WhatsappIcon size={32} round />
        </WhatsappShareButton>

        <TelegramShareButton
          url={shareData.eventUrl}
          title={shareData.shareDescription}
        >
          <TelegramIcon size={32} round />
        </TelegramShareButton>

        <LineShareButton
          url={shareData.eventUrl}
          title={shareData.shareDescription}
        >
          <LineIcon size={32} round />
        </LineShareButton>

        <EmailShareButton
          url={shareData.eventUrl}
          subject={shareData.shareTitle}
          body={`${shareData.shareDescription}\n\n`}
        >
          <EmailIcon size={32} round />
        </EmailShareButton>
      </div>
      <button className={clubEventStyles.closeButton} onClick={onRequestClose}>
        Close
      </button>
      <p>
        Sharing to Facebook and Facebook Messenger are currently unavailable.
        Sorry about that!
      </p>
    </Modal>
  );
}
Example #17
Source File: RefPage.js    From bonded-stablecoin-ui with MIT License 4 votes vote down vote up
RefPage = ({ setWalletModalVisibility }) => {
  const { activeWallet } = useSelector(state => state.settings);
  const [loading, setLoading] = useState(true);
  const { t } = useTranslation();
  const [info, setInfo] = useState({});
  const [scale, setScale] = useState(0);

  const currentYear = moment().year();
  const countDays = moment(`${currentYear + 1}-01-01`, "YYYY-MM-DD").diff(`${currentYear}-01-01`, "days");
  const countWeeks = countDays / 7;

  const refUrl = `https://${config.TESTNET ? "testnet." : ""}ostable.org/?r=${activeWallet}`;
  const appInfo = {
    url: refUrl,
    title: "Obyte bonded stablecoins: earn 16% interest in USD, 11% in BTC",
    hashtag: "#obyte"
  }
  const columns = [
    {
      title: t("ref.address", "Address"),
      dataIndex: "address",
      key: "address",
      ellipsis: {
        showTitle: true,
      },
    },
    {
      title: t("ref.usd_balance", "USD balance"),
      dataIndex: "usd_balance",
      key: "usd_balance",
      render: (value) => {
        return Number(value).toFixed(2) || <span>—</span>
      }
    }
  ];

  useEffect(() => {
    (async () => {
      let error = false;
      const infoData = await axios.get(`${config.REFERRAL_URL}/referrals/${activeWallet}`).catch((e) => {
        error = true;
        console.log("e", e);
      });

      if (!infoData || ("error" in infoData)) return setLoading(false);

      if (infoData) {
        const info = { ...infoData.data.data };
        const total = info && info.referrals && info.referrals.reduce((acc, value) => acc + value.usd_balance, 0);
        info.total = Number(total).toFixed(2);
        
        const distributionInfoData = await axios.get(`${config.REFERRAL_URL}/distributions/next`).catch((e) => {
          error = true;
          console.log("e", e);
        });
        
        if (!distributionInfoData || ("error" in distributionInfoData)) return setLoading(false)
       
        const {data: {data : {total_unscaled_rewards, total_rewards}}} = distributionInfoData;

        const scale = (total_rewards / total_unscaled_rewards) || 0;

        setScale(scale);
        
        if(!error){
          setLoading(false);
          setInfo(info);
        }
        
      }

    })();
  }, [activeWallet]);

  const pReferrerRewards = +Number(10 * scale).toFixed(3);
  const pReferrerRewardsAPY = +Number(10 * scale * countWeeks).toPrecision(4);
  const pReferralRewards = +Number(5 * scale).toFixed(3);

  return <>
    <Helmet title="Bonded stablecoins - Referral program" />
    <Title level={1} style={{ marginBottom: 30 }}>{t("ref.title", "Referral program")}</Title>
    <Row style={{ fontSize: 18 }}>
      <Col xl={{ offset: 1, span: 8 }} sm={{ span: 24 }} xs={{ span: 24 }}>
        <img className={styles.image} src={RefImage} alt="Referral program" />
        {activeWallet && info && !loading && <Paragraph className={styles.myInfo}>
          {info.distribution_date && <div>{t("ref.next_payment", "The next payment is on ")} {info.distribution_date}.</div>}
          {"my_info" in info && <div>{t("ref.expected_reward", "Your expected reward is")} {Number(info.my_info.usd_reward).toFixed(2)} IUSD.
          {info.referrer_address && t("ref.you_were_referred", "You were referred by {{referrer_address}} and this includes a reward for your own balance {{balance}}.", { balance: info.my_info.usd_balance, referrer_address: info.my_info.referrer_address })}</div>}
        </Paragraph>}
      </Col>
      <Col xl={{ offset: 1, span: 14 }} sm={{ span: 24 }} xs={{ span: 24 }}>
        {activeWallet ? <div>
          {t("ref.your_link", "This is your referral link")}:
          <div>
            <div className={styles.urlWrap}>
              <Text copyable={{ onCopy: () => message.success(t("ref.clipboard_link", "Your link was copied to the clipboard")) }}>{refUrl}</Text>
            </div>
          </div>
        </div> : <div className={styles.urlWrap_empty}><Trans i18nKey="ref.no_auth">To get a referral link, <span onClick={setWalletModalVisibility} className={styles.addWallet}>add your wallet address</span></Trans></div>}
        <div className={styles.info}>
          <Paragraph>
            {t("ref.your_link_desc", "Use it in your blogs, tweets, posts, newsletters, public profiles, videos, etc and earn referral rewards for bringing new holders into Bonded Stablecoins.")}
          </Paragraph>
          {activeWallet && <Paragraph>
            <Space style={{ justifyContent: "center", width: "100%" }}>
              <FacebookShareButton {...appInfo}>
                <FacebookIcon size={36} round={true} />
              </FacebookShareButton>
              <VKShareButton {...appInfo}>
                <VKIcon size={36} round={true} />
              </VKShareButton>
              <TwitterShareButton {...appInfo}>
                <TwitterIcon size={36} round={true} />
              </TwitterShareButton>
              <TelegramShareButton {...appInfo}>
                <TelegramIcon size={36} round={true} />
              </TelegramShareButton>
            </Space>
          </Paragraph>}
          <Trans i18nKey="ref.info" pReferrerRewards={pReferrerRewards} pReferrerRewardsAPY={pReferrerRewardsAPY} pReferralRewards={pReferralRewards}>
            <Paragraph>
              The referral rewards are paid in IUSD every Sunday and are proportional to dollar balances of the referred
              users in all tokens (stablecoins, interest tokens, growth tokens) issued on this website, as well as other
              tokens based on them: shares in <a target="_blank" rel="noopener" href="https://oswap.io/">oswap</a> liquidity pools and shares in arbitrage bots.
              The larger the total balances at the end of the weekly period, the larger the reward. Your weekly reward increases if the referred users accumulate more, decreases if they redeem or sell their tokens.
            </Paragraph>
            <Paragraph>
              The current weekly reward is <b>{{pReferrerRewards}}% of the balances of all referred users</b> at the end of the week (<b>{{pReferrerRewardsAPY}}% per year</b>).
            </Paragraph>
            <Paragraph>
              Your referrals also get rewarded for buying tokens through your link — they are expected to get <b>{{pReferralRewards}}% of their balances</b> every week.
            </Paragraph>
            <Paragraph>
              The total amount paid to all referrers and referred users is <b>$3,000 weekly</b> and is distributed in proportion to the referrals balances.
            </Paragraph>
          </Trans>
          {activeWallet && <Paragraph>
            {t("ref.title_list", "Here is the list of your referrals and their current balances")}:
          </Paragraph>}
        </div>
      </Col>
    </Row>

    {activeWallet && <Table
      loading={loading}
      columns={columns}
      footer={() => info && info.total && Number(info.total) !== 0 && <div style={{ display: "flex", justifyContent: "flex-end" }} ><b>{t("ref.total", "Total")}: {info.total} IUSD</b></div>}
      dataSource={((info && info.referrals) || []).map((r) => ({ ...r, key: r.address }))}
      locale={{
        emptyText: t("ref.empty", "no referrals yet"),
      }}
      pagination={{ pageSize: 20, hideOnSinglePage: true }}
    />}

  </>
}
Example #18
Source File: index.js    From covid-trials-dashboard with MIT License 4 votes vote down vote up
MapContainer = ({ pins }) => {
  const theme = useTheme()
  const isBigEnough = useMediaQuery(theme.breakpoints.up('sm'))
  const { t } = useTranslation()
  const [email, setEmail] = useState()
  return (
    <Wrapper>
      <div style={{ paddingBottom: '2rem' }}>
        <MaxWidth>
          <Typography
            variant='h1'
            style={{
              fontSize: '2em',
              marginTop: '1.3rem',
              marginLeft: '0.5rem',
            }}
            gutterBottom
          >
            {t('title')}
          </Typography>
          {isBigEnough && (
            <Typography
              style={{
                fontSize: '1.3em',
                marginBottom: '1.3rem',
                marginLeft: '0.5rem',
              }}
              gutterBottom
              variant='h2'
            >
              {t('subtitle')}
            </Typography>
          )}
          <MapDiv>
            <Map pins={pins} />
          </MapDiv>
          <div
            style={{
              display: 'flex',
              flexDirection: 'row-reverse',
            }}
          >
            <FacebookShareButton
              style={{ marginRight: '0.5rem' }}
              url={'https://www.coviddash.org'}
              quote={'Volunteer for COVID-19 Vaccination trials near you'}
              onClick={() => {
                ReactGA.event({
                  category: 'volunteer',
                  action: 'Clicked share via facebook',
                })
              }}
            >
              <FacebookIcon size={30} round={true} />
            </FacebookShareButton>
            <TwitterShareButton
              style={{ marginRight: '0.5rem' }}
              url={'https://www.coviddash.org'}
              title={'Volunteer for COVID-19 Vaccination trials near you'}
              hashtags={['COVID19', 'Volunteer', 'Coronavirus', 'Vaccines']}
              onClick={() => {
                ReactGA.event({
                  category: 'volunteer',
                  action: 'Clicked share via twitter',
                })
              }}
            >
              <TwitterIcon size={30} round={true} />
            </TwitterShareButton>
            <PinterestShareButton
              url={'https://www.coviddash.org'}
              style={{ marginRight: '0.5rem' }}
              media={'https://coviddash.org/CovidTrialVolunteer.png'}
              className='mr-2'
              onClick={() => {
                ReactGA.event({
                  category: 'volunteer',
                  action: 'Clicked share via pinterest',
                })
              }}
            >
              <PinterestIcon size={30} round={true} />
            </PinterestShareButton>
            <EmailShareButton
              style={{ marginRight: '0.5rem' }}
              subject={
                'I thought you might be interested in volunteering for COVID-19 Vaccination trials'
              }
              separator=' '
              body={
                'I thought you may be interested in volunteering to help save lives. Covidtrialdash.org helps you find vaccination trials near you.'
              }
              url={'https://www.covidtrialdash.org'}
              className='mr-2'
              openShareDialogOnClick={true}
              onClick={() => {
                ReactGA.event({
                  category: 'volunteer',
                  action: 'Clicked share via email',
                })
              }}
            >
              <EmailIcon size={30} round={true} />
            </EmailShareButton>
            <WhatsappShareButton
              style={{ marginRight: '0.5rem' }}
              url={'https://www.coviddash.org'}
              title='Volunteer for COVID Vaccination trials in your area.'
              className='mr-2'
              onClick={() => {
                ReactGA.event({
                  category: 'volunteer',
                  action: 'Clicked share via whatsapp',
                })
              }}
            >
              <WhatsappIcon size={30} round={true} />
            </WhatsappShareButton>
          </div>
          <div
            style={{
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
            }}
          >
            <div style={{ fontSize: '17px' }}>
              If you can&apos;t find a study now, or you&apos;d like to stay up
              to date, sign up for our email list!
            </div>
            <MailchimpSubscribe
              url={process.env.REACT_APP_MAILCHIMP_URL}
              render={({ subscribe, status, message }) => (
                <div style={{ marginTop: '1rem', width: '280px' }}>
                  <form
                    onSubmit={event => {
                      event.preventDefault()
                      subscribe({ EMAIL: email })
                    }}
                  >
                    <TextField
                      id='subscribe'
                      label='Your email'
                      variant='outlined'
                      style={{ width: '100%' }}
                      onChange={e => setEmail(e.target.value)}
                    />
                    <div style={{ marginTop: '1rem' }}>
                      <Button
                        type='submit'
                        fullWidth
                        variant='contained'
                        color='primary'
                      >
                        Subscribe
                      </Button>
                    </div>
                  </form>
                  {status === 'sending' && (
                    <p style={{ color: 'blue', textAlign: 'center' }}>
                      Sending...
                    </p>
                  )}
                  {status === 'error' && (
                    <p
                      style={{ color: 'red', textAlign: 'center' }}
                      dangerouslySetInnerHTML={{ __html: message }}
                    />
                  )}
                  {status === 'success' && (
                    <p style={{ color: 'green', textAlign: 'center' }}>
                      Subscribed!
                    </p>
                  )}
                </div>
              )}
            />
            <div style={{ fontSize: '17px', paddingTop: '2rem' }}>
              For immediate assistance, call us at +1 (224) 444-0082
            </div>
          </div>
        </MaxWidth>
      </div>
      <HomeSections />
    </Wrapper>
  )
}
Example #19
Source File: ShareQueue.jsx    From simplQ-frontend with GNU General Public License v3.0 4 votes vote down vote up
ShareQueue = ({ queueName, tourTag }) => {
  const [open, setOpen] = useState(false);
  const anchorRef = useRef(null);

  const handleToggle = () => {
    setOpen((prevOpen) => !prevOpen);
  };

  const handleClose = (event) => {
    if (anchorRef.current && anchorRef.current.contains(event.target)) {
      return;
    }
    setOpen(false);
  };

  const link = `${window.location.origin}/j/${queueName}`;
  const quote = `Hi! Use ${link} to join my queue and get live updates.`;

  return (
    <div className={styles['share']}>
      <ButtonGroup
        reactour-selector={tourTag}
        variant="contained"
        className={styles['button-background']}
        ref={anchorRef}
        aria-label="split button"
      >
        <CopyButton {...{ link }} />
        <Button
          className={styles['button-background']}
          color="primary"
          size="small"
          onClick={handleToggle}
        >
          <ArrowDropDownIcon />
        </Button>
      </ButtonGroup>
      <Popper
        className={styles['popper']}
        open={open}
        anchorEl={anchorRef.current}
        transition
        disablePortal
        placement="bottom-end"
      >
        {({ TransitionProps, placement }) => (
          <Grow
            in={TransitionProps?.in}
            onEnter={TransitionProps?.onEnter}
            onExited={TransitionProps?.onExited}
            style={{
              transformOrigin: placement === 'bottom' ? 'center top' : 'center bottom',
            }}
          >
            <Paper>
              <ClickAwayListener onClickAway={handleClose}>
                <MenuList>
                  <Typography>
                    <b>Share</b>
                  </Typography>
                  <Divider />
                  <MenuItem>
                    <FacebookShareButton
                      url={link}
                      quote={quote}
                      className={styles['share-button']}
                    >
                      <FacebookIcon size={24} round className={styles['share-icon']} />
                      <Typography>Facebook</Typography>
                    </FacebookShareButton>
                  </MenuItem>
                  <Divider />
                  <MenuItem>
                    <TwitterShareButton url={link} title={quote} className={styles['share-button']}>
                      <TwitterIcon size={24} round className={styles['share-icon']} />
                      <Typography>Twitter</Typography>
                    </TwitterShareButton>
                  </MenuItem>
                  <Divider />
                  <MenuItem>
                    <WhatsappShareButton
                      url={link}
                      title={quote}
                      className={styles['share-button']}
                    >
                      <WhatsappIcon size={24} round className={styles['share-icon']} />
                      <Typography>Whatsapp</Typography>
                    </WhatsappShareButton>
                  </MenuItem>
                </MenuList>
              </ClickAwayListener>
            </Paper>
          </Grow>
        )}
      </Popper>
    </div>
  );
}
Example #20
Source File: index.js    From paras-landing with GNU General Public License v3.0 4 votes vote down vote up
PublicationDetailPage = ({ errorCode, pubDetail, userProfile }) => {
	const store = useStore()
	const router = useRouter()
	const toast = useToast()
	const textAreaRef = useRef(null)
	const [content, setContent] = useState(
		pubDetail?.content ? EditorState.createWithContent(convertFromRaw(pubDetail.content)) : null
	)
	const [showModal, setShowModal] = useState('')
	const [isCopied, setIsCopied] = useState(false)
	const [isDeleting, setIsDeleting] = useState(false)
	const [isComponentMounted, setIsComponentMounted] = useState(false)

	useEffect(() => {
		setIsComponentMounted(true)
	}, [])

	useEffect(() => {
		if (errorCode) {
			router.push('/publication')
		}
	}, [errorCode])

	if (errorCode) {
		return <Error />
	}

	const headMeta = {
		title: `${pubDetail.title} — Paras Publication`,
		description: pubDetail.description,
		image: parseImgUrl(pubDetail.thumbnail),
	}

	const _copyLink = () => {
		textAreaRef.current.select()
		document.execCommand('copy')

		setIsCopied(true)

		setTimeout(() => {
			setShowModal(false)
			setIsCopied(false)
		}, 1500)
	}

	const _deletePublication = async () => {
		setIsDeleting(true)
		try {
			await axios.delete(`${process.env.V2_API_URL}/publications/${pubDetail._id}`, {
				headers: {
					authorization: await WalletHelper.authToken(),
				},
			})
			setTimeout(() => {
				router.push('/publication')
			}, 1000)
		} catch (err) {
			sentryCaptureException(err)
			const msg = err.response?.data?.message || `Something went wrong, try again later`
			toast.show({
				text: <div className="font-semibold text-center text-sm">{msg}</div>,
				type: 'error',
				duration: 2500,
			})
			setIsDeleting(false)
		}
	}

	return (
		<div>
			<div className="min-h-screen bg-black">
				<div
					className="fixed inset-0 opacity-75"
					style={{
						zIndex: 0,
						backgroundImage: `url('/bg.jpg')`,
						backgroundRepeat: 'no-repeat',
						backgroundSize: 'cover',
					}}
				></div>
				<Head>
					<title>{headMeta.title}</title>
					<meta name="description" content={headMeta.description} />

					<meta name="twitter:title" content={headMeta.title} />
					<meta name="twitter:card" content="summary_large_image" />
					<meta name="twitter:site" content="@ParasHQ" />
					<meta name="twitter:url" content="https://paras.id" />
					<meta name="twitter:description" content={headMeta.description} />
					<meta name="twitter:image" content={headMeta.image} />
					<meta property="og:type" content="website" />
					<meta property="og:title" content={headMeta.title} />
					<meta property="og:site_name" content={headMeta.title} />
					<meta property="og:description" content={headMeta.description} />
					<meta property="og:url" content="https://paras.id" />
					<meta property="og:image" content={headMeta.image} />
				</Head>
				<Nav />
				{isComponentMounted && (
					<div
						className="absolute z-0 opacity-0"
						style={{
							top: `-1000`,
						}}
					>
						<input ref={textAreaRef} readOnly type="text" value={window.location.href} />
					</div>
				)}
				{showModal === 'options' && (
					<Modal close={() => setShowModal('')}>
						<div className="max-w-sm w-full px-4 py-2 bg-gray-100 m-auto rounded-md">
							<div className="py-2 cursor-pointer" onClick={() => _copyLink()}>
								{isCopied ? `Copied` : `Copy Link`}
							</div>
							<div
								className="py-2 cursor-pointer"
								onClick={() => {
									setShowModal('shareTo')
								}}
							>
								Share to...
							</div>
							{!pubDetail.isComic && store.currentUser === pubDetail.author_id && (
								<>
									<Link href={`/publication/edit/${pubDetail._id}`}>
										<div
											className="py-2 cursor-pointer"
											onClick={() => setShowModal('confirmTransfer')}
										>
											Update publication
										</div>
									</Link>
									<div
										className="py-2 cursor-pointer"
										onClick={() => setShowModal('confirmDelete')}
									>
										Delete
									</div>
								</>
							)}
						</div>
					</Modal>
				)}
				{showModal === 'confirmDelete' && (
					<Modal close={() => setShowModal('')} closeOnBgClick={true} closeOnEscape={true}>
						<div className="max-w-sm w-full p-4 bg-gray-100 m-auto rounded-md">
							<h1 className="text-2xl font-bold text-gray-900 tracking-tight">Confirm Delete</h1>
							<p className="text-gray-900 mt-2">
								You are about to delete <b>{pubDetail.title}</b>
							</p>
							<button
								className="w-full outline-none h-12 mt-4 rounded-md bg-transparent text-sm font-semibold border-2 px-4 py-2 border-primary bg-primary text-gray-100"
								type="submit"
								disabled={isDeleting}
								onClick={_deletePublication}
							>
								{isDeleting ? 'Deleting...' : 'Delete my publication'}
							</button>
						</div>
					</Modal>
				)}
				{showModal === 'shareTo' && (
					<Modal close={() => setShowModal('')}>
						<div className="max-w-sm w-full px-4 py-2 bg-gray-100 m-auto rounded-md">
							<div className="py-2 cursor-pointer">
								<TwitterShareButton
									title={`Read ${pubDetail.title} only at @ParasHQ\n\n#paras #cryptoart #digitalart #tradingcards`}
									url={window.location.href}
									className="flex items-center w-full"
								>
									<TwitterIcon
										size={24}
										className="rounded-md"
										bgStyle={{
											fill: '#11111F',
										}}
									/>
									<p className="pl-2">Twitter</p>
								</TwitterShareButton>
							</div>
							<div className="py-2 cursor-pointer">
								<FacebookShareButton
									url={window.location.href}
									className="flex items-center w-full"
								>
									<FacebookIcon
										size={24}
										className="rounded-md"
										bgStyle={{
											fill: '#11111F',
										}}
									/>
									<p className="pl-2">Facebook</p>
								</FacebookShareButton>
							</div>
						</div>
					</Modal>
				)}
				<div className="max-w-5xl relative m-auto pb-12 pt-4">
					<p className="mb-8 px-4 max-w-3xl m-auto text-gray-400">
						<Link href={`/publication`}>
							<span className="cursor-pointer">Publication</span>
						</Link>
						{' > '}
						<Link href={`/publication?type=${pubDetail.type}`}>
							<span className="cursor-pointer capitalize">{pubDetail.type}</span>
						</Link>
						{' > '}
						<span className="font-semibold text-white">{pubDetail.title}</span>
					</p>
					<h1 className="titlePublication text-4xl font-bold pb-0 text-center px-4 md:px-0">
						{pubDetail.title}
					</h1>
					<div className="m-auto max-w-3xl px-4 pt-8">
						<div className="flex justify-between">
							<div className="flex space-x-4">
								<Link href={`/${pubDetail.author_id}`}>
									<div className="w-16 h-16 rounded-full overflow-hidden bg-primary cursor-pointer">
										<img
											src={parseImgUrl(userProfile?.imgUrl, null, {
												width: `800`,
											})}
											className="object-cover"
										/>
									</div>
								</Link>
								<div className="m-auto">
									<LinkToProfile
										accountId={pubDetail.author_id}
										className="text-white font-bold hover:border-white text-xl"
									/>
									<p className="text-white m-auto text-sm">{parseDate(pubDetail.updated_at)}</p>
								</div>
							</div>
							<div>
								<IconDots
									color="#ffffff"
									className="cursor-pointer mb-1"
									onClick={() => setShowModal('options')}
								/>
							</div>
						</div>
						{content && (
							<TextEditor
								title={createEditorStateWithText(pubDetail.title)}
								hideTitle={true}
								content={content}
								setContent={setContent}
								readOnly={true}
							/>
						)}
					</div>
					{pubDetail.collection_ids && pubDetail.collection_ids.length !== 0 && (
						<div className="max-w-4xl mx-auto px-4 pt-16">
							<div className="rounded-md p-2 md:p-4">
								<h4 className="text-white font-semibold text-3xl md:mb-4 text-center">
									{pubDetail.isComic ? 'Comics' : 'Collections'}
								</h4>
								<div
									className={`flex flex-wrap ${
										pubDetail.contract_token_ids.length <= 3 && 'justify-center'
									}`}
								>
									{pubDetail.collection_ids?.map((collectionId, index) => (
										<div key={index} className="w-full md:w-1/2 lg:w-1/3 flex-shrink-0 p-4">
											<EmbeddedCollection collectionId={collectionId} pubDetail={pubDetail} />
										</div>
									))}
								</div>
							</div>
						</div>
					)}
					{pubDetail.contract_token_ids && pubDetail.contract_token_ids.length !== 0 && (
						<div className="max-w-4xl mx-auto px-4 pt-16">
							<div className=" border-2 border-dashed border-gray-800 rounded-md p-4 md:p-8">
								<h4 className="text-white font-semibold text-3xl md:mb-4 text-center">
									Digital Collectibles
								</h4>
								<div
									className={`flex flex-wrap ${
										pubDetail.contract_token_ids.length <= 3 && 'justify-center'
									}`}
								>
									{pubDetail.contract_token_ids?.map((tokenId, index) => (
										<div key={index} className="w-full md:w-1/2 lg:w-1/3 flex-shrink-0 p-8">
											<EmbeddedCard tokenId={tokenId} />
										</div>
									))}
								</div>
							</div>
						</div>
					)}
				</div>
				<Footer />
			</div>
		</div>
	)
}
Example #21
Source File: CountryCard.js    From covid19-brazil-api with MIT License 4 votes vote down vote up
function CountryCard(props) {
  const [data, setData] = useState({});

  useEffect(() => {
    async function fethData() {
      const result = await axios.get(
        `${window.location.origin}/api/report/v1/${props.country}`,
      );
      setData(result.data.data);
    }
    fethData();
  }, []);

  function formatNumber(number) {
    if (number < 10) {
      return `0${number}`;
    }
    return number;
  }

  function formatDate(date) {
    const d = new Date(date);
    const day = `${formatNumber(d.getDate())}/${formatNumber(d.getMonth() + 1)}/${d.getFullYear()}`;
    const hour = `${formatNumber(d.getHours())}:${formatNumber(d.getMinutes())}`;
    return `${day} - ${hour}`;
  }

  function shareData() {
    return (`
*Casos coronavírus no ${data.country} ${mapBrands[data.country]}*

? *Atualizado* ${formatDate(data.updated_at)}

✅ *${data.confirmed}* Confirmados
? *${data.cases}* Ativos
♻️ *${data.recovered}* Recuperados
? *${data.deaths}* Mortes

? *Fonte:* WHO, CDC, ECDC, NHC and DXY
covid19-brazil-api.now.sh/status

⚠️ *Evite fake news*

☢️ *Sobre a doença*
coronavirus.saude.gov.br/index.php/sobre-a-doenca
    `);
  }

  function send() {
    analityc.event({
      category: 'share',
      action: `share-country-report-${data.country.toLowerCase()}`,
    });
    window.open(
      `https://api.whatsapp.com/send?text=${encodeURIComponent(shareData())}`,
    );
  }

  return (
    <Card
      link=""
      title={`Status ${data.country} ${mapBrands[data.country]}`}
    >
      <p>
        <span role="img" aria-label="check">✅</span>
        {' '}
        <strong>{data.confirmed}</strong>
        {' '}
        Confirmados
        {' '}
        <br />
        <span role="img" aria-label="alert">?</span>
        {' '}
        <strong>{data.cases}</strong>
        {' '}
        Ativos
        {' '}
        <br />
        <span role="img" aria-label="recovery">♻️</span>
        {' '}
        <strong>{data.recovered}</strong>
        {' '}
        Recuperados
        {' '}
        <br />
        <span role="img" aria-label="death">?</span>
        {' '}
        <strong>{data.deaths}</strong>
        {' '}
        Mortes
        <hr />
        <span role="img" aria-label="time">?</span>
        {' '}
        <strong>Atualizado</strong>
        {' '}
        {formatDate(data.updated_at)}
        {' '}
        <br />
        <span role="img" aria-label="chart">?</span>
        {' '}
        <strong>Fonte</strong>
        {' '}
        WHO
      </p>
      <strong>Compartilhar</strong>
      <div className="flex-center">
        <span className="pointer">
          <WhatsappIcon
            onClick={send}
            size={48}
          />
        </span>
        <FacebookShareButton url="https://covid19-brazil-api.now.sh/status" quote={shareData()}>
          <FacebookIcon size={48} />
        </FacebookShareButton>
        <TwitterShareButton url="https://covid19-brazil-api.now.sh/status" title={shareData().substr(1, 240)}>
          <TwitterIcon size={48} />
        </TwitterShareButton>
      </div>

      <style jsx>
        {`
      .share-button {
        width: 100%;
        background: #202124;
        color: #4ffa7b;
        font-weight: 600;
        border-radius: 30px;
        font-size: 1.1rem;
        padding: 8px 0;
        display: flex;
        justify-content: center;
        align-items: center;
        border: 0;
        cursor: pointer;
        transition: background 0.5s;
      }
      }
      .share-button img {
        margin-left: 16px
      }
      .pointer {
        cursor: pointer;
      }
      `}
      </style>
    </Card>
  );
}
Example #22
Source File: [slug].js    From paras-landing with GNU General Public License v3.0 4 votes vote down vote up
PublicationDetailPage = ({ errorCode, pubDetail, userProfile }) => {
	const store = useStore()
	const router = useRouter()
	const toast = useToast()
	const textAreaRef = useRef(null)
	const [content, setContent] = useState(
		pubDetail?.content ? EditorState.createWithContent(convertFromRaw(pubDetail.content)) : null
	)
	const [showModal, setShowModal] = useState('')
	const [isCopied, setIsCopied] = useState(false)
	const [isDeleting, setIsDeleting] = useState(false)
	const [isComponentMounted, setIsComponentMounted] = useState(false)

	useEffect(() => {
		setIsComponentMounted(true)
	}, [])

	useEffect(() => {
		if (errorCode) {
			router.push('/publication')
		}
	}, [errorCode])

	if (errorCode) {
		return <Error />
	}

	const headMeta = {
		title: `${pubDetail.title} — Paras Publication`,
		description: pubDetail.description,
		image: parseImgUrl(pubDetail.thumbnail),
	}

	const _copyLink = () => {
		textAreaRef.current.select()
		document.execCommand('copy')

		setIsCopied(true)

		setTimeout(() => {
			setShowModal(false)
			setIsCopied(false)
		}, 1500)
	}

	const _deletePublication = async () => {
		setIsDeleting(true)
		try {
			await axios.delete(`${process.env.V2_API_URL}/publications/${pubDetail._id}`, {
				headers: {
					authorization: await WalletHelper.authToken(),
				},
			})
			setTimeout(() => {
				router.push('/publication')
			}, 1000)
		} catch (err) {
			sentryCaptureException(err)
			const msg = err.response?.data?.message || 'Something went wrong, try again later.'
			toast.show({
				text: <div className="font-semibold text-center text-sm">{msg}</div>,
				type: 'error',
				duration: 2500,
			})
			setIsDeleting(false)
		}
	}

	return (
		<div>
			<div className="min-h-screen bg-black">
				<div
					className="fixed inset-0 opacity-75"
					style={{
						zIndex: 0,
						backgroundImage: `url('/bg.jpg')`,
						backgroundRepeat: 'no-repeat',
						backgroundSize: 'cover',
					}}
				></div>
				<Head>
					<title>{headMeta.title}</title>
					<meta name="description" content={headMeta.description} />

					<meta name="twitter:title" content={headMeta.title} />
					<meta name="twitter:card" content="summary_large_image" />
					<meta name="twitter:site" content="@ParasHQ" />
					<meta name="twitter:url" content="https://paras.id" />
					<meta name="twitter:description" content={headMeta.description} />
					<meta name="twitter:image" content={headMeta.image} />
					<meta property="og:type" content="website" />
					<meta property="og:title" content={headMeta.title} />
					<meta property="og:site_name" content={headMeta.title} />
					<meta property="og:description" content={headMeta.description} />
					<meta property="og:url" content="https://paras.id" />
					<meta property="og:image" content={headMeta.image} />
				</Head>
				<Nav />
				{isComponentMounted && (
					<div
						className="absolute z-0 opacity-0"
						style={{
							top: `-1000`,
						}}
					>
						<input ref={textAreaRef} readOnly type="text" value={window.location.href} />
					</div>
				)}
				{showModal === 'options' && (
					<Modal close={() => setShowModal('')}>
						<div className="max-w-sm w-full px-4 py-2 bg-gray-100 m-auto rounded-md">
							<div className="py-2 cursor-pointer" onClick={() => _copyLink()}>
								{isCopied ? `Copied` : `Copy Link`}
							</div>
							<div
								className="py-2 cursor-pointer"
								onClick={() => {
									setShowModal('shareTo')
								}}
							>
								Share to...
							</div>
							{store.currentUser === pubDetail.author_id && (
								<Link href={`/publication/edit/${pubDetail._id}`}>
									<div
										className="py-2 cursor-pointer"
										onClick={() => setShowModal('confirmTransfer')}
									>
										Update publication
									</div>
								</Link>
							)}
							{store.currentUser === pubDetail.author_id && (
								<div className="py-2 cursor-pointer" onClick={() => setShowModal('confirmDelete')}>
									Delete
								</div>
							)}
						</div>
					</Modal>
				)}
				{showModal === 'confirmDelete' && (
					<Modal close={() => setShowModal('')} closeOnBgClick={true} closeOnEscape={true}>
						<div className="max-w-sm w-full p-4 bg-gray-100 m-auto rounded-md">
							<h1 className="text-2xl font-bold text-gray-900 tracking-tight">Confirm Delete</h1>
							<p className="text-gray-900 mt-2">
								You are about to delete <b>{pubDetail.title}</b>
							</p>
							<button
								className="w-full outline-none h-12 mt-4 rounded-md bg-transparent text-sm font-semibold border-2 px-4 py-2 border-primary bg-primary text-gray-100"
								type="submit"
								disabled={isDeleting}
								onClick={_deletePublication}
							>
								{isDeleting ? 'Deleting...' : 'Delete my publication'}
							</button>
						</div>
					</Modal>
				)}
				{showModal === 'shareTo' && (
					<Modal close={() => setShowModal('')}>
						<div className="max-w-sm w-full px-4 py-2 bg-gray-100 m-auto rounded-md">
							<div className="py-2 cursor-pointer">
								<TwitterShareButton
									title={`Read ${pubDetail.title} only at @ParasHQ\n\n#paras #cryptoart #digitalart #tradingcards`}
									url={window.location.href}
									className="flex items-center w-full"
								>
									<TwitterIcon
										size={24}
										className="rounded-md"
										bgStyle={{
											fill: '#11111F',
										}}
									/>
									<p className="pl-2">Twitter</p>
								</TwitterShareButton>
							</div>
							<div className="py-2 cursor-pointer">
								<FacebookShareButton
									url={window.location.href}
									className="flex items-center w-full"
								>
									<FacebookIcon
										size={24}
										className="rounded-md"
										bgStyle={{
											fill: '#11111F',
										}}
									/>
									<p className="pl-2">Facebook</p>
								</FacebookShareButton>
							</div>
						</div>
					</Modal>
				)}
				<div className="max-w-5xl relative m-auto pb-12 pt-4">
					<p className="mb-8 px-4 max-w-3xl m-auto text-gray-400">
						<Link href={`/publication`}>
							<span className="cursor-pointer">Publication</span>
						</Link>
						{' > '}
						<Link href={`/publication?type=${pubDetail.type}`}>
							<span className="cursor-pointer capitalize">{pubDetail.type}</span>
						</Link>
						{' > '}
						<span className="font-semibold text-white">{pubDetail.title}</span>
					</p>
					<h1 className="titlePublication text-4xl font-bold pb-0 text-center px-4 md:px-0">
						{pubDetail.title}
					</h1>
					<div className="m-auto max-w-3xl px-4 pt-8">
						<div className="flex justify-between">
							<div className="flex space-x-4">
								<Link href={`/${pubDetail.author_id}`}>
									<div className="w-16 h-16 rounded-full overflow-hidden bg-primary cursor-pointer">
										<img
											src={parseImgUrl(userProfile?.imgUrl, null, {
												width: `800`,
											})}
											className="object-cover"
										/>
									</div>
								</Link>
								<div className="m-auto">
									<LinkToProfile
										accountId={pubDetail.author_id}
										className="text-white font-bold hover:border-white text-xl"
									/>
									<p className="text-white m-auto text-sm">{parseDate(pubDetail.updated_at)}</p>
								</div>
							</div>
							<div>
								<IconDots
									color="#ffffff"
									className="cursor-pointer mb-1"
									onClick={() => setShowModal('options')}
								/>
							</div>
						</div>
						{content && (
							<TextEditor
								title={createEditorStateWithText(pubDetail.title)}
								hideTitle={true}
								content={content}
								setContent={setContent}
								readOnly={true}
							/>
						)}
					</div>
					{pubDetail.contract_token_ids && pubDetail.contract_token_ids.length !== 0 && (
						<div className="max-w-4xl mx-auto px-4 pt-16">
							<div className=" border-2 border-dashed border-gray-800 rounded-md p-4 md:p-8">
								<h4 className="text-white font-semibold text-3xl md:mb-4 text-center">
									Digital Collectibles
								</h4>
								<div
									className={`flex flex-wrap ${
										pubDetail.contract_token_ids.length <= 3 && 'justify-center'
									}`}
								>
									{pubDetail.contract_token_ids?.map((tokenId, index) => (
										<div key={index} className="w-full md:w-1/2 lg:w-1/3 flex-shrink-0 p-8">
											<EmbeddedCard tokenId={tokenId} />
										</div>
									))}
								</div>
							</div>
						</div>
					)}
				</div>
				<Footer />
			</div>
		</div>
	)
}
Example #23
Source File: nearme.jsx    From howlongistheline.org with Mozilla Public License 2.0 4 votes vote down vote up
function Index({ history }) {
    {/*Initialise props*/ }
    const [clientLocation, setclientLocation] = useCookies(['location']);
    const [nearestShops, setnearestShops] = useState([]);
    const [loading, setLoading] = useState(false);
    const [loadingMessage, setLoadingMessage] = useState("Getting your location...");
    const [search, setSearch] = useState("");
    const [searchResult, setSearchResult] = useState([]);
    const [loadingCardList, setLoadingCardList] = useState({ [""]: false });
    const [isOpen, setIsOpen] = useState(false);
    const [reportId, setReportId] = useState("");

    useEffect(() => {
        checkClientLocation()
    }, [])

    useEffect(() => {
        let isCancelled = false;
        try {
            if (!isCancelled) {
                Tracker.autorun(function () {
                    if (!isCancelled) {
                        if (search == "") {
                        }
                        else {
                            var searchArray = search.split(/(\s+)/).filter( e => e.trim().length > 0)
                            let allResults = []
                            searchArray.forEach((word)=>{
                                allResults.push(LocationsIndex.search(word).fetch())
                            })
                            var flatten = _.flatten(allResults)
                            var removeDup = _.unique(flatten, false, function(item, k, v){
                                return item._id;
                            });
                            console.log(removeDup)
                            setSearchResult(removeDup)
                        }
                    }
                })
            }
        } catch (e) {
            if (!isCancelled) {
                throw e;
            }
        }
        return function cleanup() {
            isCancelled = true;
        }
    }, [search])

    function distance(lat1, lon1, lat2, lon2, unit) {
        if ((lat1 == lat2) && (lon1 == lon2)) {
            return 0;
        }
        else {
            var radlat1 = Math.PI * lat1 / 180;
            var radlat2 = Math.PI * lat2 / 180;
            var theta = lon1 - lon2;
            var radtheta = Math.PI * theta / 180;
            var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
            if (dist > 1) {
                dist = 1;
            }
            dist = Math.acos(dist);
            dist = dist * 180 / Math.PI;
            dist = dist * 60 * 1.1515;
            if (unit == "K") { dist = dist * 1.609344 }
            if (unit == "N") { dist = dist * 0.8684 }
            return dist;
        }
    }

    function checkClientLocation() {
        if (clientLocation.location != undefined) {
            if ((new Date().getTime() - new Date(clientLocation.location.time).getTime()) / 1000 < 300) {
                if (nearestShops.length == undefined || nearestShops.length <= 1) {
                    fetchNearestShops()
                } else {
                    // console.log(nearestShops)
                }
            } else { getClientLocation() }
        } else { getClientLocation() }
    }

    function getClientLocation() {
        setLoading(true)
        var options = {
            enableHighAccuracy: true,
            timeout: 30000,
            maximumAge: 300000
        };

        function success(position) {
            console.log("CLT longitude: ")
            console.log(position.coords.longitude)
            console.log("CLT latitude: ")
            console.log(position.coords.latitude)
            setclientLocation('location', { longitude: position.coords.longitude, latitude: position.coords.latitude, time: new Date() });
            fetchNearestShops(position.coords.latitude, position.coords.longitude);
        }

        function error(err) {
            setLoading(false)
            console.log("nm location failure")
            toast("Can't get current location, please try a different browser if this continues")
            console.warn(`ERROR(${err.code}): ${err.message}`);
        }

        navigator.geolocation.getCurrentPosition(success, error, options);

    }

    function fetchNearestShops(latitude, longitude) {
        console.log("CLT updating nearest stores")
        var lat;
        var long;
        if (clientLocation.location == undefined) {
            lat = latitude;
            long = longitude;
        } else {
            lat = clientLocation.location.latitude;
            long = clientLocation.location.longitude;
        }
        Meteor.call('locations.findnearby', { lat, long }, (err, result) => {
            if (result) {
                setLoading(false)
                setnearestShops(result)
            } else {
                console.log(err)
            }
        }
        );
        setLoadingMessage("Loading nearby stores...")
    }

    function renderList() {
        if (loading) {
            return (<Card>
                <ProgressBar indeterminate />
                {loadingMessage}
            </Card>)
        }
        if (search == "") {
            return nearestShops.map((location) => {
                return renderCard(location)
            }
            )
        }
        else {
            return searchResult.map((location) => {
                return renderCard(location)
            })
        }
    }

    function Line(people) {
        if(people) {
            if(people === 1) {
                return "There was 1 person in line"
            } else {
                return `There were ${getDisplayedLineLength(people)} people in line`
            }
        } else {
            return "There was no line"
        }
    }

    function renderCard(location) {
        var Indicator = "green"
        switch (true) {
            case (location.line == undefined):
                Indicator = "green"
                break
            case (location.line <= 20 && location.line >= 0):
                Indicator = "green"
                break
            case (location.line <= 35 && location.line > 20):
                Indicator = "orange"
                break
            case (location.line > 35):
                Indicator = "red"
                break
        }
        var updateNumber = location.line;
        return (
            <Card key={location._id} style={{ backgroundColor: "white" }}>
                <ListItem style={{ fontSize: 20, fontWeight: "bold" }} modifier="nodivider">
                    {location.name}
                    <div className="right">
                        <Button onClick={() => {
                            // history.push('/duplicated?id=' + location._id)
                            setIsOpen(true)
                            setReportId(location._id)
                        }}>
                            <i className="fas fa-exclamation-triangle" />
                        </Button>
                    </div>
                </ListItem>
                <ListItem modifier="nodivider" expandable>
                    <div className="left">
                        <Icon style={{ paddingRight: 20 }} icon="map-marker-alt" /> {location.address}
                    </div>
                    <div className="expandable-content">
                        <img style={{ maxHeight: 200 }} src={"https://howlongistheline.org/maps/" + location.coordinates[1] + "," + location.coordinates[0] + ",K3340"} />
                    </div>

                </ListItem>
                <ListItem modifier="nodivider">
                    <div className="center" style={{ color: Indicator }}>
                        {Line(location.line)} {moment(location.lastUpdate).fromNow()}.
                    </div>
                    <div className="right">
                        <Button onClick={() => { history.push('/stocks?id=' + location._id) }}>
                            Stock Status
                       </Button>
                    </div>
                </ListItem>
                <ListItem modifier="nodivider">
                    <div className="center">
                        If you are at this store right now, drag the slider to update the line numbers, or confirm the existing numbers.
                  </div>
                </ListItem>
                <ListItem modifier="nodivider">
                    <div className="center">
                        <Slider
                            defaultValue={parseInt(location.line) ? parseInt(location.line) : 0}
                            min={0}
                            max={MAX_LINE_LENGTH}
                            style={{ width: "80%", margin: "0px 15px" }}
                            valueLabelDisplay="auto"
                            valueLabelFormat={getDisplayedLineLength}
                            onChangeCommitted={function (event, value) {
                                if (event.type === "mouseup" || event.type === "touchend") {
                                    window.document.activeElement.value = value;
                                    let buttonText = '';
                                    if (location.line === value || (value === 0 && !location.line)) {
                                        buttonText = `Confirm ${getDisplayedLineLength(location.line)} ${location.line === 1 ? "person is" : "people are"} waiting in line`;
                                    } else {
                                        buttonText = `Update line length to ${getDisplayedLineLength(value)} ${value === 1 ? "person" : "people"}`;
                                    }
                                    document.getElementById(location._id).innerHTML = buttonText;
                                    updateNumber = value;
                                }
                            }}
                        />
                    </div>
                    <div className="right">
                    </div>
                </ListItem>
                <ListItem modifier="nodivider" style={{ flexWrap: 'wrap' }}>
                    <div className="center">
                        <Button id={location._id} onClick={
                            function (event) {
                                setLoadingCardList({
                                    ...loadingCardList,  //take existing key-value pairs and use them in our new state,
                                    [location._id]: true   //define new key-value pair with new uuid and [].
                                })
                                var loc = Locations.findOne({
                                    _id: location._id
                                })
                                var options = {
                                    enableHighAccuracy: true,
                                    timeout: 10000,
                                    maximumAge: 300000
                                };
                                navigator.geolocation.getCurrentPosition((position) => {
                                    //client side distance check
                                    var distanceInMeter = distance(position.coords.latitude, position.coords.longitude, loc.coordinates[1], loc.coordinates[0], "K") * 1000
                                    if (distanceInMeter > 100) {
                                        history.push("/editLine?id=" + location._id + "&lineSize=" + updateNumber, { location: location })
                                        return
                                    }
                                    Meteor.call('locations.updatelinesize', location._id, updateNumber, function (err, result) {
                                        if (err) {
                                            toast("Some error happened, Please try again later!")
                                            console.log(err)
                                            setLoadingCardList({
                                                ...loadingCardList,  //take existing key-value pairs and use them in our new state,
                                                [location._id]: false   //define new key-value pair with new uuid and [].
                                            })
                                            // history.push("/editLine?id=" + location._id + "&lineSize=" + updateNumber, { location: location })
                                            return
                                        }
                                        // setLoading(false)
                                        alert("The store has been updated, thank you!")
                                        history.go(0)
                                    });
                                }, (err) => {
                                    console.log(err)
                                    toast("Some error happened, Please try again later!")
                                    setLoadingCardList({
                                        ...loadingCardList,  //take existing key-value pairs and use them in our new state,
                                        [location._id]: false   //define new key-value pair with new uuid and [].
                                    })
                                }, options)
                            }
                        }>
                            Confirm {getDisplayedLineLength(location.line)} {location.line === 1 ? "person is" : "people are"} waiting in line
                </Button>
                    </div>
                    <div className="right">
                        <FacebookShareButton
                            url={"https://howlongistheline.org"}
                            quote={"There " + (location.line === 1 ? "was " : "were ") + getDisplayedLineLength(location.line) + " people waiting in line at " + location.name.trim() + " (" + location.address.trim() + ") " + moment(location.lastUpdate).fromNow()}
                            hashtag="#howlongistheline"
                        >
                            <FacebookIcon size={32} round />
                        </FacebookShareButton>
                        <TwitterShareButton
                            url={"https://howlongistheline.org"}
                            title={"There " + (location.line === 1 ? "was " : "were ") + getDisplayedLineLength(location.line) + " people waiting in line at " + location.name.trim() + " (" + location.address.trim() + ") " + moment(location.lastUpdate).fromNow()}
                        >
                            <TwitterIcon size={32} round />
                        </TwitterShareButton>

                    </div>
                </ListItem>
                {loadingCardList[location._id] ? <> <ProgressBar indeterminate /> Updating</> : <></>}
            </Card>
        )
    }

    return (
        <MainLayout>
            <div className="search-container" style={{ position: "sticky", top: 0, zIndex: 1000, background: "#fff" }}>
                <ListItem>
                    <SearchInput style={{ width: "100%", backgroundColor: "#d9f4ff", color: "black" }} placeholder="Find stores near you." onChange={(e) => {
                        setSearch(e.target.value)
                    }} />
                </ListItem>
            </div>
            <div className="border-top" style={{ marginBottom: 55 }}>
                <Card class="isa_info">
                    <i className="fas fa-info-circle" /> If something doesn't work properly, check back a few days later and it will probably be fixed.
                  Go <a href="https://github.com/howlongistheline/howlongistheline.org/issues">here</a> to see what the community behind this is currently working on.
                </Card>
                <ListTitle>
                    Stores Near You
          </ListTitle>
                {renderList()}
            </div>
            <Button modifier="large--cta" style={{ position: "fixed", bottom: 0, zIndex: 1000, minHeight: 50 }}
                // type="submit"
                onClick={() => { history.push('/addLine') }}>
                Missing store? Add it now!
                  <Icon style={{ marginLeft: 10 }} icon='fa-plus' />
            </Button>
            <ActionSheet isCancelable isOpen={isOpen}
            onCancel={()=>{setIsOpen(false)}}
            >
             <ActionSheetButton onClick={()=>{history.push('/duplicated?id=' + reportId)}}> Report Duplicated</ActionSheetButton>
             <ActionSheetButton onClick={()=>{history.push('/editLocation?id=' + reportId)}}> Report Wrong Location</ActionSheetButton>
             <ActionSheetButton onClick={()=>{setIsOpen(false)}}>Cancel</ActionSheetButton>
            </ActionSheet>
        </MainLayout>
    )
}
Example #24
Source File: Poll.js    From Insta-Poll with MIT License 4 votes vote down vote up
Poll = (props) => {
    const id = props.match.params.id;
    const {user} = UserSession();
    const uid = user.uid;
    const [label, setLabel] = useState([]);
    const [expiry, setExpiry] = useState(false);
    const [poll, setPoll] = useState(null);
    const [modal, setModal] = useState(false);
    const [pollData, setPollData] = useState([]);
    const [index, setIndex] = useState(-1);
    const handleURL = ()=>{
        navigator.clipboard.writeText("https://insta-poll-72ce3.web.app/" + poll.id);
        toast.success("URL copied to clipboard")
    }
    const showModal = () => {
        setModal(!modal);
      };
    const handleClick = (index)=>{
        setIndex(index);
      let x = poll;
      if(!x.votes[uid])
      {
        x.options.forEach((option)=>{
          if(option.index==index)
          option.count +=1;
      })
      }
      else if(x.votes[uid]!=index)
      {
        x.options.forEach((option)=>{
          if(option.index==(x.votes[uid]))
          {
            option.count-=1;
          }
          else if(option.index==index)
          {
            option.count+=1;
          }
        })
      }
          
          x.votes[uid] = index;
          updatePoll(x);
        
        
   

    }
    const handleLogout  = ()=>{
      firebase.auth().signOut().then(function() {
        }).catch(function(error) {
         
        });
  }
   useEffect(()=>{
       const docRef =  firestore.doc(`/polls/${id}`);
        const unsubscribe = docRef.onSnapshot((document)=>{
            if(document.exists)
            {   setPoll(document.data());
                let x=[], y=[];
              if(document.data().expire)
              {
                if((new Date().getTime()/1000)>=document.data().date.seconds)
                setExpiry(true);
              }
                document.data().options.forEach((option)=>{
                    x.push(option.title);
                    y.push(option.count)
                })
                if(document.data().votes && document.data().votes[uid])
                {
                    setIndex(document.data().votes[uid]);
                }
                setLabel(x);
                setPollData(y);
                
            }
            else
            {
              props.history.push("/not_found");
            }
        })
    }, [])

  
      
    const shareUrl = 'http://github.com';
    const data = {

        labels :label,
        datasets: [
          {
            label: 'Number of Votes',
            data: pollData,
            backgroundColor: [
              'rgba(255, 99, 132, 0.2)',
              'rgba(54, 162, 235, 0.2)',
              'rgba(255, 206, 86, 0.2)',
              'rgba(75, 192, 192, 0.2)',
              'rgba(153, 102, 255, 0.2)',
              'rgba(255, 159, 64, 0.2)',
            ],
            borderColor: [
              'rgba(255, 99, 132, 1)',
              'rgba(54, 162, 235, 1)',
              'rgba(255, 206, 86, 1)',
              'rgba(75, 192, 192, 1)',
              'rgba(153, 102, 255, 1)',
              'rgba(255, 159, 64, 1)',
            ],
            borderWidth: 1,
          },
        ],
      }
    
      const options = {
        scales: {
          yAxes: [
            {
              ticks: {
                beginAtZero: true,
                precision:0,
                fontFamily:"Mulish",
                fontStyle: '500'
              },
              barPercentage:"0.4"
            },
       
           
          ],
          xAxes: [
            {
              ticks: {
                beginAtZero: true,
                precision:0,
                fontFamily:"Mulish",
                fontStyle:"500"
              },
            },
          ],
        },
        legend:{
            labels:{
                fontFamily: "Mulish"
            },
        },
       
        maintainAspectRatio: false
      
    }

if(!poll)
return( <div
style={{
  width: "100%",
  display: "flex",
  height: "100vh",
  alignItems: "center",
  justifyContent: "center",
  zIndex: "23444898429"
}}
>
<img src={Loader} />
</div>)
    return (
        <div>
          <div className="logout_grid">
            <div>
                <h1 className="head_title animate__animated animate__fadeIn">{poll.title} </h1>
                </div>
                <div>
                <Button type="primary" onClick={handleLogout} className="btn_logout"> Logout <LogoutOutlined /></Button>
                </div>
                </div>
                <Link to="/"><Button type="primary" className="create_btn" >Create a new Poll</Button></Link>
                <br/>
                <ToastContainer newestOnTop autoClose={2000}/>
             <div className="flex">
             <div className="options_div animate__animated animate__fadeInLeft">
         {expiry ? (<h2>This poll is no longer accepting responses ❌</h2>) : (<h2>Select an Option ?</h2>)}       
                {expiry ? (poll.options.map((option)=>{
                           if(option.index!=index)
                  return (
                    <div className="poll_live_expire">
                      {option.title}
                    </div>
                  )
                  else
                  return(
                    <div className="poll_live_expire_selected">
                    {option.title}
                  </div>
                  )
                })) :  (poll.options.map((option)=>
                {
                    if(option.index!=index)
                    return(
                        <div className="poll_live" onClick={()=>handleClick(option.index)}>
                        {option.title}
                    </div>
                    )
                    else
                    return(
                        <div className="poll_live_selected " onClick={()=>handleClick(option.index)}>
                        {option.title}
                    </div>
                    )
                }
                   
                ))}
             </div>
{index!=-1 && ( <div className="graph animate__animated animate__fadeInRight">
             <HorizontalBar data={data}  options={options} />
        </div>)}
            
            </div>
      <div className="share_icons animate__animated animate__fadeIn">
          <h3>Share this Poll <ShareAltOutlined /></h3>
        <TwitterShareButton
            url={`https://insta-poll-72ce3.web.app/${poll.id}`}
            title={`Vote to this poll titled "${poll.title}"  generated using Insta Poll\n`}
            className="share_icon"
          >
            <TwitterIcon size={32} round />
          </TwitterShareButton>
          <WhatsappShareButton
             url={`https://insta-poll-72ce3.web.app/${poll.id}`}
             title={`Vote to this poll titled "${poll.title}"  generated using Insta Poll`}
            separator=":: "
            className="share_icon"
  
          >
            <WhatsappIcon size={32} round  />
          </WhatsappShareButton>
          <FacebookShareButton
            url={`https://insta-poll-72ce3.web.app/${poll.id}`}
            title={`Vote to this poll titled "${poll.title}"  generated using Insta Poll`}
            className="share_icon"
       
          >
            <FacebookIcon size={32} round />
          </FacebookShareButton>
          <br/>
          <Input value={`https://insta-poll-72ce3.web.app/${poll.id}`} style={{width:"15rem"}} disabled/>
          <Button type="primary" onClick={handleURL}>Copy URL</Button>
          <Button type="primary" onClick={showModal} style={{margin:"0.5rem"}}>
          Share QR Code
        </Button>
          <Modal
          visible={modal}
          onOk={showModal}
          onCancel = {showModal}
                style={{textAlign:"center"}}
        >
            <QRCode value={`https://insta-poll-72ce3.web.app/${poll.id}`} style={{height:"12rem", width:"12rem"}}  />
             </Modal>
          </div>
        </div>
    )
}
Example #25
Source File: App.js    From covid19action with MIT License 4 votes vote down vote up
function App() {
  const {
    history,
    location: { pathname },
  } = useReactRouter();

  useEffect(() => {
    if (!routes.includes(pathname)) {
      history.replace(routes[0]);
    }
    // eslint-disable-next-line
  }, []);

  const [state, dispatch] = useReducer(reducer, initialState);
  const i18n = state.i18n;

  const aRelevantLanguages = getValidLocale();

  const handleTabSelect = event => {
    history.push(mapTabToRoute(event.parameters.item.slot));
  };

  return (
    <div className="App">
      <div className="Covid19App">
        <div className="headerShellBar">
          <div className="shellBarLeft">
            <Button
              design={ButtonDesign.Transparent}
              icon="home"
              className="shellBarBtn"
              onClick={() => window.location.replace('https://myswastha.in/')}
            ></Button>
          </div>
          <div className="shellBarCenter">{i18n.HOME_TITLE}</div>
          <div className="shellBarRight">
            <Button
              design={ButtonDesign.Transparent}
              icon="world"
              className="shellBarBtn"
              onClick={() => dispatch({ type: 'openLanguageDialog' })}
            ></Button>
            <Button
              design={ButtonDesign.Transparent}
              icon="sys-help"
              className="shellBarIconBtn"
              onClick={() => dispatch({ type: 'openDialog' })}
            ></Button>
            <ActionSheet
              openBy={
                <Button
                  design={ButtonDesign.Transparent}
                  icon="share"
                  className="shellBarIconBtn"
                />
              }
              placement={'Bottom'}
            >
              <FacebookShareButton
                url="https://myswastha.in/"
                quote={i18n.SHARING_TITLE}
                hashtag="#MySwastha #FlattenTheCurve"
              >
                <FacebookIcon size={32} round={true} />
              </FacebookShareButton>
              <WhatsappShareButton url="https://myswastha.in/" title={i18n.SHARING_TITLE}>
                <WhatsappIcon size={32} round={true} />
              </WhatsappShareButton>
              <TwitterShareButton
                url="https://myswastha.in/"
                title={i18n.SHARING_TITLE}
                hashtags={['FlattenTheCurve', 'MySwastha']}
                via={['nitish_mehta']}
              >
                <TwitterIcon size={32} round={true} />
              </TwitterShareButton>
              <LinkedinShareButton url="https://myswastha.in/" title={i18n.SHARING_TITLE}>
                <LinkedinIcon size={32} round={true} />
              </LinkedinShareButton>
            </ActionSheet>
          </div>
        </div>
        <MessageStrip
          className="archivedNotification"
          icon={null}
          noCloseButton={true}
          noIcon={false}
          type={'Warning'}
        >
          NOTE: This app has been archived. <br />
          Kindly use{' '}
          <Link href="https://www.mygov.in/aarogya-setu-app/" target="_blank" wrap>
            Aarogya Setu{' '}
          </Link>{' '}
          app or{' '}
          <Link href="https://www.mohfw.gov.in/" target="_blank" wrap>
            Ministry of Health{' '}
          </Link>{' '}
          website for latest info. <b>Stay Safe &amp; Healthy !</b>
        </MessageStrip>

        <TabContainer className="c19IconTab" showOverflow onItemSelect={handleTabSelect} fixed>
          <Tab text={i18n.UNWELL} icon="stethoscope" selected={pathname === routes[0]}>
            <TabEligibilityChecker i18n={i18n} />
          </Tab>
          <Tab icon="notes" selected={pathname === routes[1]}>
            <TabIndiaInfo i18n={i18n} />
          </Tab>
          <Tab text={''} icon="business-objects-experience" selected={pathname === routes[2]}>
            <TabMoreInfo i18n={i18n} />
          </Tab>
        </TabContainer>

        <Dialog
          headerText={i18n.ABOUT_THIS_WEBSITE}
          stretch={false}
          open={state.isHelpDialogOpen}
          footer={
            <Button className="dialogFooterBtn" onClick={() => dispatch({ type: 'closeDialog' })}>
              {i18n.CLOSE}
            </Button>
          }
        >
          <div style={{ width: '300px', height: '400px' }}>
            <Label wrap className="disclaimerText">
              {i18n.WEBSITE_DISCLAIMER}
            </Label>
            <br />
            <br />
            <Label wrap>{i18n.WEBSITE_DESCRIPTION_1}</Label>
            <br />
            <br />
            <Label wrap>
              {i18n.WEBSITE_DESCRIPTION_2}{' '}
              <Link href="https://github.com/nitish-mehta/covid19action" target="_blank" wrap>
                GitHub{' '}
              </Link>
              {i18n.WEBSITE_DESCRIPTION_3}
            </Label>
            <br />
            <Label wrap>
              {i18n.WEBSITE_DESCRIPTION_4}{' '}
              <Link href="https://twitter.com/nitish_mehta" target="_blank" wrap>
                Twitter
              </Link>{' '}
              {i18n.AND}{' '}
              <Link href="https://www.linkedin.com/in/nitishmehta08/" target="_blank" wrap>
                LinkedIn.
              </Link>{' '}
            </Label>
            <br />
            <br />
            <Label wrap>{i18n.WEBSITE_DESCRIPTION_5}</Label>
            <br />
            <br />
            <FlexBox
              justifyContent={'SpaceBetween'}
              alignItems={'Stretch'}
              direction={'Row'}
              displayInline={false}
              fitContainer
            >
              <FacebookShareButton
                url="https://myswastha.in/"
                quote={i18n.SHARING_TITLE}
                hashtag="#MySwastha #FlattenTheCurve"
              >
                <FacebookIcon size={32} round={true} />
              </FacebookShareButton>
              <WhatsappShareButton url="https://myswastha.in/" title={i18n.SHARING_TITLE}>
                <WhatsappIcon size={32} round={true} />
              </WhatsappShareButton>
              <TwitterShareButton
                url="https://myswastha.in/"
                title={i18n.SHARING_TITLE}
                hashtags={['FlattenTheCurve', 'MySwastha']}
                via={['nitish_mehta']}
              >
                <TwitterIcon size={32} round={true} />
              </TwitterShareButton>{' '}
              <LinkedinShareButton url="https://myswastha.in/" title={i18n.SHARING_TITLE}>
                <LinkedinIcon size={32} round={true} />
              </LinkedinShareButton>
            </FlexBox>
          </div>
        </Dialog>

        <Dialog
          headerText={'Change Language'}
          stretch={false}
          open={state.isLanguageDialogOpen}
          footer={
            <Button
              className="dialogFooterBtn"
              onClick={() => dispatch({ type: 'closeLanguageDialog' })}
            >
              {i18n.CLOSE}
            </Button>
          }
        >
          <div style={{ width: '250px', height: '300px' }}>
            <Link
              href="
                  https://github.com/nitish-mehta/covid19action#how-can-you-help"
              target="_blank"
              wrap
            >
              (Help Improve Translations)
            </Link>{' '}
            <ul>
              {aRelevantLanguages.map(currentVal => {
                return (
                  <li key={currentVal.code}>
                    <Button
                      design={ButtonDesign.Transparent}
                      onClick={() => {
                        dispatch({ type: 'closeLanguageDialog' });
                        dispatch({
                          type: 'i18nChange',
                          payload: changeCurrentLocale(currentVal.code),
                        });
                      }}
                    >
                      {currentVal.displayText}
                    </Button>
                  </li>
                );
              })}
            </ul>
          </div>
        </Dialog>
      </div>
    </div>
  );
}
Example #26
Source File: artist-verification.js    From paras-landing with GNU General Public License v3.0 4 votes vote down vote up
Verify = () => {
	const { localeLn } = useIntl()
	const router = useRouter()
	const store = useStore()
	const toast = useToast()
	const recaptchaRef = useRef()

	const [profile, setProfile] = useState('')
	const [isSubmitting, setIsSubmitting] = useState(false)
	const [isDisable, setIsDisable] = useState(false)
	const [totalQuota, setTotalQuota] = useState(0)
	const [totalCurrent, setTotalCurrent] = useState(0)
	const [isQuotaAvail, setIsQuotaAvail] = useState(true)
	const [formState, setFormState] = useState('loading')
	const [verifyStatus, setVerifyStatus] = useState({})
	const [scheduleTimestamp, setScheduleTimestamp] = useState('')
	const {
		formState: { errors },
		register,
		handleSubmit,
		setError,
		setValue,
	} = useForm()

	useEffect(() => {
		if (router.isReady && store.currentUser) {
			setProfile(`${window.location.origin}/${store.currentUser}`)
			checkStatusVerification()
			checkQuota()
			checkFinishSchedule()
		} else if (store.initialized && store.currentUser === null) {
			router.push('/login')
		}
	}, [store])

	useEffect(() => {
		register({ name: 'captchaToken' }, { required: true })
	})

	const checkQuota = async () => {
		try {
			const resp = await axios.get(`${process.env.V2_API_URL}/verifications/check-quota`, {
				headers: {
					authorization: await WalletHelper.authToken(),
				},
			})
			const data = resp.data.data
			setTotalCurrent(data.totalCurrent > data.totalQuota ? data.totalQuota : data.totalCurrent)
			setTotalQuota(data.totalQuota)

			const status = data.totalCurrent >= data.totalQuota ? false : true
			if (!status) {
				setIsDisable(true)
				setIsQuotaAvail(false)
			}
			return status
		} catch (err) {
			sentryCaptureException(err)
			const errMsg = 'SomethingWentWrong'
			toast.show({
				text: <div className="font-semibold text-center text-sm">{localeLn(errMsg)}</div>,
				type: 'error',
				duration: 2500,
			})
			return false
		}
	}

	const checkFinishSchedule = async () => {
		try {
			const resp = await axios.get(`${process.env.V2_API_URL}/verifications/scheduled-finish`, {
				headers: {
					authorization: await WalletHelper.authToken(),
				},
			})
			const data = resp.data.data
			setScheduleTimestamp(data.timestamp)
		} catch (err) {
			sentryCaptureException(err)
			const errMsg = 'SomethingWentWrong'
			toast.show({
				text: <div className="font-semibold text-center text-sm">{localeLn(errMsg)}</div>,
				type: 'error',
				duration: 2500,
			})
		}
	}

	const checkStatusVerification = async () => {
		try {
			const resp = await axios.get(
				`${process.env.V2_API_URL}/verifications?accountId=${store.currentUser}`,
				{
					headers: {
						authorization: await WalletHelper.authToken(),
					},
				}
			)
			const data = resp.data.data.results
			if (data.length > 0) {
				setVerifyStatus(data)
				setFormState('status')
			} else if (store.userProfile.isCreator) {
				setFormState('verified')
			} else {
				setFormState('form')
			}
		} catch (err) {
			sentryCaptureException(err)
			const errMsg = 'SomethingWentWrong'
			toast.show({
				text: <div className="font-semibold text-center text-sm">{localeLn(errMsg)}</div>,
				type: 'error',
				duration: 2500,
			})
		}
	}

	const _submit = async (data) => {
		setIsSubmitting(true)
		setIsDisable(true)

		if (data.instagram && checkSocialMediaUrl(data.instagram)) {
			setError('instagram', { type: 'invalid-url' }, { shouldFocus: true })
			setIsSubmitting(false)
			setIsDisable(false)
			return
		}

		if (data.twitter && checkSocialMediaUrl(data.twitter)) {
			setError('twitter', { type: 'invalid-url' }, { shouldFocus: true })
			setIsSubmitting(false)
			setIsDisable(false)
			return
		}

		const dataPost = {
			name: data.name,
			email: data.email,
			telegram_discord: data.telegramDiscord,
			paras_profile: profile,
			instagram: data.instagram,
			twitter: data.twitter,
			captcha_token: data.captchaToken,
		}

		try {
			await axios.post(`${process.env.V2_API_URL}/verifications`, dataPost, {
				headers: {
					authorization: await WalletHelper.authToken(),
				},
			})
			toast.show({
				text: (
					<div className="font-semibold text-center text-sm">
						{localeLn('success submit submission')}
					</div>
				),
				type: 'success',
				duration: 2500,
			})
			checkStatusVerification()
			setIsSubmitting(false)
			setIsDisable(false)
		} catch (err) {
			sentryCaptureException(err)
			const errMsg = err.response.data.message || 'SomethingWentWrong'
			toast.show({
				text: <div className="font-semibold text-center text-sm">{localeLn(errMsg)}</div>,
				type: 'error',
				duration: 2500,
			})
			setIsSubmitting(false)
			setIsDisable(false)
		}
	}

	const _goToProfile = async (e) => {
		e.preventDefault()
		router.push(`/${store.currentUser}`)
	}

	const _renderLoading = () => {
		return (
			<div className="max-w-4xl relative m-auto py-12 px-4">
				<div className="flex items-center justify-center h-64 text-gray-100">
					{localeLn('LoadingLoading')}
				</div>
			</div>
		)
	}

	const _renderForm = () => {
		return (
			<div className="max-w-4xl relative m-auto py-12 px-4">
				<h1 className="text-4xl font-bold text-gray-100 text-center">
					{localeLn('ParasArtistVerification')}
				</h1>
				<div className="mt-6 text-justify text-l text-gray-300">
					<p>{localeLn('TextFormParagraph1')}</p>
					<br></br>
					<p>{localeLn('TextFormParagraph2')}</p>
					<br></br>

					<ol className="list-decimal ml-6">
						<li>{localeLn('Step1')}</li>
						<li>{localeLn('Step2')}</li>
						<li>{localeLn('Step3')}</li>
						<li>{localeLn('Step4')}</li>
						<li>{localeLn('Step5')}</li>
						<li>{localeLn('Step6')}</li>
					</ol>
					<br></br>
					<p>
						{localeLn(
							`It’s also extremely important to remember that becoming verified artist does not grant you instant success. It’s a method to introduce yourself to a bigger community of Paras.`
						)}
					</p>
				</div>
				<form onSubmit={handleSubmit(_submit)}>
					<div className="mt-6">
						<label className="mb-1 block text-lg text-gray-50">{localeLn('Email')}</label>
						<input
							type="email"
							name="email"
							className="focus:border-gray-100"
							placeholder="Email"
							ref={register({
								required: true,
							})}
						/>
						<div className="mt-2 text-sm text-red-500">
							{errors.email?.type === 'required' && 'Email is required'}
						</div>
					</div>
					<div className="mt-6">
						<label className="mb-1 block text-lg text-gray-50">{localeLn('Name')}</label>
						<input
							type="text"
							name="name"
							className="focus:border-gray-100"
							placeholder="Name"
							ref={register({
								required: true,
							})}
						/>
						<div className="mt-2 text-sm text-red-500">
							{errors.name?.type === 'required' && 'Name is required'}
						</div>
					</div>
					<div className="mt-6">
						<label className="mb-1 block text-lg text-gray-50">
							{localeLn('Telegram/Discord Account')}
						</label>
						<input
							type="text"
							name="telegramDiscord"
							className="focus:border-gray-100"
							placeholder="Telegram/Discord Account"
							ref={register({
								required: true,
							})}
						/>
						<div className="mt-2 text-sm text-red-500">
							{errors.telegramDiscord?.type === 'required' &&
								'Telegram/Discord Account is required'}
						</div>
					</div>
					<div className="mt-6">
						<label className="mb-1 block text-lg text-gray-50">{localeLn('Paras Profile')}</label>
						<input
							type="text"
							name="paras-profile"
							value={profile}
							disabled
							className="bg-gray-400"
							placeholder="Paras Profile"
						/>
					</div>
					<div className="mt-6">
						<label className="mb-1 block text-lg text-gray-50">{localeLn('Instagram')}</label>
						<input
							type="text"
							name="instagram"
							className="focus:border-gray-100"
							placeholder="Instagram"
							ref={register({
								required: true,
							})}
						/>
						<div className="mt-2 text-sm text-red-500">
							{errors.instagram?.type === 'required' && 'Instagram is required'}
							{errors.instagram?.type === 'invalid-url' &&
								localeLn('Please enter only your instagram username')}
						</div>
					</div>
					<div className="mt-6">
						<label className="mb-1 block text-lg text-gray-50">{localeLn('Twitter')}</label>
						<input
							type="text"
							name="twitter"
							className="focus:border-gray-100"
							placeholder="Twitter"
							ref={register({
								required: true,
							})}
						/>
						<div className="mt-2 text-sm text-red-500">
							{errors.twitter?.type === 'required' && 'Twitter is required'}
							{errors.twitter?.type === 'invalid-url' &&
								localeLn('Please enter only your twitter username')}
						</div>
					</div>
					<div className="mt-6">
						<ReCAPTCHA
							size="normal"
							ref={recaptchaRef}
							sitekey={process.env.RECAPTCHA_SITE_KEY}
							onChange={(token) => setValue('captchaToken', token)}
						/>
						<div className="mt-2 text-sm text-red-500">
							{errors.captchaToken?.type === 'required' && 'Captcha is required'}
						</div>
					</div>
					{!isQuotaAvail && (
						<p className="mt-6 block text-lg text-red-600">
							<strong>Quota:</strong> {totalCurrent} / {totalQuota} Quota full. Please wait for the
							next cycle {scheduleTimestamp !== '' && `at ${scheduleTimestamp} UTC+7`}
						</p>
					)}
					{isQuotaAvail && (
						<p className="mt-6 block text-lg text-gray-50">
							<strong>Quota:</strong> {totalCurrent} / {totalQuota}
						</p>
					)}
					<div className="mt-6">
						<button
							disabled={isDisable}
							className="w-full outline-none h-12 mt-4 rounded-md bg-transparent text-sm font-semibold border-2 px-4 py-2 border-primary bg-primary text-gray-100"
							type="submit"
						>
							{!isSubmitting ? 'Submit' : 'Submiting...'}
						</button>
					</div>
				</form>
			</div>
		)
	}

	const _renderCheckStat = () => {
		const dataStatus = verifyStatus[0]
		const submittedDate = dataStatus?.createdAt
			? new Date(dataStatus?.createdAt).toISOString().substring(0, 10)
			: ''
		const inReviewDate = dataStatus?.reviewedAt
			? new Date(dataStatus?.reviewedAt).toISOString().substring(0, 10)
			: ''
		const resultDate = dataStatus?.resultAt
			? new Date(dataStatus?.resultAt).toISOString().substring(0, 10)
			: ''

		return (
			<div className="max-w-4xl relative m-auto py-12 px-4">
				<h1 className="text-4xl font-bold text-gray-100 text-center">
					{localeLn('VerificationStatus')}
				</h1>
				<div className="mt-6 text-justify text-l text-gray-300 mb-20">
					<p>{localeLn('TextStatusParagraph1')}</p>
					<br></br>
					<p>{localeLn('TextStatusParagraph2')}</p>
					{resultDate && dataStatus.status === 'verified' && (
						<div className="text-center ">
							<h3 className="text-2xl font-bold text-green-500 mt-20">
								{localeLn('YouAreVerified')}
							</h3>
						</div>
					)}
				</div>
				<div className="p-5">
					<div className="mx-4 p-4">
						<div className="flex items-center">
							<div className="flex items-center text-white relative">
								<div className="absolute -ml-10 text-center mb-20 w-32 text-xs font-medium text-teal-600">
									<p className="text-sm text-gray-50">{submittedDate}</p>
									<br></br>
								</div>
								{submittedDate != '' ? (
									<div className="rounded-full transition duration-500 ease-in-out h-12 w-12 py-3 border-2 border-teal-600 bg-blue-700"></div>
								) : (
									<div className="rounded-full transition duration-500 ease-in-out h-12 w-12 py-3 border-2 border-teal-600  bg-gray-300"></div>
								)}
								<div className="absolute top-0 -ml-10 text-center mt-16 w-32 text-xs font-medium text-teal-600">
									<p className="text-lg text-gray-50">{localeLn('Submitted')}</p>
									<p className="mt-2 text-md text-gray-50">{localeLn('SubmittedDesc')}</p>
								</div>
							</div>
							<div className="flex-auto border-t-2 transition duration-500 ease-in-out border-teal-600"></div>
							<div className="flex items-center text-white relative">
								<div className="absolute -ml-10 text-center mb-20 w-32 text-xs font-medium text-teal-600">
									<p className="text-sm text-gray-50">{inReviewDate}</p>
									<br></br>
								</div>
								{inReviewDate != '' ? (
									<div className="rounded-full transition duration-500 ease-in-out h-12 w-12 py-3 border-2 border-teal-600 bg-blue-700"></div>
								) : (
									<div className="rounded-full transition duration-500 ease-in-out h-12 w-12 py-3 border-2 border-teal-600  bg-gray-300"></div>
								)}
								<div className="absolute top-0 -ml-10 text-center mt-16 w-32 text-xs font-medium text-teal-600">
									<p className="text-lg text-gray-50">{localeLn('InReview')}</p>
									<p className="mt-2 text-md text-gray-50">{localeLn('InReviewDesc')}</p>
								</div>
							</div>
							<div className="flex-auto border-t-2 transition duration-500 ease-in-out border-gray-300"></div>
							<div className="flex items-center text-gray-500 relative">
								<div className="absolute -ml-10 text-center mb-20 w-32 text-xs font-medium text-teal-600">
									<p className="text-sm text-gray-50">{resultDate}</p>
									<br></br>
								</div>
								{resultDate != '' ? (
									<div className="rounded-full transition duration-500 ease-in-out h-12 w-12 py-3 border-2 border-teal-600 bg-blue-700"></div>
								) : (
									<div className="rounded-full transition duration-500 ease-in-out h-12 w-12 py-3 border-2 border-teal-600  bg-gray-300"></div>
								)}
								<div className="absolute top-0 -ml-10 text-center mt-16 w-32 text-xs font-medium text-gray-500">
									<p className="text-lg text-gray-50">{localeLn('Result')}</p>
									<p className="mt-2 text-md text-gray-50">{localeLn('ResultDesc')}</p>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div className="p-5 mt-20">
					<center>
						<button
							className="w-6/12  outline-none h-12 mt-4 rounded-md bg-transparent text-sm font-semibold border-2 px-4 py-2 border-primary bg-primary text-gray-100"
							onClick={_goToProfile}
						>
							Profile
						</button>
					</center>
				</div>
			</div>
		)
	}

	const _renderVerified = () => {
		const verifiedDate = store.userProfile?.verifiedAt
			? new Date(store.userProfile?.verifiedAt).toISOString().substring(0, 10)
			: ''
		const urlShare = `${process.env.BASE_URL}/${store.currentUser}/creation`

		return (
			<div className="max-w-4xl relative m-auto py-12 px-4">
				<h1 className="text-4xl font-bold text-gray-100 text-center">
					{localeLn('VerificationStatus')}
				</h1>
				<div className="mt-6 text-justify text-l text-gray-300 mb-12">
					<div className=" text-center ">
						<h3 className="text-2xl font-bold text-green-500 mt-20">
							{localeLn('YouAreVerified')}
						</h3>
						<p className="mt-3">{verifiedDate && `${localeLn('Since')} ${verifiedDate}`}</p>
						<p className="mt-16 mb-3">{localeLn('ShareNow')}</p>
						<div className="flex flex-row items-center justify-center gap-3">
							<TwitterShareButton
								title={`Hey I'm verified creator on Paras. Check out my creation only on @ParasHQ\n\n#paras #cryptoart #digitalart #tradingcards`}
								url={urlShare}
								className="flex text-white"
							>
								<TwitterIcon size={24} round />
								<p className="ml-2">Twitter</p>
							</TwitterShareButton>
							<FacebookShareButton url={urlShare} className="flex text-white">
								<FacebookIcon size={24} round />
								<p className="ml-2">Facebook</p>
							</FacebookShareButton>
							<TelegramShareButton url={urlShare} className="flex text-white">
								<TelegramIcon size={24} round />
								<p className="ml-2">Telegram</p>
							</TelegramShareButton>
						</div>
					</div>
				</div>
				<center>
					<button
						className="w-6/12  outline-none h-12 mt-4 rounded-md bg-transparent text-sm font-semibold border-2 px-4 py-2 border-primary bg-primary text-gray-100"
						onClick={_goToProfile}
					>
						Profile
					</button>
				</center>
			</div>
		)
	}

	return (
		<div className="min-h-screen bg-black">
			<div
				className="fixed inset-0 opacity-75"
				style={{
					zIndex: 0,
					backgroundImage: `url('/bg.jpg')`,
					backgroundRepeat: 'no-repeat',
					backgroundSize: 'cover',
				}}
			></div>
			<Head>
				<title>{localeLn('ArtistVerification')}</title>
				<meta
					name="description"
					content="Create, Trade, and Collect Digital Collectibles. All-in-one social NFT marketplace for creators and collectors. Discover the best and latest NFT collectibles on NEAR."
				/>

				<meta
					name="twitter:title"
					content="Paras - NFT Marketplace for Digital Collectibles on NEAR"
				/>
				<meta name="twitter:card" content="summary_large_image" />
				<meta name="twitter:site" content="@ParasHQ" />
				<meta name="twitter:url" content="https://paras.id" />
				<meta
					name="twitter:description"
					content="Create, Trade, and Collect Digital Collectibles. All-in-one social NFT marketplace for creators and collectors. Discover the best and latest NFT collectibles on NEAR."
				/>
				<meta
					name="twitter:image"
					content="https://paras-media.s3-ap-southeast-1.amazonaws.com/paras-v2-twitter-card-large.png"
				/>
				<meta property="og:type" content="website" />
				<meta
					property="og:title"
					content="Paras - NFT Marketplace for Digital Collectibles on NEAR"
				/>
				<meta
					property="og:site_name"
					content="Paras - NFT Marketplace for Digital Collectibles on NEAR"
				/>
				<meta
					property="og:description"
					content="Create, Trade, and Collect Digital Collectibles. All-in-one social NFT marketplace for creators and collectors. Discover the best and latest NFT collectibles on NEAR."
				/>
				<meta property="og:url" content="https://paras.id" />
				<meta
					property="og:image"
					content="https://paras-media.s3-ap-southeast-1.amazonaws.com/paras-v2-twitter-card-large.png"
				/>
			</Head>
			<Nav />
			{formState === 'form' && _renderForm()}
			{formState === 'status' && _renderCheckStat()}
			{formState === 'verified' && _renderVerified()}
			{formState === 'loading' && _renderLoading()}
			<Footer />
		</div>
	)
}
Example #27
Source File: ActivityDetail.js    From paras-landing with GNU General Public License v3.0 4 votes vote down vote up
ActivityDetail = ({ activity, index, isLoading }) => {
	const { localeLn } = useIntl()
	const [showModal, setShowModal] = useState(null)
	const [isCopied, setIsCopied] = useState(false)
	const [showDetailActivity, setShowDetailActivity] = useState(-1)

	const shareLink = `${process.env.BASE_URL}/activity/${activity._id}`
	const [isFlipped, setIsFlipped] = useState(true)
	const [localTradedToken, setLocalTradedToken] = useState(null)
	const topCardPositionStyle = `-top-10 left-0 md:left-0 z-30`
	const bottomCardPositionStyle = `-top-8 left-2 md:left-2 z-20`
	const isTradeActivity = activity?.type?.includes('trade')
	const router = useRouter()
	const store = useStore()
	const currentUser = useStore((state) => state.currentUser)

	const { token: localToken, mutate } = useTokenOrTokenSeries({
		key: `${activity.contract_id}::${
			activity.token_series_id ? activity.token_series_id : activity.token_id.split(':')[0]
		}${activity.token_id ? `/${activity.token_id}` : ''}`,
		params: {
			lookup_likes: true,
			liked_by: currentUser,
		},
	})

	useNonInitialEffect(() => {
		if (currentUser) {
			mutate()
		}
	}, [currentUser])

	const HEADERS = [
		{
			id: 'title',
			title: 'Title',
			className: `w-3/12 p-3 h-full`,
		},
		{
			id: 'price',
			title: 'Price',
			className: `items-center text-center w-2/12 p-3 h-full`,
		},
		{
			id: 'from',
			title: 'From',
			className: `items-center w-2/12 p-3 h-full`,
		},
		{
			id: 'to',
			title: 'To',
			className: `items-center w-2/12 p-3 h-full`,
		},
		{
			id: 'time',
			title: 'Time',
			className: `w-4/12 md:w-2/12 pr-2 md:p-0 lg:p-3 text-center md:h-full`,
		},
		{
			id: 'type',
			title: 'Type',
			className: `w-2/12 p-3 h-full`,
		},
	]

	const parseType = (creator, price, from, to, type, isOffer = null) => {
		if (
			(type === 'nft_transfer' && price && from && to) ||
			(type === 'resolve_purchase' && price)
		) {
			if (isOffer) {
				return 'Accept'
			}
			return 'Sold'
		} else if (type === 'nft_transfer' && from === null) {
			return 'Minted'
		}

		if (type === 'nft_transfer' && to === null) {
			return 'Burned'
		}

		if (type === 'nft_transfer' && (!price || to === creator)) {
			return 'Transfer'
		}

		if (type === 'nft_set_series_price') {
			return 'Set Price'
		}

		if (type === 'notification_add_offer' || type === 'add_offer') {
			return 'Offer'
		}

		if (type === 'delete_offer') {
			return 'Delete Offer'
		}

		if (type === 'notification_category_accepted' || type === 'notification_category_rejected') {
			return 'Submission'
		}

		if (type === 'nft_create_series') {
			return 'Creation'
		}

		if (
			(type === 'add_market_data' || type === 'update_market_data') &&
			!activity.msg.params.is_auction
		) {
			return 'Listing'
		}

		if (type === 'delete_market_data') {
			return 'Remove Sale'
		}

		if (type === 'add_trade') {
			return 'Add Trade'
		}

		if (type === 'delete_trade') {
			return 'Delete Trade'
		}

		if (type === 'accept_trade') {
			return 'Accept Trade'
		}

		if (type === 'nft_decrease_series_copies') {
			return 'Decrease Copy'
		}

		if (type === 'accept_trade') {
			return 'Accept Trade'
		}

		if (type === 'nft_decrease_series_copies') {
			return 'Decrease Copy'
		}

		if (type === 'add_market_data' || activity.msg.params.is_auction) {
			return 'Auction'
		}

		if (type === 'add_bid') {
			return 'Bid'
		}

		if (type === 'cancel_bid') {
			return 'Cancel Bid'
		}

		return type
	}

	const fetchTradeToken = async () => {
		const params = {
			token_id: activity.msg.params.buyer_token_id,
			contract_id: activity.msg.params.buyer_nft_contract_id,
			__limit: 1,
		}
		const resp = await cachios.get(`${process.env.V2_API_URL}/token`, {
			params: params,
			ttl: 30,
		})
		setLocalTradedToken(resp.data.data.results[0])
	}

	useEffect(() => {
		if (activity?.type?.includes('trade')) {
			fetchTradeToken()
		}
	}, [])

	const handleAfterCopy = () => {
		setIsCopied(true)

		setTimeout(() => {
			setShowModal(false)
			setIsCopied(false)
		}, 1500)
	}

	const showDetail = (index) => {
		if (showDetailActivity == index) setShowDetailActivity(-1)
		else setShowDetailActivity(index)
	}

	if (activity.type === 'resolve_purchase_fail' || activity.type === 'notification_add_offer') {
		return null
	}

	return (
		<Fragment>
			<TokenSeriesDetailModal tokens={[localToken]} />
			<TokenDetailModal tokens={[localToken]} />
			{showModal === 'options' && (
				<Modal close={() => setShowModal('')}>
					<div className="max-w-sm w-full px-4 py-2 bg-gray-100 m-auto rounded-md text-black">
						<CopyLink link={shareLink} afterCopy={handleAfterCopy}>
							<div className="py-2 cursor-pointer flex items-center">
								<svg
									className="rounded-md"
									width="24"
									height="24"
									viewBox="0 0 24 24"
									fill="none"
									xmlns="http://www.w3.org/2000/svg"
								>
									<rect width="24" height="24" fill="#11111F" />
									<path
										fillRule="evenodd"
										clipRule="evenodd"
										d="M12.7147 14.4874L13.7399 15.5126L11.6894 17.5631C10.2738 18.9787 7.97871 18.9787 6.56313 17.5631C5.14755 16.1476 5.14755 13.8524 6.56313 12.4369L8.61364 10.3864L9.63889 11.4116L7.58839 13.4621C6.73904 14.3115 6.73904 15.6885 7.58839 16.5379C8.43773 17.3872 9.8148 17.3872 10.6641 16.5379L12.7147 14.4874ZM11.6894 9.36136L10.6641 8.3361L12.7146 6.2856C14.1302 4.87002 16.4253 4.87002 17.8409 6.2856C19.2565 7.70118 19.2565 9.99628 17.8409 11.4119L15.7904 13.4624L14.7651 12.4371L16.8156 10.3866C17.665 9.53726 17.665 8.1602 16.8156 7.31085C15.9663 6.4615 14.5892 6.4615 13.7399 7.31085L11.6894 9.36136ZM9.12499 13.9751L10.1502 15.0004L15.2765 9.87409L14.2513 8.84883L9.12499 13.9751Z"
										fill="white"
									/>
								</svg>
								<p className="pl-2">{isCopied ? `Copied` : `Copy Link`}</p>
							</div>
						</CopyLink>
						<div className="py-2 cursor-pointer">
							<TwitterShareButton
								title={`${descriptionMaker(
									activity,
									localToken,
									localTradedToken
								)} via @ParasHQ\n\n#paras #cryptoart #digitalart #tradingcards`}
								url={shareLink}
								className="flex items-center w-full"
							>
								<TwitterIcon
									size={24}
									className="rounded-md"
									bgStyle={{
										fill: '#11111F',
									}}
								></TwitterIcon>
								<p className="pl-2">{localeLn('Twitter')}</p>
							</TwitterShareButton>
						</div>
						<div className="py-2 cursor-pointer">
							<FacebookShareButton url={shareLink} className="flex items-center w-full">
								<FacebookIcon
									size={24}
									className="rounded-md"
									bgStyle={{
										fill: '#11111F',
									}}
								></FacebookIcon>
								<p className="pl-2">{localeLn('Facebook')}</p>
							</FacebookShareButton>
						</div>
					</div>
				</Modal>
			)}
			<div key={activity._id} className="text-white">
				<div className="w-full">
					<div className="hidden md:block">
						<div className="flex flex-row w-full text-gray-300 hover:opacity-75 items-center">
							{index === 0 &&
								HEADERS.map((d, index) => {
									return (
										<div key={d.id} className={`${HEADERS[index].className} h-full`}>
											<span className="capitalize">{localeLn(d.title)}</span>
										</div>
									)
								})}
						</div>
					</div>

					{isLoading ? (
						<ActivityListLoader />
					) : (
						<div className="flex flex-row items-center justify-between w-full cursor-pointer sm:cursor-default md:inline-flex md:w-full md:h-19 md:hover:bg-gray-800 md:hover:bg-opacity-50">
							<div className="flex items-center md:cursor-pointer md:w-3/12">
								<div className="w-8 my-2 mr-8 ml-2 bg-transparent rounded-lg z-20 relative">
									<div
										className={`${
											isTradeActivity
												? `absolute w-14 cursor-pointer ${
														isFlipped
															? `transition-all ${topCardPositionStyle}`
															: `transition-all ${bottomCardPositionStyle}`
												  }`
												: `w-16 h-16 mx-auto`
										}`}
										onClick={() => isTradeActivity && setIsFlipped(!isFlipped)}
									>
										<Link
											href={{
												pathname: router.pathname,
												query: {
													...router.query,
													...(activity.token_id
														? { tokenId: localToken?.token_id }
														: { tokenSeriesId: localToken?.token_series_id }),
													contractId: localToken?.contract_id,
												},
											}}
											as={`/token/${localToken?.contract_id}::${localToken?.token_series_id}${
												activity.token_id ? `/${localToken?.token_id}` : ''
											}`}
											scroll={false}
											shallow
										>
											<a onClick={(e) => isTradeActivity && e.preventDefault()}>
												<Media
													className="rounded-lg overflow-hidden"
													url={parseImgUrl(localToken?.metadata.media, null, {
														width: `300`,
														useOriginal: process.env.APP_ENV === 'production' ? false : true,
														isMediaCdn: localToken?.isMediaCdn,
													})}
													videoControls={false}
													videoLoop={true}
													videoMuted={true}
													autoPlay={false}
													playVideoButton={false}
												/>
											</a>
										</Link>
									</div>

									{isTradeActivity && (
										<div
											className={`${
												isTradeActivity
													? `absolute w-14 cursor-pointer ${
															!isFlipped
																? `transition-all ${topCardPositionStyle}`
																: `transition-all ${bottomCardPositionStyle}`
													  }`
													: `w-16 h-16 mx-auto`
											}`}
											onClick={() => isTradeActivity && setIsFlipped(!isFlipped)}
										>
											<Link
												href={{
													pathname: router.pathname,
													query: {
														...router.query,
														...(activity.token_id
															? { tokenId: localToken?.token_id }
															: { tokenSeriesId: localToken?.token_series_id }),
														contractId: localToken?.contract_id,
													},
												}}
												as={`/token/${localToken?.contract_id}::${localToken?.token_series_id}${
													activity.token_id ? `/${localToken?.token_id}` : ''
												}`}
												scroll={false}
												shallow
											>
												<a onClick={(e) => isTradeActivity && e.preventDefault()}>
													<Media
														className="rounded-lg overflow-hidden object-cover"
														url={parseImgUrl(localTradedToken?.metadata.media, null, {
															width: `300`,
															useOriginal: process.env.APP_ENV === 'production' ? false : true,
															isMediaCdn: localTradedToken?.isMediaCdn,
														})}
														videoControls={false}
														videoLoop={true}
														videoMuted={true}
														autoPlay={false}
														playVideoButton={false}
													/>
												</a>
											</Link>
										</div>
									)}
								</div>
								<div className="pl-4 overflow-hidden cursor-pointer w-40">
									<Link
										href={`/collection/${
											localToken?.metadata?.collection_id || localToken?.contract_id
										}`}
									>
										<a>
											<p className="opacity-80 truncate text-xs py-1 font-thin border-b-2 border-transparent hover:opacity-50 cursor-pointer">
												{localToken?.metadata?.collection_id
													? isTradeActivity
														? localTradedToken?.metadata?.collection
														: localToken?.metadata.collection
													: isTradeActivity
													? localTradedToken?.metadata?.contract_id
													: localToken?.contract_id}
											</p>
										</a>
									</Link>
									<Link
										href={{
											pathname: router.pathname,
											query: {
												...router.query,
												...(activity.token_id
													? { tokenId: localToken?.token_id }
													: { tokenSeriesId: localToken?.token_series_id }),
												contractId: localToken?.contract_id,
											},
										}}
										as={`/token/${localToken?.contract_id}::${localToken?.token_series_id}${
											activity.token_id ? `/${localToken?.token_id}` : ''
										}`}
										scroll={false}
										shallow
									>
										<a className="font-semibold z-20 text-sm md:text-md hover:text-gray-300">
											{prettyTruncate(localToken?.metadata.title, 25)}
										</a>
									</Link>
									<Link href={`/token/${activity.contract_id}::${activity.token_series_id}`}>
										<p className="w-min md:hidden font-semibold truncate z-20">
											{activity.msg.params.price !== null
												? `${prettyBalance(
														activity.msg.params.price || activity.msg.params.amount,
														24,
														4
												  )} Ⓝ `
												: '---'}
										</p>
									</Link>
								</div>
							</div>
							<div
								className={`${HEADERS[1].className} hidden md:flex md:text-sm lg:text-base font-bold justify-center`}
							>
								{activity.msg.params.price !== null
									? `${prettyBalance(
											activity.msg.params.price || activity.msg.params.amount,
											24,
											4
									  )} Ⓝ `
									: '---'}
							</div>
							<div
								className={`${HEADERS[2].className} hidden md:flex md:text-sm lg:text-base justify-start`}
							>
								<Link href={`/${activity.from}`}>
									<a className="font-thin border-b-2 border-transparent hover:border-gray-100 cursor-pointer">
										{activity.from ? prettyTruncate(activity.from, 12, 'address') : '---'}
									</a>
								</Link>
							</div>
							<div
								className={`${HEADERS[3].className} hidden md:flex md:text-sm lg:text-base justify-start`}
							>
								<Link href={`/${activity.to}`}>
									<a className="font-thin border-b-2 border-transparent hover:border-gray-100 cursor-pointer">
										{activity.to ? prettyTruncate(activity.to, 12, 'address') : '---'}
									</a>
								</Link>
							</div>
							<div
								className={`${HEADERS[4].className} text-xs text-right sm:text-base md:text-sm font-thin`}
							>
								<div className="flex flex-col md:flex-col justify-center items-end md:items-center">
									<div className="flex flex-col relative top-1 items-center justify-center pb-1 md:hidden">
										<div className="font-bold text-gray-300">
											{parseType(
												activity.creator_id,
												activity.price,
												activity.from,
												activity.to,
												activity.type
											)}
										</div>
									</div>
									<div className="hidden md:flex md:flex-row text-gray-50 opacity-50">
										{timeAgo.format(
											new Date(activity.issued_at ? activity.issued_at : 1636197684986)
										)}
									</div>
									<div className="flex flex-row md:flex-row mt-1 text-gray-50 opacity-50">
										<div
											onClick={() => setShowModal('options')}
											className="cursor-pointer w-8 h-4 md:h-8 rounded-full transition-all duration-200 hover:bg-dark-primary-4 flex items-center justify-end md:justify-center"
										>
											<svg
												width="18"
												height="18"
												viewBox="0 0 24 24"
												fill="none"
												xmlns="http://www.w3.org/2000/svg"
											>
												<path
													fillRule="evenodd"
													clipRule="evenodd"
													d="M12 2.79623V8.02302C5.45134 8.33141 2 11.7345 2 18V20.4142L3.70711 18.7071C5.95393 16.4603 8.69021 15.5189 12 15.8718V21.2038L22.5186 12L12 2.79623ZM14 10V7.20377L19.4814 12L14 16.7962V14.1529L13.1644 14.0136C9.74982 13.4445 6.74443 14.0145 4.20125 15.7165C4.94953 11.851 7.79936 10 13 10H14Z"
													fill="white"
												/>
											</svg>
										</div>
										{SHOW_TX_HASH_LINK && activity.transaction_hash && (
											<a
												href={`https://${
													process.env.APP_ENV === 'production' ? `` : `testnet.`
												}nearblocks.io/txns/${activity.transaction_hash}${
													activity.msg?.receipt_id && `#${activity.msg?.receipt_id}`
												}`}
												target={`_blank`}
											>
												<div className="w-8 h-4 md:h-8 rounded-full transition-all duration-200 hover:bg-dark-primary-4 flex items-center justify-end md:justify-center">
													<IconShareActivity size={18} />
												</div>
											</a>
										)}
									</div>
									<div
										className="flex md:hidden flex-row text-right items-center mt-2 text-gray-50 opacity-50"
										onClick={() => showDetail(index)}
									>
										{timeAgo.format(
											new Date(activity.issued_at ? activity.issued_at : 1636197684986)
										)}
										<IconTriangle size={10} />
									</div>
								</div>
							</div>
							<div
								className={`${HEADERS[4].className} font-thin hidden md:flex md:text-sm lg:text-base justify-start`}
							>
								{parseType(
									activity.creator_id,
									activity.price,
									activity.from,
									activity.to,
									activity.type
								)}
							</div>
						</div>
					)}
				</div>

				{showDetailActivity == index && (
					<div
						key={activity._id}
						className="flex order-5 w-full justify-between items-center my-2 py-2 border-t-2 border-b-2 border-opacity-10 border-white text-xs md:hidden"
					>
						<div className="flex flex-col flex-shrink text-center w-1/2">
							<p className="font-thin text-white text-opacity-50 pb-2">From</p>
							<Link href={`/${activity.from}`}>
								<p className="font-bold cursor-pointer">
									{activity.from ? prettyTruncate(activity.from, 12, 'address') : '---'}
								</p>
							</Link>
						</div>
						<div className="flex flex-col flex-shrink text-center w-1/2">
							<p className="font-thin text-white text-opacity-50 pb-2">To</p>
							<Link href={`/${activity.to}`}>
								<p className="font-bold cursor-pointer">
									{activity.to ? prettyTruncate(activity.to, 12, 'address') : '---'}
								</p>
							</Link>
						</div>
						<div className="flex flex-col flex-shrink text-center w-1/2">
							<p className="font-thin text-white text-opacity-50 pb-2">Usd Price</p>
							<p className="font-bold">
								{activity.price
									? store.nearUsdPrice !== 0 && (
											<>
												$
												{prettyBalance(
													Number(store.nearUsdPrice * formatNearAmount(activity.msg.params.price))
														.toPrecision(4)
														.toString(),
													0,
													6
												)}
											</>
									  )
									: '---'}
							</p>
						</div>
					</div>
				)}
			</div>
		</Fragment>
	)
}
Example #28
Source File: ShareButton.js    From warsinhk with MIT License 4 votes vote down vote up
function ShareButton(props) {
  const [anchorEl, setAnchorEl] = React.useState(null)
  const { site } = useStaticQuery(
    graphql`
      query {
        site {
          siteMetadata {
            siteUrl
          }
        }
      }
    `
  )

  function getPageUrl() {
    let url = `${site.siteMetadata.siteUrl}${fullPath}`

    if (props.caseId) {
      url = `${site.siteMetadata.siteUrl}${fullPath}/${props.caseId}`
    }

    if (!isSSR()) {
      url = url + decodeURIComponent(window.location.hash)
    }

    return url
  }

  function handleShareButtonClick(event) {
    if (!isSSR() && isWebShareAPISupported()) {
      const data = getWebShareData(getPageUrl())
      if (navigator.canShare(data)) {
        navigator.share(data).then(() => {
          trackCustomEvent({
            category: "general",
            action: "click",
            label: "share",
          })
        })

        return
      }
    }

    setAnchorEl(event.currentTarget)
  }

  function handleShareButtonClose(media) {
    setAnchorEl(null)
    if (typeof media === "string") {
      trackCustomEvent({
        category: "general",
        action: "click",
        label: `share_${media}`,
      })
    }
  }
  const { pathname: fullPath } = useLocation()

  const url = getPageUrl()

  return (
    <>
      <StyledIconButton
        color="inherit"
        aria-label="Share"
        aria-controls="share-menu"
        aria-haspopup="true"
        onClick={handleShareButtonClick}
      >
        <ShareIcon />
      </StyledIconButton>
      <Menu
        id="share-menu"
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClose={handleShareButtonClose}
      >
        <MenuItem onClick={() => handleShareButtonClose("facebook")}>
          <FacebookShareButton
            url={getShareUrl(url, "facebook")}
            children={<FacebookIcon size={32} round={true} />}
          />
        </MenuItem>
        <MenuItem onClick={() => handleShareButtonClose("telegram")}>
          <TelegramShareButton
            url={getShareUrl(url, "telegram")}
            children={<TelegramIcon size={32} round={true} />}
          />
        </MenuItem>
        <MenuItem onClick={() => handleShareButtonClose("whatsapp")}>
          <WhatsappShareButton
            url={getShareUrl(url, "whatsapp")}
            children={<WhatsappIcon size={32} round={true} />}
          />
        </MenuItem>
        <MenuItem onClick={() => handleShareButtonClose("twitter")}>
          <TwitterShareButton
            url={getShareUrl(url, "twitter")}
            children={<TwitterIcon size={32} round={true} />}
          />
        </MenuItem>
        <MenuItem onClick={() => handleShareButtonClose("link")}>
          <StyledCopyIcon
            onClick={() => {
              navigator.clipboard.writeText(url)
            }}
          />
        </MenuItem>
      </Menu>
    </>
  )
}
Example #29
Source File: SuccessTransactionModal.js    From paras-landing with GNU General Public License v3.0 4 votes vote down vote up
SuccessTransactionModal = () => {
	const [showModal, setShowModal] = useState(false)
	const [token, setToken] = useState(null)
	const [txDetail, setTxDetail] = useState(null)
	const { currentUser, transactionRes, setTransactionRes } = useStore()
	const router = useRouter()
	const toast = useToast()

	useEffect(() => {
		const checkTxStatus = async () => {
			const txHash = router.query.transactionHashes.split(',')
			const txStatus = await near.getTransactionStatus({
				accountId: near.currentUser.accountId,
				txHash: txHash[txHash.length - 1],
			})
			if (window.sessionStorage.getItem('categoryToken')) {
				await submitCategoryCard(txStatus)
			}
			await processTransaction(txStatus)
		}

		if (currentUser && router.query.transactionHashes) {
			checkTxStatus()
		}
	}, [currentUser, router.query.transactionHashes])

	useEffect(() => {
		if (transactionRes) {
			const txLast = transactionRes[transactionRes.length - 1]
			if (txLast) {
				processTransaction(txLast)
			} else if (transactionRes.error) {
				processTransactionError(transactionRes.error.kind.ExecutionError)
			}
		}
	}, [transactionRes])

	const processTransactionError = (err) => {
		toast.show({
			text: <div className="font-semibold text-center text-sm">{err}</div>,
			type: 'error',
			duration: null,
		})
	}

	const processTransaction = async (txStatus) => {
		if (txStatus?.status?.SuccessValue !== undefined) {
			const { receipts_outcome } = txStatus
			const { actions, receiver_id } = txStatus.transaction

			for (const action of actions) {
				const { FunctionCall } = action
				const args = JSON.parse(decodeBase64(FunctionCall.args))

				if (FunctionCall.method_name === 'nft_buy') {
					const res = await axios.get(`${process.env.V2_API_URL}/token-series`, {
						params: {
							contract_id: receiver_id,
							token_series_id: args.token_series_id,
						},
					})
					setToken(res.data.data.results[0])
					setTxDetail({ ...FunctionCall, args })
					setShowModal(true)
				} else if (FunctionCall.method_name === 'buy') {
					const res = await axios.get(`${process.env.V2_API_URL}/token`, {
						params: {
							contract_id: args.nft_contract_id,
							token_id: args.token_id,
						},
					})
					setToken(res.data.data.results[0])
					setTxDetail({ ...FunctionCall, args })
					setShowModal(true)
				} else if (FunctionCall.method_name === 'add_offer') {
					const res = await axios.get(
						`${process.env.V2_API_URL}/${args.token_id ? 'token' : 'token-series'}`,
						{
							params: {
								contract_id: args.nft_contract_id,
								token_id: args.token_id,
								token_series_id: args.token_series_id,
							},
						}
					)
					setToken(res.data.data.results[0])
					setTxDetail({ ...FunctionCall, args })
					setShowModal(true)
				} else if (FunctionCall.method_name === 'add_bid') {
					const res = await axios.get(`${process.env.V2_API_URL}/token`, {
						params: {
							contract_id: args.nft_contract_id,
							token_id: args.token_id,
						},
					})
					setToken(res.data.data.results[0])
					setTxDetail({ ...FunctionCall, args })
					setShowModal(true)
				} else if (FunctionCall.method_name === 'cancel_bid') {
					const res = await axios.get(`${process.env.V2_API_URL}/token`, {
						params: {
							contract_id: args.nft_contract_id,
							token_id: args.token_id,
						},
					})
					setToken(res.data.data.results[0])
					setTxDetail({ ...FunctionCall, args })
					setShowModal(true)
				} else if (FunctionCall.method_name === 'accept_bid') {
					const res = await axios.get(`${process.env.V2_API_URL}/token`, {
						params: {
							contract_id: args.nft_contract_id,
							token_id: args.token_id,
						},
					})
					setToken(res.data.data.results[0])
					setTxDetail({ ...FunctionCall, args })
					setShowModal(true)
				} else if (FunctionCall.method_name === 'cancel_auction') {
					const res = await axios.get(`${process.env.V2_API_URL}/token`, {
						params: {
							contract_id: args.nft_contract_id,
							token_id: args.token_id,
						},
					})
					setToken(res.data.data.results[0])
					setTxDetail({ ...FunctionCall, args })
					setShowModal(true)
				} else if (FunctionCall.method_name === 'nft_set_series_price') {
					const res = await axios.get(`${process.env.V2_API_URL}/token-series`, {
						params: {
							contract_id: receiver_id,
							token_series_id: args.token_series_id,
						},
					})
					setToken(res.data.data.results[0])
					setTxDetail({ ...FunctionCall, args })
					setShowModal(true)
				} else if (FunctionCall.method_name === 'nft_approve') {
					const msgParse = JSON.parse(args?.msg)
					const res = await axios.get(`${process.env.V2_API_URL}/token`, {
						params: {
							contract_id:
								msgParse.market_type === 'accept_trade' ||
								msgParse.market_type === 'accept_trade_paras_series'
									? msgParse?.buyer_nft_contract_id
									: receiver_id,
							token_id:
								msgParse?.market_type === 'accept_trade' ||
								msgParse?.market_type === 'accept_trade_paras_series'
									? msgParse?.buyer_token_id
									: args.token_id,
						},
					})
					setToken(res.data.data.results[0])
					setTxDetail({ ...FunctionCall, args })
					setShowModal(true)
				} else if (FunctionCall.method_name === 'delete_market_data') {
					const res = await axios.get(`${process.env.V2_API_URL}/token`, {
						params: {
							contract_id: args.nft_contract_id,
							token_id: args.token_id,
						},
					})
					setToken(res.data.data.results[0])
					setTxDetail({ ...FunctionCall, args })
					setShowModal(true)
				} else if (FunctionCall.method_name === 'nft_create_series') {
					const logs = JSON.parse(receipts_outcome[0].outcome?.logs?.[0])
					const res = await axios.get(`${process.env.V2_API_URL}/token-series`, {
						params: {
							contract_id: receiver_id,
							token_series_id: logs.params.token_series_id,
						},
					})
					setToken(res.data.data.results[0])
					setTxDetail({ ...FunctionCall, args, logs })
					setShowModal(true)
				}
			}
		}
	}

	const onCloseModal = () => {
		const key = `${token.contract_id}::${token.token_series_id}${
			token.token_id ? `/${token.token_id}` : ''
		}`
		mutate(key)
		setShowModal(false)
		setToken(null)
		if (WalletHelper.activeWallet === walletType.sender) {
			setTransactionRes(null)
		} else {
			removeTxHash()
		}
	}

	const removeTxHash = () => {
		const query = router.query
		delete query.transactionHashes
		router.replace({ pathname: router.pathname, query }, undefined, { shallow: true })
	}

	const submitCategoryCard = async (res) => {
		const _categoryId = window.sessionStorage.getItem(`categoryToken`)
		const txLast = res
		const resFromTxLast = txLast.receipts_outcome[0].outcome.logs[0]
		const resOutcome = await JSON.parse(`${resFromTxLast}`)
		await retry(
			async () => {
				const res = await axios.post(
					`${process.env.V2_API_URL}/categories/tokens`,
					{
						account_id: currentUser,
						contract_id: txLast?.transaction?.receiver_id,
						token_series_id: resOutcome?.params?.token_series_id,
						category_id: _categoryId,
						storeToSheet: _categoryId === 'art-competition' ? `true` : `false`,
					},
					{
						headers: {
							authorization: await WalletHelper.authToken(),
						},
					}
				)
				if (res.status === 403 || res.status === 400) {
					sentryCaptureException(res.data?.message || `Token series still haven't exist`)
					return
				}
				window.sessionStorage.removeItem('categoryToken')
			},
			{
				retries: 20,
				factor: 2,
			}
		)
	}

	if (!showModal || !token) return null

	const tokenUrl = `${window.location.hostname}/token/${token.contract_id}::${
		token.token_series_id
	}${token.token_id ? `/${token.token_id}` : ''}`

	const explorerUrl = (txhash) =>
		getConfig(process.env.APP_ENV || 'development').explorerUrl + '/transactions/' + txhash

	const onClickSeeToken = () => {
		const url = `/token/${token.contract_id}::${token.token_series_id}${
			token.token_id ? `/${token.token_id}` : ''
		}${txDetail.method_name === 'add_offer' ? '?tab=offers' : ''}`
		router.push(url)
		onCloseModal()
	}

	const titleText = () => {
		if (txDetail.method_name === 'add_offer') {
			return 'Offer Success'
		} else if (txDetail.method_name === 'add_bid') {
			return 'Place Bid Success'
		} else if (txDetail.method_name === 'cancel_bid') {
			return 'Success Remove Bid'
		} else if (txDetail.method_name === 'accept_bid') {
			return 'Accept Bid Success'
		} else if (txDetail.method_name === 'nft_buy' || txDetail.method_name === 'buy') {
			return 'Purchase Success'
		} else if (txDetail.method_name === 'nft_set_series_price') {
			return 'Update Price Success'
		} else if (txDetail.method_name === 'nft_approve') {
			const msg = JSON.parse(txDetail.args.msg)
			if (msg.market_type === 'sale' && !msg.is_auction) {
				return 'Update Listing Success'
			} else if (msg.market_type === 'accept_offer') {
				return 'Accept Offer Success'
			} else if (msg.market_type === 'add_trade') {
				return 'Add Trade Success'
			} else if (msg.is_auction) {
				return 'Create Auction Success'
			} else if (
				msg.market_type === 'accept_trade' ||
				msg.market_type === 'accept_trade_paras_series'
			) {
				return 'Accept Trade Success'
			}
		} else if (txDetail.method_name === 'delete_market_data') {
			const args = txDetail.args
			if (args.is_auction) {
				return 'Remove Auction Success'
			}
			return 'Remove Listing Success'
		} else if (txDetail.method_name === 'nft_create_series') {
			return 'Create Card Success'
		} else {
			return 'Transaction Success'
		}
	}

	const descText = () => {
		if (txDetail.method_name === 'add_offer') {
			return (
				<>
					You successfully offer <b>{token.metadata.title}</b> for{' '}
					{formatNearAmount(txDetail.args.price)} Ⓝ
				</>
			)
		} else if (txDetail.method_name === 'add_bid') {
			return (
				<>
					You successfully bid of auction <b>{token.metadata.title}</b> for{' '}
					{prettyBalance(txDetail.args.amount, 24, 2)} Ⓝ
				</>
			)
		} else if (txDetail.method_name === 'cancel_bid') {
			return (
				<>
					You successfully remove bid auction <b>{token.metadata.title}</b> for{' '}
					{formatNearAmount(txDetail.args.amount)} Ⓝ
				</>
			)
		} else if (txDetail.method_name === 'accept_bid') {
			return (
				<>
					You successfully accept bid auction <b>{token.metadata.title}</b>
				</>
			)
		} else if (txDetail.method_name === 'cancel_auction') {
			return (
				<>
					You successfully remove auction <b>{token.metadata.title}</b>
				</>
			)
		} else if (txDetail.method_name === 'nft_buy' || txDetail.method_name === 'buy') {
			return (
				<>
					You successfully purchase <b>{token.metadata.title}</b>
				</>
			)
		} else if (txDetail.method_name === 'nft_set_series_price') {
			if (txDetail.args.price) {
				return (
					<>
						You successfully update <b>{token.metadata.title}</b> price to{' '}
						{formatNearAmount(txDetail.args.price)} Ⓝ
					</>
				)
			}
			return (
				<>
					You successfully remove the listing <b>{token.metadata.title}</b>
				</>
			)
		} else if (txDetail.method_name === 'nft_approve') {
			const msg = JSON.parse(txDetail.args.msg)
			if (msg.market_type === 'sale') {
				return (
					<>
						You successfully {msg.is_auction ? 'create auction' : 'update'}{' '}
						<b>{token.metadata.title}</b> with starting price {formatNearAmount(msg.price || 0)} Ⓝ
					</>
				)
			} else if (msg.market_type === 'accept_offer') {
				return (
					<>
						You successfully accept offer <b>{token.metadata.title}</b>
					</>
				)
			} else if (msg.market_type === 'add_trade') {
				return (
					<>
						You successfully trade your NFT <b>{token.metadata.title}</b>
					</>
				)
			} else if (
				msg.market_type === 'accept_trade' ||
				msg.market_type === 'accept_trade_paras_series'
			) {
				return (
					<>
						You successfully accept NFT <b>{token.metadata.title}</b>
					</>
				)
			}
		} else if (txDetail.method_name === 'delete_market_data') {
			return (
				<>
					You successfully remove the listing <b>{token.metadata.title}</b>
				</>
			)
		} else if (txDetail.method_name === 'nft_create_series') {
			return (
				<>
					You successfully create <b>{token.metadata.title}</b>
				</>
			)
		}
	}

	return (
		<Modal isShow={showModal} close={onCloseModal} className="p-8">
			<div className="max-w-sm w-full p-4 bg-gray-800 md:m-auto rounded-md relative">
				<div className="absolute right-0 top-0 pr-4 pt-4">
					<div className="cursor-pointer" onClick={onCloseModal}>
						<IconX />
					</div>
				</div>
				<div>
					<h1 className="text-2xl font-bold text-white tracking-tight">{titleText()}</h1>
					<p className="text-white mt-2">{descText()}</p>
					<div className="p-4">
						<div className="w-2/3 m-auto h-56">
							<Media
								className="rounded-lg overflow-hidden h-full w-full"
								url={token.metadata.media}
								videoControls={true}
								videoLoop={true}
								videoMuted={true}
								videoPadding={false}
							/>
						</div>
					</div>
					{router.query.transactionHashes && (
						<div className="p-3 bg-gray-700 rounded-md mt-2 mb-4">
							<p className="text-gray-300 text-sm">Transaction Hash</p>
							{router.query.transactionHashes.split(',').map((txhash) => (
								<a href={explorerUrl(txhash)} key={txhash} target="_blank" rel="noreferrer">
									<p className="text-white hover:underline cursor-pointer overflow-hidden text-ellipsis">
										{txhash}
									</p>
								</a>
							))}
						</div>
					)}
					<div className="flex justify-between px-1 mb-4">
						<p className="text-sm text-white">Share to:</p>
						<div className="flex gap-2">
							<FacebookShareButton url={tokenUrl} className="flex text-white">
								<FacebookIcon size={24} round />
							</FacebookShareButton>
							<TelegramShareButton url={tokenUrl} className="flex text-white">
								<TelegramIcon size={24} round />
							</TelegramShareButton>{' '}
							<TwitterShareButton
								title={`Checkout ${token.metadata.title} from collection ${token.metadata.collection} on @ParasHQ\n\n#paras #cryptoart #digitalart #tradingcards`}
								url={tokenUrl}
								className="flex text-white"
							>
								<TwitterIcon size={24} round />
							</TwitterShareButton>
						</div>
					</div>
					<Button size="md" isFullWidth onClick={onClickSeeToken}>
						See Token
					</Button>
				</div>
			</div>
		</Modal>
	)
}