index.tsx 16 KB

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