From 84ffa59a25706a232fb0220d5466346a5cc4b5a5 Mon Sep 17 00:00:00 2001 From: d3m1d0v Date: Mon, 4 Mar 2024 15:58:01 +0300 Subject: [PATCH] fix(anchors): use entire heading text for auto named anchors 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` --- src/transform/utils.ts | 6 +++--- test/anchors.test.ts | 10 ++++++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/transform/utils.ts b/src/transform/utils.ts index 44879248..bace0d63 100644 --- a/src/transform/utils.ts +++ b/src/transform/utils.ts @@ -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, diff --git a/test/anchors.test.ts b/test/anchors.test.ts index 7f42eadc..7e0fd56e 100644 --- a/test/anchors.test.ts +++ b/test/anchors.test.ts @@ -118,4 +118,14 @@ describe('Anchors', () => { '

After include

\n', ); }); + + it('should add anchor with auto naming, using entire heading text', () => { + expect(transformYfm('## _Lorem ~~ipsum **dolor** sit~~ amet_\n\nParagraph\n')).toBe( + '

' + + '' + + 'Lorem ipsum dolor sit amet

\n' + + '

Paragraph

\n', + ); + }); });