Skip to content

Commit

Permalink
feat(toc): Support unnumbered headings (#4871)
Browse files Browse the repository at this point in the history
  • Loading branch information
Cerallin authored Mar 6, 2022
1 parent 57c54f2 commit 24d8c31
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
7 changes: 4 additions & 3 deletions lib/plugins/helper/toc.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ function tocHelper(str, options = {}) {
const { level, id, text } = el;
const href = id ? `#${encodeURL(id)}` : null;

lastNumber[level - 1]++;
if (!el.unnumbered) {
lastNumber[level - 1]++;
}

for (let i = level; i <= 5; i++) {
lastNumber[i] = 0;
Expand All @@ -55,8 +57,7 @@ function tocHelper(str, options = {}) {
result += `<a class="${className}-link">`;
}


if (listNumber) {
if (listNumber && !el.unnumbered) {
result += `<span class="${className}-number">`;

for (let i = firstLevel - 1; i < level; i++) {
Expand Down
42 changes: 42 additions & 0 deletions test/scripts/helpers/toc.js
Original file line number Diff line number Diff line change
Expand Up @@ -434,4 +434,46 @@ describe('toc', () => {

toc(input).should.eql('');
});

it('unnumbered headings', () => {
const className = 'toc';

const input = [
'<h3>Title 1</h3>',
'<h3>Title 2</h3>',
'<h4>Title 2.1</h4>',
'<h3 data-toc-unnumbered="true">Reference</h3>'
].join('');

const expected = [
`<ol class="${className}">`,
`<li class="${className}-item ${className}-level-3">`,
`<a class="${className}-link"><span class="${className}-number">1.</span> `,
`<span class="${className}-text">Title 1</span>`,
'</a>',
'</li>',
`<li class="${className}-item ${className}-level-3">`,
`<a class="${className}-link">`,
`<span class="${className}-number">2.</span> `,
`<span class="${className}-text">Title 2</span>`,
'</a>',
`<ol class="${className}-child">`,
`<li class="${className}-item ${className}-level-4">`,
`<a class="${className}-link">`,
`<span class="${className}-number">2.1.</span> `,
`<span class="${className}-text">Title 2.1</span>`,
'</a>',
'</li>',
'</ol>',
'</li>',
`<li class="${className}-item ${className}-level-3">`,
`<a class="${className}-link">`,
`<span class="${className}-text">Reference</span>`,
'</a>',
'</li>',
'</ol>'
].join('');

toc(input, { list_number: true, class: className }).should.eql(expected);
});
});

0 comments on commit 24d8c31

Please sign in to comment.