index.tsx 11 KB

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