new-segment.tsx 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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='mx-1 h-3 bg-divider-regular' />
  52. <button
  53. type='button'
  54. className='system-xs-semibold text-text-accent'
  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. }
  69. const { mutateAsync: addSegment } = useAddSegment()
  70. const handleSave = async () => {
  71. const params: SegmentUpdater = { content: '' }
  72. if (isQAModel) {
  73. if (!question.trim()) {
  74. return notify({
  75. type: 'error',
  76. message: t('datasetDocuments.segment.questionEmpty'),
  77. })
  78. }
  79. if (!answer.trim()) {
  80. return notify({
  81. type: 'error',
  82. message: t('datasetDocuments.segment.answerEmpty'),
  83. })
  84. }
  85. params.content = question
  86. params.answer = answer
  87. }
  88. else {
  89. if (!question.trim()) {
  90. return notify({
  91. type: 'error',
  92. message: t('datasetDocuments.segment.contentEmpty'),
  93. })
  94. }
  95. params.content = question
  96. }
  97. if (keywords?.length)
  98. params.keywords = keywords
  99. setLoading(true)
  100. await addSegment({ datasetId, documentId, body: params }, {
  101. onSuccess() {
  102. notify({
  103. type: 'success',
  104. message: t('datasetDocuments.segment.chunkAdded'),
  105. className: `!w-[296px] !bottom-0 ${appSidebarExpand === 'expand' ? '!left-[216px]' : '!left-14'}
  106. !top-auto !right-auto !mb-[52px] !ml-11`,
  107. customComponent: CustomButton,
  108. })
  109. handleCancel('add')
  110. refreshTimer.current = setTimeout(() => {
  111. onSave()
  112. }, 3000)
  113. },
  114. onSettled() {
  115. setLoading(false)
  116. },
  117. })
  118. }
  119. const wordCountText = useMemo(() => {
  120. const count = isQAModel ? (question.length + answer.length) : question.length
  121. return `${formatNumber(count)} ${t('datasetDocuments.segment.characters', { count })}`
  122. // eslint-disable-next-line react-hooks/exhaustive-deps
  123. }, [question.length, answer.length, isQAModel])
  124. return (
  125. <div className={'flex h-full flex-col'}>
  126. <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')}>
  127. <div className='flex flex-col'>
  128. <div className='system-xl-semibold text-text-primary'>{
  129. t('datasetDocuments.segment.addChunk')
  130. }</div>
  131. <div className='flex items-center gap-x-2'>
  132. <SegmentIndexTag label={t('datasetDocuments.segment.newChunk')!} />
  133. <Dot />
  134. <span className='system-xs-medium text-text-tertiary'>{wordCountText}</span>
  135. </div>
  136. </div>
  137. <div className='flex items-center'>
  138. {fullScreen && (
  139. <>
  140. <AddAnother className='mr-3' isChecked={addAnother} onCheck={() => setAddAnother(!addAnother)} />
  141. <ActionButtons
  142. handleCancel={handleCancel.bind(null, 'esc')}
  143. handleSave={handleSave}
  144. loading={loading}
  145. actionType='add'
  146. />
  147. <Divider type='vertical' className='ml-4 mr-2 h-3.5 bg-divider-regular' />
  148. </>
  149. )}
  150. <div className='mr-1 flex h-8 w-8 cursor-pointer items-center justify-center p-1.5' onClick={toggleFullScreen}>
  151. <RiExpandDiagonalLine className='h-4 w-4 text-text-tertiary' />
  152. </div>
  153. <div className='flex h-8 w-8 cursor-pointer items-center justify-center p-1.5' onClick={handleCancel.bind(null, 'esc')}>
  154. <RiCloseLine className='h-4 w-4 text-text-tertiary' />
  155. </div>
  156. </div>
  157. </div>
  158. <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')}>
  159. <div className={classNames('break-all overflow-hidden whitespace-pre-line', fullScreen ? 'w-1/2' : 'grow')}>
  160. <ChunkContent
  161. docForm={docForm}
  162. question={question}
  163. answer={answer}
  164. onQuestionChange={question => setQuestion(question)}
  165. onAnswerChange={answer => setAnswer(answer)}
  166. isEditMode={true}
  167. />
  168. </div>
  169. {mode === 'custom' && <Keywords
  170. className={fullScreen ? 'w-1/5' : ''}
  171. actionType='add'
  172. keywords={keywords}
  173. isEditMode={true}
  174. onKeywordsChange={keywords => setKeywords(keywords)}
  175. />}
  176. </div>
  177. {!fullScreen && (
  178. <div className='flex items-center justify-between border-t-[1px] border-t-divider-subtle p-4 pt-3'>
  179. <AddAnother isChecked={addAnother} onCheck={() => setAddAnother(!addAnother)} />
  180. <ActionButtons
  181. handleCancel={handleCancel.bind(null, 'esc')}
  182. handleSave={handleSave}
  183. loading={loading}
  184. actionType='add'
  185. />
  186. </div>
  187. )}
  188. </div>
  189. )
  190. }
  191. export default memo(NewSegmentModal)