mirror of
https://github.com/langgenius/dify.git
synced 2026-05-11 14:58:23 +08:00
# Conflicts: # .vite-hooks/pre-commit # api/controllers/console/__init__.py # api/core/agent/base_agent_runner.py # api/core/app/app_config/easy_ui_based_app/model_config/converter.py # api/core/app/apps/agent_chat/app_runner.py # api/core/entities/provider_configuration.py # api/core/helper/moderation.py # api/core/model_manager.py # api/core/rag/embedding/cached_embedding.py # api/core/rag/retrieval/dataset_retrieval.py # api/core/rag/splitter/fixed_text_splitter.py # api/core/workflow/nodes/datasource/datasource_node.py # api/core/workflow/nodes/knowledge_index/knowledge_index_node.py # api/models/human_input.py # api/providers/trace/trace-tencent/src/dify_trace_tencent/span_builder.py # api/services/workflow_service.py # api/tasks/trigger_processing_tasks.py # api/tests/integration_tests/core/workflow/nodes/datasource/test_datasource_node_integration.py # api/tests/integration_tests/workflow/nodes/test_http.py # api/tests/integration_tests/workflow/nodes/test_parameter_extractor.py # api/tests/unit_tests/controllers/service_api/app/test_conversation.py # api/tests/unit_tests/core/prompt/test_agent_history_prompt_transform.py # api/tests/unit_tests/core/variables/test_segment.py # api/tests/unit_tests/core/workflow/graph_engine/test_mock_factory.py # api/tests/unit_tests/core/workflow/nodes/answer/test_answer.py # api/tests/unit_tests/core/workflow/nodes/datasource/test_datasource_node.py # api/tests/unit_tests/core/workflow/nodes/http_request/test_http_request_node.py # api/tests/unit_tests/core/workflow/nodes/human_input/test_email_delivery_config.py # api/tests/unit_tests/services/workflow/test_workflow_human_input_delivery.py # web/app/(commonLayout)/layout.tsx # web/app/components/app/configuration/dataset-config/params-config/weighted-score.tsx # web/app/components/app/configuration/debug/debug-with-multiple-model/debug-item.tsx # web/app/components/app/workflow-log/__tests__/list.spec.tsx # web/app/components/apps/__tests__/list.spec.tsx # web/app/components/apps/list.tsx # web/app/components/base/chat/chat-with-history/header/operation.tsx # web/app/components/base/chat/chat-with-history/sidebar/operation.tsx # web/app/components/header/account-setting/data-source-page-new/operator.tsx # web/app/components/header/account-setting/members-page/operation/index.tsx # web/app/components/plugins/marketplace/sort-dropdown/__tests__/index.spec.tsx # web/app/components/plugins/marketplace/sort-dropdown/index.tsx # web/app/components/plugins/plugin-page/plugin-tasks/index.tsx # web/app/components/workflow/header/__tests__/test-run-menu.spec.tsx # web/app/components/workflow/header/test-run-menu.tsx # web/app/components/workflow/nodes/_base/components/next-step/operator.tsx # web/app/components/workflow/nodes/_base/components/panel-operator/index.tsx # web/app/components/workflow/nodes/assigner/components/__tests__/operation-selector.spec.tsx # web/app/components/workflow/nodes/assigner/components/operation-selector.tsx # web/app/components/workflow/operator/__tests__/more-actions.spec.tsx # web/app/components/workflow/operator/zoom-in-out.tsx # web/app/components/workflow/panel/version-history-panel/context-menu/menu-item.tsx # web/app/components/workflow/selection-contextmenu.tsx # web/eslint-suppressions.json Co-authored-by: FFXN <31929997+FFXN@users.noreply.github.com>
229 lines
8.5 KiB
TypeScript
229 lines
8.5 KiB
TypeScript
import type { ClipboardEvent } from 'react'
|
|
import type { ImageFile, VisionSettings } from '@/types/app'
|
|
import { toast } from '@langgenius/dify-ui/toast'
|
|
import { useCallback, useMemo, useRef, useState } from 'react'
|
|
import { useTranslation } from 'react-i18next'
|
|
import { useParams } from '@/next/navigation'
|
|
import { ALLOW_FILE_EXTENSIONS, TransferMethod } from '@/types/app'
|
|
import { getImageUploadErrorMessage, imageUpload } from './utils'
|
|
|
|
export const useImageFiles = () => {
|
|
const params = useParams()
|
|
const { t } = useTranslation()
|
|
const [files, setFiles] = useState<ImageFile[]>([])
|
|
const filesRef = useRef<ImageFile[]>([])
|
|
const handleUpload = (imageFile: ImageFile) => {
|
|
const files = filesRef.current
|
|
const index = files.findIndex(file => file._id === imageFile._id)
|
|
if (index > -1) {
|
|
const currentFile = files[index]
|
|
const newFiles = [...files.slice(0, index), { ...currentFile, ...imageFile }, ...files.slice(index + 1)]
|
|
setFiles(newFiles)
|
|
filesRef.current = newFiles
|
|
}
|
|
else {
|
|
const newFiles = [...files, imageFile]
|
|
setFiles(newFiles)
|
|
filesRef.current = newFiles
|
|
}
|
|
}
|
|
const handleRemove = (imageFileId: string) => {
|
|
const files = filesRef.current
|
|
const index = files.findIndex(file => file._id === imageFileId)
|
|
if (index > -1) {
|
|
const currentFile = files[index]
|
|
const newFiles = [...files.slice(0, index), { ...currentFile, deleted: true }, ...files.slice(index + 1)]
|
|
setFiles(newFiles)
|
|
filesRef.current = newFiles
|
|
}
|
|
}
|
|
const handleImageLinkLoadError = (imageFileId: string) => {
|
|
const files = filesRef.current
|
|
const index = files.findIndex(file => file._id === imageFileId)
|
|
if (index > -1) {
|
|
const currentFile = files[index]
|
|
const newFiles = [...files.slice(0, index), { ...currentFile, progress: -1 }, ...files.slice(index + 1)]
|
|
filesRef.current = newFiles
|
|
setFiles(newFiles)
|
|
}
|
|
}
|
|
const handleImageLinkLoadSuccess = (imageFileId: string) => {
|
|
const files = filesRef.current
|
|
const index = files.findIndex(file => file._id === imageFileId)
|
|
if (index > -1) {
|
|
const currentImageFile = files[index]
|
|
const newFiles = [...files.slice(0, index), { ...currentImageFile, progress: 100 }, ...files.slice(index + 1)]
|
|
filesRef.current = newFiles
|
|
setFiles(newFiles)
|
|
}
|
|
}
|
|
const handleReUpload = (imageFileId: string) => {
|
|
const files = filesRef.current
|
|
const index = files.findIndex(file => file._id === imageFileId)
|
|
if (index > -1) {
|
|
const currentImageFile = files[index]
|
|
imageUpload({
|
|
file: currentImageFile.file!,
|
|
onProgressCallback: (progress) => {
|
|
const newFiles = [...files.slice(0, index), { ...currentImageFile, progress }, ...files.slice(index + 1)]
|
|
filesRef.current = newFiles
|
|
setFiles(newFiles)
|
|
},
|
|
onSuccessCallback: (res) => {
|
|
const newFiles = [...files.slice(0, index), { ...currentImageFile, fileId: res.id, progress: 100 }, ...files.slice(index + 1)]
|
|
filesRef.current = newFiles
|
|
setFiles(newFiles)
|
|
},
|
|
onErrorCallback: (error?: any) => {
|
|
const errorMessage = getImageUploadErrorMessage(error, t('imageUploader.uploadFromComputerUploadError', { ns: 'common' }), t as any)
|
|
toast.error(errorMessage)
|
|
const newFiles = [...files.slice(0, index), { ...currentImageFile, progress: -1 }, ...files.slice(index + 1)]
|
|
filesRef.current = newFiles
|
|
setFiles(newFiles)
|
|
},
|
|
}, !!params.token)
|
|
}
|
|
}
|
|
const handleClear = () => {
|
|
setFiles([])
|
|
filesRef.current = []
|
|
}
|
|
const filteredFiles = useMemo(() => {
|
|
return files.filter(file => !file.deleted)
|
|
}, [files])
|
|
return {
|
|
files: filteredFiles,
|
|
onUpload: handleUpload,
|
|
onRemove: handleRemove,
|
|
onImageLinkLoadError: handleImageLinkLoadError,
|
|
onImageLinkLoadSuccess: handleImageLinkLoadSuccess,
|
|
onReUpload: handleReUpload,
|
|
onClear: handleClear,
|
|
}
|
|
}
|
|
type useLocalUploaderProps = {
|
|
disabled?: boolean
|
|
limit?: number
|
|
onUpload: (imageFile: ImageFile) => void
|
|
}
|
|
export const useLocalFileUploader = ({ limit, disabled = false, onUpload }: useLocalUploaderProps) => {
|
|
const params = useParams()
|
|
const { t } = useTranslation()
|
|
const handleLocalFileUpload = useCallback((file: File) => {
|
|
if (disabled) {
|
|
// TODO: leave some warnings?
|
|
return
|
|
}
|
|
if (!ALLOW_FILE_EXTENSIONS.includes(file.type.split('/')[1]))
|
|
return
|
|
if (limit && file.size > limit * 1024 * 1024) {
|
|
toast.error(t('imageUploader.uploadFromComputerLimit', { ns: 'common', size: limit }))
|
|
return
|
|
}
|
|
const reader = new FileReader()
|
|
reader.addEventListener('load', () => {
|
|
const imageFile = {
|
|
type: TransferMethod.local_file,
|
|
_id: `${Date.now()}`,
|
|
fileId: '',
|
|
file,
|
|
url: reader.result as string,
|
|
base64Url: reader.result as string,
|
|
progress: 0,
|
|
}
|
|
onUpload(imageFile)
|
|
imageUpload({
|
|
file: imageFile.file,
|
|
onProgressCallback: (progress) => {
|
|
onUpload({ ...imageFile, progress })
|
|
},
|
|
onSuccessCallback: (res) => {
|
|
onUpload({ ...imageFile, fileId: res.id, progress: 100 })
|
|
},
|
|
onErrorCallback: (error?: any) => {
|
|
const errorMessage = getImageUploadErrorMessage(error, t('imageUploader.uploadFromComputerUploadError', { ns: 'common' }), t as any)
|
|
toast.error(errorMessage)
|
|
onUpload({ ...imageFile, progress: -1 })
|
|
},
|
|
}, !!params.token)
|
|
}, false)
|
|
reader.addEventListener('error', () => {
|
|
toast.error(t('imageUploader.uploadFromComputerReadError', { ns: 'common' }))
|
|
}, false)
|
|
reader.readAsDataURL(file)
|
|
}, [disabled, limit, t, onUpload, params.token])
|
|
return { disabled, handleLocalFileUpload }
|
|
}
|
|
type useClipboardUploaderProps = {
|
|
files: ImageFile[]
|
|
visionConfig?: VisionSettings
|
|
onUpload: (imageFile: ImageFile) => void
|
|
}
|
|
export const useClipboardUploader = ({ visionConfig, onUpload, files }: useClipboardUploaderProps) => {
|
|
const allowLocalUpload = visionConfig?.transfer_methods?.includes(TransferMethod.local_file)
|
|
const disabled = useMemo(() => !visionConfig
|
|
|| !visionConfig?.enabled
|
|
|| !allowLocalUpload
|
|
|| files.length >= visionConfig.number_limits!, [allowLocalUpload, files.length, visionConfig])
|
|
const limit = useMemo(() => visionConfig ? +visionConfig.image_file_size_limit! : 0, [visionConfig])
|
|
const { handleLocalFileUpload } = useLocalFileUploader({ limit, onUpload, disabled })
|
|
const handleClipboardPaste = useCallback((e: ClipboardEvent<HTMLTextAreaElement>) => {
|
|
// reserve native text copy behavior
|
|
const file = e.clipboardData?.files[0]
|
|
// when copied file, prevent default action
|
|
if (file) {
|
|
e.preventDefault()
|
|
handleLocalFileUpload(file)
|
|
}
|
|
}, [handleLocalFileUpload])
|
|
return {
|
|
onPaste: handleClipboardPaste,
|
|
}
|
|
}
|
|
type useDraggableUploaderProps = {
|
|
files: ImageFile[]
|
|
visionConfig?: VisionSettings
|
|
onUpload: (imageFile: ImageFile) => void
|
|
}
|
|
export const useDraggableUploader = <T extends HTMLElement>({ visionConfig, onUpload, files }: useDraggableUploaderProps) => {
|
|
const allowLocalUpload = visionConfig?.transfer_methods?.includes(TransferMethod.local_file)
|
|
const disabled = useMemo(() => !visionConfig
|
|
|| !visionConfig?.enabled
|
|
|| !allowLocalUpload
|
|
|| files.length >= visionConfig.number_limits!, [allowLocalUpload, files.length, visionConfig])
|
|
const limit = useMemo(() => visionConfig ? +visionConfig.image_file_size_limit! : 0, [visionConfig])
|
|
const { handleLocalFileUpload } = useLocalFileUploader({ disabled, onUpload, limit })
|
|
const [isDragActive, setIsDragActive] = useState(false)
|
|
const handleDragEnter = useCallback((e: React.DragEvent<T>) => {
|
|
e.preventDefault()
|
|
e.stopPropagation()
|
|
if (!disabled)
|
|
setIsDragActive(true)
|
|
}, [disabled])
|
|
const handleDragOver = useCallback((e: React.DragEvent<T>) => {
|
|
e.preventDefault()
|
|
e.stopPropagation()
|
|
}, [])
|
|
const handleDragLeave = useCallback((e: React.DragEvent<T>) => {
|
|
e.preventDefault()
|
|
e.stopPropagation()
|
|
setIsDragActive(false)
|
|
}, [])
|
|
const handleDrop = useCallback((e: React.DragEvent<T>) => {
|
|
e.preventDefault()
|
|
e.stopPropagation()
|
|
setIsDragActive(false)
|
|
const file = e.dataTransfer.files[0]
|
|
if (!file)
|
|
return
|
|
handleLocalFileUpload(file)
|
|
}, [handleLocalFileUpload])
|
|
return {
|
|
onDragEnter: handleDragEnter,
|
|
onDragOver: handleDragOver,
|
|
onDragLeave: handleDragLeave,
|
|
onDrop: handleDrop,
|
|
isDragActive,
|
|
}
|
|
}
|