Skip to content

Instantly share code, notes, and snippets.

@hail2u
Created July 29, 2018 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hail2u/a33cbefae7be51b2485e2a3c714c1d3c to your computer and use it in GitHub Desktop.
Save hail2u/a33cbefae7be51b2485e2a3c714c1d3c to your computer and use it in GitHub Desktop.

見出しとテーマの区切りから自動セクショニング

ついにsectionタグを書くのが面倒になってきたので、自動でどうにかしようという試み。

  1. 現在のレベルが1で、見出しレベルも1
  2. 現在のレベルが1より上で、現在のレベルと見出しレベルが同じ
  3. 現在のレベルが1より上で、見出しレベルが現在のレベルより小さい
  4. 現在のレベルより見出しレベルが大きい

パターン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
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment