index.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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.sign_content = res.data.sign_content
  322. seg.keywords = res.data.keywords
  323. seg.word_count = res.data.word_count
  324. seg.hit_count = res.data.hit_count
  325. seg.enabled = res.data.enabled
  326. seg.updated_at = res.data.updated_at
  327. seg.child_chunks = res.data.child_chunks
  328. }
  329. }
  330. setSegments([...segments])
  331. refreshChunkListDataWithDetailChanged()
  332. eventEmitter?.emit('update-segment-success')
  333. },
  334. onSettled() {
  335. eventEmitter?.emit('update-segment-done')
  336. },
  337. })
  338. // eslint-disable-next-line react-hooks/exhaustive-deps
  339. }, [segments, datasetId, documentId])
  340. useEffect(() => {
  341. resetList()
  342. }, [pathname])
  343. useEffect(() => {
  344. if (importStatus === ProcessStatus.COMPLETED)
  345. resetList()
  346. }, [importStatus, resetList])
  347. const onCancelBatchOperation = useCallback(() => {
  348. setSelectedSegmentIds([])
  349. }, [])
  350. const onSelected = useCallback((segId: string) => {
  351. setSelectedSegmentIds(prev =>
  352. prev.includes(segId)
  353. ? prev.filter(id => id !== segId)
  354. : [...prev, segId],
  355. )
  356. }, [])
  357. const isAllSelected = useMemo(() => {
  358. return segments.length > 0 && segments.every(seg => selectedSegmentIds.includes(seg.id))
  359. }, [segments, selectedSegmentIds])
  360. const isSomeSelected = useMemo(() => {
  361. return segments.some(seg => selectedSegmentIds.includes(seg.id))
  362. }, [segments, selectedSegmentIds])
  363. const onSelectedAll = useCallback(() => {
  364. setSelectedSegmentIds((prev) => {
  365. const currentAllSegIds = segments.map(seg => seg.id)
  366. const prevSelectedIds = prev.filter(item => !currentAllSegIds.includes(item))
  367. return [...prevSelectedIds, ...((isAllSelected || selectedSegmentIds.length > 0) ? [] : currentAllSegIds)]
  368. })
  369. }, [segments, isAllSelected, selectedSegmentIds])
  370. const totalText = useMemo(() => {
  371. const isSearch = searchValue !== '' || selectedStatus !== 'all'
  372. if (!isSearch) {
  373. const total = segmentListData?.total ? formatNumber(segmentListData.total) : '--'
  374. const count = total === '--' ? 0 : segmentListData!.total
  375. const translationKey = (mode === 'hierarchical' && parentMode === 'paragraph')
  376. ? 'datasetDocuments.segment.parentChunks'
  377. : 'datasetDocuments.segment.chunks'
  378. return `${total} ${t(translationKey, { count })}`
  379. }
  380. else {
  381. const total = typeof segmentListData?.total === 'number' ? formatNumber(segmentListData.total) : 0
  382. const count = segmentListData?.total || 0
  383. return `${total} ${t('datasetDocuments.segment.searchResults', { count })}`
  384. }
  385. // eslint-disable-next-line react-hooks/exhaustive-deps
  386. }, [segmentListData?.total, mode, parentMode, searchValue, selectedStatus])
  387. const toggleFullScreen = useCallback(() => {
  388. setFullScreen(!fullScreen)
  389. }, [fullScreen])
  390. const viewNewlyAddedChunk = useCallback(async () => {
  391. const totalPages = segmentListData?.total_pages || 0
  392. const total = segmentListData?.total || 0
  393. const newPage = Math.ceil((total + 1) / limit)
  394. needScrollToBottom.current = true
  395. if (newPage > totalPages) {
  396. setCurrentPage(totalPages + 1)
  397. }
  398. else {
  399. resetList()
  400. currentPage !== totalPages && setCurrentPage(totalPages)
  401. }
  402. // eslint-disable-next-line react-hooks/exhaustive-deps
  403. }, [segmentListData, limit, currentPage])
  404. const { mutateAsync: deleteChildSegment } = useDeleteChildSegment()
  405. const onDeleteChildChunk = useCallback(async (segmentId: string, childChunkId: string) => {
  406. await deleteChildSegment(
  407. { datasetId, documentId, segmentId, childChunkId },
  408. {
  409. onSuccess: () => {
  410. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  411. if (parentMode === 'paragraph')
  412. resetList()
  413. else
  414. resetChildList()
  415. },
  416. onError: () => {
  417. notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
  418. },
  419. },
  420. )
  421. // eslint-disable-next-line react-hooks/exhaustive-deps
  422. }, [datasetId, documentId, parentMode])
  423. const handleAddNewChildChunk = useCallback((parentChunkId: string) => {
  424. setShowNewChildSegmentModal(true)
  425. setCurrChunkId(parentChunkId)
  426. }, [])
  427. const onSaveNewChildChunk = useCallback((newChildChunk?: ChildChunkDetail) => {
  428. if (parentMode === 'paragraph') {
  429. for (const seg of segments) {
  430. if (seg.id === currChunkId)
  431. seg.child_chunks?.push(newChildChunk!)
  432. }
  433. setSegments([...segments])
  434. refreshChunkListDataWithDetailChanged()
  435. }
  436. else {
  437. resetChildList()
  438. }
  439. // eslint-disable-next-line react-hooks/exhaustive-deps
  440. }, [parentMode, currChunkId, segments])
  441. const viewNewlyAddedChildChunk = useCallback(() => {
  442. const totalPages = childChunkListData?.total_pages || 0
  443. const total = childChunkListData?.total || 0
  444. const newPage = Math.ceil((total + 1) / limit)
  445. needScrollToBottom.current = true
  446. if (newPage > totalPages) {
  447. setCurrentPage(totalPages + 1)
  448. }
  449. else {
  450. resetChildList()
  451. currentPage !== totalPages && setCurrentPage(totalPages)
  452. }
  453. // eslint-disable-next-line react-hooks/exhaustive-deps
  454. }, [childChunkListData, limit, currentPage])
  455. const onClickSlice = useCallback((detail: ChildChunkDetail) => {
  456. setCurrChildChunk({ childChunkInfo: detail, showModal: true })
  457. setCurrChunkId(detail.segment_id)
  458. }, [])
  459. const onCloseChildSegmentDetail = useCallback(() => {
  460. setCurrChildChunk({ showModal: false })
  461. setFullScreen(false)
  462. }, [])
  463. const { mutateAsync: updateChildSegment } = useUpdateChildSegment()
  464. const handleUpdateChildChunk = useCallback(async (
  465. segmentId: string,
  466. childChunkId: string,
  467. content: string,
  468. ) => {
  469. const params: SegmentUpdater = { content: '' }
  470. if (!content.trim())
  471. return notify({ type: 'error', message: t('datasetDocuments.segment.contentEmpty') })
  472. params.content = content
  473. eventEmitter?.emit('update-child-segment')
  474. await updateChildSegment({ datasetId, documentId, segmentId, childChunkId, body: params }, {
  475. onSuccess: (res) => {
  476. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  477. onCloseChildSegmentDetail()
  478. if (parentMode === 'paragraph') {
  479. for (const seg of segments) {
  480. if (seg.id === segmentId) {
  481. for (const childSeg of seg.child_chunks!) {
  482. if (childSeg.id === childChunkId) {
  483. childSeg.content = res.data.content
  484. childSeg.type = res.data.type
  485. childSeg.word_count = res.data.word_count
  486. childSeg.updated_at = res.data.updated_at
  487. }
  488. }
  489. }
  490. }
  491. setSegments([...segments])
  492. refreshChunkListDataWithDetailChanged()
  493. }
  494. else {
  495. resetChildList()
  496. }
  497. },
  498. onSettled: () => {
  499. eventEmitter?.emit('update-child-segment-done')
  500. },
  501. })
  502. // eslint-disable-next-line react-hooks/exhaustive-deps
  503. }, [segments, childSegments, datasetId, documentId, parentMode])
  504. const onClearFilter = useCallback(() => {
  505. setInputValue('')
  506. setSearchValue('')
  507. setSelectedStatus('all')
  508. setCurrentPage(1)
  509. }, [])
  510. return (
  511. <SegmentListContext.Provider value={{
  512. isCollapsed,
  513. fullScreen,
  514. toggleFullScreen,
  515. currSegment,
  516. currChildChunk,
  517. }}>
  518. {/* Menu Bar */}
  519. {!isFullDocMode && <div className={s.docSearchWrapper}>
  520. <Checkbox
  521. className='shrink-0'
  522. checked={isAllSelected}
  523. mixed={!isAllSelected && isSomeSelected}
  524. onCheck={onSelectedAll}
  525. disabled={isLoadingSegmentList}
  526. />
  527. <div className={'system-sm-semibold-uppercase pl-5 text-text-secondary flex-1'}>{totalText}</div>
  528. <SimpleSelect
  529. onSelect={onChangeStatus}
  530. items={statusList.current}
  531. defaultValue={selectedStatus === 'all' ? 'all' : selectedStatus ? 1 : 0}
  532. className={s.select}
  533. wrapperClassName='h-fit mr-2'
  534. optionWrapClassName='w-[160px]'
  535. optionClassName='p-0'
  536. renderOption={({ item, selected }) => <StatusItem item={item} selected={selected} />}
  537. notClearable
  538. />
  539. <Input
  540. showLeftIcon
  541. showClearIcon
  542. wrapperClassName='!w-52'
  543. value={inputValue}
  544. onChange={e => handleInputChange(e.target.value)}
  545. onClear={() => handleInputChange('')}
  546. />
  547. <Divider type='vertical' className='h-3.5 mx-3' />
  548. <DisplayToggle isCollapsed={isCollapsed} toggleCollapsed={() => setIsCollapsed(!isCollapsed)} />
  549. </div>}
  550. {/* Segment list */}
  551. {
  552. isFullDocMode
  553. ? <div className={cn(
  554. 'flex flex-col grow overflow-x-hidden',
  555. (isLoadingSegmentList || isLoadingChildSegmentList) ? 'overflow-y-hidden' : 'overflow-y-auto',
  556. )}>
  557. <SegmentCard
  558. detail={segments[0]}
  559. onClick={() => onClickCard(segments[0])}
  560. loading={isLoadingSegmentList}
  561. focused={{
  562. segmentIndex: currSegment?.segInfo?.id === segments[0]?.id,
  563. segmentContent: currSegment?.segInfo?.id === segments[0]?.id,
  564. }}
  565. />
  566. <ChildSegmentList
  567. parentChunkId={segments[0]?.id}
  568. onDelete={onDeleteChildChunk}
  569. childChunks={childSegments}
  570. handleInputChange={handleInputChange}
  571. handleAddNewChildChunk={handleAddNewChildChunk}
  572. onClickSlice={onClickSlice}
  573. enabled={!archived}
  574. total={childChunkListData?.total || 0}
  575. inputValue={inputValue}
  576. onClearFilter={onClearFilter}
  577. isLoading={isLoadingSegmentList || isLoadingChildSegmentList}
  578. />
  579. </div>
  580. : <SegmentList
  581. ref={segmentListRef}
  582. embeddingAvailable={embeddingAvailable}
  583. isLoading={isLoadingSegmentList}
  584. items={segments}
  585. selectedSegmentIds={selectedSegmentIds}
  586. onSelected={onSelected}
  587. onChangeSwitch={onChangeSwitch}
  588. onDelete={onDelete}
  589. onClick={onClickCard}
  590. archived={archived}
  591. onDeleteChildChunk={onDeleteChildChunk}
  592. handleAddNewChildChunk={handleAddNewChildChunk}
  593. onClickSlice={onClickSlice}
  594. onClearFilter={onClearFilter}
  595. />
  596. }
  597. {/* Pagination */}
  598. <Divider type='horizontal' className='w-auto h-[1px] my-0 mx-6 bg-divider-subtle' />
  599. <Pagination
  600. current={currentPage - 1}
  601. onChange={cur => setCurrentPage(cur + 1)}
  602. total={(isFullDocMode ? childChunkListData?.total : segmentListData?.total) || 0}
  603. limit={limit}
  604. onLimitChange={limit => setLimit(limit)}
  605. className={isFullDocMode ? 'px-3' : ''}
  606. />
  607. {/* Edit or view segment detail */}
  608. <FullScreenDrawer
  609. isOpen={currSegment.showModal}
  610. fullScreen={fullScreen}
  611. onClose={onCloseSegmentDetail}
  612. >
  613. <SegmentDetail
  614. segInfo={currSegment.segInfo ?? { id: '' }}
  615. docForm={docForm}
  616. isEditMode={currSegment.isEditMode}
  617. onUpdate={handleUpdateSegment}
  618. onCancel={onCloseSegmentDetail}
  619. />
  620. </FullScreenDrawer>
  621. {/* Create New Segment */}
  622. <FullScreenDrawer
  623. isOpen={showNewSegmentModal}
  624. fullScreen={fullScreen}
  625. onClose={onCloseNewSegmentModal}
  626. >
  627. <NewSegment
  628. docForm={docForm}
  629. onCancel={onCloseNewSegmentModal}
  630. onSave={resetList}
  631. viewNewlyAddedChunk={viewNewlyAddedChunk}
  632. />
  633. </FullScreenDrawer>
  634. {/* Edit or view child segment detail */}
  635. <FullScreenDrawer
  636. isOpen={currChildChunk.showModal}
  637. fullScreen={fullScreen}
  638. onClose={onCloseChildSegmentDetail}
  639. >
  640. <ChildSegmentDetail
  641. chunkId={currChunkId}
  642. childChunkInfo={currChildChunk.childChunkInfo ?? { id: '' }}
  643. docForm={docForm}
  644. onUpdate={handleUpdateChildChunk}
  645. onCancel={onCloseChildSegmentDetail}
  646. />
  647. </FullScreenDrawer>
  648. {/* Create New Child Segment */}
  649. <FullScreenDrawer
  650. isOpen={showNewChildSegmentModal}
  651. fullScreen={fullScreen}
  652. onClose={onCloseNewChildChunkModal}
  653. >
  654. <NewChildSegment
  655. chunkId={currChunkId}
  656. onCancel={onCloseNewChildChunkModal}
  657. onSave={onSaveNewChildChunk}
  658. viewNewlyAddedChildChunk={viewNewlyAddedChildChunk}
  659. />
  660. </FullScreenDrawer>
  661. {/* Batch Action Buttons */}
  662. {selectedSegmentIds.length > 0
  663. && <BatchAction
  664. className='absolute left-0 bottom-16 z-20'
  665. selectedIds={selectedSegmentIds}
  666. onBatchEnable={onChangeSwitch.bind(null, true, '')}
  667. onBatchDisable={onChangeSwitch.bind(null, false, '')}
  668. onBatchDelete={onDelete.bind(null, '')}
  669. onCancel={onCancelBatchOperation}
  670. />}
  671. </SegmentListContext.Provider>
  672. )
  673. }
  674. export default Completed