index.tsx 12 KB

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