@@ -4,12 +4,40 @@ import clsx from 'clsx'
44import { useEffect , useState } from 'react'
55import { ClipboardIcon } from '../icons/ClipboardIcon'
66import { 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
834export 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
0 commit comments