index.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  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 { mutateAsync: enableSegment } = useEnableSegment()
  211. const { mutateAsync: disableSegment } = useDisableSegment()
  212. const onChangeSwitch = useCallback(async (enable: boolean, segId?: string) => {
  213. const operationApi = enable ? enableSegment : disableSegment
  214. await operationApi({ datasetId, documentId, segmentIds: segId ? [segId] : selectedSegmentIds }, {
  215. onSuccess: () => {
  216. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  217. for (const seg of segments) {
  218. if (segId ? seg.id === segId : selectedSegmentIds.includes(seg.id))
  219. seg.enabled = enable
  220. }
  221. setSegments([...segments])
  222. },
  223. onError: () => {
  224. notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
  225. },
  226. })
  227. // eslint-disable-next-line react-hooks/exhaustive-deps
  228. }, [datasetId, documentId, selectedSegmentIds, segments])
  229. const { mutateAsync: deleteSegment } = useDeleteSegment()
  230. const onDelete = useCallback(async (segId?: string) => {
  231. await deleteSegment({ datasetId, documentId, segmentIds: segId ? [segId] : selectedSegmentIds }, {
  232. onSuccess: () => {
  233. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  234. resetList()
  235. !segId && setSelectedSegmentIds([])
  236. },
  237. onError: () => {
  238. notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
  239. },
  240. })
  241. // eslint-disable-next-line react-hooks/exhaustive-deps
  242. }, [datasetId, documentId, selectedSegmentIds])
  243. const { mutateAsync: updateSegment } = useUpdateSegment()
  244. const handleUpdateSegment = useCallback(async (
  245. segmentId: string,
  246. question: string,
  247. answer: string,
  248. keywords: string[],
  249. needRegenerate = false,
  250. ) => {
  251. const params: SegmentUpdater = { content: '' }
  252. if (docForm === ChunkingMode.qa) {
  253. if (!question.trim())
  254. return notify({ type: 'error', message: t('datasetDocuments.segment.questionEmpty') })
  255. if (!answer.trim())
  256. return notify({ type: 'error', message: t('datasetDocuments.segment.answerEmpty') })
  257. params.content = question
  258. params.answer = answer
  259. }
  260. else {
  261. if (!question.trim())
  262. return notify({ type: 'error', message: t('datasetDocuments.segment.contentEmpty') })
  263. params.content = question
  264. }
  265. if (keywords.length)
  266. params.keywords = keywords
  267. if (needRegenerate)
  268. params.regenerate_child_chunks = needRegenerate
  269. eventEmitter?.emit('update-segment')
  270. await updateSegment({ datasetId, documentId, segmentId, body: params }, {
  271. onSuccess(res) {
  272. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  273. if (!needRegenerate)
  274. onCloseSegmentDetail()
  275. for (const seg of segments) {
  276. if (seg.id === segmentId) {
  277. seg.answer = res.data.answer
  278. seg.content = res.data.content
  279. seg.keywords = res.data.keywords
  280. seg.word_count = res.data.word_count
  281. seg.hit_count = res.data.hit_count
  282. seg.enabled = res.data.enabled
  283. seg.updated_at = res.data.updated_at
  284. seg.child_chunks = res.data.child_chunks
  285. }
  286. }
  287. setSegments([...segments])
  288. eventEmitter?.emit('update-segment-success')
  289. },
  290. onSettled() {
  291. eventEmitter?.emit('update-segment-done')
  292. },
  293. })
  294. // eslint-disable-next-line react-hooks/exhaustive-deps
  295. }, [segments, datasetId, documentId])
  296. useEffect(() => {
  297. if (importStatus === ProcessStatus.COMPLETED)
  298. resetList()
  299. }, [importStatus, resetList])
  300. const onCancelBatchOperation = useCallback(() => {
  301. setSelectedSegmentIds([])
  302. }, [])
  303. const onSelected = useCallback((segId: string) => {
  304. setSelectedSegmentIds(prev =>
  305. prev.includes(segId)
  306. ? prev.filter(id => id !== segId)
  307. : [...prev, segId],
  308. )
  309. }, [])
  310. const isAllSelected = useMemo(() => {
  311. return segments.length > 0 && segments.every(seg => selectedSegmentIds.includes(seg.id))
  312. }, [segments, selectedSegmentIds])
  313. const isSomeSelected = useMemo(() => {
  314. return segments.some(seg => selectedSegmentIds.includes(seg.id))
  315. }, [segments, selectedSegmentIds])
  316. const onSelectedAll = useCallback(() => {
  317. setSelectedSegmentIds((prev) => {
  318. const currentAllSegIds = segments.map(seg => seg.id)
  319. const prevSelectedIds = prev.filter(item => !currentAllSegIds.includes(item))
  320. return [...prevSelectedIds, ...((isAllSelected || selectedSegmentIds.length > 0) ? [] : currentAllSegIds)]
  321. })
  322. }, [segments, isAllSelected, selectedSegmentIds])
  323. const totalText = useMemo(() => {
  324. const isSearch = searchValue !== '' || selectedStatus !== 'all'
  325. if (!isSearch) {
  326. const total = segmentListData?.total ? formatNumber(segmentListData.total) : '--'
  327. const count = total === '--' ? 0 : segmentListData!.total
  328. const translationKey = (mode === 'hierarchical' && parentMode === 'paragraph')
  329. ? 'datasetDocuments.segment.parentChunks'
  330. : 'datasetDocuments.segment.chunks'
  331. return `${total} ${t(translationKey, { count })}`
  332. }
  333. else {
  334. const total = typeof segmentListData?.total === 'number' ? formatNumber(segmentListData.total) : 0
  335. const count = segmentListData?.total || 0
  336. return `${total} ${t('datasetDocuments.segment.searchResults', { count })}`
  337. }
  338. // eslint-disable-next-line react-hooks/exhaustive-deps
  339. }, [segmentListData?.total, mode, parentMode, searchValue, selectedStatus])
  340. const toggleFullScreen = useCallback(() => {
  341. setFullScreen(!fullScreen)
  342. }, [fullScreen])
  343. const viewNewlyAddedChunk = useCallback(async () => {
  344. const totalPages = segmentListData?.total_pages || 0
  345. const total = segmentListData?.total || 0
  346. const newPage = Math.ceil((total + 1) / limit)
  347. needScrollToBottom.current = true
  348. if (newPage > totalPages) {
  349. setCurrentPage(totalPages + 1)
  350. }
  351. else {
  352. resetList()
  353. currentPage !== totalPages && setCurrentPage(totalPages)
  354. }
  355. // eslint-disable-next-line react-hooks/exhaustive-deps
  356. }, [segmentListData, limit, currentPage])
  357. const { mutateAsync: deleteChildSegment } = useDeleteChildSegment()
  358. const onDeleteChildChunk = useCallback(async (segmentId: string, childChunkId: string) => {
  359. await deleteChildSegment(
  360. { datasetId, documentId, segmentId, childChunkId },
  361. {
  362. onSuccess: () => {
  363. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  364. if (parentMode === 'paragraph')
  365. resetList()
  366. else
  367. resetChildList()
  368. },
  369. onError: () => {
  370. notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
  371. },
  372. },
  373. )
  374. // eslint-disable-next-line react-hooks/exhaustive-deps
  375. }, [datasetId, documentId, parentMode])
  376. const handleAddNewChildChunk = useCallback((parentChunkId: string) => {
  377. setShowNewChildSegmentModal(true)
  378. setCurrChunkId(parentChunkId)
  379. }, [])
  380. const onSaveNewChildChunk = useCallback((newChildChunk?: ChildChunkDetail) => {
  381. if (parentMode === 'paragraph') {
  382. for (const seg of segments) {
  383. if (seg.id === currChunkId)
  384. seg.child_chunks?.push(newChildChunk!)
  385. }
  386. setSegments([...segments])
  387. }
  388. else {
  389. resetChildList()
  390. }
  391. // eslint-disable-next-line react-hooks/exhaustive-deps
  392. }, [parentMode, currChunkId, segments])
  393. const viewNewlyAddedChildChunk = useCallback(() => {
  394. const totalPages = childChunkListData?.total_pages || 0
  395. const total = childChunkListData?.total || 0
  396. const newPage = Math.ceil((total + 1) / limit)
  397. needScrollToBottom.current = true
  398. if (newPage > totalPages) {
  399. setCurrentPage(totalPages + 1)
  400. }
  401. else {
  402. resetChildList()
  403. currentPage !== totalPages && setCurrentPage(totalPages)
  404. }
  405. // eslint-disable-next-line react-hooks/exhaustive-deps
  406. }, [childChunkListData, limit, currentPage])
  407. const onClickSlice = useCallback((detail: ChildChunkDetail) => {
  408. setCurrChildChunk({ childChunkInfo: detail, showModal: true })
  409. setCurrChunkId(detail.segment_id)
  410. }, [])
  411. const onCloseChildSegmentDetail = useCallback(() => {
  412. setCurrChildChunk({ showModal: false })
  413. setFullScreen(false)
  414. }, [])
  415. const { mutateAsync: updateChildSegment } = useUpdateChildSegment()
  416. const handleUpdateChildChunk = useCallback(async (
  417. segmentId: string,
  418. childChunkId: string,
  419. content: string,
  420. ) => {
  421. const params: SegmentUpdater = { content: '' }
  422. if (!content.trim())
  423. return notify({ type: 'error', message: t('datasetDocuments.segment.contentEmpty') })
  424. params.content = content
  425. eventEmitter?.emit('update-child-segment')
  426. await updateChildSegment({ datasetId, documentId, segmentId, childChunkId, body: params }, {
  427. onSuccess: (res) => {
  428. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  429. onCloseChildSegmentDetail()
  430. if (parentMode === 'paragraph') {
  431. for (const seg of segments) {
  432. if (seg.id === segmentId) {
  433. for (const childSeg of seg.child_chunks!) {
  434. if (childSeg.id === childChunkId) {
  435. childSeg.content = res.data.content
  436. childSeg.type = res.data.type
  437. childSeg.word_count = res.data.word_count
  438. childSeg.updated_at = res.data.updated_at
  439. }
  440. }
  441. }
  442. }
  443. setSegments([...segments])
  444. }
  445. else {
  446. for (const childSeg of childSegments) {
  447. if (childSeg.id === childChunkId) {
  448. childSeg.content = res.data.content
  449. childSeg.type = res.data.type
  450. childSeg.word_count = res.data.word_count
  451. childSeg.updated_at = res.data.updated_at
  452. }
  453. }
  454. setChildSegments([...childSegments])
  455. }
  456. },
  457. onSettled: () => {
  458. eventEmitter?.emit('update-child-segment-done')
  459. },
  460. })
  461. // eslint-disable-next-line react-hooks/exhaustive-deps
  462. }, [segments, childSegments, datasetId, documentId, parentMode])
  463. const onClearFilter = useCallback(() => {
  464. setInputValue('')
  465. setSearchValue('')
  466. setSelectedStatus('all')
  467. setCurrentPage(1)
  468. }, [])
  469. return (
  470. <SegmentListContext.Provider value={{
  471. isCollapsed,
  472. fullScreen,
  473. toggleFullScreen,
  474. currSegment,
  475. currChildChunk,
  476. }}>
  477. {/* Menu Bar */}
  478. {!isFullDocMode && <div className={s.docSearchWrapper}>
  479. <Checkbox
  480. className='shrink-0'
  481. checked={isAllSelected}
  482. mixed={!isAllSelected && isSomeSelected}
  483. onCheck={onSelectedAll}
  484. disabled={isLoadingSegmentList}
  485. />
  486. <div className={'system-sm-semibold-uppercase pl-5 text-text-secondary flex-1'}>{totalText}</div>
  487. <SimpleSelect
  488. onSelect={onChangeStatus}
  489. items={statusList.current}
  490. defaultValue={'all'}
  491. className={s.select}
  492. wrapperClassName='h-fit mr-2'
  493. optionWrapClassName='w-[160px]'
  494. optionClassName='p-0'
  495. renderOption={({ item, selected }) => <StatusItem item={item} selected={selected} />}
  496. />
  497. <Input
  498. showLeftIcon
  499. showClearIcon
  500. wrapperClassName='!w-52'
  501. value={inputValue}
  502. onChange={e => handleInputChange(e.target.value)}
  503. onClear={() => handleInputChange('')}
  504. />
  505. <Divider type='vertical' className='h-3.5 mx-3' />
  506. <DisplayToggle isCollapsed={isCollapsed} toggleCollapsed={() => setIsCollapsed(!isCollapsed)} />
  507. </div>}
  508. {/* Segment list */}
  509. {
  510. isFullDocMode
  511. ? <div className={cn(
  512. 'flex flex-col grow overflow-x-hidden',
  513. (isLoadingSegmentList || isLoadingChildSegmentList) ? 'overflow-y-hidden' : 'overflow-y-auto',
  514. )}>
  515. <SegmentCard
  516. detail={segments[0]}
  517. onClick={() => onClickCard(segments[0])}
  518. loading={isLoadingSegmentList}
  519. focused={{
  520. segmentIndex: currSegment?.segInfo?.id === segments[0]?.id,
  521. segmentContent: currSegment?.segInfo?.id === segments[0]?.id,
  522. }}
  523. />
  524. <ChildSegmentList
  525. parentChunkId={segments[0]?.id}
  526. onDelete={onDeleteChildChunk}
  527. childChunks={childSegments}
  528. handleInputChange={handleInputChange}
  529. handleAddNewChildChunk={handleAddNewChildChunk}
  530. onClickSlice={onClickSlice}
  531. enabled={!archived}
  532. total={childChunkListData?.total || 0}
  533. inputValue={inputValue}
  534. onClearFilter={onClearFilter}
  535. isLoading={isLoadingSegmentList || isLoadingChildSegmentList}
  536. />
  537. </div>
  538. : <SegmentList
  539. ref={segmentListRef}
  540. embeddingAvailable={embeddingAvailable}
  541. isLoading={isLoadingSegmentList}
  542. items={segments}
  543. selectedSegmentIds={selectedSegmentIds}
  544. onSelected={onSelected}
  545. onChangeSwitch={onChangeSwitch}
  546. onDelete={onDelete}
  547. onClick={onClickCard}
  548. archived={archived}
  549. onDeleteChildChunk={onDeleteChildChunk}
  550. handleAddNewChildChunk={handleAddNewChildChunk}
  551. onClickSlice={onClickSlice}
  552. onClearFilter={onClearFilter}
  553. />
  554. }
  555. {/* Pagination */}
  556. <Divider type='horizontal' className='w-auto h-[1px] my-0 mx-6 bg-divider-subtle' />
  557. <Pagination
  558. current={currentPage - 1}
  559. onChange={cur => setCurrentPage(cur + 1)}
  560. total={(isFullDocMode ? childChunkListData?.total : segmentListData?.total) || 0}
  561. limit={limit}
  562. onLimitChange={limit => setLimit(limit)}
  563. className={isFullDocMode ? 'px-3' : ''}
  564. />
  565. {/* Edit or view segment detail */}
  566. <FullScreenDrawer
  567. isOpen={currSegment.showModal}
  568. fullScreen={fullScreen}
  569. >
  570. <SegmentDetail
  571. segInfo={currSegment.segInfo ?? { id: '' }}
  572. docForm={docForm}
  573. isEditMode={currSegment.isEditMode}
  574. onUpdate={handleUpdateSegment}
  575. onCancel={onCloseSegmentDetail}
  576. />
  577. </FullScreenDrawer>
  578. {/* Create New Segment */}
  579. <FullScreenDrawer
  580. isOpen={showNewSegmentModal}
  581. fullScreen={fullScreen}
  582. >
  583. <NewSegment
  584. docForm={docForm}
  585. onCancel={() => {
  586. onNewSegmentModalChange(false)
  587. setFullScreen(false)
  588. }}
  589. onSave={resetList}
  590. viewNewlyAddedChunk={viewNewlyAddedChunk}
  591. />
  592. </FullScreenDrawer>
  593. {/* Edit or view child segment detail */}
  594. <FullScreenDrawer
  595. isOpen={currChildChunk.showModal}
  596. fullScreen={fullScreen}
  597. >
  598. <ChildSegmentDetail
  599. chunkId={currChunkId}
  600. childChunkInfo={currChildChunk.childChunkInfo ?? { id: '' }}
  601. docForm={docForm}
  602. onUpdate={handleUpdateChildChunk}
  603. onCancel={onCloseChildSegmentDetail}
  604. />
  605. </FullScreenDrawer>
  606. {/* Create New Child Segment */}
  607. <FullScreenDrawer
  608. isOpen={showNewChildSegmentModal}
  609. fullScreen={fullScreen}
  610. >
  611. <NewChildSegment
  612. chunkId={currChunkId}
  613. onCancel={() => {
  614. setShowNewChildSegmentModal(false)
  615. setFullScreen(false)
  616. }}
  617. onSave={onSaveNewChildChunk}
  618. viewNewlyAddedChildChunk={viewNewlyAddedChildChunk}
  619. />
  620. </FullScreenDrawer>
  621. {/* Batch Action Buttons */}
  622. {selectedSegmentIds.length > 0
  623. && <BatchAction
  624. className='absolute left-0 bottom-16 z-20'
  625. selectedIds={selectedSegmentIds}
  626. onBatchEnable={onChangeSwitch.bind(null, true, '')}
  627. onBatchDisable={onChangeSwitch.bind(null, false, '')}
  628. onBatchDelete={onDelete.bind(null, '')}
  629. onCancel={onCancelBatchOperation}
  630. />}
  631. </SegmentListContext.Provider>
  632. )
  633. }
  634. export default Completed