index.tsx 12 KB

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