You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

image-preview.tsx 8.3KB

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