index.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. /* eslint-disable multiline-ternary */
  2. 'use client'
  3. import type { FC } from 'react'
  4. import React, { useEffect, useRef, useState } from 'react'
  5. import {
  6. RiAddLine,
  7. RiDeleteBinLine,
  8. } from '@remixicon/react'
  9. import { useContext } from 'use-context-selector'
  10. import produce from 'immer'
  11. import { useTranslation } from 'react-i18next'
  12. import { useBoolean } from 'ahooks'
  13. import { ReactSortable } from 'react-sortablejs'
  14. import cn from '@/utils/classnames'
  15. import ConfigContext from '@/context/debug-configuration'
  16. import Panel from '@/app/components/app/configuration/base/feature-panel'
  17. import Button from '@/app/components/base/button'
  18. import OperationBtn from '@/app/components/app/configuration/base/operation-btn'
  19. import { getInputKeys } from '@/app/components/base/block-input'
  20. import ConfirmAddVar from '@/app/components/app/configuration/config-prompt/confirm-add-var'
  21. import { getNewVar } from '@/utils/var'
  22. import { varHighlightHTML } from '@/app/components/app/configuration/base/var-highlight'
  23. import Toast from '@/app/components/base/toast'
  24. const MAX_QUESTION_NUM = 5
  25. export type IOpeningStatementProps = {
  26. value: string
  27. readonly?: boolean
  28. onChange?: (value: string) => void
  29. suggestedQuestions?: string[]
  30. onSuggestedQuestionsChange?: (value: string[]) => void
  31. }
  32. // regex to match the {{}} and replace it with a span
  33. const regex = /\{\{([^}]+)\}\}/g
  34. const OpeningStatement: FC<IOpeningStatementProps> = ({
  35. value = '',
  36. readonly,
  37. onChange,
  38. suggestedQuestions = [],
  39. onSuggestedQuestionsChange = () => { },
  40. }) => {
  41. const { t } = useTranslation()
  42. const {
  43. modelConfig,
  44. setModelConfig,
  45. } = useContext(ConfigContext)
  46. const promptVariables = modelConfig.configs.prompt_variables
  47. const [notIncludeKeys, setNotIncludeKeys] = useState<string[]>([])
  48. const hasValue = !!(value || '').trim()
  49. const inputRef = useRef<HTMLTextAreaElement>(null)
  50. const [isFocus, { setTrue: didSetFocus, setFalse: setBlur }] = useBoolean(false)
  51. const setFocus = () => {
  52. didSetFocus()
  53. setTimeout(() => {
  54. const input = inputRef.current
  55. if (input) {
  56. input.focus()
  57. input.setSelectionRange(input.value.length, input.value.length)
  58. }
  59. }, 0)
  60. }
  61. const [tempValue, setTempValue] = useState(value)
  62. useEffect(() => {
  63. setTempValue(value || '')
  64. }, [value])
  65. const [tempSuggestedQuestions, setTempSuggestedQuestions] = useState(suggestedQuestions || [])
  66. const notEmptyQuestions = tempSuggestedQuestions.filter(question => !!question && question.trim())
  67. const coloredContent = (tempValue || '')
  68. .replace(/</g, '&lt;')
  69. .replace(/>/g, '&gt;')
  70. .replace(regex, varHighlightHTML({ name: '$1' })) // `<span class="${highLightClassName}">{{$1}}</span>`
  71. .replace(/\n/g, '<br />')
  72. const handleEdit = () => {
  73. if (readonly)
  74. return
  75. setFocus()
  76. }
  77. const [isShowConfirmAddVar, { setTrue: showConfirmAddVar, setFalse: hideConfirmAddVar }] = useBoolean(false)
  78. const handleCancel = () => {
  79. setBlur()
  80. setTempValue(value)
  81. setTempSuggestedQuestions(suggestedQuestions)
  82. }
  83. const handleConfirm = () => {
  84. if (!(tempValue || '').trim()) {
  85. Toast.notify({
  86. type: 'error',
  87. message: t('common.errorMsg.fieldRequired', {
  88. field: t('appDebug.openingStatement.title'),
  89. }),
  90. })
  91. return
  92. }
  93. const keys = getInputKeys(tempValue)
  94. const promptKeys = promptVariables.map(item => item.key)
  95. let notIncludeKeys: string[] = []
  96. if (promptKeys.length === 0) {
  97. if (keys.length > 0)
  98. notIncludeKeys = keys
  99. }
  100. else {
  101. notIncludeKeys = keys.filter(key => !promptKeys.includes(key))
  102. }
  103. if (notIncludeKeys.length > 0) {
  104. setNotIncludeKeys(notIncludeKeys)
  105. showConfirmAddVar()
  106. return
  107. }
  108. setBlur()
  109. onChange?.(tempValue)
  110. onSuggestedQuestionsChange(tempSuggestedQuestions)
  111. }
  112. const cancelAutoAddVar = () => {
  113. onChange?.(tempValue)
  114. hideConfirmAddVar()
  115. setBlur()
  116. }
  117. const autoAddVar = () => {
  118. const newModelConfig = produce(modelConfig, (draft) => {
  119. draft.configs.prompt_variables = [...draft.configs.prompt_variables, ...notIncludeKeys.map(key => getNewVar(key, 'string'))]
  120. })
  121. onChange?.(tempValue)
  122. setModelConfig(newModelConfig)
  123. hideConfirmAddVar()
  124. setBlur()
  125. }
  126. const headerRight = !readonly ? (
  127. isFocus ? (
  128. <div className='flex items-center space-x-1'>
  129. <Button
  130. variant='ghost'
  131. size='small'
  132. onClick={handleCancel}
  133. >
  134. {t('common.operation.cancel')}
  135. </Button>
  136. <Button
  137. onClick={handleConfirm}
  138. variant="primary"
  139. size='small'
  140. >
  141. {t('common.operation.save')}
  142. </Button>
  143. </div>
  144. ) : (
  145. <OperationBtn type='edit' actionName={hasValue ? '' : t('appDebug.openingStatement.writeOpener') as string} onClick={handleEdit} />
  146. )
  147. ) : null
  148. const renderQuestions = () => {
  149. return isFocus ? (
  150. <div>
  151. <div className='flex items-center py-2'>
  152. <div className='shrink-0 flex space-x-0.5 leading-[18px] text-xs font-medium text-gray-500'>
  153. <div className='uppercase'>{t('appDebug.openingStatement.openingQuestion')}</div>
  154. <div>·</div>
  155. <div>{tempSuggestedQuestions.length}/{MAX_QUESTION_NUM}</div>
  156. </div>
  157. <div className='ml-3 grow w-0 h-px bg-[#243, 244, 246]'></div>
  158. </div>
  159. <ReactSortable
  160. className="space-y-1"
  161. list={tempSuggestedQuestions.map((name, index) => {
  162. return {
  163. id: index,
  164. name,
  165. }
  166. })}
  167. setList={list => setTempSuggestedQuestions(list.map(item => item.name))}
  168. handle='.handle'
  169. ghostClass="opacity-50"
  170. animation={150}
  171. >
  172. {tempSuggestedQuestions.map((question, index) => {
  173. return (
  174. <div className='group relative rounded-lg border border-gray-200 flex items-center pl-2.5 hover:border-gray-300 hover:bg-white' key={index}>
  175. <div className='handle flex items-center justify-center w-4 h-4 cursor-grab'>
  176. <svg width="6" height="10" viewBox="0 0 6 10" fill="none" xmlns="http://www.w3.org/2000/svg">
  177. <path fillRule="evenodd" clipRule="evenodd" d="M1 2C1.55228 2 2 1.55228 2 1C2 0.447715 1.55228 0 1 0C0.447715 0 0 0.447715 0 1C0 1.55228 0.447715 2 1 2ZM1 6C1.55228 6 2 5.55228 2 5C2 4.44772 1.55228 4 1 4C0.447715 4 0 4.44772 0 5C0 5.55228 0.447715 6 1 6ZM6 1C6 1.55228 5.55228 2 5 2C4.44772 2 4 1.55228 4 1C4 0.447715 4.44772 0 5 0C5.55228 0 6 0.447715 6 1ZM5 6C5.55228 6 6 5.55228 6 5C6 4.44772 5.55228 4 5 4C4.44772 4 4 4.44772 4 5C4 5.55228 4.44772 6 5 6ZM2 9C2 9.55229 1.55228 10 1 10C0.447715 10 0 9.55229 0 9C0 8.44771 0.447715 8 1 8C1.55228 8 2 8.44771 2 9ZM5 10C5.55228 10 6 9.55229 6 9C6 8.44771 5.55228 8 5 8C4.44772 8 4 8.44771 4 9C4 9.55229 4.44772 10 5 10Z" fill="#98A2B3" />
  178. </svg>
  179. </div>
  180. <input
  181. type="input"
  182. value={question || ''}
  183. onChange={(e) => {
  184. const value = e.target.value
  185. setTempSuggestedQuestions(tempSuggestedQuestions.map((item, i) => {
  186. if (index === i)
  187. return value
  188. return item
  189. }))
  190. }}
  191. className={'w-full overflow-x-auto pl-1.5 pr-8 text-sm leading-9 text-gray-900 border-0 grow h-9 bg-transparent focus:outline-none cursor-pointer rounded-lg'}
  192. />
  193. <div
  194. className='block absolute top-1/2 translate-y-[-50%] right-1.5 p-1 rounded-md cursor-pointer hover:bg-[#FEE4E2] hover:text-[#D92D20]'
  195. onClick={() => {
  196. setTempSuggestedQuestions(tempSuggestedQuestions.filter((_, i) => index !== i))
  197. }}
  198. >
  199. <RiDeleteBinLine className='w-3.5 h-3.5' />
  200. </div>
  201. </div>
  202. )
  203. })}</ReactSortable>
  204. {tempSuggestedQuestions.length < MAX_QUESTION_NUM && (
  205. <div
  206. onClick={() => { setTempSuggestedQuestions([...tempSuggestedQuestions, '']) }}
  207. className='mt-1 flex items-center h-9 px-3 gap-2 rounded-lg cursor-pointer text-gray-400 bg-gray-100 hover:bg-gray-200'>
  208. <RiAddLine className='w-4 h-4' />
  209. <div className='text-gray-500 text-[13px]'>{t('appDebug.variableConfig.addOption')}</div>
  210. </div>
  211. )}
  212. </div>
  213. ) : (
  214. <div className='mt-1.5 flex flex-wrap'>
  215. {notEmptyQuestions.map((question, index) => {
  216. return (
  217. <div key={index} className='mt-1 mr-1 max-w-full truncate last:mr-0 shrink-0 leading-8 items-center px-2.5 rounded-lg border border-gray-200 shadow-xs bg-white text-[13px] font-normal text-gray-900 cursor-pointer'>
  218. {question}
  219. </div>
  220. )
  221. })}
  222. </div>
  223. )
  224. }
  225. return (
  226. <Panel
  227. className={cn(isShowConfirmAddVar && 'h-[220px]', 'relative mt-4 !bg-gray-25')}
  228. title={t('appDebug.openingStatement.title')}
  229. headerIcon={
  230. <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
  231. <path fillRule="evenodd" clipRule="evenodd" d="M8.33353 1.33301C4.83572 1.33301 2.00019 4.16854 2.00019 7.66634C2.00019 8.37301 2.11619 9.05395 2.3307 9.69036C2.36843 9.80229 2.39063 9.86853 2.40507 9.91738L2.40979 9.93383L2.40729 9.93903C2.39015 9.97437 2.36469 10.0218 2.31705 10.11L1.2158 12.1484C1.14755 12.2746 1.07633 12.4064 1.02735 12.5209C0.978668 12.6348 0.899813 12.8437 0.938613 13.0914C0.984094 13.3817 1.15495 13.6373 1.40581 13.7903C1.61981 13.9208 1.843 13.9279 1.96683 13.9264C2.09141 13.925 2.24036 13.9095 2.38314 13.8947L5.81978 13.5395C5.87482 13.5338 5.9036 13.5309 5.92468 13.5292L5.92739 13.529L5.93564 13.532C5.96154 13.5413 5.99666 13.5548 6.0573 13.5781C6.76459 13.8506 7.53244 13.9997 8.33353 13.9997C11.8313 13.9997 14.6669 11.1641 14.6669 7.66634C14.6669 4.16854 11.8313 1.33301 8.33353 1.33301ZM5.9799 5.72116C6.73142 5.08698 7.73164 5.27327 8.33144 5.96584C8.93125 5.27327 9.91854 5.09365 10.683 5.72116C11.4474 6.34867 11.5403 7.41567 10.9501 8.16572C10.5845 8.6304 9.6668 9.47911 9.02142 10.0576C8.78435 10.2702 8.66582 10.3764 8.52357 10.4192C8.40154 10.456 8.26134 10.456 8.13931 10.4192C7.99706 10.3764 7.87853 10.2702 7.64147 10.0576C6.99609 9.47911 6.07839 8.6304 5.71276 8.16572C5.12259 7.41567 5.22839 6.35534 5.9799 5.72116Z" fill="#E74694" />
  232. </svg>
  233. }
  234. headerRight={headerRight}
  235. hasHeaderBottomBorder={!hasValue}
  236. isFocus={isFocus}
  237. >
  238. <div className='text-gray-700 text-sm'>
  239. {(hasValue || (!hasValue && isFocus)) ? (
  240. <>
  241. {isFocus
  242. ? (
  243. <div>
  244. <textarea
  245. ref={inputRef}
  246. value={tempValue}
  247. rows={3}
  248. onChange={e => setTempValue(e.target.value)}
  249. className="w-full px-0 text-sm border-0 bg-transparent focus:outline-none "
  250. placeholder={t('appDebug.openingStatement.placeholder') as string}
  251. >
  252. </textarea>
  253. </div>
  254. )
  255. : (
  256. <div dangerouslySetInnerHTML={{
  257. __html: coloredContent,
  258. }}></div>
  259. )}
  260. {renderQuestions()}
  261. </>) : (
  262. <div className='pt-2 pb-1 text-xs text-gray-500'>{t('appDebug.openingStatement.noDataPlaceHolder')}</div>
  263. )}
  264. {isShowConfirmAddVar && (
  265. <ConfirmAddVar
  266. varNameArr={notIncludeKeys}
  267. onConfrim={autoAddVar}
  268. onCancel={cancelAutoAddVar}
  269. onHide={hideConfirmAddVar}
  270. />
  271. )}
  272. </div>
  273. </Panel>
  274. )
  275. }
  276. export default React.memo(OpeningStatement)