Skip to content

Commit

Permalink
fix(code): Add ability to disable SEO optimization for titles
Browse files Browse the repository at this point in the history
  • Loading branch information
obenjiro authored and 3y3 committed Nov 8, 2024
1 parent d8ad8a5 commit 2682b6b
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 4 deletions.
17 changes: 13 additions & 4 deletions src/transform/plugins/anchors/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,14 @@ const removeCustomIds = (token: Token) => {
interface Options {
extractTitle?: boolean;
supportGithubAnchors?: boolean;
disableSEOFixForTitles?: boolean;
transformLink: (v: string) => string;
getPublicPath?: (options: Options, v?: string) => string;
}

const index: MarkdownItPluginCb<Options> = (md, options) => {
const {extractTitle, path, log, supportGithubAnchors, getPublicPath} = options;
const {extractTitle, path, log, supportGithubAnchors, getPublicPath, disableSEOFixForTitles} =
options;

const plugin = (state: StateCore) => {
/* Do not use the plugin if it is included in the file */
Expand Down Expand Up @@ -143,9 +145,16 @@ const index: MarkdownItPluginCb<Options> = (md, options) => {
const anchorTitle = removeCustomId(title).replace(/`/g, '');
allAnchorIds.forEach((customId) => {
const setId = id !== customId;
const linkTokens = createLinkTokens(state, customId, anchorTitle, setId, href);

inlineToken.children?.unshift(...linkTokens);
if (!disableSEOFixForTitles) {
const linkTokens = createLinkTokens(
state,
customId,
anchorTitle,
setId,
href,
);
inlineToken.children?.unshift(...linkTokens);
}

if (supportGithubAnchors) {
const ghLinkTokens = createLinkTokens(state, ghId, anchorTitle, true, href);
Expand Down
30 changes: 30 additions & 0 deletions test/anchors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,4 +144,34 @@ describe('Anchors', () => {
expect(result[1]).toBe('Test');
});
});

describe('with disableSEOFixForTitles', () => {
it('should not add anchor links when disableSEOFixForTitles is true', () => {
const {
result: {html},
} = transform('## Test heading', {
plugins: [includes, anchors],
path: mocksPath,
root: dirname(mocksPath),
getPublicPath,
disableSEOFixForTitles: true,
});

expect(html).toEqual('<h2 id="test-heading">Test heading</h2>\n');
});

it('should not add anchor links for custom anchors when disableSEOFixForTitles is true', () => {
const {
result: {html},
} = transform('## Test heading {#custom-id}', {
plugins: [includes, anchors],
path: mocksPath,
root: dirname(mocksPath),
getPublicPath,
disableSEOFixForTitles: true,
});

expect(html).toEqual('<h2 id="custom-id">Test heading</h2>\n');
});
});
});

0 comments on commit 2682b6b

Please sign in to comment.