index.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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 { 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 style from './style.module.css'
  16. import cn from '@/utils/classnames'
  17. import Divider from '@/app/components/base/divider'
  18. import Loading from '@/app/components/base/loading'
  19. import { ToastContext } from '@/app/components/base/toast'
  20. import type { ChunkingMode, ParentMode, ProcessMode } from '@/models/datasets'
  21. import { useDatasetDetailContext } from '@/context/dataset-detail'
  22. import FloatRightContainer from '@/app/components/base/float-right-container'
  23. import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
  24. import { LayoutRight2LineMod } from '@/app/components/base/icons/src/public/knowledge'
  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: File) => {
  105. const formData = new FormData()
  106. formData.append('file', csv)
  107. await segmentBatchImport({
  108. url: `/datasets/${datasetId}/documents/${documentId}/segments/batch_import`,
  109. body: formData,
  110. }, {
  111. onSuccess: (res) => {
  112. setImportStatus(res.job_status)
  113. checkProcess(res.job_id)
  114. },
  115. onError: (e) => {
  116. notify({ type: 'error', message: `${t('datasetDocuments.list.batchModal.runError')}${'message' in e ? `: ${e.message}` : ''}` })
  117. },
  118. })
  119. }
  120. const { data: documentDetail, error, refetch: detailMutate } = useDocumentDetail({
  121. datasetId,
  122. documentId,
  123. params: { metadata: 'without' },
  124. })
  125. const { data: documentMetadata, error: metadataErr, refetch: metadataMutate } = useDocumentMetadata({
  126. datasetId,
  127. documentId,
  128. params: { metadata: 'only' },
  129. })
  130. const backToPrev = () => {
  131. router.push(`/datasets/${datasetId}/documents`)
  132. }
  133. const isDetailLoading = !documentDetail && !error
  134. const isMetadataLoading = !documentMetadata && !metadataErr
  135. const embedding = ['queuing', 'indexing', 'paused'].includes((documentDetail?.display_status || '').toLowerCase())
  136. const invalidChunkList = useInvalid(useSegmentListKey)
  137. const invalidChildChunkList = useInvalid(useChildSegmentListKey)
  138. const invalidDocumentList = useInvalidDocumentList(datasetId)
  139. const handleOperate = (operateName?: string) => {
  140. invalidDocumentList()
  141. if (operateName === 'delete') {
  142. backToPrev()
  143. }
  144. else {
  145. detailMutate()
  146. // If operation is not rename, refresh the chunk list after 5 seconds
  147. if (operateName) {
  148. setTimeout(() => {
  149. invalidChunkList()
  150. invalidChildChunkList()
  151. }, 5000)
  152. }
  153. }
  154. }
  155. const mode = useMemo(() => {
  156. return documentDetail?.document_process_rule?.mode
  157. }, [documentDetail?.document_process_rule])
  158. const parentMode = useMemo(() => {
  159. return documentDetail?.document_process_rule?.rules?.parent_mode
  160. }, [documentDetail?.document_process_rule])
  161. const isFullDocMode = useMemo(() => {
  162. return mode === 'hierarchical' && parentMode === 'full-doc'
  163. }, [mode, parentMode])
  164. return (
  165. <DocumentContext.Provider value={{
  166. datasetId,
  167. documentId,
  168. docForm: documentDetail?.doc_form || '',
  169. mode,
  170. parentMode,
  171. }}>
  172. <div className='flex h-full flex-col bg-background-default'>
  173. <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'>
  174. <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'}>
  175. <RiArrowLeftLine className='h-4 w-4 text-components-button-ghost-text hover:text-text-tertiary' />
  176. </div>
  177. <DocumentTitle
  178. datasetId={datasetId}
  179. extension={documentDetail?.data_source_info?.upload_file?.extension}
  180. name={documentDetail?.name}
  181. wrapperCls='mr-2'
  182. parent_mode={parentMode}
  183. processMode={mode}
  184. />
  185. <div className='flex flex-wrap items-center'>
  186. {embeddingAvailable && documentDetail && !documentDetail.archived && !isFullDocMode && (
  187. <>
  188. <SegmentAdd
  189. importStatus={importStatus}
  190. clearProcessStatus={resetProcessStatus}
  191. showNewSegmentModal={showNewSegmentModal}
  192. showBatchModal={showBatchModal}
  193. embedding={embedding}
  194. />
  195. <Divider type='vertical' className='!mx-3 !h-[14px] !bg-divider-regular' />
  196. </>
  197. )}
  198. <StatusItem
  199. status={documentDetail?.display_status || 'available'}
  200. scene='detail'
  201. errorMessage={documentDetail?.error || ''}
  202. textCls='font-semibold text-xs uppercase'
  203. detail={{
  204. enabled: documentDetail?.enabled || false,
  205. archived: documentDetail?.archived || false,
  206. id: documentId,
  207. }}
  208. datasetId={datasetId}
  209. onUpdate={handleOperate}
  210. />
  211. <OperationAction
  212. scene='detail'
  213. embeddingAvailable={embeddingAvailable}
  214. detail={{
  215. name: documentDetail?.name || '',
  216. enabled: documentDetail?.enabled || false,
  217. archived: documentDetail?.archived || false,
  218. id: documentId,
  219. data_source_type: documentDetail?.data_source_type || '',
  220. doc_form: documentDetail?.doc_form || '',
  221. }}
  222. datasetId={datasetId}
  223. onUpdate={handleOperate}
  224. className='!w-[200px]'
  225. />
  226. <button
  227. className={style.layoutRightIcon}
  228. onClick={() => setShowMetadata(!showMetadata)}
  229. >
  230. {
  231. showMetadata
  232. ? <LayoutRight2LineMod className='h-4 w-4 text-components-button-secondary-text' />
  233. : <RiLayoutRight2Line className='h-4 w-4 text-components-button-secondary-text' />
  234. }
  235. </button>
  236. </div>
  237. </div>
  238. <div className='flex flex-1 flex-row' style={{ height: 'calc(100% - 4rem)' }}>
  239. {isDetailLoading
  240. ? <Loading type='app' />
  241. : <div className={cn('flex h-full min-w-0 grow flex-col',
  242. embedding ? '' : isFullDocMode ? 'relative pl-11 pr-11 pt-4' : 'relative pl-5 pr-11 pt-3',
  243. )}>
  244. {embedding
  245. ? <Embedding
  246. detailUpdate={detailMutate}
  247. indexingType={dataset?.indexing_technique}
  248. retrievalMethod={dataset?.retrieval_model_dict?.search_method}
  249. />
  250. : <Completed
  251. embeddingAvailable={embeddingAvailable}
  252. showNewSegmentModal={newSegmentModalVisible}
  253. onNewSegmentModalChange={setNewSegmentModalVisible}
  254. importStatus={importStatus}
  255. archived={documentDetail?.archived}
  256. />
  257. }
  258. </div>
  259. }
  260. <FloatRightContainer showClose isOpen={showMetadata} onClose={() => setShowMetadata(false)} isMobile={isMobile} panelClassname='!justify-start' footer={null}>
  261. <Metadata
  262. className='mr-2 mt-3'
  263. datasetId={datasetId}
  264. documentId={documentId}
  265. docDetail={{ ...documentDetail, ...documentMetadata, doc_type: documentMetadata?.doc_type === 'others' ? '' : documentMetadata?.doc_type } as any}
  266. />
  267. </FloatRightContainer>
  268. </div>
  269. <BatchModal
  270. isShow={batchModalVisible}
  271. onCancel={hideBatchModal}
  272. onConfirm={runBatch}
  273. docForm={documentDetail?.doc_form as ChunkingMode}
  274. />
  275. </div>
  276. </DocumentContext.Provider>
  277. )
  278. }
  279. export default DocumentDetail