Skip to content

Commit

Permalink
Improve APITable error message in case of invalid Markdown table
Browse files Browse the repository at this point in the history
  • Loading branch information
slorber committed Feb 14, 2024
1 parent b5a2efb commit f85345b
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions website/src/components/APITable/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -37,7 +46,7 @@ function APITableRow(
}: {name: string | undefined; children: ReactElement<ComponentProps<'tr'>>},
ref: React.ForwardedRef<HTMLTableRowElement>,
) {
const entryName = getText(children);
const entryName = getRowName(children);
const id = name ? `${name}-${entryName}` : entryName;
const anchor = `#${id}`;
const history = useHistory();
Expand Down Expand Up @@ -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[]}>,
Expand Down

0 comments on commit f85345b

Please sign in to comment.