1
+ import { useState } from 'react'
1
2
import { EditorContent , useEditor } from '@tiptap/react'
2
3
import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight'
3
4
import { common , createLowlight } from 'lowlight'
@@ -27,6 +28,7 @@ type Props = {
27
28
}
28
29
29
30
const CodeBlock = ( { code } : Props ) => {
31
+ const [ copied , setCopied ] = useState ( false )
30
32
31
33
const editor = useEditor ( {
32
34
editorProps : {
@@ -44,20 +46,38 @@ const CodeBlock = ({ code }: Props) => {
44
46
content : `<pre><code>${ code } </code></pre>`
45
47
} )
46
48
47
- const onCopy = ( ) => {
48
- navigator . clipboard . writeText ( code )
49
+ const onCopy = async ( ) => {
50
+ try {
51
+ if ( navigator ?. clipboard ?. writeText ) {
52
+ await navigator . clipboard . writeText ( code )
53
+ } else {
54
+ const textarea = document . createElement ( 'textarea' )
55
+ textarea . value = code
56
+ textarea . setAttribute ( 'readonly' , '' )
57
+ textarea . style . position = 'absolute'
58
+ textarea . style . left = '-9999px'
59
+ document . body . appendChild ( textarea )
60
+ textarea . select ( )
61
+ document . execCommand ( 'copy' )
62
+ document . body . removeChild ( textarea )
63
+ }
64
+
65
+ setCopied ( true )
66
+ toast . success ( 'Copied to clipboard' , { duration : 800 } )
67
+ setTimeout ( ( ) => setCopied ( false ) , 2500 )
68
+ } catch ( err ) {
69
+ console . error ( 'Copy failed:' , err )
70
+ toast . error ( 'Failed to copy' )
71
+ }
72
+ }
49
73
50
- toast . success ( 'Copied to clipboard' , {
51
- duration : 800
52
- } )
53
- }
54
74
55
75
if ( ! editor ) return null
56
76
57
77
return (
58
78
< div className = 'relative' >
59
79
< EditorContent editor = { editor } />
60
- < Tooltip content = ' Copy'>
80
+ < Tooltip content = { copied ? 'Copied' : ' Copy'} >
61
81
< IconButton
62
82
variant = 'ghost'
63
83
size = '2'
@@ -66,7 +86,7 @@ const CodeBlock = ({ code }: Props) => {
66
86
className = 'absolute right-3 top-7 text-gray-8 hover:text-gray-1'
67
87
onClick = { onCopy }
68
88
>
69
- < BiCopy />
89
+ { copied ? < BiClipboard /> : < BiCopy /> }
70
90
</ IconButton >
71
91
</ Tooltip >
72
92
</ div >
0 commit comments