tailwind-nextjs-blog/lib/remark-code-title.ts

39 lines
1.0 KiB
TypeScript
Raw Normal View History

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