@mintlify/common
Version:
Commonly shared code within Mintlify
53 lines (52 loc) • 2.31 kB
JavaScript
import { visit } from 'unist-util-visit';
const exampleNames = ['RequestExample', 'ResponseExample'];
const flowElementType = 'mdxJsxFlowElement';
function isElement(node, key = 'type', element = 'element') {
return node != undefined && node[key] === element;
}
function addCodeBlocks(tree) {
const preTree = { children: [] };
visit(tree, (node, i, parent) => {
var _a, _b;
if (parent == null || i == null || !isElement(node) || !isElement(node, 'tagName', 'pre')) {
return;
}
const code = node.children[0];
if (!isElement(code, 'tagName', 'code'))
return;
let filename = undefined;
let isExpandable = false;
const isFlowElement = isElement(parent, 'type', flowElementType);
const parentName = isFlowElement ? parent.name : undefined;
if (parentName && exampleNames.includes(parentName)) {
const parentType = parentName.slice(0, -7);
filename = i === 0 ? parentType : `${parentType} ${i + 1}`;
isExpandable = filename.includes('[expandable]');
filename = filename.replaceAll('[expandable]', '').trim();
if (!((_a = code.data) === null || _a === void 0 ? void 0 : _a.meta)) {
code.data = Object.assign(Object.assign({}, code.data), { meta: filename });
}
}
if (((_b = code.data) === null || _b === void 0 ? void 0 : _b.meta) && typeof code.data.meta === 'string') {
filename = code.data.meta;
isExpandable = filename.includes('[expandable]');
filename = filename.replaceAll('[expandable]', '').trim();
}
const wrap = {
type: flowElementType,
name: 'CodeBlock',
attributes: [
{ type: 'mdxJsxAttribute', name: 'filename', value: filename !== null && filename !== void 0 ? filename : '' },
{ type: 'mdxJsxAttribute', name: 'expandable', value: isExpandable.toString() },
],
data: { _mdxExplicitJsx: true },
children: [],
};
wrap.children = [node];
parent.children[i] = wrap;
});
tree.children = [...preTree.children, ...tree.children];
}
export function rehypeCodeBlocks() {
return addCodeBlocks;
}