image-preview.tsx 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. import type { FC } from 'react'
  2. import React, { useCallback, useEffect, useRef, useState } from 'react'
  3. import { t } from 'i18next'
  4. import { createPortal } from 'react-dom'
  5. import { RiAddBoxLine, RiCloseLine, RiDownloadCloud2Line, RiFileCopyLine, RiZoomInLine, RiZoomOutLine } from '@remixicon/react'
  6. import { useHotkeys } from 'react-hotkeys-hook'
  7. import Tooltip from '@/app/components/base/tooltip'
  8. import Toast from '@/app/components/base/toast'
  9. type ImagePreviewProps = {
  10. url: string
  11. title: string
  12. onCancel: () => void
  13. onPrev?: () => void
  14. onNext?: () => void
  15. }
  16. const isBase64 = (str: string): boolean => {
  17. try {
  18. return btoa(atob(str)) === str
  19. }
  20. catch (err) {
  21. return false
  22. }
  23. }
  24. const ImagePreview: FC<ImagePreviewProps> = ({
  25. url,
  26. title,
  27. onCancel,
  28. onPrev,
  29. onNext,
  30. }) => {
  31. const [scale, setScale] = useState(1)
  32. const [position, setPosition] = useState({ x: 0, y: 0 })
  33. const [isDragging, setIsDragging] = useState(false)
  34. const imgRef = useRef<HTMLImageElement>(null)
  35. const dragStartRef = useRef({ x: 0, y: 0 })
  36. const [isCopied, setIsCopied] = useState(false)
  37. const openInNewTab = () => {
  38. // Open in a new window, considering the case when the page is inside an iframe
  39. if (url.startsWith('http') || url.startsWith('https')) {
  40. window.open(url, '_blank')
  41. }
  42. else if (url.startsWith('data:image')) {
  43. // Base64 image
  44. const win = window.open()
  45. win?.document.write(`<img src="${url}" alt="${title}" />`)
  46. }
  47. else {
  48. Toast.notify({
  49. type: 'error',
  50. message: `Unable to open image: ${url}`,
  51. })
  52. }
  53. }
  54. const downloadImage = () => {
  55. // Open in a new window, considering the case when the page is inside an iframe
  56. if (url.startsWith('http') || url.startsWith('https')) {
  57. const a = document.createElement('a')
  58. a.href = url
  59. a.download = title
  60. a.click()
  61. }
  62. else if (url.startsWith('data:image')) {
  63. // Base64 image
  64. const a = document.createElement('a')
  65. a.href = url
  66. a.download = title
  67. a.click()
  68. }
  69. else {
  70. Toast.notify({
  71. type: 'error',
  72. message: `Unable to open image: ${url}`,
  73. })
  74. }
  75. }
  76. const zoomIn = () => {
  77. setScale(prevScale => Math.min(prevScale * 1.2, 15))
  78. }
  79. const zoomOut = () => {
  80. setScale((prevScale) => {
  81. const newScale = Math.max(prevScale / 1.2, 0.5)
  82. if (newScale === 1)
  83. setPosition({ x: 0, y: 0 }) // Reset position when fully zoomed out
  84. return newScale
  85. })
  86. }
  87. const imageBase64ToBlob = (base64: string, type = 'image/png'): Blob => {
  88. const byteCharacters = atob(base64)
  89. const byteArrays = []
  90. for (let offset = 0; offset < byteCharacters.length; offset += 512) {
  91. const slice = byteCharacters.slice(offset, offset + 512)
  92. const byteNumbers = new Array(slice.length)
  93. for (let i = 0; i < slice.length; i++)
  94. byteNumbers[i] = slice.charCodeAt(i)
  95. const byteArray = new Uint8Array(byteNumbers)
  96. byteArrays.push(byteArray)
  97. }
  98. return new Blob(byteArrays, { type })
  99. }
  100. const imageCopy = useCallback(() => {
  101. const shareImage = async () => {
  102. try {
  103. const base64Data = url.split(',')[1]
  104. const blob = imageBase64ToBlob(base64Data, 'image/png')
  105. await navigator.clipboard.write([
  106. new ClipboardItem({
  107. [blob.type]: blob,
  108. }),
  109. ])
  110. setIsCopied(true)
  111. Toast.notify({
  112. type: 'success',
  113. message: t('common.operation.imageCopied'),
  114. })
  115. }
  116. catch (err) {
  117. console.error('Failed to copy image:', err)
  118. const link = document.createElement('a')
  119. link.href = url
  120. link.download = `${title}.png`
  121. document.body.appendChild(link)
  122. link.click()
  123. document.body.removeChild(link)
  124. Toast.notify({
  125. type: 'info',
  126. message: t('common.operation.imageDownloaded'),
  127. })
  128. }
  129. }
  130. shareImage()
  131. }, [title, url])
  132. const handleWheel = useCallback((e: React.WheelEvent<HTMLDivElement>) => {
  133. if (e.deltaY < 0)
  134. zoomIn()
  135. else
  136. zoomOut()
  137. }, [])
  138. const handleMouseDown = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
  139. if (scale > 1) {
  140. setIsDragging(true)
  141. dragStartRef.current = { x: e.clientX - position.x, y: e.clientY - position.y }
  142. }
  143. }, [scale, position])
  144. const handleMouseMove = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
  145. if (isDragging && scale > 1) {
  146. const deltaX = e.clientX - dragStartRef.current.x
  147. const deltaY = e.clientY - dragStartRef.current.y
  148. // Calculate boundaries
  149. const imgRect = imgRef.current?.getBoundingClientRect()
  150. const containerRect = imgRef.current?.parentElement?.getBoundingClientRect()
  151. if (imgRect && containerRect) {
  152. const maxX = (imgRect.width * scale - containerRect.width) / 2
  153. const maxY = (imgRect.height * scale - containerRect.height) / 2
  154. setPosition({
  155. x: Math.max(-maxX, Math.min(maxX, deltaX)),
  156. y: Math.max(-maxY, Math.min(maxY, deltaY)),
  157. })
  158. }
  159. }
  160. }, [isDragging, scale])
  161. const handleMouseUp = useCallback(() => {
  162. setIsDragging(false)
  163. }, [])
  164. useEffect(() => {
  165. document.addEventListener('mouseup', handleMouseUp)
  166. return () => {
  167. document.removeEventListener('mouseup', handleMouseUp)
  168. }
  169. }, [handleMouseUp])
  170. useHotkeys('esc', onCancel)
  171. useHotkeys('up', zoomIn)
  172. useHotkeys('down', zoomOut)
  173. useHotkeys('left', onPrev || (() => {}))
  174. useHotkeys('right', onNext || (() => {}))
  175. return createPortal(
  176. <div className='fixed inset-0 p-8 flex items-center justify-center bg-black/80 z-[1000] image-preview-container'
  177. onClick={e => e.stopPropagation()}
  178. onWheel={handleWheel}
  179. onMouseDown={handleMouseDown}
  180. onMouseMove={handleMouseMove}
  181. onMouseUp={handleMouseUp}
  182. style={{ cursor: scale > 1 ? 'move' : 'default' }}
  183. tabIndex={-1}>
  184. {/* eslint-disable-next-line @next/next/no-img-element */}
  185. <img
  186. ref={imgRef}
  187. alt={title}
  188. src={isBase64(url) ? `data:image/png;base64,${url}` : url}
  189. className='max-w-full max-h-full'
  190. style={{
  191. transform: `scale(${scale}) translate(${position.x}px, ${position.y}px)`,
  192. transition: isDragging ? 'none' : 'transform 0.2s ease-in-out',
  193. }}
  194. />
  195. <Tooltip popupContent={t('common.operation.copyImage')}>
  196. <div className='absolute top-6 right-48 flex items-center justify-center w-8 h-8 rounded-lg cursor-pointer'
  197. onClick={imageCopy}>
  198. {isCopied
  199. ? <RiFileCopyLine className='w-4 h-4 text-green-500'/>
  200. : <RiFileCopyLine className='w-4 h-4 text-gray-500'/>}
  201. </div>
  202. </Tooltip>
  203. <Tooltip popupContent={t('common.operation.zoomOut')}>
  204. <div className='absolute top-6 right-40 flex items-center justify-center w-8 h-8 rounded-lg cursor-pointer'
  205. onClick={zoomOut}>
  206. <RiZoomOutLine className='w-4 h-4 text-gray-500'/>
  207. </div>
  208. </Tooltip>
  209. <Tooltip popupContent={t('common.operation.zoomIn')}>
  210. <div className='absolute top-6 right-32 flex items-center justify-center w-8 h-8 rounded-lg cursor-pointer'
  211. onClick={zoomIn}>
  212. <RiZoomInLine className='w-4 h-4 text-gray-500'/>
  213. </div>
  214. </Tooltip>
  215. <Tooltip popupContent={t('common.operation.download')}>
  216. <div className='absolute top-6 right-24 flex items-center justify-center w-8 h-8 rounded-lg cursor-pointer'
  217. onClick={downloadImage}>
  218. <RiDownloadCloud2Line className='w-4 h-4 text-gray-500'/>
  219. </div>
  220. </Tooltip>
  221. <Tooltip popupContent={t('common.operation.openInNewTab')}>
  222. <div className='absolute top-6 right-16 flex items-center justify-center w-8 h-8 rounded-lg cursor-pointer'
  223. onClick={openInNewTab}>
  224. <RiAddBoxLine className='w-4 h-4 text-gray-500'/>
  225. </div>
  226. </Tooltip>
  227. <Tooltip popupContent={t('common.operation.cancel')}>
  228. <div
  229. className='absolute top-6 right-6 flex items-center justify-center w-8 h-8 bg-white/8 rounded-lg backdrop-blur-[2px] cursor-pointer'
  230. onClick={onCancel}>
  231. <RiCloseLine className='w-4 h-4 text-gray-500'/>
  232. </div>
  233. </Tooltip>
  234. </div>,
  235. document.body,
  236. )
  237. }
  238. export default ImagePreview