import React, { useCallback, useEffect, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useDispatch, useSelector } from 'react-redux'; import userService from '../api/services/userService'; import ArrowLeft from '../assets/arrow-left.svg'; import caretSort from '../assets/caret-sort.svg'; import Edit from '../assets/edit.svg'; import EyeView from '../assets/eye-view.svg'; import NoFilesDarkIcon from '../assets/no-files-dark.svg'; import NoFilesIcon from '../assets/no-files.svg'; import SyncIcon from '../assets/sync.svg'; import Trash from '../assets/red-trash.svg'; import Pagination from '../components/DocumentPagination'; import DropdownMenu from '../components/DropdownMenu'; import Input from '../components/Input'; import SkeletonLoader from '../components/SkeletonLoader'; import Spinner from '../components/Spinner'; import { useDarkTheme, useLoaderState } from '../hooks'; import ChunkModal from '../modals/ChunkModal'; import ConfirmationModal from '../modals/ConfirmationModal'; import { ActiveState, Doc, DocumentsProps } from '../models/misc'; import { getDocs, getDocsWithPagination } from '../preferences/preferenceApi'; import { selectToken, setPaginatedDocuments, setSourceDocs, } from '../preferences/preferenceSlice'; import Upload from '../upload/Upload'; import { formatDate } from '../utils/dateTimeUtils'; import { ChunkType } from './types'; import ContextMenu, { MenuOption } from '../components/ContextMenu'; import ThreeDots from '../assets/three-dots.svg'; 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(); } }; export default function Documents({ paginatedDocuments, handleDeleteDocument, }: DocumentsProps) { const { t } = useTranslation(); const dispatch = useDispatch(); const token = useSelector(selectToken); const [searchTerm, setSearchTerm] = useState(''); const [modalState, setModalState] = useState('INACTIVE'); const [isOnboarding, setIsOnboarding] = useState(false); const [loading, setLoading] = useLoaderState(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 [activeMenuId, setActiveMenuId] = useState(null); const menuRefs = useRef<{ [key: string]: React.RefObject }>( {}, ); // Create or get a ref for each document wrapper div (not the td) const getMenuRef = (docId: string) => { if (!menuRefs.current[docId]) { menuRefs.current[docId] = React.createRef(); } return menuRefs.current[docId]; }; const handleMenuClick = (e: React.MouseEvent, docId: string) => { e.preventDefault(); e.stopPropagation(); const isAnyMenuOpen = (syncMenuState.isOpen && syncMenuState.docId === docId) || activeMenuId === docId; if (isAnyMenuOpen) { setSyncMenuState((prev) => ({ ...prev, isOpen: false, docId: null })); setActiveMenuId(null); return; } setActiveMenuId(docId); }; useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if (activeMenuId) { const activeRef = menuRefs.current[activeMenuId]; if ( activeRef?.current && !activeRef.current.contains(event.target as Node) ) { setActiveMenuId(null); } } }; document.addEventListener('mousedown', handleClickOutside); return () => document.removeEventListener('mousedown', handleClickOutside); }, [activeMenuId]); const currentDocuments = paginatedDocuments ?? []; const syncOptions = [ { label: t('settings.documents.syncFrequency.never'), value: 'never' }, { label: t('settings.documents.syncFrequency.daily'), value: 'daily' }, { label: t('settings.documents.syncFrequency.weekly'), value: 'weekly' }, { label: t('settings.documents.syncFrequency.monthly'), value: 'monthly' }, ]; const [showDocumentChunks, setShowDocumentChunks] = useState(); const [isMenuOpen, setIsMenuOpen] = useState(false); const [syncMenuState, setSyncMenuState] = useState<{ isOpen: boolean; docId: string | null; document: Doc | null; }>({ isOpen: false, docId: null, document: null, }); const refreshDocs = useCallback( ( field: 'date' | 'tokens' | undefined, pageNumber?: number, rows?: number, ) => { const page = pageNumber ?? currentPage; const rowsPerPg = rows ?? rowsPerPage; // If field is undefined, (Pagination or Search) use the current sortField const newSortField = field ?? sortField; // If field is undefined, (Pagination or Search) use the current sortOrder const newSortOrder = field === sortField ? sortOrder === 'asc' ? 'desc' : 'asc' : sortOrder; // If field is defined, update the sortField and sortOrder if (field) { setSortField(newSortField); setSortOrder(newSortOrder); } setLoading(true); getDocsWithPagination( newSortField, newSortOrder, page, rowsPerPg, searchTerm, token, ) .then((data) => { dispatch(setPaginatedDocuments(data ? data.docs : [])); setTotalPages(data ? data.totalPages : 0); }) .catch((error) => console.error(error)) .finally(() => { setLoading(false); }); }, [currentPage, rowsPerPage, sortField, sortOrder, searchTerm], ); const handleManageSync = (doc: Doc, sync_frequency: string) => { setLoading(true); userService .manageSync({ source_id: doc.id, sync_frequency }, token) .then(() => { return getDocs(token); }) .then((data) => { dispatch(setSourceDocs(data)); return getDocsWithPagination( sortField, sortOrder, currentPage, rowsPerPage, searchTerm, token, ); }) .then((paginatedData) => { dispatch( setPaginatedDocuments(paginatedData ? paginatedData.docs : []), ); setTotalPages(paginatedData ? paginatedData.totalPages : 0); }) .catch((error) => console.error('Error in handleManageSync:', error)) .finally(() => { setLoading(false); }); }; const [documentToDelete, setDocumentToDelete] = useState<{ index: number; document: Doc; } | null>(null); const [deleteModalState, setDeleteModalState] = useState('INACTIVE'); const handleDeleteConfirmation = (index: number, document: Doc) => { setDocumentToDelete({ index, document }); setDeleteModalState('ACTIVE'); }; const handleConfirmedDelete = () => { if (documentToDelete) { handleDeleteDocument(documentToDelete.index, documentToDelete.document); setDeleteModalState('INACTIVE'); setDocumentToDelete(null); } }; const getActionOptions = (index: number, document: Doc): MenuOption[] => { const actions: MenuOption[] = [ { icon: EyeView, label: t('settings.documents.view'), onClick: () => { setShowDocumentChunks(document); }, iconWidth: 18, iconHeight: 18, variant: 'primary', }, ]; if (document.syncFrequency) { actions.push({ icon: SyncIcon, label: t('settings.documents.sync'), onClick: () => { setSyncMenuState({ isOpen: true, docId: document.id ?? null, document: document, }); }, iconWidth: 14, iconHeight: 14, variant: 'primary', }); } actions.push({ icon: Trash, label: t('convTile.delete'), onClick: () => { handleDeleteConfirmation(index, document); }, iconWidth: 18, iconHeight: 18, variant: 'danger', }); return actions; }; useEffect(() => { refreshDocs(undefined, 1, rowsPerPage); }, [searchTerm]); return showDocumentChunks ? ( { setShowDocumentChunks(undefined); }} /> ) : (

{t('settings.documents.title')}

{ setSearchTerm(e.target.value); setCurrentPage(1); }} borderVariant="thin" />
{loading ? ( ) : !currentDocuments?.length ? ( ) : ( currentDocuments.map((document, index) => { const docId = document.id ? document.id.toString() : ''; return ( ); }) )}
{t('settings.documents.name')}
{t('settings.documents.date')} refreshDocs('date')} src={caretSort} alt="sort" />
{t('settings.documents.tokenUsage')} {t('settings.documents.tokenUsage')} refreshDocs('tokens')} src={caretSort} alt="sort" />
{t('settings.documents.actions')}
{t('settings.documents.noData')}
{document.name} {document.date ? formatDate(document.date) : ''} {document.tokens ? formatTokens(+document.tokens) : ''} e.stopPropagation()} >
{document.syncFrequency && ( { handleManageSync(document, value); }} defaultValue={document.syncFrequency} icon={SyncIcon} isOpen={ syncMenuState.docId === docId && syncMenuState.isOpen } onOpenChange={(isOpen) => { setSyncMenuState((prev) => ({ ...prev, isOpen, docId: isOpen ? docId : null, document: isOpen ? document : null, })); }} anchorRef={getMenuRef(docId)} position="bottom-left" offset={{ x: 24, y: -24 }} className="min-w-[120px]" /> )} { setActiveMenuId(isOpen ? docId : null); }} options={getActionOptions(index, document)} anchorRef={getMenuRef(docId)} position="bottom-left" offset={{ x: 48, y: -24 }} className="z-50" />
{ setCurrentPage(page); refreshDocs(undefined, page, rowsPerPage); }} onRowsPerPageChange={(rows) => { setRowsPerPage(rows); setCurrentPage(1); refreshDocs(undefined, 1, rows); }} />
{modalState === 'ACTIVE' && ( setModalState('INACTIVE')} onSuccessfulUpload={() => refreshDocs(undefined, currentPage, rowsPerPage) } /> )} {deleteModalState === 'ACTIVE' && documentToDelete && ( { setDeleteModalState('INACTIVE'); setDocumentToDelete(null); }} submitLabel={t('convTile.delete')} variant="danger" /> )}
); } function DocumentChunks({ document, handleGoBack, }: { document: Doc; handleGoBack: () => void; }) { const { t } = useTranslation(); const token = useSelector(selectToken); const [isDarkTheme] = useDarkTheme(); const [paginatedChunks, setPaginatedChunks] = useState([]); const [page, setPage] = useState(1); const [perPage, setPerPage] = useState(5); const [totalChunks, setTotalChunks] = useState(0); const [loading, setLoading] = useLoaderState(true); const [searchTerm, setSearchTerm] = useState(''); const [addModal, setAddModal] = useState('INACTIVE'); const [editModal, setEditModal] = useState<{ state: ActiveState; chunk: ChunkType | null; }>({ state: 'INACTIVE', chunk: null }); const fetchChunks = () => { setLoading(true); try { userService .getDocumentChunks(document.id ?? '', page, perPage, token) .then((response) => { if (!response.ok) { setLoading(false); setPaginatedChunks([]); throw new Error('Failed to fetch chunks data'); } return response.json(); }) .then((data) => { setPage(data.page); setPerPage(data.per_page); setTotalChunks(data.total); setPaginatedChunks(data.chunks); setLoading(false); }); } catch (e) { console.log(e); setLoading(false); } }; const handleAddChunk = (title: string, text: string) => { try { userService .addChunk( { id: document.id ?? '', text: text, metadata: { title: title, }, }, token, ) .then((response) => { if (!response.ok) { throw new Error('Failed to add chunk'); } fetchChunks(); }); } catch (e) { console.log(e); } }; const handleUpdateChunk = (title: string, text: string, chunk: ChunkType) => { try { userService .updateChunk( { id: document.id ?? '', chunk_id: chunk.doc_id, text: text, metadata: { title: title, }, }, token, ) .then((response) => { if (!response.ok) { throw new Error('Failed to update chunk'); } fetchChunks(); }); } catch (e) { console.log(e); } }; const handleDeleteChunk = (chunk: ChunkType) => { try { userService .deleteChunk(document.id ?? '', chunk.doc_id, token) .then((response) => { if (!response.ok) { throw new Error('Failed to delete chunk'); } setEditModal({ state: 'INACTIVE', chunk: null }); fetchChunks(); }); } catch (e) { console.log(e); } }; React.useEffect(() => { fetchChunks(); }, [page, perPage]); return (

Back to all documents

{`${totalChunks} Chunks`}

{ setSearchTerm(e.target.value); }} borderVariant="thin" />
{loading ? (
) : (
{paginatedChunks.filter((chunk) => { if (!chunk.metadata?.title) return true; return chunk.metadata.title .toLowerCase() .includes(searchTerm.toLowerCase()); }).length === 0 ? (
No tools found No chunks found
) : ( paginatedChunks .filter((chunk) => { if (!chunk.metadata?.title) return true; return chunk.metadata.title .toLowerCase() .includes(searchTerm.toLowerCase()); }) .map((chunk, index) => (

{chunk.metadata?.title ?? 'Untitled'}

{chunk.text}

)) )}
)} {!loading && paginatedChunks.filter((chunk) => { if (!chunk.metadata?.title) return true; return chunk.metadata.title .toLowerCase() .includes(searchTerm.toLowerCase()); }).length !== 0 && (
{ setPage(page); }} onRowsPerPageChange={(rows) => { setPerPage(rows); setPage(1); }} />
)} setEditModal((prev) => ({ ...prev, state }))} handleSubmit={(title, text) => { handleUpdateChunk(title, text, editModal.chunk as ChunkType); }} originalText={editModal.chunk?.text} originalTitle={editModal.chunk?.metadata?.title} handleDelete={() => { handleDeleteChunk(editModal.chunk as ChunkType); }} />
); }