index.tsx 12 KB

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