index.tsx 15 KB

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