index.tsx 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. canEditInputs: 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. canEditInputs,
  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 tablet:!h-9 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 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. : (
  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. </div>
  115. ))}
  116. </div>
  117. )
  118. }
  119. const canChat = () => {
  120. const prompt_variables = promptConfig?.prompt_variables
  121. if (!inputs || !prompt_variables || prompt_variables?.length === 0)
  122. return true
  123. let hasEmptyInput = false
  124. const requiredVars = prompt_variables?.filter(({ key, name, required }) => {
  125. const res = (!key || !key.trim()) || (!name || !name.trim()) || (required || required === undefined || required === null)
  126. return res
  127. }) || [] // compatible with old version
  128. requiredVars.forEach(({ key }) => {
  129. if (hasEmptyInput)
  130. return
  131. if (!inputs?.[key])
  132. hasEmptyInput = true
  133. })
  134. if (hasEmptyInput) {
  135. logError(t('appDebug.errorMessage.valueOfVarRequired'))
  136. return false
  137. }
  138. return !hasEmptyInput
  139. }
  140. const handleChat = () => {
  141. if (!canChat())
  142. return
  143. onStartChat(inputs)
  144. }
  145. const renderNoVarPanel = () => {
  146. if (isPublicVersion) {
  147. return (
  148. <div>
  149. <AppInfo siteInfo={siteInfo} />
  150. <TemplateVarPanel
  151. isFold={false}
  152. header={
  153. <>
  154. <PanelTitle
  155. title={t('share.chat.publicPromptConfigTitle')}
  156. className='mb-1'
  157. />
  158. <PromptTemplate html={highLightPromoptTemplate} />
  159. </>
  160. }
  161. >
  162. <ChatBtn onClick={handleChat} />
  163. </TemplateVarPanel>
  164. </div>
  165. )
  166. }
  167. // private version
  168. return (
  169. <TemplateVarPanel
  170. isFold={false}
  171. header={
  172. <AppInfo siteInfo={siteInfo} />
  173. }
  174. >
  175. <ChatBtn onClick={handleChat} />
  176. </TemplateVarPanel>
  177. )
  178. }
  179. const renderVarPanel = () => {
  180. return (
  181. <TemplateVarPanel
  182. isFold={false}
  183. header={
  184. <AppInfo siteInfo={siteInfo} />
  185. }
  186. >
  187. {renderInputs()}
  188. <ChatBtn
  189. className='mt-3 mobile:ml-0 tablet:ml-[128px]'
  190. onClick={handleChat}
  191. />
  192. </TemplateVarPanel>
  193. )
  194. }
  195. const renderVarOpBtnGroup = () => {
  196. return (
  197. <VarOpBtnGroup
  198. onConfirm={() => {
  199. if (!canChat())
  200. return
  201. onInputsChange(inputs)
  202. setIsFold(true)
  203. }}
  204. onCancel={() => {
  205. setInputs(savedInputs)
  206. setIsFold(true)
  207. }}
  208. />
  209. )
  210. }
  211. const renderHasSetInputsPublic = () => {
  212. if (!canEditInputs) {
  213. return (
  214. <TemplateVarPanel
  215. isFold={false}
  216. header={
  217. <>
  218. <PanelTitle
  219. title={t('share.chat.publicPromptConfigTitle')}
  220. className='mb-1'
  221. />
  222. <PromptTemplate html={highLightPromoptTemplate} />
  223. </>
  224. }
  225. />
  226. )
  227. }
  228. return (
  229. <TemplateVarPanel
  230. isFold={isFold}
  231. header={
  232. <>
  233. <PanelTitle
  234. title={t('share.chat.publicPromptConfigTitle')}
  235. className='mb-1'
  236. />
  237. <PromptTemplate html={highLightPromoptTemplate} />
  238. {isFold && (
  239. <div className='flex items-center justify-between mt-3 border-t border-indigo-100 pt-4 text-xs text-indigo-600'>
  240. <span className='text-gray-700'>{t('share.chat.configStatusDes')}</span>
  241. <EditBtn onClick={() => setIsFold(false)} />
  242. </div>
  243. )}
  244. </>
  245. }
  246. >
  247. {renderInputs()}
  248. {renderVarOpBtnGroup()}
  249. </TemplateVarPanel>
  250. )
  251. }
  252. const renderHasSetInputsPrivate = () => {
  253. if (!canEditInputs || !hasVar)
  254. return null
  255. return (
  256. <TemplateVarPanel
  257. isFold={isFold}
  258. header={
  259. <div className='flex items-center justify-between text-indigo-600'>
  260. <PanelTitle
  261. title={!isFold ? t('share.chat.privatePromptConfigTitle') : t('share.chat.configStatusDes')}
  262. />
  263. {isFold && (
  264. <EditBtn onClick={() => setIsFold(false)} />
  265. )}
  266. </div>
  267. }
  268. >
  269. {renderInputs()}
  270. {renderVarOpBtnGroup()}
  271. </TemplateVarPanel>
  272. )
  273. }
  274. const renderHasSetInputs = () => {
  275. if ((!isPublicVersion && !canEditInputs) || !hasVar)
  276. return null
  277. return (
  278. <div
  279. className='pt-[88px] mb-5'
  280. >
  281. {isPublicVersion ? renderHasSetInputsPublic() : renderHasSetInputsPrivate()}
  282. </div>)
  283. }
  284. return (
  285. <div className='relative mobile:min-h-[48px] tablet:min-h-[64px]'>
  286. {/* {hasSetInputs && renderHeader()} */}
  287. <div className='mx-auto pc:w-[794px] max-w-full mobile:w-full px-3.5'>
  288. {/* Has't set inputs */}
  289. {
  290. !hasSetInputs && (
  291. <div className='mobile:pt-[72px] tablet:pt-[128px] pc:pt-[200px]'>
  292. {hasVar
  293. ? (
  294. renderVarPanel()
  295. )
  296. : (
  297. renderNoVarPanel()
  298. )}
  299. </div>
  300. )
  301. }
  302. {/* Has set inputs */}
  303. {hasSetInputs && renderHasSetInputs()}
  304. {/* foot */}
  305. {!hasSetInputs && (
  306. <div className='mt-4 flex justify-between items-center h-8 text-xs text-gray-400'>
  307. {siteInfo.privacy_policy
  308. ? <div>{t('share.chat.privacyPolicyLeft')}
  309. <a
  310. className='text-gray-500'
  311. href={siteInfo.privacy_policy}
  312. target='_blank'>{t('share.chat.privacyPolicyMiddle')}</a>
  313. {t('share.chat.privacyPolicyRight')}
  314. </div>
  315. : <div>
  316. </div>}
  317. {plan === 'basic' && <a className='flex items-center pr-3 space-x-3' href="https://dify.ai/" target="_blank">
  318. <span className='uppercase'>{t('share.chat.powerBy')}</span>
  319. <FootLogo />
  320. </a>}
  321. </div>
  322. )}
  323. </div>
  324. </div >
  325. )
  326. }
  327. export default React.memo(Welcome)