From f85345bc0a7e2d9126f3a7082f9533e41eae02e6 Mon Sep 17 00:00:00 2001 From: sebastien Date: Wed, 14 Feb 2024 12:23:59 +0100 Subject: [PATCH] Improve APITable error message in case of invalid Markdown table --- website/src/components/APITable/index.tsx | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/website/src/components/APITable/index.tsx b/website/src/components/APITable/index.tsx index 049e2d4bcfd4..0772f163badd 100644 --- a/website/src/components/APITable/index.tsx +++ b/website/src/components/APITable/index.tsx @@ -22,11 +22,20 @@ interface Props { } // ReactNode equivalent of HTMLElement#innerText -function getText(node: ReactElement): string { +function getRowName(node: ReactElement): string { let curNode: ReactNode = node; while (isValidElement(curNode)) { [curNode] = React.Children.toArray(curNode.props.children); } + if (typeof curNode !== 'string') { + throw new Error( + `Could not extract APITable row name from JSX tree:\n${JSON.stringify( + node, + null, + 2, + )}`, + ); + } return curNode as string; } @@ -37,7 +46,7 @@ function APITableRow( }: {name: string | undefined; children: ReactElement>}, ref: React.ForwardedRef, ) { - const entryName = getText(children); + const entryName = getRowName(children); const id = name ? `${name}-${entryName}` : entryName; const anchor = `#${id}`; const history = useHistory(); @@ -71,6 +80,11 @@ const APITableRowComp = React.forwardRef(APITableRow); * should be generally correct in the MDX context. */ export default function APITable({children, name}: Props): JSX.Element { + if (children.type !== 'table') { + throw new Error( + 'Bad usage of APITable component.\nIt is probably that your Markdown table is malformed.\nMake sure to double-check you have the appropriate number of columns for each table row.', + ); + } const [thead, tbody] = React.Children.toArray(children.props.children) as [ ReactElement<{children: ReactElement[]}>, ReactElement<{children: ReactElement[]}>,