mirror of
https://github.com/arc53/DocsGPT.git
synced 2025-11-29 16:43:16 +00:00
(feat: attachment) integrate upload on fe
This commit is contained in:
@@ -2,6 +2,8 @@ import { useEffect, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useDarkTheme } from '../hooks';
|
||||
import { useSelector } from 'react-redux';
|
||||
import userService from '../api/services/userService';
|
||||
import endpoints from '../api/endpoints';
|
||||
import PaperPlane from '../assets/paper_plane.svg';
|
||||
import SourceIcon from '../assets/source.svg';
|
||||
import ToolIcon from '../assets/tool.svg';
|
||||
@@ -9,11 +11,12 @@ import SpinnerDark from '../assets/spinner-dark.svg';
|
||||
import Spinner from '../assets/spinner.svg';
|
||||
import SourcesPopup from './SourcesPopup';
|
||||
import ToolsPopup from './ToolsPopup';
|
||||
import { selectSelectedDocs } from '../preferences/preferenceSlice';
|
||||
import { selectSelectedDocs, selectToken } from '../preferences/preferenceSlice';
|
||||
import { ActiveState } from '../models/misc';
|
||||
import Upload from '../upload/Upload';
|
||||
import ClipIcon from '../assets/clip.svg';
|
||||
|
||||
|
||||
interface MessageInputProps {
|
||||
value: string;
|
||||
onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void;
|
||||
@@ -21,6 +24,15 @@ interface MessageInputProps {
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
interface UploadState {
|
||||
taskId: string;
|
||||
fileName: string;
|
||||
progress: number;
|
||||
attachment_id?: string;
|
||||
token_count?: number;
|
||||
status: 'uploading' | 'processing' | 'completed' | 'failed';
|
||||
}
|
||||
|
||||
export default function MessageInput({
|
||||
value,
|
||||
onChange,
|
||||
@@ -34,10 +46,139 @@ export default function MessageInput({
|
||||
const toolButtonRef = useRef<HTMLButtonElement>(null);
|
||||
const [isSourcesPopupOpen, setIsSourcesPopupOpen] = useState(false);
|
||||
const [isToolsPopupOpen, setIsToolsPopupOpen] = useState(false);
|
||||
const [uploadModalState, setUploadModalState] =
|
||||
useState<ActiveState>('INACTIVE');
|
||||
const [uploadModalState, setUploadModalState] = useState<ActiveState>('INACTIVE');
|
||||
const [uploads, setUploads] = useState<UploadState[]>([]);
|
||||
|
||||
const selectedDocs = useSelector(selectSelectedDocs);
|
||||
const token = useSelector(selectToken);
|
||||
|
||||
const handleFileAttachment = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
if (!e.target.files || e.target.files.length === 0) return;
|
||||
|
||||
const file = e.target.files[0];
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
|
||||
const apiHost = import.meta.env.VITE_API_HOST;
|
||||
const xhr = new XMLHttpRequest();
|
||||
|
||||
const uploadState: UploadState = {
|
||||
taskId: '',
|
||||
fileName: file.name,
|
||||
progress: 0,
|
||||
status: 'uploading'
|
||||
};
|
||||
|
||||
setUploads(prev => [...prev, uploadState]);
|
||||
const uploadIndex = uploads.length;
|
||||
|
||||
xhr.upload.addEventListener('progress', (event) => {
|
||||
if (event.lengthComputable) {
|
||||
const progress = Math.round((event.loaded / event.total) * 100);
|
||||
setUploads(prev => prev.map((upload, index) =>
|
||||
index === uploadIndex
|
||||
? { ...upload, progress }
|
||||
: upload
|
||||
));
|
||||
}
|
||||
});
|
||||
|
||||
xhr.onload = () => {
|
||||
if (xhr.status === 200) {
|
||||
const response = JSON.parse(xhr.responseText);
|
||||
console.log('File uploaded successfully:', response);
|
||||
|
||||
if (response.task_id) {
|
||||
setUploads(prev => prev.map((upload, index) =>
|
||||
index === uploadIndex
|
||||
? { ...upload, taskId: response.task_id, status: 'processing' }
|
||||
: upload
|
||||
));
|
||||
}
|
||||
} else {
|
||||
setUploads(prev => prev.map((upload, index) =>
|
||||
index === uploadIndex
|
||||
? { ...upload, status: 'failed' }
|
||||
: upload
|
||||
));
|
||||
console.error('Error uploading file:', xhr.responseText);
|
||||
}
|
||||
};
|
||||
|
||||
xhr.onerror = () => {
|
||||
setUploads(prev => prev.map((upload, index) =>
|
||||
index === uploadIndex
|
||||
? { ...upload, status: 'failed' }
|
||||
: upload
|
||||
));
|
||||
console.error('Network error during file upload');
|
||||
};
|
||||
|
||||
xhr.open('POST', `${apiHost}${endpoints.USER.STORE_ATTACHMENT}`);
|
||||
xhr.setRequestHeader('Authorization', `Bearer ${token}`);
|
||||
xhr.send(formData);
|
||||
e.target.value = '';
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
let timeoutIds: number[] = [];
|
||||
|
||||
const checkTaskStatus = () => {
|
||||
const processingUploads = uploads.filter(upload =>
|
||||
upload.status === 'processing' && upload.taskId
|
||||
);
|
||||
|
||||
processingUploads.forEach(upload => {
|
||||
userService
|
||||
.getTaskStatus(upload.taskId, null)
|
||||
.then((data) => data.json())
|
||||
.then((data) => {
|
||||
console.log('Task status:', data);
|
||||
|
||||
setUploads(prev => prev.map(u => {
|
||||
if (u.taskId !== upload.taskId) return u;
|
||||
|
||||
if (data.status === 'SUCCESS') {
|
||||
return {
|
||||
...u,
|
||||
status: 'completed',
|
||||
progress: 100,
|
||||
attachment_id: data.result?.attachment_id,
|
||||
token_count: data.result?.token_count
|
||||
};
|
||||
} else if (data.status === 'FAILURE') {
|
||||
return { ...u, status: 'failed' };
|
||||
} else if (data.status === 'PROGRESS' && data.result?.current) {
|
||||
return { ...u, progress: data.result.current };
|
||||
}
|
||||
return u;
|
||||
}));
|
||||
|
||||
if (data.status !== 'SUCCESS' && data.status !== 'FAILURE') {
|
||||
const timeoutId = window.setTimeout(() => checkTaskStatus(), 2000);
|
||||
timeoutIds.push(timeoutId);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('Error checking task status:', error);
|
||||
setUploads(prev => prev.map(u =>
|
||||
u.taskId === upload.taskId
|
||||
? { ...u, status: 'failed' }
|
||||
: u
|
||||
));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
if (uploads.some(upload => upload.status === 'processing')) {
|
||||
const timeoutId = window.setTimeout(checkTaskStatus, 2000);
|
||||
timeoutIds.push(timeoutId);
|
||||
}
|
||||
|
||||
return () => {
|
||||
timeoutIds.forEach(id => clearTimeout(id));
|
||||
};
|
||||
}, [uploads]);
|
||||
|
||||
const handleInput = () => {
|
||||
if (inputRef.current) {
|
||||
@@ -70,9 +211,68 @@ export default function MessageInput({
|
||||
console.log('Selected document:', doc);
|
||||
};
|
||||
|
||||
const renderUploadStatus = () => {
|
||||
const activeUploads = uploads.filter(u =>
|
||||
u.status === 'uploading' || u.status === 'processing'
|
||||
);
|
||||
|
||||
if (activeUploads.length === 0) {
|
||||
return 'Attach';
|
||||
}
|
||||
|
||||
return `Uploading ${activeUploads.length} file(s)`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full mx-2">
|
||||
<div className="flex flex-col w-full rounded-[23px] border dark:border-grey border-dark-gray bg-lotion dark:bg-transparent relative">
|
||||
<div className="flex flex-wrap gap-2 px-6 pt-3 pb-0">
|
||||
{uploads.map((upload, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-center px-3 py-1.5 rounded-[32px] border border-[#AAAAAA] dark:border-purple-taupe bg-white dark:bg-[#1F2028] text-[14px] text-[#5D5D5D] dark:text-bright-gray"
|
||||
>
|
||||
<span className="font-medium truncate max-w-[150px]">{upload.fileName}</span>
|
||||
|
||||
{upload.status === 'completed' && (
|
||||
<span className="ml-2 text-green-500">✓</span>
|
||||
)}
|
||||
|
||||
{upload.status === 'failed' && (
|
||||
<span className="ml-2 text-red-500">✗</span>
|
||||
)}
|
||||
|
||||
{(upload.status === 'uploading' || upload.status === 'processing') && (
|
||||
<div className="ml-2 w-4 h-4 relative">
|
||||
<svg className="w-4 h-4" viewBox="0 0 24 24">
|
||||
<circle
|
||||
className="text-gray-200 dark:text-gray-700"
|
||||
cx="12"
|
||||
cy="12"
|
||||
r="10"
|
||||
stroke="currentColor"
|
||||
strokeWidth="4"
|
||||
fill="none"
|
||||
/>
|
||||
<circle
|
||||
className="text-blue-600 dark:text-blue-400"
|
||||
cx="12"
|
||||
cy="12"
|
||||
r="10"
|
||||
stroke="currentColor"
|
||||
strokeWidth="4"
|
||||
fill="none"
|
||||
strokeDasharray="62.83"
|
||||
strokeDashoffset={62.83 - (upload.progress / 100) * 62.83}
|
||||
transform="rotate(-90 12 12)"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="w-full">
|
||||
<label htmlFor="message-input" className="sr-only">
|
||||
{t('inputPlaceholder')}
|
||||
@@ -116,15 +316,17 @@ export default function MessageInput({
|
||||
{t('settings.tools.label')}
|
||||
</span>
|
||||
</button>
|
||||
{/*<button
|
||||
className="flex items-center px-3 py-1.5 rounded-[32px] border border-[#AAAAAA] dark:border-purple-taupe hover:bg-gray-100 dark:hover:bg-[#2C2E3C] transition-colors"
|
||||
onClick={() => setUploadModalState('ACTIVE')}
|
||||
>
|
||||
<label className="flex items-center px-3 py-1.5 rounded-[32px] border border-[#AAAAAA] dark:border-purple-taupe hover:bg-gray-100 dark:hover:bg-[#2C2E3C] transition-colors cursor-pointer">
|
||||
<img src={ClipIcon} alt="Attach" className="w-4 h-4 mr-1.5" />
|
||||
<span className="text-[14px] text-[#5D5D5D] dark:text-bright-gray font-medium">
|
||||
Attach
|
||||
</span>
|
||||
</button>*/}
|
||||
<input
|
||||
type="file"
|
||||
className="hidden"
|
||||
onChange={handleFileAttachment}
|
||||
/>
|
||||
</label>
|
||||
|
||||
{/* Additional badges can be added here in the future */}
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user