Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

index.tsx 25KB

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