index.tsx 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { memo, useState, useEffect, useMemo } from 'react'
  4. import { HashtagIcon } from '@heroicons/react/24/solid'
  5. import { useTranslation } from 'react-i18next'
  6. import { useContext } from 'use-context-selector'
  7. import { omitBy, isNil, debounce } from 'lodash-es'
  8. import { formatNumber } from '@/utils/format'
  9. import { StatusItem } from '../../list'
  10. import { DocumentContext } from '../index'
  11. import s from './style.module.css'
  12. import Modal from '@/app/components/base/modal'
  13. import Switch from '@/app/components/base/switch'
  14. import Divider from '@/app/components/base/divider'
  15. import Input from '@/app/components/base/input'
  16. import Loading from '@/app/components/base/loading'
  17. import { ToastContext } from '@/app/components/base/toast'
  18. import { SimpleSelect, Item } from '@/app/components/base/select'
  19. import { disableSegment, enableSegment, fetchSegments } from '@/service/datasets'
  20. import type { SegmentDetailModel, SegmentsResponse, SegmentsQuery } from '@/models/datasets'
  21. import { asyncRunSafe } from '@/utils'
  22. import type { CommonResponse } from '@/models/common'
  23. import InfiniteVirtualList from "./InfiniteVirtualList";
  24. import cn from 'classnames'
  25. export const SegmentIndexTag: FC<{ positionId: string | number; className?: string }> = ({ positionId, className }) => {
  26. const localPositionId = useMemo(() => {
  27. const positionIdStr = String(positionId)
  28. if (positionIdStr.length >= 3)
  29. return positionId
  30. return positionIdStr.padStart(3, '0')
  31. }, [positionId])
  32. return (
  33. <div className={`text-gray-500 border border-gray-200 box-border flex items-center rounded-md italic text-[11px] pl-1 pr-1.5 font-medium ${className ?? ''}`}>
  34. <HashtagIcon className='w-3 h-3 text-gray-400 fill-current mr-1 stroke-current stroke-1' />
  35. {localPositionId}
  36. </div>
  37. )
  38. }
  39. type ISegmentDetailProps = {
  40. segInfo?: Partial<SegmentDetailModel> & { id: string }
  41. onChangeSwitch?: (segId: string, enabled: boolean) => Promise<void>
  42. }
  43. /**
  44. * Show all the contents of the segment
  45. */
  46. export const SegmentDetail: FC<ISegmentDetailProps> = memo(({
  47. segInfo,
  48. onChangeSwitch }) => {
  49. const { t } = useTranslation()
  50. return (
  51. <div className={'flex flex-col'}>
  52. <SegmentIndexTag positionId={segInfo?.position || ''} className='w-fit mb-6' />
  53. <div className={s.segModalContent}>{segInfo?.content}</div>
  54. <div className={s.keywordTitle}>{t('datasetDocuments.segment.keywords')}</div>
  55. <div className={s.keywordWrapper}>
  56. {!segInfo?.keywords?.length
  57. ? '-'
  58. : segInfo?.keywords?.map((word: any) => {
  59. return <div className={s.keyword}>{word}</div>
  60. })}
  61. </div>
  62. <div className={cn(s.footer, s.numberInfo)}>
  63. <div className='flex items-center'>
  64. <div className={cn(s.commonIcon, s.typeSquareIcon)} /><span className='mr-8'>{formatNumber(segInfo?.word_count as any)} {t('datasetDocuments.segment.characters')}</span>
  65. <div className={cn(s.commonIcon, s.targetIcon)} /><span className='mr-8'>{formatNumber(segInfo?.hit_count as any)} {t('datasetDocuments.segment.hitCount')}</span>
  66. <div className={cn(s.commonIcon, s.bezierCurveIcon)} /><span className={s.hashText}>{t('datasetDocuments.segment.vectorHash')}{segInfo?.index_node_hash}</span>
  67. </div>
  68. <div className='flex items-center'>
  69. <StatusItem status={segInfo?.enabled ? 'enabled' : 'disabled'} reverse textCls='text-gray-500 text-xs' />
  70. <Divider type='vertical' className='!h-2' />
  71. <Switch
  72. size='md'
  73. defaultValue={segInfo?.enabled}
  74. onChange={async val => {
  75. await onChangeSwitch?.(segInfo?.id || '', val)
  76. }}
  77. />
  78. </div>
  79. </div>
  80. </div>
  81. )
  82. })
  83. export const splitArray = (arr: any[], size = 3) => {
  84. if (!arr || !arr.length)
  85. return []
  86. const result = []
  87. for (let i = 0; i < arr.length; i += size)
  88. result.push(arr.slice(i, i + size))
  89. return result
  90. }
  91. type ICompletedProps = {
  92. // data: Array<{}> // all/part segments
  93. }
  94. /**
  95. * Embedding done, show list of all segments
  96. * Support search and filter
  97. */
  98. const Completed: FC<ICompletedProps> = () => {
  99. const { t } = useTranslation()
  100. const { notify } = useContext(ToastContext)
  101. const { datasetId = '', documentId = '' } = useContext(DocumentContext)
  102. // the current segment id and whether to show the modal
  103. const [currSegment, setCurrSegment] = useState<{ segInfo?: SegmentDetailModel; showModal: boolean }>({ showModal: false })
  104. const [searchValue, setSearchValue] = useState() // the search value
  105. const [selectedStatus, setSelectedStatus] = useState<boolean | 'all'>('all') // the selected status, enabled/disabled/undefined
  106. const [lastSegmentsRes, setLastSegmentsRes] = useState<SegmentsResponse | undefined>(undefined)
  107. const [allSegments, setAllSegments] = useState<Array<SegmentDetailModel[]>>([]) // all segments data
  108. const [loading, setLoading] = useState(false)
  109. const [total, setTotal] = useState<number | undefined>()
  110. useEffect(() => {
  111. if (lastSegmentsRes !== undefined) {
  112. getSegments(false)
  113. }
  114. }, [selectedStatus, searchValue])
  115. const onChangeStatus = ({ value }: Item) => {
  116. setSelectedStatus(value === 'all' ? 'all' : !!value)
  117. }
  118. const getSegments = async (needLastId?: boolean) => {
  119. const finalLastId = lastSegmentsRes?.data?.[lastSegmentsRes.data.length - 1]?.id || '';
  120. setLoading(true)
  121. const [e, res] = await asyncRunSafe<SegmentsResponse>(fetchSegments({
  122. datasetId,
  123. documentId,
  124. params: omitBy({
  125. last_id: !needLastId ? undefined : finalLastId,
  126. limit: 9,
  127. keyword: searchValue,
  128. enabled: selectedStatus === 'all' ? 'all' : !!selectedStatus,
  129. }, isNil) as SegmentsQuery
  130. }) as Promise<SegmentsResponse>)
  131. if (!e) {
  132. setAllSegments([...(!needLastId ? [] : allSegments), ...splitArray(res.data || [])])
  133. setLastSegmentsRes(res)
  134. if (!lastSegmentsRes) { setTotal(res?.total || 0) }
  135. }
  136. setLoading(false)
  137. }
  138. const onClickCard = (detail: SegmentDetailModel) => {
  139. setCurrSegment({ segInfo: detail, showModal: true })
  140. }
  141. const onCloseModal = () => {
  142. setCurrSegment({ ...currSegment, showModal: false })
  143. }
  144. const onChangeSwitch = async (segId: string, enabled: boolean) => {
  145. const opApi = enabled ? enableSegment : disableSegment
  146. const [e] = await asyncRunSafe<CommonResponse>(opApi({ datasetId, segmentId: segId }) as Promise<CommonResponse>)
  147. if (!e) {
  148. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  149. for (const item of allSegments) {
  150. for (const seg of item) {
  151. if (seg.id === segId) {
  152. seg.enabled = enabled
  153. }
  154. }
  155. }
  156. setAllSegments([...allSegments])
  157. } else {
  158. notify({ type: 'error', message: t('common.actionMsg.modificationFailed') })
  159. }
  160. }
  161. return (
  162. <>
  163. <div className={s.docSearchWrapper}>
  164. <div className={s.totalText}>{total ? formatNumber(total) : '--'} {t('datasetDocuments.segment.paragraphs')}</div>
  165. <SimpleSelect
  166. onSelect={onChangeStatus}
  167. items={[
  168. { value: 'all', name: t('datasetDocuments.list.index.all') },
  169. { value: 0, name: t('datasetDocuments.list.status.disabled') },
  170. { value: 1, name: t('datasetDocuments.list.status.enabled') },
  171. ]}
  172. defaultValue={'all'}
  173. className={s.select}
  174. wrapperClassName='h-fit w-[120px] mr-2' />
  175. <Input showPrefix wrapperClassName='!w-52' className='!h-8' onChange={debounce(setSearchValue, 500)} />
  176. </div>
  177. <InfiniteVirtualList
  178. hasNextPage={lastSegmentsRes?.has_more ?? true}
  179. isNextPageLoading={loading}
  180. items={allSegments}
  181. loadNextPage={getSegments}
  182. onChangeSwitch={onChangeSwitch}
  183. onClick={onClickCard}
  184. />
  185. <Modal isShow={currSegment.showModal} onClose={onCloseModal} className='!max-w-[640px]' closable>
  186. <SegmentDetail segInfo={currSegment.segInfo ?? { id: '' }} onChangeSwitch={onChangeSwitch} />
  187. </Modal>
  188. </>
  189. )
  190. }
  191. export default Completed