Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Keep Markup: Restore original nodes instead of clones #3365

Merged
merged 2 commits into from Mar 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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());
Golmote marked this conversation as resolved.
Show resolved Hide resolved
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