From 66111515337dd396f9ad7255462173c01e86a9a5 Mon Sep 17 00:00:00 2001 From: 3y3k0 <3y3k0@yandex-team.ru> Date: Mon, 24 Jul 2023 21:01:25 +0300 Subject: [PATCH] fix: link breaks anchored header since version Fixes #253 --- src/transform/headings.ts | 2 +- src/transform/plugins/anchors/index.ts | 19 +++++++++++-------- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/src/transform/headings.ts b/src/transform/headings.ts index b0c22fc6..6702df97 100644 --- a/src/transform/headings.ts +++ b/src/transform/headings.ts @@ -4,7 +4,7 @@ import {Heading} from './typings'; function getTitle(token: Token) { return ( token.children?.reduce((acc, tok) => { - if ((tok.type === 'text' && !tok.meta?.hidden) || tok.type === 'code_inline') { + if (tok.type === 'text' || tok.type === 'code_inline') { return acc + tok.content; } diff --git a/src/transform/plugins/anchors/index.ts b/src/transform/plugins/anchors/index.ts index 96c4647c..e1fa108e 100644 --- a/src/transform/plugins/anchors/index.ts +++ b/src/transform/plugins/anchors/index.ts @@ -5,6 +5,7 @@ import {headingInfo} from '../../utils'; import {CUSTOM_ID_REGEXP, CUSTOM_ID_EXCEPTION} from './constants'; import StateCore from 'markdown-it/lib/rules_core/state_core'; import Token from 'markdown-it/lib/token'; +import {escapeHtml} from 'markdown-it/lib/common/utils'; import {MarkdownItPluginCb} from '../typings'; const slugify: (str: string, opts: {}) => string = require('slugify'); @@ -21,14 +22,11 @@ function createLinkTokens(state: StateCore, id: string, title: string, setId = f open.attrSet('aria-hidden', 'true'); // SEO: render invisible heading title because link must have text content. - const spanOpen = new state.Token('span_open', 'span', 1); - const spanText = new state.Token('text', '', 0); - const spanClose = new state.Token('span_close', 'span', -1); - spanOpen.attrSet('class', 'visually-hidden'); - spanText.content = title; - spanText.meta = {hidden: true}; - - return [open, spanOpen, spanText, spanClose, close]; + const hiddenDesc = new state.Token('anchor_hidden_desc', '', 0); + + hiddenDesc.content = title; + + return [open, hiddenDesc, close]; } const getCustomIds = (content: string) => { @@ -93,6 +91,7 @@ const index: MarkdownItPluginCb = ( if (isHeading) { const {title, level} = headingInfo(tokens, i); + const inlineToken = tokens[i + 1]; let id = token.attrGet('id'); let ghId: string; @@ -158,6 +157,10 @@ const index: MarkdownItPluginCb = ( md.core.ruler.push('anchors', plugin); } } + + md.renderer.rules.anchor_hidden_desc = function (tokens, index) { + return '' + escapeHtml(tokens[index].content) + ''; + }; }; export = index;