Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

index.tsx 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { useEffect, useRef, useState } from 'react'
  4. import { useContext } from 'use-context-selector'
  5. import cn from 'classnames'
  6. import { HandThumbDownIcon, HandThumbUpIcon } from '@heroicons/react/24/outline'
  7. import { UserCircleIcon } from '@heroicons/react/24/solid'
  8. import { useTranslation } from 'react-i18next'
  9. import { randomString } from '../../app-sidebar/basic'
  10. import s from './style.module.css'
  11. import LoadingAnim from './loading-anim'
  12. import CopyBtn from './copy-btn'
  13. import Tooltip from '@/app/components/base/tooltip'
  14. import { ToastContext } from '@/app/components/base/toast'
  15. import AutoHeightTextarea from '@/app/components/base/auto-height-textarea'
  16. import Button from '@/app/components/base/button'
  17. import type { Annotation, MessageRating } from '@/models/log'
  18. import AppContext from '@/context/app-context'
  19. import { Markdown } from '@/app/components/base/markdown'
  20. import { formatNumber } from '@/utils/format'
  21. import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
  22. const stopIcon = (
  23. <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
  24. <path fill-rule="evenodd" clip-rule="evenodd" d="M7.00004 0.583313C3.45621 0.583313 0.583374 3.45615 0.583374 6.99998C0.583374 10.5438 3.45621 13.4166 7.00004 13.4166C10.5439 13.4166 13.4167 10.5438 13.4167 6.99998C13.4167 3.45615 10.5439 0.583313 7.00004 0.583313ZM4.73029 4.98515C4.66671 5.10993 4.66671 5.27328 4.66671 5.59998V8.39998C4.66671 8.72668 4.66671 8.89003 4.73029 9.01481C4.78621 9.12457 4.87545 9.21381 4.98521 9.26973C5.10999 9.33331 5.27334 9.33331 5.60004 9.33331H8.40004C8.72674 9.33331 8.89009 9.33331 9.01487 9.26973C9.12463 9.21381 9.21387 9.12457 9.2698 9.01481C9.33337 8.89003 9.33337 8.72668 9.33337 8.39998V5.59998C9.33337 5.27328 9.33337 5.10993 9.2698 4.98515C9.21387 4.87539 9.12463 4.78615 9.01487 4.73023C8.89009 4.66665 8.72674 4.66665 8.40004 4.66665H5.60004C5.27334 4.66665 5.10999 4.66665 4.98521 4.73023C4.87545 4.78615 4.78621 4.87539 4.73029 4.98515Z" fill="#667085" />
  25. </svg>
  26. )
  27. export type Feedbacktype = {
  28. rating: MessageRating
  29. content?: string | null
  30. }
  31. export type FeedbackFunc = (messageId: string, feedback: Feedbacktype) => Promise<any>
  32. export type SubmitAnnotationFunc = (messageId: string, content: string) => Promise<any>
  33. export type DisplayScene = 'web' | 'console'
  34. export type IChatProps = {
  35. chatList: IChatItem[]
  36. /**
  37. * Whether to display the editing area and rating status
  38. */
  39. feedbackDisabled?: boolean
  40. /**
  41. * Whether to display the input area
  42. */
  43. isHideFeedbackEdit?: boolean
  44. isHideSendInput?: boolean
  45. onFeedback?: FeedbackFunc
  46. onSubmitAnnotation?: SubmitAnnotationFunc
  47. checkCanSend?: () => boolean
  48. onSend?: (message: string) => void
  49. displayScene?: DisplayScene
  50. useCurrentUserAvatar?: boolean
  51. isResponsing?: boolean
  52. abortResponsing?: () => void
  53. controlClearQuery?: number
  54. controlFocus?: number
  55. isShowSuggestion?: boolean
  56. suggestionList?: string[]
  57. }
  58. export type MessageMore = {
  59. time: string
  60. tokens: number
  61. latency: number | string
  62. }
  63. export type IChatItem = {
  64. id: string
  65. content: string
  66. /**
  67. * Specific message type
  68. */
  69. isAnswer: boolean
  70. /**
  71. * The user feedback result of this message
  72. */
  73. feedback?: Feedbacktype
  74. /**
  75. * The admin feedback result of this message
  76. */
  77. adminFeedback?: Feedbacktype
  78. /**
  79. * Whether to hide the feedback area
  80. */
  81. feedbackDisabled?: boolean
  82. /**
  83. * More information about this message
  84. */
  85. more?: MessageMore
  86. annotation?: Annotation
  87. useCurrentUserAvatar?: boolean
  88. isOpeningStatement?: boolean
  89. }
  90. const OperationBtn = ({ innerContent, onClick, className }: { innerContent: React.ReactNode; onClick?: () => void; className?: string }) => (
  91. <div
  92. 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 ${className ?? ''}`}
  93. style={{ boxShadow: '0px 4px 6px -1px rgba(0, 0, 0, 0.1), 0px 2px 4px -2px rgba(0, 0, 0, 0.05)' }}
  94. onClick={onClick && onClick}
  95. >
  96. {innerContent}
  97. </div>
  98. )
  99. const MoreInfo: FC<{ more: MessageMore; isQuestion: boolean }> = ({ more, isQuestion }) => {
  100. const { t } = useTranslation()
  101. return (<div className={`mt-1 space-x-2 text-xs text-gray-400 ${isQuestion ? 'mr-2 text-right ' : 'ml-2 text-left float-right'}`}>
  102. <span>{`${t('appLog.detail.timeConsuming')} ${more.latency}${t('appLog.detail.second')}`}</span>
  103. <span>{`${t('appLog.detail.tokenCost')} ${formatNumber(more.tokens)}`}</span>
  104. <span>· </span>
  105. <span>{more.time} </span>
  106. </div>)
  107. }
  108. const OpeningStatementIcon: FC<{ className?: string }> = ({ className }) => (
  109. <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
  110. <path fillRule="evenodd" clipRule="evenodd" d="M6.25002 1C3.62667 1 1.50002 3.12665 1.50002 5.75C1.50002 6.28 1.58702 6.79071 1.7479 7.26801C1.7762 7.35196 1.79285 7.40164 1.80368 7.43828L1.80722 7.45061L1.80535 7.45452C1.79249 7.48102 1.77339 7.51661 1.73766 7.58274L0.911727 9.11152C0.860537 9.20622 0.807123 9.30503 0.770392 9.39095C0.733879 9.47635 0.674738 9.63304 0.703838 9.81878C0.737949 10.0365 0.866092 10.2282 1.05423 10.343C1.21474 10.4409 1.38213 10.4461 1.475 10.4451C1.56844 10.444 1.68015 10.4324 1.78723 10.4213L4.36472 10.1549C4.406 10.1506 4.42758 10.1484 4.44339 10.1472L4.44542 10.147L4.45161 10.1492C4.47103 10.1562 4.49738 10.1663 4.54285 10.1838C5.07332 10.3882 5.64921 10.5 6.25002 10.5C8.87338 10.5 11 8.37335 11 5.75C11 3.12665 8.87338 1 6.25002 1ZM4.48481 4.29111C5.04844 3.81548 5.7986 3.9552 6.24846 4.47463C6.69831 3.9552 7.43879 3.82048 8.01211 4.29111C8.58544 4.76175 8.6551 5.562 8.21247 6.12453C7.93825 6.47305 7.24997 7.10957 6.76594 7.54348C6.58814 7.70286 6.49924 7.78255 6.39255 7.81466C6.30103 7.84221 6.19589 7.84221 6.10436 7.81466C5.99767 7.78255 5.90878 7.70286 5.73098 7.54348C5.24694 7.10957 4.55867 6.47305 4.28444 6.12453C3.84182 5.562 3.92117 4.76675 4.48481 4.29111Z" fill="#667085" />
  111. </svg>
  112. )
  113. const RatingIcon: FC<{ isLike: boolean }> = ({ isLike }) => {
  114. return isLike ? <HandThumbUpIcon className='w-4 h-4' /> : <HandThumbDownIcon className='w-4 h-4' />
  115. }
  116. const EditIcon: FC<{ className?: string }> = ({ className }) => {
  117. return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" className={className}>
  118. <path d="M14 11.9998L13.3332 12.7292C12.9796 13.1159 12.5001 13.3332 12.0001 13.3332C11.5001 13.3332 11.0205 13.1159 10.6669 12.7292C10.3128 12.3432 9.83332 12.1265 9.33345 12.1265C8.83359 12.1265 8.35409 12.3432 7.99998 12.7292M2 13.3332H3.11636C3.44248 13.3332 3.60554 13.3332 3.75899 13.2963C3.89504 13.2637 4.0251 13.2098 4.1444 13.1367C4.27895 13.0542 4.39425 12.9389 4.62486 12.7083L13 4.33316C13.5523 3.78087 13.5523 2.88544 13 2.33316C12.4477 1.78087 11.5523 1.78087 11 2.33316L2.62484 10.7083C2.39424 10.9389 2.27894 11.0542 2.19648 11.1888C2.12338 11.3081 2.0695 11.4381 2.03684 11.5742C2 11.7276 2 11.8907 2 12.2168V13.3332Z" stroke="#6B7280" strokeLinecap="round" strokeLinejoin="round" />
  119. </svg>
  120. }
  121. export const EditIconSolid: FC<{ className?: string }> = ({ className }) => {
  122. return <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg" className={className}>
  123. <path fill-rule="evenodd" clipRule="evenodd" d="M10.8374 8.63108C11.0412 8.81739 11.0554 9.13366 10.8691 9.33747L10.369 9.88449C10.0142 10.2725 9.52293 10.5001 9.00011 10.5001C8.47746 10.5001 7.98634 10.2727 7.63157 9.8849C7.45561 9.69325 7.22747 9.59515 7.00014 9.59515C6.77271 9.59515 6.54446 9.69335 6.36846 9.88517C6.18177 10.0886 5.86548 10.1023 5.66201 9.91556C5.45853 9.72888 5.44493 9.41259 5.63161 9.20911C5.98678 8.82201 6.47777 8.59515 7.00014 8.59515C7.52251 8.59515 8.0135 8.82201 8.36867 9.20911L8.36924 9.20974C8.54486 9.4018 8.77291 9.50012 9.00011 9.50012C9.2273 9.50012 9.45533 9.40182 9.63095 9.20979L10.131 8.66276C10.3173 8.45895 10.6336 8.44476 10.8374 8.63108Z" fill="#6B7280" />
  124. <path fill-rule="evenodd" clipRule="evenodd" d="M7.89651 1.39656C8.50599 0.787085 9.49414 0.787084 10.1036 1.39656C10.7131 2.00604 10.7131 2.99419 10.1036 3.60367L3.82225 9.88504C3.81235 9.89494 3.80254 9.90476 3.79281 9.91451C3.64909 10.0585 3.52237 10.1855 3.3696 10.2791C3.23539 10.3613 3.08907 10.4219 2.93602 10.4587C2.7618 10.5005 2.58242 10.5003 2.37897 10.5001C2.3652 10.5001 2.35132 10.5001 2.33732 10.5001H1.50005C1.22391 10.5001 1.00005 10.2763 1.00005 10.0001V9.16286C1.00005 9.14886 1.00004 9.13497 1.00003 9.1212C0.999836 8.91776 0.999669 8.73838 1.0415 8.56416C1.07824 8.4111 1.13885 8.26479 1.22109 8.13058C1.31471 7.97781 1.44166 7.85109 1.58566 7.70736C1.5954 7.69764 1.60523 7.68783 1.61513 7.67793L7.89651 1.39656Z" fill="#6B7280" />
  125. </svg>
  126. }
  127. const TryToAskIcon = (
  128. <svg width="11" height="10" viewBox="0 0 11 10" fill="none" xmlns="http://www.w3.org/2000/svg">
  129. <path d="M5.88889 0.683718C5.827 0.522805 5.67241 0.416626 5.5 0.416626C5.3276 0.416626 5.173 0.522805 5.11111 0.683718L4.27279 2.86334C4.14762 3.18877 4.10829 3.28255 4.05449 3.35821C4.00051 3.43413 3.93418 3.50047 3.85826 3.55445C3.78259 3.60825 3.68881 3.64758 3.36338 3.77275L1.18376 4.61106C1.02285 4.67295 0.916668 4.82755 0.916668 4.99996C0.916668 5.17236 1.02285 5.32696 1.18376 5.38885L3.36338 6.22717C3.68881 6.35234 3.78259 6.39167 3.85826 6.44547C3.93418 6.49945 4.00051 6.56578 4.05449 6.6417C4.10829 6.71737 4.14762 6.81115 4.27279 7.13658L5.11111 9.3162C5.173 9.47711 5.3276 9.58329 5.5 9.58329C5.67241 9.58329 5.82701 9.47711 5.8889 9.3162L6.72721 7.13658C6.85238 6.81115 6.89171 6.71737 6.94551 6.6417C6.99949 6.56578 7.06583 6.49945 7.14175 6.44547C7.21741 6.39167 7.31119 6.35234 7.63662 6.22717L9.81624 5.38885C9.97715 5.32696 10.0833 5.17236 10.0833 4.99996C10.0833 4.82755 9.97715 4.67295 9.81624 4.61106L7.63662 3.77275C7.31119 3.64758 7.21741 3.60825 7.14175 3.55445C7.06583 3.50047 6.99949 3.43413 6.94551 3.35821C6.89171 3.28255 6.85238 3.18877 6.72721 2.86334L5.88889 0.683718Z" fill="#667085" />
  130. </svg>
  131. )
  132. const Divider: FC<{ name: string }> = ({ name }) => {
  133. const { t } = useTranslation()
  134. return <div className='flex items-center my-2'>
  135. <span className='text-xs text-gray-500 inline-flex items-center mr-2'>
  136. <EditIconSolid className='mr-1' />{t('appLog.detail.annotationTip', { user: name })}
  137. </span>
  138. <div className='h-[1px] bg-gray-200 flex-1'></div>
  139. </div>
  140. }
  141. const IconWrapper: FC<{ children: React.ReactNode | string }> = ({ children }) => {
  142. return <div className={'rounded-lg h-6 w-6 flex items-center justify-center hover:bg-gray-100'}>
  143. {children}
  144. </div>
  145. }
  146. type IAnswerProps = {
  147. item: IChatItem
  148. feedbackDisabled: boolean
  149. isHideFeedbackEdit: boolean
  150. onFeedback?: FeedbackFunc
  151. onSubmitAnnotation?: SubmitAnnotationFunc
  152. displayScene: DisplayScene
  153. isResponsing?: boolean
  154. }
  155. // The component needs to maintain its own state to control whether to display input component
  156. const Answer: FC<IAnswerProps> = ({ item, feedbackDisabled = false, isHideFeedbackEdit = false, onFeedback, onSubmitAnnotation, displayScene = 'web', isResponsing }) => {
  157. const { id, content, more, feedback, adminFeedback, annotation: initAnnotation } = item
  158. const [showEdit, setShowEdit] = useState(false)
  159. const [loading, setLoading] = useState(false)
  160. const [annotation, setAnnotation] = useState<Annotation | undefined | null>(initAnnotation)
  161. const [inputValue, setInputValue] = useState<string>(initAnnotation?.content ?? '')
  162. const [localAdminFeedback, setLocalAdminFeedback] = useState<Feedbacktype | undefined | null>(adminFeedback)
  163. const { userProfile } = useContext(AppContext)
  164. const { t } = useTranslation()
  165. /**
  166. * Render feedback results (distinguish between users and administrators)
  167. * User reviews cannot be cancelled in Console
  168. * @param rating feedback result
  169. * @param isUserFeedback Whether it is user's feedback
  170. * @param isWebScene Whether it is web scene
  171. * @returns comp
  172. */
  173. const renderFeedbackRating = (rating: MessageRating | undefined, isUserFeedback = true, isWebScene = true) => {
  174. if (!rating)
  175. return null
  176. const isLike = rating === 'like'
  177. const ratingIconClassname = isLike ? 'text-primary-600 bg-primary-100 hover:bg-primary-200' : 'text-red-600 bg-red-100 hover:bg-red-200'
  178. const UserSymbol = <UserCircleIcon className='absolute top-[-2px] left-[18px] w-3 h-3 rounded-lg text-gray-400 bg-white' />
  179. // The tooltip is always displayed, but the content is different for different scenarios.
  180. return (
  181. <Tooltip
  182. selector={`user-feedback-${randomString(16)}`}
  183. content={(isWebScene || (!isUserFeedback && !isWebScene)) ? isLike ? '取消赞同' : '取消反对' : (!isWebScene && isUserFeedback) ? `用户表示${isLike ? '赞同' : '反对'}` : ''}
  184. >
  185. <div
  186. 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' : ''}`}
  187. style={{ boxShadow: '0px 4px 6px -1px rgba(0, 0, 0, 0.1), 0px 2px 4px -2px rgba(0, 0, 0, 0.05)' }}
  188. {...((isWebScene || (!isUserFeedback && !isWebScene))
  189. ? {
  190. onClick: async () => {
  191. const res = await onFeedback?.(id, { rating: null })
  192. if (res && !isWebScene)
  193. setLocalAdminFeedback({ rating: null })
  194. },
  195. }
  196. : {})}
  197. >
  198. <div className={`${ratingIconClassname} rounded-lg h-6 w-6 flex items-center justify-center`}>
  199. <RatingIcon isLike={isLike} />
  200. </div>
  201. {!isWebScene && isUserFeedback && UserSymbol}
  202. </div>
  203. </Tooltip>
  204. )
  205. }
  206. /**
  207. * Different scenarios have different operation items.
  208. * @param isWebScene Whether it is web scene
  209. * @returns comp
  210. */
  211. const renderItemOperation = (isWebScene = true) => {
  212. const userOperation = () => {
  213. return feedback?.rating
  214. ? null
  215. : <div className='flex gap-1'>
  216. <Tooltip selector={`user-feedback-${randomString(16)}`} content={t('appLog.detail.operation.like') as string}>
  217. {OperationBtn({ innerContent: <IconWrapper><RatingIcon isLike={true} /></IconWrapper>, onClick: () => onFeedback?.(id, { rating: 'like' }) })}
  218. </Tooltip>
  219. <Tooltip selector={`user-feedback-${randomString(16)}`} content={t('appLog.detail.operation.dislike') as string}>
  220. {OperationBtn({ innerContent: <IconWrapper><RatingIcon isLike={false} /></IconWrapper>, onClick: () => onFeedback?.(id, { rating: 'dislike' }) })}
  221. </Tooltip>
  222. </div>
  223. }
  224. const adminOperation = () => {
  225. return <div className='flex gap-1'>
  226. <Tooltip selector={`user-feedback-${randomString(16)}`} content={t('appLog.detail.operation.addAnnotation') as string}>
  227. {OperationBtn({
  228. innerContent: <IconWrapper><EditIcon className='hover:text-gray-800' /></IconWrapper>,
  229. onClick: () => setShowEdit(true),
  230. })}
  231. </Tooltip>
  232. {!localAdminFeedback?.rating && <>
  233. <Tooltip selector={`user-feedback-${randomString(16)}`} content={t('appLog.detail.operation.like') as string}>
  234. {OperationBtn({
  235. innerContent: <IconWrapper><RatingIcon isLike={true} /></IconWrapper>,
  236. onClick: async () => {
  237. const res = await onFeedback?.(id, { rating: 'like' })
  238. if (res)
  239. setLocalAdminFeedback({ rating: 'like' })
  240. },
  241. })}
  242. </Tooltip>
  243. <Tooltip selector={`user-feedback-${randomString(16)}`} content={t('appLog.detail.operation.dislike') as string}>
  244. {OperationBtn({
  245. innerContent: <IconWrapper><RatingIcon isLike={false} /></IconWrapper>,
  246. onClick: async () => {
  247. const res = await onFeedback?.(id, { rating: 'dislike' })
  248. if (res)
  249. setLocalAdminFeedback({ rating: 'dislike' })
  250. },
  251. })}
  252. </Tooltip>
  253. </>}
  254. </div>
  255. }
  256. return (
  257. <div className={`${s.itemOperation} flex gap-2`}>
  258. {isWebScene ? userOperation() : adminOperation()}
  259. </div>
  260. )
  261. }
  262. return (
  263. <div key={id}>
  264. <div className='flex items-start'>
  265. <div className={`${s.answerIcon} w-10 h-10 shrink-0`}>
  266. {isResponsing
  267. && <div className={s.typeingIcon}>
  268. <LoadingAnim type='avatar' />
  269. </div>
  270. }
  271. </div>
  272. <div className={s.answerWrapWrap}>
  273. <div className={`${s.answerWrap} ${showEdit ? 'w-full' : ''}`}>
  274. <div className={`${s.answer} relative text-sm text-gray-900`}>
  275. <div className={'ml-2 py-3 px-4 bg-gray-100 rounded-tr-2xl rounded-b-2xl'}>
  276. {item.isOpeningStatement && (
  277. <div className='flex items-center mb-1 gap-1'>
  278. <OpeningStatementIcon />
  279. <div className='text-xs text-gray-500'>{t('appDebug.openingStatement.title')}</div>
  280. </div>
  281. )}
  282. {(isResponsing && !content)
  283. ? (
  284. <div className='flex items-center justify-center w-6 h-5'>
  285. <LoadingAnim type='text' />
  286. </div>
  287. )
  288. : (
  289. <Markdown content={content} />
  290. )}
  291. {!showEdit
  292. ? (annotation?.content
  293. && <>
  294. <Divider name={annotation?.account?.name || userProfile?.name} />
  295. {annotation.content}
  296. </>)
  297. : <>
  298. <Divider name={annotation?.account?.name || userProfile?.name} />
  299. <AutoHeightTextarea
  300. placeholder={t('appLog.detail.operation.annotationPlaceholder') as string}
  301. value={inputValue}
  302. onChange={e => setInputValue(e.target.value)}
  303. minHeight={58}
  304. 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]`}
  305. />
  306. <div className="mt-2 flex flex-row">
  307. <Button
  308. type='primary'
  309. className='mr-2'
  310. loading={loading}
  311. onClick={async () => {
  312. if (!inputValue)
  313. return
  314. setLoading(true)
  315. const res = await onSubmitAnnotation?.(id, inputValue)
  316. if (res)
  317. setAnnotation({ ...annotation, content: inputValue } as any)
  318. setLoading(false)
  319. setShowEdit(false)
  320. }}>{t('common.operation.confirm')}</Button>
  321. <Button
  322. onClick={() => {
  323. setInputValue(annotation?.content ?? '')
  324. setShowEdit(false)
  325. }}>{t('common.operation.cancel')}</Button>
  326. </div>
  327. </>
  328. }
  329. </div>
  330. <div className='absolute top-[-14px] right-[-14px] flex flex-row justify-end gap-1'>
  331. <CopyBtn
  332. value={content}
  333. className={cn(s.copyBtn, 'mr-1')}
  334. />
  335. {!feedbackDisabled && !item.feedbackDisabled && renderItemOperation(displayScene !== 'console')}
  336. {/* Admin feedback is displayed only in the background. */}
  337. {!feedbackDisabled && renderFeedbackRating(localAdminFeedback?.rating, false, false)}
  338. {/* User feedback must be displayed */}
  339. {!feedbackDisabled && renderFeedbackRating(feedback?.rating, !isHideFeedbackEdit, displayScene !== 'console')}
  340. </div>
  341. </div>
  342. {more && <MoreInfo more={more} isQuestion={false} />}
  343. </div>
  344. </div>
  345. </div>
  346. </div>
  347. )
  348. }
  349. type IQuestionProps = Pick<IChatItem, 'id' | 'content' | 'more' | 'useCurrentUserAvatar'>
  350. const Question: FC<IQuestionProps> = ({ id, content, more, useCurrentUserAvatar }) => {
  351. const { userProfile } = useContext(AppContext)
  352. const userName = userProfile?.name
  353. return (
  354. <div className='flex items-start justify-end' key={id}>
  355. <div className={s.questionWrapWrap}>
  356. <div className={`${s.question} relative text-sm text-gray-900`}>
  357. <div
  358. className={'mr-2 py-3 px-4 bg-blue-500 rounded-tl-2xl rounded-b-2xl'}
  359. >
  360. <Markdown content={content} />
  361. </div>
  362. </div>
  363. {more && <MoreInfo more={more} isQuestion={true} />}
  364. </div>
  365. {useCurrentUserAvatar
  366. ? (
  367. <div className='w-10 h-10 shrink-0 leading-10 text-center mr-2 rounded-full bg-primary-600 text-white'>
  368. {userName?.[0].toLocaleUpperCase()}
  369. </div>
  370. )
  371. : (
  372. <div className={`${s.questionIcon} w-10 h-10 shrink-0 `}></div>
  373. )}
  374. </div>
  375. )
  376. }
  377. const Chat: FC<IChatProps> = ({
  378. chatList,
  379. feedbackDisabled = false,
  380. isHideFeedbackEdit = false,
  381. isHideSendInput = false,
  382. onFeedback,
  383. onSubmitAnnotation,
  384. checkCanSend,
  385. onSend = () => { },
  386. displayScene,
  387. useCurrentUserAvatar,
  388. isResponsing,
  389. abortResponsing,
  390. controlClearQuery,
  391. controlFocus,
  392. isShowSuggestion,
  393. suggestionList,
  394. }) => {
  395. const { t } = useTranslation()
  396. const { notify } = useContext(ToastContext)
  397. const isUseInputMethod = useRef(false)
  398. const [query, setQuery] = React.useState('')
  399. const handleContentChange = (e: any) => {
  400. const value = e.target.value
  401. setQuery(value)
  402. }
  403. const logError = (message: string) => {
  404. notify({ type: 'error', message, duration: 3000 })
  405. }
  406. const valid = () => {
  407. if (!query || query.trim() === '') {
  408. logError('Message cannot be empty')
  409. return false
  410. }
  411. return true
  412. }
  413. useEffect(() => {
  414. if (controlClearQuery)
  415. setQuery('')
  416. }, [controlClearQuery])
  417. const handleSend = () => {
  418. if (!valid() || (checkCanSend && !checkCanSend()))
  419. return
  420. onSend(query)
  421. if (!isResponsing)
  422. setQuery('')
  423. }
  424. const handleKeyUp = (e: any) => {
  425. if (e.code === 'Enter') {
  426. e.preventDefault()
  427. // prevent send message when using input method enter
  428. if (!e.shiftKey && !isUseInputMethod.current)
  429. handleSend()
  430. }
  431. }
  432. const haneleKeyDown = (e: any) => {
  433. isUseInputMethod.current = e.nativeEvent.isComposing
  434. if (e.code === 'Enter' && !e.shiftKey) {
  435. setQuery(query.replace(/\n$/, ''))
  436. e.preventDefault()
  437. }
  438. }
  439. const media = useBreakpoints()
  440. const isMobile = media === MediaType.mobile
  441. const sendBtn = <div className={cn(!(!query || query.trim() === '') && s.sendBtnActive, `${s.sendBtn} w-8 h-8 cursor-pointer rounded-md`)} onClick={handleSend}></div>
  442. return (
  443. <div className={cn(!feedbackDisabled && 'px-3.5', 'h-full')}>
  444. {/* Chat List */}
  445. <div className="h-full space-y-[30px]">
  446. {chatList.map((item) => {
  447. if (item.isAnswer) {
  448. const isLast = item.id === chatList[chatList.length - 1].id
  449. return <Answer
  450. key={item.id}
  451. item={item}
  452. feedbackDisabled={feedbackDisabled}
  453. isHideFeedbackEdit={isHideFeedbackEdit}
  454. onFeedback={onFeedback}
  455. onSubmitAnnotation={onSubmitAnnotation}
  456. displayScene={displayScene ?? 'web'}
  457. isResponsing={isResponsing && isLast}
  458. />
  459. }
  460. return <Question key={item.id} id={item.id} content={item.content} more={item.more} useCurrentUserAvatar={useCurrentUserAvatar} />
  461. })}
  462. </div>
  463. {
  464. !isHideSendInput && (
  465. <div className={cn(!feedbackDisabled && '!left-3.5 !right-3.5', 'absolute z-10 bottom-0 left-0 right-0')}>
  466. {isResponsing && (
  467. <div className='flex justify-center mb-4'>
  468. <Button className='flex items-center space-x-1 bg-white' onClick={() => abortResponsing?.()}>
  469. {stopIcon}
  470. <span className='text-xs text-gray-500 font-normal'>{t('appDebug.operation.stopResponding')}</span>
  471. </Button>
  472. </div>
  473. )}
  474. {
  475. isShowSuggestion && (
  476. <div className='pt-2 mb-2 '>
  477. <div className='flex items-center justify-center mb-2.5'>
  478. <div className='grow h-[1px]'
  479. style={{
  480. background: 'linear-gradient(270deg, #F3F4F6 0%, rgba(243, 244, 246, 0) 100%)',
  481. }}></div>
  482. <div className='shrink-0 flex items-center px-3 space-x-1'>
  483. {TryToAskIcon}
  484. <span className='text-xs text-gray-500 font-medium'>{t('appDebug.feature.suggestedQuestionsAfterAnswer.tryToAsk')}</span>
  485. </div>
  486. <div className='grow h-[1px]'
  487. style={{
  488. background: 'linear-gradient(270deg, rgba(243, 244, 246, 0) 0%, #F3F4F6 100%)',
  489. }}></div>
  490. </div>
  491. <div className='flex justify-center overflow-x-scroll pb-2'>
  492. {suggestionList?.map((item, index) => (
  493. <div className='shrink-0 flex justify-center mr-2'>
  494. <Button
  495. key={index}
  496. onClick={() => setQuery(item)}
  497. >
  498. <span className='text-primary-600 text-xs font-medium'>{item}</span>
  499. </Button>
  500. </div>
  501. ))}
  502. </div>
  503. </div>)
  504. }
  505. <div className="relative">
  506. <AutoHeightTextarea
  507. value={query}
  508. onChange={handleContentChange}
  509. onKeyUp={handleKeyUp}
  510. onKeyDown={haneleKeyDown}
  511. minHeight={48}
  512. autoFocus
  513. controlFocus={controlFocus}
  514. className={`${cn(s.textArea)} resize-none block w-full pl-3 bg-gray-50 border border-gray-200 rounded-md focus:outline-none sm:text-sm text-gray-700`}
  515. />
  516. <div className="absolute top-0 right-2 flex items-center h-[48px]">
  517. <div className={`${s.count} mr-4 h-5 leading-5 text-sm bg-gray-50 text-gray-500`}>{query.trim().length}</div>
  518. {isMobile
  519. ? sendBtn
  520. : (
  521. <Tooltip
  522. selector='send-tip'
  523. htmlContent={
  524. <div>
  525. <div>{t('common.operation.send')} Enter</div>
  526. <div>{t('common.operation.lineBreak')} Shift Enter</div>
  527. </div>
  528. }
  529. >
  530. {sendBtn}
  531. </Tooltip>
  532. )}
  533. </div>
  534. </div>
  535. </div>
  536. )
  537. }
  538. </div>
  539. )
  540. }
  541. export default React.memo(Chat)