aboutsummaryrefslogtreecommitdiff
path: root/src/rehype/admonition-title-to-heading.js
blob: d84b27b22c9da190c278d177e0df444e835ee2a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import {visit} from 'unist-util-visit';

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) {
            // h2~h6のタグを見つけたら
            hId = node.properties.id;
            hContent = node.children && node.children[0] ? node.children[0].value : '';
            // h3~h6タグの隣にあるdivタグを探す
            const nextNode = parent.children[index + 1];
            if (nextNode && nextNode.tagName === 'admonition') {
              // 該当のdiv要素を見つけたらHタグの内容とline-5の#以降の文字列が一致した場合
                const contentAfterHash = nextNode.properties.title ? nextNode.properties.title.replace(/^#+/, '').trim() : '';

                if (contentAfterHash === hContent.trim()) {
                    // Hタグのidを取得しそれをdivのidに設定
                    nextNode.properties.id = hId;
                    // Hタグを削除
                    parent.children.splice(index, 1);
                }
            }
          }
        });
  };
  return transformer;
};

export default plugin;