/* eslint-disable no-mixed-operators */ 'use client' import type { FC, SVGProps } from 'react' import React, { useCallback, useEffect, useState } from 'react' import { useBoolean, useDebounceFn } from 'ahooks' import { ArrowDownIcon, TrashIcon } from '@heroicons/react/24/outline' import { pick } from 'lodash-es' import { RiMoreFill, } from '@remixicon/react' import { useContext } from 'use-context-selector' import { useRouter } from 'next/navigation' import { useTranslation } from 'react-i18next' import dayjs from 'dayjs' import { Edit03 } from '../../base/icons/src/vender/solid/general' import { Globe01 } from '../../base/icons/src/vender/line/mapsAndTravel' import s from './style.module.css' import RenameModal from './rename-modal' import cn from '@/utils/classnames' import Switch from '@/app/components/base/switch' import Divider from '@/app/components/base/divider' import Popover from '@/app/components/base/popover' import Confirm from '@/app/components/base/confirm' import Tooltip from '@/app/components/base/tooltip' import { ToastContext } from '@/app/components/base/toast' import type { IndicatorProps } from '@/app/components/header/indicator' import Indicator from '@/app/components/header/indicator' import { asyncRunSafe } from '@/utils' import { formatNumber } from '@/utils/format' import { archiveDocument, deleteDocument, disableDocument, enableDocument, syncDocument, syncWebsite, unArchiveDocument } from '@/service/datasets' import NotionIcon from '@/app/components/base/notion-icon' import ProgressBar from '@/app/components/base/progress-bar' import { DataSourceType, type DocumentDisplayStatus, type SimpleDocumentDetail } from '@/models/datasets' import type { CommonResponse } from '@/models/common' import useTimestamp from '@/hooks/use-timestamp' export const SettingsIcon = ({ className }: SVGProps) => { return } export const SyncIcon = () => { return } export const FilePlusIcon = ({ className }: SVGProps) => { return } export const ArchiveIcon = ({ className }: SVGProps) => { return } export const useIndexStatus = () => { const { t } = useTranslation() return { queuing: { color: 'orange', text: t('datasetDocuments.list.status.queuing') }, // waiting indexing: { color: 'blue', text: t('datasetDocuments.list.status.indexing') }, // indexing splitting parsing cleaning paused: { color: 'orange', text: t('datasetDocuments.list.status.paused') }, // paused error: { color: 'red', text: t('datasetDocuments.list.status.error') }, // error available: { color: 'green', text: t('datasetDocuments.list.status.available') }, // completed,archived = false,enabled = true enabled: { color: 'green', text: t('datasetDocuments.list.status.enabled') }, // completed,archived = false,enabled = true disabled: { color: 'gray', text: t('datasetDocuments.list.status.disabled') }, // completed,archived = false,enabled = false archived: { color: 'gray', text: t('datasetDocuments.list.status.archived') }, // completed,archived = true } } // status item for list export const StatusItem: FC<{ status: DocumentDisplayStatus reverse?: boolean scene?: 'list' | 'detail' textCls?: string errorMessage?: string }> = ({ status, reverse = false, scene = 'list', textCls = '', errorMessage }) => { const DOC_INDEX_STATUS_MAP = useIndexStatus() const localStatus = status.toLowerCase() as keyof typeof DOC_INDEX_STATUS_MAP return
{DOC_INDEX_STATUS_MAP[localStatus]?.text} { errorMessage && ( {errorMessage}
} triggerClassName='ml-1 w-4 h-4' /> ) } } type OperationName = 'delete' | 'archive' | 'enable' | 'disable' | 'sync' | 'un_archive' // operation action for list and detail export const OperationAction: FC<{ embeddingAvailable: boolean detail: { name: string enabled: boolean archived: boolean id: string data_source_type: string doc_form: string } datasetId: string onUpdate: (operationName?: string) => void scene?: 'list' | 'detail' className?: string }> = ({ embeddingAvailable, datasetId, detail, onUpdate, scene = 'list', className = '' }) => { const { id, enabled = false, archived = false, data_source_type } = detail || {} const [showModal, setShowModal] = useState(false) const [deleting, setDeleting] = useState(false) const { notify } = useContext(ToastContext) const { t } = useTranslation() const router = useRouter() const isListScene = scene === 'list' const onOperate = async (operationName: OperationName) => { let opApi = deleteDocument switch (operationName) { case 'archive': opApi = archiveDocument break case 'un_archive': opApi = unArchiveDocument break case 'enable': opApi = enableDocument break case 'disable': opApi = disableDocument break case 'sync': if (data_source_type === 'notion_import') opApi = syncDocument else opApi = syncWebsite break default: opApi = deleteDocument setDeleting(true) break } const [e] = await asyncRunSafe(opApi({ datasetId, documentId: id }) as Promise) if (!e) notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') }) else notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') }) if (operationName === 'delete') setDeleting(false) onUpdate(operationName) } const { run: handleSwitch } = useDebounceFn((operationName: OperationName) => { if (operationName === 'enable' && enabled) return if (operationName === 'disable' && !enabled) return onOperate(operationName) }, { wait: 500 }) const [currDocument, setCurrDocument] = useState<{ id: string name: string } | null>(null) const [isShowRenameModal, { setTrue: setShowRenameModalTrue, setFalse: setShowRenameModalFalse, }] = useBoolean(false) const handleShowRenameModal = useCallback((doc: { id: string name: string }) => { setCurrDocument(doc) setShowRenameModalTrue() }, [setShowRenameModalTrue]) const handleRenamed = useCallback(() => { onUpdate() }, [onUpdate]) return
e.stopPropagation()}> {isListScene && !embeddingAvailable && ( { }} disabled={true} size='md' /> )} {isListScene && embeddingAvailable && ( <> {archived ?
{ }} disabled={true} size='md' />
: handleSwitch(v ? 'enable' : 'disable')} size='md' /> } )} {embeddingAvailable && ( {!isListScene && <>
{!archived && enabled ? t('datasetDocuments.list.index.enable') : t('datasetDocuments.list.index.disable')}
!archived && handleSwitch(v ? 'enable' : 'disable')} disabled={archived} size='md' />
{!archived && enabled ? t('datasetDocuments.list.index.enableTip') : t('datasetDocuments.list.index.disableTip')}
} {!archived && ( <>
{ handleShowRenameModal({ id: detail.id, name: detail.name, }) }}> {t('datasetDocuments.list.table.rename')}
router.push(`/datasets/${datasetId}/documents/${detail.id}/settings`)}> {t('datasetDocuments.list.action.settings')}
{['notion_import', DataSourceType.WEB].includes(data_source_type) && (
onOperate('sync')}> {t('datasetDocuments.list.action.sync')}
)} )} {!archived &&
onOperate('archive')}> {t('datasetDocuments.list.action.archive')}
} {archived && (
onOperate('un_archive')}> {t('datasetDocuments.list.action.unarchive')}
)}
setShowModal(true)}> {t('datasetDocuments.list.action.delete')}
} trigger='click' position='br' btnElement={
} btnClassName={open => cn(isListScene ? s.actionIconWrapperList : s.actionIconWrapperDetail, open ? '!bg-gray-100 !shadow-none' : '!bg-transparent')} className={`flex justify-end !w-[200px] h-fit !z-20 ${className}`} /> )} {showModal && onOperate('delete')} onCancel={() => setShowModal(false)} /> } {isShowRenameModal && currDocument && ( )} } export const renderTdValue = (value: string | number | null, isEmptyStyle = false) => { return (
{value ?? '-'}
) } const renderCount = (count: number | undefined) => { if (!count) return renderTdValue(0, true) if (count < 1000) return count return `${formatNumber((count / 1000).toFixed(1))}k` } type LocalDoc = SimpleDocumentDetail & { percent?: number } type IDocumentListProps = { embeddingAvailable: boolean documents: LocalDoc[] datasetId: string onUpdate: () => void } /** * Document list component including basic information */ const DocumentList: FC = ({ embeddingAvailable, documents = [], datasetId, onUpdate }) => { const { t } = useTranslation() const { formatTime } = useTimestamp() const router = useRouter() const [localDocs, setLocalDocs] = useState(documents) const [enableSort, setEnableSort] = useState(false) useEffect(() => { setLocalDocs(documents) }, [documents]) const onClickSort = () => { setEnableSort(!enableSort) if (!enableSort) { const sortedDocs = [...localDocs].sort((a, b) => dayjs(a.created_at).isBefore(dayjs(b.created_at)) ? -1 : 1) setLocalDocs(sortedDocs) } else { setLocalDocs(documents) } } const [currDocument, setCurrDocument] = useState(null) const [isShowRenameModal, { setTrue: setShowRenameModalTrue, setFalse: setShowRenameModalFalse, }] = useBoolean(false) const handleShowRenameModal = useCallback((doc: LocalDoc) => { setCurrDocument(doc) setShowRenameModalTrue() }, [setShowRenameModalTrue]) const handleRenamed = useCallback(() => { onUpdate() }, [onUpdate]) return (
{localDocs.map((doc) => { const isFile = doc.data_source_type === DataSourceType.FILE const fileType = isFile ? doc.data_source_detail_dict?.upload_file?.extension : '' return { router.push(`/datasets/${datasetId}/documents/${doc.id}`) }}> })}
#
{t('datasetDocuments.list.table.header.fileName')}
{t('datasetDocuments.list.table.header.words')} {t('datasetDocuments.list.table.header.hitCount')}
{t('datasetDocuments.list.table.header.uploadTime')}
{t('datasetDocuments.list.table.header.status')} {t('datasetDocuments.list.table.header.action')}
{doc.position}
{doc?.data_source_type === DataSourceType.NOTION && } {doc?.data_source_type === DataSourceType.FILE &&
} {doc?.data_source_type === DataSourceType.WEB && } { doc.name }
{ e.stopPropagation() handleShowRenameModal(doc) }} >
{renderCount(doc.word_count)} {renderCount(doc.hit_count)} {formatTime(doc.created_at, t('datasetHitTesting.dateTimeFormat') as string)} { (['indexing', 'splitting', 'parsing', 'cleaning'].includes(doc.indexing_status) && doc?.data_source_type === DataSourceType.NOTION) ? : }
{isShowRenameModal && currDocument && ( )}
) } export default DocumentList