index.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { useMemo, useState } from 'react'
  4. import { createContext, useContext, useContextSelector } from 'use-context-selector'
  5. import { useTranslation } from 'react-i18next'
  6. import { useRouter } from 'next/navigation'
  7. import { RiArrowLeftLine, RiLayoutLeft2Line, RiLayoutRight2Line } from '@remixicon/react'
  8. import { OperationAction, StatusItem } from '../list'
  9. import DocumentPicker from '../../common/document-picker'
  10. import Completed from './completed'
  11. import Embedding from './embedding'
  12. import Metadata from '@/app/components/datasets/metadata/metadata-document'
  13. import SegmentAdd, { ProcessStatus } from './segment-add'
  14. import BatchModal from './batch-modal'
  15. import DocumentExtraActions from './document-extra-actions'
  16. import style from './style.module.css'
  17. import cn from '@/utils/classnames'
  18. import Divider from '@/app/components/base/divider'
  19. import Loading from '@/app/components/base/loading'
  20. import { ToastContext } from '@/app/components/base/toast'
  21. import type { ChunkingMode, FileItem, ParentMode, ProcessMode } from '@/models/datasets'
  22. import { useDatasetDetailContext } from '@/context/dataset-detail'
  23. import FloatRightContainer from '@/app/components/base/float-right-container'
  24. import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
  25. import { useCheckSegmentBatchImportProgress, useChildSegmentListKey, useSegmentBatchImport, useSegmentListKey } from '@/service/knowledge/use-segment'
  26. import { useDocumentDetail, useDocumentMetadata, useInvalidDocumentList } from '@/service/knowledge/use-document'
  27. import { useInvalid } from '@/service/use-base'
  28. type DocumentContextValue = {
  29. datasetId?: string
  30. documentId?: string
  31. docForm: string
  32. mode?: ProcessMode
  33. parentMode?: ParentMode
  34. }
  35. export const DocumentContext = createContext<DocumentContextValue>({ docForm: '' })
  36. export const useDocumentContext = (selector: (value: DocumentContextValue) => any) => {
  37. return useContextSelector(DocumentContext, selector)
  38. }
  39. type DocumentTitleProps = {
  40. datasetId: string
  41. extension?: string
  42. name?: string
  43. processMode?: ProcessMode
  44. parent_mode?: ParentMode
  45. iconCls?: string
  46. textCls?: string
  47. wrapperCls?: string
  48. }
  49. export const DocumentTitle: FC<DocumentTitleProps> = ({ datasetId, extension, name, processMode, parent_mode, wrapperCls }) => {
  50. const router = useRouter()
  51. return (
  52. <div className={cn('flex flex-1 items-center justify-start', wrapperCls)}>
  53. <DocumentPicker
  54. datasetId={datasetId}
  55. value={{
  56. name,
  57. extension,
  58. processMode,
  59. parentMode: parent_mode,
  60. }}
  61. onChange={(doc) => {
  62. router.push(`/datasets/${datasetId}/documents/${doc.id}`)
  63. }}
  64. />
  65. </div>
  66. )
  67. }
  68. type Props = {
  69. datasetId: string
  70. documentId: string
  71. }
  72. const DocumentDetail: FC<Props> = ({ datasetId, documentId }) => {
  73. const router = useRouter()
  74. const { t } = useTranslation()
  75. const media = useBreakpoints()
  76. const isMobile = media === MediaType.mobile
  77. const { notify } = useContext(ToastContext)
  78. const { dataset } = useDatasetDetailContext()
  79. const embeddingAvailable = !!dataset?.embedding_available
  80. const [showMetadata, setShowMetadata] = useState(!isMobile)
  81. const [newSegmentModalVisible, setNewSegmentModalVisible] = useState(false)
  82. const [batchModalVisible, setBatchModalVisible] = useState(false)
  83. const [importStatus, setImportStatus] = useState<ProcessStatus | string>()
  84. const showNewSegmentModal = () => setNewSegmentModalVisible(true)
  85. const showBatchModal = () => setBatchModalVisible(true)
  86. const hideBatchModal = () => setBatchModalVisible(false)
  87. const resetProcessStatus = () => setImportStatus('')
  88. const { mutateAsync: checkSegmentBatchImportProgress } = useCheckSegmentBatchImportProgress()
  89. const checkProcess = async (jobID: string) => {
  90. await checkSegmentBatchImportProgress({ jobID }, {
  91. onSuccess: (res) => {
  92. setImportStatus(res.job_status)
  93. if (res.job_status === ProcessStatus.WAITING || res.job_status === ProcessStatus.PROCESSING)
  94. setTimeout(() => checkProcess(res.job_id), 2500)
  95. if (res.job_status === ProcessStatus.ERROR)
  96. notify({ type: 'error', message: `${t('datasetDocuments.list.batchModal.runError')}` })
  97. },
  98. onError: (e) => {
  99. notify({ type: 'error', message: `${t('datasetDocuments.list.batchModal.runError')}${'message' in e ? `: ${e.message}` : ''}` })
  100. },
  101. })
  102. }
  103. const { mutateAsync: segmentBatchImport } = useSegmentBatchImport()
  104. const runBatch = async (csv: FileItem) => {
  105. await segmentBatchImport({
  106. url: `/datasets/${datasetId}/documents/${documentId}/segments/batch_import`,
  107. body: { upload_file_id: csv.file.id! },
  108. }, {
  109. onSuccess: (res) => {
  110. setImportStatus(res.job_status)
  111. checkProcess(res.job_id)
  112. },
  113. onError: (e) => {
  114. notify({ type: 'error', message: `${t('datasetDocuments.list.batchModal.runError')}${'message' in e ? `: ${e.message}` : ''}` })
  115. },
  116. })
  117. }
  118. const { data: documentDetail, error, refetch: detailMutate } = useDocumentDetail({
  119. datasetId,
  120. documentId,
  121. params: { metadata: 'without' },
  122. })
  123. const { data: documentMetadata } = useDocumentMetadata({
  124. datasetId,
  125. documentId,
  126. params: { metadata: 'only' },
  127. })
  128. const backToPrev = () => {
  129. // Preserve pagination and filter states when navigating back
  130. const searchParams = new URLSearchParams(window.location.search)
  131. const queryString = searchParams.toString()
  132. const separator = queryString ? '?' : ''
  133. const backPath = `/datasets/${datasetId}/documents${separator}${queryString}`
  134. router.push(backPath)
  135. }
  136. const isDetailLoading = !documentDetail && !error
  137. const embedding = ['queuing', 'indexing', 'paused'].includes((documentDetail?.display_status || '').toLowerCase())
  138. const invalidChunkList = useInvalid(useSegmentListKey)
  139. const invalidChildChunkList = useInvalid(useChildSegmentListKey)
  140. const invalidDocumentList = useInvalidDocumentList(datasetId)
  141. const handleOperate = (operateName?: string) => {
  142. invalidDocumentList()
  143. if (operateName === 'delete') {
  144. backToPrev()
  145. }
  146. else {
  147. detailMutate()
  148. // If operation is not rename, refresh the chunk list after 5 seconds
  149. if (operateName) {
  150. setTimeout(() => {
  151. invalidChunkList()
  152. invalidChildChunkList()
  153. }, 5000)
  154. }
  155. }
  156. }
  157. const mode = useMemo(() => {
  158. return documentDetail?.document_process_rule?.mode
  159. }, [documentDetail?.document_process_rule])
  160. const parentMode = useMemo(() => {
  161. return documentDetail?.document_process_rule?.rules?.parent_mode
  162. }, [documentDetail?.document_process_rule])
  163. const isFullDocMode = useMemo(() => {
  164. return mode === 'hierarchical' && parentMode === 'full-doc'
  165. }, [mode, parentMode])
  166. return (
  167. <DocumentContext.Provider value={{
  168. datasetId,
  169. documentId,
  170. docForm: documentDetail?.doc_form || '',
  171. mode,
  172. parentMode,
  173. }}>
  174. <div className='flex h-full flex-col bg-background-default'>
  175. <div className='flex min-h-16 flex-wrap items-center justify-between border-b border-b-divider-subtle py-2.5 pl-3 pr-4'>
  176. <div onClick={backToPrev} className={'flex h-8 w-8 shrink-0 cursor-pointer items-center justify-center rounded-full hover:bg-components-button-tertiary-bg'}>
  177. <RiArrowLeftLine className='h-4 w-4 text-components-button-ghost-text hover:text-text-tertiary' />
  178. </div>
  179. <DocumentTitle
  180. datasetId={datasetId}
  181. extension={documentDetail?.data_source_info?.upload_file?.extension}
  182. name={documentDetail?.name}
  183. wrapperCls='mr-2'
  184. parent_mode={parentMode}
  185. processMode={mode}
  186. />
  187. <div className='flex flex-wrap items-center'>
  188. {embeddingAvailable && documentDetail && !documentDetail.archived && !isFullDocMode && (
  189. <>
  190. <SegmentAdd
  191. importStatus={importStatus}
  192. clearProcessStatus={resetProcessStatus}
  193. showNewSegmentModal={showNewSegmentModal}
  194. showBatchModal={showBatchModal}
  195. embedding={embedding}
  196. />
  197. <Divider type='vertical' className='!mx-3 !h-[14px] !bg-divider-regular' />
  198. </>
  199. )}
  200. <StatusItem
  201. status={documentDetail?.display_status || 'available'}
  202. scene='detail'
  203. errorMessage={documentDetail?.error || ''}
  204. textCls='font-semibold text-xs uppercase'
  205. detail={{
  206. enabled: documentDetail?.enabled || false,
  207. archived: documentDetail?.archived || false,
  208. id: documentId,
  209. }}
  210. datasetId={datasetId}
  211. onUpdate={handleOperate}
  212. />
  213. {documentDetail && !documentDetail.archived && (
  214. <>
  215. <Divider type='vertical' className='!mx-3 !h-[14px] !bg-divider-regular' />
  216. <DocumentExtraActions
  217. datasetId={datasetId}
  218. documentId={documentId}
  219. documentName={documentDetail?.name || ''}
  220. />
  221. </>
  222. )}
  223. <OperationAction
  224. scene='detail'
  225. embeddingAvailable={embeddingAvailable}
  226. detail={{
  227. name: documentDetail?.name || '',
  228. enabled: documentDetail?.enabled || false,
  229. archived: documentDetail?.archived || false,
  230. id: documentId,
  231. data_source_type: documentDetail?.data_source_type || '',
  232. doc_form: documentDetail?.doc_form || '',
  233. }}
  234. datasetId={datasetId}
  235. onUpdate={handleOperate}
  236. className='!w-[200px]'
  237. />
  238. <button
  239. className={style.layoutRightIcon}
  240. onClick={() => setShowMetadata(!showMetadata)}
  241. >
  242. {
  243. showMetadata
  244. ? <RiLayoutLeft2Line className='h-4 w-4 text-components-button-secondary-text' />
  245. : <RiLayoutRight2Line className='h-4 w-4 text-components-button-secondary-text' />
  246. }
  247. </button>
  248. </div>
  249. </div>
  250. <div className='flex flex-1 flex-row' style={{ height: 'calc(100% - 4rem)' }}>
  251. {isDetailLoading
  252. ? <Loading type='app' />
  253. : <div className={cn('flex h-full min-w-0 grow flex-col',
  254. embedding ? '' : isFullDocMode ? 'relative pl-11 pr-11 pt-4' : 'relative pl-5 pr-11 pt-3',
  255. )}>
  256. {embedding
  257. ? <Embedding
  258. detailUpdate={detailMutate}
  259. indexingType={dataset?.indexing_technique}
  260. retrievalMethod={dataset?.retrieval_model_dict?.search_method}
  261. />
  262. : <Completed
  263. embeddingAvailable={embeddingAvailable}
  264. showNewSegmentModal={newSegmentModalVisible}
  265. onNewSegmentModalChange={setNewSegmentModalVisible}
  266. importStatus={importStatus}
  267. archived={documentDetail?.archived}
  268. />
  269. }
  270. </div>
  271. }
  272. <FloatRightContainer showClose isOpen={showMetadata} onClose={() => setShowMetadata(false)} isMobile={isMobile} panelClassName='!justify-start' footer={null}>
  273. <Metadata
  274. className='mr-2 mt-3'
  275. datasetId={datasetId}
  276. documentId={documentId}
  277. docDetail={{ ...documentDetail, ...documentMetadata, doc_type: documentMetadata?.doc_type === 'others' ? '' : documentMetadata?.doc_type } as any}
  278. />
  279. </FloatRightContainer>
  280. </div>
  281. <BatchModal
  282. isShow={batchModalVisible}
  283. onCancel={hideBatchModal}
  284. onConfirm={runBatch}
  285. docForm={documentDetail?.doc_form as ChunkingMode}
  286. />
  287. </div>
  288. </DocumentContext.Provider>
  289. )
  290. }
  291. export default DocumentDetail