index.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { useEffect, useState } from 'react'
  4. import { useTranslation } from 'react-i18next'
  5. import { useContext } from 'use-context-selector'
  6. import TemplateVarPanel, { PanelTitle, VarOpBtnGroup } from '../value-panel'
  7. import s from './style.module.css'
  8. import { AppInfo, ChatBtn, EditBtn, FootLogo, PromptTemplate } from './massive-component'
  9. import type { SiteInfo } from '@/models/share'
  10. import type { PromptConfig } from '@/models/debug'
  11. import { ToastContext } from '@/app/components/base/toast'
  12. import Select from '@/app/components/base/select'
  13. import { DEFAULT_VALUE_MAX_LEN } from '@/config'
  14. // regex to match the {{}} and replace it with a span
  15. const regex = /\{\{([^}]+)\}\}/g
  16. export type IWelcomeProps = {
  17. conversationName: string
  18. hasSetInputs: boolean
  19. isPublicVersion: boolean
  20. siteInfo: SiteInfo
  21. promptConfig: PromptConfig
  22. onStartChat: (inputs: Record<string, any>) => void
  23. canEidtInpus: boolean
  24. savedInputs: Record<string, any>
  25. onInputsChange: (inputs: Record<string, any>) => void
  26. plan?: string
  27. }
  28. const Welcome: FC<IWelcomeProps> = ({
  29. conversationName,
  30. hasSetInputs,
  31. isPublicVersion,
  32. siteInfo,
  33. plan,
  34. promptConfig,
  35. onStartChat,
  36. canEidtInpus,
  37. savedInputs,
  38. onInputsChange,
  39. }) => {
  40. const { t } = useTranslation()
  41. const hasVar = promptConfig.prompt_variables.length > 0
  42. const [isFold, setIsFold] = useState<boolean>(true)
  43. const [inputs, setInputs] = useState<Record<string, any>>((() => {
  44. if (hasSetInputs)
  45. return savedInputs
  46. const res: Record<string, any> = {}
  47. if (promptConfig) {
  48. promptConfig.prompt_variables.forEach((item) => {
  49. res[item.key] = ''
  50. })
  51. }
  52. // debugger
  53. return res
  54. })())
  55. useEffect(() => {
  56. if (!savedInputs) {
  57. const res: Record<string, any> = {}
  58. if (promptConfig) {
  59. promptConfig.prompt_variables.forEach((item) => {
  60. res[item.key] = ''
  61. })
  62. }
  63. setInputs(res)
  64. }
  65. else {
  66. setInputs(savedInputs)
  67. }
  68. }, [savedInputs])
  69. const highLightPromoptTemplate = (() => {
  70. if (!promptConfig)
  71. return ''
  72. const res = promptConfig.prompt_template.replace(regex, (match, p1) => {
  73. return `<span class='text-gray-800 font-bold'>${inputs?.[p1] ? inputs?.[p1] : match}</span>`
  74. })
  75. return res
  76. })()
  77. const { notify } = useContext(ToastContext)
  78. const logError = (message: string) => {
  79. notify({ type: 'error', message, duration: 3000 })
  80. }
  81. const renderHeader = () => {
  82. return (
  83. <div className='absolute top-0 left-0 right-0 flex items-center justify-between border-b border-gray-100 mobile:h-12 tablet:h-16 px-8 bg-white'>
  84. <div className='text-gray-900'>{conversationName}</div>
  85. </div>
  86. )
  87. }
  88. const renderInputs = () => {
  89. return (
  90. <div className='space-y-3'>
  91. {promptConfig.prompt_variables.map(item => (
  92. <div className='tablet:flex items-start mobile:space-y-2 tablet:space-y-0 mobile:text-xs tablet:text-sm' key={item.key}>
  93. <label className={`flex-shrink-0 flex items-center tablet:leading-9 mobile:text-gray-700 tablet:text-gray-900 mobile:font-medium pc:font-normal ${s.formLabel}`}>{item.name}</label>
  94. {item.type === 'select'
  95. && (
  96. <Select
  97. className='w-full'
  98. defaultValue={inputs?.[item.key]}
  99. onSelect={(i) => { setInputs({ ...inputs, [item.key]: i.value }) }}
  100. items={(item.options || []).map(i => ({ name: i, value: i }))}
  101. allowSearch={false}
  102. bgClassName='bg-gray-50'
  103. />
  104. )}
  105. {item.type === 'string' && (
  106. <input
  107. placeholder={`${item.name}${!item.required ? `(${t('appDebug.variableTable.optional')})` : ''}`}
  108. value={inputs?.[item.key] || ''}
  109. onChange={(e) => { setInputs({ ...inputs, [item.key]: e.target.value }) }}
  110. className={'w-full flex-grow py-2 pl-3 pr-3 box-border rounded-lg bg-gray-50'}
  111. maxLength={item.max_length || DEFAULT_VALUE_MAX_LEN}
  112. />
  113. )}
  114. {item.type === 'paragraph' && (
  115. <textarea
  116. className="w-full h-[104px] flex-grow py-2 pl-3 pr-3 box-border rounded-lg bg-gray-50"
  117. placeholder={`${item.name}${!item.required ? `(${t('appDebug.variableTable.optional')})` : ''}`}
  118. value={inputs?.[item.key] || ''}
  119. onChange={(e) => { setInputs({ ...inputs, [item.key]: e.target.value }) }}
  120. />
  121. )}
  122. </div>
  123. ))}
  124. </div>
  125. )
  126. }
  127. const canChat = () => {
  128. const prompt_variables = promptConfig?.prompt_variables
  129. if (!inputs || !prompt_variables || prompt_variables?.length === 0)
  130. return true
  131. let hasEmptyInput = ''
  132. const requiredVars = prompt_variables?.filter(({ key, name, required }) => {
  133. const res = (!key || !key.trim()) || (!name || !name.trim()) || (required || required === undefined || required === null)
  134. return res
  135. }) || [] // compatible with old version
  136. requiredVars.forEach(({ key, name }) => {
  137. if (hasEmptyInput)
  138. return
  139. if (!inputs?.[key])
  140. hasEmptyInput = name
  141. })
  142. if (hasEmptyInput) {
  143. logError(t('appDebug.errorMessage.valueOfVarRequired', { key: hasEmptyInput }))
  144. return false
  145. }
  146. return !hasEmptyInput
  147. }
  148. const handleChat = () => {
  149. if (!canChat())
  150. return
  151. onStartChat(inputs)
  152. }
  153. const renderNoVarPanel = () => {
  154. if (isPublicVersion) {
  155. return (
  156. <div>
  157. <AppInfo siteInfo={siteInfo} />
  158. <TemplateVarPanel
  159. isFold={false}
  160. header={
  161. <>
  162. <PanelTitle
  163. title={t('share.chat.publicPromptConfigTitle')}
  164. className='mb-1'
  165. />
  166. <PromptTemplate html={highLightPromoptTemplate} />
  167. </>
  168. }
  169. >
  170. <ChatBtn onClick={handleChat} />
  171. </TemplateVarPanel>
  172. </div>
  173. )
  174. }
  175. // private version
  176. return (
  177. <TemplateVarPanel
  178. isFold={false}
  179. header={
  180. <AppInfo siteInfo={siteInfo} />
  181. }
  182. >
  183. <ChatBtn onClick={handleChat} />
  184. </TemplateVarPanel>
  185. )
  186. }
  187. const renderVarPanel = () => {
  188. return (
  189. <TemplateVarPanel
  190. isFold={false}
  191. header={
  192. <AppInfo siteInfo={siteInfo} />
  193. }
  194. >
  195. {renderInputs()}
  196. <ChatBtn
  197. className='mt-3 mobile:ml-0 tablet:ml-[128px]'
  198. onClick={handleChat}
  199. />
  200. </TemplateVarPanel>
  201. )
  202. }
  203. const renderVarOpBtnGroup = () => {
  204. return (
  205. <VarOpBtnGroup
  206. onConfirm={() => {
  207. if (!canChat())
  208. return
  209. onInputsChange(inputs)
  210. setIsFold(true)
  211. }}
  212. onCancel={() => {
  213. setInputs(savedInputs)
  214. setIsFold(true)
  215. }}
  216. />
  217. )
  218. }
  219. const renderHasSetInputsPublic = () => {
  220. if (!canEidtInpus) {
  221. return (
  222. <TemplateVarPanel
  223. isFold={false}
  224. header={
  225. <>
  226. <PanelTitle
  227. title={t('share.chat.publicPromptConfigTitle')}
  228. className='mb-1'
  229. />
  230. <PromptTemplate html={highLightPromoptTemplate} />
  231. </>
  232. }
  233. />
  234. )
  235. }
  236. return (
  237. <TemplateVarPanel
  238. isFold={isFold}
  239. header={
  240. <>
  241. <PanelTitle
  242. title={t('share.chat.publicPromptConfigTitle')}
  243. className='mb-1'
  244. />
  245. <PromptTemplate html={highLightPromoptTemplate} />
  246. {isFold && (
  247. <div className='flex items-center justify-between mt-3 border-t border-indigo-100 pt-4 text-xs text-indigo-600'>
  248. <span className='text-gray-700'>{t('share.chat.configStatusDes')}</span>
  249. <EditBtn onClick={() => setIsFold(false)} />
  250. </div>
  251. )}
  252. </>
  253. }
  254. >
  255. {renderInputs()}
  256. {renderVarOpBtnGroup()}
  257. </TemplateVarPanel>
  258. )
  259. }
  260. const renderHasSetInputsPrivate = () => {
  261. if (!canEidtInpus || !hasVar)
  262. return null
  263. return (
  264. <TemplateVarPanel
  265. isFold={isFold}
  266. header={
  267. <div className='flex items-center justify-between text-indigo-600'>
  268. <PanelTitle
  269. title={!isFold ? t('share.chat.privatePromptConfigTitle') : t('share.chat.configStatusDes')}
  270. />
  271. {isFold && (
  272. <EditBtn onClick={() => setIsFold(false)} />
  273. )}
  274. </div>
  275. }
  276. >
  277. {renderInputs()}
  278. {renderVarOpBtnGroup()}
  279. </TemplateVarPanel>
  280. )
  281. }
  282. const renderHasSetInputs = () => {
  283. if ((!isPublicVersion && !canEidtInpus) || !hasVar)
  284. return null
  285. return (
  286. <div
  287. className='pt-[88px] mb-5'
  288. >
  289. {isPublicVersion ? renderHasSetInputsPublic() : renderHasSetInputsPrivate()}
  290. </div>)
  291. }
  292. return (
  293. <div className='relative mobile:min-h-[48px] tablet:min-h-[64px]'>
  294. {hasSetInputs && renderHeader()}
  295. <div className='mx-auto pc:w-[794px] max-w-full mobile:w-full px-3.5'>
  296. {/* Has't set inputs */}
  297. {
  298. !hasSetInputs && (
  299. <div className='mobile:pt-[72px] tablet:pt-[128px] pc:pt-[200px]'>
  300. {hasVar
  301. ? (
  302. renderVarPanel()
  303. )
  304. : (
  305. renderNoVarPanel()
  306. )}
  307. </div>
  308. )
  309. }
  310. {/* Has set inputs */}
  311. {hasSetInputs && renderHasSetInputs()}
  312. {/* foot */}
  313. {!hasSetInputs && (
  314. <div className='mt-4 flex justify-between items-center h-8 text-xs text-gray-400'>
  315. {siteInfo.privacy_policy
  316. ? <div>{t('share.chat.privacyPolicyLeft')}
  317. <a
  318. className='text-gray-500'
  319. href={siteInfo.privacy_policy}
  320. target='_blank'>{t('share.chat.privacyPolicyMiddle')}</a>
  321. {t('share.chat.privacyPolicyRight')}
  322. </div>
  323. : <div>
  324. </div>}
  325. {plan === 'basic' && <a className='flex items-center pr-3 space-x-3' href="https://dify.ai/" target="_blank">
  326. <span className='uppercase'>{t('share.chat.powerBy')}</span>
  327. <FootLogo />
  328. </a>}
  329. </div>
  330. )}
  331. </div>
  332. </div >
  333. )
  334. }
  335. export default React.memo(Welcome)