Skip to content
This repository was archived by the owner on May 20, 2025. It is now read-only.

Commit 4ce1d61

Browse files
committed
remove minus diffs from copied code
1 parent 22f46d9 commit 4ce1d61

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

src/components/code/CopyButton.tsx

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,40 @@ import clsx from 'clsx'
44
import { useEffect, useState } from 'react'
55
import { ClipboardIcon } from '../icons/ClipboardIcon'
66
import { cn } from '@/lib/utils'
7+
import { CodeAnnotation } from 'codehike/code'
8+
9+
// remove - diff annotations from the code
10+
const cleanCode = (code: string, annotations: CodeAnnotation[]) => {
11+
if (!annotations.length) return code
12+
13+
const lines = code.split('\n')
14+
15+
// Sort annotations by fromLineNumber in descending order to avoid conflicts
16+
const sortedAnnotations = [...annotations]
17+
.filter((a) => 'fromLineNumber' in a)
18+
.sort((a, b) => b.fromLineNumber - a.fromLineNumber)
19+
20+
for (const annotation of sortedAnnotations) {
21+
if (annotation.query === '-' && annotation.name === 'diff') {
22+
const { fromLineNumber, toLineNumber } = annotation
23+
const start = fromLineNumber - 1
24+
const end = toLineNumber
25+
26+
// Remove the lines in the range [start, end)
27+
lines.splice(start, end - start)
28+
}
29+
}
30+
31+
return lines.join('\n')
32+
}
733

834
export function CopyButton({
935
code,
36+
annotations,
1037
className,
1138
}: {
1239
code: string
40+
annotations: CodeAnnotation[]
1341
className?: string
1442
}) {
1543
const [copyCount, setCopyCount] = useState(0)
@@ -36,9 +64,11 @@ export function CopyButton({
3664
className,
3765
)}
3866
onClick={() => {
39-
window.navigator.clipboard.writeText(code).then(() => {
40-
setCopyCount((count) => count + 1)
41-
})
67+
window.navigator.clipboard
68+
.writeText(cleanCode(code, annotations))
69+
.then(() => {
70+
setCopyCount((count) => count + 1)
71+
})
4272
}}
4373
>
4474
<span

src/components/code/Pre.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ const Pre: React.FC<Props> = ({
8181
)}
8282
<CopyButton
8383
code={highlighted.code}
84+
annotations={highlighted.annotations}
8485
className={cn(showPanel && 'top-12', isBash && 'top-11')}
8586
/>
8687
<CodeHikePre

0 commit comments

Comments
 (0)