new-segment.tsx 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. import { memo, useMemo, useRef, useState } from 'react'
  2. import type { FC } from 'react'
  3. import { useTranslation } from 'react-i18next'
  4. import { useContext } from 'use-context-selector'
  5. import { useParams } from 'next/navigation'
  6. import { RiCloseLine, RiExpandDiagonalLine } from '@remixicon/react'
  7. import { useShallow } from 'zustand/react/shallow'
  8. import { useSegmentListContext } from './completed'
  9. import { SegmentIndexTag } from './completed/common/segment-index-tag'
  10. import ActionButtons from './completed/common/action-buttons'
  11. import Keywords from './completed/common/keywords'
  12. import ChunkContent from './completed/common/chunk-content'
  13. import AddAnother from './completed/common/add-another'
  14. import Dot from './completed/common/dot'
  15. import { useDocumentContext } from './index'
  16. import { useStore as useAppStore } from '@/app/components/app/store'
  17. import { ToastContext } from '@/app/components/base/toast'
  18. import { ChunkingMode, type SegmentUpdater } from '@/models/datasets'
  19. import classNames from '@/utils/classnames'
  20. import { formatNumber } from '@/utils/format'
  21. import Divider from '@/app/components/base/divider'
  22. import { useAddSegment } from '@/service/knowledge/use-segment'
  23. type NewSegmentModalProps = {
  24. onCancel: () => void
  25. docForm: ChunkingMode
  26. onSave: () => void
  27. viewNewlyAddedChunk: () => void
  28. }
  29. const NewSegmentModal: FC<NewSegmentModalProps> = ({
  30. onCancel,
  31. docForm,
  32. onSave,
  33. viewNewlyAddedChunk,
  34. }) => {
  35. const { t } = useTranslation()
  36. const { notify } = useContext(ToastContext)
  37. const [question, setQuestion] = useState('')
  38. const [answer, setAnswer] = useState('')
  39. const { datasetId, documentId } = useParams<{ datasetId: string; documentId: string }>()
  40. const [keywords, setKeywords] = useState<string[]>([])
  41. const [loading, setLoading] = useState(false)
  42. const [addAnother, setAddAnother] = useState(true)
  43. const fullScreen = useSegmentListContext(s => s.fullScreen)
  44. const toggleFullScreen = useSegmentListContext(s => s.toggleFullScreen)
  45. const mode = useDocumentContext(s => s.mode)
  46. const { appSidebarExpand } = useAppStore(useShallow(state => ({
  47. appSidebarExpand: state.appSidebarExpand,
  48. })))
  49. const refreshTimer = useRef<any>(null)
  50. const CustomButton = <>
  51. <Divider type='vertical' className='h-3 mx-1 bg-divider-regular' />
  52. <button
  53. type='button'
  54. className='text-text-accent system-xs-semibold'
  55. onClick={() => {
  56. clearTimeout(refreshTimer.current)
  57. viewNewlyAddedChunk()
  58. }}>
  59. {t('common.operation.view')}
  60. </button>
  61. </>
  62. const isQAModel = useMemo(() => {
  63. return docForm === ChunkingMode.qa
  64. }, [docForm])
  65. const handleCancel = (actionType: 'esc' | 'add' = 'esc') => {
  66. if (actionType === 'esc' || !addAnother)
  67. onCancel()
  68. setQuestion('')
  69. setAnswer('')
  70. setKeywords([])
  71. }
  72. const { mutateAsync: addSegment } = useAddSegment()
  73. const handleSave = async () => {
  74. const params: SegmentUpdater = { content: '' }
  75. if (isQAModel) {
  76. if (!question.trim()) {
  77. return notify({
  78. type: 'error',
  79. message: t('datasetDocuments.segment.questionEmpty'),
  80. })
  81. }
  82. if (!answer.trim()) {
  83. return notify({
  84. type: 'error',
  85. message: t('datasetDocuments.segment.answerEmpty'),
  86. })
  87. }
  88. params.content = question
  89. params.answer = answer
  90. }
  91. else {
  92. if (!question.trim()) {
  93. return notify({
  94. type: 'error',
  95. message: t('datasetDocuments.segment.contentEmpty'),
  96. })
  97. }
  98. params.content = question
  99. }
  100. if (keywords?.length)
  101. params.keywords = keywords
  102. setLoading(true)
  103. await addSegment({ datasetId, documentId, body: params }, {
  104. onSuccess() {
  105. notify({
  106. type: 'success',
  107. message: t('datasetDocuments.segment.chunkAdded'),
  108. className: `!w-[296px] !bottom-0 ${appSidebarExpand === 'expand' ? '!left-[216px]' : '!left-14'}
  109. !top-auto !right-auto !mb-[52px] !ml-11`,
  110. customComponent: CustomButton,
  111. })
  112. handleCancel('add')
  113. refreshTimer.current = setTimeout(() => {
  114. onSave()
  115. }, 3000)
  116. },
  117. onSettled() {
  118. setLoading(false)
  119. },
  120. })
  121. }
  122. const wordCountText = useMemo(() => {
  123. const count = isQAModel ? (question.length + answer.length) : question.length
  124. return `${formatNumber(count)} ${t('datasetDocuments.segment.characters', { count })}`
  125. // eslint-disable-next-line react-hooks/exhaustive-deps
  126. }, [question.length, answer.length, isQAModel])
  127. return (
  128. <div className={'flex flex-col h-full'}>
  129. <div className={classNames('flex items-center justify-between', fullScreen ? 'py-3 pr-4 pl-6 border border-divider-subtle' : 'pt-3 pr-3 pl-4')}>
  130. <div className='flex flex-col'>
  131. <div className='text-text-primary system-xl-semibold'>{
  132. t('datasetDocuments.segment.addChunk')
  133. }</div>
  134. <div className='flex items-center gap-x-2'>
  135. <SegmentIndexTag label={t('datasetDocuments.segment.newChunk')!} />
  136. <Dot />
  137. <span className='text-text-tertiary system-xs-medium'>{wordCountText}</span>
  138. </div>
  139. </div>
  140. <div className='flex items-center'>
  141. {fullScreen && (
  142. <>
  143. <AddAnother className='mr-3' isChecked={addAnother} onCheck={() => setAddAnother(!addAnother)} />
  144. <ActionButtons
  145. handleCancel={handleCancel.bind(null, 'esc')}
  146. handleSave={handleSave}
  147. loading={loading}
  148. actionType='add'
  149. />
  150. <Divider type='vertical' className='h-3.5 bg-divider-regular ml-4 mr-2' />
  151. </>
  152. )}
  153. <div className='w-8 h-8 flex justify-center items-center p-1.5 cursor-pointer mr-1' onClick={toggleFullScreen}>
  154. <RiExpandDiagonalLine className='w-4 h-4 text-text-tertiary' />
  155. </div>
  156. <div className='w-8 h-8 flex justify-center items-center p-1.5 cursor-pointer' onClick={handleCancel.bind(null, 'esc')}>
  157. <RiCloseLine className='w-4 h-4 text-text-tertiary' />
  158. </div>
  159. </div>
  160. </div>
  161. <div className={classNames('flex grow', fullScreen ? 'w-full flex-row justify-center px-6 pt-6 gap-x-8' : 'flex-col gap-y-1 py-3 px-4')}>
  162. <div className={classNames('break-all overflow-hidden whitespace-pre-line', fullScreen ? 'w-1/2' : 'grow')}>
  163. <ChunkContent
  164. docForm={docForm}
  165. question={question}
  166. answer={answer}
  167. onQuestionChange={question => setQuestion(question)}
  168. onAnswerChange={answer => setAnswer(answer)}
  169. isEditMode={true}
  170. />
  171. </div>
  172. {mode === 'custom' && <Keywords
  173. className={fullScreen ? 'w-1/5' : ''}
  174. actionType='add'
  175. keywords={keywords}
  176. isEditMode={true}
  177. onKeywordsChange={keywords => setKeywords(keywords)}
  178. />}
  179. </div>
  180. {!fullScreen && (
  181. <div className='flex items-center justify-between p-4 pt-3 border-t-[1px] border-t-divider-subtle'>
  182. <AddAnother isChecked={addAnother} onCheck={() => setAddAnother(!addAnother)} />
  183. <ActionButtons
  184. handleCancel={handleCancel.bind(null, 'esc')}
  185. handleSave={handleSave}
  186. loading={loading}
  187. actionType='add'
  188. />
  189. </div>
  190. )}
  191. </div>
  192. )
  193. }
  194. export default memo(NewSegmentModal)