index.tsx 25 KB

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