index.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. const SegmentDetailComponent: FC<ISegmentDetailProps> = ({
  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 SegmentDetail = memo(SegmentDetailComponent)
  194. export const splitArray = (arr: any[], size = 3) => {
  195. if (!arr || !arr.length)
  196. return []
  197. const result = []
  198. for (let i = 0; i < arr.length; i += size)
  199. result.push(arr.slice(i, i + size))
  200. return result
  201. }
  202. type ICompletedProps = {
  203. showNewSegmentModal: boolean
  204. onNewSegmentModalChange: (state: boolean) => void
  205. importStatus: ProcessStatus | string | undefined
  206. archived?: boolean
  207. // data: Array<{}> // all/part segments
  208. }
  209. /**
  210. * Embedding done, show list of all segments
  211. * Support search and filter
  212. */
  213. const Completed: FC<ICompletedProps> = ({
  214. showNewSegmentModal,
  215. onNewSegmentModalChange,
  216. importStatus,
  217. archived,
  218. }) => {
  219. const { t } = useTranslation()
  220. const { notify } = useContext(ToastContext)
  221. const { datasetId = '', documentId = '', docForm } = useContext(DocumentContext)
  222. // the current segment id and whether to show the modal
  223. const [currSegment, setCurrSegment] = useState<{ segInfo?: SegmentDetailModel; showModal: boolean }>({ showModal: false })
  224. const [searchValue, setSearchValue] = useState() // the search value
  225. const [selectedStatus, setSelectedStatus] = useState<boolean | 'all'>('all') // the selected status, enabled/disabled/undefined
  226. const [lastSegmentsRes, setLastSegmentsRes] = useState<SegmentsResponse | undefined>(undefined)
  227. const [allSegments, setAllSegments] = useState<Array<SegmentDetailModel[]>>([]) // all segments data
  228. const [loading, setLoading] = useState(false)
  229. const [total, setTotal] = useState<number | undefined>()
  230. const { eventEmitter } = useEventEmitterContextContext()
  231. const onChangeStatus = ({ value }: Item) => {
  232. setSelectedStatus(value === 'all' ? 'all' : !!value)
  233. }
  234. const getSegments = async (needLastId?: boolean) => {
  235. const finalLastId = lastSegmentsRes?.data?.[lastSegmentsRes.data.length - 1]?.id || ''
  236. setLoading(true)
  237. const [e, res] = await asyncRunSafe<SegmentsResponse>(fetchSegments({
  238. datasetId,
  239. documentId,
  240. params: omitBy({
  241. last_id: !needLastId ? undefined : finalLastId,
  242. limit: 12,
  243. keyword: searchValue,
  244. enabled: selectedStatus === 'all' ? 'all' : !!selectedStatus,
  245. }, isNil) as SegmentsQuery,
  246. }) as Promise<SegmentsResponse>)
  247. if (!e) {
  248. setAllSegments([...(!needLastId ? [] : allSegments), ...splitArray(res.data || [])])
  249. setLastSegmentsRes(res)
  250. if (!lastSegmentsRes || !needLastId)
  251. setTotal(res?.total || 0)
  252. }
  253. setLoading(false)
  254. }
  255. const resetList = () => {
  256. setLastSegmentsRes(undefined)
  257. setAllSegments([])
  258. setLoading(false)
  259. setTotal(undefined)
  260. getSegments(false)
  261. }
  262. const onClickCard = (detail: SegmentDetailModel) => {
  263. setCurrSegment({ segInfo: detail, showModal: true })
  264. }
  265. const onCloseModal = () => {
  266. setCurrSegment({ ...currSegment, showModal: false })
  267. }
  268. const onChangeSwitch = async (segId: string, enabled: boolean) => {
  269. const opApi = enabled ? enableSegment : disableSegment
  270. const [e] = await asyncRunSafe<CommonResponse>(opApi({ datasetId, segmentId: segId }) as Promise<CommonResponse>)
  271. if (!e) {
  272. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  273. for (const item of allSegments) {
  274. for (const seg of item) {
  275. if (seg.id === segId)
  276. seg.enabled = enabled
  277. }
  278. }
  279. setAllSegments([...allSegments])
  280. }
  281. else {
  282. notify({ type: 'error', message: t('common.actionMsg.modificationFailed') })
  283. }
  284. }
  285. const onDelete = async (segId: string) => {
  286. const [e] = await asyncRunSafe<CommonResponse>(deleteSegment({ datasetId, documentId, segmentId: segId }) as Promise<CommonResponse>)
  287. if (!e) {
  288. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  289. resetList()
  290. }
  291. else {
  292. notify({ type: 'error', message: t('common.actionMsg.modificationFailed') })
  293. }
  294. }
  295. const handleUpdateSegment = async (segmentId: string, question: string, answer: string, keywords: string[]) => {
  296. const params: SegmentUpdator = { content: '' }
  297. if (docForm === 'qa_model') {
  298. if (!question.trim())
  299. return notify({ type: 'error', message: t('datasetDocuments.segment.questionEmpty') })
  300. if (!answer.trim())
  301. return notify({ type: 'error', message: t('datasetDocuments.segment.answerEmpty') })
  302. params.content = question
  303. params.answer = answer
  304. }
  305. else {
  306. if (!question.trim())
  307. return notify({ type: 'error', message: t('datasetDocuments.segment.contentEmpty') })
  308. params.content = question
  309. }
  310. if (keywords.length)
  311. params.keywords = keywords
  312. try {
  313. eventEmitter?.emit('update-segment')
  314. const res = await updateSegment({ datasetId, documentId, segmentId, body: params })
  315. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  316. onCloseModal()
  317. for (const item of allSegments) {
  318. for (const seg of item) {
  319. if (seg.id === segmentId) {
  320. seg.answer = res.data.answer
  321. seg.content = res.data.content
  322. seg.keywords = res.data.keywords
  323. seg.word_count = res.data.word_count
  324. seg.hit_count = res.data.hit_count
  325. seg.index_node_hash = res.data.index_node_hash
  326. seg.enabled = res.data.enabled
  327. }
  328. }
  329. }
  330. setAllSegments([...allSegments])
  331. }
  332. finally {
  333. eventEmitter?.emit('')
  334. }
  335. }
  336. useEffect(() => {
  337. if (lastSegmentsRes !== undefined)
  338. getSegments(false)
  339. }, [selectedStatus, searchValue])
  340. useEffect(() => {
  341. if (importStatus === ProcessStatus.COMPLETED)
  342. resetList()
  343. }, [importStatus])
  344. return (
  345. <>
  346. <div className={s.docSearchWrapper}>
  347. <div className={s.totalText}>{total ? formatNumber(total) : '--'} {t('datasetDocuments.segment.paragraphs')}</div>
  348. <SimpleSelect
  349. onSelect={onChangeStatus}
  350. items={[
  351. { value: 'all', name: t('datasetDocuments.list.index.all') },
  352. { value: 0, name: t('datasetDocuments.list.status.disabled') },
  353. { value: 1, name: t('datasetDocuments.list.status.enabled') },
  354. ]}
  355. defaultValue={'all'}
  356. className={s.select}
  357. wrapperClassName='h-fit w-[120px] mr-2' />
  358. <Input showPrefix wrapperClassName='!w-52' className='!h-8' onChange={debounce(setSearchValue, 500)} />
  359. </div>
  360. <InfiniteVirtualList
  361. hasNextPage={lastSegmentsRes?.has_more ?? true}
  362. isNextPageLoading={loading}
  363. items={allSegments}
  364. loadNextPage={getSegments}
  365. onChangeSwitch={onChangeSwitch}
  366. onDelete={onDelete}
  367. onClick={onClickCard}
  368. archived={archived}
  369. />
  370. <Modal isShow={currSegment.showModal} onClose={() => {}} className='!max-w-[640px] !overflow-visible'>
  371. <SegmentDetail
  372. segInfo={currSegment.segInfo ?? { id: '' }}
  373. onChangeSwitch={onChangeSwitch}
  374. onUpdate={handleUpdateSegment}
  375. onCancel={onCloseModal}
  376. archived={archived}
  377. />
  378. </Modal>
  379. <NewSegmentModal
  380. isShow={showNewSegmentModal}
  381. docForm={docForm}
  382. onCancel={() => onNewSegmentModalChange(false)}
  383. onSave={resetList}
  384. />
  385. </>
  386. )
  387. }
  388. export default Completed