Skip to content

Commit e3c725b

Browse files
authored
fix(anchors): use entire heading text for auto named anchors (#384)
Auto-named anchors used only last _text_ token of heading. I fixed that, and now auto-naming is generated from contents of all _text_ tokens of heading. Also, it fixed some cases where inline markup got into auto-generated anchors and they became broken _Example markup_: `## _Lorem ~~ipsum **dolor** sit~~ amet_` __Before__: auto anchor is `#amet` __Now__: auto anchor is `#lorem-ipsum-dolor-sit-amet`
1 parent f0839ef commit e3c725b

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

src/transform/utils.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -50,20 +50,20 @@ export function headingInfo(tokens: Token[], idx: number) {
5050
const openToken = tokens[idx];
5151
const inlineToken = tokens[idx + 1];
5252

53-
let lastTextToken,
53+
let title = '',
5454
i = 0;
5555
while (inlineToken.children && i < inlineToken.children.length) {
5656
const token = inlineToken.children[i];
5757

5858
if (token.type === 'text') {
59-
lastTextToken = token;
59+
title += token.content;
6060
}
6161

6262
i++;
6363
}
6464

6565
const level = Number.parseInt(openToken.tag.slice(1), 10);
66-
const title = (lastTextToken && lastTextToken.content) || inlineToken.content;
66+
title ||= inlineToken.content;
6767

6868
return {
6969
level,

test/anchors.test.ts

+10
Original file line numberDiff line numberDiff line change
@@ -118,4 +118,14 @@ describe('Anchors', () => {
118118
'<p>After include</p>\n',
119119
);
120120
});
121+
122+
it('should add anchor with auto naming, using entire heading text', () => {
123+
expect(transformYfm('## _Lorem ~~ipsum **dolor** sit~~ amet_\n\nParagraph\n')).toBe(
124+
'<h2 id="lorem-ipsum-dolor-sit-amet">' +
125+
'<a href="#lorem-ipsum-dolor-sit-amet" class="yfm-anchor" aria-hidden="true">' +
126+
'<span class="visually-hidden">Lorem ipsum dolor sit amet</span></a>' +
127+
'<em>Lorem <s>ipsum <strong>dolor</strong> sit</s> amet</em></h2>\n' +
128+
'<p>Paragraph</p>\n',
129+
);
130+
});
121131
});

0 commit comments

Comments
 (0)