Skip to content

Commit

Permalink
fix: link breaks anchored header since version
Browse files Browse the repository at this point in the history
Fixes #253
  • Loading branch information
3y3k0 authored and 3y3 committed Jul 24, 2023
1 parent 532a8cd commit 6611151
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
2 changes: 1 addition & 1 deletion src/transform/headings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
19 changes: 11 additions & 8 deletions src/transform/plugins/anchors/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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) => {
Expand Down Expand Up @@ -93,6 +91,7 @@ const index: MarkdownItPluginCb<Options> = (

if (isHeading) {
const {title, level} = headingInfo(tokens, i);

const inlineToken = tokens[i + 1];
let id = token.attrGet('id');
let ghId: string;
Expand Down Expand Up @@ -158,6 +157,10 @@ const index: MarkdownItPluginCb<Options> = (
md.core.ruler.push('anchors', plugin);
}
}

md.renderer.rules.anchor_hidden_desc = function (tokens, index) {
return '<span class="visually-hidden">' + escapeHtml(tokens[index].content) + '</span>';
};
};

export = index;

0 comments on commit 6611151

Please sign in to comment.