Modified HTML for Algolia Crawler (#5441)

* Modified HTML for Algolia Crawler
* Added anchor tags within user-guide headers

To implement Algolia correctly, my changes would need to be deployed
first, as it cannot run on localhost. In the meantime, I simulated
Algolia crawling locally using Cheerio, and it worked successfully on my
end.
This commit is contained in:
Ady Beraud
2024-05-16 17:24:48 +03:00
committed by GitHub
parent afad993bb3
commit 9125e958dc
4 changed files with 52 additions and 4 deletions

View File

@ -0,0 +1,40 @@
import React, {
Children,
cloneElement,
isValidElement,
ReactElement,
ReactNode,
} from 'react';
export const wrapHeadingsWithAnchor = (children: ReactNode): ReactNode => {
const hasChildren = (
element: ReactElement,
): element is ReactElement<{ children: ReactNode }> => {
return element.props.children !== undefined;
};
return Children.map(children, (child) => {
if (
isValidElement(child) &&
typeof child.type === 'string' &&
['h1', 'h2', 'h3', 'h4'].includes(child.type)
) {
const id = child.props.children
.toString()
.replace(/\s+/g, '-')
.toLowerCase();
return cloneElement(child as ReactElement<any>, {
id: id,
children: <a href={`#${id}`}>{child.props.children}</a>,
});
}
if (isValidElement(child) && hasChildren(child)) {
return cloneElement(child, {
children: wrapHeadingsWithAnchor(child.props.children),
});
}
return child;
});
};