import type { PropsWithChildren } from 'react'; import React, { Component } from 'react'; import type { DocsContextProps, DocsRenderFunction, Parameters, Renderer, } from 'storybook/internal/types'; import { renderElement, unmountElement } from '../../../renderers/react/src/react-dom-client.tsx'; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore (these types only work once the package is compiled) import { AnchorMdx, CodeOrSourceMdx, Docs, HeadersMdx } from '@storybook/addon-docs/blocks'; // TS doesn't like that we export a component with types that it doesn't know about (TS4203) export const defaultComponents: Record = { code: CodeOrSourceMdx, a: AnchorMdx, ...HeadersMdx, }; class ErrorBoundary extends Component< PropsWithChildren<{ showException: (err: Error) => void; }> > { state = { hasError: false }; static getDerivedStateFromError() { return { hasError: true }; } componentDidCatch(err: Error) { const { showException } = this.props; showException(err); } render() { const { hasError } = this.state; const { children } = this.props; return hasError ? null : <>{children}; } } export class DocsRenderer { public render: DocsRenderFunction; public unmount: (element: HTMLElement) => void; constructor() { this.render = async ( context: DocsContextProps, docsParameter: Parameters, element: HTMLElement ): Promise => { const components = { ...defaultComponents, ...docsParameter?.components, }; const TDocs = Docs as typeof Docs; return new Promise((resolve, reject) => { import('@mdx-js/react') .then(({ MDXProvider }) => // We use a `key={}` here to reset the `hasError` state each time we render ErrorBoundary renderElement( , element ) ) .then(() => resolve()); }); }; this.unmount = (element: HTMLElement) => { unmountElement(element); }; } }