list.tsx 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { useCallback, useEffect, useMemo, useState } from 'react'
  4. import { useBoolean, useDebounceFn } from 'ahooks'
  5. import { ArrowDownIcon } from '@heroicons/react/24/outline'
  6. import { pick, uniq } from 'lodash-es'
  7. import {
  8. RiArchive2Line,
  9. RiDeleteBinLine,
  10. RiEditLine,
  11. RiEqualizer2Line,
  12. RiLoopLeftLine,
  13. RiMoreFill,
  14. } from '@remixicon/react'
  15. import { useContext } from 'use-context-selector'
  16. import { useRouter } from 'next/navigation'
  17. import { useTranslation } from 'react-i18next'
  18. import dayjs from 'dayjs'
  19. import { Edit03 } from '../../base/icons/src/vender/solid/general'
  20. import { Globe01 } from '../../base/icons/src/vender/line/mapsAndTravel'
  21. import ChunkingModeLabel from '../common/chunking-mode-label'
  22. import FileTypeIcon from '../../base/file-uploader/file-type-icon'
  23. import s from './style.module.css'
  24. import RenameModal from './rename-modal'
  25. import BatchAction from './detail/completed/common/batch-action'
  26. import cn from '@/utils/classnames'
  27. import Switch from '@/app/components/base/switch'
  28. import Divider from '@/app/components/base/divider'
  29. import Popover from '@/app/components/base/popover'
  30. import Confirm from '@/app/components/base/confirm'
  31. import Tooltip from '@/app/components/base/tooltip'
  32. import Toast, { ToastContext } from '@/app/components/base/toast'
  33. import type { ColorMap, IndicatorProps } from '@/app/components/header/indicator'
  34. import Indicator from '@/app/components/header/indicator'
  35. import { asyncRunSafe } from '@/utils'
  36. import { formatNumber } from '@/utils/format'
  37. import NotionIcon from '@/app/components/base/notion-icon'
  38. import ProgressBar from '@/app/components/base/progress-bar'
  39. import { ChunkingMode, DataSourceType, DocumentActionType, type DocumentDisplayStatus, type SimpleDocumentDetail } from '@/models/datasets'
  40. import type { CommonResponse } from '@/models/common'
  41. import useTimestamp from '@/hooks/use-timestamp'
  42. import { useDatasetDetailContextWithSelector as useDatasetDetailContext } from '@/context/dataset-detail'
  43. import type { Props as PaginationProps } from '@/app/components/base/pagination'
  44. import Pagination from '@/app/components/base/pagination'
  45. import Checkbox from '@/app/components/base/checkbox'
  46. import { useDocumentArchive, useDocumentDelete, useDocumentDisable, useDocumentEnable, useDocumentUnArchive, useSyncDocument, useSyncWebsite } from '@/service/knowledge/use-document'
  47. import { extensionToFileType } from '@/app/components/datasets/hit-testing/utils/extension-to-file-type'
  48. export const useIndexStatus = () => {
  49. const { t } = useTranslation()
  50. return {
  51. queuing: { color: 'orange', text: t('datasetDocuments.list.status.queuing') }, // waiting
  52. indexing: { color: 'blue', text: t('datasetDocuments.list.status.indexing') }, // indexing splitting parsing cleaning
  53. paused: { color: 'orange', text: t('datasetDocuments.list.status.paused') }, // paused
  54. error: { color: 'red', text: t('datasetDocuments.list.status.error') }, // error
  55. available: { color: 'green', text: t('datasetDocuments.list.status.available') }, // completed,archived = false,enabled = true
  56. enabled: { color: 'green', text: t('datasetDocuments.list.status.enabled') }, // completed,archived = false,enabled = true
  57. disabled: { color: 'gray', text: t('datasetDocuments.list.status.disabled') }, // completed,archived = false,enabled = false
  58. archived: { color: 'gray', text: t('datasetDocuments.list.status.archived') }, // completed,archived = true
  59. }
  60. }
  61. const STATUS_TEXT_COLOR_MAP: ColorMap = {
  62. green: 'text-util-colors-green-green-600',
  63. orange: 'text-util-colors-warning-warning-600',
  64. red: 'text-util-colors-red-red-600',
  65. blue: 'text-util-colors-blue-light-blue-light-600',
  66. yellow: 'text-util-colors-warning-warning-600',
  67. gray: 'text-text-tertiary',
  68. }
  69. // status item for list
  70. export const StatusItem: FC<{
  71. status: DocumentDisplayStatus
  72. reverse?: boolean
  73. scene?: 'list' | 'detail'
  74. textCls?: string
  75. errorMessage?: string
  76. detail?: {
  77. enabled: boolean
  78. archived: boolean
  79. id: string
  80. }
  81. datasetId?: string
  82. onUpdate?: (operationName?: string) => void
  83. }> = ({ status, reverse = false, scene = 'list', textCls = '', errorMessage, datasetId = '', detail, onUpdate }) => {
  84. const DOC_INDEX_STATUS_MAP = useIndexStatus()
  85. const localStatus = status.toLowerCase() as keyof typeof DOC_INDEX_STATUS_MAP
  86. const { enabled = false, archived = false, id = '' } = detail || {}
  87. const { notify } = useContext(ToastContext)
  88. const { t } = useTranslation()
  89. const { mutateAsync: enableDocument } = useDocumentEnable()
  90. const { mutateAsync: disableDocument } = useDocumentDisable()
  91. const { mutateAsync: deleteDocument } = useDocumentDelete()
  92. const onOperate = async (operationName: OperationName) => {
  93. let opApi = deleteDocument
  94. switch (operationName) {
  95. case 'enable':
  96. opApi = enableDocument
  97. break
  98. case 'disable':
  99. opApi = disableDocument
  100. break
  101. }
  102. const [e] = await asyncRunSafe<CommonResponse>(opApi({ datasetId, documentId: id }) as Promise<CommonResponse>)
  103. if (!e) {
  104. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  105. onUpdate?.(operationName)
  106. }
  107. else { notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') }) }
  108. }
  109. const { run: handleSwitch } = useDebounceFn((operationName: OperationName) => {
  110. if (operationName === 'enable' && enabled)
  111. return
  112. if (operationName === 'disable' && !enabled)
  113. return
  114. onOperate(operationName)
  115. }, { wait: 500 })
  116. const embedding = useMemo(() => {
  117. return ['queuing', 'indexing', 'paused'].includes(localStatus)
  118. }, [localStatus])
  119. return <div className={
  120. cn('flex items-center',
  121. reverse ? 'flex-row-reverse' : '',
  122. scene === 'detail' ? s.statusItemDetail : '')
  123. }>
  124. <Indicator color={DOC_INDEX_STATUS_MAP[localStatus]?.color as IndicatorProps['color']} className={reverse ? 'ml-2' : 'mr-2'} />
  125. <span className={cn(`${STATUS_TEXT_COLOR_MAP[DOC_INDEX_STATUS_MAP[localStatus].color as keyof typeof STATUS_TEXT_COLOR_MAP]} text-sm`, textCls)}>
  126. {DOC_INDEX_STATUS_MAP[localStatus]?.text}
  127. </span>
  128. {
  129. errorMessage && (
  130. <Tooltip
  131. popupContent={
  132. <div className='max-w-[260px] break-all'>{errorMessage}</div>
  133. }
  134. triggerClassName='ml-1 w-4 h-4'
  135. />
  136. )
  137. }
  138. {
  139. scene === 'detail' && (
  140. <div className='flex justify-between items-center ml-1.5'>
  141. <Tooltip
  142. popupContent={t('datasetDocuments.list.action.enableWarning')}
  143. popupClassName='text-text-secondary system-xs-medium'
  144. needsDelay
  145. disabled={!archived}
  146. >
  147. <Switch
  148. defaultValue={archived ? false : enabled}
  149. onChange={v => !archived && handleSwitch(v ? 'enable' : 'disable')}
  150. disabled={embedding || archived}
  151. size='md'
  152. />
  153. </Tooltip>
  154. </div>
  155. )
  156. }
  157. </div>
  158. }
  159. type OperationName = 'delete' | 'archive' | 'enable' | 'disable' | 'sync' | 'un_archive'
  160. // operation action for list and detail
  161. export const OperationAction: FC<{
  162. embeddingAvailable: boolean
  163. detail: {
  164. name: string
  165. enabled: boolean
  166. archived: boolean
  167. id: string
  168. data_source_type: string
  169. doc_form: string
  170. }
  171. datasetId: string
  172. onUpdate: (operationName?: string) => void
  173. scene?: 'list' | 'detail'
  174. className?: string
  175. }> = ({ embeddingAvailable, datasetId, detail, onUpdate, scene = 'list', className = '' }) => {
  176. const { id, enabled = false, archived = false, data_source_type } = detail || {}
  177. const [showModal, setShowModal] = useState(false)
  178. const [deleting, setDeleting] = useState(false)
  179. const { notify } = useContext(ToastContext)
  180. const { t } = useTranslation()
  181. const router = useRouter()
  182. const { mutateAsync: archiveDocument } = useDocumentArchive()
  183. const { mutateAsync: unArchiveDocument } = useDocumentUnArchive()
  184. const { mutateAsync: enableDocument } = useDocumentEnable()
  185. const { mutateAsync: disableDocument } = useDocumentDisable()
  186. const { mutateAsync: deleteDocument } = useDocumentDelete()
  187. const { mutateAsync: syncDocument } = useSyncDocument()
  188. const { mutateAsync: syncWebsite } = useSyncWebsite()
  189. const isListScene = scene === 'list'
  190. const onOperate = async (operationName: OperationName) => {
  191. let opApi = deleteDocument
  192. switch (operationName) {
  193. case 'archive':
  194. opApi = archiveDocument
  195. break
  196. case 'un_archive':
  197. opApi = unArchiveDocument
  198. break
  199. case 'enable':
  200. opApi = enableDocument
  201. break
  202. case 'disable':
  203. opApi = disableDocument
  204. break
  205. case 'sync':
  206. if (data_source_type === 'notion_import')
  207. opApi = syncDocument
  208. else
  209. opApi = syncWebsite
  210. break
  211. default:
  212. opApi = deleteDocument
  213. setDeleting(true)
  214. break
  215. }
  216. const [e] = await asyncRunSafe<CommonResponse>(opApi({ datasetId, documentId: id }) as Promise<CommonResponse>)
  217. if (!e) {
  218. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  219. onUpdate(operationName)
  220. }
  221. else { notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') }) }
  222. if (operationName === 'delete')
  223. setDeleting(false)
  224. }
  225. const { run: handleSwitch } = useDebounceFn((operationName: OperationName) => {
  226. if (operationName === 'enable' && enabled)
  227. return
  228. if (operationName === 'disable' && !enabled)
  229. return
  230. onOperate(operationName)
  231. }, { wait: 500 })
  232. const [currDocument, setCurrDocument] = useState<{
  233. id: string
  234. name: string
  235. } | null>(null)
  236. const [isShowRenameModal, {
  237. setTrue: setShowRenameModalTrue,
  238. setFalse: setShowRenameModalFalse,
  239. }] = useBoolean(false)
  240. const handleShowRenameModal = useCallback((doc: {
  241. id: string
  242. name: string
  243. }) => {
  244. setCurrDocument(doc)
  245. setShowRenameModalTrue()
  246. }, [setShowRenameModalTrue])
  247. const handleRenamed = useCallback(() => {
  248. onUpdate()
  249. }, [onUpdate])
  250. return <div className='flex items-center' onClick={e => e.stopPropagation()}>
  251. {isListScene && !embeddingAvailable && (
  252. <Switch defaultValue={false} onChange={() => { }} disabled={true} size='md' />
  253. )}
  254. {isListScene && embeddingAvailable && (
  255. <>
  256. {archived
  257. ? <Tooltip
  258. popupContent={t('datasetDocuments.list.action.enableWarning')}
  259. popupClassName='!font-semibold'
  260. needsDelay
  261. >
  262. <div>
  263. <Switch defaultValue={false} onChange={() => { }} disabled={true} size='md' />
  264. </div>
  265. </Tooltip>
  266. : <Switch defaultValue={enabled} onChange={v => handleSwitch(v ? 'enable' : 'disable')} size='md' />
  267. }
  268. <Divider className='!ml-4 !mr-2 !h-3' type='vertical' />
  269. </>
  270. )}
  271. {embeddingAvailable && (
  272. <>
  273. <Tooltip
  274. popupContent={t('datasetDocuments.list.action.settings')}
  275. popupClassName='text-text-secondary system-xs-medium'
  276. >
  277. <button
  278. className={cn('rounded-lg mr-2 cursor-pointer',
  279. !isListScene
  280. ? 'p-2 bg-components-button-secondary-bg hover:bg-components-button-secondary-bg-hover border-[0.5px] border-components-button-secondary-border hover:border-components-button-secondary-border-hover shadow-xs shadow-shadow-shadow-3 backdrop-blur-[5px]'
  281. : 'p-0.5 hover:bg-state-base-hover')}
  282. onClick={() => router.push(`/datasets/${datasetId}/documents/${detail.id}/settings`)}>
  283. <RiEqualizer2Line className='w-4 h-4 text-components-button-secondary-text' />
  284. </button>
  285. </Tooltip>
  286. <Popover
  287. htmlContent={
  288. <div className='w-full py-1'>
  289. {!archived && (
  290. <>
  291. <div className={s.actionItem} onClick={() => {
  292. handleShowRenameModal({
  293. id: detail.id,
  294. name: detail.name,
  295. })
  296. }}>
  297. <RiEditLine className='w-4 h-4 text-text-tertiary' />
  298. <span className={s.actionName}>{t('datasetDocuments.list.table.rename')}</span>
  299. </div>
  300. {['notion_import', DataSourceType.WEB].includes(data_source_type) && (
  301. <div className={s.actionItem} onClick={() => onOperate('sync')}>
  302. <RiLoopLeftLine className='w-4 h-4 text-text-tertiary' />
  303. <span className={s.actionName}>{t('datasetDocuments.list.action.sync')}</span>
  304. </div>
  305. )}
  306. <Divider className='my-1' />
  307. </>
  308. )}
  309. {!archived && <div className={s.actionItem} onClick={() => onOperate('archive')}>
  310. <RiArchive2Line className='w-4 h-4 text-text-tertiary' />
  311. <span className={s.actionName}>{t('datasetDocuments.list.action.archive')}</span>
  312. </div>}
  313. {archived && (
  314. <div className={s.actionItem} onClick={() => onOperate('un_archive')}>
  315. <RiArchive2Line className='w-4 h-4 text-text-tertiary' />
  316. <span className={s.actionName}>{t('datasetDocuments.list.action.unarchive')}</span>
  317. </div>
  318. )}
  319. <div className={cn(s.actionItem, s.deleteActionItem, 'group')} onClick={() => setShowModal(true)}>
  320. <RiDeleteBinLine className={'w-4 h-4 text-text-tertiary group-hover:text-text-destructive'} />
  321. <span className={cn(s.actionName, 'group-hover:text-text-destructive')}>{t('datasetDocuments.list.action.delete')}</span>
  322. </div>
  323. </div>
  324. }
  325. trigger='click'
  326. position='br'
  327. btnElement={
  328. <div className={cn(s.commonIcon)}>
  329. <RiMoreFill className='w-4 h-4 text-text-components-button-secondary-text' />
  330. </div>
  331. }
  332. btnClassName={open => cn(isListScene ? s.actionIconWrapperList : s.actionIconWrapperDetail, open ? '!hover:bg-state-base-hover !shadow-none' : '!bg-transparent')}
  333. popupClassName='!w-full'
  334. className={`flex justify-end !w-[200px] h-fit !z-20 ${className}`}
  335. />
  336. </>
  337. )}
  338. {showModal
  339. && <Confirm
  340. isShow={showModal}
  341. isLoading={deleting}
  342. isDisabled={deleting}
  343. title={t('datasetDocuments.list.delete.title')}
  344. content={t('datasetDocuments.list.delete.content')}
  345. confirmText={t('common.operation.sure')}
  346. onConfirm={() => onOperate('delete')}
  347. onCancel={() => setShowModal(false)}
  348. />
  349. }
  350. {isShowRenameModal && currDocument && (
  351. <RenameModal
  352. datasetId={datasetId}
  353. documentId={currDocument.id}
  354. name={currDocument.name}
  355. onClose={setShowRenameModalFalse}
  356. onSaved={handleRenamed}
  357. />
  358. )}
  359. </div>
  360. }
  361. export const renderTdValue = (value: string | number | null, isEmptyStyle = false) => {
  362. return (
  363. <div className={cn(isEmptyStyle ? 'text-text-tertiary' : 'text-text-secondary', s.tdValue)}>
  364. {value ?? '-'}
  365. </div>
  366. )
  367. }
  368. const renderCount = (count: number | undefined) => {
  369. if (!count)
  370. return renderTdValue(0, true)
  371. if (count < 1000)
  372. return count
  373. return `${formatNumber((count / 1000).toFixed(1))}k`
  374. }
  375. type LocalDoc = SimpleDocumentDetail & { percent?: number }
  376. type IDocumentListProps = {
  377. embeddingAvailable: boolean
  378. documents: LocalDoc[]
  379. selectedIds: string[]
  380. onSelectedIdChange: (selectedIds: string[]) => void
  381. datasetId: string
  382. pagination: PaginationProps
  383. onUpdate: () => void
  384. }
  385. /**
  386. * Document list component including basic information
  387. */
  388. const DocumentList: FC<IDocumentListProps> = ({
  389. embeddingAvailable,
  390. documents = [],
  391. selectedIds,
  392. onSelectedIdChange,
  393. datasetId,
  394. pagination,
  395. onUpdate,
  396. }) => {
  397. const { t } = useTranslation()
  398. const { formatTime } = useTimestamp()
  399. const router = useRouter()
  400. const [datasetConfig] = useDatasetDetailContext(s => [s.dataset])
  401. const chunkingMode = datasetConfig?.doc_form
  402. const isGeneralMode = chunkingMode !== ChunkingMode.parentChild
  403. const isQAMode = chunkingMode === ChunkingMode.qa
  404. const [localDocs, setLocalDocs] = useState<LocalDoc[]>(documents)
  405. const [enableSort, setEnableSort] = useState(true)
  406. useEffect(() => {
  407. setLocalDocs(documents)
  408. }, [documents])
  409. const onClickSort = () => {
  410. setEnableSort(!enableSort)
  411. if (enableSort) {
  412. const sortedDocs = [...localDocs].sort((a, b) => dayjs(a.created_at).isBefore(dayjs(b.created_at)) ? -1 : 1)
  413. setLocalDocs(sortedDocs)
  414. }
  415. else {
  416. setLocalDocs(documents)
  417. }
  418. }
  419. const [currDocument, setCurrDocument] = useState<LocalDoc | null>(null)
  420. const [isShowRenameModal, {
  421. setTrue: setShowRenameModalTrue,
  422. setFalse: setShowRenameModalFalse,
  423. }] = useBoolean(false)
  424. const handleShowRenameModal = useCallback((doc: LocalDoc) => {
  425. setCurrDocument(doc)
  426. setShowRenameModalTrue()
  427. }, [setShowRenameModalTrue])
  428. const handleRenamed = useCallback(() => {
  429. onUpdate()
  430. }, [onUpdate])
  431. const isAllSelected = useMemo(() => {
  432. return localDocs.length > 0 && localDocs.every(doc => selectedIds.includes(doc.id))
  433. }, [localDocs, selectedIds])
  434. const isSomeSelected = useMemo(() => {
  435. return localDocs.some(doc => selectedIds.includes(doc.id))
  436. }, [localDocs, selectedIds])
  437. const onSelectedAll = useCallback(() => {
  438. if (isAllSelected)
  439. onSelectedIdChange([])
  440. else
  441. onSelectedIdChange(uniq([...selectedIds, ...localDocs.map(doc => doc.id)]))
  442. }, [isAllSelected, localDocs, onSelectedIdChange, selectedIds])
  443. const { mutateAsync: archiveDocument } = useDocumentArchive()
  444. const { mutateAsync: enableDocument } = useDocumentEnable()
  445. const { mutateAsync: disableDocument } = useDocumentDisable()
  446. const { mutateAsync: deleteDocument } = useDocumentDelete()
  447. const handleAction = (actionName: DocumentActionType) => {
  448. return async () => {
  449. let opApi = deleteDocument
  450. switch (actionName) {
  451. case DocumentActionType.archive:
  452. opApi = archiveDocument
  453. break
  454. case DocumentActionType.enable:
  455. opApi = enableDocument
  456. break
  457. case DocumentActionType.disable:
  458. opApi = disableDocument
  459. break
  460. default:
  461. opApi = deleteDocument
  462. break
  463. }
  464. const [e] = await asyncRunSafe<CommonResponse>(opApi({ datasetId, documentIds: selectedIds }) as Promise<CommonResponse>)
  465. if (!e) {
  466. Toast.notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  467. onUpdate()
  468. }
  469. else { Toast.notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') }) }
  470. }
  471. }
  472. return (
  473. <div className='flex flex-col relative w-full h-full'>
  474. <div className='grow overflow-x-auto'>
  475. <table className={`min-w-[700px] max-w-full w-full border-collapse border-0 text-sm mt-3 ${s.documentTable}`}>
  476. <thead className="h-8 leading-8 border-b border-divider-subtle text-text-tertiary font-medium text-xs uppercase">
  477. <tr>
  478. <td className='w-12'>
  479. <div className='flex items-center' onClick={e => e.stopPropagation()}>
  480. <Checkbox
  481. className='shrink-0 mr-2'
  482. checked={isAllSelected}
  483. mixed={!isAllSelected && isSomeSelected}
  484. onCheck={onSelectedAll}
  485. />
  486. #
  487. </div>
  488. </td>
  489. <td>
  490. <div className='flex'>
  491. {t('datasetDocuments.list.table.header.fileName')}
  492. </div>
  493. </td>
  494. <td className='w-[130px]'>{t('datasetDocuments.list.table.header.chunkingMode')}</td>
  495. <td className='w-24'>{t('datasetDocuments.list.table.header.words')}</td>
  496. <td className='w-44'>{t('datasetDocuments.list.table.header.hitCount')}</td>
  497. <td className='w-44'>
  498. <div className='flex items-center' onClick={onClickSort}>
  499. {t('datasetDocuments.list.table.header.uploadTime')}
  500. <ArrowDownIcon className={cn('ml-0.5 h-3 w-3 stroke-current stroke-2 cursor-pointer', enableSort ? 'text-text-tertiary' : 'text-text-disabled')} />
  501. </div>
  502. </td>
  503. <td className='w-40'>{t('datasetDocuments.list.table.header.status')}</td>
  504. <td className='w-20'>{t('datasetDocuments.list.table.header.action')}</td>
  505. </tr>
  506. </thead>
  507. <tbody className="text-text-secondary">
  508. {localDocs.map((doc, index) => {
  509. const isFile = doc.data_source_type === DataSourceType.FILE
  510. const fileType = isFile ? doc.data_source_detail_dict?.upload_file?.extension : ''
  511. return <tr
  512. key={doc.id}
  513. className={'border-b border-divider-subtle h-8 hover:bg-background-default-hover cursor-pointer'}
  514. onClick={() => {
  515. router.push(`/datasets/${datasetId}/documents/${doc.id}`)
  516. }}>
  517. <td className='text-left align-middle text-text-tertiary text-xs'>
  518. <div className='flex items-center' onClick={e => e.stopPropagation()}>
  519. <Checkbox
  520. className='shrink-0 mr-2'
  521. checked={selectedIds.includes(doc.id)}
  522. onCheck={() => {
  523. onSelectedIdChange(
  524. selectedIds.includes(doc.id)
  525. ? selectedIds.filter(id => id !== doc.id)
  526. : [...selectedIds, doc.id],
  527. )
  528. }}
  529. />
  530. {/* {doc.position} */}
  531. {index + 1}
  532. </div>
  533. </td>
  534. <td>
  535. <div className={'group flex items-center mr-6 hover:mr-0 max-w-[460px]'}>
  536. <div className='shrink-0'>
  537. {doc?.data_source_type === DataSourceType.NOTION && <NotionIcon className='inline-flex mt-[-3px] mr-1.5 align-middle' type='page' src={doc.data_source_info.notion_page_icon} />}
  538. {doc?.data_source_type === DataSourceType.FILE && <FileTypeIcon type={extensionToFileType(doc?.data_source_info?.upload_file?.extension ?? fileType)} className='mr-1.5' />}
  539. {doc?.data_source_type === DataSourceType.WEB && <Globe01 className='inline-flex mt-[-3px] mr-1.5 align-middle' />}
  540. </div>
  541. <span className='text-sm truncate grow-1'>{doc.name}</span>
  542. <div className='group-hover:flex group-hover:ml-auto hidden shrink-0'>
  543. <Tooltip
  544. popupContent={t('datasetDocuments.list.table.rename')}
  545. >
  546. <div
  547. className='p-1 rounded-md cursor-pointer hover:bg-state-base-hover'
  548. onClick={(e) => {
  549. e.stopPropagation()
  550. handleShowRenameModal(doc)
  551. }}
  552. >
  553. <Edit03 className='w-4 h-4 text-text-tertiary' />
  554. </div>
  555. </Tooltip>
  556. </div>
  557. </div>
  558. </td>
  559. <td>
  560. <ChunkingModeLabel
  561. isGeneralMode={isGeneralMode}
  562. isQAMode={isQAMode}
  563. />
  564. </td>
  565. <td>{renderCount(doc.word_count)}</td>
  566. <td>{renderCount(doc.hit_count)}</td>
  567. <td className='text-text-secondary text-[13px]'>
  568. {formatTime(doc.created_at, t('datasetHitTesting.dateTimeFormat') as string)}
  569. </td>
  570. <td>
  571. {
  572. (['indexing', 'splitting', 'parsing', 'cleaning'].includes(doc.indexing_status) && doc?.data_source_type === DataSourceType.NOTION)
  573. ? <ProgressBar percent={doc.percent || 0} />
  574. : <StatusItem status={doc.display_status} />
  575. }
  576. </td>
  577. <td>
  578. <OperationAction
  579. embeddingAvailable={embeddingAvailable}
  580. datasetId={datasetId}
  581. detail={pick(doc, ['name', 'enabled', 'archived', 'id', 'data_source_type', 'doc_form'])}
  582. onUpdate={onUpdate}
  583. />
  584. </td>
  585. </tr>
  586. })}
  587. </tbody>
  588. </table>
  589. </div>
  590. {(selectedIds.length > 0) && (
  591. <BatchAction
  592. className='absolute left-0 bottom-16 z-20'
  593. selectedIds={selectedIds}
  594. onArchive={handleAction(DocumentActionType.archive)}
  595. onBatchEnable={handleAction(DocumentActionType.enable)}
  596. onBatchDisable={handleAction(DocumentActionType.disable)}
  597. onBatchDelete={handleAction(DocumentActionType.delete)}
  598. onCancel={() => {
  599. onSelectedIdChange([])
  600. }}
  601. />
  602. )}
  603. {/* Show Pagination only if the total is more than the limit */}
  604. {pagination.total && (
  605. <Pagination
  606. {...pagination}
  607. className='shrink-0 w-full px-0 pb-0'
  608. />
  609. )}
  610. {isShowRenameModal && currDocument && (
  611. <RenameModal
  612. datasetId={datasetId}
  613. documentId={currDocument.id}
  614. name={currDocument.name}
  615. onClose={setShowRenameModalFalse}
  616. onSaved={handleRenamed}
  617. />
  618. )}
  619. </div>
  620. )
  621. }
  622. export default DocumentList