index.tsx 13 KB

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