index.tsx 12 KB

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