file.tsx
1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { FC, useState } from 'react'
import type { LinkProps } from './index'
import { RiLoader4Line } from '@remixicon/react' // 使用remixicon的加载图标
const FileLink: FC<LinkProps> = ({ node, children }) => {
const [isDownloading, setIsDownloading] = useState(false)
const handleDownload = async (e: React.MouseEvent) => {
e.preventDefault()
setIsDownloading(true)
try {
const response = await fetch(node.properties.href)
const blob = await response.blob()
const url = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = node.properties.href.split('/').pop() || 'download'
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
window.URL.revokeObjectURL(url)
} catch (error) {
console.error('Download failed:', error)
} finally {
setIsDownloading(false)
}
}
return (
<a
href={node.properties.href}
onClick={handleDownload}
className="cursor-pointer underline !decoration-primary-700 decoration-dashed flex items-center gap-2"
rel="noopener noreferrer">
{isDownloading ? (
<>
<RiLoader4Line className="animate-spin" size={16} />
{children || 'Downloading...'}
</>
) : (
children || 'Download'
)}
</a>
)
}
export default FileLink