hooks.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. import { useCallback, useMemo, useRef, useState } from 'react'
  2. import type { ClipboardEvent } from 'react'
  3. import { useParams } from 'next/navigation'
  4. import { useTranslation } from 'react-i18next'
  5. import { imageUpload } from './utils'
  6. import { useToastContext } from '@/app/components/base/toast'
  7. import { ALLOW_FILE_EXTENSIONS, TransferMethod } from '@/types/app'
  8. import type { ImageFile, VisionSettings } from '@/types/app'
  9. export const useImageFiles = () => {
  10. const params = useParams()
  11. const { t } = useTranslation()
  12. const { notify } = useToastContext()
  13. const [files, setFiles] = useState<ImageFile[]>([])
  14. const filesRef = useRef<ImageFile[]>([])
  15. const handleUpload = (imageFile: ImageFile) => {
  16. const files = filesRef.current
  17. const index = files.findIndex(file => file._id === imageFile._id)
  18. if (index > -1) {
  19. const currentFile = files[index]
  20. const newFiles = [...files.slice(0, index), { ...currentFile, ...imageFile }, ...files.slice(index + 1)]
  21. setFiles(newFiles)
  22. filesRef.current = newFiles
  23. }
  24. else {
  25. const newFiles = [...files, imageFile]
  26. setFiles(newFiles)
  27. filesRef.current = newFiles
  28. }
  29. }
  30. const handleRemove = (imageFileId: string) => {
  31. const files = filesRef.current
  32. const index = files.findIndex(file => file._id === imageFileId)
  33. if (index > -1) {
  34. const currentFile = files[index]
  35. const newFiles = [...files.slice(0, index), { ...currentFile, deleted: true }, ...files.slice(index + 1)]
  36. setFiles(newFiles)
  37. filesRef.current = newFiles
  38. }
  39. }
  40. const handleImageLinkLoadError = (imageFileId: string) => {
  41. const files = filesRef.current
  42. const index = files.findIndex(file => file._id === imageFileId)
  43. if (index > -1) {
  44. const currentFile = files[index]
  45. const newFiles = [...files.slice(0, index), { ...currentFile, progress: -1 }, ...files.slice(index + 1)]
  46. filesRef.current = newFiles
  47. setFiles(newFiles)
  48. }
  49. }
  50. const handleImageLinkLoadSuccess = (imageFileId: string) => {
  51. const files = filesRef.current
  52. const index = files.findIndex(file => file._id === imageFileId)
  53. if (index > -1) {
  54. const currentImageFile = files[index]
  55. const newFiles = [...files.slice(0, index), { ...currentImageFile, progress: 100 }, ...files.slice(index + 1)]
  56. filesRef.current = newFiles
  57. setFiles(newFiles)
  58. }
  59. }
  60. const handleReUpload = (imageFileId: string) => {
  61. const files = filesRef.current
  62. const index = files.findIndex(file => file._id === imageFileId)
  63. if (index > -1) {
  64. const currentImageFile = files[index]
  65. imageUpload({
  66. file: currentImageFile.file!,
  67. onProgressCallback: (progress) => {
  68. const newFiles = [...files.slice(0, index), { ...currentImageFile, progress }, ...files.slice(index + 1)]
  69. filesRef.current = newFiles
  70. setFiles(newFiles)
  71. },
  72. onSuccessCallback: (res) => {
  73. const newFiles = [...files.slice(0, index), { ...currentImageFile, fileId: res.id, progress: 100 }, ...files.slice(index + 1)]
  74. filesRef.current = newFiles
  75. setFiles(newFiles)
  76. },
  77. onErrorCallback: () => {
  78. notify({ type: 'error', message: t('common.imageUploader.uploadFromComputerUploadError') })
  79. const newFiles = [...files.slice(0, index), { ...currentImageFile, progress: -1 }, ...files.slice(index + 1)]
  80. filesRef.current = newFiles
  81. setFiles(newFiles)
  82. },
  83. }, !!params.token)
  84. }
  85. }
  86. const handleClear = () => {
  87. setFiles([])
  88. filesRef.current = []
  89. }
  90. const filteredFiles = useMemo(() => {
  91. return files.filter(file => !file.deleted)
  92. }, [files])
  93. return {
  94. files: filteredFiles,
  95. onUpload: handleUpload,
  96. onRemove: handleRemove,
  97. onImageLinkLoadError: handleImageLinkLoadError,
  98. onImageLinkLoadSuccess: handleImageLinkLoadSuccess,
  99. onReUpload: handleReUpload,
  100. onClear: handleClear,
  101. }
  102. }
  103. type useLocalUploaderProps = {
  104. disabled?: boolean
  105. limit?: number
  106. onUpload: (imageFile: ImageFile) => void
  107. }
  108. export const useLocalFileUploader = ({ limit, disabled = false, onUpload }: useLocalUploaderProps) => {
  109. const { notify } = useToastContext()
  110. const params = useParams()
  111. const { t } = useTranslation()
  112. const handleLocalFileUpload = useCallback((file: File) => {
  113. if (disabled) {
  114. // TODO: leave some warnings?
  115. return
  116. }
  117. if (!ALLOW_FILE_EXTENSIONS.includes(file.type.split('/')[1]))
  118. return
  119. if (limit && file.size > limit * 1024 * 1024) {
  120. notify({ type: 'error', message: t('common.imageUploader.uploadFromComputerLimit', { size: limit }) })
  121. return
  122. }
  123. const reader = new FileReader()
  124. reader.addEventListener(
  125. 'load',
  126. () => {
  127. const imageFile = {
  128. type: TransferMethod.local_file,
  129. _id: `${Date.now()}`,
  130. fileId: '',
  131. file,
  132. url: reader.result as string,
  133. base64Url: reader.result as string,
  134. progress: 0,
  135. }
  136. onUpload(imageFile)
  137. imageUpload({
  138. file: imageFile.file,
  139. onProgressCallback: (progress) => {
  140. onUpload({ ...imageFile, progress })
  141. },
  142. onSuccessCallback: (res) => {
  143. onUpload({ ...imageFile, fileId: res.id, progress: 100 })
  144. },
  145. onErrorCallback: () => {
  146. notify({ type: 'error', message: t('common.imageUploader.uploadFromComputerUploadError') })
  147. onUpload({ ...imageFile, progress: -1 })
  148. },
  149. }, !!params.token)
  150. },
  151. false,
  152. )
  153. reader.addEventListener(
  154. 'error',
  155. () => {
  156. notify({ type: 'error', message: t('common.imageUploader.uploadFromComputerReadError') })
  157. },
  158. false,
  159. )
  160. reader.readAsDataURL(file)
  161. }, [disabled, limit, notify, t, onUpload, params.token])
  162. return { disabled, handleLocalFileUpload }
  163. }
  164. type useClipboardUploaderProps = {
  165. files: ImageFile[]
  166. visionConfig?: VisionSettings
  167. onUpload: (imageFile: ImageFile) => void
  168. }
  169. export const useClipboardUploader = ({ visionConfig, onUpload, files }: useClipboardUploaderProps) => {
  170. const allowLocalUpload = visionConfig?.transfer_methods?.includes(TransferMethod.local_file)
  171. const disabled = useMemo(() =>
  172. !visionConfig
  173. || !visionConfig?.enabled
  174. || !allowLocalUpload
  175. || files.length >= visionConfig.number_limits!,
  176. [allowLocalUpload, files.length, visionConfig])
  177. const limit = useMemo(() => visionConfig ? +visionConfig.image_file_size_limit! : 0, [visionConfig])
  178. const { handleLocalFileUpload } = useLocalFileUploader({ limit, onUpload, disabled })
  179. const handleClipboardPaste = useCallback((e: ClipboardEvent<HTMLTextAreaElement>) => {
  180. // reserve native text copy behavior
  181. const file = e.clipboardData?.files[0]
  182. // when copied file, prevent default action
  183. if (file) {
  184. e.preventDefault()
  185. handleLocalFileUpload(file)
  186. }
  187. }, [handleLocalFileUpload])
  188. return {
  189. onPaste: handleClipboardPaste,
  190. }
  191. }
  192. type useDraggableUploaderProps = {
  193. files: ImageFile[]
  194. visionConfig?: VisionSettings
  195. onUpload: (imageFile: ImageFile) => void
  196. }
  197. export const useDraggableUploader = <T extends HTMLElement>({ visionConfig, onUpload, files }: useDraggableUploaderProps) => {
  198. const allowLocalUpload = visionConfig?.transfer_methods?.includes(TransferMethod.local_file)
  199. const disabled = useMemo(() =>
  200. !visionConfig
  201. || !visionConfig?.enabled
  202. || !allowLocalUpload
  203. || files.length >= visionConfig.number_limits!,
  204. [allowLocalUpload, files.length, visionConfig])
  205. const limit = useMemo(() => visionConfig ? +visionConfig.image_file_size_limit! : 0, [visionConfig])
  206. const { handleLocalFileUpload } = useLocalFileUploader({ disabled, onUpload, limit })
  207. const [isDragActive, setIsDragActive] = useState(false)
  208. const handleDragEnter = useCallback((e: React.DragEvent<T>) => {
  209. e.preventDefault()
  210. e.stopPropagation()
  211. if (!disabled)
  212. setIsDragActive(true)
  213. }, [disabled])
  214. const handleDragOver = useCallback((e: React.DragEvent<T>) => {
  215. e.preventDefault()
  216. e.stopPropagation()
  217. }, [])
  218. const handleDragLeave = useCallback((e: React.DragEvent<T>) => {
  219. e.preventDefault()
  220. e.stopPropagation()
  221. setIsDragActive(false)
  222. }, [])
  223. const handleDrop = useCallback((e: React.DragEvent<T>) => {
  224. e.preventDefault()
  225. e.stopPropagation()
  226. setIsDragActive(false)
  227. const file = e.dataTransfer.files[0]
  228. if (!file)
  229. return
  230. handleLocalFileUpload(file)
  231. }, [handleLocalFileUpload])
  232. return {
  233. onDragEnter: handleDragEnter,
  234. onDragOver: handleDragOver,
  235. onDragLeave: handleDragLeave,
  236. onDrop: handleDrop,
  237. isDragActive,
  238. }
  239. }