|
| 1 | +/** |
| 2 | + * Copyright (c) Facebook, Inc. and its affiliates. |
| 3 | + * |
| 4 | + * This source code is licensed under the MIT license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + */ |
| 7 | + |
| 8 | +import React, {type ReactNode} from 'react'; |
| 9 | + |
| 10 | +// Workaround because it's difficult in MDX v1 to provide a MDX title as props |
| 11 | +// See https://github.com/facebook/docusaurus/pull/7152#issuecomment-1145779682 |
| 12 | +function extractMDXAdmonitionTitle(children: ReactNode): { |
| 13 | + mdxAdmonitionTitle: ReactNode | undefined; |
| 14 | + rest: ReactNode; |
| 15 | +} { |
| 16 | + const items = React.Children.toArray(children); |
| 17 | + const mdxAdmonitionTitle = items.find( |
| 18 | + (item) => |
| 19 | + React.isValidElement(item) && |
| 20 | + (item.props as {mdxType: string} | null)?.mdxType === |
| 21 | + 'mdxAdmonitionTitle', |
| 22 | + ) as JSX.Element | undefined; |
| 23 | + const rest = <>{items.filter((item) => item !== mdxAdmonitionTitle)}</>; |
| 24 | + return { |
| 25 | + mdxAdmonitionTitle: mdxAdmonitionTitle?.props.children, |
| 26 | + rest, |
| 27 | + }; |
| 28 | +} |
| 29 | + |
| 30 | +export function processAdmonitionProps< |
| 31 | + Props extends {readonly children: ReactNode; readonly title?: ReactNode}, |
| 32 | +>(props: Props): Props { |
| 33 | + const {mdxAdmonitionTitle, rest} = extractMDXAdmonitionTitle(props.children); |
| 34 | + const title = props.title ?? mdxAdmonitionTitle; |
| 35 | + return { |
| 36 | + ...props, |
| 37 | + // Do not return "title: undefined" prop |
| 38 | + // this might create unwanted props overrides when merging props |
| 39 | + // For example: {...default,...props} |
| 40 | + ...(title && {title}), |
| 41 | + children: rest, |
| 42 | + }; |
| 43 | +} |
0 commit comments