index.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. 'use client'
  2. import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
  3. import { useTranslation } from 'react-i18next'
  4. import { useContext } from 'use-context-selector'
  5. import useSWR from 'swr'
  6. import s from './index.module.css'
  7. import cn from '@/utils/classnames'
  8. import type { CustomFile as File, FileItem } from '@/models/datasets'
  9. import { ToastContext } from '@/app/components/base/toast'
  10. import { upload } from '@/service/base'
  11. import { fetchFileUploadConfig } from '@/service/common'
  12. import { fetchSupportFileTypes } from '@/service/datasets'
  13. import I18n from '@/context/i18n'
  14. import { LanguagesSupported } from '@/i18n/language'
  15. import { IS_CE_EDITION } from '@/config'
  16. const FILES_NUMBER_LIMIT = 20
  17. type IFileUploaderProps = {
  18. fileList: FileItem[]
  19. titleClassName?: string
  20. prepareFileList: (files: FileItem[]) => void
  21. onFileUpdate: (fileItem: FileItem, progress: number, list: FileItem[]) => void
  22. onFileListUpdate?: (files: FileItem[]) => void
  23. onPreview: (file: File) => void
  24. notSupportBatchUpload?: boolean
  25. }
  26. const FileUploader = ({
  27. fileList,
  28. titleClassName,
  29. prepareFileList,
  30. onFileUpdate,
  31. onFileListUpdate,
  32. onPreview,
  33. notSupportBatchUpload,
  34. }: IFileUploaderProps) => {
  35. const { t } = useTranslation()
  36. const { notify } = useContext(ToastContext)
  37. const { locale } = useContext(I18n)
  38. const [dragging, setDragging] = useState(false)
  39. const dropRef = useRef<HTMLDivElement>(null)
  40. const dragRef = useRef<HTMLDivElement>(null)
  41. const fileUploader = useRef<HTMLInputElement>(null)
  42. const hideUpload = notSupportBatchUpload && fileList.length > 0
  43. const { data: fileUploadConfigResponse } = useSWR({ url: '/files/upload' }, fetchFileUploadConfig)
  44. const { data: supportFileTypesResponse } = useSWR({ url: '/files/support-type' }, fetchSupportFileTypes)
  45. const supportTypes = supportFileTypesResponse?.allowed_extensions || []
  46. const supportTypesShowNames = (() => {
  47. const extensionMap: { [key: string]: string } = {
  48. md: 'markdown',
  49. pptx: 'pptx',
  50. htm: 'html',
  51. xlsx: 'xlsx',
  52. docx: 'docx',
  53. }
  54. return [...supportTypes]
  55. .map(item => extensionMap[item] || item) // map to standardized extension
  56. .map(item => item.toLowerCase()) // convert to lower case
  57. .filter((item, index, self) => self.indexOf(item) === index) // remove duplicates
  58. .map(item => item.toUpperCase()) // convert to upper case
  59. .join(locale !== LanguagesSupported[1] ? ', ' : '、 ')
  60. })()
  61. const ACCEPTS = supportTypes.map((ext: string) => `.${ext}`)
  62. const fileUploadConfig = useMemo(() => fileUploadConfigResponse ?? {
  63. file_size_limit: 15,
  64. batch_count_limit: 5,
  65. }, [fileUploadConfigResponse])
  66. const fileListRef = useRef<FileItem[]>([])
  67. // utils
  68. const getFileType = (currentFile: File) => {
  69. if (!currentFile)
  70. return ''
  71. const arr = currentFile.name.split('.')
  72. return arr[arr.length - 1]
  73. }
  74. const getFileSize = (size: number) => {
  75. if (size / 1024 < 10)
  76. return `${(size / 1024).toFixed(2)}KB`
  77. return `${(size / 1024 / 1024).toFixed(2)}MB`
  78. }
  79. const isValid = useCallback((file: File) => {
  80. const { size } = file
  81. const ext = `.${getFileType(file)}`
  82. const isValidType = ACCEPTS.includes(ext.toLowerCase())
  83. if (!isValidType)
  84. notify({ type: 'error', message: t('datasetCreation.stepOne.uploader.validation.typeError') })
  85. const isValidSize = size <= fileUploadConfig.file_size_limit * 1024 * 1024
  86. if (!isValidSize)
  87. notify({ type: 'error', message: t('datasetCreation.stepOne.uploader.validation.size', { size: fileUploadConfig.file_size_limit }) })
  88. return isValidType && isValidSize
  89. }, [fileUploadConfig, notify, t, ACCEPTS])
  90. const fileUpload = useCallback(async (fileItem: FileItem): Promise<FileItem> => {
  91. const formData = new FormData()
  92. formData.append('file', fileItem.file)
  93. const onProgress = (e: ProgressEvent) => {
  94. if (e.lengthComputable) {
  95. const percent = Math.floor(e.loaded / e.total * 100)
  96. onFileUpdate(fileItem, percent, fileListRef.current)
  97. }
  98. }
  99. return upload({
  100. xhr: new XMLHttpRequest(),
  101. data: formData,
  102. onprogress: onProgress,
  103. }, false, undefined, '?source=datasets')
  104. .then((res: File) => {
  105. const completeFile = {
  106. fileID: fileItem.fileID,
  107. file: res,
  108. progress: -1,
  109. }
  110. const index = fileListRef.current.findIndex(item => item.fileID === fileItem.fileID)
  111. fileListRef.current[index] = completeFile
  112. onFileUpdate(completeFile, 100, fileListRef.current)
  113. return Promise.resolve({ ...completeFile })
  114. })
  115. .catch((e) => {
  116. notify({ type: 'error', message: e?.response?.code === 'forbidden' ? e?.response?.message : t('datasetCreation.stepOne.uploader.failed') })
  117. onFileUpdate(fileItem, -2, fileListRef.current)
  118. return Promise.resolve({ ...fileItem })
  119. })
  120. .finally()
  121. }, [fileListRef, notify, onFileUpdate, t])
  122. const uploadBatchFiles = useCallback((bFiles: FileItem[]) => {
  123. bFiles.forEach(bf => (bf.progress = 0))
  124. return Promise.all(bFiles.map(fileUpload))
  125. }, [fileUpload])
  126. const uploadMultipleFiles = useCallback(async (files: FileItem[]) => {
  127. const batchCountLimit = fileUploadConfig.batch_count_limit
  128. const length = files.length
  129. let start = 0
  130. let end = 0
  131. while (start < length) {
  132. if (start + batchCountLimit > length)
  133. end = length
  134. else
  135. end = start + batchCountLimit
  136. const bFiles = files.slice(start, end)
  137. await uploadBatchFiles(bFiles)
  138. start = end
  139. }
  140. }, [fileUploadConfig, uploadBatchFiles])
  141. const initialUpload = useCallback((files: File[]) => {
  142. if (!files.length)
  143. return false
  144. if (files.length + fileList.length > FILES_NUMBER_LIMIT && !IS_CE_EDITION) {
  145. notify({ type: 'error', message: t('datasetCreation.stepOne.uploader.validation.filesNumber', { filesNumber: FILES_NUMBER_LIMIT }) })
  146. return false
  147. }
  148. const preparedFiles = files.map((file, index) => ({
  149. fileID: `file${index}-${Date.now()}`,
  150. file,
  151. progress: -1,
  152. }))
  153. const newFiles = [...fileListRef.current, ...preparedFiles]
  154. prepareFileList(newFiles)
  155. fileListRef.current = newFiles
  156. uploadMultipleFiles(preparedFiles)
  157. }, [prepareFileList, uploadMultipleFiles, notify, t, fileList])
  158. const handleDragEnter = (e: DragEvent) => {
  159. e.preventDefault()
  160. e.stopPropagation()
  161. e.target !== dragRef.current && setDragging(true)
  162. }
  163. const handleDragOver = (e: DragEvent) => {
  164. e.preventDefault()
  165. e.stopPropagation()
  166. }
  167. const handleDragLeave = (e: DragEvent) => {
  168. e.preventDefault()
  169. e.stopPropagation()
  170. e.target === dragRef.current && setDragging(false)
  171. }
  172. const handleDrop = useCallback((e: DragEvent) => {
  173. e.preventDefault()
  174. e.stopPropagation()
  175. setDragging(false)
  176. if (!e.dataTransfer)
  177. return
  178. const files = [...e.dataTransfer.files] as File[]
  179. const validFiles = files.filter(isValid)
  180. initialUpload(validFiles)
  181. }, [initialUpload, isValid])
  182. const selectHandle = () => {
  183. if (fileUploader.current)
  184. fileUploader.current.click()
  185. }
  186. const removeFile = (fileID: string) => {
  187. if (fileUploader.current)
  188. fileUploader.current.value = ''
  189. fileListRef.current = fileListRef.current.filter(item => item.fileID !== fileID)
  190. onFileListUpdate?.([...fileListRef.current])
  191. }
  192. const fileChangeHandle = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
  193. const files = [...(e.target.files ?? [])] as File[]
  194. initialUpload(files.filter(isValid))
  195. }, [isValid, initialUpload])
  196. useEffect(() => {
  197. dropRef.current?.addEventListener('dragenter', handleDragEnter)
  198. dropRef.current?.addEventListener('dragover', handleDragOver)
  199. dropRef.current?.addEventListener('dragleave', handleDragLeave)
  200. dropRef.current?.addEventListener('drop', handleDrop)
  201. return () => {
  202. dropRef.current?.removeEventListener('dragenter', handleDragEnter)
  203. dropRef.current?.removeEventListener('dragover', handleDragOver)
  204. dropRef.current?.removeEventListener('dragleave', handleDragLeave)
  205. dropRef.current?.removeEventListener('drop', handleDrop)
  206. }
  207. }, [handleDrop])
  208. return (
  209. <div className={s.fileUploader}>
  210. {!hideUpload && (
  211. <input
  212. ref={fileUploader}
  213. id="fileUploader"
  214. style={{ display: 'none' }}
  215. type="file"
  216. multiple={!notSupportBatchUpload}
  217. accept={ACCEPTS.join(',')}
  218. onChange={fileChangeHandle}
  219. />
  220. )}
  221. <div className={cn(s.title, titleClassName)}>{t('datasetCreation.stepOne.uploader.title')}</div>
  222. {!hideUpload && (
  223. <div ref={dropRef} className={cn(s.uploader, dragging && s.dragging)}>
  224. <div className='flex justify-center items-center min-h-6 mb-2'>
  225. <span className={s.uploadIcon} />
  226. <span>
  227. {t('datasetCreation.stepOne.uploader.button')}
  228. <label className={s.browse} onClick={selectHandle}>{t('datasetCreation.stepOne.uploader.browse')}</label>
  229. </span>
  230. </div>
  231. <div className={s.tip}>{t('datasetCreation.stepOne.uploader.tip', {
  232. size: fileUploadConfig.file_size_limit,
  233. supportTypes: supportTypesShowNames,
  234. })}</div>
  235. {dragging && <div ref={dragRef} className={s.draggingCover} />}
  236. </div>
  237. )}
  238. <div className={s.fileList}>
  239. {fileList.map((fileItem, index) => (
  240. <div
  241. key={`${fileItem.fileID}-${index}`}
  242. onClick={() => fileItem.file?.id && onPreview(fileItem.file)}
  243. className={cn(
  244. s.file,
  245. fileItem.progress < 100 && s.uploading,
  246. )}
  247. >
  248. {fileItem.progress < 100 && (
  249. <div className={s.progressbar} style={{ width: `${fileItem.progress}%` }} />
  250. )}
  251. <div className={s.fileInfo}>
  252. <div className={cn(s.fileIcon, s[getFileType(fileItem.file)])} />
  253. <div className={s.filename}>{fileItem.file.name}</div>
  254. <div className={s.size}>{getFileSize(fileItem.file.size)}</div>
  255. </div>
  256. <div className={s.actionWrapper}>
  257. {(fileItem.progress < 100 && fileItem.progress >= 0) && (
  258. <div className={s.percent}>{`${fileItem.progress}%`}</div>
  259. )}
  260. {fileItem.progress === 100 && (
  261. <div className={s.remove} onClick={(e) => {
  262. e.stopPropagation()
  263. removeFile(fileItem.fileID)
  264. }} />
  265. )}
  266. </div>
  267. </div>
  268. ))}
  269. </div>
  270. </div>
  271. )
  272. }
  273. export default FileUploader