tailwind-nextjs-blog/lib/remark-code-title.ts
Ivan Li 1536ffa319
Some checks failed
🚀 Build and deploy by ftp / 🎉 Deploy (push) Failing after 44s
chore(deps): update deps.
2023-07-09 06:19:21 +00:00

40 lines
1.0 KiB
TypeScript

import { Parent } from 'unist';
import { visit } from 'unist-util-visit';
export default function remarkCodeTitles() {
return (tree: Parent & { lang?: string }) =>
visit(
tree,
'code',
(node: Parent & { lang?: string }, index, parent: Parent) => {
const nodeLang = node.lang || '';
let language = '';
let title = '';
if (nodeLang.includes(':')) {
language = nodeLang.slice(0, nodeLang.search(':'));
title = nodeLang.slice(nodeLang.search(':') + 1, nodeLang.length);
}
if (!title) {
return;
}
const className = 'remark-code-title';
const titleNode = {
type: 'mdxJsxFlowElement',
name: 'div',
attributes: [
{ type: 'mdxJsxAttribute', name: 'className', value: className },
],
children: [{ type: 'text', value: title }],
data: { _xdmExplicitJsx: true },
};
parent.children.splice(index, 0, titleNode);
node.lang = language;
}
);
}