list.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. /* eslint-disable no-mixed-operators */
  2. 'use client'
  3. import type { FC, SVGProps } from 'react'
  4. import React, { useEffect, useState } from 'react'
  5. import { ArrowDownIcon, TrashIcon } from '@heroicons/react/24/outline'
  6. import { ExclamationCircleIcon } from '@heroicons/react/24/solid'
  7. import dayjs from 'dayjs'
  8. import { pick } from 'lodash-es'
  9. import { useContext } from 'use-context-selector'
  10. import { useRouter } from 'next/navigation'
  11. import { useTranslation } from 'react-i18next'
  12. import cn from 'classnames'
  13. import s from './style.module.css'
  14. import Switch from '@/app/components/base/switch'
  15. import Divider from '@/app/components/base/divider'
  16. import Popover from '@/app/components/base/popover'
  17. import Modal from '@/app/components/base/modal'
  18. import Button from '@/app/components/base/button'
  19. import Tooltip from '@/app/components/base/tooltip'
  20. import { ToastContext } from '@/app/components/base/toast'
  21. import type { IndicatorProps } from '@/app/components/header/indicator'
  22. import Indicator from '@/app/components/header/indicator'
  23. import { asyncRunSafe } from '@/utils'
  24. import { formatNumber } from '@/utils/format'
  25. import { archiveDocument, deleteDocument, disableDocument, enableDocument, syncDocument, unArchiveDocument } from '@/service/datasets'
  26. import NotionIcon from '@/app/components/base/notion-icon'
  27. import ProgressBar from '@/app/components/base/progress-bar'
  28. import { DataSourceType, type DocumentDisplayStatus, type SimpleDocumentDetail } from '@/models/datasets'
  29. import type { CommonResponse } from '@/models/common'
  30. import { DotsHorizontal, HelpCircle } from '@/app/components/base/icons/src/vender/line/general'
  31. export const SettingsIcon = ({ className }: SVGProps<SVGElement>) => {
  32. return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" className={className ?? ''}>
  33. <path d="M2 5.33325L10 5.33325M10 5.33325C10 6.43782 10.8954 7.33325 12 7.33325C13.1046 7.33325 14 6.43782 14 5.33325C14 4.22868 13.1046 3.33325 12 3.33325C10.8954 3.33325 10 4.22868 10 5.33325ZM6 10.6666L14 10.6666M6 10.6666C6 11.7712 5.10457 12.6666 4 12.6666C2.89543 12.6666 2 11.7712 2 10.6666C2 9.56202 2.89543 8.66659 4 8.66659C5.10457 8.66659 6 9.56202 6 10.6666Z" stroke="#667085" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
  34. </svg>
  35. }
  36. export const SyncIcon = () => {
  37. return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
  38. <path d="M5.69773 13.1783C7.29715 13.8879 9.20212 13.8494 10.8334 12.9075C13.5438 11.3427 14.4724 7.87704 12.9076 5.16672L12.7409 4.87804M3.09233 10.8335C1.52752 8.12314 2.45615 4.65746 5.16647 3.09265C6.7978 2.15081 8.70277 2.11227 10.3022 2.82185M1.66226 10.8892L3.48363 11.3773L3.97166 9.5559M12.0284 6.44393L12.5164 4.62256L14.3378 5.1106" stroke="#667085" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
  39. </svg>
  40. }
  41. export const FilePlusIcon = ({ className }: SVGProps<SVGElement>) => {
  42. return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" className={className ?? ''}>
  43. <path d="M13.3332 6.99992V4.53325C13.3332 3.41315 13.3332 2.85309 13.1152 2.42527C12.9234 2.04895 12.6175 1.74299 12.2412 1.55124C11.8133 1.33325 11.2533 1.33325 10.1332 1.33325H5.8665C4.7464 1.33325 4.18635 1.33325 3.75852 1.55124C3.3822 1.74299 3.07624 2.04895 2.88449 2.42527C2.6665 2.85309 2.6665 3.41315 2.6665 4.53325V11.4666C2.6665 12.5867 2.6665 13.1467 2.88449 13.5746C3.07624 13.9509 3.3822 14.2569 3.75852 14.4486C4.18635 14.6666 4.7464 14.6666 5.8665 14.6666H7.99984M9.33317 7.33325H5.33317M6.6665 9.99992H5.33317M10.6665 4.66659H5.33317M11.9998 13.9999V9.99992M9.99984 11.9999H13.9998" stroke="#667085" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
  44. </svg>
  45. }
  46. export const ArchiveIcon = ({ className }: SVGProps<SVGElement>) => {
  47. return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" className={className ?? ''}>
  48. <path d="M2.66683 5.33106C2.55749 5.32824 2.47809 5.32191 2.40671 5.30771C1.87779 5.2025 1.46432 4.78904 1.35912 4.26012C1.3335 4.13132 1.3335 3.97644 1.3335 3.66667C1.3335 3.3569 1.3335 3.20201 1.35912 3.07321C1.46432 2.54429 1.87779 2.13083 2.40671 2.02562C2.53551 2 2.69039 2 3.00016 2H13.0002C13.3099 2 13.4648 2 13.5936 2.02562C14.1225 2.13083 14.536 2.54429 14.6412 3.07321C14.6668 3.20201 14.6668 3.3569 14.6668 3.66667C14.6668 3.97644 14.6668 4.13132 14.6412 4.26012C14.536 4.78904 14.1225 5.2025 13.5936 5.30771C13.5222 5.32191 13.4428 5.32824 13.3335 5.33106M6.66683 8.66667H9.3335M2.66683 5.33333H13.3335V10.8C13.3335 11.9201 13.3335 12.4802 13.1155 12.908C12.9238 13.2843 12.6178 13.5903 12.2415 13.782C11.8137 14 11.2536 14 10.1335 14H5.86683C4.74672 14 4.18667 14 3.75885 13.782C3.38252 13.5903 3.07656 13.2843 2.88482 12.908C2.66683 12.4802 2.66683 11.9201 2.66683 10.8V5.33333Z" stroke="#667085" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
  49. </svg>
  50. }
  51. export const useIndexStatus = () => {
  52. const { t } = useTranslation()
  53. return {
  54. queuing: { color: 'orange', text: t('datasetDocuments.list.status.queuing') }, // waiting
  55. indexing: { color: 'blue', text: t('datasetDocuments.list.status.indexing') }, // indexing splitting parsing cleaning
  56. paused: { color: 'orange', text: t('datasetDocuments.list.status.paused') }, // paused
  57. error: { color: 'red', text: t('datasetDocuments.list.status.error') }, // error
  58. available: { color: 'green', text: t('datasetDocuments.list.status.available') }, // completed,archived = false,enabled = true
  59. enabled: { color: 'green', text: t('datasetDocuments.list.status.enabled') }, // completed,archived = false,enabled = true
  60. disabled: { color: 'gray', text: t('datasetDocuments.list.status.disabled') }, // completed,archived = false,enabled = false
  61. archived: { color: 'gray', text: t('datasetDocuments.list.status.archived') }, // completed,archived = true
  62. }
  63. }
  64. // status item for list
  65. export const StatusItem: FC<{
  66. status: DocumentDisplayStatus
  67. reverse?: boolean
  68. scene?: 'list' | 'detail'
  69. textCls?: string
  70. errorMessage?: string
  71. }> = ({ status, reverse = false, scene = 'list', textCls = '', errorMessage }) => {
  72. const DOC_INDEX_STATUS_MAP = useIndexStatus()
  73. const localStatus = status.toLowerCase() as keyof typeof DOC_INDEX_STATUS_MAP
  74. return <div className={
  75. cn('flex items-center',
  76. reverse ? 'flex-row-reverse' : '',
  77. scene === 'detail' ? s.statusItemDetail : '')
  78. }>
  79. <Indicator color={DOC_INDEX_STATUS_MAP[localStatus]?.color as IndicatorProps['color']} className={reverse ? 'ml-2' : 'mr-2'} />
  80. <span className={cn('text-gray-700 text-sm', textCls)}>{DOC_INDEX_STATUS_MAP[localStatus]?.text}</span>
  81. {
  82. errorMessage && (
  83. <Tooltip
  84. selector='dataset-document-detail-item-status'
  85. htmlContent={
  86. <div className='max-w-[260px] break-all'>{errorMessage}</div>
  87. }
  88. >
  89. <HelpCircle className='ml-1 w-[14px] h-[14px] text-gray-700' />
  90. </Tooltip>
  91. )
  92. }
  93. </div>
  94. }
  95. type OperationName = 'delete' | 'archive' | 'enable' | 'disable' | 'sync' | 'un_archive'
  96. // operation action for list and detail
  97. export const OperationAction: FC<{
  98. embeddingAvailable: boolean
  99. detail: {
  100. enabled: boolean
  101. archived: boolean
  102. id: string
  103. data_source_type: string
  104. doc_form: string
  105. }
  106. datasetId: string
  107. onUpdate: (operationName?: string) => void
  108. scene?: 'list' | 'detail'
  109. className?: string
  110. }> = ({ embeddingAvailable, datasetId, detail, onUpdate, scene = 'list', className = '' }) => {
  111. const { id, enabled = false, archived = false, data_source_type } = detail || {}
  112. const [showModal, setShowModal] = useState(false)
  113. const { notify } = useContext(ToastContext)
  114. const { t } = useTranslation()
  115. const router = useRouter()
  116. const isListScene = scene === 'list'
  117. const onOperate = async (operationName: OperationName) => {
  118. let opApi = deleteDocument
  119. switch (operationName) {
  120. case 'archive':
  121. opApi = archiveDocument
  122. break
  123. case 'un_archive':
  124. opApi = unArchiveDocument
  125. break
  126. case 'enable':
  127. opApi = enableDocument
  128. break
  129. case 'disable':
  130. opApi = disableDocument
  131. break
  132. case 'sync':
  133. opApi = syncDocument
  134. break
  135. default:
  136. opApi = deleteDocument
  137. break
  138. }
  139. const [e] = await asyncRunSafe<CommonResponse>(opApi({ datasetId, documentId: id }) as Promise<CommonResponse>)
  140. if (!e)
  141. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  142. else
  143. notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
  144. onUpdate(operationName)
  145. }
  146. return <div className='flex items-center' onClick={e => e.stopPropagation()}>
  147. {isListScene && !embeddingAvailable && (
  148. <Switch defaultValue={false} onChange={() => { }} disabled={true} size='md' />
  149. )}
  150. {isListScene && embeddingAvailable && (
  151. <>
  152. {archived
  153. ? <Tooltip selector={`list-switch-${id}`} content={t('datasetDocuments.list.action.enableWarning') as string} className='!font-semibold'>
  154. <div>
  155. <Switch defaultValue={false} onChange={() => { }} disabled={true} size='md' />
  156. </div>
  157. </Tooltip>
  158. : <Switch defaultValue={enabled} onChange={v => onOperate(v ? 'enable' : 'disable')} size='md' />
  159. }
  160. <Divider className='!ml-4 !mr-2 !h-3' type='vertical' />
  161. </>
  162. )}
  163. {embeddingAvailable && (
  164. <Popover
  165. htmlContent={
  166. <div className='w-full py-1'>
  167. {!isListScene && <>
  168. <div className='flex justify-between items-center mx-4 pt-2'>
  169. <span className={cn(s.actionName, 'font-medium')}>
  170. {!archived && enabled ? t('datasetDocuments.list.index.enable') : t('datasetDocuments.list.index.disable')}
  171. </span>
  172. <Tooltip
  173. selector={`detail-switch-${id}`}
  174. content={t('datasetDocuments.list.action.enableWarning') as string}
  175. className='!font-semibold'
  176. disabled={!archived}
  177. >
  178. <div>
  179. <Switch
  180. defaultValue={archived ? false : enabled}
  181. onChange={v => !archived && onOperate(v ? 'enable' : 'disable')}
  182. disabled={archived}
  183. size='md'
  184. />
  185. </div>
  186. </Tooltip>
  187. </div>
  188. <div className='mx-4 pb-1 pt-0.5 text-xs text-gray-500'>
  189. {!archived && enabled ? t('datasetDocuments.list.index.enableTip') : t('datasetDocuments.list.index.disableTip')}
  190. </div>
  191. <Divider />
  192. </>}
  193. {!archived && (
  194. <>
  195. <div className={s.actionItem} onClick={() => router.push(`/datasets/${datasetId}/documents/${detail.id}/settings`)}>
  196. <SettingsIcon />
  197. <span className={s.actionName}>{t('datasetDocuments.list.action.settings')}</span>
  198. </div>
  199. {data_source_type === 'notion_import' && (
  200. <div className={s.actionItem} onClick={() => onOperate('sync')}>
  201. <SyncIcon />
  202. <span className={s.actionName}>{t('datasetDocuments.list.action.sync')}</span>
  203. </div>
  204. )}
  205. <Divider className='my-1' />
  206. </>
  207. )}
  208. {!archived && <div className={s.actionItem} onClick={() => onOperate('archive')}>
  209. <ArchiveIcon />
  210. <span className={s.actionName}>{t('datasetDocuments.list.action.archive')}</span>
  211. </div>}
  212. {archived && (
  213. <div className={s.actionItem} onClick={() => onOperate('un_archive')}>
  214. <ArchiveIcon />
  215. <span className={s.actionName}>{t('datasetDocuments.list.action.unarchive')}</span>
  216. </div>
  217. )}
  218. <div className={cn(s.actionItem, s.deleteActionItem, 'group')} onClick={() => setShowModal(true)}>
  219. <TrashIcon className={'w-4 h-4 stroke-current text-gray-500 stroke-2 group-hover:text-red-500'} />
  220. <span className={cn(s.actionName, 'group-hover:text-red-500')}>{t('datasetDocuments.list.action.delete')}</span>
  221. </div>
  222. </div>
  223. }
  224. trigger='click'
  225. position='br'
  226. btnElement={
  227. <div className={cn(s.commonIcon)}>
  228. <DotsHorizontal className='w-4 h-4 text-gray-700' />
  229. </div>
  230. }
  231. btnClassName={open => cn(isListScene ? s.actionIconWrapperList : s.actionIconWrapperDetail, open ? '!bg-gray-100 !shadow-none' : '!bg-transparent')}
  232. className={`!w-[200px] h-fit !z-20 ${className}`}
  233. />
  234. )}
  235. {showModal && <Modal isShow={showModal} onClose={() => setShowModal(false)} className={s.delModal} closable>
  236. <div>
  237. <div className={s.warningWrapper}>
  238. <ExclamationCircleIcon className={s.warningIcon} />
  239. </div>
  240. <div className='text-xl font-semibold text-gray-900 mb-1'>{t('datasetDocuments.list.delete.title')}</div>
  241. <div className='text-sm text-gray-500 mb-10'>{t('datasetDocuments.list.delete.content')}</div>
  242. <div className='flex gap-2 justify-end'>
  243. <Button onClick={() => setShowModal(false)}>{t('common.operation.cancel')}</Button>
  244. <Button
  245. type='warning'
  246. onClick={() => onOperate('delete')}
  247. className='border-red-700 border-[0.5px]'
  248. >
  249. {t('common.operation.sure')}
  250. </Button>
  251. </div>
  252. </div>
  253. </Modal>}
  254. </div>
  255. }
  256. export const renderTdValue = (value: string | number | null, isEmptyStyle = false) => {
  257. return (
  258. <div className={cn(isEmptyStyle ? 'text-gray-400' : 'text-gray-700', s.tdValue)}>
  259. {value ?? '-'}
  260. </div>
  261. )
  262. }
  263. const renderCount = (count: number | undefined) => {
  264. if (!count)
  265. return renderTdValue(0, true)
  266. if (count < 1000)
  267. return count
  268. return `${formatNumber((count / 1000).toFixed(1))}k`
  269. }
  270. type LocalDoc = SimpleDocumentDetail & { percent?: number }
  271. type IDocumentListProps = {
  272. embeddingAvailable: boolean
  273. documents: LocalDoc[]
  274. datasetId: string
  275. onUpdate: () => void
  276. }
  277. /**
  278. * Document list component including basic information
  279. */
  280. const DocumentList: FC<IDocumentListProps> = ({ embeddingAvailable, documents = [], datasetId, onUpdate }) => {
  281. const { t } = useTranslation()
  282. const router = useRouter()
  283. const [localDocs, setLocalDocs] = useState<LocalDoc[]>(documents)
  284. const [enableSort, setEnableSort] = useState(false)
  285. useEffect(() => {
  286. setLocalDocs(documents)
  287. }, [documents])
  288. const onClickSort = () => {
  289. setEnableSort(!enableSort)
  290. if (!enableSort) {
  291. const sortedDocs = [...localDocs].sort((a, b) => dayjs(a.created_at).isBefore(dayjs(b.created_at)) ? -1 : 1)
  292. setLocalDocs(sortedDocs)
  293. }
  294. else {
  295. setLocalDocs(documents)
  296. }
  297. }
  298. return (
  299. <>
  300. <table className={`w-full border-collapse border-0 text-sm mt-3 ${s.documentTable}`}>
  301. <thead className="h-8 leading-8 border-b border-gray-200 text-gray-500 font-medium text-xs uppercase">
  302. <tr>
  303. <td className='w-12'>#</td>
  304. <td>{t('datasetDocuments.list.table.header.fileName')}</td>
  305. <td className='w-24'>{t('datasetDocuments.list.table.header.words')}</td>
  306. <td className='w-24'>{t('datasetDocuments.list.table.header.hitCount')}</td>
  307. <td className='w-44'>
  308. <div className='flex justify-between items-center'>
  309. {t('datasetDocuments.list.table.header.uploadTime')}
  310. <ArrowDownIcon className={cn('h-3 w-3 stroke-current stroke-2 cursor-pointer', enableSort ? 'text-gray-500' : 'text-gray-300')} onClick={onClickSort} />
  311. </div>
  312. </td>
  313. <td className='w-40'>{t('datasetDocuments.list.table.header.status')}</td>
  314. <td className='w-20'>{t('datasetDocuments.list.table.header.action')}</td>
  315. </tr>
  316. </thead>
  317. <tbody className="text-gray-700">
  318. {localDocs.map((doc) => {
  319. const suffix = doc.name.split('.').pop() || 'txt'
  320. return <tr
  321. key={doc.id}
  322. className={'border-b border-gray-200 h-8 hover:bg-gray-50 cursor-pointer'}
  323. onClick={() => {
  324. router.push(`/datasets/${datasetId}/documents/${doc.id}`)
  325. }}>
  326. <td className='text-left align-middle text-gray-500 text-xs'>{doc.position}</td>
  327. <td className={s.tdValue}>
  328. {
  329. doc?.data_source_type === DataSourceType.NOTION
  330. ? <NotionIcon className='inline-flex -mt-[3px] mr-1.5 align-middle' type='page' src={doc.data_source_info.notion_page_icon} />
  331. : <div className={cn(s[`${doc?.data_source_info?.upload_file?.extension ?? suffix}Icon`], s.commonIcon, 'mr-1.5')}></div>
  332. }
  333. {
  334. doc.data_source_type === DataSourceType.NOTION
  335. ? <span>{doc.name}</span>
  336. : <span>{doc?.name?.replace(/\.[^/.]+$/, '')}<span className='text-gray-500'>.{suffix}</span></span>
  337. }
  338. </td>
  339. <td>{renderCount(doc.word_count)}</td>
  340. <td>{renderCount(doc.hit_count)}</td>
  341. <td className='text-gray-500 text-[13px]'>
  342. {dayjs.unix(doc.created_at).format(t('datasetHitTesting.dateTimeFormat') as string)}
  343. </td>
  344. <td>
  345. {
  346. (['indexing', 'splitting', 'parsing', 'cleaning'].includes(doc.indexing_status) && doc?.data_source_type === DataSourceType.NOTION)
  347. ? <ProgressBar percent={doc.percent || 0} />
  348. : <StatusItem status={doc.display_status} />
  349. }
  350. </td>
  351. <td>
  352. <OperationAction
  353. embeddingAvailable={embeddingAvailable}
  354. datasetId={datasetId}
  355. detail={pick(doc, ['enabled', 'archived', 'id', 'data_source_type', 'doc_form'])}
  356. onUpdate={onUpdate}
  357. />
  358. </td>
  359. </tr>
  360. })}
  361. </tbody>
  362. </table>
  363. </>
  364. )
  365. }
  366. export default DocumentList