index.tsx 14 KB

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