astro/packages/markdown/remark/src/remark-mdxish.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

57 lines
1.6 KiB
TypeScript
Raw Normal View History

2022-05-24 22:03:29 +00:00
import { mdxjs } from 'micromark-extension-mdxjs';
import { mdxFromMarkdown, mdxToMarkdown } from './mdast-util-mdxish.js';
import type * as fromMarkdown from 'mdast-util-from-markdown';
import type { Tag } from 'mdast-util-mdx-jsx';
export default function remarkMdxish(this: any, options = {}) {
2022-05-24 22:03:29 +00:00
const data = this.data();
2022-05-24 22:03:29 +00:00
add('micromarkExtensions', mdxjs(options));
add('fromMarkdownExtensions', makeFromMarkdownLessStrict(mdxFromMarkdown()));
2022-05-24 22:03:29 +00:00
add('toMarkdownExtensions', mdxToMarkdown());
2022-05-24 22:03:29 +00:00
function add(field: string, value: unknown) {
const list = data[field] ? data[field] : (data[field] = []);
list.push(value);
}
}
function makeFromMarkdownLessStrict(extensions: fromMarkdown.Extension[]) {
2022-06-03 13:39:43 +00:00
extensions.forEach((extension) => {
// Fix exit handlers that are too strict
2022-06-03 13:39:43 +00:00
['mdxJsxFlowTag', 'mdxJsxTextTag'].forEach((exitHandler) => {
if (!extension.exit || !extension.exit[exitHandler]) return;
extension.exit[exitHandler] = chainHandlers(fixSelfClosing, extension.exit[exitHandler]);
});
});
return extensions;
}
const selfClosingTags = new Set([
2022-06-03 13:39:43 +00:00
'area',
'base',
'br',
'col',
'embed',
'hr',
'img',
'input',
'link',
'meta',
'source',
'track',
'wbr',
]);
function fixSelfClosing(this: fromMarkdown.CompileContext) {
const tag = this.getData('mdxJsxTag') as Tag;
2022-06-03 13:39:43 +00:00
if (tag.name && selfClosingTags.has(tag.name)) tag.selfClosing = true;
}
function chainHandlers(...handlers: fromMarkdown.Handle[]) {
2022-06-03 13:39:43 +00:00
return function handlerChain(this: fromMarkdown.CompileContext, token: fromMarkdown.Token) {
handlers.forEach((handler) => handler.call(this, token));
};
}