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.

index.tsx 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. 'use client'
  2. import type { FC, ReactNode } from 'react'
  3. import React, { useState } from 'react'
  4. import { useTranslation } from 'react-i18next'
  5. import { useContext } from 'use-context-selector'
  6. import { UserCircleIcon } from '@heroicons/react/24/solid'
  7. import cn from 'classnames'
  8. import type { CitationItem, DisplayScene, FeedbackFunc, Feedbacktype, IChatItem, SubmitAnnotationFunc, ThoughtItem } from '../type'
  9. import OperationBtn from '../operation'
  10. import LoadingAnim from '../loading-anim'
  11. import { EditIcon, EditIconSolid, OpeningStatementIcon, RatingIcon } from '../icon-component'
  12. import s from '../style.module.css'
  13. import MoreInfo from '../more-info'
  14. import CopyBtn from '../copy-btn'
  15. import Thought from '../thought'
  16. import Citation from '../citation'
  17. import { randomString } from '@/utils'
  18. import type { Annotation, MessageRating } from '@/models/log'
  19. import AppContext from '@/context/app-context'
  20. import Tooltip from '@/app/components/base/tooltip'
  21. import { Markdown } from '@/app/components/base/markdown'
  22. import AutoHeightTextarea from '@/app/components/base/auto-height-textarea'
  23. import Button from '@/app/components/base/button'
  24. import type { DataSet } from '@/models/datasets'
  25. const Divider: FC<{ name: string }> = ({ name }) => {
  26. const { t } = useTranslation()
  27. return <div className='flex items-center my-2'>
  28. <span className='text-xs text-gray-500 inline-flex items-center mr-2'>
  29. <EditIconSolid className='mr-1' />{t('appLog.detail.annotationTip', { user: name })}
  30. </span>
  31. <div className='h-[1px] bg-gray-200 flex-1'></div>
  32. </div>
  33. }
  34. const IconWrapper: FC<{ children: React.ReactNode | string }> = ({ children }) => {
  35. return <div className={'rounded-lg h-6 w-6 flex items-center justify-center hover:bg-gray-100'}>
  36. {children}
  37. </div>
  38. }
  39. export type IAnswerProps = {
  40. item: IChatItem
  41. feedbackDisabled: boolean
  42. isHideFeedbackEdit: boolean
  43. onFeedback?: FeedbackFunc
  44. onSubmitAnnotation?: SubmitAnnotationFunc
  45. displayScene: DisplayScene
  46. isResponsing?: boolean
  47. answerIcon?: ReactNode
  48. thoughts?: ThoughtItem[]
  49. citation?: CitationItem[]
  50. isThinking?: boolean
  51. dataSets?: DataSet[]
  52. isShowCitation?: boolean
  53. isShowCitationHitInfo?: boolean
  54. }
  55. // The component needs to maintain its own state to control whether to display input component
  56. const Answer: FC<IAnswerProps> = ({ item, feedbackDisabled = false, isHideFeedbackEdit = false, onFeedback, onSubmitAnnotation, displayScene = 'web', isResponsing, answerIcon, thoughts, citation, isThinking, dataSets, isShowCitation, isShowCitationHitInfo = false }) => {
  57. const { id, content, more, feedback, adminFeedback, annotation: initAnnotation } = item
  58. const [showEdit, setShowEdit] = useState(false)
  59. const [loading, setLoading] = useState(false)
  60. const [annotation, setAnnotation] = useState<Annotation | undefined | null>(initAnnotation)
  61. const [inputValue, setInputValue] = useState<string>(initAnnotation?.content ?? '')
  62. const [localAdminFeedback, setLocalAdminFeedback] = useState<Feedbacktype | undefined | null>(adminFeedback)
  63. const { userProfile } = useContext(AppContext)
  64. const { t } = useTranslation()
  65. /**
  66. * Render feedback results (distinguish between users and administrators)
  67. * User reviews cannot be cancelled in Console
  68. * @param rating feedback result
  69. * @param isUserFeedback Whether it is user's feedback
  70. * @param isWebScene Whether it is web scene
  71. * @returns comp
  72. */
  73. const renderFeedbackRating = (rating: MessageRating | undefined, isUserFeedback = true, isWebScene = true) => {
  74. if (!rating)
  75. return null
  76. const isLike = rating === 'like'
  77. const ratingIconClassname = isLike ? 'text-primary-600 bg-primary-100 hover:bg-primary-200' : 'text-red-600 bg-red-100 hover:bg-red-200'
  78. const UserSymbol = <UserCircleIcon className='absolute top-[-2px] left-[18px] w-3 h-3 rounded-lg text-gray-400 bg-white' />
  79. // The tooltip is always displayed, but the content is different for different scenarios.
  80. return (
  81. <Tooltip
  82. selector={`user-feedback-${randomString(16)}`}
  83. content={((isWebScene || (!isUserFeedback && !isWebScene)) ? isLike ? t('appDebug.operation.cancelAgree') : t('appDebug.operation.cancelDisagree') : (!isWebScene && isUserFeedback) ? `${t('appDebug.operation.userAction')}${isLike ? t('appDebug.operation.agree') : t('appDebug.operation.disagree')}` : '') as string}
  84. >
  85. <div
  86. className={`relative box-border flex items-center justify-center h-7 w-7 p-0.5 rounded-lg bg-white cursor-pointer text-gray-500 hover:text-gray-800 ${(!isWebScene && isUserFeedback) ? '!cursor-default' : ''}`}
  87. style={{ boxShadow: '0px 4px 6px -1px rgba(0, 0, 0, 0.1), 0px 2px 4px -2px rgba(0, 0, 0, 0.05)' }}
  88. {...((isWebScene || (!isUserFeedback && !isWebScene))
  89. ? {
  90. onClick: async () => {
  91. const res = await onFeedback?.(id, { rating: null })
  92. if (res && !isWebScene)
  93. setLocalAdminFeedback({ rating: null })
  94. },
  95. }
  96. : {})}
  97. >
  98. <div className={`${ratingIconClassname} rounded-lg h-6 w-6 flex items-center justify-center`}>
  99. <RatingIcon isLike={isLike} />
  100. </div>
  101. {!isWebScene && isUserFeedback && UserSymbol}
  102. </div>
  103. </Tooltip>
  104. )
  105. }
  106. /**
  107. * Different scenarios have different operation items.
  108. * @param isWebScene Whether it is web scene
  109. * @returns comp
  110. */
  111. const renderItemOperation = (isWebScene = true) => {
  112. const userOperation = () => {
  113. return feedback?.rating
  114. ? null
  115. : <div className='flex gap-1'>
  116. <Tooltip selector={`user-feedback-${randomString(16)}`} content={t('appLog.detail.operation.like') as string}>
  117. {OperationBtn({ innerContent: <IconWrapper><RatingIcon isLike={true} /></IconWrapper>, onClick: () => onFeedback?.(id, { rating: 'like' }) })}
  118. </Tooltip>
  119. <Tooltip selector={`user-feedback-${randomString(16)}`} content={t('appLog.detail.operation.dislike') as string}>
  120. {OperationBtn({ innerContent: <IconWrapper><RatingIcon isLike={false} /></IconWrapper>, onClick: () => onFeedback?.(id, { rating: 'dislike' }) })}
  121. </Tooltip>
  122. </div>
  123. }
  124. const adminOperation = () => {
  125. return <div className='flex gap-1'>
  126. <Tooltip selector={`user-feedback-${randomString(16)}`} content={t('appLog.detail.operation.addAnnotation') as string}>
  127. {OperationBtn({
  128. innerContent: <IconWrapper><EditIcon className='hover:text-gray-800' /></IconWrapper>,
  129. onClick: () => setShowEdit(true),
  130. })}
  131. </Tooltip>
  132. {!localAdminFeedback?.rating && <>
  133. <Tooltip selector={`user-feedback-${randomString(16)}`} content={t('appLog.detail.operation.like') as string}>
  134. {OperationBtn({
  135. innerContent: <IconWrapper><RatingIcon isLike={true} /></IconWrapper>,
  136. onClick: async () => {
  137. const res = await onFeedback?.(id, { rating: 'like' })
  138. if (res)
  139. setLocalAdminFeedback({ rating: 'like' })
  140. },
  141. })}
  142. </Tooltip>
  143. <Tooltip selector={`user-feedback-${randomString(16)}`} content={t('appLog.detail.operation.dislike') as string}>
  144. {OperationBtn({
  145. innerContent: <IconWrapper><RatingIcon isLike={false} /></IconWrapper>,
  146. onClick: async () => {
  147. const res = await onFeedback?.(id, { rating: 'dislike' })
  148. if (res)
  149. setLocalAdminFeedback({ rating: 'dislike' })
  150. },
  151. })}
  152. </Tooltip>
  153. </>}
  154. </div>
  155. }
  156. return (
  157. <div className={`${s.itemOperation} flex gap-2`}>
  158. {isWebScene ? userOperation() : adminOperation()}
  159. </div>
  160. )
  161. }
  162. return (
  163. <div key={id}>
  164. <div className='flex items-start'>
  165. {
  166. answerIcon || (
  167. <div className={`${s.answerIcon} w-10 h-10 shrink-0`}>
  168. {isResponsing
  169. && <div className={s.typeingIcon}>
  170. <LoadingAnim type='avatar' />
  171. </div>
  172. }
  173. </div>
  174. )
  175. }
  176. <div className={cn(s.answerWrapWrap, 'chat-answer-container')}>
  177. <div className={`${s.answerWrap} ${showEdit ? 'w-full' : ''}`}>
  178. <div className={`${s.answer} relative text-sm text-gray-900`}>
  179. <div className={'ml-2 py-3 px-4 bg-gray-100 rounded-tr-2xl rounded-b-2xl'}>
  180. {item.isOpeningStatement && (
  181. <div className='flex items-center mb-1 gap-1'>
  182. <OpeningStatementIcon />
  183. <div className='text-xs text-gray-500'>{t('appDebug.openingStatement.title')}</div>
  184. </div>
  185. )}
  186. {(thoughts && thoughts.length > 0) && (
  187. <Thought
  188. list={thoughts || []}
  189. isThinking={isThinking}
  190. dataSets={dataSets}
  191. />
  192. )}
  193. {(isResponsing && !content)
  194. ? (
  195. <div className='flex items-center justify-center w-6 h-5'>
  196. <LoadingAnim type='text' />
  197. </div>
  198. )
  199. : (
  200. <div>
  201. <Markdown content={content} />
  202. </div>
  203. )}
  204. {!showEdit
  205. ? (annotation?.content
  206. && <>
  207. <Divider name={annotation?.account?.name || userProfile?.name} />
  208. {annotation.content}
  209. </>)
  210. : <>
  211. <Divider name={annotation?.account?.name || userProfile?.name} />
  212. <AutoHeightTextarea
  213. placeholder={t('appLog.detail.operation.annotationPlaceholder') as string}
  214. value={inputValue}
  215. onChange={e => setInputValue(e.target.value)}
  216. minHeight={58}
  217. className={`${cn(s.textArea)} !py-2 resize-none block w-full !px-3 bg-gray-50 border border-gray-200 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm text-gray-700 tracking-[0.2px]`}
  218. />
  219. <div className="mt-2 flex flex-row">
  220. <Button
  221. type='primary'
  222. className='mr-2'
  223. loading={loading}
  224. onClick={async () => {
  225. if (!inputValue)
  226. return
  227. setLoading(true)
  228. const res = await onSubmitAnnotation?.(id, inputValue)
  229. if (res)
  230. setAnnotation({ ...annotation, content: inputValue } as Annotation)
  231. setLoading(false)
  232. setShowEdit(false)
  233. }}>{t('common.operation.confirm')}</Button>
  234. <Button
  235. onClick={() => {
  236. setInputValue(annotation?.content ?? '')
  237. setShowEdit(false)
  238. }}>{t('common.operation.cancel')}</Button>
  239. </div>
  240. </>
  241. }
  242. {
  243. !!citation?.length && !isThinking && isShowCitation && !isResponsing && (
  244. <Citation data={citation} showHitInfo={isShowCitationHitInfo} />
  245. )
  246. }
  247. </div>
  248. <div className='absolute top-[-14px] right-[-14px] flex flex-row justify-end gap-1'>
  249. {!item.isOpeningStatement && (
  250. <CopyBtn
  251. value={content}
  252. className={cn(s.copyBtn, 'mr-1')}
  253. />
  254. )}
  255. {!feedbackDisabled && !item.feedbackDisabled && renderItemOperation(displayScene !== 'console')}
  256. {/* Admin feedback is displayed only in the background. */}
  257. {!feedbackDisabled && renderFeedbackRating(localAdminFeedback?.rating, false, false)}
  258. {/* User feedback must be displayed */}
  259. {!feedbackDisabled && renderFeedbackRating(feedback?.rating, !isHideFeedbackEdit, displayScene !== 'console')}
  260. </div>
  261. </div>
  262. {more && <MoreInfo more={more} isQuestion={false} />}
  263. </div>
  264. </div>
  265. </div>
  266. </div>
  267. )
  268. }
  269. export default React.memo(Answer)