index.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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. className='mr-2 !h-7 !px-3 !py-[5px] text-xs font-medium text-gray-700 !rounded-md'
  134. onClick={handleCancel}>
  135. {t('common.operation.cancel')}
  136. </Button>
  137. <Button
  138. variant='primary'
  139. className='!h-7 !px-3 !py-[5px] text-xs font-medium !rounded-md'
  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 [searchValue, setSearchValue] = useState<string>() // the search value
  236. const [selectedStatus, setSelectedStatus] = useState<boolean | 'all'>('all') // the selected status, enabled/disabled/undefined
  237. const [lastSegmentsRes, setLastSegmentsRes] = useState<SegmentsResponse | undefined>(undefined)
  238. const [allSegments, setAllSegments] = useState<Array<SegmentDetailModel[]>>([]) // all segments data
  239. const [loading, setLoading] = useState(false)
  240. const [total, setTotal] = useState<number | undefined>()
  241. const { eventEmitter } = useEventEmitterContextContext()
  242. const onChangeStatus = ({ value }: Item) => {
  243. setSelectedStatus(value === 'all' ? 'all' : !!value)
  244. }
  245. const getSegments = async (needLastId?: boolean) => {
  246. const finalLastId = lastSegmentsRes?.data?.[lastSegmentsRes.data.length - 1]?.id || ''
  247. setLoading(true)
  248. const [e, res] = await asyncRunSafe<SegmentsResponse>(fetchSegments({
  249. datasetId,
  250. documentId,
  251. params: omitBy({
  252. last_id: !needLastId ? undefined : finalLastId,
  253. limit: 12,
  254. keyword: searchValue,
  255. enabled: selectedStatus === 'all' ? 'all' : !!selectedStatus,
  256. }, isNil) as SegmentsQuery,
  257. }) as Promise<SegmentsResponse>)
  258. if (!e) {
  259. setAllSegments([...(!needLastId ? [] : allSegments), ...splitArray(res.data || [])])
  260. setLastSegmentsRes(res)
  261. if (!lastSegmentsRes || !needLastId)
  262. setTotal(res?.total || 0)
  263. }
  264. setLoading(false)
  265. }
  266. const resetList = () => {
  267. setLastSegmentsRes(undefined)
  268. setAllSegments([])
  269. setLoading(false)
  270. setTotal(undefined)
  271. getSegments(false)
  272. }
  273. const onClickCard = (detail: SegmentDetailModel) => {
  274. setCurrSegment({ segInfo: detail, showModal: true })
  275. }
  276. const onCloseModal = () => {
  277. setCurrSegment({ ...currSegment, showModal: false })
  278. }
  279. const onChangeSwitch = async (segId: string, enabled: boolean) => {
  280. const opApi = enabled ? enableSegment : disableSegment
  281. const [e] = await asyncRunSafe<CommonResponse>(opApi({ datasetId, segmentId: segId }) as Promise<CommonResponse>)
  282. if (!e) {
  283. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  284. for (const item of allSegments) {
  285. for (const seg of item) {
  286. if (seg.id === segId)
  287. seg.enabled = enabled
  288. }
  289. }
  290. setAllSegments([...allSegments])
  291. }
  292. else {
  293. notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
  294. }
  295. }
  296. const onDelete = async (segId: string) => {
  297. const [e] = await asyncRunSafe<CommonResponse>(deleteSegment({ datasetId, documentId, segmentId: segId }) as Promise<CommonResponse>)
  298. if (!e) {
  299. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  300. resetList()
  301. }
  302. else {
  303. notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
  304. }
  305. }
  306. const handleUpdateSegment = async (segmentId: string, question: string, answer: string, keywords: string[]) => {
  307. const params: SegmentUpdator = { content: '' }
  308. if (docForm === 'qa_model') {
  309. if (!question.trim())
  310. return notify({ type: 'error', message: t('datasetDocuments.segment.questionEmpty') })
  311. if (!answer.trim())
  312. return notify({ type: 'error', message: t('datasetDocuments.segment.answerEmpty') })
  313. params.content = question
  314. params.answer = answer
  315. }
  316. else {
  317. if (!question.trim())
  318. return notify({ type: 'error', message: t('datasetDocuments.segment.contentEmpty') })
  319. params.content = question
  320. }
  321. if (keywords.length)
  322. params.keywords = keywords
  323. try {
  324. eventEmitter?.emit('update-segment')
  325. const res = await updateSegment({ datasetId, documentId, segmentId, body: params })
  326. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  327. onCloseModal()
  328. for (const item of allSegments) {
  329. for (const seg of item) {
  330. if (seg.id === segmentId) {
  331. seg.answer = res.data.answer
  332. seg.content = res.data.content
  333. seg.keywords = res.data.keywords
  334. seg.word_count = res.data.word_count
  335. seg.hit_count = res.data.hit_count
  336. seg.index_node_hash = res.data.index_node_hash
  337. seg.enabled = res.data.enabled
  338. }
  339. }
  340. }
  341. setAllSegments([...allSegments])
  342. }
  343. finally {
  344. eventEmitter?.emit('')
  345. }
  346. }
  347. useEffect(() => {
  348. if (lastSegmentsRes !== undefined)
  349. getSegments(false)
  350. }, [selectedStatus, searchValue])
  351. useEffect(() => {
  352. if (importStatus === ProcessStatus.COMPLETED)
  353. resetList()
  354. }, [importStatus])
  355. return (
  356. <>
  357. <div className={s.docSearchWrapper}>
  358. <div className={s.totalText}>{total ? formatNumber(total) : '--'} {t('datasetDocuments.segment.paragraphs')}</div>
  359. <SimpleSelect
  360. onSelect={onChangeStatus}
  361. items={[
  362. { value: 'all', name: t('datasetDocuments.list.index.all') },
  363. { value: 0, name: t('datasetDocuments.list.status.disabled') },
  364. { value: 1, name: t('datasetDocuments.list.status.enabled') },
  365. ]}
  366. defaultValue={'all'}
  367. className={s.select}
  368. wrapperClassName='h-fit w-[120px] mr-2' />
  369. <Input showPrefix wrapperClassName='!w-52' className='!h-8' onChange={debounce(setSearchValue, 500)} />
  370. </div>
  371. <InfiniteVirtualList
  372. embeddingAvailable={embeddingAvailable}
  373. hasNextPage={lastSegmentsRes?.has_more ?? true}
  374. isNextPageLoading={loading}
  375. items={allSegments}
  376. loadNextPage={getSegments}
  377. onChangeSwitch={onChangeSwitch}
  378. onDelete={onDelete}
  379. onClick={onClickCard}
  380. archived={archived}
  381. />
  382. <Modal isShow={currSegment.showModal} onClose={() => { }} className='!max-w-[640px] !overflow-visible'>
  383. <SegmentDetail
  384. embeddingAvailable={embeddingAvailable}
  385. segInfo={currSegment.segInfo ?? { id: '' }}
  386. onChangeSwitch={onChangeSwitch}
  387. onUpdate={handleUpdateSegment}
  388. onCancel={onCloseModal}
  389. archived={archived}
  390. />
  391. </Modal>
  392. <NewSegmentModal
  393. isShow={showNewSegmentModal}
  394. docForm={docForm}
  395. onCancel={() => onNewSegmentModalChange(false)}
  396. onSave={resetList}
  397. />
  398. </>
  399. )
  400. }
  401. export default Completed