Skip to content
This repository has been archived by the owner on Feb 28, 2022. It is now read-only.

Commit

Permalink
fix(html pipe): Generate proper identifiers for complex headings (#273)
Browse files Browse the repository at this point in the history
Properly support complex headers that include child elements (strong, em, code, etc.) when
automatically generating the heading identifiers

fix #26
  • Loading branch information
ramboz authored and tripodsan committed Apr 22, 2019
1 parent 7fbf06e commit 8c1b447
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 15 deletions.
15 changes: 2 additions & 13 deletions src/utils/heading-handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
* governing permissions and limitations under the License.
*/
const fallback = require('mdast-util-to-hast/lib/handlers/heading');
const toString = require('mdast-util-to-string');
const GithubSlugger = require('github-slugger');

/**
Expand All @@ -25,18 +26,6 @@ class HeadingHandler {
this.slugger = new GithubSlugger();
}

/**
* Gets the text content for the specified heading.
* @param {UnistParent~Heading} heading The heading node
* @returns {string} The text content for the heading
*/
static getTextContent(heading) {
return heading.children
.filter(el => el.type === 'text')
.map(el => el.value)
.join('').trim();
}

/**
* Reset the heading counter
*/
Expand All @@ -50,7 +39,7 @@ class HeadingHandler {
handler() {
return (h, node) => {
// Prepare the heading id
const headingIdentifier = this.slugger.slug(HeadingHandler.getTextContent(node));
const headingIdentifier = this.slugger.slug(toString(node));

// Inject the id after transformation
const n = Object.assign({}, node);
Expand Down
36 changes: 36 additions & 0 deletions test/fixtures/heading-ids.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,42 @@
],
"depth": 4,
"type": "heading"
},
{
"children": [
{
"children": [
{
"type": "text",
"value": "Foo"
}
],
"type": "strong"
},
{
"type": "text",
"value": " "
},
{
"children": [
{
"type": "text",
"value": "Bar"
}
],
"type": "emphasis"
},
{
"type": "text",
"value": " "
},
{
"type": "inlineCode",
"value": "Baz"
}
],
"depth": 1,
"type": "heading"
}
]
}
4 changes: 3 additions & 1 deletion test/fixtures/heading-ids.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@

### Bar

#### Bar-1
#### Bar-1

# **Foo** _bar_ `baz`
3 changes: 2 additions & 1 deletion test/testMdastToVDOM.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ describe('Test MDAST to VDOM Transformation', () => {
<h3 id="baz">Baz</h1>
<h2 id="qux">Qux</h2>
<h3 id="bar-1">Bar</h3>
<h4 id="bar-1-1">Bar-1</h4>`,
<h4 id="bar-1-1">Bar-1</h4>
<h1 id="foo-bar-baz"><strong>Foo</strong> <em>Bar</em> <code>Baz</code></h1>`,
);
});

Expand Down

0 comments on commit 8c1b447

Please sign in to comment.