gatsby#withPrefix JavaScript Examples

The following examples show how to use gatsby#withPrefix. 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: utils.js    From gatsby-plugin-anchor-links with MIT License 7 votes vote down vote up
export function handleLinkClick(to, e, onAnchorLinkClick) {
  /**
   * Log warnings on click
   */
  const improperFormatting = !to.includes('/') || !to.includes('#');
  if (improperFormatting) logWarning(errorTypes.IMPROPPER_FORMATTING);

  if (isBrowser && to.includes('#')) {
    const [anchorPath, anchor] = to.split('#');
    if (window.location.pathname === withPrefix(anchorPath)) {
      e.preventDefault();
      scroller(
        `#${anchor}`,
        window.gatsby_scroll_offset,
        window.gatsby_scroll_duration
      );
    }
  }

  if (onAnchorLinkClick) onAnchorLinkClick();
}
Example #2
Source File: custom-seo.js    From documentation with BSD Zero Clause License 6 votes vote down vote up
export default function CustomSeo({image, baseUrl, twitterHandle, ...props}) {
  const imagePath = withPrefix('/' + image);
  return (
    <SEO {...props} twitterCard="summary_large_image">
      <meta property="og:image" content="/cover.png" />
      {baseUrl && <meta name="twitter:image" content={baseUrl + imagePath} />}
      {twitterHandle && (
        <meta name="twitter:site" content={`@${twitterHandle}`} />
      )}
    </SEO>
  );
}
Example #3
Source File: sectionCheckout.js    From gatsby-starter-payments with MIT License 6 votes vote down vote up
SectionCheckout = () => {
  const [loaded, setLoaded] = useState(false)
  const scriptEl = useRef(null)

  // only add moonclerk.js when component mounts
  useEffect(() => {
    const checkoutScript = document.createElement("script")
    checkoutScript.id = "checkoutScript"
    checkoutScript.src = withPrefix("/moonclerk.js")
    scriptEl.current.appendChild(checkoutScript)
    setLoaded(true)
  }, [])

  return (
    <Container content id="checkout">
      <CheckoutContainer>
        <Content>
          <h6>Checkout</h6>
          <h1>Ready to start building the future?</h1>
          <p>
            Build websites that quickly accept payments with future-proof
            technology that runs lightning-fast globally.
          </p>
          <Seperator />
          <SliderTestimonials />
        </Content>
        {/* PASTE MOONCLERK FORM HTML ID HERE */}
        <Form id="mc1x9x8gl1q92p" ref={scriptEl} />
      </CheckoutContainer>
    </Container>
  )
}
Example #4
Source File: custom-seo.js    From webrtc-tutorial with MIT License 6 votes vote down vote up
export default function CustomSEO({ image, baseUrl, twitterHandle, ...props }) {
  const imagePath = withPrefix('/' + image);
  return (
    <SEO {...props} twitterCard="summary_large_image" favicon="/favicon-32x32.png">
      <meta name="google-site-verification" content="-qgu2UvNRmKmA2nlvPii0Ij_5KvDP7CoiPrrrt7fCDw" />
      <meta name="bytedance-verification-code" content="Di2CvrKo5GQhq+QNFxJc" />
      <script>
        {`
          (function(){
            var el = document.createElement("script");
            el.src = "https://sf1-scmcdn-tos.pstatp.com/goofy/ttzz/push.js?640b72aa3e4fdf9ffd1a9a05fc714e9cdddc3da3a07c6d62b917ee7736a67eed8d4676f17aecfe4838ef223da837021a5615cc802677690824ac7c88ac0f6a982b8d7c8c6655c9b00211740aa8a98e2e";
            el.id = "ttzz";
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(el, s);
          })(window)
        `}
      </script>
      {baseUrl && <meta property="og:image" content={baseUrl + imagePath} />}
      {baseUrl && <meta name="twitter:image" content={baseUrl + imagePath} />}
      {twitterHandle && <meta name="twitter:site" content={`@${twitterHandle}`} />}
    </SEO>
  );
}
Example #5
Source File: navbar.js    From blog with Apache License 2.0 6 votes vote down vote up
NavBar = (location) => {

  const rootPath = withPrefix("/");
  let header;

  let logoStyle = {
    height: "2.5em",
    marginBottom: 0
  };

  if (location.pathname === rootPath) {
    header = (
      <img className="logo" alt="AdoptOpenJDK logo" src={withPrefix("adopt_logo_white.svg")} style={logoStyle} />
    );
  } else {
    header = (
      <Link to={"/"} style={{ boxShadow: "none", color: "inherit", lineHeight: "0px" }}>
        <img className="logo" alt="AdoptOpenJDK logo" src={withPrefix("adopt_logo_white.svg")} style={logoStyle} />
      </Link>
    );
  }

  return (
    <header className="darkmode-ignore" id="site-header-main" style={{ display: "flex", backgroundColor: "#152935", backgroundImage: `url(${Background})`, justifyContent: "center", alignItems: "center", height: "6em"}}>
      {header}
      <SocialBar />
    </header>
  );
}
Example #6
Source File: Image.js    From tbtc-website with MIT License 6 votes vote down vote up
Image = ({ imageData, className = "" }) => {
  const { alt = "", childImageSharp, image } = imageData

  if (!!image && !!image.childImageSharp) {
    return (
      <Img
        className={className}
        alt={alt}
        {...image.childImageSharp}
      />
    )
  }

  if (!!childImageSharp) {
    return <Img className={className} alt={alt} {...childImageSharp} />
  }

  if (!!image && typeof image === "string") {
    return <img className={className} src={image} alt={alt} />
  }

  if (!!image && !!image.relativePath) {
    return (
      <img
        className={className}
        src={withPrefix(`/img/${image.relativePath}`)}
        alt={alt}
      />
    )
  }

  return null
}
Example #7
Source File: mobile-logo.js    From webrtc-tutorial with MIT License 6 votes vote down vote up
render() {
    return (
      <Wrapper>
        <img
          style={{
            margin: 0,
            maxWidth: '32px',
            maxHeight: '32px',
           }}
          src={withPrefix('/icons/icon-96x96.png')}
          alt={'logo'}
        />
      </Wrapper>
    );
  }
Example #8
Source File: logo.js    From webrtc-tutorial with MIT License 6 votes vote down vote up
export default function Logo() {
  return (
    <Wrapper>
      <img
        style={{
          maxWidth: '32px',
          maxHeight: '32px',
        }}
        src={withPrefix('/icons/icon-96x96.png')}
        alt={'logo'}
      />
    </Wrapper>
  );
}
Example #9
Source File: custom-seo.js    From firecamp-doc with MIT License 6 votes vote down vote up
export default function CustomSEO({image, baseUrl, twitterHandle, ...props}) {

  const imagePath = withPrefix('/' + image);
  // console.log(props, imagePath, 8888)
  return (
    <SEO {...props} twitterCard="summary_large_image" favicon="/images/256x256.ico">
      <meta property="og:image" content={imagePath} />
      {/* {baseUrl && <meta name="twitter:image" content={baseUrl + imagePath} />} */}
      {twitterHandle && (
        <meta name="twitter:site" content={`@${twitterHandle}`} />
      )}
    </SEO>
  );
}
Example #10
Source File: seo.js    From pdxtipjar with MIT License 6 votes vote down vote up
function SEO({ description, title }) {
  return (
    <Helmet>
      <html lang="en" />
      <title>{title}</title>
      <meta name="description" content={description} />
      <link
        rel="icon"
        type="image/png"
        href={`${withPrefix("/")}images/favicon-96x96.png`}
        sizes="96x96"
      />
      <link
        rel="icon"
        type="image/png"
        href={`${withPrefix("/")}images/favicon-32x32.png`}
        sizes="32x32"
      />
      <link
        rel="icon"
        type="image/png"
        href={`${withPrefix("/")}images/favicon-16x16.png`}
        sizes="16x16"
      />
      <meta name="twitter:card" content="summary" />
      <meta name="twitter:title" content="PDX Tip Jar" />
      <meta
        name="twitter:description"
        content="Share a small act of kindness with our
      service industry community during these uncertain times."
      />
      <meta
        name="twitter:image"
        content={`${withPrefix("/")}images/logo.png`}
      />
    </Helmet>
  );
}
Example #11
Source File: GitterRoomItem.js    From Webiu with MIT License 6 votes vote down vote up
GitterRoomItem = ({name, avatarUrl, roomUrl, userCount, visible}) => {
  return (
    <div className="gitter-room-list-item-component" aria-hidden="true" onClick={() => window.open(roomUrl, "_blank")}>
      <img className="image" alt="Avatar" src={avatarUrl && avatarUrl !== ""  ? avatarUrl : withPrefix('/images/gitterPlaceholder.png')} />
      <div>
        <p className="gitter-room-name">{name}</p>
        <p className="gitter-room-members">
          <FontAwesomeIcon icon={faUser} /> {userCount} Members
        </p>
        {visible ? <p className="gitter-room-members">
          Public IRC
        </p> : null}
      </div>
    </div>
  )
}
Example #12
Source File: seo.js    From guitar-book with MIT License 6 votes vote down vote up
export default function SEO({image, baseUrl, twitterHandle, title, description, siteName, adSense}) {
  const imagePath = withPrefix('/' + image);

  return (
    <Helmet>
      <title>{title}</title>
      <meta property="og:title" content={title} />
      <meta property="og:site_name" content={siteName} />
      <meta property="og:description" content={description} />
      <meta name="twitter:card" content="summary_large_image" />
      <meta name="twitter:title" content={title} />
      <meta name="twitter:description" content={description} />
      <meta property="og:image" content={imagePath} />
      <meta name="apple-mobile-web-app-capable" />
      {baseUrl && <meta name="twitter:image" content={baseUrl + imagePath} />}
      {twitterHandle && (
        <meta name="twitter:site" content={`@${twitterHandle}`} />
      )}
      {adSense &&
      <script
        data-ad-client={adSense}
        async
        src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
      />}
    </Helmet>
  );
}
Example #13
Source File: index.js    From Webiu with MIT License 6 votes vote down vote up
GuideLines = ({ heading, description, guidelines, image}) => {
  return (
    <div className="guide-lines-component">
      <Container>
        <Row>
          <Col>
            <h1>{heading}</h1>
            <h2>{description}</h2>
            <ol>
              {!guidelines || guidelines.map((guideline, i) => (
                <li key={i}>{guideline}</li>
              ))}
            </ol>
          </Col>
          {image ? <Col>
            <img alt="logo" src={withPrefix(image)} style={{maxWidth: "400px"}} />
          </Col> : null}
        </Row>
      </Container>
    </div>
  )
}
Example #14
Source File: index.js    From codeursenseine.com with MIT License 6 votes vote down vote up
IndexPage = () => {
  const data = useStaticQuery(graphql`
    query SiteCurrentYearQuery {
      site {
        siteMetadata {
          currentYear
        }
      }
    }
  `);

  useEffect(() => {
    window.location.href = withPrefix(`/${data.site.siteMetadata.currentYear}`);
  }, [data.site.siteMetadata.currentYear]);

  return <React.Fragment />;
}
Example #15
Source File: MailingListFeedItem.js    From Webiu with MIT License 6 votes vote down vote up
MailingListFeedItem = ({image, author, title, description, publishedDate, slug}) => {
  return (
    <div className="mailing-list-feed-item-component" onClick={() => window.open(slug, "_blank")}>
      {image && image !== "" ? (
        <img className= "image" alt="medium" src={withPrefix(image)} />
      ) : (
        <LetterAvatar name={author} />
      )}
      <div>
        <p className="post-published-author">{author}</p>
        <p className="post-published-date">
          {moment(publishedDate).format("MMMM Do YYYY, h:mm A")}{' '}
          {moment().diff(moment(publishedDate), "days") <= 7 ? <span className="new-span">NEW</span> : null}
        </p> 
        <p className="post-title">{title}</p>
        <p className="post-description">"{description.substring(0, 300) + "..."}"</p>
      </div>
    </div>
  )
}
Example #16
Source File: sidebar-nav.js    From webrtc-tutorial with MIT License 5 votes vote down vote up
function isPageSelected(path, pathname) {
  const [a, b] = [withPrefix(path), pathname].map(string =>
    string.replace(/\/$/, '')
  );
  return a === b;
}
Example #17
Source File: Layout.js    From Blogs with MIT License 5 votes vote down vote up
TemplateWrapper = ({ children }) => {
  const { title, description } = useSiteMetadata();

  return (
    <div>
      <Helmet>
        <html lang="en" />
        <title>{title}</title>
        <meta name="description" content={description} />

        <link
          rel="apple-touch-icon"
          sizes="180x180"
          href={`${withPrefix("/")}img/apple-touch-icon.png`}
        />
        <link
          rel="icon"
          type="image/png"
          href={`${withPrefix("/")}img/favicon-32x32.png`}
          sizes="32x32"
        />
        <link
          rel="icon"
          type="image/png"
          href={`${withPrefix("/")}img/favicon-16x16.png`}
          sizes="16x16"
        />

        <link
          rel="mask-icon"
          href={`${withPrefix("/")}img/safari-pinned-tab.svg`}
          color="#ff4400"
        />
        <meta name="theme-color" content="#fff" />

        <meta property="og:type" content="business.business" />
        <meta property="og:title" content={title} />
        <meta property="og:url" content="/" />
        <meta
          property="og:image"
          content={`${withPrefix("/")}img/og-image.jpg`}
        />
      </Helmet>
      <Navbar />
      <div>{children}</div>
      {/* <Footer /> */}
    </div>
  );
}
Example #18
Source File: link.js    From gatsby-starter-scientist with MIT License 5 votes vote down vote up
CustomLink = ({
  buttonStyle,
  children,
  className,
  nav,
  outline,
  to,
  ...props
}) => {
  const classes = className ? [className] : [];
  if (nav) {
    classes.push('link_nav');
  }
  if (buttonStyle) {
    classes.push('link_button');
  }
  if (outline) {
    classes.push('link_outline');
  }

  if (to.startsWith('/') && /\.[0-9a-z]+$/i.test(to)) {
    return (
      <a
        className={formatClass(classes)}
        href={withPrefix(to)}
        {...props}
      >
        {children}
      </a>
    );
  } if (to.startsWith('/')) {
    return (
      <Link
        className={formatClass(classes)}
        to={to}
        {...props}
      >
        {children}
      </Link>
    );
  }
  return (
    <a
      className={formatClass(classes)}
      href={to}
      {...props}
    >
      {children}
    </a>
  );
}
Example #19
Source File: Layout.js    From gatsby-starter-netlify-cms with MIT License 5 votes vote down vote up
TemplateWrapper = ({ children }) => {
  const { title, description } = useSiteMetadata()
  return (
    <div>
      <Helmet>
        <html lang="en" />
        <title>{title}</title>
        <meta name="description" content={description} />

        <link
          rel="apple-touch-icon"
          sizes="180x180"
          href={`${withPrefix('/')}img/apple-touch-icon.png`}
        />
        <link
          rel="icon"
          type="image/png"
          href={`${withPrefix('/')}img/favicon-32x32.png`}
          sizes="32x32"
        />
        <link
          rel="icon"
          type="image/png"
          href={`${withPrefix('/')}img/favicon-16x16.png`}
          sizes="16x16"
        />

        <link
          rel="mask-icon"
          href={`${withPrefix('/')}img/safari-pinned-tab.svg`}
          color="#ff4400"
        />
        <meta name="theme-color" content="#fff" />

        <meta property="og:type" content="business.business" />
        <meta property="og:title" content={title} />
        <meta property="og:url" content="/" />
        <meta
          property="og:image"
          content={`${withPrefix('/')}img/og-image.jpg`}
        />
      </Helmet>
      <Navbar />
      <div>{children}</div>
      <Footer />
    </div>
  )
}
Example #20
Source File: index.js    From firecamp-doc with MIT License 5 votes vote down vote up
function isPageSelected(path, pathname) {
  const [a, b] = [withPrefix(path), pathname].map(string =>
    string.replace(/\/$/, '')
  );
  return a === b;
}
Example #21
Source File: index.js    From firecamp-doc with MIT License 5 votes vote down vote up
function getId(title) {
  return withPrefix(title);
}
Example #22
Source File: gatsby-ssr.js    From newsliner-gatsby with MIT License 5 votes vote down vote up
exports.onRenderBody = ({ setHeadComponents }, pluginOptions) => {
    // We use this to build a final array to pass as the argument to setHeadComponents at the end of onRenderBody.
    let headComponents = []

    const icons = pluginOptions.icons || defaultIcons

    // If icons were generated, also add a favicon link.
    if (pluginOptions.icon) {
        let favicon = icons && icons.length ? icons[0].src : null

        if (favicon) {
            headComponents.push(
                <link
                    key={`gatsby-plugin-manifest-icon-link`}
                    rel="shortcut icon"
                    href={withPrefix(favicon)}
                />
            )
        }
    }

    // Add manifest link tag.
    headComponents.push(
        <link
            key={`gatsby-plugin-manifest-link`}
            rel="manifest"
            href={withPrefix(`/manifest.webmanifest`)}
        />
    )
    // The user has an option to opt out of the theme_color meta tag being inserted into the head.
    if (pluginOptions.theme_color) {
        let insertMetaTag = Object.keys(pluginOptions).includes(
            `theme_color_in_head`
        )
            ? pluginOptions.theme_color_in_head
            : true

        if (insertMetaTag) {
            headComponents.push(
                <meta
                    key={`gatsby-plugin-manifest-meta`}
                    name="theme-color"
                    content={pluginOptions.theme_color}
                />
            )
        }
    }

    if (pluginOptions.legacy) {
        const iconLinkTags = icons.map(icon => (
            <link
                key={`gatsby-plugin-manifest-apple-touch-icon-${icon.sizes}`}
                rel="apple-touch-icon"
                sizes={icon.sizes}
                href={withPrefix(`${icon.src}`)}
            />
        ))

        headComponents = [...headComponents, ...iconLinkTags]
    }

    setHeadComponents(headComponents)
}
Example #23
Source File: sidebar-nav.js    From guitar-book with MIT License 5 votes vote down vote up
function isPageSelected(path, pathname) {
  const [a, b] = [withPrefix(path), pathname].map(string =>
    string.replace(/\/$/, '')
  );
  return a === b;
}
Example #24
Source File: page-content.js    From guitar-book with MIT License 5 votes vote down vote up
export default function PageContent(props) {
  const contentRef = useRef(null);
  const [imagesToLoad, setImagesToLoad] = useState(0);
  const [imagesLoaded, setImagesLoaded] = useState(0);

  useMount(() => {
    if (props.hash) {
      // turn numbers at the beginning of the hash to unicode
      // see https://stackoverflow.com/a/20306237/8190832
      const hash = props.hash.toLowerCase().replace(/^#(\d)/, '#\\3$1 ');
      try {
        const hashElement = contentRef.current.querySelector(hash);
        if (hashElement) {
          hashElement.scrollIntoView();
        }
      } catch (error) {
        // let errors pass
      }
    }

    let toLoad = 0;
    const images = contentRef.current.querySelectorAll('img');
    images.forEach(image => {
      if (!image.complete) {
        image.addEventListener('load', handleImageLoad);
        toLoad++;
      }
    });

    setImagesToLoad(toLoad);
  });

  function handleImageLoad() {
    setImagesLoaded(prevImagesLoaded => prevImagesLoaded + 1);
  }

  const pageIndex = props.pages.findIndex(page => {
    const prefixedPath = withPrefix(page.path);
    return (
      prefixedPath === props.pathname ||
      prefixedPath.replace(/\/$/, '') === props.pathname
    );
  });

  const editLink = props.githubUrl && (
    <AsideLink href={props.githubUrl}>
      <IconGithub /> Edit on GitHub
    </AsideLink>
  );

  return (
    <Wrapper>
      <InnerWrapper>
        <BodyContent ref={contentRef} className="content-wrapper">
          {props.children}
        </BodyContent>
        <EditLink>{editLink}</EditLink>
        <PageNav
          prevPage={props.pages[pageIndex - 1]}
          nextPage={props.pages[pageIndex + 1]}
        />
      </InnerWrapper>
      <Aside>
        <AsideHeading>{props.title}</AsideHeading>
        {props.headings.length > 0 && (
          <SectionNav
            headings={props.headings}
            contentRef={contentRef}
            imagesLoaded={imagesLoaded === imagesToLoad}
          />
        )}
        {editLink}
      </Aside>
    </Wrapper>
  );
}
Example #25
Source File: anchor-tag.js    From gatsby-digital-garden with MIT License 4 votes vote down vote up
AnchorTag = ({
  title,
  href,
  references = [],
  withoutLink,
  withoutPopup,
  ...restProps
}) => {
  // same as in gatsby-transformer-markdown-references/src/compute-inbounds.ts#getRef
  const ref = references.find(
    (x) =>
      withPrefix(x.slug) === withPrefix(href) ||
      x.title === title ||
      (x.aliases || []).some((alias) => alias === title) ||
      basename(x.slug) === title
  );

  let content;
  let popupContent;
  let child;

  if (ref) {
    const nestedComponents = {
      a(props) {
        return <AnchorTag {...props} references={references} withoutLink />;
      },
      p(props) {
        return <span {...props} />;
      },
    };
    content =
      ref.title === ref.displayTitle ? (
        restProps.children
      ) : (
        <MDXProvider components={nestedComponents}>
          <MDXRenderer>{ref.mdx}</MDXRenderer>
        </MDXProvider>
      );
    popupContent = (
      <div id={ref.id} className="popover with-markdown">
        {ref.title === ref.displayTitle ? (
          <React.Fragment>
            <MDXProvider components={nestedComponents}>
              <MDXRenderer>{ref.mdx}</MDXRenderer>
            </MDXProvider>
          </React.Fragment>
        ) : (
          <React.Fragment>
            <h5>{ref.displayTitle}</h5>
            <ul>
              <li>
                <MDXProvider components={nestedComponents}>
                  <MDXRenderer>{ref.mdx}</MDXRenderer>
                </MDXProvider>
              </li>
            </ul>
          </React.Fragment>
        )}
        <div className="more-content-blind" />
      </div>
    );
    child = (
      <LinkToStacked {...restProps} to={ref.slug} title={title}>
        {content}
      </LinkToStacked>
    );
  } else {
    content = restProps.children;
    popupContent = <div className="popover no-max-width">{href}</div>;
    // eslint-disable-next-line jsx-a11y/anchor-has-content
    const externalLink = /^(http(s?)):\/\//i.test(href);
    child = (
      <a
        {...restProps}
        target={externalLink ? '_blank' : null}
        // Add noopener and noreferrer for security reasons
        rel={externalLink ? 'noopener noreferrer' : null}
        href={
          !href || (href.indexOf && href.indexOf("#") === 0)
            ? href
            : withPrefix(href)
        }
        title={title}
      />
    );
  }

  if (withoutLink) {
    return <span>{content}</span>;
  }

  if (withoutPopup) {
    return child;
  }

  return (
    <Tippy animation="shift-away" content={popupContent} maxWidth="none">
      {child}
    </Tippy>
  );
}
Example #26
Source File: Video.js    From ibm-enterprise-runbooks with Apache License 2.0 4 votes vote down vote up
Video = ({ autoPlay, vimeoId, youtubeId, title, src, poster, muted, ...props }) => {
  const [isPlaying, setIsPlaying] = useState(autoPlay);
  const pathPrefix = usePathPrefix();
  const videoRef = useRef(null);
  const iframeRef = useRef(null);
  const buttonClassName = cx(videoButton, {
    [videoIsPlaying]: isPlaying,
  });

  // React doesn't handle the muted attribute well
  // https://github.com/facebook/react/issues/10389#issuecomment-605689475
  useEffect(() => {
    if (muted && videoRef.current) {
      videoRef.current.setAttribute('muted', '');
    }
  }, [muted]);

  // If a video/poster is imported into an MDX file and provided through
  // a js variable, it will already have the path-prefix.
  //
  // If the src/poster is just a reference to a file in the static directory,
  // then we need to prefix for them.
  const srcContainsPrefix = pathPrefix && src && src.includes(pathPrefix);
  const fixedSrc = srcContainsPrefix ? src : withPrefix(src);

  const posterContainsPrefix =
    pathPrefix && poster && poster.includes(pathPrefix);
  const fixedPoster = posterContainsPrefix ? poster : withPrefix(poster);

  if (vimeoId) {
    return (
      <div className={videoContainer}>
        <div className={cx(video, vimeo)}>
          <div className="embedVideo-container">
            <iframe
              allow="autoplay"
              title={title}
              src={`https://player.vimeo.com/video/${vimeoId}`}
              ref={iframeRef}
              width="640"
              height="360"
              frameBorder="0"
              webkitallowfullscreen="true"
              mozallowfullscreen="true"
              allowFullScreen
            />
          </div>
        </div>
      </div>
    );
  }
  if (youtubeId){
    return (
      <div className={videoContainer}>
        <div className={cx(video, vimeo)}>
          <div className="embedVideo-container">
            <iframe
              width="640"
              height="360"
              title={title}
              src={`https://www.youtube.com/embed/${youtubeId}`}
              ref={iframeRef}
              frameborder="0"
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
              allowfullscreen
              webkitallowfullscreen="true"
              mozallowfullscreen="true"
            />
          </div>
        </div>
      </div>
    )
  }

  function onClick(e) {
    e.stopPropagation();
    if (isPlaying) {
      videoRef.current.pause();
      setIsPlaying(false);
      return;
    }

    return videoRef.current
      .play()
      .then(() => {
        setIsPlaying(true);
      })
      .catch((error) => {
        console.log(error);
      });
  }

  function onEnded() {
    setIsPlaying(false);
  }

  function onKeyDown(event) {
    if (event.key === ' ' || event.key === 'Enter') {
      event.preventDefault();
      if (isPlaying) {
        videoRef.current.pause();
        setIsPlaying(false);
        return;
      }
      return videoRef.current
        .play()
        .then(() => {
          setIsPlaying(true);
        })
        .catch((error) => {
          console.log(error);
        });
    }
  }

  return (
    <div className={videoContainer}>
      <div
        className={buttonClassName}
        role="button"
        onClick={onClick}
        onKeyDown={onKeyDown}
        tabIndex="0">
        {isPlaying ? <Pause32 /> : <Play32 />}
        <span className="bx--assistive-text">
          {isPlaying ? 'Pause' : 'Play'}
        </span>
      </div>
      {/* eslint-disable-next-line jsx-a11y/media-has-caption */}
      <video
        autoPlay={autoPlay}
        className={video}
        type="video/mp4"
        ref={videoRef}
        onEnded={onEnded}
        src={fixedSrc}
        poster={fixedPoster}
        {...props}
      />
    </div>
  );
}
Example #27
Source File: addons.jsx    From github-profile-readme-generator with Apache License 2.0 4 votes vote down vote up
Addons = (props) => {
  const { data, social, handleDataChange, handleCheckChange } = props;
  const [debounce, setDebounce] = useState(undefined);
  const [badgeOptions, setBadgeOptions] = useState({
    badgeStyle: data.badgeStyle,
    badgeColor: data.badgeColor,
    badgeLabel: data.badgeLabel,
  });

  useEffect(() => {
    setBadgeOptions({
      badgeStyle: data.badgeStyle,
      badgeColor: data.badgeColor,
      badgeLabel: data.badgeLabel,
    });
  }, [data.badgeStyle, data.badgeColor, data.badgeLabel]);

  const [githubStatsOptions, setGithubStatsOptions] = useState({
    ...data.githubStatsOptions,
  });

  useEffect(() => {
    setGithubStatsOptions({
      ...data.githubStatsOptions,
    });
  }, [data.githubStatsOptions]);

  const [topLanguagesOptions, setTopLanguagesOptions] = useState({
    ...data.topLanguagesOptions,
  });

  useEffect(() => {
    setTopLanguagesOptions({
      ...data.topLanguagesOptions,
    });
  }, [data.topLanguagesOptions]);

  const [streakStatsOptions, setStreakStatsOptions] = useState({
    ...data.streakStatsOptions,
  });

  useEffect(() => {
    setStreakStatsOptions({
      ...data.streakStatsOptions,
    });
  }, [data.streakStatsOptions]);

  const blogPostPorkflow = () => {
    const payload = {
      dev: {
        show: data.devDynamicBlogs,
        username: social.dev,
      },
      medium: {
        show: data.mediumDynamicBlogs,
        username: social.medium,
      },
      rssurl: {
        show: data.rssDynamicBlogs,
        username: social.rssurl,
      },
    };
    const actionContent = latestBlogs(payload);
    const tempElement = document.createElement('a');
    tempElement.setAttribute('href', `data:text/yaml;charset=utf-8,${encodeURIComponent(actionContent)}`);
    tempElement.setAttribute('download', 'blog-post-workflow.yml');
    tempElement.style.display = 'none';
    document.body.appendChild(tempElement);
    tempElement.click();
    document.body.removeChild(tempElement);
  };

  const onBadgeUpdate = (option, value) => {
    const callback = () => {
      const newVal = option === 'badgeLabel' && value === '' ? 'Profile views' : value;
      setBadgeOptions({ ...badgeOptions, [option]: newVal });
      handleDataChange(option, { target: { value: newVal } });
    };
    clearTimeout(debounce);
    setDebounce(setTimeout(callback, 300));
  };

  const onStatsUpdate = (option, value) => {
    const newStatsOptions = { ...githubStatsOptions, [option]: value };
    setGithubStatsOptions(newStatsOptions);
    handleDataChange('githubStatsOptions', {
      target: { value: newStatsOptions },
    });
  };

  const onTopLangUpdate = (option, value) => {
    const newLangOptions = { ...topLanguagesOptions, [option]: value };
    setTopLanguagesOptions(newLangOptions);
    handleDataChange('topLanguagesOptions', {
      target: { value: newLangOptions },
    });
  };

  const onStreakStatsUpdate = (option, value) => {
    const newStreakStatsOptions = { ...streakStatsOptions, [option]: value };
    setStreakStatsOptions(newStreakStatsOptions);
    handleDataChange('streakStatsOptions', {
      target: { value: newStreakStatsOptions },
    });
  };

  return (
    <div className="flex justify-center items-start flex-col w-full px-2 sm:px-6 mb-10">
      <div className="text-xl sm:text-2xl font-bold font-title mt-2 mb-2">Add-ons</div>
      <AddonsItem
        inputId="visitors-count"
        inputChecked={data.visitorsBadge}
        onInputChange={() => handleCheckChange('visitorsBadge')}
        Options={
          <CustomizeOptions
            title="Customize Badge"
            CustomizationOptions={
              <CustomizeBadge githubName={social.github} badgeOptions={badgeOptions} onBadgeUpdate={onBadgeUpdate} />
            }
          />
        }
      >
        display visitors count badge
      </AddonsItem>
      <AddonsItem
        inputId="github-profile-trophy"
        inputChecked={data.githubProfileTrophy}
        onInputChange={() => handleCheckChange('githubProfileTrophy')}
      >
        display github trophy
      </AddonsItem>
      <AddonsItem
        inputId="github-stats"
        inputChecked={data.githubStats}
        onInputChange={() => handleCheckChange('githubStats')}
        Options={
          <CustomizeOptions
            title="Customize Github Stats Card"
            CustomizationOptions={
              <CustomizeGithubStatsBase prefix="stats" options={githubStatsOptions} onUpdate={onStatsUpdate} />
            }
          />
        }
      >
        display github profile stats card
      </AddonsItem>
      <AddonsItem
        inputId="top-languages"
        inputChecked={data.topLanguages}
        onInputChange={() => handleCheckChange('topLanguages')}
        Options={
          <CustomizeOptions
            title="Customize Top Skills Card"
            CustomizationOptions={
              <CustomizeGithubStatsBase prefix="top-lang" options={topLanguagesOptions} onUpdate={onTopLangUpdate} />
            }
          />
        }
      >
        display top skills
      </AddonsItem>
      <AddonsItem
        inputId="streak-stats"
        inputChecked={data.streakStats}
        onInputChange={() => handleCheckChange('streakStats')}
        Options={
          <CustomizeOptions
            title="Customize Streak Stats Card"
            CustomizationOptions={
              <CustomizeStreakStats prefix="streak-stats" options={streakStatsOptions} onUpdate={onStreakStatsUpdate} />
            }
          />
        }
      >
        display github streak stats
      </AddonsItem>
      <AddonsItem
        inputId="twitter-badge"
        inputChecked={data.twitterBadge}
        onInputChange={() => handleCheckChange('twitterBadge')}
      >
        display twitter badge
      </AddonsItem>
      <AddonsItem
        inputId="dev-dynamic-blogs"
        inputChecked={data.devDynamicBlogs}
        onInputChange={() => handleCheckChange('devDynamicBlogs')}
      >
        display latest dev.to blogs dynamically (GitHub Action)
      </AddonsItem>
      <AddonsItem
        inputId="medium-dynamic-blogs"
        inputChecked={data.mediumDynamicBlogs}
        onInputChange={() => handleCheckChange('mediumDynamicBlogs')}
      >
        display latest medium blogs dynamically (GitHub Action)
      </AddonsItem>
      <AddonsItem
        inputId="rss-dynamic-blogs"
        inputChecked={data.rssDynamicBlogs}
        onInputChange={() => handleCheckChange('rssDynamicBlogs')}
      >
        display latest blogs from your personal blog dynamically (GitHub Action)
      </AddonsItem>

      {(data.devDynamicBlogs && social.dev) ||
      (data.rssDynamicBlogs && social.rssurl) ||
      (data.mediumDynamicBlogs && social.medium && isMediumUsernameValid(social.medium)) ? (
        <div className="workflow">
          <div>
            download
            <span
              id="blog-post-worklow-span"
              onClick={blogPostPorkflow}
              onKeyDown={(e) => e.keyCode === 13 && blogPostPorkflow()}
              role="button"
              tabIndex="0"
              style={{ cursor: 'pointer', color: '#002ead' }}
            >
              {' '}
              blog-post-workflow.yml
            </span>{' '}
            file(learn
            <a href={withPrefix(links.addons)} target="blank" style={{ color: '#002ead' }}>
              {' '}
              how to setup
            </a>
            )
          </div>
        </div>
      ) : (
        ''
      )}
    </div>
  );
}
Example #28
Source File: Nav.js    From codeursenseine.com with MIT License 4 votes vote down vote up
Nav = ({
  breakpoint,
  isOpen,
  onNavClose = () => {},
  ...props
}) => {
  const theme = useTheme();
  const { pathname } = useLocation();

  const data = useStaticQuery(graphql`
    query NavPagesQuery {
      site {
        siteMetadata {
          currentYear
        }
      }
    }
  `);

  const currentYear = data.site.siteMetadata.currentYear;

  return (
    <Flex
      direction="column"
      alignItems={{ [breakpoint]: "flex-end" }}
      background={theme.gradients.brand}
      color="white"
      position="fixed"
      top="0"
      left="0"
      bottom="0"
      transform={{
        base: `translate(${isOpen ? 0 : "100%"})`,
        [breakpoint]: "none",
      }}
      transition={{ base: "transform 0.4s", [breakpoint]: "none" }}
      overflowY="auto"
      overflowX="none"
      zIndex="3"
      as="nav"
      {...props}
    >
      <Flex direction="column" flexGrow={1}>
        <IconButton
          variant="unstyled"
          aria-label="Menu"
          d={{ base: "inline-flex", [breakpoint]: "none" }}
          icon={<FiX />}
          size="lg"
          position="absolute"
          top="0"
          right="0"
          onClick={() => onNavClose()}
        />
        <Stack px="2">
          <Flex
            px="2"
            pt="4vh"
            pb="2vh"
            align="center"
            justify={{ base: "center", [breakpoint]: "flex-end" }}
          >
            <Link to={`/${currentYear}`}>
              <Logo w={{ base: "8rem", [breakpoint]: "12rem" }} />
            </Link>
          </Flex>
          <Stack>
            <NavLink isMain as={Link} to={`/${currentYear}`}>
              Édition {currentYear}
            </NavLink>
            {pathname.startsWith(withPrefix(`/${currentYear}`)) && (
              <>
                {/* <NavLink as={Link} to={`/${currentYear}/programme`}>
                  Programme
                </NavLink>
                <NavLink as={Link} to={`/${currentYear}/speakers`}>
                  Intervenants
                </NavLink> */}
                <NavLink as={Link} to={`/${currentYear}/sponsors`}>
                  Sponsors
                </NavLink>
                <NavLink as={Link} to={`/${currentYear}/organisateurs`}>
                  Organisateurs
                </NavLink>
                {/* <NavLink as={Link} to={`/${currentYear}/kit-de-presse`}>
                  Kit de presse
                </NavLink> */}
                <NavLink as={Link} to={`/${currentYear}/code-of-conduct`}>
                  Code de conduite
                </NavLink>
                <NavLink as={Link} to={`/${currentYear}/review-2020-2021`}>
                  Review 2020-2021
                </NavLink>
              </>
            )}
          </Stack>
          <Stack spacing="0">
            <NavLink isMain as={Link} to="/meetups">
              Meetups
            </NavLink>
            {pathname.startsWith(withPrefix("/meetups")) && (
              <>
                <NavLink as={Link} to="/meetups/sponsors">
                  Sponsors
                </NavLink>
              </>
            )}
          </Stack>
          <Stack>
            <NavLink isMain as={Link} to="/live" title="Live Twitch">
              <span role="img" aria-label="Red circle">
                ?
              </span>{" "}
              Live Stream
            </NavLink>
          </Stack>
          <Stack>
            <NavLink isMain as={Link} to="/devoxx4kids" title="Devoxx4Kids">
              Devoxx4Kids
            </NavLink>
          </Stack>
        </Stack>
        <Stack mt="auto" p="4" mb="2">
          <NavSocial />
          <NavPreviousYears />
        </Stack>
      </Flex>
    </Flex>
  );
}