ついにsection
タグを書くのが面倒になってきたので、自動でどうにかしようという試み。
- 現在のレベルが1で、見出しレベルも1
- 現在のレベルが1より上で、現在のレベルと見出しレベルが同じ
- 現在のレベルが1より上で、見出しレベルが現在のレベルより小さい
- 現在のレベルより見出しレベルが大きい
パターン1では見出しだけ出力する。パターン4ではsection
開始タグだけを、パターン2ではsection
終了タグと開始タグを、パターン3ではsection
終了タグのみを、追加して出力すればよい。
またテーマの区切りでは現在のレベルが1の時だけそのまま出力し、そうでなければsection
終了タグを追加して出力する。
# Level 1-1
This is a level 1 section.
# Level 1-2
This is a level 1 section.
## Level 2-1
This is a level 2 section.
## Level 2-2
This is a level 2 section.
### Level 3-1
This is a level 3 section.
* * *
This is a level 2 section.
## Level 2-3
This is a level 2 section.
* * *
This is a level 1 section.
<h1>Level 1-1</h1>
<p>This is a level 1 section.</p>
<h1>Level 1-2</h1>
<p>This is a level 1 section.</p>
<section>
<h1>Level 2-1</h1>
<p>This is a level 2 section.</p>
</section>
<section>
<h1>Level 2-2</h1>
<p>This is a level 2 section.</p>
<section>
<h1>Level 3-1</h1>
<p>This is a level 3 section.</p>
</section>
<hr>
<p>This is a level 2 section.</p>
</section>
<section>
<h1>Level 2-3</h1>
<p>This is a level 2 section.</p>
</section>
<hr>
<p>This is a level 1 section.</p>
const marked = require("marked");
let currentLevel = 1;
const markupHeading = (text, level) => {
if (currentLevel === 1 && level === 1) {
return `<h1>${text}</h1>
`;
}
if (currentLevel > 1 && level === currentLevel) {
return `</section>
<section>
<h1>${text}</h1>
`;
}
if (currentLevel > 1 && level < currentLevel) {
currentLevel = level;
return `</section>
<h1>${text}</h1>
`;
}
currentLevel = level;
return `<section>
<h1>${text}</h1>
`;
};
const markupThematicBreak = () => {
if (currentLevel === 1) {
return `<hr>
`;
}
currentLevel = currentLevel - 1;
return `</section>
<hr>
`;
};
const renderer = new marked.Renderer();
renderer.heading = markupHeading;
renderer.hr = markupThemeticBreak;
module.exports = t => marked(t, {
renderer: renderer
});