file.tsx 1.37 KB
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