index.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { memo, useEffect, useMemo, useState } 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 { debounce, isNil, omitBy } from 'lodash-es'
  8. import cn from 'classnames'
  9. import { StatusItem } from '../../list'
  10. import { DocumentContext } from '../index'
  11. import { ProcessStatus } from '../segment-add'
  12. import s from './style.module.css'
  13. import InfiniteVirtualList from './InfiniteVirtualList'
  14. import { formatNumber } from '@/utils/format'
  15. import Modal from '@/app/components/base/modal'
  16. import Switch from '@/app/components/base/switch'
  17. import Divider from '@/app/components/base/divider'
  18. import Input from '@/app/components/base/input'
  19. import { ToastContext } from '@/app/components/base/toast'
  20. import type { Item } from '@/app/components/base/select'
  21. import { SimpleSelect } from '@/app/components/base/select'
  22. import { deleteSegment, disableSegment, enableSegment, fetchSegments, updateSegment } from '@/service/datasets'
  23. import type { SegmentDetailModel, SegmentUpdator, SegmentsQuery, SegmentsResponse } from '@/models/datasets'
  24. import { asyncRunSafe } from '@/utils'
  25. import type { CommonResponse } from '@/models/common'
  26. import { Edit03, XClose } from '@/app/components/base/icons/src/vender/line/general'
  27. import AutoHeightTextarea from '@/app/components/base/auto-height-textarea/common'
  28. import Button from '@/app/components/base/button'
  29. import NewSegmentModal from '@/app/components/datasets/documents/detail/new-segment-modal'
  30. import TagInput from '@/app/components/base/tag-input'
  31. import { useEventEmitterContextContext } from '@/context/event-emitter'
  32. export const SegmentIndexTag: FC<{ positionId: string | number; className?: string }> = ({ positionId, className }) => {
  33. const localPositionId = useMemo(() => {
  34. const positionIdStr = String(positionId)
  35. if (positionIdStr.length >= 3)
  36. return positionId
  37. return positionIdStr.padStart(3, '0')
  38. }, [positionId])
  39. return (
  40. <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 ?? ''}`}>
  41. <HashtagIcon className='w-3 h-3 text-gray-400 fill-current mr-1 stroke-current stroke-1' />
  42. {localPositionId}
  43. </div>
  44. )
  45. }
  46. type ISegmentDetailProps = {
  47. segInfo?: Partial<SegmentDetailModel> & { id: string }
  48. onChangeSwitch?: (segId: string, enabled: boolean) => Promise<void>
  49. onUpdate: (segmentId: string, q: string, a: string, k: string[]) => void
  50. onCancel: () => void
  51. archived?: boolean
  52. }
  53. /**
  54. * Show all the contents of the segment
  55. */
  56. export const SegmentDetail: FC<ISegmentDetailProps> = memo(({
  57. segInfo,
  58. archived,
  59. onChangeSwitch,
  60. onUpdate,
  61. onCancel,
  62. }) => {
  63. const { t } = useTranslation()
  64. const [isEditing, setIsEditing] = useState(false)
  65. const [question, setQuestion] = useState(segInfo?.content || '')
  66. const [answer, setAnswer] = useState(segInfo?.answer || '')
  67. const [keywords, setKeywords] = useState<string[]>(segInfo?.keywords || [])
  68. const { eventEmitter } = useEventEmitterContextContext()
  69. const [loading, setLoading] = useState(false)
  70. eventEmitter?.useSubscription((v) => {
  71. if (v === 'update-segment')
  72. setLoading(true)
  73. else
  74. setLoading(false)
  75. })
  76. const handleCancel = () => {
  77. setIsEditing(false)
  78. setQuestion(segInfo?.content || '')
  79. setAnswer(segInfo?.answer || '')
  80. setKeywords(segInfo?.keywords || [])
  81. }
  82. const handleSave = () => {
  83. onUpdate(segInfo?.id || '', question, answer, keywords)
  84. }
  85. const renderContent = () => {
  86. if (segInfo?.answer) {
  87. return (
  88. <>
  89. <div className='mb-1 text-xs font-medium text-gray-500'>QUESTION</div>
  90. <AutoHeightTextarea
  91. outerClassName='mb-4'
  92. className='leading-6 text-md text-gray-800'
  93. value={question}
  94. placeholder={t('datasetDocuments.segment.questionPlaceholder') || ''}
  95. onChange={e => setQuestion(e.target.value)}
  96. disabled={!isEditing}
  97. />
  98. <div className='mb-1 text-xs font-medium text-gray-500'>ANSWER</div>
  99. <AutoHeightTextarea
  100. outerClassName='mb-4'
  101. className='leading-6 text-md text-gray-800'
  102. value={answer}
  103. placeholder={t('datasetDocuments.segment.answerPlaceholder') || ''}
  104. onChange={e => setAnswer(e.target.value)}
  105. disabled={!isEditing}
  106. autoFocus
  107. />
  108. </>
  109. )
  110. }
  111. return (
  112. <AutoHeightTextarea
  113. className='leading-6 text-md text-gray-800'
  114. value={question}
  115. placeholder={t('datasetDocuments.segment.contentPlaceholder') || ''}
  116. onChange={e => setQuestion(e.target.value)}
  117. disabled={!isEditing}
  118. autoFocus
  119. />
  120. )
  121. }
  122. return (
  123. <div className={'flex flex-col relative'}>
  124. <div className='absolute right-0 top-0 flex items-center h-7'>
  125. {isEditing && (
  126. <>
  127. <Button
  128. className='mr-2 !h-7 !px-3 !py-[5px] text-xs font-medium text-gray-700 !rounded-md'
  129. onClick={handleCancel}>
  130. {t('common.operation.cancel')}
  131. </Button>
  132. <Button
  133. type='primary'
  134. className='!h-7 !px-3 !py-[5px] text-xs font-medium !rounded-md'
  135. onClick={handleSave}
  136. disabled={loading}
  137. >
  138. {t('common.operation.save')}
  139. </Button>
  140. </>
  141. )}
  142. {!isEditing && !archived && (
  143. <>
  144. <div className='group relative flex justify-center items-center w-6 h-6 hover:bg-gray-100 rounded-md cursor-pointer'>
  145. <div className={cn(s.editTip, 'hidden items-center absolute -top-10 px-3 h-[34px] bg-white rounded-lg whitespace-nowrap text-xs font-semibold text-gray-700 group-hover:flex')}>{t('common.operation.edit')}</div>
  146. <Edit03 className='w-4 h-4 text-gray-500' onClick={() => setIsEditing(true)} />
  147. </div>
  148. <div className='mx-3 w-[1px] h-3 bg-gray-200' />
  149. </>
  150. )}
  151. <div className='flex justify-center items-center w-6 h-6 cursor-pointer' onClick={onCancel}>
  152. <XClose className='w-4 h-4 text-gray-500' />
  153. </div>
  154. </div>
  155. <SegmentIndexTag positionId={segInfo?.position || ''} className='w-fit mt-[2px] mb-6' />
  156. <div className={s.segModalContent}>{renderContent()}</div>
  157. <div className={s.keywordTitle}>{t('datasetDocuments.segment.keywords')}</div>
  158. <div className={s.keywordWrapper}>
  159. {!segInfo?.keywords?.length
  160. ? '-'
  161. : (
  162. <TagInput
  163. items={keywords}
  164. onChange={newKeywords => setKeywords(newKeywords)}
  165. disableAdd={!isEditing}
  166. disableRemove={!isEditing || (keywords.length === 1)}
  167. />
  168. )
  169. }
  170. </div>
  171. <div className={cn(s.footer, s.numberInfo)}>
  172. <div className='flex items-center'>
  173. <div className={cn(s.commonIcon, s.typeSquareIcon)} /><span className='mr-8'>{formatNumber(segInfo?.word_count as any)} {t('datasetDocuments.segment.characters')}</span>
  174. <div className={cn(s.commonIcon, s.targetIcon)} /><span className='mr-8'>{formatNumber(segInfo?.hit_count as any)} {t('datasetDocuments.segment.hitCount')}</span>
  175. <div className={cn(s.commonIcon, s.bezierCurveIcon)} /><span className={s.hashText}>{t('datasetDocuments.segment.vectorHash')}{segInfo?.index_node_hash}</span>
  176. </div>
  177. <div className='flex items-center'>
  178. <StatusItem status={segInfo?.enabled ? 'enabled' : 'disabled'} reverse textCls='text-gray-500 text-xs' />
  179. <Divider type='vertical' className='!h-2' />
  180. <Switch
  181. size='md'
  182. defaultValue={segInfo?.enabled}
  183. onChange={async (val) => {
  184. await onChangeSwitch?.(segInfo?.id || '', val)
  185. }}
  186. disabled={archived}
  187. />
  188. </div>
  189. </div>
  190. </div>
  191. )
  192. })
  193. export const splitArray = (arr: any[], size = 3) => {
  194. if (!arr || !arr.length)
  195. return []
  196. const result = []
  197. for (let i = 0; i < arr.length; i += size)
  198. result.push(arr.slice(i, i + size))
  199. return result
  200. }
  201. type ICompletedProps = {
  202. showNewSegmentModal: boolean
  203. onNewSegmentModalChange: (state: boolean) => void
  204. importStatus: ProcessStatus | string | undefined
  205. archived?: boolean
  206. // data: Array<{}> // all/part segments
  207. }
  208. /**
  209. * Embedding done, show list of all segments
  210. * Support search and filter
  211. */
  212. const Completed: FC<ICompletedProps> = ({
  213. showNewSegmentModal,
  214. onNewSegmentModalChange,
  215. importStatus,
  216. archived,
  217. }) => {
  218. const { t } = useTranslation()
  219. const { notify } = useContext(ToastContext)
  220. const { datasetId = '', documentId = '', docForm } = useContext(DocumentContext)
  221. // the current segment id and whether to show the modal
  222. const [currSegment, setCurrSegment] = useState<{ segInfo?: SegmentDetailModel; showModal: boolean }>({ showModal: false })
  223. const [searchValue, setSearchValue] = useState() // the search value
  224. const [selectedStatus, setSelectedStatus] = useState<boolean | 'all'>('all') // the selected status, enabled/disabled/undefined
  225. const [lastSegmentsRes, setLastSegmentsRes] = useState<SegmentsResponse | undefined>(undefined)
  226. const [allSegments, setAllSegments] = useState<Array<SegmentDetailModel[]>>([]) // all segments data
  227. const [loading, setLoading] = useState(false)
  228. const [total, setTotal] = useState<number | undefined>()
  229. const { eventEmitter } = useEventEmitterContextContext()
  230. const onChangeStatus = ({ value }: Item) => {
  231. setSelectedStatus(value === 'all' ? 'all' : !!value)
  232. }
  233. const getSegments = async (needLastId?: boolean) => {
  234. const finalLastId = lastSegmentsRes?.data?.[lastSegmentsRes.data.length - 1]?.id || ''
  235. setLoading(true)
  236. const [e, res] = await asyncRunSafe<SegmentsResponse>(fetchSegments({
  237. datasetId,
  238. documentId,
  239. params: omitBy({
  240. last_id: !needLastId ? undefined : finalLastId,
  241. limit: 12,
  242. keyword: searchValue,
  243. enabled: selectedStatus === 'all' ? 'all' : !!selectedStatus,
  244. }, isNil) as SegmentsQuery,
  245. }) as Promise<SegmentsResponse>)
  246. if (!e) {
  247. setAllSegments([...(!needLastId ? [] : allSegments), ...splitArray(res.data || [])])
  248. setLastSegmentsRes(res)
  249. if (!lastSegmentsRes || !needLastId)
  250. setTotal(res?.total || 0)
  251. }
  252. setLoading(false)
  253. }
  254. const resetList = () => {
  255. setLastSegmentsRes(undefined)
  256. setAllSegments([])
  257. setLoading(false)
  258. setTotal(undefined)
  259. getSegments(false)
  260. }
  261. const onClickCard = (detail: SegmentDetailModel) => {
  262. setCurrSegment({ segInfo: detail, showModal: true })
  263. }
  264. const onCloseModal = () => {
  265. setCurrSegment({ ...currSegment, showModal: false })
  266. }
  267. const onChangeSwitch = async (segId: string, enabled: boolean) => {
  268. const opApi = enabled ? enableSegment : disableSegment
  269. const [e] = await asyncRunSafe<CommonResponse>(opApi({ datasetId, segmentId: segId }) as Promise<CommonResponse>)
  270. if (!e) {
  271. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  272. for (const item of allSegments) {
  273. for (const seg of item) {
  274. if (seg.id === segId)
  275. seg.enabled = enabled
  276. }
  277. }
  278. setAllSegments([...allSegments])
  279. }
  280. else {
  281. notify({ type: 'error', message: t('common.actionMsg.modificationFailed') })
  282. }
  283. }
  284. const onDelete = async (segId: string) => {
  285. const [e] = await asyncRunSafe<CommonResponse>(deleteSegment({ datasetId, documentId, segmentId: segId }) as Promise<CommonResponse>)
  286. if (!e) {
  287. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  288. resetList()
  289. }
  290. else {
  291. notify({ type: 'error', message: t('common.actionMsg.modificationFailed') })
  292. }
  293. }
  294. const handleUpdateSegment = async (segmentId: string, question: string, answer: string, keywords: string[]) => {
  295. const params: SegmentUpdator = { content: '' }
  296. if (docForm === 'qa_model') {
  297. if (!question.trim())
  298. return notify({ type: 'error', message: t('datasetDocuments.segment.questionEmpty') })
  299. if (!answer.trim())
  300. return notify({ type: 'error', message: t('datasetDocuments.segment.answerEmpty') })
  301. params.content = question
  302. params.answer = answer
  303. }
  304. else {
  305. if (!question.trim())
  306. return notify({ type: 'error', message: t('datasetDocuments.segment.contentEmpty') })
  307. params.content = question
  308. }
  309. if (keywords.length)
  310. params.keywords = keywords
  311. try {
  312. eventEmitter?.emit('update-segment')
  313. const res = await updateSegment({ datasetId, documentId, segmentId, body: params })
  314. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  315. onCloseModal()
  316. for (const item of allSegments) {
  317. for (const seg of item) {
  318. if (seg.id === segmentId) {
  319. seg.answer = res.data.answer
  320. seg.content = res.data.content
  321. seg.keywords = res.data.keywords
  322. seg.word_count = res.data.word_count
  323. seg.hit_count = res.data.hit_count
  324. seg.index_node_hash = res.data.index_node_hash
  325. seg.enabled = res.data.enabled
  326. }
  327. }
  328. }
  329. setAllSegments([...allSegments])
  330. }
  331. finally {
  332. eventEmitter?.emit('')
  333. }
  334. }
  335. useEffect(() => {
  336. if (lastSegmentsRes !== undefined)
  337. getSegments(false)
  338. }, [selectedStatus, searchValue])
  339. useEffect(() => {
  340. if (importStatus === ProcessStatus.COMPLETED)
  341. resetList()
  342. }, [importStatus])
  343. return (
  344. <>
  345. <div className={s.docSearchWrapper}>
  346. <div className={s.totalText}>{total ? formatNumber(total) : '--'} {t('datasetDocuments.segment.paragraphs')}</div>
  347. <SimpleSelect
  348. onSelect={onChangeStatus}
  349. items={[
  350. { value: 'all', name: t('datasetDocuments.list.index.all') },
  351. { value: 0, name: t('datasetDocuments.list.status.disabled') },
  352. { value: 1, name: t('datasetDocuments.list.status.enabled') },
  353. ]}
  354. defaultValue={'all'}
  355. className={s.select}
  356. wrapperClassName='h-fit w-[120px] mr-2' />
  357. <Input showPrefix wrapperClassName='!w-52' className='!h-8' onChange={debounce(setSearchValue, 500)} />
  358. </div>
  359. <InfiniteVirtualList
  360. hasNextPage={lastSegmentsRes?.has_more ?? true}
  361. isNextPageLoading={loading}
  362. items={allSegments}
  363. loadNextPage={getSegments}
  364. onChangeSwitch={onChangeSwitch}
  365. onDelete={onDelete}
  366. onClick={onClickCard}
  367. archived={archived}
  368. />
  369. <Modal isShow={currSegment.showModal} onClose={() => {}} className='!max-w-[640px] !overflow-visible'>
  370. <SegmentDetail
  371. segInfo={currSegment.segInfo ?? { id: '' }}
  372. onChangeSwitch={onChangeSwitch}
  373. onUpdate={handleUpdateSegment}
  374. onCancel={onCloseModal}
  375. archived={archived}
  376. />
  377. </Modal>
  378. <NewSegmentModal
  379. isShow={showNewSegmentModal}
  380. docForm={docForm}
  381. onCancel={() => onNewSegmentModalChange(false)}
  382. onSave={resetList}
  383. />
  384. </>
  385. )
  386. }
  387. export default Completed