@mintlify/common
Version:
Commonly shared code within Mintlify
59 lines (58 loc) • 2.08 kB
JavaScript
import { visit } from 'unist-util-visit';
export const remarkSplitTabs = () => (tree) => {
const tabsToProcess = [];
visit(tree, 'mdxJsxFlowElement', (node, index, parent) => {
if (node.name === 'Tabs' && typeof index === 'number' && parent) {
tabsToProcess.push({ node, index, parent });
}
});
// process in reverse document order so splices don't shift the saved
// indices of earlier siblings or clone-before-split nested Tabs
for (const { node, index, parent } of tabsToProcess.reverse()) {
const numberOfTabs = node.children.length;
if (numberOfTabs <= 1)
continue;
const newNodes = [];
for (let i = 0; i < numberOfTabs; i++) {
const newNode = structuredClone(node);
const defaultTabIndexAttr = newNode.attributes.find(isDefaultTabIndexAttr);
if (defaultTabIndexAttr) {
defaultTabIndexAttr.value = formValueExpression(i);
}
else {
newNode.attributes.push({
type: 'mdxJsxAttribute',
name: 'defaultTabIndex',
value: formValueExpression(i),
});
}
newNodes.push(newNode);
}
parent.children.splice(index, 1, ...newNodes);
}
};
const isDefaultTabIndexAttr = (attr) => {
return attr.type === 'mdxJsxAttribute' && attr.name === 'defaultTabIndex';
};
const formValueExpression = (value) => {
return {
type: 'mdxJsxAttributeValueExpression',
value: value.toString(),
data: {
estree: {
type: 'Program',
body: [
{
type: 'ExpressionStatement',
expression: {
type: 'Literal',
value: value,
raw: value.toString(),
},
},
],
sourceType: 'module',
},
},
};
};