index.tsx 24 KB

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