feat: upgrade to MDX v2 (#8288)

Co-authored-by: Armano <armano2@users.noreply.github.com>
This commit is contained in:
Sébastien Lorber 2023-04-21 19:48:57 +02:00 committed by GitHub
parent 10f161d578
commit bf913aea2a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
161 changed files with 4028 additions and 2821 deletions

View file

@ -6,31 +6,99 @@
*/
import escapeHtml from 'escape-html';
import toString from 'mdast-util-to-string';
import type {Parent} from 'unist';
import type {PhrasingContent, Heading} from 'mdast';
// @ts-expect-error: TODO see https://github.com/microsoft/TypeScript/issues/49721
import type {MdxJsxAttributeValueExpression} from 'mdast-util-mdx';
export function stringifyContent(node: Parent): string {
return (node.children as PhrasingContent[]).map(toValue).join('');
export function stringifyContent(
node: Parent,
toString: (param: unknown) => string, // TODO weird but works): string {
): string {
return (node.children as PhrasingContent[])
.map((item) => toValue(item, toString))
.join('');
}
export function toValue(node: PhrasingContent | Heading): string {
export function toValue(
node: PhrasingContent | Heading,
toString: (param: unknown) => string, // TODO weird but works
): string {
switch (node.type) {
case 'mdxJsxTextElement': {
const tag = node.name;
return `<${tag}>${stringifyContent(node, toString)}</${tag}>`;
}
case 'text':
return escapeHtml(node.value);
case 'heading':
return stringifyContent(node);
return stringifyContent(node, toString);
case 'inlineCode':
return `<code>${escapeHtml(node.value)}</code>`;
case 'emphasis':
return `<em>${stringifyContent(node)}</em>`;
return `<em>${stringifyContent(node, toString)}</em>`;
case 'strong':
return `<strong>${stringifyContent(node)}</strong>`;
return `<strong>${stringifyContent(node, toString)}</strong>`;
case 'delete':
return `<del>${stringifyContent(node)}</del>`;
return `<del>${stringifyContent(node, toString)}</del>`;
case 'link':
return stringifyContent(node);
return stringifyContent(node, toString);
default:
return toString(node);
}
}
export function assetRequireAttributeValue(
requireString: string,
hash: string,
): MdxJsxAttributeValueExpression {
return {
type: 'mdxJsxAttributeValueExpression',
value: `require("${requireString}").default${hash && ` + '${hash}'`}`,
data: {
estree: {
type: 'Program',
body: [
{
type: 'ExpressionStatement',
expression: {
type: 'BinaryExpression',
left: {
type: 'MemberExpression',
object: {
type: 'CallExpression',
callee: {
type: 'Identifier',
name: 'require',
},
arguments: [
{
type: 'Literal',
value: requireString,
raw: `"${requireString}"`,
},
],
optional: false,
},
property: {
type: 'Identifier',
name: 'default',
},
computed: false,
optional: false,
},
operator: '+',
right: {
type: 'Literal',
value: hash,
raw: `"${hash}"`,
},
},
},
],
sourceType: 'module',
comments: [],
},
},
};
}