Skip to content

Commit c128baf

Browse files
committed
fix(client): properly skip removed lines when copying code blocks
x-ref: #4751 (comment)
1 parent 7c1dc48 commit c128baf

File tree

1 file changed

+9
-9
lines changed

1 file changed

+9
-9
lines changed

src/client/app/composables/copyCode.ts

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,28 @@
11
import { inBrowser } from 'vitepress'
22

3+
const shellRE = /language-(shellscript|shell|bash|sh|zsh)/
4+
const ignoredNodes = ['.vp-copy-ignore', '.diff.remove'].join(', ')
5+
36
export function useCopyCode() {
47
if (inBrowser) {
58
const timeoutIdMap: WeakMap<HTMLElement, NodeJS.Timeout> = new WeakMap()
69
window.addEventListener('click', (e) => {
710
const el = e.target as HTMLElement
811
if (el.matches('div[class*="language-"] > button.copy')) {
912
const parent = el.parentElement
10-
const sibling = el.nextElementSibling?.nextElementSibling
13+
const sibling = el.nextElementSibling?.nextElementSibling // <pre> tag
1114
if (!parent || !sibling) {
1215
return
1316
}
1417

15-
const isShell = /language-(shellscript|shell|bash|sh|zsh)/.test(
16-
parent.className
17-
)
18-
19-
const ignoredNodes = ['.vp-copy-ignore', '.diff.remove']
18+
const isShell = shellRE.test(parent.className)
2019

2120
// Clone the node and remove the ignored nodes
2221
const clone = sibling.cloneNode(true) as HTMLElement
23-
clone
24-
.querySelectorAll(ignoredNodes.join(','))
25-
.forEach((node) => node.remove())
22+
clone.querySelectorAll(ignoredNodes).forEach((node) => node.remove())
23+
// remove extra newlines left after removing ignored nodes (affecting textContent because it is inside `<pre>`)
24+
// doesn't affect the newlines already in the code because they are rendered as `\n<span class="line"></span>`
25+
clone.innerHTML = clone.innerHTML.replace(/\n+/g, '\n')
2626

2727
let text = clone.textContent || ''
2828

0 commit comments

Comments
 (0)