doc.silverstripe.org/src/utils/rewriteLink.ts

83 lines
2.0 KiB
TypeScript
Raw Normal View History

2019-11-08 03:40:20 +01:00
import { createElement, ReactElement } from 'react';
import { domToReact, DomElement, HTMLReactParserOptions } from 'html-react-parser';
import { Link } from 'gatsby';
import rewriteAPILink from './rewriteAPILink';
2019-11-14 03:05:03 +01:00
import { getCurrentNode, getCurrentVersion } from '../utils/nodes';
2019-11-08 03:40:20 +01:00
import path from 'path';
interface LinkAttributes {
href?: string;
};
const rewriteLink = (
attribs: LinkAttributes,
children: DomElement[],
parseOptions: HTMLReactParserOptions
): ReactElement|false => {
const { href } = attribs;
if (!href) {
return false;
}
const currentNode = getCurrentNode();
2019-11-14 03:05:03 +01:00
const version = getCurrentVersion();
2019-11-08 03:40:20 +01:00
// api links
if (href.match(/^api\:/)) {
const newHref = rewriteAPILink(href);
return createElement(
'a',
{ href: newHref, target: '_blank' },
domToReact(children, parseOptions)
);
}
// absolute links
if (href.match(/^https?/)) {
return createElement(
'a',
{ href, target: '_blank' },
domToReact(children, parseOptions)
);
}
// Relative to root
2019-11-14 03:05:03 +01:00
if (href.startsWith('/')) {
2019-11-08 03:40:20 +01:00
return createElement(
Link,
2019-11-14 03:05:03 +01:00
{
2019-11-14 03:25:03 +01:00
to: path.join('/', 'en', version, href),
2019-11-14 03:05:03 +01:00
className: 'gatsby-link'
},
2019-11-08 03:40:20 +01:00
domToReact(children, parseOptions)
)
}
// Relative to page
if (currentNode && currentNode.parentSlug) {
return createElement(
Link,
{
to: path.join(currentNode.parentSlug, href),
className: 'gatsby-link'
},
domToReact(children, parseOptions)
)
}
// All else fails, just return the link as is.
return createElement(
Link,
{
to: path.join('/', href),
className: 'gatsby-link',
},
domToReact(children, parseOptions)
);
}
export default rewriteLink;