Skip to content

Commit

Permalink
Keep Markup: Use original nodes instead of clones (#3365)
Browse files Browse the repository at this point in the history
  • Loading branch information
Golmote committed Mar 5, 2022
1 parent 4cb3d03 commit 8a843a1
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 6 deletions.
11 changes: 6 additions & 5 deletions plugins/keep-markup/prism-keep-markup.js
Expand Up @@ -39,8 +39,8 @@
}

var o = {
// Clone the original tag to keep all attributes
clone: element.cloneNode(false),
// Store original element so we can restore it after highlighting
element: element,
posOpen: pos
};
data.push(o);
Expand Down Expand Up @@ -96,12 +96,13 @@
}

if (nodeState.nodeStart && nodeState.nodeEnd) {
// Select the range and wrap it with the clone
// Select the range and wrap it with the element
var range = document.createRange();
range.setStart(nodeState.nodeStart, nodeState.nodeStartPos);
range.setEnd(nodeState.nodeEnd, nodeState.nodeEndPos);
nodeState.node.clone.appendChild(range.extractContents());
range.insertNode(nodeState.node.clone);
nodeState.node.element.innerHTML = '';
nodeState.node.element.appendChild(range.extractContents());
range.insertNode(nodeState.node.element);
range.detach();

// Process is over
Expand Down
2 changes: 1 addition & 1 deletion plugins/keep-markup/prism-keep-markup.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions tests/plugins/keep-markup/test.js
Expand Up @@ -62,6 +62,22 @@ describe('Keep Markup', function () {
assert.strictEqual(firstPass, secondPass);
});

it('should not clone markup nodes', function () {
const pre = document.createElement('pre');
pre.className = 'language-javascript drop-tokens';
pre.innerHTML = '<code>var <mark>a = <mark>42</mark></mark>;</code>';
const code = pre.childNodes[0];
const firstNodeRefBefore = code.querySelector('mark');
const secondNodeRefBefore = firstNodeRefBefore.querySelector('mark');

Prism.highlightElement(code);
const firstNodeRefAfter = code.querySelector('mark');
const secondNodeRefAfter = firstNodeRefAfter.querySelector('mark');

assert.strictEqual(firstNodeRefBefore, firstNodeRefAfter);
assert.strictEqual(secondNodeRefBefore, secondNodeRefAfter);
});

// The markup is removed if it's the last element and the element's name is a single letter: a(nchor), b(old), i(talic)...
// https://github.com/PrismJS/prism/issues/1618
/*
Expand Down

0 comments on commit 8a843a1

Please sign in to comment.