Skip to content

Commit

Permalink
fix(anchors): use entire heading text for auto named anchors
Browse files Browse the repository at this point in the history
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`
  • Loading branch information
d3m1d0v committed Mar 4, 2024
1 parent f0839ef commit 84ffa59
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/transform/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,20 +50,20 @@ export function headingInfo(tokens: Token[], idx: number) {
const openToken = tokens[idx];
const inlineToken = tokens[idx + 1];

let lastTextToken,
let title = '',
i = 0;
while (inlineToken.children && i < inlineToken.children.length) {
const token = inlineToken.children[i];

if (token.type === 'text') {
lastTextToken = token;
title += token.content;
}

i++;
}

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

return {
level,
Expand Down
10 changes: 10 additions & 0 deletions test/anchors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,4 +118,14 @@ describe('Anchors', () => {
'<p>After include</p>\n',
);
});

it('should add anchor with auto naming, using entire heading text', () => {
expect(transformYfm('## _Lorem ~~ipsum **dolor** sit~~ amet_\n\nParagraph\n')).toBe(
'<h2 id="lorem-ipsum-dolor-sit-amet">' +
'<a href="#lorem-ipsum-dolor-sit-amet" class="yfm-anchor" aria-hidden="true">' +
'<span class="visually-hidden">Lorem ipsum dolor sit amet</span></a>' +
'<em>Lorem <s>ipsum <strong>dolor</strong> sit</s> amet</em></h2>\n' +
'<p>Paragraph</p>\n',
);
});
});

0 comments on commit 84ffa59

Please sign in to comment.