2023-07-09 14:19:21 +08:00
|
|
|
import { Parent } from 'unist';
|
|
|
|
import { visit } from 'unist-util-visit';
|
2022-07-17 21:40:41 +08:00
|
|
|
|
|
|
|
export default function remarkCodeTitles() {
|
2022-10-07 13:55:39 +08:00
|
|
|
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
|
|
|
}
|