Skip to content

Commit

Permalink
feat(toc_obj): Support unnumbered headings (#269)
Browse files Browse the repository at this point in the history
* feat(toc_obj): Support unnumbered headings

* Update readme

* Rollback TOC

* Fix typo

* Fix lint
  • Loading branch information
Cerallin committed Jan 29, 2022
1 parent ab5ad9d commit 837008b
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
9 changes: 8 additions & 1 deletion README.md
Expand Up @@ -544,7 +544,7 @@ wordWrap('Once upon a time', {width: 1})

### tocObj(str, [options])

Generate a table of contents in JSON format based on the given html string.
Generate a table of contents in JSON format based on the given html string. Headings with attribute `data-toc-unnumbered="true"` will be marked as unnumbered.

Option | Description | Default
--- | --- | ---
Expand Down Expand Up @@ -601,6 +601,13 @@ tocObj(html, { max_depth: 2 });
{ text: 'Title 2.1', id: 'title_2_1', level: 2 },
]
*/

tocObj('<h1 id="reference" data-toc-unnumbered="true">Reference</h1>')
/*
[
{ text: 'Reference', id: 'reference', level: 1, unnumbered: true }
]
*/
```

### truncate(str, [options])
Expand Down
12 changes: 11 additions & 1 deletion lib/toc_obj.js
Expand Up @@ -13,6 +13,13 @@ const getId = ({ attribs = {}, parent }) => {
return attribs.id || (!parent ? '' : getId(parent));
};

/**
* Identify a heading that to be unnumbered or not.
*/
const isUnnumbered = ({ attribs = {} }) => {
return attribs['data-toc-unnumbered'] === 'true';
};

function tocObj(str, options = {}) {
const { min_depth, max_depth } = Object.assign({
min_depth: 1,
Expand All @@ -31,6 +38,7 @@ function tocObj(str, options = {}) {
const el = headings[i];
const level = +el.name[1];
const id = getId(el);
const unnumbered = isUnnumbered(el);
let text = '';
for (const element of el.children) {
const elText = DomUtils.getText(element);
Expand All @@ -43,7 +51,9 @@ function tocObj(str, options = {}) {
}
if (!text) text = escapeHTML(DomUtils.getText(el));

result.push({ text, id, level });
const res = { text, id, level };
if (unnumbered) res.unnumbered = true;
result.push(res);
}

return result;
Expand Down
14 changes: 14 additions & 0 deletions test/toc_obj.spec.js
Expand Up @@ -165,5 +165,19 @@ describe('tocObj', () => {

result.forEach(str => str[0].text.should.eql('foobarbaz'));
});

it('unnumbered headings', () => {
const input = [
'<h1 id="title_1" data-toc-unnumbered="true">Title 1</h1>',
'<h2 data-toc-unnumbered="false" id="title_2">Title 2</h2>'
].join('');

const expected = [
{ text: 'Title 1', id: 'title_1', level: 1, unnumbered: true },
{ text: 'Title 2', id: 'title_2', level: 2 }
];

tocObj(input).should.eql(expected);
});
});
});

0 comments on commit 837008b

Please sign in to comment.