gatsby#withPrefix TypeScript 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: layout.tsx    From website with MIT License 6 votes vote down vote up
render() {
		const { title, narrowLayout } = this.props;
		return (
			<React.Fragment>

				<StaticQuery
					query={query}
					render={(data) => (
						<Helmet titleTemplate={data.site.siteMetadata.titleTemplate} defaultTitle={data.site.siteMetadata.defaultTitle}>
							{title && <title>{title}</title>}
							<meta property='og:type' content='website' />
							<meta property='og:title' content={`${title ? `${title} - ` : ''}${data.site.siteMetadata.defaultTitle}`} />
							<meta property='og:site_name' content='DataCore' />
							<meta property='og:image' content={`${data.site.siteMetadata.baseUrl}/media/logo.png`} />
							<meta property='og:description' content={data.site.siteMetadata.defaultDescription} />
							<link id='defaultThemeCSS' rel='stylesheet' type='text/css' href={withPrefix('styles/semantic.slate.css')} />
							<link rel='stylesheet' type='text/css' href={withPrefix('styles/easymde.min.css')} />
							<script src={withPrefix('styles/theming.js')} type='text/javascript' />
							<script src={withPrefix('polyfills.js')} type='text/javascript' />
						</Helmet>
					)}
				/>
				<TopMenu narrowLayout={narrowLayout}>
					{this.props.children}
				</TopMenu>
			</React.Fragment>
		);
	}
Example #2
Source File: wrapPageElement.tsx    From gatsby-plugin-react-i18next with MIT License 5 votes vote down vote up
removePathPrefix = (pathname: string) => {
  const pathPrefix = withPrefix('/');
  if (pathname.startsWith(pathPrefix)) {
    return pathname.replace(pathPrefix, '/');
  }

  return pathname;
}
Example #3
Source File: AnchorTag.tsx    From gatsby-project-kb with MIT License 4 votes vote down vote up
AnchorTag = ({
  title,
  href,
  references = [],
  withoutLink,
  withoutPopup,
  currentSlug,
  currentLocation,
  refWordMdxSlugDict,
  wikiLinkLabelTemplateFn,
  ...restProps
}: Props) => {
  // prettier-ignore
  const { anchorSlug } = genHrefInfo({ currentSlug, href })

  function getSlugByRefWord(title: string) {
    if (!refWordMdxSlugDict) return;
    if (title in refWordMdxSlugDict) return `/${refWordMdxSlugDict[title]}`
  }

  let ref: Reference | undefined

  ref = references.find((x) => {
    const refSlug = x.target.parent?.fields.slug || ''
    return (
      `/${x.refWord}` === href ||
      getSlugByRefWord(title) === refSlug ||
      withPrefix(refSlug) === withPrefix(anchorSlug)
    )
  })
  // console.log('ref', ref, 'href', href, 'anchorSlug', anchorSlug, references)

  let content
  let popupContent
  let child

  if (ref && ref.target.parent) {
    // console.log('reference is', ref, 'withoutLink', withoutLink)
    const targetFileNode = ref.target.parent
    const fields = ref.target.parent.fields
    const mdxBody = ref.target.body
    const nestedComponents = {
      a(props) {
        const {
          anchorSlug: nestedAnchorSlug,
          isExternalLink: nestedIsExternalLink,
        } = genHrefInfo({ currentSlug, href: props.href })
        if (nestedIsExternalLink) {
          return <a href={props.href}>{props.children}</a>
        } else {
          let toSlug = nestedAnchorSlug
          if (refWordMdxSlugDict) {
            // nested content's anchor label will not be replaced with topic title,
            // so it can be used to form slug
            const maybeSlug = getSlugByRefWord(props.title)
            if (maybeSlug) toSlug = maybeSlug
          }
          return <Link to={toSlug}>{props.children}</Link>
        }
      },
      p(props) {
        return <span {...props} />
      },
    }
    content = wikiLinkLabelTemplateFn
      ? wikiLinkLabelTemplateFn({ refWord: ref.refWord, title: fields.title })
      : restProps.children
    popupContent = (
      <div id={targetFileNode.id} className="anchor-tag__popover with-markdown">
        <React.Fragment>
          <MDXProvider components={nestedComponents}>
            <MDXRenderer>{mdxBody}</MDXRenderer>
          </MDXProvider>
        </React.Fragment>
      </div>
    )
    child = (
      <Link
        {...restProps}
        to={padHrefWithAnchor(fields.slug, ref.targetAnchor)}
        title={title}
      >
        {content}
      </Link>
    )
  } else {
    content = restProps.children
    popupContent = <div className="popover no-max-width">{href}</div>
    child = (
      <a
        {...restProps}
        href={
          !href || (href.indexOf && href.indexOf('#') === 0)
            ? href
            : withPrefix(href)
        }
        title={title}
      />
    )
    return child
  }

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

  if (withoutPopup) {
    return child
  }

  return (
    <Tippy
      animation="shift-away"
      content={popupContent}
      maxWidth="none"
      interactive
    >
      {child}
    </Tippy>
  )
}
Example #4
Source File: Layout.tsx    From lesesalen with MIT License 4 votes vote down vote up
Layout: React.FC<Props> = ({ location, children }) => {
  const rootPath = withPrefix("/");
  const notesPath = withPrefix("/notes/");
  const infoPath = withPrefix("/info/");
  const otherPath = withPrefix("/other/");
  let header;

  if (
    location.pathname === rootPath ||
    location.pathname === notesPath ||
    location.pathname === otherPath ||
    location.pathname === infoPath
  ) {
    header = <StyledHeader />;
  } else {
    header = (
      <h3
        style={{
          fontFamily: `Roboto, sans-serif`,
          marginTop: 0,
        }}
      >
        <Link
          style={{
            boxShadow: `none`,
            color: `inherit`,
          }}
          to={`/`}
        >
          Back to home
        </Link>
      </h3>
    );
  }

  const [spook, setSpooks] = useState<SpookSetting | null>(null);

  const renderSpook = isSpooktober
    ? (setting: SpookSetting) => {
        return (
          <div
            style={{
              position: "fixed",
              left: setting.x,
              top: setting.y,
              zIndex: 10,
            }}
          >
            <img src={setting.url} alt="A spooky ghost" />
            <div
              style={{
                position: "absolute",
                left: 10,
                bottom: 40,
              }}
            >
              Powered by Giphy
            </div>
          </div>
        );
      }
    : undefined;

  const spookEvent = isSpooktober
    ? async (x: number, y: number) => {
        if (!process.env.GATSBY_GIPHY_KEY) {
          console.log("Missing GATSBY_GIPHY_KEY environment variable");
          return;
        }
        if (!Math.floor(Math.random() * 5)) {
          const gif = await axios.get<GiphyResponse>(
            `https://api.giphy.com/v1/gifs/random?tag=skeleton&api_key=${String(
              process.env.GATSBY_GIPHY_KEY
            )}`
          );
          setSpooks({
            x: x,
            y: y,
            url: gif.data.data.images.original.url,
          });
          clearTimeout(spookTimer);
          spookTimer = setTimeout(setSpooks, 2000, null);
        }
      }
    : undefined;

  return (
    <Theme>
      <div
        style={{
          marginLeft: `auto`,
          marginRight: `auto`,
          maxWidth: rhythm(24),
          padding: `${rhythm(1.5)} ${rhythm(3 / 4)}`,
        }}
        role="button"
        {...(isSpooktober
          ? {
              tabIndex: 0,
              onMouseDown: async (e) => {
                e.persist();
                await spookEvent?.(e.clientX, e.clientY);
              },
              onKeyDown: async () => {
                const rects = document.activeElement?.getBoundingClientRect();
                await spookEvent?.(rects?.top ?? 0, rects?.left ?? 0);
              },
            }
          : {})}
      >
        <header>{header}</header>
        <Nav />
        <main>
          {isSpooktober && spook && renderSpook?.(spook)}
          {children}
        </main>
        <footer>
          © {new Date().getFullYear()}, Built with
          {` `}
          <a href="https://www.gatsbyjs.org">Gatsby</a> |{" "}
          <Link to={"/about/"}>About</Link>
        </footer>
      </div>
    </Theme>
  );
}
Example #5
Source File: wrapPageElement.tsx    From gatsby-plugin-react-i18next with MIT License 4 votes vote down vote up
wrapPageElement = (
  {element, props}: WrapPageElementBrowserArgs<any, PageContext>,
  {
    i18nextOptions = {},
    redirect = true,
    generateDefaultLanguagePage = false,
    siteUrl,
    localeJsonNodeName = 'locales',
    fallbackLanguage
  }: PluginOptions
) => {
  if (!props) return;
  const {data, pageContext, location} = props;
  const {routed, language, languages, originalPath, defaultLanguage, path} = pageContext.i18n;
  const isRedirect = redirect && !routed;

  if (isRedirect) {
    const {search} = location;

    // Skip build, Browsers only
    if (typeof window !== 'undefined') {
      let detected =
        window.localStorage.getItem(LANGUAGE_KEY) ||
        browserLang({
          languages,
          fallback: fallbackLanguage || language
        });

      if (!languages.includes(detected)) {
        detected = language;
      }

      window.localStorage.setItem(LANGUAGE_KEY, detected);

      if (detected !== defaultLanguage) {
        const queryParams = search || '';
        const newUrl = withPrefix(
          `/${detected}${removePathPrefix(location.pathname)}${queryParams}${location.hash}`
        );
        // @ts-ignore
        window.___replace(newUrl);
        return null;
      }
    }
  }

  const localeNodes: Array<{node: LocaleNode}> = data?.[localeJsonNodeName]?.edges || [];

  if (languages.length > 1 && localeNodes.length === 0 && process.env.NODE_ENV === 'development') {
    console.error(
      outdent`
      No translations were found in "${localeJsonNodeName}" key for "${originalPath}". 
      You need to add a graphql query to every page like this:
      
      export const query = graphql\`
        query($language: String!) {
          ${localeJsonNodeName}: allLocale(language: {eq: $language}}) {
            edges {
              node {
                ns
                data
                language
              }
            }
          }
        }
      \`;
      `
    );
  }

  const namespaces = localeNodes.map(({node}) => node.ns);

  // We want to set default namespace to a page namespace if it exists
  // and use other namespaces as fallback
  // this way you dont need to specify namespaces in pages
  let defaultNS = i18nextOptions.defaultNS || 'translation';
  defaultNS = namespaces.find((ns) => ns !== defaultNS) || defaultNS;
  const fallbackNS = namespaces.filter((ns) => ns !== defaultNS);

  const resources: Resource = localeNodes.reduce<Resource>((res: Resource, {node}) => {
    const parsedData: ResourceKey = JSON.parse(node.data);

    if (!(node.language in res)) res[node.language] = {};

    res[node.language][node.ns] = parsedData;

    return res;
  }, {});

  const i18n = i18next.createInstance();

  i18n.init({
    ...i18nextOptions,
    resources,
    lng: language,
    fallbackLng: defaultLanguage,
    defaultNS,
    fallbackNS,
    react: {
      useSuspense: false
    }
  });

  if (i18n.language !== language) {
    i18n.changeLanguage(language);
  }

  const context = {
    routed,
    language,
    languages,
    originalPath,
    defaultLanguage,
    generateDefaultLanguagePage,
    siteUrl,
    path
  };

  return withI18next(i18n, context)(element);
}