import React, { useState, useEffect } from 'react'; import PropTypes from 'prop-types'; import { useTranslation } from 'react-i18next'; import { useDispatch } from 'react-redux'; import userService from '../api/services/userService'; import SyncIcon from '../assets/sync.svg'; import Trash from '../assets/trash.svg'; import caretSort from '../assets/caret-sort.svg'; import DropdownMenu from '../components/DropdownMenu'; import { Doc, DocumentsProps, ActiveState } from '../models/misc'; // Ensure ActiveState type is imported import SkeletonLoader from '../components/SkeletonLoader'; import { getDocs, getDocsWithPagination } from '../preferences/preferenceApi'; import { setSourceDocs } from '../preferences/preferenceSlice'; import Input from '../components/Input'; import Upload from '../upload/Upload'; // Import the Upload component import Pagination from '../components/DocumentPagination'; // Utility function to format numbers const formatTokens = (tokens: number): string => { const roundToTwoDecimals = (num: number): string => { return (Math.round((num + Number.EPSILON) * 100) / 100).toString(); }; if (tokens >= 1_000_000_000) { return roundToTwoDecimals(tokens / 1_000_000_000) + 'b'; } else if (tokens >= 1_000_000) { return roundToTwoDecimals(tokens / 1_000_000) + 'm'; } else if (tokens >= 1_000) { return roundToTwoDecimals(tokens / 1_000) + 'k'; } else { return tokens.toString(); } }; const Documents: React.FC = ({ handleDeleteDocument }) => { const { t } = useTranslation(); const dispatch = useDispatch(); // State for search input const [searchTerm, setSearchTerm] = useState(''); // State for modal: active/inactive const [modalState, setModalState] = useState('INACTIVE'); // Initialize with inactive state const [isOnboarding, setIsOnboarding] = useState(false); // State for onboarding flag const [loading, setLoading] = useState(false); const [sortField, setSortField] = useState<'date' | 'tokens'>('date'); const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc'); // Pagination const [currentPage, setCurrentPage] = useState(1); const [rowsPerPage, setRowsPerPage] = useState(10); const [totalPages, setTotalPages] = useState(1); const [totalDocuments, setTotalDocuments] = useState(0); const [fetchedDocuments, setFetchedDocuments] = useState([]); // Filter documents based on the search term const filteredDocuments = fetchedDocuments?.filter((document) => document.name.toLowerCase().includes(searchTerm.toLowerCase()), ); // State for documents const currentDocuments = filteredDocuments ?? []; const syncOptions = [ { label: 'Never', value: 'never' }, { label: 'Daily', value: 'daily' }, { label: 'Weekly', value: 'weekly' }, { label: 'Monthly', value: 'monthly' }, ]; const refreshDocs = ( field: 'date' | 'tokens' | undefined, pageNumber?: number, rows?: number, ) => { const page = pageNumber ?? currentPage; const rowsPerPg = rows ?? rowsPerPage; if (field !== undefined) { if (field === sortField) { // Toggle sort order setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc'); } else { // Change sort field and reset order to 'desc' setSortField(field); setSortOrder('desc'); } } getDocsWithPagination(sortField, sortOrder, page, rowsPerPg) .then((data) => { //dispatch(setSourceDocs(data ? data.docs : [])); setFetchedDocuments(data ? data.docs : []); setTotalPages(data ? data.totalPages : 0); setTotalDocuments(data ? data.totalDocuments : 0); }) .catch((error) => console.error(error)) .finally(() => { setLoading(false); }); }; const handleManageSync = (doc: Doc, sync_frequency: string) => { setLoading(true); userService .manageSync({ source_id: doc.id, sync_frequency }) .then(() => { return getDocs(); }) .then((data) => { dispatch(setSourceDocs(data)); }) .catch((error) => console.error(error)) .finally(() => { setLoading(false); }); }; useEffect(() => { if (modalState === 'INACTIVE') { refreshDocs(sortField, currentPage, rowsPerPage); } }, [modalState, sortField, currentPage, rowsPerPage]); return (
setSearchTerm(e.target.value)} // Handle search input change />
{loading ? ( ) : ( {!currentDocuments?.length && ( )} {Array.isArray(currentDocuments) && currentDocuments.map((document, index) => ( ))}
{t('settings.documents.name')}
{t('settings.documents.date')} refreshDocs('date')} src={caretSort} alt="sort" />
{t('settings.documents.tokenUsage')} refreshDocs('tokens')} src={caretSort} alt="sort" />
{t('settings.documents.type')}
{t('settings.documents.noData')}
{document.name} {document.date} {document.tokens ? formatTokens(+document.tokens) : ''} {document.type === 'remote' ? 'Pre-loaded' : 'Private'}
{document.type !== 'remote' && ( Delete { event.stopPropagation(); handleDeleteDocument(index, document); }} /> )} {document.syncFrequency && (
{ handleManageSync(document, value); }} defaultValue={document.syncFrequency} icon={SyncIcon} />
)}
)}
{/* Conditionally render the Upload modal based on modalState */} {modalState === 'ACTIVE' && (
{/* Your Upload component */}
)}
{/* Pagination component with props: # Note: Every time the page changes, the refreshDocs function is called with the updated page number and rows per page. and reset cursor paginated query parameter to undefined. */} { setCurrentPage(page); refreshDocs(sortField, page, rowsPerPage); // Pass `true` to reset lastID if not using cursor }} onRowsPerPageChange={(rows) => { console.log('Pagination - Rows per Page Change:', rows); setRowsPerPage(rows); setCurrentPage(1); // Reset to page 1 on rows per page change refreshDocs(sortField, 1, rows); // Reset lastID for fresh pagination }} />
); }; Documents.propTypes = { //documents: PropTypes.array.isRequired, handleDeleteDocument: PropTypes.func.isRequired, }; export default Documents;