file uploader

This commit is contained in:
StyleZhang 2024-09-11 18:25:14 +08:00
parent 9a3b7345c4
commit 0076577764
14 changed files with 284 additions and 111 deletions

View File

@ -40,7 +40,7 @@ const ChatInputArea = ({
visionConfig,
speechToTextConfig = { enabled: true },
onSend,
theme,
// theme,
}: ChatInputAreaProps) => {
const { t } = useTranslation()
const { notify } = useToastContext()
@ -103,7 +103,7 @@ const ChatInputArea = ({
)
return (
<FileContextProvider>
<FileContextProvider onChange={() => {}}>
<>
<div
className={cn(

View File

@ -1,10 +1,10 @@
import type { ChangeEvent } from 'react'
import {
memo,
useState,
} from 'react'
import { useTranslation } from 'react-i18next'
import { RiUploadCloud2Line } from '@remixicon/react'
import FileInput from '../file-input'
import { useFile } from '../hooks'
import {
PortalToFollowElem,
@ -15,29 +15,18 @@ import Button from '@/app/components/base/button'
type FileFromLinkOrLocalProps = {
showFromLink?: boolean
onLink?: (url: string) => void
showFromLocal?: boolean
trigger: (open: boolean) => React.ReactNode
}
const FileFromLinkOrLocal = ({
showFromLink = true,
onLink,
showFromLocal = true,
trigger,
}: FileFromLinkOrLocalProps) => {
const { t } = useTranslation()
const [open, setOpen] = useState(false)
const [url, setUrl] = useState('')
const { handleLocalFileUpload } = useFile()
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
if (!file)
return
handleLocalFileUpload(file)
}
const { handleLoadFileFromLink } = useFile()
return (
<PortalToFollowElem
@ -49,7 +38,7 @@ const FileFromLinkOrLocal = ({
<PortalToFollowElemTrigger onClick={() => setOpen(v => !v)} asChild>
{trigger(open)}
</PortalToFollowElemTrigger>
<PortalToFollowElemContent>
<PortalToFollowElemContent className='z-10'>
<div className='p-3 w-[280px] bg-components-panel-bg-blur border-[0.5px] border-components-panel-border rounded-xl shadow-lg'>
{
showFromLink && (
@ -65,7 +54,7 @@ const FileFromLinkOrLocal = ({
size='small'
variant='primary'
disabled={!url}
onClick={() => onLink?.(url)}
onClick={() => handleLoadFileFromLink()}
>
{t('common.operation.ok')}
</Button>
@ -89,12 +78,7 @@ const FileFromLinkOrLocal = ({
>
<RiUploadCloud2Line className='mr-1 w-4 h-4' />
{t('common.fileUploader.uploadFromComputer')}
<input
className='absolute block inset-0 opacity-0 text-[0] w-full disabled:cursor-not-allowed cursor-pointer'
onClick={e => ((e.target as HTMLInputElement).value = '')}
type='file'
onChange={handleChange}
/>
<FileInput />
</Button>
)
}

View File

@ -0,0 +1,30 @@
import cn from '@/utils/classnames'
type FileImageRenderProps = {
imageUrl: string
className?: string
alt?: string
onLoad?: () => void
onError?: () => void
}
const FileImageRender = ({
imageUrl,
className,
alt,
onLoad,
onError,
}: FileImageRenderProps) => {
return (
<div className={cn('border-[2px] border-effects-image-frame shadow-xs', className)}>
<img
className='w-full h-full object-cover'
alt={alt}
onLoad={onLoad}
onError={onError}
src={imageUrl}
/>
</div>
)
}
export default FileImageRender

View File

@ -0,0 +1,21 @@
import { useFile } from './hooks'
const FileInput = () => {
const { handleLocalFileUpload } = useFile()
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
if (file)
handleLocalFileUpload(file)
}
return (
<input
className='absolute block inset-0 opacity-0 text-[0] w-full disabled:cursor-not-allowed cursor-pointer'
onClick={e => ((e.target as HTMLInputElement).value = '')}
type='file'
onChange={handleChange}
/>
)
}
export default FileInput

View File

@ -21,23 +21,23 @@ const FileListFlexOperation = forwardRef<HTMLDivElement>((_, ref) => {
{
files.map(file => (
<div
key={file._id}
key={file.id}
className='relative'
>
<Button
className='absolute -right-1.5 -top-1.5 p-0 w-5 h-5 rounded-full z-10'
onClick={() => handleRemoveFile(file._id)}
onClick={() => handleRemoveFile(file.id)}
>
<RiCloseLine className='w-4 h-4 text-components-button-secondary-text' />
</Button>
{
file._progress !== 100 && (
file.progress !== 100 && (
<div
className='absolute inset-0 border-[2px] border-effects-image-frame shadow-md bg-black'
>
<ProgressCircle
className='absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2'
percentage={file._progress}
percentage={file.progress}
size={16}
circleStrokeColor='stroke-components-progress-white-border'
circleFillColor='fill-transparent'

View File

@ -0,0 +1,7 @@
const FileThumb = () => {
return (
<div></div>
)
}
export default FileThumb

View File

@ -13,61 +13,62 @@ import {
RiFileWordFill,
RiMarkdownFill,
} from '@remixicon/react'
import { FileTypeEnum } from './types'
import { FileAppearanceTypeEnum } from './types'
import type { FileAppearanceType } from './types'
import cn from '@/utils/classnames'
const FILE_TYPE_ICON_MAP = {
[FileTypeEnum.PDF]: {
[FileAppearanceTypeEnum.PDF]: {
component: RiFilePdf2Fill,
color: 'text-[#EA3434]',
},
[FileTypeEnum.IMAGE]: {
[FileAppearanceTypeEnum.IMAGE]: {
component: RiFileImageFill,
color: 'text-[#00B2EA]',
},
[FileTypeEnum.VIDEO]: {
[FileAppearanceTypeEnum.VIDEO]: {
component: RiFileVideoFill,
color: 'text-[#844FDA]',
},
[FileTypeEnum.AUDIO]: {
[FileAppearanceTypeEnum.AUDIO]: {
component: RiFileMusicFill,
color: 'text-[#FF3093]',
},
[FileTypeEnum.DOCUMENT]: {
[FileAppearanceTypeEnum.DOCUMENT]: {
component: RiFileTextFill,
color: 'text-[#6F8BB5]',
},
[FileTypeEnum.CODE]: {
[FileAppearanceTypeEnum.CODE]: {
component: RiFileCodeFill,
color: 'text-[#BCC0D1]',
},
[FileTypeEnum.MARKDOWN]: {
[FileAppearanceTypeEnum.MARKDOWN]: {
component: RiMarkdownFill,
color: 'text-[#309BEC]',
},
[FileTypeEnum.OTHER]: {
[FileAppearanceTypeEnum.OTHER]: {
component: RiFile3Fill,
color: 'text-[#BCC0D1]',
},
[FileTypeEnum.EXCEL]: {
[FileAppearanceTypeEnum.EXCEL]: {
component: RiFileExcelFill,
color: 'text-[#01AC49]',
},
[FileTypeEnum.WORD]: {
[FileAppearanceTypeEnum.WORD]: {
component: RiFileWordFill,
color: 'text-[#2684FF]',
},
[FileTypeEnum.PPT]: {
[FileAppearanceTypeEnum.PPT]: {
component: RiFilePpt2Fill,
color: 'text-[#FF650F]',
},
[FileTypeEnum.GIF]: {
[FileAppearanceTypeEnum.GIF]: {
component: RiFileGifFill,
color: 'text-[#00B2EA]',
},
}
type FileTypeIconProps = {
type: keyof typeof FileTypeEnum
type: FileAppearanceType
size?: 'sm' | 'lg'
className?: string
}

View File

@ -1,32 +1,91 @@
import { memo } from 'react'
import {
RiDeleteBinLine,
RiEditCircleFill,
} from '@remixicon/react'
import FileTypeIcon from '../file-type-icon'
import type { FileEntity } from '../types'
import { useFile } from '../hooks'
import {
getFileAppearanceType,
getFileExtension,
isImage,
} from '../utils'
import FileImageRender from '../file-image-render'
import ActionButton from '@/app/components/base/action-button'
import ProgressCircle from '@/app/components/base/progress-bar/progress-circle'
import { formatFileSize } from '@/utils/format'
import cn from '@/utils/classnames'
type FileInAttachmentItemProps = {
file: FileEntity
}
const FileInAttachmentItem = ({
file,
}: FileInAttachmentItemProps) => {
const {
handleRemoveFile,
handleReUploadFile,
} = useFile()
const ext = getFileExtension(file.file)
const FileInAttachmentItem = () => {
return (
<div className='flex items-center px-3 h-12 rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg shadow-xs'>
<FileTypeIcon
type='AUDIO'
size='lg'
className='mr-3'
/>
<div className='grow'>
<div className='mb-0.5 system-xs-medium text-text-secondary'>Yellow mountain range.jpg</div>
<div className={cn(
'flex items-center pr-3 h-12 rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg shadow-xs',
file.progress === -1 && 'bg-state-destructive-hover border-state-destructive-border',
)}>
<div className='flex items-center justify-center w-12 h-12'>
{
isImage(file?.file) && (
<FileImageRender
className='w-8 h-8'
imageUrl={file.base64Url || ''}
/>
)
}
{
!isImage(file.file) && (
<FileTypeIcon
type={getFileAppearanceType(file?.file)}
size='lg'
/>
)
}
</div>
<div className='grow w-0'>
<div
className='mb-0.5 system-xs-medium text-text-secondary truncate'
title={file.file?.name}
>
{file.file?.name}
</div>
<div className='flex items-center system-2xs-medium-uppercase text-text-tertiary'>
<span>JPG</span>
{
ext && (
<span>{ext.toLowerCase()}</span>
)
}
<span className='mx-1 system-2xs-medium'></span>
<span>21.5 MB</span>
<span>{formatFileSize(file.file?.size || 0)}</span>
</div>
</div>
<div className='shrink-0 flex items-center'>
<ProgressCircle
percentage={10}
/>
<ActionButton>
{
file.progress >= 0 && file.progress < 100 && (
<ProgressCircle
className='mr-2.5'
percentage={file.progress}
/>
)
}
{
file.progress === -1 && (
<ActionButton onClick={() => handleReUploadFile(file.id)}>
<RiEditCircleFill className='mr-1 w-4 h-4 text-text-tertiary' />
</ActionButton>
)
}
<ActionButton onClick={() => handleRemoveFile(file.id)}>
<RiDeleteBinLine className='w-4 h-4' />
</ActionButton>
</div>

View File

@ -11,6 +11,8 @@ import {
FileContextProvider,
useStore,
} from '../store'
import type { FileEntity } from '../types'
import FileInput from '../file-input'
import FileInAttachmentItem from './file-in-attachment-item'
import Button from '@/app/components/base/button'
import cn from '@/utils/classnames'
@ -41,10 +43,15 @@ const FileUploaderInAttachment = () => {
<Button
key={option.value}
variant='tertiary'
className={cn('basis-1/2', open && 'bg-components-button-tertiary-bg-hover')}
className={cn('basis-1/2 relative', open && 'bg-components-button-tertiary-bg-hover')}
>
{option.icon}
<span className='ml-1'>{option.label}</span>
{
option.value === 'local' && (
<FileInput />
)
}
</Button>
)
}, [])
@ -75,7 +82,8 @@ const FileUploaderInAttachment = () => {
{
files.map(file => (
<FileInAttachmentItem
key={file._id}
key={file.id}
file={file}
/>
))
}
@ -84,9 +92,14 @@ const FileUploaderInAttachment = () => {
)
}
const FileUploaderInAttachmentWrapper = () => {
type FileUploaderInAttachmentWrapperProps = {
onChange: (files: FileEntity[]) => void
}
const FileUploaderInAttachmentWrapper = ({
onChange,
}: FileUploaderInAttachmentWrapperProps) => {
return (
<FileContextProvider>
<FileContextProvider onChange={onChange}>
<FileUploaderInAttachment />
</FileContextProvider>
)

View File

@ -3,6 +3,7 @@ import {
useCallback,
useState,
} from 'react'
import { useParams } from 'next/navigation'
import produce from 'immer'
import { v4 as uuid4 } from 'uuid'
import { useTranslation } from 'react-i18next'
@ -11,14 +12,11 @@ import { useFileStore } from './store'
import { fileUpload } from './utils'
import { useToastContext } from '@/app/components/base/toast'
type UseFileParams = {
isPublicAPI?: boolean
url?: string
}
export const useFile = () => {
const { t } = useTranslation()
const { notify } = useToastContext()
const fileStore = useFileStore()
const params = useParams()
const handleAddOrUpdateFiles = useCallback((newFile: FileEntity) => {
const {
@ -27,7 +25,7 @@ export const useFile = () => {
} = fileStore.getState()
const newFiles = produce(files, (draft) => {
const index = draft.findIndex(file => file._id === newFile._id)
const index = draft.findIndex(file => file.id === newFile.id)
if (index > -1)
draft[index] = newFile
@ -43,23 +41,44 @@ export const useFile = () => {
setFiles,
} = fileStore.getState()
const newFiles = files.filter(file => file._id !== fileId)
const newFiles = files.filter(file => file.id !== fileId)
setFiles(newFiles)
}, [fileStore])
const handleLoadFileFromLink = useCallback((fileId: string, progress: number) => {
const handleReUploadFile = useCallback((fileId: string) => {
const {
files,
setFiles,
} = fileStore.getState()
const newFiles = produce(files, (draft) => {
const index = draft.findIndex(file => file._id === fileId)
const index = files.findIndex(file => file.id === fileId)
if (index > -1)
draft[index]._progress = progress
})
setFiles(newFiles)
}, [fileStore])
if (index > -1) {
const uploadingFile = files[index]
const newFiles = produce(files, (draft) => {
draft[index].progress = 0
})
setFiles(newFiles)
fileUpload({
file: uploadingFile.file!,
onProgressCallback: (progress) => {
handleAddOrUpdateFiles({ ...uploadingFile, progress })
},
onSuccessCallback: (res) => {
handleAddOrUpdateFiles({ ...uploadingFile, fileId: res.id, progress: 100 })
},
onErrorCallback: () => {
notify({ type: 'error', message: t('common.imageUploader.uploadFromComputerUploadError') })
handleAddOrUpdateFiles({ ...uploadingFile, progress: -1 })
},
}, !!params.token)
}
}, [fileStore, notify, t, handleAddOrUpdateFiles, params])
const handleLoadFileFromLink = useCallback(() => {}, [])
const handleLoadFileFromLinkSuccess = useCallback(() => { }, [])
const handleLoadFileFromLinkError = useCallback(() => { }, [])
const handleClearFiles = useCallback(() => {
const {
@ -68,39 +87,33 @@ export const useFile = () => {
setFiles([])
}, [fileStore])
const handleLocalFileUpload = useCallback((
file: File,
{
isPublicAPI,
url,
}: UseFileParams = { isPublicAPI: false },
) => {
const handleLocalFileUpload = useCallback((file: File) => {
const reader = new FileReader()
const isImage = file.type.startsWith('image')
reader.addEventListener(
'load',
() => {
const uploadingFile = {
_id: uuid4(),
id: uuid4(),
file,
_url: reader.result as string,
_progress: 0,
_base64Url: isImage ? reader.result as string : '',
url: '',
progress: 0,
base64Url: isImage ? reader.result as string : '',
}
handleAddOrUpdateFiles(uploadingFile)
fileUpload({
file: uploadingFile.file,
onProgressCallback: (progress) => {
handleAddOrUpdateFiles({ ...uploadingFile, _progress: progress })
handleAddOrUpdateFiles({ ...uploadingFile, progress })
},
onSuccessCallback: (res) => {
handleAddOrUpdateFiles({ ...uploadingFile, _fileId: res.id, _progress: 100 })
handleAddOrUpdateFiles({ ...uploadingFile, fileId: res.id, progress: 100 })
},
onErrorCallback: () => {
notify({ type: 'error', message: t('common.imageUploader.uploadFromComputerUploadError') })
handleAddOrUpdateFiles({ ...uploadingFile, _progress: -1 })
handleAddOrUpdateFiles({ ...uploadingFile, progress: -1 })
},
}, isPublicAPI, url)
}, !!params.token)
},
false,
)
@ -112,7 +125,7 @@ export const useFile = () => {
false,
)
reader.readAsDataURL(file)
}, [notify, t, handleAddOrUpdateFiles])
}, [notify, t, handleAddOrUpdateFiles, params.token])
const handleClipboardPasteFile = useCallback((e: ClipboardEvent<HTMLTextAreaElement>) => {
const file = e.clipboardData?.files[0]
@ -154,7 +167,10 @@ export const useFile = () => {
return {
handleAddOrUpdateFiles,
handleRemoveFile,
handleReUploadFile,
handleLoadFileFromLink,
handleLoadFileFromLinkSuccess,
handleLoadFileFromLinkError,
handleClearFiles,
handleLocalFileUpload,
handleClipboardPasteFile,

View File

@ -4,9 +4,9 @@ import {
useRef,
} from 'react'
import {
create,
useStore as useZustandStore,
} from 'zustand'
import { createStore } from 'zustand/vanilla'
import type { FileEntity } from './types'
type Shape = {
@ -14,10 +14,15 @@ type Shape = {
setFiles: (files: FileEntity[]) => void
}
export const createFileStore = () => {
return createStore<Shape>(set => ({
export const createFileStore = ({
onChange,
}: Pick<FileProviderProps, 'onChange'>) => {
return create<Shape>(set => ({
files: [],
setFiles: files => set({ files }),
setFiles: (files) => {
set({ files })
onChange(files)
},
}))
}
@ -38,12 +43,18 @@ export const useFileStore = () => {
type FileProviderProps = {
children: React.ReactNode
onChange: (files: FileEntity[]) => void
isPublicAPI?: boolean
url?: string
}
export const FileContextProvider = ({ children }: FileProviderProps) => {
export const FileContextProvider = ({
children,
onChange,
}: FileProviderProps) => {
const storeRef = useRef<FileStore>()
if (!storeRef.current)
storeRef.current = createFileStore()
storeRef.current = createFileStore({ onChange })
return (
<FileContext.Provider value={storeRef.current}>

View File

@ -1,6 +1,4 @@
import type { TransferMethod } from '@/types/app'
export enum FileTypeEnum {
export enum FileAppearanceTypeEnum {
IMAGE = 'IMAGE',
VIDEO = 'VIDEO',
AUDIO = 'AUDIO',
@ -15,12 +13,13 @@ export enum FileTypeEnum {
OTHER = 'OTHER',
}
export type FileAppearanceType = keyof typeof FileAppearanceTypeEnum
export type FileEntity = {
file: File
_id: string
_fileId?: string
_progress?: number
_url?: string
_base64Url?: string
_method?: TransferMethod
id: string
file?: File
fileId?: string
progress: number
url?: string
base64Url?: string
}

View File

@ -1,3 +1,4 @@
import { FileAppearanceTypeEnum } from './types'
import { upload } from '@/service/base'
type FileUploadParams = {
@ -35,8 +36,39 @@ export const fileUpload: FileUpload = ({
})
}
export const isFileType = (type: string) => {
return (file: File) => {
return file.type === type
}
export const getFileAppearanceType = (file?: File) => {
if (!file)
return FileAppearanceTypeEnum.OTHER
const mimeType = file.type
if (mimeType.includes('image'))
return FileAppearanceTypeEnum.IMAGE
if (mimeType.includes('video'))
return FileAppearanceTypeEnum.VIDEO
if (mimeType.includes('audio'))
return FileAppearanceTypeEnum.AUDIO
if (mimeType.includes('pdf'))
return FileAppearanceTypeEnum.PDF
return FileAppearanceTypeEnum.OTHER
}
export const isImage = (file?: File) => {
return file?.type.startsWith('image')
}
export const getFileExtension = (file?: File) => {
if (!file)
return ''
const fileNamePair = file.name.split('.')
const fileNamePairLength = fileNamePair.length
if (fileNamePairLength > 1)
return fileNamePair[fileNamePairLength - 1]
return ''
}

View File

@ -114,7 +114,7 @@ const RunOnce: FC<IRunOnceProps> = ({
</div>
)
}
<FileUploaderInAttachmentWrapper />
<FileUploaderInAttachmentWrapper onChange={() => {}} />
{promptConfig.prompt_variables.length > 0 && (
<div className='mt-4 h-[1px] bg-gray-100'></div>
)}