Skip to content

Commit

Permalink
Fix IdAttribute plugin issue with encoded html entities (option to de…
Browse files Browse the repository at this point in the history
…code before slugify) Fixes #3398
  • Loading branch information
zachleat committed Aug 1, 2024
1 parent 1ac68c8 commit c39e896
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@
"cross-spawn": "^7.0.3",
"debug": "^4.3.6",
"dependency-graph": "^1.0.0",
"entities": "^5.0.0",
"fast-glob": "^3.3.2",
"filesize": "^10.1.4",
"graceful-fs": "^4.2.11",
Expand Down
8 changes: 7 additions & 1 deletion src/Plugins/IdAttributePlugin.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import matchHelper from "posthtml-match-helper";
import { decodeHTML } from "entities";

import slugifyFilter from "../Filters/Slugify.js";
import MemoizeUtil from "../Util/MemoizeFunction.js";
Expand Down Expand Up @@ -28,6 +29,7 @@ function IdAttributePlugin(eleventyConfig, options = {}) {
if (!options.selector) {
options.selector = "h1,h2,h3,h4,h5,h6";
}
options.decodeEntities = options.decodeEntities ?? true;

eleventyConfig.htmlTransformer.addPosthtmlPlugin(
"html",
Expand All @@ -39,7 +41,11 @@ function IdAttributePlugin(eleventyConfig, options = {}) {
tree.match(matchHelper(options.selector), function (node) {
if (!node.attrs?.id && node.content) {
node.attrs = node.attrs || {};
let id = options.slugify(getTextNodeContent(node));
let textContent = getTextNodeContent(node);
if (options.decodeEntities) {
textContent = decodeHTML(textContent);
}
let id = options.slugify(textContent);
if (conflictCheck[id]) {
conflictCheck[id]++;
id = `${id}-${conflictCheck[id]}`;
Expand Down
15 changes: 15 additions & 0 deletions test/IdAttributePluginTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,18 @@ test("Using the IdAttribute plugin #3356", async (t) => {
let results = await elev.toJSON();
t.is(results[0].content, `<h1 id="this-is-a-heading">This is a heading</h1><h2 id="already">This is another heading</h2><h2 id="this-is-another-heading">This is another heading</h2><h3 id="this-is-another-heading-2">This is another heading</h3>`);
});

test("Using the IdAttribute plugin with escaped quoted text", async (t) => {
let elev = new Eleventy("./test/stubs-virtual/", "./test/stubs-virtual/_site", {
config: function (eleventyConfig) {
eleventyConfig.addPlugin(IdAttributePlugin);

eleventyConfig.addTemplate("test.md", `# This is a \`"heading"\``, {});
},
});

elev.disableLogger();

let results = await elev.toJSON();
t.is(results[0].content.trim(), `<h1 id="this-is-a-heading">This is a <code>&quot;heading&quot;</code></h1>`);
});

0 comments on commit c39e896

Please sign in to comment.