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

fix(html pipe): Generate proper identifiers for complex headings #273

Merged
merged 1 commit into from
Apr 22, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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