index.tsx 15 KB

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