Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

image-preview.tsx 8.3KB

Introduce Plugins (#13836) Signed-off-by: yihong0618 <zouzou0208@gmail.com> Signed-off-by: -LAN- <laipz8200@outlook.com> Signed-off-by: xhe <xw897002528@gmail.com> Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: takatost <takatost@gmail.com> Co-authored-by: kurokobo <kuro664@gmail.com> Co-authored-by: Novice Lee <novicelee@NoviPro.local> Co-authored-by: zxhlyh <jasonapring2015@outlook.com> Co-authored-by: AkaraChen <akarachen@outlook.com> Co-authored-by: Yi <yxiaoisme@gmail.com> Co-authored-by: Joel <iamjoel007@gmail.com> Co-authored-by: JzoNg <jzongcode@gmail.com> Co-authored-by: twwu <twwu@dify.ai> Co-authored-by: Hiroshi Fujita <fujita-h@users.noreply.github.com> Co-authored-by: AkaraChen <85140972+AkaraChen@users.noreply.github.com> Co-authored-by: NFish <douxc512@gmail.com> Co-authored-by: Wu Tianwei <30284043+WTW0313@users.noreply.github.com> Co-authored-by: 非法操作 <hjlarry@163.com> Co-authored-by: Novice <857526207@qq.com> Co-authored-by: Hiroki Nagai <82458324+nagaihiroki-git@users.noreply.github.com> Co-authored-by: Gen Sato <52241300+halogen22@users.noreply.github.com> Co-authored-by: eux <euxuuu@gmail.com> Co-authored-by: huangzhuo1949 <167434202+huangzhuo1949@users.noreply.github.com> Co-authored-by: huangzhuo <huangzhuo1@xiaomi.com> Co-authored-by: lotsik <lotsik@mail.ru> Co-authored-by: crazywoola <100913391+crazywoola@users.noreply.github.com> Co-authored-by: nite-knite <nkCoding@gmail.com> Co-authored-by: Jyong <76649700+JohnJyong@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: gakkiyomi <gakkiyomi@aliyun.com> Co-authored-by: CN-P5 <heibai2006@gmail.com> Co-authored-by: CN-P5 <heibai2006@qq.com> Co-authored-by: Chuehnone <1897025+chuehnone@users.noreply.github.com> Co-authored-by: yihong <zouzou0208@gmail.com> Co-authored-by: Kevin9703 <51311316+Kevin9703@users.noreply.github.com> Co-authored-by: -LAN- <laipz8200@outlook.com> Co-authored-by: Boris Feld <lothiraldan@gmail.com> Co-authored-by: mbo <himabo@gmail.com> Co-authored-by: mabo <mabo@aeyes.ai> Co-authored-by: Warren Chen <warren.chen830@gmail.com> Co-authored-by: JzoNgKVO <27049666+JzoNgKVO@users.noreply.github.com> Co-authored-by: jiandanfeng <chenjh3@wangsu.com> Co-authored-by: zhu-an <70234959+xhdd123321@users.noreply.github.com> Co-authored-by: zhaoqingyu.1075 <zhaoqingyu.1075@bytedance.com> Co-authored-by: 海狸大師 <86974027+yenslife@users.noreply.github.com> Co-authored-by: Xu Song <xusong.vip@gmail.com> Co-authored-by: rayshaw001 <396301947@163.com> Co-authored-by: Ding Jiatong <dingjiatong@gmail.com> Co-authored-by: Bowen Liang <liangbowen@gf.com.cn> Co-authored-by: JasonVV <jasonwangiii@outlook.com> Co-authored-by: le0zh <newlight@qq.com> Co-authored-by: zhuxinliang <zhuxinliang@didiglobal.com> Co-authored-by: k-zaku <zaku99@outlook.jp> Co-authored-by: luckylhb90 <luckylhb90@gmail.com> Co-authored-by: hobo.l <hobo.l@binance.com> Co-authored-by: jiangbo721 <365065261@qq.com> Co-authored-by: 刘江波 <jiangbo721@163.com> Co-authored-by: Shun Miyazawa <34241526+miya@users.noreply.github.com> Co-authored-by: EricPan <30651140+Egfly@users.noreply.github.com> Co-authored-by: crazywoola <427733928@qq.com> Co-authored-by: sino <sino2322@gmail.com> Co-authored-by: Jhvcc <37662342+Jhvcc@users.noreply.github.com> Co-authored-by: lowell <lowell.hu@zkteco.in> Co-authored-by: Boris Polonsky <BorisPolonsky@users.noreply.github.com> Co-authored-by: Ademílson Tonato <ademilsonft@outlook.com> Co-authored-by: Ademílson Tonato <ademilson.tonato@refurbed.com> Co-authored-by: IWAI, Masaharu <iwaim.sub@gmail.com> Co-authored-by: Yueh-Po Peng (Yabi) <94939112+y10ab1@users.noreply.github.com> Co-authored-by: Jason <ggbbddjm@gmail.com> Co-authored-by: Xin Zhang <sjhpzx@gmail.com> Co-authored-by: yjc980121 <3898524+yjc980121@users.noreply.github.com> Co-authored-by: heyszt <36215648+hieheihei@users.noreply.github.com> Co-authored-by: Abdullah AlOsaimi <osaimiacc@gmail.com> Co-authored-by: Abdullah AlOsaimi <189027247+osaimi@users.noreply.github.com> Co-authored-by: Yingchun Lai <laiyingchun@apache.org> Co-authored-by: Hash Brown <hi@xzd.me> Co-authored-by: zuodongxu <192560071+zuodongxu@users.noreply.github.com> Co-authored-by: Masashi Tomooka <tmokmss@users.noreply.github.com> Co-authored-by: aplio <ryo.091219@gmail.com> Co-authored-by: Obada Khalili <54270856+obadakhalili@users.noreply.github.com> Co-authored-by: Nam Vu <zuzoovn@gmail.com> Co-authored-by: Kei YAMAZAKI <1715090+kei-yamazaki@users.noreply.github.com> Co-authored-by: TechnoHouse <13776377+deephbz@users.noreply.github.com> Co-authored-by: Riddhimaan-Senapati <114703025+Riddhimaan-Senapati@users.noreply.github.com> Co-authored-by: MaFee921 <31881301+2284730142@users.noreply.github.com> Co-authored-by: te-chan <t-nakanome@sakura-is.co.jp> Co-authored-by: HQidea <HQidea@users.noreply.github.com> Co-authored-by: Joshbly <36315710+Joshbly@users.noreply.github.com> Co-authored-by: xhe <xw897002528@gmail.com> Co-authored-by: weiwenyan-dev <154779315+weiwenyan-dev@users.noreply.github.com> Co-authored-by: ex_wenyan.wei <ex_wenyan.wei@tcl.com> Co-authored-by: engchina <12236799+engchina@users.noreply.github.com> Co-authored-by: engchina <atjapan2015@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: 呆萌闷油瓶 <253605712@qq.com> Co-authored-by: Kemal <kemalmeler@outlook.com> Co-authored-by: Lazy_Frog <4590648+lazyFrogLOL@users.noreply.github.com> Co-authored-by: Yi Xiao <54782454+YIXIAO0@users.noreply.github.com> Co-authored-by: Steven sun <98230804+Tuyohai@users.noreply.github.com> Co-authored-by: steven <sunzwj@digitalchina.com> Co-authored-by: Kalo Chin <91766386+fdb02983rhy@users.noreply.github.com> Co-authored-by: Katy Tao <34019945+KatyTao@users.noreply.github.com> Co-authored-by: depy <42985524+h4ckdepy@users.noreply.github.com> Co-authored-by: 胡春东 <gycm520@gmail.com> Co-authored-by: Junjie.M <118170653@qq.com> Co-authored-by: MuYu <mr.muzea@gmail.com> Co-authored-by: Naoki Takashima <39912547+takatea@users.noreply.github.com> Co-authored-by: Summer-Gu <37869445+gubinjie@users.noreply.github.com> Co-authored-by: Fei He <droxer.he@gmail.com> Co-authored-by: ybalbert001 <120714773+ybalbert001@users.noreply.github.com> Co-authored-by: Yuanbo Li <ybalbert@amazon.com> Co-authored-by: douxc <7553076+douxc@users.noreply.github.com> Co-authored-by: liuzhenghua <1090179900@qq.com> Co-authored-by: Wu Jiayang <62842862+Wu-Jiayang@users.noreply.github.com> Co-authored-by: Your Name <you@example.com> Co-authored-by: kimjion <45935338+kimjion@users.noreply.github.com> Co-authored-by: AugNSo <song.tiankai@icloud.com> Co-authored-by: llinvokerl <38915183+llinvokerl@users.noreply.github.com> Co-authored-by: liusurong.lsr <liusurong.lsr@alibaba-inc.com> Co-authored-by: Vasu Negi <vasu-negi@users.noreply.github.com> Co-authored-by: Hundredwz <1808096180@qq.com> Co-authored-by: Xiyuan Chen <52963600+GareArc@users.noreply.github.com>
8 meses atrás
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