aboutsummaryrefslogtreecommitdiff
path: root/src/rehype/admonition-title-to-heading-after-toc.js
diff options
context:
space:
mode:
Diffstat (limited to 'src/rehype/admonition-title-to-heading-after-toc.js')
-rw-r--r--src/rehype/admonition-title-to-heading-after-toc.js41
1 files changed, 41 insertions, 0 deletions
diff --git a/src/rehype/admonition-title-to-heading-after-toc.js b/src/rehype/admonition-title-to-heading-after-toc.js
new file mode 100644
index 00000000..5355983d
--- /dev/null
+++ b/src/rehype/admonition-title-to-heading-after-toc.js
@@ -0,0 +1,41 @@
+import {visit} from 'unist-util-visit';
+import {inspect} from 'unist-util-inspect';
+
+const plugin = (options) => {
+ const transformer = async (ast) => {
+ let hId = null;
+ let hContent = null;
+ visit(ast, 'element', (node, index, parent) => {
+ if (/^h[2-6]$/.test(node.tagName) && node.properties && node.properties.id) {
+ // H要素(h2~h6)を見つけた場合
+
+ // IDとタイトルの冒頭Text部を取得する
+ hId = node.properties.id;
+ hContent = node.children ? node.children[0].value :
+ node.children[0].children[0] ? node.children[0].children[0].value : '';
+
+ const nextNode = parent.children[index + 1];
+ if (nextNode && nextNode.tagName === 'admonition') {
+ // H要素に続くadmonition(div)を見つけた場合
+
+ // admonitionタイトルの冒頭Text部分を取得(properties.titleもしくはchildren[0].children[0].value)
+ const nextNodeTitle = nextNode.properties.title ? nextNode.properties.title :
+ nextNode.children[0] && nextNode.children[0].children[0] ? nextNode.children[0].children[0].value : '';
+
+ //console.log(nextNodeTitle.replace(/^#+/, '').trim(), hId);
+ if(/^##/.test(nextNodeTitle) && nextNodeTitle.replace(/^#+/, '').trim() === hContent.trim()) {
+ // #で始まっていて、タイトル冒頭部が同じ場合
+ // divのidをHタグのidに設定
+ nextNode.properties.id = hId;
+ //console.log(nextNode);
+ // H要素を削除
+ parent.children.splice(index, 1);
+ }
+ }
+ }
+ });
+ };
+ return transformer;
+};
+
+export default plugin; \ No newline at end of file