index.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
  4. import { useDebounceFn } from 'ahooks'
  5. import { useTranslation } from 'react-i18next'
  6. import { createContext, useContext, useContextSelector } from 'use-context-selector'
  7. import { usePathname } from 'next/navigation'
  8. import { useDocumentContext } from '../index'
  9. import { ProcessStatus } from '../segment-add'
  10. import s from './style.module.css'
  11. import SegmentList from './segment-list'
  12. import DisplayToggle from './display-toggle'
  13. import BatchAction from './common/batch-action'
  14. import SegmentDetail from './segment-detail'
  15. import SegmentCard from './segment-card'
  16. import ChildSegmentList from './child-segment-list'
  17. import NewChildSegment from './new-child-segment'
  18. import FullScreenDrawer from './common/full-screen-drawer'
  19. import ChildSegmentDetail from './child-segment-detail'
  20. import StatusItem from './status-item'
  21. import Pagination from '@/app/components/base/pagination'
  22. import cn from '@/utils/classnames'
  23. import { formatNumber } from '@/utils/format'
  24. import Divider from '@/app/components/base/divider'
  25. import Input from '@/app/components/base/input'
  26. import { ToastContext } from '@/app/components/base/toast'
  27. import type { Item } from '@/app/components/base/select'
  28. import { SimpleSelect } from '@/app/components/base/select'
  29. import { type ChildChunkDetail, ChunkingMode, type SegmentDetailModel, type SegmentUpdater } from '@/models/datasets'
  30. import NewSegment from '@/app/components/datasets/documents/detail/new-segment'
  31. import { useEventEmitterContextContext } from '@/context/event-emitter'
  32. import Checkbox from '@/app/components/base/checkbox'
  33. import {
  34. useChildSegmentList,
  35. useChildSegmentListKey,
  36. useChunkListAllKey,
  37. useChunkListDisabledKey,
  38. useChunkListEnabledKey,
  39. useDeleteChildSegment,
  40. useDeleteSegment,
  41. useDisableSegment,
  42. useEnableSegment,
  43. useSegmentList,
  44. useSegmentListKey,
  45. useUpdateChildSegment,
  46. useUpdateSegment,
  47. } from '@/service/knowledge/use-segment'
  48. import { useInvalid } from '@/service/use-base'
  49. const DEFAULT_LIMIT = 10
  50. type CurrSegmentType = {
  51. segInfo?: SegmentDetailModel
  52. showModal: boolean
  53. isEditMode?: boolean
  54. }
  55. type CurrChildChunkType = {
  56. childChunkInfo?: ChildChunkDetail
  57. showModal: boolean
  58. }
  59. type SegmentListContextValue = {
  60. isCollapsed: boolean
  61. fullScreen: boolean
  62. toggleFullScreen: (fullscreen?: boolean) => void
  63. currSegment: CurrSegmentType
  64. currChildChunk: CurrChildChunkType
  65. }
  66. const SegmentListContext = createContext<SegmentListContextValue>({
  67. isCollapsed: true,
  68. fullScreen: false,
  69. toggleFullScreen: () => {},
  70. currSegment: { showModal: false },
  71. currChildChunk: { showModal: false },
  72. })
  73. export const useSegmentListContext = (selector: (value: SegmentListContextValue) => any) => {
  74. return useContextSelector(SegmentListContext, selector)
  75. }
  76. type ICompletedProps = {
  77. embeddingAvailable: boolean
  78. showNewSegmentModal: boolean
  79. onNewSegmentModalChange: (state: boolean) => void
  80. importStatus: ProcessStatus | string | undefined
  81. archived?: boolean
  82. }
  83. /**
  84. * Embedding done, show list of all segments
  85. * Support search and filter
  86. */
  87. const Completed: FC<ICompletedProps> = ({
  88. embeddingAvailable,
  89. showNewSegmentModal,
  90. onNewSegmentModalChange,
  91. importStatus,
  92. archived,
  93. }) => {
  94. const { t } = useTranslation()
  95. const { notify } = useContext(ToastContext)
  96. const pathname = usePathname()
  97. const datasetId = useDocumentContext(s => s.datasetId) || ''
  98. const documentId = useDocumentContext(s => s.documentId) || ''
  99. const docForm = useDocumentContext(s => s.docForm)
  100. const mode = useDocumentContext(s => s.mode)
  101. const parentMode = useDocumentContext(s => s.parentMode)
  102. // the current segment id and whether to show the modal
  103. const [currSegment, setCurrSegment] = useState<CurrSegmentType>({ showModal: false })
  104. const [currChildChunk, setCurrChildChunk] = useState<CurrChildChunkType>({ showModal: false })
  105. const [currChunkId, setCurrChunkId] = useState('')
  106. const [inputValue, setInputValue] = useState<string>('') // the input value
  107. const [searchValue, setSearchValue] = useState<string>('') // the search value
  108. const [selectedStatus, setSelectedStatus] = useState<boolean | 'all'>('all') // the selected status, enabled/disabled/undefined
  109. const [segments, setSegments] = useState<SegmentDetailModel[]>([]) // all segments data
  110. const [childSegments, setChildSegments] = useState<ChildChunkDetail[]>([]) // all child segments data
  111. const [selectedSegmentIds, setSelectedSegmentIds] = useState<string[]>([])
  112. const { eventEmitter } = useEventEmitterContextContext()
  113. const [isCollapsed, setIsCollapsed] = useState(true)
  114. const [currentPage, setCurrentPage] = useState(1) // start from 1
  115. const [limit, setLimit] = useState(DEFAULT_LIMIT)
  116. const [fullScreen, setFullScreen] = useState(false)
  117. const [showNewChildSegmentModal, setShowNewChildSegmentModal] = useState(false)
  118. const segmentListRef = useRef<HTMLDivElement>(null)
  119. const childSegmentListRef = useRef<HTMLDivElement>(null)
  120. const needScrollToBottom = useRef(false)
  121. const statusList = useRef<Item[]>([
  122. { value: 'all', name: t('datasetDocuments.list.index.all') },
  123. { value: 0, name: t('datasetDocuments.list.status.disabled') },
  124. { value: 1, name: t('datasetDocuments.list.status.enabled') },
  125. ])
  126. const { run: handleSearch } = useDebounceFn(() => {
  127. setSearchValue(inputValue)
  128. setCurrentPage(1)
  129. }, { wait: 500 })
  130. const handleInputChange = (value: string) => {
  131. setInputValue(value)
  132. handleSearch()
  133. }
  134. const onChangeStatus = ({ value }: Item) => {
  135. setSelectedStatus(value === 'all' ? 'all' : !!value)
  136. setCurrentPage(1)
  137. }
  138. const isFullDocMode = useMemo(() => {
  139. return mode === 'hierarchical' && parentMode === 'full-doc'
  140. }, [mode, parentMode])
  141. const { isFetching: isLoadingSegmentList, data: segmentListData } = useSegmentList(
  142. {
  143. datasetId,
  144. documentId,
  145. params: {
  146. page: isFullDocMode ? 1 : currentPage,
  147. limit: isFullDocMode ? 10 : limit,
  148. keyword: isFullDocMode ? '' : searchValue,
  149. enabled: selectedStatus,
  150. },
  151. },
  152. )
  153. const invalidSegmentList = useInvalid(useSegmentListKey)
  154. useEffect(() => {
  155. if (segmentListData) {
  156. setSegments(segmentListData.data || [])
  157. const totalPages = segmentListData.total_pages
  158. if (totalPages < currentPage)
  159. setCurrentPage(totalPages === 0 ? 1 : totalPages)
  160. }
  161. // eslint-disable-next-line react-hooks/exhaustive-deps
  162. }, [segmentListData])
  163. useEffect(() => {
  164. if (segmentListRef.current && needScrollToBottom.current) {
  165. segmentListRef.current.scrollTo({ top: segmentListRef.current.scrollHeight, behavior: 'smooth' })
  166. needScrollToBottom.current = false
  167. }
  168. }, [segments])
  169. const { isFetching: isLoadingChildSegmentList, data: childChunkListData } = useChildSegmentList(
  170. {
  171. datasetId,
  172. documentId,
  173. segmentId: segments[0]?.id || '',
  174. params: {
  175. page: currentPage === 0 ? 1 : currentPage,
  176. limit,
  177. keyword: searchValue,
  178. },
  179. },
  180. !isFullDocMode || segments.length === 0,
  181. )
  182. const invalidChildSegmentList = useInvalid(useChildSegmentListKey)
  183. useEffect(() => {
  184. if (childSegmentListRef.current && needScrollToBottom.current) {
  185. childSegmentListRef.current.scrollTo({ top: childSegmentListRef.current.scrollHeight, behavior: 'smooth' })
  186. needScrollToBottom.current = false
  187. }
  188. }, [childSegments])
  189. useEffect(() => {
  190. if (childChunkListData) {
  191. setChildSegments(childChunkListData.data || [])
  192. const totalPages = childChunkListData.total_pages
  193. if (totalPages < currentPage)
  194. setCurrentPage(totalPages === 0 ? 1 : totalPages)
  195. }
  196. // eslint-disable-next-line react-hooks/exhaustive-deps
  197. }, [childChunkListData])
  198. const resetList = useCallback(() => {
  199. setSelectedSegmentIds([])
  200. invalidSegmentList()
  201. // eslint-disable-next-line react-hooks/exhaustive-deps
  202. }, [])
  203. const resetChildList = useCallback(() => {
  204. invalidChildSegmentList()
  205. // eslint-disable-next-line react-hooks/exhaustive-deps
  206. }, [])
  207. const onClickCard = (detail: SegmentDetailModel, isEditMode = false) => {
  208. setCurrSegment({ segInfo: detail, showModal: true, isEditMode })
  209. }
  210. const onCloseSegmentDetail = useCallback(() => {
  211. setCurrSegment({ showModal: false })
  212. setFullScreen(false)
  213. }, [])
  214. const onCloseNewSegmentModal = useCallback(() => {
  215. onNewSegmentModalChange(false)
  216. setFullScreen(false)
  217. }, [onNewSegmentModalChange])
  218. const onCloseNewChildChunkModal = useCallback(() => {
  219. setShowNewChildSegmentModal(false)
  220. setFullScreen(false)
  221. }, [])
  222. const { mutateAsync: enableSegment } = useEnableSegment()
  223. const { mutateAsync: disableSegment } = useDisableSegment()
  224. const invalidChunkListAll = useInvalid(useChunkListAllKey)
  225. const invalidChunkListEnabled = useInvalid(useChunkListEnabledKey)
  226. const invalidChunkListDisabled = useInvalid(useChunkListDisabledKey)
  227. const refreshChunkListWithStatusChanged = () => {
  228. switch (selectedStatus) {
  229. case 'all':
  230. invalidChunkListDisabled()
  231. invalidChunkListEnabled()
  232. break
  233. default:
  234. invalidSegmentList()
  235. }
  236. }
  237. const onChangeSwitch = useCallback(async (enable: boolean, segId?: string) => {
  238. const operationApi = enable ? enableSegment : disableSegment
  239. await operationApi({ datasetId, documentId, segmentIds: segId ? [segId] : selectedSegmentIds }, {
  240. onSuccess: () => {
  241. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  242. for (const seg of segments) {
  243. if (segId ? seg.id === segId : selectedSegmentIds.includes(seg.id))
  244. seg.enabled = enable
  245. }
  246. setSegments([...segments])
  247. refreshChunkListWithStatusChanged()
  248. },
  249. onError: () => {
  250. notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
  251. },
  252. })
  253. // eslint-disable-next-line react-hooks/exhaustive-deps
  254. }, [datasetId, documentId, selectedSegmentIds, segments])
  255. const { mutateAsync: deleteSegment } = useDeleteSegment()
  256. const onDelete = useCallback(async (segId?: string) => {
  257. await deleteSegment({ datasetId, documentId, segmentIds: segId ? [segId] : selectedSegmentIds }, {
  258. onSuccess: () => {
  259. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  260. resetList()
  261. !segId && setSelectedSegmentIds([])
  262. },
  263. onError: () => {
  264. notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
  265. },
  266. })
  267. // eslint-disable-next-line react-hooks/exhaustive-deps
  268. }, [datasetId, documentId, selectedSegmentIds])
  269. const { mutateAsync: updateSegment } = useUpdateSegment()
  270. const refreshChunkListDataWithDetailChanged = () => {
  271. switch (selectedStatus) {
  272. case 'all':
  273. invalidChunkListDisabled()
  274. invalidChunkListEnabled()
  275. break
  276. case true:
  277. invalidChunkListAll()
  278. invalidChunkListDisabled()
  279. break
  280. case false:
  281. invalidChunkListAll()
  282. invalidChunkListEnabled()
  283. break
  284. }
  285. }
  286. const handleUpdateSegment = useCallback(async (
  287. segmentId: string,
  288. question: string,
  289. answer: string,
  290. keywords: string[],
  291. needRegenerate = false,
  292. ) => {
  293. const params: SegmentUpdater = { content: '' }
  294. if (docForm === ChunkingMode.qa) {
  295. if (!question.trim())
  296. return notify({ type: 'error', message: t('datasetDocuments.segment.questionEmpty') })
  297. if (!answer.trim())
  298. return notify({ type: 'error', message: t('datasetDocuments.segment.answerEmpty') })
  299. params.content = question
  300. params.answer = answer
  301. }
  302. else {
  303. if (!question.trim())
  304. return notify({ type: 'error', message: t('datasetDocuments.segment.contentEmpty') })
  305. params.content = question
  306. }
  307. if (keywords.length)
  308. params.keywords = keywords
  309. if (needRegenerate)
  310. params.regenerate_child_chunks = needRegenerate
  311. eventEmitter?.emit('update-segment')
  312. await updateSegment({ datasetId, documentId, segmentId, body: params }, {
  313. onSuccess(res) {
  314. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  315. if (!needRegenerate)
  316. onCloseSegmentDetail()
  317. for (const seg of segments) {
  318. if (seg.id === segmentId) {
  319. seg.answer = res.data.answer
  320. seg.content = res.data.content
  321. seg.keywords = res.data.keywords
  322. seg.word_count = res.data.word_count
  323. seg.hit_count = res.data.hit_count
  324. seg.enabled = res.data.enabled
  325. seg.updated_at = res.data.updated_at
  326. seg.child_chunks = res.data.child_chunks
  327. }
  328. }
  329. setSegments([...segments])
  330. refreshChunkListDataWithDetailChanged()
  331. eventEmitter?.emit('update-segment-success')
  332. },
  333. onSettled() {
  334. eventEmitter?.emit('update-segment-done')
  335. },
  336. })
  337. // eslint-disable-next-line react-hooks/exhaustive-deps
  338. }, [segments, datasetId, documentId])
  339. useEffect(() => {
  340. resetList()
  341. }, [pathname])
  342. useEffect(() => {
  343. if (importStatus === ProcessStatus.COMPLETED)
  344. resetList()
  345. }, [importStatus, resetList])
  346. const onCancelBatchOperation = useCallback(() => {
  347. setSelectedSegmentIds([])
  348. }, [])
  349. const onSelected = useCallback((segId: string) => {
  350. setSelectedSegmentIds(prev =>
  351. prev.includes(segId)
  352. ? prev.filter(id => id !== segId)
  353. : [...prev, segId],
  354. )
  355. }, [])
  356. const isAllSelected = useMemo(() => {
  357. return segments.length > 0 && segments.every(seg => selectedSegmentIds.includes(seg.id))
  358. }, [segments, selectedSegmentIds])
  359. const isSomeSelected = useMemo(() => {
  360. return segments.some(seg => selectedSegmentIds.includes(seg.id))
  361. }, [segments, selectedSegmentIds])
  362. const onSelectedAll = useCallback(() => {
  363. setSelectedSegmentIds((prev) => {
  364. const currentAllSegIds = segments.map(seg => seg.id)
  365. const prevSelectedIds = prev.filter(item => !currentAllSegIds.includes(item))
  366. return [...prevSelectedIds, ...((isAllSelected || selectedSegmentIds.length > 0) ? [] : currentAllSegIds)]
  367. })
  368. }, [segments, isAllSelected, selectedSegmentIds])
  369. const totalText = useMemo(() => {
  370. const isSearch = searchValue !== '' || selectedStatus !== 'all'
  371. if (!isSearch) {
  372. const total = segmentListData?.total ? formatNumber(segmentListData.total) : '--'
  373. const count = total === '--' ? 0 : segmentListData!.total
  374. const translationKey = (mode === 'hierarchical' && parentMode === 'paragraph')
  375. ? 'datasetDocuments.segment.parentChunks'
  376. : 'datasetDocuments.segment.chunks'
  377. return `${total} ${t(translationKey, { count })}`
  378. }
  379. else {
  380. const total = typeof segmentListData?.total === 'number' ? formatNumber(segmentListData.total) : 0
  381. const count = segmentListData?.total || 0
  382. return `${total} ${t('datasetDocuments.segment.searchResults', { count })}`
  383. }
  384. // eslint-disable-next-line react-hooks/exhaustive-deps
  385. }, [segmentListData?.total, mode, parentMode, searchValue, selectedStatus])
  386. const toggleFullScreen = useCallback(() => {
  387. setFullScreen(!fullScreen)
  388. }, [fullScreen])
  389. const viewNewlyAddedChunk = useCallback(async () => {
  390. const totalPages = segmentListData?.total_pages || 0
  391. const total = segmentListData?.total || 0
  392. const newPage = Math.ceil((total + 1) / limit)
  393. needScrollToBottom.current = true
  394. if (newPage > totalPages) {
  395. setCurrentPage(totalPages + 1)
  396. }
  397. else {
  398. resetList()
  399. currentPage !== totalPages && setCurrentPage(totalPages)
  400. }
  401. // eslint-disable-next-line react-hooks/exhaustive-deps
  402. }, [segmentListData, limit, currentPage])
  403. const { mutateAsync: deleteChildSegment } = useDeleteChildSegment()
  404. const onDeleteChildChunk = useCallback(async (segmentId: string, childChunkId: string) => {
  405. await deleteChildSegment(
  406. { datasetId, documentId, segmentId, childChunkId },
  407. {
  408. onSuccess: () => {
  409. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  410. if (parentMode === 'paragraph')
  411. resetList()
  412. else
  413. resetChildList()
  414. },
  415. onError: () => {
  416. notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
  417. },
  418. },
  419. )
  420. // eslint-disable-next-line react-hooks/exhaustive-deps
  421. }, [datasetId, documentId, parentMode])
  422. const handleAddNewChildChunk = useCallback((parentChunkId: string) => {
  423. setShowNewChildSegmentModal(true)
  424. setCurrChunkId(parentChunkId)
  425. }, [])
  426. const onSaveNewChildChunk = useCallback((newChildChunk?: ChildChunkDetail) => {
  427. if (parentMode === 'paragraph') {
  428. for (const seg of segments) {
  429. if (seg.id === currChunkId)
  430. seg.child_chunks?.push(newChildChunk!)
  431. }
  432. setSegments([...segments])
  433. refreshChunkListDataWithDetailChanged()
  434. }
  435. else {
  436. resetChildList()
  437. }
  438. // eslint-disable-next-line react-hooks/exhaustive-deps
  439. }, [parentMode, currChunkId, segments])
  440. const viewNewlyAddedChildChunk = useCallback(() => {
  441. const totalPages = childChunkListData?.total_pages || 0
  442. const total = childChunkListData?.total || 0
  443. const newPage = Math.ceil((total + 1) / limit)
  444. needScrollToBottom.current = true
  445. if (newPage > totalPages) {
  446. setCurrentPage(totalPages + 1)
  447. }
  448. else {
  449. resetChildList()
  450. currentPage !== totalPages && setCurrentPage(totalPages)
  451. }
  452. // eslint-disable-next-line react-hooks/exhaustive-deps
  453. }, [childChunkListData, limit, currentPage])
  454. const onClickSlice = useCallback((detail: ChildChunkDetail) => {
  455. setCurrChildChunk({ childChunkInfo: detail, showModal: true })
  456. setCurrChunkId(detail.segment_id)
  457. }, [])
  458. const onCloseChildSegmentDetail = useCallback(() => {
  459. setCurrChildChunk({ showModal: false })
  460. setFullScreen(false)
  461. }, [])
  462. const { mutateAsync: updateChildSegment } = useUpdateChildSegment()
  463. const handleUpdateChildChunk = useCallback(async (
  464. segmentId: string,
  465. childChunkId: string,
  466. content: string,
  467. ) => {
  468. const params: SegmentUpdater = { content: '' }
  469. if (!content.trim())
  470. return notify({ type: 'error', message: t('datasetDocuments.segment.contentEmpty') })
  471. params.content = content
  472. eventEmitter?.emit('update-child-segment')
  473. await updateChildSegment({ datasetId, documentId, segmentId, childChunkId, body: params }, {
  474. onSuccess: (res) => {
  475. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  476. onCloseChildSegmentDetail()
  477. if (parentMode === 'paragraph') {
  478. for (const seg of segments) {
  479. if (seg.id === segmentId) {
  480. for (const childSeg of seg.child_chunks!) {
  481. if (childSeg.id === childChunkId) {
  482. childSeg.content = res.data.content
  483. childSeg.type = res.data.type
  484. childSeg.word_count = res.data.word_count
  485. childSeg.updated_at = res.data.updated_at
  486. }
  487. }
  488. }
  489. }
  490. setSegments([...segments])
  491. refreshChunkListDataWithDetailChanged()
  492. }
  493. else {
  494. resetChildList()
  495. }
  496. },
  497. onSettled: () => {
  498. eventEmitter?.emit('update-child-segment-done')
  499. },
  500. })
  501. // eslint-disable-next-line react-hooks/exhaustive-deps
  502. }, [segments, childSegments, datasetId, documentId, parentMode])
  503. const onClearFilter = useCallback(() => {
  504. setInputValue('')
  505. setSearchValue('')
  506. setSelectedStatus('all')
  507. setCurrentPage(1)
  508. }, [])
  509. return (
  510. <SegmentListContext.Provider value={{
  511. isCollapsed,
  512. fullScreen,
  513. toggleFullScreen,
  514. currSegment,
  515. currChildChunk,
  516. }}>
  517. {/* Menu Bar */}
  518. {!isFullDocMode && <div className={s.docSearchWrapper}>
  519. <Checkbox
  520. className='shrink-0'
  521. checked={isAllSelected}
  522. mixed={!isAllSelected && isSomeSelected}
  523. onCheck={onSelectedAll}
  524. disabled={isLoadingSegmentList}
  525. />
  526. <div className={'system-sm-semibold-uppercase pl-5 text-text-secondary flex-1'}>{totalText}</div>
  527. <SimpleSelect
  528. onSelect={onChangeStatus}
  529. items={statusList.current}
  530. defaultValue={selectedStatus === 'all' ? 'all' : selectedStatus ? 1 : 0}
  531. className={s.select}
  532. wrapperClassName='h-fit mr-2'
  533. optionWrapClassName='w-[160px]'
  534. optionClassName='p-0'
  535. renderOption={({ item, selected }) => <StatusItem item={item} selected={selected} />}
  536. notClearable
  537. />
  538. <Input
  539. showLeftIcon
  540. showClearIcon
  541. wrapperClassName='!w-52'
  542. value={inputValue}
  543. onChange={e => handleInputChange(e.target.value)}
  544. onClear={() => handleInputChange('')}
  545. />
  546. <Divider type='vertical' className='h-3.5 mx-3' />
  547. <DisplayToggle isCollapsed={isCollapsed} toggleCollapsed={() => setIsCollapsed(!isCollapsed)} />
  548. </div>}
  549. {/* Segment list */}
  550. {
  551. isFullDocMode
  552. ? <div className={cn(
  553. 'flex flex-col grow overflow-x-hidden',
  554. (isLoadingSegmentList || isLoadingChildSegmentList) ? 'overflow-y-hidden' : 'overflow-y-auto',
  555. )}>
  556. <SegmentCard
  557. detail={segments[0]}
  558. onClick={() => onClickCard(segments[0])}
  559. loading={isLoadingSegmentList}
  560. focused={{
  561. segmentIndex: currSegment?.segInfo?.id === segments[0]?.id,
  562. segmentContent: currSegment?.segInfo?.id === segments[0]?.id,
  563. }}
  564. />
  565. <ChildSegmentList
  566. parentChunkId={segments[0]?.id}
  567. onDelete={onDeleteChildChunk}
  568. childChunks={childSegments}
  569. handleInputChange={handleInputChange}
  570. handleAddNewChildChunk={handleAddNewChildChunk}
  571. onClickSlice={onClickSlice}
  572. enabled={!archived}
  573. total={childChunkListData?.total || 0}
  574. inputValue={inputValue}
  575. onClearFilter={onClearFilter}
  576. isLoading={isLoadingSegmentList || isLoadingChildSegmentList}
  577. />
  578. </div>
  579. : <SegmentList
  580. ref={segmentListRef}
  581. embeddingAvailable={embeddingAvailable}
  582. isLoading={isLoadingSegmentList}
  583. items={segments}
  584. selectedSegmentIds={selectedSegmentIds}
  585. onSelected={onSelected}
  586. onChangeSwitch={onChangeSwitch}
  587. onDelete={onDelete}
  588. onClick={onClickCard}
  589. archived={archived}
  590. onDeleteChildChunk={onDeleteChildChunk}
  591. handleAddNewChildChunk={handleAddNewChildChunk}
  592. onClickSlice={onClickSlice}
  593. onClearFilter={onClearFilter}
  594. />
  595. }
  596. {/* Pagination */}
  597. <Divider type='horizontal' className='w-auto h-[1px] my-0 mx-6 bg-divider-subtle' />
  598. <Pagination
  599. current={currentPage - 1}
  600. onChange={cur => setCurrentPage(cur + 1)}
  601. total={(isFullDocMode ? childChunkListData?.total : segmentListData?.total) || 0}
  602. limit={limit}
  603. onLimitChange={limit => setLimit(limit)}
  604. className={isFullDocMode ? 'px-3' : ''}
  605. />
  606. {/* Edit or view segment detail */}
  607. <FullScreenDrawer
  608. isOpen={currSegment.showModal}
  609. fullScreen={fullScreen}
  610. onClose={onCloseSegmentDetail}
  611. >
  612. <SegmentDetail
  613. segInfo={currSegment.segInfo ?? { id: '' }}
  614. docForm={docForm}
  615. isEditMode={currSegment.isEditMode}
  616. onUpdate={handleUpdateSegment}
  617. onCancel={onCloseSegmentDetail}
  618. />
  619. </FullScreenDrawer>
  620. {/* Create New Segment */}
  621. <FullScreenDrawer
  622. isOpen={showNewSegmentModal}
  623. fullScreen={fullScreen}
  624. onClose={onCloseNewSegmentModal}
  625. >
  626. <NewSegment
  627. docForm={docForm}
  628. onCancel={onCloseNewSegmentModal}
  629. onSave={resetList}
  630. viewNewlyAddedChunk={viewNewlyAddedChunk}
  631. />
  632. </FullScreenDrawer>
  633. {/* Edit or view child segment detail */}
  634. <FullScreenDrawer
  635. isOpen={currChildChunk.showModal}
  636. fullScreen={fullScreen}
  637. onClose={onCloseChildSegmentDetail}
  638. >
  639. <ChildSegmentDetail
  640. chunkId={currChunkId}
  641. childChunkInfo={currChildChunk.childChunkInfo ?? { id: '' }}
  642. docForm={docForm}
  643. onUpdate={handleUpdateChildChunk}
  644. onCancel={onCloseChildSegmentDetail}
  645. />
  646. </FullScreenDrawer>
  647. {/* Create New Child Segment */}
  648. <FullScreenDrawer
  649. isOpen={showNewChildSegmentModal}
  650. fullScreen={fullScreen}
  651. onClose={onCloseNewChildChunkModal}
  652. >
  653. <NewChildSegment
  654. chunkId={currChunkId}
  655. onCancel={onCloseNewChildChunkModal}
  656. onSave={onSaveNewChildChunk}
  657. viewNewlyAddedChildChunk={viewNewlyAddedChildChunk}
  658. />
  659. </FullScreenDrawer>
  660. {/* Batch Action Buttons */}
  661. {selectedSegmentIds.length > 0
  662. && <BatchAction
  663. className='absolute left-0 bottom-16 z-20'
  664. selectedIds={selectedSegmentIds}
  665. onBatchEnable={onChangeSwitch.bind(null, true, '')}
  666. onBatchDisable={onChangeSwitch.bind(null, false, '')}
  667. onBatchDelete={onDelete.bind(null, '')}
  668. onCancel={onCancelBatchOperation}
  669. />}
  670. </SegmentListContext.Provider>
  671. )
  672. }
  673. export default Completed