@mintlify/common
Version:
Commonly shared code within Mintlify
68 lines (67 loc) • 2.44 kB
JavaScript
import { toHtml } from 'hast-util-to-html';
import { visit } from 'unist-util-visit';
import { isMdxJsxFlowElementHast } from '../../lib/index.js';
const langFilename = (className) => {
switch (className) {
case 'language-shell':
return 'Bash';
case 'language-json':
return 'JSON';
case 'language-js':
return 'JavaScript';
default:
const language = className.substring(9);
return language.charAt(0).toUpperCase() + language.slice(1);
}
};
export const rehypeMdxExtractExamples = (mdxExtracts) => {
return (tree) => {
let request;
let response;
visit(tree, isMdxJsxFlowElementHast, (node, i, parent) => {
if (node.name === 'RequestExample') {
request = request !== null && request !== void 0 ? request : {
type: node.name,
children: parseChildren(node),
};
if (parent && i != null)
parent.children.splice(i, 1);
}
else if (node.name === 'ResponseExample') {
response = response !== null && response !== void 0 ? response : {
type: node.name,
children: parseChildren(node),
};
if (parent && i != null)
parent.children.splice(i, 1);
}
});
mdxExtracts.codeExamples = {
request,
response,
};
return tree;
};
};
const parseChildren = (node) => {
return node.children.filter(isMdxJsxFlowElementHast).flatMap((child) => {
var _a;
const preComponent = child.children[0];
if ((preComponent === null || preComponent === void 0 ? void 0 : preComponent.type) !== 'element')
return [];
const html = toHtml(preComponent);
let filename = Array.isArray(preComponent.properties.className) &&
typeof preComponent.properties.className[0] === 'string'
? langFilename(preComponent.properties.className[0])
: '';
if ('attributes' in child && typeof ((_a = child.attributes[0]) === null || _a === void 0 ? void 0 : _a.value) === 'string') {
filename = child.attributes[0].value;
}
return [
{
filename,
html,
},
];
});
};