index.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. 'use client'
  2. import type { FC, ReactNode } from 'react'
  3. import React, { useState } from 'react'
  4. import { useTranslation } from 'react-i18next'
  5. import { UserCircleIcon } from '@heroicons/react/24/solid'
  6. import cn from 'classnames'
  7. import type { CitationItem, DisplayScene, FeedbackFunc, Feedbacktype, IChatItem, ThoughtItem } from '../type'
  8. import OperationBtn from '../operation'
  9. import LoadingAnim from '../loading-anim'
  10. import { EditIconSolid, OpeningStatementIcon, RatingIcon } from '../icon-component'
  11. import s from '../style.module.css'
  12. import MoreInfo from '../more-info'
  13. import CopyBtn from '../copy-btn'
  14. import Thought from '../thought'
  15. import Citation from '../citation'
  16. import { randomString } from '@/utils'
  17. import type { MessageRating } from '@/models/log'
  18. import Tooltip from '@/app/components/base/tooltip'
  19. import { Markdown } from '@/app/components/base/markdown'
  20. import type { DataSet } from '@/models/datasets'
  21. import AnnotationCtrlBtn from '@/app/components/app/configuration/toolbox/annotation/annotation-ctrl-btn'
  22. import EditReplyModal from '@/app/components/app/annotation/edit-annotation-modal'
  23. import { EditTitle } from '@/app/components/app/annotation/edit-annotation-modal/edit-item'
  24. import { MessageFast } from '@/app/components/base/icons/src/vender/solid/communication'
  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. displayScene: DisplayScene
  45. isResponsing?: boolean
  46. answerIcon?: ReactNode
  47. thoughts?: ThoughtItem[]
  48. citation?: CitationItem[]
  49. isThinking?: boolean
  50. dataSets?: DataSet[]
  51. isShowCitation?: boolean
  52. isShowCitationHitInfo?: boolean
  53. // Annotation props
  54. supportAnnotation?: boolean
  55. appId?: string
  56. question: string
  57. onAnnotationEdited?: (question: string, answer: string) => void
  58. onAnnotationAdded?: (annotationId: string, authorName: string, question: string, answer: string) => void
  59. onAnnotationRemoved?: () => void
  60. }
  61. // The component needs to maintain its own state to control whether to display input component
  62. const Answer: FC<IAnswerProps> = ({
  63. item,
  64. feedbackDisabled = false,
  65. isHideFeedbackEdit = false,
  66. onFeedback,
  67. displayScene = 'web',
  68. isResponsing,
  69. answerIcon,
  70. thoughts,
  71. citation,
  72. isThinking,
  73. dataSets,
  74. isShowCitation,
  75. isShowCitationHitInfo = false,
  76. supportAnnotation,
  77. appId,
  78. question,
  79. onAnnotationEdited,
  80. onAnnotationAdded,
  81. onAnnotationRemoved,
  82. }) => {
  83. const { id, content, more, feedback, adminFeedback, annotation } = item
  84. const hasAnnotation = !!annotation?.id
  85. const [showEdit, setShowEdit] = useState(false)
  86. const [loading, setLoading] = useState(false)
  87. // const [annotation, setAnnotation] = useState<Annotation | undefined | null>(initAnnotation)
  88. // const [inputValue, setInputValue] = useState<string>(initAnnotation?.content ?? '')
  89. const [localAdminFeedback, setLocalAdminFeedback] = useState<Feedbacktype | undefined | null>(adminFeedback)
  90. // const { userProfile } = useContext(AppContext)
  91. const { t } = useTranslation()
  92. const [isShowReplyModal, setIsShowReplyModal] = useState(false)
  93. /**
  94. * Render feedback results (distinguish between users and administrators)
  95. * User reviews cannot be cancelled in Console
  96. * @param rating feedback result
  97. * @param isUserFeedback Whether it is user's feedback
  98. * @param isWebScene Whether it is web scene
  99. * @returns comp
  100. */
  101. const renderFeedbackRating = (rating: MessageRating | undefined, isUserFeedback = true, isWebScene = true) => {
  102. if (!rating)
  103. return null
  104. const isLike = rating === 'like'
  105. const ratingIconClassname = isLike ? 'text-primary-600 bg-primary-100 hover:bg-primary-200' : 'text-red-600 bg-red-100 hover:bg-red-200'
  106. const UserSymbol = <UserCircleIcon className='absolute top-[-2px] left-[18px] w-3 h-3 rounded-lg text-gray-400 bg-white' />
  107. // The tooltip is always displayed, but the content is different for different scenarios.
  108. return (
  109. <Tooltip
  110. selector={`user-feedback-${randomString(16)}`}
  111. 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}
  112. >
  113. <div
  114. 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' : ''}`}
  115. style={{ boxShadow: '0px 4px 6px -1px rgba(0, 0, 0, 0.1), 0px 2px 4px -2px rgba(0, 0, 0, 0.05)' }}
  116. {...((isWebScene || (!isUserFeedback && !isWebScene))
  117. ? {
  118. onClick: async () => {
  119. const res = await onFeedback?.(id, { rating: null })
  120. if (res && !isWebScene)
  121. setLocalAdminFeedback({ rating: null })
  122. },
  123. }
  124. : {})}
  125. >
  126. <div className={`${ratingIconClassname} rounded-lg h-6 w-6 flex items-center justify-center`}>
  127. <RatingIcon isLike={isLike} />
  128. </div>
  129. {!isWebScene && isUserFeedback && UserSymbol}
  130. </div>
  131. </Tooltip>
  132. )
  133. }
  134. const renderHasAnnotationBtn = () => {
  135. return (
  136. <div
  137. className={cn(s.hasAnnotationBtn, 'relative box-border flex items-center justify-center h-7 w-7 p-0.5 rounded-lg bg-white cursor-pointer text-[#444CE7]')}
  138. style={{ boxShadow: '0px 4px 6px -1px rgba(0, 0, 0, 0.1), 0px 2px 4px -2px rgba(0, 0, 0, 0.05)' }}
  139. >
  140. <div className='p-1 rounded-lg bg-[#EEF4FF] '>
  141. <MessageFast className='w-4 h-4' />
  142. </div>
  143. </div>
  144. )
  145. }
  146. /**
  147. * Different scenarios have different operation items.
  148. * @param isWebScene Whether it is web scene
  149. * @returns comp
  150. */
  151. const renderItemOperation = (isWebScene = true) => {
  152. const userOperation = () => {
  153. return feedback?.rating
  154. ? null
  155. : <div className='flex gap-1'>
  156. <Tooltip selector={`user-feedback-${randomString(16)}`} content={t('appLog.detail.operation.like') as string}>
  157. {OperationBtn({ innerContent: <IconWrapper><RatingIcon isLike={true} /></IconWrapper>, onClick: () => onFeedback?.(id, { rating: 'like' }) })}
  158. </Tooltip>
  159. <Tooltip selector={`user-feedback-${randomString(16)}`} content={t('appLog.detail.operation.dislike') as string}>
  160. {OperationBtn({ innerContent: <IconWrapper><RatingIcon isLike={false} /></IconWrapper>, onClick: () => onFeedback?.(id, { rating: 'dislike' }) })}
  161. </Tooltip>
  162. </div>
  163. }
  164. const adminOperation = () => {
  165. return <div className='flex gap-1'>
  166. {!localAdminFeedback?.rating && <>
  167. <Tooltip selector={`user-feedback-${randomString(16)}`} content={t('appLog.detail.operation.like') as string}>
  168. {OperationBtn({
  169. innerContent: <IconWrapper><RatingIcon isLike={true} /></IconWrapper>,
  170. onClick: async () => {
  171. const res = await onFeedback?.(id, { rating: 'like' })
  172. if (res)
  173. setLocalAdminFeedback({ rating: 'like' })
  174. },
  175. })}
  176. </Tooltip>
  177. <Tooltip selector={`user-feedback-${randomString(16)}`} content={t('appLog.detail.operation.dislike') as string}>
  178. {OperationBtn({
  179. innerContent: <IconWrapper><RatingIcon isLike={false} /></IconWrapper>,
  180. onClick: async () => {
  181. const res = await onFeedback?.(id, { rating: 'dislike' })
  182. if (res)
  183. setLocalAdminFeedback({ rating: 'dislike' })
  184. },
  185. })}
  186. </Tooltip>
  187. </>}
  188. </div>
  189. }
  190. return (
  191. <div className={`${s.itemOperation} flex gap-2`}>
  192. {isWebScene ? userOperation() : adminOperation()}
  193. </div>
  194. )
  195. }
  196. return (
  197. <div key={id}>
  198. <div className='flex items-start'>
  199. {
  200. answerIcon || (
  201. <div className={`${s.answerIcon} w-10 h-10 shrink-0`}>
  202. {isResponsing
  203. && <div className={s.typeingIcon}>
  204. <LoadingAnim type='avatar' />
  205. </div>
  206. }
  207. </div>
  208. )
  209. }
  210. <div className={cn(s.answerWrapWrap, 'chat-answer-container group')}>
  211. <div className={`${s.answerWrap} ${showEdit ? 'w-full' : ''}`}>
  212. <div className={`${s.answer} relative text-sm text-gray-900`}>
  213. <div className={'ml-2 py-3 px-4 bg-gray-100 rounded-tr-2xl rounded-b-2xl'}>
  214. {item.isOpeningStatement && (
  215. <div className='flex items-center mb-1 gap-1'>
  216. <OpeningStatementIcon />
  217. <div className='text-xs text-gray-500'>{t('appDebug.openingStatement.title')}</div>
  218. </div>
  219. )}
  220. {(thoughts && thoughts.length > 0) && (
  221. <Thought
  222. list={thoughts || []}
  223. isThinking={isThinking}
  224. dataSets={dataSets}
  225. />
  226. )}
  227. {(isResponsing && !content)
  228. ? (
  229. <div className='flex items-center justify-center w-6 h-5'>
  230. <LoadingAnim type='text' />
  231. </div>
  232. )
  233. : (
  234. <div>
  235. {annotation?.logAnnotation && (
  236. <div className='mb-1'>
  237. <div className='mb-3'>
  238. <Markdown className='line-through !text-gray-400' content={content} />
  239. </div>
  240. <EditTitle title={t('appAnnotation.editBy', {
  241. author: annotation?.logAnnotation.account?.name,
  242. })} />
  243. </div>
  244. )}
  245. <div>
  246. <Markdown content={annotation?.logAnnotation ? annotation?.logAnnotation.content : content} />
  247. </div>
  248. {(hasAnnotation && !annotation?.logAnnotation) && (
  249. <EditTitle className='mt-1' title={t('appAnnotation.editBy', {
  250. author: annotation.authorName,
  251. })} />
  252. )}
  253. </div>
  254. )}
  255. {
  256. !!citation?.length && !isThinking && isShowCitation && !isResponsing && (
  257. <Citation data={citation} showHitInfo={isShowCitationHitInfo} />
  258. )
  259. }
  260. </div>
  261. <div className='absolute top-[-14px] right-[-14px] flex flex-row justify-end gap-1'>
  262. {!item.isOpeningStatement && (
  263. <CopyBtn
  264. value={content}
  265. className={cn(s.copyBtn, 'mr-1')}
  266. />
  267. )}
  268. {(supportAnnotation && !item.isOpeningStatement) && (
  269. <AnnotationCtrlBtn
  270. appId={appId!}
  271. messageId={id}
  272. annotationId={annotation?.id || ''}
  273. className={cn(s.annotationBtn, 'ml-1')}
  274. cached={hasAnnotation}
  275. query={question}
  276. answer={content}
  277. onAdded={(id, authorName) => onAnnotationAdded?.(id, authorName, question, content)}
  278. onEdit={() => setIsShowReplyModal(true)}
  279. onRemoved={onAnnotationRemoved!}
  280. />
  281. )}
  282. <EditReplyModal
  283. isShow={isShowReplyModal}
  284. onHide={() => setIsShowReplyModal(false)}
  285. query={question}
  286. answer={content}
  287. onEdited={onAnnotationEdited!}
  288. onAdded={onAnnotationAdded!}
  289. appId={appId!}
  290. messageId={id}
  291. annotationId={annotation?.id || ''}
  292. createdAt={annotation?.created_at}
  293. onRemove={() => { }}
  294. />
  295. {hasAnnotation && renderHasAnnotationBtn()}
  296. {!feedbackDisabled && !item.feedbackDisabled && renderItemOperation(displayScene !== 'console')}
  297. {/* Admin feedback is displayed only in the background. */}
  298. {!feedbackDisabled && renderFeedbackRating(localAdminFeedback?.rating, false, false)}
  299. {/* User feedback must be displayed */}
  300. {!feedbackDisabled && renderFeedbackRating(feedback?.rating, !isHideFeedbackEdit, displayScene !== 'console')}
  301. </div>
  302. </div>
  303. {more && <MoreInfo className='invisible group-hover:visible' more={more} isQuestion={false} />}
  304. </div>
  305. </div>
  306. </div>
  307. </div>
  308. )
  309. }
  310. export default React.memo(Answer)