Docs: handle errors gracefully when extracting headings from JSX

This commit is contained in:
gbuomprisco
2024-11-01 15:03:42 +08:00
parent 9681d51a08
commit 124edb006e

View File

@@ -53,6 +53,7 @@ export function extractHeadingsFromJSX(jsx: {
function getTextContent( function getTextContent(
children: React.ReactElement[] | string | React.ReactElement, children: React.ReactElement[] | string | React.ReactElement,
): string { ): string {
try {
if (typeof children === 'string') { if (typeof children === 'string') {
return children; return children;
} }
@@ -68,12 +69,18 @@ export function extractHeadingsFromJSX(jsx: {
} }
).children ).children
) { ) {
return getTextContent((children.props as { children: React.ReactElement }).children); return getTextContent(
(children.props as { children: React.ReactElement }).children,
);
} }
return ''; return '';
} catch {
return '';
}
} }
try {
jsx.props.children.forEach((node) => { jsx.props.children.forEach((node) => {
if (!node || typeof node !== 'object' || !('type' in node)) { if (!node || typeof node !== 'object' || !('type' in node)) {
return; return;
@@ -126,6 +133,9 @@ export function extractHeadingsFromJSX(jsx: {
}); });
return headings; return headings;
} catch {
return [];
}
} }
function generateSlug(text: string): string { function generateSlug(text: string): string {