|
8 | 8 | import escapeHtml from 'escape-html';
|
9 | 9 | import type {Parent} from 'unist';
|
10 | 10 | import type {PhrasingContent, Heading} from 'mdast';
|
11 |
| -// @ts-expect-error: TODO see https://github.com/microsoft/TypeScript/issues/49721 |
12 |
| -import type {MdxJsxAttributeValueExpression} from 'mdast-util-mdx'; |
| 11 | +import type { |
| 12 | + MdxJsxAttribute, |
| 13 | + MdxJsxAttributeValueExpression, |
| 14 | + MdxJsxTextElement, |
| 15 | + // @ts-expect-error: TODO see https://github.com/microsoft/TypeScript/issues/49721 |
| 16 | +} from 'mdast-util-mdx'; |
13 | 17 |
|
14 | 18 | export function stringifyContent(
|
15 | 19 | node: Parent,
|
16 |
| - toString: (param: unknown) => string, // TODO weird but works): string { |
| 20 | + toString: (param: unknown) => string, // TODO weird but works |
17 | 21 | ): string {
|
18 | 22 | return (node.children as PhrasingContent[])
|
19 | 23 | .map((item) => toValue(item, toString))
|
20 | 24 | .join('');
|
21 | 25 | }
|
22 | 26 |
|
| 27 | +// TODO This is really a workaround, and not super reliable |
| 28 | +// For now we only support serializing tagName, className and content |
| 29 | +// Can we implement the TOC with real JSX nodes instead of html strings later? |
| 30 | +function mdxJsxTextElementToHtml( |
| 31 | + element: MdxJsxTextElement, |
| 32 | + toString: (param: unknown) => string, // TODO weird but works |
| 33 | +): string { |
| 34 | + const tag = element.name; |
| 35 | + |
| 36 | + const attributes = element.attributes.filter( |
| 37 | + (child): child is MdxJsxAttribute => child.type === 'mdxJsxAttribute', |
| 38 | + ); |
| 39 | + |
| 40 | + const classAttribute = |
| 41 | + attributes.find((attr) => attr.name === 'className') ?? |
| 42 | + attributes.find((attr) => attr.name === 'class'); |
| 43 | + |
| 44 | + const classAttributeString = classAttribute |
| 45 | + ? `class="${escapeHtml(String(classAttribute.value))}"` |
| 46 | + : ``; |
| 47 | + |
| 48 | + const allAttributes = classAttributeString ? ` ${classAttributeString}` : ''; |
| 49 | + |
| 50 | + const content = stringifyContent(element, toString); |
| 51 | + |
| 52 | + return `<${tag}${allAttributes}>${content}</${tag}>`; |
| 53 | +} |
| 54 | + |
23 | 55 | export function toValue(
|
24 | 56 | node: PhrasingContent | Heading,
|
25 | 57 | toString: (param: unknown) => string, // TODO weird but works
|
26 | 58 | ): string {
|
27 | 59 | switch (node.type) {
|
28 | 60 | case 'mdxJsxTextElement': {
|
29 |
| - const tag = node.name; |
30 |
| - return `<${tag}>${stringifyContent(node, toString)}</${tag}>`; |
| 61 | + return mdxJsxTextElementToHtml(node as MdxJsxTextElement, toString); |
31 | 62 | }
|
32 | 63 | case 'text':
|
33 | 64 | return escapeHtml(node.value);
|
|
0 commit comments