You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.tsx 11KB

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