aboutsummaryrefslogtreecommitdiff
path: root/src/remark/admonition-title-to-heading-before-toc.js
blob: 34d2f9faef37129b708a156f5747ec7f2cf5add7 (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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import {visit, SKIP, EXIT, INDEX, CONTINUE} from 'unist-util-visit';
import {inspect} from 'unist-util-inspect'

const plugin = (options) => {
  const transformer = async (ast) => {
    let hId = null;
    let hContent = null;
    let offset = 0;

    // Visitor関数を定義
    const visitor = ((node, index, parent) => {
      if (node.type === 'containerDirective') {
        const val = node.children[0].children[0].value;
        if(/^##/.test(val)) {
          // headingノードをparentのchildrenに追加
          parent.children.splice(index, 0, {
            type: 'heading',
            depth: 4, // Headingの深さを適切に設定
            children: [{ type: 'text', value: val.replace(/^#+/, '').trim() }],
          });
          //次に検索するのはindexを2つ飛ばしたノード。
          return index + 2;
        }
      }
    });

    visit(ast, 'containerDirective', visitor);
    /*
    visit(ast, 'containerDirective', (node, index, parent) => {
      //console.log(node);
      parent.children.splice(index, 0, {type: 'heading', depth: 4, children:[{type: 'text', value: 'テスト'}]});
      index++;
      //offset++;
      //console.log(offset);
      //return EXIT;
        //        if (/^h[3-6]$/.test(node.tagName) && node.properties && node.properties.id) {
            // h3~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;