You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

new-segment.tsx 7.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. import { memo, useCallback, 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 { useStore as useAppStore } from '@/app/components/app/store'
  16. import { ToastContext } from '@/app/components/base/toast'
  17. import { ChunkingMode, type SegmentUpdater } from '@/models/datasets'
  18. import classNames from '@/utils/classnames'
  19. import { formatNumber } from '@/utils/format'
  20. import Divider from '@/app/components/base/divider'
  21. import { useAddSegment } from '@/service/knowledge/use-segment'
  22. import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'
  23. import { IndexingType } from '../../create/step-two'
  24. type NewSegmentModalProps = {
  25. onCancel: () => void
  26. docForm: ChunkingMode
  27. onSave: () => void
  28. viewNewlyAddedChunk: () => void
  29. }
  30. const NewSegmentModal: FC<NewSegmentModalProps> = ({
  31. onCancel,
  32. docForm,
  33. onSave,
  34. viewNewlyAddedChunk,
  35. }) => {
  36. const { t } = useTranslation()
  37. const { notify } = useContext(ToastContext)
  38. const [question, setQuestion] = useState('')
  39. const [answer, setAnswer] = useState('')
  40. const { datasetId, documentId } = useParams<{ datasetId: string; documentId: string }>()
  41. const [keywords, setKeywords] = useState<string[]>([])
  42. const [loading, setLoading] = useState(false)
  43. const [addAnother, setAddAnother] = useState(true)
  44. const fullScreen = useSegmentListContext(s => s.fullScreen)
  45. const toggleFullScreen = useSegmentListContext(s => s.toggleFullScreen)
  46. const indexingTechnique = useDatasetDetailContextWithSelector(s => s.dataset?.indexing_technique)
  47. const { appSidebarExpand } = useAppStore(useShallow(state => ({
  48. appSidebarExpand: state.appSidebarExpand,
  49. })))
  50. const refreshTimer = useRef<any>(null)
  51. const CustomButton = useMemo(() => (
  52. <>
  53. <Divider type='vertical' className='mx-1 h-3 bg-divider-regular' />
  54. <button
  55. type='button'
  56. className='system-xs-semibold text-text-accent'
  57. onClick={() => {
  58. clearTimeout(refreshTimer.current)
  59. viewNewlyAddedChunk()
  60. }}>
  61. {t('common.operation.view')}
  62. </button>
  63. </>
  64. ), [viewNewlyAddedChunk, t])
  65. const handleCancel = useCallback((actionType: 'esc' | 'add' = 'esc') => {
  66. if (actionType === 'esc' || !addAnother)
  67. onCancel()
  68. }, [onCancel, addAnother])
  69. const { mutateAsync: addSegment } = useAddSegment()
  70. const handleSave = useCallback(async () => {
  71. const params: SegmentUpdater = { content: '' }
  72. if (docForm === ChunkingMode.qa) {
  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. setQuestion('')
  111. setAnswer('')
  112. setKeywords([])
  113. refreshTimer.current = setTimeout(() => {
  114. onSave()
  115. }, 3000)
  116. },
  117. onSettled() {
  118. setLoading(false)
  119. },
  120. })
  121. }, [docForm, keywords, addSegment, datasetId, documentId, question, answer, notify, t, appSidebarExpand, CustomButton, handleCancel, onSave])
  122. const wordCountText = useMemo(() => {
  123. const count = docForm === ChunkingMode.qa ? (question.length + answer.length) : question.length
  124. return `${formatNumber(count)} ${t('datasetDocuments.segment.characters', { count })}`
  125. }, [question.length, answer.length, docForm, t])
  126. const isECOIndexing = indexingTechnique === IndexingType.ECONOMICAL
  127. return (
  128. <div className={'flex h-full flex-col'}>
  129. <div
  130. className={classNames(
  131. 'flex items-center justify-between',
  132. fullScreen ? 'border border-divider-subtle py-3 pl-6 pr-4' : 'pl-4 pr-3 pt-3',
  133. )}
  134. >
  135. <div className='flex flex-col'>
  136. <div className='system-xl-semibold text-text-primary'>
  137. {t('datasetDocuments.segment.addChunk')}
  138. </div>
  139. <div className='flex items-center gap-x-2'>
  140. <SegmentIndexTag label={t('datasetDocuments.segment.newChunk')!} />
  141. <Dot />
  142. <span className='system-xs-medium text-text-tertiary'>{wordCountText}</span>
  143. </div>
  144. </div>
  145. <div className='flex items-center'>
  146. {fullScreen && (
  147. <>
  148. <AddAnother className='mr-3' isChecked={addAnother} onCheck={() => setAddAnother(!addAnother)} />
  149. <ActionButtons
  150. handleCancel={handleCancel.bind(null, 'esc')}
  151. handleSave={handleSave}
  152. loading={loading}
  153. actionType='add'
  154. />
  155. <Divider type='vertical' className='ml-4 mr-2 h-3.5 bg-divider-regular' />
  156. </>
  157. )}
  158. <div className='mr-1 flex h-8 w-8 cursor-pointer items-center justify-center p-1.5' onClick={toggleFullScreen}>
  159. <RiExpandDiagonalLine className='h-4 w-4 text-text-tertiary' />
  160. </div>
  161. <div className='flex h-8 w-8 cursor-pointer items-center justify-center p-1.5' onClick={handleCancel.bind(null, 'esc')}>
  162. <RiCloseLine className='h-4 w-4 text-text-tertiary' />
  163. </div>
  164. </div>
  165. </div>
  166. <div className={classNames('flex grow', fullScreen ? 'w-full flex-row justify-center gap-x-8 px-6 pt-6' : 'flex-col gap-y-1 px-4 py-3')}>
  167. <div className={classNames('overflow-hidden whitespace-pre-line break-all', fullScreen ? 'w-1/2' : 'grow')}>
  168. <ChunkContent
  169. docForm={docForm}
  170. question={question}
  171. answer={answer}
  172. onQuestionChange={question => setQuestion(question)}
  173. onAnswerChange={answer => setAnswer(answer)}
  174. isEditMode={true}
  175. />
  176. </div>
  177. {isECOIndexing && <Keywords
  178. className={fullScreen ? 'w-1/5' : ''}
  179. actionType='add'
  180. keywords={keywords}
  181. isEditMode={true}
  182. onKeywordsChange={keywords => setKeywords(keywords)}
  183. />}
  184. </div>
  185. {!fullScreen && (
  186. <div className='flex items-center justify-between border-t-[1px] border-t-divider-subtle p-4 pt-3'>
  187. <AddAnother isChecked={addAnother} onCheck={() => setAddAnother(!addAnother)} />
  188. <ActionButtons
  189. handleCancel={handleCancel.bind(null, 'esc')}
  190. handleSave={handleSave}
  191. loading={loading}
  192. actionType='add'
  193. />
  194. </div>
  195. )}
  196. </div>
  197. )
  198. }
  199. export default memo(NewSegmentModal)